Skip to content
8 changes: 7 additions & 1 deletion docs/HOT-SYNC.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
5 changes: 4 additions & 1 deletion src/runtime/host-adapter-base.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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) {
Expand Down
45 changes: 37 additions & 8 deletions src/runtime/hot-continuity.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -110,8 +113,11 @@ const fitCheckpoint = <T extends Pick<HotContinuityCheckpoint, "goal" | "summary
};
const commandOf = (source: string): string => 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 &&
Expand Down Expand Up @@ -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<string, HotContinuityCheckpoint[]>();
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<HotContinuityCheckpoint>();
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<HotContinuityCheckpoint>([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(" "));
Expand Down
22 changes: 21 additions & 1 deletion src/runtime/hot-sync-replica.ts
Original file line number Diff line number Diff line change
@@ -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";
Expand Down Expand Up @@ -45,10 +46,29 @@ export function retainHotSync(document: HotSyncDocument, requiredIds: Set<string
const mandatory = document.checkpoints.filter(required);
if (mandatory.length > 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<string, HotSyncCheckpoint[]>();
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<string>();
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);
Expand Down
32 changes: 32 additions & 0 deletions src/runtime/hot-use.ts
Original file line number Diff line number Diff line change
@@ -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<string, number> => {
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<string, unknown>).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. */ }
};
20 changes: 15 additions & 5 deletions src/runtime/lifecycle-engine.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -893,7 +894,8 @@ const boundedRecentEvents = (value: unknown, nextEntry: Record<string, unknown>)

const buildHotState = (
currentHot: Record<string, unknown>,
event: RuntimeLifecycleEvent
event: RuntimeLifecycleEvent,
lastUsed?: HotCheckpointLastUsed
): Record<string, unknown> => {
const currentWorkspaceId = asString(currentHot.workspaceId) ?? asString(currentHot.workspace_id);
const baseHot = event.workspaceId && currentWorkspaceId !== event.workspaceId ? {} : currentHot;
Expand Down Expand Up @@ -1015,7 +1017,7 @@ const buildHotState = (
...(explicitMemory ? { origin: "remember" as const } : {}),
summary: captureHotFinding(finding), occurredAt: event.occurredAt,
...(evidence ? { evidence } : {}),
});
}, lastUsed);
}
}

Expand Down Expand Up @@ -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<string, number> | null = null;
return entry => (uses ??= readHotUse(this.deps.paths.state)).get(hotCheckpointUseKey(entry)) ?? 0;
}

async stop(): Promise<void> {
if (this.timer) {
clearInterval(this.timer);
Expand Down Expand Up @@ -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<string,unknown>|undefined;
// Each capture is a new synced record. One host Stop reports the same turn
Expand Down Expand Up @@ -2044,7 +2054,7 @@ export class RuntimeLifecycleManager {
(item): item is Extract<RuntimeQueueItem, { kind: "hot_write" }> =>
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",
});
Expand Down
Loading
Loading