memory-e2e-provider.mjs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314
  1. const modelId = "memory-e2e-model";
  2. export const memoryE2EText = Object.freeze({
  3. customMemoryMarker: "# Persistent Agent Memory",
  4. customParentPrompt: "delegate",
  5. customResultMarker: "E2E_CUSTOM_AGENT_DONE",
  6. customTaskPrompt: "Store the review convention in your persistent project memory.",
  7. customWriteMarker: "E2E_CUSTOM_MEMORY_WRITTEN",
  8. closeCancellationPrompt:
  9. "Close this session while its background Memory extraction is in flight.",
  10. closeCancellationWriteMarker: "E2E_CLOSE_CANCELLED_EXTRACTION_MUST_NOT_WRITE",
  11. defaultBoundaryMarker: "E2E_MEMORY_DEFAULT_BOUNDARY",
  12. defaultBranchPrompt: "MemoryDefaultBranch check",
  13. disabledPrompt: "Check that disabled memory leaves this request unchanged.",
  14. extractedDefaultPrompt: "Check the deployment approval policy from project memory.",
  15. extractedRecallBoundaryMarker: "E2E_EXTRACTED_MEMORY_RECALL_BOUNDARY",
  16. extractedIndexPointer:
  17. "- [Deployment approval policy](deployment-approval-policy.md) — staging approval required",
  18. extractionMarker: "You are now acting as the memory extraction subagent",
  19. extractionPrompt:
  20. "The deployment policy requires staging approval because release managers need an audit trail.",
  21. extractionWriteMarker: "E2E_EXTRACTION_WRITTEN",
  22. headlessPrompt: "HeadlessMemoryExtractionDisabled",
  23. recalledPrefix: "Retrieved for possible relevance — use only if it actually applies",
  24. selectorMarker: "You are selecting memories that will be useful",
  25. });
  26. export function createMemoryExtractionCloseBarrier() {
  27. const started = deferred();
  28. const release = deferred();
  29. return {
  30. async blockResponse() {
  31. started.resolve();
  32. await release.promise;
  33. },
  34. releaseResponse() {
  35. release.resolve();
  36. },
  37. waitUntilStarted() {
  38. return started.promise;
  39. },
  40. };
  41. }
  42. export function createProviderHandler({ closeBarrier, paths, retrievalBranch }) {
  43. return async ({ body }) => {
  44. const category = classifyRequest(body);
  45. const text = requestText(body);
  46. if (category === "selector") {
  47. const selectedMemory = text.includes(memoryE2EText.extractedDefaultPrompt)
  48. ? "deployment-approval-policy.md"
  49. : "database-test-policy.md";
  50. return completion({
  51. content: JSON.stringify({ selected_memories: [selectedMemory] }),
  52. id: `memory-selector-${selectedMemory.replace(".md", "")}`,
  53. });
  54. }
  55. if (category === "extraction") {
  56. if (text.includes(memoryE2EText.closeCancellationPrompt)) {
  57. await closeBarrier.blockResponse();
  58. return completion({
  59. id: "memory-close-cancelled-extraction-late-write",
  60. toolCalls: [
  61. toolCall("memory_close_cancelled_extraction_write", "Write", {
  62. content: memoryE2EText.closeCancellationWriteMarker,
  63. file_path: paths.shutdown.cancelledFile,
  64. }),
  65. ],
  66. });
  67. }
  68. if (!text.includes(memoryE2EText.extractionPrompt)) {
  69. return completion({ content: "Nothing to save.", id: "memory-extraction-default-noop" });
  70. }
  71. if (text.includes(memoryE2EText.extractedIndexPointer)) {
  72. return completion({ content: "Nothing to save.", id: "memory-extraction-finished" });
  73. }
  74. if (text.includes(memoryE2EText.extractionWriteMarker)) {
  75. return completion({
  76. id: "memory-extraction-index-edit",
  77. toolCalls: [
  78. toolCall("memory_extraction_index_edit", "Edit", {
  79. file_path: paths.project.indexFile,
  80. new_string: updatedProjectMemoryIndex(),
  81. old_string: initialProjectMemoryIndex(),
  82. }),
  83. ],
  84. });
  85. }
  86. return completion({
  87. id: "memory-extraction-write",
  88. toolCalls: [
  89. toolCall("memory_extraction_write", "Write", {
  90. content: extractedMemoryFile(),
  91. file_path: paths.project.extractedFile,
  92. }),
  93. toolCall("memory_extraction_index_read", "Read", {
  94. file_path: paths.project.indexFile,
  95. }),
  96. ],
  97. });
  98. }
  99. if (category === "custom_agent") {
  100. if (text.includes(memoryE2EText.customWriteMarker)) {
  101. return completion({
  102. content: memoryE2EText.customResultMarker,
  103. id: "custom-memory-finished",
  104. });
  105. }
  106. return completion({
  107. id: "custom-memory-write",
  108. toolCalls: [
  109. toolCall("custom_memory_write", "Write", {
  110. content: customMemoryFile(),
  111. file_path: paths.custom.memoryFile,
  112. }),
  113. ],
  114. });
  115. }
  116. if (text.includes(memoryE2EText.disabledPrompt)) {
  117. return completion({ content: "Disabled Memory request completed.", id: "memory-disabled" });
  118. }
  119. if (text.includes(memoryE2EText.headlessPrompt)) {
  120. return completion({ content: "Headless Memory request completed.", id: "memory-headless" });
  121. }
  122. if (text.includes(memoryE2EText.closeCancellationPrompt)) {
  123. return completion({
  124. content: "Memory Extraction close scenario scheduled.",
  125. id: "memory-close-cancellation-main",
  126. });
  127. }
  128. if (text.includes(memoryE2EText.extractedDefaultPrompt)) {
  129. if (
  130. retrievalBranch === "semantic-recall" &&
  131. !text.includes(memoryE2EText.extractedRecallBoundaryMarker)
  132. ) {
  133. return completion({
  134. id: "memory-extracted-recall-boundary",
  135. toolCalls: [
  136. toolCall("memory_extracted_recall_boundary", "Bash", {
  137. command: `printf ${memoryE2EText.extractedRecallBoundaryMarker}`,
  138. }),
  139. ],
  140. });
  141. }
  142. return completion({
  143. content:
  144. retrievalBranch === "semantic-recall"
  145. ? "Extracted project Memory recalled."
  146. : "Updated project Memory index loaded.",
  147. id: "memory-extracted-default",
  148. });
  149. }
  150. if (text.includes(memoryE2EText.customParentPrompt)) {
  151. if (text.includes(memoryE2EText.customResultMarker)) {
  152. return completion({ content: "Custom Memory task completed.", id: "custom-parent-final" });
  153. }
  154. return completion({
  155. id: "custom-parent-agent",
  156. toolCalls: [
  157. toolCall("custom_parent_agent", "Agent", {
  158. description: "Persist review convention",
  159. prompt: memoryE2EText.customTaskPrompt,
  160. subagent_type: "memory-curator",
  161. }),
  162. ],
  163. });
  164. }
  165. if (text.includes(memoryE2EText.extractionPrompt)) {
  166. return completion({ content: "Deployment policy noted.", id: "memory-main-extraction" });
  167. }
  168. if (text.includes(memoryE2EText.defaultBranchPrompt)) {
  169. if (text.includes(memoryE2EText.defaultBoundaryMarker)) {
  170. return completion({ content: "Default Memory branch completed.", id: "memory-main-final" });
  171. }
  172. return completion({
  173. id: "memory-main-tool-boundary",
  174. toolCalls: [
  175. toolCall("memory_default_branch_boundary", "Bash", {
  176. command: `printf ${memoryE2EText.defaultBoundaryMarker}`,
  177. }),
  178. ],
  179. });
  180. }
  181. throw new Error(`Unexpected Memory E2E provider request: ${text.slice(-1_000)}`);
  182. };
  183. }
  184. export function classifyRequest(body) {
  185. const text = requestText(body);
  186. if (text.includes(memoryE2EText.selectorMarker)) return "selector";
  187. if (text.includes(memoryE2EText.extractionMarker)) return "extraction";
  188. if (text.includes(memoryE2EText.customMemoryMarker)) return "custom_agent";
  189. return "main";
  190. }
  191. export function requestText(body) {
  192. return [contentText(body.system), contentText(body.messages ?? body.input ?? [])]
  193. .filter(Boolean)
  194. .join("\n");
  195. }
  196. function contentText(value) {
  197. if (typeof value === "string") return value;
  198. if (Array.isArray(value)) return value.map(contentText).filter(Boolean).join("\n");
  199. if (!value || typeof value !== "object") return "";
  200. const primary = [value.text, value.content, value.output]
  201. .map(contentText)
  202. .filter(Boolean)
  203. .join("\n");
  204. const toolPayload = [value.input, value.arguments, value.tool_calls]
  205. .filter((item) => item !== undefined)
  206. .map((item) => (typeof item === "string" ? item : JSON.stringify(item)))
  207. .join("\n");
  208. return [primary, toolPayload].filter(Boolean).join("\n");
  209. }
  210. function completion({ content = "", id, toolCalls }) {
  211. return {
  212. body: {
  213. content: toolCalls
  214. ? toolCalls.map((call) => ({
  215. id: call.id,
  216. input: JSON.parse(call.function.arguments),
  217. name: call.function.name,
  218. type: "tool_use",
  219. }))
  220. : [{ text: content, type: "text" }],
  221. id: `msg_${id}`,
  222. model: modelId,
  223. role: "assistant",
  224. stop_reason: toolCalls ? "tool_use" : "end_turn",
  225. stop_sequence: null,
  226. type: "message",
  227. usage: { input_tokens: 1, output_tokens: 1 },
  228. },
  229. };
  230. }
  231. function toolCall(id, name, input) {
  232. return {
  233. function: { arguments: JSON.stringify(input), name },
  234. id,
  235. type: "function",
  236. };
  237. }
  238. function deferred() {
  239. let resolve;
  240. const promise = new Promise((settle) => {
  241. resolve = settle;
  242. });
  243. return { promise, resolve };
  244. }
  245. export function existingMemoryFile() {
  246. return `---
  247. name: database-test-policy
  248. description: Database tests must use the real database rather than mocks.
  249. metadata:
  250. type: feedback
  251. ---
  252. Use the real database for database tests; mocked database tests are not trusted.
  253. **Why:** A prior mocked test passed while production migration behavior failed.
  254. **How to apply:** Use the real database for database integration tests.
  255. `;
  256. }
  257. export function initialProjectMemoryIndex() {
  258. return "- [Database test policy](database-test-policy.md) — integration tests use isolated databases\n";
  259. }
  260. export function updatedProjectMemoryIndex() {
  261. return `${initialProjectMemoryIndex()}${memoryE2EText.extractedIndexPointer}\n`;
  262. }
  263. function extractedMemoryFile() {
  264. return `---
  265. name: deployment-approval-policy
  266. description: Deployment requires staging approval for an audit trail.
  267. metadata:
  268. type: project
  269. ---
  270. Deployment requires staging approval. ${memoryE2EText.extractionWriteMarker}
  271. **Why:** Release managers need an audit trail.
  272. **How to apply:** Require staging approval before deployment.
  273. `;
  274. }
  275. function customMemoryFile() {
  276. return `---
  277. name: review-convention
  278. description: Review findings should be grounded in first-hand evidence.
  279. metadata:
  280. type: feedback
  281. ---
  282. Ground review findings in first-hand evidence. ${memoryE2EText.customWriteMarker}
  283. **Why:** It prevents speculative defects.
  284. **How to apply:** Reproduce or inspect the active path before reporting a finding.
  285. `;
  286. }