runtime-context-announcements.test.ts 120 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687
  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. latestAnnouncedLanguage,
  34. restateContextAfterCompact,
  35. } from "../src/runtime/methods/context-refresh.js";
  36. import type { AgentRuntimeConfig, AgentRuntimeDeps } from "../src/runtime/types.js";
  37. import { resolveGenUiOutputDirectory } from "../src/runtime/helpers/gen-ui-output.js";
  38. import {
  39. buildEnvironmentAnnouncement,
  40. type EnvironmentSnapshot,
  41. } from "../src/context/sections/env-info.js";
  42. import { buildDesktopContextContent } from "../src/context/sections/desktop.js";
  43. import { createInstructionFile } from "../src/context/sections/instruction-files.js";
  44. import { createContextBuilder } from "../src/context/index.js";
  45. import { formatWorkflowStallNotification } from "../src/runtime-task/workflow-notification-copy.js";
  46. const snapshot = (...names: string[]): AgentDefinitionsSnapshot => ({
  47. activeAgents: names.map((name) => ({
  48. name,
  49. description: `Description ${name}`,
  50. source: "user",
  51. systemPrompt: "private",
  52. })),
  53. });
  54. const result = {
  55. finishReason: "stop" as const,
  56. text: "Summary of current work.",
  57. usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 },
  58. };
  59. let sessionId: ReturnType<typeof createSessionId>;
  60. let store: ReturnType<typeof createRecordingMessageStore>;
  61. let requests: ModelRequest[];
  62. const definitions = vi.fn(() => snapshot("A"));
  63. const respond = vi.fn<(request: ModelRequest) => Promise<ModelResult>>();
  64. let runtime: ReturnType<typeof createTestAgentRuntime>;
  65. function createRuntime(
  66. deps: Partial<AgentRuntimeDeps> = {},
  67. config: Partial<AgentRuntimeConfig> = {},
  68. { mcs = true, fold = false }: { mcs?: boolean; fold?: boolean } = {},
  69. ) {
  70. const modelFactory = createTestModelFactory({
  71. properties: { supportsMidConversationSystem: mcs },
  72. generateText: async (request) => {
  73. requests.push(request);
  74. return respond(request);
  75. },
  76. });
  77. return createTestAgentRuntime(
  78. sessionId,
  79. { mode: "yolo", compact: { enabled: false }, titleGeneration: { enabled: false }, ...config },
  80. {
  81. eventStore: createTestSessionEventStore(),
  82. sessionStore: store as never,
  83. getAgentDefinitions: definitions,
  84. modelFactory: fold
  85. ? (input) => ({
  86. ...modelFactory(input),
  87. requestCapabilities: { foldRemindersIntoToolResults: true },
  88. })
  89. : modelFactory,
  90. ...deps,
  91. },
  92. );
  93. }
  94. const entries = () =>
  95. (runtime as unknown as AgentRuntimeInternal).messageHistory.toRuntimeEntries();
  96. const compact = (value: ReturnType<typeof createTestAgentRuntime>, trigger?: CompactTrigger) =>
  97. (value as unknown as AgentRuntimeInternal).compactActiveConversation(
  98. undefined,
  99. createRootTraceContext({ sessionId }),
  100. [],
  101. { trigger },
  102. );
  103. beforeEach(() => {
  104. sessionId = createSessionId();
  105. store = createRecordingMessageStore();
  106. requests = [];
  107. definitions.mockReset().mockImplementation(() => snapshot("A"));
  108. respond.mockReset().mockResolvedValue(result);
  109. runtime = createRuntime();
  110. });
  111. const skillPort: SkillPort = {
  112. async discoverSkills() {
  113. return {
  114. skills: [
  115. {
  116. name: "search",
  117. description: "search things",
  118. path: "/workspace/.agents/skills/search/SKILL.md",
  119. directory: "/workspace/.agents/skills/search",
  120. rootPath: "/workspace/.agents/skills",
  121. scope: "project" as const,
  122. source: "agents" as const,
  123. safeToAutoLoad: true,
  124. frontmatterKeys: [],
  125. },
  126. ],
  127. diagnostics: [],
  128. totalDiscovered: 1,
  129. };
  130. },
  131. async loadSkill() {
  132. throw new Error("not needed");
  133. },
  134. };
  135. describe("runtime context announcements", () => {
  136. // 顺序即宣告顺序:environment → model → (agent listing) → skills → instructions → git → date。
  137. const sources = new Set([
  138. "environment",
  139. "model",
  140. "skills_listing",
  141. "context_prefix",
  142. "session_context",
  143. "date",
  144. ]);
  145. // 动态公告按隐藏提醒落盘:类型只记在 runtimeMessage.source,不写顶层 source。
  146. const runtimeSourceOf = (message: { metadata?: Record<string, unknown> }) =>
  147. (message.metadata?.runtimeMessage as { source?: string } | undefined)?.source;
  148. const isAnnouncementRecord = (message: {
  149. semantics?: { kind?: string };
  150. metadata?: Record<string, unknown>;
  151. }) =>
  152. message.semantics?.kind === "system_reminder" && sources.has(runtimeSourceOf(message) ?? "");
  153. const contextEntries = (value: ReturnType<typeof createTestAgentRuntime>) =>
  154. (value as unknown as AgentRuntimeInternal).messageHistory
  155. .toRuntimeEntries()
  156. .filter((entry) => entry.kind === "attachment" && sources.has(entry.metadata.source));
  157. const config: Partial<AgentRuntimeConfig> = {
  158. workingDirectory: "/workspace",
  159. currentDate: "2026-10-14",
  160. envInfo: {
  161. cwd: "/workspace",
  162. platform: "linux",
  163. shell: "bash",
  164. osVersion: "Linux",
  165. nodeVersion: "24",
  166. isGitRepository: true,
  167. gitStatus: "clean",
  168. gitBranch: "original",
  169. },
  170. };
  171. const now = () => new Date(2026, 9, 14, 12);
  172. const instructionsPort = (): ContextSourcePort => ({
  173. async resolveEnvironment() {
  174. return config.envInfo!;
  175. },
  176. async resolveGitContext() {
  177. return config.envInfo!;
  178. },
  179. async resolveContextSources() {
  180. return {
  181. workingDirectory: "/workspace",
  182. envInfo: config.envInfo!,
  183. userInstructions: {
  184. filePath: "/workspace/AGENTS.md",
  185. fileName: "AGENTS.md",
  186. content: "Project rule.",
  187. bytesRead: 13,
  188. sizeBytes: 13,
  189. truncated: false,
  190. },
  191. diagnostics: [],
  192. };
  193. },
  194. });
  195. const environmentPort = () =>
  196. ({
  197. async resolveContextSources() {
  198. return { workingDirectory: "/workspace", envInfo: config.envInfo!, diagnostics: [] };
  199. },
  200. resolveEnvironment: vi.fn(
  201. async ({
  202. workingDirectory,
  203. effectiveShellDisplayName,
  204. }: Pick<ContextSourceRequest, "workingDirectory" | "effectiveShellDisplayName">) => ({
  205. ...config.envInfo!,
  206. cwd: workingDirectory,
  207. shell: effectiveShellDisplayName ?? config.envInfo!.shell,
  208. isGitRepository: workingDirectory.startsWith("/workspace"),
  209. }),
  210. ),
  211. }) satisfies ContextSourcePort;
  212. // 把当前 store 复制成独立的冷存储,再从中恢复一个新 runtime。
  213. const coldRuntimeWith = async (
  214. port: SkillPort = skillPort,
  215. coldConfig: Partial<AgentRuntimeConfig> = config,
  216. coldDeps: Partial<AgentRuntimeDeps> = {},
  217. ) => {
  218. const recording = createRecordingMessageStore();
  219. // rewind 只需把分支信息写回会话;录制 store 没有 setRevert,用 updateSession 承接。
  220. const coldStore = Object.assign(recording, {
  221. async setRevert(input: { sessionID: string; revert: unknown }) {
  222. await recording.updateSession({ id: input.sessionID, revert: input.revert });
  223. },
  224. });
  225. await coldStore.createSession(await store.getSession(sessionId));
  226. coldStore.savedMessages.push(...structuredClone(store.savedMessages));
  227. coldStore.savedParts.push(...structuredClone(store.savedParts));
  228. const cold = createRuntime(
  229. {
  230. now,
  231. skillPort: port,
  232. contextSourcePort: instructionsPort(),
  233. sessionStore: coldStore as never,
  234. ...coldDeps,
  235. },
  236. coldConfig,
  237. );
  238. await cold.resumeFromStore();
  239. return { cold, coldStore };
  240. };
  241. it("announces environment and model for a custom system prompt", async () => {
  242. runtime = createRuntime(
  243. { now, contextSourcePort: environmentPort() },
  244. { ...config, systemPrompt: "Host override." },
  245. );
  246. await runtime.executeTurn("first task");
  247. // 自定义 prompt 只替换 system 正文,环境与模型公告照常发送;Git 仍不发。
  248. expect(contextEntries(runtime).map((entry) => entry.metadata?.source)).toEqual([
  249. "environment",
  250. "model",
  251. "date",
  252. ]);
  253. expect(String(requests[0]!.messages[1]!.content)).toBe("\nHost override.");
  254. });
  255. it.each([false, true])(
  256. "uses shared environment/model lifecycle for a specialized child (MCS=%s)",
  257. async (mcs) => {
  258. const contextSourcePort = environmentPort();
  259. const resolveContextSources = vi.spyOn(contextSourcePort, "resolveContextSources");
  260. const childConfig: Partial<AgentRuntimeConfig> = {
  261. ...config,
  262. taskType: "subagent_child",
  263. subagentContext: { agentPrompt: "Dedicated child identity." },
  264. subagents: { enabled: false },
  265. };
  266. runtime = createRuntime({ now, contextSourcePort }, childConfig, { mcs });
  267. await runtime.executeTurn("first child task");
  268. const initial = contextEntries(runtime);
  269. expect(initial.map((entry) => entry.metadata?.source)).toEqual([
  270. "environment",
  271. "model",
  272. "date",
  273. ]);
  274. expect(
  275. requests[0]?.messages.find((message) => String(message.content).includes("# Environment\n"))
  276. ?.role,
  277. ).toBe(mcs ? "system" : "user");
  278. const initialBody = requests[0]!.messages[1]!.content;
  279. runtime.setWorkingDirectory("/outside");
  280. const nextSelection = createTestModelSelection("test/child-next");
  281. runtime.setSessionModelSelection(nextSelection);
  282. await runtime.executeTurn("second child task");
  283. const changed = contextEntries(runtime);
  284. expect(
  285. changed.filter((entry) => entry.metadata?.source === "environment").at(-1),
  286. ).toMatchObject({
  287. content:
  288. "# Environment update\n - Primary working directory: /outside (was /workspace)\n - Is a git repository: false (was true)",
  289. });
  290. expect(changed.filter((entry) => entry.metadata?.source === "model").at(-1)).toMatchObject({
  291. content: "You are powered by the model named test/child-next.",
  292. });
  293. await runtime.executeTurn("unchanged child task");
  294. expect(contextEntries(runtime)).toEqual(changed);
  295. expect(requests.at(-1)!.messages[1]!.content).toEqual(initialBody);
  296. // child 初始快照只用父级传下的配置;端口只用于 cd 之后的环境探测。
  297. expect(resolveContextSources).not.toHaveBeenCalled();
  298. expect(contextSourcePort.resolveEnvironment).toHaveBeenCalledTimes(1);
  299. },
  300. );
  301. it.each([false, true])(
  302. "orders the first user turn by attachment collection order (MCS=%s)",
  303. async (mcs) => {
  304. runtime = createRuntime(
  305. { now, skillPort, contextSourcePort: instructionsPort() },
  306. { ...config, outputStyle: { name: "Learning", prompt: "Explain tradeoffs." } },
  307. { mcs },
  308. );
  309. await runtime.executeTurn("first");
  310. // 先产出全部输入附件(含每次收集的 output_style),请求前公告在其后,最后是本轮输入。
  311. const markers = [
  312. ["environment", "# Environment"],
  313. ["model", "You are powered by"],
  314. ["output_style_instructions", "# Output Style: Learning"],
  315. ["agents", "Available agent types"],
  316. ["skills", "The following skills"],
  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. describe("reply language", () => {
  623. const languageBody = (name: string) =>
  624. [
  625. "# Language",
  626. `Always respond in ${name}. Use ${name} for all explanations, comments, and communications with the user. Technical terms and code identifiers should remain in their original form.`,
  627. `Maintain full orthographic correctness for ${name}, including all required diacritical marks, accents, and special characters. Never substitute accented characters with their ASCII equivalents (e.g., never write "nao" for "não", "fur" for "für", or "loeschen" for "löschen").`,
  628. ].join("\n");
  629. const languageCleared = "The language preference was cleared. Match the user's language.";
  630. const languageEntries = () =>
  631. entries().filter(
  632. (entry) => entry.kind === "attachment" && entry.metadata.source === "language",
  633. );
  634. type ReadReplyLanguage = NonNullable<AgentRuntimeDeps["readReplyLanguage"]>;
  635. it("announces the Host reply language after output style once per change", async () => {
  636. let language = "简体中文";
  637. const readReplyLanguage = vi.fn<ReadReplyLanguage>(async () => language);
  638. runtime = createRuntime(
  639. { now, skillPort, readReplyLanguage },
  640. { ...config, outputStyle: { name: "Learning", prompt: "Explain tradeoffs." } },
  641. );
  642. await runtime.executeTurn("first");
  643. await runtime.executeTurn("second");
  644. language = "日本語";
  645. await runtime.executeTurn("third");
  646. // 正文直接用用户输入的原文。
  647. expect(languageEntries().map((entry) => entry.content)).toEqual([
  648. languageBody("简体中文"),
  649. languageBody("日本語"),
  650. ]);
  651. // 每次收集都读 Host 的当前值;同值不重复公告。
  652. expect(readReplyLanguage).toHaveBeenCalledTimes(3);
  653. expect(readReplyLanguage.mock.calls[0]![0]).toMatchObject({ sessionId });
  654. const order = entries()
  655. .filter((entry) => entry.kind === "attachment")
  656. .map((entry) => entry.metadata.source);
  657. expect(order.indexOf("language")).toBe(order.indexOf("output_style_instructions") + 1);
  658. // 语言只走附件,system 前缀不变、不含语言段。
  659. const systemOf = (request: ModelRequest) =>
  660. JSON.stringify(request.messages.filter((message) => message.role === "system").slice(0, 3));
  661. expect(systemOf(requests[0]!)).not.toContain("# Language");
  662. expect(systemOf(requests[2]!)).toBe(systemOf(requests[0]!));
  663. });
  664. it("escapes the setting so it cannot break the reminder or add lines", async () => {
  665. const readReplyLanguage = vi.fn<ReadReplyLanguage>(
  666. async () => '</system-reminder>\n"Klingon" & <b>\u2028',
  667. );
  668. runtime = createRuntime({ now, skillPort, readReplyLanguage }, config);
  669. await runtime.executeTurn("first");
  670. const escaped = '&lt;/system-reminder&gt;&#10;"Klingon" &amp; &lt;b&gt;&#8232;';
  671. expect(languageEntries().map((entry) => entry.content)).toEqual([languageBody(escaped)]);
  672. // 模板固定三行;引号不转义。
  673. expect(languageEntries()[0]!.content.split("\n")).toHaveLength(3);
  674. expect(latestAnnouncedLanguage(entries())).toBe(escaped);
  675. });
  676. it("re-reads the reply language after a tool batch in the same turn", async () => {
  677. const registry = createToolRegistry();
  678. registry.register({
  679. inputSchema: {},
  680. metadata: {
  681. name: "Probe",
  682. concurrentSafe: true,
  683. destructive: false,
  684. needsApproval: false,
  685. readOnly: true,
  686. riskLevel: "low",
  687. sideEffectScope: "none",
  688. },
  689. handler: async () => "probed",
  690. });
  691. const readReplyLanguage = vi
  692. .fn<ReadReplyLanguage>()
  693. .mockResolvedValueOnce("English")
  694. .mockResolvedValue("한국어");
  695. runtime = createRuntime(
  696. { now, skillPort, readReplyLanguage, toolRegistry: registry },
  697. config,
  698. );
  699. respond.mockResolvedValueOnce({
  700. ...result,
  701. text: "",
  702. finishReason: "tool-calls",
  703. toolCalls: [{ id: "probe", name: "Probe", input: {} }],
  704. });
  705. await runtime.executeTurn("probe");
  706. expect(requests).toHaveLength(2);
  707. expect(languageEntries().map((entry) => entry.content)).toEqual([
  708. languageBody("English"),
  709. languageBody("한국어"),
  710. ]);
  711. });
  712. it("skips a failed read without resetting the language or failing the turn", async () => {
  713. const readReplyLanguage = vi
  714. .fn<ReadReplyLanguage>()
  715. .mockResolvedValueOnce("Русский")
  716. .mockRejectedValueOnce(new Error("host gone"))
  717. .mockImplementationOnce(() => {
  718. throw "sync failure";
  719. });
  720. const debug = vi.fn();
  721. const louder = vi.fn();
  722. const logger = { debug, info: louder, warn: louder, error: louder, child: () => logger };
  723. runtime = createRuntime(
  724. { now, skillPort, readReplyLanguage, logger: logger as never },
  725. config,
  726. );
  727. await runtime.executeTurn("first");
  728. await runtime.executeTurn("failed");
  729. await runtime.executeTurn("thrown");
  730. expect(requests).toHaveLength(3);
  731. expect(languageEntries().map((entry) => entry.content)).toEqual([languageBody("Русский")]);
  732. // 每次收集都会读一次:失败只记 debug(生产不落盘),不升级为 info/warn。
  733. const skipped = debug.mock.calls.filter(
  734. ([, context]) => context?.event === "reply_language.read_skipped",
  735. );
  736. expect(skipped.map(([, context]) => context.errorMessage)).toEqual([
  737. "host gone",
  738. "sync failure",
  739. ]);
  740. expect(
  741. louder.mock.calls.some(([, context]) => context?.event === "reply_language.read_skipped"),
  742. ).toBe(false);
  743. });
  744. it("announces the clear text once when the setting is cleared", async () => {
  745. const readReplyLanguage = vi
  746. .fn<ReadReplyLanguage>()
  747. .mockResolvedValueOnce(null)
  748. .mockResolvedValueOnce("Русский")
  749. .mockResolvedValueOnce(null)
  750. .mockResolvedValueOnce(null)
  751. .mockResolvedValueOnce("Русский");
  752. runtime = createRuntime({ now, skillPort, readReplyLanguage }, config);
  753. for (const input of ["never set", "set", "cleared", "still cleared", "set again"]) {
  754. await runtime.executeTurn(input);
  755. }
  756. // 没有公告过时 null 不发;有语言后 null 只清除一次;再设回时重新公告。
  757. expect(languageEntries().map((entry) => entry.content)).toEqual([
  758. languageBody("Русский"),
  759. languageCleared,
  760. languageBody("Русский"),
  761. ]);
  762. });
  763. it("does not read the reply language for a subagent child", async () => {
  764. const readReplyLanguage = vi.fn<ReadReplyLanguage>(async () => "日本語");
  765. runtime = createRuntime(
  766. { now, contextSourcePort: environmentPort(), readReplyLanguage },
  767. {
  768. ...config,
  769. taskType: "subagent_child",
  770. subagentContext: { agentPrompt: "Dedicated child identity." },
  771. subagents: { enabled: false },
  772. },
  773. );
  774. await runtime.executeTurn("child task");
  775. expect(readReplyLanguage).not.toHaveBeenCalled();
  776. expect(languageEntries()).toEqual([]);
  777. });
  778. it("restates the latest language after compact unless the kept tail has one", () => {
  779. runtime = createRuntime({ now, skillPort }, config);
  780. const internal = runtime as unknown as AgentRuntimeInternal;
  781. // 与 output style 一样不受 env_info 门控。
  782. internal.latestContextBuildResult = { sections: [] } as never;
  783. const chinese = systemReminderAttachmentEntry("language", languageBody("简体中文"));
  784. const japanese = systemReminderAttachmentEntry("language", languageBody("日本語"));
  785. const style = systemReminderAttachmentEntry(
  786. "output_style_instructions",
  787. "# Output Style: Learning\nExplain tradeoffs.",
  788. );
  789. expect(
  790. restateContextAfterCompact(internal, [style, chinese, japanese], []).map((entry) => [
  791. entry.metadata.source,
  792. entry.content,
  793. ]),
  794. ).toEqual([
  795. ["output_style_instructions", style.content],
  796. ["language", japanese.content],
  797. ]);
  798. expect(restateContextAfterCompact(internal, [chinese], [japanese])).toEqual([]);
  799. // 最近一次是清除公告时不重述。
  800. const cleared = systemReminderAttachmentEntry("language", languageCleared);
  801. expect(restateContextAfterCompact(internal, [chinese, cleared], [])).toEqual([]);
  802. });
  803. it("takes the title language from the latest announcement unless it was cleared", () => {
  804. // 语言可以含句点与 ". Use ":按长度反解,再用往返校验,不会在句点处截断。
  805. const tricky = "Português (Brasil). Use formal tone";
  806. const announced = systemReminderAttachmentEntry("language", languageBody(tricky));
  807. const cleared = systemReminderAttachmentEntry("language", languageCleared);
  808. expect(latestAnnouncedLanguage([cleared, announced])).toBe(tricky);
  809. expect(latestAnnouncedLanguage([announced, cleared])).toBeUndefined();
  810. expect(latestAnnouncedLanguage([])).toBeUndefined();
  811. // 不是模板生成的正文(例如被改写过)不当作语言。
  812. const tampered = systemReminderAttachmentEntry("language", `${languageBody("日本語")} extra`);
  813. expect(latestAnnouncedLanguage([tampered])).toBeUndefined();
  814. });
  815. it.each([
  816. [
  817. "日本語",
  818. "- Write the title in 日本語. Keep technical terms and code identifiers in their original form.",
  819. ],
  820. // 用户输入里的 $& / $' 不能被当成 String.replace 的替换模式展开。
  821. [
  822. "Español $& $'",
  823. "- Write the title in Español $&amp; $'. Keep technical terms and code identifiers in their original form.",
  824. ],
  825. [null, "- Use the user's primary language."],
  826. ] as const)(
  827. "writes the session title in the latest announced language (%s)",
  828. async (language, rule) => {
  829. runtime = createRuntime(
  830. {
  831. now,
  832. skillPort,
  833. readReplyLanguage: async () => language,
  834. // Host 端口在场时标题推迟到首轮结束,这时历史里已有语言公告。
  835. providerRuntimeHeadersPort: {
  836. shouldRefreshBeforeModelRequest: () => true,
  837. refreshBeforeModelRequest: async () => ({ headersApplied: true }),
  838. },
  839. },
  840. { ...config, titleGeneration: { enabled: true } },
  841. );
  842. await runtime.executeTurn("please fix the mobile login button");
  843. const titleSystem = () =>
  844. requests
  845. .map((request) => String(request.messages[0]?.content))
  846. .find((content) => content.startsWith("Generate a concise title"));
  847. await vi.waitFor(() => expect(titleSystem()).toBeDefined());
  848. expect(titleSystem()).toContain(rule);
  849. expect(
  850. titleSystem()?.match(/^- (Write the title in|Use the user's primary language)/gmu),
  851. ).toHaveLength(1);
  852. },
  853. );
  854. });
  855. it("derives the plan-mode exit reminder from history after resume", async () => {
  856. runtime = createRuntime({ now, skillPort, contextSourcePort: instructionsPort() }, config);
  857. const internal = runtime as unknown as AgentRuntimeInternal;
  858. await runtime.executeTurn("planned");
  859. internal.messageHistory.addEntries([
  860. systemReminderAttachmentEntry("runtime_mode", "Plan mode is active."),
  861. { message: { role: "assistant", content: "plan ready" } },
  862. ]);
  863. // 冷恢复后内存标记为 false;按历史中最近的 plan 提醒判断。
  864. internal.needsPlanModeExitReminder = false;
  865. await runtime.executeTurn("build it");
  866. await runtime.executeTurn("again");
  867. const planExit = entries().filter((entry) => entry.metadata?.source === "plan_mode_exit");
  868. expect(planExit).toHaveLength(1);
  869. });
  870. it.each([undefined, CompactTrigger.Manual, CompactTrigger.Reactive])(
  871. "restores context without duplicate announcements after compact=%s",
  872. async (trigger) => {
  873. runtime = createRuntime({ now, skillPort, contextSourcePort: instructionsPort() }, config);
  874. await runtime.executeTurn("first");
  875. const initialContext = contextEntries(runtime);
  876. expect(initialContext.map((entry) => entry.metadata?.source)).toEqual([...sources]);
  877. await runtime.executeTurn("second");
  878. expect(contextEntries(runtime)).toEqual(initialContext);
  879. const announcements = store.savedMessages.filter(isAnnouncementRecord);
  880. expect(announcements).toHaveLength(6);
  881. for (const announcement of announcements) {
  882. // 顶层 source 不写新值:旧版本 App 按封闭列表校验,会拒绝整个会话。
  883. expect(announcement.source).toBeUndefined();
  884. expect(announcement.semantics?.source).toBe(runtimeSourceOf(announcement));
  885. expect(announcement).toMatchObject({
  886. semantics: {
  887. uiVisibility: "hidden",
  888. transcriptVisibility: "hidden",
  889. providerVisibility: "visible",
  890. },
  891. });
  892. }
  893. if (trigger) {
  894. const compacted = await compact(runtime, trigger);
  895. expect(compacted.outcome).toBe("compacted");
  896. await runtime.executeTurn("continue after compact");
  897. // 每个来源仍只宣告一次;顺序按 compact 后布局(见 "lays out the post-compact context")。
  898. const bySource = (items: ReturnType<typeof contextEntries>) =>
  899. [...items].sort((a, b) => a.metadata.source.localeCompare(b.metadata.source));
  900. expect(bySource(contextEntries(runtime))).toEqual(bySource(initialContext));
  901. }
  902. const liveContext = contextEntries(runtime);
  903. const { cold, coldStore } = await coldRuntimeWith(skillPort, {
  904. ...config,
  905. envInfo: { ...config.envInfo!, gitBranch: "new-probe-must-not-replace-history" },
  906. });
  907. const before = coldStore.savedMessages.filter(isAnnouncementRecord).length;
  908. await cold.executeTurn("resumed");
  909. expect(contextEntries(cold)).toEqual(liveContext);
  910. expect(coldStore.savedMessages.filter(isAnnouncementRecord)).toHaveLength(before);
  911. },
  912. );
  913. const withSkills = (
  914. skills: (base: Awaited<ReturnType<SkillPort["discoverSkills"]>>["skills"]) => typeof base,
  915. ): SkillPort => ({
  916. ...skillPort,
  917. async discoverSkills(request, options) {
  918. const outcome = await skillPort.discoverSkills(request, options);
  919. const next = skills(outcome.skills);
  920. return { ...outcome, skills: next, totalDiscovered: next.length };
  921. },
  922. });
  923. const withReviewSkill = withSkills((base) => [
  924. ...base,
  925. {
  926. ...base[0]!,
  927. name: "review",
  928. description: "review things",
  929. path: "/workspace/.agents/skills/review/SKILL.md",
  930. directory: "/workspace/.agents/skills/review",
  931. },
  932. ]);
  933. const skillsListingRecordTexts = (value: ReturnType<typeof createRecordingMessageStore>) =>
  934. value.savedParts
  935. .filter((part) => part.metadata?.runtimeMessage?.source === "skills_listing")
  936. .map((part) => String((part as { text?: string }).text));
  937. const historyIndexOfListing = (value: ReturnType<typeof createTestAgentRuntime>) =>
  938. (value as unknown as AgentRuntimeInternal).messageHistory
  939. .toRuntimeEntries()
  940. .findIndex(
  941. (entry) => entry.kind === "attachment" && entry.metadata.source === "skills_listing",
  942. );
  943. it("appends a new skill from the live catalog after a tool batch in an open session", async () => {
  944. // 实时目录端口:每次普通输入准备只读内存快照,不再调 discoverSkills。
  945. const base = (await skillPort.discoverSkills({ workingDirectory: "/workspace" })).skills;
  946. let catalog = { skills: base, diagnostics: [], totalDiscovered: base.length };
  947. const discoverSkills = vi.fn(async () => catalog);
  948. const livePort: SkillPort = {
  949. discoverSkills,
  950. currentCatalog: () => catalog,
  951. loadSkill: skillPort.loadSkill,
  952. };
  953. const registry = createToolRegistry();
  954. registry.register({
  955. inputSchema: {},
  956. metadata: {
  957. name: "WriteSkill",
  958. concurrentSafe: true,
  959. destructive: false,
  960. needsApproval: false,
  961. readOnly: true,
  962. riskLevel: "low",
  963. sideEffectScope: "none",
  964. },
  965. handler: async () => {
  966. const review = {
  967. ...base[0]!,
  968. name: "review",
  969. description: "review things",
  970. path: "/workspace/.agents/skills/review/SKILL.md",
  971. directory: "/workspace/.agents/skills/review",
  972. };
  973. catalog = { skills: [...base, review], diagnostics: [], totalDiscovered: 2 };
  974. return "written";
  975. },
  976. });
  977. // 与 agent listing 的工具批次用例相同:不带 SessionStore,工具权限不读项目规则。
  978. runtime = createRuntime(
  979. {
  980. skillPort: livePort,
  981. toolRegistry: registry,
  982. sessionStore: undefined,
  983. contextSourcePort: instructionsPort(),
  984. },
  985. config,
  986. );
  987. respond.mockResolvedValueOnce({
  988. ...result,
  989. text: "",
  990. finishReason: "tool-calls",
  991. toolCalls: [{ id: "write", name: "WriteSkill", input: {} }],
  992. });
  993. await runtime.executeTurn("write a skill");
  994. await runtime.executeTurn("continue");
  995. const listings = contextEntries(runtime).filter(
  996. (entry) => entry.metadata.source === "skills_listing",
  997. );
  998. expect(listings.map((entry) => entry.metadata.skillsListingDelta?.names)).toEqual([
  999. ["search"],
  1000. ["review"],
  1001. ]);
  1002. // 工具批次之后的请求就带上新 skill,之后的请求不重复。
  1003. expect(JSON.stringify(requests[0]!.messages)).not.toContain("- review: review things");
  1004. expect(JSON.stringify(requests[1]!.messages).split("- review: review things")).toHaveLength(2);
  1005. expect(JSON.stringify(requests[2]!.messages).split("- review: review things")).toHaveLength(2);
  1006. expect(discoverSkills).toHaveBeenCalledTimes(1);
  1007. expect(
  1008. (await runtime.getSkillCatalog(createRootTraceContext({ sessionId }))).skills.map(
  1009. (skill) => skill.name,
  1010. ),
  1011. ).toEqual(["search", "review"]);
  1012. });
  1013. it("keeps the restored skill listing and appends only the new skill after a cold resume", async () => {
  1014. runtime = createRuntime({ now, skillPort, contextSourcePort: instructionsPort() }, config);
  1015. await runtime.executeTurn("first");
  1016. const liveIndex = historyIndexOfListing(runtime);
  1017. const liveListing = contextEntries(runtime).find(
  1018. (entry) => entry.metadata.source === "skills_listing",
  1019. )!;
  1020. const { cold, coldStore } = await coldRuntimeWith(withReviewSkill);
  1021. const storedTexts = skillsListingRecordTexts(coldStore);
  1022. await cold.executeTurn("resumed");
  1023. await cold.executeTurn("again");
  1024. // 修复前冷恢复按当前目录原位改写旧列表,已发送的前缀字节改变,prompt cache 失效一次。
  1025. // 现在旧列表不动,新 skill 作为增量追加一次,之后不再重复。
  1026. const listings = contextEntries(cold).filter(
  1027. (entry) => entry.metadata.source === "skills_listing",
  1028. );
  1029. expect(listings).toHaveLength(2);
  1030. expect(listings[0]!.content).toBe(liveListing.content);
  1031. expect(listings[1]!.content).toBe(
  1032. "The following skills are available for use with the Skill tool:\n\n" +
  1033. "- review: review things (file: /workspace/.agents/skills/review/SKILL.md)",
  1034. );
  1035. expect(historyIndexOfListing(cold)).toBe(liveIndex);
  1036. const lastRequest = JSON.stringify(requests.at(-1)?.messages);
  1037. expect(lastRequest.split("- review: review things")).toHaveLength(2);
  1038. expect(lastRequest.split("- search: search things")).toHaveLength(2);
  1039. // 增量先持久化:库里多一条只含新 skill 的记录。
  1040. expect(skillsListingRecordTexts(coldStore)).toHaveLength(storedTexts.length + 1);
  1041. expect(storedTexts).toHaveLength(1);
  1042. });
  1043. it("does not announce removed skills after a cold resume", async () => {
  1044. runtime = createRuntime({ now, skillPort, contextSourcePort: instructionsPort() }, config);
  1045. await runtime.executeTurn("first");
  1046. const liveListing = contextEntries(runtime).filter(
  1047. (entry) => entry.metadata.source === "skills_listing",
  1048. );
  1049. const { cold, coldStore } = await coldRuntimeWith(withSkills(() => []));
  1050. const storedTexts = skillsListingRecordTexts(coldStore);
  1051. await cold.executeTurn("resumed");
  1052. // 删除不发通知,也不改写已发送的列表;模型调用已删除的 skill 时由 Skill tool 返回 not found。
  1053. expect(
  1054. contextEntries(cold).filter((entry) => entry.metadata.source === "skills_listing"),
  1055. ).toEqual(liveListing);
  1056. expect(skillsListingRecordTexts(coldStore)).toEqual(storedTexts);
  1057. });
  1058. it("replays the stored delta after a rewind reloads history from the store", async () => {
  1059. runtime = createRuntime({ now, skillPort, contextSourcePort: instructionsPort() }, config);
  1060. await runtime.executeTurn("first");
  1061. const { cold, coldStore } = await coldRuntimeWith(withReviewSkill);
  1062. await cold.executeTurn("resumed");
  1063. await cold.executeTurn("again");
  1064. const againPart = coldStore.savedParts.find(
  1065. (part) => (part as { text?: string }).text === "again",
  1066. );
  1067. expect(againPart).toBeDefined();
  1068. const recordsBefore = skillsListingRecordTexts(coldStore).length;
  1069. await cold.rewindConversationToMessage({
  1070. events: [],
  1071. targetMessageId: againPart!.messageID,
  1072. traceContext: createRootTraceContext({ sessionId }),
  1073. });
  1074. await cold.executeTurn("edited");
  1075. // rewind 从库重新加载历史:增量的指纹随记录恢复,不重发也不改写。
  1076. const listings = contextEntries(cold).filter(
  1077. (entry) => entry.metadata.source === "skills_listing",
  1078. );
  1079. expect(listings).toHaveLength(2);
  1080. expect(skillsListingRecordTexts(coldStore)).toHaveLength(recordsBefore);
  1081. expect(JSON.stringify(requests.at(-1)?.messages).split("- review: review things")).toHaveLength(
  1082. 2,
  1083. );
  1084. });
  1085. describe("instruction announcements after a history load", () => {
  1086. const cliStorageRoot = "/storage/cli";
  1087. const memoryConfig: Partial<AgentRuntimeConfig> = {
  1088. ...config,
  1089. memory: { cliStorageRoot, enabled: true, use: true },
  1090. };
  1091. const indexPath = join(
  1092. resolveProjectMemoryRoot({ cliStorageRoot, workspacePath: "/workspace" }),
  1093. "MEMORY.md",
  1094. );
  1095. const oldIndex = "- [Old policy](old-policy.md) — announced before the restart";
  1096. const newIndex = "- [New policy](new-policy.md) — written to disk after the announcement";
  1097. const memoryType = "user's auto-memory, persists across conversations";
  1098. const projectType = "project instructions, checked into the codebase";
  1099. const resumedChange =
  1100. "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:";
  1101. const instructionTexts = (value: ReturnType<typeof createTestAgentRuntime>) =>
  1102. contextEntries(value)
  1103. .filter((entry) => entry.metadata.source === "context_prefix")
  1104. .map((entry) => entry.content);
  1105. const instructionRecords = (value: ReturnType<typeof createRecordingMessageStore>) =>
  1106. value.savedParts.filter((part) => part.metadata?.runtimeMessage?.source === "context_prefix");
  1107. const instructionRecordTexts = (value: ReturnType<typeof createRecordingMessageStore>) =>
  1108. instructionRecords(value).map((part) => String((part as { text?: string }).text));
  1109. // AGENTS.md 的内容可在测试中修改,端口每次读取时取当前值;unreadable 时端口报读取失败的诊断。
  1110. const agentsFile = {
  1111. content: "Project rule." as string | undefined,
  1112. unreadable: false,
  1113. };
  1114. beforeEach(() => {
  1115. agentsFile.unreadable = false;
  1116. });
  1117. const agentsPort = (): ContextSourcePort => ({
  1118. ...instructionsPort(),
  1119. async resolveContextSources() {
  1120. const content = agentsFile.content;
  1121. if (agentsFile.unreadable) {
  1122. return {
  1123. workingDirectory: "/workspace",
  1124. envInfo: config.envInfo!,
  1125. diagnostics: [
  1126. {
  1127. code: "user_instructions_read_failed",
  1128. message: "EACCES: permission denied",
  1129. path: "/workspace/AGENTS.md",
  1130. },
  1131. ],
  1132. };
  1133. }
  1134. return {
  1135. workingDirectory: "/workspace",
  1136. envInfo: config.envInfo!,
  1137. ...(content === undefined
  1138. ? {}
  1139. : {
  1140. userInstructions: {
  1141. filePath: "/workspace/AGENTS.md",
  1142. fileName: "AGENTS.md",
  1143. content,
  1144. bytesRead: content.length,
  1145. sizeBytes: content.length,
  1146. truncated: false,
  1147. },
  1148. }),
  1149. diagnostics: [],
  1150. };
  1151. },
  1152. });
  1153. const announceOldIndexThenChangeDisk = async () => {
  1154. agentsFile.content = "Project rule.";
  1155. const files = new MemoryFileSystem({ [indexPath]: oldIndex });
  1156. runtime = createRuntime(
  1157. { now, skillPort, contextSourcePort: agentsPort(), fileSystemPort: files },
  1158. memoryConfig,
  1159. );
  1160. await runtime.executeTurn("first");
  1161. expect(instructionTexts(runtime)).toEqual([expect.stringContaining(oldIndex)]);
  1162. files.files[indexPath] = newIndex;
  1163. return files;
  1164. };
  1165. const resumeWith = (
  1166. files: MemoryFileSystem,
  1167. coldConfig = memoryConfig,
  1168. coldDeps: Partial<AgentRuntimeDeps> = {},
  1169. ) =>
  1170. coldRuntimeWith(skillPort, coldConfig, {
  1171. fileSystemPort: files,
  1172. contextSourcePort: agentsPort(),
  1173. ...coldDeps,
  1174. });
  1175. // 权限错误:文件在,但读不出来。
  1176. const denyReads = (files: MemoryFileSystem, path: string) => {
  1177. const read = files.readTextFile.bind(files);
  1178. files.readTextFile = async (request) => {
  1179. if (request.path !== path) return read(request);
  1180. throw createFileSystemError({
  1181. code: "permission_denied",
  1182. path,
  1183. message: `Permission denied for path: ${path}`,
  1184. });
  1185. };
  1186. return files;
  1187. };
  1188. const warningLogger = () => {
  1189. const warnings: unknown[] = [];
  1190. const logger = {
  1191. debug() {},
  1192. info() {},
  1193. warn: (_message: string, context?: unknown) => warnings.push(context),
  1194. error() {},
  1195. child: () => logger,
  1196. };
  1197. return { logger: logger as never, warnings };
  1198. };
  1199. it("keeps the sent announcement and appends a delta for the Memory index read on resume", async () => {
  1200. const files = await announceOldIndexThenChangeDisk();
  1201. const { cold, coldStore } = await resumeWith(files);
  1202. const [firstRecord] = instructionRecordTexts(coldStore);
  1203. await cold.executeTurn("resumed");
  1204. // 修复原因:恢复时原位改写已发的公告,前缀字节改变;现在原公告不动,变化追加在末尾。
  1205. const texts = instructionTexts(cold);
  1206. expect(texts).toEqual([
  1207. firstRecord,
  1208. `${resumedChange}\n\nContents of ${indexPath} (${memoryType}):\n\n${newIndex}`,
  1209. ]);
  1210. expect(firstRecord).toContain(oldIndex);
  1211. const lastRequest = JSON.stringify(requests.at(-1)?.messages);
  1212. expect(lastRequest).toContain(oldIndex);
  1213. expect(lastRequest.split(newIndex)).toHaveLength(2);
  1214. expect(lastRequest).not.toContain("runtimeMessage");
  1215. // 增量落库,带上只给 runtime 用的文件记录。
  1216. const records = instructionRecords(coldStore);
  1217. expect(records).toHaveLength(2);
  1218. expect(records[1]!.metadata?.runtimeMessage?.instructions).toEqual({
  1219. files: [{ path: indexPath, type: memoryType, hash: expect.any(String) }],
  1220. reason: "session_start",
  1221. });
  1222. // 读文件状态记录磁盘上的新索引,也就是模型最近被告知的内容;Write 按它检查。
  1223. const readState = (cold as unknown as AgentRuntimeInternal).readFileState.get(
  1224. createReadFileStatePathKey(indexPath),
  1225. );
  1226. expect(readState?.content).toBe(newIndex);
  1227. Object.assign(coldStore, { getProjectPermission: async () => null });
  1228. const write = await cold.getToolExecutor().execute({
  1229. id: createToolCallId("write-memory-index-after-resume"),
  1230. input: { content: `${newIndex}\n- [Added](added.md) — added`, file_path: indexPath },
  1231. name: "Write",
  1232. });
  1233. expect(write.success).toBe(true);
  1234. // 之后的请求和下一次冷恢复都不再重复宣告。
  1235. await cold.executeTurn("again");
  1236. expect(instructionTexts(cold)).toHaveLength(2);
  1237. files.files[indexPath] = newIndex;
  1238. store = coldStore;
  1239. const { cold: second } = await resumeWith(files);
  1240. await second.executeTurn("second resume");
  1241. expect(instructionTexts(second)).toEqual(texts);
  1242. });
  1243. it("appends nothing when the files are unchanged on resume", async () => {
  1244. const files = await announceOldIndexThenChangeDisk();
  1245. files.files[indexPath] = oldIndex;
  1246. const { cold, coldStore } = await resumeWith(files);
  1247. const stored = instructionRecordTexts(coldStore);
  1248. await cold.executeTurn("resumed");
  1249. expect(instructionTexts(cold)).toEqual(stored);
  1250. expect(instructionRecordTexts(coldStore)).toEqual(stored);
  1251. });
  1252. it("announces only the changed instruction file", async () => {
  1253. const files = await announceOldIndexThenChangeDisk();
  1254. files.files[indexPath] = oldIndex;
  1255. agentsFile.content = "Updated project rule.";
  1256. const { cold } = await resumeWith(files);
  1257. await cold.executeTurn("resumed");
  1258. expect(instructionTexts(cold).at(-1)).toBe(
  1259. `${resumedChange}\n\nContents of /workspace/AGENTS.md (${projectType}):\n\nUpdated project rule.`,
  1260. );
  1261. });
  1262. it("compares against a legacy record without file metadata", async () => {
  1263. const files = await announceOldIndexThenChangeDisk();
  1264. // 升级前写入的完整公告没有 metadata:按标题行拆出文件,没变的 AGENTS.md 不再宣告。
  1265. for (const part of instructionRecords(store)) {
  1266. delete (part.metadata!.runtimeMessage as Record<string, unknown>).instructions;
  1267. }
  1268. const { cold } = await resumeWith(files);
  1269. await cold.executeTurn("resumed");
  1270. expect(instructionTexts(cold).at(-1)).toBe(
  1271. `${resumedChange}\n\nContents of ${indexPath} (${memoryType}):\n\n${newIndex}`,
  1272. );
  1273. });
  1274. it("re-announces a delta after a rewind removes it from history", async () => {
  1275. const files = await announceOldIndexThenChangeDisk();
  1276. const { cold, coldStore } = await resumeWith(files);
  1277. await cold.executeTurn("resumed");
  1278. const resumedPart = coldStore.savedParts.find(
  1279. (part) => (part as { text?: string }).text === "resumed",
  1280. );
  1281. expect(resumedPart).toBeDefined();
  1282. await cold.rewindConversationToMessage({
  1283. events: [],
  1284. targetMessageId: resumedPart!.messageID,
  1285. traceContext: createRootTraceContext({ sessionId }),
  1286. });
  1287. await cold.executeTurn("edited");
  1288. // 已公告的文件只从剩余历史推出:增量随回退离开历史,下一次请求重新追加一次。
  1289. const texts = instructionTexts(cold);
  1290. expect(texts).toHaveLength(2);
  1291. expect(texts[0]).toContain(oldIndex);
  1292. expect(texts[1]).toContain(newIndex);
  1293. });
  1294. it("announces files that are no longer present", async () => {
  1295. await announceOldIndexThenChangeDisk();
  1296. agentsFile.content = undefined;
  1297. const { cold } = await resumeWith(new MemoryFileSystem({}), config);
  1298. await cold.executeTurn("resumed");
  1299. // 当前没有指令文件和 Memory 索引:原公告不动,追加一条撤回说明。
  1300. const texts = instructionTexts(cold);
  1301. expect(texts).toHaveLength(2);
  1302. expect(texts[0]).toContain(oldIndex);
  1303. expect(texts[1]).toBe(
  1304. [
  1305. "Instruction files were re-read when this session started.",
  1306. "Instructions no longer present: /workspace/AGENTS.md",
  1307. `Instructions no longer present: ${indexPath}`,
  1308. ].join("\n\n"),
  1309. );
  1310. });
  1311. it("announces a file that the earlier announcement did not have", async () => {
  1312. agentsFile.content = undefined;
  1313. const files = new MemoryFileSystem({ [indexPath]: oldIndex });
  1314. runtime = createRuntime(
  1315. { now, skillPort, contextSourcePort: agentsPort(), fileSystemPort: files },
  1316. memoryConfig,
  1317. );
  1318. await runtime.executeTurn("first");
  1319. agentsFile.content = "Project rule.";
  1320. const { cold } = await resumeWith(files);
  1321. await cold.executeTurn("resumed");
  1322. expect(instructionTexts(cold).at(-1)).toBe(
  1323. `${resumedChange}\n\nContents of /workspace/AGENTS.md (${projectType}):\n\nProject rule.`,
  1324. );
  1325. });
  1326. it("puts changed and removed files in one delta", async () => {
  1327. await announceOldIndexThenChangeDisk();
  1328. agentsFile.content = "Updated project rule.";
  1329. const { cold } = await resumeWith(new MemoryFileSystem({}));
  1330. await cold.executeTurn("resumed");
  1331. expect(instructionTexts(cold).at(-1)).toBe(
  1332. `${resumedChange}\n\nContents of /workspace/AGENTS.md (${projectType}):\n\nUpdated project rule.\n\nInstructions no longer present: ${indexPath}`,
  1333. );
  1334. });
  1335. it("compares a later change against the latest delta", async () => {
  1336. const files = await announceOldIndexThenChangeDisk();
  1337. const { cold, coldStore } = await resumeWith(files);
  1338. await cold.executeTurn("resumed");
  1339. // 第二次冷恢复:基准是完整公告加上一条增量,只宣告相对增量的新变化。
  1340. const thirdIndex = "- [Third policy](third-policy.md) — written after the first delta";
  1341. files.files[indexPath] = thirdIndex;
  1342. store = coldStore;
  1343. const { cold: second } = await resumeWith(files);
  1344. await second.executeTurn("second resume");
  1345. const texts = instructionTexts(second);
  1346. expect(texts).toHaveLength(3);
  1347. expect(texts[2]).toBe(
  1348. `${resumedChange}\n\nContents of ${indexPath} (${memoryType}):\n\n${thirdIndex}`,
  1349. );
  1350. });
  1351. it("announces a file again after a delta removed it", async () => {
  1352. await announceOldIndexThenChangeDisk();
  1353. agentsFile.content = undefined;
  1354. const { cold, coldStore } = await resumeWith(new MemoryFileSystem({}), config);
  1355. await cold.executeTurn("resumed");
  1356. agentsFile.content = "Project rule.";
  1357. store = coldStore;
  1358. const { cold: second } = await resumeWith(new MemoryFileSystem({}), config);
  1359. await second.executeTurn("second resume");
  1360. expect(instructionTexts(second).at(-1)).toBe(
  1361. `${resumedChange}\n\nContents of /workspace/AGENTS.md (${projectType}):\n\nProject rule.`,
  1362. );
  1363. });
  1364. // 修复原因:读取出错一律当成文件不存在,权限、占用等临时错误被宣告成 "Instructions no longer present"。
  1365. it("does not announce an unreadable file as removed on resume", async () => {
  1366. const files = await announceOldIndexThenChangeDisk();
  1367. agentsFile.unreadable = true;
  1368. const { logger, warnings } = warningLogger();
  1369. const { cold } = await resumeWith(files, memoryConfig, { logger });
  1370. await cold.executeTurn("resumed");
  1371. // AGENTS.md 读不出来:不算删除,模型保留已宣告的副本;MEMORY.md 照常比较。
  1372. expect(instructionTexts(cold).at(-1)).toBe(
  1373. `${resumedChange}\n\nContents of ${indexPath} (${memoryType}):\n\n${newIndex}`,
  1374. );
  1375. expect(warnings).toContainEqual(
  1376. expect.objectContaining({
  1377. event: "context.instructions.read_failed",
  1378. path: "/workspace/AGENTS.md",
  1379. }),
  1380. );
  1381. });
  1382. it("does not announce an unreadable Memory index as removed on resume", async () => {
  1383. const files = await announceOldIndexThenChangeDisk();
  1384. const { logger, warnings } = warningLogger();
  1385. const { cold } = await resumeWith(denyReads(files, indexPath), memoryConfig, { logger });
  1386. await cold.executeTurn("resumed");
  1387. expect(instructionTexts(cold)).toHaveLength(1);
  1388. expect(warnings).toContainEqual(
  1389. expect.objectContaining({ event: "context.instructions.read_failed", path: indexPath }),
  1390. );
  1391. });
  1392. it("drops the compaction re-read when a held file cannot be read", async () => {
  1393. const files = await announceOldIndexThenChangeDisk();
  1394. agentsFile.unreadable = true;
  1395. const compacted = await compact(runtime, CompactTrigger.Manual);
  1396. expect(compacted.outcome).toBe("compacted");
  1397. await runtime.executeTurn("after compact");
  1398. // AGENTS.md 是 runtime 持有的文件:整次重读作废,沿用原内容,MEMORY.md 的变化留到下一次读取。
  1399. const texts = instructionTexts(runtime);
  1400. expect(texts).toHaveLength(1);
  1401. expect(texts[0]).toContain("Project rule.");
  1402. expect(texts[0]).toContain(oldIndex);
  1403. expect((runtime as unknown as AgentRuntimeInternal).instructionRefreshReason).toBeUndefined();
  1404. expect(texts[0]).not.toContain(newIndex);
  1405. expect(files.readRequests.filter((request) => request.path === indexPath)).toHaveLength(2);
  1406. });
  1407. it("drops the compaction re-read when the held Memory index cannot be read", async () => {
  1408. const files = await announceOldIndexThenChangeDisk();
  1409. denyReads(files, indexPath);
  1410. agentsFile.content = "Rule changed during the session.";
  1411. const compacted = await compact(runtime, CompactTrigger.Manual);
  1412. expect(compacted.outcome).toBe("compacted");
  1413. await runtime.executeTurn("after compact");
  1414. const texts = instructionTexts(runtime);
  1415. expect(texts).toHaveLength(1);
  1416. expect(texts[0]).toContain("Project rule.");
  1417. expect(texts[0]).toContain(oldIndex);
  1418. });
  1419. it("adopts the compaction re-read when the unreadable file is not held", async () => {
  1420. agentsFile.unreadable = true;
  1421. const files = new MemoryFileSystem({ [indexPath]: oldIndex });
  1422. runtime = createRuntime(
  1423. { now, skillPort, contextSourcePort: agentsPort(), fileSystemPort: files },
  1424. memoryConfig,
  1425. );
  1426. await runtime.executeTurn("first");
  1427. files.files[indexPath] = newIndex;
  1428. const compacted = await compact(runtime, CompactTrigger.Manual);
  1429. expect(compacted.outcome).toBe("compacted");
  1430. await runtime.executeTurn("after compact");
  1431. // 一直读不出来的 AGENTS.md 不在 runtime 持有的内容里,不阻止重读;MEMORY.md 的变化照常采用。
  1432. const texts = instructionTexts(runtime);
  1433. expect(texts).toHaveLength(1);
  1434. expect(texts[0]).toContain(newIndex);
  1435. expect(texts[0]).not.toContain("AGENTS.md");
  1436. expect((runtime as unknown as AgentRuntimeInternal).instructionRefreshReason).toBe(
  1437. "compaction",
  1438. );
  1439. });
  1440. it("keeps the earlier instructions when the compaction re-read fails", async () => {
  1441. const warnings: unknown[] = [];
  1442. const logger = {
  1443. debug() {},
  1444. info() {},
  1445. warn: (_message: string, context?: unknown) => warnings.push(context),
  1446. error() {},
  1447. child: () => logger,
  1448. };
  1449. agentsFile.content = "Project rule.";
  1450. let failReads = false;
  1451. const port = agentsPort();
  1452. runtime = createRuntime(
  1453. {
  1454. now,
  1455. skillPort,
  1456. logger: logger as never,
  1457. contextSourcePort: {
  1458. ...port,
  1459. async resolveContextSources(input, options) {
  1460. if (failReads) throw new Error("disk busy");
  1461. return port.resolveContextSources(input, options);
  1462. },
  1463. },
  1464. },
  1465. config,
  1466. );
  1467. await runtime.executeTurn("first");
  1468. failReads = true;
  1469. agentsFile.content = "Rule changed during the session.";
  1470. const compacted = await compact(runtime, CompactTrigger.Manual);
  1471. expect(compacted.outcome).toBe("compacted");
  1472. expect(warnings).toContainEqual(
  1473. expect.objectContaining({
  1474. event: "context.instructions.reread_failed",
  1475. error: "disk busy",
  1476. }),
  1477. );
  1478. await runtime.executeTurn("after compact");
  1479. const texts = instructionTexts(runtime);
  1480. expect(texts).toHaveLength(1);
  1481. expect(texts[0]).toContain("Project rule.");
  1482. expect(texts[0]).not.toContain("Rule changed during the session.");
  1483. // 没有重读结果的 compaction 不改指令增量的 reason。
  1484. expect((runtime as unknown as AgentRuntimeInternal).instructionRefreshReason).toBeUndefined();
  1485. });
  1486. it("cancels the compaction when it is aborted during the instruction re-read", async () => {
  1487. agentsFile.content = "Project rule.";
  1488. const controller = new AbortController();
  1489. let abortOnRead = false;
  1490. const port = agentsPort();
  1491. runtime = createRuntime(
  1492. {
  1493. now,
  1494. skillPort,
  1495. contextSourcePort: {
  1496. ...port,
  1497. async resolveContextSources(input, options) {
  1498. if (abortOnRead) {
  1499. controller.abort();
  1500. throw new Error("read aborted");
  1501. }
  1502. return port.resolveContextSources(input, options);
  1503. },
  1504. },
  1505. },
  1506. config,
  1507. );
  1508. await runtime.executeTurn("first");
  1509. const before = entries();
  1510. abortOnRead = true;
  1511. agentsFile.content = "Rule changed during the session.";
  1512. await expect(
  1513. (runtime as unknown as AgentRuntimeInternal).compactActiveConversation(
  1514. undefined,
  1515. createRootTraceContext({ sessionId }),
  1516. [],
  1517. { abortSignal: controller.signal, trigger: CompactTrigger.Manual },
  1518. ),
  1519. ).rejects.toThrow();
  1520. // 取消时不采用重读的内容,历史保持 compact 之前的样子。
  1521. expect(entries()).toEqual(before);
  1522. expect(
  1523. (
  1524. runtime as unknown as AgentRuntimeInternal
  1525. ).latestContextBuildResult?.metaUserAttachments.find(
  1526. (item) => item.source === "context_prefix",
  1527. )?.content,
  1528. ).toContain("Project rule.");
  1529. });
  1530. it("re-reads instruction files at the end of a compaction", async () => {
  1531. const files = await announceOldIndexThenChangeDisk();
  1532. agentsFile.content = "Rule changed during the session.";
  1533. const compacted = await compact(runtime, CompactTrigger.Manual);
  1534. expect(compacted.outcome).toBe("compacted");
  1535. // 修复原因:compaction 原来沿用 runtime 启动时的内容;现在收尾时重读,新内容进入新窗口。
  1536. const readState = (runtime as unknown as AgentRuntimeInternal).readFileState.get(
  1537. createReadFileStatePathKey(indexPath),
  1538. );
  1539. expect(readState?.content).toBe(newIndex);
  1540. await runtime.executeTurn("after compact");
  1541. const texts = instructionTexts(runtime);
  1542. expect(texts).toHaveLength(1);
  1543. expect(texts[0]).toContain("Rule changed during the session.");
  1544. expect(texts[0]).toContain(newIndex);
  1545. expect(texts[0]).not.toContain(oldIndex);
  1546. expect(files.readRequests.filter((request) => request.path === indexPath)).toHaveLength(2);
  1547. });
  1548. it("places only a full block before the summary, and only when the kept tail has no full block", () => {
  1549. runtime = createRuntime({ now, skillPort, contextSourcePort: instructionsPort() }, config);
  1550. const internal = runtime as unknown as AgentRuntimeInternal;
  1551. const built = (content: string, body: string) =>
  1552. ({
  1553. sections: [],
  1554. metaUserAttachments: [
  1555. {
  1556. source: "context_prefix",
  1557. content,
  1558. files: [{ path: "/workspace/AGENTS.md", type: projectType, body }],
  1559. },
  1560. ],
  1561. }) as never;
  1562. internal.latestContextBuildResult = built("held full", "Project rule.");
  1563. const reread = built("re-read full", "Rule changed during the session.");
  1564. const oldFull = systemReminderAttachmentEntry(
  1565. "context_prefix",
  1566. `Preamble\n\nContents of /workspace/AGENTS.md (${projectType}):\n\nOld rule.`,
  1567. );
  1568. const done = { message: { role: "assistant" as const, content: "Done." } };
  1569. const leadingInstructions = (
  1570. kept: Parameters<typeof buildCompactLeadingAnnouncements>[1],
  1571. source?: Parameters<typeof buildCompactLeadingAnnouncements>[3],
  1572. ) =>
  1573. buildCompactLeadingAnnouncements(internal, kept, undefined, source)
  1574. .filter((entry) => entry.metadata.source === "context_prefix")
  1575. .map((entry) => entry.content);
  1576. // 保留段有完整块:summary 之前不放,内容变化由下一次请求追加增量。
  1577. // 修复原因:原来在 summary 之前放增量,增量排在保留段的旧公告之前,下一次请求又追加一次。
  1578. expect(leadingInstructions([oldFull, done], reread)).toEqual([]);
  1579. // 保留段只有增量:增量不算基准,放重读内容的完整块。
  1580. const keptDelta = {
  1581. ...systemReminderAttachmentEntry("context_prefix", "delta"),
  1582. metadata: {
  1583. source: "context_prefix" as const,
  1584. instructions: {
  1585. files: [{ path: "/workspace/AGENTS.md", type: projectType, hash: "h" }],
  1586. reason: "session_start" as const,
  1587. },
  1588. },
  1589. };
  1590. expect(leadingInstructions([keptDelta, done], reread)).toEqual(["re-read full"]);
  1591. // 保留段没有指令公告:放完整块;没有重读结果时用 runtime 持有的内容。
  1592. expect(leadingInstructions([done], reread)).toEqual(["re-read full"]);
  1593. expect(leadingInstructions([done])).toEqual(["held full"]);
  1594. });
  1595. it("uses the reason held by the runtime for request deltas", () => {
  1596. runtime = createRuntime({ now, skillPort, contextSourcePort: instructionsPort() }, config);
  1597. const internal = runtime as unknown as AgentRuntimeInternal;
  1598. internal.latestContextBuildResult = {
  1599. sections: [],
  1600. metaUserAttachments: [
  1601. {
  1602. source: "context_prefix",
  1603. content: "full",
  1604. files: [createInstructionFile("/workspace/AGENTS.md", projectType, "Project rule.")],
  1605. },
  1606. ],
  1607. } as never;
  1608. const history = [
  1609. systemReminderAttachmentEntry(
  1610. "context_prefix",
  1611. `Preamble\n\nContents of /workspace/AGENTS.md (${projectType}):\n\nOld rule.`,
  1612. ),
  1613. ];
  1614. const delta = () =>
  1615. buildRequestAnnouncements(internal, history).find(
  1616. (entry) => entry.metadata.source === "context_prefix",
  1617. );
  1618. expect(delta()?.content).toBe(
  1619. `${resumedChange}\n\nContents of /workspace/AGENTS.md (${projectType}):\n\nProject rule.`,
  1620. );
  1621. internal.instructionRefreshReason = "compaction";
  1622. expect(delta()?.content).toBe(
  1623. `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.`,
  1624. );
  1625. expect(delta()?.metadata).toMatchObject({ instructions: { reason: "compaction" } });
  1626. // 正文相同、类型变了(同一路径从用户级变为项目级)也算变化。
  1627. const retyped = [
  1628. systemReminderAttachmentEntry(
  1629. "context_prefix",
  1630. `Preamble\n\nContents of /workspace/AGENTS.md (user's private global instructions for all projects):\n\nProject rule.`,
  1631. ),
  1632. ];
  1633. expect(
  1634. buildRequestAnnouncements(internal, retyped).filter(
  1635. (entry) => entry.metadata.source === "context_prefix",
  1636. ),
  1637. ).toHaveLength(1);
  1638. });
  1639. // 优化原因:持有的文件只在读取时变化,原来每次请求前都对每个文件重新算 sha256。
  1640. it("hashes the held files once when they are built, and compares stored hashes on requests", () => {
  1641. const rule = "\n\nProject rule.\n\n";
  1642. const built = createContextBuilder({
  1643. workingDirectory: "/workspace",
  1644. envInfo: config.envInfo!,
  1645. userInstructions: {
  1646. filePath: "/workspace/AGENTS.md",
  1647. fileName: "AGENTS.md",
  1648. content: rule,
  1649. bytesRead: rule.length,
  1650. sizeBytes: rule.length,
  1651. truncated: false,
  1652. },
  1653. }).build();
  1654. const [file] =
  1655. built.metaUserAttachments.find((item) => item.source === "context_prefix")?.files ?? [];
  1656. // 构建时去掉首尾空白并算好 hash。
  1657. expect(file).toEqual({
  1658. path: "/workspace/AGENTS.md",
  1659. type: projectType,
  1660. body: "Project rule.",
  1661. hash: createHash("sha256").update("Project rule.").digest("hex"),
  1662. });
  1663. // 请求时只比较存好的 hash:持有文件的 hash 与历史记录相同就不宣告,不按正文重算。
  1664. runtime = createRuntime({ now, skillPort, contextSourcePort: instructionsPort() }, config);
  1665. const internal = runtime as unknown as AgentRuntimeInternal;
  1666. const held = { ...file!, hash: "stored-hash" };
  1667. internal.latestContextBuildResult = {
  1668. sections: [],
  1669. metaUserAttachments: [{ source: "context_prefix", content: "full", files: [held] }],
  1670. } as never;
  1671. const history = [
  1672. {
  1673. ...systemReminderAttachmentEntry("context_prefix", "full"),
  1674. metadata: {
  1675. source: "context_prefix" as const,
  1676. instructions: { files: [{ path: held.path, type: held.type, hash: "stored-hash" }] },
  1677. },
  1678. },
  1679. ];
  1680. expect(
  1681. buildRequestAnnouncements(internal, history).filter(
  1682. (entry) => entry.metadata.source === "context_prefix",
  1683. ),
  1684. ).toEqual([]);
  1685. });
  1686. it("adopts the re-read only when the compaction commits", async () => {
  1687. let failCommit = true;
  1688. Object.assign(store, {
  1689. async commitMessageBundle(bundle: { messages: { info: never; parts: never[] }[] }) {
  1690. if (failCommit) throw new Error("disk full");
  1691. for (const message of bundle.messages) {
  1692. store.savedMessages.push(message.info);
  1693. store.savedParts.push(...message.parts);
  1694. }
  1695. },
  1696. });
  1697. agentsFile.content = "Project rule.";
  1698. runtime = createRuntime({ now, skillPort, contextSourcePort: agentsPort() }, config);
  1699. const internal = runtime as unknown as AgentRuntimeInternal;
  1700. const held = () =>
  1701. internal.latestContextBuildResult?.metaUserAttachments.find(
  1702. (item) => item.source === "context_prefix",
  1703. )?.content;
  1704. await runtime.executeTurn("first");
  1705. await runtime.executeTurn("second");
  1706. agentsFile.content = "Rule changed during the session.";
  1707. await expect(compact(runtime, CompactTrigger.Reactive)).rejects.toThrow("disk full");
  1708. // 修复原因:重读结果原来在落库之前交给 runtime;写库失败后 runtime 已持有新内容,
  1709. // 下一次请求以 session_start 为原因宣告。现在写库失败时内容与 reason 都不变。
  1710. expect(held()).toContain("Project rule.");
  1711. expect(held()).not.toContain("Rule changed during the session.");
  1712. expect(internal.instructionRefreshReason).toBeUndefined();
  1713. failCommit = false;
  1714. await compact(runtime, CompactTrigger.Reactive);
  1715. expect(held()).toContain("Rule changed during the session.");
  1716. expect(internal.instructionRefreshReason).toBe("compaction");
  1717. await runtime.executeTurn("after compact");
  1718. // 保留段没有完整块:summary 之前放重读内容的完整块,之后的请求不再追加增量。
  1719. const texts = instructionTexts(runtime);
  1720. expect(texts).toHaveLength(1);
  1721. expect(texts[0]).toContain("Rule changed during the session.");
  1722. });
  1723. it("announces a change found when the same runtime resumes with the session-start reason", async () => {
  1724. agentsFile.content = "Project rule.";
  1725. runtime = createRuntime({ now, skillPort, contextSourcePort: agentsPort() }, config);
  1726. const internal = runtime as unknown as AgentRuntimeInternal;
  1727. await runtime.executeTurn("first");
  1728. await runtime.executeTurn("second");
  1729. agentsFile.content = "Rule changed before the compaction.";
  1730. await compact(runtime, CompactTrigger.Reactive);
  1731. expect(internal.instructionRefreshReason).toBe("compaction");
  1732. // 同一个 runtime 再次恢复(bootstrap 复用 runtime)时,启动时重读的文件是本次恢复读到的,
  1733. // 不是 compaction 重读的。
  1734. agentsFile.content = "Rule changed before the resume.";
  1735. await runtime.resumeFromStore();
  1736. expect(internal.instructionRefreshReason).toBeUndefined();
  1737. await runtime.executeTurn("after resume");
  1738. const latest = instructionTexts(runtime).at(-1);
  1739. expect(latest).toContain("Rule changed before the resume.");
  1740. expect(latest?.startsWith(resumedChange)).toBe(true);
  1741. });
  1742. });
  1743. it.each([CompactTrigger.Reactive, CompactTrigger.Manual])(
  1744. "lays out the post-compact context in announcement order after compact=%s",
  1745. async (trigger) => {
  1746. runtime = createRuntime({ now, skillPort, contextSourcePort: instructionsPort() }, config);
  1747. await runtime.executeTurn("first");
  1748. await runtime.executeTurn("second");
  1749. const compacted = await compact(runtime, trigger);
  1750. expect(compacted.outcome).toBe("compacted");
  1751. const layout = (value: ReturnType<typeof createTestAgentRuntime>) =>
  1752. (value as unknown as AgentRuntimeInternal).messageHistory
  1753. .toRuntimeEntries()
  1754. .filter((entry) => entry.kind === "attachment" || entry.message.role !== "system")
  1755. .map((entry) =>
  1756. entry.kind === "attachment"
  1757. ? entry.metadata.source
  1758. : String(entry.message.content).startsWith("This session is being continued")
  1759. ? "summary"
  1760. : entry.message.role,
  1761. );
  1762. const live = layout(runtime);
  1763. const summaryIndex = live.indexOf("summary");
  1764. const tail = live.slice(summaryIndex + 1);
  1765. // 保留段非空时,请求前公告放在 summary 之前,且不重复保留段已有的来源。
  1766. const leading = live.slice(0, summaryIndex);
  1767. const requestSources = ["context_prefix", "session_context", "date"];
  1768. if (trigger === CompactTrigger.Reactive) {
  1769. expect(leading).toEqual(requestSources.filter((source) => !tail.includes(source)));
  1770. } else {
  1771. expect(leading).toEqual([]);
  1772. }
  1773. // compaction 附件末尾:agent listing → skill 列表 → environment → model。
  1774. // compaction 必须产出 skill 列表,否则 compact 后第一次请求看不到 skill 名单。
  1775. expect(tail.slice(-4)).toEqual([
  1776. "agent_listing_delta",
  1777. "skills_listing",
  1778. "environment",
  1779. "model",
  1780. ]);
  1781. for (const source of ["skills_listing", "environment", "model"]) {
  1782. expect(tail.filter((item) => item === source)).toHaveLength(1);
  1783. }
  1784. // 存储顺序与 live 一致:公告写在 summary 之前,并由 summary 的 compaction part 声明。
  1785. const summaryRow = store.savedMessages.findIndex(
  1786. (message) => message.semantics?.kind === "compact_summary",
  1787. );
  1788. const declared =
  1789. store.savedParts.find((part) => part.type === "compaction" && part.compactBoundary)
  1790. ?.metadata?.compactLeadingMessageIds ?? [];
  1791. expect(declared).toHaveLength(leading.length);
  1792. expect(
  1793. store.savedMessages
  1794. .slice(summaryRow - declared.length, summaryRow)
  1795. .map((message) => message.id),
  1796. ).toEqual(declared);
  1797. // 冷恢复得到相同布局。
  1798. const { cold } = await coldRuntimeWith();
  1799. expect(layout(cold)).toEqual(live);
  1800. },
  1801. );
  1802. it("does not place a date before the summary when the kept tail already has one", () => {
  1803. // 保留段里已有 date 类型的公告(哪怕已过期)时,summary 之前不放日期;
  1804. // 之后的请求以保留段里的旧日期为基准,在末尾宣告一次日期变化。
  1805. runtime = createRuntime(
  1806. { now: () => new Date(2026, 9, 15, 0, 10), skillPort, contextSourcePort: instructionsPort() },
  1807. config,
  1808. );
  1809. const internal = runtime as unknown as AgentRuntimeInternal;
  1810. const kept = [
  1811. { message: { role: "assistant" as const, content: "Working on it." } },
  1812. systemReminderAttachmentEntry("date", "Today's date is 2026-10-14."),
  1813. { message: { role: "assistant" as const, content: "Done." } },
  1814. ];
  1815. const leading = buildCompactLeadingAnnouncements(internal, kept);
  1816. expect(leading.map((entry) => entry.metadata.source)).not.toContain("date");
  1817. // 普通请求前公告不受影响:同一份历史仍宣告日期变化。
  1818. expect(
  1819. buildRequestAnnouncements(internal, kept).map((entry) => entry.metadata.source),
  1820. ).toContain("date");
  1821. });
  1822. it("does not invent environment or model notices after compact when history has none", () => {
  1823. // 只重述 compact 前历史里真有的公告;历史里没有时由下一次请求的收集补上。
  1824. runtime = createRuntime({ now, skillPort, contextSourcePort: instructionsPort() }, config);
  1825. const internal = runtime as unknown as AgentRuntimeInternal;
  1826. internal.latestContextBuildResult = {
  1827. sections: [{ source: "env_info" }],
  1828. } as never;
  1829. const restated = restateContextAfterCompact(
  1830. internal,
  1831. [{ message: { role: "user", content: "legacy history" }, metadata: { source: "real_user" } }],
  1832. [],
  1833. );
  1834. expect(restated).toEqual([]);
  1835. });
  1836. it("commits announcements, summary and attachments in one store transaction", async () => {
  1837. const bundles: { messages: { info: { id: string }; parts: unknown[] }[] }[] = [];
  1838. const saveMessage = vi.spyOn(store, "saveMessage");
  1839. Object.assign(store, {
  1840. async commitMessageBundle(bundle: (typeof bundles)[number]) {
  1841. bundles.push(structuredClone(bundle));
  1842. for (const message of bundle.messages) {
  1843. store.savedMessages.push(message.info);
  1844. store.savedParts.push(...message.parts);
  1845. }
  1846. },
  1847. });
  1848. runtime = createRuntime({ now, skillPort, contextSourcePort: instructionsPort() }, config);
  1849. await runtime.executeTurn("first");
  1850. await runtime.executeTurn("second");
  1851. const savedBefore = saveMessage.mock.calls.length;
  1852. const compacted = await compact(runtime, CompactTrigger.Reactive);
  1853. expect(compacted.outcome).toBe("compacted");
  1854. expect(bundles).toHaveLength(1);
  1855. const bundleIds = bundles[0]!.messages.map((message) => message.info.id);
  1856. const committed = new Set(bundleIds);
  1857. // 整组记录只经过事务入口,不再逐条写入。
  1858. expect(
  1859. saveMessage.mock.calls.slice(savedBefore).filter(([info]) => committed.has(info.id)),
  1860. ).toEqual([]);
  1861. const summaryIndex = bundles[0]!.messages.findIndex((message) =>
  1862. message.parts.some((part) => (part as { type?: string }).type === "compaction"),
  1863. );
  1864. const declared = (
  1865. bundles[0]!.messages[summaryIndex]!.parts.find(
  1866. (part) => (part as { type?: string }).type === "compaction",
  1867. ) as { metadata?: { compactLeadingMessageIds?: string[] } }
  1868. ).metadata?.compactLeadingMessageIds;
  1869. expect(declared?.length).toBeGreaterThan(0);
  1870. expect(bundleIds.slice(0, summaryIndex)).toEqual(declared);
  1871. expect(bundleIds.length).toBeGreaterThan(summaryIndex + 1);
  1872. });
  1873. it.each([CompactTrigger.Reactive, CompactTrigger.Manual])(
  1874. "re-reads Git for the session context re-announced after compact=%s",
  1875. async (trigger) => {
  1876. const resolveGitContext = vi.fn(async () => ({
  1877. ...config.envInfo!,
  1878. gitBranch: "after-compact",
  1879. }));
  1880. runtime = createRuntime(
  1881. { now, skillPort, contextSourcePort: { ...instructionsPort(), resolveGitContext } },
  1882. config,
  1883. );
  1884. await runtime.executeTurn("first");
  1885. await runtime.executeTurn("second");
  1886. expect(resolveGitContext).not.toHaveBeenCalled();
  1887. await compact(runtime, trigger);
  1888. await runtime.executeTurn("after compact");
  1889. // 历史中没有 session_context 时重新读取 git,compact 后的快照是最新的。
  1890. expect(resolveGitContext).toHaveBeenCalledTimes(1);
  1891. const gitContext = contextEntries(runtime).filter(
  1892. (entry) => entry.metadata.source === "session_context",
  1893. );
  1894. expect(gitContext).toHaveLength(1);
  1895. expect(gitContext[0]!.content).toContain("after-compact");
  1896. expect(gitContext[0]!.content).not.toContain("original");
  1897. // 只刷新会话上下文;system 前缀不含 Git 事实,字节不变。
  1898. const prefix = (request: ModelRequest) =>
  1899. request.messages.slice(
  1900. 0,
  1901. request.messages.findIndex((message) => message.role !== "system"),
  1902. );
  1903. expect(prefix(requests.at(-1)!)).toEqual(prefix(requests[0]!));
  1904. },
  1905. );
  1906. it("keeps the re-read Git only inside the compacted history, so a failed compaction leaves none", async () => {
  1907. const resolveGitContext = vi.fn(async () => ({
  1908. ...config.envInfo!,
  1909. gitBranch: "after-compact",
  1910. }));
  1911. let failCommit = true;
  1912. Object.assign(store, {
  1913. async commitMessageBundle(bundle: { messages: { info: never; parts: never[] }[] }) {
  1914. if (failCommit) throw new Error("disk full");
  1915. for (const message of bundle.messages) {
  1916. store.savedMessages.push(message.info);
  1917. store.savedParts.push(...message.parts);
  1918. }
  1919. },
  1920. });
  1921. runtime = createRuntime(
  1922. { now, skillPort, contextSourcePort: { ...instructionsPort(), resolveGitContext } },
  1923. config,
  1924. );
  1925. await runtime.executeTurn("first");
  1926. await runtime.executeTurn("second");
  1927. const internal = runtime as unknown as {
  1928. config: { envInfo?: { gitBranch?: string } };
  1929. contextSourceSnapshot?: { envInfo: { gitBranch?: string } };
  1930. };
  1931. const announcedGit = () =>
  1932. contextEntries(runtime)
  1933. .filter((entry) => entry.metadata.source === "session_context")
  1934. .map((entry) => entry.content);
  1935. await expect(compact(runtime, CompactTrigger.Reactive)).rejects.toThrow("disk full");
  1936. // 写库失败:历史没有替换,仍是原来的公告;runtime 没有任何新的 Git 事实。
  1937. expect(resolveGitContext).toHaveBeenCalledTimes(1);
  1938. expect(announcedGit()).toEqual([expect.stringContaining("original")]);
  1939. expect(internal.contextSourceSnapshot?.envInfo.gitBranch).toBe("original");
  1940. expect(internal.config.envInfo?.gitBranch).toBe("original");
  1941. failCommit = false;
  1942. await compact(runtime, CompactTrigger.Reactive);
  1943. expect(announcedGit()).toEqual([expect.stringContaining("after-compact")]);
  1944. // 新的 Git 只存在于 compact 后的公告里;会话快照保持会话起始值。
  1945. expect(internal.contextSourceSnapshot?.envInfo.gitBranch).toBe("original");
  1946. expect(internal.config.envInfo?.gitBranch).toBe("original");
  1947. });
  1948. describe("Git session context decided once per window, only by history", () => {
  1949. const nonRepository = { ...config.envInfo!, isGitRepository: false, gitStatus: "not_repo" };
  1950. const repositories = new Set<string>();
  1951. const resolveGitContext = vi.fn(
  1952. async ({ workingDirectory }: Pick<ContextSourceRequest, "workingDirectory">) =>
  1953. repositories.has(workingDirectory)
  1954. ? { ...config.envInfo!, gitBranch: `repo:${workingDirectory}` }
  1955. : { isGitRepository: false, gitStatus: "not_repo" as const },
  1956. );
  1957. const resolveEnvironment = vi.fn(
  1958. async ({ workingDirectory }: Pick<ContextSourceRequest, "workingDirectory">) => ({
  1959. ...config.envInfo!,
  1960. cwd: workingDirectory,
  1961. isGitRepository: repositories.has(workingDirectory),
  1962. }),
  1963. );
  1964. const portStartingIn = (
  1965. envInfo: NonNullable<AgentRuntimeConfig["envInfo"]>,
  1966. ): ContextSourcePort => ({
  1967. ...instructionsPort(),
  1968. async resolveContextSources() {
  1969. return { workingDirectory: "/workspace", envInfo, diagnostics: [] };
  1970. },
  1971. resolveEnvironment,
  1972. resolveGitContext,
  1973. });
  1974. const announcedGit = (value = runtime) =>
  1975. contextEntries(value)
  1976. .filter((entry) => entry.metadata.source === "session_context")
  1977. .map((entry) => entry.content);
  1978. const environments = (value: ReturnType<typeof createTestAgentRuntime>) =>
  1979. contextEntries(value)
  1980. .filter((entry) => entry.metadata.source === "environment")
  1981. .map((entry) => entry.content);
  1982. const cd = (value: ReturnType<typeof createTestAgentRuntime>, directory: string) => {
  1983. (value as unknown as AgentRuntimeInternal).workingDirectory = directory;
  1984. };
  1985. beforeEach(() => {
  1986. repositories.clear();
  1987. resolveGitContext.mockClear();
  1988. resolveEnvironment.mockClear();
  1989. });
  1990. it("decides once per window: a non-repository start reads nothing later, also after moving into a repository", async () => {
  1991. runtime = createRuntime({ now, contextSourcePort: portStartingIn(nonRepository) }, config);
  1992. await runtime.executeTurn("first");
  1993. await runtime.executeTurn("second");
  1994. await runtime.executeTurn("third");
  1995. // 修复原因:起始快照来自文件系统查找,"不是仓库"是确定结论;原来不记住,第二个请求
  1996. // 还要再检查一次。现在首个请求用快照并记住目录,同一目录之后不再检查。
  1997. expect(resolveGitContext).not.toHaveBeenCalled();
  1998. expect(announcedGit()).toEqual([]);
  1999. repositories.add("/workspace/repo");
  2000. cd(runtime, "/workspace/repo");
  2001. await runtime.executeTurn("fourth");
  2002. await runtime.executeTurn("fifth");
  2003. // 本窗口已在首个请求决定过(没有 Git),进入仓库也不再读;环境公告照常报告新目录。
  2004. expect(resolveGitContext).not.toHaveBeenCalled();
  2005. expect(announcedGit()).toEqual([]);
  2006. expect(environments(runtime).at(-1)).toContain("Is a git repository: true (was false)");
  2007. await compact(runtime, CompactTrigger.Manual);
  2008. await runtime.executeTurn("next window");
  2009. // compaction 开始新窗口,新窗口的首个请求按当前目录读取。
  2010. expect(resolveGitContext).toHaveBeenCalledTimes(1);
  2011. expect(announcedGit()).toEqual([expect.stringContaining("repo:/workspace/repo")]);
  2012. });
  2013. it("reads Git again in a new window and remembers a directory that is not a repository", async () => {
  2014. runtime = createRuntime({ now, contextSourcePort: portStartingIn(config.envInfo!) }, config);
  2015. await runtime.executeTurn("first");
  2016. expect(announcedGit()).toEqual([expect.stringContaining("original")]);
  2017. await compact(runtime, CompactTrigger.Manual);
  2018. cd(runtime, "/scratch");
  2019. await runtime.executeTurn("outside repository");
  2020. await runtime.executeTurn("still outside");
  2021. // compaction 删掉了旧公告;新窗口的首个请求检查一次,非仓库目录记住。
  2022. expect(resolveGitContext).toHaveBeenCalledTimes(1);
  2023. expect(announcedGit()).toEqual([]);
  2024. await compact(runtime, CompactTrigger.Manual);
  2025. await runtime.executeTurn("outside again");
  2026. // 记住的目录在之后的窗口也不再检查。
  2027. expect(resolveGitContext).toHaveBeenCalledTimes(1);
  2028. repositories.add("/workspace");
  2029. cd(runtime, "/workspace");
  2030. await runtime.executeTurn("back in repository");
  2031. expect(resolveGitContext).toHaveBeenCalledTimes(1);
  2032. expect(announcedGit()).toEqual([]);
  2033. await compact(runtime, CompactTrigger.Manual);
  2034. await runtime.executeTurn("repository window");
  2035. expect(resolveGitContext).toHaveBeenCalledTimes(2);
  2036. expect(announcedGit()).toEqual([expect.stringContaining("repo:/workspace")]);
  2037. });
  2038. it("lets a compaction that keeps a tail decide again although the tail holds a date announcement", async () => {
  2039. let today = new Date(2026, 9, 14, 12);
  2040. runtime = createRuntime(
  2041. { now: () => today, contextSourcePort: portStartingIn(nonRepository) },
  2042. { ...config, compact: { enabled: true } },
  2043. );
  2044. await runtime.executeTurn("first");
  2045. await runtime.executeTurn("second");
  2046. repositories.add("/workspace/repo");
  2047. cd(runtime, "/workspace/repo");
  2048. today = new Date(2026, 9, 15, 12);
  2049. // 第三个输入的请求前公告(日期变化)先写入历史,模型随后报告上下文超限,触发 reactive compaction。
  2050. // 保留段是最后一个 assistant 之后的内容,带着这条日期变化公告。
  2051. respond.mockRejectedValueOnce(
  2052. Object.assign(new Error("provider context window exceeded"), {
  2053. code: ModelErrorCode.ModelContextExceeded,
  2054. }),
  2055. );
  2056. await runtime.executeTurn("third");
  2057. // date 只表示请求前已决定;compaction 为压缩后的历史重新决定,仍按当前目录读取。
  2058. expect(
  2059. contextEntries(runtime)
  2060. .filter((entry) => entry.metadata.source === "date")
  2061. .map((entry) => entry.content),
  2062. ).toEqual([expect.stringContaining("The date has changed")]);
  2063. expect(resolveGitContext).toHaveBeenCalledTimes(1);
  2064. expect(announcedGit()).toEqual([expect.stringContaining("repo:/workspace/repo")]);
  2065. });
  2066. it("continues the restored window after a cold resume: membership is re-read for the environment, Git waits for the next window", async () => {
  2067. runtime = createRuntime({ now, contextSourcePort: portStartingIn(nonRepository) }, config);
  2068. await runtime.executeTurn("first");
  2069. expect(announcedGit()).toEqual([]);
  2070. // 会话中途 git init:live runtime 不再检查,环境与 Git 都不变。
  2071. repositories.add("/workspace");
  2072. await runtime.executeTurn("live after git init");
  2073. expect(resolveEnvironment).not.toHaveBeenCalled();
  2074. expect(resolveGitContext).not.toHaveBeenCalled();
  2075. expect(environments(runtime)).toHaveLength(1);
  2076. const coldStore = createRecordingMessageStore();
  2077. await coldStore.createSession(await store.getSession(sessionId));
  2078. coldStore.savedMessages.push(...structuredClone(store.savedMessages));
  2079. coldStore.savedParts.push(...structuredClone(store.savedParts));
  2080. const cold = createRuntime(
  2081. { now, contextSourcePort: portStartingIn(nonRepository), sessionStore: coldStore as never },
  2082. config,
  2083. );
  2084. await cold.resumeFromStore();
  2085. await cold.executeTurn("after resume");
  2086. await cold.executeTurn("again");
  2087. // 修复原因:非仓库窗口没有 Git 公告,"不是仓库"原来只记在 runtime 内存里;冷恢复后的新
  2088. // runtime 没有这份记忆,又读 Git 并宣告,而环境公告仍写 "Is a git repository: false"。
  2089. // 现在恢复的窗口沿用历史,不读 Git;新 runtime 只重读一次是否仓库,在环境公告里报告变化。
  2090. expect(resolveGitContext).not.toHaveBeenCalled();
  2091. expect(announcedGit(cold)).toEqual([]);
  2092. expect(resolveEnvironment).toHaveBeenCalledTimes(1);
  2093. expect(environments(cold).slice(1)).toEqual([
  2094. "# Environment update\n - Is a git repository: true (was false)",
  2095. ]);
  2096. await compact(cold, CompactTrigger.Manual);
  2097. await cold.executeTurn("next window");
  2098. expect(resolveGitContext).toHaveBeenCalledTimes(1);
  2099. expect(announcedGit(cold)).toEqual([expect.stringContaining("repo:/workspace")]);
  2100. });
  2101. it("does not use a resumed session's stored snapshot as the prefetch when the restored window has not decided", async () => {
  2102. runtime = createRuntime({ now, contextSourcePort: portStartingIn(nonRepository) }, config);
  2103. await runtime.executeTurn("first");
  2104. repositories.add("/workspace");
  2105. // 恢复的历史还没有做过决定(没有 date 公告,例如旧版本写下的历史)。
  2106. const coldStore = createRecordingMessageStore();
  2107. await coldStore.createSession(await store.getSession(sessionId));
  2108. const undecided = store.savedMessages.filter(
  2109. (message) => runtimeSourceOf(message) !== "date",
  2110. );
  2111. const kept = new Set(undecided.map((message) => message.id));
  2112. coldStore.savedMessages.push(...structuredClone(undecided));
  2113. coldStore.savedParts.push(
  2114. ...structuredClone(store.savedParts.filter((part) => kept.has(part.messageID))),
  2115. );
  2116. const cold = createRuntime(
  2117. { now, contextSourcePort: portStartingIn(nonRepository), sessionStore: coldStore as never },
  2118. config,
  2119. );
  2120. await cold.resumeFromStore();
  2121. await cold.executeTurn("after resume");
  2122. // 存储里的快照不是刚读的,不能当预取;恢复后的首个请求读一次 Git。
  2123. expect(resolveGitContext).toHaveBeenCalledTimes(1);
  2124. expect(announcedGit(cold)).toEqual([expect.stringContaining("repo:/workspace")]);
  2125. expect(environments(cold).at(-1)).toBe(
  2126. "# Environment update\n - Is a git repository: true (was false)",
  2127. );
  2128. });
  2129. });
  2130. it("appends changed cwd once and keeps the initial Git snapshot", async () => {
  2131. runtime = createRuntime({ now }, config);
  2132. await runtime.executeTurn("first");
  2133. (runtime as unknown as AgentRuntimeInternal).workingDirectory = "/workspace/subdir";
  2134. await runtime.executeTurn("second");
  2135. await runtime.executeTurn("third");
  2136. const all = contextEntries(runtime);
  2137. const environments = all.filter((entry) => entry.metadata?.source === "environment");
  2138. expect(environments).toHaveLength(2);
  2139. expect(environments[1]).toMatchObject({
  2140. content:
  2141. "# Environment update\n - Primary working directory: /workspace/subdir (was /workspace)",
  2142. });
  2143. expect(all.filter((entry) => entry.metadata?.source === "session_context")).toHaveLength(1);
  2144. expect(requests[1]?.messages.map(({ role, content }) => ({ role, content }))).toEqual(
  2145. requests[2]?.messages.slice(0, -2).map(({ role, content }) => ({ role, content })),
  2146. );
  2147. });
  2148. it("lists additional working directories and announces only their change after cold resume", async () => {
  2149. const environmentEntries = (value: ReturnType<typeof createTestAgentRuntime>) =>
  2150. contextEntries(value).filter((entry) => entry.metadata?.source === "environment");
  2151. runtime = createRuntime(
  2152. { now },
  2153. { ...config, additionalDirectories: ["/work/backend", "C:\\work\\shared folder"] },
  2154. );
  2155. await runtime.executeTurn("first");
  2156. const [full] = environmentEntries(runtime);
  2157. // 运行实例内目录不变;冷恢复按新运行配置比较最近一次公告,只追加增量,原块不改写。
  2158. const cold = createRuntime(
  2159. { now },
  2160. { ...config, additionalDirectories: ["/work/backend", "/work/docs"] },
  2161. );
  2162. await cold.resumeFromStore();
  2163. await cold.executeTurn("resumed");
  2164. const environments = environmentEntries(cold);
  2165. expect(environments).toHaveLength(2);
  2166. expect(environments[0]).toEqual(full);
  2167. expect(environments[1]).toMatchObject({
  2168. content:
  2169. "# Environment update\n - Additional working directories added:\n - /work/docs\n - Additional working directories removed:\n - C:\\work\\shared folder",
  2170. metadata: {
  2171. environment: {
  2172. full: false,
  2173. snapshot: { additionalWorkingDirectories: ["/work/backend", "/work/docs"] },
  2174. },
  2175. },
  2176. });
  2177. const visible = (request: ModelRequest) =>
  2178. request.messages.map(({ role, content }) => ({ role, content }));
  2179. expect(visible(requests.at(-1)!).slice(0, requests[0]!.messages.length)).toEqual(
  2180. visible(requests[0]!),
  2181. );
  2182. });
  2183. it("announces the ZCode Desktop part and the Gen UI directory in the environment, not in the system prompt", async () => {
  2184. const environmentEntries = (value: ReturnType<typeof createTestAgentRuntime>) =>
  2185. contextEntries(value).filter((entry) => entry.metadata?.source === "environment");
  2186. const desktopConfig = (genUiOutputRoot: string): Partial<AgentRuntimeConfig> => ({
  2187. ...config,
  2188. presentationSurface: "zcode_desktop",
  2189. genUiOutputRoot,
  2190. });
  2191. const directoryOf = (value: ReturnType<typeof createTestAgentRuntime>) =>
  2192. resolveGenUiOutputDirectory(value as unknown as AgentRuntimeInternal)!;
  2193. const noLongerDesktop =
  2194. "The ZCode Desktop Context above no longer applies: this session is not shown in ZCode Desktop.";
  2195. // 不用 MCS:环境公告留在 user 侧,system 消息只有前缀。
  2196. const system = (request: ModelRequest) =>
  2197. request.messages.filter((message) => message.role === "system");
  2198. runtime = createRuntime(
  2199. { now, fileSystemPort: new MemoryFileSystem({}) as never },
  2200. desktopConfig("/data/visualizations"),
  2201. { mcs: false },
  2202. );
  2203. await runtime.executeTurn("first");
  2204. const directory = directoryOf(runtime);
  2205. // 修复原因:Desktop 段与目录原来写在 system 里;system 由 prompt 快照冻结,fork 后子会话继续发送父会话的目录,
  2206. // 灰度翻转或换到 terminal 恢复时也继续发送旧的 Desktop 段。现在两者都随环境公告发送。
  2207. const systemText = JSON.stringify(system(requests[0]!));
  2208. expect(systemText).not.toContain("ZCode Desktop Context");
  2209. expect(systemText).not.toContain(directory);
  2210. const [full] = environmentEntries(runtime);
  2211. expect(full!.content).toContain(
  2212. ` - Is a git repository: true\n - Visualization directory for this session: ${directory}\n - Platform: linux`,
  2213. );
  2214. expect(full!.content.endsWith(`\n\n${buildDesktopContextContent(true)}`)).toBe(true);
  2215. expect(full!.metadata).toMatchObject({
  2216. environment: {
  2217. full: true,
  2218. snapshot: { desktopContext: true, visualizationDirectory: directory },
  2219. },
  2220. });
  2221. // 目录变化(fork 换了 session id,或换了输出根目录):形态不变,只追加一行目录,system 字节不变。
  2222. const cold = createRuntime(
  2223. { now, fileSystemPort: new MemoryFileSystem({}) as never },
  2224. desktopConfig("/other/visualizations"),
  2225. { mcs: false },
  2226. );
  2227. await cold.resumeFromStore();
  2228. await cold.executeTurn("resumed");
  2229. const next = directoryOf(cold);
  2230. expect(environmentEntries(cold)).toHaveLength(2);
  2231. expect(environmentEntries(cold)[1]).toMatchObject({
  2232. content: `# Environment update\n - Visualization directory for this session: ${next} (was ${directory})`,
  2233. metadata: { environment: { full: false, snapshot: { visualizationDirectory: next } } },
  2234. });
  2235. expect(system(requests.at(-1)!)).toEqual(system(requests[0]!));
  2236. // 升级前的环境元数据没有 Desktop 形态与目录:补目录行,再补整段 Desktop 文字。
  2237. for (const part of store.savedParts) {
  2238. const environment = (
  2239. part.metadata?.runtimeMessage as { environment?: { snapshot: Record<string, unknown> } }
  2240. )?.environment;
  2241. delete environment?.snapshot.visualizationDirectory;
  2242. delete environment?.snapshot.desktopContext;
  2243. }
  2244. const legacy = createRuntime(
  2245. { now, fileSystemPort: new MemoryFileSystem({}) as never },
  2246. desktopConfig("/other/visualizations"),
  2247. { mcs: false },
  2248. );
  2249. await legacy.resumeFromStore();
  2250. await legacy.executeTurn("after upgrade");
  2251. expect(environmentEntries(legacy).at(-1)!.content).toBe(
  2252. `# Environment update\n - Visualization directory for this session: ${next}\n\n${buildDesktopContextContent(true)}`,
  2253. );
  2254. // 换到 terminal 恢复:追加一句 Desktop 段不再适用,system 仍不变。
  2255. const terminal = createRuntime(
  2256. { now, fileSystemPort: new MemoryFileSystem({}) as never },
  2257. config,
  2258. { mcs: false },
  2259. );
  2260. await terminal.resumeFromStore();
  2261. await terminal.executeTurn("in the terminal");
  2262. expect(environmentEntries(terminal).at(-1)!.content).toBe(
  2263. `# Environment update\n - Visualization directory for this session: none (was ${next})\n\n${noLongerDesktop}`,
  2264. );
  2265. expect(system(requests.at(-1)!)).toEqual(system(requests[0]!));
  2266. // 仍在 Desktop,但不再有目录:省略 Gen UI 整段,不再注入不可用提示或控件说明。
  2267. const previous = environmentEntries(legacy).at(-1)!.metadata as {
  2268. environment: { snapshot: EnvironmentSnapshot };
  2269. };
  2270. const { visualizationDirectory: _removed, ...withoutDirectory } = previous.environment.snapshot;
  2271. expect(
  2272. buildEnvironmentAnnouncement(withoutDirectory, previous.environment.snapshot, true)?.content,
  2273. ).toBe(
  2274. `# Environment update\n - Visualization directory for this session: none (was ${next})\n\n${buildDesktopContextContent(false)}`,
  2275. );
  2276. expect(buildDesktopContextContent(false)).not.toMatch(/Interactive views|Gen UI|modelContent/);
  2277. // 只有 Desktop 段变化:更新就是这段文字,不带标题。
  2278. const { desktopContext: _desktop, ...terminalSnapshot } = withoutDirectory;
  2279. expect(buildEnvironmentAnnouncement(withoutDirectory, terminalSnapshot, true)?.content).toBe(
  2280. buildDesktopContextContent(false),
  2281. );
  2282. });
  2283. it("refreshes repository membership, deduplicates, and compares the return trip with the latest snapshot", async () => {
  2284. const contextSourcePort = environmentPort();
  2285. runtime = createRuntime({ now, contextSourcePort }, config);
  2286. await runtime.executeTurn("first");
  2287. const initialGit = contextEntries(runtime).find(
  2288. (entry) => entry.metadata?.source === "session_context",
  2289. );
  2290. runtime.setWorkingDirectory("/outside");
  2291. await runtime.executeTurn("leave repo");
  2292. await runtime.executeTurn("same directory");
  2293. const updates = contextEntries(runtime).filter(
  2294. (entry) => entry.metadata?.source === "environment",
  2295. );
  2296. expect(updates).toHaveLength(2);
  2297. expect(updates[1]).toMatchObject({
  2298. content:
  2299. "# Environment update\n - Primary working directory: /outside (was /workspace)\n - Is a git repository: false (was true)",
  2300. metadata: {
  2301. environment: { full: false, snapshot: { cwd: "/outside", isGitRepository: false } },
  2302. },
  2303. });
  2304. expect(contextSourcePort.resolveEnvironment).toHaveBeenCalledTimes(1);
  2305. expect(requests[1]?.messages.at(-1)).toMatchObject({
  2306. role: "system",
  2307. content: updates[1]?.kind === "attachment" ? updates[1].content : "",
  2308. });
  2309. runtime.setWorkingDirectory("/workspace");
  2310. await runtime.executeTurn("return to repo");
  2311. expect(
  2312. contextEntries(runtime)
  2313. .filter((entry) => entry.metadata?.source === "environment")
  2314. .at(-1),
  2315. ).toMatchObject({
  2316. content:
  2317. "# Environment update\n - Primary working directory: /workspace (was /outside)\n - Is a git repository: true (was false)",
  2318. });
  2319. expect(
  2320. contextEntries(runtime).filter((entry) => entry.metadata?.source === "session_context"),
  2321. ).toEqual([initialGit]);
  2322. });
  2323. it("re-reads only repository membership once after a cold resume and announces a change as an update", async () => {
  2324. runtime = createRuntime({ now, contextSourcePort: environmentPort() }, config);
  2325. await runtime.executeTurn("first");
  2326. const environmentsOf = (value: ReturnType<typeof createTestAgentRuntime>) =>
  2327. contextEntries(value)
  2328. .filter((entry) => entry.metadata?.source === "environment")
  2329. .map((entry) => entry.content);
  2330. const gitOf = (value: ReturnType<typeof createTestAgentRuntime>) =>
  2331. contextEntries(value).filter((entry) => entry.metadata?.source === "session_context");
  2332. // 是否仓库没变:新 runtime 读一次,不追加公告。
  2333. const unchanged = environmentPort();
  2334. const { cold: same } = await coldRuntimeWith(skillPort, config, {
  2335. contextSourcePort: unchanged,
  2336. });
  2337. await same.executeTurn("resumed");
  2338. await same.executeTurn("again");
  2339. expect(unchanged.resolveEnvironment).toHaveBeenCalledTimes(1);
  2340. expect(environmentsOf(same)).toEqual(environmentsOf(runtime));
  2341. // .git 已删除:只取是否仓库,平台与系统版本沿用历史,不出完整块;Git 公告沿用历史。
  2342. const changed = environmentPort();
  2343. changed.resolveEnvironment.mockImplementation(async ({ workingDirectory }) => ({
  2344. ...config.envInfo!,
  2345. cwd: workingDirectory,
  2346. platform: "darwin",
  2347. osVersion: "Darwin",
  2348. isGitRepository: false,
  2349. }));
  2350. const { cold } = await coldRuntimeWith(skillPort, config, { contextSourcePort: changed });
  2351. await cold.executeTurn("resumed");
  2352. await cold.executeTurn("again");
  2353. expect(changed.resolveEnvironment).toHaveBeenCalledTimes(1);
  2354. expect(environmentsOf(cold)).toEqual([
  2355. ...environmentsOf(runtime),
  2356. "# Environment update\n - Is a git repository: false (was true)",
  2357. ]);
  2358. expect(gitOf(cold)).toEqual(gitOf(runtime));
  2359. });
  2360. it("restores environment snapshot metadata and emits a full block when its original block is removed", async () => {
  2361. const contextSourcePort = environmentPort();
  2362. runtime = createRuntime({ now, contextSourcePort }, config);
  2363. await runtime.executeTurn("first");
  2364. runtime.setWorkingDirectory("/outside");
  2365. await runtime.executeTurn("leave repo");
  2366. const cold = createRuntime({ now, contextSourcePort }, config);
  2367. await cold.resumeFromStore();
  2368. cold.setWorkingDirectory("/outside");
  2369. await cold.executeTurn("resume here");
  2370. expect(contextEntries(cold)).toEqual(contextEntries(runtime));
  2371. const internal = cold as unknown as AgentRuntimeInternal;
  2372. internal.messageHistory.replaceMessages(
  2373. internal.messageHistory
  2374. .toRuntimeEntries()
  2375. .filter(
  2376. (entry) =>
  2377. !(
  2378. entry.kind === "attachment" &&
  2379. entry.metadata.source === "environment" &&
  2380. entry.metadata.environment?.full
  2381. ),
  2382. ),
  2383. );
  2384. await cold.executeTurn("after history reduction");
  2385. expect(
  2386. contextEntries(cold)
  2387. .filter((entry) => entry.metadata?.source === "environment")
  2388. .at(-1),
  2389. ).toMatchObject({
  2390. content: expect.stringContaining("# Environment\n"),
  2391. metadata: {
  2392. environment: { full: true, snapshot: { cwd: "/outside", isGitRepository: false } },
  2393. },
  2394. });
  2395. });
  2396. 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 () => {
  2397. const contextSourcePort = environmentPort();
  2398. runtime = createRuntime({ now, contextSourcePort }, config);
  2399. await runtime.executeTurn("first");
  2400. contextSourcePort.resolveEnvironment.mockImplementationOnce(async () => {
  2401. runtime.setWorkingDirectory("/latest");
  2402. return { ...config.envInfo!, cwd: "/probed", shell: "fish", isGitRepository: true };
  2403. });
  2404. contextSourcePort.resolveEnvironment.mockImplementationOnce(async ({ workingDirectory }) => ({
  2405. ...config.envInfo!,
  2406. cwd: workingDirectory,
  2407. platform: "darwin",
  2408. isGitRepository: false,
  2409. }));
  2410. const latestEnvironment = () =>
  2411. contextEntries(runtime)
  2412. .filter((entry) => entry.metadata?.source === "environment")
  2413. .at(-1);
  2414. runtime.setWorkingDirectory("/probed");
  2415. await runtime.executeTurn("move during probe");
  2416. // 公告使用探测前读到的目录及其事实,不重试;目录在 IO 期间的变化留给下一次请求。
  2417. // shell 与目录一样只追加变化行,不再整块重发。
  2418. expect(latestEnvironment()).toMatchObject({
  2419. content:
  2420. "# Environment update\n - Primary working directory: /probed (was /workspace)\n - Shell: fish (was bash)",
  2421. metadata: {
  2422. environment: { full: false, snapshot: { cwd: "/probed", shell: "fish" } },
  2423. },
  2424. });
  2425. expect(contextSourcePort.resolveEnvironment).toHaveBeenCalledTimes(1);
  2426. await runtime.executeTurn("next");
  2427. expect(latestEnvironment()).toMatchObject({
  2428. content: expect.stringContaining("# Environment\n"),
  2429. metadata: {
  2430. environment: {
  2431. full: true,
  2432. snapshot: { cwd: "/latest", platform: "darwin", isGitRepository: false },
  2433. },
  2434. },
  2435. });
  2436. expect(contextSourcePort.resolveEnvironment).toHaveBeenCalledTimes(2);
  2437. });
  2438. describe("CMD rule in the environment notice", () => {
  2439. // 实验验证过的中文规则的英文译文;改字需要重新验证。
  2440. const cmdRule =
  2441. "Bash tool commands are parsed by cmd.exe. Do not use Unix commands such as ls, cat, head, tail, grep, or wc; prefer the dedicated file tools for listing directories and reading files, and use dir, type, or findstr when you need a shell command.";
  2442. const cmdSelection = {
  2443. dialect: "cmd",
  2444. display: { name: "cmd.exe" },
  2445. id: "auto:cmd",
  2446. path: "C:\\Windows\\System32\\cmd.exe",
  2447. source: "auto-detected",
  2448. } as const;
  2449. const windows: EnvironmentSnapshot = {
  2450. cwd: "C:\\work",
  2451. platform: "win32",
  2452. shell: "cmd.exe",
  2453. osVersion: "Windows 11",
  2454. isGitRepository: true,
  2455. additionalWorkingDirectories: [],
  2456. };
  2457. const environmentNotices = (value: ReturnType<typeof createTestAgentRuntime>) =>
  2458. contextEntries(value).filter((entry) => entry.metadata?.source === "environment");
  2459. it("puts the rule in the Shell bullet of the first notice of a CMD session", async () => {
  2460. runtime = createRuntime(
  2461. { now, contextSourcePort: environmentPort() },
  2462. { ...config, bashShellSelection: cmdSelection },
  2463. );
  2464. await runtime.executeTurn("first");
  2465. const [notice] = environmentNotices(runtime);
  2466. // 规则只在 Shell 行括号里,标题前没有别的段落;没有旧值时不写 was。
  2467. expect(notice?.content).toMatch(/^# Environment\n/);
  2468. expect(notice?.content).toContain(`\n - Shell: cmd.exe (${cmdRule})\n`);
  2469. expect(notice?.content.split(cmdRule)).toHaveLength(2);
  2470. // 不是 cmd.exe 的 shell 不带规则。
  2471. expect(
  2472. buildEnvironmentAnnouncement({ ...windows, shell: "Git Bash" }, undefined, false)?.content,
  2473. ).toContain("\n - Shell: Git Bash\n");
  2474. });
  2475. it("puts the rule in the Shell bullet when an update changes to cmd.exe and only writes was otherwise", () => {
  2476. // 旧会话公告过 system shell 或 CMD,下一次冷恢复换成 cmd.exe 时补上规则。
  2477. for (const old of ["system shell", "CMD", "Git Bash"]) {
  2478. expect(
  2479. buildEnvironmentAnnouncement(windows, { ...windows, shell: old }, true)?.content,
  2480. ).toBe(`# Environment update\n - Shell: cmd.exe (was ${old}; ${cmdRule})`);
  2481. }
  2482. // 旧 Windows 会话的 Shell 可能为空:括号里只有规则。
  2483. expect(buildEnvironmentAnnouncement(windows, { ...windows, shell: "" }, true)?.content).toBe(
  2484. `# Environment update\n - Shell: cmd.exe (${cmdRule})`,
  2485. );
  2486. // 离开 cmd.exe 只写机械的 was。
  2487. expect(
  2488. buildEnvironmentAnnouncement({ ...windows, shell: "Git Bash" }, windows, true)?.content,
  2489. ).toBe("# Environment update\n - Shell: Git Bash (was cmd.exe)");
  2490. // shell 没变时只报其他变化,不重复规则。
  2491. expect(
  2492. buildEnvironmentAnnouncement({ ...windows, cwd: "C:\\other" }, windows, true)?.content,
  2493. ).toBe("# Environment update\n - Primary working directory: C:\\other (was C:\\work)");
  2494. });
  2495. it("marks leaving cmd.exe on the Shell line when the full block is sent again", () => {
  2496. // 平台/系统版本变化(或 compact 后没有完整块)时重发完整块;上一次是 cmd.exe 时 Shell 行带 was。
  2497. const upgraded = { ...windows, shell: "Git Bash", osVersion: "Windows 12" };
  2498. const leaving = buildEnvironmentAnnouncement(upgraded, windows, true)!;
  2499. expect(leaving.environment.full).toBe(true);
  2500. expect(leaving.content).toMatch(/^# Environment\n/);
  2501. expect(leaving.content).toContain("\n - Shell: Git Bash (was cmd.exe)\n");
  2502. // 仍是 cmd.exe,或从别的 shell 换成 cmd.exe 时,完整块的 Shell 行括号里只有规则。
  2503. for (const previousShell of ["cmd.exe", "Git Bash"]) {
  2504. const toCmd = buildEnvironmentAnnouncement(
  2505. { ...windows, osVersion: "Windows 12" },
  2506. { ...windows, shell: previousShell },
  2507. true,
  2508. )!;
  2509. expect(toCmd.content).toMatch(/^# Environment\n/);
  2510. expect(toCmd.content).toContain(`\n - Shell: cmd.exe (${cmdRule})\n`);
  2511. }
  2512. // 其他 shell 之间的完整块不变。
  2513. expect(
  2514. buildEnvironmentAnnouncement(
  2515. { ...upgraded, shell: "zsh" },
  2516. { ...windows, shell: "bash" },
  2517. true,
  2518. )?.content,
  2519. ).toContain("\n - Shell: zsh\n");
  2520. });
  2521. });
  2522. it("republishes a full block for legacy metadata and does not leak snapshot metadata on MCS downgrade", async () => {
  2523. runtime = createRuntime({ now, contextSourcePort: environmentPort() }, config);
  2524. await runtime.executeTurn("first");
  2525. const internal = runtime as unknown as AgentRuntimeInternal;
  2526. const legacy = internal.messageHistory.toRuntimeEntries();
  2527. for (const entry of legacy) {
  2528. if (entry.metadata?.source === "environment") delete entry.metadata.environment;
  2529. }
  2530. internal.messageHistory.replaceMessages(legacy);
  2531. await runtime.executeTurn("legacy history");
  2532. expect(
  2533. contextEntries(runtime).filter((entry) => entry.metadata?.source === "environment"),
  2534. ).toHaveLength(2);
  2535. runtime.setWorkingDirectory("/outside");
  2536. await runtime.executeTurn("leave");
  2537. const returnedEntries = internal.messageHistory.toRuntimeEntries();
  2538. const returnedEnvironment = returnedEntries
  2539. .filter((entry) => entry.metadata?.source === "environment")
  2540. .at(-1)!;
  2541. returnedEnvironment.metadata!.environment!.snapshot.cwd = "/mutated-entry";
  2542. expect(contextEntries(runtime).at(-1)).not.toEqual(returnedEnvironment);
  2543. const projected = buildProviderRequestMessages({
  2544. entries: internal.messageHistory.toRuntimeEntries(),
  2545. useMidConversationSystem: false,
  2546. }).messages;
  2547. expect(JSON.stringify(projected)).not.toMatch(/"(?:metadata|snapshot|environment)"/u);
  2548. expect(
  2549. projected.some(
  2550. (message) =>
  2551. message.role === "user" &&
  2552. String(message.content).includes("<system-reminder>\n# Environment update\n"),
  2553. ),
  2554. ).toBe(true);
  2555. });
  2556. it("does not commit a failed context write and retries the missing sources", async () => {
  2557. runtime = createRuntime({ now, skillPort, contextSourcePort: instructionsPort() }, config);
  2558. const savePart = store.savePart;
  2559. store.savePart = async (part) => {
  2560. if (part.metadata?.runtimeMessage?.source === "environment")
  2561. throw new Error("context write failed");
  2562. await savePart(part);
  2563. };
  2564. await expect(runtime.executeTurn("first")).rejects.toThrow();
  2565. expect(respond).not.toHaveBeenCalled();
  2566. // environment 是第一条公告;它写入失败时,后续来源都不会提交。
  2567. expect(contextEntries(runtime).map((entry) => entry.metadata?.source)).toEqual([]);
  2568. store.savePart = savePart;
  2569. await runtime.executeTurn("retry");
  2570. expect(contextEntries(runtime).map((entry) => entry.metadata?.source)).toEqual([...sources]);
  2571. });
  2572. });