runtime-context-announcements.test.ts 102 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278
  1. import { createHash } from "node:crypto";
  2. import { join } from "node:path";
  3. import { beforeEach, describe, expect, it, vi } from "vitest";
  4. import {
  5. CompactTrigger,
  6. createFileSystemError,
  7. createRootTraceContext,
  8. createSessionId,
  9. createToolCallId,
  10. ModelErrorCode,
  11. type ContextSourcePort,
  12. type ContextSourceRequest,
  13. type ModelRequest,
  14. type ModelResult,
  15. type SkillPort,
  16. } from "@zcode/contracts";
  17. import { createTestAgentRuntime } from "./test-agent-runtime.js";
  18. import { createTestModelSelection } from "./test-model-selection.js";
  19. import { createTestSessionEventStore } from "./test-event-store.js";
  20. import { createTestModelFactory } from "./test-runtime-model.js";
  21. import { createRecordingMessageStore } from "./runtime-output-token-continuation-test-helpers.js";
  22. import { createToolRegistry } from "../src/tool/registry.js";
  23. import { createReadFileStatePathKey } from "../src/tool/read-file-state.js";
  24. import { resolveProjectMemoryRoot } from "../src/memory/project-root.js";
  25. import { MemoryFileSystem } from "./memory-test-utils.js";
  26. import type { AgentDefinitionsSnapshot } from "../src/subagent/definitions.js";
  27. import { buildProviderRequestMessages } from "../src/runtime/helpers/provider-request-messages.js";
  28. import { systemReminderAttachmentEntry } from "../src/agent/message-history.js";
  29. import type { AgentRuntimeInternal } from "../src/runtime/internal.js";
  30. import {
  31. buildCompactLeadingAnnouncements,
  32. buildRequestAnnouncements,
  33. restateContextAfterCompact,
  34. } from "../src/runtime/methods/context-refresh.js";
  35. import type { AgentRuntimeConfig, AgentRuntimeDeps } from "../src/runtime/types.js";
  36. import { resolveGenUiOutputDirectory } from "../src/runtime/helpers/gen-ui-output.js";
  37. import {
  38. buildEnvironmentAnnouncement,
  39. type EnvironmentSnapshot,
  40. } from "../src/context/sections/env-info.js";
  41. import { buildDesktopContextContent } from "../src/context/sections/desktop.js";
  42. import { createInstructionFile } from "../src/context/sections/instruction-files.js";
  43. import { createContextBuilder } from "../src/context/index.js";
  44. import { formatWorkflowStallNotification } from "../src/runtime-task/workflow-notification-copy.js";
  45. const snapshot = (...names: string[]): AgentDefinitionsSnapshot => ({
  46. activeAgents: names.map((name) => ({
  47. name,
  48. description: `Description ${name}`,
  49. source: "user",
  50. systemPrompt: "private",
  51. })),
  52. });
  53. const result = {
  54. finishReason: "stop" as const,
  55. text: "Summary of current work.",
  56. usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 },
  57. };
  58. let sessionId: ReturnType<typeof createSessionId>;
  59. let store: ReturnType<typeof createRecordingMessageStore>;
  60. let requests: ModelRequest[];
  61. const definitions = vi.fn(() => snapshot("A"));
  62. const respond = vi.fn<(request: ModelRequest) => Promise<ModelResult>>();
  63. let runtime: ReturnType<typeof createTestAgentRuntime>;
  64. function createRuntime(
  65. deps: Partial<AgentRuntimeDeps> = {},
  66. config: Partial<AgentRuntimeConfig> = {},
  67. { mcs = true, fold = false }: { mcs?: boolean; fold?: boolean } = {},
  68. ) {
  69. const modelFactory = createTestModelFactory({
  70. properties: { supportsMidConversationSystem: mcs },
  71. generateText: async (request) => {
  72. requests.push(request);
  73. return respond(request);
  74. },
  75. });
  76. return createTestAgentRuntime(
  77. sessionId,
  78. { mode: "yolo", compact: { enabled: false }, titleGeneration: { enabled: false }, ...config },
  79. {
  80. eventStore: createTestSessionEventStore(),
  81. sessionStore: store as never,
  82. getAgentDefinitions: definitions,
  83. modelFactory: fold
  84. ? (input) => ({
  85. ...modelFactory(input),
  86. requestCapabilities: { foldRemindersIntoToolResults: true },
  87. })
  88. : modelFactory,
  89. ...deps,
  90. },
  91. );
  92. }
  93. const entries = () =>
  94. (runtime as unknown as AgentRuntimeInternal).messageHistory.toRuntimeEntries();
  95. const compact = (value: ReturnType<typeof createTestAgentRuntime>, trigger?: CompactTrigger) =>
  96. (value as unknown as AgentRuntimeInternal).compactActiveConversation(
  97. undefined,
  98. createRootTraceContext({ sessionId }),
  99. [],
  100. { trigger },
  101. );
  102. beforeEach(() => {
  103. sessionId = createSessionId();
  104. store = createRecordingMessageStore();
  105. requests = [];
  106. definitions.mockReset().mockImplementation(() => snapshot("A"));
  107. respond.mockReset().mockResolvedValue(result);
  108. runtime = createRuntime();
  109. });
  110. const skillPort: SkillPort = {
  111. async discoverSkills() {
  112. return {
  113. skills: [
  114. {
  115. name: "search",
  116. description: "search things",
  117. path: "/workspace/.agents/skills/search/SKILL.md",
  118. directory: "/workspace/.agents/skills/search",
  119. rootPath: "/workspace/.agents/skills",
  120. scope: "project" as const,
  121. source: "agents" as const,
  122. safeToAutoLoad: true,
  123. frontmatterKeys: [],
  124. },
  125. ],
  126. diagnostics: [],
  127. totalDiscovered: 1,
  128. };
  129. },
  130. async loadSkill() {
  131. throw new Error("not needed");
  132. },
  133. };
  134. describe("runtime context announcements", () => {
  135. // 顺序即宣告顺序:environment → model → (agent listing) → skills → instructions → git → date。
  136. const sources = new Set([
  137. "environment",
  138. "model",
  139. "skills_listing",
  140. "context_prefix",
  141. "session_context",
  142. "date",
  143. ]);
  144. // 动态公告按隐藏提醒落盘:类型只记在 runtimeMessage.source,不写顶层 source。
  145. const runtimeSourceOf = (message: { metadata?: Record<string, unknown> }) =>
  146. (message.metadata?.runtimeMessage as { source?: string } | undefined)?.source;
  147. const isAnnouncementRecord = (message: {
  148. semantics?: { kind?: string };
  149. metadata?: Record<string, unknown>;
  150. }) =>
  151. message.semantics?.kind === "system_reminder" && sources.has(runtimeSourceOf(message) ?? "");
  152. const contextEntries = (value: ReturnType<typeof createTestAgentRuntime>) =>
  153. (value as unknown as AgentRuntimeInternal).messageHistory
  154. .toRuntimeEntries()
  155. .filter((entry) => entry.kind === "attachment" && sources.has(entry.metadata.source));
  156. const config: Partial<AgentRuntimeConfig> = {
  157. workingDirectory: "/workspace",
  158. currentDate: "2026-10-14",
  159. envInfo: {
  160. cwd: "/workspace",
  161. platform: "linux",
  162. shell: "bash",
  163. osVersion: "Linux",
  164. nodeVersion: "24",
  165. isGitRepository: true,
  166. gitStatus: "clean",
  167. gitBranch: "original",
  168. },
  169. };
  170. const now = () => new Date(2026, 9, 14, 12);
  171. const instructionsPort = (): ContextSourcePort => ({
  172. async resolveEnvironment() {
  173. return config.envInfo!;
  174. },
  175. async resolveGitContext() {
  176. return config.envInfo!;
  177. },
  178. async resolveContextSources() {
  179. return {
  180. workingDirectory: "/workspace",
  181. envInfo: config.envInfo!,
  182. userInstructions: {
  183. filePath: "/workspace/AGENTS.md",
  184. fileName: "AGENTS.md",
  185. content: "Project rule.",
  186. bytesRead: 13,
  187. sizeBytes: 13,
  188. truncated: false,
  189. },
  190. diagnostics: [],
  191. };
  192. },
  193. });
  194. const environmentPort = () =>
  195. ({
  196. async resolveContextSources() {
  197. return { workingDirectory: "/workspace", envInfo: config.envInfo!, diagnostics: [] };
  198. },
  199. resolveEnvironment: vi.fn(
  200. async ({
  201. workingDirectory,
  202. effectiveShellDisplayName,
  203. }: Pick<ContextSourceRequest, "workingDirectory" | "effectiveShellDisplayName">) => ({
  204. ...config.envInfo!,
  205. cwd: workingDirectory,
  206. shell: effectiveShellDisplayName ?? config.envInfo!.shell,
  207. isGitRepository: workingDirectory.startsWith("/workspace"),
  208. }),
  209. ),
  210. }) satisfies ContextSourcePort;
  211. // 把当前 store 复制成独立的冷存储,再从中恢复一个新 runtime。
  212. const coldRuntimeWith = async (
  213. port: SkillPort = skillPort,
  214. coldConfig: Partial<AgentRuntimeConfig> = config,
  215. coldDeps: Partial<AgentRuntimeDeps> = {},
  216. ) => {
  217. const recording = createRecordingMessageStore();
  218. // rewind 只需把分支信息写回会话;录制 store 没有 setRevert,用 updateSession 承接。
  219. const coldStore = Object.assign(recording, {
  220. async setRevert(input: { sessionID: string; revert: unknown }) {
  221. await recording.updateSession({ id: input.sessionID, revert: input.revert });
  222. },
  223. });
  224. await coldStore.createSession(await store.getSession(sessionId));
  225. coldStore.savedMessages.push(...structuredClone(store.savedMessages));
  226. coldStore.savedParts.push(...structuredClone(store.savedParts));
  227. const cold = createRuntime(
  228. {
  229. now,
  230. skillPort: port,
  231. contextSourcePort: instructionsPort(),
  232. sessionStore: coldStore as never,
  233. ...coldDeps,
  234. },
  235. coldConfig,
  236. );
  237. await cold.resumeFromStore();
  238. return { cold, coldStore };
  239. };
  240. it("announces environment and model for a custom system prompt", async () => {
  241. runtime = createRuntime(
  242. { now, contextSourcePort: environmentPort() },
  243. { ...config, systemPrompt: "Host override." },
  244. );
  245. await runtime.executeTurn("first task");
  246. // 自定义 prompt 只替换 system 正文,环境与模型公告照常发送;Git 仍不发。
  247. expect(contextEntries(runtime).map((entry) => entry.metadata?.source)).toEqual([
  248. "environment",
  249. "model",
  250. "date",
  251. ]);
  252. expect(String(requests[0]!.messages[1]!.content)).toBe("\nHost override.");
  253. });
  254. it.each([false, true])(
  255. "uses shared environment/model lifecycle for a specialized child (MCS=%s)",
  256. async (mcs) => {
  257. const contextSourcePort = environmentPort();
  258. const resolveContextSources = vi.spyOn(contextSourcePort, "resolveContextSources");
  259. const childConfig: Partial<AgentRuntimeConfig> = {
  260. ...config,
  261. taskType: "subagent_child",
  262. subagentContext: { agentPrompt: "Dedicated child identity." },
  263. subagents: { enabled: false },
  264. };
  265. runtime = createRuntime({ now, contextSourcePort }, childConfig, { mcs });
  266. await runtime.executeTurn("first child task");
  267. const initial = contextEntries(runtime);
  268. expect(initial.map((entry) => entry.metadata?.source)).toEqual([
  269. "environment",
  270. "model",
  271. "date",
  272. ]);
  273. expect(
  274. requests[0]?.messages.find((message) => String(message.content).includes("# Environment\n"))
  275. ?.role,
  276. ).toBe(mcs ? "system" : "user");
  277. const initialBody = requests[0]!.messages[1]!.content;
  278. runtime.setWorkingDirectory("/outside");
  279. const nextSelection = createTestModelSelection("test/child-next");
  280. runtime.setSessionModelSelection(nextSelection);
  281. await runtime.executeTurn("second child task");
  282. const changed = contextEntries(runtime);
  283. expect(
  284. changed.filter((entry) => entry.metadata?.source === "environment").at(-1),
  285. ).toMatchObject({
  286. content:
  287. "# Environment update\n - Primary working directory: /outside (was /workspace)\n - Is a git repository: false (was true)",
  288. });
  289. expect(changed.filter((entry) => entry.metadata?.source === "model").at(-1)).toMatchObject({
  290. content: "You are powered by the model named test/child-next.",
  291. });
  292. await runtime.executeTurn("unchanged child task");
  293. expect(contextEntries(runtime)).toEqual(changed);
  294. expect(requests.at(-1)!.messages[1]!.content).toEqual(initialBody);
  295. // child 初始快照只用父级传下的配置;端口只用于 cd 之后的环境探测。
  296. expect(resolveContextSources).not.toHaveBeenCalled();
  297. expect(contextSourcePort.resolveEnvironment).toHaveBeenCalledTimes(1);
  298. },
  299. );
  300. it.each([false, true])(
  301. "orders the first user turn by attachment collection order (MCS=%s)",
  302. async (mcs) => {
  303. runtime = createRuntime(
  304. { now, skillPort, contextSourcePort: instructionsPort() },
  305. { ...config, outputStyle: { name: "Learning", prompt: "Explain tradeoffs." } },
  306. { mcs },
  307. );
  308. await runtime.executeTurn("first");
  309. // 先产出全部输入附件(含每次收集的 output_style),请求前公告在其后,最后是本轮输入。
  310. const markers = [
  311. ["environment", "# Environment"],
  312. ["model", "You are powered by"],
  313. ["output_style_instructions", "# Output Style: Learning"],
  314. ["agents", "Available agent types"],
  315. ["skills", "The following skills"],
  316. ["total_tokens", "<total_tokens>15000000 tokens left</total_tokens>"],
  317. ["output_style", "Learning output style is active"],
  318. ["instructions", "Codebase and user instructions"],
  319. ["session_context", "As you answer"],
  320. ["date", "Today's date is"],
  321. ] as const;
  322. const messages = requests[0]!.messages.filter((message) => message.role !== "system");
  323. const userTexts = messages.map((message) => String(message.content));
  324. const promptIndex = userTexts.indexOf("first");
  325. const kinds = userTexts.slice(0, promptIndex).map((text) => {
  326. const body = text.replace(/^<system-reminder>\n/u, "");
  327. return markers.find(([, marker]) => body.startsWith(marker))?.[0];
  328. });
  329. const userSide = ["instructions", "session_context"];
  330. expect(kinds).toEqual(mcs ? userSide : markers.map(([kind]) => kind));
  331. if (mcs) {
  332. // MCS 下其余公告在 user run 末尾合成一条 system,顺序不变,user 侧没有 skill 列表。
  333. const system = requests[0]!.messages.at(-1)!;
  334. expect(system.role).toBe("system");
  335. const positions = markers
  336. .filter(([kind]) => !userSide.includes(kind))
  337. .map(([, marker]) => String(system.content).indexOf(marker));
  338. expect(positions.every((position) => position >= 0)).toBe(true);
  339. expect(positions).toEqual([...positions].sort((a, b) => a - b));
  340. expect(userTexts.some((text) => text.includes("search things"))).toBe(false);
  341. }
  342. // 默认测试模型不合并相邻 user,紧挨输入的那一块也不补换行。
  343. expect(userTexts.slice(0, promptIndex).every((text) => !text.endsWith("\n"))).toBe(true);
  344. },
  345. );
  346. it("ends only the block right before the first input with a newline when the model merges adjacent user content", async () => {
  347. // 声明合并相邻 user 内容(foldRemindersIntoToolResults)时,紧挨输入的那一块以换行结尾,其余块不补。
  348. runtime = createRuntime({ now, skillPort, contextSourcePort: instructionsPort() }, config, {
  349. mcs: false,
  350. fold: true,
  351. });
  352. await runtime.executeTurn("first");
  353. const userTexts = requests[0]!.messages
  354. .filter((message) => message.role !== "system")
  355. .map((message) => String(message.content));
  356. const promptIndex = userTexts.indexOf("first");
  357. expect(promptIndex).toBeGreaterThan(1);
  358. expect(userTexts[promptIndex - 1]).toMatch(/<\/system-reminder>\n$/u);
  359. expect(userTexts.slice(0, promptIndex - 1).every((text) => !text.endsWith("\n"))).toBe(true);
  360. });
  361. describe("turns started by a notification", () => {
  362. const marker = "NOTIFICATION_MARKER";
  363. const startTurn = {
  364. task_notification: () =>
  365. (runtime as any).enqueueBackgroundTaskNotification({
  366. text: `<task-notification><task-id>${marker}</task-id><status>completed</status></task-notification>`,
  367. traceContext: createRootTraceContext({ sessionId }),
  368. }),
  369. subagent_reply: () =>
  370. (runtime as any).enqueueSubagentMessage({
  371. responseId: "response",
  372. agentId: "agent",
  373. agentType: "general-purpose",
  374. childSessionId: createSessionId(),
  375. childToolCallId: "child-call",
  376. summary: "progress",
  377. message: marker,
  378. traceContext: createRootTraceContext({ sessionId }),
  379. }),
  380. };
  381. const contextMarkers = [
  382. "# Environment",
  383. "You are powered by",
  384. "Available agent types",
  385. "The following skills",
  386. "Codebase and user instructions",
  387. "Today's date is",
  388. ];
  389. const waitForRequests = (count: number) =>
  390. vi.waitFor(() => expect(requests.length).toBeGreaterThanOrEqual(count));
  391. const requestText = (request: ModelRequest) =>
  392. request.messages.map((message) => JSON.stringify(message.content)).join("\n");
  393. const createNotifiedRuntime = (mcs: boolean, deps: Partial<AgentRuntimeDeps> = {}) =>
  394. createRuntime({ now, skillPort, contextSourcePort: instructionsPort(), ...deps }, config, {
  395. mcs,
  396. });
  397. it.each([
  398. ["task_notification", false],
  399. ["task_notification", true],
  400. ["subagent_reply", false],
  401. ["subagent_reply", true],
  402. ] as const)(
  403. "skips input attachments but keeps request announcements on the first %s request (MCS=%s)",
  404. async (input, mcs) => {
  405. runtime = createNotifiedRuntime(mcs);
  406. await runtime.ensureSessionPersistedForExternalActivity("initial session");
  407. startTurn[input]();
  408. await waitForRequests(1);
  409. const messages = requests[0]!.messages;
  410. const indexOf = (text: string) =>
  411. messages.findIndex((message) => JSON.stringify(message.content).includes(text));
  412. const notificationIndex = indexOf(marker);
  413. expect(messages[notificationIndex]!.role).toBe("user");
  414. // 跳过附件时只跳过输入附件;请求前公告照常运行。
  415. for (const contextMarker of contextMarkers.slice(0, 4)) {
  416. expect(requestText(requests[0]!)).not.toContain(contextMarker);
  417. }
  418. // 公告冒泡到通知之前;MCS 文本落在 user run 末尾。
  419. expect(indexOf("Codebase and user instructions")).toBeLessThan(notificationIndex);
  420. if (mcs) {
  421. expect(messages.at(-1)!.role).toBe("system");
  422. expect(indexOf("Today's date is")).toBe(messages.length - 1);
  423. } else {
  424. expect(indexOf("Today's date is")).toBeLessThan(notificationIndex);
  425. expect(notificationIndex).toBe(messages.length - 1);
  426. }
  427. expect(contextEntries(runtime).map((entry) => entry.metadata.source)).toEqual(
  428. expect.arrayContaining(["context_prefix", "date"]),
  429. );
  430. expect(
  431. contextEntries(runtime).some((entry) =>
  432. ["environment", "model", "skills_listing"].includes(entry.metadata.source),
  433. ),
  434. ).toBe(false);
  435. },
  436. );
  437. // 修复原因:空闲整批原来存成一个 "\n\n" 连接的字符串,投影时再按 <task-notification> 开头猜边界;
  438. // workflow 运行中通知不以它开头,被并进前一条通知的包装。现在每条通知是同一条消息的一个文本块,
  439. // 整条消息一个事务写入,冷恢复保留这些块,live 与冷恢复发出的块逐字节相同。
  440. it.each([true, false])(
  441. "keeps each notification of an idle batch in its own block live and after a cold resume (MCS=%s)",
  442. async (mcs) => {
  443. const bundles: { messages: { info: { source?: string }; parts: unknown[] }[] }[] = [];
  444. Object.assign(store, {
  445. async commitMessageBundle(bundle: (typeof bundles)[number]) {
  446. bundles.push(structuredClone(bundle));
  447. for (const message of bundle.messages) {
  448. store.savedMessages.push(message.info);
  449. store.savedParts.push(...message.parts);
  450. }
  451. },
  452. });
  453. let releaseFirst!: () => void;
  454. const firstHeld = new Promise<void>((resolve) => {
  455. releaseFirst = resolve;
  456. });
  457. respond.mockImplementationOnce(async () => {
  458. await firstHeld;
  459. return result;
  460. });
  461. runtime = createNotifiedRuntime(mcs);
  462. await runtime.ensureSessionPersistedForExternalActivity("initial session");
  463. const enqueue = (text: string) =>
  464. (runtime as any).enqueueBackgroundTaskNotification({
  465. text,
  466. traceContext: createRootTraceContext({ sessionId }),
  467. });
  468. const stall = formatWorkflowStallNotification({
  469. runLabel: "wf",
  470. runId: "run_1",
  471. sinceMs: 600000,
  472. });
  473. enqueue("<task-notification><task-id>first</task-id></task-notification>");
  474. await waitForRequests(1);
  475. // 第一条通知的请求进行中到达的两条,在下一次空闲时成为同一批。
  476. enqueue("<task-notification><task-id>bash-1</task-id></task-notification>");
  477. enqueue(stall);
  478. releaseFirst();
  479. await waitForRequests(2);
  480. await vi.waitFor(() => expect(runtime.getActiveTurnInfo()).toBeUndefined());
  481. const batchMessage = (request: ModelRequest) =>
  482. request.messages.find(
  483. (message) =>
  484. message.role === "user" &&
  485. Array.isArray(message.content) &&
  486. JSON.stringify(message.content).includes("bash-1"),
  487. );
  488. const live = batchMessage(requests[1]!)!;
  489. const blocks = live.content as { type: string; text: string }[];
  490. expect(blocks.map((block) => block.type)).toEqual(["text", "text"]);
  491. expect(blocks[0]!.text).toMatch(
  492. /^<system-reminder>\n\[SYSTEM NOTIFICATION - NOT USER INPUT\]/u,
  493. );
  494. expect(blocks[0]!.text).toContain("bash-1");
  495. expect(blocks[0]!.text).not.toContain("workflow-stall");
  496. expect(blocks[0]!.text.endsWith("</system-reminder>\n")).toBe(true);
  497. expect(blocks[1]!.text).toContain("<workflow-stall>");
  498. expect(blocks[1]!.text.endsWith("</system-reminder>")).toBe(true);
  499. // 一个事务写入一条消息、两个 part。
  500. const batchBundles = bundles.filter((bundle) =>
  501. bundle.messages.some((message) => message.info.source === "background_task"),
  502. );
  503. expect(batchBundles.map((bundle) => bundle.messages.map((m) => m.parts.length))).toEqual([
  504. [2],
  505. ]);
  506. const coldStore = createRecordingMessageStore();
  507. await coldStore.createSession(await store.getSession(sessionId));
  508. coldStore.savedMessages.push(...structuredClone(store.savedMessages));
  509. coldStore.savedParts.push(...structuredClone(store.savedParts));
  510. const cold = createRuntime(
  511. {
  512. now,
  513. skillPort,
  514. contextSourcePort: instructionsPort(),
  515. sessionStore: coldStore as never,
  516. },
  517. config,
  518. { mcs },
  519. );
  520. await cold.resumeFromStore();
  521. await cold.executeTurn("after resume");
  522. expect(batchMessage(requests.at(-1)!)?.content).toEqual(live.content);
  523. },
  524. );
  525. it("collects the skipped context after a tool result in the same turn", async () => {
  526. const registry = createToolRegistry();
  527. registry.register({
  528. inputSchema: {},
  529. metadata: {
  530. name: "Probe",
  531. concurrentSafe: true,
  532. destructive: false,
  533. needsApproval: false,
  534. readOnly: true,
  535. riskLevel: "low",
  536. sideEffectScope: "none",
  537. },
  538. handler: async () => "probed",
  539. });
  540. runtime = createNotifiedRuntime(false, { toolRegistry: registry });
  541. respond.mockResolvedValueOnce({
  542. ...result,
  543. text: "",
  544. finishReason: "tool-calls",
  545. toolCalls: [{ id: "probe", name: "Probe", input: {} }],
  546. });
  547. await runtime.ensureSessionPersistedForExternalActivity("initial session");
  548. startTurn.task_notification();
  549. await waitForRequests(2);
  550. const texts = requests[1]!.messages.map((message) => JSON.stringify(message.content));
  551. const notificationIndex = texts.findIndex((text) => text.includes(marker));
  552. const toolIndex = requests[1]!.messages.findIndex((message) => message.role === "tool");
  553. const environmentIndex = texts.findIndex((text) => text.includes("# Environment"));
  554. expect(notificationIndex).toBeLessThan(toolIndex);
  555. expect(environmentIndex).toBeGreaterThan(toolIndex);
  556. });
  557. it("keeps the plan-mode exit reminder pending for the next collected request", async () => {
  558. runtime = createNotifiedRuntime(false);
  559. (runtime as unknown as AgentRuntimeInternal).needsPlanModeExitReminder = true;
  560. await runtime.ensureSessionPersistedForExternalActivity("initial session");
  561. startTurn.task_notification();
  562. await waitForRequests(1);
  563. await vi.waitFor(() => expect(runtime.getActiveTurnInfo()).toBeUndefined());
  564. const planExit = () =>
  565. entries().filter((entry) => entry.metadata?.source === "plan_mode_exit");
  566. expect(planExit()).toHaveLength(0);
  567. expect((runtime as unknown as AgentRuntimeInternal).needsPlanModeExitReminder).toBe(true);
  568. await runtime.executeTurn("next");
  569. expect((runtime as unknown as AgentRuntimeInternal).needsPlanModeExitReminder).toBe(false);
  570. expect(planExit()).toHaveLength(1);
  571. });
  572. });
  573. it("announces output style instructions after the model once per change and resets when cleared", async () => {
  574. runtime = createRuntime(
  575. { now, skillPort },
  576. { ...config, outputStyle: { name: "Learning", prompt: "Explain tradeoffs.\n" } },
  577. );
  578. await runtime.executeTurn("first");
  579. await runtime.executeTurn("second");
  580. runtime.updateConfig({ outputStyle: { name: "Learning", prompt: "Explain briefly." } });
  581. await runtime.executeTurn("third");
  582. runtime.updateConfig({ outputStyle: undefined });
  583. await runtime.executeTurn("fourth");
  584. await runtime.executeTurn("fifth");
  585. const attachments = entries().filter((entry) => entry.kind === "attachment");
  586. expect(
  587. attachments
  588. .filter((entry) => entry.metadata.source === "output_style_instructions")
  589. .map((entry) => entry.content),
  590. ).toEqual([
  591. "# Output Style: Learning\nExplain tradeoffs.",
  592. "# Output Style: Learning\nExplain briefly.",
  593. "The output style was reset to the default. Respond in your usual style.",
  594. ]);
  595. // 输入附件顺序:environment → model → output style 指令。
  596. const order = attachments.map((entry) => entry.metadata.source);
  597. expect(order.indexOf("output_style_instructions")).toBe(order.indexOf("model") + 1);
  598. // system 不再携带 output style 指令。
  599. expect(
  600. JSON.stringify(requests[0]!.messages.slice(0, 3).map((message) => message.content)),
  601. ).not.toContain("# Output Style");
  602. });
  603. it("restates the latest output style after compact unless the kept tail has one or it was reset", () => {
  604. runtime = createRuntime({ now, skillPort }, config);
  605. const internal = runtime as unknown as AgentRuntimeInternal;
  606. // output style 的重述不受 env_info 门控。
  607. internal.latestContextBuildResult = { sections: [] } as never;
  608. const style = systemReminderAttachmentEntry(
  609. "output_style_instructions",
  610. "# Output Style: Learning\nExplain tradeoffs.",
  611. );
  612. const reset = systemReminderAttachmentEntry(
  613. "output_style_instructions",
  614. "The output style was reset to the default. Respond in your usual style.",
  615. );
  616. expect(restateContextAfterCompact(internal, [style], []).map((entry) => entry.content)).toEqual(
  617. [style.content],
  618. );
  619. expect(restateContextAfterCompact(internal, [style], [style])).toEqual([]);
  620. expect(restateContextAfterCompact(internal, [style, reset], [])).toEqual([]);
  621. });
  622. it("derives the plan-mode exit reminder from history after resume", async () => {
  623. runtime = createRuntime({ now, skillPort, contextSourcePort: instructionsPort() }, config);
  624. const internal = runtime as unknown as AgentRuntimeInternal;
  625. await runtime.executeTurn("planned");
  626. internal.messageHistory.addEntries([
  627. systemReminderAttachmentEntry("runtime_mode", "Plan mode is active."),
  628. { message: { role: "assistant", content: "plan ready" } },
  629. ]);
  630. // 冷恢复后内存标记为 false;按历史中最近的 plan 提醒判断。
  631. internal.needsPlanModeExitReminder = false;
  632. await runtime.executeTurn("build it");
  633. await runtime.executeTurn("again");
  634. const planExit = entries().filter((entry) => entry.metadata?.source === "plan_mode_exit");
  635. expect(planExit).toHaveLength(1);
  636. });
  637. it.each([undefined, CompactTrigger.Manual, CompactTrigger.Reactive])(
  638. "restores context without duplicate announcements after compact=%s",
  639. async (trigger) => {
  640. runtime = createRuntime({ now, skillPort, contextSourcePort: instructionsPort() }, config);
  641. await runtime.executeTurn("first");
  642. const initialContext = contextEntries(runtime);
  643. expect(initialContext.map((entry) => entry.metadata?.source)).toEqual([...sources]);
  644. await runtime.executeTurn("second");
  645. expect(contextEntries(runtime)).toEqual(initialContext);
  646. const announcements = store.savedMessages.filter(isAnnouncementRecord);
  647. expect(announcements).toHaveLength(6);
  648. for (const announcement of announcements) {
  649. // 顶层 source 不写新值:旧版本 App 按封闭列表校验,会拒绝整个会话。
  650. expect(announcement.source).toBeUndefined();
  651. expect(announcement.semantics?.source).toBe(runtimeSourceOf(announcement));
  652. expect(announcement).toMatchObject({
  653. semantics: {
  654. uiVisibility: "hidden",
  655. transcriptVisibility: "hidden",
  656. providerVisibility: "visible",
  657. },
  658. });
  659. }
  660. if (trigger) {
  661. const compacted = await compact(runtime, trigger);
  662. expect(compacted.outcome).toBe("compacted");
  663. await runtime.executeTurn("continue after compact");
  664. // 每个来源仍只宣告一次;顺序按 compact 后布局(见 "lays out the post-compact context")。
  665. const bySource = (items: ReturnType<typeof contextEntries>) =>
  666. [...items].sort((a, b) => a.metadata.source.localeCompare(b.metadata.source));
  667. expect(bySource(contextEntries(runtime))).toEqual(bySource(initialContext));
  668. }
  669. const liveContext = contextEntries(runtime);
  670. const { cold, coldStore } = await coldRuntimeWith(skillPort, {
  671. ...config,
  672. envInfo: { ...config.envInfo!, gitBranch: "new-probe-must-not-replace-history" },
  673. });
  674. const before = coldStore.savedMessages.filter(isAnnouncementRecord).length;
  675. await cold.executeTurn("resumed");
  676. expect(contextEntries(cold)).toEqual(liveContext);
  677. expect(coldStore.savedMessages.filter(isAnnouncementRecord)).toHaveLength(before);
  678. },
  679. );
  680. const withSkills = (
  681. skills: (base: Awaited<ReturnType<SkillPort["discoverSkills"]>>["skills"]) => typeof base,
  682. ): SkillPort => ({
  683. ...skillPort,
  684. async discoverSkills(request, options) {
  685. const outcome = await skillPort.discoverSkills(request, options);
  686. const next = skills(outcome.skills);
  687. return { ...outcome, skills: next, totalDiscovered: next.length };
  688. },
  689. });
  690. const withReviewSkill = withSkills((base) => [
  691. ...base,
  692. {
  693. ...base[0]!,
  694. name: "review",
  695. description: "review things",
  696. path: "/workspace/.agents/skills/review/SKILL.md",
  697. directory: "/workspace/.agents/skills/review",
  698. },
  699. ]);
  700. const skillsListingRecordTexts = (value: ReturnType<typeof createRecordingMessageStore>) =>
  701. value.savedParts
  702. .filter((part) => part.metadata?.runtimeMessage?.source === "skills_listing")
  703. .map((part) => String((part as { text?: string }).text));
  704. const historyIndexOfListing = (value: ReturnType<typeof createTestAgentRuntime>) =>
  705. (value as unknown as AgentRuntimeInternal).messageHistory
  706. .toRuntimeEntries()
  707. .findIndex(
  708. (entry) => entry.kind === "attachment" && entry.metadata.source === "skills_listing",
  709. );
  710. it("updates the restored skill listing in place when a resumed session finds a changed catalog", async () => {
  711. runtime = createRuntime({ now, skillPort, contextSourcePort: instructionsPort() }, config);
  712. await runtime.executeTurn("first");
  713. const liveIndex = historyIndexOfListing(runtime);
  714. const { cold, coldStore } = await coldRuntimeWith(withReviewSkill);
  715. const storedTexts = skillsListingRecordTexts(coldStore);
  716. await cold.executeTurn("resumed");
  717. await cold.executeTurn("again");
  718. // 目录变化不插入新公告:原位置上的那一条换成当前目录,之后不再变化。
  719. const listings = contextEntries(cold).filter(
  720. (entry) => entry.metadata.source === "skills_listing",
  721. );
  722. expect(listings).toHaveLength(1);
  723. expect(listings[0]!.content).toContain("- review: review things");
  724. expect(listings[0]!.content).toContain("- search: search things");
  725. expect(historyIndexOfListing(cold)).toBe(liveIndex);
  726. const lastRequest = JSON.stringify(requests.at(-1)?.messages);
  727. expect(lastRequest.split("- review: review things")).toHaveLength(2);
  728. // 只改内存:库里的记录不变,也没有新增 skill 列表记录。
  729. expect(skillsListingRecordTexts(coldStore)).toEqual(storedTexts);
  730. // 先确认确实存过一条,否则空数组上的 every 恒为真。
  731. expect(storedTexts).toHaveLength(1);
  732. expect(storedTexts.every((text) => !text.includes("review"))).toBe(true);
  733. });
  734. it("drops the restored skill listing when a resumed session finds no skills", async () => {
  735. runtime = createRuntime({ now, skillPort, contextSourcePort: instructionsPort() }, config);
  736. await runtime.executeTurn("first");
  737. const { cold, coldStore } = await coldRuntimeWith(withSkills(() => []));
  738. const storedTexts = skillsListingRecordTexts(coldStore);
  739. await cold.executeTurn("resumed");
  740. // 目录清空时没有新内容可宣告,旧名单必须从历史里去掉,不能继续发给模型。
  741. expect(contextEntries(cold).some((entry) => entry.metadata.source === "skills_listing")).toBe(
  742. false,
  743. );
  744. expect(JSON.stringify(requests.at(-1)?.messages)).not.toContain(
  745. "The following skills are available",
  746. );
  747. expect(skillsListingRecordTexts(coldStore)).toEqual(storedTexts);
  748. });
  749. it("applies the current catalog again when a rewind reloads history from the store", async () => {
  750. runtime = createRuntime({ now, skillPort, contextSourcePort: instructionsPort() }, config);
  751. await runtime.executeTurn("first");
  752. const { cold, coldStore } = await coldRuntimeWith(withReviewSkill);
  753. await cold.executeTurn("resumed");
  754. await cold.executeTurn("again");
  755. const againPart = coldStore.savedParts.find(
  756. (part) => (part as { text?: string }).text === "again",
  757. );
  758. expect(againPart).toBeDefined();
  759. await cold.rewindConversationToMessage({
  760. events: [],
  761. targetMessageId: againPart!.messageID,
  762. traceContext: createRootTraceContext({ sessionId }),
  763. });
  764. await cold.executeTurn("edited");
  765. // rewind 从库重新加载历史,库里仍是旧名单;加载后同样按当前目录原位更新。
  766. const listings = contextEntries(cold).filter(
  767. (entry) => entry.metadata.source === "skills_listing",
  768. );
  769. expect(listings).toHaveLength(1);
  770. expect(listings[0]!.content).toContain("- review: review things");
  771. expect(JSON.stringify(requests.at(-1)?.messages)).toContain("- review: review things");
  772. });
  773. describe("instruction announcements after a history load", () => {
  774. const cliStorageRoot = "/storage/cli";
  775. const memoryConfig: Partial<AgentRuntimeConfig> = {
  776. ...config,
  777. memory: { cliStorageRoot, enabled: true, use: true },
  778. };
  779. const indexPath = join(
  780. resolveProjectMemoryRoot({ cliStorageRoot, workspacePath: "/workspace" }),
  781. "MEMORY.md",
  782. );
  783. const oldIndex = "- [Old policy](old-policy.md) — announced before the restart";
  784. const newIndex = "- [New policy](new-policy.md) — written to disk after the announcement";
  785. const memoryType = "user's auto-memory, persists across conversations";
  786. const projectType = "project instructions, checked into the codebase";
  787. const resumedChange =
  788. "Instruction files were re-read when this session started; these differ from their earlier copies — each replaces its earlier copy, and the instructions preamble above still applies:";
  789. const instructionTexts = (value: ReturnType<typeof createTestAgentRuntime>) =>
  790. contextEntries(value)
  791. .filter((entry) => entry.metadata.source === "context_prefix")
  792. .map((entry) => entry.content);
  793. const instructionRecords = (value: ReturnType<typeof createRecordingMessageStore>) =>
  794. value.savedParts.filter((part) => part.metadata?.runtimeMessage?.source === "context_prefix");
  795. const instructionRecordTexts = (value: ReturnType<typeof createRecordingMessageStore>) =>
  796. instructionRecords(value).map((part) => String((part as { text?: string }).text));
  797. // AGENTS.md 的内容可在测试中修改,端口每次读取时取当前值;unreadable 时端口报读取失败的诊断。
  798. const agentsFile = {
  799. content: "Project rule." as string | undefined,
  800. unreadable: false,
  801. };
  802. beforeEach(() => {
  803. agentsFile.unreadable = false;
  804. });
  805. const agentsPort = (): ContextSourcePort => ({
  806. ...instructionsPort(),
  807. async resolveContextSources() {
  808. const content = agentsFile.content;
  809. if (agentsFile.unreadable) {
  810. return {
  811. workingDirectory: "/workspace",
  812. envInfo: config.envInfo!,
  813. diagnostics: [
  814. {
  815. code: "user_instructions_read_failed",
  816. message: "EACCES: permission denied",
  817. path: "/workspace/AGENTS.md",
  818. },
  819. ],
  820. };
  821. }
  822. return {
  823. workingDirectory: "/workspace",
  824. envInfo: config.envInfo!,
  825. ...(content === undefined
  826. ? {}
  827. : {
  828. userInstructions: {
  829. filePath: "/workspace/AGENTS.md",
  830. fileName: "AGENTS.md",
  831. content,
  832. bytesRead: content.length,
  833. sizeBytes: content.length,
  834. truncated: false,
  835. },
  836. }),
  837. diagnostics: [],
  838. };
  839. },
  840. });
  841. const announceOldIndexThenChangeDisk = async () => {
  842. agentsFile.content = "Project rule.";
  843. const files = new MemoryFileSystem({ [indexPath]: oldIndex });
  844. runtime = createRuntime(
  845. { now, skillPort, contextSourcePort: agentsPort(), fileSystemPort: files },
  846. memoryConfig,
  847. );
  848. await runtime.executeTurn("first");
  849. expect(instructionTexts(runtime)).toEqual([expect.stringContaining(oldIndex)]);
  850. files.files[indexPath] = newIndex;
  851. return files;
  852. };
  853. const resumeWith = (
  854. files: MemoryFileSystem,
  855. coldConfig = memoryConfig,
  856. coldDeps: Partial<AgentRuntimeDeps> = {},
  857. ) =>
  858. coldRuntimeWith(skillPort, coldConfig, {
  859. fileSystemPort: files,
  860. contextSourcePort: agentsPort(),
  861. ...coldDeps,
  862. });
  863. // 权限错误:文件在,但读不出来。
  864. const denyReads = (files: MemoryFileSystem, path: string) => {
  865. const read = files.readTextFile.bind(files);
  866. files.readTextFile = async (request) => {
  867. if (request.path !== path) return read(request);
  868. throw createFileSystemError({
  869. code: "permission_denied",
  870. path,
  871. message: `Permission denied for path: ${path}`,
  872. });
  873. };
  874. return files;
  875. };
  876. const warningLogger = () => {
  877. const warnings: unknown[] = [];
  878. const logger = {
  879. debug() {},
  880. info() {},
  881. warn: (_message: string, context?: unknown) => warnings.push(context),
  882. error() {},
  883. child: () => logger,
  884. };
  885. return { logger: logger as never, warnings };
  886. };
  887. it("keeps the sent announcement and appends a delta for the Memory index read on resume", async () => {
  888. const files = await announceOldIndexThenChangeDisk();
  889. const { cold, coldStore } = await resumeWith(files);
  890. const [firstRecord] = instructionRecordTexts(coldStore);
  891. await cold.executeTurn("resumed");
  892. // 修复原因:恢复时原位改写已发的公告,前缀字节改变;现在原公告不动,变化追加在末尾。
  893. const texts = instructionTexts(cold);
  894. expect(texts).toEqual([
  895. firstRecord,
  896. `${resumedChange}\n\nContents of ${indexPath} (${memoryType}):\n\n${newIndex}`,
  897. ]);
  898. expect(firstRecord).toContain(oldIndex);
  899. const lastRequest = JSON.stringify(requests.at(-1)?.messages);
  900. expect(lastRequest).toContain(oldIndex);
  901. expect(lastRequest.split(newIndex)).toHaveLength(2);
  902. expect(lastRequest).not.toContain("runtimeMessage");
  903. // 增量落库,带上只给 runtime 用的文件记录。
  904. const records = instructionRecords(coldStore);
  905. expect(records).toHaveLength(2);
  906. expect(records[1]!.metadata?.runtimeMessage?.instructions).toEqual({
  907. files: [{ path: indexPath, type: memoryType, hash: expect.any(String) }],
  908. reason: "session_start",
  909. });
  910. // 读文件状态记录磁盘上的新索引,也就是模型最近被告知的内容;Write 按它检查。
  911. const readState = (cold as unknown as AgentRuntimeInternal).readFileState.get(
  912. createReadFileStatePathKey(indexPath),
  913. );
  914. expect(readState?.content).toBe(newIndex);
  915. Object.assign(coldStore, { getProjectPermission: async () => null });
  916. const write = await cold.getToolExecutor().execute({
  917. id: createToolCallId("write-memory-index-after-resume"),
  918. input: { content: `${newIndex}\n- [Added](added.md) — added`, file_path: indexPath },
  919. name: "Write",
  920. });
  921. expect(write.success).toBe(true);
  922. // 之后的请求和下一次冷恢复都不再重复宣告。
  923. await cold.executeTurn("again");
  924. expect(instructionTexts(cold)).toHaveLength(2);
  925. files.files[indexPath] = newIndex;
  926. store = coldStore;
  927. const { cold: second } = await resumeWith(files);
  928. await second.executeTurn("second resume");
  929. expect(instructionTexts(second)).toEqual(texts);
  930. });
  931. it("appends nothing when the files are unchanged on resume", async () => {
  932. const files = await announceOldIndexThenChangeDisk();
  933. files.files[indexPath] = oldIndex;
  934. const { cold, coldStore } = await resumeWith(files);
  935. const stored = instructionRecordTexts(coldStore);
  936. await cold.executeTurn("resumed");
  937. expect(instructionTexts(cold)).toEqual(stored);
  938. expect(instructionRecordTexts(coldStore)).toEqual(stored);
  939. });
  940. it("announces only the changed instruction file", async () => {
  941. const files = await announceOldIndexThenChangeDisk();
  942. files.files[indexPath] = oldIndex;
  943. agentsFile.content = "Updated project rule.";
  944. const { cold } = await resumeWith(files);
  945. await cold.executeTurn("resumed");
  946. expect(instructionTexts(cold).at(-1)).toBe(
  947. `${resumedChange}\n\nContents of /workspace/AGENTS.md (${projectType}):\n\nUpdated project rule.`,
  948. );
  949. });
  950. it("compares against a legacy record without file metadata", async () => {
  951. const files = await announceOldIndexThenChangeDisk();
  952. // 升级前写入的完整公告没有 metadata:按标题行拆出文件,没变的 AGENTS.md 不再宣告。
  953. for (const part of instructionRecords(store)) {
  954. delete (part.metadata!.runtimeMessage as Record<string, unknown>).instructions;
  955. }
  956. const { cold } = await resumeWith(files);
  957. await cold.executeTurn("resumed");
  958. expect(instructionTexts(cold).at(-1)).toBe(
  959. `${resumedChange}\n\nContents of ${indexPath} (${memoryType}):\n\n${newIndex}`,
  960. );
  961. });
  962. it("re-announces a delta after a rewind removes it from history", async () => {
  963. const files = await announceOldIndexThenChangeDisk();
  964. const { cold, coldStore } = await resumeWith(files);
  965. await cold.executeTurn("resumed");
  966. const resumedPart = coldStore.savedParts.find(
  967. (part) => (part as { text?: string }).text === "resumed",
  968. );
  969. expect(resumedPart).toBeDefined();
  970. await cold.rewindConversationToMessage({
  971. events: [],
  972. targetMessageId: resumedPart!.messageID,
  973. traceContext: createRootTraceContext({ sessionId }),
  974. });
  975. await cold.executeTurn("edited");
  976. // 已公告的文件只从剩余历史推出:增量随回退离开历史,下一次请求重新追加一次。
  977. const texts = instructionTexts(cold);
  978. expect(texts).toHaveLength(2);
  979. expect(texts[0]).toContain(oldIndex);
  980. expect(texts[1]).toContain(newIndex);
  981. });
  982. it("announces files that are no longer present", async () => {
  983. await announceOldIndexThenChangeDisk();
  984. agentsFile.content = undefined;
  985. const { cold } = await resumeWith(new MemoryFileSystem({}), config);
  986. await cold.executeTurn("resumed");
  987. // 当前没有指令文件和 Memory 索引:原公告不动,追加一条撤回说明。
  988. const texts = instructionTexts(cold);
  989. expect(texts).toHaveLength(2);
  990. expect(texts[0]).toContain(oldIndex);
  991. expect(texts[1]).toBe(
  992. [
  993. "Instruction files were re-read when this session started.",
  994. "Instructions no longer present: /workspace/AGENTS.md",
  995. `Instructions no longer present: ${indexPath}`,
  996. ].join("\n\n"),
  997. );
  998. });
  999. it("announces a file that the earlier announcement did not have", async () => {
  1000. agentsFile.content = undefined;
  1001. const files = new MemoryFileSystem({ [indexPath]: oldIndex });
  1002. runtime = createRuntime(
  1003. { now, skillPort, contextSourcePort: agentsPort(), fileSystemPort: files },
  1004. memoryConfig,
  1005. );
  1006. await runtime.executeTurn("first");
  1007. agentsFile.content = "Project rule.";
  1008. const { cold } = await resumeWith(files);
  1009. await cold.executeTurn("resumed");
  1010. expect(instructionTexts(cold).at(-1)).toBe(
  1011. `${resumedChange}\n\nContents of /workspace/AGENTS.md (${projectType}):\n\nProject rule.`,
  1012. );
  1013. });
  1014. it("puts changed and removed files in one delta", async () => {
  1015. await announceOldIndexThenChangeDisk();
  1016. agentsFile.content = "Updated project rule.";
  1017. const { cold } = await resumeWith(new MemoryFileSystem({}));
  1018. await cold.executeTurn("resumed");
  1019. expect(instructionTexts(cold).at(-1)).toBe(
  1020. `${resumedChange}\n\nContents of /workspace/AGENTS.md (${projectType}):\n\nUpdated project rule.\n\nInstructions no longer present: ${indexPath}`,
  1021. );
  1022. });
  1023. it("compares a later change against the latest delta", async () => {
  1024. const files = await announceOldIndexThenChangeDisk();
  1025. const { cold, coldStore } = await resumeWith(files);
  1026. await cold.executeTurn("resumed");
  1027. // 第二次冷恢复:基准是完整公告加上一条增量,只宣告相对增量的新变化。
  1028. const thirdIndex = "- [Third policy](third-policy.md) — written after the first delta";
  1029. files.files[indexPath] = thirdIndex;
  1030. store = coldStore;
  1031. const { cold: second } = await resumeWith(files);
  1032. await second.executeTurn("second resume");
  1033. const texts = instructionTexts(second);
  1034. expect(texts).toHaveLength(3);
  1035. expect(texts[2]).toBe(
  1036. `${resumedChange}\n\nContents of ${indexPath} (${memoryType}):\n\n${thirdIndex}`,
  1037. );
  1038. });
  1039. it("announces a file again after a delta removed it", async () => {
  1040. await announceOldIndexThenChangeDisk();
  1041. agentsFile.content = undefined;
  1042. const { cold, coldStore } = await resumeWith(new MemoryFileSystem({}), config);
  1043. await cold.executeTurn("resumed");
  1044. agentsFile.content = "Project rule.";
  1045. store = coldStore;
  1046. const { cold: second } = await resumeWith(new MemoryFileSystem({}), config);
  1047. await second.executeTurn("second resume");
  1048. expect(instructionTexts(second).at(-1)).toBe(
  1049. `${resumedChange}\n\nContents of /workspace/AGENTS.md (${projectType}):\n\nProject rule.`,
  1050. );
  1051. });
  1052. // 修复原因:读取出错一律当成文件不存在,权限、占用等临时错误被宣告成 "Instructions no longer present"。
  1053. it("does not announce an unreadable file as removed on resume", async () => {
  1054. const files = await announceOldIndexThenChangeDisk();
  1055. agentsFile.unreadable = true;
  1056. const { logger, warnings } = warningLogger();
  1057. const { cold } = await resumeWith(files, memoryConfig, { logger });
  1058. await cold.executeTurn("resumed");
  1059. // AGENTS.md 读不出来:不算删除,模型保留已宣告的副本;MEMORY.md 照常比较。
  1060. expect(instructionTexts(cold).at(-1)).toBe(
  1061. `${resumedChange}\n\nContents of ${indexPath} (${memoryType}):\n\n${newIndex}`,
  1062. );
  1063. expect(warnings).toContainEqual(
  1064. expect.objectContaining({
  1065. event: "context.instructions.read_failed",
  1066. path: "/workspace/AGENTS.md",
  1067. }),
  1068. );
  1069. });
  1070. it("does not announce an unreadable Memory index as removed on resume", async () => {
  1071. const files = await announceOldIndexThenChangeDisk();
  1072. const { logger, warnings } = warningLogger();
  1073. const { cold } = await resumeWith(denyReads(files, indexPath), memoryConfig, { logger });
  1074. await cold.executeTurn("resumed");
  1075. expect(instructionTexts(cold)).toHaveLength(1);
  1076. expect(warnings).toContainEqual(
  1077. expect.objectContaining({ event: "context.instructions.read_failed", path: indexPath }),
  1078. );
  1079. });
  1080. it("drops the compaction re-read when a held file cannot be read", async () => {
  1081. const files = await announceOldIndexThenChangeDisk();
  1082. agentsFile.unreadable = true;
  1083. const compacted = await compact(runtime, CompactTrigger.Manual);
  1084. expect(compacted.outcome).toBe("compacted");
  1085. await runtime.executeTurn("after compact");
  1086. // AGENTS.md 是 runtime 持有的文件:整次重读作废,沿用原内容,MEMORY.md 的变化留到下一次读取。
  1087. const texts = instructionTexts(runtime);
  1088. expect(texts).toHaveLength(1);
  1089. expect(texts[0]).toContain("Project rule.");
  1090. expect(texts[0]).toContain(oldIndex);
  1091. expect((runtime as unknown as AgentRuntimeInternal).instructionRefreshReason).toBeUndefined();
  1092. expect(texts[0]).not.toContain(newIndex);
  1093. expect(files.readRequests.filter((request) => request.path === indexPath)).toHaveLength(2);
  1094. });
  1095. it("drops the compaction re-read when the held Memory index cannot be read", async () => {
  1096. const files = await announceOldIndexThenChangeDisk();
  1097. denyReads(files, indexPath);
  1098. agentsFile.content = "Rule changed during the session.";
  1099. const compacted = await compact(runtime, CompactTrigger.Manual);
  1100. expect(compacted.outcome).toBe("compacted");
  1101. await runtime.executeTurn("after compact");
  1102. const texts = instructionTexts(runtime);
  1103. expect(texts).toHaveLength(1);
  1104. expect(texts[0]).toContain("Project rule.");
  1105. expect(texts[0]).toContain(oldIndex);
  1106. });
  1107. it("adopts the compaction re-read when the unreadable file is not held", async () => {
  1108. agentsFile.unreadable = true;
  1109. const files = new MemoryFileSystem({ [indexPath]: oldIndex });
  1110. runtime = createRuntime(
  1111. { now, skillPort, contextSourcePort: agentsPort(), fileSystemPort: files },
  1112. memoryConfig,
  1113. );
  1114. await runtime.executeTurn("first");
  1115. files.files[indexPath] = newIndex;
  1116. const compacted = await compact(runtime, CompactTrigger.Manual);
  1117. expect(compacted.outcome).toBe("compacted");
  1118. await runtime.executeTurn("after compact");
  1119. // 一直读不出来的 AGENTS.md 不在 runtime 持有的内容里,不阻止重读;MEMORY.md 的变化照常采用。
  1120. const texts = instructionTexts(runtime);
  1121. expect(texts).toHaveLength(1);
  1122. expect(texts[0]).toContain(newIndex);
  1123. expect(texts[0]).not.toContain("AGENTS.md");
  1124. expect((runtime as unknown as AgentRuntimeInternal).instructionRefreshReason).toBe(
  1125. "compaction",
  1126. );
  1127. });
  1128. it("keeps the earlier instructions when the compaction re-read fails", async () => {
  1129. const warnings: unknown[] = [];
  1130. const logger = {
  1131. debug() {},
  1132. info() {},
  1133. warn: (_message: string, context?: unknown) => warnings.push(context),
  1134. error() {},
  1135. child: () => logger,
  1136. };
  1137. agentsFile.content = "Project rule.";
  1138. let failReads = false;
  1139. const port = agentsPort();
  1140. runtime = createRuntime(
  1141. {
  1142. now,
  1143. skillPort,
  1144. logger: logger as never,
  1145. contextSourcePort: {
  1146. ...port,
  1147. async resolveContextSources(input, options) {
  1148. if (failReads) throw new Error("disk busy");
  1149. return port.resolveContextSources(input, options);
  1150. },
  1151. },
  1152. },
  1153. config,
  1154. );
  1155. await runtime.executeTurn("first");
  1156. failReads = true;
  1157. agentsFile.content = "Rule changed during the session.";
  1158. const compacted = await compact(runtime, CompactTrigger.Manual);
  1159. expect(compacted.outcome).toBe("compacted");
  1160. expect(warnings).toContainEqual(
  1161. expect.objectContaining({
  1162. event: "context.instructions.reread_failed",
  1163. error: "disk busy",
  1164. }),
  1165. );
  1166. await runtime.executeTurn("after compact");
  1167. const texts = instructionTexts(runtime);
  1168. expect(texts).toHaveLength(1);
  1169. expect(texts[0]).toContain("Project rule.");
  1170. expect(texts[0]).not.toContain("Rule changed during the session.");
  1171. // 没有重读结果的 compaction 不改指令增量的 reason。
  1172. expect((runtime as unknown as AgentRuntimeInternal).instructionRefreshReason).toBeUndefined();
  1173. });
  1174. it("cancels the compaction when it is aborted during the instruction re-read", async () => {
  1175. agentsFile.content = "Project rule.";
  1176. const controller = new AbortController();
  1177. let abortOnRead = false;
  1178. const port = agentsPort();
  1179. runtime = createRuntime(
  1180. {
  1181. now,
  1182. skillPort,
  1183. contextSourcePort: {
  1184. ...port,
  1185. async resolveContextSources(input, options) {
  1186. if (abortOnRead) {
  1187. controller.abort();
  1188. throw new Error("read aborted");
  1189. }
  1190. return port.resolveContextSources(input, options);
  1191. },
  1192. },
  1193. },
  1194. config,
  1195. );
  1196. await runtime.executeTurn("first");
  1197. const before = entries();
  1198. abortOnRead = true;
  1199. agentsFile.content = "Rule changed during the session.";
  1200. await expect(
  1201. (runtime as unknown as AgentRuntimeInternal).compactActiveConversation(
  1202. undefined,
  1203. createRootTraceContext({ sessionId }),
  1204. [],
  1205. { abortSignal: controller.signal, trigger: CompactTrigger.Manual },
  1206. ),
  1207. ).rejects.toThrow();
  1208. // 取消时不采用重读的内容,历史保持 compact 之前的样子。
  1209. expect(entries()).toEqual(before);
  1210. expect(
  1211. (
  1212. runtime as unknown as AgentRuntimeInternal
  1213. ).latestContextBuildResult?.metaUserAttachments.find(
  1214. (item) => item.source === "context_prefix",
  1215. )?.content,
  1216. ).toContain("Project rule.");
  1217. });
  1218. it("re-reads instruction files at the end of a compaction", async () => {
  1219. const files = await announceOldIndexThenChangeDisk();
  1220. agentsFile.content = "Rule changed during the session.";
  1221. const compacted = await compact(runtime, CompactTrigger.Manual);
  1222. expect(compacted.outcome).toBe("compacted");
  1223. // 修复原因:compaction 原来沿用 runtime 启动时的内容;现在收尾时重读,新内容进入新窗口。
  1224. const readState = (runtime as unknown as AgentRuntimeInternal).readFileState.get(
  1225. createReadFileStatePathKey(indexPath),
  1226. );
  1227. expect(readState?.content).toBe(newIndex);
  1228. await runtime.executeTurn("after compact");
  1229. const texts = instructionTexts(runtime);
  1230. expect(texts).toHaveLength(1);
  1231. expect(texts[0]).toContain("Rule changed during the session.");
  1232. expect(texts[0]).toContain(newIndex);
  1233. expect(texts[0]).not.toContain(oldIndex);
  1234. expect(files.readRequests.filter((request) => request.path === indexPath)).toHaveLength(2);
  1235. });
  1236. it("places only a full block before the summary, and only when the kept tail has no full block", () => {
  1237. runtime = createRuntime({ now, skillPort, contextSourcePort: instructionsPort() }, config);
  1238. const internal = runtime as unknown as AgentRuntimeInternal;
  1239. const built = (content: string, body: string) =>
  1240. ({
  1241. sections: [],
  1242. metaUserAttachments: [
  1243. {
  1244. source: "context_prefix",
  1245. content,
  1246. files: [{ path: "/workspace/AGENTS.md", type: projectType, body }],
  1247. },
  1248. ],
  1249. }) as never;
  1250. internal.latestContextBuildResult = built("held full", "Project rule.");
  1251. const reread = built("re-read full", "Rule changed during the session.");
  1252. const oldFull = systemReminderAttachmentEntry(
  1253. "context_prefix",
  1254. `Preamble\n\nContents of /workspace/AGENTS.md (${projectType}):\n\nOld rule.`,
  1255. );
  1256. const done = { message: { role: "assistant" as const, content: "Done." } };
  1257. const leadingInstructions = (
  1258. kept: Parameters<typeof buildCompactLeadingAnnouncements>[1],
  1259. source?: Parameters<typeof buildCompactLeadingAnnouncements>[3],
  1260. ) =>
  1261. buildCompactLeadingAnnouncements(internal, kept, undefined, source)
  1262. .filter((entry) => entry.metadata.source === "context_prefix")
  1263. .map((entry) => entry.content);
  1264. // 保留段有完整块:summary 之前不放,内容变化由下一次请求追加增量。
  1265. // 修复原因:原来在 summary 之前放增量,增量排在保留段的旧公告之前,下一次请求又追加一次。
  1266. expect(leadingInstructions([oldFull, done], reread)).toEqual([]);
  1267. // 保留段只有增量:增量不算基准,放重读内容的完整块。
  1268. const keptDelta = {
  1269. ...systemReminderAttachmentEntry("context_prefix", "delta"),
  1270. metadata: {
  1271. source: "context_prefix" as const,
  1272. instructions: {
  1273. files: [{ path: "/workspace/AGENTS.md", type: projectType, hash: "h" }],
  1274. reason: "session_start" as const,
  1275. },
  1276. },
  1277. };
  1278. expect(leadingInstructions([keptDelta, done], reread)).toEqual(["re-read full"]);
  1279. // 保留段没有指令公告:放完整块;没有重读结果时用 runtime 持有的内容。
  1280. expect(leadingInstructions([done], reread)).toEqual(["re-read full"]);
  1281. expect(leadingInstructions([done])).toEqual(["held full"]);
  1282. });
  1283. it("uses the reason held by the runtime for request deltas", () => {
  1284. runtime = createRuntime({ now, skillPort, contextSourcePort: instructionsPort() }, config);
  1285. const internal = runtime as unknown as AgentRuntimeInternal;
  1286. internal.latestContextBuildResult = {
  1287. sections: [],
  1288. metaUserAttachments: [
  1289. {
  1290. source: "context_prefix",
  1291. content: "full",
  1292. files: [createInstructionFile("/workspace/AGENTS.md", projectType, "Project rule.")],
  1293. },
  1294. ],
  1295. } as never;
  1296. const history = [
  1297. systemReminderAttachmentEntry(
  1298. "context_prefix",
  1299. `Preamble\n\nContents of /workspace/AGENTS.md (${projectType}):\n\nOld rule.`,
  1300. ),
  1301. ];
  1302. const delta = () =>
  1303. buildRequestAnnouncements(internal, history).find(
  1304. (entry) => entry.metadata.source === "context_prefix",
  1305. );
  1306. expect(delta()?.content).toBe(
  1307. `${resumedChange}\n\nContents of /workspace/AGENTS.md (${projectType}):\n\nProject rule.`,
  1308. );
  1309. internal.instructionRefreshReason = "compaction";
  1310. expect(delta()?.content).toBe(
  1311. `Instruction files were re-read after the conversation was compacted; these differ from their earlier copies — each replaces its earlier copy, and the instructions preamble above still applies:\n\nContents of /workspace/AGENTS.md (${projectType}):\n\nProject rule.`,
  1312. );
  1313. expect(delta()?.metadata).toMatchObject({ instructions: { reason: "compaction" } });
  1314. // 正文相同、类型变了(同一路径从用户级变为项目级)也算变化。
  1315. const retyped = [
  1316. systemReminderAttachmentEntry(
  1317. "context_prefix",
  1318. `Preamble\n\nContents of /workspace/AGENTS.md (user's private global instructions for all projects):\n\nProject rule.`,
  1319. ),
  1320. ];
  1321. expect(
  1322. buildRequestAnnouncements(internal, retyped).filter(
  1323. (entry) => entry.metadata.source === "context_prefix",
  1324. ),
  1325. ).toHaveLength(1);
  1326. });
  1327. // 优化原因:持有的文件只在读取时变化,原来每次请求前都对每个文件重新算 sha256。
  1328. it("hashes the held files once when they are built, and compares stored hashes on requests", () => {
  1329. const rule = "\n\nProject rule.\n\n";
  1330. const built = createContextBuilder({
  1331. workingDirectory: "/workspace",
  1332. envInfo: config.envInfo!,
  1333. userInstructions: {
  1334. filePath: "/workspace/AGENTS.md",
  1335. fileName: "AGENTS.md",
  1336. content: rule,
  1337. bytesRead: rule.length,
  1338. sizeBytes: rule.length,
  1339. truncated: false,
  1340. },
  1341. }).build();
  1342. const [file] =
  1343. built.metaUserAttachments.find((item) => item.source === "context_prefix")?.files ?? [];
  1344. // 构建时去掉首尾空白并算好 hash。
  1345. expect(file).toEqual({
  1346. path: "/workspace/AGENTS.md",
  1347. type: projectType,
  1348. body: "Project rule.",
  1349. hash: createHash("sha256").update("Project rule.").digest("hex"),
  1350. });
  1351. // 请求时只比较存好的 hash:持有文件的 hash 与历史记录相同就不宣告,不按正文重算。
  1352. runtime = createRuntime({ now, skillPort, contextSourcePort: instructionsPort() }, config);
  1353. const internal = runtime as unknown as AgentRuntimeInternal;
  1354. const held = { ...file!, hash: "stored-hash" };
  1355. internal.latestContextBuildResult = {
  1356. sections: [],
  1357. metaUserAttachments: [{ source: "context_prefix", content: "full", files: [held] }],
  1358. } as never;
  1359. const history = [
  1360. {
  1361. ...systemReminderAttachmentEntry("context_prefix", "full"),
  1362. metadata: {
  1363. source: "context_prefix" as const,
  1364. instructions: { files: [{ path: held.path, type: held.type, hash: "stored-hash" }] },
  1365. },
  1366. },
  1367. ];
  1368. expect(
  1369. buildRequestAnnouncements(internal, history).filter(
  1370. (entry) => entry.metadata.source === "context_prefix",
  1371. ),
  1372. ).toEqual([]);
  1373. });
  1374. it("adopts the re-read only when the compaction commits", async () => {
  1375. let failCommit = true;
  1376. Object.assign(store, {
  1377. async commitMessageBundle(bundle: { messages: { info: never; parts: never[] }[] }) {
  1378. if (failCommit) throw new Error("disk full");
  1379. for (const message of bundle.messages) {
  1380. store.savedMessages.push(message.info);
  1381. store.savedParts.push(...message.parts);
  1382. }
  1383. },
  1384. });
  1385. agentsFile.content = "Project rule.";
  1386. runtime = createRuntime({ now, skillPort, contextSourcePort: agentsPort() }, config);
  1387. const internal = runtime as unknown as AgentRuntimeInternal;
  1388. const held = () =>
  1389. internal.latestContextBuildResult?.metaUserAttachments.find(
  1390. (item) => item.source === "context_prefix",
  1391. )?.content;
  1392. await runtime.executeTurn("first");
  1393. await runtime.executeTurn("second");
  1394. agentsFile.content = "Rule changed during the session.";
  1395. await expect(compact(runtime, CompactTrigger.Reactive)).rejects.toThrow("disk full");
  1396. // 修复原因:重读结果原来在落库之前交给 runtime;写库失败后 runtime 已持有新内容,
  1397. // 下一次请求以 session_start 为原因宣告。现在写库失败时内容与 reason 都不变。
  1398. expect(held()).toContain("Project rule.");
  1399. expect(held()).not.toContain("Rule changed during the session.");
  1400. expect(internal.instructionRefreshReason).toBeUndefined();
  1401. failCommit = false;
  1402. await compact(runtime, CompactTrigger.Reactive);
  1403. expect(held()).toContain("Rule changed during the session.");
  1404. expect(internal.instructionRefreshReason).toBe("compaction");
  1405. await runtime.executeTurn("after compact");
  1406. // 保留段没有完整块:summary 之前放重读内容的完整块,之后的请求不再追加增量。
  1407. const texts = instructionTexts(runtime);
  1408. expect(texts).toHaveLength(1);
  1409. expect(texts[0]).toContain("Rule changed during the session.");
  1410. });
  1411. it("announces a change found when the same runtime resumes with the session-start reason", async () => {
  1412. agentsFile.content = "Project rule.";
  1413. runtime = createRuntime({ now, skillPort, contextSourcePort: agentsPort() }, config);
  1414. const internal = runtime as unknown as AgentRuntimeInternal;
  1415. await runtime.executeTurn("first");
  1416. await runtime.executeTurn("second");
  1417. agentsFile.content = "Rule changed before the compaction.";
  1418. await compact(runtime, CompactTrigger.Reactive);
  1419. expect(internal.instructionRefreshReason).toBe("compaction");
  1420. // 同一个 runtime 再次恢复(bootstrap 复用 runtime)时,启动时重读的文件是本次恢复读到的,
  1421. // 不是 compaction 重读的。
  1422. agentsFile.content = "Rule changed before the resume.";
  1423. await runtime.resumeFromStore();
  1424. expect(internal.instructionRefreshReason).toBeUndefined();
  1425. await runtime.executeTurn("after resume");
  1426. const latest = instructionTexts(runtime).at(-1);
  1427. expect(latest).toContain("Rule changed before the resume.");
  1428. expect(latest?.startsWith(resumedChange)).toBe(true);
  1429. });
  1430. });
  1431. it.each([CompactTrigger.Reactive, CompactTrigger.Manual])(
  1432. "lays out the post-compact context in announcement order after compact=%s",
  1433. async (trigger) => {
  1434. runtime = createRuntime({ now, skillPort, contextSourcePort: instructionsPort() }, config);
  1435. await runtime.executeTurn("first");
  1436. await runtime.executeTurn("second");
  1437. const compacted = await compact(runtime, trigger);
  1438. expect(compacted.outcome).toBe("compacted");
  1439. const layout = (value: ReturnType<typeof createTestAgentRuntime>) =>
  1440. (value as unknown as AgentRuntimeInternal).messageHistory
  1441. .toRuntimeEntries()
  1442. .filter((entry) => entry.kind === "attachment" || entry.message.role !== "system")
  1443. .map((entry) =>
  1444. entry.kind === "attachment"
  1445. ? entry.metadata.source
  1446. : String(entry.message.content).startsWith("This session is being continued")
  1447. ? "summary"
  1448. : entry.message.role,
  1449. );
  1450. const live = layout(runtime);
  1451. const summaryIndex = live.indexOf("summary");
  1452. const tail = live.slice(summaryIndex + 1);
  1453. // 保留段非空时,请求前公告放在 summary 之前,且不重复保留段已有的来源。
  1454. const leading = live.slice(0, summaryIndex);
  1455. const requestSources = ["context_prefix", "session_context", "date"];
  1456. if (trigger === CompactTrigger.Reactive) {
  1457. expect(leading).toEqual(requestSources.filter((source) => !tail.includes(source)));
  1458. } else {
  1459. expect(leading).toEqual([]);
  1460. }
  1461. // compaction 附件末尾:agent listing → skill 列表 → environment → model。
  1462. // compaction 必须产出 skill 列表,否则 compact 后第一次请求看不到 skill 名单。
  1463. expect(tail.slice(-4)).toEqual([
  1464. "agent_listing_delta",
  1465. "skills_listing",
  1466. "environment",
  1467. "model",
  1468. ]);
  1469. for (const source of ["skills_listing", "environment", "model"]) {
  1470. expect(tail.filter((item) => item === source)).toHaveLength(1);
  1471. }
  1472. // 存储顺序与 live 一致:公告写在 summary 之前,并由 summary 的 compaction part 声明。
  1473. const summaryRow = store.savedMessages.findIndex(
  1474. (message) => message.semantics?.kind === "compact_summary",
  1475. );
  1476. const declared =
  1477. store.savedParts.find((part) => part.type === "compaction" && part.compactBoundary)
  1478. ?.metadata?.compactLeadingMessageIds ?? [];
  1479. expect(declared).toHaveLength(leading.length);
  1480. expect(
  1481. store.savedMessages
  1482. .slice(summaryRow - declared.length, summaryRow)
  1483. .map((message) => message.id),
  1484. ).toEqual(declared);
  1485. // 冷恢复得到相同布局。
  1486. const { cold } = await coldRuntimeWith();
  1487. expect(layout(cold)).toEqual(live);
  1488. },
  1489. );
  1490. it("does not place a date before the summary when the kept tail already has one", () => {
  1491. // 保留段里已有 date 类型的公告(哪怕已过期)时,summary 之前不放日期;
  1492. // 之后的请求以保留段里的旧日期为基准,在末尾宣告一次日期变化。
  1493. runtime = createRuntime(
  1494. { now: () => new Date(2026, 9, 15, 0, 10), skillPort, contextSourcePort: instructionsPort() },
  1495. config,
  1496. );
  1497. const internal = runtime as unknown as AgentRuntimeInternal;
  1498. const kept = [
  1499. { message: { role: "assistant" as const, content: "Working on it." } },
  1500. systemReminderAttachmentEntry("date", "Today's date is 2026-10-14."),
  1501. { message: { role: "assistant" as const, content: "Done." } },
  1502. ];
  1503. const leading = buildCompactLeadingAnnouncements(internal, kept);
  1504. expect(leading.map((entry) => entry.metadata.source)).not.toContain("date");
  1505. // 普通请求前公告不受影响:同一份历史仍宣告日期变化。
  1506. expect(
  1507. buildRequestAnnouncements(internal, kept).map((entry) => entry.metadata.source),
  1508. ).toContain("date");
  1509. });
  1510. it("does not invent environment or model notices after compact when history has none", () => {
  1511. // 只重述 compact 前历史里真有的公告;历史里没有时由下一次请求的收集补上。
  1512. runtime = createRuntime({ now, skillPort, contextSourcePort: instructionsPort() }, config);
  1513. const internal = runtime as unknown as AgentRuntimeInternal;
  1514. internal.latestContextBuildResult = {
  1515. sections: [{ source: "env_info" }],
  1516. } as never;
  1517. const restated = restateContextAfterCompact(
  1518. internal,
  1519. [{ message: { role: "user", content: "legacy history" }, metadata: { source: "real_user" } }],
  1520. [],
  1521. );
  1522. expect(restated).toEqual([]);
  1523. });
  1524. it("commits announcements, summary and attachments in one store transaction", async () => {
  1525. const bundles: { messages: { info: { id: string }; parts: unknown[] }[] }[] = [];
  1526. const saveMessage = vi.spyOn(store, "saveMessage");
  1527. Object.assign(store, {
  1528. async commitMessageBundle(bundle: (typeof bundles)[number]) {
  1529. bundles.push(structuredClone(bundle));
  1530. for (const message of bundle.messages) {
  1531. store.savedMessages.push(message.info);
  1532. store.savedParts.push(...message.parts);
  1533. }
  1534. },
  1535. });
  1536. runtime = createRuntime({ now, skillPort, contextSourcePort: instructionsPort() }, config);
  1537. await runtime.executeTurn("first");
  1538. await runtime.executeTurn("second");
  1539. const savedBefore = saveMessage.mock.calls.length;
  1540. const compacted = await compact(runtime, CompactTrigger.Reactive);
  1541. expect(compacted.outcome).toBe("compacted");
  1542. expect(bundles).toHaveLength(1);
  1543. const bundleIds = bundles[0]!.messages.map((message) => message.info.id);
  1544. const committed = new Set(bundleIds);
  1545. // 整组记录只经过事务入口,不再逐条写入。
  1546. expect(
  1547. saveMessage.mock.calls.slice(savedBefore).filter(([info]) => committed.has(info.id)),
  1548. ).toEqual([]);
  1549. const summaryIndex = bundles[0]!.messages.findIndex((message) =>
  1550. message.parts.some((part) => (part as { type?: string }).type === "compaction"),
  1551. );
  1552. const declared = (
  1553. bundles[0]!.messages[summaryIndex]!.parts.find(
  1554. (part) => (part as { type?: string }).type === "compaction",
  1555. ) as { metadata?: { compactLeadingMessageIds?: string[] } }
  1556. ).metadata?.compactLeadingMessageIds;
  1557. expect(declared?.length).toBeGreaterThan(0);
  1558. expect(bundleIds.slice(0, summaryIndex)).toEqual(declared);
  1559. expect(bundleIds.length).toBeGreaterThan(summaryIndex + 1);
  1560. });
  1561. it.each([CompactTrigger.Reactive, CompactTrigger.Manual])(
  1562. "re-reads Git for the session context re-announced after compact=%s",
  1563. async (trigger) => {
  1564. const resolveGitContext = vi.fn(async () => ({
  1565. ...config.envInfo!,
  1566. gitBranch: "after-compact",
  1567. }));
  1568. runtime = createRuntime(
  1569. { now, skillPort, contextSourcePort: { ...instructionsPort(), resolveGitContext } },
  1570. config,
  1571. );
  1572. await runtime.executeTurn("first");
  1573. await runtime.executeTurn("second");
  1574. expect(resolveGitContext).not.toHaveBeenCalled();
  1575. await compact(runtime, trigger);
  1576. await runtime.executeTurn("after compact");
  1577. // 历史中没有 session_context 时重新读取 git,compact 后的快照是最新的。
  1578. expect(resolveGitContext).toHaveBeenCalledTimes(1);
  1579. const gitContext = contextEntries(runtime).filter(
  1580. (entry) => entry.metadata.source === "session_context",
  1581. );
  1582. expect(gitContext).toHaveLength(1);
  1583. expect(gitContext[0]!.content).toContain("after-compact");
  1584. expect(gitContext[0]!.content).not.toContain("original");
  1585. // 只刷新会话上下文;system 前缀不含 Git 事实,字节不变。
  1586. const prefix = (request: ModelRequest) =>
  1587. request.messages.slice(
  1588. 0,
  1589. request.messages.findIndex((message) => message.role !== "system"),
  1590. );
  1591. expect(prefix(requests.at(-1)!)).toEqual(prefix(requests[0]!));
  1592. },
  1593. );
  1594. it("keeps the re-read Git only inside the compacted history, so a failed compaction leaves none", async () => {
  1595. const resolveGitContext = vi.fn(async () => ({
  1596. ...config.envInfo!,
  1597. gitBranch: "after-compact",
  1598. }));
  1599. let failCommit = true;
  1600. Object.assign(store, {
  1601. async commitMessageBundle(bundle: { messages: { info: never; parts: never[] }[] }) {
  1602. if (failCommit) throw new Error("disk full");
  1603. for (const message of bundle.messages) {
  1604. store.savedMessages.push(message.info);
  1605. store.savedParts.push(...message.parts);
  1606. }
  1607. },
  1608. });
  1609. runtime = createRuntime(
  1610. { now, skillPort, contextSourcePort: { ...instructionsPort(), resolveGitContext } },
  1611. config,
  1612. );
  1613. await runtime.executeTurn("first");
  1614. await runtime.executeTurn("second");
  1615. const internal = runtime as unknown as {
  1616. config: { envInfo?: { gitBranch?: string } };
  1617. contextSourceSnapshot?: { envInfo: { gitBranch?: string } };
  1618. };
  1619. const announcedGit = () =>
  1620. contextEntries(runtime)
  1621. .filter((entry) => entry.metadata.source === "session_context")
  1622. .map((entry) => entry.content);
  1623. await expect(compact(runtime, CompactTrigger.Reactive)).rejects.toThrow("disk full");
  1624. // 写库失败:历史没有替换,仍是原来的公告;runtime 没有任何新的 Git 事实。
  1625. expect(resolveGitContext).toHaveBeenCalledTimes(1);
  1626. expect(announcedGit()).toEqual([expect.stringContaining("original")]);
  1627. expect(internal.contextSourceSnapshot?.envInfo.gitBranch).toBe("original");
  1628. expect(internal.config.envInfo?.gitBranch).toBe("original");
  1629. failCommit = false;
  1630. await compact(runtime, CompactTrigger.Reactive);
  1631. expect(announcedGit()).toEqual([expect.stringContaining("after-compact")]);
  1632. // 新的 Git 只存在于 compact 后的公告里;会话快照保持会话起始值。
  1633. expect(internal.contextSourceSnapshot?.envInfo.gitBranch).toBe("original");
  1634. expect(internal.config.envInfo?.gitBranch).toBe("original");
  1635. });
  1636. describe("Git session context decided once per window, only by history", () => {
  1637. const nonRepository = { ...config.envInfo!, isGitRepository: false, gitStatus: "not_repo" };
  1638. const repositories = new Set<string>();
  1639. const resolveGitContext = vi.fn(
  1640. async ({ workingDirectory }: Pick<ContextSourceRequest, "workingDirectory">) =>
  1641. repositories.has(workingDirectory)
  1642. ? { ...config.envInfo!, gitBranch: `repo:${workingDirectory}` }
  1643. : { isGitRepository: false, gitStatus: "not_repo" as const },
  1644. );
  1645. const resolveEnvironment = vi.fn(
  1646. async ({ workingDirectory }: Pick<ContextSourceRequest, "workingDirectory">) => ({
  1647. ...config.envInfo!,
  1648. cwd: workingDirectory,
  1649. isGitRepository: repositories.has(workingDirectory),
  1650. }),
  1651. );
  1652. const portStartingIn = (
  1653. envInfo: NonNullable<AgentRuntimeConfig["envInfo"]>,
  1654. ): ContextSourcePort => ({
  1655. ...instructionsPort(),
  1656. async resolveContextSources() {
  1657. return { workingDirectory: "/workspace", envInfo, diagnostics: [] };
  1658. },
  1659. resolveEnvironment,
  1660. resolveGitContext,
  1661. });
  1662. const announcedGit = (value = runtime) =>
  1663. contextEntries(value)
  1664. .filter((entry) => entry.metadata.source === "session_context")
  1665. .map((entry) => entry.content);
  1666. const environments = (value: ReturnType<typeof createTestAgentRuntime>) =>
  1667. contextEntries(value)
  1668. .filter((entry) => entry.metadata.source === "environment")
  1669. .map((entry) => entry.content);
  1670. const cd = (value: ReturnType<typeof createTestAgentRuntime>, directory: string) => {
  1671. (value as unknown as AgentRuntimeInternal).workingDirectory = directory;
  1672. };
  1673. beforeEach(() => {
  1674. repositories.clear();
  1675. resolveGitContext.mockClear();
  1676. resolveEnvironment.mockClear();
  1677. });
  1678. it("decides once per window: a non-repository start reads nothing later, also after moving into a repository", async () => {
  1679. runtime = createRuntime({ now, contextSourcePort: portStartingIn(nonRepository) }, config);
  1680. await runtime.executeTurn("first");
  1681. await runtime.executeTurn("second");
  1682. await runtime.executeTurn("third");
  1683. // 修复原因:起始快照来自文件系统查找,"不是仓库"是确定结论;原来不记住,第二个请求
  1684. // 还要再检查一次。现在首个请求用快照并记住目录,同一目录之后不再检查。
  1685. expect(resolveGitContext).not.toHaveBeenCalled();
  1686. expect(announcedGit()).toEqual([]);
  1687. repositories.add("/workspace/repo");
  1688. cd(runtime, "/workspace/repo");
  1689. await runtime.executeTurn("fourth");
  1690. await runtime.executeTurn("fifth");
  1691. // 本窗口已在首个请求决定过(没有 Git),进入仓库也不再读;环境公告照常报告新目录。
  1692. expect(resolveGitContext).not.toHaveBeenCalled();
  1693. expect(announcedGit()).toEqual([]);
  1694. expect(environments(runtime).at(-1)).toContain("Is a git repository: true (was false)");
  1695. await compact(runtime, CompactTrigger.Manual);
  1696. await runtime.executeTurn("next window");
  1697. // compaction 开始新窗口,新窗口的首个请求按当前目录读取。
  1698. expect(resolveGitContext).toHaveBeenCalledTimes(1);
  1699. expect(announcedGit()).toEqual([expect.stringContaining("repo:/workspace/repo")]);
  1700. });
  1701. it("reads Git again in a new window and remembers a directory that is not a repository", async () => {
  1702. runtime = createRuntime({ now, contextSourcePort: portStartingIn(config.envInfo!) }, config);
  1703. await runtime.executeTurn("first");
  1704. expect(announcedGit()).toEqual([expect.stringContaining("original")]);
  1705. await compact(runtime, CompactTrigger.Manual);
  1706. cd(runtime, "/scratch");
  1707. await runtime.executeTurn("outside repository");
  1708. await runtime.executeTurn("still outside");
  1709. // compaction 删掉了旧公告;新窗口的首个请求检查一次,非仓库目录记住。
  1710. expect(resolveGitContext).toHaveBeenCalledTimes(1);
  1711. expect(announcedGit()).toEqual([]);
  1712. await compact(runtime, CompactTrigger.Manual);
  1713. await runtime.executeTurn("outside again");
  1714. // 记住的目录在之后的窗口也不再检查。
  1715. expect(resolveGitContext).toHaveBeenCalledTimes(1);
  1716. repositories.add("/workspace");
  1717. cd(runtime, "/workspace");
  1718. await runtime.executeTurn("back in repository");
  1719. expect(resolveGitContext).toHaveBeenCalledTimes(1);
  1720. expect(announcedGit()).toEqual([]);
  1721. await compact(runtime, CompactTrigger.Manual);
  1722. await runtime.executeTurn("repository window");
  1723. expect(resolveGitContext).toHaveBeenCalledTimes(2);
  1724. expect(announcedGit()).toEqual([expect.stringContaining("repo:/workspace")]);
  1725. });
  1726. it("lets a compaction that keeps a tail decide again although the tail holds a date announcement", async () => {
  1727. let today = new Date(2026, 9, 14, 12);
  1728. runtime = createRuntime(
  1729. { now: () => today, contextSourcePort: portStartingIn(nonRepository) },
  1730. { ...config, compact: { enabled: true } },
  1731. );
  1732. await runtime.executeTurn("first");
  1733. await runtime.executeTurn("second");
  1734. repositories.add("/workspace/repo");
  1735. cd(runtime, "/workspace/repo");
  1736. today = new Date(2026, 9, 15, 12);
  1737. // 第三个输入的请求前公告(日期变化)先写入历史,模型随后报告上下文超限,触发 reactive compaction。
  1738. // 保留段是最后一个 assistant 之后的内容,带着这条日期变化公告。
  1739. respond.mockRejectedValueOnce(
  1740. Object.assign(new Error("provider context window exceeded"), {
  1741. code: ModelErrorCode.ModelContextExceeded,
  1742. }),
  1743. );
  1744. await runtime.executeTurn("third");
  1745. // date 只表示请求前已决定;compaction 为压缩后的历史重新决定,仍按当前目录读取。
  1746. expect(
  1747. contextEntries(runtime)
  1748. .filter((entry) => entry.metadata.source === "date")
  1749. .map((entry) => entry.content),
  1750. ).toEqual([expect.stringContaining("The date has changed")]);
  1751. expect(resolveGitContext).toHaveBeenCalledTimes(1);
  1752. expect(announcedGit()).toEqual([expect.stringContaining("repo:/workspace/repo")]);
  1753. });
  1754. it("continues the restored window after a cold resume: membership is re-read for the environment, Git waits for the next window", async () => {
  1755. runtime = createRuntime({ now, contextSourcePort: portStartingIn(nonRepository) }, config);
  1756. await runtime.executeTurn("first");
  1757. expect(announcedGit()).toEqual([]);
  1758. // 会话中途 git init:live runtime 不再检查,环境与 Git 都不变。
  1759. repositories.add("/workspace");
  1760. await runtime.executeTurn("live after git init");
  1761. expect(resolveEnvironment).not.toHaveBeenCalled();
  1762. expect(resolveGitContext).not.toHaveBeenCalled();
  1763. expect(environments(runtime)).toHaveLength(1);
  1764. const coldStore = createRecordingMessageStore();
  1765. await coldStore.createSession(await store.getSession(sessionId));
  1766. coldStore.savedMessages.push(...structuredClone(store.savedMessages));
  1767. coldStore.savedParts.push(...structuredClone(store.savedParts));
  1768. const cold = createRuntime(
  1769. { now, contextSourcePort: portStartingIn(nonRepository), sessionStore: coldStore as never },
  1770. config,
  1771. );
  1772. await cold.resumeFromStore();
  1773. await cold.executeTurn("after resume");
  1774. await cold.executeTurn("again");
  1775. // 修复原因:非仓库窗口没有 Git 公告,"不是仓库"原来只记在 runtime 内存里;冷恢复后的新
  1776. // runtime 没有这份记忆,又读 Git 并宣告,而环境公告仍写 "Is a git repository: false"。
  1777. // 现在恢复的窗口沿用历史,不读 Git;新 runtime 只重读一次是否仓库,在环境公告里报告变化。
  1778. expect(resolveGitContext).not.toHaveBeenCalled();
  1779. expect(announcedGit(cold)).toEqual([]);
  1780. expect(resolveEnvironment).toHaveBeenCalledTimes(1);
  1781. expect(environments(cold).slice(1)).toEqual([
  1782. "# Environment update\n - Is a git repository: true (was false)",
  1783. ]);
  1784. await compact(cold, CompactTrigger.Manual);
  1785. await cold.executeTurn("next window");
  1786. expect(resolveGitContext).toHaveBeenCalledTimes(1);
  1787. expect(announcedGit(cold)).toEqual([expect.stringContaining("repo:/workspace")]);
  1788. });
  1789. it("does not use a resumed session's stored snapshot as the prefetch when the restored window has not decided", async () => {
  1790. runtime = createRuntime({ now, contextSourcePort: portStartingIn(nonRepository) }, config);
  1791. await runtime.executeTurn("first");
  1792. repositories.add("/workspace");
  1793. // 恢复的历史还没有做过决定(没有 date 公告,例如旧版本写下的历史)。
  1794. const coldStore = createRecordingMessageStore();
  1795. await coldStore.createSession(await store.getSession(sessionId));
  1796. const undecided = store.savedMessages.filter(
  1797. (message) => runtimeSourceOf(message) !== "date",
  1798. );
  1799. const kept = new Set(undecided.map((message) => message.id));
  1800. coldStore.savedMessages.push(...structuredClone(undecided));
  1801. coldStore.savedParts.push(
  1802. ...structuredClone(store.savedParts.filter((part) => kept.has(part.messageID))),
  1803. );
  1804. const cold = createRuntime(
  1805. { now, contextSourcePort: portStartingIn(nonRepository), sessionStore: coldStore as never },
  1806. config,
  1807. );
  1808. await cold.resumeFromStore();
  1809. await cold.executeTurn("after resume");
  1810. // 存储里的快照不是刚读的,不能当预取;恢复后的首个请求读一次 Git。
  1811. expect(resolveGitContext).toHaveBeenCalledTimes(1);
  1812. expect(announcedGit(cold)).toEqual([expect.stringContaining("repo:/workspace")]);
  1813. expect(environments(cold).at(-1)).toBe(
  1814. "# Environment update\n - Is a git repository: true (was false)",
  1815. );
  1816. });
  1817. });
  1818. it("appends changed cwd once and keeps the initial Git snapshot", async () => {
  1819. runtime = createRuntime({ now }, config);
  1820. await runtime.executeTurn("first");
  1821. (runtime as unknown as AgentRuntimeInternal).workingDirectory = "/workspace/subdir";
  1822. await runtime.executeTurn("second");
  1823. await runtime.executeTurn("third");
  1824. const all = contextEntries(runtime);
  1825. const environments = all.filter((entry) => entry.metadata?.source === "environment");
  1826. expect(environments).toHaveLength(2);
  1827. expect(environments[1]).toMatchObject({
  1828. content:
  1829. "# Environment update\n - Primary working directory: /workspace/subdir (was /workspace)",
  1830. });
  1831. expect(all.filter((entry) => entry.metadata?.source === "session_context")).toHaveLength(1);
  1832. // 第三轮只追加:上一轮回复、轮首的 token 预算提醒和第三问。
  1833. expect(requests[1]?.messages.map(({ role, content }) => ({ role, content }))).toEqual(
  1834. requests[2]?.messages.slice(0, -3).map(({ role, content }) => ({ role, content })),
  1835. );
  1836. });
  1837. it("lists additional working directories and announces only their change after cold resume", async () => {
  1838. const environmentEntries = (value: ReturnType<typeof createTestAgentRuntime>) =>
  1839. contextEntries(value).filter((entry) => entry.metadata?.source === "environment");
  1840. runtime = createRuntime(
  1841. { now },
  1842. { ...config, additionalDirectories: ["/work/backend", "C:\\work\\shared folder"] },
  1843. );
  1844. await runtime.executeTurn("first");
  1845. const [full] = environmentEntries(runtime);
  1846. // 运行实例内目录不变;冷恢复按新运行配置比较最近一次公告,只追加增量,原块不改写。
  1847. const cold = createRuntime(
  1848. { now },
  1849. { ...config, additionalDirectories: ["/work/backend", "/work/docs"] },
  1850. );
  1851. await cold.resumeFromStore();
  1852. await cold.executeTurn("resumed");
  1853. const environments = environmentEntries(cold);
  1854. expect(environments).toHaveLength(2);
  1855. expect(environments[0]).toEqual(full);
  1856. expect(environments[1]).toMatchObject({
  1857. content:
  1858. "# Environment update\n - Additional working directories added:\n - /work/docs\n - Additional working directories removed:\n - C:\\work\\shared folder",
  1859. metadata: {
  1860. environment: {
  1861. full: false,
  1862. snapshot: { additionalWorkingDirectories: ["/work/backend", "/work/docs"] },
  1863. },
  1864. },
  1865. });
  1866. const visible = (request: ModelRequest) =>
  1867. request.messages.map(({ role, content }) => ({ role, content }));
  1868. expect(visible(requests.at(-1)!).slice(0, requests[0]!.messages.length)).toEqual(
  1869. visible(requests[0]!),
  1870. );
  1871. });
  1872. it("announces the ZCode Desktop part and the Gen UI directory in the environment, not in the system prompt", async () => {
  1873. const environmentEntries = (value: ReturnType<typeof createTestAgentRuntime>) =>
  1874. contextEntries(value).filter((entry) => entry.metadata?.source === "environment");
  1875. const desktopConfig = (genUiOutputRoot: string): Partial<AgentRuntimeConfig> => ({
  1876. ...config,
  1877. presentationSurface: "zcode_desktop",
  1878. genUiOutputRoot,
  1879. });
  1880. const directoryOf = (value: ReturnType<typeof createTestAgentRuntime>) =>
  1881. resolveGenUiOutputDirectory(value as unknown as AgentRuntimeInternal)!;
  1882. const noLongerDesktop =
  1883. "The ZCode Desktop Context above no longer applies: this session is not shown in ZCode Desktop.";
  1884. // 不用 MCS:环境公告留在 user 侧,system 消息只有前缀。
  1885. const system = (request: ModelRequest) =>
  1886. request.messages.filter((message) => message.role === "system");
  1887. runtime = createRuntime(
  1888. { now, fileSystemPort: new MemoryFileSystem({}) as never },
  1889. desktopConfig("/data/visualizations"),
  1890. { mcs: false },
  1891. );
  1892. await runtime.executeTurn("first");
  1893. const directory = directoryOf(runtime);
  1894. // 修复原因:Desktop 段与目录原来写在 system 里;system 由 prompt 快照冻结,fork 后子会话继续发送父会话的目录,
  1895. // 灰度翻转或换到 terminal 恢复时也继续发送旧的 Desktop 段。现在两者都随环境公告发送。
  1896. const systemText = JSON.stringify(system(requests[0]!));
  1897. expect(systemText).not.toContain("ZCode Desktop Context");
  1898. expect(systemText).not.toContain(directory);
  1899. const [full] = environmentEntries(runtime);
  1900. expect(full!.content).toContain(
  1901. ` - Is a git repository: true\n - Visualization directory for this session: ${directory}\n - Platform: linux`,
  1902. );
  1903. expect(full!.content.endsWith(`\n\n${buildDesktopContextContent(true)}`)).toBe(true);
  1904. expect(full!.metadata).toMatchObject({
  1905. environment: {
  1906. full: true,
  1907. snapshot: { desktopContext: true, visualizationDirectory: directory },
  1908. },
  1909. });
  1910. // 目录变化(fork 换了 session id,或换了输出根目录):形态不变,只追加一行目录,system 字节不变。
  1911. const cold = createRuntime(
  1912. { now, fileSystemPort: new MemoryFileSystem({}) as never },
  1913. desktopConfig("/other/visualizations"),
  1914. { mcs: false },
  1915. );
  1916. await cold.resumeFromStore();
  1917. await cold.executeTurn("resumed");
  1918. const next = directoryOf(cold);
  1919. expect(environmentEntries(cold)).toHaveLength(2);
  1920. expect(environmentEntries(cold)[1]).toMatchObject({
  1921. content: `# Environment update\n - Visualization directory for this session: ${next} (was ${directory})`,
  1922. metadata: { environment: { full: false, snapshot: { visualizationDirectory: next } } },
  1923. });
  1924. expect(system(requests.at(-1)!)).toEqual(system(requests[0]!));
  1925. // 升级前的环境元数据没有 Desktop 形态与目录:补目录行,再补整段 Desktop 文字。
  1926. for (const part of store.savedParts) {
  1927. const environment = (
  1928. part.metadata?.runtimeMessage as { environment?: { snapshot: Record<string, unknown> } }
  1929. )?.environment;
  1930. delete environment?.snapshot.visualizationDirectory;
  1931. delete environment?.snapshot.desktopContext;
  1932. }
  1933. const legacy = createRuntime(
  1934. { now, fileSystemPort: new MemoryFileSystem({}) as never },
  1935. desktopConfig("/other/visualizations"),
  1936. { mcs: false },
  1937. );
  1938. await legacy.resumeFromStore();
  1939. await legacy.executeTurn("after upgrade");
  1940. expect(environmentEntries(legacy).at(-1)!.content).toBe(
  1941. `# Environment update\n - Visualization directory for this session: ${next}\n\n${buildDesktopContextContent(true)}`,
  1942. );
  1943. // 换到 terminal 恢复:追加一句 Desktop 段不再适用,system 仍不变。
  1944. const terminal = createRuntime(
  1945. { now, fileSystemPort: new MemoryFileSystem({}) as never },
  1946. config,
  1947. { mcs: false },
  1948. );
  1949. await terminal.resumeFromStore();
  1950. await terminal.executeTurn("in the terminal");
  1951. expect(environmentEntries(terminal).at(-1)!.content).toBe(
  1952. `# Environment update\n - Visualization directory for this session: none (was ${next})\n\n${noLongerDesktop}`,
  1953. );
  1954. expect(system(requests.at(-1)!)).toEqual(system(requests[0]!));
  1955. // 仍在 Desktop,但不再有目录:省略 Gen UI 整段,不再注入不可用提示或控件说明。
  1956. const previous = environmentEntries(legacy).at(-1)!.metadata as {
  1957. environment: { snapshot: EnvironmentSnapshot };
  1958. };
  1959. const { visualizationDirectory: _removed, ...withoutDirectory } = previous.environment.snapshot;
  1960. expect(
  1961. buildEnvironmentAnnouncement(withoutDirectory, previous.environment.snapshot, true)?.content,
  1962. ).toBe(
  1963. `# Environment update\n - Visualization directory for this session: none (was ${next})\n\n${buildDesktopContextContent(false)}`,
  1964. );
  1965. expect(buildDesktopContextContent(false)).not.toMatch(/Interactive views|Gen UI|modelContent/);
  1966. // 只有 Desktop 段变化:更新就是这段文字,不带标题。
  1967. const { desktopContext: _desktop, ...terminalSnapshot } = withoutDirectory;
  1968. expect(buildEnvironmentAnnouncement(withoutDirectory, terminalSnapshot, true)?.content).toBe(
  1969. buildDesktopContextContent(false),
  1970. );
  1971. });
  1972. it("refreshes repository membership, deduplicates, and compares the return trip with the latest snapshot", async () => {
  1973. const contextSourcePort = environmentPort();
  1974. runtime = createRuntime({ now, contextSourcePort }, config);
  1975. await runtime.executeTurn("first");
  1976. const initialGit = contextEntries(runtime).find(
  1977. (entry) => entry.metadata?.source === "session_context",
  1978. );
  1979. runtime.setWorkingDirectory("/outside");
  1980. await runtime.executeTurn("leave repo");
  1981. await runtime.executeTurn("same directory");
  1982. const updates = contextEntries(runtime).filter(
  1983. (entry) => entry.metadata?.source === "environment",
  1984. );
  1985. expect(updates).toHaveLength(2);
  1986. expect(updates[1]).toMatchObject({
  1987. content:
  1988. "# Environment update\n - Primary working directory: /outside (was /workspace)\n - Is a git repository: false (was true)",
  1989. metadata: {
  1990. environment: { full: false, snapshot: { cwd: "/outside", isGitRepository: false } },
  1991. },
  1992. });
  1993. expect(contextSourcePort.resolveEnvironment).toHaveBeenCalledTimes(1);
  1994. // 同一条 MCS system 里,环境变化之后是轮首的 token 预算提醒。
  1995. expect(requests[1]?.messages.at(-1)).toMatchObject({
  1996. role: "system",
  1997. content: `${updates[1]?.kind === "attachment" ? updates[1].content : ""}\n\n<total_tokens>15000000 tokens left</total_tokens>`,
  1998. });
  1999. runtime.setWorkingDirectory("/workspace");
  2000. await runtime.executeTurn("return to repo");
  2001. expect(
  2002. contextEntries(runtime)
  2003. .filter((entry) => entry.metadata?.source === "environment")
  2004. .at(-1),
  2005. ).toMatchObject({
  2006. content:
  2007. "# Environment update\n - Primary working directory: /workspace (was /outside)\n - Is a git repository: true (was false)",
  2008. });
  2009. expect(
  2010. contextEntries(runtime).filter((entry) => entry.metadata?.source === "session_context"),
  2011. ).toEqual([initialGit]);
  2012. });
  2013. it("re-reads only repository membership once after a cold resume and announces a change as an update", async () => {
  2014. runtime = createRuntime({ now, contextSourcePort: environmentPort() }, config);
  2015. await runtime.executeTurn("first");
  2016. const environmentsOf = (value: ReturnType<typeof createTestAgentRuntime>) =>
  2017. contextEntries(value)
  2018. .filter((entry) => entry.metadata?.source === "environment")
  2019. .map((entry) => entry.content);
  2020. const gitOf = (value: ReturnType<typeof createTestAgentRuntime>) =>
  2021. contextEntries(value).filter((entry) => entry.metadata?.source === "session_context");
  2022. // 是否仓库没变:新 runtime 读一次,不追加公告。
  2023. const unchanged = environmentPort();
  2024. const { cold: same } = await coldRuntimeWith(skillPort, config, {
  2025. contextSourcePort: unchanged,
  2026. });
  2027. await same.executeTurn("resumed");
  2028. await same.executeTurn("again");
  2029. expect(unchanged.resolveEnvironment).toHaveBeenCalledTimes(1);
  2030. expect(environmentsOf(same)).toEqual(environmentsOf(runtime));
  2031. // .git 已删除:只取是否仓库,平台与系统版本沿用历史,不出完整块;Git 公告沿用历史。
  2032. const changed = environmentPort();
  2033. changed.resolveEnvironment.mockImplementation(async ({ workingDirectory }) => ({
  2034. ...config.envInfo!,
  2035. cwd: workingDirectory,
  2036. platform: "darwin",
  2037. osVersion: "Darwin",
  2038. isGitRepository: false,
  2039. }));
  2040. const { cold } = await coldRuntimeWith(skillPort, config, { contextSourcePort: changed });
  2041. await cold.executeTurn("resumed");
  2042. await cold.executeTurn("again");
  2043. expect(changed.resolveEnvironment).toHaveBeenCalledTimes(1);
  2044. expect(environmentsOf(cold)).toEqual([
  2045. ...environmentsOf(runtime),
  2046. "# Environment update\n - Is a git repository: false (was true)",
  2047. ]);
  2048. expect(gitOf(cold)).toEqual(gitOf(runtime));
  2049. });
  2050. it("restores environment snapshot metadata and emits a full block when its original block is removed", async () => {
  2051. const contextSourcePort = environmentPort();
  2052. runtime = createRuntime({ now, contextSourcePort }, config);
  2053. await runtime.executeTurn("first");
  2054. runtime.setWorkingDirectory("/outside");
  2055. await runtime.executeTurn("leave repo");
  2056. const cold = createRuntime({ now, contextSourcePort }, config);
  2057. await cold.resumeFromStore();
  2058. cold.setWorkingDirectory("/outside");
  2059. await cold.executeTurn("resume here");
  2060. expect(contextEntries(cold)).toEqual(contextEntries(runtime));
  2061. const internal = cold as unknown as AgentRuntimeInternal;
  2062. internal.messageHistory.replaceMessages(
  2063. internal.messageHistory
  2064. .toRuntimeEntries()
  2065. .filter(
  2066. (entry) =>
  2067. !(
  2068. entry.kind === "attachment" &&
  2069. entry.metadata.source === "environment" &&
  2070. entry.metadata.environment?.full
  2071. ),
  2072. ),
  2073. );
  2074. await cold.executeTurn("after history reduction");
  2075. expect(
  2076. contextEntries(cold)
  2077. .filter((entry) => entry.metadata?.source === "environment")
  2078. .at(-1),
  2079. ).toMatchObject({
  2080. content: expect.stringContaining("# Environment\n"),
  2081. metadata: {
  2082. environment: { full: true, snapshot: { cwd: "/outside", isGitRepository: false } },
  2083. },
  2084. });
  2085. });
  2086. it("announces a shell change as an update, replaces the full block on a platform change and catches up a directory moved during the probe", async () => {
  2087. const contextSourcePort = environmentPort();
  2088. runtime = createRuntime({ now, contextSourcePort }, config);
  2089. await runtime.executeTurn("first");
  2090. contextSourcePort.resolveEnvironment.mockImplementationOnce(async () => {
  2091. runtime.setWorkingDirectory("/latest");
  2092. return { ...config.envInfo!, cwd: "/probed", shell: "fish", isGitRepository: true };
  2093. });
  2094. contextSourcePort.resolveEnvironment.mockImplementationOnce(async ({ workingDirectory }) => ({
  2095. ...config.envInfo!,
  2096. cwd: workingDirectory,
  2097. platform: "darwin",
  2098. isGitRepository: false,
  2099. }));
  2100. const latestEnvironment = () =>
  2101. contextEntries(runtime)
  2102. .filter((entry) => entry.metadata?.source === "environment")
  2103. .at(-1);
  2104. runtime.setWorkingDirectory("/probed");
  2105. await runtime.executeTurn("move during probe");
  2106. // 公告使用探测前读到的目录及其事实,不重试;目录在 IO 期间的变化留给下一次请求。
  2107. // shell 与目录一样只追加变化行,不再整块重发。
  2108. expect(latestEnvironment()).toMatchObject({
  2109. content:
  2110. "# Environment update\n - Primary working directory: /probed (was /workspace)\n - Shell: fish (was bash)",
  2111. metadata: {
  2112. environment: { full: false, snapshot: { cwd: "/probed", shell: "fish" } },
  2113. },
  2114. });
  2115. expect(contextSourcePort.resolveEnvironment).toHaveBeenCalledTimes(1);
  2116. await runtime.executeTurn("next");
  2117. expect(latestEnvironment()).toMatchObject({
  2118. content: expect.stringContaining("# Environment\n"),
  2119. metadata: {
  2120. environment: {
  2121. full: true,
  2122. snapshot: { cwd: "/latest", platform: "darwin", isGitRepository: false },
  2123. },
  2124. },
  2125. });
  2126. expect(contextSourcePort.resolveEnvironment).toHaveBeenCalledTimes(2);
  2127. });
  2128. it("republishes a full block for legacy metadata and does not leak snapshot metadata on MCS downgrade", async () => {
  2129. runtime = createRuntime({ now, contextSourcePort: environmentPort() }, config);
  2130. await runtime.executeTurn("first");
  2131. const internal = runtime as unknown as AgentRuntimeInternal;
  2132. const legacy = internal.messageHistory.toRuntimeEntries();
  2133. for (const entry of legacy) {
  2134. if (entry.metadata?.source === "environment") delete entry.metadata.environment;
  2135. }
  2136. internal.messageHistory.replaceMessages(legacy);
  2137. await runtime.executeTurn("legacy history");
  2138. expect(
  2139. contextEntries(runtime).filter((entry) => entry.metadata?.source === "environment"),
  2140. ).toHaveLength(2);
  2141. runtime.setWorkingDirectory("/outside");
  2142. await runtime.executeTurn("leave");
  2143. const returnedEntries = internal.messageHistory.toRuntimeEntries();
  2144. const returnedEnvironment = returnedEntries
  2145. .filter((entry) => entry.metadata?.source === "environment")
  2146. .at(-1)!;
  2147. returnedEnvironment.metadata!.environment!.snapshot.cwd = "/mutated-entry";
  2148. expect(contextEntries(runtime).at(-1)).not.toEqual(returnedEnvironment);
  2149. const projected = buildProviderRequestMessages({
  2150. entries: internal.messageHistory.toRuntimeEntries(),
  2151. useMidConversationSystem: false,
  2152. }).messages;
  2153. expect(JSON.stringify(projected)).not.toMatch(/"(?:metadata|snapshot|environment)"/u);
  2154. expect(
  2155. projected.some(
  2156. (message) =>
  2157. message.role === "user" &&
  2158. String(message.content).includes("<system-reminder>\n# Environment update\n"),
  2159. ),
  2160. ).toBe(true);
  2161. });
  2162. it("does not commit a failed context write and retries the missing sources", async () => {
  2163. runtime = createRuntime({ now, skillPort, contextSourcePort: instructionsPort() }, config);
  2164. const savePart = store.savePart;
  2165. store.savePart = async (part) => {
  2166. if (part.metadata?.runtimeMessage?.source === "environment")
  2167. throw new Error("context write failed");
  2168. await savePart(part);
  2169. };
  2170. await expect(runtime.executeTurn("first")).rejects.toThrow();
  2171. expect(respond).not.toHaveBeenCalled();
  2172. // environment 是第一条公告;它写入失败时,后续来源都不会提交。
  2173. expect(contextEntries(runtime).map((entry) => entry.metadata?.source)).toEqual([]);
  2174. store.savePart = savePart;
  2175. await runtime.executeTurn("retry");
  2176. expect(contextEntries(runtime).map((entry) => entry.metadata?.source)).toEqual([...sources]);
  2177. });
  2178. });