case-bash-read-state.mjs 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278
  1. import { readFile, writeFile } from "node:fs/promises";
  2. import { join } from "node:path";
  3. import { FAKE_MODEL } from "./constants.mjs";
  4. import {
  5. assertCondition,
  6. assertProviderCapture,
  7. buildCaseResult,
  8. buildRuntimeConfig,
  9. createApp,
  10. fakeProviderConfig,
  11. makeCaseDirs,
  12. modelRequests,
  13. stringifyModelRequest,
  14. writeProviderConfig,
  15. } from "./case-utils.mjs";
  16. import { writeJsonFile } from "./artifacts.mjs";
  17. import { prepareWorkspace } from "./workspace.mjs";
  18. import {
  19. chatCompletion,
  20. startScriptedProvider,
  21. stopScriptedProvider,
  22. writeScriptedCaptureFile,
  23. } from "./scripted-provider.mjs";
  24. const CASE_NAME = "bash-read-state";
  25. const COMPLETION_MARKER = "BASH_READ_STATE_E2E_DONE";
  26. const TARGET_FILE = "target.txt";
  27. const INITIAL_CONTENT = "alpha\nbeta\n";
  28. const FORMATTED_CONTENT = "delta\nbeta\n";
  29. const STALE_HINT =
  30. "[This command modified 1 file you've previously read: target.txt. Call Read before editing.]";
  31. const NOT_READ_ERROR = "File has not been read yet. Read it first before writing to it.";
  32. export const bashReadStateCase = {
  33. name: CASE_NAME,
  34. requiresApiKey: false,
  35. async run(input) {
  36. const events = [];
  37. const paths = await makeCaseDirs({ ...input, caseName: CASE_NAME });
  38. const targetPath = join(paths.workspace, TARGET_FILE);
  39. let app;
  40. let provider;
  41. try {
  42. await prepareWorkspace({
  43. fixtureDir: input.fixtureDir,
  44. workspace: paths.workspace,
  45. });
  46. await writeFile(targetPath, INITIAL_CONTENT);
  47. await writeFormatterScript(paths.workspace);
  48. provider = await startScriptedProvider({
  49. handler: createBashReadStateHandler({ targetPath }),
  50. name: CASE_NAME,
  51. });
  52. await writeProviderConfig(
  53. paths.configPath,
  54. fakeProviderConfig({
  55. baseURL: provider.baseURL,
  56. model: FAKE_MODEL,
  57. storageDir: paths.storageDir,
  58. }),
  59. );
  60. app = await createApp({
  61. configPath: paths.configPath,
  62. modules: input.modules,
  63. runtimeConfig: buildRuntimeConfig({
  64. compact: {
  65. contextWindow: 1_000_000,
  66. microcompact: { enabled: false },
  67. },
  68. maxTurns: 8,
  69. workspace: paths.workspace,
  70. }),
  71. storageDir: paths.storageDir,
  72. });
  73. const result = await app.submitPrompt(buildPrompt({ targetPath }), {
  74. onEvent: async (event) => events.push(event),
  75. });
  76. await assertBashReadStateOutcome({
  77. events,
  78. records: provider.records,
  79. response: result.response,
  80. SessionEventType: input.modules.SessionEventType,
  81. targetPath,
  82. });
  83. assertProviderCapture(provider.records);
  84. await writeScriptedCaptureFile(provider, paths.capturePath);
  85. await writeJsonFile(paths.eventsPath, events);
  86. const resultPayload = buildCaseResult({
  87. capturedProviderRequestCount: provider.records.length,
  88. caseName: CASE_NAME,
  89. capturePath: paths.capturePath,
  90. events,
  91. eventsPath: paths.eventsPath,
  92. response: result.response,
  93. resultPath: paths.resultPath,
  94. traceId: result.traceId,
  95. });
  96. await writeJsonFile(paths.resultPath, resultPayload);
  97. return resultPayload;
  98. } catch (error) {
  99. await writeScriptedCaptureFile(provider, paths.capturePath);
  100. await writeJsonFile(paths.eventsPath, events);
  101. throw error;
  102. } finally {
  103. await app?.close?.();
  104. await stopScriptedProvider(provider);
  105. }
  106. },
  107. };
  108. function buildPrompt({ targetPath }) {
  109. return [
  110. "Run the Bash read-state E2E.",
  111. `First use Bash to run cat ${TARGET_FILE}.`,
  112. `Then use Edit to replace alpha with gamma in ${targetPath}.`,
  113. "Then use Bash to run node scripts/overwrite-target.mjs --fix.",
  114. "When the stale read hint appears, answer with the completion marker only.",
  115. `Completion marker: ${COMPLETION_MARKER}`,
  116. ].join("\n");
  117. }
  118. function createBashReadStateHandler({ targetPath }) {
  119. let requestCount = 0;
  120. return async ({ body }) => {
  121. requestCount += 1;
  122. const requestText = JSON.stringify(body?.messages ?? []);
  123. if (requestCount === 1) {
  124. return {
  125. body: chatCompletion({
  126. model: body?.model,
  127. toolCalls: [
  128. openAiToolCall("call_bash_read_state_cat", "Bash", {
  129. command: `cat ${TARGET_FILE}`,
  130. description: "Read target through Bash cat",
  131. }),
  132. ],
  133. }),
  134. };
  135. }
  136. if (requestCount === 2) {
  137. assertCondition(
  138. requestText.includes("alpha") && requestText.includes("beta"),
  139. "expected Bash cat output before Edit",
  140. { requestText: tailForDiagnostics(requestText) },
  141. );
  142. assertCondition(!requestText.includes(NOT_READ_ERROR), "unexpected read guard before Edit", {
  143. requestText: tailForDiagnostics(requestText),
  144. });
  145. return {
  146. body: chatCompletion({
  147. model: body?.model,
  148. toolCalls: [
  149. openAiToolCall("call_bash_read_state_edit", "Edit", {
  150. file_path: targetPath,
  151. old_string: "alpha",
  152. new_string: "gamma",
  153. }),
  154. ],
  155. }),
  156. };
  157. }
  158. if (requestCount === 3) {
  159. assertCondition(
  160. requestText.includes("has been updated successfully"),
  161. "expected Edit success after Bash cat read-state backfill",
  162. { requestText: tailForDiagnostics(requestText) },
  163. );
  164. assertCondition(!requestText.includes(NOT_READ_ERROR), "Edit should not fail unread guard", {
  165. requestText: tailForDiagnostics(requestText),
  166. });
  167. return {
  168. body: chatCompletion({
  169. model: body?.model,
  170. toolCalls: [
  171. openAiToolCall("call_bash_read_state_format", "Bash", {
  172. command: "node scripts/overwrite-target.mjs --fix",
  173. description: "Rewrite the previously read target file",
  174. }),
  175. ],
  176. }),
  177. };
  178. }
  179. if (requestCount === 4) {
  180. assertCondition(requestText.includes(STALE_HINT), "expected Bash stale read hint", {
  181. requestText: tailForDiagnostics(requestText),
  182. });
  183. return {
  184. body: chatCompletion({
  185. content: COMPLETION_MARKER,
  186. model: body?.model,
  187. }),
  188. };
  189. }
  190. return {
  191. body: chatCompletion({
  192. content: "BASH_READ_STATE_E2E_UNEXPECTED_EXTRA_REQUEST",
  193. model: body?.model,
  194. }),
  195. };
  196. };
  197. }
  198. async function assertBashReadStateOutcome(input) {
  199. const { events, records, response, SessionEventType, targetPath } = input;
  200. const finalContent = await readFile(targetPath, "utf8");
  201. const requestContexts = modelRequests(events, SessionEventType).map(stringifyModelRequest);
  202. const providerRequestTexts = records.map(providerRequestMessageText);
  203. const allProviderText = providerRequestTexts.join("\n");
  204. assertCondition(response.includes(COMPLETION_MARKER), `expected ${COMPLETION_MARKER}`, {
  205. response,
  206. });
  207. assertCondition(finalContent === FORMATTED_CONTENT, "expected formatter to rewrite target file", {
  208. finalContent,
  209. targetPath,
  210. });
  211. assertCondition(
  212. requestContexts.some((context) => context.includes("alpha") && context.includes("beta")),
  213. "expected model context to include Bash cat output",
  214. );
  215. assertCondition(
  216. requestContexts.some((context) => context.includes("has been updated successfully")),
  217. "expected model context to include Edit success",
  218. );
  219. assertCondition(allProviderText.includes(STALE_HINT), "expected provider request stale hint", {
  220. staleHint: STALE_HINT,
  221. });
  222. assertCondition(
  223. !allProviderText.includes(NOT_READ_ERROR),
  224. "unexpected unread guard in provider traffic",
  225. );
  226. }
  227. async function writeFormatterScript(workspace) {
  228. const script = [
  229. "import { writeFile } from 'node:fs/promises';",
  230. "await new Promise((resolve) => setTimeout(resolve, 30));",
  231. `await writeFile(${JSON.stringify(TARGET_FILE)}, ${JSON.stringify(FORMATTED_CONTENT)});`,
  232. "console.log('formatted target');",
  233. "",
  234. ].join("\n");
  235. await writeFile(join(workspace, "scripts", "overwrite-target.mjs"), script);
  236. }
  237. function providerRequestMessageText(record) {
  238. try {
  239. const body = JSON.parse(record.requestBody);
  240. const messages = Array.isArray(body?.messages) ? body.messages : [];
  241. return messages.map((message) => JSON.stringify(message.content ?? "")).join("\n");
  242. } catch {
  243. return "";
  244. }
  245. }
  246. function tailForDiagnostics(text) {
  247. return text.slice(Math.max(0, text.length - 4_000));
  248. }
  249. function openAiToolCall(id, name, input) {
  250. return {
  251. id,
  252. type: "function",
  253. function: {
  254. name,
  255. arguments: JSON.stringify(input),
  256. },
  257. };
  258. }