| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687 |
- import { createHash } from "node:crypto";
- import { join } from "node:path";
- import { beforeEach, describe, expect, it, vi } from "vitest";
- import {
- CompactTrigger,
- createFileSystemError,
- createRootTraceContext,
- createSessionId,
- createToolCallId,
- ModelErrorCode,
- type ContextSourcePort,
- type ContextSourceRequest,
- type ModelRequest,
- type ModelResult,
- type SkillPort,
- } from "@zcode/contracts";
- import { createTestAgentRuntime } from "./test-agent-runtime.js";
- import { createTestModelSelection } from "./test-model-selection.js";
- import { createTestSessionEventStore } from "./test-event-store.js";
- import { createTestModelFactory } from "./test-runtime-model.js";
- import { createRecordingMessageStore } from "./runtime-output-token-continuation-test-helpers.js";
- import { createToolRegistry } from "../src/tool/registry.js";
- import { createReadFileStatePathKey } from "../src/tool/read-file-state.js";
- import { resolveProjectMemoryRoot } from "../src/memory/project-root.js";
- import { MemoryFileSystem } from "./memory-test-utils.js";
- import type { AgentDefinitionsSnapshot } from "../src/subagent/definitions.js";
- import { buildProviderRequestMessages } from "../src/runtime/helpers/provider-request-messages.js";
- import { systemReminderAttachmentEntry } from "../src/agent/message-history.js";
- import type { AgentRuntimeInternal } from "../src/runtime/internal.js";
- import {
- buildCompactLeadingAnnouncements,
- buildRequestAnnouncements,
- latestAnnouncedLanguage,
- restateContextAfterCompact,
- } from "../src/runtime/methods/context-refresh.js";
- import type { AgentRuntimeConfig, AgentRuntimeDeps } from "../src/runtime/types.js";
- import { resolveGenUiOutputDirectory } from "../src/runtime/helpers/gen-ui-output.js";
- import {
- buildEnvironmentAnnouncement,
- type EnvironmentSnapshot,
- } from "../src/context/sections/env-info.js";
- import { buildDesktopContextContent } from "../src/context/sections/desktop.js";
- import { createInstructionFile } from "../src/context/sections/instruction-files.js";
- import { createContextBuilder } from "../src/context/index.js";
- import { formatWorkflowStallNotification } from "../src/runtime-task/workflow-notification-copy.js";
- const snapshot = (...names: string[]): AgentDefinitionsSnapshot => ({
- activeAgents: names.map((name) => ({
- name,
- description: `Description ${name}`,
- source: "user",
- systemPrompt: "private",
- })),
- });
- const result = {
- finishReason: "stop" as const,
- text: "Summary of current work.",
- usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 },
- };
- let sessionId: ReturnType<typeof createSessionId>;
- let store: ReturnType<typeof createRecordingMessageStore>;
- let requests: ModelRequest[];
- const definitions = vi.fn(() => snapshot("A"));
- const respond = vi.fn<(request: ModelRequest) => Promise<ModelResult>>();
- let runtime: ReturnType<typeof createTestAgentRuntime>;
- function createRuntime(
- deps: Partial<AgentRuntimeDeps> = {},
- config: Partial<AgentRuntimeConfig> = {},
- { mcs = true, fold = false }: { mcs?: boolean; fold?: boolean } = {},
- ) {
- const modelFactory = createTestModelFactory({
- properties: { supportsMidConversationSystem: mcs },
- generateText: async (request) => {
- requests.push(request);
- return respond(request);
- },
- });
- return createTestAgentRuntime(
- sessionId,
- { mode: "yolo", compact: { enabled: false }, titleGeneration: { enabled: false }, ...config },
- {
- eventStore: createTestSessionEventStore(),
- sessionStore: store as never,
- getAgentDefinitions: definitions,
- modelFactory: fold
- ? (input) => ({
- ...modelFactory(input),
- requestCapabilities: { foldRemindersIntoToolResults: true },
- })
- : modelFactory,
- ...deps,
- },
- );
- }
- const entries = () =>
- (runtime as unknown as AgentRuntimeInternal).messageHistory.toRuntimeEntries();
- const compact = (value: ReturnType<typeof createTestAgentRuntime>, trigger?: CompactTrigger) =>
- (value as unknown as AgentRuntimeInternal).compactActiveConversation(
- undefined,
- createRootTraceContext({ sessionId }),
- [],
- { trigger },
- );
- beforeEach(() => {
- sessionId = createSessionId();
- store = createRecordingMessageStore();
- requests = [];
- definitions.mockReset().mockImplementation(() => snapshot("A"));
- respond.mockReset().mockResolvedValue(result);
- runtime = createRuntime();
- });
- const skillPort: SkillPort = {
- async discoverSkills() {
- return {
- skills: [
- {
- name: "search",
- description: "search things",
- path: "/workspace/.agents/skills/search/SKILL.md",
- directory: "/workspace/.agents/skills/search",
- rootPath: "/workspace/.agents/skills",
- scope: "project" as const,
- source: "agents" as const,
- safeToAutoLoad: true,
- frontmatterKeys: [],
- },
- ],
- diagnostics: [],
- totalDiscovered: 1,
- };
- },
- async loadSkill() {
- throw new Error("not needed");
- },
- };
- describe("runtime context announcements", () => {
- // 顺序即宣告顺序:environment → model → (agent listing) → skills → instructions → git → date。
- const sources = new Set([
- "environment",
- "model",
- "skills_listing",
- "context_prefix",
- "session_context",
- "date",
- ]);
- // 动态公告按隐藏提醒落盘:类型只记在 runtimeMessage.source,不写顶层 source。
- const runtimeSourceOf = (message: { metadata?: Record<string, unknown> }) =>
- (message.metadata?.runtimeMessage as { source?: string } | undefined)?.source;
- const isAnnouncementRecord = (message: {
- semantics?: { kind?: string };
- metadata?: Record<string, unknown>;
- }) =>
- message.semantics?.kind === "system_reminder" && sources.has(runtimeSourceOf(message) ?? "");
- const contextEntries = (value: ReturnType<typeof createTestAgentRuntime>) =>
- (value as unknown as AgentRuntimeInternal).messageHistory
- .toRuntimeEntries()
- .filter((entry) => entry.kind === "attachment" && sources.has(entry.metadata.source));
- const config: Partial<AgentRuntimeConfig> = {
- workingDirectory: "/workspace",
- currentDate: "2026-10-14",
- envInfo: {
- cwd: "/workspace",
- platform: "linux",
- shell: "bash",
- osVersion: "Linux",
- nodeVersion: "24",
- isGitRepository: true,
- gitStatus: "clean",
- gitBranch: "original",
- },
- };
- const now = () => new Date(2026, 9, 14, 12);
- const instructionsPort = (): ContextSourcePort => ({
- async resolveEnvironment() {
- return config.envInfo!;
- },
- async resolveGitContext() {
- return config.envInfo!;
- },
- async resolveContextSources() {
- return {
- workingDirectory: "/workspace",
- envInfo: config.envInfo!,
- userInstructions: {
- filePath: "/workspace/AGENTS.md",
- fileName: "AGENTS.md",
- content: "Project rule.",
- bytesRead: 13,
- sizeBytes: 13,
- truncated: false,
- },
- diagnostics: [],
- };
- },
- });
- const environmentPort = () =>
- ({
- async resolveContextSources() {
- return { workingDirectory: "/workspace", envInfo: config.envInfo!, diagnostics: [] };
- },
- resolveEnvironment: vi.fn(
- async ({
- workingDirectory,
- effectiveShellDisplayName,
- }: Pick<ContextSourceRequest, "workingDirectory" | "effectiveShellDisplayName">) => ({
- ...config.envInfo!,
- cwd: workingDirectory,
- shell: effectiveShellDisplayName ?? config.envInfo!.shell,
- isGitRepository: workingDirectory.startsWith("/workspace"),
- }),
- ),
- }) satisfies ContextSourcePort;
- // 把当前 store 复制成独立的冷存储,再从中恢复一个新 runtime。
- const coldRuntimeWith = async (
- port: SkillPort = skillPort,
- coldConfig: Partial<AgentRuntimeConfig> = config,
- coldDeps: Partial<AgentRuntimeDeps> = {},
- ) => {
- const recording = createRecordingMessageStore();
- // rewind 只需把分支信息写回会话;录制 store 没有 setRevert,用 updateSession 承接。
- const coldStore = Object.assign(recording, {
- async setRevert(input: { sessionID: string; revert: unknown }) {
- await recording.updateSession({ id: input.sessionID, revert: input.revert });
- },
- });
- await coldStore.createSession(await store.getSession(sessionId));
- coldStore.savedMessages.push(...structuredClone(store.savedMessages));
- coldStore.savedParts.push(...structuredClone(store.savedParts));
- const cold = createRuntime(
- {
- now,
- skillPort: port,
- contextSourcePort: instructionsPort(),
- sessionStore: coldStore as never,
- ...coldDeps,
- },
- coldConfig,
- );
- await cold.resumeFromStore();
- return { cold, coldStore };
- };
- it("announces environment and model for a custom system prompt", async () => {
- runtime = createRuntime(
- { now, contextSourcePort: environmentPort() },
- { ...config, systemPrompt: "Host override." },
- );
- await runtime.executeTurn("first task");
- // 自定义 prompt 只替换 system 正文,环境与模型公告照常发送;Git 仍不发。
- expect(contextEntries(runtime).map((entry) => entry.metadata?.source)).toEqual([
- "environment",
- "model",
- "date",
- ]);
- expect(String(requests[0]!.messages[1]!.content)).toBe("\nHost override.");
- });
- it.each([false, true])(
- "uses shared environment/model lifecycle for a specialized child (MCS=%s)",
- async (mcs) => {
- const contextSourcePort = environmentPort();
- const resolveContextSources = vi.spyOn(contextSourcePort, "resolveContextSources");
- const childConfig: Partial<AgentRuntimeConfig> = {
- ...config,
- taskType: "subagent_child",
- subagentContext: { agentPrompt: "Dedicated child identity." },
- subagents: { enabled: false },
- };
- runtime = createRuntime({ now, contextSourcePort }, childConfig, { mcs });
- await runtime.executeTurn("first child task");
- const initial = contextEntries(runtime);
- expect(initial.map((entry) => entry.metadata?.source)).toEqual([
- "environment",
- "model",
- "date",
- ]);
- expect(
- requests[0]?.messages.find((message) => String(message.content).includes("# Environment\n"))
- ?.role,
- ).toBe(mcs ? "system" : "user");
- const initialBody = requests[0]!.messages[1]!.content;
- runtime.setWorkingDirectory("/outside");
- const nextSelection = createTestModelSelection("test/child-next");
- runtime.setSessionModelSelection(nextSelection);
- await runtime.executeTurn("second child task");
- const changed = contextEntries(runtime);
- expect(
- changed.filter((entry) => entry.metadata?.source === "environment").at(-1),
- ).toMatchObject({
- content:
- "# Environment update\n - Primary working directory: /outside (was /workspace)\n - Is a git repository: false (was true)",
- });
- expect(changed.filter((entry) => entry.metadata?.source === "model").at(-1)).toMatchObject({
- content: "You are powered by the model named test/child-next.",
- });
- await runtime.executeTurn("unchanged child task");
- expect(contextEntries(runtime)).toEqual(changed);
- expect(requests.at(-1)!.messages[1]!.content).toEqual(initialBody);
- // child 初始快照只用父级传下的配置;端口只用于 cd 之后的环境探测。
- expect(resolveContextSources).not.toHaveBeenCalled();
- expect(contextSourcePort.resolveEnvironment).toHaveBeenCalledTimes(1);
- },
- );
- it.each([false, true])(
- "orders the first user turn by attachment collection order (MCS=%s)",
- async (mcs) => {
- runtime = createRuntime(
- { now, skillPort, contextSourcePort: instructionsPort() },
- { ...config, outputStyle: { name: "Learning", prompt: "Explain tradeoffs." } },
- { mcs },
- );
- await runtime.executeTurn("first");
- // 先产出全部输入附件(含每次收集的 output_style),请求前公告在其后,最后是本轮输入。
- const markers = [
- ["environment", "# Environment"],
- ["model", "You are powered by"],
- ["output_style_instructions", "# Output Style: Learning"],
- ["agents", "Available agent types"],
- ["skills", "The following skills"],
- ["output_style", "Learning output style is active"],
- ["instructions", "Codebase and user instructions"],
- ["session_context", "As you answer"],
- ["date", "Today's date is"],
- ] as const;
- const messages = requests[0]!.messages.filter((message) => message.role !== "system");
- const userTexts = messages.map((message) => String(message.content));
- const promptIndex = userTexts.indexOf("first");
- const kinds = userTexts.slice(0, promptIndex).map((text) => {
- const body = text.replace(/^<system-reminder>\n/u, "");
- return markers.find(([, marker]) => body.startsWith(marker))?.[0];
- });
- const userSide = ["instructions", "session_context"];
- expect(kinds).toEqual(mcs ? userSide : markers.map(([kind]) => kind));
- if (mcs) {
- // MCS 下其余公告在 user run 末尾合成一条 system,顺序不变,user 侧没有 skill 列表。
- const system = requests[0]!.messages.at(-1)!;
- expect(system.role).toBe("system");
- const positions = markers
- .filter(([kind]) => !userSide.includes(kind))
- .map(([, marker]) => String(system.content).indexOf(marker));
- expect(positions.every((position) => position >= 0)).toBe(true);
- expect(positions).toEqual([...positions].sort((a, b) => a - b));
- expect(userTexts.some((text) => text.includes("search things"))).toBe(false);
- }
- // 默认测试模型不合并相邻 user,紧挨输入的那一块也不补换行。
- expect(userTexts.slice(0, promptIndex).every((text) => !text.endsWith("\n"))).toBe(true);
- },
- );
- it("ends only the block right before the first input with a newline when the model merges adjacent user content", async () => {
- // 声明合并相邻 user 内容(foldRemindersIntoToolResults)时,紧挨输入的那一块以换行结尾,其余块不补。
- runtime = createRuntime({ now, skillPort, contextSourcePort: instructionsPort() }, config, {
- mcs: false,
- fold: true,
- });
- await runtime.executeTurn("first");
- const userTexts = requests[0]!.messages
- .filter((message) => message.role !== "system")
- .map((message) => String(message.content));
- const promptIndex = userTexts.indexOf("first");
- expect(promptIndex).toBeGreaterThan(1);
- expect(userTexts[promptIndex - 1]).toMatch(/<\/system-reminder>\n$/u);
- expect(userTexts.slice(0, promptIndex - 1).every((text) => !text.endsWith("\n"))).toBe(true);
- });
- describe("turns started by a notification", () => {
- const marker = "NOTIFICATION_MARKER";
- const startTurn = {
- task_notification: () =>
- (runtime as any).enqueueBackgroundTaskNotification({
- text: `<task-notification><task-id>${marker}</task-id><status>completed</status></task-notification>`,
- traceContext: createRootTraceContext({ sessionId }),
- }),
- subagent_reply: () =>
- (runtime as any).enqueueSubagentMessage({
- responseId: "response",
- agentId: "agent",
- agentType: "general-purpose",
- childSessionId: createSessionId(),
- childToolCallId: "child-call",
- summary: "progress",
- message: marker,
- traceContext: createRootTraceContext({ sessionId }),
- }),
- };
- const contextMarkers = [
- "# Environment",
- "You are powered by",
- "Available agent types",
- "The following skills",
- "Codebase and user instructions",
- "Today's date is",
- ];
- const waitForRequests = (count: number) =>
- vi.waitFor(() => expect(requests.length).toBeGreaterThanOrEqual(count));
- const requestText = (request: ModelRequest) =>
- request.messages.map((message) => JSON.stringify(message.content)).join("\n");
- const createNotifiedRuntime = (mcs: boolean, deps: Partial<AgentRuntimeDeps> = {}) =>
- createRuntime({ now, skillPort, contextSourcePort: instructionsPort(), ...deps }, config, {
- mcs,
- });
- it.each([
- ["task_notification", false],
- ["task_notification", true],
- ["subagent_reply", false],
- ["subagent_reply", true],
- ] as const)(
- "skips input attachments but keeps request announcements on the first %s request (MCS=%s)",
- async (input, mcs) => {
- runtime = createNotifiedRuntime(mcs);
- await runtime.ensureSessionPersistedForExternalActivity("initial session");
- startTurn[input]();
- await waitForRequests(1);
- const messages = requests[0]!.messages;
- const indexOf = (text: string) =>
- messages.findIndex((message) => JSON.stringify(message.content).includes(text));
- const notificationIndex = indexOf(marker);
- expect(messages[notificationIndex]!.role).toBe("user");
- // 跳过附件时只跳过输入附件;请求前公告照常运行。
- for (const contextMarker of contextMarkers.slice(0, 4)) {
- expect(requestText(requests[0]!)).not.toContain(contextMarker);
- }
- // 公告冒泡到通知之前;MCS 文本落在 user run 末尾。
- expect(indexOf("Codebase and user instructions")).toBeLessThan(notificationIndex);
- if (mcs) {
- expect(messages.at(-1)!.role).toBe("system");
- expect(indexOf("Today's date is")).toBe(messages.length - 1);
- } else {
- expect(indexOf("Today's date is")).toBeLessThan(notificationIndex);
- expect(notificationIndex).toBe(messages.length - 1);
- }
- expect(contextEntries(runtime).map((entry) => entry.metadata.source)).toEqual(
- expect.arrayContaining(["context_prefix", "date"]),
- );
- expect(
- contextEntries(runtime).some((entry) =>
- ["environment", "model", "skills_listing"].includes(entry.metadata.source),
- ),
- ).toBe(false);
- },
- );
- // 修复原因:空闲整批原来存成一个 "\n\n" 连接的字符串,投影时再按 <task-notification> 开头猜边界;
- // workflow 运行中通知不以它开头,被并进前一条通知的包装。现在每条通知是同一条消息的一个文本块,
- // 整条消息一个事务写入,冷恢复保留这些块,live 与冷恢复发出的块逐字节相同。
- it.each([true, false])(
- "keeps each notification of an idle batch in its own block live and after a cold resume (MCS=%s)",
- async (mcs) => {
- const bundles: { messages: { info: { source?: string }; parts: unknown[] }[] }[] = [];
- Object.assign(store, {
- async commitMessageBundle(bundle: (typeof bundles)[number]) {
- bundles.push(structuredClone(bundle));
- for (const message of bundle.messages) {
- store.savedMessages.push(message.info);
- store.savedParts.push(...message.parts);
- }
- },
- });
- let releaseFirst!: () => void;
- const firstHeld = new Promise<void>((resolve) => {
- releaseFirst = resolve;
- });
- respond.mockImplementationOnce(async () => {
- await firstHeld;
- return result;
- });
- runtime = createNotifiedRuntime(mcs);
- await runtime.ensureSessionPersistedForExternalActivity("initial session");
- const enqueue = (text: string) =>
- (runtime as any).enqueueBackgroundTaskNotification({
- text,
- traceContext: createRootTraceContext({ sessionId }),
- });
- const stall = formatWorkflowStallNotification({
- runLabel: "wf",
- runId: "run_1",
- sinceMs: 600000,
- });
- enqueue("<task-notification><task-id>first</task-id></task-notification>");
- await waitForRequests(1);
- // 第一条通知的请求进行中到达的两条,在下一次空闲时成为同一批。
- enqueue("<task-notification><task-id>bash-1</task-id></task-notification>");
- enqueue(stall);
- releaseFirst();
- await waitForRequests(2);
- await vi.waitFor(() => expect(runtime.getActiveTurnInfo()).toBeUndefined());
- const batchMessage = (request: ModelRequest) =>
- request.messages.find(
- (message) =>
- message.role === "user" &&
- Array.isArray(message.content) &&
- JSON.stringify(message.content).includes("bash-1"),
- );
- const live = batchMessage(requests[1]!)!;
- const blocks = live.content as { type: string; text: string }[];
- expect(blocks.map((block) => block.type)).toEqual(["text", "text"]);
- expect(blocks[0]!.text).toMatch(
- /^<system-reminder>\n\[SYSTEM NOTIFICATION - NOT USER INPUT\]/u,
- );
- expect(blocks[0]!.text).toContain("bash-1");
- expect(blocks[0]!.text).not.toContain("workflow-stall");
- expect(blocks[0]!.text.endsWith("</system-reminder>\n")).toBe(true);
- expect(blocks[1]!.text).toContain("<workflow-stall>");
- expect(blocks[1]!.text.endsWith("</system-reminder>")).toBe(true);
- // 一个事务写入一条消息、两个 part。
- const batchBundles = bundles.filter((bundle) =>
- bundle.messages.some((message) => message.info.source === "background_task"),
- );
- expect(batchBundles.map((bundle) => bundle.messages.map((m) => m.parts.length))).toEqual([
- [2],
- ]);
- const coldStore = createRecordingMessageStore();
- await coldStore.createSession(await store.getSession(sessionId));
- coldStore.savedMessages.push(...structuredClone(store.savedMessages));
- coldStore.savedParts.push(...structuredClone(store.savedParts));
- const cold = createRuntime(
- {
- now,
- skillPort,
- contextSourcePort: instructionsPort(),
- sessionStore: coldStore as never,
- },
- config,
- { mcs },
- );
- await cold.resumeFromStore();
- await cold.executeTurn("after resume");
- expect(batchMessage(requests.at(-1)!)?.content).toEqual(live.content);
- },
- );
- it("collects the skipped context after a tool result in the same turn", async () => {
- const registry = createToolRegistry();
- registry.register({
- inputSchema: {},
- metadata: {
- name: "Probe",
- concurrentSafe: true,
- destructive: false,
- needsApproval: false,
- readOnly: true,
- riskLevel: "low",
- sideEffectScope: "none",
- },
- handler: async () => "probed",
- });
- runtime = createNotifiedRuntime(false, { toolRegistry: registry });
- respond.mockResolvedValueOnce({
- ...result,
- text: "",
- finishReason: "tool-calls",
- toolCalls: [{ id: "probe", name: "Probe", input: {} }],
- });
- await runtime.ensureSessionPersistedForExternalActivity("initial session");
- startTurn.task_notification();
- await waitForRequests(2);
- const texts = requests[1]!.messages.map((message) => JSON.stringify(message.content));
- const notificationIndex = texts.findIndex((text) => text.includes(marker));
- const toolIndex = requests[1]!.messages.findIndex((message) => message.role === "tool");
- const environmentIndex = texts.findIndex((text) => text.includes("# Environment"));
- expect(notificationIndex).toBeLessThan(toolIndex);
- expect(environmentIndex).toBeGreaterThan(toolIndex);
- });
- it("keeps the plan-mode exit reminder pending for the next collected request", async () => {
- runtime = createNotifiedRuntime(false);
- (runtime as unknown as AgentRuntimeInternal).needsPlanModeExitReminder = true;
- await runtime.ensureSessionPersistedForExternalActivity("initial session");
- startTurn.task_notification();
- await waitForRequests(1);
- await vi.waitFor(() => expect(runtime.getActiveTurnInfo()).toBeUndefined());
- const planExit = () =>
- entries().filter((entry) => entry.metadata?.source === "plan_mode_exit");
- expect(planExit()).toHaveLength(0);
- expect((runtime as unknown as AgentRuntimeInternal).needsPlanModeExitReminder).toBe(true);
- await runtime.executeTurn("next");
- expect((runtime as unknown as AgentRuntimeInternal).needsPlanModeExitReminder).toBe(false);
- expect(planExit()).toHaveLength(1);
- });
- });
- it("announces output style instructions after the model once per change and resets when cleared", async () => {
- runtime = createRuntime(
- { now, skillPort },
- { ...config, outputStyle: { name: "Learning", prompt: "Explain tradeoffs.\n" } },
- );
- await runtime.executeTurn("first");
- await runtime.executeTurn("second");
- runtime.updateConfig({ outputStyle: { name: "Learning", prompt: "Explain briefly." } });
- await runtime.executeTurn("third");
- runtime.updateConfig({ outputStyle: undefined });
- await runtime.executeTurn("fourth");
- await runtime.executeTurn("fifth");
- const attachments = entries().filter((entry) => entry.kind === "attachment");
- expect(
- attachments
- .filter((entry) => entry.metadata.source === "output_style_instructions")
- .map((entry) => entry.content),
- ).toEqual([
- "# Output Style: Learning\nExplain tradeoffs.",
- "# Output Style: Learning\nExplain briefly.",
- "The output style was reset to the default. Respond in your usual style.",
- ]);
- // 输入附件顺序:environment → model → output style 指令。
- const order = attachments.map((entry) => entry.metadata.source);
- expect(order.indexOf("output_style_instructions")).toBe(order.indexOf("model") + 1);
- // system 不再携带 output style 指令。
- expect(
- JSON.stringify(requests[0]!.messages.slice(0, 3).map((message) => message.content)),
- ).not.toContain("# Output Style");
- });
- it("restates the latest output style after compact unless the kept tail has one or it was reset", () => {
- runtime = createRuntime({ now, skillPort }, config);
- const internal = runtime as unknown as AgentRuntimeInternal;
- // output style 的重述不受 env_info 门控。
- internal.latestContextBuildResult = { sections: [] } as never;
- const style = systemReminderAttachmentEntry(
- "output_style_instructions",
- "# Output Style: Learning\nExplain tradeoffs.",
- );
- const reset = systemReminderAttachmentEntry(
- "output_style_instructions",
- "The output style was reset to the default. Respond in your usual style.",
- );
- expect(restateContextAfterCompact(internal, [style], []).map((entry) => entry.content)).toEqual(
- [style.content],
- );
- expect(restateContextAfterCompact(internal, [style], [style])).toEqual([]);
- expect(restateContextAfterCompact(internal, [style, reset], [])).toEqual([]);
- });
- describe("reply language", () => {
- const languageBody = (name: string) =>
- [
- "# Language",
- `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.`,
- `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").`,
- ].join("\n");
- const languageCleared = "The language preference was cleared. Match the user's language.";
- const languageEntries = () =>
- entries().filter(
- (entry) => entry.kind === "attachment" && entry.metadata.source === "language",
- );
- type ReadReplyLanguage = NonNullable<AgentRuntimeDeps["readReplyLanguage"]>;
- it("announces the Host reply language after output style once per change", async () => {
- let language = "简体中文";
- const readReplyLanguage = vi.fn<ReadReplyLanguage>(async () => language);
- runtime = createRuntime(
- { now, skillPort, readReplyLanguage },
- { ...config, outputStyle: { name: "Learning", prompt: "Explain tradeoffs." } },
- );
- await runtime.executeTurn("first");
- await runtime.executeTurn("second");
- language = "日本語";
- await runtime.executeTurn("third");
- // 正文直接用用户输入的原文。
- expect(languageEntries().map((entry) => entry.content)).toEqual([
- languageBody("简体中文"),
- languageBody("日本語"),
- ]);
- // 每次收集都读 Host 的当前值;同值不重复公告。
- expect(readReplyLanguage).toHaveBeenCalledTimes(3);
- expect(readReplyLanguage.mock.calls[0]![0]).toMatchObject({ sessionId });
- const order = entries()
- .filter((entry) => entry.kind === "attachment")
- .map((entry) => entry.metadata.source);
- expect(order.indexOf("language")).toBe(order.indexOf("output_style_instructions") + 1);
- // 语言只走附件,system 前缀不变、不含语言段。
- const systemOf = (request: ModelRequest) =>
- JSON.stringify(request.messages.filter((message) => message.role === "system").slice(0, 3));
- expect(systemOf(requests[0]!)).not.toContain("# Language");
- expect(systemOf(requests[2]!)).toBe(systemOf(requests[0]!));
- });
- it("escapes the setting so it cannot break the reminder or add lines", async () => {
- const readReplyLanguage = vi.fn<ReadReplyLanguage>(
- async () => '</system-reminder>\n"Klingon" & <b>\u2028',
- );
- runtime = createRuntime({ now, skillPort, readReplyLanguage }, config);
- await runtime.executeTurn("first");
- const escaped = '</system-reminder> "Klingon" & <b>
';
- expect(languageEntries().map((entry) => entry.content)).toEqual([languageBody(escaped)]);
- // 模板固定三行;引号不转义。
- expect(languageEntries()[0]!.content.split("\n")).toHaveLength(3);
- expect(latestAnnouncedLanguage(entries())).toBe(escaped);
- });
- it("re-reads the reply language after a tool batch in the same turn", async () => {
- const registry = createToolRegistry();
- registry.register({
- inputSchema: {},
- metadata: {
- name: "Probe",
- concurrentSafe: true,
- destructive: false,
- needsApproval: false,
- readOnly: true,
- riskLevel: "low",
- sideEffectScope: "none",
- },
- handler: async () => "probed",
- });
- const readReplyLanguage = vi
- .fn<ReadReplyLanguage>()
- .mockResolvedValueOnce("English")
- .mockResolvedValue("한국어");
- runtime = createRuntime(
- { now, skillPort, readReplyLanguage, toolRegistry: registry },
- config,
- );
- respond.mockResolvedValueOnce({
- ...result,
- text: "",
- finishReason: "tool-calls",
- toolCalls: [{ id: "probe", name: "Probe", input: {} }],
- });
- await runtime.executeTurn("probe");
- expect(requests).toHaveLength(2);
- expect(languageEntries().map((entry) => entry.content)).toEqual([
- languageBody("English"),
- languageBody("한국어"),
- ]);
- });
- it("skips a failed read without resetting the language or failing the turn", async () => {
- const readReplyLanguage = vi
- .fn<ReadReplyLanguage>()
- .mockResolvedValueOnce("Русский")
- .mockRejectedValueOnce(new Error("host gone"))
- .mockImplementationOnce(() => {
- throw "sync failure";
- });
- const debug = vi.fn();
- const louder = vi.fn();
- const logger = { debug, info: louder, warn: louder, error: louder, child: () => logger };
- runtime = createRuntime(
- { now, skillPort, readReplyLanguage, logger: logger as never },
- config,
- );
- await runtime.executeTurn("first");
- await runtime.executeTurn("failed");
- await runtime.executeTurn("thrown");
- expect(requests).toHaveLength(3);
- expect(languageEntries().map((entry) => entry.content)).toEqual([languageBody("Русский")]);
- // 每次收集都会读一次:失败只记 debug(生产不落盘),不升级为 info/warn。
- const skipped = debug.mock.calls.filter(
- ([, context]) => context?.event === "reply_language.read_skipped",
- );
- expect(skipped.map(([, context]) => context.errorMessage)).toEqual([
- "host gone",
- "sync failure",
- ]);
- expect(
- louder.mock.calls.some(([, context]) => context?.event === "reply_language.read_skipped"),
- ).toBe(false);
- });
- it("announces the clear text once when the setting is cleared", async () => {
- const readReplyLanguage = vi
- .fn<ReadReplyLanguage>()
- .mockResolvedValueOnce(null)
- .mockResolvedValueOnce("Русский")
- .mockResolvedValueOnce(null)
- .mockResolvedValueOnce(null)
- .mockResolvedValueOnce("Русский");
- runtime = createRuntime({ now, skillPort, readReplyLanguage }, config);
- for (const input of ["never set", "set", "cleared", "still cleared", "set again"]) {
- await runtime.executeTurn(input);
- }
- // 没有公告过时 null 不发;有语言后 null 只清除一次;再设回时重新公告。
- expect(languageEntries().map((entry) => entry.content)).toEqual([
- languageBody("Русский"),
- languageCleared,
- languageBody("Русский"),
- ]);
- });
- it("does not read the reply language for a subagent child", async () => {
- const readReplyLanguage = vi.fn<ReadReplyLanguage>(async () => "日本語");
- runtime = createRuntime(
- { now, contextSourcePort: environmentPort(), readReplyLanguage },
- {
- ...config,
- taskType: "subagent_child",
- subagentContext: { agentPrompt: "Dedicated child identity." },
- subagents: { enabled: false },
- },
- );
- await runtime.executeTurn("child task");
- expect(readReplyLanguage).not.toHaveBeenCalled();
- expect(languageEntries()).toEqual([]);
- });
- it("restates the latest language after compact unless the kept tail has one", () => {
- runtime = createRuntime({ now, skillPort }, config);
- const internal = runtime as unknown as AgentRuntimeInternal;
- // 与 output style 一样不受 env_info 门控。
- internal.latestContextBuildResult = { sections: [] } as never;
- const chinese = systemReminderAttachmentEntry("language", languageBody("简体中文"));
- const japanese = systemReminderAttachmentEntry("language", languageBody("日本語"));
- const style = systemReminderAttachmentEntry(
- "output_style_instructions",
- "# Output Style: Learning\nExplain tradeoffs.",
- );
- expect(
- restateContextAfterCompact(internal, [style, chinese, japanese], []).map((entry) => [
- entry.metadata.source,
- entry.content,
- ]),
- ).toEqual([
- ["output_style_instructions", style.content],
- ["language", japanese.content],
- ]);
- expect(restateContextAfterCompact(internal, [chinese], [japanese])).toEqual([]);
- // 最近一次是清除公告时不重述。
- const cleared = systemReminderAttachmentEntry("language", languageCleared);
- expect(restateContextAfterCompact(internal, [chinese, cleared], [])).toEqual([]);
- });
- it("takes the title language from the latest announcement unless it was cleared", () => {
- // 语言可以含句点与 ". Use ":按长度反解,再用往返校验,不会在句点处截断。
- const tricky = "Português (Brasil). Use formal tone";
- const announced = systemReminderAttachmentEntry("language", languageBody(tricky));
- const cleared = systemReminderAttachmentEntry("language", languageCleared);
- expect(latestAnnouncedLanguage([cleared, announced])).toBe(tricky);
- expect(latestAnnouncedLanguage([announced, cleared])).toBeUndefined();
- expect(latestAnnouncedLanguage([])).toBeUndefined();
- // 不是模板生成的正文(例如被改写过)不当作语言。
- const tampered = systemReminderAttachmentEntry("language", `${languageBody("日本語")} extra`);
- expect(latestAnnouncedLanguage([tampered])).toBeUndefined();
- });
- it.each([
- [
- "日本語",
- "- Write the title in 日本語. Keep technical terms and code identifiers in their original form.",
- ],
- // 用户输入里的 $& / $' 不能被当成 String.replace 的替换模式展开。
- [
- "Español $& $'",
- "- Write the title in Español $& $'. Keep technical terms and code identifiers in their original form.",
- ],
- [null, "- Use the user's primary language."],
- ] as const)(
- "writes the session title in the latest announced language (%s)",
- async (language, rule) => {
- runtime = createRuntime(
- {
- now,
- skillPort,
- readReplyLanguage: async () => language,
- // Host 端口在场时标题推迟到首轮结束,这时历史里已有语言公告。
- providerRuntimeHeadersPort: {
- shouldRefreshBeforeModelRequest: () => true,
- refreshBeforeModelRequest: async () => ({ headersApplied: true }),
- },
- },
- { ...config, titleGeneration: { enabled: true } },
- );
- await runtime.executeTurn("please fix the mobile login button");
- const titleSystem = () =>
- requests
- .map((request) => String(request.messages[0]?.content))
- .find((content) => content.startsWith("Generate a concise title"));
- await vi.waitFor(() => expect(titleSystem()).toBeDefined());
- expect(titleSystem()).toContain(rule);
- expect(
- titleSystem()?.match(/^- (Write the title in|Use the user's primary language)/gmu),
- ).toHaveLength(1);
- },
- );
- });
- it("derives the plan-mode exit reminder from history after resume", async () => {
- runtime = createRuntime({ now, skillPort, contextSourcePort: instructionsPort() }, config);
- const internal = runtime as unknown as AgentRuntimeInternal;
- await runtime.executeTurn("planned");
- internal.messageHistory.addEntries([
- systemReminderAttachmentEntry("runtime_mode", "Plan mode is active."),
- { message: { role: "assistant", content: "plan ready" } },
- ]);
- // 冷恢复后内存标记为 false;按历史中最近的 plan 提醒判断。
- internal.needsPlanModeExitReminder = false;
- await runtime.executeTurn("build it");
- await runtime.executeTurn("again");
- const planExit = entries().filter((entry) => entry.metadata?.source === "plan_mode_exit");
- expect(planExit).toHaveLength(1);
- });
- it.each([undefined, CompactTrigger.Manual, CompactTrigger.Reactive])(
- "restores context without duplicate announcements after compact=%s",
- async (trigger) => {
- runtime = createRuntime({ now, skillPort, contextSourcePort: instructionsPort() }, config);
- await runtime.executeTurn("first");
- const initialContext = contextEntries(runtime);
- expect(initialContext.map((entry) => entry.metadata?.source)).toEqual([...sources]);
- await runtime.executeTurn("second");
- expect(contextEntries(runtime)).toEqual(initialContext);
- const announcements = store.savedMessages.filter(isAnnouncementRecord);
- expect(announcements).toHaveLength(6);
- for (const announcement of announcements) {
- // 顶层 source 不写新值:旧版本 App 按封闭列表校验,会拒绝整个会话。
- expect(announcement.source).toBeUndefined();
- expect(announcement.semantics?.source).toBe(runtimeSourceOf(announcement));
- expect(announcement).toMatchObject({
- semantics: {
- uiVisibility: "hidden",
- transcriptVisibility: "hidden",
- providerVisibility: "visible",
- },
- });
- }
- if (trigger) {
- const compacted = await compact(runtime, trigger);
- expect(compacted.outcome).toBe("compacted");
- await runtime.executeTurn("continue after compact");
- // 每个来源仍只宣告一次;顺序按 compact 后布局(见 "lays out the post-compact context")。
- const bySource = (items: ReturnType<typeof contextEntries>) =>
- [...items].sort((a, b) => a.metadata.source.localeCompare(b.metadata.source));
- expect(bySource(contextEntries(runtime))).toEqual(bySource(initialContext));
- }
- const liveContext = contextEntries(runtime);
- const { cold, coldStore } = await coldRuntimeWith(skillPort, {
- ...config,
- envInfo: { ...config.envInfo!, gitBranch: "new-probe-must-not-replace-history" },
- });
- const before = coldStore.savedMessages.filter(isAnnouncementRecord).length;
- await cold.executeTurn("resumed");
- expect(contextEntries(cold)).toEqual(liveContext);
- expect(coldStore.savedMessages.filter(isAnnouncementRecord)).toHaveLength(before);
- },
- );
- const withSkills = (
- skills: (base: Awaited<ReturnType<SkillPort["discoverSkills"]>>["skills"]) => typeof base,
- ): SkillPort => ({
- ...skillPort,
- async discoverSkills(request, options) {
- const outcome = await skillPort.discoverSkills(request, options);
- const next = skills(outcome.skills);
- return { ...outcome, skills: next, totalDiscovered: next.length };
- },
- });
- const withReviewSkill = withSkills((base) => [
- ...base,
- {
- ...base[0]!,
- name: "review",
- description: "review things",
- path: "/workspace/.agents/skills/review/SKILL.md",
- directory: "/workspace/.agents/skills/review",
- },
- ]);
- const skillsListingRecordTexts = (value: ReturnType<typeof createRecordingMessageStore>) =>
- value.savedParts
- .filter((part) => part.metadata?.runtimeMessage?.source === "skills_listing")
- .map((part) => String((part as { text?: string }).text));
- const historyIndexOfListing = (value: ReturnType<typeof createTestAgentRuntime>) =>
- (value as unknown as AgentRuntimeInternal).messageHistory
- .toRuntimeEntries()
- .findIndex(
- (entry) => entry.kind === "attachment" && entry.metadata.source === "skills_listing",
- );
- it("appends a new skill from the live catalog after a tool batch in an open session", async () => {
- // 实时目录端口:每次普通输入准备只读内存快照,不再调 discoverSkills。
- const base = (await skillPort.discoverSkills({ workingDirectory: "/workspace" })).skills;
- let catalog = { skills: base, diagnostics: [], totalDiscovered: base.length };
- const discoverSkills = vi.fn(async () => catalog);
- const livePort: SkillPort = {
- discoverSkills,
- currentCatalog: () => catalog,
- loadSkill: skillPort.loadSkill,
- };
- const registry = createToolRegistry();
- registry.register({
- inputSchema: {},
- metadata: {
- name: "WriteSkill",
- concurrentSafe: true,
- destructive: false,
- needsApproval: false,
- readOnly: true,
- riskLevel: "low",
- sideEffectScope: "none",
- },
- handler: async () => {
- const review = {
- ...base[0]!,
- name: "review",
- description: "review things",
- path: "/workspace/.agents/skills/review/SKILL.md",
- directory: "/workspace/.agents/skills/review",
- };
- catalog = { skills: [...base, review], diagnostics: [], totalDiscovered: 2 };
- return "written";
- },
- });
- // 与 agent listing 的工具批次用例相同:不带 SessionStore,工具权限不读项目规则。
- runtime = createRuntime(
- {
- skillPort: livePort,
- toolRegistry: registry,
- sessionStore: undefined,
- contextSourcePort: instructionsPort(),
- },
- config,
- );
- respond.mockResolvedValueOnce({
- ...result,
- text: "",
- finishReason: "tool-calls",
- toolCalls: [{ id: "write", name: "WriteSkill", input: {} }],
- });
- await runtime.executeTurn("write a skill");
- await runtime.executeTurn("continue");
- const listings = contextEntries(runtime).filter(
- (entry) => entry.metadata.source === "skills_listing",
- );
- expect(listings.map((entry) => entry.metadata.skillsListingDelta?.names)).toEqual([
- ["search"],
- ["review"],
- ]);
- // 工具批次之后的请求就带上新 skill,之后的请求不重复。
- expect(JSON.stringify(requests[0]!.messages)).not.toContain("- review: review things");
- expect(JSON.stringify(requests[1]!.messages).split("- review: review things")).toHaveLength(2);
- expect(JSON.stringify(requests[2]!.messages).split("- review: review things")).toHaveLength(2);
- expect(discoverSkills).toHaveBeenCalledTimes(1);
- expect(
- (await runtime.getSkillCatalog(createRootTraceContext({ sessionId }))).skills.map(
- (skill) => skill.name,
- ),
- ).toEqual(["search", "review"]);
- });
- it("keeps the restored skill listing and appends only the new skill after a cold resume", async () => {
- runtime = createRuntime({ now, skillPort, contextSourcePort: instructionsPort() }, config);
- await runtime.executeTurn("first");
- const liveIndex = historyIndexOfListing(runtime);
- const liveListing = contextEntries(runtime).find(
- (entry) => entry.metadata.source === "skills_listing",
- )!;
- const { cold, coldStore } = await coldRuntimeWith(withReviewSkill);
- const storedTexts = skillsListingRecordTexts(coldStore);
- await cold.executeTurn("resumed");
- await cold.executeTurn("again");
- // 修复前冷恢复按当前目录原位改写旧列表,已发送的前缀字节改变,prompt cache 失效一次。
- // 现在旧列表不动,新 skill 作为增量追加一次,之后不再重复。
- const listings = contextEntries(cold).filter(
- (entry) => entry.metadata.source === "skills_listing",
- );
- expect(listings).toHaveLength(2);
- expect(listings[0]!.content).toBe(liveListing.content);
- expect(listings[1]!.content).toBe(
- "The following skills are available for use with the Skill tool:\n\n" +
- "- review: review things (file: /workspace/.agents/skills/review/SKILL.md)",
- );
- expect(historyIndexOfListing(cold)).toBe(liveIndex);
- const lastRequest = JSON.stringify(requests.at(-1)?.messages);
- expect(lastRequest.split("- review: review things")).toHaveLength(2);
- expect(lastRequest.split("- search: search things")).toHaveLength(2);
- // 增量先持久化:库里多一条只含新 skill 的记录。
- expect(skillsListingRecordTexts(coldStore)).toHaveLength(storedTexts.length + 1);
- expect(storedTexts).toHaveLength(1);
- });
- it("does not announce removed skills after a cold resume", async () => {
- runtime = createRuntime({ now, skillPort, contextSourcePort: instructionsPort() }, config);
- await runtime.executeTurn("first");
- const liveListing = contextEntries(runtime).filter(
- (entry) => entry.metadata.source === "skills_listing",
- );
- const { cold, coldStore } = await coldRuntimeWith(withSkills(() => []));
- const storedTexts = skillsListingRecordTexts(coldStore);
- await cold.executeTurn("resumed");
- // 删除不发通知,也不改写已发送的列表;模型调用已删除的 skill 时由 Skill tool 返回 not found。
- expect(
- contextEntries(cold).filter((entry) => entry.metadata.source === "skills_listing"),
- ).toEqual(liveListing);
- expect(skillsListingRecordTexts(coldStore)).toEqual(storedTexts);
- });
- it("replays the stored delta after a rewind reloads history from the store", async () => {
- runtime = createRuntime({ now, skillPort, contextSourcePort: instructionsPort() }, config);
- await runtime.executeTurn("first");
- const { cold, coldStore } = await coldRuntimeWith(withReviewSkill);
- await cold.executeTurn("resumed");
- await cold.executeTurn("again");
- const againPart = coldStore.savedParts.find(
- (part) => (part as { text?: string }).text === "again",
- );
- expect(againPart).toBeDefined();
- const recordsBefore = skillsListingRecordTexts(coldStore).length;
- await cold.rewindConversationToMessage({
- events: [],
- targetMessageId: againPart!.messageID,
- traceContext: createRootTraceContext({ sessionId }),
- });
- await cold.executeTurn("edited");
- // rewind 从库重新加载历史:增量的指纹随记录恢复,不重发也不改写。
- const listings = contextEntries(cold).filter(
- (entry) => entry.metadata.source === "skills_listing",
- );
- expect(listings).toHaveLength(2);
- expect(skillsListingRecordTexts(coldStore)).toHaveLength(recordsBefore);
- expect(JSON.stringify(requests.at(-1)?.messages).split("- review: review things")).toHaveLength(
- 2,
- );
- });
- describe("instruction announcements after a history load", () => {
- const cliStorageRoot = "/storage/cli";
- const memoryConfig: Partial<AgentRuntimeConfig> = {
- ...config,
- memory: { cliStorageRoot, enabled: true, use: true },
- };
- const indexPath = join(
- resolveProjectMemoryRoot({ cliStorageRoot, workspacePath: "/workspace" }),
- "MEMORY.md",
- );
- const oldIndex = "- [Old policy](old-policy.md) — announced before the restart";
- const newIndex = "- [New policy](new-policy.md) — written to disk after the announcement";
- const memoryType = "user's auto-memory, persists across conversations";
- const projectType = "project instructions, checked into the codebase";
- const resumedChange =
- "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:";
- const instructionTexts = (value: ReturnType<typeof createTestAgentRuntime>) =>
- contextEntries(value)
- .filter((entry) => entry.metadata.source === "context_prefix")
- .map((entry) => entry.content);
- const instructionRecords = (value: ReturnType<typeof createRecordingMessageStore>) =>
- value.savedParts.filter((part) => part.metadata?.runtimeMessage?.source === "context_prefix");
- const instructionRecordTexts = (value: ReturnType<typeof createRecordingMessageStore>) =>
- instructionRecords(value).map((part) => String((part as { text?: string }).text));
- // AGENTS.md 的内容可在测试中修改,端口每次读取时取当前值;unreadable 时端口报读取失败的诊断。
- const agentsFile = {
- content: "Project rule." as string | undefined,
- unreadable: false,
- };
- beforeEach(() => {
- agentsFile.unreadable = false;
- });
- const agentsPort = (): ContextSourcePort => ({
- ...instructionsPort(),
- async resolveContextSources() {
- const content = agentsFile.content;
- if (agentsFile.unreadable) {
- return {
- workingDirectory: "/workspace",
- envInfo: config.envInfo!,
- diagnostics: [
- {
- code: "user_instructions_read_failed",
- message: "EACCES: permission denied",
- path: "/workspace/AGENTS.md",
- },
- ],
- };
- }
- return {
- workingDirectory: "/workspace",
- envInfo: config.envInfo!,
- ...(content === undefined
- ? {}
- : {
- userInstructions: {
- filePath: "/workspace/AGENTS.md",
- fileName: "AGENTS.md",
- content,
- bytesRead: content.length,
- sizeBytes: content.length,
- truncated: false,
- },
- }),
- diagnostics: [],
- };
- },
- });
- const announceOldIndexThenChangeDisk = async () => {
- agentsFile.content = "Project rule.";
- const files = new MemoryFileSystem({ [indexPath]: oldIndex });
- runtime = createRuntime(
- { now, skillPort, contextSourcePort: agentsPort(), fileSystemPort: files },
- memoryConfig,
- );
- await runtime.executeTurn("first");
- expect(instructionTexts(runtime)).toEqual([expect.stringContaining(oldIndex)]);
- files.files[indexPath] = newIndex;
- return files;
- };
- const resumeWith = (
- files: MemoryFileSystem,
- coldConfig = memoryConfig,
- coldDeps: Partial<AgentRuntimeDeps> = {},
- ) =>
- coldRuntimeWith(skillPort, coldConfig, {
- fileSystemPort: files,
- contextSourcePort: agentsPort(),
- ...coldDeps,
- });
- // 权限错误:文件在,但读不出来。
- const denyReads = (files: MemoryFileSystem, path: string) => {
- const read = files.readTextFile.bind(files);
- files.readTextFile = async (request) => {
- if (request.path !== path) return read(request);
- throw createFileSystemError({
- code: "permission_denied",
- path,
- message: `Permission denied for path: ${path}`,
- });
- };
- return files;
- };
- const warningLogger = () => {
- const warnings: unknown[] = [];
- const logger = {
- debug() {},
- info() {},
- warn: (_message: string, context?: unknown) => warnings.push(context),
- error() {},
- child: () => logger,
- };
- return { logger: logger as never, warnings };
- };
- it("keeps the sent announcement and appends a delta for the Memory index read on resume", async () => {
- const files = await announceOldIndexThenChangeDisk();
- const { cold, coldStore } = await resumeWith(files);
- const [firstRecord] = instructionRecordTexts(coldStore);
- await cold.executeTurn("resumed");
- // 修复原因:恢复时原位改写已发的公告,前缀字节改变;现在原公告不动,变化追加在末尾。
- const texts = instructionTexts(cold);
- expect(texts).toEqual([
- firstRecord,
- `${resumedChange}\n\nContents of ${indexPath} (${memoryType}):\n\n${newIndex}`,
- ]);
- expect(firstRecord).toContain(oldIndex);
- const lastRequest = JSON.stringify(requests.at(-1)?.messages);
- expect(lastRequest).toContain(oldIndex);
- expect(lastRequest.split(newIndex)).toHaveLength(2);
- expect(lastRequest).not.toContain("runtimeMessage");
- // 增量落库,带上只给 runtime 用的文件记录。
- const records = instructionRecords(coldStore);
- expect(records).toHaveLength(2);
- expect(records[1]!.metadata?.runtimeMessage?.instructions).toEqual({
- files: [{ path: indexPath, type: memoryType, hash: expect.any(String) }],
- reason: "session_start",
- });
- // 读文件状态记录磁盘上的新索引,也就是模型最近被告知的内容;Write 按它检查。
- const readState = (cold as unknown as AgentRuntimeInternal).readFileState.get(
- createReadFileStatePathKey(indexPath),
- );
- expect(readState?.content).toBe(newIndex);
- Object.assign(coldStore, { getProjectPermission: async () => null });
- const write = await cold.getToolExecutor().execute({
- id: createToolCallId("write-memory-index-after-resume"),
- input: { content: `${newIndex}\n- [Added](added.md) — added`, file_path: indexPath },
- name: "Write",
- });
- expect(write.success).toBe(true);
- // 之后的请求和下一次冷恢复都不再重复宣告。
- await cold.executeTurn("again");
- expect(instructionTexts(cold)).toHaveLength(2);
- files.files[indexPath] = newIndex;
- store = coldStore;
- const { cold: second } = await resumeWith(files);
- await second.executeTurn("second resume");
- expect(instructionTexts(second)).toEqual(texts);
- });
- it("appends nothing when the files are unchanged on resume", async () => {
- const files = await announceOldIndexThenChangeDisk();
- files.files[indexPath] = oldIndex;
- const { cold, coldStore } = await resumeWith(files);
- const stored = instructionRecordTexts(coldStore);
- await cold.executeTurn("resumed");
- expect(instructionTexts(cold)).toEqual(stored);
- expect(instructionRecordTexts(coldStore)).toEqual(stored);
- });
- it("announces only the changed instruction file", async () => {
- const files = await announceOldIndexThenChangeDisk();
- files.files[indexPath] = oldIndex;
- agentsFile.content = "Updated project rule.";
- const { cold } = await resumeWith(files);
- await cold.executeTurn("resumed");
- expect(instructionTexts(cold).at(-1)).toBe(
- `${resumedChange}\n\nContents of /workspace/AGENTS.md (${projectType}):\n\nUpdated project rule.`,
- );
- });
- it("compares against a legacy record without file metadata", async () => {
- const files = await announceOldIndexThenChangeDisk();
- // 升级前写入的完整公告没有 metadata:按标题行拆出文件,没变的 AGENTS.md 不再宣告。
- for (const part of instructionRecords(store)) {
- delete (part.metadata!.runtimeMessage as Record<string, unknown>).instructions;
- }
- const { cold } = await resumeWith(files);
- await cold.executeTurn("resumed");
- expect(instructionTexts(cold).at(-1)).toBe(
- `${resumedChange}\n\nContents of ${indexPath} (${memoryType}):\n\n${newIndex}`,
- );
- });
- it("re-announces a delta after a rewind removes it from history", async () => {
- const files = await announceOldIndexThenChangeDisk();
- const { cold, coldStore } = await resumeWith(files);
- await cold.executeTurn("resumed");
- const resumedPart = coldStore.savedParts.find(
- (part) => (part as { text?: string }).text === "resumed",
- );
- expect(resumedPart).toBeDefined();
- await cold.rewindConversationToMessage({
- events: [],
- targetMessageId: resumedPart!.messageID,
- traceContext: createRootTraceContext({ sessionId }),
- });
- await cold.executeTurn("edited");
- // 已公告的文件只从剩余历史推出:增量随回退离开历史,下一次请求重新追加一次。
- const texts = instructionTexts(cold);
- expect(texts).toHaveLength(2);
- expect(texts[0]).toContain(oldIndex);
- expect(texts[1]).toContain(newIndex);
- });
- it("announces files that are no longer present", async () => {
- await announceOldIndexThenChangeDisk();
- agentsFile.content = undefined;
- const { cold } = await resumeWith(new MemoryFileSystem({}), config);
- await cold.executeTurn("resumed");
- // 当前没有指令文件和 Memory 索引:原公告不动,追加一条撤回说明。
- const texts = instructionTexts(cold);
- expect(texts).toHaveLength(2);
- expect(texts[0]).toContain(oldIndex);
- expect(texts[1]).toBe(
- [
- "Instruction files were re-read when this session started.",
- "Instructions no longer present: /workspace/AGENTS.md",
- `Instructions no longer present: ${indexPath}`,
- ].join("\n\n"),
- );
- });
- it("announces a file that the earlier announcement did not have", async () => {
- agentsFile.content = undefined;
- const files = new MemoryFileSystem({ [indexPath]: oldIndex });
- runtime = createRuntime(
- { now, skillPort, contextSourcePort: agentsPort(), fileSystemPort: files },
- memoryConfig,
- );
- await runtime.executeTurn("first");
- agentsFile.content = "Project rule.";
- const { cold } = await resumeWith(files);
- await cold.executeTurn("resumed");
- expect(instructionTexts(cold).at(-1)).toBe(
- `${resumedChange}\n\nContents of /workspace/AGENTS.md (${projectType}):\n\nProject rule.`,
- );
- });
- it("puts changed and removed files in one delta", async () => {
- await announceOldIndexThenChangeDisk();
- agentsFile.content = "Updated project rule.";
- const { cold } = await resumeWith(new MemoryFileSystem({}));
- await cold.executeTurn("resumed");
- expect(instructionTexts(cold).at(-1)).toBe(
- `${resumedChange}\n\nContents of /workspace/AGENTS.md (${projectType}):\n\nUpdated project rule.\n\nInstructions no longer present: ${indexPath}`,
- );
- });
- it("compares a later change against the latest delta", async () => {
- const files = await announceOldIndexThenChangeDisk();
- const { cold, coldStore } = await resumeWith(files);
- await cold.executeTurn("resumed");
- // 第二次冷恢复:基准是完整公告加上一条增量,只宣告相对增量的新变化。
- const thirdIndex = "- [Third policy](third-policy.md) — written after the first delta";
- files.files[indexPath] = thirdIndex;
- store = coldStore;
- const { cold: second } = await resumeWith(files);
- await second.executeTurn("second resume");
- const texts = instructionTexts(second);
- expect(texts).toHaveLength(3);
- expect(texts[2]).toBe(
- `${resumedChange}\n\nContents of ${indexPath} (${memoryType}):\n\n${thirdIndex}`,
- );
- });
- it("announces a file again after a delta removed it", async () => {
- await announceOldIndexThenChangeDisk();
- agentsFile.content = undefined;
- const { cold, coldStore } = await resumeWith(new MemoryFileSystem({}), config);
- await cold.executeTurn("resumed");
- agentsFile.content = "Project rule.";
- store = coldStore;
- const { cold: second } = await resumeWith(new MemoryFileSystem({}), config);
- await second.executeTurn("second resume");
- expect(instructionTexts(second).at(-1)).toBe(
- `${resumedChange}\n\nContents of /workspace/AGENTS.md (${projectType}):\n\nProject rule.`,
- );
- });
- // 修复原因:读取出错一律当成文件不存在,权限、占用等临时错误被宣告成 "Instructions no longer present"。
- it("does not announce an unreadable file as removed on resume", async () => {
- const files = await announceOldIndexThenChangeDisk();
- agentsFile.unreadable = true;
- const { logger, warnings } = warningLogger();
- const { cold } = await resumeWith(files, memoryConfig, { logger });
- await cold.executeTurn("resumed");
- // AGENTS.md 读不出来:不算删除,模型保留已宣告的副本;MEMORY.md 照常比较。
- expect(instructionTexts(cold).at(-1)).toBe(
- `${resumedChange}\n\nContents of ${indexPath} (${memoryType}):\n\n${newIndex}`,
- );
- expect(warnings).toContainEqual(
- expect.objectContaining({
- event: "context.instructions.read_failed",
- path: "/workspace/AGENTS.md",
- }),
- );
- });
- it("does not announce an unreadable Memory index as removed on resume", async () => {
- const files = await announceOldIndexThenChangeDisk();
- const { logger, warnings } = warningLogger();
- const { cold } = await resumeWith(denyReads(files, indexPath), memoryConfig, { logger });
- await cold.executeTurn("resumed");
- expect(instructionTexts(cold)).toHaveLength(1);
- expect(warnings).toContainEqual(
- expect.objectContaining({ event: "context.instructions.read_failed", path: indexPath }),
- );
- });
- it("drops the compaction re-read when a held file cannot be read", async () => {
- const files = await announceOldIndexThenChangeDisk();
- agentsFile.unreadable = true;
- const compacted = await compact(runtime, CompactTrigger.Manual);
- expect(compacted.outcome).toBe("compacted");
- await runtime.executeTurn("after compact");
- // AGENTS.md 是 runtime 持有的文件:整次重读作废,沿用原内容,MEMORY.md 的变化留到下一次读取。
- const texts = instructionTexts(runtime);
- expect(texts).toHaveLength(1);
- expect(texts[0]).toContain("Project rule.");
- expect(texts[0]).toContain(oldIndex);
- expect((runtime as unknown as AgentRuntimeInternal).instructionRefreshReason).toBeUndefined();
- expect(texts[0]).not.toContain(newIndex);
- expect(files.readRequests.filter((request) => request.path === indexPath)).toHaveLength(2);
- });
- it("drops the compaction re-read when the held Memory index cannot be read", async () => {
- const files = await announceOldIndexThenChangeDisk();
- denyReads(files, indexPath);
- agentsFile.content = "Rule changed during the session.";
- const compacted = await compact(runtime, CompactTrigger.Manual);
- expect(compacted.outcome).toBe("compacted");
- await runtime.executeTurn("after compact");
- const texts = instructionTexts(runtime);
- expect(texts).toHaveLength(1);
- expect(texts[0]).toContain("Project rule.");
- expect(texts[0]).toContain(oldIndex);
- });
- it("adopts the compaction re-read when the unreadable file is not held", async () => {
- agentsFile.unreadable = true;
- const files = new MemoryFileSystem({ [indexPath]: oldIndex });
- runtime = createRuntime(
- { now, skillPort, contextSourcePort: agentsPort(), fileSystemPort: files },
- memoryConfig,
- );
- await runtime.executeTurn("first");
- files.files[indexPath] = newIndex;
- const compacted = await compact(runtime, CompactTrigger.Manual);
- expect(compacted.outcome).toBe("compacted");
- await runtime.executeTurn("after compact");
- // 一直读不出来的 AGENTS.md 不在 runtime 持有的内容里,不阻止重读;MEMORY.md 的变化照常采用。
- const texts = instructionTexts(runtime);
- expect(texts).toHaveLength(1);
- expect(texts[0]).toContain(newIndex);
- expect(texts[0]).not.toContain("AGENTS.md");
- expect((runtime as unknown as AgentRuntimeInternal).instructionRefreshReason).toBe(
- "compaction",
- );
- });
- it("keeps the earlier instructions when the compaction re-read fails", async () => {
- const warnings: unknown[] = [];
- const logger = {
- debug() {},
- info() {},
- warn: (_message: string, context?: unknown) => warnings.push(context),
- error() {},
- child: () => logger,
- };
- agentsFile.content = "Project rule.";
- let failReads = false;
- const port = agentsPort();
- runtime = createRuntime(
- {
- now,
- skillPort,
- logger: logger as never,
- contextSourcePort: {
- ...port,
- async resolveContextSources(input, options) {
- if (failReads) throw new Error("disk busy");
- return port.resolveContextSources(input, options);
- },
- },
- },
- config,
- );
- await runtime.executeTurn("first");
- failReads = true;
- agentsFile.content = "Rule changed during the session.";
- const compacted = await compact(runtime, CompactTrigger.Manual);
- expect(compacted.outcome).toBe("compacted");
- expect(warnings).toContainEqual(
- expect.objectContaining({
- event: "context.instructions.reread_failed",
- error: "disk busy",
- }),
- );
- await runtime.executeTurn("after compact");
- const texts = instructionTexts(runtime);
- expect(texts).toHaveLength(1);
- expect(texts[0]).toContain("Project rule.");
- expect(texts[0]).not.toContain("Rule changed during the session.");
- // 没有重读结果的 compaction 不改指令增量的 reason。
- expect((runtime as unknown as AgentRuntimeInternal).instructionRefreshReason).toBeUndefined();
- });
- it("cancels the compaction when it is aborted during the instruction re-read", async () => {
- agentsFile.content = "Project rule.";
- const controller = new AbortController();
- let abortOnRead = false;
- const port = agentsPort();
- runtime = createRuntime(
- {
- now,
- skillPort,
- contextSourcePort: {
- ...port,
- async resolveContextSources(input, options) {
- if (abortOnRead) {
- controller.abort();
- throw new Error("read aborted");
- }
- return port.resolveContextSources(input, options);
- },
- },
- },
- config,
- );
- await runtime.executeTurn("first");
- const before = entries();
- abortOnRead = true;
- agentsFile.content = "Rule changed during the session.";
- await expect(
- (runtime as unknown as AgentRuntimeInternal).compactActiveConversation(
- undefined,
- createRootTraceContext({ sessionId }),
- [],
- { abortSignal: controller.signal, trigger: CompactTrigger.Manual },
- ),
- ).rejects.toThrow();
- // 取消时不采用重读的内容,历史保持 compact 之前的样子。
- expect(entries()).toEqual(before);
- expect(
- (
- runtime as unknown as AgentRuntimeInternal
- ).latestContextBuildResult?.metaUserAttachments.find(
- (item) => item.source === "context_prefix",
- )?.content,
- ).toContain("Project rule.");
- });
- it("re-reads instruction files at the end of a compaction", async () => {
- const files = await announceOldIndexThenChangeDisk();
- agentsFile.content = "Rule changed during the session.";
- const compacted = await compact(runtime, CompactTrigger.Manual);
- expect(compacted.outcome).toBe("compacted");
- // 修复原因:compaction 原来沿用 runtime 启动时的内容;现在收尾时重读,新内容进入新窗口。
- const readState = (runtime as unknown as AgentRuntimeInternal).readFileState.get(
- createReadFileStatePathKey(indexPath),
- );
- expect(readState?.content).toBe(newIndex);
- await runtime.executeTurn("after compact");
- const texts = instructionTexts(runtime);
- expect(texts).toHaveLength(1);
- expect(texts[0]).toContain("Rule changed during the session.");
- expect(texts[0]).toContain(newIndex);
- expect(texts[0]).not.toContain(oldIndex);
- expect(files.readRequests.filter((request) => request.path === indexPath)).toHaveLength(2);
- });
- it("places only a full block before the summary, and only when the kept tail has no full block", () => {
- runtime = createRuntime({ now, skillPort, contextSourcePort: instructionsPort() }, config);
- const internal = runtime as unknown as AgentRuntimeInternal;
- const built = (content: string, body: string) =>
- ({
- sections: [],
- metaUserAttachments: [
- {
- source: "context_prefix",
- content,
- files: [{ path: "/workspace/AGENTS.md", type: projectType, body }],
- },
- ],
- }) as never;
- internal.latestContextBuildResult = built("held full", "Project rule.");
- const reread = built("re-read full", "Rule changed during the session.");
- const oldFull = systemReminderAttachmentEntry(
- "context_prefix",
- `Preamble\n\nContents of /workspace/AGENTS.md (${projectType}):\n\nOld rule.`,
- );
- const done = { message: { role: "assistant" as const, content: "Done." } };
- const leadingInstructions = (
- kept: Parameters<typeof buildCompactLeadingAnnouncements>[1],
- source?: Parameters<typeof buildCompactLeadingAnnouncements>[3],
- ) =>
- buildCompactLeadingAnnouncements(internal, kept, undefined, source)
- .filter((entry) => entry.metadata.source === "context_prefix")
- .map((entry) => entry.content);
- // 保留段有完整块:summary 之前不放,内容变化由下一次请求追加增量。
- // 修复原因:原来在 summary 之前放增量,增量排在保留段的旧公告之前,下一次请求又追加一次。
- expect(leadingInstructions([oldFull, done], reread)).toEqual([]);
- // 保留段只有增量:增量不算基准,放重读内容的完整块。
- const keptDelta = {
- ...systemReminderAttachmentEntry("context_prefix", "delta"),
- metadata: {
- source: "context_prefix" as const,
- instructions: {
- files: [{ path: "/workspace/AGENTS.md", type: projectType, hash: "h" }],
- reason: "session_start" as const,
- },
- },
- };
- expect(leadingInstructions([keptDelta, done], reread)).toEqual(["re-read full"]);
- // 保留段没有指令公告:放完整块;没有重读结果时用 runtime 持有的内容。
- expect(leadingInstructions([done], reread)).toEqual(["re-read full"]);
- expect(leadingInstructions([done])).toEqual(["held full"]);
- });
- it("uses the reason held by the runtime for request deltas", () => {
- runtime = createRuntime({ now, skillPort, contextSourcePort: instructionsPort() }, config);
- const internal = runtime as unknown as AgentRuntimeInternal;
- internal.latestContextBuildResult = {
- sections: [],
- metaUserAttachments: [
- {
- source: "context_prefix",
- content: "full",
- files: [createInstructionFile("/workspace/AGENTS.md", projectType, "Project rule.")],
- },
- ],
- } as never;
- const history = [
- systemReminderAttachmentEntry(
- "context_prefix",
- `Preamble\n\nContents of /workspace/AGENTS.md (${projectType}):\n\nOld rule.`,
- ),
- ];
- const delta = () =>
- buildRequestAnnouncements(internal, history).find(
- (entry) => entry.metadata.source === "context_prefix",
- );
- expect(delta()?.content).toBe(
- `${resumedChange}\n\nContents of /workspace/AGENTS.md (${projectType}):\n\nProject rule.`,
- );
- internal.instructionRefreshReason = "compaction";
- expect(delta()?.content).toBe(
- `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.`,
- );
- expect(delta()?.metadata).toMatchObject({ instructions: { reason: "compaction" } });
- // 正文相同、类型变了(同一路径从用户级变为项目级)也算变化。
- const retyped = [
- systemReminderAttachmentEntry(
- "context_prefix",
- `Preamble\n\nContents of /workspace/AGENTS.md (user's private global instructions for all projects):\n\nProject rule.`,
- ),
- ];
- expect(
- buildRequestAnnouncements(internal, retyped).filter(
- (entry) => entry.metadata.source === "context_prefix",
- ),
- ).toHaveLength(1);
- });
- // 优化原因:持有的文件只在读取时变化,原来每次请求前都对每个文件重新算 sha256。
- it("hashes the held files once when they are built, and compares stored hashes on requests", () => {
- const rule = "\n\nProject rule.\n\n";
- const built = createContextBuilder({
- workingDirectory: "/workspace",
- envInfo: config.envInfo!,
- userInstructions: {
- filePath: "/workspace/AGENTS.md",
- fileName: "AGENTS.md",
- content: rule,
- bytesRead: rule.length,
- sizeBytes: rule.length,
- truncated: false,
- },
- }).build();
- const [file] =
- built.metaUserAttachments.find((item) => item.source === "context_prefix")?.files ?? [];
- // 构建时去掉首尾空白并算好 hash。
- expect(file).toEqual({
- path: "/workspace/AGENTS.md",
- type: projectType,
- body: "Project rule.",
- hash: createHash("sha256").update("Project rule.").digest("hex"),
- });
- // 请求时只比较存好的 hash:持有文件的 hash 与历史记录相同就不宣告,不按正文重算。
- runtime = createRuntime({ now, skillPort, contextSourcePort: instructionsPort() }, config);
- const internal = runtime as unknown as AgentRuntimeInternal;
- const held = { ...file!, hash: "stored-hash" };
- internal.latestContextBuildResult = {
- sections: [],
- metaUserAttachments: [{ source: "context_prefix", content: "full", files: [held] }],
- } as never;
- const history = [
- {
- ...systemReminderAttachmentEntry("context_prefix", "full"),
- metadata: {
- source: "context_prefix" as const,
- instructions: { files: [{ path: held.path, type: held.type, hash: "stored-hash" }] },
- },
- },
- ];
- expect(
- buildRequestAnnouncements(internal, history).filter(
- (entry) => entry.metadata.source === "context_prefix",
- ),
- ).toEqual([]);
- });
- it("adopts the re-read only when the compaction commits", async () => {
- let failCommit = true;
- Object.assign(store, {
- async commitMessageBundle(bundle: { messages: { info: never; parts: never[] }[] }) {
- if (failCommit) throw new Error("disk full");
- for (const message of bundle.messages) {
- store.savedMessages.push(message.info);
- store.savedParts.push(...message.parts);
- }
- },
- });
- agentsFile.content = "Project rule.";
- runtime = createRuntime({ now, skillPort, contextSourcePort: agentsPort() }, config);
- const internal = runtime as unknown as AgentRuntimeInternal;
- const held = () =>
- internal.latestContextBuildResult?.metaUserAttachments.find(
- (item) => item.source === "context_prefix",
- )?.content;
- await runtime.executeTurn("first");
- await runtime.executeTurn("second");
- agentsFile.content = "Rule changed during the session.";
- await expect(compact(runtime, CompactTrigger.Reactive)).rejects.toThrow("disk full");
- // 修复原因:重读结果原来在落库之前交给 runtime;写库失败后 runtime 已持有新内容,
- // 下一次请求以 session_start 为原因宣告。现在写库失败时内容与 reason 都不变。
- expect(held()).toContain("Project rule.");
- expect(held()).not.toContain("Rule changed during the session.");
- expect(internal.instructionRefreshReason).toBeUndefined();
- failCommit = false;
- await compact(runtime, CompactTrigger.Reactive);
- expect(held()).toContain("Rule changed during the session.");
- expect(internal.instructionRefreshReason).toBe("compaction");
- await runtime.executeTurn("after compact");
- // 保留段没有完整块:summary 之前放重读内容的完整块,之后的请求不再追加增量。
- const texts = instructionTexts(runtime);
- expect(texts).toHaveLength(1);
- expect(texts[0]).toContain("Rule changed during the session.");
- });
- it("announces a change found when the same runtime resumes with the session-start reason", async () => {
- agentsFile.content = "Project rule.";
- runtime = createRuntime({ now, skillPort, contextSourcePort: agentsPort() }, config);
- const internal = runtime as unknown as AgentRuntimeInternal;
- await runtime.executeTurn("first");
- await runtime.executeTurn("second");
- agentsFile.content = "Rule changed before the compaction.";
- await compact(runtime, CompactTrigger.Reactive);
- expect(internal.instructionRefreshReason).toBe("compaction");
- // 同一个 runtime 再次恢复(bootstrap 复用 runtime)时,启动时重读的文件是本次恢复读到的,
- // 不是 compaction 重读的。
- agentsFile.content = "Rule changed before the resume.";
- await runtime.resumeFromStore();
- expect(internal.instructionRefreshReason).toBeUndefined();
- await runtime.executeTurn("after resume");
- const latest = instructionTexts(runtime).at(-1);
- expect(latest).toContain("Rule changed before the resume.");
- expect(latest?.startsWith(resumedChange)).toBe(true);
- });
- });
- it.each([CompactTrigger.Reactive, CompactTrigger.Manual])(
- "lays out the post-compact context in announcement order after compact=%s",
- async (trigger) => {
- runtime = createRuntime({ now, skillPort, contextSourcePort: instructionsPort() }, config);
- await runtime.executeTurn("first");
- await runtime.executeTurn("second");
- const compacted = await compact(runtime, trigger);
- expect(compacted.outcome).toBe("compacted");
- const layout = (value: ReturnType<typeof createTestAgentRuntime>) =>
- (value as unknown as AgentRuntimeInternal).messageHistory
- .toRuntimeEntries()
- .filter((entry) => entry.kind === "attachment" || entry.message.role !== "system")
- .map((entry) =>
- entry.kind === "attachment"
- ? entry.metadata.source
- : String(entry.message.content).startsWith("This session is being continued")
- ? "summary"
- : entry.message.role,
- );
- const live = layout(runtime);
- const summaryIndex = live.indexOf("summary");
- const tail = live.slice(summaryIndex + 1);
- // 保留段非空时,请求前公告放在 summary 之前,且不重复保留段已有的来源。
- const leading = live.slice(0, summaryIndex);
- const requestSources = ["context_prefix", "session_context", "date"];
- if (trigger === CompactTrigger.Reactive) {
- expect(leading).toEqual(requestSources.filter((source) => !tail.includes(source)));
- } else {
- expect(leading).toEqual([]);
- }
- // compaction 附件末尾:agent listing → skill 列表 → environment → model。
- // compaction 必须产出 skill 列表,否则 compact 后第一次请求看不到 skill 名单。
- expect(tail.slice(-4)).toEqual([
- "agent_listing_delta",
- "skills_listing",
- "environment",
- "model",
- ]);
- for (const source of ["skills_listing", "environment", "model"]) {
- expect(tail.filter((item) => item === source)).toHaveLength(1);
- }
- // 存储顺序与 live 一致:公告写在 summary 之前,并由 summary 的 compaction part 声明。
- const summaryRow = store.savedMessages.findIndex(
- (message) => message.semantics?.kind === "compact_summary",
- );
- const declared =
- store.savedParts.find((part) => part.type === "compaction" && part.compactBoundary)
- ?.metadata?.compactLeadingMessageIds ?? [];
- expect(declared).toHaveLength(leading.length);
- expect(
- store.savedMessages
- .slice(summaryRow - declared.length, summaryRow)
- .map((message) => message.id),
- ).toEqual(declared);
- // 冷恢复得到相同布局。
- const { cold } = await coldRuntimeWith();
- expect(layout(cold)).toEqual(live);
- },
- );
- it("does not place a date before the summary when the kept tail already has one", () => {
- // 保留段里已有 date 类型的公告(哪怕已过期)时,summary 之前不放日期;
- // 之后的请求以保留段里的旧日期为基准,在末尾宣告一次日期变化。
- runtime = createRuntime(
- { now: () => new Date(2026, 9, 15, 0, 10), skillPort, contextSourcePort: instructionsPort() },
- config,
- );
- const internal = runtime as unknown as AgentRuntimeInternal;
- const kept = [
- { message: { role: "assistant" as const, content: "Working on it." } },
- systemReminderAttachmentEntry("date", "Today's date is 2026-10-14."),
- { message: { role: "assistant" as const, content: "Done." } },
- ];
- const leading = buildCompactLeadingAnnouncements(internal, kept);
- expect(leading.map((entry) => entry.metadata.source)).not.toContain("date");
- // 普通请求前公告不受影响:同一份历史仍宣告日期变化。
- expect(
- buildRequestAnnouncements(internal, kept).map((entry) => entry.metadata.source),
- ).toContain("date");
- });
- it("does not invent environment or model notices after compact when history has none", () => {
- // 只重述 compact 前历史里真有的公告;历史里没有时由下一次请求的收集补上。
- runtime = createRuntime({ now, skillPort, contextSourcePort: instructionsPort() }, config);
- const internal = runtime as unknown as AgentRuntimeInternal;
- internal.latestContextBuildResult = {
- sections: [{ source: "env_info" }],
- } as never;
- const restated = restateContextAfterCompact(
- internal,
- [{ message: { role: "user", content: "legacy history" }, metadata: { source: "real_user" } }],
- [],
- );
- expect(restated).toEqual([]);
- });
- it("commits announcements, summary and attachments in one store transaction", async () => {
- const bundles: { messages: { info: { id: string }; parts: unknown[] }[] }[] = [];
- const saveMessage = vi.spyOn(store, "saveMessage");
- Object.assign(store, {
- async commitMessageBundle(bundle: (typeof bundles)[number]) {
- bundles.push(structuredClone(bundle));
- for (const message of bundle.messages) {
- store.savedMessages.push(message.info);
- store.savedParts.push(...message.parts);
- }
- },
- });
- runtime = createRuntime({ now, skillPort, contextSourcePort: instructionsPort() }, config);
- await runtime.executeTurn("first");
- await runtime.executeTurn("second");
- const savedBefore = saveMessage.mock.calls.length;
- const compacted = await compact(runtime, CompactTrigger.Reactive);
- expect(compacted.outcome).toBe("compacted");
- expect(bundles).toHaveLength(1);
- const bundleIds = bundles[0]!.messages.map((message) => message.info.id);
- const committed = new Set(bundleIds);
- // 整组记录只经过事务入口,不再逐条写入。
- expect(
- saveMessage.mock.calls.slice(savedBefore).filter(([info]) => committed.has(info.id)),
- ).toEqual([]);
- const summaryIndex = bundles[0]!.messages.findIndex((message) =>
- message.parts.some((part) => (part as { type?: string }).type === "compaction"),
- );
- const declared = (
- bundles[0]!.messages[summaryIndex]!.parts.find(
- (part) => (part as { type?: string }).type === "compaction",
- ) as { metadata?: { compactLeadingMessageIds?: string[] } }
- ).metadata?.compactLeadingMessageIds;
- expect(declared?.length).toBeGreaterThan(0);
- expect(bundleIds.slice(0, summaryIndex)).toEqual(declared);
- expect(bundleIds.length).toBeGreaterThan(summaryIndex + 1);
- });
- it.each([CompactTrigger.Reactive, CompactTrigger.Manual])(
- "re-reads Git for the session context re-announced after compact=%s",
- async (trigger) => {
- const resolveGitContext = vi.fn(async () => ({
- ...config.envInfo!,
- gitBranch: "after-compact",
- }));
- runtime = createRuntime(
- { now, skillPort, contextSourcePort: { ...instructionsPort(), resolveGitContext } },
- config,
- );
- await runtime.executeTurn("first");
- await runtime.executeTurn("second");
- expect(resolveGitContext).not.toHaveBeenCalled();
- await compact(runtime, trigger);
- await runtime.executeTurn("after compact");
- // 历史中没有 session_context 时重新读取 git,compact 后的快照是最新的。
- expect(resolveGitContext).toHaveBeenCalledTimes(1);
- const gitContext = contextEntries(runtime).filter(
- (entry) => entry.metadata.source === "session_context",
- );
- expect(gitContext).toHaveLength(1);
- expect(gitContext[0]!.content).toContain("after-compact");
- expect(gitContext[0]!.content).not.toContain("original");
- // 只刷新会话上下文;system 前缀不含 Git 事实,字节不变。
- const prefix = (request: ModelRequest) =>
- request.messages.slice(
- 0,
- request.messages.findIndex((message) => message.role !== "system"),
- );
- expect(prefix(requests.at(-1)!)).toEqual(prefix(requests[0]!));
- },
- );
- it("keeps the re-read Git only inside the compacted history, so a failed compaction leaves none", async () => {
- const resolveGitContext = vi.fn(async () => ({
- ...config.envInfo!,
- gitBranch: "after-compact",
- }));
- let failCommit = true;
- Object.assign(store, {
- async commitMessageBundle(bundle: { messages: { info: never; parts: never[] }[] }) {
- if (failCommit) throw new Error("disk full");
- for (const message of bundle.messages) {
- store.savedMessages.push(message.info);
- store.savedParts.push(...message.parts);
- }
- },
- });
- runtime = createRuntime(
- { now, skillPort, contextSourcePort: { ...instructionsPort(), resolveGitContext } },
- config,
- );
- await runtime.executeTurn("first");
- await runtime.executeTurn("second");
- const internal = runtime as unknown as {
- config: { envInfo?: { gitBranch?: string } };
- contextSourceSnapshot?: { envInfo: { gitBranch?: string } };
- };
- const announcedGit = () =>
- contextEntries(runtime)
- .filter((entry) => entry.metadata.source === "session_context")
- .map((entry) => entry.content);
- await expect(compact(runtime, CompactTrigger.Reactive)).rejects.toThrow("disk full");
- // 写库失败:历史没有替换,仍是原来的公告;runtime 没有任何新的 Git 事实。
- expect(resolveGitContext).toHaveBeenCalledTimes(1);
- expect(announcedGit()).toEqual([expect.stringContaining("original")]);
- expect(internal.contextSourceSnapshot?.envInfo.gitBranch).toBe("original");
- expect(internal.config.envInfo?.gitBranch).toBe("original");
- failCommit = false;
- await compact(runtime, CompactTrigger.Reactive);
- expect(announcedGit()).toEqual([expect.stringContaining("after-compact")]);
- // 新的 Git 只存在于 compact 后的公告里;会话快照保持会话起始值。
- expect(internal.contextSourceSnapshot?.envInfo.gitBranch).toBe("original");
- expect(internal.config.envInfo?.gitBranch).toBe("original");
- });
- describe("Git session context decided once per window, only by history", () => {
- const nonRepository = { ...config.envInfo!, isGitRepository: false, gitStatus: "not_repo" };
- const repositories = new Set<string>();
- const resolveGitContext = vi.fn(
- async ({ workingDirectory }: Pick<ContextSourceRequest, "workingDirectory">) =>
- repositories.has(workingDirectory)
- ? { ...config.envInfo!, gitBranch: `repo:${workingDirectory}` }
- : { isGitRepository: false, gitStatus: "not_repo" as const },
- );
- const resolveEnvironment = vi.fn(
- async ({ workingDirectory }: Pick<ContextSourceRequest, "workingDirectory">) => ({
- ...config.envInfo!,
- cwd: workingDirectory,
- isGitRepository: repositories.has(workingDirectory),
- }),
- );
- const portStartingIn = (
- envInfo: NonNullable<AgentRuntimeConfig["envInfo"]>,
- ): ContextSourcePort => ({
- ...instructionsPort(),
- async resolveContextSources() {
- return { workingDirectory: "/workspace", envInfo, diagnostics: [] };
- },
- resolveEnvironment,
- resolveGitContext,
- });
- const announcedGit = (value = runtime) =>
- contextEntries(value)
- .filter((entry) => entry.metadata.source === "session_context")
- .map((entry) => entry.content);
- const environments = (value: ReturnType<typeof createTestAgentRuntime>) =>
- contextEntries(value)
- .filter((entry) => entry.metadata.source === "environment")
- .map((entry) => entry.content);
- const cd = (value: ReturnType<typeof createTestAgentRuntime>, directory: string) => {
- (value as unknown as AgentRuntimeInternal).workingDirectory = directory;
- };
- beforeEach(() => {
- repositories.clear();
- resolveGitContext.mockClear();
- resolveEnvironment.mockClear();
- });
- it("decides once per window: a non-repository start reads nothing later, also after moving into a repository", async () => {
- runtime = createRuntime({ now, contextSourcePort: portStartingIn(nonRepository) }, config);
- await runtime.executeTurn("first");
- await runtime.executeTurn("second");
- await runtime.executeTurn("third");
- // 修复原因:起始快照来自文件系统查找,"不是仓库"是确定结论;原来不记住,第二个请求
- // 还要再检查一次。现在首个请求用快照并记住目录,同一目录之后不再检查。
- expect(resolveGitContext).not.toHaveBeenCalled();
- expect(announcedGit()).toEqual([]);
- repositories.add("/workspace/repo");
- cd(runtime, "/workspace/repo");
- await runtime.executeTurn("fourth");
- await runtime.executeTurn("fifth");
- // 本窗口已在首个请求决定过(没有 Git),进入仓库也不再读;环境公告照常报告新目录。
- expect(resolveGitContext).not.toHaveBeenCalled();
- expect(announcedGit()).toEqual([]);
- expect(environments(runtime).at(-1)).toContain("Is a git repository: true (was false)");
- await compact(runtime, CompactTrigger.Manual);
- await runtime.executeTurn("next window");
- // compaction 开始新窗口,新窗口的首个请求按当前目录读取。
- expect(resolveGitContext).toHaveBeenCalledTimes(1);
- expect(announcedGit()).toEqual([expect.stringContaining("repo:/workspace/repo")]);
- });
- it("reads Git again in a new window and remembers a directory that is not a repository", async () => {
- runtime = createRuntime({ now, contextSourcePort: portStartingIn(config.envInfo!) }, config);
- await runtime.executeTurn("first");
- expect(announcedGit()).toEqual([expect.stringContaining("original")]);
- await compact(runtime, CompactTrigger.Manual);
- cd(runtime, "/scratch");
- await runtime.executeTurn("outside repository");
- await runtime.executeTurn("still outside");
- // compaction 删掉了旧公告;新窗口的首个请求检查一次,非仓库目录记住。
- expect(resolveGitContext).toHaveBeenCalledTimes(1);
- expect(announcedGit()).toEqual([]);
- await compact(runtime, CompactTrigger.Manual);
- await runtime.executeTurn("outside again");
- // 记住的目录在之后的窗口也不再检查。
- expect(resolveGitContext).toHaveBeenCalledTimes(1);
- repositories.add("/workspace");
- cd(runtime, "/workspace");
- await runtime.executeTurn("back in repository");
- expect(resolveGitContext).toHaveBeenCalledTimes(1);
- expect(announcedGit()).toEqual([]);
- await compact(runtime, CompactTrigger.Manual);
- await runtime.executeTurn("repository window");
- expect(resolveGitContext).toHaveBeenCalledTimes(2);
- expect(announcedGit()).toEqual([expect.stringContaining("repo:/workspace")]);
- });
- it("lets a compaction that keeps a tail decide again although the tail holds a date announcement", async () => {
- let today = new Date(2026, 9, 14, 12);
- runtime = createRuntime(
- { now: () => today, contextSourcePort: portStartingIn(nonRepository) },
- { ...config, compact: { enabled: true } },
- );
- await runtime.executeTurn("first");
- await runtime.executeTurn("second");
- repositories.add("/workspace/repo");
- cd(runtime, "/workspace/repo");
- today = new Date(2026, 9, 15, 12);
- // 第三个输入的请求前公告(日期变化)先写入历史,模型随后报告上下文超限,触发 reactive compaction。
- // 保留段是最后一个 assistant 之后的内容,带着这条日期变化公告。
- respond.mockRejectedValueOnce(
- Object.assign(new Error("provider context window exceeded"), {
- code: ModelErrorCode.ModelContextExceeded,
- }),
- );
- await runtime.executeTurn("third");
- // date 只表示请求前已决定;compaction 为压缩后的历史重新决定,仍按当前目录读取。
- expect(
- contextEntries(runtime)
- .filter((entry) => entry.metadata.source === "date")
- .map((entry) => entry.content),
- ).toEqual([expect.stringContaining("The date has changed")]);
- expect(resolveGitContext).toHaveBeenCalledTimes(1);
- expect(announcedGit()).toEqual([expect.stringContaining("repo:/workspace/repo")]);
- });
- it("continues the restored window after a cold resume: membership is re-read for the environment, Git waits for the next window", async () => {
- runtime = createRuntime({ now, contextSourcePort: portStartingIn(nonRepository) }, config);
- await runtime.executeTurn("first");
- expect(announcedGit()).toEqual([]);
- // 会话中途 git init:live runtime 不再检查,环境与 Git 都不变。
- repositories.add("/workspace");
- await runtime.executeTurn("live after git init");
- expect(resolveEnvironment).not.toHaveBeenCalled();
- expect(resolveGitContext).not.toHaveBeenCalled();
- expect(environments(runtime)).toHaveLength(1);
- const coldStore = createRecordingMessageStore();
- await coldStore.createSession(await store.getSession(sessionId));
- coldStore.savedMessages.push(...structuredClone(store.savedMessages));
- coldStore.savedParts.push(...structuredClone(store.savedParts));
- const cold = createRuntime(
- { now, contextSourcePort: portStartingIn(nonRepository), sessionStore: coldStore as never },
- config,
- );
- await cold.resumeFromStore();
- await cold.executeTurn("after resume");
- await cold.executeTurn("again");
- // 修复原因:非仓库窗口没有 Git 公告,"不是仓库"原来只记在 runtime 内存里;冷恢复后的新
- // runtime 没有这份记忆,又读 Git 并宣告,而环境公告仍写 "Is a git repository: false"。
- // 现在恢复的窗口沿用历史,不读 Git;新 runtime 只重读一次是否仓库,在环境公告里报告变化。
- expect(resolveGitContext).not.toHaveBeenCalled();
- expect(announcedGit(cold)).toEqual([]);
- expect(resolveEnvironment).toHaveBeenCalledTimes(1);
- expect(environments(cold).slice(1)).toEqual([
- "# Environment update\n - Is a git repository: true (was false)",
- ]);
- await compact(cold, CompactTrigger.Manual);
- await cold.executeTurn("next window");
- expect(resolveGitContext).toHaveBeenCalledTimes(1);
- expect(announcedGit(cold)).toEqual([expect.stringContaining("repo:/workspace")]);
- });
- it("does not use a resumed session's stored snapshot as the prefetch when the restored window has not decided", async () => {
- runtime = createRuntime({ now, contextSourcePort: portStartingIn(nonRepository) }, config);
- await runtime.executeTurn("first");
- repositories.add("/workspace");
- // 恢复的历史还没有做过决定(没有 date 公告,例如旧版本写下的历史)。
- const coldStore = createRecordingMessageStore();
- await coldStore.createSession(await store.getSession(sessionId));
- const undecided = store.savedMessages.filter(
- (message) => runtimeSourceOf(message) !== "date",
- );
- const kept = new Set(undecided.map((message) => message.id));
- coldStore.savedMessages.push(...structuredClone(undecided));
- coldStore.savedParts.push(
- ...structuredClone(store.savedParts.filter((part) => kept.has(part.messageID))),
- );
- const cold = createRuntime(
- { now, contextSourcePort: portStartingIn(nonRepository), sessionStore: coldStore as never },
- config,
- );
- await cold.resumeFromStore();
- await cold.executeTurn("after resume");
- // 存储里的快照不是刚读的,不能当预取;恢复后的首个请求读一次 Git。
- expect(resolveGitContext).toHaveBeenCalledTimes(1);
- expect(announcedGit(cold)).toEqual([expect.stringContaining("repo:/workspace")]);
- expect(environments(cold).at(-1)).toBe(
- "# Environment update\n - Is a git repository: true (was false)",
- );
- });
- });
- it("appends changed cwd once and keeps the initial Git snapshot", async () => {
- runtime = createRuntime({ now }, config);
- await runtime.executeTurn("first");
- (runtime as unknown as AgentRuntimeInternal).workingDirectory = "/workspace/subdir";
- await runtime.executeTurn("second");
- await runtime.executeTurn("third");
- const all = contextEntries(runtime);
- const environments = all.filter((entry) => entry.metadata?.source === "environment");
- expect(environments).toHaveLength(2);
- expect(environments[1]).toMatchObject({
- content:
- "# Environment update\n - Primary working directory: /workspace/subdir (was /workspace)",
- });
- expect(all.filter((entry) => entry.metadata?.source === "session_context")).toHaveLength(1);
- expect(requests[1]?.messages.map(({ role, content }) => ({ role, content }))).toEqual(
- requests[2]?.messages.slice(0, -2).map(({ role, content }) => ({ role, content })),
- );
- });
- it("lists additional working directories and announces only their change after cold resume", async () => {
- const environmentEntries = (value: ReturnType<typeof createTestAgentRuntime>) =>
- contextEntries(value).filter((entry) => entry.metadata?.source === "environment");
- runtime = createRuntime(
- { now },
- { ...config, additionalDirectories: ["/work/backend", "C:\\work\\shared folder"] },
- );
- await runtime.executeTurn("first");
- const [full] = environmentEntries(runtime);
- // 运行实例内目录不变;冷恢复按新运行配置比较最近一次公告,只追加增量,原块不改写。
- const cold = createRuntime(
- { now },
- { ...config, additionalDirectories: ["/work/backend", "/work/docs"] },
- );
- await cold.resumeFromStore();
- await cold.executeTurn("resumed");
- const environments = environmentEntries(cold);
- expect(environments).toHaveLength(2);
- expect(environments[0]).toEqual(full);
- expect(environments[1]).toMatchObject({
- content:
- "# Environment update\n - Additional working directories added:\n - /work/docs\n - Additional working directories removed:\n - C:\\work\\shared folder",
- metadata: {
- environment: {
- full: false,
- snapshot: { additionalWorkingDirectories: ["/work/backend", "/work/docs"] },
- },
- },
- });
- const visible = (request: ModelRequest) =>
- request.messages.map(({ role, content }) => ({ role, content }));
- expect(visible(requests.at(-1)!).slice(0, requests[0]!.messages.length)).toEqual(
- visible(requests[0]!),
- );
- });
- it("announces the ZCode Desktop part and the Gen UI directory in the environment, not in the system prompt", async () => {
- const environmentEntries = (value: ReturnType<typeof createTestAgentRuntime>) =>
- contextEntries(value).filter((entry) => entry.metadata?.source === "environment");
- const desktopConfig = (genUiOutputRoot: string): Partial<AgentRuntimeConfig> => ({
- ...config,
- presentationSurface: "zcode_desktop",
- genUiOutputRoot,
- });
- const directoryOf = (value: ReturnType<typeof createTestAgentRuntime>) =>
- resolveGenUiOutputDirectory(value as unknown as AgentRuntimeInternal)!;
- const noLongerDesktop =
- "The ZCode Desktop Context above no longer applies: this session is not shown in ZCode Desktop.";
- // 不用 MCS:环境公告留在 user 侧,system 消息只有前缀。
- const system = (request: ModelRequest) =>
- request.messages.filter((message) => message.role === "system");
- runtime = createRuntime(
- { now, fileSystemPort: new MemoryFileSystem({}) as never },
- desktopConfig("/data/visualizations"),
- { mcs: false },
- );
- await runtime.executeTurn("first");
- const directory = directoryOf(runtime);
- // 修复原因:Desktop 段与目录原来写在 system 里;system 由 prompt 快照冻结,fork 后子会话继续发送父会话的目录,
- // 灰度翻转或换到 terminal 恢复时也继续发送旧的 Desktop 段。现在两者都随环境公告发送。
- const systemText = JSON.stringify(system(requests[0]!));
- expect(systemText).not.toContain("ZCode Desktop Context");
- expect(systemText).not.toContain(directory);
- const [full] = environmentEntries(runtime);
- expect(full!.content).toContain(
- ` - Is a git repository: true\n - Visualization directory for this session: ${directory}\n - Platform: linux`,
- );
- expect(full!.content.endsWith(`\n\n${buildDesktopContextContent(true)}`)).toBe(true);
- expect(full!.metadata).toMatchObject({
- environment: {
- full: true,
- snapshot: { desktopContext: true, visualizationDirectory: directory },
- },
- });
- // 目录变化(fork 换了 session id,或换了输出根目录):形态不变,只追加一行目录,system 字节不变。
- const cold = createRuntime(
- { now, fileSystemPort: new MemoryFileSystem({}) as never },
- desktopConfig("/other/visualizations"),
- { mcs: false },
- );
- await cold.resumeFromStore();
- await cold.executeTurn("resumed");
- const next = directoryOf(cold);
- expect(environmentEntries(cold)).toHaveLength(2);
- expect(environmentEntries(cold)[1]).toMatchObject({
- content: `# Environment update\n - Visualization directory for this session: ${next} (was ${directory})`,
- metadata: { environment: { full: false, snapshot: { visualizationDirectory: next } } },
- });
- expect(system(requests.at(-1)!)).toEqual(system(requests[0]!));
- // 升级前的环境元数据没有 Desktop 形态与目录:补目录行,再补整段 Desktop 文字。
- for (const part of store.savedParts) {
- const environment = (
- part.metadata?.runtimeMessage as { environment?: { snapshot: Record<string, unknown> } }
- )?.environment;
- delete environment?.snapshot.visualizationDirectory;
- delete environment?.snapshot.desktopContext;
- }
- const legacy = createRuntime(
- { now, fileSystemPort: new MemoryFileSystem({}) as never },
- desktopConfig("/other/visualizations"),
- { mcs: false },
- );
- await legacy.resumeFromStore();
- await legacy.executeTurn("after upgrade");
- expect(environmentEntries(legacy).at(-1)!.content).toBe(
- `# Environment update\n - Visualization directory for this session: ${next}\n\n${buildDesktopContextContent(true)}`,
- );
- // 换到 terminal 恢复:追加一句 Desktop 段不再适用,system 仍不变。
- const terminal = createRuntime(
- { now, fileSystemPort: new MemoryFileSystem({}) as never },
- config,
- { mcs: false },
- );
- await terminal.resumeFromStore();
- await terminal.executeTurn("in the terminal");
- expect(environmentEntries(terminal).at(-1)!.content).toBe(
- `# Environment update\n - Visualization directory for this session: none (was ${next})\n\n${noLongerDesktop}`,
- );
- expect(system(requests.at(-1)!)).toEqual(system(requests[0]!));
- // 仍在 Desktop,但不再有目录:省略 Gen UI 整段,不再注入不可用提示或控件说明。
- const previous = environmentEntries(legacy).at(-1)!.metadata as {
- environment: { snapshot: EnvironmentSnapshot };
- };
- const { visualizationDirectory: _removed, ...withoutDirectory } = previous.environment.snapshot;
- expect(
- buildEnvironmentAnnouncement(withoutDirectory, previous.environment.snapshot, true)?.content,
- ).toBe(
- `# Environment update\n - Visualization directory for this session: none (was ${next})\n\n${buildDesktopContextContent(false)}`,
- );
- expect(buildDesktopContextContent(false)).not.toMatch(/Interactive views|Gen UI|modelContent/);
- // 只有 Desktop 段变化:更新就是这段文字,不带标题。
- const { desktopContext: _desktop, ...terminalSnapshot } = withoutDirectory;
- expect(buildEnvironmentAnnouncement(withoutDirectory, terminalSnapshot, true)?.content).toBe(
- buildDesktopContextContent(false),
- );
- });
- it("refreshes repository membership, deduplicates, and compares the return trip with the latest snapshot", async () => {
- const contextSourcePort = environmentPort();
- runtime = createRuntime({ now, contextSourcePort }, config);
- await runtime.executeTurn("first");
- const initialGit = contextEntries(runtime).find(
- (entry) => entry.metadata?.source === "session_context",
- );
- runtime.setWorkingDirectory("/outside");
- await runtime.executeTurn("leave repo");
- await runtime.executeTurn("same directory");
- const updates = contextEntries(runtime).filter(
- (entry) => entry.metadata?.source === "environment",
- );
- expect(updates).toHaveLength(2);
- expect(updates[1]).toMatchObject({
- content:
- "# Environment update\n - Primary working directory: /outside (was /workspace)\n - Is a git repository: false (was true)",
- metadata: {
- environment: { full: false, snapshot: { cwd: "/outside", isGitRepository: false } },
- },
- });
- expect(contextSourcePort.resolveEnvironment).toHaveBeenCalledTimes(1);
- expect(requests[1]?.messages.at(-1)).toMatchObject({
- role: "system",
- content: updates[1]?.kind === "attachment" ? updates[1].content : "",
- });
- runtime.setWorkingDirectory("/workspace");
- await runtime.executeTurn("return to repo");
- expect(
- contextEntries(runtime)
- .filter((entry) => entry.metadata?.source === "environment")
- .at(-1),
- ).toMatchObject({
- content:
- "# Environment update\n - Primary working directory: /workspace (was /outside)\n - Is a git repository: true (was false)",
- });
- expect(
- contextEntries(runtime).filter((entry) => entry.metadata?.source === "session_context"),
- ).toEqual([initialGit]);
- });
- it("re-reads only repository membership once after a cold resume and announces a change as an update", async () => {
- runtime = createRuntime({ now, contextSourcePort: environmentPort() }, config);
- await runtime.executeTurn("first");
- const environmentsOf = (value: ReturnType<typeof createTestAgentRuntime>) =>
- contextEntries(value)
- .filter((entry) => entry.metadata?.source === "environment")
- .map((entry) => entry.content);
- const gitOf = (value: ReturnType<typeof createTestAgentRuntime>) =>
- contextEntries(value).filter((entry) => entry.metadata?.source === "session_context");
- // 是否仓库没变:新 runtime 读一次,不追加公告。
- const unchanged = environmentPort();
- const { cold: same } = await coldRuntimeWith(skillPort, config, {
- contextSourcePort: unchanged,
- });
- await same.executeTurn("resumed");
- await same.executeTurn("again");
- expect(unchanged.resolveEnvironment).toHaveBeenCalledTimes(1);
- expect(environmentsOf(same)).toEqual(environmentsOf(runtime));
- // .git 已删除:只取是否仓库,平台与系统版本沿用历史,不出完整块;Git 公告沿用历史。
- const changed = environmentPort();
- changed.resolveEnvironment.mockImplementation(async ({ workingDirectory }) => ({
- ...config.envInfo!,
- cwd: workingDirectory,
- platform: "darwin",
- osVersion: "Darwin",
- isGitRepository: false,
- }));
- const { cold } = await coldRuntimeWith(skillPort, config, { contextSourcePort: changed });
- await cold.executeTurn("resumed");
- await cold.executeTurn("again");
- expect(changed.resolveEnvironment).toHaveBeenCalledTimes(1);
- expect(environmentsOf(cold)).toEqual([
- ...environmentsOf(runtime),
- "# Environment update\n - Is a git repository: false (was true)",
- ]);
- expect(gitOf(cold)).toEqual(gitOf(runtime));
- });
- it("restores environment snapshot metadata and emits a full block when its original block is removed", async () => {
- const contextSourcePort = environmentPort();
- runtime = createRuntime({ now, contextSourcePort }, config);
- await runtime.executeTurn("first");
- runtime.setWorkingDirectory("/outside");
- await runtime.executeTurn("leave repo");
- const cold = createRuntime({ now, contextSourcePort }, config);
- await cold.resumeFromStore();
- cold.setWorkingDirectory("/outside");
- await cold.executeTurn("resume here");
- expect(contextEntries(cold)).toEqual(contextEntries(runtime));
- const internal = cold as unknown as AgentRuntimeInternal;
- internal.messageHistory.replaceMessages(
- internal.messageHistory
- .toRuntimeEntries()
- .filter(
- (entry) =>
- !(
- entry.kind === "attachment" &&
- entry.metadata.source === "environment" &&
- entry.metadata.environment?.full
- ),
- ),
- );
- await cold.executeTurn("after history reduction");
- expect(
- contextEntries(cold)
- .filter((entry) => entry.metadata?.source === "environment")
- .at(-1),
- ).toMatchObject({
- content: expect.stringContaining("# Environment\n"),
- metadata: {
- environment: { full: true, snapshot: { cwd: "/outside", isGitRepository: false } },
- },
- });
- });
- 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 () => {
- const contextSourcePort = environmentPort();
- runtime = createRuntime({ now, contextSourcePort }, config);
- await runtime.executeTurn("first");
- contextSourcePort.resolveEnvironment.mockImplementationOnce(async () => {
- runtime.setWorkingDirectory("/latest");
- return { ...config.envInfo!, cwd: "/probed", shell: "fish", isGitRepository: true };
- });
- contextSourcePort.resolveEnvironment.mockImplementationOnce(async ({ workingDirectory }) => ({
- ...config.envInfo!,
- cwd: workingDirectory,
- platform: "darwin",
- isGitRepository: false,
- }));
- const latestEnvironment = () =>
- contextEntries(runtime)
- .filter((entry) => entry.metadata?.source === "environment")
- .at(-1);
- runtime.setWorkingDirectory("/probed");
- await runtime.executeTurn("move during probe");
- // 公告使用探测前读到的目录及其事实,不重试;目录在 IO 期间的变化留给下一次请求。
- // shell 与目录一样只追加变化行,不再整块重发。
- expect(latestEnvironment()).toMatchObject({
- content:
- "# Environment update\n - Primary working directory: /probed (was /workspace)\n - Shell: fish (was bash)",
- metadata: {
- environment: { full: false, snapshot: { cwd: "/probed", shell: "fish" } },
- },
- });
- expect(contextSourcePort.resolveEnvironment).toHaveBeenCalledTimes(1);
- await runtime.executeTurn("next");
- expect(latestEnvironment()).toMatchObject({
- content: expect.stringContaining("# Environment\n"),
- metadata: {
- environment: {
- full: true,
- snapshot: { cwd: "/latest", platform: "darwin", isGitRepository: false },
- },
- },
- });
- expect(contextSourcePort.resolveEnvironment).toHaveBeenCalledTimes(2);
- });
- describe("CMD rule in the environment notice", () => {
- // 实验验证过的中文规则的英文译文;改字需要重新验证。
- const cmdRule =
- "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.";
- const cmdSelection = {
- dialect: "cmd",
- display: { name: "cmd.exe" },
- id: "auto:cmd",
- path: "C:\\Windows\\System32\\cmd.exe",
- source: "auto-detected",
- } as const;
- const windows: EnvironmentSnapshot = {
- cwd: "C:\\work",
- platform: "win32",
- shell: "cmd.exe",
- osVersion: "Windows 11",
- isGitRepository: true,
- additionalWorkingDirectories: [],
- };
- const environmentNotices = (value: ReturnType<typeof createTestAgentRuntime>) =>
- contextEntries(value).filter((entry) => entry.metadata?.source === "environment");
- it("puts the rule in the Shell bullet of the first notice of a CMD session", async () => {
- runtime = createRuntime(
- { now, contextSourcePort: environmentPort() },
- { ...config, bashShellSelection: cmdSelection },
- );
- await runtime.executeTurn("first");
- const [notice] = environmentNotices(runtime);
- // 规则只在 Shell 行括号里,标题前没有别的段落;没有旧值时不写 was。
- expect(notice?.content).toMatch(/^# Environment\n/);
- expect(notice?.content).toContain(`\n - Shell: cmd.exe (${cmdRule})\n`);
- expect(notice?.content.split(cmdRule)).toHaveLength(2);
- // 不是 cmd.exe 的 shell 不带规则。
- expect(
- buildEnvironmentAnnouncement({ ...windows, shell: "Git Bash" }, undefined, false)?.content,
- ).toContain("\n - Shell: Git Bash\n");
- });
- it("puts the rule in the Shell bullet when an update changes to cmd.exe and only writes was otherwise", () => {
- // 旧会话公告过 system shell 或 CMD,下一次冷恢复换成 cmd.exe 时补上规则。
- for (const old of ["system shell", "CMD", "Git Bash"]) {
- expect(
- buildEnvironmentAnnouncement(windows, { ...windows, shell: old }, true)?.content,
- ).toBe(`# Environment update\n - Shell: cmd.exe (was ${old}; ${cmdRule})`);
- }
- // 旧 Windows 会话的 Shell 可能为空:括号里只有规则。
- expect(buildEnvironmentAnnouncement(windows, { ...windows, shell: "" }, true)?.content).toBe(
- `# Environment update\n - Shell: cmd.exe (${cmdRule})`,
- );
- // 离开 cmd.exe 只写机械的 was。
- expect(
- buildEnvironmentAnnouncement({ ...windows, shell: "Git Bash" }, windows, true)?.content,
- ).toBe("# Environment update\n - Shell: Git Bash (was cmd.exe)");
- // shell 没变时只报其他变化,不重复规则。
- expect(
- buildEnvironmentAnnouncement({ ...windows, cwd: "C:\\other" }, windows, true)?.content,
- ).toBe("# Environment update\n - Primary working directory: C:\\other (was C:\\work)");
- });
- it("marks leaving cmd.exe on the Shell line when the full block is sent again", () => {
- // 平台/系统版本变化(或 compact 后没有完整块)时重发完整块;上一次是 cmd.exe 时 Shell 行带 was。
- const upgraded = { ...windows, shell: "Git Bash", osVersion: "Windows 12" };
- const leaving = buildEnvironmentAnnouncement(upgraded, windows, true)!;
- expect(leaving.environment.full).toBe(true);
- expect(leaving.content).toMatch(/^# Environment\n/);
- expect(leaving.content).toContain("\n - Shell: Git Bash (was cmd.exe)\n");
- // 仍是 cmd.exe,或从别的 shell 换成 cmd.exe 时,完整块的 Shell 行括号里只有规则。
- for (const previousShell of ["cmd.exe", "Git Bash"]) {
- const toCmd = buildEnvironmentAnnouncement(
- { ...windows, osVersion: "Windows 12" },
- { ...windows, shell: previousShell },
- true,
- )!;
- expect(toCmd.content).toMatch(/^# Environment\n/);
- expect(toCmd.content).toContain(`\n - Shell: cmd.exe (${cmdRule})\n`);
- }
- // 其他 shell 之间的完整块不变。
- expect(
- buildEnvironmentAnnouncement(
- { ...upgraded, shell: "zsh" },
- { ...windows, shell: "bash" },
- true,
- )?.content,
- ).toContain("\n - Shell: zsh\n");
- });
- });
- it("republishes a full block for legacy metadata and does not leak snapshot metadata on MCS downgrade", async () => {
- runtime = createRuntime({ now, contextSourcePort: environmentPort() }, config);
- await runtime.executeTurn("first");
- const internal = runtime as unknown as AgentRuntimeInternal;
- const legacy = internal.messageHistory.toRuntimeEntries();
- for (const entry of legacy) {
- if (entry.metadata?.source === "environment") delete entry.metadata.environment;
- }
- internal.messageHistory.replaceMessages(legacy);
- await runtime.executeTurn("legacy history");
- expect(
- contextEntries(runtime).filter((entry) => entry.metadata?.source === "environment"),
- ).toHaveLength(2);
- runtime.setWorkingDirectory("/outside");
- await runtime.executeTurn("leave");
- const returnedEntries = internal.messageHistory.toRuntimeEntries();
- const returnedEnvironment = returnedEntries
- .filter((entry) => entry.metadata?.source === "environment")
- .at(-1)!;
- returnedEnvironment.metadata!.environment!.snapshot.cwd = "/mutated-entry";
- expect(contextEntries(runtime).at(-1)).not.toEqual(returnedEnvironment);
- const projected = buildProviderRequestMessages({
- entries: internal.messageHistory.toRuntimeEntries(),
- useMidConversationSystem: false,
- }).messages;
- expect(JSON.stringify(projected)).not.toMatch(/"(?:metadata|snapshot|environment)"/u);
- expect(
- projected.some(
- (message) =>
- message.role === "user" &&
- String(message.content).includes("<system-reminder>\n# Environment update\n"),
- ),
- ).toBe(true);
- });
- it("does not commit a failed context write and retries the missing sources", async () => {
- runtime = createRuntime({ now, skillPort, contextSourcePort: instructionsPort() }, config);
- const savePart = store.savePart;
- store.savePart = async (part) => {
- if (part.metadata?.runtimeMessage?.source === "environment")
- throw new Error("context write failed");
- await savePart(part);
- };
- await expect(runtime.executeTurn("first")).rejects.toThrow();
- expect(respond).not.toHaveBeenCalled();
- // environment 是第一条公告;它写入失败时,后续来源都不会提交。
- expect(contextEntries(runtime).map((entry) => entry.metadata?.source)).toEqual([]);
- store.savePart = savePart;
- await runtime.executeTurn("retry");
- expect(contextEntries(runtime).map((entry) => entry.metadata?.source)).toEqual([...sources]);
- });
- });
|