runtime-reminders.test.ts 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458
  1. import { describe, expect, it } from "vitest";
  2. import { createSessionId } from "@zcode/contracts";
  3. import {
  4. RUNTIME_MODE_REMINDER_CONFIG,
  5. TODO_REMINDER_CONFIG,
  6. buildDateChangeReminderBody,
  7. buildPlanModeExitReminderBody,
  8. buildRuntimeModeReminderBody,
  9. buildRuntimeOutputStyleReminderBody,
  10. buildTodoReminderBody,
  11. buildProviderRequestMessages,
  12. buildRepeatedToolCallReminderBody,
  13. buildToolCallBudgetReminderBody,
  14. formatConversationForkNoticeBody,
  15. getTodoReminderTurnCounts,
  16. runtimeMetadataForSyntheticUserMessageSource,
  17. shouldBuildTodoReminder,
  18. } from "../src/runtime/helpers/index.js";
  19. import {
  20. legacySyntheticRuntimeMetadata,
  21. realUserRuntimeMetadata,
  22. systemReminderAttachmentEntry,
  23. type RuntimeMessageEntry,
  24. } from "../src/agent/message-history.js";
  25. import { buildCompactSummaryRequestMessages } from "../src/runtime/methods/compact-active-helpers.js";
  26. describe("runtime request reminders", () => {
  27. it("maps a subagent message to direct user-like runtime metadata", () => {
  28. expect(runtimeMetadataForSyntheticUserMessageSource("subagent_message")).toEqual(
  29. legacySyntheticRuntimeMetadata(),
  30. );
  31. });
  32. it("maps a persisted plugin reference back to its attachment source", () => {
  33. expect(runtimeMetadataForSyntheticUserMessageSource("plugin_reference")).toEqual({
  34. source: "plugin_reference",
  35. });
  36. });
  37. it("builds a one-time plan mode exit reminder", () => {
  38. const body = buildPlanModeExitReminderBody();
  39. expect(body).toContain("## Exited Plan Mode");
  40. expect(body).toContain("You can now make edits");
  41. expect(body).not.toContain("<system-reminder>");
  42. expect(body).not.toContain("source=");
  43. });
  44. it("counts assistant turns since the latest TodoWrite and todo reminder markers", () => {
  45. const entries = [
  46. { message: { role: "user" as const, content: "start" }, metadata: realUserRuntimeMetadata() },
  47. {
  48. message: {
  49. role: "assistant" as const,
  50. content: "",
  51. toolCalls: [{ id: "todo-write-1", name: "TodoWrite", input: {} }],
  52. },
  53. },
  54. { message: { role: "tool" as const, content: "ok", toolCallId: "todo-write-1", toolName: "TodoWrite" } },
  55. { message: { role: "assistant" as const, content: "after write 1" } },
  56. {
  57. message: { role: "user" as const, content: "todo reminder" },
  58. metadata: { source: "todo_reminder" as const },
  59. },
  60. { message: { role: "assistant" as const, content: "after reminder 1" } },
  61. { message: { role: "assistant" as const, content: "after reminder 2" } },
  62. ];
  63. expect(getTodoReminderTurnCounts(entries)).toEqual({
  64. turnsSinceLastReminder: 2,
  65. turnsSinceLastTodoWrite: 3,
  66. });
  67. });
  68. it("stops scanning todo cadence history once both latest markers are found", () => {
  69. const entries: RuntimeMessageEntry[] = [
  70. { message: { role: "assistant", content: "old assistant turn" } },
  71. { message: { role: "assistant", content: "older assistant turn" } },
  72. {
  73. message: {
  74. role: "assistant",
  75. content: "",
  76. toolCalls: [{ id: "todo-write-latest", name: "TodoWrite", input: {} }],
  77. },
  78. },
  79. {
  80. message: { role: "user", content: "latest todo reminder" },
  81. metadata: { source: "todo_reminder" },
  82. },
  83. { message: { role: "assistant", content: "newer assistant turn" } },
  84. ];
  85. const guardedEntries = new Proxy(entries, {
  86. get(target, property, receiver) {
  87. if (property === "0" || property === "1") {
  88. throw new Error("older history should not be read after both todo markers are found");
  89. }
  90. return Reflect.get(target, property, receiver);
  91. },
  92. });
  93. expect(getTodoReminderTurnCounts(guardedEntries)).toEqual({
  94. turnsSinceLastReminder: 1,
  95. turnsSinceLastTodoWrite: 1,
  96. });
  97. });
  98. it("treats sessions without TodoWrite or prior todo reminders as counting from the start", () => {
  99. const entries = Array.from({ length: TODO_REMINDER_CONFIG.TURNS_SINCE_WRITE }, (_, index) => ({
  100. message: { role: "assistant" as const, content: `assistant turn ${index}` },
  101. }));
  102. expect(getTodoReminderTurnCounts(entries)).toEqual({
  103. turnsSinceLastReminder: TODO_REMINDER_CONFIG.TURNS_BETWEEN_REMINDERS,
  104. turnsSinceLastTodoWrite: TODO_REMINDER_CONFIG.TURNS_SINCE_WRITE,
  105. });
  106. });
  107. it("resets todo cadence when TodoWrite appears in a recent assistant turn", () => {
  108. const entries = [
  109. { message: { role: "assistant" as const, content: "old assistant 1" } },
  110. {
  111. message: {
  112. role: "assistant" as const,
  113. content: "",
  114. toolCalls: [{ id: "todo-write-recent", name: "TodoWrite", input: {} }],
  115. },
  116. },
  117. { message: { role: "tool" as const, content: "ok", toolCallId: "todo-write-recent", toolName: "TodoWrite" } },
  118. { message: { role: "assistant" as const, content: "recent assistant" } },
  119. ];
  120. expect(getTodoReminderTurnCounts(entries)).toMatchObject({
  121. turnsSinceLastTodoWrite: 1,
  122. });
  123. });
  124. it("allows another todo reminder when the previous marker is old enough", () => {
  125. const entries = [
  126. {
  127. message: { role: "user" as const, content: "old todo reminder" },
  128. metadata: { source: "todo_reminder" as const },
  129. },
  130. ...Array.from({ length: TODO_REMINDER_CONFIG.TURNS_BETWEEN_REMINDERS }, (_, index) => ({
  131. message: { role: "assistant" as const, content: `assistant turn ${index}` },
  132. })),
  133. ];
  134. expect(shouldBuildTodoReminder(entries)).toBe(true);
  135. });
  136. it("omits todo list details when a due reminder has no current todos", () => {
  137. const body = buildTodoReminderBody([]);
  138. expect(body).toContain("The TodoWrite tool hasn't been used recently.");
  139. expect(body).not.toContain("<system-reminder>");
  140. expect(body).toContain("Only use it if it's relevant to the current work.");
  141. expect(body).toContain("ignore if not applicable");
  142. expect(body).not.toContain("Here are the existing contents of your todo list:");
  143. expect(body).not.toContain("[pending]");
  144. });
  145. it("builds an aligned todo reminder without the old authoritative todo_state wording", () => {
  146. const body = buildTodoReminderBody([
  147. {
  148. content: "Review prompt trajectory output",
  149. priority: "high",
  150. status: "in_progress",
  151. },
  152. ]);
  153. expect(body).toContain("1. [in_progress] Review prompt trajectory output");
  154. expect(body).not.toContain("<system-reminder>");
  155. expect(body).toContain("The TodoWrite tool hasn't been used recently.");
  156. expect(body).toContain("Only use it if it's relevant to the current work.");
  157. expect(body).toContain("ignore if not applicable");
  158. expect(body).toContain("Here are the existing contents of your todo list:");
  159. expect(body).not.toContain("Current session todo state (authoritative):");
  160. expect(body).not.toContain("source=");
  161. });
  162. it("builds date change reminder with no-user-mention wording", () => {
  163. const body = buildDateChangeReminderBody("2026-06-03", "2026-06-04");
  164. expect(body).toContain("The date has changed. Today's date is now 2026-06-04.");
  165. expect(body).not.toContain("<system-reminder>");
  166. expect(body).toContain("DO NOT mention this to the user explicitly");
  167. expect(body).not.toContain("from 2026-06-03 to 2026-06-04");
  168. });
  169. it("escapes nested system reminder-like text in conversation fork notices", () => {
  170. const body = formatConversationForkNoticeBody({
  171. parentSessionId: createSessionId("parent-<system-reminder>") as never,
  172. targetMessageId: "message-</system-reminder>" as never,
  173. });
  174. expect(body).not.toContain("<system-reminder>");
  175. expect(body).not.toContain("</system-reminder>");
  176. expect(body).toContain("parentSessionId: sess_parent-&lt;system-reminder>");
  177. expect(body).toContain("targetMessageId: message-&lt;/system-reminder>");
  178. });
  179. it("builds output style reminder only for non-empty active style", () => {
  180. expect(buildRuntimeOutputStyleReminderBody(undefined)).toBeNull();
  181. expect(
  182. buildRuntimeOutputStyleReminderBody({
  183. name: "Default",
  184. prompt: " ",
  185. }),
  186. ).toBeNull();
  187. const body = buildRuntimeOutputStyleReminderBody({
  188. name: "Learning",
  189. prompt: "Explain tradeoffs while solving the task.",
  190. });
  191. expect(body).toBe("Learning output style is active. Remember to follow the specific guidelines for this style.");
  192. expect(body).toContain("Learning output style is active");
  193. expect(body).not.toContain("Explain tradeoffs while solving the task.");
  194. expect(body).not.toContain("<system-reminder>");
  195. expect(body).not.toContain("source=");
  196. });
  197. it("builds plan mode reminders with human-turn cadence and full/sparse cycle", () => {
  198. const firstBody = buildRuntimeModeReminderBody(
  199. [{ message: { role: "user", content: "make a plan" }, metadata: realUserRuntimeMetadata() }],
  200. "plan",
  201. );
  202. expect(firstBody).toContain("Plan mode is active");
  203. expect(firstBody).not.toContain("<system-reminder>");
  204. expect(firstBody).toContain("MUST NOT make any edits");
  205. expect(firstBody).toContain("## Plan Workflow");
  206. expect(firstBody).not.toContain("ExitPlanModeV2");
  207. const recent = buildRuntimeModeReminderBody(
  208. [
  209. {
  210. message: { role: "user", content: "old full plan reminder" },
  211. metadata: { source: "runtime_mode" },
  212. },
  213. ...Array.from(
  214. { length: RUNTIME_MODE_REMINDER_CONFIG.TURNS_BETWEEN_ATTACHMENTS - 1 },
  215. (_, index) => ({
  216. message: { role: "user" as const, content: `follow up ${index}` },
  217. metadata: realUserRuntimeMetadata(),
  218. }),
  219. ),
  220. ],
  221. "plan",
  222. );
  223. expect(recent).toBeNull();
  224. const sparse = buildRuntimeModeReminderBody(
  225. [
  226. {
  227. message: { role: "user", content: "old full plan reminder" },
  228. metadata: { source: "runtime_mode" },
  229. },
  230. ...Array.from(
  231. { length: RUNTIME_MODE_REMINDER_CONFIG.TURNS_BETWEEN_ATTACHMENTS },
  232. (_, index) => ({
  233. message: { role: "user" as const, content: `follow up ${index}` },
  234. metadata: realUserRuntimeMetadata(),
  235. }),
  236. ),
  237. ],
  238. "plan",
  239. );
  240. expect(sparse).toContain("Plan mode still active");
  241. expect(sparse).toContain("Read-only.");
  242. expect(sparse).not.toContain("## Plan Workflow");
  243. expect(sparse).not.toContain("<system-reminder>");
  244. const nextFull = buildRuntimeModeReminderBody(
  245. [
  246. ...Array.from(
  247. { length: RUNTIME_MODE_REMINDER_CONFIG.FULL_REMINDER_EVERY_N_ATTACHMENTS },
  248. (_, index) => ({
  249. message: { role: "user" as const, content: `prior runtime reminder ${index}` },
  250. metadata: { source: "runtime_mode" as const },
  251. }),
  252. ),
  253. ...Array.from(
  254. { length: RUNTIME_MODE_REMINDER_CONFIG.TURNS_BETWEEN_ATTACHMENTS },
  255. (_, index) => ({
  256. message: { role: "user" as const, content: `later follow up ${index}` },
  257. metadata: realUserRuntimeMetadata(),
  258. }),
  259. ),
  260. ],
  261. "plan",
  262. );
  263. expect(nextFull).toContain("Plan mode is active");
  264. expect(buildRuntimeModeReminderBody([], "build")).toBeNull();
  265. });
  266. it("builds model anomaly reminder bodies without wrapping", () => {
  267. const budgetBody = buildToolCallBudgetReminderBody(42);
  268. const repeatedBody = buildRepeatedToolCallReminderBody("Read", 3);
  269. expect(budgetBody).toContain("This turn has already made 42 tool calls.");
  270. expect(repeatedBody).toContain("You have called Read with the same input 3 times in a row.");
  271. expect(budgetBody).not.toContain("<system-reminder>");
  272. expect(repeatedBody).not.toContain("<system-reminder>");
  273. });
  274. it("uses metadata instead of system-reminder text to find the latest real user", () => {
  275. const entries: RuntimeMessageEntry[] = [
  276. { message: { role: "system", content: "system prompt" } },
  277. {
  278. message: {
  279. role: "user",
  280. content: "<system-reminder>\nuser typed this literal tag\n</system-reminder>",
  281. },
  282. metadata: realUserRuntimeMetadata(),
  283. },
  284. ];
  285. const { messages } = buildProviderRequestMessages({ entries, applyCacheControl: true });
  286. expect(messages.at(-1)).toMatchObject({
  287. role: "user",
  288. cacheControl: { type: "ephemeral" },
  289. });
  290. });
  291. it("bubbles legacy synthetic system-reminder text before latest non-system cache-control finalization", () => {
  292. const entries: RuntimeMessageEntry[] = [
  293. {
  294. message: {
  295. role: "user",
  296. content: "<system-reminder>\nuser typed this literal tag\n</system-reminder>",
  297. },
  298. metadata: realUserRuntimeMetadata(),
  299. },
  300. {
  301. message: {
  302. role: "user",
  303. content: "<system-reminder>\nlegacy synthetic reminder\n</system-reminder>",
  304. },
  305. metadata: legacySyntheticRuntimeMetadata(),
  306. },
  307. ];
  308. const { messages } = buildProviderRequestMessages({ entries, applyCacheControl: true });
  309. expect(messages).toEqual([
  310. {
  311. role: "user",
  312. content: "<system-reminder>\nlegacy synthetic reminder\n</system-reminder>",
  313. },
  314. {
  315. role: "user",
  316. content: "<system-reminder>\nuser typed this literal tag\n</system-reminder>",
  317. cacheControl: { type: "ephemeral" },
  318. },
  319. ]);
  320. });
  321. it("does not append runtime target reminders to provider request entries", () => {
  322. const entries: RuntimeMessageEntry[] = [
  323. { message: { role: "system", content: "system prompt" } },
  324. {
  325. message: { role: "user", content: "compare prompts" },
  326. metadata: realUserRuntimeMetadata(),
  327. },
  328. {
  329. message: {
  330. role: "user",
  331. content: "<system-reminder>\nPlan mode is active\n</system-reminder>",
  332. },
  333. metadata: { source: "runtime_mode" },
  334. },
  335. ];
  336. expect(entries).toHaveLength(3);
  337. expect(entries[1]).toMatchObject({
  338. message: {
  339. role: "user",
  340. content: "compare prompts",
  341. },
  342. });
  343. expect(entries[1]?.message).not.toHaveProperty("cacheControl");
  344. const { messages } = buildProviderRequestMessages({ entries, applyCacheControl: true });
  345. expect(messages).toHaveLength(3);
  346. expect(messages[1]).toEqual({
  347. role: "user",
  348. content: "compare prompts",
  349. });
  350. expect(messages[2]).toMatchObject({
  351. role: "user",
  352. cacheControl: { type: "ephemeral" },
  353. });
  354. expect(JSON.stringify(messages[2]?.content)).toContain("Plan mode is active");
  355. const reminderTexts = String(JSON.stringify(messages));
  356. expect(reminderTexts).toContain("compare prompts");
  357. expect(reminderTexts).not.toContain("Current session goal state");
  358. expect(reminderTexts).not.toContain("Review prompt trajectory output");
  359. expect(JSON.stringify(messages)).not.toContain("projectionPolicy");
  360. });
  361. it("projects compact summary requests with attachment ordering and skipped cache write", () => {
  362. const messages = buildCompactSummaryRequestMessages(
  363. [
  364. { message: { role: "system", content: "system prompt" } },
  365. {
  366. message: { role: "user", content: "<system-reminder>\nprefix\n</system-reminder>" },
  367. metadata: { source: "context_prefix" },
  368. },
  369. {
  370. message: { role: "user", content: "summarize this history" },
  371. metadata: realUserRuntimeMetadata(),
  372. },
  373. systemReminderAttachmentEntry("output_style", "Use concise output for this turn."),
  374. ],
  375. "Create compact summary.",
  376. );
  377. expect(messages).toHaveLength(5);
  378. expect(messages[1]).toEqual({
  379. role: "user",
  380. content: "<system-reminder>\nprefix\n</system-reminder>",
  381. });
  382. expect(messages[2]).toEqual({
  383. role: "user",
  384. content: "summarize this history",
  385. cacheControl: { type: "ephemeral" },
  386. });
  387. expect(messages[3]).toMatchObject({
  388. role: "user",
  389. });
  390. expect(messages[3]).not.toHaveProperty("cacheControl");
  391. expect(messages[4]).toEqual({
  392. role: "system",
  393. content: "Use concise output for this turn.",
  394. });
  395. expect(JSON.stringify(messages[3]?.content)).toContain("Create compact summary.");
  396. expect(JSON.stringify(messages)).not.toContain("output_style");
  397. });
  398. it("keeps a trailing newline after the request user context system-reminder close tag", () => {
  399. const { messages } = buildProviderRequestMessages({
  400. entries: [
  401. { message: { role: "system", content: "system prompt" } },
  402. systemReminderAttachmentEntry(
  403. "context_prefix",
  404. "As you answer the user's questions, you can use the following context:\n# currentDate\nToday's date is 2026-06-28.",
  405. ),
  406. { message: { role: "user", content: "hello" }, metadata: realUserRuntimeMetadata() },
  407. ],
  408. });
  409. expect(messages[1]).toEqual({
  410. role: "user",
  411. content:
  412. "<system-reminder>\nAs you answer the user's questions, you can use the following context:\n# currentDate\nToday's date is 2026-06-28.\n</system-reminder>\n",
  413. });
  414. });
  415. });