Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
fix(mcp-host): preserve download accounting and live ownership
Alfredo Lopezbe5df030326e
diff --git a/docs/operations/gfs-large-file-host-downloads.md b/docs/operations/gfs-large-file-host-downloads.mdindex 8fa275991..aff5af06a 100644--- a/docs/operations/gfs-large-file-host-downloads.md+++ b/docs/operations/gfs-large-file-host-downloads.md@@ -97,8 +97,9 @@ unavailable until recovery; a replacement needs fresh GFS authorization.- The working directory and `HOME` are the caller workspace. A supplied allowlisted or dynamic `HOME` cannot relocate execution outside it.- Each command requires live user approval.- Combined retained command output is bounded to 1 MiB. Live progress is bounded to 64 KiB. Exceeding the output bound terminates the process group and returns a truthful `output_limit_exceeded` result.-- A processing lease is acquired after approval and before the child process is created. It is released only after process-group termination and output settlement. If acquisition fails, no process starts; if release fails, the result is an error and cleanup protection remains for recovery.-- Expiry does not remove a copy protected by an admitted execution lease. Recovery conservatively retains leases until their bounded deadline rather than assuming that a child died with the Host.+- A processing lease is acquired after approval and before the child process is created. Integrity checks precede its processing budget, and file expiry, lease expiry and shutdown are rechecked after durable admission. If admission becomes unavailable, it is rolled back and no process starts.+- The lease is released only after process-group termination and output settlement. A live execution protects its copy even if the durable deadline has elapsed; a timer alone does not prove physical termination. If release fails, the result is an error and cleanup protection remains.+- Recovery without a live owner conservatively retains leases until their bounded deadline rather than assuming that a child died with the Host. A failed admission rollback retains its durable reservation until that deadline without registering an execution that never started.Unix directory modes and random directory names do not provide cross-caller OS isolation when a Host shares one UID. Approved arbitrary shell access remains a documented Stage 1 residual; stronger executor isolation is separate Stage 2 work.@@ -110,9 +111,13 @@ Generic workspace tools reject direct and symlink-resolved access to `.gfs-downl- Completed copies expire after the configured TTL, seven days by default.- Host and caller quotas account for partial and completed files. Unknown or corrupt accounting fails closed rather than reporting zero usage.+- A new store publishes an atomic schema-1 ledger before accepting transfers. Every existing ledger is parsed, including empty content; invalid record or lease maps are rejected.+- A pre-existing store directory with a missing ledger is unknown accounting, including an interrupted first initialization before ledger publication. Startup rejects it and preserves retained bytes for operator recovery instead of silently resetting quota. This can require recovery after a bootstrap interruption.+- Startup does not reconstruct an accounting directory deleted in its entirety while caller copies remain. Approved shell commands share the Host UID and can destroy this state; whole-store deletion remains outside the recovery guarantee and requires operator inventory of retained copies.- Only positively identified expired entries are deleted. A cleanup failure remains charged and is observable for recovery.- Startup reconciles the ledger and partial files before the capability is advertised.- Shutdown stops new admission, drains active work where possible, and leaves unproven lease/recovery state protected.+- Pending and queued admission rechecks shutdown after asynchronous validation and persistence. Shutdown rechecks active ownership before releasing the writer lease.## Metricsdiff --git a/mcp-host/package-lock.json b/mcp-host/package-lock.jsonindex d74aa345a..e523568e4 100644--- a/mcp-host/package-lock.json+++ b/mcp-host/package-lock.json@@ -1,12 +1,12 @@{"name": "clerum-mcp-host",- "version": "0.1.488",+ "version": "0.1.489","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-mcp-host",- "version": "0.1.488",+ "version": "0.1.489","license": "SEE LICENSE IN LICENSE","dependencies": {"@anthropic-ai/sdk": "^0.32.0",diff --git a/mcp-host/package.json b/mcp-host/package.jsonindex cef9cdc9c..36bf0bf79 100644--- a/mcp-host/package.json+++ b/mcp-host/package.json@@ -1,6 +1,6 @@{"name": "clerum-mcp-host",- "version": "0.1.488",+ "version": "0.1.489","description": "MCP Host - reads Host CRD and provides LLM access via OpenAI/Claude","main": "dist/main.js","engines": {diff --git a/mcp-host/src/internalTools/gfsDownloadStore.test.ts b/mcp-host/src/internalTools/gfsDownloadStore.test.tsindex 5b0f41453..6591d1adf 100644--- a/mcp-host/src/internalTools/gfsDownloadStore.test.ts+++ b/mcp-host/src/internalTools/gfsDownloadStore.test.ts@@ -339,6 +339,142 @@ describe('GFS download store', () => {code: 'corrupt_store_ledger',})})++ 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(),+ })+ 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, '')++ 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')+ })++ 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)++ const reopened = new GfsDownloadStore(hostRoot)+ await expect(reopened.initialize()).rejects.toMatchObject({+ code: 'corrupt_store_ledger',+ })+ expect(await fs.readFile(ledgerPath, 'utf8')).toBe(persisted)+ expect(await fs.readFile(path.join(callerRoot, receipt.path), 'utf8')).toBe('fixture')+ })++ 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(),+ })+ 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.rm(ledgerPath)++ // 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('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 })+ try {+ await expect(new GfsDownloadStore(isolatedRoot).initialize()).rejects.toMatchObject({+ code: 'corrupt_store_ledger',+ })+ expect(await fs.readdir(isolatedStoreRoot)).not.toContain('ledger-v1.json')+ } finally {+ await fs.rm(isolatedRoot, { 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(),+ })+ 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')+ 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(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')+ })+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({diff --git a/mcp-host/src/internalTools/gfsDownloadStore.ts b/mcp-host/src/internalTools/gfsDownloadStore.tsindex af001866c..29f060577 100644--- a/mcp-host/src/internalTools/gfsDownloadStore.ts+++ b/mcp-host/src/internalTools/gfsDownloadStore.ts@@ -97,7 +97,8 @@ function parseLedger(raw: string): StoreLedger {parsed === null ||(parsed as { schemaVersion?: unknown }).schemaVersion !== 1 ||typeof (parsed as { records?: unknown }).records !== 'object' ||- (parsed as { records: unknown }).records === null+ (parsed as { records: unknown }).records === null ||+ Array.isArray((parsed as { records: unknown }).records))throw new GfsDownloadStoreError('corrupt_store_ledger')@@ -147,7 +148,11 @@ function parseLedger(raw: string): StoreLedger {}const rawProcessingLeases = (parsed as { processingLeases?: unknown }).processingLeasesif (rawProcessingLeases !== undefined) {- if (typeof rawProcessingLeases !== 'object' || rawProcessingLeases === null)+ if (+ typeof rawProcessingLeases !== 'object' ||+ rawProcessingLeases === null ||+ Array.isArray(rawProcessingLeases)+ )throw new GfsDownloadStoreError('corrupt_store_ledger')for (const [id, value] of Object.entries(rawProcessingLeases)) {const lease = value as GfsProcessingLeaseRecord@@ -255,20 +260,43 @@ export class GfsDownloadStore {const hostInfo = await fs.lstat(this.hostRoot)if (!hostInfo.isDirectory() || hostInfo.isSymbolicLink())throw new GfsDownloadStoreError('workspace_unavailable')- await fs.mkdir(this.storeRoot, { recursive: true, mode: 0o700 })+ // 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+ }const storeInfo = await fs.lstat(this.storeRoot)if (!storeInfo.isDirectory() || storeInfo.isSymbolicLink() || storeInfo.mode & 0o077)throw new GfsDownloadStoreError('workspace_unavailable')await this.acquireWriterLease()- let raw = ''+ let raw: string | undefinedtry {try {raw = await fs.readFile(this.ledgerPath, 'utf8')} catch (error) {if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error}- if (raw) this.ledger = parseLedger(raw)+ if (raw !== undefined) {+ // A successful read must always parse, including empty content, so a+ // truncated ledger fails closed.+ this.ledger = parseLedger(raw)+ } 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 = trueawait this.cleanupExpired()@@ -320,6 +348,8 @@ export class GfsDownloadStore {}await this.serialize(async () => {+ this.assertInitialized()+ if (this.closing) throw new GfsDownloadStoreError('download_busy')const usage = usageFor(Object.values(this.ledger.records))const callerBytes = usage.callerBytes[input.callerIdentity] ?? 0if (usage.bytes + input.sizeBytes > GFS_FILE_LIMITS.storageBytes)@@ -728,6 +758,8 @@ export class GfsDownloadStore {throw new GfsDownloadStoreError('download_busy')return this.serialize(async () => {+ this.assertInitialized()+ if (this.closing) throw new GfsDownloadStoreError('download_busy')const now = Date.now()const retained = Object.values(this.ledger.records).filter(record => record.callerIdentity === callerIdentity@@ -747,13 +779,17 @@ export class GfsDownloadStore {}}for (const record of candidates) await this.inspect(record.path, callerIdentity)+ if (this.closing) throw new GfsDownloadStoreError('download_busy')+ const admittedAt = Date.now()+ if (retained.some(record => Date.parse(record.expiresAt) <= admittedAt))+ throw new GfsDownloadStoreError('download_expired')const leaseId = randomUUID()- const expiresAt = new Date(now + requestedMs).toISOString()+ const expiresAt = new Date(admittedAt + requestedMs).toISOString()const lease: GfsProcessingLeaseRecord = {leaseId,callerIdentity,recordIds: candidates.map(record => record.id),- acquiredAt: new Date(now).toISOString(),+ acquiredAt: new Date(admittedAt).toISOString(),expiresAt,}this.ledger.processingLeases ??= {}@@ -764,6 +800,27 @@ export class GfsDownloadStore {delete this.ledger.processingLeases[leaseId]throw error}+ // Hashing and durable publication can outlast either deadline. Only+ // return a new lease while both remain valid; an already admitted+ // execution keeps its existing protection after the file's expiry.+ const publishedAt = Date.now()+ const denial = retained.some(record => Date.parse(record.expiresAt) <= publishedAt)+ ? 'download_expired'+ : this.closing || Date.parse(expiresAt) <= publishedAt+ ? 'download_busy'+ : undefined+ if (denial) {+ delete this.ledger.processingLeases[leaseId]+ try {+ await this.persist()+ } catch (error) {+ // A failed rollback retains the durable reservation until its+ // deadline, without registering an execution that never started.+ this.ledger.processingLeases[leaseId] = lease+ throw error+ }+ throw new GfsDownloadStoreError(denial)+ }this.liveProcessingLeases.add(leaseId)return { leaseId, expiresAt }})@@ -821,6 +878,12 @@ export class GfsDownloadStore {throw new GfsDownloadStoreError('download_busy')}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.liveProcessingLeases.size > 0) {+ this.closing = false+ throw new GfsDownloadStoreError('download_busy')+ }this.initialized = falsetry {await this.serialize(async () => {@@ -838,9 +901,10 @@ export class GfsDownloadStore {const removed: string[] = []let stateChanged = falsefor (const [leaseId, lease] of Object.entries(this.ledger.processingLeases ?? {})) {- if (Date.parse(lease.expiresAt) <= now) {+ // A live execution releases its lease after process-group termination.+ // The durable deadline governs recovery when no live owner remains.+ if (Date.parse(lease.expiresAt) <= now && !this.liveProcessingLeases.has(leaseId)) {delete this.ledger.processingLeases![leaseId]- this.liveProcessingLeases.delete(leaseId)stateChanged = true}}@@ -1012,7 +1076,9 @@ export class GfsDownloadStore {private hasProcessingLease(recordId: string, now: number): boolean {return Object.values(this.ledger.processingLeases ?? {}).some(- lease => Date.parse(lease.expiresAt) > now && lease.recordIds.includes(recordId)+ lease =>+ (this.liveProcessingLeases.has(lease.leaseId) || Date.parse(lease.expiresAt) > now) &&+ lease.recordIds.includes(recordId))}diff --git a/mcp-host/src/internalTools/gfsDownloadStoreProcessingLease.test.ts b/mcp-host/src/internalTools/gfsDownloadStoreProcessingLease.test.tsindex 5be8e87cf..fce95ba4e 100644--- a/mcp-host/src/internalTools/gfsDownloadStoreProcessingLease.test.ts+++ b/mcp-host/src/internalTools/gfsDownloadStoreProcessingLease.test.ts@@ -100,6 +100,217 @@ describe('GfsDownloadStore processing leases', () => {await store.close()})+ it('rejects expiry during integrity inspection before publishing a lease', async () => {+ const receipt = await publishFixture()+ const clock = vi.spyOn(Date, 'now').mockReturnValue(Date.now())+ const inspect = store.inspect.bind(store)+ vi.spyOn(store, 'inspect').mockImplementationOnce(async (...args) => {+ const verified = await inspect(...args)+ clock.mockReturnValue(Date.parse(receipt.expiresAt))+ return verified+ })++ await expect(+ store.processingLeaseProvider('caller-a').acquireProcessingLease()+ ).rejects.toMatchObject({ code: 'download_expired' })+ const ledger = JSON.parse(+ fs.readFileSync(path.join(hostRoot, '.gfs-download-store', 'ledger-v1.json'), 'utf8')+ )+ expect(Object.keys(ledger.processingLeases)).toHaveLength(0)+ await store.close()+ })++ it('starts the processing budget after integrity inspection completes', async () => {+ await publishFixture()+ const startedAt = Date.now()+ const clock = vi.spyOn(Date, 'now').mockReturnValue(startedAt)+ const inspect = store.inspect.bind(store)+ vi.spyOn(store, 'inspect').mockImplementationOnce(async (...args) => {+ const verified = await inspect(...args)+ clock.mockReturnValue(startedAt + 1_000)+ return verified+ })++ const provider = store.processingLeaseProvider('caller-a')+ const lease = await provider.acquireProcessingLease({ durationMs: 500 })+ expect(Date.parse(lease.expiresAt)).toBe(startedAt + 1_500)+ await provider.releaseProcessingLease(lease)+ await store.close()+ })++ it('rolls back a durable lease when the file expires during persistence', async () => {+ const receipt = await publishFixture()+ const clock = vi.spyOn(Date, 'now').mockReturnValue(Date.now())+ const persistedStore = store as unknown as { persist: () => Promise<void> }+ const persist = persistedStore.persist.bind(store)+ vi.spyOn(persistedStore, 'persist').mockImplementationOnce(async () => {+ await persist()+ clock.mockReturnValue(Date.parse(receipt.expiresAt))+ })++ await expect(+ store.processingLeaseProvider('caller-a').acquireProcessingLease()+ ).rejects.toMatchObject({ code: 'download_expired' })+ const ledger = JSON.parse(+ fs.readFileSync(path.join(hostRoot, '.gfs-download-store', 'ledger-v1.json'), 'utf8')+ )+ expect(Object.keys(ledger.processingLeases)).toHaveLength(0)+ expect(store.debugUsage().bytes).toBe(7)+ await store.cleanupExpired()+ expect(store.debugRecord(receipt.id)).toBeUndefined()+ await store.close()+ })++ it('rejects a processing budget exhausted while persisting admission', async () => {+ await publishFixture()+ const startedAt = Date.now()+ const clock = vi.spyOn(Date, 'now').mockReturnValue(startedAt)+ const persistedStore = store as unknown as { persist: () => Promise<void> }+ const persist = persistedStore.persist.bind(store)+ vi.spyOn(persistedStore, 'persist').mockImplementationOnce(async () => {+ await persist()+ clock.mockReturnValue(startedAt + 500)+ })++ await expect(+ store.processingLeaseProvider('caller-a').acquireProcessingLease({ durationMs: 500 })+ ).rejects.toMatchObject({ code: 'download_busy' })+ const ledger = JSON.parse(+ fs.readFileSync(path.join(hostRoot, '.gfs-download-store', 'ledger-v1.json'), 'utf8')+ )+ expect(Object.keys(ledger.processingLeases)).toHaveLength(0)+ const provider = store.processingLeaseProvider('caller-a')+ const retry = await provider.acquireProcessingLease({ durationMs: 500 })+ await provider.releaseProcessingLease(retry)+ await store.close()+ })++ it('retains a failed admission rollback until its durable deadline without a live execution', async () => {+ const receipt = await publishFixture()+ const clock = vi.spyOn(Date, 'now').mockReturnValue(Date.now())+ const persistedStore = store as unknown as { persist: () => Promise<void> }+ const persist = persistedStore.persist.bind(store)+ vi.spyOn(persistedStore, 'persist')+ .mockImplementationOnce(async () => {+ await persist()+ clock.mockReturnValue(Date.parse(receipt.expiresAt))+ })+ .mockRejectedValueOnce(new Error('rollback unavailable'))++ await expect(+ store.processingLeaseProvider('caller-a').acquireProcessingLease()+ ).rejects.toThrow('rollback unavailable')+ const ledger = JSON.parse(+ fs.readFileSync(path.join(hostRoot, '.gfs-download-store', 'ledger-v1.json'), 'utf8')+ )+ const reservations = Object.values(ledger.processingLeases) as Array<{ expiresAt: string }>+ expect(reservations).toHaveLength(1)+ expect(store.debugUsage().bytes).toBe(7)++ clock.mockReturnValue(Date.parse(reservations[0]!.expiresAt) + 1)+ await store.cleanupExpired()+ expect(store.debugRecord(receipt.id)).toBeUndefined()+ await store.close()+ })++ it.each(['inspection', 'persistence'] as const)(+ 'fences pending and queued admissions when closing during %s',+ async phase => {+ 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+ })+ if (phase === 'inspection') {+ const inspect = store.inspect.bind(store)+ vi.spyOn(store, 'inspect').mockImplementationOnce(async (...args) => {+ const verified = await inspect(...args)+ entered()+ await barrier+ return verified+ })+ } else {+ const persistedStore = store as unknown as { persist: () => Promise<void> }+ const persist = persistedStore.persist.bind(store)+ vi.spyOn(persistedStore, 'persist').mockImplementationOnce(async () => {+ await persist()+ entered()+ await barrier+ })+ }++ const provider = store.processingLeaseProvider('caller-a')+ const first = provider.acquireProcessingLease()+ await waiting+ const outcomes = Promise.allSettled([first, provider.acquireProcessingLease()])+ const closed = store.close()+ resume()++ const results = await outcomes+ await closed+ for (const result of results) {+ expect(result.status).toBe('rejected')+ if (result.status === 'rejected')+ expect(result.reason).toMatchObject({ code: 'download_busy' })+ }+ expect(fs.existsSync(path.join(callerRoot, receipt.path))).toBe(true)+ const restarted = new GfsDownloadStore(hostRoot)+ await restarted.initialize()+ expect(restarted.debugUsage().bytes).toBe(7)+ await restarted.close()+ }+ )++ 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+ })+ 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(fs.readdirSync(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()+ })+it('recovers admission when an expired record has no directory left to clean', async () => {const receipt = await publishFixture()// Crash-after-rm analogue: the directory is gone while the ledger entry and@@ -164,6 +375,23 @@ describe('GfsDownloadStore processing leases', () => {expect(store.debugRecord(receipt.id)).toBeUndefined()})+ it('protects a live execution past both deadlines until its explicit release', async () => {+ const receipt = await publishFixture()+ const provider = store.processingLeaseProvider('caller-a')+ const lease = await provider.acquireProcessingLease({ durationMs: 500 })+ const cleanupAt = Math.max(Date.parse(receipt.expiresAt), Date.parse(lease.expiresAt)) + 1++ await store.cleanupExpired(cleanupAt)+ expect(fs.existsSync(path.join(callerRoot, receipt.path))).toBe(true)+ expect(store.debugRecord(receipt.id)).toBeDefined()+ await expect(store.close(10)).rejects.toMatchObject({ code: 'download_busy' })++ await provider.releaseProcessingLease(lease)+ await store.cleanupExpired(cleanupAt)+ expect(store.debugRecord(receipt.id)).toBeUndefined()+ await store.close()+ })+it('recovers a lease conservatively after a store restart', async () => {const receipt = await publishFixture(new Date(Date.now() + 250).toISOString())const lease = await store