Skip to content

Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure

TypeScript

test(desktop): prove governed GFS CLI processing end to end

Alfredo Lopez1a909c2099ba
diff --git a/desktop-app/test/e2e-playwright/gfs-agent-large-file-cli.test.ts b/desktop-app/test/e2e-playwright/gfs-agent-large-file-cli.test.ts
new file mode 100644
index 000000000..f38971374
--- /dev/null
+++ b/desktop-app/test/e2e-playwright/gfs-agent-large-file-cli.test.ts
@@ -0,0 +1,225 @@
+/**
+ * E2E_GUARDIAN_IPC_FLOW — Electron delegates the chat/tool journey to its main
+ * process, so there is no renderer HTTP request to alias.
+ *
+ * E2E contract (e2e-test-guardian):
+ * - Real user journey: login → Files → visible upload of an exact 3,836,961-byte
+ * CSV → exact managed agent chat → governed download → user-visible
+ * `shell_exec` approval → completed tool stepper and bounded response.
+ * - Business signals: the download step reports a workspace file; the approved
+ * Node command reports the independently generated CSV record count and a
+ * sentinel located beyond the former 3 MiB boundary.
+ * - Setup shortcuts: managed agent/folder fixture seeding and the local CSV
+ * buffer are named preconditions. No provider-route mock, storage mutation,
+ * direct API trigger, or broad network mock is used.
+ */
+import { type Locator, type Page, expect, test } from '@playwright/test'
+import { randomUUID } from 'node:crypto'
+import { exactNameFilter } from './helpers/agentLocators'
+import { type ManagedGfsAgent, getManagedAgentDisplayName } from './helpers/gfsAgentDiscovery'
+import {
+ type AgentGfsFixtures,
+ assertGfsInfraHealthy,
+ seedAgentGfsFixtures,
+} from './helpers/gfsFixtures'
+import {
+ GFS_LARGE_CSV_SIZE,
+ GFS_OLD_VISUAL_LIMIT,
+ type GfsLargeCsvFixture,
+ resolveGfsLargeCsvFixture,
+} from './helpers/gfsLargeFileCsvFixture'
+import { openAgentsPage, openResourcesNavItem } from './navigationHelpers'
+import { launchAndLogin } from './workflowUi'
+
+const OWNER_EMAIL = '[email protected]'
+const RESPONSE_TIMEOUT_MS = 420_000
+const PROGRESS_TIMEOUT_MS = 45_000
+const runToken = `GFS-LARGE-CLI-${randomUUID()}`
+
+async function enterAgentChat(page: Page, agentName: string): Promise<void> {
+ await openAgentsPage(page)
+ const exactAgent = page.getByLabel(`Open agent ${agentName}`, { exact: true })
+ await expect(exactAgent).toBeVisible({ timeout: 30_000 })
+ await exactAgent.click()
+ await page.getByTestId('nav-chat').click()
+ const chatInput = page.getByTestId('chat-input')
+ await expect(chatInput).toBeVisible({ timeout: 45_000 })
+
+ const selectedAgentInNewChat = page
+ .getByRole('button', { name: 'Switch chat agent' })
+ .filter(exactNameFilter(agentName))
+ const selectedAgentInThread = page
+ .getByRole('navigation', { name: 'Chat breadcrumb' })
+ .getByText(agentName, { exact: true })
+ if (
+ !(await selectedAgentInNewChat.isVisible().catch(() => false)) &&
+ !(await selectedAgentInThread.isVisible().catch(() => false))
+ ) {
+ await page.getByRole('button', { name: 'Switch chat agent' }).click()
+ await page.getByRole('menuitem', { name: agentName, exact: true }).click()
+ }
+ await expect(selectedAgentInNewChat.or(selectedAgentInThread)).toBeVisible({
+ timeout: 15_000,
+ })
+}
+
+async function sendTaskAndApproveShell(
+ page: Page,
+ prompt: string
+): Promise<{ response: Locator; expandButton: Locator }> {
+ const responseCountBefore = await page.getByTestId('agent-response').count()
+ const approvalCountBefore = await page.getByTestId('approval-approve-btn').count()
+ const progressCountBefore = await page.getByTestId('progress-expand-btn').count()
+ const response = page.getByTestId('agent-response').filter({ hasText: runToken })
+ let approvedShell = false
+
+ await page.getByTestId('chat-input').fill(prompt)
+ await page.getByTestId('send-button').click()
+
+ const deadline = Date.now() + RESPONSE_TIMEOUT_MS
+ for (;;) {
+ const remaining = deadline - Date.now()
+ if (remaining <= 0) throw new Error('Timed out waiting for approval or final response')
+ const approvalButtons = await page.getByTestId('approval-approve-btn').all()
+ const nextApproval = approvalButtons[approvalCountBefore]
+ if (!nextApproval) throw new Error('new shell approval was not created')
+ const first = await Promise.race([
+ nextApproval
+ .waitFor({ state: 'visible', timeout: remaining })
+ .then(() => 'approval' as const),
+ response.waitFor({ state: 'visible', timeout: remaining }).then(() => 'response' as const),
+ ]).catch(error => {
+ throw error
+ })
+ void nextApproval.waitFor({ state: 'hidden', timeout: 1 }).catch(() => undefined)
+
+ if (first === 'response') break
+ const stepper = page.getByTestId('progress-stepper').filter({ has: nextApproval })
+ await expect(stepper).toBeVisible({ timeout: 10_000 })
+ const approvalText = await stepper.innerText()
+ if (/shell_exec/i.test(approvalText)) {
+ approvedShell = true
+ expect(approvalText).toContain('node')
+ if (csv.source === 'synthetic') expect(approvalText).toContain(csv.sentinel!)
+ else expect(approvalText).toContain('createHash')
+ }
+ await nextApproval.click()
+ }
+
+ expect(approvedShell, 'the journey must approve an actual shell_exec command').toBe(true)
+ await expect(response).toContainText(/ROWS=/, { timeout: RESPONSE_TIMEOUT_MS })
+ await expect(response).toContainText(/PROOF=[0-9a-f]{16}/, {
+ timeout: RESPONSE_TIMEOUT_MS,
+ })
+ const progressButtons = await page.getByTestId('progress-expand-btn').all()
+ const expandButton = progressButtons[progressCountBefore]
+ if (!expandButton) throw new Error('new tool-progress stepper was not created')
+ await expect(expandButton).toBeVisible({ timeout: PROGRESS_TIMEOUT_MS })
+ return { response, expandButton }
+}
+
+function toolStepRow(page: Page, toolName: string): Locator {
+ return page.getByTestId(/^step-row-/).filter({ hasText: toolName })
+}
+
+async function stepOutput(row: Locator): Promise<Locator> {
+ await row.click()
+ const output = row
+ .locator('xpath=following-sibling::*[@data-testid="step-output-panel"][1]')
+ .locator('.stepper-step-output-code')
+ await expect(output).toBeVisible({ timeout: 10_000 })
+ return output
+}
+
+test.describe('GFS agent large-file CLI journey', () => {
+ test.describe.configure({ mode: 'serial' })
+
+ let fixtures: AgentGfsFixtures
+ let agentLabel: string
+ let csv: GfsLargeCsvFixture
+
+ test.beforeAll(() => {
+ assertGfsInfraHealthy()
+ fixtures = seedAgentGfsFixtures(OWNER_EMAIL)
+ agentLabel = getManagedAgentDisplayName(fixtures.agent)
+ csv = resolveGfsLargeCsvFixture()
+ expect(csv.buffer.byteLength).toBe(GFS_LARGE_CSV_SIZE)
+ if (csv.source === 'synthetic')
+ expect(csv.buffer.indexOf(csv.sentinel!, 'utf8')).toBeGreaterThan(GFS_OLD_VISUAL_LIMIT)
+ })
+
+ test.afterAll(() => {
+ fixtures?.cleanup()
+ })
+
+ test('user uploads a 3.8 MiB CSV and approves local processing', async () => {
+ const { app, page } = await launchAndLogin(OWNER_EMAIL)
+ try {
+ await test.step('user uploads the exact CSV through Files', async () => {
+ await openResourcesNavItem(page, 'nav-files')
+ await expect(page.getByRole('heading', { name: 'Files', exact: true })).toBeVisible()
+ const shared = page.getByRole('region', { name: 'GFS resources shared with you' })
+ await expect(shared).toContainText(fixtures.granted.name, { timeout: 30_000 })
+ await shared.getByRole('button', { name: fixtures.granted.name, exact: true }).click()
+ const browser = page.getByRole('region', { name: 'EvenDrive browser' })
+ await expect(browser).toBeVisible({ timeout: 30_000 })
+ await browser.getByLabel('Upload file').setInputFiles({
+ name: csv.fileName,
+ mimeType: 'text/csv',
+ buffer: csv.buffer,
+ })
+ await expect(page.getByText(`Uploaded ${csv.fileName}`)).toBeVisible({
+ timeout: 30_000,
+ })
+ await expect(browser.getByRole('button', { name: csv.fileName, exact: true })).toBeVisible({
+ timeout: 30_000,
+ })
+ })
+
+ let expandButton: Locator
+ let response: Locator
+ await test.step('exact agent downloads and processes the file after approval', async () => {
+ await enterAgentChat(page, agentLabel)
+ const prompt =
+ `Download "/${fixtures.granted.name}/${csv.fileName}" from GFS drive main with clerum__gfs_download. ` +
+ 'Do not print or file_read the whole file. After the workspace_file receipt returns, use exactly one approved shell_exec ' +
+ 'Node.js command with the receipt path as an argument. Parse complete CSV records with quote-state tracking (never count raw newlines), ' +
+ 'compute the SHA-256 of the final 4096 bytes and print its first 16 lowercase hex characters. ' +
+ `Print only bounded output in this exact shape: RUN=${runToken} ROWS=<record count> PROOF=<16 hex characters>.`
+ const result = await sendTaskAndApproveShell(page, prompt)
+ expandButton = result.expandButton
+ response = result.response
+ })
+
+ await test.step('tool stepper proves governed transfer and local execution', async () => {
+ await expandButton.click()
+ const downloadRow = toolStepRow(page, 'gfs_download')
+ await expect(downloadRow).toBeVisible({ timeout: 15_000 })
+ await expect(downloadRow.locator('.stepper-step-duration.state-error')).toHaveCount(0)
+ await expect(await stepOutput(downloadRow)).toContainText('workspace_file')
+
+ const shellRow = toolStepRow(page, 'shell_exec')
+ await expect(shellRow).toBeVisible({ timeout: 15_000 })
+ await expect(shellRow.locator('.stepper-step-duration.state-error')).toHaveCount(0)
+ await expect(await stepOutput(shellRow)).toContainText(`ROWS=${csv.recordCount}`)
+ await expect(await stepOutput(shellRow)).toContainText(`PROOF=${csv.tailProof}`)
+
+ await expect(response).toContainText(`ROWS=${csv.recordCount}`)
+ await expect(response).toContainText(`PROOF=${csv.tailProof}`)
+ await expect(response).not.toContain('zzzzzzzzzz')
+ })
+
+ await test.step('source remains visible after read-only processing', async () => {
+ await openResourcesNavItem(page, 'nav-files')
+ const shared = page.getByRole('region', { name: 'GFS resources shared with you' })
+ await shared.getByRole('button', { name: fixtures.granted.name, exact: true }).click()
+ const browser = page.getByRole('region', { name: 'EvenDrive browser' })
+ await expect(browser.getByRole('button', { name: csv.fileName })).toBeVisible({
+ timeout: 30_000,
+ })
+ })
+ } finally {
+ await app.close()
+ }
+ })
+})
diff --git a/desktop-app/test/e2e-playwright/helpers/gfsLargeFileCsvFixture.ts b/desktop-app/test/e2e-playwright/helpers/gfsLargeFileCsvFixture.ts
new file mode 100644
index 000000000..596a3598a
--- /dev/null
+++ b/desktop-app/test/e2e-playwright/helpers/gfsLargeFileCsvFixture.ts
@@ -0,0 +1,122 @@
+import * as crypto from 'node:crypto'
+import * as fs from 'node:fs'
+import * as path from 'node:path'
+
+// E2E_GUARDIAN_IPC_FLOW: this pure fixture has no renderer network boundary.
+// The Desktop journey that consumes it exercises the Electron IPC path.
+export const GFS_LARGE_CSV_SIZE = 3_836_961
+export const GFS_OLD_VISUAL_LIMIT = 3_145_728
+
+export interface GfsLargeCsvFixture {
+ fileName: string
+ buffer: Buffer
+ recordCount: number
+ sentinel?: string
+ tailProof: string
+ source: 'synthetic' | 'actual'
+}
+
+function csvField(value: string): string {
+ return `"${value.replace(/"/g, '""')}"`
+}
+
+export function buildGfsLargeCsvFixture(): GfsLargeCsvFixture {
+ const sentinel = `GFS_LARGE_CSV_SENTINEL_${crypto.randomUUID()}`
+ let content = `${csvField('id,record name')},${csvField('notes,value')}\n`
+ let recordCount = 1
+
+ for (let index = 1; ; index += 1) {
+ const multiline = index % 97 === 0
+ const notes = multiline
+ ? `first line\nsecond line with ""escaped quotes"" and, commas ${index}`
+ : `ordinary notes ${index}`
+ const row = `${csvField(`record-${index}`)},${csvField(
+ `name, with comma ${index}`
+ )},${csvField(notes)},${csvField(String(index % 17))}\n`
+ const finalPrefix = `${csvField('record-final')},${csvField(
+ 'final, sentinel row'
+ )},${csvField(`${sentinel}`)}`
+ const minimumFinalLength = finalPrefix.length + 2
+ if (Buffer.byteLength(content, 'utf8') + row.length + minimumFinalLength > GFS_LARGE_CSV_SIZE)
+ break
+ content += row
+ recordCount += 1
+ }
+
+ const finalPrefix = `${csvField('record-final')},${csvField(
+ 'final, sentinel row'
+ )},${csvField(`${sentinel}`)}`
+ const closing = `${csvField('0')}\n`
+ const usedBytes = Buffer.byteLength(content, 'utf8') + finalPrefix.length + closing.length
+ if (usedBytes > GFS_LARGE_CSV_SIZE) throw new Error('GFS large CSV fixture sizing underflow')
+ const padding = 'z'.repeat(GFS_LARGE_CSV_SIZE - usedBytes)
+ content += `${finalPrefix}${padding}${closing}`
+ recordCount += 1
+
+ const buffer = Buffer.from(content, 'utf8')
+ if (buffer.byteLength !== GFS_LARGE_CSV_SIZE)
+ throw new Error(`expected exactly ${GFS_LARGE_CSV_SIZE} bytes, got ${buffer.byteLength}`)
+ if (buffer.indexOf(sentinel, 'utf8') <= GFS_OLD_VISUAL_LIMIT)
+ throw new Error('sentinel must start beyond the former 3 MiB visual limit')
+
+ return {
+ fileName: `gfs-large-file-${crypto.randomUUID()}.csv`,
+ buffer,
+ recordCount,
+ sentinel,
+ tailProof: crypto
+ .createHash('sha256')
+ .update(buffer.subarray(Math.max(0, buffer.byteLength - 4096)))
+ .digest('hex')
+ .slice(0, 16),
+ source: 'synthetic',
+ }
+}
+
+function countCsvRecords(buffer: Buffer): number {
+ let records = 0
+ let insideQuotes = false
+ let sawRecordBytes = false
+ for (const byte of buffer) {
+ if (byte === 0x22) {
+ insideQuotes = !insideQuotes
+ sawRecordBytes = true
+ continue
+ }
+ if (byte === 0x0a && !insideQuotes) {
+ records += 1
+ sawRecordBytes = false
+ continue
+ }
+ if (byte !== 0x0d) sawRecordBytes = true
+ }
+ return records + (sawRecordBytes ? 1 : 0)
+}
+
+/**
+ * Resolve the incident-shaped CSV. CI uses the deterministic synthetic buffer;
+ * a local run can provide the original customer CSV through
+ * `E2E_GFS_LARGE_CSV_PATH`. The original is never copied into the repository.
+ */
+export function resolveGfsLargeCsvFixture(): GfsLargeCsvFixture {
+ const explicitPath = process.env.E2E_GFS_LARGE_CSV_PATH
+ if (!explicitPath) return buildGfsLargeCsvFixture()
+
+ const buffer = fs.readFileSync(explicitPath)
+ if (buffer.byteLength !== GFS_LARGE_CSV_SIZE)
+ throw new Error(
+ `E2E_GFS_LARGE_CSV_PATH must contain exactly ${GFS_LARGE_CSV_SIZE} bytes; got ${buffer.byteLength}`
+ )
+
+ return {
+ fileName: path.basename(explicitPath),
+ buffer,
+ recordCount: countCsvRecords(buffer),
+ tailProof: crypto
+ .createHash('sha256')
+ .update(buffer.subarray(Math.max(0, buffer.byteLength - 4096)))
+ .digest('hex')
+ .slice(0, 16),
+ source: 'actual',
+ }
+}
diff --git a/mcp-host/package-lock.json b/mcp-host/package-lock.json
index a7fba88cd..10cb1d7b7 100644
--- a/mcp-host/package-lock.json
+++ b/mcp-host/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "clerum-mcp-host",
- "version": "0.1.481",
+ "version": "0.1.482",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-mcp-host",
- "version": "0.1.481",
+ "version": "0.1.482",
"license": "SEE LICENSE IN LICENSE",
"dependencies": {
"@anthropic-ai/sdk": "^0.32.0",
diff --git a/mcp-host/package.json b/mcp-host/package.json
index 0724ea0e8..30b90dae3 100644
--- a/mcp-host/package.json
+++ b/mcp-host/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-mcp-host",
- "version": "0.1.481",
+ "version": "0.1.482",
"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/gfs.ts b/mcp-host/src/internalTools/gfs.ts
index 32ca68d77..cbb56ebc0 100644
--- a/mcp-host/src/internalTools/gfs.ts
+++ b/mcp-host/src/internalTools/gfs.ts
@@ -1,7 +1,3 @@
-import { createHash } from 'node:crypto'
-import { constants as fsConstants } from 'node:fs'
-import * as fs from 'node:fs/promises'
-import * as path from 'node:path'
import type { FileReferenceV1 } from '@clerum/gfs-interaction-policy'
import type { FileReferenceResolution } from '../agent/fileReferenceResolver'
import { inspectImage, validateImage } from '../visualInput/imageValidation'
@@ -146,70 +142,10 @@ function workspaceFileUsage(visualDelivery: 'included' | 'not_included', visualR
}
}
-async function resolveManagedImagePath(receipt: GfsDownloadResult, callerWorkspacePath: string) {
- const realRoot = await fs.realpath(callerWorkspacePath)
- const target = path.resolve(callerWorkspacePath, receipt.path)
- const realTarget = await fs.realpath(target)
- const managedRoot = path.join(realRoot, '.gfs-downloads')
- const relativeToManagedRoot = path.relative(managedRoot, realTarget)
- if (
- relativeToManagedRoot.startsWith('..') ||
- path.isAbsolute(relativeToManagedRoot) ||
- !receipt.path.startsWith('.gfs-downloads/')
- )
- throw new VisualInputError('identity_mismatch')
- return target
-}
-
-async function readManagedImageBytes(
- receipt: GfsDownloadResult,
- callerWorkspacePath: string
-): Promise<Buffer> {
- const target = await resolveManagedImagePath(receipt, callerWorkspacePath)
-
- const handle = await fs.open(
- target,
- fsConstants.O_RDONLY | fsConstants.O_NOFOLLOW | fsConstants.O_EXCL
- )
- try {
- const stat = await handle.stat()
- if (
- !stat.isFile() ||
- stat.size !== receipt.sizeBytes ||
- (stat.mode & 0o777) !== 0o600 ||
- stat.nlink !== 1
- )
- throw new VisualInputError('identity_mismatch')
- const bytes = await handle.readFile()
- if (createHash('sha256').update(bytes).digest('hex') !== receipt.sha256)
- throw new VisualInputError('identity_mismatch')
- return bytes
- } finally {
- await handle.close()
- }
-}
-
-async function readManagedImagePrefix(
- receipt: GfsDownloadResult,
- callerWorkspacePath: string
-): Promise<Buffer> {
- const target = await resolveManagedImagePath(receipt, callerWorkspacePath)
- const handle = await fs.open(
- target,
- fsConstants.O_RDONLY | fsConstants.O_NOFOLLOW | fsConstants.O_EXCL
- )
- try {
- const prefix = Buffer.alloc(16)
- const { bytesRead } = await handle.read(prefix, 0, prefix.length, 0)
- return prefix.subarray(0, bytesRead)
- } finally {
- await handle.close()
- }
-}
-
async function projectManagedImage(
receipt: GfsDownloadResult,
- callerWorkspacePath: string,
+ downloadStore: GfsDownloadStore,
+ callerIdentity: string,
options: InternalToolExecutionOptions | undefined,
knownBytes?: Buffer
): Promise<InternalToolResult> {
@@ -217,7 +153,7 @@ async function projectManagedImage(
try {
let bytes = knownBytes
if (bytes === undefined) {
- const prefix = await readManagedImagePrefix(receipt, callerWorkspacePath)
+ const prefix = await downloadStore.readManagedFilePrefix(receipt.path, callerIdentity)
const hasImageMagic =
prefix.length >= 3 &&
((prefix[0] === 0x89 && prefix[1] === 0x50 && prefix[2] === 0x4e) ||
@@ -233,7 +169,7 @@ async function projectManagedImage(
usage: workspaceFileUsage('not_included', visualReason),
}),
}
- bytes = await readManagedImageBytes(receipt, callerWorkspacePath)
+ bytes = await downloadStore.readManagedFile(receipt.path, callerIdentity)
}
const image = inspectImage(bytes)
if (image) {
@@ -520,7 +456,7 @@ export function buildGfsReadTools(
metadata.source.version,
options
)
- return await projectManagedImage(receipt, callerWorkspacePath!, options)
+ return await projectManagedImage(receipt, downloadStore!, callerIdentity!, options)
} else {
recordGfsDownloadAdmission('workspace_unavailable')
expectedVersion ??= metadata.source.version
@@ -556,7 +492,13 @@ export function buildGfsReadTools(
file.source.version,
options
)
- return await projectManagedImage(receipt, callerWorkspacePath!, options, file.bytes)
+ return await projectManagedImage(
+ receipt,
+ downloadStore!,
+ callerIdentity!,
+ options,
+ file.bytes
+ )
}
const visualInput = options?.visualInput
if (!visualInput)
diff --git a/mcp-host/src/internalTools/gfsDownloadStore.ts b/mcp-host/src/internalTools/gfsDownloadStore.ts
index d0d9d1ae5..80cb1a9e9 100644
--- a/mcp-host/src/internalTools/gfsDownloadStore.ts
+++ b/mcp-host/src/internalTools/gfsDownloadStore.ts
@@ -218,18 +218,6 @@ async function sha256FileHandle(handle: fs.FileHandle): Promise<string> {
return digest.digest('hex')
}
-async function sha256File(path: string): Promise<string> {
- const handle = await fs.open(
- path,
- constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK
- )
- try {
- return await sha256FileHandle(handle)
- } finally {
- await handle.close()
- }
-}
-
/** One Host/PVC-owned durable store; task registries receive bound handles. */
export class GfsDownloadStore {
private hostRoot: string
@@ -482,20 +470,24 @@ export class GfsDownloadStore {
if (record.state !== 'completed' || !record.sha256)
throw new GfsDownloadStoreError('download_missing')
const source = path.join(this.hostRoot, record.hostPath)
- const info = await fs.lstat(source).catch(() => undefined)
- if (
- !info?.isFile() ||
- info.isSymbolicLink() ||
- info.size !== record.sizeBytes ||
- (info.mode & 0o777) !== 0o600
- )
- throw new GfsDownloadStoreError('download_missing')
- const digest = createHash('sha256')
- const handle = await fs.open(
- source,
- constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK
- )
+ const handle = await fs
+ .open(
+ source,
+ constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_EXCL | constants.O_NONBLOCK
+ )
+ .catch(() => undefined)
+ if (!handle) throw new GfsDownloadStoreError('download_missing')
+ let digestValid = false
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 digest = createHash('sha256')
const chunk = Buffer.alloc(64 * 1024)
let position = 0
for (;;) {
@@ -504,10 +496,11 @@ export class GfsDownloadStore {
digest.update(chunk.subarray(0, bytesRead))
position += bytesRead
}
+ digestValid = digest.digest('hex') === record.sha256
} finally {
await handle.close()
}
- if (digest.digest('hex') !== record.sha256) throw new GfsDownloadStoreError('download_missing')
+ if (!digestValid) throw new GfsDownloadStoreError('download_missing')
return {
id: record.id,
source: record.source,
@@ -518,6 +511,86 @@ export class GfsDownloadStore {
}
}
+ 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 source = path.join(this.hostRoot, record.hostPath)
+ const handle = await fs
+ .open(
+ source,
+ constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_EXCL | constants.O_NONBLOCK
+ )
+ .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 = await handle.readFile()
+ } finally {
+ await handle.close()
+ }
+ if (createHash('sha256').update(bytes).digest('hex') !== record.sha256)
+ throw new GfsDownloadStoreError('download_missing')
+ return bytes
+ }
+
+ async readManagedFilePrefix(
+ callerRelativePath: string,
+ callerIdentity: string,
+ prefixBytes = 16
+ ): Promise<Buffer> {
+ this.assertInitialized()
+ 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 source = path.join(this.hostRoot, record.hostPath)
+ const handle = await fs
+ .open(
+ source,
+ constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_EXCL | constants.O_NONBLOCK
+ )
+ .catch(() => undefined)
+ if (!handle) throw new GfsDownloadStoreError('download_missing')
+ 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()
+ }
+ }
+
processingLeaseProvider(callerIdentity: string): GfsProcessingLeaseProvider {
return {
acquireProcessingLease: (options?: GfsProcessingLeaseAcquisition) =>
diff --git a/mcp-host/src/internalTools/gfsLargeFile.test.ts b/mcp-host/src/internalTools/gfsLargeFile.test.ts
index 5dbcc2567..45fd03c1a 100644
--- a/mcp-host/src/internalTools/gfsLargeFile.test.ts
+++ b/mcp-host/src/internalTools/gfsLargeFile.test.ts
@@ -58,6 +58,12 @@ function result(tool: InternalToolDefinition, args: Record<string, unknown>) {
}))
}
+function fakeDownloadStore(): GfsDownloadStore {
+ return {
+ readManagedFilePrefix: async () => Buffer.from('not-an-image'),
+ } as unknown as GfsDownloadStore
+}
+
describe('GFS large-file tool routing', () => {
it('does not expose generic workspace delivery without a store', () => {
expect(
@@ -80,7 +86,7 @@ describe('GFS large-file tool routing', () => {
const managedFile = path.join(callerWorkspace, '.gfs-downloads/input-download-1/source')
fs.mkdirSync(path.dirname(managedFile), { recursive: true })
fs.writeFileSync(managedFile, 'not-an-image-prefix', 'utf8')
- const store = {} as GfsDownloadStore
+ const store = fakeDownloadStore()
const tool = buildGfsReadTools(gfs, {
referencedFiles: new Map(),
downloadStore: store,
@@ -128,7 +134,7 @@ describe('GFS large-file tool routing', () => {
const managedFile = path.join(callerWorkspace, '.gfs-downloads/input-download-2/source')
fs.mkdirSync(path.dirname(managedFile), { recursive: true })
fs.writeFileSync(managedFile, 'not-an-image-prefix', 'utf8')
- const store = {} as GfsDownloadStore
+ const store = fakeDownloadStore()
const tool = buildGfsReadTools(gfs, {
referencedFiles: new Map(),
downloadStore: store,
@@ -162,7 +168,7 @@ describe('GFS large-file tool routing', () => {
sha256: 'c'.repeat(64),
expiresAt: '2026-10-08T00:00:00.000Z',
}))
- const store = {} as GfsDownloadStore
+ const store = fakeDownloadStore()
const tool = buildGfsReadTools(client({ download }), {
referencedFiles: new Map(),
downloadStore: store,
@@ -193,7 +199,7 @@ describe('GFS large-file tool routing', () => {
}))
const gfs = client({ read: vi.fn(async () => content(png)), download })
gfs.readMetadata = vi.fn(async () => snapshot(png.byteLength))
- const store = {} as GfsDownloadStore
+ const store = fakeDownloadStore()
const tool = buildGfsReadTools(gfs, {
referencedFiles: new Map(),
downloadStore: store,
@@ -219,7 +225,7 @@ describe('GFS large-file tool routing', () => {
const download = vi.fn(async () => {
throw new GfsDownloadError('version_conflict')
})
- const store = {} as GfsDownloadStore
+ const store = fakeDownloadStore()
const tool = buildGfsReadTools(client({ download }), {
referencedFiles: new Map(),
downloadStore: store,