Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
refactor(mcp-host): replace the GFS download store ledger, writer lease and operator recovery
Alfredo Lopez503931b61027
diff --git a/mcp-host/package-lock.json b/mcp-host/package-lock.jsonindex 611c9df81..9aa0c3a94 100644--- a/mcp-host/package-lock.json+++ b/mcp-host/package-lock.json@@ -1,12 +1,12 @@{"name": "clerum-mcp-host",- "version": "0.1.522",+ "version": "0.1.523","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-mcp-host",- "version": "0.1.522",+ "version": "0.1.523","license": "SEE LICENSE IN LICENSE","dependencies": {"@anthropic-ai/sdk": "^0.32.0",diff --git a/mcp-host/package.json b/mcp-host/package.jsonindex ad9532281..b2b6704b7 100644--- a/mcp-host/package.json+++ b/mcp-host/package.json@@ -1,6 +1,6 @@{"name": "clerum-mcp-host",- "version": "0.1.522",+ "version": "0.1.523","description": "MCP Host - reads Host CRD and provides LLM access via OpenAI/Claude","main": "dist/main.js","engines": {diff --git a/mcp-host/src/__tests__/fixtures/devGfsStoreFixture.ts b/mcp-host/src/__tests__/fixtures/devGfsStoreFixture.tsnew file mode 100644index 000000000..be62a6b06--- /dev/null+++ b/mcp-host/src/__tests__/fixtures/devGfsStoreFixture.ts@@ -0,0 +1,182 @@+/**+ * Builds the on-disk state the ledger-based GFS download store leaves behind,+ * so restart tests can prove the filesystem store never blocks on it.+ *+ * The shapes are copied literally from the dev store at 74e0d81d9:+ * - mcp-host/src/internalTools/gfsDownloadStore.ts (StoreLedger, GfsDownloadRecord,+ * GfsProcessingLeaseRecord, GfsReceiptOwnerRecord and parseLedger);+ * - mcp-host/src/internalTools/gfsStoreWriterLease.ts (the v2 writer.lock fence+ * and writer-v2.sqlite).+ * The v3 fence is the one the store at b8f01e18e writes. writer-v2.sqlite is an+ * empty private file: nothing under test opens it.+ */+import { createHash, randomUUID } from 'node:crypto'+import * as fs from 'node:fs/promises'+import * as path from 'node:path'++export type DevLedgerShape = 'records' | 'processingLeasesEmpty' | 'none'+export type DevFenceShape = 'v2-matching' | 'v2-mismatched-device' | 'v2-no-device' | 'v3' | 'none'+export type DevUserDirectoryState =+ | 'completed'+ | 'transferring-partial'+ | 'quarantined'+ | 'missing'+ | 'orphan-partial'++export interface DevStoreShape {+ ledger: DevLedgerShape+ fence: DevFenceShape+ sqlite: boolean+ userDirs: DevUserDirectoryState[]+ /** A processing lease left by a crashed pre-#1019 Host, expired or still live. */+ lease?: 'expired' | 'live'+}++export interface DevStore {+ /** `<root>/.gfs-download-store`. */+ storeRoot: string+ /** The exact ledger-v1.json text written, when the shape has a ledger. */+ ledgerText?: string+ /** Absolute `input-<uuid>` directories written under the caller root. */+ userDirectories: string[]+ /** Bytes of every source and source.partial file written. */+ userBytes: number+ callerIdentity: string+ callerRoot: string+}++const OWNERSHIP = 'sqlite-exclusive-v1'+export const DEV_CALLER_IDENTITY = 'caller-dev'+const LEASE_ID = '77777777-7777-4777-8777-777777777777'+const WRITER_SESSION_ID = '88888888-8888-4888-8888-888888888888'+const FILE_BYTES = 4096++function recordState(state: DevUserDirectoryState): string | undefined {+ switch (state) {+ case 'completed':+ return 'completed'+ case 'transferring-partial':+ return 'transferring'+ case 'quarantined':+ return 'quarantined'+ case 'missing':+ return 'missing'+ case 'orphan-partial':+ return undefined+ }+}++export async function buildDevStore(root: string, shape: DevStoreShape): Promise<DevStore> {+ const storeRoot = path.join(root, '.gfs-download-store')+ const callerRoot = path.join(root, 'users', DEV_CALLER_IDENTITY)+ await fs.mkdir(callerRoot, { recursive: true, mode: 0o700 })+ const now = Date.now()+ const records: Record<string, unknown> = {}+ const userDirectories: string[] = []+ let userBytes = 0++ for (const [index, state] of shape.userDirs.entries()) {+ const id = randomUUID()+ const directory = path.join('users', DEV_CALLER_IDENTITY, '.gfs-downloads', `input-${id}`)+ const absolute = path.join(root, directory)+ await fs.mkdir(absolute, { recursive: true, mode: 0o700 })+ userDirectories.push(absolute)+ const bytes = Buffer.alloc(FILE_BYTES, index + 1)+ const sha256 = createHash('sha256').update(bytes).digest('hex')+ if (state === 'completed' || state === 'quarantined') {+ await fs.writeFile(path.join(absolute, 'source'), bytes, { mode: 0o600 })+ userBytes += bytes.byteLength+ }+ if (state === 'transferring-partial' || state === 'orphan-partial') {+ await fs.writeFile(path.join(absolute, 'source.partial'), bytes, { mode: 0o600 })+ userBytes += bytes.byteLength+ }+ const ledgerState = recordState(state)+ if (ledgerState === undefined) continue+ const resourceId = (index + 1).toString(16).padStart(32, '0')+ records[id] = {+ id,+ callerIdentity: DEV_CALLER_IDENTITY,+ source: {+ kind: 'gfs',+ drive: 'main',+ resourceId,+ gfsUri: `gfs://main/${resourceId}`,+ name: `dev-${index + 1}.bin`,+ version: 1,+ },+ directory,+ path: path.join('.gfs-downloads', `input-${id}`, 'source'),+ hostPath: path.join(directory, 'source'),+ sizeBytes: bytes.byteLength,+ ...(ledgerState === 'transferring' ? {} : { sha256 }),+ createdAt: new Date(now - 60 * 60_000).toISOString(),+ expiresAt: new Date(now + 60 * 60_000).toISOString(),+ state: ledgerState,+ }+ }++ const hasStoreRoot = shape.ledger !== 'none' || shape.fence !== 'none' || shape.sqlite+ if (hasStoreRoot) await fs.mkdir(storeRoot, { mode: 0o700 })++ let ledgerText: string | undefined+ if (shape.ledger !== 'none') {+ const processingLeases: Record<string, unknown> = {}+ if (shape.lease !== undefined)+ processingLeases[LEASE_ID] = {+ leaseId: LEASE_ID,+ callerIdentity: '_system',+ recordIds: [],+ acquiredAt: new Date(now - 120_000).toISOString(),+ expiresAt: new Date(now + (shape.lease === 'live' ? 600_000 : -60_000)).toISOString(),+ writerSessionId: WRITER_SESSION_ID,+ }+ const ledger =+ shape.ledger === 'records'+ ? { schemaVersion: 1, records, processingLeases, retentionOwners: {} }+ : { schemaVersion: 1, records: {}, processingLeases }+ ledgerText = JSON.stringify(ledger)+ await fs.writeFile(path.join(storeRoot, 'ledger-v1.json'), ledgerText, { mode: 0o600 })+ }++ const databasePath = path.join(storeRoot, 'writer-v2.sqlite')+ if (shape.sqlite) await fs.writeFile(databasePath, '', { mode: 0o600 })++ if (shape.fence !== 'none') {+ // The fence names the database inode; without a database file it names a+ // fixed one, as a fence left next to a lost database would.+ const identity = shape.sqlite+ ? await fs.stat(databasePath, { bigint: true })+ : { dev: 1n, ino: 1n }+ const fence =+ shape.fence === 'v2-matching'+ ? {+ schemaVersion: 2,+ ownership: OWNERSHIP,+ databaseDevice: String(identity.dev),+ databaseInode: String(identity.ino),+ }+ : shape.fence === 'v2-mismatched-device'+ ? {+ schemaVersion: 2,+ ownership: OWNERSHIP,+ databaseDevice: String(identity.dev + 1n),+ databaseInode: String(identity.ino),+ }+ : shape.fence === 'v2-no-device'+ ? { schemaVersion: 2, ownership: OWNERSHIP, databaseInode: String(identity.ino) }+ : { schemaVersion: 3, ownership: OWNERSHIP, databaseInode: String(identity.ino) }+ await fs.writeFile(path.join(storeRoot, 'writer.lock'), JSON.stringify(fence), {+ mode: 0o600,+ })+ }++ return {+ storeRoot,+ ...(ledgerText === undefined ? {} : { ledgerText }),+ userDirectories,+ userBytes,+ callerIdentity: DEV_CALLER_IDENTITY,+ callerRoot,+ }+}diff --git a/mcp-host/src/__tests__/gfsLedgerPublicationRace.test.ts b/mcp-host/src/__tests__/gfsLedgerPublicationRace.test.tsdeleted file mode 100644index 2f86b2f9d..000000000--- a/mcp-host/src/__tests__/gfsLedgerPublicationRace.test.ts+++ /dev/null@@ -1,115 +0,0 @@-import { afterEach, describe, expect, it, vi } from 'vitest'-import { randomUUID } from 'node:crypto'-import * as fs from 'node:fs/promises'-import { tmpdir } from 'node:os'-import { join } from 'node:path'-import { type GfsRuntime, bootstrapGfsRuntime } from '../gfsRuntime'-import { GfsDownloadStore } from '../internalTools/gfsDownloadStore'--/**- * The live writer publishes every ledger by writing a temporary file and- * renaming it over `ledger-v1.json`. A standby that reads the ledger during- * writer contention can open the old inode and then `lstat` the name after the- * rename. This hook performs that real rename at exactly that point, once.- */-const race = vi.hoisted(() => ({- armed: false,- fired: 0,- publish: undefined as undefined | ((ledgerPath: string) => Promise<void>),-}))--vi.mock('node:fs/promises', async importOriginal => {- const actual = await importOriginal<typeof import('node:fs/promises')>()- const lstat = (async (target: Parameters<typeof actual.lstat>[0], ...rest: unknown[]) => {- if (race.armed && String(target).endsWith('/.gfs-download-store/ledger-v1.json')) {- race.armed = false- race.fired += 1- await race.publish?.(String(target))- }- return (actual.lstat as (...args: unknown[]) => unknown)(target, ...rest)- }) as typeof actual.lstat- return { ...actual, lstat, default: { ...actual, lstat } }-})--/** Same file operations as the live writer's persist(): new inode, then rename. */-async function publishLedgerCopy(ledgerPath: string): Promise<void> {- const raw = await fs.readFile(ledgerPath, 'utf8')- const temporary = `${ledgerPath}.tmp-${randomUUID()}`- await fs.writeFile(temporary, raw, { flag: 'wx', mode: 0o600 })- await fs.rename(temporary, ledgerPath)-}--const roots: string[] = []-const stores: GfsDownloadStore[] = []-const runtimes: GfsRuntime[] = []--async function root() {- const value = await fs.mkdtemp(join(tmpdir(), 'gfs-ledger-race-'))- roots.push(value)- return value-}--async function ledgerInode(value: string): Promise<bigint> {- const real = await fs.realpath(value)- return (await fs.stat(join(real, '.gfs-download-store', 'ledger-v1.json'), { bigint: true })).ino-}--afterEach(async () => {- race.armed = false- race.fired = 0- race.publish = undefined- for (const runtime of runtimes.splice(0)) await runtime.stop()- for (const store of stores.splice(0)) await store.close()- vi.restoreAllMocks()- for (const value of roots.splice(0)) await fs.rm(value, { recursive: true, force: true })-})--describe('GFS ledger publication during writer contention', () => {- it('reports a ledger renamed by the live writer as transient contention, not corruption', async () => {- const value = await root()- const first = new GfsDownloadStore(value)- stores.push(first)- await first.initialize()- const before = await ledgerInode(value)- race.publish = publishLedgerCopy- race.armed = true-- const second = new GfsDownloadStore(value)- await expect(second.initialize()).rejects.toMatchObject({- code: 'writer_locked',- transientWriterContention: true,- })-- // Witness: the rename really happened between the standby's open and lstat.- expect(race.fired).toBe(1)- expect(await ledgerInode(value)).not.toBe(before)- })-- it('keeps retrying through a ledger publication and starts cleanup after the old writer releases', async () => {- const value = await root()- const first = new GfsDownloadStore(value)- stores.push(first)- await first.initialize()- let resolveCleanup!: () => void- const cleanupStarted = new Promise<void>(resolve => {- resolveCleanup = resolve- })- const cleanup = vi- .spyOn(GfsDownloadStore.prototype, 'cleanupExpired')- .mockImplementation(async () => {- resolveCleanup()- })- race.publish = publishLedgerCopy- race.armed = true-- const runtime = await bootstrapGfsRuntime(value, { retryDelayMs: 25, maxRetryAttempts: 40 })- runtimes.push(runtime)- expect(race.fired).toBe(1)- expect(runtime.store.isAvailable()).toBe(false)-- await first.close()- await cleanupStarted- expect(runtime.store.isAvailable()).toBe(true)- expect(cleanup).toHaveBeenCalledOnce()- })-})diff --git a/mcp-host/src/__tests__/gfsRuntime.test.ts b/mcp-host/src/__tests__/gfsRuntime.test.tsindex 617a90847..35c100b5c 100644--- a/mcp-host/src/__tests__/gfsRuntime.test.ts+++ b/mcp-host/src/__tests__/gfsRuntime.test.ts@@ -1,26 +1,14 @@import { afterEach, describe, expect, it, vi } from 'vitest'import { createHash } from 'node:crypto'import * as fs from 'node:fs/promises'-import type { FileHandle } from 'node:fs/promises'import { tmpdir } from 'node:os'import { join } from 'node:path'+import { register } from 'prom-client'import { type GfsRuntime, bootstrapGfsRuntime } from '../gfsRuntime'-import { GfsDownloadStore, GfsDownloadStoreError } from '../internalTools/gfsDownloadStore'+import { GfsDownloadStore } from '../internalTools/gfsDownloadStore'import { logger } from '../logger'-// The logger binds its error sink when its module is evaluated and keeps only-// name/code/status of an Error. Installing this sink before any import makes-// it the logger's error sink, so T8 reads the exact JSON line written.-const serializedErrorLines = vi.hoisted(() => {- const lines: string[] = []- console.error = (...args: unknown[]) => {- lines.push(args.map(String).join(' '))- }- return lines-})-const roots: string[] = []-const stores: GfsDownloadStore[] = []const runtimes: GfsRuntime[] = []function deferred() {@@ -37,341 +25,189 @@ async function root() {return value}+async function start(hostRoot: string, cycleMs?: number): Promise<GfsRuntime> {+ const runtime = await bootstrapGfsRuntime(hostRoot, cycleMs === undefined ? {} : { cycleMs })+ runtimes.push(runtime)+ return runtime+}++/** A Host root that is a symlink: initialize refuses it with workspace_unavailable. */+async function symlinkedHostRoot(): Promise<{ link: string; target: string }> {+ const base = await root()+ const target = join(base, 'real-host')+ await fs.mkdir(target, { mode: 0o700 })+ const link = join(base, 'host-link')+ await fs.symlink(target, link)+ return { link, target }+}++async function expiryCount(outcome: string): Promise<number> {+ const metric = register.getSingleMetric('clerum_gfs_download_expiry_total')+ if (metric === undefined) throw new Error('expiry metric is not registered')+ const { values } = await metric.get()+ return values+ .filter(sample => sample.labels.outcome === outcome)+ .reduce((sum, sample) => sum + sample.value, 0)+}+afterEach(async () => {vi.useRealTimers()for (const runtime of runtimes.splice(0)) await runtime.stop()- for (const store of stores.splice(0)) await store.close()vi.restoreAllMocks()for (const value of roots.splice(0)) await fs.rm(value, { recursive: true, force: true })})describe('GFS runtime bootstrap', () => {- it('contains recovery-required startup and does not retry unverified contention', async () => {- const value = await root()- await fs.mkdir(join(value, '.gfs-download-store'), { mode: 0o700 })- const initialize = vi.spyOn(GfsDownloadStore.prototype, 'initialize')- const runtime = await bootstrapGfsRuntime(value)- runtimes.push(runtime)-- expect(runtime.store.isAvailable()).toBe(false)+ it('bootstraps an available store and a workspace provider', async () => {+ const runtime = await start(await root())+ expect(runtime.store.isAvailable()).toBe(true)expect(runtime.workspaceProvider).toBeDefined()- expect(initialize).toHaveBeenCalledOnce()- await runtime.stop()})- it('retries verified v2 writer contention and starts cleanup when the old writer releases', async () => {- const value = await root()- const first = new GfsDownloadStore(value)- stores.push(first)- await first.initialize()- const cleanupStarted = deferred()- const cleanup = vi- .spyOn(GfsDownloadStore.prototype, 'cleanupExpired')- .mockImplementation(async () => {- cleanupStarted.resolve()- })- // Fake timers keep each retry out of the old writer's close(). With real- // timers a 25 ms retry can start verifying the in-process prior owner and- // see it release mid-verification; that is classified as ambiguous- // ownership (non-transient), the retry ends in recovery-required state and- // cleanup never starts. Under host load this hung the test until the 5 s- // timeout. Store I/O stays real; only the retry schedule is controlled.- vi.useFakeTimers()- const initialize = vi.spyOn(GfsDownloadStore.prototype, 'initialize')- const runtime = await bootstrapGfsRuntime(value, { retryDelayMs: 25, maxRetryAttempts: 40 })- runtimes.push(runtime)- expect(runtime.store.isAvailable()).toBe(false)- expect(cleanup).not.toHaveBeenCalled()- await expect(initialize.mock.results[0]!.value).rejects.toMatchObject({- code: 'writer_locked',- transientWriterContention: true,- })- expect(vi.getTimerCount()).toBe(1)-- // A retry while the old writer still holds stays verified contention and- // schedules the next retry instead of ending the supervision.- await vi.advanceTimersByTimeAsync(25)- expect(initialize).toHaveBeenCalledTimes(2)- await expect(initialize.mock.results[1]!.value).rejects.toMatchObject({- code: 'writer_locked',- transientWriterContention: true,- })- // The settled rejection reschedules through promise callbacks only; flush- // microtasks without advancing the fake clock.- for (let turn = 0; turn < 20 && vi.getTimerCount() === 0; turn += 1) await Promise.resolve()- expect(vi.getTimerCount()).toBe(1)- expect(runtime.store.isAvailable()).toBe(false)- expect(cleanup).not.toHaveBeenCalled()-- await first.close()- await vi.advanceTimersByTimeAsync(25)- expect(initialize).toHaveBeenCalledTimes(3)- await cleanupStarted.promise- expect(runtime.store.isAvailable()).toBe(true)- expect(cleanup).toHaveBeenCalledOnce()- await runtime.stop()+ it('rejects a cycle interval below 25ms', async () => {+ await expect(bootstrapGfsRuntime(await root(), { cycleMs: 24 })).rejects.toThrow(+ 'GFS runtime cycleMs must be an integer of at least 25ms'+ )})- it('stops retry scheduling without reacquiring after shutdown', async () => {- const value = await root()- const first = new GfsDownloadStore(value)- stores.push(first)- await first.initialize()- vi.useFakeTimers()+ it('a failed initialize is logged with its code and the next cycle makes the store available', async () => {+ const { link } = await symlinkedHostRoot()+ const error = vi.spyOn(logger, 'error')const initialize = vi.spyOn(GfsDownloadStore.prototype, 'initialize')- const runtime = await bootstrapGfsRuntime(value, { retryDelayMs: 25, maxRetryAttempts: 40 })- runtimes.push(runtime)- await runtime.stop()- await first.close()- await vi.advanceTimersByTimeAsync(100)-- expect(initialize).toHaveBeenCalledOnce()- expect(runtime.store.isAvailable()).toBe(false)- expect(vi.getTimerCount()).toBe(0)- })- it('joins a slow retry, closes its late ownership, and never schedules a post-stop sweep', async () => {- const value = await root()- vi.useFakeTimers()- let available = false- const retryEntered = deferred()- const retryReleased = deferred()- vi.spyOn(GfsDownloadStore.prototype, 'isAvailable').mockImplementation(() => available)- vi.spyOn(GfsDownloadStore.prototype, 'initialize')- .mockRejectedValueOnce(new GfsDownloadStoreError('writer_locked', true))- .mockImplementation(async () => {- retryEntered.resolve()- await retryReleased.promise- available = true- })- const cleanup = vi.spyOn(GfsDownloadStore.prototype, 'cleanupExpired').mockResolvedValue()- const close = vi.spyOn(GfsDownloadStore.prototype, 'close').mockImplementation(async () => {- available = false- })- const runtime = await bootstrapGfsRuntime(value, { retryDelayMs: 25 })- runtimes.push(runtime)- await vi.advanceTimersByTimeAsync(25)- await retryEntered.promise- const stopping = runtime.stop()- expect(runtime.stop()).toBe(stopping)- expect(close).not.toHaveBeenCalled()- try {- await vi.advanceTimersByTimeAsync(60 * 60 * 1000)- expect(cleanup).not.toHaveBeenCalled()- } finally {- retryReleased.resolve()- }- await stopping+ const runtime = await start(link, 25)- expect(close).toHaveBeenCalledOnce()expect(runtime.store.isAvailable()).toBe(false)- expect(cleanup).not.toHaveBeenCalled()- expect(vi.getTimerCount()).toBe(0)- })-- it('serializes slow sweeps and joins the current sweep before closing', async () => {- const value = await root()- vi.useFakeTimers()- const sweepEntered = deferred()- const sweepReleased = deferred()- vi.spyOn(GfsDownloadStore.prototype, 'initialize').mockResolvedValue()- vi.spyOn(GfsDownloadStore.prototype, 'isAvailable').mockReturnValue(true)- const close = vi.spyOn(GfsDownloadStore.prototype, 'close').mockResolvedValue()- const cleanup = vi- .spyOn(GfsDownloadStore.prototype, 'cleanupExpired')- .mockResolvedValueOnce()- .mockImplementation(async () => {- sweepEntered.resolve()- await sweepReleased.promise- })- const runtime = await bootstrapGfsRuntime(value)- runtimes.push(runtime)- await vi.advanceTimersByTimeAsync(60 * 60 * 1000)- await sweepEntered.promise- const stopping = runtime.stop()- try {- await vi.advanceTimersByTimeAsync(3 * 60 * 60 * 1000)- expect(cleanup).toHaveBeenCalledTimes(2)- expect(close).not.toHaveBeenCalled()- } finally {- sweepReleased.resolve()- }- await stopping-- expect(close).toHaveBeenCalledOnce()- expect(vi.getTimerCount()).toBe(0)+ expect(error).toHaveBeenCalledWith(+ { component: 'gfs-runtime', code: 'workspace_unavailable' },+ expect.stringContaining('retried by the hourly cycle')+ )+ // The cause goes away: the symlink becomes a real directory.+ await fs.rm(link)+ await fs.mkdir(link, { mode: 0o700 })+ await vi.waitFor(() => expect(runtime.store.isAvailable()).toBe(true), {+ timeout: 5_000,+ interval: 10,+ })+ // Witness: availability came from a cycle-driven initialize, not the first one.+ expect(initialize.mock.calls.length).toBeGreaterThanOrEqual(2)})- it('U9: logs an error and stops the periodic lifecycle when the store becomes unavailable after initialize', async () => {- vi.useFakeTimers()- const value = await root()- const initialize = vi.spyOn(GfsDownloadStore.prototype, 'initialize')- const error = vi.spyOn(logger, 'error')- const warn = vi.spyOn(logger, 'warn')- // Real sweeps throughout: the store becomes unavailable only because a real- // persist fails during a periodic sweep, which marks the store `unsafe`.- const cleanup = vi.spyOn(GfsDownloadStore.prototype, 'cleanupExpired')- const runtime = await bootstrapGfsRuntime(value)- runtimes.push(runtime)- await expect(initialize.mock.results[0]!.value).resolves.toBeUndefined()- // initialize() sweeps once itself; the lifecycle's first sweep is the second.- for (let turn = 0; turn < 20 && cleanup.mock.calls.length < 2; turn += 1)- await Promise.resolve()- expect(cleanup).toHaveBeenCalledTimes(2)- await cleanup.mock.results[1]!.value- // The settled sweep schedules the next one through promise callbacks only;- // flush microtasks without advancing the fake clock.- for (let turn = 0; turn < 20 && vi.getTimerCount() === 0; turn += 1) await Promise.resolve()- expect(runtime.store.isAvailable()).toBe(true)- expect(vi.getTimerCount()).toBe(1)-- // A published record that expires before the next periodic sweep, so that- // sweep must remove it and persist the released charge.- const callerRoot = join(value, 'users', 'caller-a')+ it('the cycle sweeps expired downloads', async () => {+ const hostRoot = await root()+ const callerRoot = join(hostRoot, 'users', 'caller-a')await fs.mkdir(callerRoot, { recursive: true, mode: 0o700 })+ vi.useFakeTimers({ toFake: ['Date'] })+ vi.setSystemTime(new Date('2026-10-08T10:00:00.000Z'))+ const runtime = await start(hostRoot, 25)+ const bytes = Buffer.from('expired content')const transfer = await runtime.store.createTransfer({callerIdentity: 'caller-a',callerWorkspacePath: callerRoot,source: {kind: 'gfs',drive: 'main',- resourceId: 'a'.repeat(32),- gfsUri: `gfs://main/${'a'.repeat(32)}`,- name: 'input.csv',- version: 7,+ resourceId: 'f'.repeat(32),+ gfsUri: `gfs://main/${'f'.repeat(32)}`,+ name: 'expired.bin',+ version: 1,},- sizeBytes: 7,+ sizeBytes: bytes.byteLength,expiresAt: new Date(Date.now() + 60_000).toISOString(),})- await fs.writeFile(join(callerRoot, transfer.partialPath), 'fixture')- const receipt = await runtime.store.publish(+ await fs.writeFile(join(callerRoot, transfer.partialPath), bytes)+ await runtime.store.publish(transfer.id,'caller-a',- createHash('sha256').update('fixture').digest('hex')+ createHash('sha256').update(bytes).digest('hex'))- expect(runtime.store.debugRecord(receipt.id)?.state).toBe('completed')+ const directory = join(callerRoot, '.gfs-downloads', `input-${transfer.id}`)+ // Witness: the published download is on disk before it expires.+ await expect(fs.lstat(join(directory, 'source'))).resolves.toBeDefined()+ const removed = await expiryCount('expired_removed')- // The next ledger write fails at the filesystem layer, before its rename.- const probe = await fs.open(join(value, '.gfs-download-store', 'ledger-v1.json'), 'r')- const prototype = Object.getPrototypeOf(probe) as FileHandle- await probe.close()- const originalWriteFile = prototype.writeFile- const failedLedgerWrites: Record<string, Record<string, unknown>>[] = []- vi.spyOn(prototype, 'writeFile').mockImplementation(async function (- this: FileHandle,- ...args: Parameters<FileHandle['writeFile']>- ) {- const [data] = args- if (- failedLedgerWrites.length === 0 &&- typeof data === 'string' &&- data.includes('"records"')- ) {- failedLedgerWrites.push(JSON.parse(data))- throw Object.assign(new Error('injected ledger write failure'), { code: 'EIO' })- }- return originalWriteFile.apply(this, args)- })+ vi.setSystemTime(Date.now() + 120_000)- await vi.advanceTimersByTimeAsync(60 * 60 * 1000)- // Witness: the periodic sweep ran and its persist is the write that failed,- // releasing the expired record's charge. The sweep does real I/O, so wait- // for it to settle rather than for the fake clock.- expect(cleanup).toHaveBeenCalledTimes(3)- await expect(cleanup.mock.results[2]!.value).rejects.toThrow('injected ledger write failure')- const stopLogged = () =>- error.mock.calls.some(- ([, message]) => typeof message === 'string' && message.includes('no longer available')- )- for (let turn = 0; turn < 20 && !stopLogged(); turn += 1) await Promise.resolve()- expect(failedLedgerWrites).toHaveLength(1)- expect(failedLedgerWrites[0]!.records).not.toHaveProperty(receipt.id)- expect(- warn.mock.calls.filter(([, message]) => message === 'GFS download cleanup failed')- ).toHaveLength(1)- expect(runtime.store.isAvailable()).toBe(false)- const stopLogs = error.mock.calls.filter(- ([, message]) => typeof message === 'string' && message.includes('no longer available')+ await vi.waitFor(+ async () => {+ await expect(fs.lstat(directory)).rejects.toMatchObject({ code: 'ENOENT' })+ },+ { timeout: 5_000, interval: 10 })- expect(stopLogs).toEqual([- [- { component: 'gfs-runtime', available: false },- 'GFS download store is no longer available; periodic cleanup stopped and managed GFS operations are disabled',- ],- ])- // The lifecycle schedules nothing more: another period passes without a sweep.- expect(vi.getTimerCount()).toBe(0)- await vi.advanceTimersByTimeAsync(60 * 60 * 1000)- expect(cleanup).toHaveBeenCalledTimes(3)+ expect(await expiryCount('expired_removed')).toBe(removed + 1)})- it('closes initialized ownership even when a failed persist has made the store unavailable', async () => {- const runtime = await bootstrapGfsRuntime(await root())- runtimes.push(runtime)- const close = vi.spyOn(runtime.store, 'close')- vi.spyOn(runtime.store, 'isAvailable').mockReturnValue(false)+ it('stop joins the cycle in flight and closes the store', async () => {+ const runtime = await start(await root(), 25)+ const sweepStarted = deferred()+ const releaseSweep = deferred()+ const cleanup = vi+ .spyOn(GfsDownloadStore.prototype, 'cleanupExpired')+ .mockImplementationOnce(async () => {+ sweepStarted.resolve()+ await releaseSweep.promise+ return { removedExpired: 0, removedIncomplete: 0, removeFailed: 0 }+ })+ await sweepStarted.promise+ let stopped = false+ const stopping = runtime.stop().then(() => {+ stopped = true+ })+ await new Promise(resolve => setTimeout(resolve, 50))+ expect(stopped).toBe(false)++ releaseSweep.resolve()+ await stopping- await runtime.stop()- expect(close).toHaveBeenCalledOnce()- vi.restoreAllMocks()+ expect(cleanup).toHaveBeenCalledOnce()expect(runtime.store.isAvailable()).toBe(false)+ await expect(+ runtime.store.createTransfer({+ callerIdentity: 'caller-a',+ callerWorkspacePath: join(tmpdir(), 'unused'),+ source: {+ kind: 'gfs',+ drive: 'main',+ resourceId: 'a'.repeat(32),+ gfsUri: `gfs://main/${'a'.repeat(32)}`,+ name: 'after-stop.bin',+ version: 1,+ },+ sizeBytes: 1,+ expiresAt: new Date(Date.now() + 60_000).toISOString(),+ })+ ).rejects.toMatchObject({ code: 'download_busy' })})- it('ends bounded retries when the verified contention budget is exhausted', async () => {- const value = await root()- vi.useFakeTimers()- vi.spyOn(GfsDownloadStore.prototype, 'isAvailable').mockReturnValue(false)- const initialize = vi- .spyOn(GfsDownloadStore.prototype, 'initialize')- .mockRejectedValue(new GfsDownloadStoreError('writer_locked', true))- const cleanup = vi.spyOn(GfsDownloadStore.prototype, 'cleanupExpired').mockResolvedValue()- const runtime = await bootstrapGfsRuntime(value, { retryDelayMs: 25, maxRetryAttempts: 2 })- runtimes.push(runtime)- await vi.advanceTimersByTimeAsync(100)-- expect(initialize).toHaveBeenCalledTimes(3)- expect(cleanup).not.toHaveBeenCalled()- expect(vi.getTimerCount()).toBe(0)- })+ it('stop during a slow cycle initialize leaves the store unavailable', async () => {+ const { link } = await symlinkedHostRoot()+ const realInitialize = GfsDownloadStore.prototype.initialize+ const retryStarted = deferred()+ const releaseRetry = deferred()+ let calls = 0+ vi.spyOn(GfsDownloadStore.prototype, 'initialize').mockImplementation(async function (+ this: GfsDownloadStore+ ) {+ calls += 1+ if (calls === 2) {+ retryStarted.resolve()+ await releaseRetry.promise+ }+ return realInitialize.call(this)+ })+ const runtime = await start(link, 25)+ expect(runtime.store.isAvailable()).toBe(false)+ await fs.rm(link)+ await fs.mkdir(link, { mode: 0o700 })+ await retryStarted.promise- it('T8: the serialized recovery-required line names the writer refusal branch as writerDetail', async () => {- const value = await root()- const bootstrap = new GfsDownloadStore(value)- await bootstrap.initialize()- await bootstrap.close()- const storeRoot = join(await fs.realpath(value), '.gfs-download-store')- const database = await fs.stat(join(storeRoot, 'writer-v2.sqlite'), { bigint: true })- await fs.writeFile(- join(storeRoot, 'writer.lock'),- JSON.stringify({- schemaVersion: 2,- ownership: 'sqlite-exclusive-v1',- databaseDevice: String(database.dev),- databaseInode: String(database.ino + 1n),- }),- { mode: 0o600 }- )+ const stopping = runtime.stop()+ releaseRetry.resolve()+ await stopping- serializedErrorLines.length = 0- const runtime = await bootstrapGfsRuntime(value)- runtimes.push(runtime)+ // Witness: the slow retry ran to completion before the store was closed.+ expect(calls).toBe(2)expect(runtime.store.isAvailable()).toBe(false)-- const entries = serializedErrorLines- .filter(line => line.startsWith('{'))- .map(line => JSON.parse(line) as Record<string, unknown>)- const recovery = entries.filter(- entry =>- entry.msg ===- 'GFS download store entered recovery-required state; managed GFS operations are disabled'- )- expect(recovery).toHaveLength(1)- expect(recovery[0]).toMatchObject({- level: 'error',- component: 'gfs-runtime',- writerDetail: 'database_identity_changed',- err: { name: 'GfsDownloadStoreError', code: 'writer_locked' },- available: false,- })+ await expect(runtime.store.initialize()).rejects.toMatchObject({ code: 'download_busy' })})})diff --git a/mcp-host/src/agent/__tests__/taskExecutor.gfsExecutionSafety.test.ts b/mcp-host/src/agent/__tests__/taskExecutor.gfsExecutionSafety.test.tsindex b47a13c16..1a625f5f7 100644--- a/mcp-host/src/agent/__tests__/taskExecutor.gfsExecutionSafety.test.ts+++ b/mcp-host/src/agent/__tests__/taskExecutor.gfsExecutionSafety.test.ts@@ -1,9 +1,9 @@import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'import { spawn } from 'child_process'import * as fs from 'node:fs/promises'-import type { FileHandle } from 'node:fs/promises'import { tmpdir } from 'node:os'import { join } from 'node:path'+import { buildDevStore } from '../../__tests__/fixtures/devGfsStoreFixture'import { config as appConfig } from '../../config'import { ConversationManager } from '../../core/conversation/conversation'import { SimpleEventEmitter } from '../../core/orchestration/eventEmitter'@@ -98,53 +98,56 @@ afterEach(async () => {Object.assign(appConfig.nativeTool, savedNativeTool)})+/**+ * A store whose Host root is a symlink: initialize refuses it with+ * workspace_unavailable. The shell workspace stays on the real temp root.+ */async function unavailableStore() {const root = await fs.mkdtemp(join(tmpdir(), 'gfs-shell-safety-'))roots.push(root)- await fs.mkdir(join(root, '.gfs-download-store'), { mode: 0o700 })- const store = new GfsDownloadStore(root)+ const target = join(root, 'store-target')+ await fs.mkdir(target, { mode: 0o700 })+ const link = join(root, 'store-link')+ await fs.symlink(target, link)+ const store = new GfsDownloadStore(link)stores.push(store)- // A store directory without a ledger must refuse to initialize. Capture the- // rejection instead of swallowing it so tests can assert which failure the- // store reported; an initialize that resolves breaks the fixture loudly.+ // Capture the rejection instead of swallowing it so tests can assert which+ // failure the store reported; an initialize that resolves breaks the fixture+ // loudly.const initError = await store.initialize().then(() => {- throw new Error('unavailableStore fixture: initialize() resolved on a ledger-less store')+ throw new Error('unavailableStore fixture: initialize() resolved on a symlinked Host root')},(error: unknown) => error)+ expect(initError).toMatchObject({ code: 'workspace_unavailable' })return { root, store, initError }}/**- * A closed store whose ledger carries a processing lease written by a pre-#1019- * Host that crashed: empty and owned by a foreign writer session. By default- * the lease is expired; `live` seeds one whose expiry is still in the future.+ * A store whose Host root still holds what the pre-#1028 image left on disk: a+ * ledger with an empty processing lease written by a crashed Host, the v2+ * writer fence and its database. By default the lease is expired; `live`+ * seeds one whose expiry is still in the future.*/-async function seedLegacyLeaseLedger({ live = false }: { live?: boolean } = {}) {+async function preRedesignStore({ live = false }: { live?: boolean } = {}) {const root = await fs.mkdtemp(join(tmpdir(), 'gfs-shell-safety-legacy-'))roots.push(root)- const first = new GfsDownloadStore(root)- await first.initialize()- await first.close()- const ledgerPath = join(root, '.gfs-download-store', 'ledger-v1.json')- const ledger = JSON.parse(await fs.readFile(ledgerPath, 'utf8'))- const leaseId = '77777777-7777-4777-8777-777777777777'- const seededLease = {- leaseId,- callerIdentity: '_system',- recordIds: [],- acquiredAt: new Date(Date.now() - 120_000).toISOString(),- expiresAt: new Date(Date.now() + (live ? 600_000 : -60_000)).toISOString(),- writerSessionId: '88888888-8888-4888-8888-888888888888',+ const devStore = await buildDevStore(root, {+ ledger: 'processingLeasesEmpty',+ fence: 'v2-matching',+ sqlite: true,+ userDirs: [],+ lease: live ? 'live' : 'expired',+ })+ if (devStore.ledgerText === undefined)+ throw new Error('preRedesignStore fixture: no ledger was written')+ const ledger = JSON.parse(devStore.ledgerText) as {+ processingLeases: Record<string, { expiresAt: string }>}- ledger.processingLeases = { [leaseId]: seededLease }- await fs.writeFile(ledgerPath, JSON.stringify(ledger), { mode: 0o600 })- return { root, ledgerPath, seededLease }-}--async function legacyLeaseStore({ live = false }: { live?: boolean } = {}) {- const { root, seededLease } = await seedLegacyLeaseLedger({ live })+ const [seededLease] = Object.values(ledger.processingLeases)+ if (seededLease === undefined)+ throw new Error('preRedesignStore fixture: no processing lease was written')const store = new GfsDownloadStore(root)stores.push(store)await store.initialize()@@ -173,7 +176,7 @@ async function shellScenario({approvalEnabled = true,shellApprovalDisabled = false,healthy = false,- legacyLease = false,+ preRedesign = false,channelCaller = false,missingCallerRoot = false,calls = [{ id: 'shell-safety', name: 'shell_exec', arguments: { command: 'pwd' } }],@@ -185,7 +188,7 @@ async function shellScenario({approvalEnabled?: booleanshellApprovalDisabled?: booleanhealthy?: boolean- legacyLease?: boolean+ preRedesign?: booleanchannelCaller?: booleanmissingCallerRoot?: booleancalls?: ToolCall[]@@ -198,8 +201,8 @@ async function shellScenario({appConfig.enableApproval = approvalEnabledconst fixture: StoreFixture = storeFixture? await storeFixture()- : legacyLease- ? await legacyLeaseStore()+ : preRedesign+ ? await preRedesignStore(): healthy? await healthyStore(): await unavailableStore()@@ -323,10 +326,10 @@ it.each([})-it('X1: an inherited legacy lease no longer blocks an approved shell or GFS delivery', async () => {+it('X1: a store left by the pre-#1028 image no longer blocks an approved shell or GFS delivery', async () => {const scenario = await shellScenario({source: 'channel',- legacyLease: true,+ preRedesign: true,channelCaller: true,})expect(scenario.store.isAvailable()).toBe(true)@@ -346,7 +349,7 @@ it('X1: an inherited legacy lease no longer blocks an approved shell or GFS deliexpect(toolResult).not.toContain('download_busy')})-it('X2: a store at corrupt_store_ledger keeps shell and GFS reads but withdraws delivery', async () => {+it('X2: a store at workspace_unavailable keeps shell and GFS reads but withdraws delivery', async () => {const scenario = await shellScenario({source: 'cron',calls: [@@ -358,10 +361,10 @@ it('X2: a store at corrupt_store_ledger keeps shell and GFS reads but withdraws{ id: 'shell-safety', name: 'shell_exec', arguments: { command: 'pwd' } },],})- // Witness: the store refused to initialize with exactly corrupt_store_ledger,+ // Witness: the store refused to initialize with exactly workspace_unavailable,// not with any other initialize failure.expect(scenario.storeInitError).toBeInstanceOf(GfsDownloadStoreError)- expect(scenario.storeInitError).toMatchObject({ code: 'corrupt_store_ledger' })+ expect(scenario.storeInitError).toMatchObject({ code: 'workspace_unavailable' })expect(scenario.store.isAvailable()).toBe(false)await scenario.executor.run()@@ -383,7 +386,7 @@ it('X2: a store at corrupt_store_ledger keeps shell and GFS reads but withdrawsexpect(JSON.stringify(scenario.providerCalls.at(-1))).toContain(scenario.callerWorkspace)})-it('X2b: a store at corrupt_store_ledger still answers admitted inline reads, accessible and resolve', async () => {+it('X2b: a store at workspace_unavailable still answers admitted inline reads, accessible and resolve', async () => {const smallResourceId = 'd'.repeat(32)const smallSource = {kind: 'gfs' as const,@@ -425,9 +428,9 @@ it('X2b: a store at corrupt_store_ledger still answers admitted inline reads, ac{ id: 'gfs-resolve', name: 'clerum__gfs_resolve', arguments: { uri: accessibleUri } },],})- // Same fixture as X2: the store refused to initialize with corrupt_store_ledger.+ // Same fixture as X2: the store refused to initialize with workspace_unavailable.expect(scenario.storeInitError).toBeInstanceOf(GfsDownloadStoreError)- expect(scenario.storeInitError).toMatchObject({ code: 'corrupt_store_ledger' })+ expect(scenario.storeInitError).toMatchObject({ code: 'workspace_unavailable' })expect(scenario.store.isAvailable()).toBe(false)await scenario.executor.run()@@ -617,10 +620,10 @@ function shellDispatchWindows(timeline: string[]) {}}-it('X1-shell: an inherited legacy lease does not stop an approved shell (#1019)', async () => {+it('X1-shell: a store left by the pre-#1028 image does not stop an approved shell (#1019)', async () => {const scenario = await shellScenario({source: 'channel',- legacyLease: true,+ preRedesign: true,channelCaller: true,})await scenario.executor.run()@@ -636,10 +639,10 @@ it('X1-shell: an inherited legacy lease does not stop an approved shell (#1019)'expect(scenario.onFail).not.toHaveBeenCalled()})-it('X1-delivery: an inherited legacy lease is discarded and GFS delivery stays advertised (#1019)', async () => {+it('X1-delivery: a store left by the pre-#1028 image is ignored and GFS delivery stays advertised (#1019)', async () => {const scenario = await shellScenario({source: 'channel',- legacyLease: true,+ preRedesign: true,channelCaller: true,})await scenario.executor.run()@@ -668,34 +671,28 @@ function shellToolResult(providerCalls: ChatMessage[][], toolCallId: string): streturn typeof message.content === 'string' ? message.content : JSON.stringify(message.content)}-async function liveLegacyLeaseScenario(call: ToolCall) {+async function livePreRedesignScenario(call: ToolCall) {let seededLease: { expiresAt: string } | undefinedconst scenario = await shellScenario({source: 'channel',channelCaller: true,calls: [call],storeFixture: async () => {- const fixture = await legacyLeaseStore({ live: true })+ const fixture = await preRedesignStore({ live: true })seededLease = fixture.seededLeasereturn fixture},})- // Witness: the seeded lease is live by its own expiry, so its discard cannot+ // Witness: the seeded lease is live by its own expiry, so ignoring it cannot// be explained by expiry.expect(seededLease).toBeDefined()expect(Date.parse(seededLease!.expiresAt)).toBeGreaterThan(Date.now())return scenario}-async function persistedLedger(root: string): Promise<Record<string, unknown>> {- return JSON.parse(- await fs.readFile(join(root, '.gfs-download-store', 'ledger-v1.json'), 'utf8')- ) as Record<string, unknown>-}--it('X1-shell-live: an inherited non-expired legacy lease does not stop an approved shell (#1019)', async () => {+it('X1-shell-live: a store with a non-expired legacy lease left by the pre-#1028 image does not stop an approved shell (#1019)', async () => {const { call, marker } = markerCall('shell-live', 'X1_SHELL_LIVE')- const scenario = await liveLegacyLeaseScenario(call)+ const scenario = await livePreRedesignScenario(call)await scenario.executor.run()// Witness: the executor reached the live approval gate for shell_exec.expect(scenario.onApprovalNeeded).toHaveBeenCalledTimes(1)@@ -707,14 +704,11 @@ it('X1-shell-live: an inherited non-expired legacy lease does not stop an approvexpect(vi.mocked(spawn).mock.calls[0]![2]).toMatchObject({ cwd: scenario.callerWorkspace })expect(shellToolResult(scenario.providerCalls, call.id)).toContain(marker)expect(scenario.onFail).not.toHaveBeenCalled()- const onDisk = await persistedLedger(scenario.root)- expect(onDisk).toHaveProperty('records')- expect(onDisk).not.toHaveProperty('processingLeases')})-it('X1-delivery-live: an inherited non-expired legacy lease is discarded and GFS delivery stays advertised (#1019)', async () => {+it('X1-delivery-live: a store with a non-expired legacy lease left by the pre-#1028 image is ignored and GFS delivery stays advertised (#1019)', async () => {const { call, marker } = markerCall('shell-live-delivery', 'X1_DELIVERY_LIVE')- const scenario = await liveLegacyLeaseScenario(call)+ const scenario = await livePreRedesignScenario(call)await scenario.executor.run()// Witness: the provider received a tool list built by the executor's registry.expect(scenario.advertisedTools.length).toBeGreaterThan(0)@@ -727,9 +721,6 @@ it('X1-delivery-live: an inherited non-expired legacy lease is discarded and GFSexpect(shellToolResult(scenario.providerCalls, call.id)).toContain(marker)expect(scenario.onFail).not.toHaveBeenCalled()- const onDisk = await persistedLedger(scenario.root)- expect(onDisk).toHaveProperty('records')- expect(onDisk).not.toHaveProperty('processingLeases')})describe('U5-TE: TaskExecutor runs a managed shell with a timeout above the former lease ceiling (#1021)', () => {@@ -792,25 +783,15 @@ it('X3-TE: a shell dispatch inside TaskExecutor makes zero GFS download store caexpect(executeWindows[0]!.storeCalls).toEqual([])})-/** Another live writer holds the store directory, so this store cannot initialize. */-async function contendedStore(): Promise<StoreFixture> {- const root = await fs.mkdtemp(join(tmpdir(), 'gfs-shell-safety-contended-'))+/** A store that was constructed but never initialized. */+async function uninitializedStore(): Promise<StoreFixture> {+ const root = await fs.mkdtemp(join(tmpdir(), 'gfs-shell-safety-uninitialized-'))roots.push(root)- const holder = new GfsDownloadStore(root)- stores.push(holder)- await holder.initialize()const store = new GfsDownloadStore(root)stores.push(store)- const initError = await store.initialize().then(- () => {- throw new Error('contendedStore fixture: initialize() resolved while another writer held it')- },- (error: unknown) => error- )- // Witness: the holder is the live writer the contended store lost to.- expect(holder.isAvailable()).toBe(true)- expect(initError).toMatchObject({ code: 'writer_locked', transientWriterContention: true })- return { root, store, initError }+ // Witness: a store that never ran initialize() reports itself unavailable.+ expect(store.isAvailable()).toBe(false)+ return { root, store }}/** A store that initialized and was then closed. */@@ -822,58 +803,11 @@ async function closedStore(): Promise<StoreFixture> {return { root, store }}-/**- * A store whose initialize rejects because the persist of the legacy-lease- * discard fails with EIO before the ledger rename.- */-async function discardPersistFailedStore(): Promise<StoreFixture> {- const { root, ledgerPath } = await seedLegacyLeaseLedger()- const probe = await fs.open(ledgerPath, 'r')- const prototype = Object.getPrototypeOf(probe) as FileHandle- await probe.close()- const originalWriteFile = prototype.writeFile- let failedLedgerWrite: Record<string, unknown> | undefined- const writeSpy = vi.spyOn(prototype, 'writeFile').mockImplementation(async function (- this: FileHandle,- ...args: Parameters<FileHandle['writeFile']>- ) {- const [data] = args- if (failedLedgerWrite === undefined && typeof data === 'string') {- const written = JSON.parse(data) as Record<string, unknown>- if ('records' in written && !('processingLeases' in written)) {- failedLedgerWrite = written- throw Object.assign(new Error('injected ledger write failure'), { code: 'EIO' })- }- }- return originalWriteFile.apply(this, args)- })- const store = new GfsDownloadStore(root)- stores.push(store)- let initError: unknown- try {- initError = await store.initialize().then(- () => {- throw new Error('discardPersistFailedStore fixture: initialize() resolved')- },- (error: unknown) => error- )- } finally {- writeSpy.mockRestore()- }- // Witness: the failing write was the discard's own lease-free ledger, and the- // lease is still on disk.- expect(initError).toMatchObject({ code: 'EIO', message: 'injected ledger write failure' })- expect(failedLedgerWrite).toBeDefined()- expect(failedLedgerWrite).not.toHaveProperty('processingLeases')- expect(JSON.parse(await fs.readFile(ledgerPath, 'utf8'))).toHaveProperty('processingLeases')- return { root, store, initError }-}-describe('X6: an approved shell runs while the store is unavailable', () => {it.each([- ['writer contention', contendedStore],+ ['never initialized', uninitializedStore],['store closed', closedStore],- ['initialize rejected by an EIO persist during the legacy discard', discardPersistFailedStore],+ ['initialize rejected with workspace_unavailable', unavailableStore],] as const)('%s', async (_label, storeFixture) => {const { call, marker } = markerCall('shell-unavailable', 'X6_SHELL')const timeline: string[] = []diff --git a/mcp-host/src/agent/__tests__/taskExecutor.gfsPreparation.test.ts b/mcp-host/src/agent/__tests__/taskExecutor.gfsPreparation.test.tsindex f3554d189..95698a5e7 100644--- a/mcp-host/src/agent/__tests__/taskExecutor.gfsPreparation.test.ts+++ b/mcp-host/src/agent/__tests__/taskExecutor.gfsPreparation.test.ts@@ -469,7 +469,7 @@ describe('TaskExecutor prepares admitted GFS files before its first model call',expect(test.executor.executorState).toBe('waiting_approval')expect(test.onApprovalNeeded).toHaveBeenCalledTimes(1)expect(test.requests).toHaveLength(1)- expect(test.store.debugUsage().files).toBe(1)+ expect((await test.store.debugInventory()).files).toBe(1)expect(test.releaseReceiptOwner).not.toHaveBeenCalled()expect(JSON.stringify(test.executor.pendingApproval)).not.toContain(bytes.toString())expect(JSON.stringify(test.executor.pendingApproval)).not.toContain(bytes.toString('base64'))@@ -573,7 +573,7 @@ describe('TaskExecutor prepares admitted GFS files before its first model call',expect(test.contentRequests).toBe(1)expect(test.requests).toEqual([])- expect(test.store.debugUsage().files).toBe(0)+ expect((await test.store.debugInventory()).files).toBe(0)expect(test.releaseReceiptOwner).toHaveBeenCalledWith(test.task.id, 'unit-caller')})@@ -590,7 +590,7 @@ describe('TaskExecutor prepares admitted GFS files before its first model call',expect(test.contentRequests).toBe(1)expect(test.requests).toHaveLength(1)- expect(test.store.debugUsage().files).toBe(0)+ expect((await test.store.debugInventory()).files).toBe(0)expect(test.releaseReceiptOwner).toHaveBeenCalledWith(test.task.id, 'unit-caller')})@@ -639,7 +639,7 @@ describe('TaskExecutor prepares admitted GFS files before its first model call',await runexpect(order).toEqual(['admission-settled', 'owner-release'])- expect(test.store.debugUsage().files).toBe(0)+ expect((await test.store.debugInventory()).files).toBe(0)expect(test.onFail).not.toHaveBeenCalled()expect(test.lifecycle.getStatus(test.task.id)).toBe('cancelled')})@@ -672,7 +672,7 @@ describe('TaskExecutor prepares admitted GFS files before its first model call',await runexpect(test.requests).toEqual([])- expect(test.store.debugUsage().files).toBe(0)+ expect((await test.store.debugInventory()).files).toBe(0)expect(test.releaseReceiptOwner).toHaveBeenCalledWith(test.task.id, 'unit-caller')})diff --git a/mcp-host/src/agent/taskExecutor.ts b/mcp-host/src/agent/taskExecutor.tsindex 16ea13e30..81e1c945e 100644--- a/mcp-host/src/agent/taskExecutor.ts+++ b/mcp-host/src/agent/taskExecutor.ts@@ -1067,9 +1067,12 @@ export class TaskExecutor {}/**- * A retention owner spans preparation, an approval suspension, and cold resume.- * Release happens only after this executor reaches a terminal state. A failed- * release leaves the owner recorded, so its retained records stay protected.+ * A retention owner spans preparation and an approval suspension in this+ * process; pins live in memory, so after a Host restart a cold resume finds+ * no pin and its file may have expired or been evicted, and the model+ * downloads it again. Release happens only after this executor reaches a+ * terminal state. A failed release leaves the pin in place, so its files stay+ * protected until the Host restarts.*/private settleGfsRetentionOwner(): Promise<void> {if (this.state === 'waiting_approval' && !this.abortController.signal.aborted)diff --git a/mcp-host/src/core/tools/__tests__/nativeToolRegistry.shellStoreDecoupling.test.ts b/mcp-host/src/core/tools/__tests__/nativeToolRegistry.shellStoreDecoupling.test.tsindex cb0164317..8ddfbbe68 100644--- a/mcp-host/src/core/tools/__tests__/nativeToolRegistry.shellStoreDecoupling.test.ts+++ b/mcp-host/src/core/tools/__tests__/nativeToolRegistry.shellStoreDecoupling.test.ts@@ -139,7 +139,7 @@ describe('managed shell_exec without the GFS download store (#1019), registry-le'publish','reusableReceipt','fail',- 'inspect',+ 'readManagedFile','releaseReceiptOwner','cleanupExpired','close',diff --git a/mcp-host/src/gfsRuntime.ts b/mcp-host/src/gfsRuntime.tsindex 3b56cf54e..3d554b26d 100644--- a/mcp-host/src/gfsRuntime.ts+++ b/mcp-host/src/gfsRuntime.ts@@ -9,28 +9,24 @@ export interface GfsRuntime {}export interface GfsRuntimeOptions {- retryDelayMs?: number- maxRetryAttempts?: number+ /** Interval of the lifecycle cycle: initialize when unavailable, otherwise sweep. */+ cycleMs?: number}-function transientWriterContention(error: unknown): boolean {- return (- error instanceof GfsDownloadStoreError &&- error.code === 'writer_locked' &&- error.transientWriterContention === true- )-}+const DEFAULT_CYCLE_MS = 60 * 60 * 1000-// The logger keeps only name/code/status of an Error, so the writer refusal-// branch is logged as its own field.-function writerDetail(error: unknown): string | undefined {- return error instanceof GfsDownloadStoreError ? error.detail : undefined+function failureCode(error: unknown): string {+ if (error instanceof GfsDownloadStoreError) return error.code+ const code = (error as NodeJS.ErrnoException)?.code+ return typeof code === 'string' ? code : 'unknown'}/*** Contain GFS store failure without removing the caller workspace or falling* back to an unprotected shared-root shell. Ordinary RPC startup continues;* `store.isAvailable()` is the single managed-operation availability signal.+ * A store that failed to initialize is retried by the same cycle that sweeps,+ * so delivery returns without a Host restart once the cause is gone.*/export async function bootstrapGfsRuntime(hostRoot: string,@@ -38,142 +34,83 @@ export async function bootstrapGfsRuntime(): Promise<GfsRuntime> {const workspaceProvider = new ScopedWorkspaceProvider(hostRoot)const store = new GfsDownloadStore(hostRoot)+ const cycleMs = options.cycleMs ?? DEFAULT_CYCLE_MS+ if (!Number.isSafeInteger(cycleMs) || cycleMs < 25)+ throw new Error('GFS runtime cycleMs must be an integer of at least 25ms')let stopped = false- let lifecycleTimer: ReturnType<typeof setTimeout> | undefined- let lifecycleInFlight: Promise<void> | undefined+ let cycleTimer: ReturnType<typeof setTimeout> | undefined+ let cycleInFlight: Promise<void> | undefinedlet stopping: Promise<void> | undefined- let attempts = 0- const retryDelayMs = options.retryDelayMs ?? 2_000- const maxRetryAttempts = options.maxRetryAttempts ?? 60- if (!Number.isSafeInteger(retryDelayMs) || retryDelayMs < 25)- throw new Error('GFS runtime retryDelayMs must be an integer of at least 25ms')- if (!Number.isSafeInteger(maxRetryAttempts) || maxRetryAttempts < 1)- throw new Error('GFS runtime maxRetryAttempts must be a positive integer')- type LifecycleStep = { kind: 'retry' | 'cleanup'; delayMs: number }- const clearLifecycleTimer = () => {- if (lifecycleTimer) clearTimeout(lifecycleTimer)- lifecycleTimer = undefined- }- // A store whose initialize() resolved is available; it becomes unavailable- // only afterwards, when a persist fails (`unsafe`) or writer ownership is- // lost. The periodic lifecycle then ends for good, so that is logged as an- // error rather than returning silently.- const lifecycleStopped = (): undefined => {- logger.error(- { component: 'gfs-runtime', available: false },- 'GFS download store is no longer available; periodic cleanup stopped and managed GFS operations are disabled'- )- return undefined- }- const cycle = async (kind: LifecycleStep['kind']): Promise<LifecycleStep | undefined> => {- if (stopped) return- if (kind === 'retry') {- attempts += 1- try {- await store.initialize()- } catch (error) {- if (stopped) return- if (!transientWriterContention(error)) {- logger.error(- {- component: 'gfs-runtime',- err: error,- writerDetail: writerDetail(error),- attempt: attempts,- },- 'GFS writer retry ended in recovery-required state'- )- return- }- if (attempts >= maxRetryAttempts) {- logger.error(- { component: 'gfs-runtime', attempt: attempts },- 'GFS writer retry budget exhausted; managed operations remain disabled'- )- return- }- return { kind: 'retry', delayMs: retryDelayMs }- }+ const initialize = async (): Promise<void> => {+ try {+ await store.initialize()+ } catch (error) {if (stopped) return- logger.info(- { component: 'gfs-runtime', attempt: attempts },- 'GFS writer retry initialization completed'+ logger.error(+ { component: 'gfs-runtime', code: failureCode(error) },+ 'GFS download store unavailable; managed GFS operations are disabled and initialization is retried by the hourly cycle')}+ }++ const cycle = async (): Promise<void> => {if (stopped) return- if (!store.isAvailable()) return lifecycleStopped()+ if (!store.isAvailable()) {+ await initialize()+ return+ }try {await store.cleanupExpired()} catch (error) {- logger.warn({ component: 'gfs-runtime', err: error }, 'GFS download cleanup failed')+ // cleanupExpired already counted sweep_failed for its own failures.+ logger.warn(+ { component: 'gfs-runtime', code: failureCode(error) },+ 'GFS download cleanup failed; the next cycle retries it'+ )}- if (stopped) return- if (!store.isAvailable()) return lifecycleStopped()- return { kind: 'cleanup', delayMs: 60 * 60 * 1000 }- }- const schedule = (step: LifecycleStep): void => {- if (stopped || lifecycleTimer || lifecycleInFlight) return- lifecycleTimer = setTimeout(() => {- lifecycleTimer = undefined- startCycle(step.kind)- }, step.delayMs)- lifecycleTimer.unref?.()- }- const startCycle = (kind: LifecycleStep['kind']): void => {- if (stopped || lifecycleInFlight) return- // One promise owns initialization and sweeps. Schedule only after it has- // settled, so a slow sweep never overlaps another mutation or loses its join.- lifecycleInFlight = cycle(kind).then(- next => {- lifecycleInFlight = undefined- if (!stopped && next) schedule(next)- },- error => {- lifecycleInFlight = undefined- logger.error(- { component: 'gfs-runtime', err: error, attempt: attempts },- 'Unexpected GFS runtime lifecycle error'- )- }- )}- try {- await store.initialize()- startCycle('cleanup')- } catch (error) {- if (transientWriterContention(error)) {- logger.warn(- { component: 'gfs-runtime', retryDelayMs, maxRetryAttempts },- 'GFS writer is transiently owned by another verified Pod; supervised retry started'- )- schedule({ kind: 'retry', delayMs: retryDelayMs })- } else {- logger.error(- {- component: 'gfs-runtime',- err: error,- writerDetail: writerDetail(error),- available: store.isAvailable(),+ const schedule = (): void => {+ if (stopped || cycleTimer || cycleInFlight) return+ cycleTimer = setTimeout(() => {+ cycleTimer = undefined+ // One promise owns initialization and sweeps; the next cycle is+ // scheduled only after it settles, so cycles never overlap.+ cycleInFlight = cycle().then(+ () => {+ cycleInFlight = undefined+ schedule()},- 'GFS download store entered recovery-required state; managed GFS operations are disabled'+ error => {+ cycleInFlight = undefined+ logger.error(+ { component: 'gfs-runtime', code: failureCode(error) },+ 'Unexpected GFS runtime cycle error'+ )+ schedule()+ })- }+ }, cycleMs)+ cycleTimer.unref?.()}+ cycleInFlight = initialize().finally(() => {+ cycleInFlight = undefined+ })+ await cycleInFlight+ schedule()+return {store,workspaceProvider,stop() {if (stopping) return stoppingstopped = true- clearLifecycleTimer()+ if (cycleTimer) clearTimeout(cycleTimer)+ cycleTimer = undefinedstopping = (async () => {- await lifecycleInFlight- // An initialized store can still own its writer after a failed persist- // has made isAvailable() false. Close unconditionally, including a- // retry that won during stop.+ await cycleInFlightawait store.close()})()return stoppingdiff --git a/mcp-host/src/internalTools/gfsContentDownload.test.ts b/mcp-host/src/internalTools/gfsContentDownload.test.tsindex 592ac99d0..ee96c6847 100644--- a/mcp-host/src/internalTools/gfsContentDownload.test.ts+++ b/mcp-host/src/internalTools/gfsContentDownload.test.ts@@ -3,10 +3,35 @@ import { createHash } from 'node:crypto'import * as fs from 'node:fs/promises'import { tmpdir } from 'node:os'import * as path from 'node:path'+import { register } from 'prom-client'import { downloadGfsContent } from './gfsContentDownload'import { readGfsMetadata } from './gfsContentRead'import { GfsDownloadStore } from './gfsDownloadStore'+const { rmFailure } = vi.hoisted(() => ({+ /** `target` is a name prefix under `.gfs-downloads`, e.g. the store's `.trash-` names. */+ rmFailure: { target: undefined as string | undefined, injected: 0 },+}))+// Pass-through `rm`: one test makes the store's removal of a transfer+// directory fail once, as a read-only parent or a busy mount would.+vi.mock('node:fs/promises', async original => {+ const actual = await original<typeof import('node:fs/promises')>()+ return {+ ...actual,+ rm: async (...values: Parameters<typeof actual.rm>) => {+ if (+ rmFailure.target !== undefined &&+ String(values[0]).includes(`/.gfs-downloads/${rmFailure.target}`)+ ) {+ rmFailure.target = undefined+ rmFailure.injected += 1+ throw Object.assign(new Error('simulated rm failure'), { code: 'EACCES' })+ }+ return actual.rm(...values)+ },+ }+})+const args = { drive: 'main', resourceId: 'a'.repeat(32) }const uri = `gfs://main/${args.resourceId}`let hostRoot: string@@ -73,6 +98,16 @@ function options(overrides: Record<string, unknown> = {}) {}}+async function expiryCount(outcome: string): Promise<number> {+ const metric = register.getSingleMetric('clerum_gfs_download_expiry_total')+ if (metric === undefined)+ throw new Error('metric clerum_gfs_download_expiry_total is not registered')+ const { values } = await metric.get()+ return values+ .filter(sample => sample.labels.outcome === outcome)+ .reduce((sum, sample) => sum + sample.value, 0)+}+async function retainedDirectories(): Promise<string[]> {return fs.readdir(path.join(callerRoot, '.gfs-downloads')).catch(() => [])}@@ -86,6 +121,8 @@ beforeEach(async () => {})afterEach(async () => {+ rmFailure.target = undefined+ rmFailure.injected = 0vi.useRealTimers()vi.restoreAllMocks()await fs.rm(hostRoot, { recursive: true, force: true })@@ -306,7 +343,7 @@ describe('governed GFS content download', () => {releaseSync()await rejectedexpect(await retainedDirectories()).toEqual([])- expect(store.debugUsage()).toMatchObject({ bytes: 0, files: 0 })+ expect(await store.debugInventory()).toMatchObject({ bytes: 0, files: 0 })await downloadGfsContent(harness(new Uint8Array([1])), args, options())})@@ -346,11 +383,11 @@ describe('governed GFS content download', () => {releaseRead()await rejectedexpect(await retainedDirectories()).toEqual([])- expect(store.debugUsage()).toMatchObject({ bytes: 0, files: 0 })+ expect(await store.debugInventory()).toMatchObject({ bytes: 0, files: 0 })await downloadGfsContent(harness(new Uint8Array([1])), args, options())})- it('keeps quota reserved when cancellation cleanup fails', async () => {+ it('releases the reservation when cancellation cleanup fails and a later sweep removes the leftover', async () => {const controller = new AbortController()const bytes = new Uint8Array([1, 2, 3, 4, 5])const probe = await fs.open(path.join(callerRoot, 'probe'), 'w')@@ -380,36 +417,46 @@ describe('governed GFS content download', () => {const rejected = expect(pending).rejects.toMatchObject({ code: 'cancelled' })await syncStartedconst [name] = await retainedDirectories()- const directory = path.join(callerRoot, '.gfs-downloads', name)- await fs.rename(directory, `${directory}.parked`)- await fs.writeFile(directory, 'not-a-directory')+ const removeFailed = await expiryCount('remove_failed')+ // The store renames a directory to a private `.trash-<uuid>` name before rm.+ rmFailure.target = '.trash-'controller.abort()releaseSync()await rejected- expect(store.debugUsage()).toMatchObject({ bytes: bytes.byteLength, files: 1 })- const ledger = JSON.parse(- await fs.readFile(path.join(hostRoot, '.gfs-download-store', 'ledger-v1.json'), 'utf8')- ) as { records: Record<string, { state: string; sha256?: string }> }- const [record] = Object.values(ledger.records)- expect(record?.state).toBe('cleanup_failed')- expect(record?.sha256).toBeUndefined()++ // Witness: the store's removal was attempted and failed exactly once.+ expect(rmFailure.injected).toBe(1)+ expect(await expiryCount('remove_failed')).toBe(removeFailed + 1)+ // The leftover is the renamed transfer: incomplete and holding no reservation.+ const retained = await retainedDirectories()+ expect(retained).not.toContain(name)+ expect(retained).toHaveLength(1)+ expect(retained[0]).toMatch(/^\.trash-[0-9a-f-]{36}$/)+ const directory = path.join(callerRoot, '.gfs-downloads', retained[0]!)+ await expect(fs.lstat(directory)).resolves.toBeDefined()+ await expect(fs.lstat(path.join(directory, 'meta.json'))).rejects.toMatchObject({+ code: 'ENOENT',+ })+ expect(await store.debugInventory()).toMatchObject({ bytes: 0, files: 0 })await expect(downloadGfsContent(harness(new Uint8Array([1])), args, options())).resolves.toMatchObject({sizeBytes: 1,})+ // The next admission read the disk and removed the leftover.+ await expect(fs.lstat(directory)).rejects.toMatchObject({ code: 'ENOENT' })})it('reuses a verified copy only after fresh authorization without renewing its TTL', async () => {const bytes = new Uint8Array([1, 2, 3, 4])const request = vi.fn(harness(bytes))const first = await downloadGfsContent(request, args, options())- const usage = store.debugUsage()+ const usage = await store.debugInventory()const second = await downloadGfsContent(request, args, options())expect(second).toEqual(first)expect(second.expiresAt).toBe(first.expiresAt)- expect(store.debugUsage()).toEqual(usage)+ expect(await store.debugInventory()).toEqual(usage)expect(request.mock.calls).toHaveLength(3)expect(request.mock.calls.filter(([url]) => url.includes('/content?'))).toHaveLength(1)})@@ -421,7 +468,7 @@ describe('governed GFS content download', () => {await expect(downloadGfsContent(request, args, options())).rejects.toThrow('gfsc 403')expect(request).toHaveBeenCalledOnce()- expect(store.debugUsage()).toMatchObject({ bytes: bytes.byteLength, files: 1 })+ expect(await store.debugInventory()).toMatchObject({ bytes: bytes.byteLength, files: 1 })})it('does not substitute a retained version for a newly stale reference', async () => {@@ -437,7 +484,7 @@ describe('governed GFS content download', () => {expect(request).toHaveBeenCalledOnce()})- it('replaces an invalid cached copy through the authorized source and keeps old bytes accounted', async () => {+ it('replaces an invalid cached copy through the authorized source and removes the invalid copy', async () => {const bytes = new Uint8Array([1, 2, 3])const first = await downloadGfsContent(harness(bytes), args, options())await fs.writeFile(path.join(callerRoot, first.path), new Uint8Array([3, 2, 1]))@@ -447,8 +494,10 @@ describe('governed GFS content download', () => {expect(second.id).not.toBe(first.id)expect(second.sha256).toBe(first.sha256)expect(request).toHaveBeenCalledTimes(2)- expect(store.debugRecord(first.id)?.state).toBe('missing')- expect(store.debugUsage()).toMatchObject({ bytes: bytes.byteLength * 2, files: 2 })+ await expect(+ fs.lstat(path.join(callerRoot, '.gfs-downloads', `input-${first.id}`))+ ).rejects.toMatchObject({ code: 'ENOENT' })+ expect(await store.debugInventory()).toMatchObject({ bytes: bytes.byteLength, files: 1 })await expect(store.readManagedFile(second.path, 'caller-a')).resolves.toEqual(Buffer.from(bytes))diff --git a/mcp-host/src/internalTools/gfsDownloadMetrics.test.ts b/mcp-host/src/internalTools/gfsDownloadMetrics.test.tsindex faea0f738..c6ccb539b 100644--- a/mcp-host/src/internalTools/gfsDownloadMetrics.test.ts+++ b/mcp-host/src/internalTools/gfsDownloadMetrics.test.ts@@ -7,9 +7,7 @@ import {recordGfsDownloadExpiry,recordGfsDownloadQuota,recordGfsDownloadTransfer,- recordGfsLegacyProcessingLeasesDiscarded,recordGfsShellOutputLimit,- setGfsQuarantinedRecords,} from './gfsDownloadMetrics'async function counterValue(name: string): Promise<number> {@@ -19,6 +17,16 @@ async function counterValue(name: string): Promise<number> {return values.reduce((sum, sample) => sum + sample.value, 0)}+async function expiryValue(outcome: string): Promise<number> {+ const metric = register.getSingleMetric('clerum_gfs_download_expiry_total')+ if (metric === undefined)+ throw new Error('metric clerum_gfs_download_expiry_total is not registered')+ const { values } = await metric.get()+ return values+ .filter(sample => sample.labels.outcome === outcome)+ .reduce((sum, sample) => sum + sample.value, 0)+}+describe('GFS download metrics', () => {it('registers fixed-cardinality instruments on the global metrics endpoint', async () => {const scraped = await register.metrics()@@ -38,7 +46,7 @@ describe('GFS download metrics', () => {exitGfsDownloadTransfer()recordGfsShellOutputLimit('output_limit_exceeded')recordGfsDownloadQuota('caller', 'storage_bytes')- recordGfsDownloadExpiry('cleanup_failed')+ recordGfsDownloadExpiry('remove_failed')const scraped = await register.metrics()expect(scraped).toContain('clerum_gfs_download_admissions_total{outcome="workspace_attempt"}')@@ -50,25 +58,34 @@ describe('GFS download metrics', () => {expect(scraped).toContain('clerum_gfs_download_quota_total{scope="caller",reason="storage_bytes"}')- expect(scraped).toContain('clerum_gfs_download_expiry_total{outcome="cleanup_failed"}')+ expect(scraped).toContain('clerum_gfs_download_expiry_total{outcome="remove_failed"}')})- it('U10: registers the legacy-lease discard counter and the quarantined-records gauge', async () => {+ it('U10: counts every expiry outcome and no longer registers the ledger-era instruments', async () => {+ const outcomes = [+ 'expired_removed',+ 'incomplete_removed',+ 'remove_failed',+ 'retired_legacy_store',+ 'sweep_failed',+ ] as const+ const before = new Map<string, number>()+ for (const outcome of outcomes) before.set(outcome, await expiryValue(outcome))+ for (const outcome of outcomes) recordGfsDownloadExpiry(outcome)+ for (const outcome of outcomes)+ expect(await expiryValue(outcome)).toBe(before.get(outcome)! + 1)+const scraped = await register.metrics()- expect(scraped).toContain('# TYPE clerum_gfs_legacy_processing_leases_discarded_total counter')- expect(scraped).toContain('# TYPE clerum_gfs_download_store_quarantined_records gauge')- const discardedBefore = await counterValue(- 'clerum_gfs_legacy_processing_leases_discarded_total'+ // Witness: the scrape carries the instruments this module still registers.+ expect(scraped).toContain('# TYPE clerum_gfs_download_expiry_total counter')+ expect(scraped).toContain('# TYPE clerum_gfs_download_quota_total counter')+ expect(scraped).not.toContain('clerum_gfs_legacy_processing_leases_discarded_total')+ expect(scraped).not.toContain('clerum_gfs_download_store_quarantined_records')+ expect(register.getSingleMetric('clerum_gfs_legacy_processing_leases_discarded_total')).toBe(+ undefined)- recordGfsLegacyProcessingLeasesDiscarded(2)- expect(await counterValue('clerum_gfs_legacy_processing_leases_discarded_total')).toBe(- discardedBefore + 2+ expect(register.getSingleMetric('clerum_gfs_download_store_quarantined_records')).toBe(+ undefined)- // A gauge carries the current count: setting it twice never accumulates.- setGfsQuarantinedRecords(3)- setGfsQuarantinedRecords(3)- expect(await counterValue('clerum_gfs_download_store_quarantined_records')).toBe(3)- setGfsQuarantinedRecords(0)- expect(await counterValue('clerum_gfs_download_store_quarantined_records')).toBe(0)})})diff --git a/mcp-host/src/internalTools/gfsDownloadMetrics.ts b/mcp-host/src/internalTools/gfsDownloadMetrics.tsindex 44c0008b2..ecb9fc7e1 100644--- a/mcp-host/src/internalTools/gfsDownloadMetrics.ts+++ b/mcp-host/src/internalTools/gfsDownloadMetrics.ts@@ -49,7 +49,7 @@ export type GfsDownloadExpiryOutcome =| 'expired_removed'| 'incomplete_removed'| 'remove_failed'- | 'cleanup_failed'+ | 'retired_legacy_store'| 'sweep_failed'const gfsDownloadAdmissionsTotal = getOrCreateCounter({@@ -94,25 +94,6 @@ const gfsDownloadExpiryTotal = getOrCreateCounter({labelNames: ['outcome'] as const as Array<'outcome'>,})-const gfsLegacyProcessingLeasesDiscardedTotal = getOrCreateCounter({- name: 'clerum_gfs_legacy_processing_leases_discarded_total',- help: 'Legacy shell processing leases discarded from the GFS download store ledger at initialize.',- labelNames: [] as const as Array<never>,-})--const gfsDownloadStoreQuarantinedRecords = getOrCreateGauge({- name: 'clerum_gfs_download_store_quarantined_records',- help: 'GFS download store records currently quarantined, set at each initialize after reconcile; they stay charged to quota. Operator recovery reclassifies only copies whose content still matches their recorded hash; any other quarantined copy stays charged, and the operator recovery tool cannot release it.',-})--export function recordGfsLegacyProcessingLeasesDiscarded(count: number): void {- gfsLegacyProcessingLeasesDiscardedTotal.inc(count)-}--export function setGfsQuarantinedRecords(count: number): void {- gfsDownloadStoreQuarantinedRecords.set(count)-}-export function recordGfsDownloadAdmission(outcome: GfsDownloadAdmissionOutcome): void {gfsDownloadAdmissionsTotal.labels(outcome).inc()}diff --git a/mcp-host/src/internalTools/gfsDownloadStore.test.ts b/mcp-host/src/internalTools/gfsDownloadStore.test.tsindex 31173b731..17b32cd0e 100644--- a/mcp-host/src/internalTools/gfsDownloadStore.test.ts+++ b/mcp-host/src/internalTools/gfsDownloadStore.test.ts@@ -1,842 +1,811 @@import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'-import { createHash } from 'node:crypto'+import * as crypto from 'node:crypto'import * as fs from 'node:fs/promises'import { tmpdir } from 'node:os'import * as path from 'node:path'-import { ShellTool } from '../core/tools/shell'+import { register } from 'prom-client'+import { logger } from '../logger'import type { GfsImageSource } from '../visualInput/policy'-import { GfsDownloadStore } from './gfsDownloadStore'-import { GFS_FILE_LIMITS } from './gfsFilePolicy'--const source: GfsImageSource = {- kind: 'gfs',- drive: 'main',- resourceId: 'a'.repeat(32),- gfsUri: `gfs://main/${'a'.repeat(32)}`,- name: 'input.csv',- version: 7,-}-+import { GfsDownloadStore, GfsDownloadStoreError } from './gfsDownloadStore'++const { statfsBoundary, renameBoundary, rmBoundary, lstatBoundary, hashBoundary } = vi.hoisted(+ () => ({+ statfsBoundary: vi.fn(),+ renameBoundary: vi.fn(),+ rmBoundary: vi.fn(),+ lstatBoundary: vi.fn(),+ hashBoundary: vi.fn(),+ })+)+// Pass-through boundaries: every test starts with the real implementation and+// overrides one call only where it simulates a filesystem failure or observes+// an order. Test setup and assertions use the actual modules.+vi.mock('node:fs/promises', async original => ({+ ...(await original<typeof fs>()),+ statfs: statfsBoundary,+ rename: renameBoundary,+ rm: rmBoundary,+ lstat: lstatBoundary,+}))+vi.mock('node:crypto', async original => ({+ ...(await original<typeof crypto>()),+ createHash: hashBoundary,+}))++let nativeFs: typeof fs+let nativeCrypto: typeof cryptolet hostRoot: stringlet callerRoot: stringlet store: GfsDownloadStore+const extraStores: GfsDownloadStore[] = []++const CALLER = 'caller-a'++function sourceFor(index: number, version = 1): GfsImageSource {+ const resourceId = index.toString(16).padStart(32, '0')+ return {+ kind: 'gfs',+ drive: 'main',+ resourceId,+ gfsUri: `gfs://main/${resourceId}`,+ name: `fixture-${index}.bin`,+ version,+ }+}++function future(ms = 60 * 60_000): string {+ return new Date(Date.now() + ms).toISOString()+}++function digest(bytes: Buffer): string {+ return nativeCrypto.createHash('sha256').update(bytes).digest('hex')+}++async function callerDirectory(host: string, caller: string): Promise<string> {+ const root = path.join(host, 'users', caller)+ await nativeFs.mkdir(root, { recursive: true, mode: 0o700 })+ return root+}++function downloadDirectory(root: string, id: string): string {+ return path.join(root, '.gfs-downloads', `input-${id}`)+}++async function exists(target: string): Promise<boolean> {+ try {+ await nativeFs.lstat(target)+ return true+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') return false+ throw error+ }+}++async function startTransfer(+ target: GfsDownloadStore,+ root: string,+ caller: string,+ index: number,+ sizeBytes: number,+ options: { version?: number; owner?: string } = {}+) {+ const bytes = Buffer.alloc(sizeBytes, (index % 251) + 1)+ const transfer = await target.createTransfer({+ callerIdentity: caller,+ callerWorkspacePath: root,+ source: sourceFor(index, options.version ?? 1),+ sizeBytes,+ expiresAt: future(),+ ...(options.owner === undefined ? {} : { retentionOwnerId: options.owner }),+ })+ await nativeFs.writeFile(path.join(root, transfer.partialPath), bytes)+ return { transfer, bytes }+}++async function completedCopy(+ target: GfsDownloadStore,+ root: string,+ caller: string,+ index: number,+ sizeBytes: number,+ options: { version?: number; owner?: string } = {}+) {+ const { transfer, bytes } = await startTransfer(target, root, caller, index, sizeBytes, options)+ const receipt = await target.publish(transfer.id, caller, digest(bytes))+ return { receipt, bytes }+}++async function metricValue(name: string, labels: Record<string, string>): Promise<number> {+ const metric = register.getSingleMetric(name)+ if (metric === undefined) throw new Error(`metric ${name} is not registered`)+ const { values } = await metric.get()+ return values+ .filter(sample => Object.entries(labels).every(([key, value]) => sample.labels[key] === value))+ .reduce((sum, sample) => sum + sample.value, 0)+}++const expiryCount = (outcome: string) =>+ metricValue('clerum_gfs_download_expiry_total', { outcome })+const quotaCount = (scope: string, reason: string) =>+ metricValue('clerum_gfs_download_quota_total', { scope, reason })++async function openStore(host: string): Promise<GfsDownloadStore> {+ const opened = new GfsDownloadStore(host)+ extraStores.push(opened)+ await opened.initialize()+ return opened+}++/** Re-imports the store with environment limits; the logger of that copy is not spied. */+async function loadLimitedStore(env: Record<string, string>) {+ const saved = { ...process.env }+ Object.assign(process.env, env)+ try {+ vi.resetModules()+ const storeModule = await import('./gfsDownloadStore')+ const policyModule = await import('./gfsFilePolicy')+ return { Store: storeModule.GfsDownloadStore, limits: policyModule.GFS_FILE_LIMITS }+ } finally {+ for (const key of Object.keys(process.env)) if (!(key in saved)) delete process.env[key]+ for (const [key, value] of Object.entries(saved)) {+ if (value === undefined) delete process.env[key]+ else process.env[key] = value+ }+ }+}++async function limitedStore(env: Record<string, string>) {+ const { Store, limits } = await loadLimitedStore(env)+ const limited = new Store(hostRoot)+ extraStores.push(limited as unknown as GfsDownloadStore)+ await limited.initialize()+ return { limited, limits }+}++/** Distinct createdAt values so the oldest-first eviction order is deterministic. */+function tick(): void {+ vi.setSystemTime(Date.now() + 1_000)+}++async function writeMeta(directory: string, meta: Record<string, unknown>): Promise<void> {+ await nativeFs.writeFile(path.join(directory, 'meta.json'), JSON.stringify(meta), {+ mode: 0o600,+ })+}++function metaFor(id: string, bytes: Buffer, overrides: Record<string, unknown> = {}) {+ const now = Date.now()+ return {+ schemaVersion: 1,+ id,+ callerIdentity: CALLER,+ source: sourceFor(900),+ sizeBytes: bytes.byteLength,+ sha256: digest(bytes),+ createdAt: new Date(now).toISOString(),+ expiresAt: new Date(now + 60 * 60_000).toISOString(),+ ...overrides,+ }+}++async function handMadeDirectory(root: string): Promise<{ id: string; directory: string }> {+ const id = nativeCrypto.randomUUID()+ const directory = downloadDirectory(root, id)+ await nativeFs.mkdir(directory, { recursive: true, mode: 0o700 })+ await nativeFs.chmod(path.dirname(directory), 0o700)+ return { id, directory }+}beforeEach(async () => {- hostRoot = await fs.mkdtemp(path.join(tmpdir(), 'gfs-download-store-'))- callerRoot = path.join(hostRoot, 'users', 'caller-a')- await fs.mkdir(callerRoot, { recursive: true, mode: 0o700 })+ nativeFs = await vi.importActual<typeof fs>('node:fs/promises')+ nativeCrypto = await vi.importActual<typeof crypto>('node:crypto')+ vi.useFakeTimers({ toFake: ['Date'] })+ vi.setSystemTime(new Date('2026-10-08T10:00:00.000Z'))+ for (const boundary of [statfsBoundary, renameBoundary, rmBoundary, lstatBoundary, hashBoundary])+ boundary.mockReset()+ statfsBoundary.mockImplementation(nativeFs.statfs)+ renameBoundary.mockImplementation(nativeFs.rename)+ rmBoundary.mockImplementation(nativeFs.rm)+ lstatBoundary.mockImplementation(nativeFs.lstat)+ hashBoundary.mockImplementation((algorithm: string) => nativeCrypto.createHash(algorithm))+ hostRoot = await nativeFs.mkdtemp(path.join(tmpdir(), 'gfs-store-'))+ callerRoot = await callerDirectory(hostRoot, CALLER)store = new GfsDownloadStore(hostRoot)await store.initialize()})afterEach(async () => {vi.restoreAllMocks()- await store.close(0).catch(async () => {- // Fixture consumers are settled by test teardown, even for negative paths.- await (- store as unknown as { writerLease?: { release(): Promise<void> } }- ).writerLease?.release()- })- await fs.rm(hostRoot, { recursive: true, force: true })+ vi.useRealTimers()+ for (const opened of extraStores.splice(0)) await opened.close(0)+ await store.close(0)+ await nativeFs.rm(hostRoot, { recursive: true, force: true })})-describe('GFS download store', () => {- it('creates a caller-relative transfer and publishes an exact completed record', async () => {- const expiresAt = new Date(Date.now() + 60_000).toISOString()- const transfer = await store.createTransfer({- callerIdentity: 'caller-a',- callerWorkspacePath: callerRoot,- source,- sizeBytes: 7,- expiresAt,- })+describe('GFS download store: publication', () => {+ it('F1: publish writes meta.json before source and every visible source has a meta.json', async () => {+ const { transfer, bytes } = await startTransfer(store, callerRoot, CALLER, 1, 32)+ renameBoundary.mockClear()+ const receipt = await store.publish(transfer.id, CALLER, digest(bytes))++ const renamedTo = renameBoundary.mock.calls.map(([, to]) => path.basename(String(to)))+ // Witness: both renames of the publication happened.+ expect(renamedTo).toHaveLength(2)+ expect(renamedTo).toEqual(['meta.json', 'source'])+ const directory = downloadDirectory(callerRoot, receipt.id)+ expect((await nativeFs.readdir(directory)).sort()).toEqual(['meta.json', 'source'])+ const meta = JSON.parse(await nativeFs.readFile(path.join(directory, 'meta.json'), 'utf8'))+ expect(meta).toMatchObject({+ schemaVersion: 1,+ id: receipt.id,+ callerIdentity: CALLER,+ sizeBytes: 32,+ sha256: digest(bytes),+ })+ expect(receipt.path).toBe(`.gfs-downloads/input-${receipt.id}/source`)+ })- expect(transfer.path).toMatch(/^\.gfs-downloads\/input-[a-f0-9-]+\/source$/)- expect(path.isAbsolute(transfer.path)).toBe(false)- expect(await fs.realpath(path.dirname(path.join(callerRoot, transfer.path)))).toBe(- await fs.realpath(- path.join(callerRoot, '.gfs-downloads', path.basename(path.dirname(transfer.path)))- )- )- expect((await fs.stat(path.join(callerRoot, `${transfer.path}.partial`))).mode & 0o777).toBe(- 0o600+ it('F2: a cancelled publish leaves an incomplete directory that is not reusable and is swept', async () => {+ const { transfer, bytes } = await startTransfer(store, callerRoot, CALLER, 2, 16)+ const controller = new AbortController()+ renameBoundary.mockImplementation(async (from: string, to: string) => {+ await nativeFs.rename(from, to)+ // Cancelled after meta.json is visible and before source is.+ if (path.basename(to) === 'meta.json') controller.abort()+ })+ await expect(+ store.publish(transfer.id, CALLER, digest(bytes), { signal: controller.signal })+ ).rejects.toMatchObject({ code: 'publication_cancelled' })+ renameBoundary.mockImplementation(nativeFs.rename)++ const directory = downloadDirectory(callerRoot, transfer.id)+ // Witness: the cancelled directory is on disk with meta.json and no source.+ expect((await nativeFs.readdir(directory)).sort()).toEqual(['meta.json', 'source.partial'])+ await expect(store.reusableReceipt(CALLER, sourceFor(2), 16)).resolves.toBeUndefined()++ // A Host stop leaves the reservation behind; the next start sweeps it.+ await store.close(0)+ const info = vi.spyOn(logger, 'info')+ await openStore(hostRoot)+ expect(await exists(directory)).toBe(false)+ expect(info).toHaveBeenCalledWith(+ expect.objectContaining({ component: 'GfsDownloadStore', removedIncomplete: 1 }),+ 'GFS download store initialized')+ })- await fs.writeFile(path.join(callerRoot, `${transfer.path}.partial`), 'fixture')- const receipt = await store.publish(- transfer.id,- 'caller-a',- createHash('sha256').update('fixture').digest('hex')- )+ it('F3: a crash between the two renames leaves meta.json and source.partial and the next store removes it', async () => {+ const bytes = Buffer.alloc(24, 7)+ const { id, directory } = await handMadeDirectory(callerRoot)+ await writeMeta(directory, metaFor(id, bytes))+ await nativeFs.writeFile(path.join(directory, 'source.partial'), bytes, { mode: 0o600 })+ const info = vi.spyOn(logger, 'info')- expect(receipt).toMatchObject({- source,- path: transfer.path,- sizeBytes: 7,- sha256: createHash('sha256').update('fixture').digest('hex'),- expiresAt,- })- await expect(fs.stat(path.join(callerRoot, `${transfer.path}.partial`))).rejects.toMatchObject({- code: 'ENOENT',- })- expect((await fs.stat(path.join(callerRoot, transfer.path))).mode & 0o777).toBe(0o600)- })+ await openStore(hostRoot)- it('binds receipts to the caller and fails closed on expiry or missing bytes', async () => {- const transfer = await store.createTransfer({- callerIdentity: 'caller-a',- callerWorkspacePath: callerRoot,- source,- sizeBytes: 1,- expiresAt: new Date(Date.now() + 60_000).toISOString(),- })- await fs.writeFile(path.join(callerRoot, `${transfer.path}.partial`), 'x')- const receipt = await store.publish(- transfer.id,- 'caller-a',- createHash('sha256').update('x').digest('hex')+ expect(await exists(directory)).toBe(false)+ expect(info).toHaveBeenCalledWith(+ expect.objectContaining({ removedIncomplete: 1, retainedCompleted: 0 }),+ 'GFS download store initialized')+ })- await expect(store.inspect(receipt.path, 'caller-b')).rejects.toMatchObject({- code: 'caller_mismatch',- })- await expect(store.inspect(receipt.path, 'caller-a')).resolves.toMatchObject({- id: transfer.id,- })-- await fs.writeFile(path.join(callerRoot, receipt.path), 'y')- await expect(store.inspect(receipt.path, 'caller-a')).rejects.toMatchObject({- code: 'download_missing',- })- await fs.writeFile(path.join(callerRoot, receipt.path), 'x')- await expect(store.inspect(receipt.path, 'caller-a')).resolves.toMatchObject({- id: transfer.id,+ it('F4: an EIO while writing meta.json fails that publish only and the next admission succeeds', async () => {+ const { transfer, bytes } = await startTransfer(store, callerRoot, CALLER, 4, 16)+ renameBoundary.mockImplementationOnce(async () => {+ throw Object.assign(new Error('injected EIO'), { code: 'EIO' })})-- const record = store.debugRecord(transfer.id)!- record.expiresAt = new Date(Date.now() - 1).toISOString()- await store.debugPersist()- await expect(store.inspect(receipt.path, 'caller-a')).rejects.toMatchObject({- code: 'download_expired',+ await expect(store.publish(transfer.id, CALLER, digest(bytes))).rejects.toMatchObject({+ code: 'storage_write_failed',})+ // The producer's cleanup path: the id stayed active so fail() can remove it.+ await store.fail(transfer.id, CALLER)+ expect(await exists(downloadDirectory(callerRoot, transfer.id))).toBe(false)- await fs.unlink(path.join(callerRoot, receipt.path))- record.expiresAt = new Date(Date.now() + 60_000).toISOString()- await store.debugPersist()- await expect(store.inspect(receipt.path, 'caller-a')).rejects.toMatchObject({- code: 'download_missing',- })+ const next = await completedCopy(store, callerRoot, CALLER, 5, 16)+ expect(next.receipt.sha256).toBe(digest(next.bytes))+ await expect(store.readManagedFile(next.receipt.path, CALLER)).resolves.toEqual(next.bytes)})+})- it('enforces caller and aggregate byte/file quotas from the durable ledger', async () => {- await expect(- store.createTransfer({- callerIdentity: 'caller-a',- callerWorkspacePath: callerRoot,- source,- sizeBytes: GFS_FILE_LIMITS.maxFileBytes + 1,- expiresAt: new Date().toISOString(),- })- ).rejects.toMatchObject({ code: 'host_quota_exceeded' })-- const bytes = Buffer.alloc(1024)- for (let index = 0; index < GFS_FILE_LIMITS.callerRetainedFiles; index += 1) {- const transfer = await store.createTransfer({- callerIdentity: 'caller-a',- callerWorkspacePath: callerRoot,- source,- sizeBytes: 1024,- expiresAt: new Date(Date.now() + 60_000).toISOString(),- retentionOwnerId: 'quota-fixture-task',- })- await fs.writeFile(path.join(callerRoot, transfer.partialPath), bytes)- await store.publish(transfer.id, 'caller-a', createHash('sha256').update(bytes).digest('hex'))- }-- await expect(- store.createTransfer({- callerIdentity: 'caller-a',- callerWorkspacePath: callerRoot,- source,- sizeBytes: 1024,- expiresAt: new Date().toISOString(),- })- ).rejects.toMatchObject({ code: 'caller_quota_exceeded' })- expect(store.debugUsage()).toMatchObject({- bytes: GFS_FILE_LIMITS.callerRetainedFiles * 1024,- files: GFS_FILE_LIMITS.callerRetainedFiles,- callerBytes: { 'caller-a': GFS_FILE_LIMITS.callerRetainedFiles * 1024 },- callerFiles: { 'caller-a': GFS_FILE_LIMITS.callerRetainedFiles },- })- await store.releaseReceiptOwner('quota-fixture-task', 'caller-a')+describe('GFS download store: reuse', () => {+ it('F5: reuse returns the same id when the content hash matches', async () => {+ const { receipt } = await completedCopy(store, callerRoot, CALLER, 6, 40)+ const reused = await store.reusableReceipt(CALLER, sourceFor(6), 40)+ expect(reused).toMatchObject({ id: receipt.id, sha256: receipt.sha256, path: receipt.path })})- it('reconstructs completed charges after process restart', async () => {- const transfer = await store.createTransfer({- callerIdentity: 'caller-a',- callerWorkspacePath: callerRoot,- source,- sizeBytes: 1024,- expiresAt: new Date(Date.now() + 60_000).toISOString(),- })- await fs.writeFile(path.join(callerRoot, transfer.partialPath), Buffer.alloc(1024))- await store.publish(- transfer.id,- 'caller-a',- createHash('sha256').update(Buffer.alloc(1024)).digest('hex')- )+ it('F6: reuse deletes a directory whose content no longer matches and returns undefined', async () => {+ const { receipt } = await completedCopy(store, callerRoot, CALLER, 7, 40)+ const directory = downloadDirectory(callerRoot, receipt.id)+ await nativeFs.writeFile(path.join(directory, 'source'), Buffer.alloc(40, 0xee))+ hashBoundary.mockClear()- await store.close()- const reopened = new GfsDownloadStore(hostRoot)- await reopened.initialize()- expect(reopened.debugUsage()).toEqual({- bytes: 1024,- files: 1,- callerBytes: { 'caller-a': 1024 },- callerFiles: { 'caller-a': 1 },- })+ await expect(store.reusableReceipt(CALLER, sourceFor(7), 40)).resolves.toBeUndefined()- reopened.debugRecord(transfer.id)!.sizeBytes = GFS_FILE_LIMITS.callerStorageBytes - 512- await reopened.debugPersist()- await expect(- reopened.createTransfer({- callerIdentity: 'caller-a',- callerWorkspacePath: callerRoot,- source,- sizeBytes: 1024,- expiresAt: new Date().toISOString(),- })- ).rejects.toMatchObject({ code: 'caller_quota_exceeded' })- await reopened.close()+ // Witness: the content was hashed exactly once before the verdict.+ expect(hashBoundary).toHaveBeenCalledTimes(1)+ expect(await exists(directory)).toBe(false)})- it('releases a failed transfer when its exact directory is removed', async () => {- const transfer = await store.createTransfer({- callerIdentity: 'caller-a',- callerWorkspacePath: callerRoot,- source,- sizeBytes: 1024,- expiresAt: new Date().toISOString(),- })- await store.fail(transfer.id, 'caller-a')- expect(store.debugUsage()).toEqual({ bytes: 0, files: 0, callerBytes: {}, callerFiles: {} })- await expect(fs.stat(path.join(callerRoot, transfer.path))).rejects.toMatchObject({- code: 'ENOENT',+ it('F7: reuse does not match another caller, another version or an expired entry', async () => {+ const { receipt } = await completedCopy(store, callerRoot, CALLER, 8, 12)+ await expect(store.reusableReceipt('caller-b', sourceFor(8), 12)).resolves.toBeUndefined()+ await expect(store.reusableReceipt(CALLER, sourceFor(8, 2), 12)).resolves.toBeUndefined()+ // Witness: the same parameters with the right caller do match.+ await expect(store.reusableReceipt(CALLER, sourceFor(8), 12)).resolves.toMatchObject({+ id: receipt.id,})+ vi.setSystemTime(Date.now() + 2 * 60 * 60_000)+ await expect(store.reusableReceipt(CALLER, sourceFor(8), 12)).resolves.toBeUndefined()})+})- it('releases a failed transfer whose directory is already absent', async () => {- const transfer = await store.createTransfer({- callerIdentity: 'caller-a',- callerWorkspacePath: callerRoot,- source,- sizeBytes: 1024,- expiresAt: new Date(Date.now() + 60_000).toISOString(),- })- // Crash-after-rm analogue: the directory is gone while the durable charge- // and its ledger entry remain.- await fs.rm(path.join(callerRoot, path.dirname(transfer.path)), {- recursive: true,- force: true,- })+/** The smallest limits the policy accepts with two callers' worth of Host storage. */+const HOST_30_CALLER_15 = {+ MCP_HOST_GFS_MAX_FILE_BYTES: '10',+ MCP_HOST_GFS_DOWNLOAD_STORAGE_BYTES: '30',+ MCP_HOST_GFS_CALLER_DOWNLOAD_STORAGE_BYTES: '15',+}- await store.fail(transfer.id, 'caller-a')+describe('GFS download store: quotas and eviction', () => {+ it("F8: a caller over quota evicts its own oldest completed downloads, never another caller's", async () => {+ const { limited, limits } = await limitedStore({ MCP_HOST_GFS_CALLER_DOWNLOAD_MAX_FILES: '2' })+ expect(limits.callerRetainedFiles).toBe(2)+ const otherRoot = await callerDirectory(hostRoot, 'caller-b')+ const other = await completedCopy(limited, otherRoot, 'caller-b', 10, 8)+ tick()+ const oldest = await completedCopy(limited, callerRoot, CALLER, 11, 8)+ tick()+ const newer = await completedCopy(limited, callerRoot, CALLER, 12, 8)+ tick()++ await startTransfer(limited, callerRoot, CALLER, 13, 8)++ expect(await exists(downloadDirectory(callerRoot, oldest.receipt.id))).toBe(false)+ // Witnesses: the caller's newer copy and the other caller's older copy stay.+ expect(await exists(downloadDirectory(callerRoot, newer.receipt.id))).toBe(true)+ expect(await exists(downloadDirectory(otherRoot, other.receipt.id))).toBe(true)+ })- expect(store.debugRecord(transfer.id)).toBeUndefined()- expect(store.debugUsage()).toEqual({ bytes: 0, files: 0, callerBytes: {}, callerFiles: {} })+ it("F9: a host over quota may evict any caller's oldest completed download", async () => {+ const { limited } = await limitedStore(HOST_30_CALLER_15)+ const otherRoot = await callerDirectory(hostRoot, 'caller-b')+ const thirdRoot = await callerDirectory(hostRoot, 'caller-c')+ const other = await completedCopy(limited, otherRoot, 'caller-b', 20, 10)+ tick()+ const third = await completedCopy(limited, thirdRoot, 'caller-c', 21, 10)+ tick()+ const own = await completedCopy(limited, callerRoot, CALLER, 22, 10)+ tick()++ // caller-a stays within 15; the Host would reach 35 of 30.+ await startTransfer(limited, callerRoot, CALLER, 23, 5)++ expect(await exists(downloadDirectory(otherRoot, other.receipt.id))).toBe(false)+ // Witnesses: only the oldest copy went, whoever owned the newer ones.+ expect(await exists(downloadDirectory(thirdRoot, third.receipt.id))).toBe(true)+ expect(await exists(downloadDirectory(callerRoot, own.receipt.id))).toBe(true)})- it('keeps the charge when absence cannot be proven at lstat', async () => {- const transfer = await store.createTransfer({- callerIdentity: 'caller-a',- callerWorkspacePath: callerRoot,- source,- sizeBytes: 7,- expiresAt: new Date(Date.now() + 60_000).toISOString(),- })- await fs.writeFile(path.join(callerRoot, `${transfer.path}.partial`), 'fixture')- await store.publish(- transfer.id,- 'caller-a',- createHash('sha256').update('fixture').digest('hex')- )- const record = store.debugRecord(transfer.id)!- record.expiresAt = new Date(Date.now() - 1).toISOString()- await store.debugPersist()- // A regular file where the download directory belongs makes lstat fail with- // ENOTDIR. Only ENOENT proves absence; this must stay charged.- await fs.rm(path.join(callerRoot, '.gfs-downloads'), { recursive: true, force: true })- await fs.writeFile(path.join(callerRoot, '.gfs-downloads'), 'not-a-directory')-- await store.cleanupExpired()-- expect(store.debugRecord(transfer.id)).toMatchObject({ state: 'cleanup_failed' })- expect(store.debugUsage()).toEqual({- bytes: 7,- files: 1,- callerBytes: { 'caller-a': 7 },- callerFiles: { 'caller-a': 1 },- })+ it('F10: when eviction cannot make room nothing is deleted', async () => {+ const { limited } = await limitedStore({ MCP_HOST_GFS_CALLER_DOWNLOAD_MAX_FILES: '2' })+ await completedCopy(limited, callerRoot, CALLER, 30, 8, { owner: 'task-1' })+ tick()+ await completedCopy(limited, callerRoot, CALLER, 31, 8, { owner: 'task-1' })+ const downloads = path.join(callerRoot, '.gfs-downloads')+ const before = (await nativeFs.readdir(downloads)).sort()+ const denied = await quotaCount('caller', 'retained_files')+ lstatBoundary.mockClear()++ await expect(startTransfer(limited, callerRoot, CALLER, 32, 8)).rejects.toMatchObject({+ code: 'caller_quota_exceeded',+ })++ // Witness: the admission read the inventory before refusing.+ expect(lstatBoundary.mock.calls.length).toBeGreaterThan(0)+ expect((await nativeFs.readdir(downloads)).sort()).toEqual(before)+ expect(before).toHaveLength(2)+ expect(await quotaCount('caller', 'retained_files')).toBe(denied + 1)})- it('reserves active-transfer slots atomically per caller and Host', async () => {- const first = await store.createTransfer({- callerIdentity: 'caller-a',- callerWorkspacePath: callerRoot,- source,- sizeBytes: 1,- expiresAt: new Date().toISOString(),- })+ it('F11: pinned and active downloads are never evicted', async () => {+ const { limited } = await limitedStore({+ ...HOST_30_CALLER_15,+ })+ const otherRoot = await callerDirectory(hostRoot, 'caller-b')+ const thirdRoot = await callerDirectory(hostRoot, 'caller-c')+ const pinned = await completedCopy(limited, callerRoot, CALLER, 40, 10, { owner: 'task-40' })+ tick()+ const active = await startTransfer(limited, otherRoot, 'caller-b', 41, 10)+ tick()+ const unpinned = await completedCopy(limited, thirdRoot, 'caller-c', 42, 10)+ tick()++ // The Host would reach 40 of 30; one eviction makes room.+ await startTransfer(limited, await callerDirectory(hostRoot, 'caller-d'), 'caller-d', 43, 10)++ // Witness: the only eligible copy, although the newest, was evicted.+ expect(await exists(downloadDirectory(thirdRoot, unpinned.receipt.id))).toBe(false)+ expect(await exists(downloadDirectory(callerRoot, pinned.receipt.id))).toBe(true)+ expect(await exists(downloadDirectory(otherRoot, active.transfer.id))).toBe(true)+ })- await expect(- store.createTransfer({- callerIdentity: 'caller-a',- callerWorkspacePath: callerRoot,- source,- sizeBytes: 1,- expiresAt: new Date().toISOString(),- })- ).rejects.toMatchObject({ code: 'download_busy' })+ it('F12: free space is checked with active reservations and the 16 MiB reserve', async () => {+ const otherRoot = await callerDirectory(hostRoot, 'caller-b')+ await startTransfer(store, otherRoot, 'caller-b', 50, 4096 * 10)+ const observed = await nativeFs.statfs(hostRoot, { bigint: true })+ const reserveBlocks = (16n * 1024n * 1024n) / 4096n+ // Room for the request and the reserve, but not for the active reservation.+ statfsBoundary.mockResolvedValue({ ...observed, bsize: 4096n, bavail: reserveBlocks + 2n })+ const denied = await quotaCount('host', 'free_space')- const callerBRoot = path.join(hostRoot, 'users', 'caller-b')- await fs.mkdir(callerBRoot, { recursive: true, mode: 0o700 })- const second = await store.createTransfer({- callerIdentity: 'caller-b',- callerWorkspacePath: callerBRoot,- source,- sizeBytes: 1,- expiresAt: new Date().toISOString(),+ await expect(startTransfer(store, callerRoot, CALLER, 51, 4096)).rejects.toMatchObject({+ code: 'host_quota_exceeded',})+ expect(statfsBoundary).toHaveBeenCalled()+ expect(await quotaCount('host', 'free_space')).toBe(denied + 1)- const callerCRoot = path.join(hostRoot, 'users', 'caller-c')- await fs.mkdir(callerCRoot, { recursive: true, mode: 0o700 })- await expect(- store.createTransfer({- callerIdentity: 'caller-c',- callerWorkspacePath: callerCRoot,- source,- sizeBytes: 1,- expiresAt: new Date().toISOString(),- })- ).rejects.toMatchObject({ code: 'download_busy' })-- await store.fail(first.id, 'caller-a')- await store.fail(second.id, 'caller-b')- await store.createTransfer({- callerIdentity: 'caller-a',- callerWorkspacePath: callerRoot,- source,- sizeBytes: 1,- expiresAt: new Date().toISOString(),- })+ // Control: with room for the active reservation too, the same request is admitted.+ statfsBoundary.mockResolvedValue({ ...observed, bsize: 4096n, bavail: reserveBlocks + 11n })+ await expect(startTransfer(store, callerRoot, CALLER, 51, 4096)).resolves.toBeDefined()})- it('rejects a second live writer and accepts initialization after close', async () => {- const second = new GfsDownloadStore(hostRoot)- await expect(second.initialize()).rejects.toMatchObject({ code: 'writer_locked' })- await store.close()- await second.initialize()- await second.close()+ it('F13: eviction candidates are not hashed', async () => {+ const { limited } = await limitedStore({+ ...HOST_30_CALLER_15,+ })+ const first = await completedCopy(limited, callerRoot, CALLER, 60, 3)+ tick()+ const second = await completedCopy(limited, callerRoot, CALLER, 61, 3)+ tick()+ const third = await completedCopy(limited, callerRoot, CALLER, 62, 9)+ tick()+ hashBoundary.mockClear()++ // 15 retained + 6 requested against 15: the plan takes the two 3-byte copies.+ await startTransfer(limited, callerRoot, CALLER, 64, 6)++ // Witness: two candidates were evicted.+ expect(await exists(downloadDirectory(callerRoot, first.receipt.id))).toBe(false)+ expect(await exists(downloadDirectory(callerRoot, second.receipt.id))).toBe(false)+ expect(hashBoundary).not.toHaveBeenCalled()+ expect(await exists(downloadDirectory(callerRoot, third.receipt.id))).toBe(true)})- it('fails closed on a corrupt durable ledger', async () => {- await store.close()- await fs.writeFile(path.join(hostRoot, '.gfs-download-store', 'ledger-v1.json'), '{bad')- const reopened = new GfsDownloadStore(hostRoot)- await expect(reopened.initialize()).rejects.toMatchObject({- code: 'corrupt_store_ledger',- })+ it('F14: size above maxFileBytes is refused before any filesystem work', async () => {+ const { limited } = await limitedStore({ MCP_HOST_GFS_MAX_FILE_BYTES: '10' })+ statfsBoundary.mockClear()+ lstatBoundary.mockClear()+ await expect(startTransfer(limited, callerRoot, CALLER, 70, 11)).rejects.toMatchObject({+ code: 'host_quota_exceeded',+ })+ expect(statfsBoundary).not.toHaveBeenCalled()+ expect(lstatBoundary).not.toHaveBeenCalled()+ // Witness: the boundaries are live for an admissible size.+ await startTransfer(limited, callerRoot, CALLER, 71, 10)+ expect(statfsBoundary).toHaveBeenCalled()+ expect(lstatBoundary).toHaveBeenCalled()})- it('fails closed on an existing zero-byte ledger and keeps the retained source', async () => {- const transfer = await store.createTransfer({- callerIdentity: 'caller-a',- callerWorkspacePath: callerRoot,- source,- sizeBytes: 7,- expiresAt: new Date(Date.now() + 60_000).toISOString(),+ it('F15: concurrency limits per caller and per host return download_busy', async () => {+ const callerBusy = await quotaCount('caller', 'active_downloads')+ const hostBusy = await quotaCount('host', 'active_downloads')+ await startTransfer(store, callerRoot, CALLER, 80, 4)+ await expect(startTransfer(store, callerRoot, CALLER, 81, 4)).rejects.toMatchObject({+ code: 'download_busy',})- await fs.writeFile(path.join(callerRoot, `${transfer.path}.partial`), 'fixture')- const receipt = await store.publish(- transfer.id,- 'caller-a',- createHash('sha256').update('fixture').digest('hex')- )- await store.close()-- const ledgerPath = path.join(hostRoot, '.gfs-download-store', 'ledger-v1.json')- await fs.writeFile(ledgerPath, '')+ expect(await quotaCount('caller', 'active_downloads')).toBe(callerBusy + 1)- const reopened = new GfsDownloadStore(hostRoot)- await expect(reopened.initialize()).rejects.toMatchObject({- code: 'corrupt_store_ledger',- })- // The unreadable ledger and the retained source must survive untouched.- expect(await fs.readFile(ledgerPath, 'utf8')).toBe('')- expect(await fs.readFile(path.join(callerRoot, receipt.path), 'utf8')).toBe('fixture')+ await startTransfer(store, await callerDirectory(hostRoot, 'caller-b'), 'caller-b', 82, 4)+ await expect(+ startTransfer(store, await callerDirectory(hostRoot, 'caller-c'), 'caller-c', 83, 4)+ ).rejects.toMatchObject({ code: 'download_busy' })+ expect(await quotaCount('host', 'active_downloads')).toBe(hostBusy + 1)})+})- it('fails closed on an array-shaped persisted ledger and keeps the retained source', async () => {- const transfer = await store.createTransfer({- callerIdentity: 'caller-a',- callerWorkspacePath: callerRoot,- source,- sizeBytes: 7,- expiresAt: new Date(Date.now() + 60_000).toISOString(),- })- await fs.writeFile(path.join(callerRoot, `${transfer.path}.partial`), 'fixture')- const receipt = await store.publish(- transfer.id,- 'caller-a',- createHash('sha256').update('fixture').digest('hex')- )- await store.close()-- const ledgerPath = path.join(hostRoot, '.gfs-download-store', 'ledger-v1.json')- // `typeof [] === 'object'` and Object.entries([]) is empty, so an array-shaped- // records map reads as an empty ledger unless it is rejected explicitly.- const persisted = JSON.stringify({ schemaVersion: 1, records: [] })- await fs.writeFile(ledgerPath, persisted)+describe('GFS download store: sweep', () => {+ it('F16: the sweep removes incomplete directories of every shape and keeps complete ones', async () => {+ const kept = await completedCopy(store, callerRoot, CALLER, 90, 20)+ const bytes = Buffer.alloc(20, 3)+ const shapes: string[] = []++ const orphanPartial = await handMadeDirectory(callerRoot)+ await nativeFs.writeFile(path.join(orphanPartial.directory, 'source.partial'), bytes)+ const metaWithoutSource = await handMadeDirectory(callerRoot)+ await writeMeta(metaWithoutSource.directory, metaFor(metaWithoutSource.id, bytes))+ const sourceWithoutMeta = await handMadeDirectory(callerRoot)+ await nativeFs.writeFile(path.join(sourceWithoutMeta.directory, 'source'), bytes)+ const invalidMeta = await handMadeDirectory(callerRoot)+ await writeMeta(invalidMeta.directory, metaFor(invalidMeta.id, bytes, { sha256: 'nope' }))+ await nativeFs.writeFile(path.join(invalidMeta.directory, 'source'), bytes)+ const wrongSize = await handMadeDirectory(callerRoot)+ await writeMeta(wrongSize.directory, metaFor(wrongSize.id, bytes))+ await nativeFs.writeFile(path.join(wrongSize.directory, 'source'), Buffer.alloc(21, 3))+ for (const shape of [+ orphanPartial,+ metaWithoutSource,+ sourceWithoutMeta,+ invalidMeta,+ wrongSize,+ ])+ shapes.push(shape.directory)+ const removed = await expiryCount('incomplete_removed')- const reopened = new GfsDownloadStore(hostRoot)- await expect(reopened.initialize()).rejects.toMatchObject({- code: 'corrupt_store_ledger',+ await expect(store.cleanupExpired()).resolves.toEqual({+ removedExpired: 0,+ removedIncomplete: 5,+ removeFailed: 0,})- expect(await fs.readFile(ledgerPath, 'utf8')).toBe(persisted)- expect(await fs.readFile(path.join(callerRoot, receipt.path), 'utf8')).toBe('fixture')++ for (const directory of shapes) expect(await exists(directory)).toBe(false)+ expect(await expiryCount('incomplete_removed')).toBe(removed + 5)+ // Witness: the complete download stays on disk and readable through the index.+ await expect(store.readManagedFile(kept.receipt.path, CALLER)).resolves.toEqual(kept.bytes)})- it('rejects an existing store whose durable ledger is missing', async () => {- const transfer = await store.createTransfer({- callerIdentity: 'caller-a',- callerWorkspacePath: callerRoot,- source,- sizeBytes: 7,- expiresAt: new Date(Date.now() + 60_000).toISOString(),+ it('F17: the sweep removes expired complete downloads unless pinned', async () => {+ const pinned = await completedCopy(store, callerRoot, CALLER, 100, 8, { owner: 'task-100' })+ const loose = await completedCopy(store, callerRoot, CALLER, 101, 8)+ const later = Date.now() + 2 * 60 * 60_000++ await expect(store.cleanupExpired(later)).resolves.toEqual({+ removedExpired: 1,+ removedIncomplete: 0,+ removeFailed: 0,})- await fs.writeFile(path.join(callerRoot, `${transfer.path}.partial`), 'fixture')- const receipt = await store.publish(- transfer.id,- 'caller-a',- createHash('sha256').update('fixture').digest('hex')- )- await store.close()+ expect(await exists(downloadDirectory(callerRoot, loose.receipt.id))).toBe(false)+ expect(await exists(downloadDirectory(callerRoot, pinned.receipt.id))).toBe(true)- const ledgerPath = path.join(hostRoot, '.gfs-download-store', 'ledger-v1.json')- await fs.rm(ledgerPath)+ await store.releaseReceiptOwner('task-100', CALLER)+ await expect(store.cleanupExpired(later)).resolves.toMatchObject({ removedExpired: 1 })+ expect(await exists(downloadDirectory(callerRoot, pinned.receipt.id))).toBe(false)+ })- // The directory already existed with no durable ledger: unknown state, not- // a fresh store. Reject without recreating the ledger or touching sources.- await expect(new GfsDownloadStore(hostRoot).initialize()).rejects.toMatchObject({- code: 'corrupt_store_ledger',- })- await expect(fs.stat(ledgerPath)).rejects.toMatchObject({ code: 'ENOENT' })- expect(await fs.readFile(path.join(callerRoot, receipt.path), 'utf8')).toBe('fixture')- // A retry must fail on state, not on a writer lease leaked by the failure.- await expect(new GfsDownloadStore(hostRoot).initialize()).rejects.toMatchObject({- code: 'corrupt_store_ledger',- })+ it('F18: the sweep ignores entries that are not input-<uuid>', async () => {+ const downloads = path.join(callerRoot, '.gfs-downloads')+ await nativeFs.mkdir(downloads, { mode: 0o700 })+ const foreign = [+ path.join(downloads, 'input-not-a-uuid'),+ path.join(downloads, `input-${nativeCrypto.randomUUID().toUpperCase()}`),+ path.join(downloads, 'notes'),+ ]+ for (const directory of foreign) await nativeFs.mkdir(directory, { mode: 0o700 })+ await nativeFs.writeFile(path.join(downloads, 'readme.txt'), 'kept')+ const incomplete = await handMadeDirectory(callerRoot)++ await expect(store.cleanupExpired()).resolves.toMatchObject({ removedIncomplete: 1 })++ // Witness: the incomplete store directory next to them was removed.+ expect(await exists(incomplete.directory)).toBe(false)+ for (const directory of foreign) expect(await exists(directory)).toBe(true)+ expect(await exists(path.join(downloads, 'readme.txt'))).toBe(true)})- it('rejects a preexisting store directory that has no durable ledger', async () => {- const isolatedRoot = await fs.mkdtemp(path.join(tmpdir(), 'gfs-store-existing-'))- const isolatedStoreRoot = path.join(isolatedRoot, '.gfs-download-store')- await fs.mkdir(isolatedStoreRoot, { mode: 0o700 })+ it('F19: a symlinked .gfs-downloads is removed without following it', async () => {+ const outside = await nativeFs.mkdtemp(path.join(tmpdir(), 'gfs-store-outside-'))try {- await expect(new GfsDownloadStore(isolatedRoot).initialize()).rejects.toMatchObject({- code: 'corrupt_store_ledger',- })- expect(await fs.readdir(isolatedStoreRoot)).not.toContain('ledger-v1.json')+ const victim = path.join(outside, `input-${nativeCrypto.randomUUID()}`)+ await nativeFs.mkdir(victim, { mode: 0o700 })+ await nativeFs.writeFile(path.join(victim, 'source.partial'), 'outside')+ const link = path.join(callerRoot, '.gfs-downloads')+ await nativeFs.symlink(outside, link)++ await expect(store.cleanupExpired()).resolves.toMatchObject({ removedIncomplete: 1 })++ expect(await exists(link)).toBe(false)+ await expect(nativeFs.readFile(path.join(victim, 'source.partial'), 'utf8')).resolves.toBe(+ 'outside'+ )} finally {- await fs.rm(isolatedRoot, { recursive: true, force: true })+ await nativeFs.rm(outside, { recursive: true, force: true })}})- it('rejects an array-shaped processingLeases map and keeps the retained source', async () => {- const transfer = await store.createTransfer({- callerIdentity: 'caller-a',- callerWorkspacePath: callerRoot,- source,- sizeBytes: 7,- expiresAt: new Date(Date.now() + 60_000).toISOString(),+ it('F20: a failed removal is logged and counted, does not block admission and is retried', async () => {+ const stuck = await handMadeDirectory(callerRoot)+ rmBoundary.mockImplementation(async (target: string, options: unknown) => {+ // The store renames the directory to a private `.trash-<uuid>` name, then removes that.+ if (path.basename(target).startsWith('.trash-'))+ throw Object.assign(new Error('injected EACCES'), { code: 'EACCES' })+ return nativeFs.rm(target, options as Parameters<typeof nativeFs.rm>[1])})- await fs.writeFile(path.join(callerRoot, `${transfer.path}.partial`), 'fixture')- const receipt = await store.publish(- transfer.id,- 'caller-a',- createHash('sha256').update('fixture').digest('hex')- )- await store.close()+ const warn = vi.spyOn(logger, 'warn')+ const failed = await expiryCount('remove_failed')- const ledgerPath = path.join(hostRoot, '.gfs-download-store', 'ledger-v1.json')- const persisted = JSON.parse(await fs.readFile(ledgerPath, 'utf8')) as {- processingLeases?: unknown- }- persisted.processingLeases = []- const rewritten = JSON.stringify(persisted)- await fs.writeFile(ledgerPath, rewritten)+ await expect(store.cleanupExpired()).resolves.toMatchObject({ removeFailed: 1 })- await expect(new GfsDownloadStore(hostRoot).initialize()).rejects.toMatchObject({- code: 'corrupt_store_ledger',- })- expect(await fs.readFile(ledgerPath, 'utf8')).toBe(rewritten)- expect(await fs.readFile(path.join(callerRoot, receipt.path), 'utf8')).toBe('fixture')+ expect(warn).toHaveBeenCalledWith(+ { component: 'GfsDownloadStore', code: 'EACCES' },+ expect.stringContaining('could not remove')+ )+ expect(await expiryCount('remove_failed')).toBe(failed + 1)+ const downloads = path.dirname(stuck.directory)+ const leftover = (await nativeFs.readdir(downloads)).filter(name => name.startsWith('.trash-'))+ expect(leftover).toHaveLength(1)+ expect(await exists(stuck.directory)).toBe(false)+ const next = await completedCopy(store, callerRoot, CALLER, 110, 8)+ await expect(store.readManagedFile(next.receipt.path, CALLER)).resolves.toEqual(next.bytes)++ // Once removal works again, the next sweep removes the renamed leftover.+ rmBoundary.mockImplementation(nativeFs.rm)+ await expect(store.cleanupExpired()).resolves.toMatchObject({ removedIncomplete: 1 })+ expect(await exists(path.join(downloads, leftover[0]!))).toBe(false)})+})- it('does not commit a publication released after abort and keeps failed cleanup reserved', async () => {- const expiresAt = new Date(Date.now() + 60_000).toISOString()- const transfer = await store.createTransfer({- callerIdentity: 'caller-a',- callerWorkspacePath: callerRoot,- source,- sizeBytes: 7,- expiresAt,- })- await fs.writeFile(path.join(callerRoot, `${transfer.path}.partial`), 'fixture')- const sha256 = createHash('sha256').update('fixture').digest('hex')- const probe = await fs.open(path.join(callerRoot, 'probe'), 'w')- const prototype = Object.getPrototypeOf(probe) as fs.FileHandle- await probe.close()- const controller = new AbortController()- let releaseRead!: () => void- const readBlocked = new Promise<void>(resolve => {- releaseRead = resolve- })- let readEntered!: () => void- const readStarted = new Promise<void>(resolve => {- readEntered = resolve+describe('GFS download store: managed reads', () => {+ it('F21: readManagedFile returns the exact bytes and answers another caller like a missing copy', async () => {+ const { receipt, bytes } = await completedCopy(store, callerRoot, CALLER, 120, 33)+ await expect(store.readManagedFile(receipt.path, CALLER)).resolves.toEqual(bytes)+ await expect(store.readManagedFile(receipt.path, 'caller-b')).rejects.toMatchObject({+ code: 'download_missing',})- let heldRead = false- const originalRead = prototype.read- vi.spyOn(prototype, 'read').mockImplementation(async function (- this: fs.FileHandle,- ...values: unknown[]- ) {- const info = await this.stat()- if (!heldRead && info.isFile() && info.size === 7) {- heldRead = true- readEntered()- await readBlocked- }- return originalRead.apply(this, values as never)+ await expect(+ store.readManagedFile(`.gfs-downloads/input-${nativeCrypto.randomUUID()}/source`, CALLER)+ ).rejects.toMatchObject({ code: 'download_missing' })+ await expect(store.readManagedFile('../escape/source', CALLER)).rejects.toMatchObject({+ code: 'download_missing',})+ })- const pending = store.publish(transfer.id, 'caller-a', sha256, { signal: controller.signal })- const rejected = expect(pending).rejects.toMatchObject({ code: 'publication_cancelled' })- await readStarted- controller.abort()- releaseRead()- await rejected- expect(store.debugRecord(transfer.id)).toMatchObject({ state: 'transferring' })- expect(store.debugRecord(transfer.id)?.sha256).toBeUndefined()- vi.restoreAllMocks()-- // Force an unproven absence: a regular file where the download directory- // belongs makes lstat fail with ENOTDIR, so the charge must stay reserved.- await fs.rm(path.join(callerRoot, '.gfs-downloads'), { recursive: true, force: true })- await fs.writeFile(path.join(callerRoot, '.gfs-downloads'), 'not-a-directory')- await expect(store.fail(transfer.id, 'caller-a')).rejects.toMatchObject({- code: 'storage_write_failed',- })- expect(store.debugRecord(transfer.id)).toMatchObject({- state: 'cleanup_failed',- sizeBytes: 7,+ it('F22: readManagedFile deletes a tampered source and reports download_missing', async () => {+ const { receipt } = await completedCopy(store, callerRoot, CALLER, 122, 16)+ const directory = downloadDirectory(callerRoot, receipt.id)+ await nativeFs.writeFile(path.join(directory, 'source'), Buffer.alloc(16, 0xab))+ hashBoundary.mockClear()++ await expect(store.readManagedFile(receipt.path, CALLER)).rejects.toMatchObject({+ code: 'download_missing',})- expect(store.debugUsage()).toMatchObject({ bytes: 7, files: 1 })++ // Witness: the bytes were hashed once, then the directory was removed.+ expect(hashBoundary).toHaveBeenCalledTimes(1)+ expect(await exists(directory)).toBe(false)})- it('rejects a managed file that grows after its size check without reading the extra body', async () => {+ it('F23: readManagedFilePrefix bounds and size check', async () => {+ const bytes = Buffer.from('0123456789abcdef0123')const transfer = await store.createTransfer({- callerIdentity: 'caller-a',+ callerIdentity: CALLER,callerWorkspacePath: callerRoot,- source,- sizeBytes: 7,- expiresAt: new Date(Date.now() + 60_000).toISOString(),+ source: sourceFor(123),+ sizeBytes: bytes.byteLength,+ expiresAt: future(),})- await fs.writeFile(path.join(callerRoot, `${transfer.path}.partial`), 'fixture')- const receipt = await store.publish(- transfer.id,- 'caller-a',- createHash('sha256').update('fixture').digest('hex')+ await nativeFs.writeFile(path.join(callerRoot, transfer.partialPath), bytes)+ const receipt = await store.publish(transfer.id, CALLER, digest(bytes))++ await expect(store.readManagedFilePrefix(receipt.path, CALLER, 4)).resolves.toEqual(+ Buffer.from('0123'))- await expect(store.readManagedFile(receipt.path, 'caller-a')).resolves.toEqual(- Buffer.from('fixture')+ await expect(store.readManagedFilePrefix(receipt.path, CALLER)).resolves.toEqual(+ bytes.subarray(0, 16))-- const probe = await fs.open(path.join(callerRoot, 'probe'), 'w')- const prototype = Object.getPrototypeOf(probe) as fs.FileHandle- await probe.close()- let grown = false- const sourceInfo = await fs.stat(path.join(callerRoot, receipt.path))- let readBytes = 0- const originalRead = prototype.read- vi.spyOn(prototype, 'read').mockImplementation(async function (- this: fs.FileHandle,- ...values: unknown[]- ) {- const info = await this.stat()- if (!grown && info.isFile() && info.ino === sourceInfo.ino) {- grown = true- // Mutate immediately after the reader admitted the original size, so- // the bounded EOF probe must detect growth before returning its bytes.- await fs.appendFile(path.join(callerRoot, receipt.path), 'X'.repeat(64))- }- const result = await originalRead.apply(this, values as never)- readBytes += result.bytesRead- return result- })-- await expect(store.readManagedFile(receipt.path, 'caller-a')).rejects.toMatchObject({+ for (const invalid of [0, -1, 4097, 1.5])+ await expect(store.readManagedFilePrefix(receipt.path, CALLER, invalid)).rejects.toThrow(+ RangeError+ )+ await nativeFs.appendFile(path.join(downloadDirectory(callerRoot, receipt.id), 'source'), 'x')+ await expect(store.readManagedFilePrefix(receipt.path, CALLER, 4)).rejects.toMatchObject({code: 'download_missing',})- expect(grown).toBe(true)- expect(readBytes).toBe(receipt.sizeBytes + 1)})-- it.each([- ['temporary journal sync', 'abort'],- ['temporary journal sync', 'deadline'],- ['committed journal directory sync', 'abort'],- ['committed journal directory sync', 'deadline'],- ] as const)(- 'keeps publication unreadable during cancellation at %s (%s)',- async (phase, cancellation) => {- const transfer = await store.createTransfer({- callerIdentity: 'caller-a',- callerWorkspacePath: callerRoot,- source,- sizeBytes: 7,- expiresAt: new Date(Date.now() + 60_000).toISOString(),- })- await fs.writeFile(path.join(callerRoot, `${transfer.path}.partial`), 'fixture')- const ledgerDirectory = path.join(hostRoot, '.gfs-download-store')- const directoryInfo = await fs.stat(ledgerDirectory)- const probe = await fs.open(path.join(callerRoot, 'probe'), 'w')- const prototype = Object.getPrototypeOf(probe) as fs.FileHandle- await probe.close()- let release!: () => void- const blocked = new Promise<void>(resolve => {- release = resolve- })- let entered!: () => void- const started = new Promise<void>(resolve => {- entered = resolve- })- let held = false- const originalSync = prototype.sync- vi.spyOn(prototype, 'sync').mockImplementation(async function (this: fs.FileHandle) {- const info = await this.stat()- const atBoundary =- phase === 'temporary journal sync'- ? info.isFile() && info.size > 7- : info.isDirectory() && info.ino === directoryInfo.ino- if (!held && atBoundary && store.debugRecord(transfer.id)?.state === 'completed') {- held = true- entered()- await blocked- }- return originalSync.call(this)- })- const controller = new AbortController()- let now = Date.now()- const deadlineMs = now + 1000- if (cancellation === 'deadline') vi.spyOn(Date, 'now').mockImplementation(() => now)- const pending = store.publish(- transfer.id,- 'caller-a',- createHash('sha256').update('fixture').digest('hex'),- { signal: controller.signal, deadlineMs }- )- const rejected = expect(pending).rejects.toMatchObject({ code: 'publication_cancelled' })- await started- if (cancellation === 'abort') controller.abort()- else now = deadlineMs- release()- await rejected-- expect(store.debugRecord(transfer.id)).toMatchObject({ state: 'transferring' })- expect(store.debugRecord(transfer.id)?.sha256).toBeUndefined()- await expect(store.readManagedFile(transfer.path, 'caller-a')).rejects.toMatchObject({- code: 'download_missing',- })- const ledger = JSON.parse(- await fs.readFile(path.join(ledgerDirectory, 'ledger-v1.json'), 'utf8')- )- expect(ledger.records[transfer.id].state).toBe('transferring')- expect(ledger.records[transfer.id].sha256).toBeUndefined()- expect((await fs.readdir(ledgerDirectory)).filter(name => name.includes('.tmp-'))).toEqual([])- expect(store.debugUsage()).toMatchObject({ bytes: 7, files: 1 })- await store.fail(transfer.id, 'caller-a')- expect(store.debugUsage()).toMatchObject({ bytes: 0, files: 0 })- }- )})-describe('S6: expiry and admission without processing-lease exemptions (#1019)', () => {- async function publishFixture(- expiresAt = new Date(Date.now() + 60_000).toISOString(),- retentionOwnerId?: string- ) {- const transfer = await store.createTransfer({- callerIdentity: 'caller-a',- callerWorkspacePath: callerRoot,- source,- sizeBytes: 7,- expiresAt,- retentionOwnerId,- })- await fs.writeFile(path.join(callerRoot, transfer.partialPath), 'fixture')- return store.publish(- transfer.id,- 'caller-a',- createHash('sha256').update('fixture').digest('hex')- )- }-- // Store behaviour only: this shell has no store reference, so the test shows- // that expiry is unaffected by a shell run that read the copy. Decoupling of- // the shell from the store is proven by the TaskExecutor-level X3-TE test.- it('removes an expired record even after a shell read it: expiry is unaffected by the shell run', async () => {- const receipt = await publishFixture()- const shell = new ShellTool(callerRoot, 5_000, ['PATH'], () => ({}), undefined, true)- const read = await shell.execute({ command: `cat ${JSON.stringify(receipt.path)}` })- expect(read.is_error).toBe(false)- expect(read.content).toContain('fixture')- await store.cleanupExpired(Date.parse(receipt.expiresAt) + 1)- expect(store.debugRecord(receipt.id)).toBeUndefined()- await expect(fs.lstat(path.join(callerRoot, path.dirname(receipt.path)))).rejects.toMatchObject(- { code: 'ENOENT' }- )- expect(store.debugUsage()).toMatchObject({ bytes: 0, files: 0 })- })+describe('GFS download store: pins, lifecycle and errors', () => {+ it('F24: releaseReceiptOwner unpins only its own caller and a second store on the same root sees no pins', async () => {+ const pinned = await completedCopy(store, callerRoot, CALLER, 130, 8, { owner: 'task-130' })+ const rootB = await callerDirectory(hostRoot, 'caller-b')+ // The same owner id under another caller is another pin, not a refusal.+ const other = await completedCopy(store, rootB, 'caller-b', 131, 8, { owner: 'task-130' })+ const later = Date.now() + 2 * 60 * 60_000+ await expect(store.releaseReceiptOwner('unknown-owner', CALLER)).resolves.toBeUndefined()+ await expect(store.releaseReceiptOwner('task-130', 'caller-b')).resolves.toBeUndefined()+ // Witness: caller-b's release freed only caller-b's copy; CALLER's pin holds.+ await expect(store.cleanupExpired(later)).resolves.toMatchObject({ removedExpired: 1 })+ expect(await exists(downloadDirectory(rootB, other.receipt.id))).toBe(false)+ expect(await exists(downloadDirectory(callerRoot, pinned.receipt.id))).toBe(true)- it('keeps an expired record only while a retention owner holds it', async () => {- const receipt = await publishFixture(undefined, 'waiting-approval-task')- await store.cleanupExpired(Date.parse(receipt.expiresAt) + 1)- expect(store.debugRecord(receipt.id)).toBeDefined()- expect(await fs.readFile(path.join(callerRoot, receipt.path), 'utf8')).toBe('fixture')- await store.releaseReceiptOwner('waiting-approval-task', 'caller-a')- await store.cleanupExpired(Date.parse(receipt.expiresAt) + 1)- expect(store.debugRecord(receipt.id)).toBeUndefined()+ await store.close()+ const second = await openStore(hostRoot)+ await expect(second.cleanupExpired(later)).resolves.toMatchObject({ removedExpired: 1 })+ expect(await exists(downloadDirectory(callerRoot, pinned.receipt.id))).toBe(false)})- it('fences a transfer whose caller validation completes after shutdown', async () => {- const receipt = await publishFixture()- let resume!: () => void- let entered!: () => void- const barrier = new Promise<void>(resolve => {- resume = resolve- })- const waiting = new Promise<void>(resolve => {- entered = resolve- })- const validatingStore = store as unknown as {- validateCallerRoot: (root: string) => Promise<string>- }- const validate = validatingStore.validateCallerRoot.bind(store)- vi.spyOn(validatingStore, 'validateCallerRoot').mockImplementationOnce(async root => {- const validated = await validate(root)- entered()- await barrier- return validated+ it('F25: close drains active transfers and refuses new admissions', async () => {+ const { transfer, bytes } = await startTransfer(store, callerRoot, CALLER, 140, 8)+ let closed = false+ const closing = store.close().then(() => {+ closed = true})- const outcome = Promise.allSettled([- store.createTransfer({- callerIdentity: 'caller-a',- callerWorkspacePath: callerRoot,- source,- sizeBytes: 7,- expiresAt: new Date(Date.now() + 60_000).toISOString(),- }),- ])- await waiting- await store.close()- resume()-- const [result] = await outcome- expect(result!.status).toBe('rejected')- if (result!.status === 'rejected')- expect(result!.reason).toMatchObject({ code: 'workspace_unavailable' })- expect(await fs.readdir(path.join(callerRoot, '.gfs-downloads'))).toEqual([- path.basename(path.dirname(receipt.path)),- ])- const restarted = new GfsDownloadStore(hostRoot)- await restarted.initialize()- expect(restarted.debugUsage().bytes).toBe(7)- await restarted.close()+ await expect(+ startTransfer(store, await callerDirectory(hostRoot, 'caller-b'), 'caller-b', 141, 8)+ ).rejects.toMatchObject({ code: 'download_busy' })+ expect(store.isAvailable()).toBe(false)+ expect(closed).toBe(false)++ const receipt = await store.publish(transfer.id, CALLER, digest(bytes))+ await closing+ expect(closed).toBe(true)+ expect(receipt.id).toBe(transfer.id)+ await expect(store.initialize()).rejects.toMatchObject({ code: 'download_busy' })})- it('keeps another caller admissible while one caller has an expired record', async () => {- const expired = await publishFixture()- const callerBRoot = path.join(hostRoot, 'users', 'caller-b')- await fs.mkdir(callerBRoot, { recursive: true, mode: 0o700 })- // Caller B's expiry is derived from caller A's, so the mocked clock below- // is strictly before it however fast the fixtures run.- const callerBTransfer = await store.createTransfer({- callerIdentity: 'caller-b',- callerWorkspacePath: callerBRoot,- source,- sizeBytes: 7,- expiresAt: new Date(Date.parse(expired.expiresAt) + 60_000).toISOString(),- })- await fs.writeFile(path.join(callerBRoot, callerBTransfer.partialPath), 'fixture')- const callerBReceipt = await store.publish(- callerBTransfer.id,- 'caller-b',- createHash('sha256').update('fixture').digest('hex')- )- vi.spyOn(Date, 'now').mockReturnValue(Date.parse(expired.expiresAt) + 1)+ it('F25b: close with an active transfer that never finishes resolves within the deadline', async () => {+ const { transfer, bytes } = await startTransfer(store, callerRoot, CALLER, 150, 8)+ const warn = vi.spyOn(logger, 'warn')+ const started = performance.now()++ await store.close(50)- await store.cleanupExpired()- expect(store.debugRecord(expired.id)).toBeUndefined()- expect(store.isAvailable()).toBe(true)- expect(await store.reusableReceipt('caller-b', source, 7)).toMatchObject({- id: callerBReceipt.id,+ expect(performance.now() - started).toBeLessThan(2_000)+ // Witness: the store reports the transfer it left behind.+ expect(warn).toHaveBeenCalledWith(+ { component: 'GfsDownloadStore', active: 1 },+ expect.stringContaining('closed with active transfers')+ )+ await expect(store.publish(transfer.id, CALLER, digest(bytes))).rejects.toMatchObject({+ code: 'download_busy',})+ await expect(store.fail(transfer.id, CALLER)).rejects.toMatchObject({ code: 'download_busy' })+ await expect(store.close()).resolves.toBeUndefined()})- it('rechecks failed-transfer ownership after a queued publication', async () => {- const transfer = await store.createTransfer({- callerIdentity: 'caller-a',- callerWorkspacePath: callerRoot,- source,- sizeBytes: 7,- expiresAt: new Date(Date.now() + 60_000).toISOString(),- })- await fs.writeFile(path.join(callerRoot, transfer.partialPath), 'fixture')- const persistedStore = store as unknown as { persist: () => Promise<void> }- const persist = persistedStore.persist.bind(store)- let resume!: () => void- let entered!: () => void- const barrier = new Promise<void>(resolve => {- resume = resolve+ it('F26: error codes for an uninitialized, a closed and an unknown transfer', async () => {+ const uninitialized = new GfsDownloadStore(hostRoot)+ const probe = `.gfs-downloads/input-${nativeCrypto.randomUUID()}/source`+ await expect(uninitialized.readManagedFile(probe, CALLER)).rejects.toMatchObject({+ code: 'workspace_unavailable',})- const waiting = new Promise<void>(resolve => {- entered = resolve+ await expect(+ uninitialized.createTransfer({+ callerIdentity: CALLER,+ callerWorkspacePath: callerRoot,+ source: sourceFor(160),+ sizeBytes: 1,+ expiresAt: future(),+ })+ ).rejects.toMatchObject({ code: 'workspace_unavailable' })+ await expect(uninitialized.close()).resolves.toBeUndefined()+ await expect(uninitialized.initialize()).rejects.toMatchObject({ code: 'download_busy' })++ const { transfer } = await startTransfer(store, callerRoot, CALLER, 161, 4)+ // Another caller's transfer is answered exactly like an unknown id.+ await expect(store.fail(transfer.id, 'caller-b')).rejects.toMatchObject({+ code: 'download_busy',})- vi.spyOn(persistedStore, 'persist').mockImplementationOnce(async () => {- await persist()- entered()- await barrier+ await expect(store.fail(nativeCrypto.randomUUID(), CALLER)).rejects.toMatchObject({+ code: 'download_busy',})- const published = store.publish(- transfer.id,- 'caller-a',- createHash('sha256').update('fixture').digest('hex')- )- await waiting- const failed = expect(store.fail(transfer.id, 'caller-a')).rejects.toMatchObject({+ await expect(+ store.publish(nativeCrypto.randomUUID(), CALLER, 'a'.repeat(64))+ ).rejects.toMatchObject({ code: 'download_missing' })+ await expect(store.publish(transfer.id, CALLER, 'not-a-digest')).rejects.toThrow(RangeError)+ // Witness: the transfer is live and the caller's fail() removes it.+ await store.fail(transfer.id, CALLER)+ expect(await exists(downloadDirectory(callerRoot, transfer.id))).toBe(false)++ await store.close()+ await expect(store.readManagedFile(probe, CALLER)).rejects.toMatchObject({code: 'download_busy',})- resume()- const receipt = await published- await failed- expect(store.debugRecord(receipt.id)).toMatchObject({ state: 'completed' })- expect(await fs.readFile(path.join(callerRoot, receipt.path), 'utf8')).toBe('fixture')- const ledger = JSON.parse(- await fs.readFile(path.join(hostRoot, '.gfs-download-store', 'ledger-v1.json'), 'utf8')- )- expect(ledger.records[receipt.id].state).toBe('completed')- expect(ledger).not.toHaveProperty('processingLeases')+ await expect(store.close()).resolves.toBeUndefined()+ })++ it('F27: a Host root that is a symlink makes initialize reject with workspace_unavailable', async () => {+ const real = path.join(hostRoot, 'real-store')+ await nativeFs.mkdir(real, { mode: 0o700 })+ const link = path.join(hostRoot, 'store-link')+ await nativeFs.symlink(real, link)+ const linked = new GfsDownloadStore(link)+ extraStores.push(linked)++ await expect(linked.initialize()).rejects.toBeInstanceOf(GfsDownloadStoreError)+ await expect(linked.initialize()).rejects.toMatchObject({ code: 'workspace_unavailable' })+ expect(linked.isAvailable()).toBe(false)+ // Witness: the same directory through its real path initializes.+ await expect(openStore(real)).resolves.toBeInstanceOf(GfsDownloadStore)})})diff --git a/mcp-host/src/internalTools/gfsDownloadStore.ts b/mcp-host/src/internalTools/gfsDownloadStore.tsindex 5e4861cf1..dfed29a7d 100644--- a/mcp-host/src/internalTools/gfsDownloadStore.ts+++ b/mcp-host/src/internalTools/gfsDownloadStore.ts@@ -4,244 +4,209 @@ import * as fs from 'node:fs/promises'import * as path from 'node:path'import { logger } from '../logger'import type { GfsImageSource } from '../visualInput/policy'-import {- recordGfsDownloadExpiry,- recordGfsDownloadQuota,- recordGfsLegacyProcessingLeasesDiscarded,- setGfsQuarantinedRecords,-} from './gfsDownloadMetrics'+import { recordGfsDownloadExpiry, recordGfsDownloadQuota } from './gfsDownloadMetrics'import {GFS_FILE_LIMITS,GFS_HOST_ACTIVE_DOWNLOADS,GFS_HOST_RETAINED_FILES,} from './gfsFilePolicy'-import {- PrivateStoreNameMovedError,- openPrivateStoreObject,- verifyPrivateStoreDirectory,-} from './gfsStorePrivateFiles'-import {- GfsStoreWriterLease,- GfsStoreWriterOwnershipError,- type WriterFenceDetail,-} from './gfsStoreWriterLease'+import { openPrivateStoreObject, verifyPrivateStoreDirectory } from './gfsStorePrivateFiles'const GFS_DOWNLOAD_STORE_LOG_COMPONENT = 'GfsDownloadStore'+/** Caller-root directory that holds every download of that caller. */+const DOWNLOADS_DIRECTORY = '.gfs-downloads'+const META_FILE = 'meta.json'+const SOURCE_FILE = 'source'+const PARTIAL_FILE = 'source.partial'+const META_MAX_BYTES = 64 * 1024+const FREE_SPACE_RESERVE_BYTES = 16n * 1024n * 1024n++const UUID_PATTERN = '[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}'+/** The only directory names under `.gfs-downloads` that belong to the store. */+export const GFS_INPUT_DIRECTORY_RE = new RegExp(`^input-(${UUID_PATTERN})$`)+/** A directory renamed out of the way before removal; swept if a removal stops. */+const TRASH_PREFIX = '.trash-'+const TRASH_DIRECTORY_RE = new RegExp(`^\\.trash-${UUID_PATTERN}$`)+/** Caller-relative receipt path; the same contract gfsFilePreparation enforces. */+const RECEIPT_PATH_RE = new RegExp(`^\\.gfs-downloads/input-(${UUID_PATTERN})/source$`)+const SHA256_RE = /^[0-9a-f]{64}$/+export type GfsDownloadStoreErrorCode =| 'caller_mismatch'| 'caller_quota_exceeded'- | 'corrupt_store_ledger'+ | 'download_busy'| 'download_expired'| 'download_missing'- | 'download_busy'| 'host_quota_exceeded'| 'publication_cancelled'| 'storage_write_failed'- | 'unsupported_store_schema'| 'workspace_unavailable'- | 'writer_locked'export class GfsDownloadStoreError extends Error {- constructor(- readonly code: GfsDownloadStoreErrorCode,- readonly transientWriterContention = false,- /** Writer-ownership refusal branch; set only when the writer lease named it. */- readonly detail?: WriterFenceDetail- ) {+ constructor(readonly code: GfsDownloadStoreErrorCode) {super(`GFS download store failed (${code})`)this.name = 'GfsDownloadStoreError'}}-export interface GfsDownloadRecord {+export interface GfsDownloadTransfer {id: string- callerIdentity: string- source: GfsImageSource- directory: string- /** Caller-workspace-relative path safe for a model-visible receipt. */path: string- /** Host-workspace-relative path used only inside the store. */- hostPath: string+ partialPath: stringsizeBytes: number- sha256?: string- createdAt: stringexpiresAt: string- state: 'transferring' | 'completed' | 'missing' | 'cleanup_failed' | 'quarantined'}-export interface GfsDownloadTransfer {+export interface GfsDownloadReceipt {id: string+ source: GfsImageSourcepath: string- partialPath: stringsizeBytes: number+ sha256: stringexpiresAt: string}-export interface GfsDownloadReceipt {+/** Serialized receipt written to `meta.json`; the store writes nothing else. */+interface StoredMeta {+ schemaVersion: 1id: string+ callerIdentity: stringsource: GfsImageSource- path: stringsizeBytes: numbersha256: string+ createdAt: stringexpiresAt: string}-export interface StoreLedger {- schemaVersion: 1- records: Record<string, GfsDownloadRecord>+/**+ * A complete download: `meta.json` parses and `source` has the recorded size.+ * Provenance lives only in memory. A `published` entry was written by this+ * process, so its caller identity and sha256 are trusted. An `adopted` entry+ * was found on disk (left by an earlier process or planted by a shell command+ * running with the Host UID): it counts against the quota of the directory+ * that contains it and is swept, but it is never reused, read or pinned.+ */+/** dev/ino of an inode, compared against an open descriptor or a later lstat. */+interface InodeIdentity {+ dev: bigint+ ino: bigint+}++function sameInode(left: InodeIdentity, right: InodeIdentity): boolean {+ return left.dev === right.dev && left.ino === right.ino+}++interface Entry extends StoredMeta {+ /** Absolute `<callerRoot>/.gfs-downloads/input-<id>` directory. */+ directory: string/**- * Legacy shell processing leases written before #1019. Still validated when- * a ledger carries them, discarded at initialize, and never written again.+ * The `source` inode this process published. Reads and reuse serve only a+ * descriptor whose inode is this one; adopted entries have none and are+ * never served.*/- processingLeases?: Record<string, LegacyProcessingLeaseRecord>- retentionOwners?: Record<string, GfsReceiptOwnerRecord>+ sourceIdentity?: InodeIdentity+ /** `<hostRoot>/users/<key>` containing the entry: the owner for quota and inventory. */+ callerRoot: string+ provenance: 'published' | 'adopted'+ /** Last publish, reuse or managed read in this process; adopted entries use createdAt. */+ lastUsedMs: number}-interface LegacyProcessingLeaseRecord {- leaseId: string+/** A reservation held in memory between createTransfer and publish/fail. */+interface ActiveTransfer {+ id: stringcallerIdentity: string- recordIds: string[]- acquiredAt: string+ callerRoot: string+ source: GfsImageSource+ directory: string+ /** The input directory created at admission; publication writes only into it. */+ directoryIdentity?: InodeIdentity+ sizeBytes: number+ createdAt: stringexpiresAt: string- writerSessionId?: string}-interface GfsReceiptOwnerRecord {- ownerId: string- callerIdentity: string- writerSessionId: string- recordIds: string[]+export interface GfsDownloadSweepResult {+ removedExpired: number+ removedIncomplete: number+ removeFailed: number}-const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i-const SHA256_RE = /^[0-9a-f]{64}$/+interface SweepTotals extends GfsDownloadSweepResult {+ retainedCompleted: number+ retainedBytes: number+ /** Retained entries this process did not publish. */+ adopted: number+}++export interface GfsDownloadInventory {+ bytes: number+ files: number+ /** Keyed by the caller directory name (`users/<key>`), never by a recorded identity. */+ byCaller: Map<string, { bytes: number; files: number }>+}++type DirectoryState =+ | { state: 'absent' }+ | { state: 'incomplete' }+ | { state: 'complete'; entry: Entry }++function isValidSource(value: unknown): value is GfsImageSource {+ if (typeof value !== 'object' || value === null || Array.isArray(value)) return false+ const source = value as Record<string, unknown>+ return (+ source.kind === 'gfs' &&+ typeof source.drive === 'string' &&+ typeof source.resourceId === 'string' &&+ typeof source.gfsUri === 'string' &&+ typeof source.name === 'string' &&+ Number.isSafeInteger(source.version) &&+ (source.version as number) >= 0 &&+ (source.attachmentId === undefined || typeof source.attachmentId === 'string') &&+ (source.toolCallId === undefined || typeof source.toolCallId === 'string')+ )+}-export function parseLedger(raw: string): StoreLedger {+/** A recorded createdAt may lead this clock by at most this much (clock skew between Pods). */+const CREATED_AT_MAX_LEAD_MS = 60_000++/**+ * Returns undefined for anything that is not a schema-1 receipt for+ * `expectedId`. The time bounds keep a planted meta.json from outliving the+ * retention window: no complete entry can expire later than+ * `now + CREATED_AT_MAX_LEAD_MS + retentionMs`.+ */+function parseMeta(raw: string, expectedId: string, now: number): StoredMeta | undefined {let parsed: unknowntry {parsed = JSON.parse(raw)} catch {- throw new GfsDownloadStoreError('corrupt_store_ledger')+ return undefined}+ if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) return undefined+ const meta = parsed as Record<string, unknown>+ const createdAt = typeof meta.createdAt === 'string' ? Date.parse(meta.createdAt) : NaN+ const expiresAt = typeof meta.expiresAt === 'string' ? Date.parse(meta.expiresAt) : NaNif (- typeof parsed !== 'object' ||- parsed === null ||- (parsed as { schemaVersion?: unknown }).schemaVersion !== 1 ||- typeof (parsed as { records?: unknown }).records !== 'object' ||- (parsed as { records: unknown }).records === null ||- Array.isArray((parsed as { records: unknown }).records)+ meta.schemaVersion !== 1 ||+ meta.id !== expectedId ||+ typeof meta.callerIdentity !== 'string' ||+ meta.callerIdentity.length === 0 ||+ !isValidSource(meta.source) ||+ !Number.isSafeInteger(meta.sizeBytes) ||+ (meta.sizeBytes as number) < 0 ||+ (meta.sizeBytes as number) > GFS_FILE_LIMITS.maxFileBytes ||+ typeof meta.sha256 !== 'string' ||+ !SHA256_RE.test(meta.sha256) ||+ !Number.isFinite(createdAt) ||+ !Number.isFinite(expiresAt) ||+ expiresAt < createdAt ||+ expiresAt > createdAt + GFS_FILE_LIMITS.retentionMs ||+ createdAt > now + CREATED_AT_MAX_LEAD_MS)- throw new GfsDownloadStoreError('corrupt_store_ledger')-- const records = (parsed as { records: Record<string, unknown> }).records- const result: StoreLedger = {- schemaVersion: 1,- records: {},- retentionOwners: {},- }- for (const [id, value] of Object.entries(records)) {- if (!UUID_RE.test(id) || typeof value !== 'object' || value === null)- throw new GfsDownloadStoreError('corrupt_store_ledger')- const record = value as GfsDownloadRecord- const source = record.source- if (- !UUID_RE.test(record.id) ||- record.id !== id ||- typeof record.callerIdentity !== 'string' ||- record.callerIdentity.length === 0 ||- typeof source?.kind !== 'string' ||- source.kind !== 'gfs' ||- typeof source.drive !== 'string' ||- typeof source.resourceId !== 'string' ||- typeof source.gfsUri !== 'string' ||- typeof source.name !== 'string' ||- !Number.isSafeInteger(source.version) ||- source.version < 0 ||- typeof record.directory !== 'string' ||- path.isAbsolute(record.directory) ||- record.directory.includes('..') ||- record.directory !==- path.join(- path.dirname(path.dirname(record.directory)),- '.gfs-downloads',- `input-${record.id}`- ) ||- typeof record.path !== 'string' ||- record.path !== path.join('.gfs-downloads', `input-${record.id}`, 'source') ||- typeof record.hostPath !== 'string' ||- record.hostPath !== path.join(record.directory, 'source') ||- !Number.isSafeInteger(record.sizeBytes) ||- record.sizeBytes < 0 ||- !['transferring', 'completed', 'missing', 'cleanup_failed', 'quarantined'].includes(- record.state- ) ||- (record.sha256 !== undefined && !SHA256_RE.test(record.sha256)) ||- (record.state === 'completed' && !SHA256_RE.test(record.sha256 ?? '')) ||- !Number.isFinite(Date.parse(record.createdAt)) ||- !Number.isFinite(Date.parse(record.expiresAt))- )- throw new GfsDownloadStoreError('corrupt_store_ledger')- result.records[id] = record- }- const rawProcessingLeases = (parsed as { processingLeases?: unknown }).processingLeases- if (rawProcessingLeases !== undefined) {- if (- typeof rawProcessingLeases !== 'object' ||- rawProcessingLeases === null ||- Array.isArray(rawProcessingLeases)- )- throw new GfsDownloadStoreError('corrupt_store_ledger')- result.processingLeases = {}- for (const [id, value] of Object.entries(rawProcessingLeases)) {- const lease = value as LegacyProcessingLeaseRecord- if (- !UUID_RE.test(id) ||- typeof value !== 'object' ||- value === null ||- lease.leaseId !== id ||- typeof lease.callerIdentity !== 'string' ||- lease.callerIdentity.length === 0 ||- !Array.isArray(lease.recordIds) ||- lease.recordIds.some(recordId => !UUID_RE.test(recordId)) ||- new Set(lease.recordIds).size !== lease.recordIds.length ||- lease.recordIds.some(- recordId => result.records[recordId]?.callerIdentity !== lease.callerIdentity- ) ||- (lease.writerSessionId !== undefined && !UUID_RE.test(lease.writerSessionId)) ||- !Number.isFinite(Date.parse(lease.acquiredAt)) ||- !Number.isFinite(Date.parse(lease.expiresAt)) ||- Date.parse(lease.expiresAt) <= Date.parse(lease.acquiredAt)- )- throw new GfsDownloadStoreError('corrupt_store_ledger')- result.processingLeases[id] = lease- }- }- const owners = (parsed as { retentionOwners?: unknown }).retentionOwners- if (owners !== undefined) {- if (typeof owners !== 'object' || owners === null || Array.isArray(owners))- throw new GfsDownloadStoreError('corrupt_store_ledger')- for (const [ownerId, value] of Object.entries(owners)) {- if (typeof value !== 'object' || value === null)- throw new GfsDownloadStoreError('corrupt_store_ledger')- const owner = value as GfsReceiptOwnerRecord- if (- !validReceiptOwnerId(ownerId) ||- owner.ownerId !== ownerId ||- typeof owner.callerIdentity !== 'string' ||- owner.callerIdentity.length === 0 ||- !UUID_RE.test(owner.writerSessionId) ||- !Array.isArray(owner.recordIds) ||- new Set(owner.recordIds).size !== owner.recordIds.length ||- owner.recordIds.some(- id => !UUID_RE.test(id) || result.records[id]?.callerIdentity !== owner.callerIdentity- )- )- throw new GfsDownloadStoreError('corrupt_store_ledger')- result.retentionOwners![ownerId] = owner- }- }- return result+ return undefined+ return meta as unknown as StoredMeta}function validReceiptOwnerId(ownerId: string): boolean {@@ -254,33 +219,25 @@ function validReceiptOwnerId(ownerId: string): boolean {)}-interface Usage {- bytes: number- files: number- callerBytes: Record<string, number>- callerFiles: Record<string, number>-}-function isWithinDirectory(child: string, parent: string): boolean {const relative = path.relative(parent, child)return relative !== '' && !relative.startsWith('..') && !path.isAbsolute(relative)}-function usageFor(records: Iterable<GfsDownloadRecord>): Usage {- const usage: Usage = {- bytes: 0,- files: 0,- callerBytes: Object.create(null) as Record<string, number>,- callerFiles: Object.create(null) as Record<string, number>,- }- for (const record of records) {- usage.bytes += record.sizeBytes- usage.files += 1- usage.callerBytes[record.callerIdentity] =- (usage.callerBytes[record.callerIdentity] ?? 0) + record.sizeBytes- usage.callerFiles[record.callerIdentity] = (usage.callerFiles[record.callerIdentity] ?? 0) + 1+function errorCode(error: unknown): string {+ const code = (error as NodeJS.ErrnoException)?.code+ return typeof code === 'string' ? code : 'unknown'+}++/** A removal is proven by ENOENT, not by `fs.rm` returning. */+async function assertAbsent(target: string): Promise<void> {+ try {+ await fs.lstat(target)+ } catch (error) {+ if (errorCode(error) === 'ENOENT') return+ throw error}- return usage+ throw new GfsDownloadStoreError('storage_write_failed')}async function syncDirectory(directory: string): Promise<void> {@@ -307,119 +264,101 @@ async function sha256FileHandle(handle: fs.FileHandle, assertActive?: () => voidreturn digest.digest('hex')}-/** One Host/PVC-owned durable store; task registries receive bound handles. */+function receiptPath(id: string): string {+ return path.join(DOWNLOADS_DIRECTORY, `input-${id}`, SOURCE_FILE)+}++/** `<callerRoot>/.gfs-downloads/input-<id>` → `<callerRoot>`. */+/** Owner ids are scoped to their caller; the encoding is unambiguous for any strings. */+function pinKey(callerIdentity: string, ownerId: string): string {+ return JSON.stringify([callerIdentity, ownerId])+}++function callerRootOf(directory: string): string {+ return path.dirname(path.dirname(directory))+}++/** Adopted copies go first (oldest recorded first), then published ones least recently used. */+function evictionOrder(left: Entry, right: Entry): number {+ if (left.provenance !== right.provenance) return left.provenance === 'adopted' ? -1 : 1+ return left.lastUsedMs - right.lastUsedMs || left.id.localeCompare(right.id)+}++/**+ * GFS download store whose only state is the directory tree under+ * `users/<caller>/.gfs-downloads`. The filesystem is the truth for existence,+ * quota and cleanup: the in-memory index is rebuilt from disk at startup and+ * re-checked on admission and by every sweep. It is never the truth for who+ * downloaded a copy or for its hash: reuse and managed reads serve only copies+ * this process published. Active transfers and retention pins live in memory.+ */export class GfsDownloadStore {private hostRoot: stringprivate readonly requestedHostRoot: string- private storeRoot: string- private ledgerPath: string- private writerLease?: GfsStoreWriterLease- private writerSessionId = randomUUID()- private ledger: StoreLedger = {- schemaVersion: 1,- records: {},- retentionOwners: {},- }+ private readonly entries = new Map<string, Entry>()+ private readonly active = new Map<string, ActiveTransfer>()private readonly activeByCaller = new Map<string, number>()- private readonly activeIds = new Set<string>()- private active = 0- private mutationTail = Promise.resolve()+ /** Keyed by `pinKey(callerIdentity, ownerId)`: callers never share or see a pin. */+ private readonly pins = new Map<string, Set<string>>()+ private mutationTail: Promise<void> = Promise.resolve()+ private drainWaiters: Array<() => void> = []+ private initializing?: Promise<void>private initialized = falseprivate closing = false- private unsafe = false+ private closed = falseconstructor(hostRoot: string) {this.hostRoot = path.resolve(hostRoot)this.requestedHostRoot = this.hostRoot- this.storeRoot = path.join(this.hostRoot, '.gfs-download-store')- this.ledgerPath = path.join(this.storeRoot, 'ledger-v1.json')}isAvailable(): boolean {- if (!this.initialized || this.unsafe || !this.writerLease) return false- try {- this.writerLease.assertHeld()- return true- } catch {- return false- }+ return this.initialized && !this.closing && !this.closed}+ /**+ * Rejects only when the Host root itself is unusable (workspace_unavailable)+ * or the store was closed (download_busy). Leftover download directories+ * are removed or adopted; none of them can make initialize fail.+ */async initialize(): Promise<void> {+ if (this.closed || this.closing) throw new GfsDownloadStoreError('download_busy')if (this.initialized) return- await fs.mkdir(this.hostRoot, { recursive: true, mode: 0o700 })- const requestedHostInfo = await fs.lstat(this.hostRoot)- if (!requestedHostInfo.isDirectory() || requestedHostInfo.isSymbolicLink())- throw new GfsDownloadStoreError('workspace_unavailable')- this.hostRoot = await fs.realpath(this.hostRoot)- this.storeRoot = path.join(this.hostRoot, '.gfs-download-store')- this.ledgerPath = path.join(this.storeRoot, 'ledger-v1.json')- const hostInfo = await fs.lstat(this.hostRoot)- if (!hostInfo.isDirectory() || hostInfo.isSymbolicLink())- throw new GfsDownloadStoreError('workspace_unavailable')- // Exclusive, non-recursive creation distinguishes a genuinely new store- // directory from one that already existed. The host root above is created- // recursively, so only the store directory itself is probed here.- let createdStoreRoot = false- try {- await fs.mkdir(this.storeRoot, { mode: 0o700 })- createdStoreRoot = true- } catch (error) {- if ((error as NodeJS.ErrnoException).code !== 'EEXIST') throw error- }- try {- await verifyPrivateStoreDirectory(this.storeRoot)- } catch {- throw new GfsDownloadStoreError('workspace_unavailable')- }+ this.initializing ??= this.runInitialize().finally(() => {+ this.initializing = undefined+ })+ return this.initializing+ }- await this.acquireWriterLease(createdStoreRoot)- this.writerSessionId = randomUUID()- let raw: string | undefined+ private async runInitialize(): Promise<void> {try {- try {- const handle = await openPrivateStoreObject(- this.ledgerPath,- 'file',- constants.O_RDONLY,- false- )- try {- raw = await handle.readFile('utf8')- parseLedger(raw)- await handle.chmod(0o600)- } finally {- await handle.close()- }- } catch (error) {- if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error- }- if (raw !== undefined) {- // A successful read must always parse, including empty content, so a- // truncated ledger fails closed.- this.ledger = parseLedger(raw)- await this.discardLegacyProcessingLeases()- } else if (createdStoreRoot) {- // Genuinely new store directory: make the durable schema-1 ledger exist- // before reconciliation or any transfer exposure, so a ledger missing- // later is unambiguously unknown state.- await this.persist()- } else {- // The directory already existed with no durable ledger: a lost ledger- // or an interrupted first creation. Both are unknown state. Fail closed- // for operator recovery instead of silently resetting quota.- throw new GfsDownloadStoreError('corrupt_store_ledger')- }- await this.reconcile()- this.initialized = true- await this.cleanupExpired()- await this.persist()- this.reportQuarantine()+ await fs.mkdir(this.requestedHostRoot, { recursive: true, mode: 0o700 })+ const requested = await fs.lstat(this.requestedHostRoot)+ if (!requested.isDirectory() || requested.isSymbolicLink())+ throw new GfsDownloadStoreError('workspace_unavailable')+ this.hostRoot = await fs.realpath(this.requestedHostRoot)+ const resolved = await fs.lstat(this.hostRoot)+ if (!resolved.isDirectory() || resolved.isSymbolicLink())+ throw new GfsDownloadStoreError('workspace_unavailable')} catch (error) {- this.initialized = false- await this.releaseWriterLease()- throw error+ if (error instanceof GfsDownloadStoreError) throw error+ throw new GfsDownloadStoreError('workspace_unavailable')}+ const totals = await this.serialize(() => this.sweep(Date.now()))+ if (this.closed || this.closing) throw new GfsDownloadStoreError('download_busy')+ this.initialized = true+ logger.info(+ {+ component: GFS_DOWNLOAD_STORE_LOG_COMPONENT,+ removedIncomplete: totals.removedIncomplete,+ removedExpired: totals.removedExpired,+ retainedCompleted: totals.retainedCompleted,+ retainedBytes: totals.retainedBytes,+ adopted: totals.adopted,+ retiredLegacyStore: false,+ },+ 'GFS download store initialized'+ )}async createTransfer(input: {@@ -431,46 +370,42 @@ export class GfsDownloadStore {/** Task lifetime protection; release only after every physical consumer has settled. */retentionOwnerId?: string}): Promise<GfsDownloadTransfer> {- this.assertInitialized()- if (this.closing) throw new GfsDownloadStoreError('download_busy')+ this.assertAdmitting()if (!Number.isSafeInteger(input.sizeBytes) ||input.sizeBytes < 0 ||input.sizeBytes > GFS_FILE_LIMITS.maxFileBytes)throw new GfsDownloadStoreError('host_quota_exceeded')-if (typeof input.callerIdentity !== 'string' || input.callerIdentity.length === 0)throw new GfsDownloadStoreError('caller_mismatch')- if (!Number.isFinite(Date.parse(input.expiresAt)))- throw new GfsDownloadStoreError('corrupt_store_ledger')+ if (!isValidSource(input.source)) throw new RangeError('GFS download source is malformed')+ const createdAtMs = Date.now()+ const expiresAtMs = Date.parse(input.expiresAt)+ if (!Number.isFinite(expiresAtMs) || expiresAtMs < createdAtMs)+ throw new RangeError('GFS download expiry must be a future ISO timestamp')+ // The same bound parseMeta applies, so a published copy stays valid on disk.+ if (expiresAtMs > createdAtMs + GFS_FILE_LIMITS.retentionMs)+ throw new RangeError('GFS download expiry must be within the retention window')+ if (input.retentionOwnerId !== undefined) this.assertReceiptOwner(input.retentionOwnerId)const callerRoot = await this.validateCallerRoot(input.callerWorkspacePath)const id = randomUUID()- const relativeDirectory = path.join(- path.relative(this.hostRoot, callerRoot),- '.gfs-downloads',- `input-${id}`- )- const absoluteDirectory = path.join(this.hostRoot, relativeDirectory)- const hostPath = path.join(relativeDirectory, 'source')- const callerPath = path.relative(callerRoot, path.join(this.hostRoot, hostPath))- const record: GfsDownloadRecord = {+ const downloadsRoot = path.join(callerRoot, DOWNLOADS_DIRECTORY)+ const directory = path.join(downloadsRoot, `input-${id}`)+ const transfer: ActiveTransfer = {id,callerIdentity: input.callerIdentity,+ callerRoot,source: input.source,- directory: relativeDirectory,- path: callerPath,- hostPath,+ directory,sizeBytes: input.sizeBytes,- createdAt: new Date().toISOString(),+ createdAt: new Date(createdAtMs).toISOString(),expiresAt: input.expiresAt,- state: 'transferring',}await this.serialize(async () => {- this.assertInitialized()- if (this.closing) throw new GfsDownloadStoreError('download_busy')- if (this.active >= GFS_HOST_ACTIVE_DOWNLOADS) {+ this.assertAdmitting()+ if (this.active.size >= GFS_HOST_ACTIVE_DOWNLOADS) {recordGfsDownloadQuota('host', 'active_downloads')throw new GfsDownloadStoreError('download_busy')}@@ -481,11 +416,13 @@ export class GfsDownloadStore {recordGfsDownloadQuota('caller', 'active_downloads')throw new GfsDownloadStoreError('download_busy')}- if (input.retentionOwnerId !== undefined)- this.assertReceiptOwner(input.retentionOwnerId, input.callerIdentity)+ if (input.retentionOwnerId !== undefined) this.assertReceiptOwner(input.retentionOwnerId)+ // Verified free capacity first: no eviction happens for an admission the+ // volume cannot hold anyway. Measured again after eviction below.await this.assertPhysicalCapacity(input.sizeBytes)- await this.reclaimForAdmission(input.callerIdentity, input.sizeBytes)- const denial = this.quotaDenial(input.callerIdentity, input.sizeBytes)+ await this.sweep(Date.now())+ await this.reclaimForAdmission(callerRoot, input.sizeBytes)+ const denial = this.quotaDenial(callerRoot, input.sizeBytes)if (denial) {recordGfsDownloadQuota(denial.scope, denial.reason)throw new GfsDownloadStoreError(@@ -494,81 +431,44 @@ export class GfsDownloadStore {}await this.assertPhysicalCapacity(input.sizeBytes)- const previousOwner =- input.retentionOwnerId === undefined- ? undefined- : this.ledger.retentionOwners?.[input.retentionOwnerId]+ this.addActive(transfer)try {- if (input.retentionOwnerId !== undefined)- this.retainReceiptRecord(record, input.retentionOwnerId)- this.ledger.records[id] = record- await this.persist()+ await this.ensureDownloadsRoot(downloadsRoot)+ await fs.mkdir(directory, { mode: 0o700 })+ await this.verifyEntryDirectory(directory)+ transfer.directoryIdentity = await fs.lstat(directory, { bigint: true })+ const partial = await fs.open(+ path.join(directory, PARTIAL_FILE),+ constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW,+ 0o600+ )+ await partial.close()} catch (error) {- // No filesystem transfer or worker has been exposed. In-memory- // admission rolls back; an uncertain durable write stays fail-closed.- delete this.ledger.records[id]- if (input.retentionOwnerId !== undefined) {- if (previousOwner) this.ledger.retentionOwners![input.retentionOwnerId] = previousOwner- else delete this.ledger.retentionOwners![input.retentionOwnerId]- }- throw error+ this.releaseActive(id)+ await this.removeDirectory(directory, 'incomplete_removed')+ if (error instanceof GfsDownloadStoreError) throw error+ throw new GfsDownloadStoreError('storage_write_failed')}- this.active += 1- this.activeIds.add(id)- this.activeByCaller.set(- input.callerIdentity,- (this.activeByCaller.get(input.callerIdentity) ?? 0) + 1- )- return undefined+ if (input.retentionOwnerId !== undefined)+ this.pin(input.retentionOwnerId, input.callerIdentity, id)})- try {- await this.assertWriterOwnership()- const cacheRoot = path.dirname(absoluteDirectory)- try {- await fs.mkdir(cacheRoot, { mode: 0o700 })- } catch (error) {- if ((error as NodeJS.ErrnoException).code !== 'EEXIST') throw error- }- await verifyPrivateStoreDirectory(cacheRoot)- await fs.mkdir(absoluteDirectory, { mode: 0o700 })- await this.verifyManagedDirectory(record)- const partial = await fs.open(- path.join(this.hostRoot, `${record.hostPath}.partial`),- constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW,- 0o600- )- await partial.close()- } catch (error) {- try {- await this.serialize(async () => {- record.state = 'cleanup_failed'- // The producer's new pin has never exposed a transfer or receipt, so- // proven absence rolls it back. Delete/prove absence before- // releasing the durable reservation.- if (!(await this.removeRecordDirectory(record))) {- await this.persist()- throw new GfsDownloadStoreError('storage_write_failed')- }- await this.releaseRecordCharge(record)- })- } finally {- this.releaseActive(record)- }- if (error instanceof GfsDownloadStoreError) throw error- throw new GfsDownloadStoreError('storage_write_failed')- }-- const callerPartialPath = `${record.path}.partial`+ const callerPath = receiptPath(id)return {id,- path: record.path,- partialPath: callerPartialPath,+ path: callerPath,+ partialPath: `${callerPath}.partial`,sizeBytes: input.sizeBytes,expiresAt: input.expiresAt,}}+ /**+ * Publication order: sync source.partial, write meta.json (tmp + rename),+ * rename source.partial to source, sync the directory. A crash between the+ * renames leaves meta.json without source, which the sweep removes. Any+ * failure leaves the id active so the caller's fail() removes the directory.+ */async publish(id: string,callerIdentity: string,@@ -576,75 +476,131 @@ export class GfsDownloadStore {publication?: { signal?: AbortSignal; deadlineMs?: number }): Promise<GfsDownloadReceipt> {this.assertInitialized()- const record = this.record(id)- const receipt = await this.serialize(async () => {- if (record.callerIdentity !== callerIdentity)- throw new GfsDownloadStoreError('caller_mismatch')- if (!SHA256_RE.test(sha256)) throw new GfsDownloadStoreError('corrupt_store_ledger')- if (record.state !== 'transferring') throw new GfsDownloadStoreError('download_missing')- if (Date.parse(record.expiresAt) <= Date.now())+ if (!SHA256_RE.test(sha256)) throw new RangeError('GFS download digest is malformed')+ const transfer = this.active.get(id)+ // Another caller's transfer or copy is answered exactly like an unknown id.+ if (!transfer || transfer.callerIdentity !== callerIdentity)+ throw new GfsDownloadStoreError('download_missing')+ const entry = await this.serialize(async () => {+ // close() may have timed out while this waited: the reservation is gone.+ if (this.closed) throw new GfsDownloadStoreError('download_busy')+ if (this.active.get(id) !== transfer) throw new GfsDownloadStoreError('download_missing')+ if (Date.parse(transfer.expiresAt) <= Date.now())throw new GfsDownloadStoreError('download_expired')- const partial = path.join(this.hostRoot, `${record.hostPath}.partial`)- const source = path.join(this.hostRoot, record.hostPath)- await this.verifyManagedDirectory(record)- const partialHandle = await openPrivateStoreObject(- partial,- 'file',- constants.O_RDONLY,- false- ).catch(() => undefined)- if (!partialHandle) throw new GfsDownloadStoreError('download_missing')- let renamed = false- try {- const info = await partialHandle.stat()- if (!info.isFile() || info.isSymbolicLink() || info.size !== record.sizeBytes)- throw new GfsDownloadStoreError('download_missing')- if (- (await sha256FileHandle(partialHandle, () => this.assertPublicationOpen(publication))) !==- sha256- )- throw new GfsDownloadStoreError('corrupt_store_ledger')- // A finished rename is not a publication. The journal commit below is.- this.assertPublicationOpen(publication)- const named = await fs.lstat(partial)- if (named.isSymbolicLink() || named.dev !== info.dev || named.ino !== info.ino)- throw new GfsDownloadStoreError('download_missing')- await partialHandle.chmod(0o600)- await this.assertWriterOwnership()- await fs.rename(partial, source)- renamed = true- } finally {- await partialHandle.close()- }- if (!renamed) throw new GfsDownloadStoreError('download_missing')- await syncDirectory(path.dirname(source))this.assertPublicationOpen(publication)- record.state = 'completed'- record.sha256 = sha256+ let published: Entrytry {- await this.persist(publication)- this.assertPublicationOpen(publication)+ published = await this.writePublication(transfer, sha256, publication)} catch (error) {- // Publication is not observable outside this serialized operation until- // its journal has settled. Cancellation restores charged, unreadable- // transfer state even when it arrives during the atomic journal commit.- record.state = 'transferring'- delete record.sha256- if (error instanceof GfsDownloadStoreError && error.code === 'publication_cancelled')- await this.persist()- throw error- }- return {- id,- source: record.source,- path: record.path,- sizeBytes: record.sizeBytes,- sha256,- expiresAt: record.expiresAt,+ if (error instanceof GfsDownloadStoreError) throw error+ throw new GfsDownloadStoreError('storage_write_failed')}+ // Indexed and released in the same critical section, so no sweep can+ // observe the directory as neither active nor indexed.+ this.entries.set(id, published)+ this.releaseActive(id)+ return published+ })+ return this.receiptFor(entry, entry.source)+ }++ private async writePublication(+ transfer: ActiveTransfer,+ sha256: string,+ publication?: { signal?: AbortSignal; deadlineMs?: number }+ ): Promise<Entry> {+ const partialPath = path.join(transfer.directory, PARTIAL_FILE)+ const sourcePath = path.join(transfer.directory, SOURCE_FILE)+ const metaPath = path.join(transfer.directory, META_FILE)+ // The caller directory may have been replaced by a symlink since admission.+ await this.verifyEntryDirectory(transfer.directory)+ const partial = await openPrivateStoreObject(+ partialPath,+ 'file',+ constants.O_RDONLY,+ false+ ).catch(() => {+ throw new GfsDownloadStoreError('download_missing')})- this.releaseActive(record)- return receipt+ let sourceIdentity: InodeIdentity+ try {+ // A path swapped after the check above resolves to another directory:+ // the input directory must still be the one created at admission.+ await this.assertTransferDirectory(transfer)+ sourceIdentity = await partial.stat({ bigint: true })+ const info = await partial.stat()+ if (!info.isFile() || info.size !== transfer.sizeBytes)+ throw new GfsDownloadStoreError('download_missing')+ const digest = await sha256FileHandle(partial, () => this.assertPublicationOpen(publication))+ if (digest !== sha256) throw new GfsDownloadStoreError('storage_write_failed')+ const named = await fs.lstat(partialPath)+ if (named.isSymbolicLink() || named.dev !== info.dev || named.ino !== info.ino)+ throw new GfsDownloadStoreError('download_missing')+ await partial.chmod(0o600)+ await partial.sync()+ } finally {+ await partial.close()+ }++ const meta: StoredMeta = {+ schemaVersion: 1,+ id: transfer.id,+ callerIdentity: transfer.callerIdentity,+ source: transfer.source,+ sizeBytes: transfer.sizeBytes,+ sha256,+ createdAt: transfer.createdAt,+ expiresAt: transfer.expiresAt,+ }+ const temporary = path.join(transfer.directory, `${META_FILE}.tmp-${randomUUID()}`)+ let temporaryExists = false+ try {+ const handle = await fs.open(+ temporary,+ constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW,+ 0o600+ )+ temporaryExists = true+ try {+ await handle.writeFile(JSON.stringify(meta), 'utf8')+ await handle.sync()+ } finally {+ await handle.close()+ }+ this.assertPublicationOpen(publication)+ await this.assertTransferDirectory(transfer)+ await fs.rename(temporary, metaPath)+ temporaryExists = false+ } finally {+ if (temporaryExists) await fs.rm(temporary, { force: true }).catch(() => undefined)+ }+ // The last cancellation point: once source exists the download is complete.+ this.assertPublicationOpen(publication)+ await this.assertTransferDirectory(transfer)+ await fs.rename(partialPath, sourcePath)+ await syncDirectory(transfer.directory)+ // Only the inode that was hashed is published, wherever the name now leads.+ if (!sameInode(await fs.lstat(sourcePath, { bigint: true }), sourceIdentity))+ throw new GfsDownloadStoreError('storage_write_failed')+ return {+ ...meta,+ directory: transfer.directory,+ sourceIdentity: { dev: sourceIdentity.dev, ino: sourceIdentity.ino },+ callerRoot: transfer.callerRoot,+ provenance: 'published',+ lastUsedMs: Date.now(),+ }+ }++ /** The transfer's input directory is still the inode created at admission. */+ private async assertTransferDirectory(transfer: ActiveTransfer): Promise<void> {+ const current = await fs.lstat(transfer.directory, { bigint: true })+ if (+ !transfer.directoryIdentity ||+ !current.isDirectory() ||+ !sameInode(current, transfer.directoryIdentity)+ )+ throw new GfsDownloadStoreError('workspace_unavailable')}/** Reuse only after the caller has freshly authorized this exact source version. */@@ -654,188 +610,108 @@ export class GfsDownloadStore {sizeBytes: number,bounds?: { signal?: AbortSignal; deadlineMs?: number; retentionOwnerId?: string }): Promise<GfsDownloadReceipt | undefined> {- this.assertInitialized()+ this.assertAdmitting()return this.serialize(async () => {+ this.assertAdmitting()this.assertPublicationOpen(bounds)- if (bounds?.retentionOwnerId !== undefined)- this.assertReceiptOwner(bounds.retentionOwnerId, callerIdentity, true)- const record = Object.values(this.ledger.records).find(- item =>- item.callerIdentity === callerIdentity &&- item.state === 'completed' &&- Date.parse(item.expiresAt) > Date.now() &&- item.sizeBytes === sizeBytes &&- item.source.drive === source.drive &&- item.source.resourceId === source.resourceId &&- item.source.version === source.version &&- item.sha256 !== undefined+ if (bounds?.retentionOwnerId !== undefined) this.assertReceiptOwner(bounds.retentionOwnerId)+ // Only copies this process published: an adopted meta.json carries an+ // identity and a digest that anyone with the Host UID could have written.+ // A miss is final; the caller downloads the file again.+ const entry = [...this.entries.values()].find(+ candidate =>+ candidate.provenance === 'published' &&+ candidate.callerIdentity === callerIdentity &&+ Date.parse(candidate.expiresAt) > Date.now() &&+ candidate.sizeBytes === sizeBytes &&+ candidate.source.drive === source.drive &&+ candidate.source.resourceId === source.resourceId &&+ candidate.source.version === source.version)- if (!record) return undefined- const unavailable = async (): Promise<undefined> => {- record.state = 'missing'- delete record.sha256- await this.persist()- return undefined- }- const handle = await this.openRecordContent(record).catch(() => undefined)- if (!handle) return unavailable()+ if (!entry) return undefined+ let verified = falsetry {- const info = await handle.stat()- if (!info.isFile() || info.size !== sizeBytes || (info.mode & 0o777) !== 0o600)- return unavailable()- if (- (await sha256FileHandle(handle, () => this.assertPublicationOpen(bounds))) !==- record.sha256- )- return unavailable()- } finally {- await handle.close()- }- this.assertPublicationOpen(bounds)- if (bounds?.retentionOwnerId !== undefined) {- const previousOwner = this.ledger.retentionOwners?.[bounds.retentionOwnerId]- this.retainReceiptRecord(record, bounds.retentionOwnerId, true)+ const handle = await this.openEntryContent(entry)try {- await this.persist(bounds)- } catch (error) {- if (previousOwner) this.ledger.retentionOwners![bounds.retentionOwnerId] = previousOwner- else delete this.ledger.retentionOwners![bounds.retentionOwnerId]- throw error+ const info = await handle.stat()+ verified =+ info.isFile() &&+ info.size === sizeBytes &&+ (info.mode & 0o777) === 0o600 &&+ (await sha256FileHandle(handle, () => this.assertPublicationOpen(bounds))) ===+ entry.sha256+ } finally {+ await handle.close()}+ } catch (error) {+ if (error instanceof GfsDownloadStoreError && error.code === 'publication_cancelled')+ throw error+ verified = false}- return {- id: record.id,- source,- path: record.path,- sizeBytes: record.sizeBytes,- sha256: record.sha256!,- expiresAt: record.expiresAt,+ if (!verified) {+ await this.removeEntry(entry, 'incomplete_removed')+ return undefined}+ this.assertPublicationOpen(bounds)+ entry.lastUsedMs = Date.now()+ if (bounds?.retentionOwnerId !== undefined)+ this.pin(bounds.retentionOwnerId, callerIdentity, entry.id)+ return this.receiptFor(entry, source)})}+ /**+ * Called by the producer after a transfer that was not published. The+ * directory is removed and the reservation released; a publish that failed+ * keeps its id active precisely so this call can clean it up.+ */async fail(id: string, callerIdentity: string): Promise<void> {- const record = this.record(id)- if (record.callerIdentity !== callerIdentity) throw new GfsDownloadStoreError('caller_mismatch')- if (!this.activeIds.has(id) && record.state !== 'cleanup_failed')+ const transfer = this.active.get(id)+ // Another caller's transfer or copy is answered exactly like an unknown id.+ if (!transfer || transfer.callerIdentity !== callerIdentity)throw new GfsDownloadStoreError('download_busy')- try {- this.assertInitialized()- await this.serialize(async () => {- this.assertInitialized()- if (record.callerIdentity !== callerIdentity)- throw new GfsDownloadStoreError('caller_mismatch')- // Publication or another admission may have settled while this waited.- if (- (!this.activeIds.has(id) && record.state !== 'cleanup_failed') ||- record.state === 'completed'- )- throw new GfsDownloadStoreError('download_busy')- record.state = 'cleanup_failed'- if (this.hasReceiptOwner(id)) {- await this.persist()- return- }- if (!(await this.removeRecordDirectory(record))) {- await this.persist()- throw new GfsDownloadStoreError('storage_write_failed')- }- await this.releaseRecordCharge(record)- })- } finally {- // The caller invokes failure only after its stream/descriptor is settled.- // Uncertain bytes stay charged.- this.releaseActive(record)- }+ await this.serialize(async () => {+ if (this.closed) throw new GfsDownloadStoreError('download_busy')+ // Publication may have settled while this waited.+ if (this.active.get(id) !== transfer) throw new GfsDownloadStoreError('download_busy')+ this.releaseActive(id)+ this.unpinId(id)+ if (!(await this.removeDirectory(transfer.directory, 'incomplete_removed')))+ throw new GfsDownloadStoreError('storage_write_failed')+ })}- async inspect(- callerRelativePath: string,- callerIdentity: string- ): Promise<GfsDownloadReceipt & { id: string }> {- this.assertInitialized()- const record = Object.values(this.ledger.records).find(- item => item.callerIdentity === callerIdentity && item.path === callerRelativePath- )- if (!record) throw new GfsDownloadStoreError('caller_mismatch')- if (Date.parse(record.expiresAt) <= Date.now())- throw new GfsDownloadStoreError('download_expired')- if (record.state !== 'completed' || !record.sha256)- throw new GfsDownloadStoreError('download_missing')- const handle = await this.openRecordContent(record).catch(() => undefined)- if (!handle) throw new GfsDownloadStoreError('download_missing')- let digestValid = false++ async readManagedFile(callerRelativePath: string, callerIdentity: string): Promise<Buffer> {+ const entry = this.managedEntry(callerRelativePath, callerIdentity)+ let bytes: Buffertry {- const info = await handle.stat()- if (- !info.isFile() ||- info.isSymbolicLink() ||- info.size !== record.sizeBytes ||- (info.mode & 0o777) !== 0o600- )- throw new GfsDownloadStoreError('download_missing')- const digest = createHash('sha256')- const chunk = Buffer.alloc(64 * 1024)- let position = 0- for (;;) {- const { bytesRead } = await handle.read(chunk, 0, chunk.byteLength, position)- if (bytesRead === 0) break- digest.update(chunk.subarray(0, bytesRead))- position += bytesRead+ const handle = await this.openEntryContent(entry)+ try {+ const info = await handle.stat()+ if (!info.isFile() || info.size !== entry.sizeBytes || (info.mode & 0o777) !== 0o600)+ throw new GfsDownloadStoreError('download_missing')+ bytes = Buffer.alloc(entry.sizeBytes)+ let offset = 0+ while (offset < entry.sizeBytes) {+ const { bytesRead } = await handle.read(bytes, offset, entry.sizeBytes - offset, offset)+ if (bytesRead <= 0) throw new GfsDownloadStoreError('download_missing')+ offset += bytesRead+ }+ const probe = Buffer.alloc(1)+ const extra = await handle.read(probe, 0, 1, entry.sizeBytes)+ if (extra.bytesRead !== 0) throw new GfsDownloadStoreError('download_missing')+ } finally {+ await handle.close()}- digestValid = digest.digest('hex') === record.sha256- } finally {- await handle.close()+ } catch {+ throw new GfsDownloadStoreError('download_missing')}- if (!digestValid) throw new GfsDownloadStoreError('download_missing')- return {- id: record.id,- source: record.source,- path: record.path,- sizeBytes: record.sizeBytes,- sha256: record.sha256,- expiresAt: record.expiresAt,+ if (createHash('sha256').update(bytes).digest('hex') !== entry.sha256) {+ // A copy whose bytes no longer match its receipt is not a cache entry.+ await this.serialize(() => this.removeEntry(entry, 'incomplete_removed'))+ throw new GfsDownloadStoreError('download_missing')}- }-- async readManagedFile(callerRelativePath: string, callerIdentity: string): Promise<Buffer> {- this.assertInitialized()- const record = Object.values(this.ledger.records).find(- item => item.callerIdentity === callerIdentity && item.path === callerRelativePath- )- if (!record) throw new GfsDownloadStoreError('caller_mismatch')- if (Date.parse(record.expiresAt) <= Date.now())- throw new GfsDownloadStoreError('download_expired')- if (record.state !== 'completed' || !record.sha256)- throw new GfsDownloadStoreError('download_missing')-- const handle = await this.openRecordContent(record).catch(() => undefined)- if (!handle) throw new GfsDownloadStoreError('download_missing')- let bytes: Buffer- try {- const info = await handle.stat()- if (- !info.isFile() ||- info.isSymbolicLink() ||- info.size !== record.sizeBytes ||- (info.mode & 0o777) !== 0o600- )- throw new GfsDownloadStoreError('download_missing')- bytes = Buffer.alloc(record.sizeBytes)- let offset = 0- while (offset < record.sizeBytes) {- const { bytesRead } = await handle.read(bytes, offset, record.sizeBytes - offset, offset)- if (bytesRead <= 0) throw new GfsDownloadStoreError('download_missing')- offset += bytesRead- }- const probe = Buffer.alloc(1)- const extra = await handle.read(probe, 0, 1, record.sizeBytes)- if (extra.bytesRead !== 0) throw new GfsDownloadStoreError('download_missing')- } finally {- await handle.close()- }- if (createHash('sha256').update(bytes).digest('hex') !== record.sha256)- throw new GfsDownloadStoreError('download_missing')- return bytes+ return bytes}async readManagedFilePrefix(@@ -843,189 +719,401 @@ export class GfsDownloadStore {callerIdentity: string,prefixBytes = 16): Promise<Buffer> {- this.assertInitialized()+ this.assertReadable()if (!Number.isSafeInteger(prefixBytes) || prefixBytes <= 0 || prefixBytes > 4096)- throw new GfsDownloadStoreError('corrupt_store_ledger')- const record = Object.values(this.ledger.records).find(- item => item.callerIdentity === callerIdentity && item.path === callerRelativePath- )- if (!record) throw new GfsDownloadStoreError('caller_mismatch')- if (Date.parse(record.expiresAt) <= Date.now())- throw new GfsDownloadStoreError('download_expired')- if (record.state !== 'completed' || !record.sha256)- throw new GfsDownloadStoreError('download_missing')-- const handle = await this.openRecordContent(record).catch(() => undefined)- if (!handle) throw new GfsDownloadStoreError('download_missing')+ throw new RangeError('GFS managed-file prefix must be between 1 and 4096 bytes')+ const entry = this.managedEntry(callerRelativePath, callerIdentity)try {- const info = await handle.stat()- if (- !info.isFile() ||- info.isSymbolicLink() ||- info.size !== record.sizeBytes ||- (info.mode & 0o777) !== 0o600- )- throw new GfsDownloadStoreError('download_missing')- const prefix = Buffer.alloc(prefixBytes)- const { bytesRead } = await handle.read(prefix, 0, prefix.byteLength, 0)- return prefix.subarray(0, bytesRead)- } finally {- await handle.close()+ const handle = await this.openEntryContent(entry)+ try {+ const info = await handle.stat()+ if (!info.isFile() || info.size !== entry.sizeBytes || (info.mode & 0o777) !== 0o600)+ throw new GfsDownloadStoreError('download_missing')+ const prefix = Buffer.alloc(prefixBytes)+ const { bytesRead } = await handle.read(prefix, 0, prefix.byteLength, 0)+ return prefix.subarray(0, bytesRead)+ } finally {+ await handle.close()+ }+ } catch {+ throw new GfsDownloadStoreError('download_missing')}}- /** Caller/task lifecycle must prove consumer settlement before invoking this. */+ /**+ * Caller/task lifecycle must prove consumer settlement before invoking this.+ * Releases only the caller's own pin; an owner id another caller uses is a+ * different pin, so the call is the same no-op as for an unknown owner.+ */async releaseReceiptOwner(ownerId: string, callerIdentity: string): Promise<void> {- this.assertInitialized()+ this.assertReadable()await this.serialize(async () => {- const owner = this.ledger.retentionOwners?.[ownerId]- if (!owner) return- if (owner.callerIdentity !== callerIdentity)- throw new GfsDownloadStoreError('caller_mismatch')- delete this.ledger.retentionOwners![ownerId]- try {- await this.persist()- } catch (error) {- this.ledger.retentionOwners![ownerId] = owner- throw error- }- await this.cleanupSettledFailedTransfers(callerIdentity)+ this.pins.delete(pinKey(callerIdentity, ownerId))})}- private assertReceiptOwner(- ownerId: string,- callerIdentity: string,- allowPriorOwner = false- ): void {- if (!validReceiptOwnerId(ownerId)) throw new GfsDownloadStoreError('caller_mismatch')- const existing = this.ledger.retentionOwners?.[ownerId]- if (existing && existing.callerIdentity !== callerIdentity)- throw new GfsDownloadStoreError('caller_mismatch')- if (existing && existing.writerSessionId !== this.writerSessionId && !allowPriorOwner)- throw new GfsDownloadStoreError('download_busy')- }-- private retainReceiptRecord(- record: GfsDownloadRecord,- ownerId: string,- allowPriorOwner = false- ): void {- this.assertReceiptOwner(ownerId, record.callerIdentity, allowPriorOwner)- this.ledger.retentionOwners ??= {}- const existing = this.ledger.retentionOwners[ownerId]- this.ledger.retentionOwners[ownerId] = {- ownerId,- callerIdentity: record.callerIdentity,- writerSessionId: this.writerSessionId,- recordIds: [...new Set([...(existing?.recordIds ?? []), record.id])],+ /** Removes expired and incomplete downloads; startup runs the same sweep. */+ async cleanupExpired(now = Date.now()): Promise<GfsDownloadSweepResult> {+ this.assertReadable()+ try {+ const totals = await this.serialize(() => this.sweep(now))+ return {+ removedExpired: totals.removedExpired,+ removedIncomplete: totals.removedIncomplete,+ removeFailed: totals.removeFailed,+ }+ } catch (error) {+ recordGfsDownloadExpiry('sweep_failed')+ throw error}}- private forgetReceiptRecord(recordId: string): void {- for (const [ownerId, owner] of Object.entries(this.ledger.retentionOwners ?? {})) {- const recordIds = owner.recordIds.filter(id => id !== recordId)- if (recordIds.length === 0) delete this.ledger.retentionOwners![ownerId]- else this.ledger.retentionOwners![ownerId] = { ...owner, recordIds }+ /**+ * Stops admitting, waits for active transfers until the deadline and then+ * closes regardless. Transfers still active afterwards get download_busy+ * from publish/fail; their directories are removed by the next start.+ */+ async close(drainTimeoutMs = 5_000): Promise<void> {+ if (this.closed || this.closing) return+ if (!this.initialized) {+ this.closed = true+ return}+ this.closing = true+ let timer: NodeJS.Timeout | undefined+ const deadline = new Promise<void>(resolve => {+ timer = setTimeout(resolve, drainTimeoutMs)+ })+ const drained = new Promise<void>(resolve => {+ if (this.active.size === 0) resolve()+ else this.drainWaiters.push(resolve)+ })+ // Active transfers first, then whatever mutation is still in flight; both+ // bounded by the same deadline.+ await Promise.race([drained.then(() => this.mutationTail), deadline])+ clearTimeout(timer)+ if (this.active.size > 0)+ logger.warn(+ { component: GFS_DOWNLOAD_STORE_LOG_COMPONENT, active: this.active.size },+ 'GFS download store closed with active transfers; their directories are removed at the next start'+ )+ this.closed = true+ this.closing = false}- private hasReceiptOwner(recordId: string): boolean {- return Object.values(this.ledger.retentionOwners ?? {}).some(owner =>- owner.recordIds.includes(recordId)- )- }-- private hasLiveReceiptOwners(): boolean {- return Object.values(this.ledger.retentionOwners ?? {}).some(- owner => owner.writerSessionId === this.writerSessionId- )+ /** Test-only: complete downloads on disk plus in-memory reservations. Read-only. */+ async debugInventory(): Promise<GfsDownloadInventory> {+ const inventory: GfsDownloadInventory = { bytes: 0, files: 0, byCaller: new Map() }+ const add = (callerRoot: string, sizeBytes: number) => {+ const key = path.basename(callerRoot)+ inventory.bytes += sizeBytes+ inventory.files += 1+ const caller = inventory.byCaller.get(key) ?? { bytes: 0, files: 0 }+ caller.bytes += sizeBytes+ caller.files += 1+ inventory.byCaller.set(key, caller)+ }+ const now = Date.now()+ for (const { id, directory } of await this.listInputDirectories()) {+ if (this.active.get(id)?.directory === directory) continue+ const state = await this.inspectDirectory(directory, id, now)+ if (state.state === 'complete') add(state.entry.callerRoot, state.entry.sizeBytes)+ }+ for (const transfer of this.active.values()) add(transfer.callerRoot, transfer.sizeBytes)+ return inventory}- debugRecord(id: string): GfsDownloadRecord | undefined {- return this.ledger.records[id]- }+ /**+ * Walks `users/*\/.gfs-downloads/*` plus every indexed directory. Incomplete+ * directories and expired, unpinned complete ones are removed; complete ones+ * are (re)indexed, new ones as adopted. Active transfers of this process are+ * never touched, and a published entry is never replaced: another directory+ * carrying the id of a reservation or of a published copy is removed, and an+ * id found in several directories with neither is removed everywhere (a+ * random uuid does not repeat by chance).+ */+ private async sweep(now: number): Promise<SweepTotals> {+ const totals: SweepTotals = {+ removedExpired: 0,+ removedIncomplete: 0,+ removeFailed: 0,+ retainedCompleted: 0,+ retainedBytes: 0,+ adopted: 0,+ }+ const candidates = new Map<string, string[]>()+ const addCandidate = (id: string, directory: string) => {+ const directories = candidates.get(id) ?? []+ if (!directories.includes(directory)) directories.push(directory)+ candidates.set(id, directories)+ }+ for (const { id, directory } of await this.listInputDirectories(totals))+ addCandidate(id, directory)+ for (const entry of this.entries.values()) addCandidate(entry.id, entry.directory)+ const removeIncomplete = async (directory: string) => {+ if (await this.removeDirectory(directory, 'incomplete_removed')) totals.removedIncomplete += 1+ else totals.removeFailed += 1+ }- debugUsage(): Usage {- return usageFor(Object.values(this.ledger.records))+ for (const [id, directories] of candidates) {+ const indexed = this.entries.get(id)+ const owned =+ this.active.get(id)?.directory ??+ (indexed?.provenance === 'published' ? indexed.directory : undefined)+ if (owned === undefined && directories.length > 1) {+ this.forget(id)+ for (const duplicate of directories) await removeIncomplete(duplicate)+ continue+ }+ if (owned !== undefined)+ for (const duplicate of directories)+ if (duplicate !== owned) await removeIncomplete(duplicate)+ if (this.active.has(id)) continue+ const directory = owned ?? directories[0]!+ const state =+ indexed && indexed.directory === directory+ ? await this.recheckIndexed(indexed)+ : await this.inspectDirectory(directory, id, now)+ if (state.state === 'absent') {+ this.forget(id)+ continue+ }+ if (state.state === 'incomplete') {+ this.forget(id)+ await removeIncomplete(directory)+ continue+ }+ const entry = state.entry+ if (Date.parse(entry.expiresAt) <= now && !this.isPinned(id)) {+ this.forget(id)+ if (await this.removeDirectory(directory, 'expired_removed')) totals.removedExpired += 1+ else totals.removeFailed += 1+ continue+ }+ this.entries.set(id, entry)+ totals.retainedCompleted += 1+ totals.retainedBytes += entry.sizeBytes+ if (entry.provenance === 'adopted') totals.adopted += 1+ }+ return totals}- async debugPersist(): Promise<void> {- await this.persist()+ /**+ * Lists store-owned directories. A `.gfs-downloads` that is a symlink or not+ * a directory is removed without following it; names that do not match+ * `input-<uuid>` are left alone because they are not the store's.+ */+ private async listInputDirectories(+ totals?: SweepTotals+ ): Promise<Array<{ id: string; directory: string }>> {+ const found: Array<{ id: string; directory: string }> = []+ const usersRoot = path.join(this.hostRoot, 'users')+ let users: import('node:fs').Dirent[]+ try {+ const info = await fs.lstat(usersRoot)+ if (!info.isDirectory()) return found+ users = await fs.readdir(usersRoot, { withFileTypes: true })+ } catch (error) {+ if (errorCode(error) === 'ENOENT') return found+ this.reportSweepFailure(error)+ return found+ }+ for (const user of users) {+ if (!user.isDirectory()) continue+ const downloadsRoot = path.join(usersRoot, user.name, DOWNLOADS_DIRECTORY)+ let children: import('node:fs').Dirent[]+ try {+ const info = await fs.lstat(downloadsRoot)+ if (!info.isDirectory()) {+ if (totals) {+ if (await this.removeDirectory(downloadsRoot, 'incomplete_removed'))+ totals.removedIncomplete += 1+ else totals.removeFailed += 1+ }+ continue+ }+ children = await fs.readdir(downloadsRoot, { withFileTypes: true })+ } catch (error) {+ if (errorCode(error) === 'ENOENT') continue+ this.reportSweepFailure(error)+ continue+ }+ for (const child of children) {+ const match = GFS_INPUT_DIRECTORY_RE.exec(child.name)+ if (match) found.push({ id: match[1]!, directory: path.join(downloadsRoot, child.name) })+ else if (totals && TRASH_DIRECTORY_RE.test(child.name)) {+ // Left by a removal that stopped between its rename and its rm.+ if (+ await this.removeDirectory(path.join(downloadsRoot, child.name), 'incomplete_removed')+ )+ totals.removedIncomplete += 1+ else totals.removeFailed += 1+ }+ }+ }+ return found}- async close(drainTimeoutMs = 5_000): Promise<void> {- if (!this.initialized) return- this.closing = true- const deadline = Date.now() + drainTimeoutMs- while ((this.activeIds.size > 0 || this.hasLiveReceiptOwners()) && Date.now() < deadline) {- await new Promise(resolve => setTimeout(resolve, 25))- }- if (this.activeIds.size > 0 || this.hasLiveReceiptOwners()) {- this.closing = false- throw new GfsDownloadStoreError('download_busy')+ /** Reads one directory from disk; a complete result is always `adopted`. */+ private async inspectDirectory(+ directory: string,+ id: string,+ now: number+ ): Promise<DirectoryState> {+ let info: import('node:fs').Stats+ try {+ info = await fs.lstat(directory)+ } catch (error) {+ if (errorCode(error) === 'ENOENT') return { state: 'absent' }+ return { state: 'incomplete' }}- await this.mutationTail- // Work already queued before shutdown can finish admission while close- // waits. Never release writer ownership over a newly active operation.- if (this.activeIds.size > 0 || this.hasLiveReceiptOwners()) {- this.closing = false- throw new GfsDownloadStoreError('download_busy')+ if (!info.isDirectory()) return { state: 'incomplete' }+ let raw: string+ try {+ const handle = await fs.open(+ path.join(directory, META_FILE),+ constants.O_RDONLY | constants.O_NOFOLLOW+ )+ try {+ const metaInfo = await handle.stat()+ if (!metaInfo.isFile() || metaInfo.size > META_MAX_BYTES) return { state: 'incomplete' }+ raw = await handle.readFile('utf8')+ } finally {+ await handle.close()+ }+ } catch {+ return { state: 'incomplete' }}+ const meta = parseMeta(raw, id, now)+ if (!meta) return { state: 'incomplete' }try {- await this.serialize(async () => {- await this.persist()- })- } finally {- this.initialized = false- await this.releaseWriterLease()- this.closing = false+ const source = await fs.lstat(path.join(directory, SOURCE_FILE))+ if (!source.isFile() || source.size !== meta.sizeBytes) return { state: 'incomplete' }+ } catch {+ return { state: 'incomplete' }+ }+ return {+ state: 'complete',+ entry: {+ ...meta,+ directory,+ callerRoot: callerRootOf(directory),+ provenance: 'adopted',+ lastUsedMs: Date.parse(meta.createdAt),+ },}}- async cleanupExpired(now = Date.now()): Promise<void> {- this.assertInitialized()+ /** An indexed entry is re-checked with one lstat; meta.json is not re-read. */+ private async recheckIndexed(entry: Entry): Promise<DirectoryState> {try {- await this.serialize(async () => {- for (const record of Object.values(this.ledger.records)) {- if (- Date.parse(record.expiresAt) > now ||- this.activeIds.has(record.id) ||- this.hasReceiptOwner(record.id) ||- record.state === 'quarantined'- )- continue- if (await this.removeRecordDirectory(record)) {- await this.releaseRecordCharge(record)- recordGfsDownloadExpiry('expired_removed')- } else {- record.state = 'cleanup_failed'- await this.persist()- recordGfsDownloadExpiry('cleanup_failed')- }- }- })+ const source = await fs.lstat(path.join(entry.directory, SOURCE_FILE))+ if (source.isFile() && source.size === entry.sizeBytes) return { state: 'complete', entry }} catch (error) {- recordGfsDownloadExpiry('sweep_failed')- throw error+ if (errorCode(error) === 'ENOENT') {+ try {+ await fs.lstat(entry.directory)+ } catch (directoryError) {+ if (errorCode(directoryError) === 'ENOENT') return { state: 'absent' }+ }+ }}+ return { state: 'incomplete' }}- private async cleanupSettledFailedTransfers(callerIdentity: string): Promise<void> {- for (const record of Object.values(this.ledger.records)) {+ /**+ * Index lookup for a managed read. Only a copy this process published for+ * this caller is served. An adopted, unknown or another caller's id is the+ * same download_missing, decided from the index alone: the disk is not+ * probed, because nothing on disk can prove who downloaded a copy, and a+ * foreign copy must cost no more work than a missing one.+ */+ private managedEntry(callerRelativePath: string, callerIdentity: string): Entry {+ this.assertReadable()+ const match = RECEIPT_PATH_RE.exec(callerRelativePath)+ if (!match) throw new GfsDownloadStoreError('download_missing')+ const entry = this.entries.get(match[1]!)+ if (!entry || entry.provenance !== 'published' || entry.callerIdentity !== callerIdentity)+ throw new GfsDownloadStoreError('download_missing')+ if (Date.parse(entry.expiresAt) <= Date.now())+ throw new GfsDownloadStoreError('download_expired')+ entry.lastUsedMs = Date.now()+ return entry+ }++ private async openEntryContent(entry: Entry): Promise<fs.FileHandle> {+ await this.verifyEntryDirectory(entry.directory)+ const handle = await openPrivateStoreObject(+ path.join(entry.directory, SOURCE_FILE),+ 'file',+ constants.O_RDONLY,+ false+ )+ try {+ // The descriptor, not the path, decides: a name swapped after the+ // directory check opens another inode and is refused.if (- record.callerIdentity !== callerIdentity ||- record.state !== 'cleanup_failed' ||- this.activeIds.has(record.id) ||- this.hasReceiptOwner(record.id)+ !entry.sourceIdentity ||+ !sameInode(await handle.stat({ bigint: true }), entry.sourceIdentity))- continue- if (await this.removeRecordDirectory(record)) await this.releaseRecordCharge(record)+ throw new GfsDownloadStoreError('download_missing')+ const info = await handle.stat()+ if (info.size !== entry.sizeBytes) throw new GfsDownloadStoreError('download_missing')+ if ((info.mode & 0o7777) !== 0o600) {+ // Restore the private mode only for content that still matches.+ if ((await sha256FileHandle(handle)) !== entry.sha256)+ throw new GfsDownloadStoreError('download_missing')+ await handle.chmod(0o600)+ }+ return handle+ } catch (error) {+ await handle.close()+ throw error+ }+ }++ private async verifyEntryDirectory(directory: string): Promise<void> {+ if (!isWithinDirectory(directory, this.hostRoot))+ throw new GfsDownloadStoreError('workspace_unavailable')+ const callerRoot = path.dirname(path.dirname(directory))+ if ((await fs.realpath(callerRoot)) !== callerRoot)+ throw new GfsDownloadStoreError('workspace_unavailable')+ await verifyPrivateStoreDirectory(path.dirname(directory))+ await verifyPrivateStoreDirectory(directory)+ }++ /**+ * A `.gfs-downloads` that is a symlink, not a directory, or not private to+ * this process is removed without following it and recreated, so a shell+ * command can cost a caller its cached copies but never block its downloads.+ */+ private async ensureDownloadsRoot(downloadsRoot: string): Promise<void> {+ try {+ await fs.mkdir(downloadsRoot, { mode: 0o700 })+ return+ } catch (error) {+ if (errorCode(error) !== 'EEXIST') throw error}+ try {+ await verifyPrivateStoreDirectory(downloadsRoot)+ return+ } catch {+ // Not a private directory: replaced below.+ }+ for (const id of this.idsUnder(downloadsRoot)) this.forget(id)+ await this.removeVerified(downloadsRoot)+ await fs.mkdir(downloadsRoot, { mode: 0o700 })+ await verifyPrivateStoreDirectory(downloadsRoot)+ }++ private idsUnder(downloadsRoot: string): string[] {+ return [...this.entries.values()]+ .filter(entry => path.dirname(entry.directory) === downloadsRoot)+ .map(entry => entry.id)}private async assertPhysicalCapacity(sizeBytes: number): Promise<void> {- const space = await fs.statfs(this.storeRoot, { bigint: true })+ const space = await fs.statfs(this.hostRoot, { bigint: true })if (space.bsize <= 0n || space.bavail < 0n) {recordGfsDownloadQuota('host', 'free_space')throw new GfsDownloadStoreError('host_quota_exceeded')@@ -1034,32 +1122,46 @@ export class GfsDownloadStore {const amount = BigInt(bytes)return ((amount + space.bsize - 1n) / space.bsize) * space.bsize}- let required = reserve(sizeBytes) + 16n * 1024n * 1024n- for (const id of this.activeIds) {- const record = this.ledger.records[id]- // Use the full outstanding reservation rather than optimistically- // crediting sparse, shared or concurrently written physical allocation.- if (record && record.state !== 'completed') required += reserve(record.sizeBytes)- }- // Allocated/apparent cache bytes are not proven freeable bytes on shared,- // reflink or snapshot filesystems. Require currently verified free capacity- // before any destructive quota reclaim, then measure it again afterward.+ let required = reserve(sizeBytes) + FREE_SPACE_RESERVE_BYTES+ // Use the full outstanding reservation of every active transfer rather+ // than crediting sparse, shared or concurrently written allocation.+ for (const transfer of this.active.values()) required += reserve(transfer.sizeBytes)if (space.bavail * space.bsize < required) {recordGfsDownloadQuota('host', 'free_space')throw new GfsDownloadStoreError('host_quota_exceeded')}}+ /** Caller usage is keyed by the caller directory that holds each copy, never by meta.json. */+ private usage(excluded: ReadonlySet<string> = new Set()) {+ const usage = {+ bytes: 0,+ files: 0,+ callerBytes: new Map<string, number>(),+ callerFiles: new Map<string, number>(),+ }+ const add = (callerRoot: string, sizeBytes: number) => {+ usage.bytes += sizeBytes+ usage.files += 1+ usage.callerBytes.set(callerRoot, (usage.callerBytes.get(callerRoot) ?? 0) + sizeBytes)+ usage.callerFiles.set(callerRoot, (usage.callerFiles.get(callerRoot) ?? 0) + 1)+ }+ for (const entry of this.entries.values())+ if (!excluded.has(entry.id)) add(entry.callerRoot, entry.sizeBytes)+ for (const transfer of this.active.values()) add(transfer.callerRoot, transfer.sizeBytes)+ return usage+ }+private quotaDenial(- callerIdentity: string,+ callerRoot: string,sizeBytes: number,- records: Iterable<GfsDownloadRecord> = Object.values(this.ledger.records)+ excluded?: ReadonlySet<string>): { scope: 'host' | 'caller'; reason: 'storage_bytes' | 'retained_files' } | undefined {- const usage = usageFor(records)+ const usage = this.usage(excluded)// Prove caller admission before considering eviction of another caller.- if ((usage.callerBytes[callerIdentity] ?? 0) + sizeBytes > GFS_FILE_LIMITS.callerStorageBytes)+ if ((usage.callerBytes.get(callerRoot) ?? 0) + sizeBytes > GFS_FILE_LIMITS.callerStorageBytes)return { scope: 'caller', reason: 'storage_bytes' }- if ((usage.callerFiles[callerIdentity] ?? 0) >= GFS_FILE_LIMITS.callerRetainedFiles)+ if ((usage.callerFiles.get(callerRoot) ?? 0) >= GFS_FILE_LIMITS.callerRetainedFiles)return { scope: 'caller', reason: 'retained_files' }if (usage.bytes + sizeBytes > GFS_FILE_LIMITS.storageBytes)return { scope: 'host', reason: 'storage_bytes' }@@ -1067,305 +1169,184 @@ export class GfsDownloadStore {return undefined}- /** Retention is an upper bound; verified, unused completed copies are a cache. */- private async reclaimForAdmission(callerIdentity: string, sizeBytes: number): Promise<void> {- if (!this.quotaDenial(callerIdentity, sizeBytes)) return- const candidates = Object.values(this.ledger.records)- .filter(- record =>- record.state === 'completed' &&- !this.activeIds.has(record.id) &&- !this.hasReceiptOwner(record.id)- )- .sort(- (left, right) =>- Date.parse(left.createdAt) - Date.parse(right.createdAt) ||- left.id.localeCompare(right.id)- )- const verified: GfsDownloadRecord[] = []- for (const record of candidates) {- try {- await this.verifyRecordContent(record)- verified.push(record)- } catch {- // Corrupt or inaccessible content is not a safe eviction candidate.- }- }- const remaining = new Map(Object.values(this.ledger.records).map(record => [record.id, record]))- const plan: GfsDownloadRecord[] = []+ /**+ * Completed, unpinned copies are a cache. The whole eviction plan is computed+ * before anything is deleted: adopted copies first, so files planted in one+ * directory can never cost another caller a copy this process published,+ * then published copies least recently used first. A caller denial evicts+ * only copies in that caller's directory. With no feasible plan nothing is+ * deleted and the admission fails with the quota code; nothing is retained,+ * so the next admission plans again. Candidates are not hashed: a corrupt+ * copy is as good an eviction candidate as a sound one.+ */+ private async reclaimForAdmission(callerRoot: string, sizeBytes: number): Promise<void> {+ if (!this.quotaDenial(callerRoot, sizeBytes)) return+ const candidates = [...this.entries.values()]+ .filter(entry => !this.isPinned(entry.id))+ .sort(evictionOrder)+ const plan = new Set<string>()for (;;) {- const denial = this.quotaDenial(callerIdentity, sizeBytes, remaining.values())+ const denial = this.quotaDenial(callerRoot, sizeBytes, plan)if (!denial) break- const next = verified.find(- record =>- remaining.has(record.id) &&- (denial.scope === 'host' || record.callerIdentity === callerIdentity)+ const next = candidates.find(+ entry => !plan.has(entry.id) && (denial.scope === 'host' || entry.callerRoot === callerRoot))- // No feasible complete plan means no destructive cache-pressure effects.if (!next) return- remaining.delete(next.id)- plan.push(next)+ plan.add(next.id)}- await this.assertPhysicalCapacity(sizeBytes)- for (const record of plan) {- if (!(await this.removeRecordDirectory(record))) continue- await this.releaseRecordCharge(record)+ for (const id of plan) {+ const entry = this.entries.get(id)+ if (entry) await this.removeEntry(entry, 'expired_removed', false)}}- private async releaseRecordCharge(record: GfsDownloadRecord): Promise<void> {- const previousOwners = this.ledger.retentionOwners- this.ledger.retentionOwners = { ...previousOwners }- this.forgetReceiptRecord(record.id)- delete this.ledger.records[record.id]- try {- await this.persist()- } catch (error) {- this.ledger.records[record.id] = record- this.ledger.retentionOwners = previousOwners- throw error- }+ /** Removes an indexed entry's directory and forgets it. */+ private async removeEntry(+ entry: Entry,+ outcome: 'incomplete_removed' | 'expired_removed',+ count = true+ ): Promise<void> {+ this.forget(entry.id)+ await this.removeDirectory(entry.directory, count ? outcome : undefined)}- private async removeRecordDirectory(record: GfsDownloadRecord): Promise<boolean> {- await this.assertWriterOwnership()- const directory = path.join(this.hostRoot, record.directory)+ /**+ * `fs.rm` does not follow the final component, but it resolves every parent+ * component, so a caller directory or `.gfs-downloads` replaced by a symlink+ * after indexing would point the removal outside the Host root. The parent+ * must therefore be its own real path inside the Host root, and the+ * directory must be gone afterwards. A refusal or a failure is logged with+ * its code and counted; the next sweep retries what is still listed.+ */+ private async removeDirectory(+ directory: string,+ outcome: 'incomplete_removed' | 'expired_removed' | undefined+ ): Promise<boolean> {try {- await this.verifyManagedDirectory(record)- await fs.rm(directory, { recursive: true, force: true })- // A successful rm alone is not proof that a racing replacement is absent.- await fs.lstat(directory)- return false+ await this.removeVerified(directory)} catch (error) {- return (error as NodeJS.ErrnoException).code === 'ENOENT'+ recordGfsDownloadExpiry('remove_failed')+ logger.warn(+ { component: GFS_DOWNLOAD_STORE_LOG_COMPONENT, code: errorCode(error) },+ 'GFS download store could not remove a download directory; the next sweep retries it'+ )+ return false}+ if (outcome) recordGfsDownloadExpiry(outcome)+ return true}- private async verifyManagedDirectory(record: GfsDownloadRecord): Promise<void> {- const directory = path.join(this.hostRoot, record.directory)- if (!isWithinDirectory(directory, this.hostRoot))- throw new GfsDownloadStoreError('workspace_unavailable')- if (- (await fs.realpath(path.dirname(path.dirname(directory)))) !==- path.dirname(path.dirname(directory))- )- throw new GfsDownloadStoreError('workspace_unavailable')- await verifyPrivateStoreDirectory(path.dirname(directory))- await verifyPrivateStoreDirectory(directory)- }-- private async openRecordContent(record: GfsDownloadRecord): Promise<fs.FileHandle> {- await this.verifyManagedDirectory(record)- const handle = await openPrivateStoreObject(- path.join(this.hostRoot, record.hostPath),- 'file',- constants.O_RDONLY,- false- )+ /**+ * Node has no unlinkat/renameat, so the window between a path check and a+ * path-based removal cannot be closed, only narrowed. The entry is first+ * renamed to a store-private name inside its verified parent; the parent is+ * then verified again, and only that private name is removed. When the+ * parent moved in between, the rename is undone and the removal refused,+ * so whatever the swapped path led to keeps its name and content.+ */+ private async removeVerified(directory: string): Promise<void> {+ await this.assertRemovable(directory)+ const trash = path.join(path.dirname(directory), `${TRASH_PREFIX}${randomUUID()}`)try {- const info = await handle.stat()- if (info.size !== record.sizeBytes) throw new GfsDownloadStoreError('download_missing')- if ((info.mode & 0o7777) !== 0o600) {- if (!record.sha256 || (await sha256FileHandle(handle)) !== record.sha256)- throw new GfsDownloadStoreError('download_missing')- await handle.chmod(0o600)- }- return handle+ await fs.rename(directory, trash)} catch (error) {- await handle.close()- throw error+ if (errorCode(error) !== 'ENOENT') throw error+ await assertAbsent(directory)+ return}- }-- private async verifyRecordContent(record: GfsDownloadRecord): Promise<void> {- const handle = await this.openRecordContent(record)try {- if (!record.sha256 || (await sha256FileHandle(handle)) !== record.sha256)- throw new GfsDownloadStoreError('download_missing')- } finally {- await handle.close()+ await this.assertRemovable(trash)+ } catch (error) {+ await fs.rename(trash, directory)+ throw error}+ await fs.rm(trash, { recursive: true, force: true })+ await assertAbsent(trash)}- /**- * #1019: shell_exec no longer holds processing leases, so no lease in a- * ledger written by an earlier build protects an executor of this boot. A- * lease left by a crashed Host would otherwise fence the store forever. The- * field is removed durably before reconciliation. The confirmed warning and- * the counter are emitted only after that removal is persisted. A failed- * persist restores the in-memory map and initialize rejects, but the ledger- * on disk is not necessarily untouched: `persist` can fail after the rename- * (the directory sync), when the lease-free ledger is already the visible- * file and no later boot will see the leases again. That outcome is logged- * as unknown and never counted, because the counter counts confirmed- * discards only.- */- private async discardLegacyProcessingLeases(): Promise<void> {- const legacy = this.ledger.processingLeases- if (legacy === undefined) return- const discarded = Object.keys(legacy).length- delete this.ledger.processingLeases- // An empty legacy map is dropped by the final initialize persist.- if (discarded === 0) return+ /** The parent of a directory about to be removed is real and inside the Host root. */+ private async assertRemovable(directory: string): Promise<void> {+ const parent = path.dirname(directory)+ if (!isWithinDirectory(parent, this.hostRoot))+ throw new GfsDownloadStoreError('workspace_unavailable')+ let real: stringtry {- await this.persist()+ real = await fs.realpath(parent)} catch (error) {- this.ledger.processingLeases = legacy- logger.warn(- {- component: GFS_DOWNLOAD_STORE_LOG_COMPONENT,- legacyProcessingLeases: discarded,- outcome: 'unknown',- },- `GFS download store could not confirm the discard of ${discarded} legacy processing lease(s) at initialize; the discard may already be visible on disk because the persist can fail after the ledger rename`- )+ // No parent, nothing to remove: `fs.rm` with `force` is a no-op.+ if (errorCode(error) === 'ENOENT') returnthrow error}- logger.warn(- { component: GFS_DOWNLOAD_STORE_LOG_COMPONENT, discarded },- `GFS download store discarded ${discarded} legacy processing lease(s) at initialize`- )- recordGfsLegacyProcessingLeasesDiscarded(discarded)+ if (real !== parent) throw new GfsDownloadStoreError('workspace_unavailable')}- /**- * Quarantined records stay charged to quota (`usageFor`); this store never- * reuses or deletes them. Called once per initialize, after reconcile and- * the final persist, so the count includes records this boot quarantined.- * The gauge carries the current count, so repeated boots never add the same- * backlog twice.- */- private reportQuarantine(): void {- const quarantined = Object.values(this.ledger.records).filter(- record => record.state === 'quarantined'- ).length- setGfsQuarantinedRecords(quarantined)- if (quarantined === 0) return+ private reportSweepFailure(error: unknown): void {+ recordGfsDownloadExpiry('sweep_failed')logger.warn(- { component: GFS_DOWNLOAD_STORE_LOG_COMPONENT, quarantined },- `GFS download store holds ${quarantined} quarantined record(s) charged to quota. Operator recovery reclassifies only copies whose content still matches their recorded hash; any other quarantined copy stays charged, and the operator recovery tool cannot release it`+ { component: GFS_DOWNLOAD_STORE_LOG_COMPONENT, code: errorCode(error) },+ 'GFS download store could not list a download directory; the next sweep retries it')}- private async reconcile(): Promise<void> {- for (const record of Object.values(this.ledger.records)) {- // Kernel ownership recovery proves only the previous Host writer exited.- // Unfinished/uncertain transfers stay charged. A completed copy is reused- // only after its content re-verifies: a shell command can have altered it- // (#1019 accepted risk), and an altered copy is quarantined.- if (record.state !== 'completed') {- record.state = 'quarantined'- continue- }- try {- await this.verifyRecordContent(record)- } catch {- record.state = 'quarantined'- }+ private receiptFor(entry: Entry, source: GfsImageSource): GfsDownloadReceipt {+ return {+ id: entry.id,+ source,+ path: receiptPath(entry.id),+ sizeBytes: entry.sizeBytes,+ sha256: entry.sha256,+ expiresAt: entry.expiresAt,}}- private async persist(publication?: {- signal?: AbortSignal- deadlineMs?: number- }): Promise<void> {- const temporary = `${this.ledgerPath}.tmp-${randomUUID()}`- try {- await this.assertWriterOwnership()- this.assertPublicationOpen(publication)- const handle = await fs.open(- temporary,- constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL,- 0o600- )- try {- await handle.writeFile(JSON.stringify(this.ledger), 'utf8')- await handle.sync()- } finally {- await handle.close()- }- this.assertPublicationOpen(publication)- await fs.rename(temporary, this.ledgerPath)- await syncDirectory(this.storeRoot)- this.assertPublicationOpen(publication)- } catch (error) {- if (error instanceof GfsDownloadStoreError && error.code === 'publication_cancelled') {- try {- await fs.rm(temporary, { force: true })- } catch {- this.unsafe = true- throw new GfsDownloadStoreError('storage_write_failed')- }- } else this.unsafe = true- throw error- }+ /** A malformed owner id is refused; pins are per caller, so no id is taken. */+ private assertReceiptOwner(ownerId: string): void {+ if (!validReceiptOwnerId(ownerId)) throw new GfsDownloadStoreError('caller_mismatch')}- private async acquireWriterLease(allowBootstrap: boolean): Promise<void> {- const lease = new GfsStoreWriterLease(this.storeRoot, allowBootstrap)- try {- await lease.acquire()- this.writerLease = lease- // A v2 fence is accepted by inode only and stays on disk unchanged. Its- // stale device is the persistent-disk reattach case; device numbers are- // not secrets.- const accepted = lease.lastAcquire- if (accepted?.fenceSchema === 2 && accepted.storedDevice !== accepted.currentDevice)- logger.info(- {- component: GFS_DOWNLOAD_STORE_LOG_COMPONENT,- storedDevice: accepted.storedDevice,- currentDevice: accepted.currentDevice,- },- 'GFS writer fence v2 accepted with stale device'- )- } catch (error) {- if (error instanceof GfsStoreWriterOwnershipError) {- if (error.transientWriterContention) {- // Contention alone must not turn a lost/corrupt durable journal into- // a retryable state. Read only; the live writer retains all effects.- let handle: fs.FileHandle | undefined- try {- handle = await openPrivateStoreObject(- this.ledgerPath,- 'file',- constants.O_RDONLY,- false- )- parseLedger(await handle.readFile('utf8'))- } catch (readError) {- // The live writer publishes every ledger by renaming a new inode over- // this name, so a name that moved between open and lstat is that- // writer at work, not corruption. The next retry judges the new ledger.- if (!(readError instanceof PrivateStoreNameMovedError))- throw new GfsDownloadStoreError('corrupt_store_ledger')- } finally {- await handle?.close()- }- }- throw new GfsDownloadStoreError(error.reason, error.transientWriterContention, error.detail)- }- throw new GfsDownloadStoreError('workspace_unavailable')+ private pin(ownerId: string, callerIdentity: string, id: string): void {+ const key = pinKey(callerIdentity, ownerId)+ const ids = this.pins.get(key) ?? new Set<string>()+ ids.add(id)+ this.pins.set(key, ids)+ }++ private isPinned(id: string): boolean {+ for (const ids of this.pins.values()) if (ids.has(id)) return true+ return false+ }++ private unpinId(id: string): void {+ for (const [key, ids] of this.pins) {+ ids.delete(id)+ if (ids.size === 0) this.pins.delete(key)}}- private async releaseWriterLease(): Promise<void> {- await this.writerLease?.release()- this.writerLease = undefined+ private forget(id: string): void {+ this.entries.delete(id)+ this.unpinId(id)}- private async assertWriterOwnership(): Promise<void> {- try {- if (!this.writerLease)- throw new GfsStoreWriterOwnershipError('Writer ownership lost', 'ownership_lost')- await this.writerLease.verifyHeld()- } catch (error) {- this.unsafe = true- throw new GfsDownloadStoreError(- 'writer_locked',- false,- error instanceof GfsStoreWriterOwnershipError ? error.detail : undefined- )+ private addActive(transfer: ActiveTransfer): void {+ this.active.set(transfer.id, transfer)+ this.activeByCaller.set(+ transfer.callerIdentity,+ (this.activeByCaller.get(transfer.callerIdentity) ?? 0) + 1+ )+ }++ private releaseActive(id: string): void {+ const transfer = this.active.get(id)+ if (!transfer) return+ this.active.delete(id)+ const current = this.activeByCaller.get(transfer.callerIdentity) ?? 0+ if (current <= 1) this.activeByCaller.delete(transfer.callerIdentity)+ else this.activeByCaller.set(transfer.callerIdentity, current - 1)+ if (this.active.size === 0) {+ const waiters = this.drainWaiters+ this.drainWaiters = []+ for (const resolve of waiters) resolve()}}@@ -1388,21 +1369,6 @@ export class GfsDownloadStore {return real}- private record(id: string): GfsDownloadRecord {- const record = this.ledger.records[id]- if (!record) throw new GfsDownloadStoreError('download_missing')- return record- }-- private releaseActive(record: GfsDownloadRecord): void {- if (!this.activeIds.has(record.id)) return- this.active = Math.max(0, this.active - 1)- this.activeIds.delete(record.id)- const current = this.activeByCaller.get(record.callerIdentity) ?? 0- if (current <= 1) this.activeByCaller.delete(record.callerIdentity)- else this.activeByCaller.set(record.callerIdentity, current - 1)- }-private async serialize<T>(operation: () => Promise<T>): Promise<T> {const previous = this.mutationTaillet unlock!: () => void@@ -1411,8 +1377,6 @@ export class GfsDownloadStore {})await previoustry {- if (!this.writerLease) throw new GfsDownloadStoreError('workspace_unavailable')- await this.assertWriterOwnership()return await operation()} finally {unlock()@@ -1427,17 +1391,19 @@ export class GfsDownloadStore {throw new GfsDownloadStoreError('publication_cancelled')}+ /** Not initialized: workspace_unavailable. Closed: download_busy. */private assertInitialized(): void {+ if (this.closed) throw new GfsDownloadStoreError('download_busy')if (!this.initialized) throw new GfsDownloadStoreError('workspace_unavailable')- if (this.unsafe) throw new GfsDownloadStoreError('storage_write_failed')- try {- this.writerLease?.assertHeld()- } catch (error) {- throw new GfsDownloadStoreError(- 'writer_locked',- false,- error instanceof GfsStoreWriterOwnershipError ? error.detail : undefined- )- }+ }++ private assertReadable(): void {+ this.assertInitialized()+ }++ /** Admission also stops while close() drains. */+ private assertAdmitting(): void {+ this.assertInitialized()+ if (this.closing) throw new GfsDownloadStoreError('download_busy')}}diff --git a/mcp-host/src/internalTools/gfsDownloadStoreAdversarialQuota.test.ts b/mcp-host/src/internalTools/gfsDownloadStoreAdversarialQuota.test.tsdeleted file mode 100644index b92e9d35c..000000000--- a/mcp-host/src/internalTools/gfsDownloadStoreAdversarialQuota.test.ts+++ /dev/null@@ -1,914 +0,0 @@-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'-import { createHash } from 'node:crypto'-import * as fs from 'node:fs/promises'-import { tmpdir } from 'node:os'-import * as path from 'node:path'-import { ShellTool } from '../core/tools/shell'-import { GfsDownloadStore } from './gfsDownloadStore'-import { GFS_FILE_LIMITS } from './gfsFilePolicy'--const { statfsBoundary } = vi.hoisted(() => ({ statfsBoundary: vi.fn() }))-// Physical capacity is a deterministic filesystem boundary for the capacity-// block below. Every other call, and every other test, uses the real statfs.-vi.mock('node:fs/promises', async original => ({- ...(await original<typeof fs>()),- statfs: statfsBoundary,-}))-let nativeFs: typeof fs--/**- * Adversarial quota/reuse/rollback regression probes.- *- * These are mutation-sensitive on purpose: each block fails when its guard is- * removed from gfsDownloadStore.ts. Pressure eviction is expected, so every- * denial assertion keeps its targets protected with an explicit receipt owner;- * a shell run never protects a copy (#1019). Positive blocks assert the earliest-created- * eligible copy is the one reclaimed.- */--interface ProbeSource {- kind: 'gfs'- drive: string- resourceId: string- gfsUri: string- name: string- version: number-}--function sourceFor(index: number, version: number): ProbeSource {- const resourceId = index.toString(16).padStart(32, '0')- return {- kind: 'gfs',- drive: 'main',- resourceId,- gfsUri: `gfs://main/${resourceId}`,- name: `fixture-${index}.bin`,- version,- }-}--function future(ms = 60_000): string {- return new Date(Date.now() + ms).toISOString()-}--const CALLER = 'caller-a'--/**- * Timeout for tests that publish the full default host retained-file cap (64- * records). Each publication is durable on purpose: about 5.4 fsyncs and 6.3- * writer-ownership verifications per record, constant per record (no growth- * with ledger size). Measured on the development host for 64 one-byte- * publications: 3.2-8.9 s at load average 27-38, worst 13.2 s at load 37;- * fsync alone is 46-54% of it. In the full suite with 7 extra busy processes- * (load average 37-68) these tests took 11.3 s and 13.4 s. The default 5 s- * timeout cannot hold that work under load, and fewer records would no longer- * reach the default cap.- */-const DEFAULT_CAP_PUBLICATION_TIMEOUT_MS = 30_000--let hostRoot: string-let callerRoot: string-let store: GfsDownloadStore--async function callerDirectory(host: string, caller: string): Promise<string> {- const root = path.join(host, 'users', caller)- await fs.mkdir(root, { recursive: true, mode: 0o700 })- return root-}--async function completedCopy(- target: GfsDownloadStore,- root: string,- caller: string,- index: number,- version: number,- sizeBytes: number,- retentionOwnerId?: string-) {- const bytes = Buffer.alloc(sizeBytes, index % 251)- const transfer = await target.createTransfer({- callerIdentity: caller,- callerWorkspacePath: root,- source: sourceFor(index, version),- sizeBytes,- expiresAt: future(),- ...(retentionOwnerId === undefined ? {} : { retentionOwnerId }),- })- await fs.writeFile(path.join(root, transfer.partialPath), bytes)- return target.publish(transfer.id, caller, createHash('sha256').update(bytes).digest('hex'))-}--async function readLedger(host: string): Promise<{- records: Record<string, { id: string; state: string; sizeBytes: number }>- retentionOwners?: Record<string, { ownerId: string; callerIdentity: string; recordIds: string[] }>-}> {- return JSON.parse(- await fs.readFile(path.join(host, '.gfs-download-store', 'ledger-v1.json'), 'utf8')- )-}--async function forceAgeOrder(target: GfsDownloadStore, ids: string[]): Promise<void> {- const base = Date.now() - 60_000- for (const [index, id] of ids.entries()) {- target.debugRecord(id)!.createdAt = new Date(base + index).toISOString()- }- await target.debugPersist()-}--async function loadLimitedStore(env: Record<string, string>) {- const saved = { ...process.env }- Object.assign(process.env, env)- vi.resetModules()- const storeModule = await import('./gfsDownloadStore')- const policyModule = await import('./gfsFilePolicy')- for (const key of Object.keys(process.env)) if (!(key in saved)) delete process.env[key]- for (const [key, value] of Object.entries(saved)) {- if (value === undefined) delete process.env[key]- else process.env[key] = value- }- return { Store: storeModule.GfsDownloadStore, limits: policyModule.GFS_FILE_LIMITS }-}--/** Host 100 / caller 50 / max 20: the boundary the feasibility plan must respect. */-async function withLimitedStore(- run: (limited: GfsDownloadStore, host: string) => Promise<void>-): Promise<void> {- const { Store, limits } = await loadLimitedStore({- MCP_HOST_GFS_MAX_FILE_BYTES: '20',- MCP_HOST_GFS_DOWNLOAD_STORAGE_BYTES: '100',- MCP_HOST_GFS_CALLER_DOWNLOAD_STORAGE_BYTES: '50',- })- expect(limits).toMatchObject({ maxFileBytes: 20, storageBytes: 100, callerStorageBytes: 50 })- const host = await fs.mkdtemp(path.join(tmpdir(), 'gfs-adversarial-limits-'))- const limited = new Store(host)- await limited.initialize()- try {- await run(limited, host)- } finally {- await limited.close(0).catch(() => undefined)- await fs.rm(host, { recursive: true, force: true })- }-}--/** caller-a: pinned 20+20+10. caller-b: unpinned 5x10. Host at 100/100. */-async function seedCrossCallerPressure(- target: GfsDownloadStore,- host: string,- pinnedOwner: string-): Promise<{ pinned: string[]; unpinned: string[]; aRoot: string; bRoot: string }> {- const aRoot = await callerDirectory(host, 'caller-a')- const bRoot = await callerDirectory(host, 'caller-b')- const pinned: string[] = []- const unpinned: string[] = []- let index = 0- for (const size of [20, 20, 10]) {- index += 1- pinned.push((await completedCopy(target, aRoot, 'caller-a', index, 1, size, pinnedOwner)).id)- }- for (let file = 0; file < 5; file += 1) {- index += 1- unpinned.push((await completedCopy(target, bRoot, 'caller-b', index, 1, 10)).id)- }- return { pinned, unpinned, aRoot, bRoot }-}--beforeEach(async () => {- nativeFs = await vi.importActual<typeof fs>('node:fs/promises')- statfsBoundary.mockReset()- statfsBoundary.mockImplementation(nativeFs.statfs)- hostRoot = await fs.mkdtemp(path.join(tmpdir(), 'gfs-adversarial-quota-'))- callerRoot = await callerDirectory(hostRoot, CALLER)- store = new GfsDownloadStore(hostRoot)- await store.initialize()-})--afterEach(async () => {- await store.close(0).catch(() => undefined)- await fs.rm(hostRoot, { recursive: true, force: true })-})--describe('GFS download store adversarial quota', () => {- it('evicts the earliest-created eligible copy under caller pressure and admits', async () => {- const size = GFS_FILE_LIMITS.inlineTextBytes + 1- const receipts = []- for (let index = 1; index <= GFS_FILE_LIMITS.callerRetainedFiles; index += 1)- receipts.push(await completedCopy(store, callerRoot, CALLER, index, 1, size))- const ids = receipts.map(receipt => receipt.id)- await forceAgeOrder(store, ids)-- const next = await store.createTransfer({- callerIdentity: CALLER,- callerWorkspacePath: callerRoot,- source: sourceFor(90, 1),- sizeBytes: size,- expiresAt: future(),- })-- expect(store.debugRecord(ids[0])).toBeUndefined()- for (const id of ids.slice(1))- expect(store.debugRecord(id)).toMatchObject({ state: 'completed' })- expect(store.debugRecord(next.id)).toMatchObject({ state: 'transferring' })- expect(store.debugUsage()).toMatchObject({- files: GFS_FILE_LIMITS.callerRetainedFiles,- callerFiles: { [CALLER]: GFS_FILE_LIMITS.callerRetainedFiles },- })- await expect(- fs.stat(path.join(callerRoot, path.dirname(receipts[0].path)))- ).rejects.toMatchObject({ code: 'ENOENT' })- await store.fail(next.id, CALLER)- })-- it('keeps a protected oldest copy and evicts the next eligible copy', async () => {- const size = GFS_FILE_LIMITS.inlineTextBytes + 1- const receipts = []- for (let index = 1; index <= GFS_FILE_LIMITS.callerRetainedFiles; index += 1)- receipts.push(- await completedCopy(- store,- callerRoot,- CALLER,- index,- 1,- size,- index === 1 ? 'oldest-owner' : undefined- )- )- const ids = receipts.map(receipt => receipt.id)- await forceAgeOrder(store, ids)-- const next = await store.createTransfer({- callerIdentity: CALLER,- callerWorkspacePath: callerRoot,- source: sourceFor(91, 1),- sizeBytes: size,- expiresAt: future(),- })-- expect(store.debugRecord(ids[0])).toMatchObject({ state: 'completed' })- expect(store.debugRecord(ids[1])).toBeUndefined()- for (const id of ids.slice(2))- expect(store.debugRecord(id)).toMatchObject({ state: 'completed' })- expect(store.debugUsage()).toMatchObject({ files: GFS_FILE_LIMITS.callerRetainedFiles })- await store.releaseReceiptOwner('oldest-owner', CALLER)- await store.fail(next.id, CALLER)- })-- it('denies admission when the host aggregate byte charge cannot be evicted', async () => {- const receipt = await completedCopy(store, callerRoot, CALLER, 1, 1, 8, 'byte-owner')- store.debugRecord(receipt.id)!.sizeBytes = GFS_FILE_LIMITS.storageBytes - 1024- await store.debugPersist()-- // The requesting caller must have zero charges so the caller-first quota- // check cannot mask the host aggregate guard.- const otherRoot = await callerDirectory(hostRoot, 'caller-b')- await expect(- store.createTransfer({- callerIdentity: 'caller-b',- callerWorkspacePath: otherRoot,- source: sourceFor(2, 1),- sizeBytes: 4096,- expiresAt: future(),- })- ).rejects.toMatchObject({ code: 'host_quota_exceeded' })- expect(store.debugRecord(receipt.id)).toMatchObject({ state: 'completed' })- expect(store.debugUsage()).toMatchObject({ files: 1, callerFiles: { [CALLER]: 1 } })- expect(Object.keys(store.debugUsage().callerFiles)).toEqual([CALLER])- await store.releaseReceiptOwner('byte-owner', CALLER)- })-- it(- 'denies the 65th pinned record at the host retained-file cap',- async () => {- const callers: string[] = []- for (let callerIndex = 0; callerIndex < 8; callerIndex += 1) {- const caller = `caller-${callerIndex}`- const root = await callerDirectory(hostRoot, caller)- callers.push(caller)- for (let file = 0; file < GFS_FILE_LIMITS.callerRetainedFiles; file += 1) {- await completedCopy(store, root, caller, callerIndex * 10 + file, 1, 1, `${caller}-owner`)- }- }- expect(store.debugUsage()).toMatchObject({ files: 64 })-- const freshRoot = await callerDirectory(hostRoot, 'caller-z')- await expect(- store.createTransfer({- callerIdentity: 'caller-z',- callerWorkspacePath: freshRoot,- source: sourceFor(999, 1),- sizeBytes: 1,- expiresAt: future(),- })- ).rejects.toMatchObject({ code: 'host_quota_exceeded' })- expect(store.debugUsage()).toMatchObject({ files: 64 })- for (const caller of callers) await store.releaseReceiptOwner(`${caller}-owner`, caller)- },- DEFAULT_CAP_PUBLICATION_TIMEOUT_MS- )-- it('rolls back charge, owner pins, and active slots when mkdir fails with proven absence', async () => {- await fs.chmod(callerRoot, 0o500)- try {- await expect(- store.createTransfer({- callerIdentity: CALLER,- callerWorkspacePath: callerRoot,- source: sourceFor(1, 1),- sizeBytes: 16,- expiresAt: future(),- retentionOwnerId: 'rollback-owner',- })- ).rejects.toMatchObject({ code: 'storage_write_failed' })- } finally {- await fs.chmod(callerRoot, 0o700)- }-- expect(store.debugUsage()).toEqual({ bytes: 0, files: 0, callerBytes: {}, callerFiles: {} })- const ledger = await readLedger(hostRoot)- expect(ledger.records).toEqual({})- expect(ledger.retentionOwners ?? {}).toEqual({})- await expect(fs.stat(path.join(callerRoot, '.gfs-downloads'))).rejects.toMatchObject({- code: 'ENOENT',- })-- const retry = await store.createTransfer({- callerIdentity: CALLER,- callerWorkspacePath: callerRoot,- source: sourceFor(2, 1),- sizeBytes: 16,- expiresAt: future(),- })- expect(store.debugRecord(retry.id)).toMatchObject({ state: 'transferring' })- await store.fail(retry.id, CALLER)- })-- it('retains the charged record and its owner pin when absence is ambiguous', async () => {- const cacheRoot = path.join(callerRoot, '.gfs-downloads')- await fs.mkdir(cacheRoot, { mode: 0o700 })- await fs.chmod(cacheRoot, 0o777)-- await expect(- store.createTransfer({- callerIdentity: CALLER,- callerWorkspacePath: callerRoot,- source: sourceFor(1, 1),- sizeBytes: 16,- expiresAt: future(),- retentionOwnerId: 'ambiguous-owner',- })- ).rejects.toMatchObject({ code: 'storage_write_failed' })-- const ledger = await readLedger(hostRoot)- const records = Object.values(ledger.records)- expect(records).toHaveLength(1)- expect(records[0]).toMatchObject({ state: 'cleanup_failed', sizeBytes: 16 })- expect(ledger.retentionOwners?.['ambiguous-owner']?.recordIds).toEqual([records[0].id])- expect(store.debugUsage()).toMatchObject({ bytes: 16, files: 1, callerFiles: { [CALLER]: 1 } })-- // Active slots must be released even though the charge stays reserved.- const secondRoot = await callerDirectory(hostRoot, 'caller-b')- const thirdRoot = await callerDirectory(hostRoot, 'caller-c')- const second = await store.createTransfer({- callerIdentity: 'caller-b',- callerWorkspacePath: secondRoot,- source: sourceFor(11, 1),- sizeBytes: 16,- expiresAt: future(),- })- const third = await store.createTransfer({- callerIdentity: 'caller-c',- callerWorkspacePath: thirdRoot,- source: sourceFor(12, 1),- sizeBytes: 16,- expiresAt: future(),- })- await store.fail(second.id, 'caller-b')- await store.fail(third.id, 'caller-c')- await store.releaseReceiptOwner('ambiguous-owner', CALLER)- })-- it('reuses only the exact version and size, and the reuse-time pin protects the copy', async () => {- const receipt = await completedCopy(store, callerRoot, CALLER, 1, 7, 4096)- await expect(- store.reusableReceipt(CALLER, sourceFor(1, 7), 4096, { retentionOwnerId: 'reuse-owner' })- ).resolves.toMatchObject({ id: receipt.id, sizeBytes: 4096, source: sourceFor(1, 7) })- await expect(store.reusableReceipt(CALLER, sourceFor(1, 8), 4096)).resolves.toBeUndefined()- await expect(store.reusableReceipt(CALLER, sourceFor(1, 7), 4097)).resolves.toBeUndefined()-- for (let index = 2; index <= GFS_FILE_LIMITS.callerRetainedFiles; index += 1)- await completedCopy(store, callerRoot, CALLER, index, 1, 4096, 'filler-owner')- await expect(- store.createTransfer({- callerIdentity: CALLER,- callerWorkspacePath: callerRoot,- source: sourceFor(50, 1),- sizeBytes: 4096,- expiresAt: future(),- })- ).rejects.toMatchObject({ code: 'caller_quota_exceeded' })- expect(store.debugRecord(receipt.id)).toMatchObject({ state: 'completed' })- await store.releaseReceiptOwner('reuse-owner', CALLER)- await store.releaseReceiptOwner('filler-owner', CALLER)- })-- // Store behaviour only: this shell has no store reference, so the test shows- // that eviction is unaffected by a shell run that read the copy. Decoupling of- // the shell from the store is proven by the TaskExecutor-level X3-TE test.- it('evicts a copy a shell has just read: eviction is unaffected by the shell run (#1019)', async () => {- const size = GFS_FILE_LIMITS.inlineTextBytes + 1- const receipts = []- for (let index = 1; index <= GFS_FILE_LIMITS.callerRetainedFiles; index += 1)- receipts.push(await completedCopy(store, callerRoot, CALLER, index, 1, size))- const ids = receipts.map(receipt => receipt.id)- await forceAgeOrder(store, ids)-- const shell = new ShellTool(callerRoot, 5_000, ['PATH'], () => ({}), undefined, true)- const read = await shell.execute({- command: `wc -c < ${JSON.stringify(receipts[0]!.path)}`,- })- expect(read.is_error).toBe(false)- expect(read.content).toMatch(new RegExp(`\\b${size}\\b`))-- const next = await store.createTransfer({- callerIdentity: CALLER,- callerWorkspacePath: callerRoot,- source: sourceFor(92, 1),- sizeBytes: size,- expiresAt: future(),- })- expect(store.debugRecord(ids[0]!)).toBeUndefined()- for (const id of ids.slice(1))- expect(store.debugRecord(id)).toMatchObject({ state: 'completed' })- expect(store.debugUsage()).toMatchObject({ files: GFS_FILE_LIMITS.callerRetainedFiles })- await store.fail(next.id, CALLER)- })-- it('releases a receipt owner only for the owning caller and then allows eviction', async () => {- const size = GFS_FILE_LIMITS.inlineTextBytes + 1- for (let index = 1; index <= GFS_FILE_LIMITS.callerRetainedFiles; index += 1)- await completedCopy(store, callerRoot, CALLER, index, 1, size, 'release-owner')-- await expect(store.releaseReceiptOwner('release-owner', 'caller-b')).rejects.toMatchObject({- code: 'caller_mismatch',- })- await expect(store.releaseReceiptOwner('missing-owner', CALLER)).resolves.toBeUndefined()- const pressure = {- callerIdentity: CALLER,- callerWorkspacePath: callerRoot,- source: sourceFor(93, 1),- sizeBytes: size,- expiresAt: future(),- }- await expect(store.createTransfer(pressure)).rejects.toMatchObject({- code: 'caller_quota_exceeded',- })-- await store.releaseReceiptOwner('release-owner', CALLER)- const next = await store.createTransfer(pressure)- expect(store.debugUsage()).toMatchObject({ files: GFS_FILE_LIMITS.callerRetainedFiles })- await store.fail(next.id, CALLER)- })-- it('discards inherited legacy leases and adopts a verified inherited pin only after revalidation', async () => {- const receipt = await completedCopy(store, callerRoot, CALLER, 1, 1, 7)- await store.close()-- const ledgerPath = path.join(hostRoot, '.gfs-download-store', 'ledger-v1.json')- const readLedger = async () => JSON.parse(await fs.readFile(ledgerPath, 'utf8'))- const writeLedger = async (value: unknown) => fs.writeFile(ledgerPath, JSON.stringify(value))- const foreignSession = '00000000-0000-4000-8000-000000000000'-- // Phase 1: a legacy PROCESSING LEASE written before #1019 that protected a- // copy. It is discarded at initialize; the copy re-verifies and stays usable.- let ledger = await readLedger()- ledger.processingLeases = {- '11111111-1111-4111-8111-111111111111': {- leaseId: '11111111-1111-4111-8111-111111111111',- callerIdentity: CALLER,- recordIds: [receipt.id],- acquiredAt: new Date(Date.now() - 60_000).toISOString(),- expiresAt: new Date(Date.now() + GFS_FILE_LIMITS.retentionMs).toISOString(),- writerSessionId: foreignSession,- },- }- await writeLedger(ledger)-- let reopened = new GfsDownloadStore(hostRoot)- await reopened.initialize()- expect(reopened.isAvailable()).toBe(true)- expect(reopened.debugRecord(receipt.id)).toMatchObject({ state: 'completed' })- expect(reopened.debugUsage()).toMatchObject({ bytes: 7, files: 1 })- expect(await readLedger()).not.toHaveProperty('processingLeases')- await expect(reopened.reusableReceipt(CALLER, sourceFor(1, 1), 7)).resolves.toMatchObject({- id: receipt.id,- })- const admitted = await reopened.createTransfer({- callerIdentity: CALLER,- callerWorkspacePath: callerRoot,- source: sourceFor(2, 1),- sizeBytes: 7,- expiresAt: future(),- })- await reopened.fail(admitted.id, CALLER)- await reopened.close()-- // Phase 2: an empty inherited lease, the shape that fenced the Host forever- // before #1019, is discarded the same way.- ledger = await readLedger()- ledger.processingLeases = {- '22222222-2222-4222-8222-222222222222': {- leaseId: '22222222-2222-4222-8222-222222222222',- callerIdentity: CALLER,- recordIds: [],- acquiredAt: new Date(Date.now() - 60_000).toISOString(),- expiresAt: new Date(Date.now() + GFS_FILE_LIMITS.retentionMs).toISOString(),- writerSessionId: foreignSession,- },- }- await writeLedger(ledger)- reopened = new GfsDownloadStore(hostRoot)- await reopened.initialize()- expect(reopened.isAvailable()).toBe(true)- expect(reopened.debugRecord(receipt.id)).toMatchObject({ state: 'completed' })- expect(await readLedger()).not.toHaveProperty('processingLeases')- await reopened.close()-- // Phase 3: receipt-only inherited pins are not executors. Integrity-checked- // copies stay completed and protective, and a same-caller reuse may adopt- // the exact owner after version/size/hash validation; other pins survive.- ledger = await readLedger()- ledger.processingLeases = {}- ledger.records[receipt.id].state = 'completed'- ledger.retentionOwners = {- 'carry-owner': {- ownerId: 'carry-owner',- callerIdentity: CALLER,- writerSessionId: foreignSession,- recordIds: [receipt.id],- },- 'other-owner': {- ownerId: 'other-owner',- callerIdentity: CALLER,- writerSessionId: foreignSession,- recordIds: [receipt.id],- },- }- await writeLedger(ledger)-- reopened = new GfsDownloadStore(hostRoot)- await reopened.initialize()- expect(reopened.isAvailable()).toBe(true)- expect(reopened.debugRecord(receipt.id)).toMatchObject({ state: 'completed' })- expect((await readLedger()).retentionOwners['carry-owner'].writerSessionId).toBe(foreignSession)-- await expect(- reopened.reusableReceipt(CALLER, sourceFor(1, 1), 7, { retentionOwnerId: 'carry-owner' })- ).resolves.toMatchObject({ id: receipt.id })- const adopted = (await readLedger()).retentionOwners- expect(adopted['carry-owner'].writerSessionId).not.toBe(foreignSession)- expect(adopted['other-owner'].writerSessionId).toBe(foreignSession)- expect(adopted['other-owner'].recordIds).toEqual([receipt.id])-- const fillers = []- for (let index = 2; index <= GFS_FILE_LIMITS.callerRetainedFiles; index += 1)- fillers.push(await completedCopy(reopened, callerRoot, CALLER, index, 1, 7, 'filler-owner'))- await forceAgeOrder(reopened, [receipt.id, ...fillers.map(filler => filler.id)])- const pressure = {- callerIdentity: CALLER,- callerWorkspacePath: callerRoot,- source: sourceFor(94, 1),- sizeBytes: 7,- expiresAt: future(),- }- await expect(reopened.createTransfer(pressure)).rejects.toMatchObject({- code: 'caller_quota_exceeded',- })- expect(reopened.debugRecord(receipt.id)).toMatchObject({ state: 'completed' })-- await reopened.releaseReceiptOwner('carry-owner', CALLER)- await reopened.releaseReceiptOwner('other-owner', CALLER)- await reopened.releaseReceiptOwner('filler-owner', CALLER)- const next = await reopened.createTransfer(pressure)- expect(reopened.debugRecord(receipt.id)).toBeUndefined()- await reopened.fail(next.id, CALLER)- await reopened.close()- })-- it('denies a caller at its own limit without evicting another caller copy', async () => {- await withLimitedStore(async (limited, host) => {- const { pinned, unpinned, aRoot } = await seedCrossCallerPressure(limited, host, 'a-owner')- expect(limited.debugUsage()).toMatchObject({ bytes: 100, files: 8 })-- // caller-a needs 50 more than its own budget allows; no eviction plan can- // make it admissible, so caller-b copies must survive untouched.- await expect(- limited.createTransfer({- callerIdentity: 'caller-a',- callerWorkspacePath: aRoot,- source: sourceFor(500, 1),- sizeBytes: 20,- expiresAt: future(),- })- ).rejects.toMatchObject({ code: 'caller_quota_exceeded' })-- for (const id of [...pinned, ...unpinned])- expect(limited.debugRecord(id)).toMatchObject({ state: 'completed' })- expect(limited.debugUsage()).toMatchObject({ bytes: 100, files: 8 })- await limited.releaseReceiptOwner('a-owner', 'caller-a')- })- })-- it('rejects an invalid retention owner before any reclaim or eviction', async () => {- await withLimitedStore(async (limited, host) => {- const { pinned, unpinned, bRoot } = await seedCrossCallerPressure(limited, host, 'a-owner')- const cRoot = await callerDirectory(host, 'caller-c')-- await expect(- limited.createTransfer({- callerIdentity: 'caller-c',- callerWorkspacePath: cRoot,- source: sourceFor(600, 1),- sizeBytes: 20,- expiresAt: future(),- retentionOwnerId: '__proto__',- })- ).rejects.toMatchObject({ code: 'caller_mismatch' })-- for (const id of [...pinned, ...unpinned])- expect(limited.debugRecord(id)).toMatchObject({ state: 'completed' })- expect(limited.debugUsage()).toMatchObject({ bytes: 100, files: 8 })- const survivor = limited.debugRecord(unpinned[0])!- await expect(fs.stat(path.join(bRoot, path.dirname(survivor.path)))).resolves.toBeTruthy()- await limited.releaseReceiptOwner('a-owner', 'caller-a')- })- })-- it('evicts the earliest eligible cross-caller copy when the host plan is feasible', async () => {- await withLimitedStore(async (limited, host) => {- const receipts = []- for (let callerIndex = 0; callerIndex < 5; callerIndex += 1) {- const caller = `caller-${callerIndex}`- const root = await callerDirectory(host, caller)- receipts.push(await completedCopy(limited, root, caller, 700 + callerIndex, 1, 20))- }- expect(limited.debugUsage()).toMatchObject({ bytes: 100, files: 5 })- await forceAgeOrder(- limited,- receipts.map(receipt => receipt.id)- )-- const freshRoot = await callerDirectory(host, 'caller-new')- const next = await limited.createTransfer({- callerIdentity: 'caller-new',- callerWorkspacePath: freshRoot,- source: sourceFor(800, 1),- sizeBytes: 20,- expiresAt: future(),- })-- expect(limited.debugRecord(receipts[0].id)).toBeUndefined()- for (const receipt of receipts.slice(1))- expect(limited.debugRecord(receipt.id)).toMatchObject({ state: 'completed' })- expect(limited.debugUsage()).toMatchObject({ bytes: 100, files: 5 })- await limited.fail(next.id, 'caller-new')- })- })-})--const MARGIN = 16 * 1024 * 1024-const capacitySource = sourceFor(200, 7)--/** Physical-capacity admission, ported from the deleted lease-capacity suite (#1019). */-describe('GFS download store physical capacity and reclaim', () => {- const capacityStores: GfsDownloadStore[] = []- const capacityRoots: string[] = []-- afterEach(async () => {- vi.restoreAllMocks()- statfsBoundary.mockImplementation(nativeFs.statfs)- for (const target of capacityStores.splice(0))- await target.close(0).catch(async () => {- await (- target as unknown as { writerLease?: { release(): Promise<void> } }- ).writerLease?.release()- })- for (const root of capacityRoots.splice(0))- await nativeFs.rm(root, { recursive: true, force: true })- })-- async function setup(extra: Record<string, string> = {}) {- const { Store } = await loadLimitedStore({- MCP_HOST_GFS_MAX_FILE_BYTES: '20',- MCP_HOST_GFS_DOWNLOAD_STORAGE_BYTES: '100',- MCP_HOST_GFS_CALLER_DOWNLOAD_STORAGE_BYTES: '50',- ...extra,- })- const root = await nativeFs.mkdtemp(path.join(tmpdir(), 'gfs-capacity-'))- capacityRoots.push(root)- const target = new Store(root)- capacityStores.push(target)- await target.initialize()- return { root, store: target }- }-- async function copy(- target: GfsDownloadStore,- root: string,- identity: string,- bytes = 7,- owner?: string- ) {- const transfer = await target.createTransfer({- callerIdentity: identity,- callerWorkspacePath: root,- source: capacitySource,- sizeBytes: bytes,- expiresAt: future(),- retentionOwnerId: owner,- })- const body = Buffer.alloc(bytes, 65)- await nativeFs.writeFile(path.join(root, transfer.partialPath), body)- return target.publish(transfer.id, identity, createHash('sha256').update(body).digest('hex'))- }-- async function capacity(root: string, bytes: number) {- const observed = await nativeFs.statfs(root, { bigint: true })- statfsBoundary.mockResolvedValue({- ...observed,- bsize: 4096n,- bavail: BigInt(Math.floor(bytes / 4096)),- })- }-- it('rejects impossible physical margin before evicting another caller at a logical quota boundary', async () => {- const { root, store: target } = await setup()- const otherRoot = await callerDirectory(root, 'caller-b')- const receipts = []- for (let index = 0; index < 5; index++)- receipts.push(await copy(target, otherRoot, 'caller-b', 10))- const requestRoot = await callerDirectory(root, 'caller-a')- // Add durable, protected charges to make aggregate 100 while requester has room.- for (const identity of ['caller-c', 'caller-d', 'caller-e', 'caller-f', 'caller-g'])- await copy(target, await callerDirectory(root, identity), identity, 10, `${identity}-owner`)- await capacity(root, 0)- await expect(- target.createTransfer({- callerIdentity: 'caller-a',- callerWorkspacePath: requestRoot,- source: capacitySource,- sizeBytes: 20,- expiresAt: future(),- })- ).rejects.toMatchObject({ code: 'host_quota_exceeded' })- expect(target.debugUsage()).toMatchObject({ bytes: 100, files: 10 })- for (const receipt of receipts) expect(target.debugRecord(receipt.id)).toBeDefined()- for (const identity of ['caller-c', 'caller-d', 'caller-e', 'caller-f', 'caller-g'])- await target.releaseReceiptOwner(`${identity}-owner`, identity)- // 10 durable publications measured 3.3 s on a loaded host, inside Vitest's 5 s default.- }, 30_000)-- it(- 'keeps all default-cap small copies when current physical capacity is zero',- async () => {- const { root, store: target } = await setup({- MCP_HOST_GFS_MAX_FILE_BYTES: '1024',- MCP_HOST_GFS_DOWNLOAD_STORAGE_BYTES: String(1024 * 1024),- MCP_HOST_GFS_CALLER_DOWNLOAD_STORAGE_BYTES: String(128 * 1024),- })- const receipts = []- for (let index = 0; index < 8; index++) {- const identity = `caller-${index}`- const directory = await callerDirectory(root, identity)- for (let file = 0; file < 8; file++)- receipts.push(await copy(target, directory, identity, 1))- }- await capacity(root, 0)- await expect(- target.createTransfer({- callerIdentity: 'caller-new',- callerWorkspacePath: await callerDirectory(root, 'caller-new'),- source: capacitySource,- sizeBytes: 1,- expiresAt: future(),- })- ).rejects.toMatchObject({ code: 'host_quota_exceeded' })- expect(target.debugUsage().files).toBe(64)- for (const receipt of receipts) expect(target.debugRecord(receipt.id)).toBeDefined()- },- DEFAULT_CAP_PUBLICATION_TIMEOUT_MS- )-- it('respects pending active reservations before any cache-pressure effect', async () => {- const { root, store: target } = await setup({ MCP_HOST_GFS_CALLER_DOWNLOAD_MAX_FILES: '1' })- const cachedRoot = await callerDirectory(root, 'caller-a')- const receipt = await copy(target, cachedRoot, 'caller-a', 7)- const active = await target.createTransfer({- callerIdentity: 'caller-b',- callerWorkspacePath: await callerDirectory(root, 'caller-b'),- source: capacitySource,- sizeBytes: 7,- expiresAt: future(),- })- await capacity(root, MARGIN + 4096)- await expect(- target.createTransfer({- callerIdentity: 'caller-a',- callerWorkspacePath: cachedRoot,- source: capacitySource,- sizeBytes: 7,- expiresAt: future(),- })- ).rejects.toMatchObject({ code: 'host_quota_exceeded' })- expect(target.debugRecord(receipt.id)).toBeDefined()- await target.fail(active.id, 'caller-b')- })-- it('never credits sparse apparent bytes as available physical capacity', async () => {- const bytes = 16 * 1024 * 1024- const { root, store: target } = await setup({- MCP_HOST_GFS_MAX_FILE_BYTES: String(bytes),- MCP_HOST_GFS_DOWNLOAD_STORAGE_BYTES: String(bytes * 4),- MCP_HOST_GFS_CALLER_DOWNLOAD_STORAGE_BYTES: String(bytes * 2),- MCP_HOST_GFS_CALLER_DOWNLOAD_MAX_FILES: '1',- })- const sparseRoot = await callerDirectory(root, 'caller-a')- const transfer = await target.createTransfer({- callerIdentity: 'caller-a',- callerWorkspacePath: sparseRoot,- source: capacitySource,- sizeBytes: bytes,- expiresAt: future(),- })- const handle = await nativeFs.open(path.join(sparseRoot, transfer.partialPath), 'r+')- await handle.truncate(bytes)- await handle.close()- const sparse = await nativeFs.stat(path.join(sparseRoot, transfer.partialPath))- expect(sparse.blocks * 512).toBeLessThan(sparse.size)- const receipt = await target.publish(- transfer.id,- 'caller-a',- createHash('sha256').update(Buffer.alloc(bytes)).digest('hex')- )- await capacity(root, 0)- await expect(- target.createTransfer({- callerIdentity: 'caller-a',- callerWorkspacePath: sparseRoot,- source: capacitySource,- sizeBytes: 7,- expiresAt: future(),- })- ).rejects.toMatchObject({ code: 'host_quota_exceeded' })- expect(target.debugRecord(receipt.id)).toBeDefined()- expect((await nativeFs.stat(path.join(sparseRoot, receipt.path))).size).toBe(bytes)- })-- it('refuses admission if real capacity changes after a positively settled victim', async () => {- const { root, store: target } = await setup({ MCP_HOST_GFS_CALLER_DOWNLOAD_MAX_FILES: '1' })- const victimRoot = await callerDirectory(root, 'caller-a')- const receipt = await copy(target, victimRoot, 'caller-a', 7)- const directory = path.join(victimRoot, path.dirname(receipt.path))- const observed = await nativeFs.statfs(root, { bigint: true })- statfsBoundary.mockImplementation(async () => {- try {- await nativeFs.lstat(directory)- return observed- } catch (error) {- if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error- return { ...observed, bavail: 0n }- }- })- await expect(- target.createTransfer({- callerIdentity: 'caller-a',- callerWorkspacePath: victimRoot,- source: capacitySource,- sizeBytes: 7,- expiresAt: future(),- })- ).rejects.toMatchObject({ code: 'host_quota_exceeded' })- expect(target.debugUsage().files).toBe(0)- await expect(nativeFs.lstat(directory)).rejects.toMatchObject({ code: 'ENOENT' })- })-- it('reclaims logical quota and admits when real physical capacity is already sufficient', async () => {- const { root, store: target } = await setup({ MCP_HOST_GFS_CALLER_DOWNLOAD_MAX_FILES: '1' })- const reclaimRoot = await callerDirectory(root, 'caller-a')- const receipt = await copy(target, reclaimRoot, 'caller-a', 7)- const before = await nativeFs.statfs(root, { bigint: true })- expect(before.bavail * before.bsize).toBeGreaterThan(BigInt(MARGIN + 4096))- const next = await target.createTransfer({- callerIdentity: 'caller-a',- callerWorkspacePath: reclaimRoot,- source: capacitySource,- sizeBytes: 7,- expiresAt: future(),- })- expect(target.debugRecord(receipt.id)).toBeUndefined()- await expect(- nativeFs.lstat(path.join(reclaimRoot, path.dirname(receipt.path)))- ).rejects.toMatchObject({ code: 'ENOENT' })- expect(target.debugRecord(next.id)).toBeDefined()- await target.fail(next.id, 'caller-a')- })-})diff --git a/mcp-host/src/internalTools/gfsDownloadStoreBoundaries.test.ts b/mcp-host/src/internalTools/gfsDownloadStoreBoundaries.test.tsindex 6bf9f791b..21093ab6c 100644--- a/mcp-host/src/internalTools/gfsDownloadStoreBoundaries.test.ts+++ b/mcp-host/src/internalTools/gfsDownloadStoreBoundaries.test.ts@@ -27,7 +27,7 @@ import {withEnvironment,} from '../__tests__/fixtures/gfsStoreTestKit'import { logger } from '../logger'-import { GfsDownloadStoreError, GfsDownloadStoreFs } from './gfsDownloadStoreFs'+import { GfsDownloadStore, GfsDownloadStoreError } from './gfsDownloadStore'import { GFS_FILE_LIMITS, GFS_HOST_RETAINED_FILES } from './gfsFilePolicy'const { statfsBoundary, renameBoundary, openBoundary, realpathBoundary } = vi.hoisted(() => ({@@ -62,8 +62,8 @@ let nativeFs: typeof fslet hostRoot: stringlet rootA: stringlet rootB: string-let store: GfsDownloadStoreFs-const extraStores: GfsDownloadStoreFs[] = []+let store: GfsDownloadStore+const extraStores: GfsDownloadStore[] = []const outsideRoots: string[] = []function receiptPathOf(id: string): string {@@ -88,11 +88,11 @@ function plantComplete(root: string, identity: string, index: number, bytes: Buf})}-async function limitedStore(env: Record<string, string>): Promise<GfsDownloadStoreFs> {+async function limitedStore(env: Record<string, string>): Promise<GfsDownloadStore> {return withEnvironment(env, async () => {vi.resetModules()- const { GfsDownloadStoreFs: Store } = await import('./gfsDownloadStoreFs')- const opened = new Store(hostRoot) as unknown as GfsDownloadStoreFs+ const { GfsDownloadStore: Store } = await import('./gfsDownloadStore')+ const opened = new Store(hostRoot) as unknown as GfsDownloadStoreextraStores.push(opened)await opened.initialize()return opened@@ -123,7 +123,7 @@ beforeEach(async () => {hostRoot = syncFs.mkdtempSync(path.join(tmpdir(), 'gfs-store-boundaries-'))rootA = callerDirectory(hostRoot, A)rootB = callerDirectory(hostRoot, B)- store = new GfsDownloadStoreFs(hostRoot)+ store = new GfsDownloadStore(hostRoot)await store.initialize()})@@ -566,7 +566,7 @@ describe('GFS download store boundaries: in-process concurrency', () => {it('C4: a sweep requested during publication runs after it and keeps the copy', async () => {const { transfer, bytes } = await startTransfer(store, rootA, A, 353, 12)- let sweep: ReturnType<GfsDownloadStoreFs['cleanupExpired']> | undefined+ let sweep: ReturnType<GfsDownloadStore['cleanupExpired']> | undefinedrenameBoundary.mockImplementation(async (from: string, to: string) => {await nativeFs.rename(from, to)// Between the two renames: meta.json is visible, source is not yet.@@ -696,9 +696,9 @@ function opensUnder(id: string): number {describe('GFS download store boundaries: caller isolation', () => {const reads = {- readManagedFile: (target: GfsDownloadStoreFs, receiptPath: string, caller: string) =>+ readManagedFile: (target: GfsDownloadStore, receiptPath: string, caller: string) =>target.readManagedFile(receiptPath, caller),- readManagedFilePrefix: (target: GfsDownloadStoreFs, receiptPath: string, caller: string) =>+ readManagedFilePrefix: (target: GfsDownloadStore, receiptPath: string, caller: string) =>target.readManagedFilePrefix(receiptPath, caller, 4),} as constdiff --git a/mcp-host/src/internalTools/gfsDownloadStoreFs.test.ts b/mcp-host/src/internalTools/gfsDownloadStoreFs.test.tsdeleted file mode 100644index 5a9fa3e80..000000000--- a/mcp-host/src/internalTools/gfsDownloadStoreFs.test.ts+++ /dev/null@@ -1,811 +0,0 @@-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'-import * as crypto from 'node:crypto'-import * as fs from 'node:fs/promises'-import { tmpdir } from 'node:os'-import * as path from 'node:path'-import { register } from 'prom-client'-import { logger } from '../logger'-import type { GfsImageSource } from '../visualInput/policy'-import { GfsDownloadStoreError, GfsDownloadStoreFs } from './gfsDownloadStoreFs'--const { statfsBoundary, renameBoundary, rmBoundary, lstatBoundary, hashBoundary } = vi.hoisted(- () => ({- statfsBoundary: vi.fn(),- renameBoundary: vi.fn(),- rmBoundary: vi.fn(),- lstatBoundary: vi.fn(),- hashBoundary: vi.fn(),- })-)-// Pass-through boundaries: every test starts with the real implementation and-// overrides one call only where it simulates a filesystem failure or observes-// an order. Test setup and assertions use the actual modules.-vi.mock('node:fs/promises', async original => ({- ...(await original<typeof fs>()),- statfs: statfsBoundary,- rename: renameBoundary,- rm: rmBoundary,- lstat: lstatBoundary,-}))-vi.mock('node:crypto', async original => ({- ...(await original<typeof crypto>()),- createHash: hashBoundary,-}))--let nativeFs: typeof fs-let nativeCrypto: typeof crypto-let hostRoot: string-let callerRoot: string-let store: GfsDownloadStoreFs-const extraStores: GfsDownloadStoreFs[] = []--const CALLER = 'caller-a'--function sourceFor(index: number, version = 1): GfsImageSource {- const resourceId = index.toString(16).padStart(32, '0')- return {- kind: 'gfs',- drive: 'main',- resourceId,- gfsUri: `gfs://main/${resourceId}`,- name: `fixture-${index}.bin`,- version,- }-}--function future(ms = 60 * 60_000): string {- return new Date(Date.now() + ms).toISOString()-}--function digest(bytes: Buffer): string {- return nativeCrypto.createHash('sha256').update(bytes).digest('hex')-}--async function callerDirectory(host: string, caller: string): Promise<string> {- const root = path.join(host, 'users', caller)- await nativeFs.mkdir(root, { recursive: true, mode: 0o700 })- return root-}--function downloadDirectory(root: string, id: string): string {- return path.join(root, '.gfs-downloads', `input-${id}`)-}--async function exists(target: string): Promise<boolean> {- try {- await nativeFs.lstat(target)- return true- } catch (error) {- if ((error as NodeJS.ErrnoException).code === 'ENOENT') return false- throw error- }-}--async function startTransfer(- target: GfsDownloadStoreFs,- root: string,- caller: string,- index: number,- sizeBytes: number,- options: { version?: number; owner?: string } = {}-) {- const bytes = Buffer.alloc(sizeBytes, (index % 251) + 1)- const transfer = await target.createTransfer({- callerIdentity: caller,- callerWorkspacePath: root,- source: sourceFor(index, options.version ?? 1),- sizeBytes,- expiresAt: future(),- ...(options.owner === undefined ? {} : { retentionOwnerId: options.owner }),- })- await nativeFs.writeFile(path.join(root, transfer.partialPath), bytes)- return { transfer, bytes }-}--async function completedCopy(- target: GfsDownloadStoreFs,- root: string,- caller: string,- index: number,- sizeBytes: number,- options: { version?: number; owner?: string } = {}-) {- const { transfer, bytes } = await startTransfer(target, root, caller, index, sizeBytes, options)- const receipt = await target.publish(transfer.id, caller, digest(bytes))- return { receipt, bytes }-}--async function metricValue(name: string, labels: Record<string, string>): Promise<number> {- const metric = register.getSingleMetric(name)- if (metric === undefined) throw new Error(`metric ${name} is not registered`)- const { values } = await metric.get()- return values- .filter(sample => Object.entries(labels).every(([key, value]) => sample.labels[key] === value))- .reduce((sum, sample) => sum + sample.value, 0)-}--const expiryCount = (outcome: string) =>- metricValue('clerum_gfs_download_expiry_total', { outcome })-const quotaCount = (scope: string, reason: string) =>- metricValue('clerum_gfs_download_quota_total', { scope, reason })--async function openStore(host: string): Promise<GfsDownloadStoreFs> {- const opened = new GfsDownloadStoreFs(host)- extraStores.push(opened)- await opened.initialize()- return opened-}--/** Re-imports the store with environment limits; the logger of that copy is not spied. */-async function loadLimitedStore(env: Record<string, string>) {- const saved = { ...process.env }- Object.assign(process.env, env)- try {- vi.resetModules()- const storeModule = await import('./gfsDownloadStoreFs')- const policyModule = await import('./gfsFilePolicy')- return { Store: storeModule.GfsDownloadStoreFs, limits: policyModule.GFS_FILE_LIMITS }- } finally {- for (const key of Object.keys(process.env)) if (!(key in saved)) delete process.env[key]- for (const [key, value] of Object.entries(saved)) {- if (value === undefined) delete process.env[key]- else process.env[key] = value- }- }-}--async function limitedStore(env: Record<string, string>) {- const { Store, limits } = await loadLimitedStore(env)- const limited = new Store(hostRoot)- extraStores.push(limited as unknown as GfsDownloadStoreFs)- await limited.initialize()- return { limited, limits }-}--/** Distinct createdAt values so the oldest-first eviction order is deterministic. */-function tick(): void {- vi.setSystemTime(Date.now() + 1_000)-}--async function writeMeta(directory: string, meta: Record<string, unknown>): Promise<void> {- await nativeFs.writeFile(path.join(directory, 'meta.json'), JSON.stringify(meta), {- mode: 0o600,- })-}--function metaFor(id: string, bytes: Buffer, overrides: Record<string, unknown> = {}) {- const now = Date.now()- return {- schemaVersion: 1,- id,- callerIdentity: CALLER,- source: sourceFor(900),- sizeBytes: bytes.byteLength,- sha256: digest(bytes),- createdAt: new Date(now).toISOString(),- expiresAt: new Date(now + 60 * 60_000).toISOString(),- ...overrides,- }-}--async function handMadeDirectory(root: string): Promise<{ id: string; directory: string }> {- const id = nativeCrypto.randomUUID()- const directory = downloadDirectory(root, id)- await nativeFs.mkdir(directory, { recursive: true, mode: 0o700 })- await nativeFs.chmod(path.dirname(directory), 0o700)- return { id, directory }-}--beforeEach(async () => {- nativeFs = await vi.importActual<typeof fs>('node:fs/promises')- nativeCrypto = await vi.importActual<typeof crypto>('node:crypto')- vi.useFakeTimers({ toFake: ['Date'] })- vi.setSystemTime(new Date('2026-10-08T10:00:00.000Z'))- for (const boundary of [statfsBoundary, renameBoundary, rmBoundary, lstatBoundary, hashBoundary])- boundary.mockReset()- statfsBoundary.mockImplementation(nativeFs.statfs)- renameBoundary.mockImplementation(nativeFs.rename)- rmBoundary.mockImplementation(nativeFs.rm)- lstatBoundary.mockImplementation(nativeFs.lstat)- hashBoundary.mockImplementation((algorithm: string) => nativeCrypto.createHash(algorithm))- hostRoot = await nativeFs.mkdtemp(path.join(tmpdir(), 'gfs-store-fs-'))- callerRoot = await callerDirectory(hostRoot, CALLER)- store = new GfsDownloadStoreFs(hostRoot)- await store.initialize()-})--afterEach(async () => {- vi.restoreAllMocks()- vi.useRealTimers()- for (const opened of extraStores.splice(0)) await opened.close(0)- await store.close(0)- await nativeFs.rm(hostRoot, { recursive: true, force: true })-})--describe('filesystem-backed GFS download store: publication', () => {- it('F1: publish writes meta.json before source and every visible source has a meta.json', async () => {- const { transfer, bytes } = await startTransfer(store, callerRoot, CALLER, 1, 32)- renameBoundary.mockClear()- const receipt = await store.publish(transfer.id, CALLER, digest(bytes))-- const renamedTo = renameBoundary.mock.calls.map(([, to]) => path.basename(String(to)))- // Witness: both renames of the publication happened.- expect(renamedTo).toHaveLength(2)- expect(renamedTo).toEqual(['meta.json', 'source'])- const directory = downloadDirectory(callerRoot, receipt.id)- expect((await nativeFs.readdir(directory)).sort()).toEqual(['meta.json', 'source'])- const meta = JSON.parse(await nativeFs.readFile(path.join(directory, 'meta.json'), 'utf8'))- expect(meta).toMatchObject({- schemaVersion: 1,- id: receipt.id,- callerIdentity: CALLER,- sizeBytes: 32,- sha256: digest(bytes),- })- expect(receipt.path).toBe(`.gfs-downloads/input-${receipt.id}/source`)- })-- it('F2: a cancelled publish leaves an incomplete directory that is not reusable and is swept', async () => {- const { transfer, bytes } = await startTransfer(store, callerRoot, CALLER, 2, 16)- const controller = new AbortController()- renameBoundary.mockImplementation(async (from: string, to: string) => {- await nativeFs.rename(from, to)- // Cancelled after meta.json is visible and before source is.- if (path.basename(to) === 'meta.json') controller.abort()- })- await expect(- store.publish(transfer.id, CALLER, digest(bytes), { signal: controller.signal })- ).rejects.toMatchObject({ code: 'publication_cancelled' })- renameBoundary.mockImplementation(nativeFs.rename)-- const directory = downloadDirectory(callerRoot, transfer.id)- // Witness: the cancelled directory is on disk with meta.json and no source.- expect((await nativeFs.readdir(directory)).sort()).toEqual(['meta.json', 'source.partial'])- await expect(store.reusableReceipt(CALLER, sourceFor(2), 16)).resolves.toBeUndefined()-- // A Host stop leaves the reservation behind; the next start sweeps it.- await store.close(0)- const info = vi.spyOn(logger, 'info')- await openStore(hostRoot)- expect(await exists(directory)).toBe(false)- expect(info).toHaveBeenCalledWith(- expect.objectContaining({ component: 'GfsDownloadStore', removedIncomplete: 1 }),- 'GFS download store initialized'- )- })-- it('F3: a crash between the two renames leaves meta.json and source.partial and the next store removes it', async () => {- const bytes = Buffer.alloc(24, 7)- const { id, directory } = await handMadeDirectory(callerRoot)- await writeMeta(directory, metaFor(id, bytes))- await nativeFs.writeFile(path.join(directory, 'source.partial'), bytes, { mode: 0o600 })- const info = vi.spyOn(logger, 'info')-- await openStore(hostRoot)-- expect(await exists(directory)).toBe(false)- expect(info).toHaveBeenCalledWith(- expect.objectContaining({ removedIncomplete: 1, retainedCompleted: 0 }),- 'GFS download store initialized'- )- })-- it('F4: an EIO while writing meta.json fails that publish only and the next admission succeeds', async () => {- const { transfer, bytes } = await startTransfer(store, callerRoot, CALLER, 4, 16)- renameBoundary.mockImplementationOnce(async () => {- throw Object.assign(new Error('injected EIO'), { code: 'EIO' })- })- await expect(store.publish(transfer.id, CALLER, digest(bytes))).rejects.toMatchObject({- code: 'storage_write_failed',- })- // The producer's cleanup path: the id stayed active so fail() can remove it.- await store.fail(transfer.id, CALLER)- expect(await exists(downloadDirectory(callerRoot, transfer.id))).toBe(false)-- const next = await completedCopy(store, callerRoot, CALLER, 5, 16)- expect(next.receipt.sha256).toBe(digest(next.bytes))- await expect(store.readManagedFile(next.receipt.path, CALLER)).resolves.toEqual(next.bytes)- })-})--describe('filesystem-backed GFS download store: reuse', () => {- it('F5: reuse returns the same id when the content hash matches', async () => {- const { receipt } = await completedCopy(store, callerRoot, CALLER, 6, 40)- const reused = await store.reusableReceipt(CALLER, sourceFor(6), 40)- expect(reused).toMatchObject({ id: receipt.id, sha256: receipt.sha256, path: receipt.path })- })-- it('F6: reuse deletes a directory whose content no longer matches and returns undefined', async () => {- const { receipt } = await completedCopy(store, callerRoot, CALLER, 7, 40)- const directory = downloadDirectory(callerRoot, receipt.id)- await nativeFs.writeFile(path.join(directory, 'source'), Buffer.alloc(40, 0xee))- hashBoundary.mockClear()-- await expect(store.reusableReceipt(CALLER, sourceFor(7), 40)).resolves.toBeUndefined()-- // Witness: the content was hashed exactly once before the verdict.- expect(hashBoundary).toHaveBeenCalledTimes(1)- expect(await exists(directory)).toBe(false)- })-- it('F7: reuse does not match another caller, another version or an expired entry', async () => {- const { receipt } = await completedCopy(store, callerRoot, CALLER, 8, 12)- await expect(store.reusableReceipt('caller-b', sourceFor(8), 12)).resolves.toBeUndefined()- await expect(store.reusableReceipt(CALLER, sourceFor(8, 2), 12)).resolves.toBeUndefined()- // Witness: the same parameters with the right caller do match.- await expect(store.reusableReceipt(CALLER, sourceFor(8), 12)).resolves.toMatchObject({- id: receipt.id,- })- vi.setSystemTime(Date.now() + 2 * 60 * 60_000)- await expect(store.reusableReceipt(CALLER, sourceFor(8), 12)).resolves.toBeUndefined()- })-})--/** The smallest limits the policy accepts with two callers' worth of Host storage. */-const HOST_30_CALLER_15 = {- MCP_HOST_GFS_MAX_FILE_BYTES: '10',- MCP_HOST_GFS_DOWNLOAD_STORAGE_BYTES: '30',- MCP_HOST_GFS_CALLER_DOWNLOAD_STORAGE_BYTES: '15',-}--describe('filesystem-backed GFS download store: quotas and eviction', () => {- it("F8: a caller over quota evicts its own oldest completed downloads, never another caller's", async () => {- const { limited, limits } = await limitedStore({ MCP_HOST_GFS_CALLER_DOWNLOAD_MAX_FILES: '2' })- expect(limits.callerRetainedFiles).toBe(2)- const otherRoot = await callerDirectory(hostRoot, 'caller-b')- const other = await completedCopy(limited, otherRoot, 'caller-b', 10, 8)- tick()- const oldest = await completedCopy(limited, callerRoot, CALLER, 11, 8)- tick()- const newer = await completedCopy(limited, callerRoot, CALLER, 12, 8)- tick()-- await startTransfer(limited, callerRoot, CALLER, 13, 8)-- expect(await exists(downloadDirectory(callerRoot, oldest.receipt.id))).toBe(false)- // Witnesses: the caller's newer copy and the other caller's older copy stay.- expect(await exists(downloadDirectory(callerRoot, newer.receipt.id))).toBe(true)- expect(await exists(downloadDirectory(otherRoot, other.receipt.id))).toBe(true)- })-- it("F9: a host over quota may evict any caller's oldest completed download", async () => {- const { limited } = await limitedStore(HOST_30_CALLER_15)- const otherRoot = await callerDirectory(hostRoot, 'caller-b')- const thirdRoot = await callerDirectory(hostRoot, 'caller-c')- const other = await completedCopy(limited, otherRoot, 'caller-b', 20, 10)- tick()- const third = await completedCopy(limited, thirdRoot, 'caller-c', 21, 10)- tick()- const own = await completedCopy(limited, callerRoot, CALLER, 22, 10)- tick()-- // caller-a stays within 15; the Host would reach 35 of 30.- await startTransfer(limited, callerRoot, CALLER, 23, 5)-- expect(await exists(downloadDirectory(otherRoot, other.receipt.id))).toBe(false)- // Witnesses: only the oldest copy went, whoever owned the newer ones.- expect(await exists(downloadDirectory(thirdRoot, third.receipt.id))).toBe(true)- expect(await exists(downloadDirectory(callerRoot, own.receipt.id))).toBe(true)- })-- it('F10: when eviction cannot make room nothing is deleted', async () => {- const { limited } = await limitedStore({ MCP_HOST_GFS_CALLER_DOWNLOAD_MAX_FILES: '2' })- await completedCopy(limited, callerRoot, CALLER, 30, 8, { owner: 'task-1' })- tick()- await completedCopy(limited, callerRoot, CALLER, 31, 8, { owner: 'task-1' })- const downloads = path.join(callerRoot, '.gfs-downloads')- const before = (await nativeFs.readdir(downloads)).sort()- const denied = await quotaCount('caller', 'retained_files')- lstatBoundary.mockClear()-- await expect(startTransfer(limited, callerRoot, CALLER, 32, 8)).rejects.toMatchObject({- code: 'caller_quota_exceeded',- })-- // Witness: the admission read the inventory before refusing.- expect(lstatBoundary.mock.calls.length).toBeGreaterThan(0)- expect((await nativeFs.readdir(downloads)).sort()).toEqual(before)- expect(before).toHaveLength(2)- expect(await quotaCount('caller', 'retained_files')).toBe(denied + 1)- })-- it('F11: pinned and active downloads are never evicted', async () => {- const { limited } = await limitedStore({- ...HOST_30_CALLER_15,- })- const otherRoot = await callerDirectory(hostRoot, 'caller-b')- const thirdRoot = await callerDirectory(hostRoot, 'caller-c')- const pinned = await completedCopy(limited, callerRoot, CALLER, 40, 10, { owner: 'task-40' })- tick()- const active = await startTransfer(limited, otherRoot, 'caller-b', 41, 10)- tick()- const unpinned = await completedCopy(limited, thirdRoot, 'caller-c', 42, 10)- tick()-- // The Host would reach 40 of 30; one eviction makes room.- await startTransfer(limited, await callerDirectory(hostRoot, 'caller-d'), 'caller-d', 43, 10)-- // Witness: the only eligible copy, although the newest, was evicted.- expect(await exists(downloadDirectory(thirdRoot, unpinned.receipt.id))).toBe(false)- expect(await exists(downloadDirectory(callerRoot, pinned.receipt.id))).toBe(true)- expect(await exists(downloadDirectory(otherRoot, active.transfer.id))).toBe(true)- })-- it('F12: free space is checked with active reservations and the 16 MiB reserve', async () => {- const otherRoot = await callerDirectory(hostRoot, 'caller-b')- await startTransfer(store, otherRoot, 'caller-b', 50, 4096 * 10)- const observed = await nativeFs.statfs(hostRoot, { bigint: true })- const reserveBlocks = (16n * 1024n * 1024n) / 4096n- // Room for the request and the reserve, but not for the active reservation.- statfsBoundary.mockResolvedValue({ ...observed, bsize: 4096n, bavail: reserveBlocks + 2n })- const denied = await quotaCount('host', 'free_space')-- await expect(startTransfer(store, callerRoot, CALLER, 51, 4096)).rejects.toMatchObject({- code: 'host_quota_exceeded',- })- expect(statfsBoundary).toHaveBeenCalled()- expect(await quotaCount('host', 'free_space')).toBe(denied + 1)-- // Control: with room for the active reservation too, the same request is admitted.- statfsBoundary.mockResolvedValue({ ...observed, bsize: 4096n, bavail: reserveBlocks + 11n })- await expect(startTransfer(store, callerRoot, CALLER, 51, 4096)).resolves.toBeDefined()- })-- it('F13: eviction candidates are not hashed', async () => {- const { limited } = await limitedStore({- ...HOST_30_CALLER_15,- })- const first = await completedCopy(limited, callerRoot, CALLER, 60, 3)- tick()- const second = await completedCopy(limited, callerRoot, CALLER, 61, 3)- tick()- const third = await completedCopy(limited, callerRoot, CALLER, 62, 9)- tick()- hashBoundary.mockClear()-- // 15 retained + 6 requested against 15: the plan takes the two 3-byte copies.- await startTransfer(limited, callerRoot, CALLER, 64, 6)-- // Witness: two candidates were evicted.- expect(await exists(downloadDirectory(callerRoot, first.receipt.id))).toBe(false)- expect(await exists(downloadDirectory(callerRoot, second.receipt.id))).toBe(false)- expect(hashBoundary).not.toHaveBeenCalled()- expect(await exists(downloadDirectory(callerRoot, third.receipt.id))).toBe(true)- })-- it('F14: size above maxFileBytes is refused before any filesystem work', async () => {- const { limited } = await limitedStore({ MCP_HOST_GFS_MAX_FILE_BYTES: '10' })- statfsBoundary.mockClear()- lstatBoundary.mockClear()- await expect(startTransfer(limited, callerRoot, CALLER, 70, 11)).rejects.toMatchObject({- code: 'host_quota_exceeded',- })- expect(statfsBoundary).not.toHaveBeenCalled()- expect(lstatBoundary).not.toHaveBeenCalled()- // Witness: the boundaries are live for an admissible size.- await startTransfer(limited, callerRoot, CALLER, 71, 10)- expect(statfsBoundary).toHaveBeenCalled()- expect(lstatBoundary).toHaveBeenCalled()- })-- it('F15: concurrency limits per caller and per host return download_busy', async () => {- const callerBusy = await quotaCount('caller', 'active_downloads')- const hostBusy = await quotaCount('host', 'active_downloads')- await startTransfer(store, callerRoot, CALLER, 80, 4)- await expect(startTransfer(store, callerRoot, CALLER, 81, 4)).rejects.toMatchObject({- code: 'download_busy',- })- expect(await quotaCount('caller', 'active_downloads')).toBe(callerBusy + 1)-- await startTransfer(store, await callerDirectory(hostRoot, 'caller-b'), 'caller-b', 82, 4)- await expect(- startTransfer(store, await callerDirectory(hostRoot, 'caller-c'), 'caller-c', 83, 4)- ).rejects.toMatchObject({ code: 'download_busy' })- expect(await quotaCount('host', 'active_downloads')).toBe(hostBusy + 1)- })-})--describe('filesystem-backed GFS download store: sweep', () => {- it('F16: the sweep removes incomplete directories of every shape and keeps complete ones', async () => {- const kept = await completedCopy(store, callerRoot, CALLER, 90, 20)- const bytes = Buffer.alloc(20, 3)- const shapes: string[] = []-- const orphanPartial = await handMadeDirectory(callerRoot)- await nativeFs.writeFile(path.join(orphanPartial.directory, 'source.partial'), bytes)- const metaWithoutSource = await handMadeDirectory(callerRoot)- await writeMeta(metaWithoutSource.directory, metaFor(metaWithoutSource.id, bytes))- const sourceWithoutMeta = await handMadeDirectory(callerRoot)- await nativeFs.writeFile(path.join(sourceWithoutMeta.directory, 'source'), bytes)- const invalidMeta = await handMadeDirectory(callerRoot)- await writeMeta(invalidMeta.directory, metaFor(invalidMeta.id, bytes, { sha256: 'nope' }))- await nativeFs.writeFile(path.join(invalidMeta.directory, 'source'), bytes)- const wrongSize = await handMadeDirectory(callerRoot)- await writeMeta(wrongSize.directory, metaFor(wrongSize.id, bytes))- await nativeFs.writeFile(path.join(wrongSize.directory, 'source'), Buffer.alloc(21, 3))- for (const shape of [- orphanPartial,- metaWithoutSource,- sourceWithoutMeta,- invalidMeta,- wrongSize,- ])- shapes.push(shape.directory)- const removed = await expiryCount('incomplete_removed')-- await expect(store.cleanupExpired()).resolves.toEqual({- removedExpired: 0,- removedIncomplete: 5,- removeFailed: 0,- })-- for (const directory of shapes) expect(await exists(directory)).toBe(false)- expect(await expiryCount('incomplete_removed')).toBe(removed + 5)- // Witness: the complete download stays on disk and readable through the index.- await expect(store.readManagedFile(kept.receipt.path, CALLER)).resolves.toEqual(kept.bytes)- })-- it('F17: the sweep removes expired complete downloads unless pinned', async () => {- const pinned = await completedCopy(store, callerRoot, CALLER, 100, 8, { owner: 'task-100' })- const loose = await completedCopy(store, callerRoot, CALLER, 101, 8)- const later = Date.now() + 2 * 60 * 60_000-- await expect(store.cleanupExpired(later)).resolves.toEqual({- removedExpired: 1,- removedIncomplete: 0,- removeFailed: 0,- })- expect(await exists(downloadDirectory(callerRoot, loose.receipt.id))).toBe(false)- expect(await exists(downloadDirectory(callerRoot, pinned.receipt.id))).toBe(true)-- await store.releaseReceiptOwner('task-100', CALLER)- await expect(store.cleanupExpired(later)).resolves.toMatchObject({ removedExpired: 1 })- expect(await exists(downloadDirectory(callerRoot, pinned.receipt.id))).toBe(false)- })-- it('F18: the sweep ignores entries that are not input-<uuid>', async () => {- const downloads = path.join(callerRoot, '.gfs-downloads')- await nativeFs.mkdir(downloads, { mode: 0o700 })- const foreign = [- path.join(downloads, 'input-not-a-uuid'),- path.join(downloads, `input-${nativeCrypto.randomUUID().toUpperCase()}`),- path.join(downloads, 'notes'),- ]- for (const directory of foreign) await nativeFs.mkdir(directory, { mode: 0o700 })- await nativeFs.writeFile(path.join(downloads, 'readme.txt'), 'kept')- const incomplete = await handMadeDirectory(callerRoot)-- await expect(store.cleanupExpired()).resolves.toMatchObject({ removedIncomplete: 1 })-- // Witness: the incomplete store directory next to them was removed.- expect(await exists(incomplete.directory)).toBe(false)- for (const directory of foreign) expect(await exists(directory)).toBe(true)- expect(await exists(path.join(downloads, 'readme.txt'))).toBe(true)- })-- it('F19: a symlinked .gfs-downloads is removed without following it', async () => {- const outside = await nativeFs.mkdtemp(path.join(tmpdir(), 'gfs-store-fs-outside-'))- try {- const victim = path.join(outside, `input-${nativeCrypto.randomUUID()}`)- await nativeFs.mkdir(victim, { mode: 0o700 })- await nativeFs.writeFile(path.join(victim, 'source.partial'), 'outside')- const link = path.join(callerRoot, '.gfs-downloads')- await nativeFs.symlink(outside, link)-- await expect(store.cleanupExpired()).resolves.toMatchObject({ removedIncomplete: 1 })-- expect(await exists(link)).toBe(false)- await expect(nativeFs.readFile(path.join(victim, 'source.partial'), 'utf8')).resolves.toBe(- 'outside'- )- } finally {- await nativeFs.rm(outside, { recursive: true, force: true })- }- })-- it('F20: a failed removal is logged and counted, does not block admission and is retried', async () => {- const stuck = await handMadeDirectory(callerRoot)- rmBoundary.mockImplementation(async (target: string, options: unknown) => {- // The store renames the directory to a private `.trash-<uuid>` name, then removes that.- if (path.basename(target).startsWith('.trash-'))- throw Object.assign(new Error('injected EACCES'), { code: 'EACCES' })- return nativeFs.rm(target, options as Parameters<typeof nativeFs.rm>[1])- })- const warn = vi.spyOn(logger, 'warn')- const failed = await expiryCount('remove_failed')-- await expect(store.cleanupExpired()).resolves.toMatchObject({ removeFailed: 1 })-- expect(warn).toHaveBeenCalledWith(- { component: 'GfsDownloadStore', code: 'EACCES' },- expect.stringContaining('could not remove')- )- expect(await expiryCount('remove_failed')).toBe(failed + 1)- const downloads = path.dirname(stuck.directory)- const leftover = (await nativeFs.readdir(downloads)).filter(name => name.startsWith('.trash-'))- expect(leftover).toHaveLength(1)- expect(await exists(stuck.directory)).toBe(false)- const next = await completedCopy(store, callerRoot, CALLER, 110, 8)- await expect(store.readManagedFile(next.receipt.path, CALLER)).resolves.toEqual(next.bytes)-- // Once removal works again, the next sweep removes the renamed leftover.- rmBoundary.mockImplementation(nativeFs.rm)- await expect(store.cleanupExpired()).resolves.toMatchObject({ removedIncomplete: 1 })- expect(await exists(path.join(downloads, leftover[0]!))).toBe(false)- })-})--describe('filesystem-backed GFS download store: managed reads', () => {- it('F21: readManagedFile returns the exact bytes and answers another caller like a missing copy', async () => {- const { receipt, bytes } = await completedCopy(store, callerRoot, CALLER, 120, 33)- await expect(store.readManagedFile(receipt.path, CALLER)).resolves.toEqual(bytes)- await expect(store.readManagedFile(receipt.path, 'caller-b')).rejects.toMatchObject({- code: 'download_missing',- })- await expect(- store.readManagedFile(`.gfs-downloads/input-${nativeCrypto.randomUUID()}/source`, CALLER)- ).rejects.toMatchObject({ code: 'download_missing' })- await expect(store.readManagedFile('../escape/source', CALLER)).rejects.toMatchObject({- code: 'download_missing',- })- })-- it('F22: readManagedFile deletes a tampered source and reports download_missing', async () => {- const { receipt } = await completedCopy(store, callerRoot, CALLER, 122, 16)- const directory = downloadDirectory(callerRoot, receipt.id)- await nativeFs.writeFile(path.join(directory, 'source'), Buffer.alloc(16, 0xab))- hashBoundary.mockClear()-- await expect(store.readManagedFile(receipt.path, CALLER)).rejects.toMatchObject({- code: 'download_missing',- })-- // Witness: the bytes were hashed once, then the directory was removed.- expect(hashBoundary).toHaveBeenCalledTimes(1)- expect(await exists(directory)).toBe(false)- })-- it('F23: readManagedFilePrefix bounds and size check', async () => {- const bytes = Buffer.from('0123456789abcdef0123')- const transfer = await store.createTransfer({- callerIdentity: CALLER,- callerWorkspacePath: callerRoot,- source: sourceFor(123),- sizeBytes: bytes.byteLength,- expiresAt: future(),- })- await nativeFs.writeFile(path.join(callerRoot, transfer.partialPath), bytes)- const receipt = await store.publish(transfer.id, CALLER, digest(bytes))-- await expect(store.readManagedFilePrefix(receipt.path, CALLER, 4)).resolves.toEqual(- Buffer.from('0123')- )- await expect(store.readManagedFilePrefix(receipt.path, CALLER)).resolves.toEqual(- bytes.subarray(0, 16)- )- for (const invalid of [0, -1, 4097, 1.5])- await expect(store.readManagedFilePrefix(receipt.path, CALLER, invalid)).rejects.toThrow(- RangeError- )- await nativeFs.appendFile(path.join(downloadDirectory(callerRoot, receipt.id), 'source'), 'x')- await expect(store.readManagedFilePrefix(receipt.path, CALLER, 4)).rejects.toMatchObject({- code: 'download_missing',- })- })-})--describe('filesystem-backed GFS download store: pins, lifecycle and errors', () => {- it('F24: releaseReceiptOwner unpins only its own caller and a second store on the same root sees no pins', async () => {- const pinned = await completedCopy(store, callerRoot, CALLER, 130, 8, { owner: 'task-130' })- const rootB = await callerDirectory(hostRoot, 'caller-b')- // The same owner id under another caller is another pin, not a refusal.- const other = await completedCopy(store, rootB, 'caller-b', 131, 8, { owner: 'task-130' })- const later = Date.now() + 2 * 60 * 60_000- await expect(store.releaseReceiptOwner('unknown-owner', CALLER)).resolves.toBeUndefined()- await expect(store.releaseReceiptOwner('task-130', 'caller-b')).resolves.toBeUndefined()- // Witness: caller-b's release freed only caller-b's copy; CALLER's pin holds.- await expect(store.cleanupExpired(later)).resolves.toMatchObject({ removedExpired: 1 })- expect(await exists(downloadDirectory(rootB, other.receipt.id))).toBe(false)- expect(await exists(downloadDirectory(callerRoot, pinned.receipt.id))).toBe(true)-- await store.close()- const second = await openStore(hostRoot)- await expect(second.cleanupExpired(later)).resolves.toMatchObject({ removedExpired: 1 })- expect(await exists(downloadDirectory(callerRoot, pinned.receipt.id))).toBe(false)- })-- it('F25: close drains active transfers and refuses new admissions', async () => {- const { transfer, bytes } = await startTransfer(store, callerRoot, CALLER, 140, 8)- let closed = false- const closing = store.close().then(() => {- closed = true- })- await expect(- startTransfer(store, await callerDirectory(hostRoot, 'caller-b'), 'caller-b', 141, 8)- ).rejects.toMatchObject({ code: 'download_busy' })- expect(store.isAvailable()).toBe(false)- expect(closed).toBe(false)-- const receipt = await store.publish(transfer.id, CALLER, digest(bytes))- await closing- expect(closed).toBe(true)- expect(receipt.id).toBe(transfer.id)- await expect(store.initialize()).rejects.toMatchObject({ code: 'download_busy' })- })-- it('F25b: close with an active transfer that never finishes resolves within the deadline', async () => {- const { transfer, bytes } = await startTransfer(store, callerRoot, CALLER, 150, 8)- const warn = vi.spyOn(logger, 'warn')- const started = performance.now()-- await store.close(50)-- expect(performance.now() - started).toBeLessThan(2_000)- // Witness: the store reports the transfer it left behind.- expect(warn).toHaveBeenCalledWith(- { component: 'GfsDownloadStore', active: 1 },- expect.stringContaining('closed with active transfers')- )- await expect(store.publish(transfer.id, CALLER, digest(bytes))).rejects.toMatchObject({- code: 'download_busy',- })- await expect(store.fail(transfer.id, CALLER)).rejects.toMatchObject({ code: 'download_busy' })- await expect(store.close()).resolves.toBeUndefined()- })-- it('F26: error codes for an uninitialized, a closed and an unknown transfer', async () => {- const uninitialized = new GfsDownloadStoreFs(hostRoot)- const probe = `.gfs-downloads/input-${nativeCrypto.randomUUID()}/source`- await expect(uninitialized.readManagedFile(probe, CALLER)).rejects.toMatchObject({- code: 'workspace_unavailable',- })- await expect(- uninitialized.createTransfer({- callerIdentity: CALLER,- callerWorkspacePath: callerRoot,- source: sourceFor(160),- sizeBytes: 1,- expiresAt: future(),- })- ).rejects.toMatchObject({ code: 'workspace_unavailable' })- await expect(uninitialized.close()).resolves.toBeUndefined()- await expect(uninitialized.initialize()).rejects.toMatchObject({ code: 'download_busy' })-- const { transfer } = await startTransfer(store, callerRoot, CALLER, 161, 4)- // Another caller's transfer is answered exactly like an unknown id.- await expect(store.fail(transfer.id, 'caller-b')).rejects.toMatchObject({- code: 'download_busy',- })- await expect(store.fail(nativeCrypto.randomUUID(), CALLER)).rejects.toMatchObject({- code: 'download_busy',- })- await expect(- store.publish(nativeCrypto.randomUUID(), CALLER, 'a'.repeat(64))- ).rejects.toMatchObject({ code: 'download_missing' })- await expect(store.publish(transfer.id, CALLER, 'not-a-digest')).rejects.toThrow(RangeError)- // Witness: the transfer is live and the caller's fail() removes it.- await store.fail(transfer.id, CALLER)- expect(await exists(downloadDirectory(callerRoot, transfer.id))).toBe(false)-- await store.close()- await expect(store.readManagedFile(probe, CALLER)).rejects.toMatchObject({- code: 'download_busy',- })- await expect(store.close()).resolves.toBeUndefined()- })-- it('F27: a Host root that is a symlink makes initialize reject with workspace_unavailable', async () => {- const real = path.join(hostRoot, 'real-store')- await nativeFs.mkdir(real, { mode: 0o700 })- const link = path.join(hostRoot, 'store-link')- await nativeFs.symlink(real, link)- const linked = new GfsDownloadStoreFs(link)- extraStores.push(linked)-- await expect(linked.initialize()).rejects.toBeInstanceOf(GfsDownloadStoreError)- await expect(linked.initialize()).rejects.toMatchObject({ code: 'workspace_unavailable' })- expect(linked.isAvailable()).toBe(false)- // Witness: the same directory through its real path initializes.- await expect(openStore(real)).resolves.toBeInstanceOf(GfsDownloadStoreFs)- })-})diff --git a/mcp-host/src/internalTools/gfsDownloadStoreFs.ts b/mcp-host/src/internalTools/gfsDownloadStoreFs.tsdeleted file mode 100644index 6f5c3b794..000000000--- a/mcp-host/src/internalTools/gfsDownloadStoreFs.ts+++ /dev/null@@ -1,1409 +0,0 @@-import { createHash, randomUUID } from 'node:crypto'-import { constants } from 'node:fs'-import * as fs from 'node:fs/promises'-import * as path from 'node:path'-import { logger } from '../logger'-import type { GfsImageSource } from '../visualInput/policy'-import { recordGfsDownloadExpiry, recordGfsDownloadQuota } from './gfsDownloadMetrics'-import {- GFS_FILE_LIMITS,- GFS_HOST_ACTIVE_DOWNLOADS,- GFS_HOST_RETAINED_FILES,-} from './gfsFilePolicy'-import { openPrivateStoreObject, verifyPrivateStoreDirectory } from './gfsStorePrivateFiles'--const GFS_DOWNLOAD_STORE_LOG_COMPONENT = 'GfsDownloadStore'--/** Caller-root directory that holds every download of that caller. */-const DOWNLOADS_DIRECTORY = '.gfs-downloads'-const META_FILE = 'meta.json'-const SOURCE_FILE = 'source'-const PARTIAL_FILE = 'source.partial'-const META_MAX_BYTES = 64 * 1024-const FREE_SPACE_RESERVE_BYTES = 16n * 1024n * 1024n--const UUID_PATTERN = '[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}'-/** The only directory names under `.gfs-downloads` that belong to the store. */-export const GFS_INPUT_DIRECTORY_RE = new RegExp(`^input-(${UUID_PATTERN})$`)-/** A directory renamed out of the way before removal; swept if a removal stops. */-const TRASH_PREFIX = '.trash-'-const TRASH_DIRECTORY_RE = new RegExp(`^\\.trash-${UUID_PATTERN}$`)-/** Caller-relative receipt path; the same contract gfsFilePreparation enforces. */-const RECEIPT_PATH_RE = new RegExp(`^\\.gfs-downloads/input-(${UUID_PATTERN})/source$`)-const SHA256_RE = /^[0-9a-f]{64}$/--export type GfsDownloadStoreErrorCode =- | 'caller_mismatch'- | 'caller_quota_exceeded'- | 'download_busy'- | 'download_expired'- | 'download_missing'- | 'host_quota_exceeded'- | 'publication_cancelled'- | 'storage_write_failed'- | 'workspace_unavailable'--export class GfsDownloadStoreError extends Error {- constructor(readonly code: GfsDownloadStoreErrorCode) {- super(`GFS download store failed (${code})`)- this.name = 'GfsDownloadStoreError'- }-}--export interface GfsDownloadTransfer {- id: string- path: string- partialPath: string- sizeBytes: number- expiresAt: string-}--export interface GfsDownloadReceipt {- id: string- source: GfsImageSource- path: string- sizeBytes: number- sha256: string- expiresAt: string-}--/** Serialized receipt written to `meta.json`; the store writes nothing else. */-interface StoredMeta {- schemaVersion: 1- id: string- callerIdentity: string- source: GfsImageSource- sizeBytes: number- sha256: string- createdAt: string- expiresAt: string-}--/**- * A complete download: `meta.json` parses and `source` has the recorded size.- * Provenance lives only in memory. A `published` entry was written by this- * process, so its caller identity and sha256 are trusted. An `adopted` entry- * was found on disk (left by an earlier process or planted by a shell command- * running with the Host UID): it counts against the quota of the directory- * that contains it and is swept, but it is never reused, read or pinned.- */-/** dev/ino of an inode, compared against an open descriptor or a later lstat. */-interface InodeIdentity {- dev: bigint- ino: bigint-}--function sameInode(left: InodeIdentity, right: InodeIdentity): boolean {- return left.dev === right.dev && left.ino === right.ino-}--interface Entry extends StoredMeta {- /** Absolute `<callerRoot>/.gfs-downloads/input-<id>` directory. */- directory: string- /**- * The `source` inode this process published. Reads and reuse serve only a- * descriptor whose inode is this one; adopted entries have none and are- * never served.- */- sourceIdentity?: InodeIdentity- /** `<hostRoot>/users/<key>` containing the entry: the owner for quota and inventory. */- callerRoot: string- provenance: 'published' | 'adopted'- /** Last publish, reuse or managed read in this process; adopted entries use createdAt. */- lastUsedMs: number-}--/** A reservation held in memory between createTransfer and publish/fail. */-interface ActiveTransfer {- id: string- callerIdentity: string- callerRoot: string- source: GfsImageSource- directory: string- /** The input directory created at admission; publication writes only into it. */- directoryIdentity?: InodeIdentity- sizeBytes: number- createdAt: string- expiresAt: string-}--export interface GfsDownloadSweepResult {- removedExpired: number- removedIncomplete: number- removeFailed: number-}--interface SweepTotals extends GfsDownloadSweepResult {- retainedCompleted: number- retainedBytes: number- /** Retained entries this process did not publish. */- adopted: number-}--export interface GfsDownloadInventory {- bytes: number- files: number- /** Keyed by the caller directory name (`users/<key>`), never by a recorded identity. */- byCaller: Map<string, { bytes: number; files: number }>-}--type DirectoryState =- | { state: 'absent' }- | { state: 'incomplete' }- | { state: 'complete'; entry: Entry }--function isValidSource(value: unknown): value is GfsImageSource {- if (typeof value !== 'object' || value === null || Array.isArray(value)) return false- const source = value as Record<string, unknown>- return (- source.kind === 'gfs' &&- typeof source.drive === 'string' &&- typeof source.resourceId === 'string' &&- typeof source.gfsUri === 'string' &&- typeof source.name === 'string' &&- Number.isSafeInteger(source.version) &&- (source.version as number) >= 0 &&- (source.attachmentId === undefined || typeof source.attachmentId === 'string') &&- (source.toolCallId === undefined || typeof source.toolCallId === 'string')- )-}--/** A recorded createdAt may lead this clock by at most this much (clock skew between Pods). */-const CREATED_AT_MAX_LEAD_MS = 60_000--/**- * Returns undefined for anything that is not a schema-1 receipt for- * `expectedId`. The time bounds keep a planted meta.json from outliving the- * retention window: no complete entry can expire later than- * `now + CREATED_AT_MAX_LEAD_MS + retentionMs`.- */-function parseMeta(raw: string, expectedId: string, now: number): StoredMeta | undefined {- let parsed: unknown- try {- parsed = JSON.parse(raw)- } catch {- return undefined- }- if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) return undefined- const meta = parsed as Record<string, unknown>- const createdAt = typeof meta.createdAt === 'string' ? Date.parse(meta.createdAt) : NaN- const expiresAt = typeof meta.expiresAt === 'string' ? Date.parse(meta.expiresAt) : NaN- if (- meta.schemaVersion !== 1 ||- meta.id !== expectedId ||- typeof meta.callerIdentity !== 'string' ||- meta.callerIdentity.length === 0 ||- !isValidSource(meta.source) ||- !Number.isSafeInteger(meta.sizeBytes) ||- (meta.sizeBytes as number) < 0 ||- (meta.sizeBytes as number) > GFS_FILE_LIMITS.maxFileBytes ||- typeof meta.sha256 !== 'string' ||- !SHA256_RE.test(meta.sha256) ||- !Number.isFinite(createdAt) ||- !Number.isFinite(expiresAt) ||- expiresAt < createdAt ||- expiresAt > createdAt + GFS_FILE_LIMITS.retentionMs ||- createdAt > now + CREATED_AT_MAX_LEAD_MS- )- return undefined- return meta as unknown as StoredMeta-}--function validReceiptOwnerId(ownerId: string): boolean {- return (- typeof ownerId === 'string' &&- ownerId.length > 0 &&- ownerId.length <= 256 &&- !/[\u0000-\u001f\u007f]/.test(ownerId) &&- !['__proto__', 'constructor', 'prototype'].includes(ownerId)- )-}--function isWithinDirectory(child: string, parent: string): boolean {- const relative = path.relative(parent, child)- return relative !== '' && !relative.startsWith('..') && !path.isAbsolute(relative)-}--function errorCode(error: unknown): string {- const code = (error as NodeJS.ErrnoException)?.code- return typeof code === 'string' ? code : 'unknown'-}--/** A removal is proven by ENOENT, not by `fs.rm` returning. */-async function assertAbsent(target: string): Promise<void> {- try {- await fs.lstat(target)- } catch (error) {- if (errorCode(error) === 'ENOENT') return- throw error- }- throw new GfsDownloadStoreError('storage_write_failed')-}--async function syncDirectory(directory: string): Promise<void> {- const handle = await fs.open(directory, 'r')- try {- await handle.sync()- } finally {- await handle.close()- }-}--async function sha256FileHandle(handle: fs.FileHandle, assertActive?: () => void): Promise<string> {- const digest = createHash('sha256')- const chunk = Buffer.alloc(64 * 1024)- let position = 0- for (;;) {- assertActive?.()- const { bytesRead } = await handle.read(chunk, 0, chunk.byteLength, position)- if (bytesRead === 0) break- digest.update(chunk.subarray(0, bytesRead))- position += bytesRead- }- assertActive?.()- return digest.digest('hex')-}--function receiptPath(id: string): string {- return path.join(DOWNLOADS_DIRECTORY, `input-${id}`, SOURCE_FILE)-}--/** `<callerRoot>/.gfs-downloads/input-<id>` → `<callerRoot>`. */-/** Owner ids are scoped to their caller; the encoding is unambiguous for any strings. */-function pinKey(callerIdentity: string, ownerId: string): string {- return JSON.stringify([callerIdentity, ownerId])-}--function callerRootOf(directory: string): string {- return path.dirname(path.dirname(directory))-}--/** Adopted copies go first (oldest recorded first), then published ones least recently used. */-function evictionOrder(left: Entry, right: Entry): number {- if (left.provenance !== right.provenance) return left.provenance === 'adopted' ? -1 : 1- return left.lastUsedMs - right.lastUsedMs || left.id.localeCompare(right.id)-}--/**- * GFS download store whose only state is the directory tree under- * `users/<caller>/.gfs-downloads`. The filesystem is the truth for existence,- * quota and cleanup: the in-memory index is rebuilt from disk at startup and- * re-checked on admission and by every sweep. It is never the truth for who- * downloaded a copy or for its hash: reuse and managed reads serve only copies- * this process published. Active transfers and retention pins live in memory.- */-export class GfsDownloadStoreFs {- private hostRoot: string- private readonly requestedHostRoot: string- private readonly entries = new Map<string, Entry>()- private readonly active = new Map<string, ActiveTransfer>()- private readonly activeByCaller = new Map<string, number>()- /** Keyed by `pinKey(callerIdentity, ownerId)`: callers never share or see a pin. */- private readonly pins = new Map<string, Set<string>>()- private mutationTail: Promise<void> = Promise.resolve()- private drainWaiters: Array<() => void> = []- private initializing?: Promise<void>- private initialized = false- private closing = false- private closed = false-- constructor(hostRoot: string) {- this.hostRoot = path.resolve(hostRoot)- this.requestedHostRoot = this.hostRoot- }-- isAvailable(): boolean {- return this.initialized && !this.closing && !this.closed- }-- /**- * Rejects only when the Host root itself is unusable (workspace_unavailable)- * or the store was closed (download_busy). Leftover download directories- * are removed or adopted; none of them can make initialize fail.- */- async initialize(): Promise<void> {- if (this.closed || this.closing) throw new GfsDownloadStoreError('download_busy')- if (this.initialized) return- this.initializing ??= this.runInitialize().finally(() => {- this.initializing = undefined- })- return this.initializing- }-- private async runInitialize(): Promise<void> {- try {- await fs.mkdir(this.requestedHostRoot, { recursive: true, mode: 0o700 })- const requested = await fs.lstat(this.requestedHostRoot)- if (!requested.isDirectory() || requested.isSymbolicLink())- throw new GfsDownloadStoreError('workspace_unavailable')- this.hostRoot = await fs.realpath(this.requestedHostRoot)- const resolved = await fs.lstat(this.hostRoot)- if (!resolved.isDirectory() || resolved.isSymbolicLink())- throw new GfsDownloadStoreError('workspace_unavailable')- } catch (error) {- if (error instanceof GfsDownloadStoreError) throw error- throw new GfsDownloadStoreError('workspace_unavailable')- }- const totals = await this.serialize(() => this.sweep(Date.now()))- if (this.closed || this.closing) throw new GfsDownloadStoreError('download_busy')- this.initialized = true- logger.info(- {- component: GFS_DOWNLOAD_STORE_LOG_COMPONENT,- removedIncomplete: totals.removedIncomplete,- removedExpired: totals.removedExpired,- retainedCompleted: totals.retainedCompleted,- retainedBytes: totals.retainedBytes,- adopted: totals.adopted,- retiredLegacyStore: false,- },- 'GFS download store initialized'- )- }-- async createTransfer(input: {- callerIdentity: string- callerWorkspacePath: string- source: GfsImageSource- sizeBytes: number- expiresAt: string- /** Task lifetime protection; release only after every physical consumer has settled. */- retentionOwnerId?: string- }): Promise<GfsDownloadTransfer> {- this.assertAdmitting()- if (- !Number.isSafeInteger(input.sizeBytes) ||- input.sizeBytes < 0 ||- input.sizeBytes > GFS_FILE_LIMITS.maxFileBytes- )- throw new GfsDownloadStoreError('host_quota_exceeded')- if (typeof input.callerIdentity !== 'string' || input.callerIdentity.length === 0)- throw new GfsDownloadStoreError('caller_mismatch')- if (!isValidSource(input.source)) throw new RangeError('GFS download source is malformed')- const createdAtMs = Date.now()- const expiresAtMs = Date.parse(input.expiresAt)- if (!Number.isFinite(expiresAtMs) || expiresAtMs < createdAtMs)- throw new RangeError('GFS download expiry must be a future ISO timestamp')- // The same bound parseMeta applies, so a published copy stays valid on disk.- if (expiresAtMs > createdAtMs + GFS_FILE_LIMITS.retentionMs)- throw new RangeError('GFS download expiry must be within the retention window')- if (input.retentionOwnerId !== undefined) this.assertReceiptOwner(input.retentionOwnerId)- const callerRoot = await this.validateCallerRoot(input.callerWorkspacePath)- const id = randomUUID()- const downloadsRoot = path.join(callerRoot, DOWNLOADS_DIRECTORY)- const directory = path.join(downloadsRoot, `input-${id}`)- const transfer: ActiveTransfer = {- id,- callerIdentity: input.callerIdentity,- callerRoot,- source: input.source,- directory,- sizeBytes: input.sizeBytes,- createdAt: new Date(createdAtMs).toISOString(),- expiresAt: input.expiresAt,- }-- await this.serialize(async () => {- this.assertAdmitting()- if (this.active.size >= GFS_HOST_ACTIVE_DOWNLOADS) {- recordGfsDownloadQuota('host', 'active_downloads')- throw new GfsDownloadStoreError('download_busy')- }- if (- (this.activeByCaller.get(input.callerIdentity) ?? 0) >=- GFS_FILE_LIMITS.callerActiveDownloads- ) {- recordGfsDownloadQuota('caller', 'active_downloads')- throw new GfsDownloadStoreError('download_busy')- }- if (input.retentionOwnerId !== undefined) this.assertReceiptOwner(input.retentionOwnerId)- // Verified free capacity first: no eviction happens for an admission the- // volume cannot hold anyway. Measured again after eviction below.- await this.assertPhysicalCapacity(input.sizeBytes)- await this.sweep(Date.now())- await this.reclaimForAdmission(callerRoot, input.sizeBytes)- const denial = this.quotaDenial(callerRoot, input.sizeBytes)- if (denial) {- recordGfsDownloadQuota(denial.scope, denial.reason)- throw new GfsDownloadStoreError(- denial.scope === 'host' ? 'host_quota_exceeded' : 'caller_quota_exceeded'- )- }- await this.assertPhysicalCapacity(input.sizeBytes)-- this.addActive(transfer)- try {- await this.ensureDownloadsRoot(downloadsRoot)- await fs.mkdir(directory, { mode: 0o700 })- await this.verifyEntryDirectory(directory)- transfer.directoryIdentity = await fs.lstat(directory, { bigint: true })- const partial = await fs.open(- path.join(directory, PARTIAL_FILE),- constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW,- 0o600- )- await partial.close()- } catch (error) {- this.releaseActive(id)- await this.removeDirectory(directory, 'incomplete_removed')- if (error instanceof GfsDownloadStoreError) throw error- throw new GfsDownloadStoreError('storage_write_failed')- }- if (input.retentionOwnerId !== undefined)- this.pin(input.retentionOwnerId, input.callerIdentity, id)- })-- const callerPath = receiptPath(id)- return {- id,- path: callerPath,- partialPath: `${callerPath}.partial`,- sizeBytes: input.sizeBytes,- expiresAt: input.expiresAt,- }- }-- /**- * Publication order: sync source.partial, write meta.json (tmp + rename),- * rename source.partial to source, sync the directory. A crash between the- * renames leaves meta.json without source, which the sweep removes. Any- * failure leaves the id active so the caller's fail() removes the directory.- */- async publish(- id: string,- callerIdentity: string,- sha256: string,- publication?: { signal?: AbortSignal; deadlineMs?: number }- ): Promise<GfsDownloadReceipt> {- this.assertInitialized()- if (!SHA256_RE.test(sha256)) throw new RangeError('GFS download digest is malformed')- const transfer = this.active.get(id)- // Another caller's transfer or copy is answered exactly like an unknown id.- if (!transfer || transfer.callerIdentity !== callerIdentity)- throw new GfsDownloadStoreError('download_missing')- const entry = await this.serialize(async () => {- // close() may have timed out while this waited: the reservation is gone.- if (this.closed) throw new GfsDownloadStoreError('download_busy')- if (this.active.get(id) !== transfer) throw new GfsDownloadStoreError('download_missing')- if (Date.parse(transfer.expiresAt) <= Date.now())- throw new GfsDownloadStoreError('download_expired')- this.assertPublicationOpen(publication)- let published: Entry- try {- published = await this.writePublication(transfer, sha256, publication)- } catch (error) {- if (error instanceof GfsDownloadStoreError) throw error- throw new GfsDownloadStoreError('storage_write_failed')- }- // Indexed and released in the same critical section, so no sweep can- // observe the directory as neither active nor indexed.- this.entries.set(id, published)- this.releaseActive(id)- return published- })- return this.receiptFor(entry, entry.source)- }-- private async writePublication(- transfer: ActiveTransfer,- sha256: string,- publication?: { signal?: AbortSignal; deadlineMs?: number }- ): Promise<Entry> {- const partialPath = path.join(transfer.directory, PARTIAL_FILE)- const sourcePath = path.join(transfer.directory, SOURCE_FILE)- const metaPath = path.join(transfer.directory, META_FILE)- // The caller directory may have been replaced by a symlink since admission.- await this.verifyEntryDirectory(transfer.directory)- const partial = await openPrivateStoreObject(- partialPath,- 'file',- constants.O_RDONLY,- false- ).catch(() => {- throw new GfsDownloadStoreError('download_missing')- })- let sourceIdentity: InodeIdentity- try {- // A path swapped after the check above resolves to another directory:- // the input directory must still be the one created at admission.- await this.assertTransferDirectory(transfer)- sourceIdentity = await partial.stat({ bigint: true })- const info = await partial.stat()- if (!info.isFile() || info.size !== transfer.sizeBytes)- throw new GfsDownloadStoreError('download_missing')- const digest = await sha256FileHandle(partial, () => this.assertPublicationOpen(publication))- if (digest !== sha256) throw new GfsDownloadStoreError('storage_write_failed')- const named = await fs.lstat(partialPath)- if (named.isSymbolicLink() || named.dev !== info.dev || named.ino !== info.ino)- throw new GfsDownloadStoreError('download_missing')- await partial.chmod(0o600)- await partial.sync()- } finally {- await partial.close()- }-- const meta: StoredMeta = {- schemaVersion: 1,- id: transfer.id,- callerIdentity: transfer.callerIdentity,- source: transfer.source,- sizeBytes: transfer.sizeBytes,- sha256,- createdAt: transfer.createdAt,- expiresAt: transfer.expiresAt,- }- const temporary = path.join(transfer.directory, `${META_FILE}.tmp-${randomUUID()}`)- let temporaryExists = false- try {- const handle = await fs.open(- temporary,- constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW,- 0o600- )- temporaryExists = true- try {- await handle.writeFile(JSON.stringify(meta), 'utf8')- await handle.sync()- } finally {- await handle.close()- }- this.assertPublicationOpen(publication)- await this.assertTransferDirectory(transfer)- await fs.rename(temporary, metaPath)- temporaryExists = false- } finally {- if (temporaryExists) await fs.rm(temporary, { force: true }).catch(() => undefined)- }- // The last cancellation point: once source exists the download is complete.- this.assertPublicationOpen(publication)- await this.assertTransferDirectory(transfer)- await fs.rename(partialPath, sourcePath)- await syncDirectory(transfer.directory)- // Only the inode that was hashed is published, wherever the name now leads.- if (!sameInode(await fs.lstat(sourcePath, { bigint: true }), sourceIdentity))- throw new GfsDownloadStoreError('storage_write_failed')- return {- ...meta,- directory: transfer.directory,- sourceIdentity: { dev: sourceIdentity.dev, ino: sourceIdentity.ino },- callerRoot: transfer.callerRoot,- provenance: 'published',- lastUsedMs: Date.now(),- }- }-- /** The transfer's input directory is still the inode created at admission. */- private async assertTransferDirectory(transfer: ActiveTransfer): Promise<void> {- const current = await fs.lstat(transfer.directory, { bigint: true })- if (- !transfer.directoryIdentity ||- !current.isDirectory() ||- !sameInode(current, transfer.directoryIdentity)- )- throw new GfsDownloadStoreError('workspace_unavailable')- }-- /** Reuse only after the caller has freshly authorized this exact source version. */- async reusableReceipt(- callerIdentity: string,- source: GfsImageSource,- sizeBytes: number,- bounds?: { signal?: AbortSignal; deadlineMs?: number; retentionOwnerId?: string }- ): Promise<GfsDownloadReceipt | undefined> {- this.assertAdmitting()- return this.serialize(async () => {- this.assertAdmitting()- this.assertPublicationOpen(bounds)- if (bounds?.retentionOwnerId !== undefined) this.assertReceiptOwner(bounds.retentionOwnerId)- // Only copies this process published: an adopted meta.json carries an- // identity and a digest that anyone with the Host UID could have written.- // A miss is final; the caller downloads the file again.- const entry = [...this.entries.values()].find(- candidate =>- candidate.provenance === 'published' &&- candidate.callerIdentity === callerIdentity &&- Date.parse(candidate.expiresAt) > Date.now() &&- candidate.sizeBytes === sizeBytes &&- candidate.source.drive === source.drive &&- candidate.source.resourceId === source.resourceId &&- candidate.source.version === source.version- )- if (!entry) return undefined- let verified = false- try {- const handle = await this.openEntryContent(entry)- try {- const info = await handle.stat()- verified =- info.isFile() &&- info.size === sizeBytes &&- (info.mode & 0o777) === 0o600 &&- (await sha256FileHandle(handle, () => this.assertPublicationOpen(bounds))) ===- entry.sha256- } finally {- await handle.close()- }- } catch (error) {- if (error instanceof GfsDownloadStoreError && error.code === 'publication_cancelled')- throw error- verified = false- }- if (!verified) {- await this.removeEntry(entry, 'incomplete_removed')- return undefined- }- this.assertPublicationOpen(bounds)- entry.lastUsedMs = Date.now()- if (bounds?.retentionOwnerId !== undefined)- this.pin(bounds.retentionOwnerId, callerIdentity, entry.id)- return this.receiptFor(entry, source)- })- }-- /**- * Called by the producer after a transfer that was not published. The- * directory is removed and the reservation released; a publish that failed- * keeps its id active precisely so this call can clean it up.- */- async fail(id: string, callerIdentity: string): Promise<void> {- const transfer = this.active.get(id)- // Another caller's transfer or copy is answered exactly like an unknown id.- if (!transfer || transfer.callerIdentity !== callerIdentity)- throw new GfsDownloadStoreError('download_busy')- await this.serialize(async () => {- if (this.closed) throw new GfsDownloadStoreError('download_busy')- // Publication may have settled while this waited.- if (this.active.get(id) !== transfer) throw new GfsDownloadStoreError('download_busy')- this.releaseActive(id)- this.unpinId(id)- if (!(await this.removeDirectory(transfer.directory, 'incomplete_removed')))- throw new GfsDownloadStoreError('storage_write_failed')- })- }-- async readManagedFile(callerRelativePath: string, callerIdentity: string): Promise<Buffer> {- const entry = this.managedEntry(callerRelativePath, callerIdentity)- let bytes: Buffer- try {- const handle = await this.openEntryContent(entry)- try {- const info = await handle.stat()- if (!info.isFile() || info.size !== entry.sizeBytes || (info.mode & 0o777) !== 0o600)- throw new GfsDownloadStoreError('download_missing')- bytes = Buffer.alloc(entry.sizeBytes)- let offset = 0- while (offset < entry.sizeBytes) {- const { bytesRead } = await handle.read(bytes, offset, entry.sizeBytes - offset, offset)- if (bytesRead <= 0) throw new GfsDownloadStoreError('download_missing')- offset += bytesRead- }- const probe = Buffer.alloc(1)- const extra = await handle.read(probe, 0, 1, entry.sizeBytes)- if (extra.bytesRead !== 0) throw new GfsDownloadStoreError('download_missing')- } finally {- await handle.close()- }- } catch {- throw new GfsDownloadStoreError('download_missing')- }- if (createHash('sha256').update(bytes).digest('hex') !== entry.sha256) {- // A copy whose bytes no longer match its receipt is not a cache entry.- await this.serialize(() => this.removeEntry(entry, 'incomplete_removed'))- throw new GfsDownloadStoreError('download_missing')- }- return bytes- }-- async readManagedFilePrefix(- callerRelativePath: string,- callerIdentity: string,- prefixBytes = 16- ): Promise<Buffer> {- this.assertReadable()- if (!Number.isSafeInteger(prefixBytes) || prefixBytes <= 0 || prefixBytes > 4096)- throw new RangeError('GFS managed-file prefix must be between 1 and 4096 bytes')- const entry = this.managedEntry(callerRelativePath, callerIdentity)- try {- const handle = await this.openEntryContent(entry)- try {- const info = await handle.stat()- if (!info.isFile() || info.size !== entry.sizeBytes || (info.mode & 0o777) !== 0o600)- throw new GfsDownloadStoreError('download_missing')- const prefix = Buffer.alloc(prefixBytes)- const { bytesRead } = await handle.read(prefix, 0, prefix.byteLength, 0)- return prefix.subarray(0, bytesRead)- } finally {- await handle.close()- }- } catch {- throw new GfsDownloadStoreError('download_missing')- }- }-- /**- * Caller/task lifecycle must prove consumer settlement before invoking this.- * Releases only the caller's own pin; an owner id another caller uses is a- * different pin, so the call is the same no-op as for an unknown owner.- */- async releaseReceiptOwner(ownerId: string, callerIdentity: string): Promise<void> {- this.assertReadable()- await this.serialize(async () => {- this.pins.delete(pinKey(callerIdentity, ownerId))- })- }-- /** Removes expired and incomplete downloads; startup runs the same sweep. */- async cleanupExpired(now = Date.now()): Promise<GfsDownloadSweepResult> {- this.assertReadable()- try {- const totals = await this.serialize(() => this.sweep(now))- return {- removedExpired: totals.removedExpired,- removedIncomplete: totals.removedIncomplete,- removeFailed: totals.removeFailed,- }- } catch (error) {- recordGfsDownloadExpiry('sweep_failed')- throw error- }- }-- /**- * Stops admitting, waits for active transfers until the deadline and then- * closes regardless. Transfers still active afterwards get download_busy- * from publish/fail; their directories are removed by the next start.- */- async close(drainTimeoutMs = 5_000): Promise<void> {- if (this.closed || this.closing) return- if (!this.initialized) {- this.closed = true- return- }- this.closing = true- let timer: NodeJS.Timeout | undefined- const deadline = new Promise<void>(resolve => {- timer = setTimeout(resolve, drainTimeoutMs)- })- const drained = new Promise<void>(resolve => {- if (this.active.size === 0) resolve()- else this.drainWaiters.push(resolve)- })- // Active transfers first, then whatever mutation is still in flight; both- // bounded by the same deadline.- await Promise.race([drained.then(() => this.mutationTail), deadline])- clearTimeout(timer)- if (this.active.size > 0)- logger.warn(- { component: GFS_DOWNLOAD_STORE_LOG_COMPONENT, active: this.active.size },- 'GFS download store closed with active transfers; their directories are removed at the next start'- )- this.closed = true- this.closing = false- }-- /** Test-only: complete downloads on disk plus in-memory reservations. Read-only. */- async debugInventory(): Promise<GfsDownloadInventory> {- const inventory: GfsDownloadInventory = { bytes: 0, files: 0, byCaller: new Map() }- const add = (callerRoot: string, sizeBytes: number) => {- const key = path.basename(callerRoot)- inventory.bytes += sizeBytes- inventory.files += 1- const caller = inventory.byCaller.get(key) ?? { bytes: 0, files: 0 }- caller.bytes += sizeBytes- caller.files += 1- inventory.byCaller.set(key, caller)- }- const now = Date.now()- for (const { id, directory } of await this.listInputDirectories()) {- if (this.active.get(id)?.directory === directory) continue- const state = await this.inspectDirectory(directory, id, now)- if (state.state === 'complete') add(state.entry.callerRoot, state.entry.sizeBytes)- }- for (const transfer of this.active.values()) add(transfer.callerRoot, transfer.sizeBytes)- return inventory- }-- /**- * Walks `users/*\/.gfs-downloads/*` plus every indexed directory. Incomplete- * directories and expired, unpinned complete ones are removed; complete ones- * are (re)indexed, new ones as adopted. Active transfers of this process are- * never touched, and a published entry is never replaced: another directory- * carrying the id of a reservation or of a published copy is removed, and an- * id found in several directories with neither is removed everywhere (a- * random uuid does not repeat by chance).- */- private async sweep(now: number): Promise<SweepTotals> {- const totals: SweepTotals = {- removedExpired: 0,- removedIncomplete: 0,- removeFailed: 0,- retainedCompleted: 0,- retainedBytes: 0,- adopted: 0,- }- const candidates = new Map<string, string[]>()- const addCandidate = (id: string, directory: string) => {- const directories = candidates.get(id) ?? []- if (!directories.includes(directory)) directories.push(directory)- candidates.set(id, directories)- }- for (const { id, directory } of await this.listInputDirectories(totals))- addCandidate(id, directory)- for (const entry of this.entries.values()) addCandidate(entry.id, entry.directory)- const removeIncomplete = async (directory: string) => {- if (await this.removeDirectory(directory, 'incomplete_removed')) totals.removedIncomplete += 1- else totals.removeFailed += 1- }-- for (const [id, directories] of candidates) {- const indexed = this.entries.get(id)- const owned =- this.active.get(id)?.directory ??- (indexed?.provenance === 'published' ? indexed.directory : undefined)- if (owned === undefined && directories.length > 1) {- this.forget(id)- for (const duplicate of directories) await removeIncomplete(duplicate)- continue- }- if (owned !== undefined)- for (const duplicate of directories)- if (duplicate !== owned) await removeIncomplete(duplicate)- if (this.active.has(id)) continue- const directory = owned ?? directories[0]!- const state =- indexed && indexed.directory === directory- ? await this.recheckIndexed(indexed)- : await this.inspectDirectory(directory, id, now)- if (state.state === 'absent') {- this.forget(id)- continue- }- if (state.state === 'incomplete') {- this.forget(id)- await removeIncomplete(directory)- continue- }- const entry = state.entry- if (Date.parse(entry.expiresAt) <= now && !this.isPinned(id)) {- this.forget(id)- if (await this.removeDirectory(directory, 'expired_removed')) totals.removedExpired += 1- else totals.removeFailed += 1- continue- }- this.entries.set(id, entry)- totals.retainedCompleted += 1- totals.retainedBytes += entry.sizeBytes- if (entry.provenance === 'adopted') totals.adopted += 1- }- return totals- }-- /**- * Lists store-owned directories. A `.gfs-downloads` that is a symlink or not- * a directory is removed without following it; names that do not match- * `input-<uuid>` are left alone because they are not the store's.- */- private async listInputDirectories(- totals?: SweepTotals- ): Promise<Array<{ id: string; directory: string }>> {- const found: Array<{ id: string; directory: string }> = []- const usersRoot = path.join(this.hostRoot, 'users')- let users: import('node:fs').Dirent[]- try {- const info = await fs.lstat(usersRoot)- if (!info.isDirectory()) return found- users = await fs.readdir(usersRoot, { withFileTypes: true })- } catch (error) {- if (errorCode(error) === 'ENOENT') return found- this.reportSweepFailure(error)- return found- }- for (const user of users) {- if (!user.isDirectory()) continue- const downloadsRoot = path.join(usersRoot, user.name, DOWNLOADS_DIRECTORY)- let children: import('node:fs').Dirent[]- try {- const info = await fs.lstat(downloadsRoot)- if (!info.isDirectory()) {- if (totals) {- if (await this.removeDirectory(downloadsRoot, 'incomplete_removed'))- totals.removedIncomplete += 1- else totals.removeFailed += 1- }- continue- }- children = await fs.readdir(downloadsRoot, { withFileTypes: true })- } catch (error) {- if (errorCode(error) === 'ENOENT') continue- this.reportSweepFailure(error)- continue- }- for (const child of children) {- const match = GFS_INPUT_DIRECTORY_RE.exec(child.name)- if (match) found.push({ id: match[1]!, directory: path.join(downloadsRoot, child.name) })- else if (totals && TRASH_DIRECTORY_RE.test(child.name)) {- // Left by a removal that stopped between its rename and its rm.- if (- await this.removeDirectory(path.join(downloadsRoot, child.name), 'incomplete_removed')- )- totals.removedIncomplete += 1- else totals.removeFailed += 1- }- }- }- return found- }-- /** Reads one directory from disk; a complete result is always `adopted`. */- private async inspectDirectory(- directory: string,- id: string,- now: number- ): Promise<DirectoryState> {- let info: import('node:fs').Stats- try {- info = await fs.lstat(directory)- } catch (error) {- if (errorCode(error) === 'ENOENT') return { state: 'absent' }- return { state: 'incomplete' }- }- if (!info.isDirectory()) return { state: 'incomplete' }- let raw: string- try {- const handle = await fs.open(- path.join(directory, META_FILE),- constants.O_RDONLY | constants.O_NOFOLLOW- )- try {- const metaInfo = await handle.stat()- if (!metaInfo.isFile() || metaInfo.size > META_MAX_BYTES) return { state: 'incomplete' }- raw = await handle.readFile('utf8')- } finally {- await handle.close()- }- } catch {- return { state: 'incomplete' }- }- const meta = parseMeta(raw, id, now)- if (!meta) return { state: 'incomplete' }- try {- const source = await fs.lstat(path.join(directory, SOURCE_FILE))- if (!source.isFile() || source.size !== meta.sizeBytes) return { state: 'incomplete' }- } catch {- return { state: 'incomplete' }- }- return {- state: 'complete',- entry: {- ...meta,- directory,- callerRoot: callerRootOf(directory),- provenance: 'adopted',- lastUsedMs: Date.parse(meta.createdAt),- },- }- }-- /** An indexed entry is re-checked with one lstat; meta.json is not re-read. */- private async recheckIndexed(entry: Entry): Promise<DirectoryState> {- try {- const source = await fs.lstat(path.join(entry.directory, SOURCE_FILE))- if (source.isFile() && source.size === entry.sizeBytes) return { state: 'complete', entry }- } catch (error) {- if (errorCode(error) === 'ENOENT') {- try {- await fs.lstat(entry.directory)- } catch (directoryError) {- if (errorCode(directoryError) === 'ENOENT') return { state: 'absent' }- }- }- }- return { state: 'incomplete' }- }-- /**- * Index lookup for a managed read. Only a copy this process published for- * this caller is served. An adopted, unknown or another caller's id is the- * same download_missing, decided from the index alone: the disk is not- * probed, because nothing on disk can prove who downloaded a copy, and a- * foreign copy must cost no more work than a missing one.- */- private managedEntry(callerRelativePath: string, callerIdentity: string): Entry {- this.assertReadable()- const match = RECEIPT_PATH_RE.exec(callerRelativePath)- if (!match) throw new GfsDownloadStoreError('download_missing')- const entry = this.entries.get(match[1]!)- if (!entry || entry.provenance !== 'published' || entry.callerIdentity !== callerIdentity)- throw new GfsDownloadStoreError('download_missing')- if (Date.parse(entry.expiresAt) <= Date.now())- throw new GfsDownloadStoreError('download_expired')- entry.lastUsedMs = Date.now()- return entry- }-- private async openEntryContent(entry: Entry): Promise<fs.FileHandle> {- await this.verifyEntryDirectory(entry.directory)- const handle = await openPrivateStoreObject(- path.join(entry.directory, SOURCE_FILE),- 'file',- constants.O_RDONLY,- false- )- try {- // The descriptor, not the path, decides: a name swapped after the- // directory check opens another inode and is refused.- if (- !entry.sourceIdentity ||- !sameInode(await handle.stat({ bigint: true }), entry.sourceIdentity)- )- throw new GfsDownloadStoreError('download_missing')- const info = await handle.stat()- if (info.size !== entry.sizeBytes) throw new GfsDownloadStoreError('download_missing')- if ((info.mode & 0o7777) !== 0o600) {- // Restore the private mode only for content that still matches.- if ((await sha256FileHandle(handle)) !== entry.sha256)- throw new GfsDownloadStoreError('download_missing')- await handle.chmod(0o600)- }- return handle- } catch (error) {- await handle.close()- throw error- }- }-- private async verifyEntryDirectory(directory: string): Promise<void> {- if (!isWithinDirectory(directory, this.hostRoot))- throw new GfsDownloadStoreError('workspace_unavailable')- const callerRoot = path.dirname(path.dirname(directory))- if ((await fs.realpath(callerRoot)) !== callerRoot)- throw new GfsDownloadStoreError('workspace_unavailable')- await verifyPrivateStoreDirectory(path.dirname(directory))- await verifyPrivateStoreDirectory(directory)- }-- /**- * A `.gfs-downloads` that is a symlink, not a directory, or not private to- * this process is removed without following it and recreated, so a shell- * command can cost a caller its cached copies but never block its downloads.- */- private async ensureDownloadsRoot(downloadsRoot: string): Promise<void> {- try {- await fs.mkdir(downloadsRoot, { mode: 0o700 })- return- } catch (error) {- if (errorCode(error) !== 'EEXIST') throw error- }- try {- await verifyPrivateStoreDirectory(downloadsRoot)- return- } catch {- // Not a private directory: replaced below.- }- for (const id of this.idsUnder(downloadsRoot)) this.forget(id)- await this.removeVerified(downloadsRoot)- await fs.mkdir(downloadsRoot, { mode: 0o700 })- await verifyPrivateStoreDirectory(downloadsRoot)- }-- private idsUnder(downloadsRoot: string): string[] {- return [...this.entries.values()]- .filter(entry => path.dirname(entry.directory) === downloadsRoot)- .map(entry => entry.id)- }-- private async assertPhysicalCapacity(sizeBytes: number): Promise<void> {- const space = await fs.statfs(this.hostRoot, { bigint: true })- if (space.bsize <= 0n || space.bavail < 0n) {- recordGfsDownloadQuota('host', 'free_space')- throw new GfsDownloadStoreError('host_quota_exceeded')- }- const reserve = (bytes: number): bigint => {- const amount = BigInt(bytes)- return ((amount + space.bsize - 1n) / space.bsize) * space.bsize- }- let required = reserve(sizeBytes) + FREE_SPACE_RESERVE_BYTES- // Use the full outstanding reservation of every active transfer rather- // than crediting sparse, shared or concurrently written allocation.- for (const transfer of this.active.values()) required += reserve(transfer.sizeBytes)- if (space.bavail * space.bsize < required) {- recordGfsDownloadQuota('host', 'free_space')- throw new GfsDownloadStoreError('host_quota_exceeded')- }- }-- /** Caller usage is keyed by the caller directory that holds each copy, never by meta.json. */- private usage(excluded: ReadonlySet<string> = new Set()) {- const usage = {- bytes: 0,- files: 0,- callerBytes: new Map<string, number>(),- callerFiles: new Map<string, number>(),- }- const add = (callerRoot: string, sizeBytes: number) => {- usage.bytes += sizeBytes- usage.files += 1- usage.callerBytes.set(callerRoot, (usage.callerBytes.get(callerRoot) ?? 0) + sizeBytes)- usage.callerFiles.set(callerRoot, (usage.callerFiles.get(callerRoot) ?? 0) + 1)- }- for (const entry of this.entries.values())- if (!excluded.has(entry.id)) add(entry.callerRoot, entry.sizeBytes)- for (const transfer of this.active.values()) add(transfer.callerRoot, transfer.sizeBytes)- return usage- }-- private quotaDenial(- callerRoot: string,- sizeBytes: number,- excluded?: ReadonlySet<string>- ): { scope: 'host' | 'caller'; reason: 'storage_bytes' | 'retained_files' } | undefined {- const usage = this.usage(excluded)- // Prove caller admission before considering eviction of another caller.- if ((usage.callerBytes.get(callerRoot) ?? 0) + sizeBytes > GFS_FILE_LIMITS.callerStorageBytes)- return { scope: 'caller', reason: 'storage_bytes' }- if ((usage.callerFiles.get(callerRoot) ?? 0) >= GFS_FILE_LIMITS.callerRetainedFiles)- return { scope: 'caller', reason: 'retained_files' }- if (usage.bytes + sizeBytes > GFS_FILE_LIMITS.storageBytes)- return { scope: 'host', reason: 'storage_bytes' }- if (usage.files >= GFS_HOST_RETAINED_FILES) return { scope: 'host', reason: 'retained_files' }- return undefined- }-- /**- * Completed, unpinned copies are a cache. The whole eviction plan is computed- * before anything is deleted: adopted copies first, so files planted in one- * directory can never cost another caller a copy this process published,- * then published copies least recently used first. A caller denial evicts- * only copies in that caller's directory. With no feasible plan nothing is- * deleted and the admission fails with the quota code; nothing is retained,- * so the next admission plans again. Candidates are not hashed: a corrupt- * copy is as good an eviction candidate as a sound one.- */- private async reclaimForAdmission(callerRoot: string, sizeBytes: number): Promise<void> {- if (!this.quotaDenial(callerRoot, sizeBytes)) return- const candidates = [...this.entries.values()]- .filter(entry => !this.isPinned(entry.id))- .sort(evictionOrder)- const plan = new Set<string>()- for (;;) {- const denial = this.quotaDenial(callerRoot, sizeBytes, plan)- if (!denial) break- const next = candidates.find(- entry => !plan.has(entry.id) && (denial.scope === 'host' || entry.callerRoot === callerRoot)- )- if (!next) return- plan.add(next.id)- }- for (const id of plan) {- const entry = this.entries.get(id)- if (entry) await this.removeEntry(entry, 'expired_removed', false)- }- }-- /** Removes an indexed entry's directory and forgets it. */- private async removeEntry(- entry: Entry,- outcome: 'incomplete_removed' | 'expired_removed',- count = true- ): Promise<void> {- this.forget(entry.id)- await this.removeDirectory(entry.directory, count ? outcome : undefined)- }-- /**- * `fs.rm` does not follow the final component, but it resolves every parent- * component, so a caller directory or `.gfs-downloads` replaced by a symlink- * after indexing would point the removal outside the Host root. The parent- * must therefore be its own real path inside the Host root, and the- * directory must be gone afterwards. A refusal or a failure is logged with- * its code and counted; the next sweep retries what is still listed.- */- private async removeDirectory(- directory: string,- outcome: 'incomplete_removed' | 'expired_removed' | undefined- ): Promise<boolean> {- try {- await this.removeVerified(directory)- } catch (error) {- recordGfsDownloadExpiry('remove_failed')- logger.warn(- { component: GFS_DOWNLOAD_STORE_LOG_COMPONENT, code: errorCode(error) },- 'GFS download store could not remove a download directory; the next sweep retries it'- )- return false- }- if (outcome) recordGfsDownloadExpiry(outcome)- return true- }-- /**- * Node has no unlinkat/renameat, so the window between a path check and a- * path-based removal cannot be closed, only narrowed. The entry is first- * renamed to a store-private name inside its verified parent; the parent is- * then verified again, and only that private name is removed. When the- * parent moved in between, the rename is undone and the removal refused,- * so whatever the swapped path led to keeps its name and content.- */- private async removeVerified(directory: string): Promise<void> {- await this.assertRemovable(directory)- const trash = path.join(path.dirname(directory), `${TRASH_PREFIX}${randomUUID()}`)- try {- await fs.rename(directory, trash)- } catch (error) {- if (errorCode(error) !== 'ENOENT') throw error- await assertAbsent(directory)- return- }- try {- await this.assertRemovable(trash)- } catch (error) {- await fs.rename(trash, directory)- throw error- }- await fs.rm(trash, { recursive: true, force: true })- await assertAbsent(trash)- }-- /** The parent of a directory about to be removed is real and inside the Host root. */- private async assertRemovable(directory: string): Promise<void> {- const parent = path.dirname(directory)- if (!isWithinDirectory(parent, this.hostRoot))- throw new GfsDownloadStoreError('workspace_unavailable')- let real: string- try {- real = await fs.realpath(parent)- } catch (error) {- // No parent, nothing to remove: `fs.rm` with `force` is a no-op.- if (errorCode(error) === 'ENOENT') return- throw error- }- if (real !== parent) throw new GfsDownloadStoreError('workspace_unavailable')- }-- private reportSweepFailure(error: unknown): void {- recordGfsDownloadExpiry('sweep_failed')- logger.warn(- { component: GFS_DOWNLOAD_STORE_LOG_COMPONENT, code: errorCode(error) },- 'GFS download store could not list a download directory; the next sweep retries it'- )- }-- private receiptFor(entry: Entry, source: GfsImageSource): GfsDownloadReceipt {- return {- id: entry.id,- source,- path: receiptPath(entry.id),- sizeBytes: entry.sizeBytes,- sha256: entry.sha256,- expiresAt: entry.expiresAt,- }- }-- /** A malformed owner id is refused; pins are per caller, so no id is taken. */- private assertReceiptOwner(ownerId: string): void {- if (!validReceiptOwnerId(ownerId)) throw new GfsDownloadStoreError('caller_mismatch')- }-- private pin(ownerId: string, callerIdentity: string, id: string): void {- const key = pinKey(callerIdentity, ownerId)- const ids = this.pins.get(key) ?? new Set<string>()- ids.add(id)- this.pins.set(key, ids)- }-- private isPinned(id: string): boolean {- for (const ids of this.pins.values()) if (ids.has(id)) return true- return false- }-- private unpinId(id: string): void {- for (const [key, ids] of this.pins) {- ids.delete(id)- if (ids.size === 0) this.pins.delete(key)- }- }-- private forget(id: string): void {- this.entries.delete(id)- this.unpinId(id)- }-- private addActive(transfer: ActiveTransfer): void {- this.active.set(transfer.id, transfer)- this.activeByCaller.set(- transfer.callerIdentity,- (this.activeByCaller.get(transfer.callerIdentity) ?? 0) + 1- )- }-- private releaseActive(id: string): void {- const transfer = this.active.get(id)- if (!transfer) return- this.active.delete(id)- const current = this.activeByCaller.get(transfer.callerIdentity) ?? 0- if (current <= 1) this.activeByCaller.delete(transfer.callerIdentity)- else this.activeByCaller.set(transfer.callerIdentity, current - 1)- if (this.active.size === 0) {- const waiters = this.drainWaiters- this.drainWaiters = []- for (const resolve of waiters) resolve()- }- }-- private async validateCallerRoot(callerRoot: string): Promise<string> {- const lexical = path.resolve(callerRoot)- const expected = isWithinDirectory(lexical, this.hostRoot)- ? lexical- : isWithinDirectory(lexical, this.requestedHostRoot)- ? path.join(this.hostRoot, path.relative(this.requestedHostRoot, lexical))- : undefined- if (expected === undefined) throw new GfsDownloadStoreError('workspace_unavailable')- const real = await fs.realpath(lexical).catch(() => {- throw new GfsDownloadStoreError('workspace_unavailable')- })- if (real !== expected || !isWithinDirectory(real, await fs.realpath(this.hostRoot)))- throw new GfsDownloadStoreError('workspace_unavailable')- const info = await fs.lstat(real)- if (!info.isDirectory() || info.isSymbolicLink())- throw new GfsDownloadStoreError('workspace_unavailable')- return real- }-- private async serialize<T>(operation: () => Promise<T>): Promise<T> {- const previous = this.mutationTail- let unlock!: () => void- this.mutationTail = new Promise<void>(resolve => {- unlock = resolve- })- await previous- try {- return await operation()- } finally {- unlock()- }- }-- private assertPublicationOpen(publication?: { signal?: AbortSignal; deadlineMs?: number }): void {- if (- publication?.signal?.aborted ||- (publication?.deadlineMs !== undefined && Date.now() >= publication.deadlineMs)- )- throw new GfsDownloadStoreError('publication_cancelled')- }-- /** Not initialized: workspace_unavailable. Closed: download_busy. */- private assertInitialized(): void {- if (this.closed) throw new GfsDownloadStoreError('download_busy')- if (!this.initialized) throw new GfsDownloadStoreError('workspace_unavailable')- }-- private assertReadable(): void {- this.assertInitialized()- }-- /** Admission also stops while close() drains. */- private assertAdmitting(): void {- this.assertInitialized()- if (this.closing) throw new GfsDownloadStoreError('download_busy')- }-}diff --git a/mcp-host/src/internalTools/gfsDownloadStoreMetrics.test.ts b/mcp-host/src/internalTools/gfsDownloadStoreMetrics.test.tsdeleted file mode 100644index e095a2fed..000000000--- a/mcp-host/src/internalTools/gfsDownloadStoreMetrics.test.ts+++ /dev/null@@ -1,110 +0,0 @@-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'-import { createHash } from 'node:crypto'-import * as fs from 'node:fs/promises'-import { tmpdir } from 'node:os'-import * as path from 'node:path'-import { register } from 'prom-client'-import { GfsDownloadStore } from './gfsDownloadStore'--let root: string-let callerRoot: string-let store: GfsDownloadStore-const source = {- kind: 'gfs' as const,- drive: 'main',- resourceId: 'a'.repeat(32),- gfsUri: `gfs://main/${'a'.repeat(32)}`,- name: 'input.csv',- version: 7,-}--beforeEach(async () => {- root = await fs.mkdtemp(path.join(tmpdir(), 'gfs-store-metrics-'))- callerRoot = path.join(root, 'users', 'caller-a')- await fs.mkdir(callerRoot, { recursive: true, mode: 0o700 })- store = new GfsDownloadStore(root)- await store.initialize()-})-afterEach(async () => {- vi.restoreAllMocks()- await store.close(0).catch(async () => {- await (- store as unknown as { writerLease?: { release(): Promise<void> } }- ).writerLease?.release()- })- await fs.rm(root, { recursive: true, force: true })-})-async function metric(name: string, labels: Record<string, string>): Promise<number> {- const data = await register.getSingleMetric(name)!.get()- return (- data.values.find(value =>- Object.entries(labels).every(([key, expected]) => value.labels[key] === expected)- )?.value ?? 0- )-}-async function completed() {- const transfer = await store.createTransfer({- callerIdentity: 'caller-a',- callerWorkspacePath: callerRoot,- source,- sizeBytes: 7,- expiresAt: new Date(Date.now() + 60_000).toISOString(),- })- await fs.writeFile(path.join(callerRoot, transfer.partialPath), 'fixture')- return store.publish(- transfer.id,- 'caller-a',- createHash('sha256').update('fixture').digest('hex')- )-}--describe('GFS store decision metrics', () => {- it('records the actual caller concurrency rejection with fixed labels', async () => {- const name = 'clerum_gfs_download_quota_total'- const labels = { scope: 'caller', reason: 'active_downloads' }- const before = await metric(name, labels)- const input = {- callerIdentity: 'caller-a',- callerWorkspacePath: callerRoot,- source,- sizeBytes: 7,- expiresAt: new Date(Date.now() + 60_000).toISOString(),- }- const transfer = await store.createTransfer(input)- await expect(store.createTransfer(input)).rejects.toMatchObject({ code: 'download_busy' })- expect(await metric(name, labels)).toBe(before + 1)- await store.fail(transfer.id, 'caller-a')- })-- it.each(['removed', 'failed'] as const)(- 'records actual expired-directory cleanup (%s)',- async outcome => {- const receipt = await completed()- const name = 'clerum_gfs_download_expiry_total'- const labels = { outcome: outcome === 'removed' ? 'expired_removed' : 'cleanup_failed' }- const before = await metric(name, labels)- if (outcome === 'failed') {- await fs.rm(path.join(callerRoot, '.gfs-downloads'), { recursive: true, force: true })- await fs.writeFile(path.join(callerRoot, '.gfs-downloads'), 'not-a-directory')- }- await store.cleanupExpired(Date.parse(receipt.expiresAt) + 1)- expect(await metric(name, labels)).toBe(before + 1)- expect(store.debugUsage().bytes).toBe(outcome === 'removed' ? 0 : 7)- }- )-- it('records a failed sweep while retaining the uncertain durable charge', async () => {- const receipt = await completed()- const name = 'clerum_gfs_download_expiry_total'- const labels = { outcome: 'sweep_failed' }- const before = await metric(name, labels)- vi.spyOn(store as unknown as { persist(): Promise<void> }, 'persist').mockRejectedValueOnce(- new Error('journal unavailable')- )- await expect(store.cleanupExpired(Date.parse(receipt.expiresAt) + 1)).rejects.toThrow(- 'journal unavailable'- )- expect(await metric(name, labels)).toBe(before + 1)- expect(store.debugUsage().bytes).toBe(7)- })-})diff --git a/mcp-host/src/internalTools/gfsDownloadStoreProvenance.test.ts b/mcp-host/src/internalTools/gfsDownloadStoreProvenance.test.tsindex ddb88f844..0ba8bc06a 100644--- a/mcp-host/src/internalTools/gfsDownloadStoreProvenance.test.ts+++ b/mcp-host/src/internalTools/gfsDownloadStoreProvenance.test.ts@@ -27,7 +27,7 @@ import {withEnvironment,} from '../__tests__/fixtures/gfsStoreTestKit'import { logger } from '../logger'-import { GfsDownloadStoreFs } from './gfsDownloadStoreFs'+import { GfsDownloadStore } from './gfsDownloadStore'const { hashBoundary } = vi.hoisted(() => ({ hashBoundary: vi.fn() }))// Pass-through: the store hashes through createHash; the kit uses crypto.hash.@@ -44,8 +44,8 @@ let nativeCrypto: typeof cryptolet hostRoot: stringlet rootA: stringlet rootB: string-let store: GfsDownloadStoreFs-const extraStores: GfsDownloadStoreFs[] = []+let store: GfsDownloadStore+const extraStores: GfsDownloadStore[] = []const outsideRoots: string[] = []function receiptPathOf(id: string): string {@@ -68,8 +68,8 @@ function plantComplete(})}-async function openStore(): Promise<GfsDownloadStoreFs> {- const opened = new GfsDownloadStoreFs(hostRoot)+async function openStore(): Promise<GfsDownloadStore> {+ const opened = new GfsDownloadStore(hostRoot)extraStores.push(opened)await opened.initialize()return opened@@ -81,7 +81,7 @@ function outsideDirectory(): string {return outside}-async function expectNotServed(target: GfsDownloadStoreFs, id: string, identity: string) {+async function expectNotServed(target: GfsDownloadStore, id: string, identity: string) {await expect(target.readManagedFile(receiptPathOf(id), identity)).rejects.toMatchObject({code: 'download_missing',})@@ -106,7 +106,7 @@ beforeEach(async () => {hostRoot = syncFs.mkdtempSync(path.join(tmpdir(), 'gfs-store-provenance-'))rootA = callerDirectory(hostRoot, A)rootB = callerDirectory(hostRoot, B)- store = new GfsDownloadStoreFs(hostRoot)+ store = new GfsDownloadStore(hostRoot)await store.initialize()})@@ -187,9 +187,9 @@ describe('GFS download store provenance: planted copies', () => {},async () => {vi.resetModules()- const { GfsDownloadStoreFs: Store } = await import('./gfsDownloadStoreFs')+ const { GfsDownloadStore: Store } = await import('./gfsDownloadStore')const opened = new Store(hostRoot)- extraStores.push(opened as unknown as GfsDownloadStoreFs)+ extraStores.push(opened as unknown as GfsDownloadStore)await opened.initialize()return opened}diff --git a/mcp-host/src/internalTools/gfsDownloadStoreRecovery.test.ts b/mcp-host/src/internalTools/gfsDownloadStoreRecovery.test.tsdeleted file mode 100644index bfd0c30be..000000000--- a/mcp-host/src/internalTools/gfsDownloadStoreRecovery.test.ts+++ /dev/null@@ -1,1016 +0,0 @@-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'-import { type ChildProcess, spawn } from 'node:child_process'-import { createHash } from 'node:crypto'-import { constants } from 'node:fs'-import * as fs from 'node:fs/promises'-import type { FileHandle } from 'node:fs/promises'-import { tmpdir } from 'node:os'-import * as path from 'node:path'-import { register } from 'prom-client'-import { ShellTool } from '../core/tools/shell'-import { logger } from '../logger'-import type { GfsImageSource } from '../visualInput/policy'-import { GfsDownloadStore } from './gfsDownloadStore'--const source: GfsImageSource = {- kind: 'gfs',- drive: 'main',- resourceId: 'a'.repeat(32),- gfsUri: `gfs://main/${'a'.repeat(32)}`,- name: 'input.csv',- version: 7,-}-const storeModule = path.join(__dirname, 'gfsDownloadStore.ts')-const childProgram = `-const fs = require('node:fs');-const ts = require('typescript');-require.extensions['.ts'] = (module, filename) => {- const content = ts.transpileModule(fs.readFileSync(filename, 'utf8'), {- compilerOptions: { target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.CommonJS, esModuleInterop: true }- }).outputText;- module._compile(content, filename);-};-const { GfsDownloadStore } = require(process.argv[1]);-const path = require('node:path');-const { createHash } = require('node:crypto');-(async () => {- const root = process.argv[2];- const mode = process.argv[3];- const store = new GfsDownloadStore(root);- await store.initialize();- if (mode === 'pin' || mode === 'transfer') {- const callerRoot = path.join(root, 'users', 'caller-a');- fs.mkdirSync(callerRoot, { recursive: true, mode: 0o700 });- const bytes = Buffer.from('fixture');- const transfer = await store.createTransfer({ callerIdentity: 'caller-a', callerWorkspacePath: callerRoot,- source: ${JSON.stringify(source)}, sizeBytes: bytes.length, expiresAt: new Date(Date.now() + 60000).toISOString(),- retentionOwnerId: mode === 'pin' ? '11111111-1111-4111-8111-111111111111' : undefined });- if (mode === 'transfer') {- // The Host dies here, mid-transfer: the record stays 'transferring'.- process.send({ transferId: transfer.id });- setInterval(() => {}, 1000);- return;- }- fs.writeFileSync(path.join(callerRoot, transfer.partialPath), bytes);- const receipt = await store.publish(transfer.id, 'caller-a', createHash('sha256').update(bytes).digest('hex'));- await store.reusableReceipt('caller-a', ${JSON.stringify(source)}, 7, { retentionOwnerId: '22222222-2222-4222-8222-222222222222' });- process.send({ receipt });- } else process.send({ ready: true });- setInterval(() => {}, 1000);-})().catch(error => { process.send({ error: error.code || String(error), transientWriterContention: error.transientWriterContention === true }); process.exit(1); });-`--let root: string-let stores: GfsDownloadStore[]-let children: ChildProcess[]-let executors: number[]-beforeEach(async () => {- root = await fs.mkdtemp(path.join(tmpdir(), 'gfs-store-recovery-'))- stores = []- children = []- executors = []-})-afterEach(async () => {- for (const pid of executors) {- try {- process.kill(-pid, 'SIGKILL')- } catch {- /* fixture exited */- }- }- for (const child of children) {- if (child.exitCode === null && child.signalCode === null) await kill(child)- }- for (const store of stores) await store.close(1).catch(() => undefined)- await fs.rm(root, { recursive: true, force: true })-})-function kill(child: ChildProcess, signal: NodeJS.Signals = 'SIGKILL'): Promise<void> {- return new Promise(resolve => {- child.once('exit', () => resolve())- child.kill(signal)- })-}-async function childStore(mode = 'hold'): Promise<{ child: ChildProcess; message: any }> {- const child = spawn(process.execPath, ['-e', childProgram, storeModule, root, mode], {- cwd: path.resolve(__dirname, '../..'),- stdio: ['ignore', 'ignore', 'pipe', 'ipc'],- })- children.push(child)- const message = await new Promise<any>((resolve, reject) => {- let errors = ''- child.stderr?.on('data', chunk => {- errors += String(chunk)- })- child.once('message', resolve)- child.once('error', reject)- child.once('exit', code => {- if (code !== 0) reject(new Error(errors || `child exit ${code}`))- })- })- return { child, message }-}-function freshStore(): GfsDownloadStore {- const store = new GfsDownloadStore(root)- stores.push(store)- return store-}-async function fixture(- store: GfsDownloadStore,- retentionOwnerId?: string,- fixtureSource: GfsImageSource = source-) {- const callerRoot = path.join(root, 'users', 'caller-a')- await fs.mkdir(callerRoot, { recursive: true, mode: 0o700 })- const transfer = await store.createTransfer({- callerIdentity: 'caller-a',- callerWorkspacePath: callerRoot,- source: fixtureSource,- sizeBytes: 7,- expiresAt: new Date(Date.now() + 60_000).toISOString(),- retentionOwnerId,- })- await fs.writeFile(path.join(callerRoot, transfer.partialPath), 'fixture')- return store.publish(- transfer.id,- 'caller-a',- createHash('sha256').update('fixture').digest('hex')- )-}--const DISCARDED_COUNTER = 'clerum_gfs_legacy_processing_leases_discarded_total'-const QUARANTINED_GAUGE = 'clerum_gfs_download_store_quarantined_records'-const FOREIGN_WRITER_SESSION = '33333333-3333-4333-8333-333333333333'-const LEGACY_LEASE_ID = '44444444-4444-4444-8444-444444444444'-const otherSource: GfsImageSource = {- ...source,- resourceId: 'b'.repeat(32),- gfsUri: `gfs://main/${'b'.repeat(32)}`,- name: 'other.csv',-}--function ledgerFile(): string {- return path.join(root, '.gfs-download-store', 'ledger-v1.json')-}--async function counterValue(name: string): Promise<number> {- const metric = register.getSingleMetric(name)- if (metric === undefined) throw new Error(`metric ${name} is not registered`)- const { values } = await metric.get()- return values.reduce((sum, sample) => sum + sample.value, 0)-}--/** A processing lease exactly as a pre-#1019 Host wrote it, by default expired and empty. */-function legacyLease(overrides: Record<string, unknown> = {}): Record<string, unknown> {- return {- leaseId: LEGACY_LEASE_ID,- callerIdentity: 'caller-a',- recordIds: [],- acquiredAt: new Date(Date.now() - 120_000).toISOString(),- expiresAt: new Date(Date.now() - 60_000).toISOString(),- writerSessionId: FOREIGN_WRITER_SESSION,- ...overrides,- }-}--/** Writes legacy leases into the ledger of a closed store, as an older build left them. */-async function seedLegacyLeases(leases: Record<string, unknown>[]): Promise<string> {- const ledger = JSON.parse(await fs.readFile(ledgerFile(), 'utf8'))- ledger.processingLeases = Object.fromEntries(leases.map(lease => [lease.leaseId, lease]))- const raw = JSON.stringify(ledger)- await fs.writeFile(ledgerFile(), raw, { mode: 0o600 })- return raw-}--async function closedStore(): Promise<void> {- const store = freshStore()- await store.initialize()- await store.close()-}--function discardWarnings(calls: unknown[][]): unknown[][] {- return calls.filter(- call => typeof call[1] === 'string' && call[1].includes('legacy processing lease')- )-}--describe('legacy processing leases after #1019', () => {- afterEach(() => {- vi.restoreAllMocks()- })-- it('S1: discards an expired foreign-session lease left by a crashed Host and admits downloads', async () => {- await closedStore()- await seedLegacyLeases([legacyLease()])- const warn = vi.spyOn(logger, 'warn')- const before = await counterValue(DISCARDED_COUNTER)- const reopened = freshStore()- await reopened.initialize()- // The persisted discard is the claim; the counter and the log follow it.- const onDisk = JSON.parse(await fs.readFile(ledgerFile(), 'utf8'))- expect(onDisk.records).toEqual({})- expect(onDisk).not.toHaveProperty('processingLeases')- expect((await counterValue(DISCARDED_COUNTER)) - before).toBe(1)- expect(discardWarnings(warn.mock.calls)).toEqual([- [- { component: 'GfsDownloadStore', discarded: 1 },- 'GFS download store discarded 1 legacy processing lease(s) at initialize',- ],- ])- expect(reopened.isAvailable()).toBe(true)- const receipt = await fixture(reopened)- expect(reopened.debugRecord(receipt.id)?.state).toBe('completed')- expect(reopened.debugUsage()).toMatchObject({ bytes: 7, files: 1 })- })-- it('S1b: discards a non-expired foreign-session lease left by a crashed Host and admits downloads', async () => {- await closedStore()- const raw = await seedLegacyLeases([- legacyLease({ expiresAt: new Date(Date.now() + 600_000).toISOString() }),- ])- // Witness: the seeded lease is still live by its own expiry, so the discard- // below cannot be explained by expiry.- const seeded = JSON.parse(raw).processingLeases[LEGACY_LEASE_ID]- expect(Date.parse(seeded.expiresAt)).toBeGreaterThan(Date.now())- const warn = vi.spyOn(logger, 'warn')- const before = await counterValue(DISCARDED_COUNTER)- const reopened = freshStore()- await reopened.initialize()- const onDisk = JSON.parse(await fs.readFile(ledgerFile(), 'utf8'))- expect(onDisk.records).toEqual({})- expect(onDisk).not.toHaveProperty('processingLeases')- expect((await counterValue(DISCARDED_COUNTER)) - before).toBe(1)- expect(discardWarnings(warn.mock.calls)).toEqual([- [- { component: 'GfsDownloadStore', discarded: 1 },- 'GFS download store discarded 1 legacy processing lease(s) at initialize',- ],- ])- expect(reopened.isAvailable()).toBe(true)- const receipt = await fixture(reopened)- expect(reopened.debugRecord(receipt.id)?.state).toBe('completed')- expect(reopened.debugUsage()).toMatchObject({ bytes: 7, files: 1 })- })-- it('S1c: discards several legacy leases from different foreign sessions in one initialize and counts each', async () => {- const store = freshStore()- await store.initialize()- const protectedReceipt = await fixture(store)- await store.close()- const leaseIds = [- '55555555-5555-4555-8555-555555555551',- '55555555-5555-4555-8555-555555555552',- '55555555-5555-4555-8555-555555555553',- ]- const sessions = [- '66666666-6666-4666-8666-666666666661',- '66666666-6666-4666-8666-666666666662',- '66666666-6666-4666-8666-666666666663',- ]- const raw = await seedLegacyLeases([- // Expired, protecting the completed record.- legacyLease({- leaseId: leaseIds[0],- writerSessionId: sessions[0],- recordIds: [protectedReceipt.id],- }),- // Not expired, protecting the same record.- legacyLease({- leaseId: leaseIds[1],- writerSessionId: sessions[1],- recordIds: [protectedReceipt.id],- expiresAt: new Date(Date.now() + 600_000).toISOString(),- }),- // Not expired, protecting no record.- legacyLease({- leaseId: leaseIds[2],- writerSessionId: sessions[2],- expiresAt: new Date(Date.now() + 600_000).toISOString(),- }),- ])- // Witness: the ledger the store reads carries three leases from three- // distinct foreign sessions, one expired and two still live.- const seeded = Object.values(JSON.parse(raw).processingLeases) as Array<{- writerSessionId: string- expiresAt: string- }>- expect(seeded).toHaveLength(3)- expect(new Set(seeded.map(lease => lease.writerSessionId)).size).toBe(3)- expect(seeded.filter(lease => Date.parse(lease.expiresAt) > Date.now())).toHaveLength(2)- const warn = vi.spyOn(logger, 'warn')- const before = await counterValue(DISCARDED_COUNTER)- const reopened = freshStore()- await reopened.initialize()- const onDisk = JSON.parse(await fs.readFile(ledgerFile(), 'utf8'))- expect(onDisk).not.toHaveProperty('processingLeases')- expect(Object.keys(onDisk.records)).toEqual([protectedReceipt.id])- expect((await counterValue(DISCARDED_COUNTER)) - before).toBe(3)- expect(discardWarnings(warn.mock.calls)).toEqual([- [- { component: 'GfsDownloadStore', discarded: 3 },- 'GFS download store discarded 3 legacy processing lease(s) at initialize',- ],- ])- expect(reopened.isAvailable()).toBe(true)- expect(reopened.debugRecord(protectedReceipt.id)?.state).toBe('completed')- const receipt = await fixture(reopened, undefined, otherSource)- expect(reopened.debugRecord(receipt.id)?.state).toBe('completed')- expect(reopened.debugUsage()).toMatchObject({ bytes: 14, files: 2 })- })-- it('S2:re-verifies records a discarded lease protected, reusing the intact copy and quarantining the altered one', async () => {- const store = freshStore()- await store.initialize()- const intact = await fixture(store)- const altered = await fixture(store, undefined, otherSource)- await store.close()- await seedLegacyLeases([- legacyLease({- recordIds: [intact.id, altered.id],- expiresAt: new Date(Date.now() + 600_000).toISOString(),- }),- ])- await fs.writeFile(path.join(root, 'users', 'caller-a', altered.path), 'changed')- const before = await counterValue(DISCARDED_COUNTER)- const reopened = freshStore()- await reopened.initialize()- const onDisk = JSON.parse(await fs.readFile(ledgerFile(), 'utf8'))- expect(onDisk).not.toHaveProperty('processingLeases')- expect(Object.keys(onDisk.records).sort()).toEqual([intact.id, altered.id].sort())- expect((await counterValue(DISCARDED_COUNTER)) - before).toBe(1)- expect(reopened.isAvailable()).toBe(true)- expect(await reopened.reusableReceipt('caller-a', source, 7)).toMatchObject({- id: intact.id,- sha256: intact.sha256,- })- expect(reopened.debugRecord(intact.id)?.state).toBe('completed')- expect(reopened.debugRecord(altered.id)?.state).toBe('quarantined')- expect(await reopened.reusableReceipt('caller-a', otherSource, 7)).toBeUndefined()- })-- it.each([- ['a lease id that is not a UUID', { leaseId: 'not-a-uuid' }],- [- 'an expiry that does not follow acquisition',- { acquiredAt: '2026-01-01T00:00:00.000Z', expiresAt: '2026-01-01T00:00:00.000Z' },- ],- ])(- 'S3: fails closed on a malformed legacy lease (%s) without touching the ledger',- async (_label, overrides) => {- await closedStore()- const raw = await seedLegacyLeases([legacyLease(overrides)])- const before = await counterValue(DISCARDED_COUNTER)- await expect(freshStore().initialize()).rejects.toMatchObject({- code: 'corrupt_store_ledger',- })- expect(await fs.readFile(ledgerFile(), 'utf8')).toBe(raw)- expect((await counterValue(DISCARDED_COUNTER)) - before).toBe(0)- }- )-- it('S4: a clean restart discards nothing', async () => {- const store = freshStore()- await store.initialize()- await fixture(store)- await store.close()- const warn = vi.spyOn(logger, 'warn')- const before = await counterValue(DISCARDED_COUNTER)- const reopened = freshStore()- await reopened.initialize()- expect(reopened.isAvailable()).toBe(true)- expect(reopened.debugUsage()).toMatchObject({ bytes: 7, files: 1 })- const onDisk = JSON.parse(await fs.readFile(ledgerFile(), 'utf8'))- expect(onDisk).not.toHaveProperty('processingLeases')- expect(Object.keys(onDisk.records)).toHaveLength(1)- expect((await counterValue(DISCARDED_COUNTER)) - before).toBe(0)- expect(discardWarnings(warn.mock.calls)).toEqual([])- })-- // Store behaviour only: this shell has no store reference, so the test shows- // that close() is unaffected by a concurrent shell run. Decoupling of the- // shell from the store is proven by the TaskExecutor-level X3-TE test.- it('S5: close() is blocked only by its own transfers and is unaffected by a concurrent shell run', async () => {- const store = freshStore()- await store.initialize()- const callerRoot = path.join(root, 'users', 'caller-a')- await fs.mkdir(callerRoot, { recursive: true, mode: 0o700 })- const transfer = await store.createTransfer({- callerIdentity: 'caller-a',- callerWorkspacePath: callerRoot,- source,- sizeBytes: 7,- expiresAt: new Date(Date.now() + 60_000).toISOString(),- })- await expect(store.close(0)).rejects.toMatchObject({ code: 'download_busy' })- expect(store.isAvailable()).toBe(true)- await store.fail(transfer.id, 'caller-a')-- const shell = new ShellTool(callerRoot, 30_000, ['PATH'], () => ({}), undefined, true)- const controller = new AbortController()- const pidFile = path.join(callerRoot, 'shell.pid')- const running = shell.execute(- { command: `echo $$ > ${JSON.stringify(pidFile)}; exec sleep 30` },- { signal: controller.signal, onOutput: () => undefined }- )- let pid = ''- for (const deadline = Date.now() + 5_000; pid === '' && Date.now() < deadline; ) {- pid = (await fs.readFile(pidFile, 'utf8').catch(() => '')).trim()- if (pid === '') await new Promise(resolve => setTimeout(resolve, 10))- }- expect(pid).toMatch(/^[0-9]+$/)- await store.close(0)- expect(store.isAvailable()).toBe(false)- // Witness: the shell was still running when close() resolved.- expect(() => process.kill(Number(pid), 0)).not.toThrow()- controller.abort()- const result = await running- expect(result.is_error).toBe(true)- })-- it('S8: a discard whose persist fails before the rename leaves the ledger byte-identical and is retried by the next initialize', async () => {- await closedStore()- const raw = await seedLegacyLeases([legacyLease()])- const probe = await fs.open(ledgerFile(), 'r')- const prototype = Object.getPrototypeOf(probe) as FileHandle- await probe.close()- const originalWriteFile = prototype.writeFile- // The real persist runs; only the temporary-ledger write of the discard- // fails, before the rename can make anything visible.- let failedLedgerWrite: Record<string, unknown> | undefined- vi.spyOn(prototype, 'writeFile').mockImplementation(async function (- this: FileHandle,- ...args: Parameters<FileHandle['writeFile']>- ) {- const [data] = args- if (failedLedgerWrite === undefined && typeof data === 'string') {- const written = JSON.parse(data) as Record<string, unknown>- if ('records' in written && !('processingLeases' in written)) {- failedLedgerWrite = written- throw Object.assign(new Error('injected ledger write failure'), { code: 'EIO' })- }- }- return originalWriteFile.apply(this, args)- })- const warn = vi.spyOn(logger, 'warn')- const before = await counterValue(DISCARDED_COUNTER)- const interrupted = freshStore()- const privateStore = interrupted as unknown as {- ledger: { processingLeases?: Record<string, unknown> }- reconcile: () => Promise<void>- }- const reconcile = vi.spyOn(privateStore, 'reconcile')- await expect(interrupted.initialize()).rejects.toThrow('injected ledger write failure')- // Witness: the failing write is the discard's own lease-free ledger, and- // initialize stopped before reconcile.- expect(failedLedgerWrite).toBeDefined()- expect(failedLedgerWrite).not.toHaveProperty('processingLeases')- expect(reconcile).not.toHaveBeenCalled()- expect(privateStore.ledger.processingLeases?.[LEGACY_LEASE_ID]).toBeDefined()- expect(interrupted.isAvailable()).toBe(false)- expect(await fs.readFile(ledgerFile(), 'utf8')).toBe(raw)- expect(JSON.parse(raw).processingLeases[LEGACY_LEASE_ID]).toBeDefined()- expect((await counterValue(DISCARDED_COUNTER)) - before).toBe(0)- expect(discardWarnings(warn.mock.calls)).toEqual([- [- { component: 'GfsDownloadStore', legacyProcessingLeases: 1, outcome: 'unknown' },- 'GFS download store could not confirm the discard of 1 legacy processing lease(s) at initialize; the discard may already be visible on disk because the persist can fail after the ledger rename',- ],- ])-- const retried = freshStore()- await retried.initialize()- expect(retried.isAvailable()).toBe(true)- expect(JSON.parse(await fs.readFile(ledgerFile(), 'utf8'))).not.toHaveProperty(- 'processingLeases'- )- expect((await counterValue(DISCARDED_COUNTER)) - before).toBe(1)- expect(- discardWarnings(warn.mock.calls).filter(- call =>- JSON.stringify(call[0]) ===- JSON.stringify({ component: 'GfsDownloadStore', discarded: 1 })- )- ).toHaveLength(1)- })-- it('S8b: a discard whose directory sync fails after the rename warns with an unknown outcome and does not count the discard', async () => {- await closedStore()- await seedLegacyLeases([legacyLease()])- const storeDirectory = await fs.stat(path.join(root, '.gfs-download-store'))- const probe = await fs.open(ledgerFile(), 'r')- const prototype = Object.getPrototypeOf(probe) as FileHandle- await probe.close()- const originalSync = prototype.sync- let injected = 0- // Only the store-directory fsync that follows the ledger rename fails: the- // writer lease also syncs this directory, but before the discard the- // visible ledger still carries the legacy lease.- vi.spyOn(prototype, 'sync').mockImplementation(async function (this: FileHandle) {- const info = await this.stat()- if (injected === 0 && info.isDirectory() && info.ino === storeDirectory.ino) {- const visible = JSON.parse(await fs.readFile(ledgerFile(), 'utf8'))- if (!('processingLeases' in visible)) {- injected += 1- throw Object.assign(new Error('injected directory sync failure'), { code: 'EIO' })- }- }- return originalSync.call(this)- })- const warn = vi.spyOn(logger, 'warn')- const before = await counterValue(DISCARDED_COUNTER)- const interrupted = freshStore()- await expect(interrupted.initialize()).rejects.toThrow('injected directory sync failure')- expect(injected).toBe(1)- expect(interrupted.isAvailable()).toBe(false)- // Witness that the rename happened: the visible ledger is already lease-free.- expect(JSON.parse(await fs.readFile(ledgerFile(), 'utf8'))).not.toHaveProperty(- 'processingLeases'- )- expect(discardWarnings(warn.mock.calls)).toEqual([- [- { component: 'GfsDownloadStore', legacyProcessingLeases: 1, outcome: 'unknown' },- 'GFS download store could not confirm the discard of 1 legacy processing lease(s) at initialize; the discard may already be visible on disk because the persist can fail after the ledger rename',- ],- ])- expect((await counterValue(DISCARDED_COUNTER)) - before).toBe(0)- })-- it('S9: reports the current quarantined-record count after reconcile without double counting across boots', async () => {- const { child, message } = await childStore('transfer')- expect(message.transferId).toMatch(/^[0-9a-f-]{36}$/)- await kill(child)- const warn = vi.spyOn(logger, 'warn')- const quarantineWarnings = () =>- warn.mock.calls.filter(- call =>- JSON.stringify(call[0]) ===- JSON.stringify({ component: 'GfsDownloadStore', quarantined: 1 })- )- const recovering = freshStore()- await recovering.initialize()- // The boot that quarantines the interrupted transfer reports it.- expect(recovering.debugRecord(message.transferId)?.state).toBe('quarantined')- expect(await counterValue(QUARANTINED_GAUGE)).toBe(1)- expect(quarantineWarnings()).toHaveLength(1)- await recovering.close()-- const next = freshStore()- await next.initialize()- // The same backlog on the next boot keeps the gauge at 1, not 2.- expect(next.debugRecord(message.transferId)?.state).toBe('quarantined')- expect(await counterValue(QUARANTINED_GAUGE)).toBe(1)- expect(quarantineWarnings()).toHaveLength(2)- expect(next.debugUsage().bytes).toBe(7)- })-- it('S10: a legacy lease next to a half-finished transfer: the lease is discarded and the transfer is quarantined in the same initialize', async () => {- const { child, message } = await childStore('transfer')- expect(message.transferId).toMatch(/^[0-9a-f-]{36}$/)- await kill(child)- const raw = await seedLegacyLeases([legacyLease({ recordIds: [message.transferId] })])- // Witness: the ledger the store reads carries both the lease and the- // interrupted transfer, whose host partial is still on disk.- const seeded = JSON.parse(raw)- expect(seeded.processingLeases[LEGACY_LEASE_ID].recordIds).toEqual([message.transferId])- const seededRecord = seeded.records[message.transferId]- expect(seededRecord.state).toBe('transferring')- const hostPartial = path.join(root, `${seededRecord.hostPath}.partial`)- expect((await fs.lstat(hostPartial)).isFile()).toBe(true)-- const warn = vi.spyOn(logger, 'warn')- const before = await counterValue(DISCARDED_COUNTER)- const recovering = freshStore()- await recovering.initialize()- expect(recovering.isAvailable()).toBe(true)- expect(recovering.debugRecord(message.transferId)?.state).toBe('quarantined')- expect(recovering.debugUsage().bytes).toBe(7)- expect((await counterValue(DISCARDED_COUNTER)) - before).toBe(1)- expect(await counterValue(QUARANTINED_GAUGE)).toBe(1)- expect(discardWarnings(warn.mock.calls)).toEqual([- [- { component: 'GfsDownloadStore', discarded: 1 },- 'GFS download store discarded 1 legacy processing lease(s) at initialize',- ],- ])- // The persisted ledger reflects both outcomes of the one initialize.- const persisted = await fs.readFile(ledgerFile(), 'utf8')- const onDisk = JSON.parse(persisted)- expect(onDisk).not.toHaveProperty('processingLeases')- expect(Object.keys(onDisk.records)).toEqual([message.transferId])- expect(onDisk.records[message.transferId].state).toBe('quarantined')- await recovering.close()-- // A second initialize finds nothing left to discard and rewrites nothing.- const secondBefore = await counterValue(DISCARDED_COUNTER)- const next = freshStore()- await next.initialize()- expect(next.isAvailable()).toBe(true)- expect(next.debugRecord(message.transferId)?.state).toBe('quarantined')- expect(next.debugUsage().bytes).toBe(7)- expect((await counterValue(DISCARDED_COUNTER)) - secondBefore).toBe(0)- expect(discardWarnings(warn.mock.calls)).toHaveLength(1)- await next.close()- expect(await fs.readFile(ledgerFile(), 'utf8')).toBe(persisted)- })-})--describe('first boot of a Host locked by a persistent-disk reattach (#1028)', () => {- afterEach(() => {- vi.restoreAllMocks()- })-- it('T7: recovers the store behind a stale-device v2 fence and keeps every record it must keep', async () => {- const owner = '55555555-5555-4555-8555-555555555555'- const thirdSource: GfsImageSource = {- ...source,- resourceId: 'c'.repeat(32),- gfsUri: `gfs://main/${'c'.repeat(32)}`,- name: 'third.csv',- }- const crashed = freshStore()- await crashed.initialize()- const reusable = await fixture(crashed)- const pinned = await fixture(crashed, owner, otherSource)- const callerRoot = path.join(root, 'users', 'caller-a')- const transfer = await crashed.createTransfer({- callerIdentity: 'caller-a',- callerWorkspacePath: callerRoot,- source: thirdSource,- sizeBytes: 7,- expiresAt: new Date(Date.now() + 60_000).toISOString(),- })- // The Host dies holding the writer; releasing the kernel connection models it.- await (- crashed as unknown as { writerLease: { release(): Promise<void> } }- ).writerLease.release()-- // An older build left a processing lease, and the pinned copy expired- // while the Host was locked.- const seededLedger = JSON.parse(await fs.readFile(ledgerFile(), 'utf8'))- seededLedger.records[pinned.id].expiresAt = new Date(Date.now() - 60_000).toISOString()- seededLedger.processingLeases = {- [LEGACY_LEASE_ID]: legacyLease({ recordIds: [transfer.id] }),- }- await fs.writeFile(ledgerFile(), JSON.stringify(seededLedger), { mode: 0o600 })- // The disk came back under another device node: the v2 fence keeps the- // inode and carries a stale device.- const storeRoot = path.join(await fs.realpath(root), '.gfs-download-store')- const database = await fs.stat(path.join(storeRoot, 'writer-v2.sqlite'), { bigint: true })- const staleDevice = String(database.dev + 1n)- const v2 = JSON.stringify({- schemaVersion: 2,- ownership: 'sqlite-exclusive-v1',- databaseDevice: staleDevice,- databaseInode: String(database.ino),- })- await fs.writeFile(path.join(storeRoot, 'writer.lock'), v2, { mode: 0o600 })- // Witness: the seeded store holds every state this boot has to handle.- expect(seededLedger.records[reusable.id].state).toBe('completed')- expect(seededLedger.records[pinned.id].state).toBe('completed')- expect(seededLedger.records[transfer.id].state).toBe('transferring')- expect(seededLedger.retentionOwners[owner].recordIds).toEqual([pinned.id])- const pinnedPath = path.join(callerRoot, pinned.path)- expect(await fs.readFile(pinnedPath, 'utf8')).toBe('fixture')-- const warn = vi.spyOn(logger, 'warn')- const info = vi.spyOn(logger, 'info')- const recovering = freshStore()- await recovering.initialize()-- expect(recovering.isAvailable()).toBe(true)- expect(- info.mock.calls.filter(call => call[1] === 'GFS writer fence v2 accepted with stale device')- ).toEqual([- [- {- component: 'GfsDownloadStore',- storedDevice: staleDevice,- currentDevice: String(database.dev),- },- 'GFS writer fence v2 accepted with stale device',- ],- ])- expect(await fs.readFile(path.join(storeRoot, 'writer.lock'), 'utf8')).toBe(v2)- expect(discardWarnings(warn.mock.calls)).toEqual([- [- { component: 'GfsDownloadStore', discarded: 1 },- 'GFS download store discarded 1 legacy processing lease(s) at initialize',- ],- ])- expect(recovering.debugRecord(transfer.id)?.state).toBe('quarantined')- expect(recovering.debugRecord(pinned.id)?.state).toBe('completed')- // Three copies of 7 bytes stay charged, including the quarantined transfer.- expect(recovering.debugUsage().bytes).toBe(21)-- const persisted = JSON.parse(await fs.readFile(ledgerFile(), 'utf8'))- expect(persisted).not.toHaveProperty('processingLeases')- expect(persisted.records[transfer.id].state).toBe('quarantined')- expect(persisted.records[pinned.id].state).toBe('completed')- expect(persisted.retentionOwners[owner]).toEqual(seededLedger.retentionOwners[owner])- // The first-boot expiry sweep kept the expired copy its owner still pins.- expect(await fs.readFile(pinnedPath, 'utf8')).toBe('fixture')- expect(await recovering.reusableReceipt('caller-a', source, 7)).toMatchObject({- id: reusable.id,- sha256: reusable.sha256,- })- })-})--describe('GFS writer recovery and filesystem invariants', () => {- it.each(['SIGKILL', 'SIGTERM'] as const)(- 'excludes another process and recovers after %s on the same inode',- async signal => {- const { child, message } = await childStore()- expect(message).toEqual({ ready: true })- const databasePath = path.join(root, '.gfs-download-store', 'writer-v2.sqlite')- const before = await fs.stat(databasePath)- await expect(freshStore().initialize()).rejects.toMatchObject({ code: 'writer_locked' })- await kill(child, signal)- const reopened = freshStore()- await reopened.initialize()- const after = await fs.stat(databasePath)- expect([after.dev, after.ino]).toEqual([before.dev, before.ino])- await reopened.close()- expect((await fs.stat(databasePath)).ino).toBe(before.ino)- await expect(- fs.open(- path.join(root, '.gfs-download-store', 'writer.lock'),- constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL- )- ).rejects.toMatchObject({ code: 'EEXIST' })- }- )-- it('labels verified v2 contention and reinitializes the same store after the old process settles', async () => {- const { child } = await childStore()- const store = freshStore()- const storeRoot = path.join(root, '.gfs-download-store')- const before = await fs.stat(path.join(storeRoot, 'writer-v2.sqlite'), { bigint: true })- const ledgerBefore = await fs.readFile(path.join(storeRoot, 'ledger-v1.json'), 'utf8')- await expect(store.initialize()).rejects.toMatchObject({- code: 'writer_locked',- transientWriterContention: true,- })- expect(store.isAvailable()).toBe(false)- expect(await fs.readFile(path.join(storeRoot, 'ledger-v1.json'), 'utf8')).toBe(ledgerBefore)- await kill(child)- await store.initialize()- expect(store.isAvailable()).toBe(true)- expect(store.debugUsage().files).toBe(0)- const after = await fs.stat(path.join(storeRoot, 'writer-v2.sqlite'), { bigint: true })- expect([after.dev, after.ino]).toEqual([before.dev, before.ino])- const contender = await childStore()- expect(contender.message).toEqual({ error: 'writer_locked', transientWriterContention: true })- })-- it('labels a verified same-process active v2 writer as contention without exposing transfers', async () => {- const first = freshStore()- await first.initialize()- const second = freshStore()- await expect(second.initialize()).rejects.toMatchObject({- code: 'writer_locked',- transientWriterContention: true,- })- await first.close()- await second.initialize()- expect(second.isAvailable()).toBe(true)- })-- it.each(['ledger', 'marker', 'inode'] as const)(- 'never labels corrupt or replaced v2 state as transient (%s)',- async kind => {- const { child } = await childStore()- const storeRoot = path.join(root, '.gfs-download-store')- if (kind === 'ledger') await fs.writeFile(path.join(storeRoot, 'ledger-v1.json'), '{bad')- if (kind === 'marker') await fs.writeFile(path.join(storeRoot, 'writer.lock'), '{bad')- if (kind === 'inode') {- await fs.rename(- path.join(storeRoot, 'writer-v2.sqlite'),- path.join(storeRoot, 'writer-v2.sqlite.saved')- )- await fs.writeFile(path.join(storeRoot, 'writer-v2.sqlite'), '', { mode: 0o600 })- }- await expect(freshStore().initialize()).rejects.toMatchObject({- code: kind === 'ledger' ? 'corrupt_store_ledger' : 'writer_locked',- transientWriterContention: false,- })- await kill(child)- }- )-- it('reauthorizes a clean v2 cold-resume copy for the exact task owner and preserves every other pin', async () => {- const { child, message } = await childStore('pin')- await kill(child)- const ledgerPath = path.join(root, '.gfs-download-store', 'ledger-v1.json')- const ownerId = '11111111-1111-4111-8111-111111111111'- const otherId = '22222222-2222-4222-8222-222222222222'- const before = JSON.parse(await fs.readFile(ledgerPath, 'utf8'))- const reopened = freshStore()- await reopened.initialize()- expect(reopened.isAvailable()).toBe(true)- expect(reopened.debugRecord(message.receipt.id)?.state).toBe('completed')- // The download boundary freshly authorizes this exact remote source before- // invoking reuse; trusted task identity comes from persisted TaskExecutor.- const receipt = await reopened.reusableReceipt('caller-a', source, 7, {- retentionOwnerId: ownerId,- })- expect(receipt).toMatchObject({ id: message.receipt.id, sha256: message.receipt.sha256 })- const after = JSON.parse(await fs.readFile(ledgerPath, 'utf8'))- expect(after.retentionOwners[ownerId].writerSessionId).not.toBe(- before.retentionOwners[ownerId].writerSessionId- )- expect(after.retentionOwners[otherId]).toEqual(before.retentionOwners[otherId])- await reopened.releaseReceiptOwner(ownerId, 'caller-a')- await reopened.cleanupExpired(Date.parse(message.receipt.expiresAt) + 1)- expect(reopened.debugUsage().bytes).toBe(7)- await expect(reopened.releaseReceiptOwner(otherId, 'caller-b')).rejects.toMatchObject({- code: 'caller_mismatch',- })- await reopened.releaseReceiptOwner(otherId, 'caller-a')- await reopened.cleanupExpired(Date.parse(message.receipt.expiresAt) + 1)- expect(reopened.debugUsage().bytes).toBe(0)- })-- it.each(['caller', 'version', 'size', 'hash'] as const)(- 'does not adopt an inherited pin when fresh reuse validation fails (%s)',- async kind => {- const { child, message } = await childStore('pin')- await kill(child)- const ledgerPath = path.join(root, '.gfs-download-store', 'ledger-v1.json')- const ownerId = '11111111-1111-4111-8111-111111111111'- const before = JSON.parse(await fs.readFile(ledgerPath, 'utf8'))- if (kind === 'hash')- await fs.writeFile(path.join(root, 'users', 'caller-a', message.receipt.path), 'changed')- const reopened = freshStore()- await reopened.initialize()- if (kind === 'caller') {- await expect(- reopened.reusableReceipt('caller-b', source, 7, { retentionOwnerId: ownerId })- ).rejects.toMatchObject({ code: 'caller_mismatch' })- } else {- const receipt = await reopened.reusableReceipt(- 'caller-a',- kind === 'version' ? { ...source, version: source.version + 1 } : source,- kind === 'size' ? 8 : 7,- { retentionOwnerId: ownerId }- )- expect(receipt).toBeUndefined()- }- const after = JSON.parse(await fs.readFile(ledgerPath, 'utf8'))- expect(after.retentionOwners[ownerId]).toEqual(before.retentionOwners[ownerId])- expect(reopened.debugUsage().bytes).toBe(7)- }- )-- it('keeps kernel ownership after busy close and admits another process only after consumers settle', async () => {- const store = freshStore()- await store.initialize()- const receipt = await fixture(store, 'live-task')- await expect(store.close(0)).rejects.toMatchObject({ code: 'download_busy' })- expect(store.isAvailable()).toBe(true)- const contender = await childStore()- expect(contender.message).toEqual({ error: 'writer_locked', transientWriterContention: true })- expect(store.debugUsage()).toMatchObject({ bytes: 7, files: 1 })- expect(await store.inspect(receipt.path, 'caller-a')).toMatchObject({ id: receipt.id })- await store.releaseReceiptOwner('live-task', 'caller-a')- await store.close()- const successor = await childStore()- expect(successor.message).toEqual({ ready: true })- await kill(successor.child)- })-- it('releases an idle kernel writer after a real failed close journal without deleting its fence', async () => {- const store = freshStore()- await store.initialize()- const receipt = await fixture(store)- const storeRoot = path.join(root, '.gfs-download-store')- const ledgerPath = path.join(storeRoot, 'ledger-v1.json')- const ledger = await fs.readFile(ledgerPath)- await fs.rename(ledgerPath, `${ledgerPath}.saved`)- await fs.mkdir(ledgerPath, { mode: 0o700 })- await expect(store.close(0)).rejects.toMatchObject({ code: 'EISDIR' })- expect(store.isAvailable()).toBe(false)- await store.close(0)- // Fixture operator restores the exact ledger after proving the old writer closed.- await fs.rmdir(ledgerPath)- await fs.writeFile(ledgerPath, ledger, { mode: 0o600 })- const reopened = freshStore()- await reopened.initialize()- expect(await reopened.inspect(receipt.path, 'caller-a')).toMatchObject({ id: receipt.id })- await expect(- fs.open(- path.join(storeRoot, 'writer.lock'),- constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL- )- ).rejects.toMatchObject({ code: 'EEXIST' })- })-- it('keeps ambiguous legacy ownership untouched and rejects rollback through O_EXCL', async () => {- const storeRoot = path.join(root, '.gfs-download-store')- await fs.mkdir(storeRoot, { mode: 0o700 })- const legacy = JSON.stringify({- pid: 123,- leaseId: 'legacy',- acquiredAt: new Date(0).toISOString(),- })- await fs.writeFile(path.join(storeRoot, 'writer.lock'), legacy, { mode: 0o600 })- for (let attempt = 0; attempt < 2; attempt++)- await expect(freshStore().initialize()).rejects.toMatchObject({- code: 'writer_locked',- transientWriterContention: false,- })- expect(await fs.readFile(path.join(storeRoot, 'writer.lock'), 'utf8')).toBe(legacy)- expect(await fs.readdir(storeRoot)).toEqual(['writer.lock'])- })-- it('requires an operator transition for an unfenced legacy ledger even without writer.lock', async () => {- const storeRoot = path.join(root, '.gfs-download-store')- await fs.mkdir(storeRoot, { mode: 0o700 })- const legacyLedger = JSON.stringify({ schemaVersion: 1, records: {}, processingLeases: {} })- await fs.writeFile(path.join(storeRoot, 'ledger-v1.json'), legacyLedger, { mode: 0o600 })- for (let attempt = 0; attempt < 2; attempt++)- await expect(freshStore().initialize()).rejects.toMatchObject({- code: 'unsupported_store_schema',- })- expect(await fs.readFile(path.join(storeRoot, 'ledger-v1.json'), 'utf8')).toBe(legacyLedger)- expect(await fs.readdir(storeRoot)).toEqual(['ledger-v1.json'])- })-- it('rejects a missing or replaced lock database rather than creating a second inode', async () => {- const store = freshStore()- await store.initialize()- await store.close()- const databasePath = path.join(root, '.gfs-download-store', 'writer-v2.sqlite')- await fs.rename(databasePath, `${databasePath}.old`)- // #1028: a fence naming a database that is gone is a writer refusal with- // its own detail, never a generic workspace failure.- await expect(freshStore().initialize()).rejects.toMatchObject({- code: 'writer_locked',- transientWriterContention: false,- detail: 'database_missing',- })- // Exclusive creation proves initialization left the target absent in the- // same atomic operation. An unexpected second inode fails with EEXIST.- let replacementDatabase: FileHandle | undefined- try {- replacementDatabase = await fs.open(databasePath, 'wx', 0o600)- } finally {- await replacementDatabase?.close()- }- await expect(freshStore().initialize()).rejects.toMatchObject({- code: 'writer_locked',- detail: 'database_identity_changed',- })- })-- it('restores only verified owned fsGroup transformations without relaxing privacy', async () => {- const store = freshStore()- await store.initialize()- const receipt = await fixture(store)- await store.close()- const storeRoot = path.join(root, '.gfs-download-store')- const cacheRoot = path.join(root, 'users', 'caller-a', '.gfs-downloads')- for (const directory of [- storeRoot,- cacheRoot,- path.dirname(path.join(root, 'users', 'caller-a', receipt.path)),- ])- await fs.chmod(directory, 0o2770)- for (const filename of ['writer.lock', 'writer-v2.sqlite', 'ledger-v1.json'])- await fs.chmod(path.join(storeRoot, filename), 0o660)- const sourcePath = path.join(root, 'users', 'caller-a', receipt.path)- await fs.chmod(sourcePath, 0o660)- const reopened = freshStore()- await reopened.initialize()- expect((await fs.stat(storeRoot)).mode & 0o7777).toBe(0o700)- expect((await fs.stat(sourcePath)).mode & 0o7777).toBe(0o600)- expect(await reopened.reusableReceipt('caller-a', source, 7)).toMatchObject({ id: receipt.id })- })-- it.each(['mode', 'hardlink', 'symlink', 'hash'] as const)(- 'quarantines untrusted completed content (%s)',- async kind => {- const store = freshStore()- await store.initialize()- const receipt = await fixture(store)- await store.close()- const sourcePath = path.join(root, 'users', 'caller-a', receipt.path)- if (kind === 'mode') await fs.chmod(sourcePath, 0o644)- if (kind === 'hardlink') await fs.link(sourcePath, path.join(root, 'other-link'))- if (kind === 'symlink') {- await fs.rename(sourcePath, path.join(root, 'other-file'))- await fs.symlink(path.join(root, 'other-file'), sourcePath)- }- if (kind === 'hash') {- await fs.writeFile(sourcePath, 'changed')- await fs.chmod(sourcePath, 0o660)- }- const reopened = freshStore()- await reopened.initialize()- expect(reopened.debugRecord(receipt.id)).toMatchObject({ state: 'quarantined' })- expect(reopened.debugUsage().bytes).toBe(7)- await reopened.cleanupExpired(Date.parse(receipt.expiresAt) + 1)- expect(reopened.debugUsage().bytes).toBe(7)- if (kind === 'hash') expect((await fs.stat(sourcePath)).mode & 0o7777).toBe(0o660)- }- )-})diff --git a/mcp-host/src/internalTools/gfsDownloadStoreReservationRollback.test.ts b/mcp-host/src/internalTools/gfsDownloadStoreReservationRollback.test.tsdeleted file mode 100644index bc6ba6cce..000000000--- a/mcp-host/src/internalTools/gfsDownloadStoreReservationRollback.test.ts+++ /dev/null@@ -1,147 +0,0 @@-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'-import { createHash } from 'node:crypto'-import * as fs from 'node:fs/promises'-import { tmpdir } from 'node:os'-import * as path from 'node:path'-import type { GfsImageSource } from '../visualInput/policy'-import { GfsDownloadStore } from './gfsDownloadStore'--/**- * The reservation persist in createTransfer is the only durable write before a- * transfer is exposed. When it fails, the in-memory record and the retention- * owner roll back, so no later persist (close() included) writes a phantom- * reservation that the next boot would quarantine and keep charged to quota.- */--const source: GfsImageSource = {- kind: 'gfs',- drive: 'main',- resourceId: 'a'.repeat(32),- gfsUri: `gfs://main/${'a'.repeat(32)}`,- name: 'input.csv',- version: 7,-}-const otherSource: GfsImageSource = {- ...source,- resourceId: 'b'.repeat(32),- gfsUri: `gfs://main/${'b'.repeat(32)}`,- name: 'other.csv',-}-const OWNER_ID = '55555555-5555-4555-8555-555555555555'--let root: string-let callerRoot: string-let store: GfsDownloadStore--beforeEach(async () => {- root = await fs.mkdtemp(path.join(tmpdir(), 'gfs-reservation-rollback-'))- callerRoot = path.join(root, 'users', 'caller-a')- await fs.mkdir(callerRoot, { recursive: true, mode: 0o700 })- store = new GfsDownloadStore(root)- await store.initialize()-})--afterEach(async () => {- vi.restoreAllMocks()- await store.close(0).catch(() => undefined)- await fs.rm(root, { recursive: true, force: true })-})--async function ledgerOnDisk(): Promise<{- records: Record<string, unknown>- retentionOwners?: Record<string, { recordIds: string[] }>-}> {- return JSON.parse(- await fs.readFile(path.join(root, '.gfs-download-store', 'ledger-v1.json'), 'utf8')- )-}--function privateLedger(): {- records: Record<string, unknown>- retentionOwners?: Record<string, { recordIds: string[] }>-} {- return (store as unknown as { ledger: ReturnType<typeof privateLedger> }).ledger-}--function failNextPersist() {- return vi- .spyOn(store as unknown as { persist: () => Promise<void> }, 'persist')- .mockRejectedValueOnce(new Error('reservation unavailable'))-}--describe('createTransfer reservation persist failure', () => {- it('rolls back the reservation and a new retention owner, and close() persists no phantom record', async () => {- const before = await ledgerOnDisk()- const persist = failNextPersist()- await expect(- store.createTransfer({- callerIdentity: 'caller-a',- callerWorkspacePath: callerRoot,- source,- sizeBytes: 7,- expiresAt: new Date(Date.now() + 60_000).toISOString(),- retentionOwnerId: OWNER_ID,- })- ).rejects.toThrow('reservation unavailable')- // Witness: the rejection came from the reservation persist itself.- expect(persist).toHaveBeenCalledOnce()- expect(store.debugUsage()).toMatchObject({ bytes: 0, files: 0 })- expect(privateLedger().records).toEqual({})- expect(privateLedger().retentionOwners?.[OWNER_ID]).toBeUndefined()- expect(await ledgerOnDisk()).toEqual(before)- await expect(fs.lstat(path.join(callerRoot, '.gfs-downloads'))).rejects.toMatchObject({- code: 'ENOENT',- })-- await store.close(0)- const closed = await ledgerOnDisk()- expect(closed.records).toEqual({})- expect(closed.retentionOwners?.[OWNER_ID]).toBeUndefined()- })-- it('restores an existing retention owner and close() persists only the published record', async () => {- const transfer = await store.createTransfer({- callerIdentity: 'caller-a',- callerWorkspacePath: callerRoot,- source,- sizeBytes: 7,- expiresAt: new Date(Date.now() + 60_000).toISOString(),- retentionOwnerId: OWNER_ID,- })- await fs.writeFile(path.join(callerRoot, transfer.partialPath), 'fixture')- const published = await store.publish(- transfer.id,- 'caller-a',- createHash('sha256').update('fixture').digest('hex')- )- const ownerBefore = structuredClone(privateLedger().retentionOwners?.[OWNER_ID])- expect(ownerBefore?.recordIds).toEqual([published.id])- const before = await ledgerOnDisk()-- const persist = failNextPersist()- await expect(- store.createTransfer({- callerIdentity: 'caller-a',- callerWorkspacePath: callerRoot,- source: otherSource,- sizeBytes: 7,- expiresAt: new Date(Date.now() + 60_000).toISOString(),- retentionOwnerId: OWNER_ID,- })- ).rejects.toThrow('reservation unavailable')- expect(persist).toHaveBeenCalledOnce()- expect(store.debugUsage()).toMatchObject({ bytes: 7, files: 1 })- expect(Object.keys(privateLedger().records)).toEqual([published.id])- expect(privateLedger().retentionOwners?.[OWNER_ID]).toEqual(ownerBefore)- expect(await ledgerOnDisk()).toEqual(before)- expect(await fs.readdir(path.join(callerRoot, '.gfs-downloads'))).toEqual([- path.basename(path.dirname(published.path)),- ])-- await store.releaseReceiptOwner(OWNER_ID, 'caller-a')- await store.close(0)- const closed = await ledgerOnDisk()- expect(Object.keys(closed.records)).toEqual([published.id])- expect(closed.retentionOwners?.[OWNER_ID]).toBeUndefined()- })-})diff --git a/mcp-host/src/internalTools/gfsManagedImage.test.ts b/mcp-host/src/internalTools/gfsManagedImage.test.tsindex 1f4ef8ded..19a6ee332 100644--- a/mcp-host/src/internalTools/gfsManagedImage.test.ts+++ b/mcp-host/src/internalTools/gfsManagedImage.test.ts@@ -7,7 +7,11 @@ import { JPEG_2X2_BASE64, PNG_2X2_BASE64 } from '../llm/__tests__/codexImageFixtimport { resolveVisualDeliveryLimits } from '../visualInput/deliveryLimits'import { VisualInputBudget } from '../visualInput/policy'import { type GfscReadClient, buildGfsReadTools } from './gfs'-import { type GfsDownloadStore, GfsDownloadStoreError } from './gfsDownloadStore'+import {+ type GfsDownloadStore,+ GfsDownloadStoreError,+ type GfsDownloadStoreErrorCode,+} from './gfsDownloadStore'const MIB = 1024 * 1024const target = { drive: 'main', resourceId: 'a'.repeat(32) }@@ -336,3 +340,44 @@ describe('GFS managed image projection', () => {expect(subject.budget.residentBytes).toBe(0)})})++describe('GFS download store errors at the tool boundary', () => {+ const codes: GfsDownloadStoreErrorCode[] = [+ 'caller_mismatch',+ 'caller_quota_exceeded',+ 'download_busy',+ 'download_expired',+ 'download_missing',+ 'host_quota_exceeded',+ 'publication_cancelled',+ 'storage_write_failed',+ 'workspace_unavailable',+ ]++ it.each(codes)('surfaces store code %s to the model', async code => {+ const subject = scenario(largePng, {+ readManaged: async () => {+ throw new GfsDownloadStoreError(code)+ },+ })+ const result = await subject.run()++ expect(subject.store.readManagedFile).toHaveBeenCalledTimes(1)+ expect(result.success).toBe(false)+ expect(result.error).toBe(`GFS download store failed (${code})`)+ expect(subject.budget.residentBytes).toBe(0)+ })++ it.each(codes)('surfaces download admission code %s to the model', async code => {+ const subject = scenario(largePng)+ subject.client.download.mockImplementation(async () => {+ throw new GfsDownloadStoreError(code)+ })+ const result = await subject.run()++ expect(subject.client.download).toHaveBeenCalledTimes(1)+ expect(subject.store.readManagedFile).not.toHaveBeenCalled()+ expect(result.success).toBe(false)+ expect(result.error).toBe(`GFS download store failed (${code})`)+ })+})diff --git a/mcp-host/src/internalTools/gfsStoreOperatorRecovery.test.ts b/mcp-host/src/internalTools/gfsStoreOperatorRecovery.test.tsdeleted file mode 100644index 06bd31da2..000000000--- a/mcp-host/src/internalTools/gfsStoreOperatorRecovery.test.ts+++ /dev/null@@ -1,289 +0,0 @@-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'-import { createHash } from 'node:crypto'-import * as fs from 'node:fs/promises'-import type { FileHandle } from 'node:fs/promises'-import { tmpdir } from 'node:os'-import * as path from 'node:path'-import { GfsDownloadStore } from './gfsDownloadStore'-import {- GfsStoreRecoveryError,- type GfsStoreRecoveryInput,- inspectGfsStoreRecovery,- recoverGfsStoreUnderPhysicalFence,-} from './gfsStoreOperatorRecovery'--let root: string-let callerRoot: string-let stores: GfsDownloadStore[]-const source = {- kind: 'gfs' as const,- drive: 'main',- resourceId: 'a'.repeat(32),- gfsUri: `gfs://main/${'a'.repeat(32)}`,- name: 'input.csv',- version: 7,-}-const OWNER = '11111111-1111-4111-8111-111111111111'-beforeEach(async () => {- root = await fs.mkdtemp(path.join(tmpdir(), 'gfs-operator-recovery-'))- callerRoot = path.join(root, 'users', 'caller-a')- await fs.mkdir(callerRoot, { recursive: true, mode: 0o755 })- stores = []-})-afterEach(async () => {- vi.restoreAllMocks()- for (const store of stores)- await store.close(0).catch(async () => {- await (- store as unknown as { writerLease?: { release(): Promise<void> } }- ).writerLease?.release()- })- await fs.rm(root, { recursive: true, force: true })-})-function fresh() {- const store = new GfsDownloadStore(root)- stores.push(store)- return store-}-async function publish(store: GfsDownloadStore, owner?: string, caller = callerRoot) {- const transfer = await store.createTransfer({- callerIdentity: 'caller-a',- callerWorkspacePath: caller,- source,- sizeBytes: 7,- expiresAt: new Date(Date.now() + 60_000).toISOString(),- retentionOwnerId: owner,- })- await fs.writeFile(path.join(caller, transfer.partialPath), 'fixture')- return store.publish(- transfer.id,- 'caller-a',- createHash('sha256').update('fixture').digest('hex')- )-}-async function recoveryInput(- extra: Partial<GfsStoreRecoveryInput> = {}-): Promise<GfsStoreRecoveryInput> {- const inventory = await inspectGfsStoreRecovery(root)- return {- hostRoot: root,- expectedLedgerSha256: inventory.ledgerSha256,- expectedWriterFenceSha256: inventory.writerFenceSha256,- expectedSourceInventorySha256: inventory.sourceInventorySha256,- settledProcessingLeaseIds: [],- // This isolated fixture has no Pod or spawned executor. Store connections- // are explicitly closed first; this callback tests the helper's ordering,- // never stands in for the separately required real runtime fence.- withPhysicalFence: operation => operation(async () => undefined),- ...extra,- }-}-async function simulateWriterDeath(store: GfsDownloadStore) {- // No stream or executor was launched by these allocation fixtures; release- // the actual kernel connection to model loss of the old Host process.- await (store as unknown as { writerLease: { release(): Promise<void> } }).writerLease.release()-}--async function expectPrivateExclusiveCreateToFail(target: string): Promise<void> {- let unexpectedHandle: FileHandle | undefined- try {- await expect(async () => {- unexpectedHandle = await fs.open(target, 'wx', 0o600)- }).rejects.toMatchObject({ code: 'EEXIST' })- } finally {- await unexpectedHandle?.close()- }-}--async function legacyCopy() {- const store = fresh()- await store.initialize()- const receipt = await publish(store)- await store.close()- const storeRoot = path.join(root, '.gfs-download-store')- // Temporary-fixture conversion to the real legacy format (no v2 database),- // after the only writer has actually closed. Production state is untouched.- await fs.unlink(path.join(storeRoot, 'writer-v2.sqlite'))- await fs.writeFile(- path.join(storeRoot, 'writer.lock'),- JSON.stringify({ pid: 123, leaseId: OWNER, acquiredAt: new Date(0).toISOString() }),- { mode: 0o600 }- )- return receipt-}--describe('local GFS operator recovery', () => {- it('returns source-free opaque selections and never normalizes modes during live inspection', async () => {- const store = fresh()- await store.initialize()- const receipt = await publish(store)- const sourcePath = path.join(callerRoot, receipt.path)- await fs.chmod(sourcePath, 0o660)- const inventory = await inspectGfsStoreRecovery(root)- expect(inventory.counts).toMatchObject({ files: 1, bytes: 7, sourceFiles: 1 })- expect(inventory.selections).toEqual({- processingLeaseIds: [],- receiptOwnerIds: [],- removablePartialIds: [],- })- expect(JSON.stringify(inventory)).not.toContain('input.csv')- expect(JSON.stringify(inventory)).not.toContain('caller-a')- expect(JSON.stringify(inventory)).not.toContain(root)- expect((await fs.stat(sourcePath)).mode & 0o7777).toBe(0o660)- })-- it('transitions a fenced legacy store in place and preserves completed copy identity and quota', async () => {- const receipt = await legacyCopy()- const markerPath = path.join(root, '.gfs-download-store', 'writer.lock')- const markerBefore = await fs.stat(markerPath)- const outcome = await recoverGfsStoreUnderPhysicalFence(await recoveryInput())- expect(outcome.before.counts).toMatchObject({ files: 1, bytes: 7 })- expect(outcome.after.counts).toMatchObject({ files: 1, bytes: 7 })- expect((await fs.stat(markerPath)).ino).toBe(markerBefore.ino)- await expectPrivateExclusiveCreateToFail(markerPath)- const reopened = fresh()- await reopened.initialize()- expect(await reopened.reusableReceipt('caller-a', source, 7)).toMatchObject({- id: receipt.id,- sha256: receipt.sha256,- })- })-- it('S7: settles a legacy ledger that still carries a pre-#1019 processing lease', async () => {- const store = fresh()- await store.initialize()- const receipt = await publish(store)- await simulateWriterDeath(store)- // A Host older than #1019 died holding a lease over this copy. Seed the- // lease exactly as that build persisted it.- const ledgerPath = path.join(root, '.gfs-download-store', 'ledger-v1.json')- const ledger = JSON.parse(await fs.readFile(ledgerPath, 'utf8'))- const leaseId = '55555555-5555-4555-8555-555555555555'- ledger.processingLeases = {- [leaseId]: {- leaseId,- callerIdentity: 'caller-a',- recordIds: [receipt.id],- acquiredAt: new Date(Date.now() - 60_000).toISOString(),- expiresAt: new Date(Date.now() + 60_000).toISOString(),- writerSessionId: '66666666-6666-4666-8666-666666666666',- },- }- await fs.writeFile(ledgerPath, JSON.stringify(ledger), { mode: 0o600 })- const input = await recoveryInput({ settledProcessingLeaseIds: [leaseId] })- const result = await recoverGfsStoreUnderPhysicalFence(input)- expect(result.before.selections.processingLeaseIds).toEqual([leaseId])- expect(result.after.counts).toMatchObject({ files: 1, bytes: 7, processingLeases: 0 })- const recovered = fresh()- await recovered.initialize()- expect(recovered.isAvailable()).toBe(true)- expect(await recovered.reusableReceipt('caller-a', source, 7)).toMatchObject({ id: receipt.id })- })-- it('preserves partial bytes and charge by default, then removes only the exact reviewed settled partial', async () => {- const store = fresh()- await store.initialize()- const transfer = await store.createTransfer({- callerIdentity: 'caller-a',- callerWorkspacePath: callerRoot,- source,- sizeBytes: 7,- expiresAt: new Date(Date.now() + 60_000).toISOString(),- })- await fs.writeFile(path.join(callerRoot, transfer.partialPath), 'partial')- await simulateWriterDeath(store)- const preserved = await recoverGfsStoreUnderPhysicalFence(await recoveryInput())- expect(preserved.after.counts).toMatchObject({ files: 1, bytes: 7, partialFiles: 1 })- expect(await fs.readFile(path.join(callerRoot, transfer.partialPath), 'utf8')).toBe('partial')- const removed = await recoverGfsStoreUnderPhysicalFence(- await recoveryInput({ removeSettledTransferIds: [transfer.id] })- )- expect(removed.after.counts).toMatchObject({ files: 0, bytes: 0, partialFiles: 0 })- await expect(- fs.lstat(path.join(callerRoot, path.dirname(transfer.path)))- ).rejects.toMatchObject({ code: 'ENOENT' })- })-- it('never selects or deletes a renamed source with missing publication metadata', async () => {- const store = fresh()- await store.initialize()- const receipt = await publish(store)- const record = store.debugRecord(receipt.id)!- record.state = 'transferring'- delete record.sha256- await store.debugPersist()- await store.close()- const inventory = await inspectGfsStoreRecovery(root)- expect(inventory.selections.removablePartialIds).not.toContain(receipt.id)- await expect(- recoverGfsStoreUnderPhysicalFence(- await recoveryInput({ removeSettledTransferIds: [receipt.id] })- )- ).rejects.toMatchObject({ code: 'invalid_selection' })- expect(await fs.readFile(path.join(callerRoot, receipt.path), 'utf8')).toBe('fixture')- })-- it.each(['empty-ledger', 'different-cache'] as const)(- 'rejects unjournaled reserved caller caches (%s)',- async scenario => {- const store = fresh()- await store.initialize()- await publish(store)- await store.close()- const ledgerPath = path.join(root, '.gfs-download-store', 'ledger-v1.json')- if (scenario === 'empty-ledger') {- await fs.writeFile(ledgerPath, JSON.stringify({ schemaVersion: 1, records: {} }))- } else {- const unknown = path.join(root, 'users', 'other-caller', '.gfs-downloads', `input-${OWNER}`)- await fs.mkdir(unknown, { recursive: true, mode: 0o700 })- await fs.writeFile(path.join(unknown, 'source.partial'), 'unknown', { mode: 0o600 })- }- await expect(inspectGfsStoreRecovery(root)).rejects.toMatchObject({- code: 'invalid_inventory',- })- }- )-- it('rejects changed snapshot and duplicate, unknown, or completed selections before any transition', async () => {- const receipt = await legacyCopy()- const input = await recoveryInput()- const markerPath = path.join(root, '.gfs-download-store', 'writer.lock')- const before = await fs.readFile(markerPath, 'utf8')- for (const extra of [- { expectedLedgerSha256: '0'.repeat(64) },- { settledProcessingLeaseIds: [OWNER, OWNER] },- { terminalReceiptOwnerIds: [OWNER] },- { removeSettledTransferIds: [receipt.id] },- ])- await expect(- recoverGfsStoreUnderPhysicalFence({ ...input, ...extra })- ).rejects.toBeInstanceOf(GfsStoreRecoveryError)- expect(await fs.readFile(markerPath, 'utf8')).toBe(before)- })-- it('keeps old-binary exclusion and charged state recoverable when the physical fence is lost mid-marker write', async () => {- const receipt = await legacyCopy()- const markerPath = path.join(root, '.gfs-download-store', 'writer.lock')- const input = await recoveryInput({- withPhysicalFence: operation =>- operation(async () => {- if ((await fs.stat(markerPath)).size === 0)- throw new GfsStoreRecoveryError('snapshot_changed')- }),- })- await expect(recoverGfsStoreUnderPhysicalFence(input)).rejects.toMatchObject({- code: 'snapshot_changed',- })- const databasePath = path.join(root, '.gfs-download-store', 'writer-v2.sqlite')- const databaseBefore = await fs.stat(databasePath)- expect((await fs.stat(markerPath)).size).toBe(0)- await expectPrivateExclusiveCreateToFail(markerPath)- expect(await fs.readFile(path.join(callerRoot, receipt.path), 'utf8')).toBe('fixture')- const retried = await recoverGfsStoreUnderPhysicalFence(await recoveryInput())- expect(retried.after.counts).toMatchObject({ files: 1, bytes: 7 })- expect((await fs.stat(databasePath)).ino).toBe(databaseBefore.ino)- const reopened = fresh()- await reopened.initialize()- expect(reopened.debugUsage().bytes).toBe(7)- })-})diff --git a/mcp-host/src/internalTools/gfsStoreOperatorRecovery.ts b/mcp-host/src/internalTools/gfsStoreOperatorRecovery.tsdeleted file mode 100644index 18845c0ce..000000000--- a/mcp-host/src/internalTools/gfsStoreOperatorRecovery.ts+++ /dev/null@@ -1,498 +0,0 @@-import { createHash, randomUUID } from 'node:crypto'-import { type Dir, constants } from 'node:fs'-import * as fs from 'node:fs/promises'-import * as path from 'node:path'-import { type GfsDownloadRecord, type StoreLedger, parseLedger } from './gfsDownloadStore'-import { openPrivateStoreObject } from './gfsStorePrivateFiles'-import { GfsStoreWriterLease } from './gfsStoreWriterLease'--export class GfsStoreRecoveryError extends Error {- constructor(- readonly code:- | 'snapshot_changed'- | 'invalid_inventory'- | 'invalid_selection'- | 'storage_write_failed'- ) {- super(`GFS store operator recovery failed (${code})`)- }-}--export interface GfsStoreRecoveryCounts {- files: number- bytes: number- processingLeases: number- receiptOwners: number- sourceFiles: number- partialFiles: number-}--/** Bounded, source-free inventory that is safe to print in the local runbook. */-export interface GfsStoreRecoveryInventory {- ledgerSha256: string- writerFenceSha256: string | 'absent'- sourceInventorySha256: string- counts: GfsStoreRecoveryCounts- selections: {- processingLeaseIds: string[]- receiptOwnerIds: string[]- removablePartialIds: string[]- }-}--export interface GfsStoreRecoveryReceipt {- before: GfsStoreRecoveryInventory- after: GfsStoreRecoveryInventory- settledProcessingLeases: number- terminalReceiptOwners: number- removedSettledTransfers: number-}--export interface GfsStoreRecoveryInput {- hostRoot: string- expectedLedgerSha256: string- expectedWriterFenceSha256: string | 'absent'- expectedSourceInventorySha256: string- settledProcessingLeaseIds: string[]- terminalReceiptOwnerIds?: string[]- removeSettledTransferIds?: string[]- /**- * The local operator owns an exclusive runtime/profile fence for this whole- * callback. assertHeld must prove actual Host/executor physical settlement,- * including deleted-pod descendants, not a PID/TTL/replica-count inference.- * No Host RPC, environment flag, or model-supplied provider exposes this API.- */- withPhysicalFence(- operation: (assertHeld: () => Promise<void>) => Promise<GfsStoreRecoveryReceipt>- ): Promise<GfsStoreRecoveryReceipt>-}--interface FileInventory {- present: boolean- sizeBytes?: number- sha256?: string-}-interface RecordInventory {- id: string- source: FileInventory- partial: FileInventory-}-interface Snapshot {- root: string- storeRoot: string- ledger: StoreLedger- sources: RecordInventory[]- inventory: GfsStoreRecoveryInventory-}-const SHA256_RE = /^[0-9a-f]{64}$/-const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i-const MAX_OPERATOR_OWNERS = 4096-const MAX_OPERATOR_LEDGER_BYTES = 32 * 1024 * 1024--function hash(bytes: string | Buffer): string {- return createHash('sha256').update(bytes).digest('hex')-}-function within(child: string, parent: string): boolean {- const relative = path.relative(parent, child)- return relative !== '' && !relative.startsWith('..') && !path.isAbsolute(relative)-}--async function readOwnedFile(filename: string): Promise<Buffer> {- const handle = await openPrivateStoreObject(filename, 'file', constants.O_RDONLY, false)- try {- const before = await handle.stat({ bigint: true })- if (before.size > BigInt(MAX_OPERATOR_LEDGER_BYTES))- throw new GfsStoreRecoveryError('invalid_inventory')- const bytes = await handle.readFile()- const after = await handle.stat({ bigint: true })- const named = await fs.lstat(filename, { bigint: true })- if (- before.size !== after.size ||- before.mtimeNs !== after.mtimeNs ||- before.ctimeNs !== after.ctimeNs ||- named.dev !== before.dev ||- named.ino !== before.ino ||- named.isSymbolicLink()- )- throw new GfsStoreRecoveryError('snapshot_changed')- return bytes- } finally {- await handle.close()- }-}--async function verifyDirectory(directory: string): Promise<void> {- if ((await fs.realpath(directory)) !== directory)- throw new GfsStoreRecoveryError('invalid_inventory')- const handle = await openPrivateStoreObject(directory, 'directory', constants.O_RDONLY, false)- await handle.close()-}--async function verifyCallerRoot(directory: string): Promise<void> {- if ((await fs.realpath(directory)) !== directory)- throw new GfsStoreRecoveryError('invalid_inventory')- const handle = await fs.open(- directory,- constants.O_RDONLY | constants.O_DIRECTORY | constants.O_NOFOLLOW- )- try {- const info = await handle.stat()- const named = await fs.lstat(directory)- if (- !info.isDirectory() ||- named.isSymbolicLink() ||- typeof process.getuid !== 'function' ||- info.uid !== process.getuid() ||- named.dev !== info.dev ||- named.ino !== info.ino- )- throw new GfsStoreRecoveryError('invalid_inventory')- } finally {- await handle.close()- }-}--async function inventoryFile(- filename: string,- assertHeld?: () => Promise<void>-): Promise<FileInventory> {- let handle: fs.FileHandle- try {- handle = await openPrivateStoreObject(filename, 'file', constants.O_RDONLY, false)- } catch (error) {- if ((error as NodeJS.ErrnoException).code === 'ENOENT') return { present: false }- throw error- }- try {- const before = await handle.stat({ bigint: true })- const digest = createHash('sha256')- const chunk = Buffer.alloc(64 * 1024)- let position = 0- for (;;) {- await assertHeld?.()- const read = await handle.read(chunk, 0, chunk.length, position)- if (read.bytesRead === 0) break- digest.update(chunk.subarray(0, read.bytesRead))- position += read.bytesRead- }- const after = await handle.stat({ bigint: true })- const named = await fs.lstat(filename, { bigint: true })- if (- before.size !== after.size ||- before.mtimeNs !== after.mtimeNs ||- before.ctimeNs !== after.ctimeNs ||- named.dev !== before.dev ||- named.ino !== before.ino ||- named.isSymbolicLink() ||- BigInt(position) !== before.size- )- throw new GfsStoreRecoveryError('snapshot_changed')- return { present: true, sizeBytes: position, sha256: digest.digest('hex') }- } finally {- await handle.close()- }-}--async function snapshot(hostRoot: string, assertHeld?: () => Promise<void>): Promise<Snapshot> {- try {- const requested = path.resolve(hostRoot)- const hostInfo = await fs.lstat(requested)- if (!hostInfo.isDirectory() || hostInfo.isSymbolicLink())- throw new GfsStoreRecoveryError('invalid_inventory')- const root = await fs.realpath(requested)- const storeRoot = path.join(root, '.gfs-download-store')- await verifyDirectory(storeRoot)- const ledgerBytes = await readOwnedFile(path.join(storeRoot, 'ledger-v1.json'))- const ledger = parseLedger(ledgerBytes.toString('utf8'))- if (- Object.keys(ledger.records).length > 64 ||- Object.keys(ledger.processingLeases ?? {}).length > MAX_OPERATOR_OWNERS ||- Object.keys(ledger.retentionOwners ?? {}).length > MAX_OPERATOR_OWNERS ||- Object.keys(ledger.retentionOwners ?? {}).some(id => !UUID_RE.test(id))- )- throw new GfsStoreRecoveryError('invalid_inventory')- const records = Object.values(ledger.records).sort((left, right) =>- left.id.localeCompare(right.id)- )- const sources: RecordInventory[] = []- const expectedDirectories = new Map<string, Set<string>>()- for (const record of records) {- const directory = path.join(root, record.directory)- if (!within(directory, root)) throw new GfsStoreRecoveryError('invalid_inventory')- const cacheRoot = path.dirname(directory)- const callerRoot = path.dirname(cacheRoot)- if (path.dirname(callerRoot) !== path.join(root, 'users'))- throw new GfsStoreRecoveryError('invalid_inventory')- const expected = expectedDirectories.get(cacheRoot) ?? new Set<string>()- expected.add(path.basename(directory))- expectedDirectories.set(cacheRoot, expected)- try {- await verifyCallerRoot(path.dirname(cacheRoot))- await verifyDirectory(cacheRoot)- await verifyDirectory(directory)- } catch (error) {- if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error- sources.push({ id: record.id, source: { present: false }, partial: { present: false } })- continue- }- const names = await fs.readdir(directory)- if (names.some(name => name !== 'source' && name !== 'source.partial'))- throw new GfsStoreRecoveryError('invalid_inventory')- sources.push({- id: record.id,- source: await inventoryFile(path.join(root, record.hostPath), assertHeld),- partial: await inventoryFile(path.join(root, `${record.hostPath}.partial`), assertHeld),- })- }- // Census only the reserved cache path under the repository's verified- // users/<caller> scheme; never open ordinary customer or memory contents.- const usersRoot = path.join(root, 'users')- let users: Dir | undefined- try {- await verifyCallerRoot(usersRoot)- users = await fs.opendir(usersRoot)- } catch (error) {- if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error- }- if (users) {- for await (const entry of users) {- await assertHeld?.()- if (!entry.isDirectory() || entry.isSymbolicLink())- throw new GfsStoreRecoveryError('invalid_inventory')- const callerRoot = path.join(usersRoot, entry.name)- await verifyCallerRoot(callerRoot)- const cacheRoot = path.join(callerRoot, '.gfs-downloads')- let names: string[]- try {- await verifyDirectory(cacheRoot)- names = await fs.readdir(cacheRoot)- } catch (error) {- if ((error as NodeJS.ErrnoException).code === 'ENOENT') continue- throw error- }- const expected = expectedDirectories.get(cacheRoot) ?? new Set<string>()- if (names.some(name => !expected.has(name)))- throw new GfsStoreRecoveryError('invalid_inventory')- }- }- let writerFenceSha256: string | 'absent' = 'absent'- try {- writerFenceSha256 = hash(await readOwnedFile(path.join(storeRoot, 'writer.lock')))- } catch (error) {- if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error- }- // The journal may have been replaced while the sources were hashed.- if (hash(await readOwnedFile(path.join(storeRoot, 'ledger-v1.json'))) !== hash(ledgerBytes))- throw new GfsStoreRecoveryError('snapshot_changed')- return {- root,- storeRoot,- ledger,- sources,- inventory: {- ledgerSha256: hash(ledgerBytes),- writerFenceSha256,- sourceInventorySha256: hash(JSON.stringify(sources)),- counts: {- files: records.length,- bytes: records.reduce((sum, record) => sum + record.sizeBytes, 0),- processingLeases: Object.keys(ledger.processingLeases ?? {}).length,- receiptOwners: Object.keys(ledger.retentionOwners ?? {}).length,- sourceFiles: sources.filter(item => item.source.present).length,- partialFiles: sources.filter(item => item.partial.present).length,- },- selections: {- processingLeaseIds: Object.keys(ledger.processingLeases ?? {}).sort(),- receiptOwnerIds: Object.keys(ledger.retentionOwners ?? {}).sort(),- removablePartialIds: records- .filter(- record =>- record.state !== 'completed' &&- record.sha256 === undefined &&- !sources.find(item => item.id === record.id)?.source.present- )- .map(record => record.id),- },- },- }- } catch (error) {- if (error instanceof GfsStoreRecoveryError) throw error- throw new GfsStoreRecoveryError('invalid_inventory')- }-}--/** Read-only; a later transition rejects any ledger, fence or source drift. */-export async function inspectGfsStoreRecovery(- hostRoot: string-): Promise<GfsStoreRecoveryInventory> {- return (await snapshot(hostRoot)).inventory-}--function selected(ids: string[], available: Record<string, unknown>): void {- if (- !Array.isArray(ids) ||- new Set(ids).size !== ids.length ||- ids.some(id => typeof id !== 'string' || !Object.hasOwn(available, id))- )- throw new GfsStoreRecoveryError('invalid_selection')-}--async function persist(- state: Snapshot,- lease: GfsStoreWriterLease,- assertHeld: () => Promise<void>-): Promise<void> {- const ledgerPath = path.join(state.storeRoot, 'ledger-v1.json')- const temporary = `${ledgerPath}.tmp-${randomUUID()}`- try {- await assertHeld()- await lease.verifyHeld()- const handle = await fs.open(- temporary,- constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW,- 0o600- )- try {- await assertHeld()- await lease.verifyHeld()- await handle.writeFile(JSON.stringify(state.ledger))- await assertHeld()- await lease.verifyHeld()- await handle.sync()- } finally {- await handle.close()- }- await assertHeld()- await lease.verifyHeld()- await fs.rename(temporary, ledgerPath)- const directory = await openPrivateStoreObject(- state.storeRoot,- 'directory',- constants.O_RDONLY,- true,- assertHeld- )- try {- await assertHeld()- await lease.verifyHeld()- await directory.sync()- } finally {- await directory.close()- }- await assertHeld()- await lease.verifyHeld()- } catch (error) {- // The last journal still charges every uncertain copy. An uncommitted temp- // is private recovery evidence and is never interpreted as an empty store.- if (error instanceof GfsStoreRecoveryError) throw error- throw new GfsStoreRecoveryError('storage_write_failed')- }-}--/** Narrow local operator transition; caller supplies a real held physical fence. */-export async function recoverGfsStoreUnderPhysicalFence(- input: GfsStoreRecoveryInput-): Promise<GfsStoreRecoveryReceipt> {- if (- !SHA256_RE.test(input.expectedLedgerSha256) ||- !SHA256_RE.test(input.expectedSourceInventorySha256) ||- !(- input.expectedWriterFenceSha256 === 'absent' ||- SHA256_RE.test(input.expectedWriterFenceSha256)- )- )- throw new GfsStoreRecoveryError('snapshot_changed')- return input.withPhysicalFence(async assertHeld => {- await assertHeld()- const state = await snapshot(input.hostRoot, assertHeld)- if (- state.inventory.ledgerSha256 !== input.expectedLedgerSha256 ||- state.inventory.writerFenceSha256 !== input.expectedWriterFenceSha256 ||- state.inventory.sourceInventorySha256 !== input.expectedSourceInventorySha256- )- throw new GfsStoreRecoveryError('snapshot_changed')- const executionIds = input.settledProcessingLeaseIds- const ownerIds = input.terminalReceiptOwnerIds ?? []- const transferIds = input.removeSettledTransferIds ?? []- selected(executionIds, state.ledger.processingLeases ?? {})- selected(ownerIds, state.ledger.retentionOwners ?? {})- selected(transferIds, state.ledger.records)- for (const id of transferIds) {- const record = state.ledger.records[id]- if (- record.state === 'completed' ||- record.sha256 !== undefined ||- state.sources.find(item => item.id === id)?.source.present ||- Object.values(state.ledger.processingLeases ?? {}).some(- lease => !executionIds.includes(lease.leaseId) && lease.recordIds.includes(id)- ) ||- Object.values(state.ledger.retentionOwners ?? {}).some(- owner => !ownerIds.includes(owner.ownerId) && owner.recordIds.includes(id)- )- )- throw new GfsStoreRecoveryError('invalid_selection')- }- const writer = new GfsStoreWriterLease(state.storeRoot, false)- try {- await writer.acquireForRecovery({- expectedWriterFenceSha256: input.expectedWriterFenceSha256,- assertPhysicalFenceHeld: assertHeld,- })- // Metadata settlement is durable before deleting a selected partial. A- // crash before that commit retains every reservation; a crash afterward- // leaves all remaining bytes charged until deletion is positively proven.- for (const id of executionIds) delete state.ledger.processingLeases![id]- for (const id of ownerIds) delete state.ledger.retentionOwners![id]- for (const record of Object.values(state.ledger.records)) {- const source = state.sources.find(item => item.id === record.id)?.source- const published =- source?.present &&- source.sizeBytes === record.sizeBytes &&- source.sha256 === record.sha256 &&- record.sha256 !== undefined- record.state =- Object.keys(state.ledger.processingLeases ?? {}).length === 0 && published- ? 'completed'- : 'quarantined'- }- await persist(state, writer, assertHeld)- for (const id of transferIds) {- const record: GfsDownloadRecord = state.ledger.records[id]- const directory = path.join(state.root, record.directory)- await assertHeld()- await writer.verifyHeld()- try {- await verifyCallerRoot(path.dirname(path.dirname(directory)))- await verifyDirectory(path.dirname(directory))- await verifyDirectory(directory)- await assertHeld()- await writer.verifyHeld()- await fs.rm(directory, { recursive: true, force: true })- await fs.lstat(directory)- throw new GfsStoreRecoveryError('storage_write_failed')- } catch (error) {- if ((error as NodeJS.ErrnoException).code !== 'ENOENT') {- if (error instanceof GfsStoreRecoveryError) throw error- throw new GfsStoreRecoveryError('storage_write_failed')- }- }- await assertHeld()- await writer.verifyHeld()- delete state.ledger.records[id]- await persist(state, writer, assertHeld)- }- await assertHeld()- await writer.verifyHeld()- const after = (await snapshot(input.hostRoot, assertHeld)).inventory- return {- before: state.inventory,- after,- settledProcessingLeases: executionIds.length,- terminalReceiptOwners: ownerIds.length,- removedSettledTransfers: transferIds.length,- }- } finally {- await writer.release()- }- })-}diff --git a/mcp-host/src/internalTools/gfsStoreWriterFence.test.ts b/mcp-host/src/internalTools/gfsStoreWriterFence.test.tsdeleted file mode 100644index 22357e74a..000000000--- a/mcp-host/src/internalTools/gfsStoreWriterFence.test.ts+++ /dev/null@@ -1,310 +0,0 @@-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'-import Database from 'better-sqlite3'-import { createHash } from 'node:crypto'-import * as fs from 'node:fs/promises'-import { tmpdir } from 'node:os'-import * as path from 'node:path'-import { logger } from '../logger'-import { GfsDownloadStore } from './gfsDownloadStore'-import { GfsStoreWriterLease } from './gfsStoreWriterLease'--/**- * #1028: a v2 writer fence recorded the database device, and a persistent disk- * reattached under another device node changed it, which locked the store for- * good. The fence is now judged by ownership and inode only. A v2 fence is- * accepted in place and never rewritten; v3 (no device) is written only at- * bootstrap. Live writers stay excluded by the SQLite exclusive lock.- */-const OWNERSHIP = 'sqlite-exclusive-v1'-const V2_ACCEPTED = 'GFS writer fence v2 accepted with stale device'--let root: string-let stores: GfsDownloadStore[]-let leases: GfsStoreWriterLease[]-let connections: Database.Database[]--beforeEach(async () => {- root = await fs.mkdtemp(path.join(tmpdir(), 'gfs-writer-fence-'))- stores = []- leases = []- connections = []-})--afterEach(async () => {- vi.restoreAllMocks()- for (const connection of connections) if (connection.open) connection.close()- for (const value of leases) await value.release()- for (const store of stores) await store.close(0).catch(() => undefined)- await fs.rm(root, { recursive: true, force: true })-})--function freshStore(): GfsDownloadStore {- const store = new GfsDownloadStore(root)- stores.push(store)- return store-}--function lease(storeRoot: string): GfsStoreWriterLease {- const value = new GfsStoreWriterLease(storeRoot, false)- leases.push(value)- return value-}--function connection(storeRoot: string): Database.Database {- const value = new Database(path.join(storeRoot, 'writer-v2.sqlite'), {- timeout: 0,- fileMustExist: true,- })- connections.push(value)- return value-}--/** A bootstrapped store whose only writer has closed. */-async function closedStoreRoot(): Promise<string> {- const store = freshStore()- await store.initialize()- await store.close()- return path.join(await fs.realpath(root), '.gfs-download-store')-}--async function databaseIdentity(storeRoot: string): Promise<{ dev: string; ino: string }> {- const info = await fs.stat(path.join(storeRoot, 'writer-v2.sqlite'), { bigint: true })- return { dev: String(info.dev), ino: String(info.ino) }-}--/** Byte-exact v2 fence as the c8f898209 writer serialized it. */-function v2Fence(device: string, inode: string): string {- return JSON.stringify({- schemaVersion: 2,- ownership: OWNERSHIP,- databaseDevice: device,- databaseInode: inode,- })-}--function markerPath(storeRoot: string): string {- return path.join(storeRoot, 'writer.lock')-}--async function writeFence(storeRoot: string, bytes: string): Promise<void> {- await fs.writeFile(markerPath(storeRoot), bytes, { mode: 0o600 })-}--function sha256(value: string): string {- return createHash('sha256').update(value).digest('hex')-}--function acceptanceLogs(spy: { mock: { calls: unknown[][] } }): unknown[][] {- return spy.mock.calls.filter(call => call[1] === V2_ACCEPTED)-}--describe('GFS writer fence across a persistent-disk reattach (#1028)', () => {- it('T1: accepts a v2 fence whose device changed when its inode matches, keeps it byte-for-byte and logs both devices', async () => {- const storeRoot = await closedStoreRoot()- const { dev, ino } = await databaseIdentity(storeRoot)- const staleDevice = String(BigInt(dev) + 1n)- const v2 = v2Fence(staleDevice, ino)- await writeFence(storeRoot, v2)- const info = vi.spyOn(logger, 'info')-- const store = freshStore()- await store.initialize()-- expect(store.isAvailable()).toBe(true)- expect(await fs.readFile(markerPath(storeRoot), 'utf8')).toBe(v2)- expect(acceptanceLogs(info)).toEqual([- [- { component: 'GfsDownloadStore', storedDevice: staleDevice, currentDevice: dev },- V2_ACCEPTED,- ],- ])- await store.close()- expect(await fs.readFile(markerPath(storeRoot), 'utf8')).toBe(v2)- })-- it('T2: refuses a v2 fence naming another database inode as permanent database_identity_changed', async () => {- const storeRoot = await closedStoreRoot()- const { dev, ino } = await databaseIdentity(storeRoot)- const foreign = v2Fence(dev, String(BigInt(ino) + 1n))- await writeFence(storeRoot, foreign)-- const store = freshStore()- await expect(store.initialize()).rejects.toMatchObject({- code: 'writer_locked',- transientWriterContention: false,- detail: 'database_identity_changed',- })- expect(store.isAvailable()).toBe(false)- expect(await fs.readFile(markerPath(storeRoot), 'utf8')).toBe(foreign)-- // Witness: the same store with only the inode corrected is accepted, so the- // refusal came from the inode and nothing else.- await writeFence(storeRoot, v2Fence(dev, ino))- await store.initialize()- expect(store.isAvailable()).toBe(true)- })-- it('T3: bootstrap writes the v3 fence, a v3 reopen acquires, and reacquisition leaves its hash unchanged', async () => {- const store = freshStore()- await store.initialize()- const storeRoot = path.join(await fs.realpath(root), '.gfs-download-store')- const { dev, ino } = await databaseIdentity(storeRoot)- const v3 = JSON.stringify({ schemaVersion: 3, ownership: OWNERSHIP, databaseInode: ino })- expect(await fs.readFile(markerPath(storeRoot), 'utf8')).toBe(v3)- await store.close()- const bootstrapHash = sha256(await fs.readFile(markerPath(storeRoot), 'utf8'))-- const info = vi.spyOn(logger, 'info')- const reopened = freshStore()- await reopened.initialize()- expect(reopened.isAvailable()).toBe(true)- expect(acceptanceLogs(info)).toEqual([])- await reopened.close()-- const direct = lease(storeRoot)- await direct.acquire()- direct.assertHeld()- expect(direct.lastAcquire).toEqual({ fenceSchema: 3, currentDevice: dev })- await direct.release()- expect(sha256(await fs.readFile(markerPath(storeRoot), 'utf8'))).toBe(bootstrapHash)- })-- it('T4: a second real SQLite connection excludes the writer as verified transient contention while v2 stays on disk', async () => {- const storeRoot = await closedStoreRoot()- const { dev, ino } = await databaseIdentity(storeRoot)- const staleDevice = String(BigInt(dev) + 1n)- const v2 = v2Fence(staleDevice, ino)- await writeFence(storeRoot, v2)-- const other = connection(storeRoot)- other.pragma('journal_mode = DELETE')- other.exec('BEGIN EXCLUSIVE')- expect(other.inTransaction).toBe(true)- await expect(lease(storeRoot).acquire()).rejects.toMatchObject({- reason: 'writer_locked',- transientWriterContention: true,- detail: 'sqlite_busy_verified',- })- expect(await fs.readFile(markerPath(storeRoot), 'utf8')).toBe(v2)- other.close()-- const held = lease(storeRoot)- await held.acquire()- held.assertHeld()- expect(held.lastAcquire).toEqual({- fenceSchema: 2,- storedDevice: staleDevice,- currentDevice: dev,- })- // While the lease holds, another real connection cannot take the lock.- const contender = connection(storeRoot)- let contenderCode: unknown- try {- contender.exec('BEGIN EXCLUSIVE')- } catch (error) {- contenderCode = (error as { code?: unknown }).code- }- expect(contenderCode).toBe('SQLITE_BUSY')- expect(await fs.readFile(markerPath(storeRoot), 'utf8')).toBe(v2)- })-- it.each([- ['empty', () => ''],- ['truncated v2', (dev: string, ino: string) => v2Fence(dev, ino).slice(0, 24)],- [- 'v1 legacy lease id',- () => JSON.stringify({ pid: 123, leaseId: 'legacy', acquiredAt: new Date(0).toISOString() }),- ],- [- 'unknown schema version',- (_dev: string, ino: string) =>- JSON.stringify({ schemaVersion: 4, ownership: OWNERSHIP, databaseInode: ino }),- ],- [- 'foreign ownership',- (_dev: string, ino: string) =>- JSON.stringify({ schemaVersion: 3, ownership: 'other', databaseInode: ino }),- ],- ] as const)(- 'T5: refuses the %s fence as legacy_fence and leaves it in place',- async (_name, build) => {- const storeRoot = await closedStoreRoot()- const { dev, ino } = await databaseIdentity(storeRoot)- const fence = build(dev, ino)- await writeFence(storeRoot, fence)-- await expect(lease(storeRoot).acquire()).rejects.toMatchObject({- reason: 'writer_locked',- transientWriterContention: false,- detail: 'legacy_fence',- })- expect(await fs.readFile(markerPath(storeRoot), 'utf8')).toBe(fence)-- // Witness: the same database with a valid fence is acquired.- await writeFence(storeRoot, v2Fence(dev, ino))- const valid = lease(storeRoot)- await valid.acquire()- valid.assertHeld()- }- )-- it('T6: operator recovery accepts a v2 fence with another device in place and refuses another inode', async () => {- const storeRoot = await closedStoreRoot()- const { dev, ino } = await databaseIdentity(storeRoot)- const v2 = v2Fence(String(BigInt(dev) + 1n), ino)- await writeFence(storeRoot, v2)- let fenceChecks = 0- const assertPhysicalFenceHeld = async () => {- fenceChecks += 1- }-- const operator = lease(storeRoot)- await operator.acquireForRecovery({- expectedWriterFenceSha256: sha256(v2),- assertPhysicalFenceHeld,- })- await operator.verifyHeld()- expect(fenceChecks).toBeGreaterThan(0)- expect(operator.lastAcquire?.fenceSchema).toBe(2)- // The inspected hash stays valid: the v2 file is not rewritten.- expect(await fs.readFile(markerPath(storeRoot), 'utf8')).toBe(v2)- await operator.release()-- const foreign = v2Fence(dev, String(BigInt(ino) + 1n))- await writeFence(storeRoot, foreign)- await expect(- lease(storeRoot).acquireForRecovery({- expectedWriterFenceSha256: sha256(foreign),- assertPhysicalFenceHeld,- })- ).rejects.toMatchObject({- reason: 'writer_locked',- transientWriterContention: false,- detail: 'database_identity_changed',- })- expect(await fs.readFile(markerPath(storeRoot), 'utf8')).toBe(foreign)- })-- it('T9: assertInitialized and assertWriterOwnership propagate ownership_lost', async () => {- const store = freshStore()- await store.initialize()- expect(store.isAvailable()).toBe(true)- // Witness: the guarded call succeeds while the writer is held.- await store.cleanupExpired()-- await (store as unknown as { writerLease: GfsStoreWriterLease }).writerLease.release()- // cleanupExpired checks assertInitialized first.- await expect(store.cleanupExpired()).rejects.toMatchObject({- code: 'writer_locked',- transientWriterContention: false,- detail: 'ownership_lost',- })- // close() reaches assertWriterOwnership through serialize, without assertInitialized.- await expect(store.close(0)).rejects.toMatchObject({- code: 'writer_locked',- transientWriterContention: false,- detail: 'ownership_lost',- })- expect(store.isAvailable()).toBe(false)- })-})diff --git a/mcp-host/src/internalTools/gfsStoreWriterLease.ts b/mcp-host/src/internalTools/gfsStoreWriterLease.tsdeleted file mode 100644index 87ac33a67..000000000--- a/mcp-host/src/internalTools/gfsStoreWriterLease.ts+++ /dev/null@@ -1,400 +0,0 @@-import Database from 'better-sqlite3'-import { createHash } from 'node:crypto'-import { constants } from 'node:fs'-import * as fs from 'node:fs/promises'-import * as path from 'node:path'-import { isPrivateStoreStatTrusted, openPrivateStoreObject } from './gfsStorePrivateFiles'--const OWNERSHIP = 'sqlite-exclusive-v1'--/**- * Closed set naming the branch that refused writer ownership. It carries no- * path, inode or device value, so it is safe to log as a structured field.- */-export type WriterFenceDetail =- | 'local_owner_active'- | 'local_owner_ambiguous'- | 'fence_unreadable'- | 'fence_snapshot_changed'- | 'legacy_fence'- | 'missing_fence_with_ledger'- | 'missing_fence_without_ledger'- | 'database_missing'- | 'database_identity_changed'- | 'sqlite_busy_verified'- | 'sqlite_busy_unverified'- | 'ownership_lost'- | 'path_identity_changed'- | 'root_path_changed'- | 'fence_changed'--export class GfsStoreWriterOwnershipError extends Error {- constructor(- message: string,- readonly detail: WriterFenceDetail,- readonly reason:- | 'writer_locked'- | 'unsupported_store_schema'- | 'corrupt_store_ledger' = 'writer_locked',- readonly transientWriterContention = false- ) {- super(message)- }-}--/**- * The fence a successful acquisition verified. A v2 fence also recorded the- * database device, which changes when a persistent disk is reattached under- * another device node; only its inode is compared.- */-export interface GfsStoreWriterFenceAcceptance {- fenceSchema: 2 | 3- storedDevice?: string- currentDevice: string-}--interface KnownWriterFence {- schemaVersion: 2 | 3- databaseInode: string- databaseDevice?: string-}--/**- * v2 fences ({schemaVersion:2, ownership, databaseDevice, databaseInode}) stay- * on disk unchanged on Hosts that wrote them; v3 omits the device. Both are- * accepted by ownership and inode. Anything else is legacy or foreign.- */-function parseKnownFence(marker: string): KnownWriterFence | undefined {- try {- const parsed = JSON.parse(marker) as {- schemaVersion?: unknown- ownership?: unknown- databaseInode?: unknown- databaseDevice?: unknown- }- if (- (parsed.schemaVersion !== 2 && parsed.schemaVersion !== 3) ||- parsed.ownership !== OWNERSHIP ||- typeof parsed.databaseInode !== 'string'- )- return undefined- return {- schemaVersion: parsed.schemaVersion,- databaseInode: parsed.databaseInode,- databaseDevice:- parsed.schemaVersion === 2 && typeof parsed.databaseDevice === 'string'- ? parsed.databaseDevice- : undefined,- }- } catch {- /* An operator can repair the exact hashed interrupted fence. */- return undefined- }-}--interface OperatorOwnershipTransition {- expectedWriterFenceSha256: string | 'absent'- assertPhysicalFenceHeld(): Promise<void>-}--/**- * Kernel ownership is released on process death. Database and sentinel inodes- * stay in place; old O_EXCL binaries remain fenced even during operator repair.- */-export class GfsStoreWriterLease {- private static readonly localOwners = new Map<string, GfsStoreWriterLease>()- private database?: Database.Database- private databaseHandle?: fs.FileHandle- private markerHandle?: fs.FileHandle- private rootHandle?: fs.FileHandle- private localOwner = false- // True while this lease is acquiring or releasing. Either ends on its own,- // and the next attempt judges the store from scratch.- private inTransition = false- private verifiedMarker?: string- private acceptance?: GfsStoreWriterFenceAcceptance- private readonly databasePath: string- private readonly markerPath: string-- constructor(- private readonly root: string,- private readonly allowBootstrap: boolean- ) {- this.databasePath = path.join(root, 'writer-v2.sqlite')- this.markerPath = path.join(root, 'writer.lock')- }-- acquire(): Promise<void> {- return this.acquireInternal()- }-- /** Internal operator helper only; never exposed through Host tools or RPC. */- acquireForRecovery(transition: OperatorOwnershipTransition): Promise<void> {- return this.acquireInternal(transition)- }-- /** The fence verified by the last successful acquisition of this lease. */- get lastAcquire(): GfsStoreWriterFenceAcceptance | undefined {- return this.acceptance- }-- private async acquireInternal(transition?: OperatorOwnershipTransition): Promise<void> {- const priorOwner = GfsStoreWriterLease.localOwners.get(this.root)- if (priorOwner) {- let transient = priorOwner.inTransition- try {- if (!transient && priorOwner.verifiedMarker) {- await priorOwner.verifyHeld()- await priorOwner.verifyOwnershipPaths(priorOwner.verifiedMarker)- transient = true- }- } catch {- // Ambiguous or changed ownership is never a retry signal, unless the- // owner started releasing while it was being checked.- transient = priorOwner.inTransition- }- throw new GfsStoreWriterOwnershipError(- 'Writer already active',- transient ? 'local_owner_active' : 'local_owner_ambiguous',- 'writer_locked',- transient- )- }- GfsStoreWriterLease.localOwners.set(this.root, this)- this.localOwner = true- this.inTransition = true- this.acceptance = undefined- let contentionMarker: string | undefined- try {- await transition?.assertPhysicalFenceHeld()- this.rootHandle = await openPrivateStoreObject(- this.root,- 'directory',- constants.O_RDONLY,- true,- transition?.assertPhysicalFenceHeld- )- let marker: string | undefined- try {- this.markerHandle = await openPrivateStoreObject(- this.markerPath,- 'file',- transition ? constants.O_RDWR : constants.O_RDONLY,- false- )- marker = await this.markerHandle.readFile('utf8')- } catch (error) {- if ((error as NodeJS.ErrnoException).code !== 'ENOENT')- throw new GfsStoreWriterOwnershipError(- 'Legacy or ambiguous writer fence',- 'fence_unreadable'- )- }- if (transition) {- const actual =- marker === undefined ? 'absent' : createHash('sha256').update(marker).digest('hex')- if (actual !== transition.expectedWriterFenceSha256)- throw new GfsStoreWriterOwnershipError('Writer fence changed', 'fence_snapshot_changed')- }- const knownFence = marker === undefined ? undefined : parseKnownFence(marker)- if (marker !== undefined && !knownFence && !transition)- throw new GfsStoreWriterOwnershipError('Legacy or ambiguous writer fence', 'legacy_fence')- if (marker === undefined && !this.allowBootstrap && !transition) {- let ledgerExists = true- try {- await fs.lstat(path.join(this.root, 'ledger-v1.json'))- } catch (error) {- if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error- ledgerExists = false- }- // Legacy empty execution leases were not durable. Absence of a lock- // cannot prove their executor stopped; only a physical fence can.- throw new GfsStoreWriterOwnershipError(- 'Operator transition required',- ledgerExists ? 'missing_fence_with_ledger' : 'missing_fence_without_ledger',- ledgerExists ? 'unsupported_store_schema' : 'corrupt_store_ledger'- )- }- if (!knownFence) {- await transition?.assertPhysicalFenceHeld()- try {- const created = await fs.open(- this.databasePath,- constants.O_RDWR | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW,- 0o600- )- try {- await transition?.assertPhysicalFenceHeld()- await created.sync()- } finally {- await created.close()- }- } catch (error) {- if ((error as NodeJS.ErrnoException).code !== 'EEXIST') throw error- }- }- // A missing/replaced database behind an existing fence is never recreated.- try {- this.databaseHandle = await openPrivateStoreObject(- this.databasePath,- 'file',- constants.O_RDWR,- false- )- } catch (error) {- if (knownFence && (error as NodeJS.ErrnoException).code === 'ENOENT')- throw new GfsStoreWriterOwnershipError('Writer database missing', 'database_missing')- throw error- }- const info = await this.databaseHandle.stat({ bigint: true })- const databaseInode = String(info.ino)- // The device is deliberately not compared: a persistent disk reattached- // under another device node keeps its inodes. Live writers stay excluded- // by BEGIN EXCLUSIVE and the descriptor/name identity checks below.- if (knownFence && knownFence.databaseInode !== databaseInode)- throw new GfsStoreWriterOwnershipError(- 'Writer database inode changed',- 'database_identity_changed'- )- if (knownFence && !transition) contentionMarker = marker- await transition?.assertPhysicalFenceHeld()- await this.databaseHandle.chmod(0o600)- this.database = new Database(this.databasePath, { timeout: 0, fileMustExist: true })- this.database.pragma('journal_mode = DELETE')- this.database.exec('BEGIN EXCLUSIVE')- // An accepted v2 or v3 fence is never rewritten; the normal-path marker- // descriptor is read-only. Only a missing fence (bootstrap) or an operator- // transition over a hashed legacy fence writes the v3 fence.- const fence =- knownFence && marker !== undefined- ? marker- : JSON.stringify({ schemaVersion: 3, ownership: OWNERSHIP, databaseInode })- if (!knownFence) {- await transition?.assertPhysicalFenceHeld()- if (!this.markerHandle) {- this.markerHandle = await fs.open(- this.markerPath,- constants.O_RDWR | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW,- 0o600- )- }- // Rewrite through the verified descriptor without unlinking the legacy- // fence. A crash leaves its inode present, still excluding old binaries.- const bytes = Buffer.from(fence)- await transition?.assertPhysicalFenceHeld()- await this.markerHandle.truncate(0)- let offset = 0- while (offset < bytes.length) {- await transition?.assertPhysicalFenceHeld()- const written = await this.markerHandle.write(- bytes,- offset,- bytes.length - offset,- offset- )- if (written.bytesWritten === 0) throw new Error('Writer fence write did not progress')- offset += written.bytesWritten- }- await transition?.assertPhysicalFenceHeld()- await this.markerHandle.truncate(bytes.length)- await transition?.assertPhysicalFenceHeld()- await this.markerHandle.sync()- }- await transition?.assertPhysicalFenceHeld()- await this.markerHandle!.chmod(0o600)- this.verifiedMarker = fence- await this.verifyHeld()- await transition?.assertPhysicalFenceHeld()- await this.rootHandle.sync()- this.acceptance = {- fenceSchema: knownFence?.schemaVersion ?? 3,- storedDevice: knownFence?.databaseDevice,- currentDevice: String(info.dev),- }- this.inTransition = false- } catch (error) {- let transient = false- if ((error as { code?: string }).code === 'SQLITE_BUSY' && contentionMarker) {- try {- await this.verifyOwnershipPaths(contentionMarker)- transient = true- } catch {- /* A changed fence is permanent recovery state. */- }- }- await this.release()- if ((error as { code?: string }).code === 'SQLITE_BUSY')- throw new GfsStoreWriterOwnershipError(- 'Writer already active',- transient ? 'sqlite_busy_verified' : 'sqlite_busy_unverified',- 'writer_locked',- transient- )- throw error- }- }-- assertHeld(): void {- if (!this.localOwner || !this.database?.open || !this.database.inTransaction)- throw new GfsStoreWriterOwnershipError('Writer ownership lost', 'ownership_lost')- }-- async verifyHeld(): Promise<void> {- this.assertHeld()- if (!this.verifiedMarker)- throw new GfsStoreWriterOwnershipError('Writer ownership lost', 'ownership_lost')- await this.verifyOwnershipPaths(this.verifiedMarker)- this.assertHeld()- }-- private async verifyOwnershipPaths(expectedMarker: string): Promise<void> {- for (const [filename, handle, kind] of [- [this.root, this.rootHandle, 'directory'],- [this.markerPath, this.markerHandle, 'file'],- [this.databasePath, this.databaseHandle, 'file'],- ] as const) {- if (!handle) throw new GfsStoreWriterOwnershipError('Writer ownership lost', 'ownership_lost')- const metadata = await handle.stat()- const opened = await handle.stat({ bigint: true })- const named = await fs.lstat(filename, { bigint: true })- if (- !isPrivateStoreStatTrusted(metadata, kind) ||- named.isSymbolicLink() ||- named.dev !== opened.dev ||- named.ino !== opened.ino- )- throw new GfsStoreWriterOwnershipError('Writer inode changed', 'path_identity_changed')- }- if ((await fs.realpath(this.root)) !== this.root)- throw new GfsStoreWriterOwnershipError('Writer path changed', 'root_path_changed')- const marker = await openPrivateStoreObject(this.markerPath, 'file', constants.O_RDONLY, false)- try {- if ((await marker.readFile('utf8')) !== expectedMarker)- throw new GfsStoreWriterOwnershipError('Writer fence changed', 'fence_changed')- } finally {- await marker.close()- }- }-- async release(): Promise<void> {- // Closing the connection rolls back its lock-only transaction and releases- // kernel ownership. No on-disk ownership inode is removed.- this.inTransition = true- this.database?.close()- this.database = undefined- this.verifiedMarker = undefined- const outcomes = await Promise.allSettled([- this.databaseHandle?.close(),- this.markerHandle?.close(),- this.rootHandle?.close(),- ])- this.databaseHandle = undefined- this.markerHandle = undefined- this.rootHandle = undefined- if (this.localOwner && GfsStoreWriterLease.localOwners.get(this.root) === this)- GfsStoreWriterLease.localOwners.delete(this.root)- this.localOwner = false- const failure = outcomes.find(outcome => outcome.status === 'rejected')- if (failure?.status === 'rejected') throw failure.reason- }-}diff --git a/mcp-host/src/internalTools/gfsStoreWriterLeaseTransition.test.ts b/mcp-host/src/internalTools/gfsStoreWriterLeaseTransition.test.tsdeleted file mode 100644index 622b798d8..000000000--- a/mcp-host/src/internalTools/gfsStoreWriterLeaseTransition.test.ts+++ /dev/null@@ -1,106 +0,0 @@-import { afterEach, describe, expect, it } from 'vitest'-import * as fs from 'node:fs/promises'-import { tmpdir } from 'node:os'-import { join } from 'node:path'-import { GfsDownloadStore } from './gfsDownloadStore'-import { GfsStoreWriterLease } from './gfsStoreWriterLease'--/**- * A same-process writer that is still acquiring, or already releasing, is a- * transition that ends by itself: the next attempt re-judges the store from- * scratch. Only a held writer whose fence or inodes changed is permanent.- * `acquire()` reads the in-process owner synchronously, so starting it right- * after another lease's `acquire()`/`release()` lands inside that transition.- */-const roots: string[] = []-const leases: GfsStoreWriterLease[] = []--async function v2StoreRoot(): Promise<string> {- const value = await fs.mkdtemp(join(tmpdir(), 'gfs-lease-transition-'))- roots.push(value)- const store = new GfsDownloadStore(value)- await store.initialize()- await store.close()- return join(await fs.realpath(value), '.gfs-download-store')-}--function lease(storeRoot: string): GfsStoreWriterLease {- const value = new GfsStoreWriterLease(storeRoot, false)- leases.push(value)- return value-}--afterEach(async () => {- for (const value of leases.splice(0)) await value.release()- for (const value of roots.splice(0)) await fs.rm(value, { recursive: true, force: true })-})--describe('GFS writer lease during a same-process ownership transition', () => {- it('reports a writer that is releasing as transient contention', async () => {- const storeRoot = await v2StoreRoot()- const first = lease(storeRoot)- await first.acquire()- first.assertHeld()-- const releasing = first.release()- await expect(lease(storeRoot).acquire()).rejects.toMatchObject({- reason: 'writer_locked',- transientWriterContention: true,- })- await releasing-- // Witness: the transition really ended and the next attempt owns the store.- const next = lease(storeRoot)- await next.acquire()- next.assertHeld()- })-- it('reports a writer that starts releasing during the contention check as transient', async () => {- const storeRoot = await v2StoreRoot()- const first = lease(storeRoot)- await first.acquire()-- const attempt = lease(storeRoot).acquire()- const releasing = first.release()- await expect(attempt).rejects.toMatchObject({- reason: 'writer_locked',- transientWriterContention: true,- })- await releasing- expect(() => first.assertHeld()).toThrow('Writer ownership lost')-- const next = lease(storeRoot)- await next.acquire()- next.assertHeld()- })-- it('reports a writer that is still acquiring as transient contention', async () => {- const storeRoot = await v2StoreRoot()- const first = lease(storeRoot)-- const acquiring = first.acquire()- await expect(lease(storeRoot).acquire()).rejects.toMatchObject({- reason: 'writer_locked',- transientWriterContention: true,- })- await acquiring- // Witness: the in-flight acquisition completed and holds the lock.- first.assertHeld()- })-- it('keeps a held writer whose fence changed as permanent recovery state', async () => {- const storeRoot = await v2StoreRoot()- const first = lease(storeRoot)- await first.acquire()- // Witness: before the change the same contention is transient.- await expect(lease(storeRoot).acquire()).rejects.toMatchObject({- transientWriterContention: true,- })-- await fs.writeFile(join(storeRoot, 'writer.lock'), '{bad')- await expect(lease(storeRoot).acquire()).rejects.toMatchObject({- reason: 'writer_locked',- transientWriterContention: false,- })- })-})diff --git a/mcp-host/src/workspace/__tests__/gfsCallerRootBinding.test.ts b/mcp-host/src/workspace/__tests__/gfsCallerRootBinding.test.tsindex 5b21df271..d28a6166f 100644--- a/mcp-host/src/workspace/__tests__/gfsCallerRootBinding.test.ts+++ b/mcp-host/src/workspace/__tests__/gfsCallerRootBinding.test.ts@@ -41,6 +41,18 @@ describe('NativeRegistry GFS caller file-tool binding', () => {fs.rmSync(root, { recursive: true, force: true })})+ /**+ * Host-root accounting the file tools must never reach. The filesystem store+ * writes none, so tests seed the protected pre-#1028 namespace after the+ * store has initialized.+ */+ function seedHostAccounting(): string {+ const ledger = path.join(root, '.gfs-download-store', 'ledger-v1.json')+ fs.mkdirSync(path.dirname(ledger), { recursive: true, mode: 0o700 })+ fs.writeFileSync(ledger, 'accounting-sentinel', { mode: 0o600 })+ return ledger+ }+function source(): IncomingMessage {return {content: 'process file',@@ -89,7 +101,7 @@ describe('NativeRegistry GFS caller file-tool binding', () => {expect(fs.existsSync(path.join(callerRoot, 'own.txt'))).toBe(true)expect(fs.existsSync(path.join(root, 'own.txt'))).toBe(false)- const ledger = path.join(root, '.gfs-download-store', 'ledger-v1.json')+ const ledger = seedHostAccounting()const before = fs.readFileSync(ledger, 'utf-8')const directRead = await registryForCaller.get('file_read')!.execute({path: '.gfs-download-store/ledger-v1.json',@@ -147,7 +159,7 @@ describe('NativeRegistry GFS caller file-tool binding', () => {const provider = new ScopedWorkspaceProvider(root)const lexicalCallerRoot = provider.forSource(source()).userRootPathfs.rmSync(lexicalCallerRoot, { recursive: true, force: true })- fs.symlinkSync(path.join(root, '.gfs-download-store'), lexicalCallerRoot)+ fs.symlinkSync(path.dirname(seedHostAccounting()), lexicalCallerRoot)const binding = resolveCallerRootBinding(provider, source())expect(binding.root).toBeUndefined()@@ -183,8 +195,8 @@ describe('NativeRegistry GFS caller file-tool binding', () => {store = new GfsDownloadStore(root)stores.push(store)await store.initialize()- const accountingRoot = path.join(root, '.gfs-download-store')- const ledger = path.join(accountingRoot, 'ledger-v1.json')+ const ledger = seedHostAccounting()+ const accountingRoot = path.dirname(ledger)const before = fs.readFileSync(ledger, 'utf-8')fs.symlinkSync(accountingRoot, path.join(root, 'users'))const provider = new ScopedWorkspaceProvider(root)@@ -219,7 +231,7 @@ describe('NativeRegistry GFS caller file-tool binding', () => {const binding = resolveCallerRootBinding(provider, source())expect(binding.root).toBeDefined()const bound = registry(binding.root)- const ledger = path.join(root, '.gfs-download-store', 'ledger-v1.json')+ const ledger = seedHostAccounting()const before = fs.readFileSync(ledger, 'utf-8')fs.rmSync(binding.root!, { recursive: true, force: true })diff --git a/scripts/ci/pinned-vitest-cases/mcp-host.json b/scripts/ci/pinned-vitest-cases/mcp-host.jsonindex 396236224..5bae17df7 100644--- a/scripts/ci/pinned-vitest-cases/mcp-host.json+++ b/scripts/ci/pinned-vitest-cases/mcp-host.json@@ -73,11 +73,11 @@},{"suite": "taskExecutor.gfsExecutionSafety.test.ts",- "fullName": "X1-shell: an inherited legacy lease does not stop an approved shell (#1019)"+ "fullName": "X1-shell: a store left by the pre-#1028 image does not stop an approved shell (#1019)"},{"suite": "taskExecutor.gfsExecutionSafety.test.ts",- "fullName": "X1-delivery: an inherited legacy lease is discarded and GFS delivery stays advertised (#1019)"+ "fullName": "X1-delivery: a store left by the pre-#1028 image is ignored and GFS delivery stays advertised (#1019)"},{"suite": "taskExecutor.gfsExecutionSafety.test.ts",@@ -91,49 +91,21 @@"suite": "taskExecutor.gfsExecutionSafety.test.ts","fullName": "X3-TE: a shell dispatch inside TaskExecutor makes zero GFS download store calls (#1019)"},- {- "suite": "gfsDownloadStoreRecovery.test.ts",- "fullName": "legacy processing leases after #1019 S1: discards an expired foreign-session lease left by a crashed Host and admits downloads"- },- {- "suite": "gfsDownloadStoreRecovery.test.ts",- "fullName": "legacy processing leases after #1019 S1b: discards a non-expired foreign-session lease left by a crashed Host and admits downloads"- },{"suite": "taskExecutor.gfsExecutionSafety.test.ts",- "fullName": "X2b: a store at corrupt_store_ledger still answers admitted inline reads, accessible and resolve"- },- {- "suite": "gfsDownloadStoreRecovery.test.ts",- "fullName": "legacy processing leases after #1019 S8: a discard whose persist fails before the rename leaves the ledger byte-identical and is retried by the next initialize"- },- {- "suite": "gfsDownloadStoreRecovery.test.ts",- "fullName": "legacy processing leases after #1019 S8b: a discard whose directory sync fails after the rename warns with an unknown outcome and does not count the discard"- },- {- "suite": "gfsDownloadStoreRecovery.test.ts",- "fullName": "legacy processing leases after #1019 S9: reports the current quarantined-record count after reconcile without double counting across boots"- },- {- "suite": "gfsDownloadStoreRecovery.test.ts",- "fullName": "legacy processing leases after #1019 S1c: discards several legacy leases from different foreign sessions in one initialize and counts each"- },- {- "suite": "gfsDownloadStoreRecovery.test.ts",- "fullName": "legacy processing leases after #1019 S10: a legacy lease next to a half-finished transfer: the lease is discarded and the transfer is quarantined in the same initialize"+ "fullName": "X2b: a store at workspace_unavailable still answers admitted inline reads, accessible and resolve"},{"suite": "taskExecutor.gfsExecutionSafety.test.ts",- "fullName": "X1-shell-live: an inherited non-expired legacy lease does not stop an approved shell (#1019)"+ "fullName": "X1-shell-live: a store with a non-expired legacy lease left by the pre-#1028 image does not stop an approved shell (#1019)"},{"suite": "taskExecutor.gfsExecutionSafety.test.ts",- "fullName": "X1-delivery-live: an inherited non-expired legacy lease is discarded and GFS delivery stays advertised (#1019)"+ "fullName": "X1-delivery-live: a store with a non-expired legacy lease left by the pre-#1028 image is ignored and GFS delivery stays advertised (#1019)"},{"suite": "taskExecutor.gfsExecutionSafety.test.ts",- "fullName": "X6: an approved shell runs while the store is unavailable writer contention"+ "fullName": "X6: an approved shell runs while the store is unavailable never initialized"},{"suite": "taskExecutor.gfsExecutionSafety.test.ts",@@ -141,7 +113,7 @@},{"suite": "taskExecutor.gfsExecutionSafety.test.ts",- "fullName": "X6: an approved shell runs while the store is unavailable initialize rejected by an EIO persist during the legacy discard"+ "fullName": "X6: an approved shell runs while the store is unavailable initialize rejected with workspace_unavailable"},{"suite": "shell.detachedStdio.test.ts",@@ -168,51 +140,379 @@"fullName": "CLERUM_TOOL_PROGRESS_INTERVAL_MS (#1028 P2) P2-b: malformed and sub-second values stop startup with the exact message and do not echo the value"},{- "suite": "gfsStoreWriterFence.test.ts",- "fullName": "GFS writer fence across a persistent-disk reattach (#1028) T1: accepts a v2 fence whose device changed when its inode matches, keeps it byte-for-byte and logs both devices"+ "suite": "taskExecutor.gfsLiveApproval.integration.test.ts",+ "fullName": "requires live shell approval while the GFS download store is unavailable: store closed"},{- "suite": "gfsStoreWriterFence.test.ts",- "fullName": "GFS writer fence across a persistent-disk reattach (#1028) T2: refuses a v2 fence naming another database inode as permanent database_identity_changed"+ "suite": "taskExecutor.gfsLiveApproval.integration.test.ts",+ "fullName": "requires live shell approval while the GFS download store is unavailable: store never initialized"},{- "suite": "gfsStoreWriterFence.test.ts",- "fullName": "GFS writer fence across a persistent-disk reattach (#1028) T3: bootstrap writes the v3 fence, a v3 reopen acquires, and reacquisition leaves its hash unchanged"+ "suite": "gfsDownloadStore.test.ts",+ "fullName": "GFS download store: publication F1: publish writes meta.json before source and every visible source has a meta.json"},{- "suite": "gfsStoreWriterFence.test.ts",- "fullName": "GFS writer fence across a persistent-disk reattach (#1028) T4: a second real SQLite connection excludes the writer as verified transient contention while v2 stays on disk"+ "suite": "gfsDownloadStore.test.ts",+ "fullName": "GFS download store: publication F4: an EIO while writing meta.json fails that publish only and the next admission succeeds"},{- "suite": "gfsStoreWriterFence.test.ts",- "fullName": "GFS writer fence across a persistent-disk reattach (#1028) T5: refuses the empty fence as legacy_fence and leaves it in place"+ "suite": "gfsDownloadStore.test.ts",+ "fullName": "GFS download store: reuse F6: reuse deletes a directory whose content no longer matches and returns undefined"},{- "suite": "gfsStoreWriterFence.test.ts",- "fullName": "GFS writer fence across a persistent-disk reattach (#1028) T5: refuses the unknown schema version fence as legacy_fence and leaves it in place"+ "suite": "gfsDownloadStore.test.ts",+ "fullName": "GFS download store: quotas and eviction F8: a caller over quota evicts its own oldest completed downloads, never another caller's"},{- "suite": "gfsStoreWriterFence.test.ts",- "fullName": "GFS writer fence across a persistent-disk reattach (#1028) T6: operator recovery accepts a v2 fence with another device in place and refuses another inode"+ "suite": "gfsDownloadStore.test.ts",+ "fullName": "GFS download store: quotas and eviction F10: when eviction cannot make room nothing is deleted"},{- "suite": "gfsDownloadStoreRecovery.test.ts",- "fullName": "first boot of a Host locked by a persistent-disk reattach (#1028) T7: recovers the store behind a stale-device v2 fence and keeps every record it must keep"+ "suite": "gfsDownloadStore.test.ts",+ "fullName": "GFS download store: sweep F16: the sweep removes incomplete directories of every shape and keeps complete ones"},{"suite": "gfsRuntime.test.ts",- "fullName": "GFS runtime bootstrap T8: the serialized recovery-required line names the writer refusal branch as writerDetail"+ "fullName": "GFS runtime bootstrap a failed initialize is logged with its code and the next cycle makes the store available"},{- "suite": "gfsStoreWriterFence.test.ts",- "fullName": "GFS writer fence across a persistent-disk reattach (#1028) T9: assertInitialized and assertWriterOwnership propagate ownership_lost"+ "suite": "gfsRuntime.test.ts",+ "fullName": "GFS runtime bootstrap stop joins the cycle in flight and closes the store"},{- "suite": "taskExecutor.gfsLiveApproval.integration.test.ts",- "fullName": "requires live shell approval while the GFS download store is unavailable: store closed"+ "suite": "gfsDownloadStoreBoundaries.test.ts",+ "fullName": "GFS download store boundaries: meta.json validation 'V1: malformed JSON is incomplete'"},{- "suite": "taskExecutor.gfsLiveApproval.integration.test.ts",- "fullName": "requires live shell approval while the GFS download store is unavailable: store never initialized"+ "suite": "gfsDownloadStoreBoundaries.test.ts",+ "fullName": "GFS download store boundaries: meta.json validation 'V2: meta one byte over the size limit…'"+ },+ {+ "suite": "gfsDownloadStoreBoundaries.test.ts",+ "fullName": "GFS download store boundaries: meta.json validation 'V3: meta exactly at the size limit is…'"+ },+ {+ "suite": "gfsDownloadStoreBoundaries.test.ts",+ "fullName": "GFS download store boundaries: meta.json validation 'V4: wrong schemaVersion is incomplete'"+ },+ {+ "suite": "gfsDownloadStoreBoundaries.test.ts",+ "fullName": "GFS download store boundaries: meta.json validation 'V5: meta id that differs from its dir…'"+ },+ {+ "suite": "gfsDownloadStoreBoundaries.test.ts",+ "fullName": "GFS download store boundaries: meta.json validation 'V6: expiresAt before createdAt is inc…'"+ },+ {+ "suite": "gfsDownloadStoreBoundaries.test.ts",+ "fullName": "GFS download store boundaries: meta.json validation 'V7: meta exactly at the retention bou…'"+ },+ {+ "suite": "gfsDownloadStoreBoundaries.test.ts",+ "fullName": "GFS download store boundaries: meta.json validation 'V8: meta past the retention bound by …'"+ },+ {+ "suite": "gfsDownloadStoreBoundaries.test.ts",+ "fullName": "GFS download store boundaries: meta.json validation 'V9: createdAt exactly one minute ahea…'"+ },+ {+ "suite": "gfsDownloadStoreBoundaries.test.ts",+ "fullName": "GFS download store boundaries: meta.json validation 'V10: createdAt more than one minute a…'"+ },+ {+ "suite": "gfsDownloadStoreBoundaries.test.ts",+ "fullName": "GFS download store boundaries: meta.json validation 'V12: sizeBytes different from the sou…'"+ },+ {+ "suite": "gfsDownloadStoreBoundaries.test.ts",+ "fullName": "GFS download store boundaries: meta.json validation V11: sizeBytes above maxFileBytes is incomplete"+ },+ {+ "suite": "gfsDownloadStoreBoundaries.test.ts",+ "fullName": "GFS download store boundaries: meta.json validation V13: an adopted entry with non-private modes is counted but never served"+ },+ {+ "suite": "gfsDownloadStoreBoundaries.test.ts",+ "fullName": "GFS download store boundaries: meta.json validation V14: a published copy with non-private modes is not reused or read"+ },+ {+ "suite": "gfsDownloadStoreBoundaries.test.ts",+ "fullName": "GFS download store boundaries: meta.json validation V15: an admission past the retention window is refused"+ },+ {+ "suite": "gfsDownloadStoreBoundaries.test.ts",+ "fullName": "GFS download store boundaries: quota and capacity Q1: caller bytes exactly at the budget are admitted and one byte more is refused"+ },+ {+ "suite": "gfsDownloadStoreBoundaries.test.ts",+ "fullName": "GFS download store boundaries: quota and capacity Q2: caller file count at the limit is refused and one below is admitted"+ },+ {+ "suite": "gfsDownloadStoreBoundaries.test.ts",+ "fullName": "GFS download store boundaries: quota and capacity Q3: Host bytes exactly at the budget are admitted and one byte more is refused"+ },+ {+ "suite": "gfsDownloadStoreBoundaries.test.ts",+ "fullName": "GFS download store boundaries: quota and capacity Q4: Host file count at the limit is refused and one below is admitted"+ },+ {+ "suite": "gfsDownloadStoreBoundaries.test.ts",+ "fullName": "GFS download store boundaries: quota and capacity Q5: free space exactly at the threshold is admitted and one byte less is refused"+ },+ {+ "suite": "gfsDownloadStoreBoundaries.test.ts",+ "fullName": "GFS download store boundaries: quota and capacity Q6: a statfs failure refuses that admission loudly and the next one succeeds"+ },+ {+ "suite": "gfsDownloadStoreBoundaries.test.ts",+ "fullName": "GFS download store boundaries: quota and capacity Q7: a zero-byte file publishes, reads, reuses and has an empty prefix"+ },+ {+ "suite": "gfsDownloadStoreBoundaries.test.ts",+ "fullName": "GFS download store boundaries: quota and capacity Q9: Host eviction takes adopted copies before any published copy"+ },+ {+ "suite": "gfsDownloadStoreBoundaries.test.ts",+ "fullName": "GFS download store boundaries: quota and capacity Q10: caller eviction takes adopted copies in its own directory before its published copies"+ },+ {+ "suite": "gfsDownloadStoreBoundaries.test.ts",+ "fullName": "GFS download store boundaries: quota and capacity Q11: published copies are evicted least recently used first"+ },+ {+ "suite": "gfsDownloadStoreBoundaries.test.ts",+ "fullName": "GFS download store boundaries: quota and capacity Q12: when every copy is pinned admission fails with the quota code and succeeds after release"+ },+ {+ "suite": "gfsDownloadStoreBoundaries.test.ts",+ "fullName": "GFS download store boundaries: expiry E1: reuse matches until one millisecond before expiry"+ },+ {+ "suite": "gfsDownloadStoreBoundaries.test.ts",+ "fullName": "GFS download store boundaries: expiry E2: a managed read succeeds until one millisecond before expiry"+ },+ {+ "suite": "gfsDownloadStoreBoundaries.test.ts",+ "fullName": "GFS download store boundaries: expiry E3: the sweep removes a copy exactly at its expiry"+ },+ {+ "suite": "gfsDownloadStoreBoundaries.test.ts",+ "fullName": "GFS download store boundaries: in-process concurrency C1: two concurrent downloads of one source by one caller both publish and reuse returns one of them"+ },+ {+ "suite": "gfsDownloadStoreBoundaries.test.ts",+ "fullName": "GFS download store boundaries: in-process concurrency C2: two callers downloading one source each reuse their own copy"+ },+ {+ "suite": "gfsDownloadStoreBoundaries.test.ts",+ "fullName": "GFS download store boundaries: in-process concurrency C3: a sweep during an active transfer leaves its partial file alone"+ },+ {+ "suite": "gfsDownloadStoreBoundaries.test.ts",+ "fullName": "GFS download store boundaries: in-process concurrency C4: a sweep requested during publication runs after it and keeps the copy"+ },+ {+ "suite": "gfsDownloadStoreBoundaries.test.ts",+ "fullName": "GFS download store boundaries: in-process concurrency C5: close requested during publication waits for it"+ },+ {+ "suite": "gfsDownloadStoreBoundaries.test.ts",+ "fullName": "GFS download store boundaries: in-process concurrency C7: fail() after a partial write removes the directory and releases the reservation"+ },+ {+ "suite": "gfsDownloadStoreBoundaries.test.ts",+ "fullName": "GFS download store boundaries: in-process concurrency C8: fail() after publish is refused and the copy stays readable"+ },+ {+ "suite": "gfsDownloadStoreBoundaries.test.ts",+ "fullName": "GFS download store boundaries: integrity 'I2: truncated source on reuse'"+ },+ {+ "suite": "gfsDownloadStoreBoundaries.test.ts",+ "fullName": "GFS download store boundaries: integrity 'I4: source replaced by a directory on…'"+ },+ {+ "suite": "gfsDownloadStoreBoundaries.test.ts",+ "fullName": "GFS download store boundaries: integrity 'I3: truncated source on managed read'"+ },+ {+ "suite": "gfsDownloadStoreBoundaries.test.ts",+ "fullName": "GFS download store boundaries: integrity 'I5: source replaced by a directory on…'"+ },+ {+ "suite": "gfsDownloadStoreProvenance.test.ts",+ "fullName": "GFS download store provenance: planted copies T-S1: a planted entry in the caller's directory is never reused"+ },+ {+ "suite": "gfsDownloadStoreProvenance.test.ts",+ "fullName": "GFS download store provenance: planted copies T-S2: a planted entry is never read through the managed path"+ },+ {+ "suite": "gfsDownloadStoreProvenance.test.ts",+ "fullName": "GFS download store provenance: planted copies T-S3: a planted directory with a published id is removed and the published copy is untouched"+ },+ {+ "suite": "gfsDownloadStoreProvenance.test.ts",+ "fullName": "GFS download store provenance: planted copies T-S4: a planted entry is charged to the directory that contains it"+ },+ {+ "suite": "gfsDownloadStoreProvenance.test.ts",+ "fullName": "GFS download store provenance: planted copies T-R1: a restart keeps the copy for accounting and cleanup but does not reuse it"+ },+ {+ "suite": "gfsDownloadStoreProvenance.test.ts",+ "fullName": "GFS download store provenance: planted copies P7: a planted entry with the caller's own identity is neither reused nor read"+ },+ {+ "suite": "gfsDownloadStoreProvenance.test.ts",+ "fullName": "GFS download store provenance: planted copies P8: a meta identity that differs from its directory grants nothing to either caller"+ },+ {+ "suite": "gfsDownloadStoreProvenance.test.ts",+ "fullName": "GFS download store provenance: planted copies P9: duplicate ids without a published entry are all removed"+ },+ {+ "suite": "gfsDownloadStoreProvenance.test.ts",+ "fullName": "GFS download store provenance: planted copies P10: a planted directory with an active id is removed and the transfer still publishes"+ },+ {+ "suite": "gfsDownloadStoreProvenance.test.ts",+ "fullName": "GFS download store provenance: planted copies P11: symlink as input directory"+ },+ {+ "suite": "gfsDownloadStoreProvenance.test.ts",+ "fullName": "GFS download store provenance: planted copies P11: symlink as meta.json"+ },+ {+ "suite": "gfsDownloadStoreProvenance.test.ts",+ "fullName": "GFS download store provenance: planted copies P11: symlink as source"+ },+ {+ "suite": "gfsDownloadStoreProvenance.test.ts",+ "fullName": "GFS download store provenance: planted copies P15: a .gfs-downloads that is a file is removed and the caller can still download"+ },+ {+ "suite": "gfsDownloadStoreProvenance.test.ts",+ "fullName": "GFS download store provenance: planted copies P16: a symlinked caller directory is neither listed nor accepted as a caller root"+ },+ {+ "suite": "gfsDownloadStoreProvenance.test.ts",+ "fullName": "GFS download store provenance: planted copies P17: a hardlinked published source is not reused and is downloaded again"+ },+ {+ "suite": "gfsManagedImage.test.ts",+ "fullName": "GFS download store errors at the tool boundary surfaces store code caller_mismatch to the model"+ },+ {+ "suite": "gfsManagedImage.test.ts",+ "fullName": "GFS download store errors at the tool boundary surfaces store code caller_quota_exceeded to the model"+ },+ {+ "suite": "gfsManagedImage.test.ts",+ "fullName": "GFS download store errors at the tool boundary surfaces store code download_busy to the model"+ },+ {+ "suite": "gfsManagedImage.test.ts",+ "fullName": "GFS download store errors at the tool boundary surfaces store code download_expired to the model"+ },+ {+ "suite": "gfsManagedImage.test.ts",+ "fullName": "GFS download store errors at the tool boundary surfaces store code download_missing to the model"+ },+ {+ "suite": "gfsManagedImage.test.ts",+ "fullName": "GFS download store errors at the tool boundary surfaces store code host_quota_exceeded to the model"+ },+ {+ "suite": "gfsManagedImage.test.ts",+ "fullName": "GFS download store errors at the tool boundary surfaces store code publication_cancelled to the model"+ },+ {+ "suite": "gfsManagedImage.test.ts",+ "fullName": "GFS download store errors at the tool boundary surfaces store code storage_write_failed to the model"+ },+ {+ "suite": "gfsManagedImage.test.ts",+ "fullName": "GFS download store errors at the tool boundary surfaces store code workspace_unavailable to the model"+ },+ {+ "suite": "gfsManagedImage.test.ts",+ "fullName": "GFS download store errors at the tool boundary surfaces download admission code caller_mismatch to the model"+ },+ {+ "suite": "gfsManagedImage.test.ts",+ "fullName": "GFS download store errors at the tool boundary surfaces download admission code caller_quota_exceeded to the model"+ },+ {+ "suite": "gfsManagedImage.test.ts",+ "fullName": "GFS download store errors at the tool boundary surfaces download admission code download_busy to the model"+ },+ {+ "suite": "gfsManagedImage.test.ts",+ "fullName": "GFS download store errors at the tool boundary surfaces download admission code download_expired to the model"+ },+ {+ "suite": "gfsManagedImage.test.ts",+ "fullName": "GFS download store errors at the tool boundary surfaces download admission code download_missing to the model"+ },+ {+ "suite": "gfsManagedImage.test.ts",+ "fullName": "GFS download store errors at the tool boundary surfaces download admission code host_quota_exceeded to the model"+ },+ {+ "suite": "gfsManagedImage.test.ts",+ "fullName": "GFS download store errors at the tool boundary surfaces download admission code publication_cancelled to the model"+ },+ {+ "suite": "gfsManagedImage.test.ts",+ "fullName": "GFS download store errors at the tool boundary surfaces download admission code storage_write_failed to the model"+ },+ {+ "suite": "gfsManagedImage.test.ts",+ "fullName": "GFS download store errors at the tool boundary surfaces download admission code workspace_unavailable to the model"+ },+ {+ "suite": "gfsDownloadStoreProvenance.test.ts",+ "fullName": "GFS download store provenance: planted copies P18: a caller directory replaced by a symlink after publish is not followed by the expiry sweep"+ },+ {+ "suite": "gfsDownloadStoreProvenance.test.ts",+ "fullName": "GFS download store provenance: planted copies P18: a caller directory replaced by a symlink after publish is not followed by the failed reuse"+ },+ {+ "suite": "gfsDownloadStoreProvenance.test.ts",+ "fullName": "GFS download store provenance: planted copies P19: a caller directory replaced by a symlink before publish is refused and nothing is written outside"+ },+ {+ "suite": "gfsDownloadStoreBoundaries.test.ts",+ "fullName": "GFS download store boundaries: caller isolation U1: readManagedFile answers another caller's copy exactly like a nonexistent one, without opening it"+ },+ {+ "suite": "gfsDownloadStoreBoundaries.test.ts",+ "fullName": "GFS download store boundaries: caller isolation U1: readManagedFilePrefix answers another caller's copy exactly like a nonexistent one, without opening it"+ },+ {+ "suite": "gfsDownloadStoreBoundaries.test.ts",+ "fullName": "GFS download store boundaries: caller isolation U2: an expired copy of another caller is still answered as nonexistent, not as expired"+ },+ {+ "suite": "gfsDownloadStoreBoundaries.test.ts",+ "fullName": "GFS download store boundaries: caller isolation U3: publish and fail answer another caller's transfer exactly like an unknown id"+ },+ {+ "suite": "gfsDownloadStoreBoundaries.test.ts",+ "fullName": "GFS download store boundaries: caller isolation U4: an owner id another caller pins is neither refused nor released across callers"+ },+ {+ "suite": "gfsDownloadStoreBoundaries.test.ts",+ "fullName": "GFS download store boundaries: path swapped between check and use K1: a removal whose parent is swapped after the check renames back and touches nothing outside"+ },+ {+ "suite": "gfsDownloadStoreBoundaries.test.ts",+ "fullName": "GFS download store boundaries: path swapped between check and use K2: a publication whose caller directory is swapped after the check writes nothing outside"+ },+ {+ "suite": "gfsDownloadStoreBoundaries.test.ts",+ "fullName": "GFS download store boundaries: path swapped between check and use K3: a read whose caller directory is swapped after the check serves nothing from outside"}]