Multiplayer agent harness for work.
Keep pi's system prompt tail stable and stop replaying stale environment notes (#1159)
Joshua France33404a220b13
diff --git a/src/core/orchestrator.ts b/src/core/orchestrator.tsindex f85612db8..8002fd657 100644--- a/src/core/orchestrator.ts+++ b/src/core/orchestrator.ts@@ -2597,11 +2597,12 @@ export function createOrchestrator(deps: OrchestratorDeps): Orchestrator {const principalDelivered = await recentPrincipalDeliveryNote(deps.deliveries, session.threadRef);const sender = !automatedTurn && input.text.trim() ? senderNote(actor.displayName) : "";const unscreenedNote = inputUnscreened || inbound.unscreened.length ? unscreenedNotice("inbound content") : "";- const turnEnv = environmentNote(- [manifest, principalDelivered, sender, unscreenedNote, input.conversationHeader?.trim(), volatileContext]+ const turnEnvironment = environmentNote(+ [manifest, principalDelivered, sender, unscreenedNote, input.conversationHeader?.trim()].filter((s) => s && s.trim()).join("\n\n"),);+ const turnVolatile = environmentNote(volatileContext);const baseText = input.proactiveOpener && !input.text.trim() ? PROACTIVE_OPENER_PROMPT : input.text;const pausedTurnUserEntry = input.approval? [...visibleHistory].reverse().find((e) => e.type === "user" && !isOverheardEntry(e))@@ -2631,7 +2632,6 @@ export function createOrchestrator(deps: OrchestratorDeps): Orchestrator {const turnInput = partial? resumeNote({ backgroundJobs: !!backgroundBroker, workRecorded: !!resume }): baseText;- const turnEnvironment = turnEnv;const isPollFire = automatedTurn && !!input.surface && isPollSurface(input.surface);const sessionUsedTools = visibleHistory.some((e) => e.type === "tool_call");if (@@ -2815,7 +2815,6 @@ export function createOrchestrator(deps: OrchestratorDeps): Orchestrator {const runHarnessSegment = (harnessInput: string,extras: {- environment?: string;priorTurns?: typeof input.priorTurns;overheard?: typeof importedOverheard;attachments?: typeof inbound.metas;@@ -2855,7 +2854,8 @@ export function createOrchestrator(deps: OrchestratorDeps): Orchestrator {input: harnessInput,...(!partial && messageTs ? { triggerTs: messageTs } : {}),...(!partial && entryTs ? { entryTs } : {}),- ...(extras.environment ? { environment: extras.environment } : {}),+ ...(turnEnvironment ? { environment: turnEnvironment } : {}),+ ...(turnVolatile ? { volatileContext: turnVolatile } : {}),...(extras.priorTurns?.length ? { priorTurns: extras.priorTurns } : {}),...(extras.overheard?.length ? { overheard: extras.overheard } : {}),...(extras.attachments?.length ? { attachments: extras.attachments } : {}),@@ -3168,10 +3168,7 @@ export function createOrchestrator(deps: OrchestratorDeps): Orchestrator {segment = await runHarnessSegment(resumeNote() +"\nRuntime handoff completed. Continue the user's unfinished request using the saved conversation and tool results. Do not repeat completed actions or ask the user to repeat the request.",- {- ...(turnEnvironment ? { environment: turnEnvironment } : {}),- ...(inbound.images.length ? { images: inbound.images } : {}),- },+ inbound.images.length ? { images: inbound.images } : {},{ history: resumedHistory, ...(resumedTape ? { tape: resumedTape } : {}) },);modelCalls += segment.modelCalls ?? 0;@@ -3181,7 +3178,6 @@ export function createOrchestrator(deps: OrchestratorDeps): Orchestrator {};const primaryServedTape = !!tapeRows?.serve && history === visibleHistory;let result = await runHarnessTurn(turnInput, {- ...(turnEnvironment ? { environment: turnEnvironment } : {}),...(priorTurns?.length ? { priorTurns } : {}),...(importedOverheard.length ? { overheard: importedOverheard } : {}),...(inbound.metas.length ? { attachments: inbound.metas } : {}),@@ -3294,10 +3290,7 @@ export function createOrchestrator(deps: OrchestratorDeps): Orchestrator {: undefined;result = await runHarnessTurn("[system] You were addressed directly. Reply with the `slack` tool's `post` action, or decline explicitly with stay_silent — ending the turn without either is not allowed here.",- {- ...(turnEnvironment ? { environment: turnEnvironment } : {}),- ...(nudgeTape?.mode !== "serve" && inbound.images.length ? { images: inbound.images } : {}),- },+ nudgeTape?.mode !== "serve" && inbound.images.length ? { images: inbound.images } : {},{ history: nudgeHistory, ...(nudgeTape ? { tape: nudgeTape } : {}) },);if (primaryStopped && !result.stopped)diff --git a/src/harness/claude-harness.ts b/src/harness/claude-harness.tsindex 8a8e033ee..29adef4a6 100644--- a/src/harness/claude-harness.ts+++ b/src/harness/claude-harness.ts@@ -216,7 +216,9 @@ function promptText(turn: HarnessTurnInput): string {: seedPriorTurns(turn.priorTurns ?? []).map((message) => message.text).join("\n");- return [replay, prior, turn.input, turn.environment].filter((value) => value?.trim()).join("\n\n");+ return [replay, prior, turn.input, turn.environment, turn.volatileContext]+ .filter((value) => value?.trim())+ .join("\n\n");}function userMessage(text: string, images: HarnessTurnInput["images"] = []): SDKUserMessage {diff --git a/src/harness/codex-harness.ts b/src/harness/codex-harness.tsindex 09dd6ade1..becab2680 100644--- a/src/harness/codex-harness.ts+++ b/src/harness/codex-harness.ts@@ -358,14 +358,14 @@ export function codexReasoningEffort(value: string | undefined): "low" | "medium}export function codexTurnInputText(- turn: Pick<HarnessTurnInput, "history" | "priorTurns" | "input" | "environment">,+ turn: Pick<HarnessTurnInput, "history" | "priorTurns" | "input" | "environment" | "volatileContext">,): string {const prior = turn.history.length? "": seedPriorTurns(turn.priorTurns ?? []).map((message) => message.text).join("\n");- return [prior, turn.input, turn.environment].filter((item) => item?.trim()).join("\n\n");+ return [prior, turn.input, turn.environment, turn.volatileContext].filter((item) => item?.trim()).join("\n\n");}export function createCodexHarness(opts: CodexHarnessOptions = {}): Harness {diff --git a/src/harness/harness.ts b/src/harness/harness.tsindex 42ad45e65..3d2ab63ce 100644--- a/src/harness/harness.ts+++ b/src/harness/harness.ts@@ -78,6 +78,7 @@ export interface HarnessTurnInput {triggerTs?: string;entryTs?: string;environment?: string;+ volatileContext?: string;priorTurns?: ConversationTurn[];overheard?: OverheardEntryPayload[];attachments?: AttachmentMeta[];diff --git a/src/harness/mock-harness.ts b/src/harness/mock-harness.tsindex d38e92840..d05bb8181 100644--- a/src/harness/mock-harness.ts+++ b/src/harness/mock-harness.ts@@ -102,7 +102,9 @@ export function createMockHarness(): Harness {},scopeLabel: turn.scopeLabel,});- const modelPrompt = [turn.input, turn.environment].filter((s) => s && s.trim()).join("\n\n");+ const modelPrompt = [turn.input, turn.environment, turn.volatileContext]+ .filter((s) => s && s.trim())+ .join("\n\n");turn.recordModelCall({model: "mock",@@ -329,7 +331,7 @@ export function createMockHarness(): Harness {} else if (command0 === "!histcount") {reply = `history:${turn.history.length}`;} else if (command0 === "!sysprompt") {- reply = [turn.systemPrompt, turn.environment].filter((s) => s && s.trim()).join("\n\n");+ reply = [turn.systemPrompt, turn.environment, turn.volatileContext].filter((s) => s && s.trim()).join("\n\n");} else if (command0 === "!wallclock") {reply = `wallclock:${turn.turnWallClockMs ?? 0}`;} else if (command0 === "!surfacename") {diff --git a/src/harness/opencode-harness.ts b/src/harness/opencode-harness.tsindex 02c0737ef..624933d49 100644--- a/src/harness/opencode-harness.ts+++ b/src/harness/opencode-harness.ts@@ -960,7 +960,7 @@ export function createOpenCodeHarness(opts: OpenCodeHarnessOptions = {}): Harnes}}};- const prompt = [turn.input, turn.environment].filter((item) => item?.trim()).join("\n\n");+ const prompt = [turn.input, turn.environment, turn.volatileContext].filter((item) => item?.trim()).join("\n\n");const promptParts: Array<Record<string, unknown>> = [{ type: "text", text: prompt },...(turn.images ?? []).map((image, index) => ({diff --git a/src/harness/pi-harness.ts b/src/harness/pi-harness.tsindex 85bd62546..696f9ad1c 100644--- a/src/harness/pi-harness.ts+++ b/src/harness/pi-harness.ts@@ -1,5 +1,5 @@import { Type } from "typebox";-import { mkdtempSync, rmSync, writeFileSync } from "node:fs";+import { mkdirSync, mkdtempSync, rmSync, statSync, writeFileSync } from "node:fs";import { tmpdir } from "node:os";import { join } from "node:path";import {@@ -7,6 +7,7 @@ import {DefaultResourceLoader,ModelRuntime,SessionManager,+ SettingsManager,type AgentSession,} from "@earendil-works/pi-coding-agent";import {@@ -442,6 +443,7 @@ interface TurnSession {composedPromptTokens: number;cwd: string;agentDir: string;+ ephemeralCwd?: string;}interface PerCallStat {@@ -645,8 +647,10 @@ function sumCacheUsage(interface IsolatedResources {resourceLoader: DefaultResourceLoader;+ settingsManager: SettingsManager;cwd: string;agentDir: string;+ ephemeralCwd?: string;}const MAX_CAPTURED_PAYLOAD_CHARS = 2_000_000;@@ -705,6 +709,21 @@ export function stoppedPartialTapeMessage(};}+export function withoutVolatileContext(message: unknown, sent: string, durable: string): unknown {+ if (sent === durable || !durable.trim()) return message;+ const m = message as { content?: unknown };+ if (typeof m?.content === "string") return m.content === sent ? { ...m, content: durable } : message;+ if (!Array.isArray(m?.content)) return message;+ return {+ ...(message as Record<string, unknown>),+ content: m.content.map((block) =>+ (block as { type?: unknown; text?: unknown })?.type === "text" && (block as { text?: unknown }).text === sent+ ? { ...(block as object), text: durable }+ : block,+ ),+ };+}+export function stripImageBytes(message: unknown, images?: readonly { artifactId?: string }[]): unknown {const m = message as { content?: unknown };if (!m || !Array.isArray(m.content)) return message;@@ -1072,13 +1091,29 @@ export function wallClockTurnFailure(return !cancelAborted || wallClock === "abandoned";}+export function stableCwd(prefix: string): string {+ return join(tmpdir(), `${prefix}-cwd`);+}+async function createIsolatedResources(prefix: string, systemPrompt: string): Promise<IsolatedResources> {- const cwd = mkdtempSync(join(tmpdir(), `${prefix}-cwd-`));+ let cwd = stableCwd(prefix);+ let ephemeralCwd: string | undefined;+ try {+ mkdirSync(cwd, { recursive: true });+ if (!statSync(cwd).isDirectory()) throw new Error(`${cwd} is not a directory`);+ } catch (e) {+ swallow("pi: shared cwd unavailable; using a per-turn cwd (prompt cache prefix changes)", e);+ cwd = mkdtempSync(join(tmpdir(), `${prefix}-cwd-`));+ ephemeralCwd = cwd;+ }const agentDir = mkdtempSync(join(tmpdir(), `${prefix}-agent-`));+ const settingsManager = SettingsManager.inMemory({}, { projectTrusted: false });const resourceLoader = new DefaultResourceLoader({cwd,agentDir,+ settingsManager,systemPrompt,+ appendSystemPrompt: [],noExtensions: true,noSkills: true,noPromptTemplates: true,@@ -1086,11 +1121,12 @@ async function createIsolatedResources(prefix: string, systemPrompt: string): PrnoContextFiles: true,});await resourceLoader.reload();- return { resourceLoader, cwd, agentDir };+ return { resourceLoader, settingsManager, cwd, agentDir, ...(ephemeralCwd ? { ephemeralCwd } : {}) };}-function removeIsolatedDirs(dirs: { cwd: string; agentDir: string }): void {- for (const dir of [dirs.cwd, dirs.agentDir]) {+function removeIsolatedDirs(dirs: { agentDir: string; ephemeralCwd?: string }): void {+ for (const dir of [dirs.agentDir, dirs.ephemeralCwd]) {+ if (!dir) continue;try {rmSync(dir, { recursive: true, force: true });} catch (e) {@@ -1224,12 +1260,16 @@ export async function oneShot(opts?: { signal?: AbortSignal; modelGateway?: ModelGatewayTransportConfig },): Promise<string | undefined> {const modelRuntime = await buildModelRuntime(keys, opts?.modelGateway);- const { resourceLoader, cwd, agentDir } = await createIsolatedResources(prefix, systemPrompt);+ const { resourceLoader, settingsManager, cwd, agentDir, ephemeralCwd } = await createIsolatedResources(+ prefix,+ systemPrompt,+ );try {const { session } = await createAgentSession({model,modelRuntime,resourceLoader,+ settingsManager,customTools: [],noTools: "builtin",sessionManager: SessionManager.inMemory(),@@ -1251,8 +1291,7 @@ export async function oneShot(}return piLastAssistantTextOrThrow(session);} finally {- rmSync(cwd, { recursive: true, force: true });- rmSync(agentDir, { recursive: true, force: true });+ removeIsolatedDirs({ agentDir, ephemeralCwd });}}@@ -1533,7 +1572,10 @@ export function createPiHarness(opts?: PiHarnessOptions): Harness {systemCacheSplit ? "long" : undefined,);const ref: ToolContextRef = { current: null };- const { resourceLoader, cwd, agentDir } = await createIsolatedResources(tempDirPrefix, composedPrompt);+ const { resourceLoader, settingsManager, cwd, agentDir, ephemeralCwd } = await createIsolatedResources(+ tempDirPrefix,+ composedPrompt,+ );const compileMs = Date.now() - compileStart;let session: AgentSession;@@ -1542,6 +1584,7 @@ export function createPiHarness(opts?: PiHarnessOptions): Harness {model,modelRuntime,resourceLoader,+ settingsManager,customTools: createAgentTools(ref, {scratchExec,ownerAuthExec,@@ -1565,7 +1608,7 @@ export function createPiHarness(opts?: PiHarnessOptions): Harness {agentDir,}));} catch (err) {- removeIsolatedDirs({ cwd, agentDir });+ removeIsolatedDirs({ agentDir, ephemeralCwd });throw err;}@@ -1592,7 +1635,7 @@ export function createPiHarness(opts?: PiHarnessOptions): Harness {scopeLabel: turnScope!,});} catch (err) {- removeIsolatedDirs({ cwd, agentDir });+ removeIsolatedDirs({ agentDir, ephemeralCwd });throw err;}}@@ -1673,6 +1716,7 @@ export function createPiHarness(opts?: PiHarnessOptions): Harness {composedPromptTokens: countTokens(composedPrompt),cwd,agentDir,+ ...(ephemeralCwd ? { ephemeralCwd } : {}),};return { entry, compileMs };}@@ -1777,7 +1821,8 @@ export function createPiHarness(opts?: PiHarnessOptions): Harness {if (pausedGoalAtStart) return goalPausedNote(pausedGoalAtStart);return "";})();- const modelPrompt = [goalNote, turn.input, turn.environment].filter((s) => s && s.trim()).join("\n\n");+ const durablePrompt = [goalNote, turn.input, turn.environment].filter((s) => s && s.trim()).join("\n\n");+ const modelPrompt = [durablePrompt, turn.volatileContext].filter((s) => s && s.trim()).join("\n\n");entry.ref.llmCapture = [];entry.ref.modelCalls = 0;entry.ref.modelDispatch = [];@@ -1810,6 +1855,13 @@ export function createPiHarness(opts?: PiHarnessOptions): Harness {entryCreatedAt: steer!.entryCreatedAt,};};+ const tapedTrigger = (message: unknown): unknown => {+ const taped = withoutVolatileContext(message, modelPrompt, durablePrompt);+ if (taped === message && durablePrompt.trim() && modelPrompt !== durablePrompt) {+ console.error(`[pi] taped trigger kept its volatile context session=${turn.session.id}`);+ }+ return taped;+ };const tapeMessage = async (message: unknown): Promise<void> => {if (!turn.tape || tapeError) return;const role = (message as { role?: string }).role;@@ -1823,7 +1875,10 @@ export function createPiHarness(opts?: PiHarnessOptions): Harness {const rec: NewTapeRecord = {kind: "message",harness: "pi",- payload: stripImageBytes(message, isTrigger ? turn.images : undefined),+ payload: stripImageBytes(+ isTrigger ? tapedTrigger(message) : message,+ isTrigger ? turn.images : undefined,+ ),scopeLabel: resultScope ?? turn.scopeLabel,...(isTrigger? {diff --git a/test/pi-harness-environment-notes.test.ts b/test/pi-harness-environment-notes.test.tsnew file mode 100644index 000000000..72a579477--- /dev/null+++ b/test/pi-harness-environment-notes.test.ts@@ -0,0 +1,35 @@+import assert from "node:assert/strict";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { test } from "node:test";+import { stableCwd, withoutVolatileContext } from "../src/harness/pi-harness.ts";++test("the cwd pi appends to the system prompt is one constant path per harness", () => {+ assert.equal(stableCwd("pi"), join(tmpdir(), "pi-cwd"));+ assert.equal(stableCwd("pi"), stableCwd("pi"));+});++const durable = "what's on today?\n\n<environment>\nThis message is from @alice.\n</environment>";+const volatile = "<environment>\n## The user's local time\nMonday 9am\n</environment>";+const sent = `${durable}\n\n${volatile}`;++test("the taped trigger message keeps the durable note and drops the volatile one", () => {+ assert.deepEqual(withoutVolatileContext({ role: "user", content: sent }, sent, durable), {+ role: "user",+ content: durable,+ });+ const image = { type: "image", data: "abc", mimeType: "image/png" };+ assert.deepEqual(+ withoutVolatileContext({ role: "user", content: [{ type: "text", text: sent }, image] }, sent, durable),+ { role: "user", content: [{ type: "text", text: durable }, image] },+ );+});++test("messages that are not the trigger text, or would become empty, pass through by reference", () => {+ const other = { role: "user", content: "steer: stop" };+ assert.equal(withoutVolatileContext(other, sent, durable), other);+ const noVolatile = { role: "user", content: durable };+ assert.equal(withoutVolatileContext(noVolatile, durable, durable), noVolatile);+ const onlyVolatile = { role: "user", content: volatile };+ assert.equal(withoutVolatileContext(onlyVolatile, volatile, ""), onlyVolatile);+});diff --git a/test/pi-harness-freshness.test.ts b/test/pi-harness-freshness.test.tsindex c0ee9015e..be9cda2c2 100644--- a/test/pi-harness-freshness.test.ts+++ b/test/pi-harness-freshness.test.ts@@ -1,9 +1,9 @@import { test } from "node:test";import assert from "node:assert/strict";-import { readdirSync } from "node:fs";+import { readdirSync, rmSync, writeFileSync } from "node:fs";import { tmpdir } from "node:os";import { countTokens } from "../src/util/tokens.ts";-import { createPiHarness } from "../src/harness/pi-harness.ts";+import { createPiHarness, stableCwd } from "../src/harness/pi-harness.ts";import type { HarnessTurnInput } from "../src/harness/harness.ts";function countTempDirs(prefix: string): number {@@ -52,15 +52,31 @@ test("every turn composes the freshly resolved system prompt", async () => {assert.equal(recorded[1]!.inputTokens, countTokens(second) + countTokens("hi"));});-test("each turn removes its isolated resource directories", async () => {+test("each turn removes its agent directory and reuses one constant cwd", async () => {const prefix = `pi-turn-${process.pid}`;const harness = createPiHarness({ tempDirPrefix: prefix });const recorded: Array<{ model: string; inputTokens: number; entryCount: number }> = [];await runIgnoringPromptError(harness, recordingTurn("BASE", recorded, "cleanup"));+ await runIgnoringPromptError(harness, recordingTurn("BASE", recorded, "cleanup-2"));+ assert.equal(countTempDirs(`${prefix}-agent-`), 0);+ assert.equal(countTempDirs(`${prefix}-cwd`), 1);+ rmSync(stableCwd(prefix), { recursive: true, force: true });+});++test("a squatted shared cwd falls back to a per-turn cwd that is removed afterwards", async () => {+ const prefix = `pi-squat-${process.pid}`;+ writeFileSync(stableCwd(prefix), "not a directory");+ const harness = createPiHarness({ tempDirPrefix: prefix });+ const recorded: Array<{ model: string; inputTokens: number; entryCount: number }> = [];++ await runIgnoringPromptError(harness, recordingTurn("BASE", recorded, "squat"));++ assert.equal(recorded.length, 1, "the turn still reached the model call");assert.equal(countTempDirs(`${prefix}-cwd-`), 0);assert.equal(countTempDirs(`${prefix}-agent-`), 0);+ rmSync(stableCwd(prefix), { force: true });});test("the Pi harness exposes no session-reset hook after removing session state", () => {diff --git a/test/pi-harness-oneshot.test.ts b/test/pi-harness-oneshot.test.tsindex cd3a87afe..ada09acaf 100644--- a/test/pi-harness-oneshot.test.ts+++ b/test/pi-harness-oneshot.test.ts@@ -237,14 +237,14 @@ test("piHarnessConfigOptions omits the optional fields when the config leaves thtest("oneShot removes its temp dirs even when the session call throws", async () => {const prefix = "pi-onesh-test";- const before = countTempDirs(prefix);+ const before = countTempDirs(`${prefix}-agent-`);const fakeModel = { id: "claude-sonnet-4-5" } as unknown as Parameters<typeof oneShot>[1];await assert.rejects(oneShot(prefix, fakeModel, "test-key", "system", "prompt"));- const after = countTempDirs(prefix);- assert.equal(after, before, "oneShot must leave no temp dirs behind");+ const after = countTempDirs(`${prefix}-agent-`);+ assert.equal(after, before, "oneShot must leave no agent dirs behind");});test("oneShot completes an authenticated Pi 0.82 turn", async (t) => {diff --git a/test/system-prompt-order.test.ts b/test/system-prompt-order.test.tsindex 4c19c133c..f3afa7b22 100644--- a/test/system-prompt-order.test.ts+++ b/test/system-prompt-order.test.ts@@ -18,6 +18,7 @@ import { createModelGateway } from "../src/model/model-gateway.ts";import { createAuditLog } from "../src/audit/audit-log.ts";import { createRateLimiter } from "../src/ratelimit/rate-limiter.ts";import { createMockHarness } from "../src/harness/mock-harness.ts";+import type { HarnessTurnInput } from "../src/harness/harness.ts";import { createCronStore, type CronStore } from "../src/cron/cron-store.ts";import { createDeployStore } from "../src/deploy/deploy-store.ts";import { createDockerDeployProvider } from "../src/deploy/docker-deploy-provider.ts";@@ -96,6 +97,7 @@ function buildOrchestrator(skills?: SkillStore;skillBundles?: SkillBundleStore;securityScreener?: SecurityScreener;+ harness?: ReturnType<typeof createMockHarness>;managedGroups?: Pick<ManagedGroupDirectory, "recognizes" | "members" | "version" | "withVersion" | "slackChannel">;isCurrentSharedScopeMember?: IsCurrentSharedScopeMember;} = {},@@ -480,7 +482,11 @@ test("the system prompt is byte-identical across two turns a minute apart; the c`"## ${title}" must not be in the system prompt`,);}- assert.match(environmentOf(first.reply ?? ""), /## The user's local time/);+ assert.match(+ environmentOf(first.reply ?? ""),+ /<environment>\n## The user's local time/,+ "the clock opens its own environment note, separate from the durable per-message facts",+ );assert.notEqual(environmentOf(second.reply ?? ""), environmentOf(first.reply ?? ""), "the clock moved a minute");assert.equal(systemOf(second.reply ?? ""),@@ -489,6 +495,36 @@ test("the system prompt is byte-identical across two turns a minute apart; the c);});+test("the harness receives the clock and memory as volatile context; the durable note keeps the sender", async () => {+ const mock = createMockHarness();+ const received: HarnessTurnInput[] = [];+ const harness = {+ ...mock,+ turns: {+ ...mock.turns,+ runTurn: (turn: HarnessTurnInput) => {+ received.push(turn);+ return mock.turns.runTurn(turn);+ },+ },+ };+ const { orchestrator: orch, memory } = buildOrchestrator({ harness });+ await memory.replace(scopeId("personal", "U1"), "- remembers the chartreuse mug");++ const res = await orch.handleTurn(+ dm("dm:U1:volatile-split", "hello", {+ actor: { ...actor, displayName: "Alice" },+ timezone: "America/New_York",+ }),+ );+ assert.equal(res.status, "ok");+ const turn = received.at(-1)!;+ assert.match(turn.environment ?? "", /This message is from @Alice/);+ assert.doesNotMatch(turn.environment ?? "", /The user's local time|chartreuse/);+ assert.match(turn.volatileContext ?? "", /^<environment>\n## The user's local time/);+ assert.match(turn.volatileContext ?? "", /chartreuse/);+});+test("the cached prefix survives skill-store reordering + a recordUse-style metadata update", async () => {const mkSkill = (name: string, lastUsedAt?: number) => ({skill: { manifest: { name, description: `does ${name}` }, lastUsedAt },