Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions docs/HOT-SYNC.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,15 @@ 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
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
captured in (`evidence.workspace`: HEAD, branch, uncommitted changes, and up to
10 untracked files with content hashes; names that look private are left out), and command output may carry the
commit it ran at. The field is optional and travels inside the opaque evidence,
so older clients ignore it, and it counts toward the same 30,000-character
budget. When the checkpoint is shown in a tree that differs, the prompt gets one
warning line and marks on the affected excerpts. Nothing is restored or
rewritten. Handoff capsules do not carry it yet.

The daemon is the only writer. Its worker discovers cloud scopes, verifies
signatures, uses conditional reads and writes, and reconciles conflicts. It
prioritizes active workspaces and pending writes while rotating through recovery
Expand Down
3 changes: 2 additions & 1 deletion src/runtime/claude-code-adapter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -610,7 +610,7 @@ export const claudeCodeContinuityTranslationContract: ContinuityTranslationContr
});
},
normalizeToContinuityIr: (captured, targetRuntime = null) =>
normalizeCapturedContextToContinuityIr(captured, targetRuntime),
normalizeCapturedContextToContinuityIr(captured, targetRuntime, { workspaceState: true }),
materializeFromContinuityIr: (translation, targetRuntime = "claude-code") =>
materializeContinuityIrForRuntime(translation, targetRuntime),
reportFidelity: (translation) => translation.fidelity,
Expand Down Expand Up @@ -1308,6 +1308,7 @@ export class ClaudeCodeRuntimeAdapter extends HostRuntimeAdapterBase {
hostVersion: input.hostVersion,
...ids,
goal: importedHandoffGoal({ sourceRuntime: capsule.sourceRuntime, objective: capsule.continuityIr.task.objective, createdAt: capsule.createdAt }),
sourceWorkspace: capsule.continuityIr.provenance?.workspace,
content: renderImportedHandoffMemory({
sourceRuntime: capsule.sourceRuntime,
signedBy: verification.signedBy,
Expand Down
3 changes: 2 additions & 1 deletion src/runtime/codex-adapter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -642,7 +642,7 @@ export const codexContinuityTranslationContract: ContinuityTranslationContract<C
});
},
normalizeToContinuityIr: (captured, targetRuntime = null) =>
normalizeCapturedContextToContinuityIr(captured, targetRuntime),
normalizeCapturedContextToContinuityIr(captured, targetRuntime, { workspaceState: true }),
materializeFromContinuityIr: (translation, targetRuntime = "codex") =>
materializeContinuityIrForRuntime(translation, targetRuntime),
reportFidelity: (translation) => translation.fidelity,
Expand Down Expand Up @@ -1328,6 +1328,7 @@ export class CodexRuntimeAdapter extends HostRuntimeAdapterBase {
hostVersion: input.hostVersion,
...ids,
goal: importedHandoffGoal({ sourceRuntime: capsule.sourceRuntime, objective: capsule.continuityIr.task.objective, createdAt: capsule.createdAt }),
sourceWorkspace: capsule.continuityIr.provenance?.workspace,
content: renderImportedHandoffMemory({
sourceRuntime: capsule.sourceRuntime,
signedBy: verification.signedBy,
Expand Down
22 changes: 21 additions & 1 deletion src/runtime/continuity-ir.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,20 @@ import path from "path";

import { buildEngineAttachment, type EngineAttachment, validateEngineAttachment } from "../protocol/engine-attachments";
import { sanitizePersistentAgentToken } from "./persistent-agent-utils";
import { readWorkspaceGitState, type WorkspaceGitState } from "./workspace-state";

const exportedStates = new Map<string, WorkspaceGitState | null>();
/** Read once per export; an unreadable or non-git root yields nothing. */
const exportWorkspaceState = (root: string): WorkspaceGitState | null => {
if (!exportedStates.has(root)) {
let state: WorkspaceGitState | null = null;
try { state = root ? readWorkspaceGitState(root) : null; } catch { state = null; }
// A capsule leaves this machine: commit, branch and dirty state only, no untracked names or content hashes.
exportedStates.set(root, state ? { head: state.head, branch: state.branch, dirty: state.dirty, untracked: [] } : null);
setTimeout(() => exportedStates.delete(root), 1000).unref?.();
}
return exportedStates.get(root) ?? null;
};

export const CONTINUITY_IR_VERSION = "continuity_ir_v1";

Expand Down Expand Up @@ -150,6 +164,8 @@ export type ContinuityIr = {
createdAt: string;
captureKind: "session" | "turn";
workspaceRootRedacted: boolean;
/** Git state of the exporting workspace (commit, branch, dirty; no file names), so an import elsewhere can warn on drift. */
workspace?: WorkspaceGitState;
};
};

Expand Down Expand Up @@ -568,8 +584,11 @@ export const buildContinuityFidelityReport = (input: {

export const normalizeCapturedContextToContinuityIr = (
captured: CapturedContinuityContext,
targetRuntime: ContinuityRuntime | null = null
targetRuntime: ContinuityRuntime | null = null,
options: { workspaceState?: boolean } = {}
): ContinuityTranslationResult => {
// Only a host's own handoff export opts in. Capsules sent to someone else (deal handoffs) never carry it.
const workspaceState = options.workspaceState ? exportWorkspaceState(captured.workspaceRoot) : null;
const fieldEffects: ContinuityFieldEffect[] = [
{
field: "operationalContext.workspaceRoot",
Expand Down Expand Up @@ -639,6 +658,7 @@ export const normalizeCapturedContextToContinuityIr = (
createdAt: new Date().toISOString(),
captureKind: captured.turnId ? "turn" : "session",
workspaceRootRedacted: true,
...(workspaceState ? { workspace: workspaceState } : {}),
},
};

Expand Down
42 changes: 28 additions & 14 deletions src/runtime/host-adapter-base.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,12 @@ 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, hotCheckpointDigest, renderHotCheckpointPointer, renderHotCheckpoints, selectHotCheckpoints, type SelectedHotCheckpoint } from "./hot-continuity";
import { HOT_CONTEXT_LIMIT, HOT_FULL_RENDER_LIMIT, hotCheckpointDigest, type HotRenderWorkspace, renderHotCheckpointPointer, renderHotCheckpoints, selectHotCheckpoints, type SelectedHotCheckpoint } from "./hot-continuity";
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 { evidenceFromToolCall, readTaskEvidence, taskEvidenceCaptureEnabled, type TaskEvidence } from "./task-evidence";
import { evidenceFromToolCall, readTaskEvidence, taskEvidenceCaptureEnabled, withWorkspaceState, type TaskEvidence } from "./task-evidence";
import type { LocalRuntimeClient } from "./local-client";
import {
appendVerifiedArchiveContext,
Expand Down Expand Up @@ -209,7 +210,7 @@ export abstract class HostRuntimeAdapterBase {
// this turn. Never inspect tool output when automatic memory is disabled.
const status = await this.client.status(this.config.profileName).catch(() => null);
if (status?.profile?.memoryMode !== "auto" && status?.profile?.memoryMode !== "assist") return undefined;
return readTaskEvidence(file, sessionId, workspaceRoot, since, goal ?? "");
return withWorkspaceState(readTaskEvidence(file, sessionId, workspaceRoot, since, goal ?? ""), readWorkspaceGitState(workspaceRoot));
}

/** This host's Crosshead command, or null when no wrapper is installed (other hosts). */
Expand Down Expand Up @@ -243,7 +244,7 @@ export abstract class HostRuntimeAdapterBase {
* 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, sessionId?: string): { text: string | undefined; refresh: boolean } {
protected renderHotContext(snapshot: unknown, prompt: string, workspaceId: string, sessionStart: boolean, sessionId?: string, workspaceRoot?: 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"));
Expand All @@ -254,9 +255,16 @@ export abstract class HostRuntimeAdapterBase {
};
const command = this.bridgeCommand();
const selected = selectHotCheckpoints(snapshot, prompt, this.config.workspaceOnly ? workspaceId : undefined);
// Compare saved git state with this tree only when a checkpoint carries some, and only once.
let here: HotRenderWorkspace | undefined | null = null;
const where = (): HotRenderWorkspace | undefined => {
if (here === null) here = workspaceRoot && selected.some(entry => entry.evidence?.workspace || entry.evidence?.sources.length)
? { root: workspaceRoot, git: readWorkspaceGitState(workspaceRoot) } : undefined;
return here;
};
if (!tracked) {
if (!command || !home || !selected.length) return { text: undefined, refresh };
return { text: this.renderSelectedHotContext(selected, workspaceId, sessionStart, command, home), refresh };
return { text: this.renderSelectedHotContext(selected, workspaceId, sessionStart, command, home, where()), refresh };
}
const delivered = refresh ? new Set<string>() : delivery!.delivered;
const items = selected.map(entry => {
Expand All @@ -275,22 +283,22 @@ export abstract class HostRuntimeAdapterBase {
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));
const pages = paginateCheckpoint(renderHotCheckpoints([item.entry], HOT_FULL_RENDER_LIMIT, where()));
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);
? this.renderSelectedHotContext(full, workspaceId, sessionStart, command, home!, where())
: renderHotCheckpoints(full, HOT_CONTEXT_LIMIT, where());
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 {
const full = renderHotCheckpoints(selected, HOT_FULL_RENDER_LIMIT);
private renderSelectedHotContext(selected: SelectedHotCheckpoint[], workspaceId: string, sessionStart: boolean, command: string, home: string, here?: HotRenderWorkspace): string {
const full = renderHotCheckpoints(selected, HOT_FULL_RENDER_LIMIT, here);
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);
Expand All @@ -301,7 +309,7 @@ export abstract class HostRuntimeAdapterBase {
const remaining = pages.length - inline === 1 ? `page ${pages.length}` : `pages ${inline + 1} to ${pages.length}, one page number per call`;
return sessionStart
? `${pages.slice(0, inline).join("\n")}\n[Crosshead: ${shown} of ${pages.length} of the saved checkpoint shown. The rest holds further saved findings and observed sources. Before relying on partial values, read ${remaining}, with this Crosshead command: ${read(inline + 1)}]`
: `${renderHotCheckpoints(selected, HOT_CONTEXT_LIMIT)}\n[Crosshead: excerpt only. The saved checkpoint has ${pages.length} page${pages.length === 1 ? "" : "s"}; read from the start with: ${read(1)}]`;
: `${renderHotCheckpoints(selected, HOT_CONTEXT_LIMIT, here)}\n[Crosshead: excerpt only. The saved checkpoint has ${pages.length} page${pages.length === 1 ? "" : "s"}; read from the start with: ${read(1)}]`;
}

/**
Expand All @@ -311,11 +319,13 @@ export abstract class HostRuntimeAdapterBase {
*/
async recordToolEvidence(input: HostAdapterToolEvidenceRequest): Promise<boolean> {
if (!(this.config.sourceExcerpts ?? taskEvidenceCaptureEnabled())) return false;
const taskEvidence = evidenceFromToolCall(input.toolName, input.toolInput, input.toolResponse, input.workspaceRoot, nowIso(), input.failed === true);
if (!taskEvidence.sources.length) return false;
const observed = evidenceFromToolCall(input.toolName, input.toolInput, input.toolResponse, input.workspaceRoot, nowIso(), input.failed === true);
if (!observed.sources.length) return false;
const profileName = input.profileName ?? this.config.profileName;
const status = await this.client.status(profileName).catch(() => null);
if (status?.profile?.memoryMode !== "auto" && status?.profile?.memoryMode !== "assist") return false;
// Command output is stamped with the commit it ran at.
const taskEvidence = withWorkspaceState(observed, readWorkspaceGitState(input.workspaceRoot));
await this.client.emitEvent({
runtime: this.identity.runtimeId,
profileName,
Expand Down Expand Up @@ -420,7 +430,7 @@ 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)
? this.renderHotContext(preTurnHotMemory, input.prompt, workspaceId, input.sessionStart === true, input.sessionId, input.workspaceRoot)
: { text: undefined, refresh: true };
let contextText = input.prompt.trim() ? renderRuntimeStartupContext({
runtime: this.identity.runtimeId,
Expand Down Expand Up @@ -635,7 +645,10 @@ export abstract class HostRuntimeAdapterBase {
turnId: string;
goal: string;
content: string;
/** Git state the capsule was exported from; the imported checkpoint warns when this tree differs. */
sourceWorkspace?: unknown;
}): Promise<{ saved: boolean; notSavedReason?: string }> {
const workspace = normalizeWorkspaceGitState(input.sourceWorkspace);
const response = await this.client.emitEvent({
eventId: input.eventId,
runtime: this.identity.runtimeId,
Expand All @@ -648,6 +661,7 @@ export abstract class HostRuntimeAdapterBase {
goal: input.goal,
content: input.content,
handoffTurnId: input.turnId,
...(workspace ? { taskEvidence: { version: 1, sources: [], coverage: "unavailable", omitted: 0, workspace } } : {}),
},
metadata: {
hostVersion: input.hostVersion ?? this.identity.wrapperVersionFallback,
Expand Down
Loading
Loading