runtime-reminders.test.ts 16 KB

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