{"record":{"id":"7685b232969dab75","repo":"mastra-ai/mastra","slug":"eexist","errorCode":"EEXIST","errorMessage":"File already exists: ${path}","messagePattern":"File already exists: (.+?)","errorType":"exception","errorClass":"FileExistsError","httpStatus":null,"severity":"error","filePath":"packages/core/src/workspace/filesystem/local-filesystem.ts","lineNumber":463,"sourceCode":"        // Compare via Date objects — Node's stats.mtime applies internal\n        // rounding that can diverge from Math.floor(stats.mtimeMs).\n        if (currentStat.mtime.getTime() !== options.expectedMtime.getTime()) {\n          throw new StaleFileError(inputPath, options.expectedMtime, currentStat.mtime);\n        }\n      } catch (error: unknown) {\n        if (error instanceof StaleFileError) throw error;\n        // File doesn't exist yet — no conflict possible, proceed with write\n        if (!isEnoentError(error)) throw error;\n      }\n    }\n\n    // Use 'wx' flag for atomic overwrite check (avoids TOCTOU race)\n    const writeFlag = options?.overwrite === false ? 'wx' : 'w';\n    try {\n      await fs.writeFile(absolutePath, this.toBuffer(content), { flag: writeFlag });\n    } catch (error: unknown) {\n      if (options?.overwrite === false && isEexistError(error)) {\n        throw new FileExistsError(inputPath);\n      }\n      throw error;\n    }\n  }\n\n  async appendFile(inputPath: string, content: FileContent): Promise<void> {\n    const contentSize = Buffer.isBuffer(content) ? content.length : content.length;\n    this.logger.debug('Appending to file', { path: inputPath, size: contentSize });\n    await this.ensureReady();\n    this.assertWritable('appendFile');\n    const absolutePath = this.resolvePath(inputPath);\n    await this.assertPathContained(absolutePath);\n    const dir = nodePath.dirname(absolutePath);\n    await fs.mkdir(dir, { recursive: true });\n    await fs.appendFile(absolutePath, this.toBuffer(content));\n  }\n\n  async deleteFile(inputPath: string, options?: RemoveOptions): Promise<void> {","sourceCodeStart":445,"sourceCodeEnd":481,"githubUrl":"https://github.com/mastra-ai/mastra/blob/75dd419e613fe9c39f846ffc500716141b74fda6/packages/core/src/workspace/filesystem/local-filesystem.ts#L445-L481","documentation":"writeFile throws FileExistsError (code EEXIST) when options.overwrite === false and the target file already exists. The library writes with the atomic 'wx' flag so the existence check and write are a single filesystem operation, avoiding TOCTOU races — the error means the file genuinely existed at write time. Default behavior (overwrite unspecified/true) silently replaces the file.","triggerScenarios":"writeFile(path, data, { overwrite: false }) where path already exists; create-once semantics (e.g. writing an idempotency marker or new record file) colliding with an existing file; two concurrent create-if-absent writes — exactly one wins, the other gets EEXIST.","commonSituations":"Rerunning a job that already created its output file; agent retry after a timeout that actually succeeded the first time; naming collisions when generating files from user input (two requests named the same).","solutions":["Set overwrite: true (or omit the option) if replacing the file is intended.","Choose a unique target name (timestamp/uuid suffix) for create-once semantics.","Treat FileExistsError as a success signal in idempotent flows — the artifact already exists, so read it instead.","Catch FileExistsError and retry with a new filename or after checking the existing file's content."],"exampleFix":"// before\nawait fs.writeFile('lock', 'me', { overwrite: false }); // FileExistsError on rerun\n// after\ntry {\n  await fs.writeFile(`locks/${runId}.lock`, 'me', { overwrite: false });\n} catch (e) {\n  if (e instanceof FileExistsError) return; // idempotent: already created\n  throw e;\n}","handlingStrategy":"try-catch","validationCode":"let exists = true;\ntry { await ws.stat(p); } catch { exists = false; }\nif (exists && mustNotOverwrite) {\n  throw new Error(`${p} already exists; pick a unique name`);\n}","typeGuard":"import { FileExistsError } from '@mastra/core/workspace/errors';\nfunction isFileExistsError(e: unknown): e is FileExistsError {\n  return e instanceof FileExistsError ||\n    (e instanceof Error && 'code' in e && (e as { code?: string }).code === 'EEXIST');\n}","tryCatchPattern":"try {\n  await ws.writeFile(p, data, { overwrite: false });\n} catch (e) {\n  if (isFileExistsError(e)) {\n    return await ws.readFile(p, { encoding: 'utf8' }); // idempotent: reuse existing\n  }\n  throw e;\n}","preventionTips":["Use overwrite: false only for create-once artifacts; it's the atomic 'wx' path.","Generate unique names (runId/uuid/timestamp suffix) for anything written more than once.","Treat EEXIST as success in idempotent/retry flows.","Clean up or rotate old artifacts so create-once writes don't collide on reruns."],"tags":["filesystem","eexist","file-exists","concurrency"],"backgroundTag":"eexist-file-already-exists","analyzedSha":"75dd419e613fe9c39f846ffc500716141b74fda6","analyzedAt":"2026-08-30T00:15:31.844Z","schemaVersion":2},"datasetVersion":"2026-08-30T03:17:51.788Z"}