{"record":{"id":"df01cd4400101584","repo":"mastra-ai/mastra","slug":"filenotfounderror-path","errorCode":null,"errorMessage":"FileNotFoundError: ${path}","messagePattern":"FileNotFoundError: (.+?)","errorType":"error_code","errorClass":"FileNotFoundError","httpStatus":null,"severity":"error","filePath":"mastracode/sdk/src/agents/sandbox-filesystem.ts","lineNumber":256,"sourceCode":"    const result = await this.exec(script);\n    if (result.exitCode !== 0) {\n      throw new Error(`${context} failed (exit ${result.exitCode}): ${result.stderr.trim() || result.stdout.trim()}`);\n    }\n    return result;\n  }\n\n  // ── File operations ────────────────────────────────────────────────────\n\n  async readFile(path: string, options?: ReadOptions): Promise<string | Buffer> {\n    const abs = await this.resolveAsync(path);\n    await this.assertContainedRealpath(abs, path);\n    // Guard clauses first: redirecting from a directory \"succeeds\" with empty\n    // output on some shells, so classify before reading.\n    const result = await this.exec(\n      `if [ -d ${shellQuote(abs)} ]; then exit ${EXIT_IS_DIRECTORY}; elif [ ! -e ${shellQuote(abs)} ]; then exit ${EXIT_NOT_FOUND}; fi; base64 < ${shellQuote(abs)}`,\n    );\n    if (result.exitCode === EXIT_IS_DIRECTORY) throw new IsDirectoryError(path);\n    if (result.exitCode === EXIT_NOT_FOUND) throw new FileNotFoundError(path);\n    if (result.exitCode !== 0) {\n      throw new Error(`readFile ${path} failed (exit ${result.exitCode}): ${result.stderr.trim()}`);\n    }\n    const buffer = Buffer.from(result.stdout.replace(/\\s/g, ''), 'base64');\n    if (options?.encoding) {\n      return buffer.toString(options.encoding);\n    }\n    return buffer;\n  }\n\n  async writeFile(path: string, content: FileContent, options?: WriteOptions): Promise<void> {\n    const abs = await this.resolveAsync(path);\n    await this.assertContainedDest(abs, path);\n    const b64 = toBuffer(content).toString('base64');\n    const dir = posixPath.dirname(abs);\n    const mkdir = options?.recursive === false ? '' : `mkdir -p ${shellQuote(dir)} && `;\n    if (options?.overwrite === false) {\n      // `set -C` (noclobber) makes the redirect itself the exclusivity check —","sourceCodeStart":238,"sourceCodeEnd":274,"githubUrl":"https://github.com/mastra-ai/mastra/blob/75dd419e613fe9c39f846ffc500716141b74fda6/mastracode/sdk/src/agents/sandbox-filesystem.ts#L238-L274","documentation":"readFile() runs a shell probe in the sandbox that classifies the target before reading: directories exit with EXIT_IS_DIRECTORY and non-existent paths exit with EXIT_NOT_FOUND, so the sandbox throws FileNotFoundError(path) instead of attempting a base64 read. This gives callers a typed, distinguishable signal that the requested path does not exist inside the sandbox workspace (after symlink-containment checks passed).","triggerScenarios":"Calling sandbox.files.readFile(path) when the file does not exist at the resolved workspace-relative path: a typo'd path, reading a file that was deleted or never written, reading a path that only exists on the host but not in the sandbox workdir, or a case-sensitivity mismatch (Linux sandbox vs macOS host).","commonSituations":"Agents reading generated output before the producing step ran; stale cache of previously-existing files; tests asserting on fixture files not copied into the sandbox workdir; referencing absolute host paths that get resolved inside the sandbox where they don't exist.","solutions":["Check the file exists (or create it) before reading: verify the producing step (writeFile/copyFile) ran first.","Print/verify the exact path being passed and how it resolves relative to the sandbox basePath — remove leading host-absolute segments if the file lives inside the workdir.","Use the force/idempotent pattern on the write side (or copyFile) to ensure the file is present before read.","Wrap in try/catch on FileNotFoundError and treat as an expected 'missing' outcome rather than a crash."],"exampleFix":"// before\\nconst content = await sandbox.fs.readFile('output/result.json');\\n// after\\nlet content: string;\\ntry {\\n  content = await sandbox.fs.readFile('output/result.json', { encoding: 'utf8' });\\n} catch (e) {\\n  if (e instanceof FileNotFoundError) content = '';\\n  else throw e;\\n}","handlingStrategy":"try-catch","validationCode":"let exists = false;\\ntry {\\n  await fs.readFile(path);\\n  exists = true;\\n} catch { /* probe read */ }","typeGuard":"function isFileNotFoundError(e: unknown): e is FileNotFoundError {\\n  return e instanceof FileNotFoundError;\\n}","tryCatchPattern":"try {\\n  const content = await fs.readFile(path);\\n} catch (e) {\\n  if (e instanceof FileNotFoundError) {\\n    // handle missing file: default value or early return\\n  } else {\\n    throw e;\\n  }\\n}","preventionTips":["Ensure the producing step completed before reading outputs.","Use workspace-relative paths consistently; never assume host-absolute paths map into the sandbox.","Check path casing on Linux sandboxes.","Prefer reading only after writeFile/copyFile of the same path succeeded."],"tags":["filesystem","sandbox","file-not-found"],"backgroundTag":"file-not-found","analyzedSha":"75dd419e613fe9c39f846ffc500716141b74fda6","analyzedAt":"2026-08-30T00:15:31.844Z","schemaVersion":2},"datasetVersion":"2026-08-30T03:17:51.788Z"}