diff --git a/docs/HOT-SYNC.md b/docs/HOT-SYNC.md index bb5e468..d3960d1 100644 --- a/docs/HOT-SYNC.md +++ b/docs/HOT-SYNC.md @@ -19,7 +19,13 @@ Pending checkpoints have a separate durable outbox. They survive restart, network failure, and retry exhaustion, even when they no longer fit the recent context view. Each upload is at most 128 KiB; recent context retains at most 12 checkpoints and 30,000 characters, with the existing 4,200-character prompt -budget. The store allows 64 MiB per identity and API origin. A full or unwritable +budget. After the newest checkpoint, the latest three explicit saves of each +workspace (six in all, within half the character budget) are kept ahead of +other history, so newer turns do not evict them. Devices still on an older +client retain by recency and can drop them until they upgrade. Local-only +profiles (no hot sync) also keep history that is still being delivered to +sessions ahead of idle, merely recent history; synced profiles do not, so that +every device retains the same set. The store allows 64 MiB per identity and API origin. A full or unwritable store fails the new capture explicitly and preserves existing pending captures. A checkpoint's evidence may carry the git state of the workspace it was diff --git a/src/runtime/host-adapter-base.ts b/src/runtime/host-adapter-base.ts index 5237f3d..3e1e09e 100644 --- a/src/runtime/host-adapter-base.ts +++ b/src/runtime/host-adapter-base.ts @@ -9,7 +9,8 @@ import { HOT_CONTEXT_LIMIT, HOT_FULL_RENDER_LIMIT, hotCheckpointDigest, type Hot import { readSessionDelivery, recordSessionDelivery } from "./hook-session-context"; import { normalizeWorkspaceGitState, readWorkspaceGitState } from "./workspace-state"; import { CHECKPOINT_PAGE_CHARS, inlineCheckpointPages, paginateCheckpoint, saveCheckpointPages } from "./checkpoint-pages"; -import { resolveRuntimeHome } from "./local-runtime"; +import { ensureRuntimeHomeLayout, resolveRuntimeHome } from "./local-runtime"; +import { hotCheckpointUseKey, recordHotUse } from "./hot-use"; import { evidenceFromToolCall, readTaskEvidence, taskEvidenceCaptureEnabled, withWorkspaceState, type TaskEvidence } from "./task-evidence"; import type { LocalRuntimeClient } from "./local-client"; import { @@ -280,6 +281,8 @@ export abstract class HostRuntimeAdapterBase { return { text: selected.length ? "" : undefined, refresh }; } const full = items.filter(item => item.mode === "full").map(item => item.entry); + // Delivered checkpoints count as used, so local retention keeps them ahead of idle history. + recordHotUse(ensureRuntimeHomeLayout(home!).state, full.map(hotCheckpointUseKey)); const pointers = items.filter(item => item.mode === "pointer").map(item => { let read: string | null = null; if (command) { diff --git a/src/runtime/hot-continuity.ts b/src/runtime/hot-continuity.ts index 8d53d51..f828281 100644 --- a/src/runtime/hot-continuity.ts +++ b/src/runtime/hot-continuity.ts @@ -21,6 +21,9 @@ export const HOT_CONTEXT_LIMIT = 4200; // back to the small budget. This bounds the complete rendering that is paged. export const HOT_FULL_RENDER_LIMIT = 80000; const MAX_CHECKPOINTS = 12; +// Explicit saves per workspace kept ahead of other history (the user chose them). +export const PROTECTED_SAVES = 3; +export const PROTECTED_SAVES_TOTAL = 6; // The hot-sync replica (hot-sync-replica.ts) refuses a checkpoint whose request, // finding and serialized evidence exceed 30,000 characters. Every stored // checkpoint is kept under that with the same measure, so a checkpoint that is @@ -110,8 +113,11 @@ const fitCheckpoint = source.replace(/ \(exited non-zero\)$/, ""); +/** Epoch ms when a checkpoint was last delivered on this machine, or 0. */ +export type HotCheckpointLastUsed = (entry: HotContinuityCheckpoint) => number; + export const updateHotCheckpoints = ( - previous: unknown, next: HotContinuityCheckpoint + previous: unknown, next: HotContinuityCheckpoint, lastUsed?: HotCheckpointLastUsed ): HotContinuityCheckpoint[] => { const sameTurn = (entry: HotContinuityCheckpoint): boolean => entry.runtime === next.runtime && entry.workspaceId === next.workspaceId && @@ -142,16 +148,39 @@ export const updateHotCheckpoints = ( entries.push(fitCheckpoint({ ...next, goal: next.goal.slice(0, HOT_REQUEST_LIMIT), ...(next.goalTruncated || next.goal.length > HOT_REQUEST_LIMIT ? { goalTruncated: true } : {}), summary: captureHotFinding(next.summary), ...(evidence ? { evidence } : {}) })); - const bounded: HotContinuityCheckpoint[] = []; - let size = 0; - for (const entry of entries.reverse()) { + // Retention order: the newest checkpoint (the present), then the latest explicit + // saves of each workspace, then the rest by most recent use or capture. An entry + // that does not fit is skipped, so a smaller one behind it can still be kept. + const newest = entries[entries.length - 1]!; + const history = entries.slice(0, -1); + const savesByWorkspace = new Map(); + for (const entry of history.filter(entry => entry.origin === "remember").sort((a, b) => timestamp(b.occurredAt) - timestamp(a.occurredAt))) { + const key = entry.workspaceId ?? ""; + savesByWorkspace.set(key, [...(savesByWorkspace.get(key) ?? []), entry]); + } + const saves = new Set(); + let savedChars = 0; + for (const entry of [...savesByWorkspace.values()].flatMap(list => list.slice(0, PROTECTED_SAVES)) + .sort((a, b) => timestamp(b.occurredAt) - timestamp(a.occurredAt)).slice(0, PROTECTED_SAVES_TOTAL)) { + // Saves may take at most half the history budget. + const chars = entry.goal.length + entry.summary.length + taskEvidenceChars(entry.evidence); + if (savedChars + chars > MAX_HISTORY_CHARS / 2) continue; + savedChars += chars; + saves.add(entry); + } + const recency = (entry: HotContinuityCheckpoint): number => Math.max(timestamp(entry.occurredAt), lastUsed?.(entry) ?? 0); + const rest = history.filter(entry => !saves.has(entry)).map((entry, index) => ({ entry, index })) + .sort((a, b) => recency(b.entry) - recency(a.entry) || b.index - a.index).map(({ entry }) => entry); + const kept = new Set([newest]); + let size = newest.goal.length + newest.summary.length + taskEvidenceChars(newest.evidence); + for (const entry of [...[...saves].sort((a, b) => timestamp(b.occurredAt) - timestamp(a.occurredAt)), ...rest]) { const chars = entry.goal.length + entry.summary.length + taskEvidenceChars(entry.evidence); - // The newest checkpoint is always kept; the bound trims history, not the present. - if (bounded.length > 0 && (bounded.length >= MAX_CHECKPOINTS || size + chars > MAX_HISTORY_CHARS)) break; - bounded.push(entry); + if (kept.size >= MAX_CHECKPOINTS || size + chars > MAX_HISTORY_CHARS) continue; + kept.add(entry); size += chars; } - return bounded.reverse(); + // Stored order stays chronological by capture. + return entries.filter(entry => kept.has(entry)); }; const STOP_WORDS = new Set(("a an and are as at be been but by can do for from had has have i if in into is it its may of on or our should that the their then there these they this to was we were will with would you your").split(" ")); diff --git a/src/runtime/hot-sync-replica.ts b/src/runtime/hot-sync-replica.ts index de5e9ad..783f012 100644 --- a/src/runtime/hot-sync-replica.ts +++ b/src/runtime/hot-sync-replica.ts @@ -1,3 +1,4 @@ +import { PROTECTED_SAVES, PROTECTED_SAVES_TOTAL } from "./hot-continuity"; import { createHash } from "node:crypto"; import { existsSync, readFileSync, readdirSync, statSync } from "node:fs"; import path from "node:path"; @@ -45,10 +46,29 @@ export function retainHotSync(document: HotSyncDocument, requiredIds: Set 12 || mandatory.reduce((sum, c) => sum + size(c), 0) > 30000) throw new Error("Pending conflict group exceeds the hot-memory budget; captures remain pending"); + // The newest visible checkpoint (the present) comes first; then the latest explicit + // saves of each workspace, within half the character budget, ahead of other history. + // Deterministic (no device-local use), so every device retains the same set. + const visible = (c: HotSyncCheckpoint) => !supersededIds.has(c.id) && !conflictIds.has(c.id) && !c.conflictOf; + const byRecency = (a: HotSyncCheckpoint, b: HotSyncCheckpoint) => Date.parse(b.occurredAt) - Date.parse(a.occurredAt) || a.id.localeCompare(b.id); + const newestId = document.checkpoints.filter(visible).sort(byRecency)[0]?.id; + const savesByWorkspace = new Map(); + for (const c of document.checkpoints.filter(c => c.origin === "remember" && visible(c)) + .sort((a, b) => Date.parse(b.occurredAt) - Date.parse(a.occurredAt) || a.id.localeCompare(b.id))) + savesByWorkspace.set(c.workspaceId, [...(savesByWorkspace.get(c.workspaceId) ?? []), c]); + const protectedIds = new Set(); + let protectedChars = 0; + for (const c of [...savesByWorkspace.values()].flatMap(list => list.slice(0, PROTECTED_SAVES)).sort(byRecency).slice(0, PROTECTED_SAVES_TOTAL)) { + if (protectedChars + size(c) > 15000) continue; + protectedChars += size(c); + protectedIds.add(c.id); + } let chars = 0; const checkpoints: HotSyncCheckpoint[] = []; for (const c of [...document.checkpoints].sort((a, b) => Number(required(b)) - Number(required(a)) || - Number(supersededIds.has(a.id)) - Number(supersededIds.has(b.id)) || Date.parse(b.occurredAt) - Date.parse(a.occurredAt) || a.id.localeCompare(b.id))) { + Number(supersededIds.has(a.id)) - Number(supersededIds.has(b.id)) || Number(b.id === newestId) - Number(a.id === newestId) || + Number(protectedIds.has(b.id)) - Number(protectedIds.has(a.id)) || + Date.parse(b.occurredAt) - Date.parse(a.occurredAt) || a.id.localeCompare(b.id))) { if (checkpoints.length === 12 || chars + size(c) > 30000) continue; chars += size(c); diff --git a/src/runtime/hot-use.ts b/src/runtime/hot-use.ts new file mode 100644 index 0000000..a3ff897 --- /dev/null +++ b/src/runtime/hot-use.ts @@ -0,0 +1,32 @@ +import { readFileSync } from "fs"; +import path from "path"; +import { writeJsonFile } from "./runtime-persistence"; + +// When each hot checkpoint was last delivered to a session. Local only, never +// synced: retention on this machine prefers checkpoints that are still being +// used over ones that are merely recent. The synced replica stays +// deterministic across devices and does not read this. +const MAX_ENTRIES = 256; +const useFile = (stateDir: string): string => path.join(stateDir, "hot-checkpoint-use.json"); + +/** Identity of a checkpoint that survives re-rendering and evidence merges. */ +export const hotCheckpointUseKey = (entry: { workspaceId: string | null; runtime: string; origin?: string; sessionId: string | null; turnId: string | null; goal: string }): string => + JSON.stringify([entry.workspaceId, entry.runtime, entry.origin ?? null, entry.sessionId, entry.turnId, entry.goal.slice(0, 200)]); + +export const readHotUse = (stateDir: string): Map => { + try { + const value = JSON.parse(readFileSync(useFile(stateDir), "utf8")) as unknown; + if (!value || typeof value !== "object" || Array.isArray(value)) return new Map(); + return new Map(Object.entries(value as Record).flatMap(([key, at]) => + typeof at === "number" && Number.isFinite(at) ? [[key, at] as [string, number]] : [])); + } catch { return new Map(); } +}; + +export const recordHotUse = (stateDir: string, keys: string[], at: number = Date.now()): void => { + if (!keys.length) return; + try { + const uses = readHotUse(stateDir); + for (const key of keys) { uses.delete(key); uses.set(key, at); } + writeJsonFile(useFile(stateDir), Object.fromEntries([...uses.entries()].sort((a, b) => a[1] - b[1]).slice(-MAX_ENTRIES))); + } catch { /* Use only ranks retention; a lost write keeps age order. */ } +}; diff --git a/src/runtime/lifecycle-engine.ts b/src/runtime/lifecycle-engine.ts index 58b987c..cb1f95f 100644 --- a/src/runtime/lifecycle-engine.ts +++ b/src/runtime/lifecycle-engine.ts @@ -16,7 +16,8 @@ import { COLLABORATION_EVENT_PRIORITIES } from "../protocol/collaboration"; import { DURABLE_INBOX_STATUSES, DURABLE_INBOX_TERMINAL_STATUSES } from "../protocol/inbox"; import { HOT_SCOPE_ALL } from "../protocol/memory"; import { HANDOFF_IMPORT_COMMAND, IMPORTED_HANDOFF_TURN_PREFIX } from "./handoff-import"; -import { captureHotFinding, HOT_TURN_IN_PROGRESS, renderHotCheckpoints, selectHotCheckpoints, updateHotCheckpoints } from "./hot-continuity"; +import { hotCheckpointUseKey, readHotUse } from "./hot-use"; +import { captureHotFinding, type HotCheckpointLastUsed, HOT_TURN_IN_PROGRESS, renderHotCheckpoints, selectHotCheckpoints, updateHotCheckpoints } from "./hot-continuity"; import { normalizeTaskEvidence } from "./task-evidence"; import { buildHotContextActionCue, @@ -893,7 +894,8 @@ const boundedRecentEvents = (value: unknown, nextEntry: Record) const buildHotState = ( currentHot: Record, - event: RuntimeLifecycleEvent + event: RuntimeLifecycleEvent, + lastUsed?: HotCheckpointLastUsed ): Record => { const currentWorkspaceId = asString(currentHot.workspaceId) ?? asString(currentHot.workspace_id); const baseHot = event.workspaceId && currentWorkspaceId !== event.workspaceId ? {} : currentHot; @@ -1015,7 +1017,7 @@ const buildHotState = ( ...(explicitMemory ? { origin: "remember" as const } : {}), summary: captureHotFinding(finding), occurredAt: event.occurredAt, ...(evidence ? { evidence } : {}), - }); + }, lastUsed); } } @@ -1607,6 +1609,14 @@ export class RuntimeLifecycleManager { }, this.workerIntervalMs); } + /** Local delivery times rank which history this machine keeps (see hot-use.ts). */ + private hotCheckpointLastUsed(): HotCheckpointLastUsed { + // Read only when retention actually has to choose. Synced profiles retain + // through the replica, which does not use local delivery times. + let uses: Map | null = null; + return entry => (uses ??= readHotUse(this.deps.paths.state)).get(hotCheckpointUseKey(entry)) ?? 0; + } + async stop(): Promise { if (this.timer) { clearInterval(this.timer); @@ -1999,7 +2009,7 @@ export class RuntimeLifecycleManager { const manager=getHotSyncManager({stateDir:this.deps.paths.state,origin:profile.apiBase,npub:profile.npub,nsec:secret.nsec,profileName}); const scope=workspaceHotScope(event.runtime,event.workspaceId) ?? "shared"; const current=parseStructuredHotState(String(manager.readWorkspace(event.runtime,event.workspaceId ?? "").content ?? "")); - const hot=buildHotState(current,event); + const hot=buildHotState(current,event,this.hotCheckpointLastUsed()); const checkpoints=Array.isArray(hot.continuityCheckpoints)?hot.continuityCheckpoints:[]; const last=checkpoints[checkpoints.length-1] as Record|undefined; // Each capture is a new synced record. One host Stop reports the same turn @@ -2044,7 +2054,7 @@ export class RuntimeLifecycleManager { (item): item is Extract => item.kind === "hot_write" && item.profileName === event.profileName && item.payload.scope === scope && item.workspaceId === event.workspaceId ); - const hotState = buildHotState(pending?.payload.hotState ?? currentHot, event); + const hotState = buildHotState(pending?.payload.hotState ?? currentHot, event, this.hotCheckpointLastUsed()); const queued = this.enqueueHotWrite(state, event, hotState, { immediate: event.type === "compact.started" || event.type === "compact.completed", }); diff --git a/tests/runtime/hot-retention.test.ts b/tests/runtime/hot-retention.test.ts new file mode 100644 index 0000000..8478088 --- /dev/null +++ b/tests/runtime/hot-retention.test.ts @@ -0,0 +1,101 @@ +import { describe, expect, it } from "vitest"; +import { mkdtempSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import path from "node:path"; + +import { updateHotCheckpoints, type HotContinuityCheckpoint } from "../../src/runtime/hot-continuity"; +import { hotCheckpointUseKey, readHotUse, recordHotUse } from "../../src/runtime/hot-use"; +import { retainHotSync } from "../../src/runtime/hot-sync-replica"; +import { HOT_SYNC_VERSION, validHotSyncDocument, type HotSyncCheckpoint } from "../../src/protocol/hot-sync"; + +const at = (minute: number): string => new Date(Date.UTC(2026, 10, 1, 0, minute)).toISOString(); +const entry = (i: number, overrides: Partial = {}): HotContinuityCheckpoint => ({ + runtime: "codex", workspaceId: "repo:/w", sessionId: `s${i}`, turnId: `t${i}`, goal: `Task ${i}`, summary: `Finding ${i}`, occurredAt: at(i), ...overrides, +}); +const fill = (count: number, first: HotContinuityCheckpoint[] = [], lastUsed?: (e: HotContinuityCheckpoint) => number): HotContinuityCheckpoint[] => { + let stored: HotContinuityCheckpoint[] = []; + for (const item of first) stored = updateHotCheckpoints(stored, item, lastUsed); + for (let i = 100; i < 100 + count; i += 1) stored = updateHotCheckpoints(stored, entry(i), lastUsed); + return stored; +}; + +describe("local hot retention", () => { + it("keeps the latest explicit saves when newer work would evict them by age", () => { + const saves = [1, 2, 3, 4].map(i => entry(i, { origin: "remember", goal: "", summary: `Saved fact ${i}` })); + const stored = fill(12, saves); + expect(stored).toHaveLength(12); + const kept = stored.filter(e => e.origin === "remember").map(e => e.summary); + expect(kept).toEqual(["Saved fact 2", "Saved fact 3", "Saved fact 4"]); + // The newest capture is always kept, and stored order stays chronological. + expect(stored.at(-1)?.goal).toBe("Task 111"); + expect(stored.map(e => e.occurredAt)).toEqual([...stored.map(e => e.occurredAt)].sort()); + }); + + it("caps protected saves across workspaces", () => { + const saves = Array.from({ length: 12 }, (_, i) => entry(i, { origin: "remember", goal: "", workspaceId: `repo:/w${i % 4}`, summary: `Saved ${i}` })); + const stored = fill(12, saves); + expect(stored.filter(e => e.origin === "remember")).toHaveLength(6); + }); + + it("prefers history that is still being delivered over idle newer history", () => { + const used = entry(5, { goal: "Parcel batching contract" }); + const stored = fill(12, [used], e => e.turnId === "t5" ? Date.parse(at(500)) : 0); + expect(stored.some(e => e.turnId === "t5")).toBe(true); + expect(stored.some(e => e.turnId === "t100")).toBe(false); + expect(fill(12, [used]).some(e => e.turnId === "t5")).toBe(false); + }); + + it("records use locally, bounded", () => { + const state = mkdtempSync(path.join(tmpdir(), "crosshead-hot-use-")); + try { + recordHotUse(state, [hotCheckpointUseKey(entry(1))], 1000); + recordHotUse(state, Array.from({ length: 300 }, (_, i) => `k${i}`), 2000); + const uses = readHotUse(state); + expect(uses.size).toBe(256); + expect(uses.get("k299")).toBe(2000); + } finally { rmSync(state, { recursive: true, force: true }); } + }); +}); + +describe("replica retention", () => { + const sync = (i: number, overrides: Partial = {}): HotSyncCheckpoint => ({ + id: `c${String(i).padStart(3, "0")}`, deviceId: "d", runtime: "codex", workspaceId: "repo:/w", occurredAt: at(i), goal: `Task ${i}`, summary: `Finding ${i}`, ...overrides, + }); + it("keeps the latest explicit saves deterministically", () => { + const checkpoints = [...[1, 2, 3, 4].map(i => sync(i, { origin: "remember" })), ...Array.from({ length: 12 }, (_, i) => sync(100 + i))]; + const document = { version: HOT_SYNC_VERSION, namespace: "n", scope: "s", epoch: 0, checkpoints } as const; + const kept = retainHotSync({ ...document, checkpoints: [...checkpoints] }); + expect(kept.checkpoints).toHaveLength(12); + expect(kept.checkpoints.filter(c => c.origin === "remember").map(c => c.id)).toEqual(["c002", "c003", "c004"]); + expect(retainHotSync({ ...document, checkpoints: [...checkpoints].reverse() }).checkpoints.map(c => c.id)).toEqual(kept.checkpoints.map(c => c.id)); + }); + + it("never drops the newest capture for protected saves", () => { + const big = "x".repeat(9000); + const checkpoints = [1, 2, 3].map(i => sync(i, { origin: "remember", summary: big })).concat([sync(50, { summary: "y".repeat(5000) })]); + const kept = retainHotSync({ version: HOT_SYNC_VERSION, namespace: "n", scope: "s", epoch: 0, checkpoints }); + expect(kept.checkpoints.map(c => c.id)).toContain("c050"); + // Saves are held to half the budget; the rest of history still fits by recency. + expect(kept.checkpoints.filter(c => c.origin === "remember").length).toBeLessThanOrEqual(2); + }); + + it("does not protect a save that is disputed or superseded", () => { + const checkpoints = [sync(1, { origin: "remember" }), sync(2, { origin: "remember", supersedes: ["c001"] }), ...Array.from({ length: 12 }, (_, i) => sync(100 + i))]; + const kept = retainHotSync({ version: HOT_SYNC_VERSION, namespace: "n", scope: "s", epoch: 0, checkpoints }); + expect(kept.checkpoints.map(c => c.id)).toContain("c002"); + expect(kept.checkpoints.map(c => c.id)).not.toContain("c001"); + }); + + it("interoperates with an older client that retains by recency only", () => { + const checkpoints = [...[1, 2, 3].map(i => sync(i, { origin: "remember" })), ...Array.from({ length: 12 }, (_, i) => sync(100 + i))]; + const document = { version: HOT_SYNC_VERSION, namespace: "n", scope: "s", epoch: 0, checkpoints }; + const ours = retainHotSync(document); + expect(validHotSyncDocument(ours)).toBe(true); + // An older client keeps the newest 12 by time; its document is valid for us, and we keep what is left stable. + const older = { ...ours, checkpoints: [...ours.checkpoints].sort((a, b) => Date.parse(b.occurredAt) - Date.parse(a.occurredAt)).slice(0, 12) }; + expect(validHotSyncDocument(older)).toBe(true); + const again = retainHotSync(older); + expect(again.checkpoints.map(c => c.id).sort()).toEqual(older.checkpoints.map(c => c.id).sort()); + expect(retainHotSync(again).checkpoints).toEqual(again.checkpoints); + }); +});