{"record":{"id":"4547efc701d1c366","repo":"mastra-ai/mastra","slug":"writefile-path-failed-exit-result-exitcode","errorCode":null,"errorMessage":"writeFile ${path} failed (exit ${result.exitCode}): ${result.stderr.trim()}","messagePattern":"writeFile (.+?) failed \\(exit (.+?)\\): (.+?)","errorType":"exception","errorClass":null,"httpStatus":null,"severity":"error","filePath":"mastracode/sdk/src/agents/sandbox-filesystem.ts","lineNumber":281,"sourceCode":"    }\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\n  async deleteFile(path: string, options?: RemoveOptions): Promise<void> {\n    const abs = await this.resolveAsync(path);","sourceCodeStart":263,"sourceCodeEnd":299,"githubUrl":"https://github.com/mastra-ai/mastra/blob/75dd419e613fe9c39f846ffc500716141b74fda6/mastracode/sdk/src/agents/sandbox-filesystem.ts#L263-L299","documentation":"writeFile throws this generic Error when the sandbox shell command exits with a non-zero code that is not the EXIT_EXISTS sentinel — i.e. the write failed for a reason other than 'file already exists'. The message carries the path, exit code, and stderr from the failed shell command.","triggerScenarios":"writeFile where mkdir -p on the parent directory fails (permission denied or parent is a file); base64 -d failing on the pipeline; the destination being an existing directory; noclobber create failing for reasons besides existence; disk-full on the sandbox volume.","commonSituations":"Passing a directory as the write path; the parent path component being a regular file (e.g. writing 'a/b' where 'a' is a file); sandbox volume quota exhausted; restrictive umask/ownership after container restarts.","solutions":["Read the stderr portion of the message to identify the concrete shell failure (mkdir vs base64 vs redirect).","Verify the destination path is a file path, not a directory, and each parent component is a directory.","Check sandbox disk space/quota (df) if the failure is 'No space left on device'.","Ensure the sandbox user has write permission on the target directory, or recreate the workspace.","Retry the operation — transient sandbox or volume errors can cause one-off failures."],"exampleFix":"// before\\nawait fs.writeFile('out/data.txt', buf);\\n// after\\ntry {\\n  await fs.writeFile('out/data.txt', buf);\\n} catch (e) {\\n  if (e instanceof Error && e.message.includes('Is a directory')) {\\n    await fs.deleteFile('out/data.txt', { force: true });\\n    await fs.writeFile('out/data.txt', buf);\\n  } else throw e;\\n}","handlingStrategy":"retry","validationCode":"// Verify destination is writable and parents are directories\\nconst entries = await fs.readDirectory(posix.dirname(destPath));\\nif (entries.directories.every(d => d.path !== posix.basename(destPath)) === false) {\\n  throw new Error('destination is a directory');\\n}","typeGuard":"function isWriteFailureError(e: unknown): boolean {\\n  return e instanceof Error && /^writeFile .* failed \\\\(exit/.test(e.message);\\n}","tryCatchPattern":"try {\\n  await fs.writeFile(path, content);\\n} catch (e) {\\n  if (e instanceof Error && /ENOSPC|No space left/.test(e.message)) {\\n    // free space or fail fast\\n  } else if (e instanceof Error && e.message.includes('failed (exit')) {\\n    // log stderr from message; retry once\\n  }\\n  throw e;\\n}","preventionTips":["Ensure target paths are files, never directories.","Keep parent path components as directories (no file/dir name collisions).","Monitor sandbox disk usage for quota exhaustion.","Use default recursive mkdir (don't set recursive:false unless parents exist)."],"tags":["filesystem","sandbox","write-failure","shell"],"backgroundTag":"command-exit-code-failure","analyzedSha":"75dd419e613fe9c39f846ffc500716141b74fda6","analyzedAt":"2026-08-30T00:15:31.844Z","schemaVersion":2},"datasetVersion":"2026-08-30T03:17:51.788Z"}