run.mjs 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163
  1. #!/usr/bin/env node
  2. import { chmod, mkdtemp, readFile, rm, stat, symlink, writeFile } from "node:fs/promises";
  3. import { tmpdir } from "node:os";
  4. import { dirname, join, resolve } from "node:path";
  5. import { fileURLToPath, pathToFileURL } from "node:url";
  6. const scriptDir = dirname(fileURLToPath(import.meta.url));
  7. const repoRoot = resolve(scriptDir, "../../../..");
  8. async function main() {
  9. if (process.platform === "win32") {
  10. console.log(JSON.stringify({ reason: "POSIX mode semantics are not available on win32", status: "skipped" }));
  11. return;
  12. }
  13. const [{ writeToolEntry }, { editToolEntry }, { createNodeFileSystemAdapter }] = await Promise.all([
  14. import(pathToFileURL(join(repoRoot, "apps/zcode-cli/packages/core/dist/tool/handlers/write.js")).href),
  15. import(pathToFileURL(join(repoRoot, "apps/zcode-cli/packages/core/dist/tool/handlers/edit.js")).href),
  16. import(pathToFileURL(join(repoRoot, "apps/zcode-cli/packages/adapters/dist/fs/index.js")).href),
  17. ]);
  18. const writeTool = requireTool(writeToolEntry, "Write");
  19. const editTool = requireTool(editToolEntry, "Edit");
  20. const runRoot = await mkdtemp(join(tmpdir(), "zcode-file-tools-atomic-e2e-"));
  21. const fsPort = createNodeFileSystemAdapter();
  22. const results = [];
  23. try {
  24. const writePath = join(runRoot, "write.sh");
  25. await writeFile(writePath, "#!/usr/bin/env bash\necho old-write\n", "utf8");
  26. await chmod(writePath, 0o755);
  27. await writeTool.handler(
  28. {
  29. file_path: writePath,
  30. content: "#!/usr/bin/env bash\necho new-write\n",
  31. },
  32. createToolContext({
  33. fsPort,
  34. readFileState: await readStateFor(fsPort, writePath),
  35. workspaceRoot: runRoot,
  36. }),
  37. );
  38. await assertFile(writePath, "#!/usr/bin/env bash\necho new-write\n", 0o755);
  39. results.push({ case: "write-preserves-executable-mode", status: "passed" });
  40. const editPath = join(runRoot, "edit.sh");
  41. await writeFile(editPath, "#!/usr/bin/env bash\necho old-edit\n", "utf8");
  42. await chmod(editPath, 0o755);
  43. await editTool.handler(
  44. {
  45. file_path: editPath,
  46. old_string: "old-edit",
  47. new_string: "new-edit",
  48. },
  49. createToolContext({
  50. fsPort,
  51. workspaceRoot: runRoot,
  52. }),
  53. );
  54. await assertFile(editPath, "#!/usr/bin/env bash\necho new-edit\n", 0o755);
  55. results.push({ case: "edit-preserves-executable-mode", status: "passed" });
  56. const targetPath = join(runRoot, "target.sh");
  57. const linkPath = join(runRoot, "link.sh");
  58. await writeFile(targetPath, "#!/usr/bin/env bash\necho target\n", "utf8");
  59. await chmod(targetPath, 0o755);
  60. await symlink(targetPath, linkPath);
  61. await assertRejectsSymlinkWrite(writeTool, fsPort, linkPath, runRoot);
  62. expectEqual(await readFile(targetPath, "utf8"), "#!/usr/bin/env bash\necho target\n", "symlink target content");
  63. results.push({ case: "write-rejects-symlink-target", status: "passed" });
  64. console.log(JSON.stringify({ cases: results, status: "passed" }, null, 2));
  65. } finally {
  66. await rm(runRoot, { force: true, recursive: true });
  67. }
  68. }
  69. function requireTool(toolEntry, name) {
  70. if (toolEntry.metadata?.name !== name) {
  71. throw new Error(`Missing built-in tool: ${name}`);
  72. }
  73. return toolEntry;
  74. }
  75. function createToolContext({ fsPort, readFileState, workspaceRoot }) {
  76. return {
  77. abortSignal: new AbortController().signal,
  78. fileSystemPort: fsPort,
  79. readFileState,
  80. sessionId: "file_tools_atomic_write_e2e_session",
  81. spanId: "file_tools_atomic_write_e2e_span",
  82. toolCallId: "file_tools_atomic_write_e2e_tool",
  83. traceId: "file_tools_atomic_write_e2e_trace",
  84. turnId: "file_tools_atomic_write_e2e_turn",
  85. workingDirectory: workspaceRoot,
  86. workspaceRoot,
  87. };
  88. }
  89. async function readStateFor(fsPort, filePath) {
  90. const read = await fsPort.readTextFile({ path: filePath });
  91. return new Map([
  92. [
  93. filePath,
  94. {
  95. content: read.content,
  96. isPartialView: false,
  97. limit: undefined,
  98. mtimeMs: read.revision?.mtimeMs === undefined ? undefined : Math.floor(read.revision.mtimeMs),
  99. offset: undefined,
  100. path: filePath,
  101. readAt: new Date(),
  102. revisionId: read.revision?.id,
  103. sizeBytes: read.revision?.sizeBytes ?? Buffer.byteLength(read.content, "utf8"),
  104. sourceTool: "Read",
  105. },
  106. ],
  107. ]);
  108. }
  109. async function assertFile(filePath, expectedContent, expectedMode) {
  110. expectEqual(await readFile(filePath, "utf8"), expectedContent, `${filePath} content`);
  111. const actualMode = (await stat(filePath)).mode & 0o777;
  112. expectEqual(actualMode, expectedMode, `${filePath} mode`);
  113. }
  114. async function assertRejectsSymlinkWrite(writeTool, fsPort, linkPath, workspaceRoot) {
  115. try {
  116. await writeTool.handler(
  117. {
  118. file_path: linkPath,
  119. content: "#!/usr/bin/env bash\necho overwritten\n",
  120. },
  121. createToolContext({
  122. fsPort,
  123. readFileState: await readStateFor(fsPort, linkPath),
  124. workspaceRoot,
  125. }),
  126. );
  127. } catch (error) {
  128. const expectedMessage = `Refusing to write through symlink: ${linkPath}. Resolve the symlink and pass the real target path explicitly.`;
  129. if (error?.message !== expectedMessage) {
  130. throw new Error(`Unexpected symlink error message: ${error?.message}`, { cause: error });
  131. }
  132. return;
  133. }
  134. throw new Error("Expected Write through symlink to be rejected");
  135. }
  136. function expectEqual(actual, expected, label) {
  137. if (actual === expected) return;
  138. throw new Error(`${label}: expected ${formatValue(expected)}, got ${formatValue(actual)}`);
  139. }
  140. function formatValue(value) {
  141. return typeof value === "number" ? `0o${value.toString(8)}` : JSON.stringify(value);
  142. }
  143. main().catch((error) => {
  144. console.error(error);
  145. process.exitCode = 1;
  146. });