runtime-context-announcements.test.ts 70 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577
  1. import { join } from "node:path";
  2. import { beforeEach, describe, expect, it, vi } from "vitest";
  3. import {
  4. CompactTrigger,
  5. createRootTraceContext,
  6. createSessionId,
  7. createToolCallId,
  8. ModelErrorCode,
  9. type ContextSourcePort,
  10. type ContextSourceRequest,
  11. type ModelRequest,
  12. type ModelResult,
  13. type SkillPort,
  14. } from "@zcode/contracts";
  15. import { createTestAgentRuntime } from "./test-agent-runtime.js";
  16. import { createTestModelSelection } from "./test-model-selection.js";
  17. import { createTestSessionEventStore } from "./test-event-store.js";
  18. import { createTestModelFactory } from "./test-runtime-model.js";
  19. import { createRecordingMessageStore } from "./runtime-output-token-continuation-test-helpers.js";
  20. import { createToolRegistry } from "../src/tool/registry.js";
  21. import { createReadFileStatePathKey } from "../src/tool/read-file-state.js";
  22. import { resolveProjectMemoryRoot } from "../src/memory/project-root.js";
  23. import { MemoryFileSystem } from "./memory-test-utils.js";
  24. import type { AgentDefinitionsSnapshot } from "../src/subagent/definitions.js";
  25. import { buildProviderRequestMessages } from "../src/runtime/helpers/provider-request-messages.js";
  26. import { systemReminderAttachmentEntry } from "../src/agent/message-history.js";
  27. import type { AgentRuntimeInternal } from "../src/runtime/internal.js";
  28. import {
  29. buildCompactLeadingAnnouncements,
  30. buildRequestAnnouncements,
  31. restateContextAfterCompact,
  32. } from "../src/runtime/methods/context-refresh.js";
  33. import type { AgentRuntimeConfig, AgentRuntimeDeps } from "../src/runtime/types.js";
  34. import { formatWorkflowStallNotification } from "../src/runtime-task/workflow-notification-copy.js";
  35. const snapshot = (...names: string[]): AgentDefinitionsSnapshot => ({
  36. activeAgents: names.map((name) => ({
  37. name,
  38. description: `Description ${name}`,
  39. source: "user",
  40. systemPrompt: "private",
  41. })),
  42. });
  43. const result = {
  44. finishReason: "stop" as const,
  45. text: "Summary of current work.",
  46. usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 },
  47. };
  48. let sessionId: ReturnType<typeof createSessionId>;
  49. let store: ReturnType<typeof createRecordingMessageStore>;
  50. let requests: ModelRequest[];
  51. const definitions = vi.fn(() => snapshot("A"));
  52. const respond = vi.fn<(request: ModelRequest) => Promise<ModelResult>>();
  53. let runtime: ReturnType<typeof createTestAgentRuntime>;
  54. function createRuntime(
  55. deps: Partial<AgentRuntimeDeps> = {},
  56. config: Partial<AgentRuntimeConfig> = {},
  57. { mcs = true, fold = false }: { mcs?: boolean; fold?: boolean } = {},
  58. ) {
  59. const modelFactory = createTestModelFactory({
  60. properties: { supportsMidConversationSystem: mcs },
  61. generateText: async (request) => {
  62. requests.push(request);
  63. return respond(request);
  64. },
  65. });
  66. return createTestAgentRuntime(
  67. sessionId,
  68. { mode: "yolo", compact: { enabled: false }, titleGeneration: { enabled: false }, ...config },
  69. {
  70. eventStore: createTestSessionEventStore(),
  71. sessionStore: store as never,
  72. getAgentDefinitions: definitions,
  73. modelFactory: fold
  74. ? (input) => ({
  75. ...modelFactory(input),
  76. requestCapabilities: { foldRemindersIntoToolResults: true },
  77. })
  78. : modelFactory,
  79. ...deps,
  80. },
  81. );
  82. }
  83. const entries = () =>
  84. (runtime as unknown as AgentRuntimeInternal).messageHistory.toRuntimeEntries();
  85. const compact = (value: ReturnType<typeof createTestAgentRuntime>, trigger?: CompactTrigger) =>
  86. (value as unknown as AgentRuntimeInternal).compactActiveConversation(
  87. undefined,
  88. createRootTraceContext({ sessionId }),
  89. [],
  90. { trigger },
  91. );
  92. beforeEach(() => {
  93. sessionId = createSessionId();
  94. store = createRecordingMessageStore();
  95. requests = [];
  96. definitions.mockReset().mockImplementation(() => snapshot("A"));
  97. respond.mockReset().mockResolvedValue(result);
  98. runtime = createRuntime();
  99. });
  100. const skillPort: SkillPort = {
  101. async discoverSkills() {
  102. return {
  103. skills: [
  104. {
  105. name: "search",
  106. description: "search things",
  107. path: "/workspace/.agents/skills/search/SKILL.md",
  108. directory: "/workspace/.agents/skills/search",
  109. rootPath: "/workspace/.agents/skills",
  110. scope: "project" as const,
  111. source: "agents" as const,
  112. safeToAutoLoad: true,
  113. frontmatterKeys: [],
  114. },
  115. ],
  116. diagnostics: [],
  117. totalDiscovered: 1,
  118. };
  119. },
  120. async loadSkill() {
  121. throw new Error("not needed");
  122. },
  123. };
  124. describe("runtime context announcements", () => {
  125. // 顺序即宣告顺序:environment → model → (agent listing) → skills → instructions → git → date。
  126. const sources = new Set([
  127. "environment",
  128. "model",
  129. "skills_listing",
  130. "context_prefix",
  131. "session_context",
  132. "date",
  133. ]);
  134. // 动态公告按隐藏提醒落盘:类型只记在 runtimeMessage.source,不写顶层 source。
  135. const runtimeSourceOf = (message: { metadata?: Record<string, unknown> }) =>
  136. (message.metadata?.runtimeMessage as { source?: string } | undefined)?.source;
  137. const isAnnouncementRecord = (message: {
  138. semantics?: { kind?: string };
  139. metadata?: Record<string, unknown>;
  140. }) =>
  141. message.semantics?.kind === "system_reminder" && sources.has(runtimeSourceOf(message) ?? "");
  142. const contextEntries = (value: ReturnType<typeof createTestAgentRuntime>) =>
  143. (value as unknown as AgentRuntimeInternal).messageHistory
  144. .toRuntimeEntries()
  145. .filter((entry) => entry.kind === "attachment" && sources.has(entry.metadata.source));
  146. const config: Partial<AgentRuntimeConfig> = {
  147. workingDirectory: "/workspace",
  148. currentDate: "2026-10-14",
  149. envInfo: {
  150. cwd: "/workspace",
  151. platform: "linux",
  152. shell: "bash",
  153. osVersion: "Linux",
  154. nodeVersion: "24",
  155. isGitRepository: true,
  156. gitStatus: "clean",
  157. gitBranch: "original",
  158. },
  159. };
  160. const now = () => new Date(2026, 9, 14, 12);
  161. const instructionsPort = (): ContextSourcePort => ({
  162. async resolveEnvironment() {
  163. return config.envInfo!;
  164. },
  165. async resolveGitContext() {
  166. return config.envInfo!;
  167. },
  168. async resolveContextSources() {
  169. return {
  170. workingDirectory: "/workspace",
  171. envInfo: config.envInfo!,
  172. userInstructions: {
  173. filePath: "/workspace/AGENTS.md",
  174. fileName: "AGENTS.md",
  175. content: "Project rule.",
  176. bytesRead: 13,
  177. sizeBytes: 13,
  178. truncated: false,
  179. },
  180. diagnostics: [],
  181. };
  182. },
  183. });
  184. const environmentPort = () =>
  185. ({
  186. async resolveContextSources() {
  187. return { workingDirectory: "/workspace", envInfo: config.envInfo!, diagnostics: [] };
  188. },
  189. resolveEnvironment: vi.fn(
  190. async ({
  191. workingDirectory,
  192. effectiveShellDisplayName,
  193. }: Pick<ContextSourceRequest, "workingDirectory" | "effectiveShellDisplayName">) => ({
  194. ...config.envInfo!,
  195. cwd: workingDirectory,
  196. shell: effectiveShellDisplayName ?? config.envInfo!.shell,
  197. isGitRepository: workingDirectory.startsWith("/workspace"),
  198. }),
  199. ),
  200. }) satisfies ContextSourcePort;
  201. // 把当前 store 复制成独立的冷存储,再从中恢复一个新 runtime。
  202. const coldRuntimeWith = async (
  203. port: SkillPort = skillPort,
  204. coldConfig: Partial<AgentRuntimeConfig> = config,
  205. coldDeps: Partial<AgentRuntimeDeps> = {},
  206. ) => {
  207. const recording = createRecordingMessageStore();
  208. // rewind 只需把分支信息写回会话;录制 store 没有 setRevert,用 updateSession 承接。
  209. const coldStore = Object.assign(recording, {
  210. async setRevert(input: { sessionID: string; revert: unknown }) {
  211. await recording.updateSession({ id: input.sessionID, revert: input.revert });
  212. },
  213. });
  214. await coldStore.createSession(await store.getSession(sessionId));
  215. coldStore.savedMessages.push(...structuredClone(store.savedMessages));
  216. coldStore.savedParts.push(...structuredClone(store.savedParts));
  217. const cold = createRuntime(
  218. {
  219. now,
  220. skillPort: port,
  221. contextSourcePort: instructionsPort(),
  222. sessionStore: coldStore as never,
  223. ...coldDeps,
  224. },
  225. coldConfig,
  226. );
  227. await cold.resumeFromStore();
  228. return { cold, coldStore };
  229. };
  230. it("announces environment and model for a custom system prompt", async () => {
  231. runtime = createRuntime(
  232. { now, contextSourcePort: environmentPort() },
  233. { ...config, systemPrompt: "Host override." },
  234. );
  235. await runtime.executeTurn("first task");
  236. // 自定义 prompt 只替换 system 正文,环境与模型公告照常发送;Git 仍不发。
  237. expect(contextEntries(runtime).map((entry) => entry.metadata?.source)).toEqual([
  238. "environment",
  239. "model",
  240. "date",
  241. ]);
  242. expect(String(requests[0]!.messages[1]!.content)).toBe("\nHost override.");
  243. });
  244. it.each([false, true])(
  245. "uses shared environment/model lifecycle for a specialized child (MCS=%s)",
  246. async (mcs) => {
  247. const contextSourcePort = environmentPort();
  248. const resolveContextSources = vi.spyOn(contextSourcePort, "resolveContextSources");
  249. const childConfig: Partial<AgentRuntimeConfig> = {
  250. ...config,
  251. taskType: "subagent_child",
  252. subagentContext: { agentPrompt: "Dedicated child identity." },
  253. subagents: { enabled: false },
  254. };
  255. runtime = createRuntime({ now, contextSourcePort }, childConfig, { mcs });
  256. await runtime.executeTurn("first child task");
  257. const initial = contextEntries(runtime);
  258. expect(initial.map((entry) => entry.metadata?.source)).toEqual([
  259. "environment",
  260. "model",
  261. "date",
  262. ]);
  263. expect(
  264. requests[0]?.messages.find((message) => String(message.content).includes("# Environment\n"))
  265. ?.role,
  266. ).toBe(mcs ? "system" : "user");
  267. const initialBody = requests[0]!.messages[1]!.content;
  268. runtime.setWorkingDirectory("/outside");
  269. const nextSelection = createTestModelSelection("test/child-next");
  270. runtime.setSessionModelSelection(nextSelection);
  271. await runtime.executeTurn("second child task");
  272. const changed = contextEntries(runtime);
  273. expect(
  274. changed.filter((entry) => entry.metadata?.source === "environment").at(-1),
  275. ).toMatchObject({
  276. content:
  277. "# Environment update\n - Primary working directory: /outside (was /workspace)\n - Is a git repository: false (was true)",
  278. });
  279. expect(changed.filter((entry) => entry.metadata?.source === "model").at(-1)).toMatchObject({
  280. content: "You are powered by the model named test/child-next.",
  281. });
  282. await runtime.executeTurn("unchanged child task");
  283. expect(contextEntries(runtime)).toEqual(changed);
  284. expect(requests.at(-1)!.messages[1]!.content).toEqual(initialBody);
  285. // child 初始快照只用父级传下的配置;端口只用于 cd 之后的环境探测。
  286. expect(resolveContextSources).not.toHaveBeenCalled();
  287. expect(contextSourcePort.resolveEnvironment).toHaveBeenCalledTimes(1);
  288. },
  289. );
  290. it.each([false, true])(
  291. "orders the first user turn by attachment collection order (MCS=%s)",
  292. async (mcs) => {
  293. runtime = createRuntime(
  294. { now, skillPort, contextSourcePort: instructionsPort() },
  295. { ...config, outputStyle: { name: "Learning", prompt: "Explain tradeoffs." } },
  296. { mcs },
  297. );
  298. await runtime.executeTurn("first");
  299. // 先产出全部输入附件(含每次收集的 output_style),请求前公告在其后,最后是本轮输入。
  300. const markers = [
  301. ["environment", "# Environment"],
  302. ["model", "You are powered by"],
  303. ["output_style_instructions", "# Output Style: Learning"],
  304. ["agents", "Available agent types"],
  305. ["skills", "The following skills"],
  306. ["output_style", "Learning output style is active"],
  307. ["instructions", "Codebase and user instructions"],
  308. ["session_context", "As you answer"],
  309. ["date", "Today's date is"],
  310. ] as const;
  311. const messages = requests[0]!.messages.filter((message) => message.role !== "system");
  312. const userTexts = messages.map((message) => String(message.content));
  313. const promptIndex = userTexts.indexOf("first");
  314. const kinds = userTexts.slice(0, promptIndex).map((text) => {
  315. const body = text.replace(/^<system-reminder>\n/u, "");
  316. return markers.find(([, marker]) => body.startsWith(marker))?.[0];
  317. });
  318. const userSide = ["instructions", "session_context"];
  319. expect(kinds).toEqual(mcs ? userSide : markers.map(([kind]) => kind));
  320. if (mcs) {
  321. // MCS 下其余公告在 user run 末尾合成一条 system,顺序不变,user 侧没有 skill 列表。
  322. const system = requests[0]!.messages.at(-1)!;
  323. expect(system.role).toBe("system");
  324. const positions = markers
  325. .filter(([kind]) => !userSide.includes(kind))
  326. .map(([, marker]) => String(system.content).indexOf(marker));
  327. expect(positions.every((position) => position >= 0)).toBe(true);
  328. expect(positions).toEqual([...positions].sort((a, b) => a - b));
  329. expect(userTexts.some((text) => text.includes("search things"))).toBe(false);
  330. }
  331. // 默认测试模型不合并相邻 user,紧挨输入的那一块也不补换行。
  332. expect(userTexts.slice(0, promptIndex).every((text) => !text.endsWith("\n"))).toBe(true);
  333. },
  334. );
  335. it("ends only the block right before the first input with a newline when the model merges adjacent user content", async () => {
  336. // 声明合并相邻 user 内容(foldRemindersIntoToolResults)时,紧挨输入的那一块以换行结尾,其余块不补。
  337. runtime = createRuntime({ now, skillPort, contextSourcePort: instructionsPort() }, config, {
  338. mcs: false,
  339. fold: true,
  340. });
  341. await runtime.executeTurn("first");
  342. const userTexts = requests[0]!.messages
  343. .filter((message) => message.role !== "system")
  344. .map((message) => String(message.content));
  345. const promptIndex = userTexts.indexOf("first");
  346. expect(promptIndex).toBeGreaterThan(1);
  347. expect(userTexts[promptIndex - 1]).toMatch(/<\/system-reminder>\n$/u);
  348. expect(userTexts.slice(0, promptIndex - 1).every((text) => !text.endsWith("\n"))).toBe(true);
  349. });
  350. describe("turns started by a notification", () => {
  351. const marker = "NOTIFICATION_MARKER";
  352. const startTurn = {
  353. task_notification: () =>
  354. (runtime as any).enqueueBackgroundTaskNotification({
  355. text: `<task-notification><task-id>${marker}</task-id><status>completed</status></task-notification>`,
  356. traceContext: createRootTraceContext({ sessionId }),
  357. }),
  358. subagent_reply: () =>
  359. (runtime as any).enqueueSubagentMessage({
  360. responseId: "response",
  361. agentId: "agent",
  362. agentType: "general-purpose",
  363. childSessionId: createSessionId(),
  364. childToolCallId: "child-call",
  365. summary: "progress",
  366. message: marker,
  367. traceContext: createRootTraceContext({ sessionId }),
  368. }),
  369. };
  370. const contextMarkers = [
  371. "# Environment",
  372. "You are powered by",
  373. "Available agent types",
  374. "The following skills",
  375. "Codebase and user instructions",
  376. "Today's date is",
  377. ];
  378. const waitForRequests = (count: number) =>
  379. vi.waitFor(() => expect(requests.length).toBeGreaterThanOrEqual(count));
  380. const requestText = (request: ModelRequest) =>
  381. request.messages.map((message) => JSON.stringify(message.content)).join("\n");
  382. const createNotifiedRuntime = (mcs: boolean, deps: Partial<AgentRuntimeDeps> = {}) =>
  383. createRuntime({ now, skillPort, contextSourcePort: instructionsPort(), ...deps }, config, {
  384. mcs,
  385. });
  386. it.each([
  387. ["task_notification", false],
  388. ["task_notification", true],
  389. ["subagent_reply", false],
  390. ["subagent_reply", true],
  391. ] as const)(
  392. "skips input attachments but keeps request announcements on the first %s request (MCS=%s)",
  393. async (input, mcs) => {
  394. runtime = createNotifiedRuntime(mcs);
  395. await runtime.ensureSessionPersistedForExternalActivity("initial session");
  396. startTurn[input]();
  397. await waitForRequests(1);
  398. const messages = requests[0]!.messages;
  399. const indexOf = (text: string) =>
  400. messages.findIndex((message) => JSON.stringify(message.content).includes(text));
  401. const notificationIndex = indexOf(marker);
  402. expect(messages[notificationIndex]!.role).toBe("user");
  403. // 跳过附件时只跳过输入附件;请求前公告照常运行。
  404. for (const contextMarker of contextMarkers.slice(0, 4)) {
  405. expect(requestText(requests[0]!)).not.toContain(contextMarker);
  406. }
  407. // 公告冒泡到通知之前;MCS 文本落在 user run 末尾。
  408. expect(indexOf("Codebase and user instructions")).toBeLessThan(notificationIndex);
  409. if (mcs) {
  410. expect(messages.at(-1)!.role).toBe("system");
  411. expect(indexOf("Today's date is")).toBe(messages.length - 1);
  412. } else {
  413. expect(indexOf("Today's date is")).toBeLessThan(notificationIndex);
  414. expect(notificationIndex).toBe(messages.length - 1);
  415. }
  416. expect(contextEntries(runtime).map((entry) => entry.metadata.source)).toEqual(
  417. expect.arrayContaining(["context_prefix", "date"]),
  418. );
  419. expect(
  420. contextEntries(runtime).some((entry) =>
  421. ["environment", "model", "skills_listing"].includes(entry.metadata.source),
  422. ),
  423. ).toBe(false);
  424. },
  425. );
  426. // 修复原因:空闲整批原来存成一个 "\n\n" 连接的字符串,投影时再按 <task-notification> 开头猜边界;
  427. // workflow 运行中通知不以它开头,被并进前一条通知的包装。现在每条通知是同一条消息的一个文本块,
  428. // 整条消息一个事务写入,冷恢复保留这些块,live 与冷恢复发出的块逐字节相同。
  429. it.each([true, false])(
  430. "keeps each notification of an idle batch in its own block live and after a cold resume (MCS=%s)",
  431. async (mcs) => {
  432. const bundles: { messages: { info: { source?: string }; parts: unknown[] }[] }[] = [];
  433. Object.assign(store, {
  434. async commitMessageBundle(bundle: (typeof bundles)[number]) {
  435. bundles.push(structuredClone(bundle));
  436. for (const message of bundle.messages) {
  437. store.savedMessages.push(message.info);
  438. store.savedParts.push(...message.parts);
  439. }
  440. },
  441. });
  442. let releaseFirst!: () => void;
  443. const firstHeld = new Promise<void>((resolve) => {
  444. releaseFirst = resolve;
  445. });
  446. respond.mockImplementationOnce(async () => {
  447. await firstHeld;
  448. return result;
  449. });
  450. runtime = createNotifiedRuntime(mcs);
  451. await runtime.ensureSessionPersistedForExternalActivity("initial session");
  452. const enqueue = (text: string) =>
  453. (runtime as any).enqueueBackgroundTaskNotification({
  454. text,
  455. traceContext: createRootTraceContext({ sessionId }),
  456. });
  457. const stall = formatWorkflowStallNotification({
  458. runLabel: "wf",
  459. runId: "run_1",
  460. sinceMs: 600000,
  461. });
  462. enqueue("<task-notification><task-id>first</task-id></task-notification>");
  463. await waitForRequests(1);
  464. // 第一条通知的请求进行中到达的两条,在下一次空闲时成为同一批。
  465. enqueue("<task-notification><task-id>bash-1</task-id></task-notification>");
  466. enqueue(stall);
  467. releaseFirst();
  468. await waitForRequests(2);
  469. await vi.waitFor(() => expect(runtime.getActiveTurnInfo()).toBeUndefined());
  470. const batchMessage = (request: ModelRequest) =>
  471. request.messages.find(
  472. (message) =>
  473. message.role === "user" &&
  474. Array.isArray(message.content) &&
  475. JSON.stringify(message.content).includes("bash-1"),
  476. );
  477. const live = batchMessage(requests[1]!)!;
  478. const blocks = live.content as { type: string; text: string }[];
  479. expect(blocks.map((block) => block.type)).toEqual(["text", "text"]);
  480. expect(blocks[0]!.text).toMatch(
  481. /^<system-reminder>\n\[SYSTEM NOTIFICATION - NOT USER INPUT\]/u,
  482. );
  483. expect(blocks[0]!.text).toContain("bash-1");
  484. expect(blocks[0]!.text).not.toContain("workflow-stall");
  485. expect(blocks[0]!.text.endsWith("</system-reminder>\n")).toBe(true);
  486. expect(blocks[1]!.text).toContain("<workflow-stall>");
  487. expect(blocks[1]!.text.endsWith("</system-reminder>")).toBe(true);
  488. // 一个事务写入一条消息、两个 part。
  489. const batchBundles = bundles.filter((bundle) =>
  490. bundle.messages.some((message) => message.info.source === "background_task"),
  491. );
  492. expect(batchBundles.map((bundle) => bundle.messages.map((m) => m.parts.length))).toEqual([
  493. [2],
  494. ]);
  495. const coldStore = createRecordingMessageStore();
  496. await coldStore.createSession(await store.getSession(sessionId));
  497. coldStore.savedMessages.push(...structuredClone(store.savedMessages));
  498. coldStore.savedParts.push(...structuredClone(store.savedParts));
  499. const cold = createRuntime(
  500. {
  501. now,
  502. skillPort,
  503. contextSourcePort: instructionsPort(),
  504. sessionStore: coldStore as never,
  505. },
  506. config,
  507. { mcs },
  508. );
  509. await cold.resumeFromStore();
  510. await cold.executeTurn("after resume");
  511. expect(batchMessage(requests.at(-1)!)?.content).toEqual(live.content);
  512. },
  513. );
  514. it("collects the skipped context after a tool result in the same turn", async () => {
  515. const registry = createToolRegistry();
  516. registry.register({
  517. inputSchema: {},
  518. metadata: {
  519. name: "Probe",
  520. concurrentSafe: true,
  521. destructive: false,
  522. needsApproval: false,
  523. readOnly: true,
  524. riskLevel: "low",
  525. sideEffectScope: "none",
  526. },
  527. handler: async () => "probed",
  528. });
  529. runtime = createNotifiedRuntime(false, { toolRegistry: registry });
  530. respond.mockResolvedValueOnce({
  531. ...result,
  532. text: "",
  533. finishReason: "tool-calls",
  534. toolCalls: [{ id: "probe", name: "Probe", input: {} }],
  535. });
  536. await runtime.ensureSessionPersistedForExternalActivity("initial session");
  537. startTurn.task_notification();
  538. await waitForRequests(2);
  539. const texts = requests[1]!.messages.map((message) => JSON.stringify(message.content));
  540. const notificationIndex = texts.findIndex((text) => text.includes(marker));
  541. const toolIndex = requests[1]!.messages.findIndex((message) => message.role === "tool");
  542. const environmentIndex = texts.findIndex((text) => text.includes("# Environment"));
  543. expect(notificationIndex).toBeLessThan(toolIndex);
  544. expect(environmentIndex).toBeGreaterThan(toolIndex);
  545. });
  546. it("keeps the plan-mode exit reminder pending for the next collected request", async () => {
  547. runtime = createNotifiedRuntime(false);
  548. (runtime as unknown as AgentRuntimeInternal).needsPlanModeExitReminder = true;
  549. await runtime.ensureSessionPersistedForExternalActivity("initial session");
  550. startTurn.task_notification();
  551. await waitForRequests(1);
  552. await vi.waitFor(() => expect(runtime.getActiveTurnInfo()).toBeUndefined());
  553. const planExit = () =>
  554. entries().filter((entry) => entry.metadata?.source === "plan_mode_exit");
  555. expect(planExit()).toHaveLength(0);
  556. expect((runtime as unknown as AgentRuntimeInternal).needsPlanModeExitReminder).toBe(true);
  557. await runtime.executeTurn("next");
  558. expect((runtime as unknown as AgentRuntimeInternal).needsPlanModeExitReminder).toBe(false);
  559. expect(planExit()).toHaveLength(1);
  560. });
  561. });
  562. it("announces output style instructions after the model once per change and resets when cleared", async () => {
  563. runtime = createRuntime(
  564. { now, skillPort },
  565. { ...config, outputStyle: { name: "Learning", prompt: "Explain tradeoffs.\n" } },
  566. );
  567. await runtime.executeTurn("first");
  568. await runtime.executeTurn("second");
  569. runtime.updateConfig({ outputStyle: { name: "Learning", prompt: "Explain briefly." } });
  570. await runtime.executeTurn("third");
  571. runtime.updateConfig({ outputStyle: undefined });
  572. await runtime.executeTurn("fourth");
  573. await runtime.executeTurn("fifth");
  574. const attachments = entries().filter((entry) => entry.kind === "attachment");
  575. expect(
  576. attachments
  577. .filter((entry) => entry.metadata.source === "output_style_instructions")
  578. .map((entry) => entry.content),
  579. ).toEqual([
  580. "# Output Style: Learning\nExplain tradeoffs.",
  581. "# Output Style: Learning\nExplain briefly.",
  582. "The output style was reset to the default. Respond in your usual style.",
  583. ]);
  584. // 输入附件顺序:environment → model → output style 指令。
  585. const order = attachments.map((entry) => entry.metadata.source);
  586. expect(order.indexOf("output_style_instructions")).toBe(order.indexOf("model") + 1);
  587. // system 不再携带 output style 指令。
  588. expect(
  589. JSON.stringify(requests[0]!.messages.slice(0, 3).map((message) => message.content)),
  590. ).not.toContain("# Output Style");
  591. });
  592. it("restates the latest output style after compact unless the kept tail has one or it was reset", () => {
  593. runtime = createRuntime({ now, skillPort }, config);
  594. const internal = runtime as unknown as AgentRuntimeInternal;
  595. // output style 的重述不受 env_info 门控。
  596. internal.latestContextBuildResult = { sections: [] } as never;
  597. const style = systemReminderAttachmentEntry(
  598. "output_style_instructions",
  599. "# Output Style: Learning\nExplain tradeoffs.",
  600. );
  601. const reset = systemReminderAttachmentEntry(
  602. "output_style_instructions",
  603. "The output style was reset to the default. Respond in your usual style.",
  604. );
  605. expect(restateContextAfterCompact(internal, [style], []).map((entry) => entry.content)).toEqual(
  606. [style.content],
  607. );
  608. expect(restateContextAfterCompact(internal, [style], [style])).toEqual([]);
  609. expect(restateContextAfterCompact(internal, [style, reset], [])).toEqual([]);
  610. });
  611. it("derives the plan-mode exit reminder from history after resume", async () => {
  612. runtime = createRuntime({ now, skillPort, contextSourcePort: instructionsPort() }, config);
  613. const internal = runtime as unknown as AgentRuntimeInternal;
  614. await runtime.executeTurn("planned");
  615. internal.messageHistory.addEntries([
  616. systemReminderAttachmentEntry("runtime_mode", "Plan mode is active."),
  617. { message: { role: "assistant", content: "plan ready" } },
  618. ]);
  619. // 冷恢复后内存标记为 false;按历史中最近的 plan 提醒判断。
  620. internal.needsPlanModeExitReminder = false;
  621. await runtime.executeTurn("build it");
  622. await runtime.executeTurn("again");
  623. const planExit = entries().filter((entry) => entry.metadata?.source === "plan_mode_exit");
  624. expect(planExit).toHaveLength(1);
  625. });
  626. it.each([undefined, CompactTrigger.Manual, CompactTrigger.Reactive])(
  627. "restores context without duplicate announcements after compact=%s",
  628. async (trigger) => {
  629. runtime = createRuntime({ now, skillPort, contextSourcePort: instructionsPort() }, config);
  630. await runtime.executeTurn("first");
  631. const initialContext = contextEntries(runtime);
  632. expect(initialContext.map((entry) => entry.metadata?.source)).toEqual([...sources]);
  633. await runtime.executeTurn("second");
  634. expect(contextEntries(runtime)).toEqual(initialContext);
  635. const announcements = store.savedMessages.filter(isAnnouncementRecord);
  636. expect(announcements).toHaveLength(6);
  637. for (const announcement of announcements) {
  638. // 顶层 source 不写新值:旧版本 App 按封闭列表校验,会拒绝整个会话。
  639. expect(announcement.source).toBeUndefined();
  640. expect(announcement.semantics?.source).toBe(runtimeSourceOf(announcement));
  641. expect(announcement).toMatchObject({
  642. semantics: {
  643. uiVisibility: "hidden",
  644. transcriptVisibility: "hidden",
  645. providerVisibility: "visible",
  646. },
  647. });
  648. }
  649. if (trigger) {
  650. const compacted = await compact(runtime, trigger);
  651. expect(compacted.outcome).toBe("compacted");
  652. await runtime.executeTurn("continue after compact");
  653. // 每个来源仍只宣告一次;顺序按 compact 后布局(见 "lays out the post-compact context")。
  654. const bySource = (items: ReturnType<typeof contextEntries>) =>
  655. [...items].sort((a, b) => a.metadata.source.localeCompare(b.metadata.source));
  656. expect(bySource(contextEntries(runtime))).toEqual(bySource(initialContext));
  657. }
  658. const liveContext = contextEntries(runtime);
  659. const { cold, coldStore } = await coldRuntimeWith(skillPort, {
  660. ...config,
  661. envInfo: { ...config.envInfo!, gitBranch: "new-probe-must-not-replace-history" },
  662. });
  663. const before = coldStore.savedMessages.filter(isAnnouncementRecord).length;
  664. await cold.executeTurn("resumed");
  665. expect(contextEntries(cold)).toEqual(liveContext);
  666. expect(coldStore.savedMessages.filter(isAnnouncementRecord)).toHaveLength(before);
  667. },
  668. );
  669. const withSkills = (
  670. skills: (base: Awaited<ReturnType<SkillPort["discoverSkills"]>>["skills"]) => typeof base,
  671. ): SkillPort => ({
  672. ...skillPort,
  673. async discoverSkills(request, options) {
  674. const outcome = await skillPort.discoverSkills(request, options);
  675. const next = skills(outcome.skills);
  676. return { ...outcome, skills: next, totalDiscovered: next.length };
  677. },
  678. });
  679. const withReviewSkill = withSkills((base) => [
  680. ...base,
  681. {
  682. ...base[0]!,
  683. name: "review",
  684. description: "review things",
  685. path: "/workspace/.agents/skills/review/SKILL.md",
  686. directory: "/workspace/.agents/skills/review",
  687. },
  688. ]);
  689. const skillsListingRecordTexts = (value: ReturnType<typeof createRecordingMessageStore>) =>
  690. value.savedParts
  691. .filter((part) => part.metadata?.runtimeMessage?.source === "skills_listing")
  692. .map((part) => String((part as { text?: string }).text));
  693. const historyIndexOfListing = (value: ReturnType<typeof createTestAgentRuntime>) =>
  694. (value as unknown as AgentRuntimeInternal).messageHistory
  695. .toRuntimeEntries()
  696. .findIndex(
  697. (entry) => entry.kind === "attachment" && entry.metadata.source === "skills_listing",
  698. );
  699. it("updates the restored skill listing in place when a resumed session finds a changed catalog", async () => {
  700. runtime = createRuntime({ now, skillPort, contextSourcePort: instructionsPort() }, config);
  701. await runtime.executeTurn("first");
  702. const liveIndex = historyIndexOfListing(runtime);
  703. const { cold, coldStore } = await coldRuntimeWith(withReviewSkill);
  704. const storedTexts = skillsListingRecordTexts(coldStore);
  705. await cold.executeTurn("resumed");
  706. await cold.executeTurn("again");
  707. // 目录变化不插入新公告:原位置上的那一条换成当前目录,之后不再变化。
  708. const listings = contextEntries(cold).filter(
  709. (entry) => entry.metadata.source === "skills_listing",
  710. );
  711. expect(listings).toHaveLength(1);
  712. expect(listings[0]!.content).toContain("- review: review things");
  713. expect(listings[0]!.content).toContain("- search: search things");
  714. expect(historyIndexOfListing(cold)).toBe(liveIndex);
  715. const lastRequest = JSON.stringify(requests.at(-1)?.messages);
  716. expect(lastRequest.split("- review: review things")).toHaveLength(2);
  717. // 只改内存:库里的记录不变,也没有新增 skill 列表记录。
  718. expect(skillsListingRecordTexts(coldStore)).toEqual(storedTexts);
  719. // 先确认确实存过一条,否则空数组上的 every 恒为真。
  720. expect(storedTexts).toHaveLength(1);
  721. expect(storedTexts.every((text) => !text.includes("review"))).toBe(true);
  722. });
  723. it("drops the restored skill listing when a resumed session finds no skills", async () => {
  724. runtime = createRuntime({ now, skillPort, contextSourcePort: instructionsPort() }, config);
  725. await runtime.executeTurn("first");
  726. const { cold, coldStore } = await coldRuntimeWith(withSkills(() => []));
  727. const storedTexts = skillsListingRecordTexts(coldStore);
  728. await cold.executeTurn("resumed");
  729. // 目录清空时没有新内容可宣告,旧名单必须从历史里去掉,不能继续发给模型。
  730. expect(contextEntries(cold).some((entry) => entry.metadata.source === "skills_listing")).toBe(
  731. false,
  732. );
  733. expect(JSON.stringify(requests.at(-1)?.messages)).not.toContain(
  734. "The following skills are available",
  735. );
  736. expect(skillsListingRecordTexts(coldStore)).toEqual(storedTexts);
  737. });
  738. it("applies the current catalog again when a rewind reloads history from the store", async () => {
  739. runtime = createRuntime({ now, skillPort, contextSourcePort: instructionsPort() }, config);
  740. await runtime.executeTurn("first");
  741. const { cold, coldStore } = await coldRuntimeWith(withReviewSkill);
  742. await cold.executeTurn("resumed");
  743. await cold.executeTurn("again");
  744. const againPart = coldStore.savedParts.find(
  745. (part) => (part as { text?: string }).text === "again",
  746. );
  747. expect(againPart).toBeDefined();
  748. await cold.rewindConversationToMessage({
  749. events: [],
  750. targetMessageId: againPart!.messageID,
  751. traceContext: createRootTraceContext({ sessionId }),
  752. });
  753. await cold.executeTurn("edited");
  754. // rewind 从库重新加载历史,库里仍是旧名单;加载后同样按当前目录原位更新。
  755. const listings = contextEntries(cold).filter(
  756. (entry) => entry.metadata.source === "skills_listing",
  757. );
  758. expect(listings).toHaveLength(1);
  759. expect(listings[0]!.content).toContain("- review: review things");
  760. expect(JSON.stringify(requests.at(-1)?.messages)).toContain("- review: review things");
  761. });
  762. describe("restored instructions after a history load", () => {
  763. const cliStorageRoot = "/storage/cli";
  764. const memoryConfig: Partial<AgentRuntimeConfig> = {
  765. ...config,
  766. memory: { cliStorageRoot, enabled: true, use: true },
  767. };
  768. const indexPath = join(
  769. resolveProjectMemoryRoot({ cliStorageRoot, workspacePath: "/workspace" }),
  770. "MEMORY.md",
  771. );
  772. const oldIndex = "- [Old policy](old-policy.md) — announced before the restart";
  773. const newIndex = "- [New policy](new-policy.md) — written to disk after the announcement";
  774. const instructionTexts = (value: ReturnType<typeof createTestAgentRuntime>) =>
  775. contextEntries(value)
  776. .filter((entry) => entry.metadata.source === "context_prefix")
  777. .map((entry) => entry.content);
  778. const instructionRecordTexts = (value: ReturnType<typeof createRecordingMessageStore>) =>
  779. value.savedParts
  780. .filter((part) => part.metadata?.runtimeMessage?.source === "context_prefix")
  781. .map((part) => String((part as { text?: string }).text));
  782. const announceOldIndexThenChangeDisk = async () => {
  783. const files = new MemoryFileSystem({ [indexPath]: oldIndex });
  784. runtime = createRuntime(
  785. { now, skillPort, contextSourcePort: instructionsPort(), fileSystemPort: files },
  786. memoryConfig,
  787. );
  788. await runtime.executeTurn("first");
  789. expect(instructionTexts(runtime)).toEqual([expect.stringContaining(oldIndex)]);
  790. files.files[indexPath] = newIndex;
  791. return files;
  792. };
  793. it("updates the restored instructions in place to the Memory index read on resume", async () => {
  794. const files = await announceOldIndexThenChangeDisk();
  795. const { cold, coldStore } = await coldRuntimeWith(skillPort, memoryConfig, {
  796. fileSystemPort: files,
  797. });
  798. const storedTexts = instructionRecordTexts(coldStore);
  799. await cold.executeTurn("resumed");
  800. // 修复原因:恢复的旧公告原样发给模型,读文件状态却记录磁盘上的新索引;
  801. // Write 的新鲜度检查因此放行,模型按看到的旧索引写入,会覆盖它没见过的新索引。
  802. expect(instructionTexts(cold)).toEqual([expect.stringContaining(newIndex)]);
  803. const lastRequest = JSON.stringify(requests.at(-1)?.messages);
  804. expect(lastRequest).toContain(newIndex);
  805. expect(lastRequest).not.toContain(oldIndex);
  806. const readState = (cold as unknown as AgentRuntimeInternal).readFileState.get(
  807. createReadFileStatePathKey(indexPath),
  808. );
  809. expect(readState?.content).toBe(newIndex);
  810. // 只改内存:库里的记录保持第一次的内容,也没有新增指令公告。
  811. expect(instructionRecordTexts(coldStore)).toEqual(storedTexts);
  812. // 先确认确实存过一条,否则空数组上的 every 恒为真。
  813. expect(storedTexts).toHaveLength(1);
  814. expect(storedTexts.every((text) => text.includes(oldIndex))).toBe(true);
  815. // 模型看到的内容与读文件状态一致,Write 按这份内容检查。录制 store 没有项目权限规则。
  816. Object.assign(coldStore, { getProjectPermission: async () => null });
  817. const write = await cold.getToolExecutor().execute({
  818. id: createToolCallId("write-memory-index-after-resume"),
  819. input: { content: `${newIndex}\n- [Added](added.md) — added`, file_path: indexPath },
  820. name: "Write",
  821. });
  822. expect(write.success).toBe(true);
  823. expect(files.files[indexPath]).toBe(`${newIndex}\n- [Added](added.md) — added`);
  824. });
  825. it("keeps the current Memory index when a rewind reloads the old record from the store", async () => {
  826. const files = await announceOldIndexThenChangeDisk();
  827. const { cold, coldStore } = await coldRuntimeWith(skillPort, memoryConfig, {
  828. fileSystemPort: files,
  829. });
  830. await cold.executeTurn("resumed");
  831. await cold.executeTurn("again");
  832. const againPart = coldStore.savedParts.find(
  833. (part) => (part as { text?: string }).text === "again",
  834. );
  835. expect(againPart).toBeDefined();
  836. await cold.rewindConversationToMessage({
  837. events: [],
  838. targetMessageId: againPart!.messageID,
  839. traceContext: createRootTraceContext({ sessionId }),
  840. });
  841. await cold.executeTurn("edited");
  842. // rewind 从库重新加载历史,库里仍是旧索引;加载后同样原位换成当前内容。
  843. expect(instructionTexts(cold)).toEqual([expect.stringContaining(newIndex)]);
  844. expect(JSON.stringify(requests.at(-1)?.messages)).not.toContain(oldIndex);
  845. });
  846. it("drops the restored instructions when the resumed runtime has none", async () => {
  847. await announceOldIndexThenChangeDisk();
  848. const { cold } = await coldRuntimeWith(skillPort, config, {
  849. contextSourcePort: {
  850. ...instructionsPort(),
  851. async resolveContextSources() {
  852. return { workingDirectory: "/workspace", envInfo: config.envInfo!, diagnostics: [] };
  853. },
  854. },
  855. });
  856. await cold.executeTurn("resumed");
  857. // 当前没有指令文件和 Memory 索引时没有新内容可宣告,旧公告必须从历史里去掉。
  858. expect(instructionTexts(cold)).toEqual([]);
  859. expect(JSON.stringify(requests.at(-1)?.messages)).not.toContain(oldIndex);
  860. });
  861. });
  862. it.each([CompactTrigger.Reactive, CompactTrigger.Manual])(
  863. "lays out the post-compact context in announcement order after compact=%s",
  864. async (trigger) => {
  865. runtime = createRuntime({ now, skillPort, contextSourcePort: instructionsPort() }, config);
  866. await runtime.executeTurn("first");
  867. await runtime.executeTurn("second");
  868. const compacted = await compact(runtime, trigger);
  869. expect(compacted.outcome).toBe("compacted");
  870. const layout = (value: ReturnType<typeof createTestAgentRuntime>) =>
  871. (value as unknown as AgentRuntimeInternal).messageHistory
  872. .toRuntimeEntries()
  873. .filter((entry) => entry.kind === "attachment" || entry.message.role !== "system")
  874. .map((entry) =>
  875. entry.kind === "attachment"
  876. ? entry.metadata.source
  877. : String(entry.message.content).startsWith("This session is being continued")
  878. ? "summary"
  879. : entry.message.role,
  880. );
  881. const live = layout(runtime);
  882. const summaryIndex = live.indexOf("summary");
  883. const tail = live.slice(summaryIndex + 1);
  884. // 保留段非空时,请求前公告放在 summary 之前,且不重复保留段已有的来源。
  885. const leading = live.slice(0, summaryIndex);
  886. const requestSources = ["context_prefix", "session_context", "date"];
  887. if (trigger === CompactTrigger.Reactive) {
  888. expect(leading).toEqual(requestSources.filter((source) => !tail.includes(source)));
  889. } else {
  890. expect(leading).toEqual([]);
  891. }
  892. // compaction 附件末尾:agent listing → skill 列表 → environment → model。
  893. // compaction 必须产出 skill 列表,否则 compact 后第一次请求看不到 skill 名单。
  894. expect(tail.slice(-4)).toEqual([
  895. "agent_listing_delta",
  896. "skills_listing",
  897. "environment",
  898. "model",
  899. ]);
  900. for (const source of ["skills_listing", "environment", "model"]) {
  901. expect(tail.filter((item) => item === source)).toHaveLength(1);
  902. }
  903. // 存储顺序与 live 一致:公告写在 summary 之前,并由 summary 的 compaction part 声明。
  904. const summaryRow = store.savedMessages.findIndex(
  905. (message) => message.semantics?.kind === "compact_summary",
  906. );
  907. const declared =
  908. store.savedParts.find((part) => part.type === "compaction" && part.compactBoundary)
  909. ?.metadata?.compactLeadingMessageIds ?? [];
  910. expect(declared).toHaveLength(leading.length);
  911. expect(
  912. store.savedMessages
  913. .slice(summaryRow - declared.length, summaryRow)
  914. .map((message) => message.id),
  915. ).toEqual(declared);
  916. // 冷恢复得到相同布局。
  917. const { cold } = await coldRuntimeWith();
  918. expect(layout(cold)).toEqual(live);
  919. },
  920. );
  921. it("does not place a date before the summary when the kept tail already has one", () => {
  922. // 保留段里已有 date 类型的公告(哪怕已过期)时,summary 之前不放日期;
  923. // 之后的请求以保留段里的旧日期为基准,在末尾宣告一次日期变化。
  924. runtime = createRuntime(
  925. { now: () => new Date(2026, 9, 15, 0, 10), skillPort, contextSourcePort: instructionsPort() },
  926. config,
  927. );
  928. const internal = runtime as unknown as AgentRuntimeInternal;
  929. const kept = [
  930. { message: { role: "assistant" as const, content: "Working on it." } },
  931. systemReminderAttachmentEntry("date", "Today's date is 2026-10-14."),
  932. { message: { role: "assistant" as const, content: "Done." } },
  933. ];
  934. const leading = buildCompactLeadingAnnouncements(internal, kept);
  935. expect(leading.map((entry) => entry.metadata.source)).not.toContain("date");
  936. // 普通请求前公告不受影响:同一份历史仍宣告日期变化。
  937. expect(
  938. buildRequestAnnouncements(internal, kept).map((entry) => entry.metadata.source),
  939. ).toContain("date");
  940. });
  941. it("does not invent environment or model notices after compact when history has none", () => {
  942. // 只重述 compact 前历史里真有的公告;历史里没有时由下一次请求的收集补上。
  943. runtime = createRuntime({ now, skillPort, contextSourcePort: instructionsPort() }, config);
  944. const internal = runtime as unknown as AgentRuntimeInternal;
  945. internal.latestContextBuildResult = {
  946. sections: [{ source: "env_info" }],
  947. } as never;
  948. const restated = restateContextAfterCompact(
  949. internal,
  950. [{ message: { role: "user", content: "legacy history" }, metadata: { source: "real_user" } }],
  951. [],
  952. );
  953. expect(restated).toEqual([]);
  954. });
  955. it("commits announcements, summary and attachments in one store transaction", async () => {
  956. const bundles: { messages: { info: { id: string }; parts: unknown[] }[] }[] = [];
  957. const saveMessage = vi.spyOn(store, "saveMessage");
  958. Object.assign(store, {
  959. async commitMessageBundle(bundle: (typeof bundles)[number]) {
  960. bundles.push(structuredClone(bundle));
  961. for (const message of bundle.messages) {
  962. store.savedMessages.push(message.info);
  963. store.savedParts.push(...message.parts);
  964. }
  965. },
  966. });
  967. runtime = createRuntime({ now, skillPort, contextSourcePort: instructionsPort() }, config);
  968. await runtime.executeTurn("first");
  969. await runtime.executeTurn("second");
  970. const savedBefore = saveMessage.mock.calls.length;
  971. const compacted = await compact(runtime, CompactTrigger.Reactive);
  972. expect(compacted.outcome).toBe("compacted");
  973. expect(bundles).toHaveLength(1);
  974. const bundleIds = bundles[0]!.messages.map((message) => message.info.id);
  975. const committed = new Set(bundleIds);
  976. // 整组记录只经过事务入口,不再逐条写入。
  977. expect(
  978. saveMessage.mock.calls.slice(savedBefore).filter(([info]) => committed.has(info.id)),
  979. ).toEqual([]);
  980. const summaryIndex = bundles[0]!.messages.findIndex((message) =>
  981. message.parts.some((part) => (part as { type?: string }).type === "compaction"),
  982. );
  983. const declared = (
  984. bundles[0]!.messages[summaryIndex]!.parts.find(
  985. (part) => (part as { type?: string }).type === "compaction",
  986. ) as { metadata?: { compactLeadingMessageIds?: string[] } }
  987. ).metadata?.compactLeadingMessageIds;
  988. expect(declared?.length).toBeGreaterThan(0);
  989. expect(bundleIds.slice(0, summaryIndex)).toEqual(declared);
  990. expect(bundleIds.length).toBeGreaterThan(summaryIndex + 1);
  991. });
  992. it.each([CompactTrigger.Reactive, CompactTrigger.Manual])(
  993. "re-reads Git for the session context re-announced after compact=%s",
  994. async (trigger) => {
  995. const resolveGitContext = vi.fn(async () => ({
  996. ...config.envInfo!,
  997. gitBranch: "after-compact",
  998. }));
  999. runtime = createRuntime(
  1000. { now, skillPort, contextSourcePort: { ...instructionsPort(), resolveGitContext } },
  1001. config,
  1002. );
  1003. await runtime.executeTurn("first");
  1004. await runtime.executeTurn("second");
  1005. expect(resolveGitContext).not.toHaveBeenCalled();
  1006. await compact(runtime, trigger);
  1007. await runtime.executeTurn("after compact");
  1008. // 历史中没有 session_context 时重新读取 git,compact 后的快照是最新的。
  1009. expect(resolveGitContext).toHaveBeenCalledTimes(1);
  1010. const gitContext = contextEntries(runtime).filter(
  1011. (entry) => entry.metadata.source === "session_context",
  1012. );
  1013. expect(gitContext).toHaveLength(1);
  1014. expect(gitContext[0]!.content).toContain("after-compact");
  1015. expect(gitContext[0]!.content).not.toContain("original");
  1016. // 只刷新会话上下文;system 前缀不含 Git 事实,字节不变。
  1017. const prefix = (request: ModelRequest) =>
  1018. request.messages.slice(
  1019. 0,
  1020. request.messages.findIndex((message) => message.role !== "system"),
  1021. );
  1022. expect(prefix(requests.at(-1)!)).toEqual(prefix(requests[0]!));
  1023. },
  1024. );
  1025. it("keeps the re-read Git only inside the compacted history, so a failed compaction leaves none", async () => {
  1026. const resolveGitContext = vi.fn(async () => ({
  1027. ...config.envInfo!,
  1028. gitBranch: "after-compact",
  1029. }));
  1030. let failCommit = true;
  1031. Object.assign(store, {
  1032. async commitMessageBundle(bundle: { messages: { info: never; parts: never[] }[] }) {
  1033. if (failCommit) throw new Error("disk full");
  1034. for (const message of bundle.messages) {
  1035. store.savedMessages.push(message.info);
  1036. store.savedParts.push(...message.parts);
  1037. }
  1038. },
  1039. });
  1040. runtime = createRuntime(
  1041. { now, skillPort, contextSourcePort: { ...instructionsPort(), resolveGitContext } },
  1042. config,
  1043. );
  1044. await runtime.executeTurn("first");
  1045. await runtime.executeTurn("second");
  1046. const internal = runtime as unknown as {
  1047. config: { envInfo?: { gitBranch?: string } };
  1048. contextSourceSnapshot?: { envInfo: { gitBranch?: string } };
  1049. };
  1050. const announcedGit = () =>
  1051. contextEntries(runtime)
  1052. .filter((entry) => entry.metadata.source === "session_context")
  1053. .map((entry) => entry.content);
  1054. await expect(compact(runtime, CompactTrigger.Reactive)).rejects.toThrow("disk full");
  1055. // 写库失败:历史没有替换,仍是原来的公告;runtime 没有任何新的 Git 事实。
  1056. expect(resolveGitContext).toHaveBeenCalledTimes(1);
  1057. expect(announcedGit()).toEqual([expect.stringContaining("original")]);
  1058. expect(internal.contextSourceSnapshot?.envInfo.gitBranch).toBe("original");
  1059. expect(internal.config.envInfo?.gitBranch).toBe("original");
  1060. failCommit = false;
  1061. await compact(runtime, CompactTrigger.Reactive);
  1062. expect(announcedGit()).toEqual([expect.stringContaining("after-compact")]);
  1063. // 新的 Git 只存在于 compact 后的公告里;会话快照保持会话起始值。
  1064. expect(internal.contextSourceSnapshot?.envInfo.gitBranch).toBe("original");
  1065. expect(internal.config.envInfo?.gitBranch).toBe("original");
  1066. });
  1067. describe("Git session context decided once per window, only by history", () => {
  1068. const nonRepository = { ...config.envInfo!, isGitRepository: false, gitStatus: "not_repo" };
  1069. const repositories = new Set<string>();
  1070. const resolveGitContext = vi.fn(
  1071. async ({ workingDirectory }: Pick<ContextSourceRequest, "workingDirectory">) =>
  1072. repositories.has(workingDirectory)
  1073. ? { ...config.envInfo!, gitBranch: `repo:${workingDirectory}` }
  1074. : { isGitRepository: false, gitStatus: "not_repo" as const },
  1075. );
  1076. const resolveEnvironment = vi.fn(
  1077. async ({ workingDirectory }: Pick<ContextSourceRequest, "workingDirectory">) => ({
  1078. ...config.envInfo!,
  1079. cwd: workingDirectory,
  1080. isGitRepository: repositories.has(workingDirectory),
  1081. }),
  1082. );
  1083. const portStartingIn = (
  1084. envInfo: NonNullable<AgentRuntimeConfig["envInfo"]>,
  1085. ): ContextSourcePort => ({
  1086. ...instructionsPort(),
  1087. async resolveContextSources() {
  1088. return { workingDirectory: "/workspace", envInfo, diagnostics: [] };
  1089. },
  1090. resolveEnvironment,
  1091. resolveGitContext,
  1092. });
  1093. const announcedGit = (value = runtime) =>
  1094. contextEntries(value)
  1095. .filter((entry) => entry.metadata.source === "session_context")
  1096. .map((entry) => entry.content);
  1097. const environments = (value: ReturnType<typeof createTestAgentRuntime>) =>
  1098. contextEntries(value)
  1099. .filter((entry) => entry.metadata.source === "environment")
  1100. .map((entry) => entry.content);
  1101. const cd = (value: ReturnType<typeof createTestAgentRuntime>, directory: string) => {
  1102. (value as unknown as AgentRuntimeInternal).workingDirectory = directory;
  1103. };
  1104. beforeEach(() => {
  1105. repositories.clear();
  1106. resolveGitContext.mockClear();
  1107. resolveEnvironment.mockClear();
  1108. });
  1109. it("decides once per window: a non-repository start reads nothing later, also after moving into a repository", async () => {
  1110. runtime = createRuntime({ now, contextSourcePort: portStartingIn(nonRepository) }, config);
  1111. await runtime.executeTurn("first");
  1112. await runtime.executeTurn("second");
  1113. await runtime.executeTurn("third");
  1114. // 修复原因:起始快照来自文件系统查找,"不是仓库"是确定结论;原来不记住,第二个请求
  1115. // 还要再检查一次。现在首个请求用快照并记住目录,同一目录之后不再检查。
  1116. expect(resolveGitContext).not.toHaveBeenCalled();
  1117. expect(announcedGit()).toEqual([]);
  1118. repositories.add("/workspace/repo");
  1119. cd(runtime, "/workspace/repo");
  1120. await runtime.executeTurn("fourth");
  1121. await runtime.executeTurn("fifth");
  1122. // 本窗口已在首个请求决定过(没有 Git),进入仓库也不再读;环境公告照常报告新目录。
  1123. expect(resolveGitContext).not.toHaveBeenCalled();
  1124. expect(announcedGit()).toEqual([]);
  1125. expect(environments(runtime).at(-1)).toContain("Is a git repository: true (was false)");
  1126. await compact(runtime, CompactTrigger.Manual);
  1127. await runtime.executeTurn("next window");
  1128. // compaction 开始新窗口,新窗口的首个请求按当前目录读取。
  1129. expect(resolveGitContext).toHaveBeenCalledTimes(1);
  1130. expect(announcedGit()).toEqual([expect.stringContaining("repo:/workspace/repo")]);
  1131. });
  1132. it("reads Git again in a new window and remembers a directory that is not a repository", async () => {
  1133. runtime = createRuntime({ now, contextSourcePort: portStartingIn(config.envInfo!) }, config);
  1134. await runtime.executeTurn("first");
  1135. expect(announcedGit()).toEqual([expect.stringContaining("original")]);
  1136. await compact(runtime, CompactTrigger.Manual);
  1137. cd(runtime, "/scratch");
  1138. await runtime.executeTurn("outside repository");
  1139. await runtime.executeTurn("still outside");
  1140. // compaction 删掉了旧公告;新窗口的首个请求检查一次,非仓库目录记住。
  1141. expect(resolveGitContext).toHaveBeenCalledTimes(1);
  1142. expect(announcedGit()).toEqual([]);
  1143. await compact(runtime, CompactTrigger.Manual);
  1144. await runtime.executeTurn("outside again");
  1145. // 记住的目录在之后的窗口也不再检查。
  1146. expect(resolveGitContext).toHaveBeenCalledTimes(1);
  1147. repositories.add("/workspace");
  1148. cd(runtime, "/workspace");
  1149. await runtime.executeTurn("back in repository");
  1150. expect(resolveGitContext).toHaveBeenCalledTimes(1);
  1151. expect(announcedGit()).toEqual([]);
  1152. await compact(runtime, CompactTrigger.Manual);
  1153. await runtime.executeTurn("repository window");
  1154. expect(resolveGitContext).toHaveBeenCalledTimes(2);
  1155. expect(announcedGit()).toEqual([expect.stringContaining("repo:/workspace")]);
  1156. });
  1157. it("lets a compaction that keeps a tail decide again although the tail holds a date announcement", async () => {
  1158. let today = new Date(2026, 9, 14, 12);
  1159. runtime = createRuntime(
  1160. { now: () => today, contextSourcePort: portStartingIn(nonRepository) },
  1161. { ...config, compact: { enabled: true } },
  1162. );
  1163. await runtime.executeTurn("first");
  1164. await runtime.executeTurn("second");
  1165. repositories.add("/workspace/repo");
  1166. cd(runtime, "/workspace/repo");
  1167. today = new Date(2026, 9, 15, 12);
  1168. // 第三个输入的请求前公告(日期变化)先写入历史,模型随后报告上下文超限,触发 reactive compaction。
  1169. // 保留段是最后一个 assistant 之后的内容,带着这条日期变化公告。
  1170. respond.mockRejectedValueOnce(
  1171. Object.assign(new Error("provider context window exceeded"), {
  1172. code: ModelErrorCode.ModelContextExceeded,
  1173. }),
  1174. );
  1175. await runtime.executeTurn("third");
  1176. // date 只表示请求前已决定;compaction 为压缩后的历史重新决定,仍按当前目录读取。
  1177. expect(
  1178. contextEntries(runtime)
  1179. .filter((entry) => entry.metadata.source === "date")
  1180. .map((entry) => entry.content),
  1181. ).toEqual([expect.stringContaining("The date has changed")]);
  1182. expect(resolveGitContext).toHaveBeenCalledTimes(1);
  1183. expect(announcedGit()).toEqual([expect.stringContaining("repo:/workspace/repo")]);
  1184. });
  1185. it("continues the restored window after a cold resume: membership is re-read for the environment, Git waits for the next window", async () => {
  1186. runtime = createRuntime({ now, contextSourcePort: portStartingIn(nonRepository) }, config);
  1187. await runtime.executeTurn("first");
  1188. expect(announcedGit()).toEqual([]);
  1189. // 会话中途 git init:live runtime 不再检查,环境与 Git 都不变。
  1190. repositories.add("/workspace");
  1191. await runtime.executeTurn("live after git init");
  1192. expect(resolveEnvironment).not.toHaveBeenCalled();
  1193. expect(resolveGitContext).not.toHaveBeenCalled();
  1194. expect(environments(runtime)).toHaveLength(1);
  1195. const coldStore = createRecordingMessageStore();
  1196. await coldStore.createSession(await store.getSession(sessionId));
  1197. coldStore.savedMessages.push(...structuredClone(store.savedMessages));
  1198. coldStore.savedParts.push(...structuredClone(store.savedParts));
  1199. const cold = createRuntime(
  1200. { now, contextSourcePort: portStartingIn(nonRepository), sessionStore: coldStore as never },
  1201. config,
  1202. );
  1203. await cold.resumeFromStore();
  1204. await cold.executeTurn("after resume");
  1205. await cold.executeTurn("again");
  1206. // 修复原因:非仓库窗口没有 Git 公告,"不是仓库"原来只记在 runtime 内存里;冷恢复后的新
  1207. // runtime 没有这份记忆,又读 Git 并宣告,而环境公告仍写 "Is a git repository: false"。
  1208. // 现在恢复的窗口沿用历史,不读 Git;新 runtime 只重读一次是否仓库,在环境公告里报告变化。
  1209. expect(resolveGitContext).not.toHaveBeenCalled();
  1210. expect(announcedGit(cold)).toEqual([]);
  1211. expect(resolveEnvironment).toHaveBeenCalledTimes(1);
  1212. expect(environments(cold).slice(1)).toEqual([
  1213. "# Environment update\n - Is a git repository: true (was false)",
  1214. ]);
  1215. await compact(cold, CompactTrigger.Manual);
  1216. await cold.executeTurn("next window");
  1217. expect(resolveGitContext).toHaveBeenCalledTimes(1);
  1218. expect(announcedGit(cold)).toEqual([expect.stringContaining("repo:/workspace")]);
  1219. });
  1220. it("does not use a resumed session's stored snapshot as the prefetch when the restored window has not decided", async () => {
  1221. runtime = createRuntime({ now, contextSourcePort: portStartingIn(nonRepository) }, config);
  1222. await runtime.executeTurn("first");
  1223. repositories.add("/workspace");
  1224. // 恢复的历史还没有做过决定(没有 date 公告,例如旧版本写下的历史)。
  1225. const coldStore = createRecordingMessageStore();
  1226. await coldStore.createSession(await store.getSession(sessionId));
  1227. const undecided = store.savedMessages.filter(
  1228. (message) => runtimeSourceOf(message) !== "date",
  1229. );
  1230. const kept = new Set(undecided.map((message) => message.id));
  1231. coldStore.savedMessages.push(...structuredClone(undecided));
  1232. coldStore.savedParts.push(
  1233. ...structuredClone(store.savedParts.filter((part) => kept.has(part.messageID))),
  1234. );
  1235. const cold = createRuntime(
  1236. { now, contextSourcePort: portStartingIn(nonRepository), sessionStore: coldStore as never },
  1237. config,
  1238. );
  1239. await cold.resumeFromStore();
  1240. await cold.executeTurn("after resume");
  1241. // 存储里的快照不是刚读的,不能当预取;恢复后的首个请求读一次 Git。
  1242. expect(resolveGitContext).toHaveBeenCalledTimes(1);
  1243. expect(announcedGit(cold)).toEqual([expect.stringContaining("repo:/workspace")]);
  1244. expect(environments(cold).at(-1)).toBe(
  1245. "# Environment update\n - Is a git repository: true (was false)",
  1246. );
  1247. });
  1248. });
  1249. it("appends changed cwd once and keeps the initial Git snapshot", async () => {
  1250. runtime = createRuntime({ now }, config);
  1251. await runtime.executeTurn("first");
  1252. (runtime as unknown as AgentRuntimeInternal).workingDirectory = "/workspace/subdir";
  1253. await runtime.executeTurn("second");
  1254. await runtime.executeTurn("third");
  1255. const all = contextEntries(runtime);
  1256. const environments = all.filter((entry) => entry.metadata?.source === "environment");
  1257. expect(environments).toHaveLength(2);
  1258. expect(environments[1]).toMatchObject({
  1259. content:
  1260. "# Environment update\n - Primary working directory: /workspace/subdir (was /workspace)",
  1261. });
  1262. expect(all.filter((entry) => entry.metadata?.source === "session_context")).toHaveLength(1);
  1263. expect(requests[1]?.messages.map(({ role, content }) => ({ role, content }))).toEqual(
  1264. requests[2]?.messages.slice(0, -2).map(({ role, content }) => ({ role, content })),
  1265. );
  1266. });
  1267. it("lists additional working directories and announces only their change after cold resume", async () => {
  1268. const environmentEntries = (value: ReturnType<typeof createTestAgentRuntime>) =>
  1269. contextEntries(value).filter((entry) => entry.metadata?.source === "environment");
  1270. runtime = createRuntime(
  1271. { now },
  1272. { ...config, additionalDirectories: ["/work/backend", "C:\\work\\shared folder"] },
  1273. );
  1274. await runtime.executeTurn("first");
  1275. const [full] = environmentEntries(runtime);
  1276. // 运行实例内目录不变;冷恢复按新运行配置比较最近一次公告,只追加增量,原块不改写。
  1277. const cold = createRuntime(
  1278. { now },
  1279. { ...config, additionalDirectories: ["/work/backend", "/work/docs"] },
  1280. );
  1281. await cold.resumeFromStore();
  1282. await cold.executeTurn("resumed");
  1283. const environments = environmentEntries(cold);
  1284. expect(environments).toHaveLength(2);
  1285. expect(environments[0]).toEqual(full);
  1286. expect(environments[1]).toMatchObject({
  1287. content:
  1288. "# Environment update\n - Additional working directories added:\n - /work/docs\n - Additional working directories removed:\n - C:\\work\\shared folder",
  1289. metadata: {
  1290. environment: {
  1291. full: false,
  1292. snapshot: { additionalWorkingDirectories: ["/work/backend", "/work/docs"] },
  1293. },
  1294. },
  1295. });
  1296. const visible = (request: ModelRequest) =>
  1297. request.messages.map(({ role, content }) => ({ role, content }));
  1298. expect(visible(requests.at(-1)!).slice(0, requests[0]!.messages.length)).toEqual(
  1299. visible(requests[0]!),
  1300. );
  1301. });
  1302. it("refreshes repository membership, deduplicates, and compares the return trip with the latest snapshot", async () => {
  1303. const contextSourcePort = environmentPort();
  1304. runtime = createRuntime({ now, contextSourcePort }, config);
  1305. await runtime.executeTurn("first");
  1306. const initialGit = contextEntries(runtime).find(
  1307. (entry) => entry.metadata?.source === "session_context",
  1308. );
  1309. runtime.setWorkingDirectory("/outside");
  1310. await runtime.executeTurn("leave repo");
  1311. await runtime.executeTurn("same directory");
  1312. const updates = contextEntries(runtime).filter(
  1313. (entry) => entry.metadata?.source === "environment",
  1314. );
  1315. expect(updates).toHaveLength(2);
  1316. expect(updates[1]).toMatchObject({
  1317. content:
  1318. "# Environment update\n - Primary working directory: /outside (was /workspace)\n - Is a git repository: false (was true)",
  1319. metadata: {
  1320. environment: { full: false, snapshot: { cwd: "/outside", isGitRepository: false } },
  1321. },
  1322. });
  1323. expect(contextSourcePort.resolveEnvironment).toHaveBeenCalledTimes(1);
  1324. expect(requests[1]?.messages.at(-1)).toMatchObject({
  1325. role: "system",
  1326. content: updates[1]?.kind === "attachment" ? updates[1].content : "",
  1327. });
  1328. runtime.setWorkingDirectory("/workspace");
  1329. await runtime.executeTurn("return to repo");
  1330. expect(
  1331. contextEntries(runtime)
  1332. .filter((entry) => entry.metadata?.source === "environment")
  1333. .at(-1),
  1334. ).toMatchObject({
  1335. content:
  1336. "# Environment update\n - Primary working directory: /workspace (was /outside)\n - Is a git repository: true (was false)",
  1337. });
  1338. expect(
  1339. contextEntries(runtime).filter((entry) => entry.metadata?.source === "session_context"),
  1340. ).toEqual([initialGit]);
  1341. });
  1342. it("re-reads only repository membership once after a cold resume and announces a change as an update", async () => {
  1343. runtime = createRuntime({ now, contextSourcePort: environmentPort() }, config);
  1344. await runtime.executeTurn("first");
  1345. const environmentsOf = (value: ReturnType<typeof createTestAgentRuntime>) =>
  1346. contextEntries(value)
  1347. .filter((entry) => entry.metadata?.source === "environment")
  1348. .map((entry) => entry.content);
  1349. const gitOf = (value: ReturnType<typeof createTestAgentRuntime>) =>
  1350. contextEntries(value).filter((entry) => entry.metadata?.source === "session_context");
  1351. // 是否仓库没变:新 runtime 读一次,不追加公告。
  1352. const unchanged = environmentPort();
  1353. const { cold: same } = await coldRuntimeWith(skillPort, config, {
  1354. contextSourcePort: unchanged,
  1355. });
  1356. await same.executeTurn("resumed");
  1357. await same.executeTurn("again");
  1358. expect(unchanged.resolveEnvironment).toHaveBeenCalledTimes(1);
  1359. expect(environmentsOf(same)).toEqual(environmentsOf(runtime));
  1360. // .git 已删除:只取是否仓库,平台与系统版本沿用历史,不出完整块;Git 公告沿用历史。
  1361. const changed = environmentPort();
  1362. changed.resolveEnvironment.mockImplementation(async ({ workingDirectory }) => ({
  1363. ...config.envInfo!,
  1364. cwd: workingDirectory,
  1365. platform: "darwin",
  1366. osVersion: "Darwin",
  1367. isGitRepository: false,
  1368. }));
  1369. const { cold } = await coldRuntimeWith(skillPort, config, { contextSourcePort: changed });
  1370. await cold.executeTurn("resumed");
  1371. await cold.executeTurn("again");
  1372. expect(changed.resolveEnvironment).toHaveBeenCalledTimes(1);
  1373. expect(environmentsOf(cold)).toEqual([
  1374. ...environmentsOf(runtime),
  1375. "# Environment update\n - Is a git repository: false (was true)",
  1376. ]);
  1377. expect(gitOf(cold)).toEqual(gitOf(runtime));
  1378. });
  1379. it("restores environment snapshot metadata and emits a full block when its original block is removed", async () => {
  1380. const contextSourcePort = environmentPort();
  1381. runtime = createRuntime({ now, contextSourcePort }, config);
  1382. await runtime.executeTurn("first");
  1383. runtime.setWorkingDirectory("/outside");
  1384. await runtime.executeTurn("leave repo");
  1385. const cold = createRuntime({ now, contextSourcePort }, config);
  1386. await cold.resumeFromStore();
  1387. cold.setWorkingDirectory("/outside");
  1388. await cold.executeTurn("resume here");
  1389. expect(contextEntries(cold)).toEqual(contextEntries(runtime));
  1390. const internal = cold as unknown as AgentRuntimeInternal;
  1391. internal.messageHistory.replaceMessages(
  1392. internal.messageHistory
  1393. .toRuntimeEntries()
  1394. .filter(
  1395. (entry) =>
  1396. !(
  1397. entry.kind === "attachment" &&
  1398. entry.metadata.source === "environment" &&
  1399. entry.metadata.environment?.full
  1400. ),
  1401. ),
  1402. );
  1403. await cold.executeTurn("after history reduction");
  1404. expect(
  1405. contextEntries(cold)
  1406. .filter((entry) => entry.metadata?.source === "environment")
  1407. .at(-1),
  1408. ).toMatchObject({
  1409. content: expect.stringContaining("# Environment\n"),
  1410. metadata: {
  1411. environment: { full: true, snapshot: { cwd: "/outside", isGitRepository: false } },
  1412. },
  1413. });
  1414. });
  1415. it("replaces the full block on shell or platform changes and catches up a directory moved during the probe", async () => {
  1416. const contextSourcePort = environmentPort();
  1417. runtime = createRuntime({ now, contextSourcePort }, config);
  1418. await runtime.executeTurn("first");
  1419. contextSourcePort.resolveEnvironment.mockImplementationOnce(async () => {
  1420. runtime.setWorkingDirectory("/latest");
  1421. return { ...config.envInfo!, cwd: "/probed", shell: "fish", isGitRepository: true };
  1422. });
  1423. contextSourcePort.resolveEnvironment.mockImplementationOnce(async ({ workingDirectory }) => ({
  1424. ...config.envInfo!,
  1425. cwd: workingDirectory,
  1426. platform: "darwin",
  1427. isGitRepository: false,
  1428. }));
  1429. const latestEnvironment = () =>
  1430. contextEntries(runtime)
  1431. .filter((entry) => entry.metadata?.source === "environment")
  1432. .at(-1);
  1433. runtime.setWorkingDirectory("/probed");
  1434. await runtime.executeTurn("move during probe");
  1435. // 公告使用探测前读到的目录及其事实,不重试;目录在 IO 期间的变化留给下一次请求。
  1436. expect(latestEnvironment()).toMatchObject({
  1437. content: expect.stringContaining("# Environment\n"),
  1438. metadata: {
  1439. environment: { full: true, snapshot: { cwd: "/probed", shell: "fish" } },
  1440. },
  1441. });
  1442. expect(contextSourcePort.resolveEnvironment).toHaveBeenCalledTimes(1);
  1443. await runtime.executeTurn("next");
  1444. expect(latestEnvironment()).toMatchObject({
  1445. content: expect.stringContaining("# Environment\n"),
  1446. metadata: {
  1447. environment: {
  1448. full: true,
  1449. snapshot: { cwd: "/latest", platform: "darwin", isGitRepository: false },
  1450. },
  1451. },
  1452. });
  1453. expect(contextSourcePort.resolveEnvironment).toHaveBeenCalledTimes(2);
  1454. });
  1455. it("republishes a full block for legacy metadata and does not leak snapshot metadata on MCS downgrade", async () => {
  1456. runtime = createRuntime({ now, contextSourcePort: environmentPort() }, config);
  1457. await runtime.executeTurn("first");
  1458. const internal = runtime as unknown as AgentRuntimeInternal;
  1459. const legacy = internal.messageHistory.toRuntimeEntries();
  1460. for (const entry of legacy) {
  1461. if (entry.metadata?.source === "environment") delete entry.metadata.environment;
  1462. }
  1463. internal.messageHistory.replaceMessages(legacy);
  1464. await runtime.executeTurn("legacy history");
  1465. expect(
  1466. contextEntries(runtime).filter((entry) => entry.metadata?.source === "environment"),
  1467. ).toHaveLength(2);
  1468. runtime.setWorkingDirectory("/outside");
  1469. await runtime.executeTurn("leave");
  1470. const returnedEntries = internal.messageHistory.toRuntimeEntries();
  1471. const returnedEnvironment = returnedEntries
  1472. .filter((entry) => entry.metadata?.source === "environment")
  1473. .at(-1)!;
  1474. returnedEnvironment.metadata!.environment!.snapshot.cwd = "/mutated-entry";
  1475. expect(contextEntries(runtime).at(-1)).not.toEqual(returnedEnvironment);
  1476. const projected = buildProviderRequestMessages({
  1477. entries: internal.messageHistory.toRuntimeEntries(),
  1478. useMidConversationSystem: false,
  1479. }).messages;
  1480. expect(JSON.stringify(projected)).not.toMatch(/"(?:metadata|snapshot|environment)"/u);
  1481. expect(
  1482. projected.some(
  1483. (message) =>
  1484. message.role === "user" &&
  1485. String(message.content).includes("<system-reminder>\n# Environment update\n"),
  1486. ),
  1487. ).toBe(true);
  1488. });
  1489. it("does not commit a failed context write and retries the missing sources", async () => {
  1490. runtime = createRuntime({ now, skillPort, contextSourcePort: instructionsPort() }, config);
  1491. const savePart = store.savePart;
  1492. store.savePart = async (part) => {
  1493. if (part.metadata?.runtimeMessage?.source === "environment")
  1494. throw new Error("context write failed");
  1495. await savePart(part);
  1496. };
  1497. await expect(runtime.executeTurn("first")).rejects.toThrow();
  1498. expect(respond).not.toHaveBeenCalled();
  1499. // environment 是第一条公告;它写入失败时,后续来源都不会提交。
  1500. expect(contextEntries(runtime).map((entry) => entry.metadata?.source)).toEqual([]);
  1501. store.savePart = savePart;
  1502. await runtime.executeTurn("retry");
  1503. expect(contextEntries(runtime).map((entry) => entry.metadata?.source)).toEqual([...sources]);
  1504. });
  1505. });