Multiplayer agent harness for work.
Mark calendar days in the model's replayed context (#2411)
Regan Bella4e96623e972
diff --git a/src/harness/pi-harness.ts b/src/harness/pi-harness.tsindex 3e81154b1..c9aeb1187 100644--- a/src/harness/pi-harness.ts+++ b/src/harness/pi-harness.ts@@ -97,6 +97,7 @@ import { startSignalPoll, type RunSignalStore } from "../runs/run-signal-store.timport {planColdStartSeed,reconstructMessagesFromHistory,+ dayMarkerPrefix,recordedMessageTimestamps,replayPreamble,userPromptText,@@ -1840,7 +1841,13 @@ export function createPiHarness(opts?: PiHarnessOptions): Harness {},scopeLabel: turn.scopeLabel,});- const modelPrompt = userPromptText({ goalNote, text: turn.input, environment: turn.environment });+ const modelPrompt =+ (userEntry+ ? dayMarkerPrefix(+ turn.history.findLast((e) => e.type === "user" && e.seq < userEntry.seq),+ userEntry,+ )+ : "") + userPromptText({ goalNote, text: turn.input, environment: turn.environment });entry.ref.llmCapture = [];entry.ref.modelCalls = 0;entry.ref.modelDispatch = [];diff --git a/src/harness/replay.ts b/src/harness/replay.tsindex 2e8635ff5..29b564506 100644--- a/src/harness/replay.ts+++ b/src/harness/replay.ts@@ -17,6 +17,7 @@ import { CONTEXT_SUMMARY_HEADER, INTERRUPTED_TOOL_RESULT, unrecordedToolResult }import { contextSummaryPayload } from "../sessions/session-store.ts";import { isoFromTs, messageTag } from "../util/message-tag.ts";import { isObj } from "../util/objects.ts";+import { DEFAULT_CRON_TIMEZONE } from "../cron/schedule.ts";export const TURN_STOPPED_KIND = "turn_stopped";@@ -125,6 +126,25 @@ export function selectOverheardToImport(return out;}+const DAY_MARKER_FORMAT = new Intl.DateTimeFormat("en-US", {+ weekday: "long",+ month: "long",+ day: "numeric",+ year: "numeric",+ timeZone: DEFAULT_CRON_TIMEZONE,+});++function entryDay(e: SessionEntry): string {+ const ov = overheardPayload(e);+ const sent = ov ? Date.parse(isoFromTs(ov.ts)) : Number.NaN;+ return DAY_MARKER_FORMAT.format(Number.isFinite(sent) ? sent : e.createdAt);+}++export function dayMarkerPrefix(previous: SessionEntry | undefined, e: SessionEntry): string {+ const day = entryDay(e);+ return previous && entryDay(previous) === day ? "" : `── ${day} ──\n`;+}+export function renderOverheard(p: OverheardEntryPayload): string {const body = p.text || (p.files?.length ? "(shared file)" : "");return messageTag(@@ -319,6 +339,7 @@ export function reconstructMessagesFromHistory(});let previous: SessionEntry | undefined;+ let previousUser: SessionEntry | undefined;let batch: AssistantMessage | undefined;for (const e of history) {const prior = previous;@@ -358,9 +379,11 @@ export function reconstructMessagesFromHistory(continue;}if (e.type === "user") {+ const day = dayMarkerPrefix(previousUser, e);+ previousUser = e;const ov = overheardPayload(e);if (ov) {- if (ov.text.trim() || ov.files?.length) raw.push(userMsg(renderOverheard(ov), e.createdAt));+ if (ov.text.trim() || ov.files?.length) raw.push(userMsg(day + renderOverheard(ov), e.createdAt));} else {const p = (e.payload ?? {}) as Record<string, unknown>;const t = userPromptText(p);@@ -368,7 +391,7 @@ export function reconstructMessagesFromHistory(if (t || images.length)raw.push({role: "user",- content: [{ type: "text", text: t }, ...images.map((ref) => ({ type: "image" as const, ref }))],+ content: [{ type: "text", text: day + t }, ...images.map((ref) => ({ type: "image" as const, ref }))],timestamp: e.createdAt,});}diff --git a/test/message-revisions.test.ts b/test/message-revisions.test.tsindex a435325dc..d2c8ab1e8 100644--- a/test/message-revisions.test.ts+++ b/test/message-revisions.test.ts@@ -185,7 +185,7 @@ test("the marker renders into model context on the entries-replay path", () => {] as unknown as SessionEntry[];const messages = reconstructMessagesFromHistory(history);const texts = messages.map((m) => (m.content[0] as { text: string }).text);- assert.equal(texts[0], "original text");+ assert.equal(texts[0], "── Wednesday, December 31, 1969 ──\noriginal text");assert.match(texts[1]!, /<message-edited id="100.1" author="Alex Morgan"[^>]*>fixed <text><\/message-edited>/);assert.match(texts[2]!,diff --git a/test/pi-harness-continue.test.ts b/test/pi-harness-continue.test.tsindex 6e1b0bb6a..cb4f10da0 100644--- a/test/pi-harness-continue.test.ts+++ b/test/pi-harness-continue.test.ts@@ -129,7 +129,7 @@ test("a genuine resume whose context ends at a recorded tool result continues th);assert.deepEqual(userTexts(requests),- ["list the files"],+ ["── Wednesday, December 31, 1969 ──\nlist the files"],"the request reaches the model once and nothing else is prompted",);assert.deepEqual(@@ -161,14 +161,14 @@ test("a resume that re-runs a retry-safe call continues the assistant turn right);const flattened = JSON.stringify(requests[0]!.messages);assert.ok(flattened.includes("shared/q2.md"), "the model sees the re-run result");- assert.deepEqual(userTexts(requests), ["list the files"]);+ assert.deepEqual(userTexts(requests), ["── Wednesday, December 31, 1969 ──\nlist the files"]);assert.ok(!flattened.includes("[interrupted"));});test("a resume whose last tool call never recorded a result continues silently after the interrupted result", async () => {const { sink, requests } = await runResume([ASK, CALL], { continueTurn: true, resumeUserSeq: ASK.seq });assert.ok(JSON.stringify(requests[0]!.messages.at(-1)).includes(INTERRUPTED_TOOL_RESULT));- assert.deepEqual(userTexts(requests), ["list the files"]);+ assert.deepEqual(userTexts(requests), ["── Wednesday, December 31, 1969 ──\nlist the files"]);assert.deepEqual(sink.entries.map((e) => e.type),["assistant"],@@ -178,7 +178,7 @@ test("a resume whose last tool call never recorded a result continues silently atest("a resume that died before any work continues from the recorded request without re-sending it", async () => {const { sink, requests } = await runResume([ASK], { continueTurn: true, resumeUserSeq: ASK.seq });assert.equal(requests[0]!.messages.length, 1);- assert.deepEqual(userTexts(requests), ["list the files"]);+ assert.deepEqual(userTexts(requests), ["── Wednesday, December 31, 1969 ──\nlist the files"]);assert.deepEqual(sink.entries.map((e) => e.type),["assistant"],@@ -207,7 +207,7 @@ test("a resume that died before delivering its reply drops that reply and contin});assert.equal(requests[0]!.messages.at(-1)!.role, "user");assert.ok(!JSON.stringify(requests[0]!.messages).includes("Here are"));- assert.deepEqual(userTexts(requests), ["list the files"]);+ assert.deepEqual(userTexts(requests), ["── Wednesday, December 31, 1969 ──\nlist the files"]);assert.deepEqual(sink.entries.map((e) => e.type),["assistant"],diff --git a/test/pi-harness-freshness.test.ts b/test/pi-harness-freshness.test.tsindex 24a4ad9b4..1a4f0a41c 100644--- a/test/pi-harness-freshness.test.ts+++ b/test/pi-harness-freshness.test.ts@@ -24,7 +24,7 @@ function recordingTurn(tools: {} as HarnessTurnInput["tools"],scopeLabel: "scope" as HarnessTurnInput["scopeLabel"],orgScopeId: "org:test" as HarnessTurnInput["orgScopeId"],- emit: async (entry) => ({ ...entry, seq: 1 }) as Awaited<ReturnType<HarnessTurnInput["emit"]>>,+ emit: async (entry) => ({ ...entry, seq: 1, createdAt: 0 }) as Awaited<ReturnType<HarnessTurnInput["emit"]>>,recordModelCall: (rec) => recorded.push(rec),};}@@ -49,8 +49,9 @@ test("every turn composes the freshly resolved system prompt", async () => {await runIgnoringPromptError(harness, recordingTurn(first, recorded, "fresh-prompt"));await runIgnoringPromptError(harness, recordingTurn(second, recorded, "fresh-prompt"));- assert.equal(recorded[0]!.inputTokens, countTokens(first) + countTokens("hi"));- assert.equal(recorded[1]!.inputTokens, countTokens(second) + countTokens("hi"));+ const prompt = "── Wednesday, December 31, 1969 ──\nhi";+ assert.equal(recorded[0]!.inputTokens, countTokens(first) + countTokens(prompt));+ assert.equal(recorded[1]!.inputTokens, countTokens(second) + countTokens(prompt));});test("the cwd pi appends to the system prompt is one constant path per harness", () => {diff --git a/test/pi-harness-replay-fidelity.test.ts b/test/pi-harness-replay-fidelity.test.tsindex 44e599fb3..81013dfdc 100644--- a/test/pi-harness-replay-fidelity.test.ts+++ b/test/pi-harness-replay-fidelity.test.ts@@ -1,4 +1,4 @@-import { test } from "node:test";+import { mock, test } from "node:test";import assert from "node:assert/strict";import { createPiHarness, EMPTY_ENDING_NOTE } from "../src/harness/pi-harness.ts";import type { HarnessTurnInput } from "../src/harness/harness.ts";@@ -195,6 +195,31 @@ test("the next turn's anthropic request replays the previous turn byte-for-byte:]);});+test("a turn on a later day is prompted under that day's marker and replays it byte-for-byte on the next turn", async () => {+ const reply = (text: string) => () => anthropicSse([{ type: "text", text }], "end_turn");+ const userTexts = (body: Body) =>+ (body.messages as Array<{ role: string; content: Array<{ type: string; text?: string }> }>)+ .filter((m) => m.role === "user")+ .map((m) => m.content.find((b) => b.type === "text")?.text);+ mock.timers.enable({ apis: ["Date"], now: Date.parse("2026-10-16T17:00:00Z") });+ try {+ const friday = await runTurn("the deadline is Friday", [], [reply("Noted.")]);+ mock.timers.setTime(Date.parse("2026-10-19T18:00:00Z"));+ const monday = await runTurn("has the deadline passed?", forModelContext(friday.emitted), [reply("Yes.")]);+ assert.deepEqual(userTexts(monday.bodies[0]!), [+ "── Friday, October 16, 2026 ──\nthe deadline is Friday",+ "── Monday, October 19, 2026 ──\nhas the deadline passed?",+ ]);+ const later = await runTurn("thanks", forModelContext([...friday.emitted, ...monday.emitted]), [reply("Sure.")]);+ const before = withoutCacheControl(monday.bodies[0]!.messages) as unknown[];+ const after = withoutCacheControl(later.bodies[0]!.messages) as unknown[];+ assert.equal(JSON.stringify(after.slice(0, before.length)), JSON.stringify(before));+ assert.equal(userTexts(later.bodies[0]!).at(-1), "thanks");+ } finally {+ mock.timers.reset();+ }+});+test("the next turn's OpenAI Responses request replays the previous turn's reasoning items, messages and calls exactly", async () => {const reasoning = (id: string, text: string) => ({type: "reasoning",diff --git a/test/replay.test.ts b/test/replay.test.tsindex 2352ecd11..f8e1b3bf5 100644--- a/test/replay.test.ts+++ b/test/replay.test.ts@@ -210,7 +210,7 @@ test("reconstructMessagesFromHistory opens with a fixed user frame when the agen[["user", [{ type: "text", text: AGENT_OPENED_TEXT }]],["assistant", [{ type: "text", text: "daily digest" }]],- ["user", [{ type: "text", text: "thanks" }]],+ ["user", [{ type: "text", text: "── Wednesday, December 31, 1969 ──\nthanks" }]],],);});@@ -528,7 +528,10 @@ test("reconstructMessagesFromHistory replays the environment note the user messa];const [user] = reconstructMessagesFromHistory(history);assert.deepEqual(user!.content, [- { type: "text", text: "what's on today?\n\n<environment>\nIt is Monday 9am\n</environment>" },+ {+ type: "text",+ text: "── Wednesday, December 31, 1969 ──\nwhat's on today?\n\n<environment>\nIt is Monday 9am\n</environment>",+ },]);});@@ -692,3 +695,32 @@ test("a tool result cut off by a deploy says so in its replayed result", () => {const text = JSON.stringify(reconstructMessagesFromHistory(history));assert.match(text, /A routine platform deploy interrupted this call/);});++test("replayed context marks each Pacific calendar day once, dating overheard Slack messages by when they were sent", () => {+ const imported = Date.parse("2026-10-19T18:00:00Z");+ const overheard = (iso: string, text: string): SessionEntry => ({+ ...overheardEntry(String(Date.parse(iso) / 1000), "Dana", text),+ createdAt: imported,+ });+ const msgs = reconstructMessagesFromHistory([+ overheard("2026-10-15T20:00:00Z", "kickoff today"),+ overheard("2026-10-16T16:00:00Z", "the deadline is Friday"),+ overheard("2026-10-17T05:30:00Z", "still Friday night here"),+ overheard("2026-10-17T08:00:00Z", "saturday early"),+ { ...ent("user", { text: "has the deadline passed?" }, 5), createdAt: imported },+ ]);+ const lines = msgs.flatMap((m) =>+ m.content.flatMap((b) => (b.type === "text" ? b.text.split("\n").filter((l) => l.startsWith("──")) : [])),+ );+ assert.deepEqual(lines, [+ "── Thursday, October 15, 2026 ──",+ "── Friday, October 16, 2026 ──",+ "── Saturday, October 17, 2026 ──",+ "── Monday, October 19, 2026 ──",+ ]);+ assert.match((msgs[2]!.content[0] as { text: string }).text, /^<message overheard="true"/);+ assert.equal(+ (msgs[4]!.content[0] as { text: string }).text,+ "── Monday, October 19, 2026 ──\nhas the deadline passed?",+ );+});