From ee5e08bdf2e62718644eca42f9237216c0367220 Mon Sep 17 00:00:00 2001 From: Josh Winters Date: Mon, 23 Nov 2026 18:16:39 -0500 Subject: [PATCH 1/5] Send each hot checkpoint once per session; point to unrelated ones Claude Code and Codex sessions received the top hot checkpoint on every prompt, even when it shared no words with the prompt, and the same excerpt and the ~600-character capture contract were repeated each turn. - Record per host session which checkpoint digests it received (local state only). A checkpoint the session already holds is not sent again; PreCompact, PostCompact, SessionStart(compact), a changed checkpoint or 25 prompts without a reset send it again. - After the first prompt, a checkpoint that shares no terms with the prompt is reduced to one line naming its request and the page command. - The capture contract is sent only when the session holds no earlier delivery (first prompt, after compaction). - Within an entry, superseded earlier findings come first and the latest finding last, labelled with its time. Other hosts are unchanged. Task Master 162. --- README.md | 7 +- src/runtime/claude-code-hook.ts | 9 +- src/runtime/codex-hook.ts | 4 +- src/runtime/hook-session-context.ts | 64 +++++++++++++ src/runtime/host-adapter-base.ts | 58 ++++++++++-- src/runtime/hot-continuity.ts | 57 ++++++++--- src/runtime/startup-context.ts | 8 +- tests/runtime/hot-continuity.test.ts | 4 +- tests/runtime/hot-delivery.test.ts | 137 +++++++++++++++++++++++++++ 9 files changed, 325 insertions(+), 23 deletions(-) create mode 100644 tests/runtime/hot-delivery.test.ts diff --git a/README.md b/README.md index d28bf5f..3434e48 100644 --- a/README.md +++ b/README.md @@ -230,7 +230,12 @@ a fresh session after choosing either setting. `--allow-stale`. - Imported text is labelled as an imported handoff, not as something you saved yourself. It is not promoted to warm memory. Until the project records newer - work (and for at most seven days) it is included in every prompt there. + work (and for at most seven days) it is offered to every session there. +- Within one Claude Code or Codex session, a checkpoint is sent once, not on + every prompt. It is sent again after compaction or when the checkpoint + changes. After a session's first prompt, a checkpoint that shares no words + with the prompt is shown only as a one-line pointer with the command that + reads it. - `crosshead remember ""` saves one explicit fact for the current project; new sessions in either host receive it. - `crosshead status`, `crosshead doctor` and `crosshead logs` show what the diff --git a/src/runtime/claude-code-hook.ts b/src/runtime/claude-code-hook.ts index f55b6f7..6868a04 100644 --- a/src/runtime/claude-code-hook.ts +++ b/src/runtime/claude-code-hook.ts @@ -4,7 +4,7 @@ import { existsSync, readFileSync } from "fs"; import path from "path"; import { captureHotFinding } from "./hot-continuity"; -import { claimSessionStartContext, releaseSessionStartContext } from "./hook-session-context"; +import { claimSessionStartContext, releaseSessionStartContext, resetSessionDelivery } from "./hook-session-context"; import { readLastAssistantMessage } from "./hook-transcript"; import { recordTokenUsageHook, tokenUsagePhase } from "./token-usage"; @@ -402,6 +402,13 @@ export const runOnlyBotsClaudeCodeHookCli = async ( const event = normalizedEventName.replace(/_/g, ""); // Older Claude Code releases send child auto-compactions with the exact // parent payload. Only the manual trigger identifies a parent compaction. + const compactSessionId = pickString(payload, ["session_id", "sessionId", "session.id", "conversation_id", "conversationId"]); + if (event === "precompact" || event === "postcompact" || (event === "sessionstart" && pickString(payload, ["source", "payload.source"]) === "compact")) { + // Any compaction, including the automatic ones skipped below, drops what the + // session held, so its checkpoints are sent again. A child compaction that + // reuses the parent's id only costs the parent one repeat. + if (compactSessionId) resetSessionDelivery(runtimeHome, "claude-code", { sessionId: compactSessionId }); + } if ((event === "precompact" || event === "postcompact") && pickCompactionTrigger(payload) !== "manual") return; if (event === "sessionstart" && pickString(payload, ["source", "payload.source"]) === "compact") return; const viaPlugin = isPluginHookInvocation(flags); diff --git a/src/runtime/codex-hook.ts b/src/runtime/codex-hook.ts index f1bb8fc..e231fb2 100644 --- a/src/runtime/codex-hook.ts +++ b/src/runtime/codex-hook.ts @@ -17,7 +17,7 @@ import { import { ensureRuntimeHomeLayout } from "./local-runtime"; import { compactContinuitySummary } from "./summary-compaction"; import { captureHotFinding } from "./hot-continuity"; -import { claimSessionStartContext, releaseSessionStartContext } from "./hook-session-context"; +import { claimSessionStartContext, releaseSessionStartContext, resetSessionDelivery } from "./hook-session-context"; import { readLastAssistantMessage } from "./hook-transcript"; import { recordTokenUsageHook, tokenUsagePhase } from "./token-usage"; import { loadProfile, writeJsonFile } from "./runtime-persistence"; @@ -528,6 +528,8 @@ export const runOnlyBotsCodexHookCli = async ( pickString(payload, ["turn_id", "turnId", "event_id", "eventId", "id", "message_id", "messageId"]) ?? state.turnId ?? null; + // Compaction drops what the session held; its checkpoints are sent again. + if (requestedSessionId) resetSessionDelivery(runtimeHome, "codex", { sessionId: requestedSessionId }); const turnState = selectHookTurnState(state, requestedSessionId, requestedTurnId); const sessionId = turnState.sessionId ?? requestedSessionId ?? buildSyntheticSessionId(); const turnId = turnState.turnId ?? requestedTurnId ?? null; diff --git a/src/runtime/hook-session-context.ts b/src/runtime/hook-session-context.ts index 5ecffaf..d80b601 100644 --- a/src/runtime/hook-session-context.ts +++ b/src/runtime/hook-session-context.ts @@ -32,6 +32,7 @@ export const claimSessionStartContext = (runtimeHome: string, host: string, work /** After compaction the host has dropped earlier context, so the next prompt is a fresh start. */ export const releaseSessionStartContext = (runtimeHome: string, host: string, workspaceId: string): void => { + resetSessionDelivery(runtimeHome, host, { workspaceId }); try { const file = markerFile(runtimeHome, host), marker = readMarker(file); if (!Object.hasOwn(marker, workspaceId)) return; @@ -39,3 +40,66 @@ export const releaseSessionStartContext = (runtimeHome: string, host: string, wo writeJsonFile(file, marker); } catch { /* A missed release only costs the larger budget once. */ } }; + +// Which hot checkpoints each host session has already been given. A checkpoint +// the session already holds is not sent again on every prompt; compaction, a +// session start or a changed checkpoint (a new digest) sends it again. +// Local state only: never synced, keyed by host session. +const deliveryFile = (runtimeHome: string, host: string): string => + path.join(ensureRuntimeHomeLayout(runtimeHome).state, `${host}-context-delivery.json`); +// A safety net for compactions no hook reports: after this many prompts the +// session receives its checkpoints again. +export const HOT_REDELIVERY_PROMPTS = 25; +const MAX_DELIVERY_SESSIONS = 64; +const MAX_DELIVERY_DIGESTS = 48; + +type DeliveryRecord = { workspaceId: string; digests: string[]; prompts: number; updatedAt: string }; + +const readDeliveries = (file: string): Record => { + if (!existsSync(file)) return {}; + try { + const parsed = JSON.parse(readFileSync(file, "utf8")) as unknown; + if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return {}; + return Object.fromEntries(Object.entries(parsed as Record).flatMap(([key, value]) => { + const item = value as Partial | null; + return item && typeof item === "object" && Array.isArray(item.digests) && typeof item.prompts === "number" + ? [[key, { workspaceId: String(item.workspaceId ?? ""), digests: item.digests.filter((d): d is string => typeof d === "string"), prompts: item.prompts, updatedAt: String(item.updatedAt ?? "") }]] + : []; + })); + } catch { return {}; } +}; + +/** + * What this session already received. `refresh` is true when it must be treated + * as holding nothing: no record (new session, or reset by compaction) or the + * redelivery interval has passed. + */ +export const readSessionDelivery = (runtimeHome: string, host: string, sessionId: string): { delivered: Set; refresh: boolean } => { + try { + const record = readDeliveries(deliveryFile(runtimeHome, host))[sessionId]; + if (!record || record.prompts >= HOT_REDELIVERY_PROMPTS) return { delivered: new Set(), refresh: true }; + return { delivered: new Set(record.digests), refresh: false }; + } catch { return { delivered: new Set(), refresh: true }; } +}; + +/** Record this prompt's deliveries. `refresh` starts a new record; otherwise digests are added. */ +export const recordSessionDelivery = (runtimeHome: string, host: string, workspaceId: string, sessionId: string, digests: string[], refresh: boolean): void => { + try { + const file = deliveryFile(runtimeHome, host), records = readDeliveries(file); + const previous = refresh ? undefined : records[sessionId]; + delete records[sessionId]; + const merged = [...new Set([...(previous?.digests ?? []), ...digests])].slice(-MAX_DELIVERY_DIGESTS); + const next = { ...records, [sessionId]: { workspaceId, digests: merged, prompts: (previous?.prompts ?? 0) + 1, updatedAt: new Date().toISOString() } }; + writeJsonFile(file, Object.fromEntries(Object.entries(next).slice(-MAX_DELIVERY_SESSIONS))); + } catch { /* A lost record only means a checkpoint is sent again. */ } +}; + +/** Compaction dropped what the session held: forget its deliveries (one session, or every session in a workspace). */ +export const resetSessionDelivery = (runtimeHome: string, host: string, target: { sessionId?: string | null; workspaceId?: string | null }): void => { + try { + const file = deliveryFile(runtimeHome, host), records = readDeliveries(file); + const kept = Object.entries(records).filter(([session, record]) => + !(target.sessionId && session === target.sessionId) && !(target.workspaceId && record.workspaceId === target.workspaceId)); + if (kept.length !== Object.keys(records).length) writeJsonFile(file, Object.fromEntries(kept)); + } catch { /* A failed reset can only withhold a repeat; the redelivery interval bounds that. */ } +}; diff --git a/src/runtime/host-adapter-base.ts b/src/runtime/host-adapter-base.ts index 6d5323f..8ab6053 100644 --- a/src/runtime/host-adapter-base.ts +++ b/src/runtime/host-adapter-base.ts @@ -5,7 +5,8 @@ export { filterHotMemorySnapshotForWorkspace } from "./workspace-memory"; import { existsSync } from "fs"; import { nowIso, renderInjectedPrompt, shellQuote } from "./adapter-utils"; import path from "path"; -import { HOT_CONTEXT_LIMIT, HOT_FULL_RENDER_LIMIT, renderHotCheckpoints, selectHotCheckpoints } from "./hot-continuity"; +import { HOT_CONTEXT_LIMIT, HOT_FULL_RENDER_LIMIT, hotCheckpointDigest, renderHotCheckpointPointer, renderHotCheckpoints, selectHotCheckpoints, type SelectedHotCheckpoint } from "./hot-continuity"; +import { readSessionDelivery, recordSessionDelivery } from "./hook-session-context"; import { CHECKPOINT_PAGE_CHARS, inlineCheckpointPages, paginateCheckpoint, saveCheckpointPages } from "./checkpoint-pages"; import { resolveRuntimeHome } from "./local-runtime"; import { evidenceFromToolCall, readTaskEvidence, taskEvidenceCaptureEnabled, type TaskEvidence } from "./task-evidence"; @@ -235,18 +236,58 @@ export abstract class HostRuntimeAdapterBase { * Whenever more is saved than is shown, the pages are stored and the text ends * with the exact command that prints them, so an agent never has to stop or * guess because a note was cut off. + * + * On Claude Code and Codex, a checkpoint the session already received is not + * sent again (compaction or a changed checkpoint sends it again), and after + * the first prompt a checkpoint that shares no terms with the prompt is + * reduced to a one-line pointer. `refresh` is true when the session holds no + * earlier delivery: its first prompt, or the first after compaction. */ - protected renderHotContext(snapshot: unknown, prompt: string, workspaceId: string, sessionStart: boolean): string | undefined { + protected renderHotContext(snapshot: unknown, prompt: string, workspaceId: string, sessionStart: boolean, sessionId?: string): { text: string | undefined; refresh: boolean } { + const home = this.config.runtimeHome; + const host = this.identity.runtimeId as string; + const tracked = Boolean(home && sessionId && (host === "claude-code" || host === "codex")); + const delivery = tracked ? readSessionDelivery(home!, host, sessionId!) : null; + const refresh = sessionStart || !delivery || delivery.refresh; + const record = (digests: string[]): void => { + if (tracked) recordSessionDelivery(home!, host, workspaceId, sessionId!, digests, refresh); + }; const command = this.bridgeCommand(); - if (!command || !this.config.runtimeHome) return undefined; const selected = selectHotCheckpoints(snapshot, prompt, this.config.workspaceOnly ? workspaceId : undefined); - if (!selected.length) return undefined; + if (!tracked) { + if (!command || !home || !selected.length) return { text: undefined, refresh }; + return { text: this.renderSelectedHotContext(selected, workspaceId, sessionStart, command, home), refresh }; + } + const delivered = refresh ? new Set() : delivery!.delivered; + const items = selected.map(entry => { + const digest = hotCheckpointDigest(entry); + const mode: "full" | "pointer" = !sessionStart && entry.match === "unrelated" ? "pointer" : "full"; + return { entry, mode, full: `${digest}:full`, pointer: `${digest}:pointer` }; + }).filter(item => !delivered.has(item.full) && !(item.mode === "pointer" && delivered.has(item.pointer))); + record(items.map(item => item.mode === "full" ? item.full : item.pointer)); + if (!items.length) return { text: selected.length ? "" : undefined, refresh }; + const full = items.filter(item => item.mode === "full").map(item => item.entry); + const pointers = items.filter(item => item.mode === "pointer").map(item => { + let read: string | null = null; + if (command) { + const pages = paginateCheckpoint(renderHotCheckpoints([item.entry], HOT_FULL_RENDER_LIMIT)); + read = `${command.replace("%PAGE%", " 1")} --key ${saveCheckpointPages(home!, host, workspaceId, pages)}`; + } + return renderHotCheckpointPointer(item.entry, read); + }); + const body = !full.length ? "" : command + ? this.renderSelectedHotContext(full, workspaceId, sessionStart, command, home!) + : renderHotCheckpoints(full, HOT_CONTEXT_LIMIT); + return { text: [body, ...pointers].filter(Boolean).join("\n"), refresh }; + } + + private renderSelectedHotContext(selected: SelectedHotCheckpoint[], workspaceId: string, sessionStart: boolean, command: string, home: string): string { const full = renderHotCheckpoints(selected, HOT_FULL_RENDER_LIMIT); const inline = sessionStart ? inlineCheckpointPages(this.identity.runtimeId) : 0; if (full.length <= (sessionStart ? CHECKPOINT_PAGE_CHARS * inline : HOT_CONTEXT_LIMIT)) return full; const pages = paginateCheckpoint(full); if (sessionStart && pages.length <= inline) return full; - const key = saveCheckpointPages(this.config.runtimeHome, this.identity.runtimeId, workspaceId, pages); + const key = saveCheckpointPages(home, this.identity.runtimeId, workspaceId, pages); const read = (page: number): string => `${command.replace("%PAGE%", ` ${page}`)} --key ${key}`; const shown = inline === 1 ? "page 1" : `pages 1 to ${inline}`; const remaining = pages.length - inline === 1 ? `page ${pages.length}` : `pages ${inline + 1} to ${pages.length}, one page number per call`; @@ -370,6 +411,9 @@ export abstract class HostRuntimeAdapterBase { }); // The daemon supplies verified archive excerpts through a dedicated field. // The hosted pack's context text, metadata and diagnostics stay outside the prompt. + const hot = input.prompt.trim() + ? this.renderHotContext(preTurnHotMemory, input.prompt, workspaceId, input.sessionStart === true, input.sessionId) + : { text: undefined, refresh: true }; let contextText = input.prompt.trim() ? renderRuntimeStartupContext({ runtime: this.identity.runtimeId, profileName, @@ -387,7 +431,9 @@ export abstract class HostRuntimeAdapterBase { freshness, hotMemorySnapshot: preTurnHotMemory, goal: input.prompt, - hotContextText: this.renderHotContext(preTurnHotMemory, input.prompt, workspaceId, input.sessionStart === true), + hotContextText: hot.text, + // The capture contract is long; a session that already received it keeps it until compaction. + captureGuidance: hot.refresh, }) : ""; if (input.prompt.trim()) contextText = appendVerifiedArchiveContext(contextText, contextPack); const supportsSubagents = this.identity.runtimeId === "codex" || this.identity.runtimeId === "claude-code"; diff --git a/src/runtime/hot-continuity.ts b/src/runtime/hot-continuity.ts index 3a61b50..bed7f6f 100644 --- a/src/runtime/hot-continuity.ts +++ b/src/runtime/hot-continuity.ts @@ -1,3 +1,4 @@ +import { createHash } from "crypto"; import { compactContinuitySummary } from "./summary-compaction"; import { normalizeTaskEvidence, preferFileSources, renderTaskEvidence, taskEvidenceChars, type TaskEvidence } from "./task-evidence"; import { IMPORTED_HANDOFF_TURN_PREFIX } from "./handoff-import"; @@ -42,8 +43,21 @@ export type HotContinuityCheckpoint = { export type SelectedHotCheckpoint = HotContinuityCheckpoint & { // A read-time view over retained checkpoints, not a second persisted ledger. earlierFindings?: Array<{ runtime: string; occurredAt: string; summary: string }>; + /** + * Why this entry was selected. "unrelated" is the top-ranked checkpoint when + * the prompt shares no terms with any checkpoint: a session's first prompt + * still gets it in full, a later prompt only a pointer to it. + */ + match?: "related" | "unrelated" | "saved" | "imported"; }; +/** Content identity of a selected checkpoint: equal digests render the same text. */ +export const hotCheckpointDigest = (entry: SelectedHotCheckpoint): string => + createHash("sha256").update(JSON.stringify([ + entry.workspaceId, entry.runtime, entry.origin ?? null, entry.goal, entry.summary, entry.occurredAt, + entry.evidence?.sources.map(source => source.sha256) ?? [], entry.earlierFindings?.map(f => [f.occurredAt, f.summary]) ?? [], + ])).digest("hex").slice(0, 16); + const record = (value: unknown): Record | null => { if (typeof value === "string") { try { return record(JSON.parse(value)); } catch { return null; } @@ -241,14 +255,14 @@ export const selectHotCheckpoints = ( }).sort((a, b) => b.score - a.score || a.index - b.index); const first = scored[0]; if (!first) return []; - const chosen = scored.filter((entry, index) => index === 0 || (entry.score > 0 && entry.score >= first.score * 0.6)) - .slice(0, 2).map(({ entry }) => entry); + const chosen: SelectedHotCheckpoint[] = scored.filter((entry, index) => index === 0 || (entry.score > 0 && entry.score >= first.score * 0.6)) + .slice(0, 2).map(({ entry, score }) => ({ ...entry, match: score > 0 ? "related" as const : "unrelated" as const })); // An explicit save is a deliberate handoff. Boilerplate shared between an // unrelated later request and the current one must not rank it out, so the // most recent save in this workspace is always included. One only: every // extra entry divides the small per-prompt budget further. - const saved = chosen.some(entry => entry.origin === "remember") ? [] : unique.filter(entry => entry.origin === "remember") - .sort((a, b) => timestamp(b.occurredAt) - timestamp(a.occurredAt)).slice(0, 1); + const saved: SelectedHotCheckpoint[] = chosen.some(entry => entry.origin === "remember") ? [] : unique.filter(entry => entry.origin === "remember") + .sort((a, b) => timestamp(b.occurredAt) - timestamp(a.occurredAt)).slice(0, 1).map(entry => ({ ...entry, match: "saved" as const })); // A handoff just imported here is what the next session came to continue. Include the latest // import, first, until the workspace has recorded a few newer checkpoints (one turn finishing // in the session that ran the import must not end it), even when the prompt shares no words with @@ -260,7 +274,22 @@ export const selectHotCheckpoints = ( const newerWork = latestImport ? unique.filter(entry => entry !== latestImport && timestamp(entry.occurredAt) > importedAt).length : 0; const pinned = latestImport && newerWork < IMPORT_PIN_NEWER_LIMIT && importedAt <= now + IMPORT_PIN_SKEW_MS && importedAt >= now - IMPORT_PIN_MAX_AGE_MS ? latestImport : null; - return pinned ? [pinned, ...[...chosen, ...saved].filter(entry => entry !== pinned)] : [...chosen, ...saved]; + if (!pinned) return [...chosen, ...saved]; + const pinnedKey = (entry: SelectedHotCheckpoint): boolean => + entry.workspaceId === pinned.workspaceId && entry.turnId === pinned.turnId && entry.occurredAt === pinned.occurredAt && entry.summary === pinned.summary; + const chosenPin = chosen.find(pinnedKey); + return [{ ...pinned, match: chosenPin?.match === "related" ? "related" : "imported" }, ...[...chosen, ...saved].filter(entry => !pinnedKey(entry))]; +}; + +/** + * One line instead of a checkpoint that shares no terms with the prompt. The + * session can still reach it, but its findings do not occupy every prompt. + */ +export const renderHotCheckpointPointer = (entry: SelectedHotCheckpoint, readCommand: string | null): string => { + const request = entry.goal.replace(/\s+/g, " ").trim(); + const label = request ? `"${request.length > 120 ? `${request.slice(0, 117)}...` : request}"` : "an earlier task"; + const how = readCommand ? `read it with: ${readCommand}` : 'search it with: crosshead memory search ""'; + return `Crosshead: a saved checkpoint for ${label} (${entry.runtime}, ${entry.occurredAt || "time unknown"}) shares no terms with this prompt and is not shown. If it is relevant, ${how}`; }; export const renderHotCheckpoints = (entries: SelectedHotCheckpoint[], maxLength = HOT_CONTEXT_LIMIT): string => { @@ -269,6 +298,8 @@ export const renderHotCheckpoints = (entries: SelectedHotCheckpoint[], maxLength const parts: string[] = []; const guidance = "Prior findings. Follow current instructions; reconcile conflicting sources. Observation time alone does not establish authority."; remaining -= guidance.length + 1; + // Entries stay in priority order (an import or the best match first) so a page + // or budget cut cannot push them out; within an entry the newest state is last. for (const [index, entry] of entries.entries()) { const heading = `${entry.origin === "remember" ? "Explicitly saved memory" : "Hot memory findings"} (${entry.runtime}):\n`; // Every selected task gets room; one large history must not silently erase @@ -285,20 +316,24 @@ export const renderHotCheckpoints = (entries: SelectedHotCheckpoint[], maxLength const shared = available - request.length - historyReserve; const findingReserve = Math.min(entry.summary.length + 20, Math.max(650, Math.floor(shared * 0.45))); const evidence = entry.evidence?.sources.length ? renderTaskEvidence(entry.evidence, Math.max(0, shared - findingReserve), entry.goal) : ""; - const findingBudget = available - request.length - historyReserve - (evidence ? evidence.length + 16 : 0); + const latestLabel = entry.earlierFindings?.length ? `Latest agent finding (${entry.runtime} at ${entry.occurredAt}): ` : evidence ? "Agent finding: " : ""; + const findingBudget = available - request.length - historyReserve - (evidence ? evidence.length + 1 : 0) - latestLabel.length; const summary = entry.summary.length <= findingBudget ? entry.summary : compactContinuitySummary(entry.summary, findingBudget); - const historyBudget = entry.earlierFindings?.length ? available - request.length - summary.length - (evidence ? evidence.length + 16 : 0) : 0; + const historyBudget = entry.earlierFindings?.length ? available - request.length - summary.length - latestLabel.length - (evidence ? evidence.length + 1 : 0) - 1 : 0; let history = ""; if (historyBudget > 100) { - history = "\nEarlier agent findings (may be superseded; bounded excerpts):"; - for (const prior of entry.earlierFindings ?? []) { + // Oldest first, then the latest finding: the newest state is read last. + history = `Earlier agent findings (superseded by the latest finding at ${entry.occurredAt || "a later time"} where they conflict; bounded excerpts):`; + for (const prior of (entry.earlierFindings ?? []).slice().reverse()) { const prefix = `\n${prior.runtime} at ${prior.occurredAt}: `; const space = historyBudget - history.length - prefix.length - 24; - if (space < 60) break; + if (space < 60) continue; history += prefix + prior.summary.slice(0, space) + (prior.summary.length > space ? " [finding incomplete]" : ""); } + history += "\n"; } - const finding = `${request}${evidence ? `${evidence}\nAgent finding: ${summary}` : summary}${history}`.slice(0, available); + const latest = history || evidence ? latestLabel || "Agent finding: " : ""; + const finding = `${request}${evidence ? `${evidence}\n` : ""}${history}${latest}${summary}`.slice(0, available); parts.push(`${heading}${finding}`); remaining -= heading.length + finding.length + 1; } diff --git a/src/runtime/startup-context.ts b/src/runtime/startup-context.ts index e25a96d..77428c9 100644 --- a/src/runtime/startup-context.ts +++ b/src/runtime/startup-context.ts @@ -35,6 +35,8 @@ type RuntimeStartupContextInput = { injectedContext: string; /** Hot checkpoint text already rendered by the host adapter (paged at session start). */ hotContextText?: string; + /** Include the capture contract. False once the session has it (after its first prompt, until compaction). */ + captureGuidance?: boolean; freshness?: RuntimeStartupFreshness | null; hotMemorySnapshot?: Record | null; goal?: string | null; @@ -682,7 +684,7 @@ export const renderRuntimeStartupContext = (input: RuntimeStartupContextInput): // A fresh store still needs a capture contract. Otherwise the agent may invent // a repository memory file or omit facts that are absent from its final answer. // Native hooks capture findings plus bounded observed workspace reads. - const captureGuidance = input.runtime !== "pi" && (input.mode === "auto" || input.mode === "assist") + const captureGuidance = input.runtime !== "pi" && input.captureGuidance !== false && (input.mode === "auto" || input.mode === "assist") ? `Crosshead hooks automatically capture your final response${input.sourceExcerpts ? " and bounded workspace file-read evidence" : ""} as a continuity checkpoint. When handing off unfinished work, include the exact discovered requirements: input/output types and units, boundary rules, decisions and rejected alternatives, verification, and next steps. Distinguish observed facts from assumptions. No manual hook invocation or repository memory file is needed. Continuity does not authorize file changes; obey the user's read-only and other task constraints.` : null; const manifest = input.manifest; @@ -739,7 +741,9 @@ export const renderRuntimeStartupContext = (input: RuntimeStartupContextInput): formatHealthLine(input.status), formatLifecycleLine(input.actions, manifest), manifest ? formatLayerLine("Hot memory", manifest.hotMemory) : hasHotMemoryFallback - ? input.hotContextText || renderHotCheckpoints(selectHotCheckpoints(input.hotMemorySnapshot, input.goal ?? null, input.workspaceId)) || formatFreeHotMemorySnapshotLine(input.hotMemorySnapshot) + // An empty string from the adapter means the session already holds these checkpoints. + ? input.hotContextText !== undefined ? input.hotContextText || null + : renderHotCheckpoints(selectHotCheckpoints(input.hotMemorySnapshot, input.goal ?? null, input.workspaceId)) || formatFreeHotMemorySnapshotLine(input.hotMemorySnapshot) : null, formatWarmLine(manifest), manifest && (manifest.layeredContext.available > 0 || manifest.layeredContext.injected > 0) diff --git a/tests/runtime/hot-continuity.test.ts b/tests/runtime/hot-continuity.test.ts index c1c4139..cd10a9e 100644 --- a/tests/runtime/hot-continuity.test.ts +++ b/tests/runtime/hot-continuity.test.ts @@ -71,8 +71,10 @@ describe("hot continuity findings", () => { expect(selected[0]?.summary).toBe(corrected.summary); const delivered = renderHotCheckpoints(selected); expect(delivered).toContain("43 items, replacing 37"); - expect(delivered).toContain("Earlier agent findings (may be superseded"); + expect(delivered).toContain("Earlier agent findings (superseded by the latest finding at 2026-10-17T02:00:00.000Z"); expect(delivered).toContain("37 items"); + // The newest state is read last, after the superseded history. + expect(delivered.indexOf("43 items, replacing 37")).toBeGreaterThan(delivered.indexOf("37 items.")); }); it("preserves sources and prior decisions across host updates, duplicated scopes and source conflicts", () => { diff --git a/tests/runtime/hot-delivery.test.ts b/tests/runtime/hot-delivery.test.ts new file mode 100644 index 0000000..a46ec3e --- /dev/null +++ b/tests/runtime/hot-delivery.test.ts @@ -0,0 +1,137 @@ +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { afterEach, describe, expect, it } from "vitest"; + +import { HostRuntimeAdapterBase, type HostAdapterIdentity } from "../../src/runtime/host-adapter-base"; +import { releaseSessionStartContext, resetSessionDelivery, HOT_REDELIVERY_PROMPTS } from "../../src/runtime/hook-session-context"; +import { renderHotCheckpoints, selectHotCheckpoints, type HotContinuityCheckpoint } from "../../src/runtime/hot-continuity"; +import type { LocalRuntimeClient } from "../../src/runtime/local-client"; + +const workspaceId = "repo:/fixture"; +const checkpoint = (overrides: Partial = {}): HotContinuityCheckpoint => ({ + runtime: "codex", workspaceId, sessionId: "earlier", turnId: "inspect", + goal: "Investigate the parcel batching contract", summary: "Parcel batches contain at most 37 items.", + occurredAt: "2026-10-17T01:00:00.000Z", ...overrides, +}); +const snapshotOf = (entries: HotContinuityCheckpoint[]) => ({ scope: "all", scopes: [{ + scope: "codex", content: JSON.stringify({ workspaceId, continuityCheckpoints: entries }), +}] }); + +class Adapter extends HostRuntimeAdapterBase { + protected readonly identity: HostAdapterIdentity; + protected readonly config; + constructor(protected readonly client: LocalRuntimeClient, runtimeHome: string, runtimeId: "codex" | "claude-code" | "pi" = "codex") { + super(); + this.identity = { runtimeId, wrapperVersionFallback: "test", requestLabel: "Codex" } as HostAdapterIdentity; + this.config = { profileName: "default", hostHome: "/host", adapterVersion: "test", runtimeHome }; + } + protected async attachWorkspace(): Promise {} +} + +const homes: string[] = []; +afterEach(() => { for (const home of homes.splice(0)) rmSync(home, { recursive: true, force: true }); }); + +const harness = (entries: HotContinuityCheckpoint[], runtimeId: "codex" | "claude-code" | "pi" = "codex", wrapper = true) => { + const home = mkdtempSync(path.join(tmpdir(), "crosshead-hot-delivery-")); + homes.push(home); + if (wrapper) { + mkdirSync(path.join(home, "bin"), { recursive: true }); + for (const name of ["crosshead-codex", "crosshead-claude-code"]) writeFileSync(path.join(home, "bin", name), "#!/bin/sh\n", { mode: 0o755 }); + } + let snapshot = snapshotOf(entries); + const client = { + readHotMemory: async () => snapshot, + emitEvent: async () => ({ mode: "assist", warnings: [], contextPack: null }), + status: async () => ({ profile: { memoryMode: "assist" } }), + } as unknown as LocalRuntimeClient; + const adapter = new Adapter(client, home, runtimeId); + const prompt = async (text: string, options: { sessionStart?: boolean; sessionId?: string } = {}) => + (await adapter.prepareTurn({ workspaceRoot: "/fixture", workspaceId, sessionId: options.sessionId ?? "s1", turnId: `t-${Math.random()}`, prompt: text, sessionStart: options.sessionStart ?? false })).contextText; + return { home, prompt, setEntries: (next: HotContinuityCheckpoint[]) => { snapshot = snapshotOf(next); } }; +}; + +describe("hot checkpoint delivery per session", () => { + it("sends the full checkpoint at session start even when the prompt shares no terms", async () => { + const h = harness([checkpoint()]); + const text = await h.prompt("continue", { sessionStart: true }); + expect(text).toContain("Parcel batches contain at most 37 items."); + expect(text).toContain("Crosshead hooks automatically capture your final response"); + }); + + it("does not resend a checkpoint the session already received, and omits the capture contract after the first prompt", async () => { + const h = harness([checkpoint()]); + expect(await h.prompt("Resume parcel batching", { sessionStart: true })).toContain("37 items"); + const second = await h.prompt("Resume parcel batching"); + expect(second).not.toContain("37 items"); + expect(second).not.toContain("Crosshead hooks automatically capture your final response"); + expect(second).not.toContain("saved checkpoint for"); + }); + + it("reduces an unrelated checkpoint to a one-line pointer after the first prompt, once", async () => { + const h = harness([checkpoint()]); + const first = await h.prompt("Rename the logging helper in utils", { sessionId: "s2" }); + expect(first).not.toContain("37 items"); + const pointer = first.split("\n").filter(line => line.includes("saved checkpoint for")); + expect(pointer).toHaveLength(1); + expect(pointer[0]).toContain('"Investigate the parcel batching contract"'); + expect(pointer[0]).toContain("checkpoint-page 1"); + expect(pointer[0]).toContain("--key "); + expect(first).not.toContain("excerpt only"); + expect(await h.prompt("Rename the logging helper in utils", { sessionId: "s2" })).not.toContain("saved checkpoint for"); + // Once the prompt relates to it, the session gets the checkpoint itself. + expect(await h.prompt("What did the parcel batching investigation find?", { sessionId: "s2" })).toContain("37 items"); + }); + + it("resends after compaction, after a checkpoint change and after the redelivery interval", async () => { + const h = harness([checkpoint()]); + await h.prompt("Resume parcel batching", { sessionStart: true }); + resetSessionDelivery(h.home, "codex", { sessionId: "s1" }); + const afterCompaction = await h.prompt("Resume parcel batching"); + expect(afterCompaction).toContain("37 items"); + expect(afterCompaction).toContain("Crosshead hooks automatically capture your final response"); + releaseSessionStartContext(h.home, "codex", workspaceId); + expect(await h.prompt("Resume parcel batching")).toContain("37 items"); + h.setEntries([checkpoint({ summary: "Parcel batches contain at most 43 items.", occurredAt: "2026-10-17T03:00:00.000Z", turnId: "later" })]); + expect(await h.prompt("Resume parcel batching")).toContain("43 items"); + const repeats: boolean[] = []; + for (let index = 0; index < HOT_REDELIVERY_PROMPTS; index += 1) repeats.push((await h.prompt("Resume parcel batching")).includes("43 items")); + // Withheld while the session holds it, then sent exactly once when the interval passes. + expect(repeats.filter(Boolean)).toHaveLength(1); + expect(repeats[0]).toBe(false); + }); + + it("delivers an explicit save once even when unrelated to the prompt", async () => { + const save = checkpoint({ origin: "remember", goal: "", summary: "Remember: staging deploys need the blue key.", turnId: "remember-1", occurredAt: "2026-10-17T02:00:00.000Z" }); + const h = harness([checkpoint(), save]); + const first = await h.prompt("Resume parcel batching", { sessionStart: true }); + expect(first).toContain("staging deploys need the blue key"); + expect(await h.prompt("Resume parcel batching")).not.toContain("blue key"); + }); + + it("keeps sessions independent", async () => { + const h = harness([checkpoint()]); + await h.prompt("Resume parcel batching", { sessionStart: true, sessionId: "a" }); + expect(await h.prompt("Resume parcel batching", { sessionStart: true, sessionId: "b" })).toContain("37 items"); + }); + + it("works without a host wrapper and leaves other hosts unchanged", async () => { + const plain = harness([checkpoint()], "codex", false); + expect(await plain.prompt("Resume parcel batching", { sessionStart: true })).toContain("37 items"); + expect(await plain.prompt("Resume parcel batching")).not.toContain("37 items"); + const pointer = await plain.prompt("Rename the logging helper", { sessionId: "s3" }); + expect(pointer).toContain('crosshead memory search ""'); + const pi = harness([checkpoint()], "pi"); + expect(await pi.prompt("Resume parcel batching")).toContain("37 items"); + expect(await pi.prompt("Resume parcel batching")).toContain("37 items"); + }); +}); + +describe("selection labels", () => { + it("marks a zero-score top entry unrelated and a matching one related", () => { + const snapshot = snapshotOf([checkpoint()]); + expect(selectHotCheckpoints(snapshot, "Rename the logging helper")[0]?.match).toBe("unrelated"); + expect(selectHotCheckpoints(snapshot, "Resume parcel batching")[0]?.match).toBe("related"); + expect(renderHotCheckpoints(selectHotCheckpoints(snapshot, "x"))).toContain("37 items"); + }); +}); From 27b171afb1a64aefa0fb73cefec2d209825eb39c Mon Sep 17 00:00:00 2001 From: Josh Winters Date: Mon, 23 Nov 2026 18:17:23 -0500 Subject: [PATCH 2/5] Checkpoint wording: keep open items, tie passed checks to a tree, state precedence as conditions - Summary compaction now ranks sentences about unresolved, blocked or remaining work as important, so they survive when a finding is cut. - The capture contract asks that a check reported as passed name the command, working directory, commit and dirty state, and that a saved status (tests, CI, review, mergeability) be checked again before use. - The prior-findings guidance is written as one conditional sentence per conflict case: current message, what the agent sees now, and other saved findings. The separate 'Unresolved:' field waits on the task 161 headroom pilot. Task Master 165 (items 1, 3, 4). --- src/runtime/hot-continuity.ts | 3 ++- src/runtime/startup-context.ts | 2 +- src/runtime/summary-compaction.ts | 9 +++++++++ tests/runtime/codex-hook-summary.test.ts | 17 +++++++++++++++++ tests/runtime/hot-continuity.test.ts | 3 +++ tests/runtime/startup-context-capture.test.ts | 8 ++++++++ 6 files changed, 40 insertions(+), 2 deletions(-) diff --git a/src/runtime/hot-continuity.ts b/src/runtime/hot-continuity.ts index bed7f6f..4604c78 100644 --- a/src/runtime/hot-continuity.ts +++ b/src/runtime/hot-continuity.ts @@ -296,7 +296,8 @@ export const renderHotCheckpoints = (entries: SelectedHotCheckpoint[], maxLength if (entries.length === 0) return ""; let remaining = maxLength; const parts: string[] = []; - const guidance = "Prior findings. Follow current instructions; reconcile conflicting sources. Observation time alone does not establish authority."; + // Conditional sentences, one case each: they are easier to apply than a ranking rule. + const guidance = "Prior findings, observed earlier; not current truth. If one conflicts with the user's current message, follow the message. If one conflicts with a file or command output you see now, trust what you see now and say so. If saved findings conflict with each other, the later time does not settle it; check the source."; remaining -= guidance.length + 1; // Entries stay in priority order (an import or the best match first) so a page // or budget cut cannot push them out; within an entry the newest state is last. diff --git a/src/runtime/startup-context.ts b/src/runtime/startup-context.ts index 77428c9..3a05d48 100644 --- a/src/runtime/startup-context.ts +++ b/src/runtime/startup-context.ts @@ -685,7 +685,7 @@ export const renderRuntimeStartupContext = (input: RuntimeStartupContextInput): // a repository memory file or omit facts that are absent from its final answer. // Native hooks capture findings plus bounded observed workspace reads. const captureGuidance = input.runtime !== "pi" && input.captureGuidance !== false && (input.mode === "auto" || input.mode === "assist") - ? `Crosshead hooks automatically capture your final response${input.sourceExcerpts ? " and bounded workspace file-read evidence" : ""} as a continuity checkpoint. When handing off unfinished work, include the exact discovered requirements: input/output types and units, boundary rules, decisions and rejected alternatives, verification, and next steps. Distinguish observed facts from assumptions. No manual hook invocation or repository memory file is needed. Continuity does not authorize file changes; obey the user's read-only and other task constraints.` + ? `Crosshead hooks automatically capture your final response${input.sourceExcerpts ? " and bounded workspace file-read evidence" : ""} as a continuity checkpoint. When handing off unfinished work, include the exact discovered requirements: input/output types and units, boundary rules, decisions and rejected alternatives, verification, and next steps. Distinguish observed facts from assumptions. For any check you report as passed, give the command, working directory, commit and whether the tree had uncommitted changes. Before acting on a saved status (tests, CI, review, mergeability), check it again live. No manual hook invocation or repository memory file is needed. Continuity does not authorize file changes; obey the user's read-only and other task constraints.` : null; const manifest = input.manifest; const trimmedContext = input.injectedContext.trim(); diff --git a/src/runtime/summary-compaction.ts b/src/runtime/summary-compaction.ts index 5c82572..3de3c5d 100644 --- a/src/runtime/summary-compaction.ts +++ b/src/runtime/summary-compaction.ts @@ -29,6 +29,15 @@ const IMPORTANT_SUMMARY_PATTERNS = [ /\bhidden\b/i, /\berror\b/i, /\bwarning\b/i, + // What is still open is what the next session needs most. + /\bunresolved\b/i, + /\bblocked\b/i, + /\bblocker\b/i, + /\bremaining\b/i, + /\bremains\b/i, + /\bnot (?:yet )?(?:done|finished|verified|fixed)\b/i, + /\bstill (?:open|failing|pending)\b/i, + /\bTODO\b/, /`[^`]+`/, ]; diff --git a/tests/runtime/codex-hook-summary.test.ts b/tests/runtime/codex-hook-summary.test.ts index f344626..ee532d4 100644 --- a/tests/runtime/codex-hook-summary.test.ts +++ b/tests/runtime/codex-hook-summary.test.ts @@ -42,4 +42,21 @@ describe("Codex hook turn summary compaction", () => { expect(compacted).toContain("Public API constraint"); expect(compacted).not.toContain(tempPath); }); + + it("keeps what is still unresolved or blocked when compacting", () => { + const summary = [ + "I read the parser and the three fixtures in detail and summarised each of them for the record.", + "The tokenizer handles quoted strings and escapes the same way in every fixture I looked at today.", + "Formatting of the output table was adjusted to align the columns more neatly than before.", + "Unresolved: the negative-offset case still returns the wrong row.", + "Deploy is blocked on the staging credentials, which only the operator can rotate.", + "Remaining work is the migration for the archived rows.", + "Overall the session went smoothly and the code is in a reasonable state now.", + ].join(" "); + const compacted = compactContinuitySummary(summary, 260); + expect(compacted.length).toBeLessThanOrEqual(260); + expect(compacted).toContain("negative-offset case"); + expect(compacted).toContain("blocked on the staging credentials"); + expect(compacted).toContain("migration for the archived rows"); + }); }); diff --git a/tests/runtime/hot-continuity.test.ts b/tests/runtime/hot-continuity.test.ts index cd10a9e..ad29819 100644 --- a/tests/runtime/hot-continuity.test.ts +++ b/tests/runtime/hot-continuity.test.ts @@ -75,6 +75,9 @@ describe("hot continuity findings", () => { expect(delivered).toContain("37 items"); // The newest state is read last, after the superseded history. expect(delivered.indexOf("43 items, replacing 37")).toBeGreaterThan(delivered.indexOf("37 items.")); + // The precedence rule is stated as conditions, one case each. + expect(delivered).toContain("If one conflicts with the user's current message, follow the message."); + expect(delivered).toContain("trust what you see now and say so"); }); it("preserves sources and prior decisions across host updates, duplicated scopes and source conflicts", () => { diff --git a/tests/runtime/startup-context-capture.test.ts b/tests/runtime/startup-context-capture.test.ts index 5bcb042..adf13cd 100644 --- a/tests/runtime/startup-context-capture.test.ts +++ b/tests/runtime/startup-context-capture.test.ts @@ -14,6 +14,14 @@ describe("native hook capture contract", () => { expect(context).toContain("Distinguish observed facts from assumptions"); expect(context).toContain("No manual hook invocation or repository memory file is needed"); expect(context).toContain("does not authorize file changes"); + // A saved "tests passed" is only useful with what was run, where and on which tree. + expect(context).toContain("give the command, working directory, commit and whether the tree had uncommitted changes"); + expect(context).toContain("check it again live"); + }); + + it("omits the capture contract once the session holds it", () => { + expect(renderRuntimeStartupContext({ ...empty, actions: [], warnings: [], runtime: "codex", mode: "assist", captureGuidance: false })) + .not.toContain("capture your final response"); }); it.each(["off", "manual"] as const)("does not promise automatic capture in %s mode", mode => { From 0d5a30359911823ef567edae06348a713865dfce Mon Sep 17 00:00:00 2001 From: Josh Winters Date: Mon, 23 Nov 2026 18:22:35 -0500 Subject: [PATCH 3/5] Hot delivery review fixes: full checkpoint when a session holds nothing, per-session files From an independent review: - Pointer vs full is decided by whether the session holds any delivery, not by the start claim, so a lost claim, an auto-compaction or a racing hook process still gets the full checkpoint. - One delivery file per host session. A compaction reset deletes it, so another session's concurrent write cannot restore the stale record. - A session's own checkpoints are not sent back to it until compaction. - The earlier-findings header is written only when a finding fits under it, so the latest finding is never cut to make room. - A pointer also names the search command, in case its page key has been evicted. --- src/runtime/hook-session-context.ts | 62 +++++++++++++++++----------- src/runtime/host-adapter-base.ts | 7 +++- src/runtime/hot-continuity.ts | 14 ++++--- tests/runtime/hot-continuity.test.ts | 11 +++++ tests/runtime/hot-delivery.test.ts | 43 +++++++++++++++++-- 5 files changed, 101 insertions(+), 36 deletions(-) diff --git a/src/runtime/hook-session-context.ts b/src/runtime/hook-session-context.ts index d80b601..ddc09d4 100644 --- a/src/runtime/hook-session-context.ts +++ b/src/runtime/hook-session-context.ts @@ -1,4 +1,5 @@ -import { existsSync, readFileSync } from "fs"; +import { createHash } from "crypto"; +import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync, statSync } from "fs"; import path from "path"; import { ensureRuntimeHomeLayout } from "./local-runtime"; import { writeJsonFile } from "./runtime-persistence"; @@ -44,9 +45,11 @@ export const releaseSessionStartContext = (runtimeHome: string, host: string, wo // Which hot checkpoints each host session has already been given. A checkpoint // the session already holds is not sent again on every prompt; compaction, a // session start or a changed checkpoint (a new digest) sends it again. -// Local state only: never synced, keyed by host session. -const deliveryFile = (runtimeHome: string, host: string): string => - path.join(ensureRuntimeHomeLayout(runtimeHome).state, `${host}-context-delivery.json`); +// Local state only, never synced: one file per host session, so a compaction +// reset (deleting the file) cannot be undone by another session's write. +const deliveryDir = (runtimeHome: string): string => path.join(ensureRuntimeHomeLayout(runtimeHome).state, "context-delivery"); +const deliveryFile = (runtimeHome: string, host: string, sessionId: string): string => + path.join(deliveryDir(runtimeHome), `${host}-${createHash("sha256").update(sessionId).digest("hex").slice(0, 24)}.json`); // A safety net for compactions no hook reports: after this many prompts the // session receives its checkpoints again. export const HOT_REDELIVERY_PROMPTS = 25; @@ -55,18 +58,13 @@ const MAX_DELIVERY_DIGESTS = 48; type DeliveryRecord = { workspaceId: string; digests: string[]; prompts: number; updatedAt: string }; -const readDeliveries = (file: string): Record => { - if (!existsSync(file)) return {}; +const readDelivery = (file: string): DeliveryRecord | null => { try { - const parsed = JSON.parse(readFileSync(file, "utf8")) as unknown; - if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return {}; - return Object.fromEntries(Object.entries(parsed as Record).flatMap(([key, value]) => { - const item = value as Partial | null; - return item && typeof item === "object" && Array.isArray(item.digests) && typeof item.prompts === "number" - ? [[key, { workspaceId: String(item.workspaceId ?? ""), digests: item.digests.filter((d): d is string => typeof d === "string"), prompts: item.prompts, updatedAt: String(item.updatedAt ?? "") }]] - : []; - })); - } catch { return {}; } + const item = JSON.parse(readFileSync(file, "utf8")) as Partial | null; + return item && typeof item === "object" && Array.isArray(item.digests) && typeof item.prompts === "number" + ? { workspaceId: String(item.workspaceId ?? ""), digests: item.digests.filter((d): d is string => typeof d === "string"), prompts: item.prompts, updatedAt: String(item.updatedAt ?? "") } + : null; + } catch { return null; } }; /** @@ -76,7 +74,7 @@ const readDeliveries = (file: string): Record => { */ export const readSessionDelivery = (runtimeHome: string, host: string, sessionId: string): { delivered: Set; refresh: boolean } => { try { - const record = readDeliveries(deliveryFile(runtimeHome, host))[sessionId]; + const record = readDelivery(deliveryFile(runtimeHome, host, sessionId)); if (!record || record.prompts >= HOT_REDELIVERY_PROMPTS) return { delivered: new Set(), refresh: true }; return { delivered: new Set(record.digests), refresh: false }; } catch { return { delivered: new Set(), refresh: true }; } @@ -85,21 +83,35 @@ export const readSessionDelivery = (runtimeHome: string, host: string, sessionId /** Record this prompt's deliveries. `refresh` starts a new record; otherwise digests are added. */ export const recordSessionDelivery = (runtimeHome: string, host: string, workspaceId: string, sessionId: string, digests: string[], refresh: boolean): void => { try { - const file = deliveryFile(runtimeHome, host), records = readDeliveries(file); - const previous = refresh ? undefined : records[sessionId]; - delete records[sessionId]; + const file = deliveryFile(runtimeHome, host, sessionId); + const previous = refresh ? null : readDelivery(file); const merged = [...new Set([...(previous?.digests ?? []), ...digests])].slice(-MAX_DELIVERY_DIGESTS); - const next = { ...records, [sessionId]: { workspaceId, digests: merged, prompts: (previous?.prompts ?? 0) + 1, updatedAt: new Date().toISOString() } }; - writeJsonFile(file, Object.fromEntries(Object.entries(next).slice(-MAX_DELIVERY_SESSIONS))); + mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 }); + writeJsonFile(file, { workspaceId, digests: merged, prompts: (previous?.prompts ?? 0) + 1, updatedAt: new Date().toISOString() }); + if (refresh) pruneDeliveries(runtimeHome); } catch { /* A lost record only means a checkpoint is sent again. */ } }; +const pruneDeliveries = (runtimeHome: string): void => { + const dir = deliveryDir(runtimeHome); + const files = readdirSync(dir).filter(name => name.endsWith(".json")).map(name => { + const file = path.join(dir, name); + try { return { file, at: statSync(file).mtimeMs }; } catch { return null; } + }).filter((entry): entry is { file: string; at: number } => entry !== null).sort((a, b) => b.at - a.at); + for (const stale of files.slice(MAX_DELIVERY_SESSIONS)) rmSync(stale.file, { force: true }); +}; + /** Compaction dropped what the session held: forget its deliveries (one session, or every session in a workspace). */ export const resetSessionDelivery = (runtimeHome: string, host: string, target: { sessionId?: string | null; workspaceId?: string | null }): void => { try { - const file = deliveryFile(runtimeHome, host), records = readDeliveries(file); - const kept = Object.entries(records).filter(([session, record]) => - !(target.sessionId && session === target.sessionId) && !(target.workspaceId && record.workspaceId === target.workspaceId)); - if (kept.length !== Object.keys(records).length) writeJsonFile(file, Object.fromEntries(kept)); + if (target.sessionId) rmSync(deliveryFile(runtimeHome, host, target.sessionId), { force: true }); + if (!target.workspaceId) return; + const dir = deliveryDir(runtimeHome); + if (!existsSync(dir)) return; + for (const name of readdirSync(dir)) { + if (!name.startsWith(`${host}-`) || !name.endsWith(".json")) continue; + const file = path.join(dir, name); + if (readDelivery(file)?.workspaceId === target.workspaceId) rmSync(file, { force: true }); + } } catch { /* A failed reset can only withhold a repeat; the redelivery interval bounds that. */ } }; diff --git a/src/runtime/host-adapter-base.ts b/src/runtime/host-adapter-base.ts index 8ab6053..1500d0d 100644 --- a/src/runtime/host-adapter-base.ts +++ b/src/runtime/host-adapter-base.ts @@ -261,9 +261,12 @@ export abstract class HostRuntimeAdapterBase { const delivered = refresh ? new Set() : delivery!.delivered; const items = selected.map(entry => { const digest = hotCheckpointDigest(entry); - const mode: "full" | "pointer" = !sessionStart && entry.match === "unrelated" ? "pointer" : "full"; + // A session that holds nothing yet (first prompt, after compaction) gets every selected checkpoint in full. + const mode: "full" | "pointer" = !refresh && entry.match === "unrelated" ? "pointer" : "full"; return { entry, mode, full: `${digest}:full`, pointer: `${digest}:pointer` }; - }).filter(item => !delivered.has(item.full) && !(item.mode === "pointer" && delivered.has(item.pointer))); + }).filter(item => !delivered.has(item.full) && !(item.mode === "pointer" && delivered.has(item.pointer)) && + // The session wrote its own checkpoints; until compaction it still holds that work. + (refresh || !item.entry.sessionId || item.entry.sessionId !== sessionId)); record(items.map(item => item.mode === "full" ? item.full : item.pointer)); if (!items.length) return { text: selected.length ? "" : undefined, refresh }; const full = items.filter(item => item.mode === "full").map(item => item.entry); diff --git a/src/runtime/hot-continuity.ts b/src/runtime/hot-continuity.ts index 4604c78..43ec3d9 100644 --- a/src/runtime/hot-continuity.ts +++ b/src/runtime/hot-continuity.ts @@ -288,7 +288,7 @@ export const selectHotCheckpoints = ( export const renderHotCheckpointPointer = (entry: SelectedHotCheckpoint, readCommand: string | null): string => { const request = entry.goal.replace(/\s+/g, " ").trim(); const label = request ? `"${request.length > 120 ? `${request.slice(0, 117)}...` : request}"` : "an earlier task"; - const how = readCommand ? `read it with: ${readCommand}` : 'search it with: crosshead memory search ""'; + const how = readCommand ? `read it with: ${readCommand} (or search: crosshead memory search "")` : 'search it with: crosshead memory search ""'; return `Crosshead: a saved checkpoint for ${label} (${entry.runtime}, ${entry.occurredAt || "time unknown"}) shares no terms with this prompt and is not shown. If it is relevant, ${how}`; }; @@ -322,16 +322,18 @@ export const renderHotCheckpoints = (entries: SelectedHotCheckpoint[], maxLength const summary = entry.summary.length <= findingBudget ? entry.summary : compactContinuitySummary(entry.summary, findingBudget); const historyBudget = entry.earlierFindings?.length ? available - request.length - summary.length - latestLabel.length - (evidence ? evidence.length + 1 : 0) - 1 : 0; let history = ""; - if (historyBudget > 100) { + const historyHeader = `Earlier agent findings (superseded by the latest finding at ${entry.occurredAt || "a later time"} where they conflict; bounded excerpts):`; + if (historyBudget - historyHeader.length - 1 > 100) { // Oldest first, then the latest finding: the newest state is read last. - history = `Earlier agent findings (superseded by the latest finding at ${entry.occurredAt || "a later time"} where they conflict; bounded excerpts):`; + let body = ""; for (const prior of (entry.earlierFindings ?? []).slice().reverse()) { const prefix = `\n${prior.runtime} at ${prior.occurredAt}: `; - const space = historyBudget - history.length - prefix.length - 24; + const space = historyBudget - historyHeader.length - 1 - body.length - prefix.length - 24; if (space < 60) continue; - history += prefix + prior.summary.slice(0, space) + (prior.summary.length > space ? " [finding incomplete]" : ""); + body += prefix + prior.summary.slice(0, space) + (prior.summary.length > space ? " [finding incomplete]" : ""); } - history += "\n"; + // A header with no finding under it is noise. + if (body) history = `${historyHeader}${body}\n`; } const latest = history || evidence ? latestLabel || "Agent finding: " : ""; const finding = `${request}${evidence ? `${evidence}\n` : ""}${history}${latest}${summary}`.slice(0, available); diff --git a/tests/runtime/hot-continuity.test.ts b/tests/runtime/hot-continuity.test.ts index ad29819..eadaa64 100644 --- a/tests/runtime/hot-continuity.test.ts +++ b/tests/runtime/hot-continuity.test.ts @@ -80,6 +80,17 @@ describe("hot continuity findings", () => { expect(delivered).toContain("trust what you see now and say so"); }); + it("keeps the latest finding whole when there is no room for earlier ones", () => { + const latest = "Correction: parcel batches hold 43 items. ".repeat(8).trim(); + for (const budget of [700, 800, 900, 1000, 1100]) { + const rendered = renderHotCheckpoints([{ ...checkpoint({ summary: latest, occurredAt: "2026-10-17T02:00:00.000Z" }), + earlierFindings: [{ runtime: "codex", occurredAt: "2026-10-17T01:00:00.000Z", summary: "Earlier observation. ".repeat(40) }] }], budget); + expect(rendered.length).toBeLessThanOrEqual(budget); + expect(rendered.endsWith("43 items.")).toBe(true); + if (rendered.includes("Earlier agent findings")) expect(rendered).toMatch(/Earlier agent findings[^\n]*\ncodex at /); + } + }); + it("preserves sources and prior decisions across host updates, duplicated scopes and source conflicts", () => { for (const source of ["codex", "claude-code"]) for (const receiver of ["codex", "claude-code"]) { for (const conflict of [false, true]) for (const reversed of [false, true]) { diff --git a/tests/runtime/hot-delivery.test.ts b/tests/runtime/hot-delivery.test.ts index a46ec3e..abcb2e4 100644 --- a/tests/runtime/hot-delivery.test.ts +++ b/tests/runtime/hot-delivery.test.ts @@ -69,7 +69,9 @@ describe("hot checkpoint delivery per session", () => { }); it("reduces an unrelated checkpoint to a one-line pointer after the first prompt, once", async () => { - const h = harness([checkpoint()]); + const h = harness([checkpoint(), checkpoint({ goal: "Tune the retry backoff", summary: "Backoff doubles from 200 ms.", turnId: "retry", occurredAt: "2026-10-17T00:30:00.000Z" })]); + // The session's first prompt receives what it selects in full. + await h.prompt("Tune the retry backoff", { sessionId: "s2", sessionStart: true }); const first = await h.prompt("Rename the logging helper in utils", { sessionId: "s2" }); expect(first).not.toContain("37 items"); const pointer = first.split("\n").filter(line => line.includes("saved checkpoint for")); @@ -119,14 +121,49 @@ describe("hot checkpoint delivery per session", () => { const plain = harness([checkpoint()], "codex", false); expect(await plain.prompt("Resume parcel batching", { sessionStart: true })).toContain("37 items"); expect(await plain.prompt("Resume parcel batching")).not.toContain("37 items"); - const pointer = await plain.prompt("Rename the logging helper", { sessionId: "s3" }); - expect(pointer).toContain('crosshead memory search ""'); + const two = harness([checkpoint(), checkpoint({ goal: "Tune the retry backoff", summary: "Backoff doubles from 200 ms.", turnId: "retry", occurredAt: "2026-10-17T00:30:00.000Z" })], "codex", false); + await two.prompt("Tune the retry backoff", { sessionId: "s3", sessionStart: true }); + const pointer = await two.prompt("Rename the logging helper", { sessionId: "s3" }); + expect(pointer).toContain("saved checkpoint for"); + expect(pointer).toContain('search it with: crosshead memory search ""'); const pi = harness([checkpoint()], "pi"); expect(await pi.prompt("Resume parcel batching")).toContain("37 items"); expect(await pi.prompt("Resume parcel batching")).toContain("37 items"); }); }); +describe("delivery edge cases from review", () => { + it("gives a session that holds nothing the full checkpoint even when the start claim was lost", async () => { + const h = harness([checkpoint()]); + // sessionStart false (failed claim, auto-compaction, racing hook) but no record yet. + const text = await h.prompt("continue", { sessionId: "fresh" }); + expect(text).toContain("37 items"); + expect(text).not.toContain("saved checkpoint for"); + await h.prompt("continue", { sessionId: "fresh" }); + resetSessionDelivery(h.home, "codex", { sessionId: "fresh" }); + expect(await h.prompt("continue", { sessionId: "fresh" })).toContain("37 items"); + }); + + it("does not let another session's write undo a compaction reset", async () => { + const h = harness([checkpoint()]); + await h.prompt("Resume parcel batching", { sessionStart: true, sessionId: "a" }); + await h.prompt("Resume parcel batching", { sessionStart: true, sessionId: "b" }); + resetSessionDelivery(h.home, "codex", { sessionId: "a" }); + await h.prompt("Resume parcel batching", { sessionId: "b" }); + expect(await h.prompt("Resume parcel batching", { sessionId: "a" })).toContain("37 items"); + }); + + it("does not send a session its own checkpoints until compaction", async () => { + const own = checkpoint({ sessionId: "s1", turnId: "own", summary: "Own finding: parcel weights are grams.", occurredAt: "2026-10-17T05:00:00.000Z" }); + const h = harness([own]); + await h.prompt("Resume parcel batching", { sessionStart: true }); + h.setEntries([{ ...own, summary: "Own finding: parcel weights are kilograms.", occurredAt: "2026-10-17T06:00:00.000Z" }]); + expect(await h.prompt("Resume parcel batching")).not.toContain("kilograms"); + resetSessionDelivery(h.home, "codex", { sessionId: "s1" }); + expect(await h.prompt("Resume parcel batching")).toContain("kilograms"); + }); +}); + describe("selection labels", () => { it("marks a zero-score top entry unrelated and a matching one related", () => { const snapshot = snapshotOf([checkpoint()]); From 6a413a0fe10864a2a62c3c689dc8440103ec595e Mon Sep 17 00:00:00 2001 From: Josh Winters Date: Mon, 23 Nov 2026 19:02:15 -0500 Subject: [PATCH 4/5] Reset checkpoint delivery on every session start; end-to-end hook test A started, resumed, cleared or forked session holds none of what a reused session id recorded, so SessionStart resets that session's delivery in both hooks (a false reset costs one repeat). New test drives the installed hook commands against a real daemon on both hosts: first prompt delivers, a repeat does not, automatic PreCompact and a later SessionStart deliver again. --- src/runtime/claude-code-hook.ts | 2 + src/runtime/codex-hook.ts | 2 + tests/runtime/hot-delivery-hooks.test.ts | 65 ++++++++++++++++++++++++ 3 files changed, 69 insertions(+) create mode 100644 tests/runtime/hot-delivery-hooks.test.ts diff --git a/src/runtime/claude-code-hook.ts b/src/runtime/claude-code-hook.ts index 6868a04..63d16de 100644 --- a/src/runtime/claude-code-hook.ts +++ b/src/runtime/claude-code-hook.ts @@ -520,6 +520,8 @@ export const runOnlyBotsClaudeCodeHookCli = async ( pickString(payload, ["session_id", "sessionId", "session.id", "conversation_id", "conversationId"]) ?? state.sessionId ?? buildSyntheticSessionId(); + // A (re)started session holds none of the checkpoints a reused session id recorded. + resetSessionDelivery(runtimeHome, "claude-code", { sessionId }); await adapter.sessionStarted({ workspaceRoot, workspaceId, diff --git a/src/runtime/codex-hook.ts b/src/runtime/codex-hook.ts index e231fb2..d69010c 100644 --- a/src/runtime/codex-hook.ts +++ b/src/runtime/codex-hook.ts @@ -496,6 +496,8 @@ export const runOnlyBotsCodexHookCli = async ( pickString(payload, ["session_id", "sessionId", "session.id", "conversation_id", "conversationId"]) ?? state.sessionId ?? buildSyntheticSessionId(); + // A (re)started session holds none of the checkpoints a reused session id recorded. + resetSessionDelivery(runtimeHome, "codex", { sessionId }); await adapter.sessionStarted({ workspaceRoot, workspaceId, diff --git a/tests/runtime/hot-delivery-hooks.test.ts b/tests/runtime/hot-delivery-hooks.test.ts new file mode 100644 index 0000000..e9b5153 --- /dev/null +++ b/tests/runtime/hot-delivery-hooks.test.ts @@ -0,0 +1,65 @@ +import { spawnSync } from "node:child_process"; +import { mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { afterEach, describe, expect, it } from "vitest"; +import { generateRuntimeIdentity, installRuntimeCore, setupRuntimeProfile, stopDetachedRuntimeDaemon } from "../../src/runtime/local-runtime"; +import { readDaemonOwnershipState } from "../../src/runtime/daemon-ownership"; +import { resolveRuntimePaths } from "../../src/runtime/runtime-persistence"; +import { writeLocalHotMemory } from "../../src/runtime/local-hot-memory"; +import { inspectWorkspaceHooks } from "../../src/runtime/workspace-hooks"; + +// End to end through the installed hook commands and a real daemon: a checkpoint +// reaches a session once, and again after compaction or a session start. +const repo = path.resolve(__dirname, "../.."); +const cliFile = path.join(repo, "dist/runtime/cli.js"); +const daemonFile = path.join(repo, "dist/runtime/daemon.js"); +const dirs: string[] = []; +afterEach(() => { for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true }); }); + +describe("hot checkpoint delivery through installed hooks", () => { + it("sends a checkpoint once per session and again after compaction or a session start, on both hosts", async () => { + const root = realpathSync(mkdtempSync(path.join(tmpdir(), "xhd-delivery-"))); dirs.push(root); + const home = path.join(root, "runtime"), project = path.join(root, "project"); + const codexHome = path.join(root, "codex"), claudeHome = path.join(root, "claude"); + for (const dir of [project, codexHome, claudeHome]) mkdirSync(dir, { recursive: true }); + const env = { PATH: process.env.PATH!, TMPDIR: tmpdir(), CODEX_HOME: codexHome, CLAUDE_CONFIG_DIR: claudeHome, CROSSHEAD_HOOK_AUTOSTART: "0" }; + const cli = (...args: string[]) => { + const result = spawnSync(process.execPath, [cliFile, ...args, "--home", home], { cwd: project, env, encoding: "utf8", timeout: 12000 }); + expect(result.status, result.stderr || result.stdout).toBe(0); + return result.stdout; + }; + const invoke = (host: "codex" | "claude-code", event: string, payload: object): string => { + const file = inspectWorkspaceHooks(home, project).bindings.find(binding => binding.host === host)!.file; + const command = JSON.parse(readFileSync(file, "utf8")).hooks[event].at(-1).hooks[0].command; + const result = spawnSync("sh", ["-c", command], { cwd: project, env, input: JSON.stringify({ cwd: project, ...payload }), encoding: "utf8", timeout: 10000 }); + expect(result.status, result.stderr).toBe(0); + return result.stdout; + }; + const paths = resolveRuntimePaths(home); + await setupRuntimeProfile({ home, profileName: "work", apiBase: "http://127.0.0.1:0", ...generateRuntimeIdentity(), makeDefault: false }); + await installRuntimeCore({ home, cliScriptPath: cliFile, daemonScriptPath: daemonFile }); + const requirement = "Existing invoice requirements use integer cents and round half up."; + writeLocalHotMemory(paths.state, JSON.stringify({ runtime: "codex", continuityCheckpoints: [{ + runtime: "codex", workspaceId: null, sessionId: "old", turnId: "old", goal: "invoice requirements", summary: requirement, occurredAt: new Date().toISOString(), + }] }), "codex"); + try { + cli("quickstart", "--scope", "project", "--adapter", "both", "--profile", "work", "--workspace-root", project, "--codex-home", codexHome, "--claude-home", claudeHome, "--port", "0", "--json"); + for (const host of ["codex", "claude-code"] as const) { + const session = `${host}-session`; + const prompt = (text = "Continue invoice requirements") => invoke(host, "UserPromptSubmit", { session_id: session, prompt: text }); + invoke(host, "SessionStart", { source: "startup", session_id: session }); + expect(prompt()).toContain(requirement); + const again = prompt(); + expect(again).not.toContain(requirement); + expect(again).not.toContain("capture your final response"); + // Automatic compaction (Claude Code skips its other work for it) still resets delivery. + invoke(host, "PreCompact", { session_id: session, trigger: "auto" }); + expect(prompt()).toContain(requirement); + expect(prompt()).not.toContain(requirement); + invoke(host, "SessionStart", { source: "resume", session_id: session }); + expect(prompt()).toContain(requirement); + } + } finally { if (readDaemonOwnershipState(paths)) await stopDetachedRuntimeDaemon(home); } + }, 120000); +}); From d71dc8d0fa5e6fb365746c89f4e6ec828528a1d8 Mon Sep 17 00:00:00 2001 From: Josh Winters Date: Mon, 23 Nov 2026 19:17:41 -0500 Subject: [PATCH 5/5] History budget favors the most recent earlier finding; record delivery after rendering From the completion review: - With newest-last ordering the oldest earlier finding took the history budget first. Budget now goes newest first; text still reads oldest to newest, then the latest finding. - The per-session delivery record is written after the text is built, so a failure while rendering never marks an unsent checkpoint as delivered. --- src/runtime/host-adapter-base.ts | 11 ++++++++--- src/runtime/hot-continuity.ts | 15 ++++++++++----- tests/runtime/hot-continuity.test.ts | 10 ++++++++++ 3 files changed, 28 insertions(+), 8 deletions(-) diff --git a/src/runtime/host-adapter-base.ts b/src/runtime/host-adapter-base.ts index 1500d0d..db24aae 100644 --- a/src/runtime/host-adapter-base.ts +++ b/src/runtime/host-adapter-base.ts @@ -267,8 +267,10 @@ export abstract class HostRuntimeAdapterBase { }).filter(item => !delivered.has(item.full) && !(item.mode === "pointer" && delivered.has(item.pointer)) && // The session wrote its own checkpoints; until compaction it still holds that work. (refresh || !item.entry.sessionId || item.entry.sessionId !== sessionId)); - record(items.map(item => item.mode === "full" ? item.full : item.pointer)); - if (!items.length) return { text: selected.length ? "" : undefined, refresh }; + if (!items.length) { + record([]); + return { text: selected.length ? "" : undefined, refresh }; + } const full = items.filter(item => item.mode === "full").map(item => item.entry); const pointers = items.filter(item => item.mode === "pointer").map(item => { let read: string | null = null; @@ -281,7 +283,10 @@ export abstract class HostRuntimeAdapterBase { const body = !full.length ? "" : command ? this.renderSelectedHotContext(full, workspaceId, sessionStart, command, home!) : renderHotCheckpoints(full, HOT_CONTEXT_LIMIT); - return { text: [body, ...pointers].filter(Boolean).join("\n"), refresh }; + const text = [body, ...pointers].filter(Boolean).join("\n"); + // Recorded only once the text exists, so a failure above never marks an unsent checkpoint as delivered. + record(items.map(item => item.mode === "full" ? item.full : item.pointer)); + return { text, refresh }; } private renderSelectedHotContext(selected: SelectedHotCheckpoint[], workspaceId: string, sessionStart: boolean, command: string, home: string): string { diff --git a/src/runtime/hot-continuity.ts b/src/runtime/hot-continuity.ts index 43ec3d9..29e2195 100644 --- a/src/runtime/hot-continuity.ts +++ b/src/runtime/hot-continuity.ts @@ -325,13 +325,18 @@ export const renderHotCheckpoints = (entries: SelectedHotCheckpoint[], maxLength const historyHeader = `Earlier agent findings (superseded by the latest finding at ${entry.occurredAt || "a later time"} where they conflict; bounded excerpts):`; if (historyBudget - historyHeader.length - 1 > 100) { // Oldest first, then the latest finding: the newest state is read last. - let body = ""; - for (const prior of (entry.earlierFindings ?? []).slice().reverse()) { + // Budget goes to the most recent earlier finding first; the text then reads oldest to newest. + const pieces: string[] = []; + let used = 0; + for (const prior of entry.earlierFindings ?? []) { const prefix = `\n${prior.runtime} at ${prior.occurredAt}: `; - const space = historyBudget - historyHeader.length - 1 - body.length - prefix.length - 24; - if (space < 60) continue; - body += prefix + prior.summary.slice(0, space) + (prior.summary.length > space ? " [finding incomplete]" : ""); + const space = historyBudget - historyHeader.length - 1 - used - prefix.length - 24; + if (space < 60) break; + const piece = prefix + prior.summary.slice(0, space) + (prior.summary.length > space ? " [finding incomplete]" : ""); + pieces.push(piece); + used += piece.length; } + const body = pieces.reverse().join(""); // A header with no finding under it is noise. if (body) history = `${historyHeader}${body}\n`; } diff --git a/tests/runtime/hot-continuity.test.ts b/tests/runtime/hot-continuity.test.ts index eadaa64..605390e 100644 --- a/tests/runtime/hot-continuity.test.ts +++ b/tests/runtime/hot-continuity.test.ts @@ -80,6 +80,16 @@ describe("hot continuity findings", () => { expect(delivered).toContain("trust what you see now and say so"); }); + it("gives the most recent earlier finding the history budget and prints history oldest first", () => { + const rendered = renderHotCheckpoints([{ ...checkpoint({ summary: "Latest: 43 items.", occurredAt: "2026-10-17T03:00:00.000Z" }), earlierFindings: [ + { runtime: "codex", occurredAt: "2026-10-17T02:00:00.000Z", summary: "Second finding, 40 items. " + "detail ".repeat(200) }, + { runtime: "codex", occurredAt: "2026-10-17T01:00:00.000Z", summary: "First finding, 37 items. " + "detail ".repeat(200) }, + ] }], 2000); + expect(rendered).toContain("Second finding, 40 items."); + if (rendered.includes("First finding")) expect(rendered.indexOf("First finding")).toBeLessThan(rendered.indexOf("Second finding")); + expect(rendered.trimEnd().endsWith("Latest: 43 items.")).toBe(true); + }); + it("keeps the latest finding whole when there is no room for earlier ones", () => { const latest = "Correction: parcel batches hold 43 items. ".repeat(8).trim(); for (const budget of [700, 800, 900, 1000, 1100]) {