{"record":{"id":"231df12cda677180","repo":"mastra-ai/mastra","slug":"fileexistserror-path","errorCode":null,"errorMessage":"FileExistsError: ${path}","messagePattern":"FileExistsError: (.+?)","errorType":"error_code","errorClass":"FileExistsError","httpStatus":null,"severity":"error","filePath":"mastracode/sdk/src/agents/sandbox-filesystem.ts","lineNumber":279,"sourceCode":"    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 —\n      // no exists() pre-check that could race with a concurrent writer.\n      const result = await this.exec(\n        `${mkdir}{ (set -C; printf %s ${shellQuote(b64)} | base64 -d > ${shellQuote(abs)}) 2>/dev/null || { [ -e ${shellQuote(abs)} ] && exit ${EXIT_EXISTS} || exit 1; }; }`,\n      );\n      if (result.exitCode === EXIT_EXISTS) throw new FileExistsError(path);\n      if (result.exitCode !== 0) {\n        throw new Error(`writeFile ${path} failed (exit ${result.exitCode}): ${result.stderr.trim()}`);\n      }\n      return;\n    }\n    await this.execOk(`${mkdir}printf %s ${shellQuote(b64)} | base64 -d > ${shellQuote(abs)}`, `writeFile ${path}`);\n  }\n\n  async appendFile(path: string, content: FileContent): Promise<void> {\n    const abs = await this.resolveAsync(path);\n    await this.assertContainedDest(abs, path);\n    const b64 = toBuffer(content).toString('base64');\n    await this.execOk(\n      `mkdir -p ${shellQuote(posixPath.dirname(abs))} && printf %s ${shellQuote(b64)} | base64 -d >> ${shellQuote(abs)}`,\n      `appendFile ${path}`,\n    );\n  }\n","sourceCodeStart":261,"sourceCodeEnd":297,"githubUrl":"https://github.com/mastra-ai/mastra/blob/75dd419e613fe9c39f846ffc500716141b74fda6/mastracode/sdk/src/agents/sandbox-filesystem.ts#L261-L297","documentation":"When writeFile is called with { overwrite: false }, the sandbox performs an atomic create using `set -C` (noclobber): if the destination already exists, the redirect fails and the shell exits with EXIT_EXISTS, causing a FileExistsError(path). The library throws this instead of silently clobbering an existing file, using the redirect itself as the exclusivity check to avoid a race with concurrent writers.","triggerScenarios":"writeFile(path, content, { overwrite: false }) when path already exists in the sandbox workspace — e.g. re-running an idempotent-looking step, two agents writing the same output path, or a leftover file from a previous run.","commonSituations":"Retrying a failed agent run without cleaning the workdir; intentional create-only semantics (lock files, 'first writer wins'); a concurrent workflow instance racing for the same output filename.","solutions":["Pass { overwrite: true } (or omit options) if replacing the file is acceptable.","Delete the existing file first with deleteFile(path, { force: true }) before writing.","Write to a unique filename (timestamp/UUID suffix) to avoid collisions.","Catch FileExistsError and treat it as 'already created by someone else' — often the desired outcome for lock-file patterns."],"exampleFix":"// before\\nawait fs.writeFile('state.lock', 'claimed', { overwrite: false });\\n// after\\ntry {\\n  await fs.writeFile('state.lock', 'claimed', { overwrite: false });\\n} catch (e) {\\n  if (!(e instanceof FileExistsError)) throw e;\\n  // lock already held — proceed or bail\\n}","handlingStrategy":"try-catch","validationCode":"// Optional pre-check (racy — noclobber in writeFile is the real guarantee)\\nconst existing = await fs.readDirectory(parentDir);\\nconst willConflict = existing.files.some(f => f.path === targetName);","typeGuard":"function isFileExistsError(e: unknown): e is FileExistsError {\\n  return e instanceof FileExistsError;\\n}","tryCatchPattern":"try {\\n  await fs.writeFile(path, content, { overwrite: false });\\n} catch (e) {\\n  if (e instanceof FileExistsError) {\\n    // create-only semantics: file already present, decide to reuse or bail\\n  } else {\\n    throw e;\\n  }\\n}","preventionTips":["Use overwrite:false only when create-once semantics are intended (locks, idempotency markers).","Clean the workdir between runs, or write to unique names.","Treat FileExistsError as an expected outcome for first-writer-wins flows.","Don't add your own exists() pre-check to decide overwrite — use overwrite:true instead."],"tags":["filesystem","sandbox","file-exists","write-conflict"],"backgroundTag":"file-already-exists","analyzedSha":"75dd419e613fe9c39f846ffc500716141b74fda6","analyzedAt":"2026-08-30T00:15:31.844Z","schemaVersion":2},"datasetVersion":"2026-08-30T03:17:51.788Z"}