diff --git a/docs/HOT-SYNC.md b/docs/HOT-SYNC.md index 3369a89..bb5e468 100644 --- a/docs/HOT-SYNC.md +++ b/docs/HOT-SYNC.md @@ -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 diff --git a/src/runtime/claude-code-adapter.ts b/src/runtime/claude-code-adapter.ts index b7efb41..e9c9b25 100644 --- a/src/runtime/claude-code-adapter.ts +++ b/src/runtime/claude-code-adapter.ts @@ -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, @@ -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, diff --git a/src/runtime/codex-adapter.ts b/src/runtime/codex-adapter.ts index 8994861..165f510 100644 --- a/src/runtime/codex-adapter.ts +++ b/src/runtime/codex-adapter.ts @@ -642,7 +642,7 @@ export const codexContinuityTranslationContract: ContinuityTranslationContract - normalizeCapturedContextToContinuityIr(captured, targetRuntime), + normalizeCapturedContextToContinuityIr(captured, targetRuntime, { workspaceState: true }), materializeFromContinuityIr: (translation, targetRuntime = "codex") => materializeContinuityIrForRuntime(translation, targetRuntime), reportFidelity: (translation) => translation.fidelity, @@ -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, diff --git a/src/runtime/continuity-ir.ts b/src/runtime/continuity-ir.ts index 2ef7eb1..df11e63 100644 --- a/src/runtime/continuity-ir.ts +++ b/src/runtime/continuity-ir.ts @@ -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(); +/** 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"; @@ -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; }; }; @@ -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", @@ -639,6 +658,7 @@ export const normalizeCapturedContextToContinuityIr = ( createdAt: new Date().toISOString(), captureKind: captured.turnId ? "turn" : "session", workspaceRootRedacted: true, + ...(workspaceState ? { workspace: workspaceState } : {}), }, }; diff --git a/src/runtime/host-adapter-base.ts b/src/runtime/host-adapter-base.ts index db24aae..5237f3d 100644 --- a/src/runtime/host-adapter-base.ts +++ b/src/runtime/host-adapter-base.ts @@ -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, @@ -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). */ @@ -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")); @@ -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() : delivery!.delivered; const items = selected.map(entry => { @@ -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); @@ -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)}]`; } /** @@ -311,11 +319,13 @@ export abstract class HostRuntimeAdapterBase { */ async recordToolEvidence(input: HostAdapterToolEvidenceRequest): Promise { 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, @@ -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, @@ -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, @@ -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, diff --git a/src/runtime/hot-continuity.ts b/src/runtime/hot-continuity.ts index 29e2195..8d53d51 100644 --- a/src/runtime/hot-continuity.ts +++ b/src/runtime/hot-continuity.ts @@ -1,6 +1,7 @@ import { createHash } from "crypto"; import { compactContinuitySummary } from "./summary-compaction"; import { normalizeTaskEvidence, preferFileSources, renderTaskEvidence, taskEvidenceChars, type TaskEvidence } from "./task-evidence"; +import { describeWorkspaceDrift, fileExcerptState, type WorkspaceGitState } from "./workspace-state"; import { IMPORTED_HANDOFF_TURN_PREFIX } from "./handoff-import"; // Capture and delivery have separate bounds. Keep exact findings, including list/code @@ -94,8 +95,16 @@ const checkpointSize = (entry: Pick>(entry: T): T => { let evidence = entry.evidence; + // Names of dropped sources and untracked files are worth less than any excerpt: they go first. + if (evidence && checkpointSize({ ...entry, evidence }) > HOT_CHECKPOINT_BUDGET && (evidence.omittedSources || evidence.workspace?.untracked.length)) { + const { omittedSources: _names, ...rest } = evidence; + evidence = { ...rest, ...(rest.workspace ? { workspace: { ...rest.workspace, untracked: [], untrackedOmitted: (rest.workspace.untrackedOmitted ?? 0) + rest.workspace.untracked.length } } : {}) }; + } while (evidence?.sources.length && checkpointSize({ ...entry, evidence }) > HOT_CHECKPOINT_BUDGET) { - evidence = { ...evidence, sources: evidence.sources.slice(0, -1), omitted: evidence.omitted + 1 }; + const last = evidence.sources[evidence.sources.length - 1]!; + const next = { ...evidence, sources: evidence.sources.slice(0, -1), omitted: evidence.omitted + 1 }; + const named = { ...next, omittedSources: [...(evidence.omittedSources ?? []), { source: last.source.slice(0, 160), sha256: last.sha256 }].slice(-8) }; + evidence = checkpointSize({ ...entry, evidence: named }) <= HOT_CHECKPOINT_BUDGET ? named : next; } return evidence === entry.evidence ? entry : { ...entry, evidence }; }; @@ -118,13 +127,17 @@ export const updateHotCheckpoints = ( // Stop may follow compaction, after the source has left the host transcript. // Keep earlier evidence; repeated quotes dedupe by bytes, while conflicting // versions remain visible. Observation recency alone cannot establish authority. - const evidence = freshEvidence?.sources.length ? normalizeTaskEvidence({ ...freshEvidence, + const merged = freshEvidence?.sources.length ? normalizeTaskEvidence({ ...freshEvidence, + omittedSources: [...(prior?.evidence?.omittedSources ?? []), ...(freshEvidence.omittedSources ?? [])], // Two captures of one command (the per-call hook and the end-of-turn // transcript, or a rerun) are one observation: the newest replaces the older. // Differing versions of a file are kept so they can be reconciled. sources: preferFileSources([...freshEvidence.sources, ...(prior?.evidence?.sources ?? []).filter(s => !freshEvidence.sources.some(n => n.sha256 === s.sha256 || (s.source.startsWith("$ ") && commandOf(n.source) === commandOf(s.source))))]), }) : prior?.evidence ?? freshEvidence; + // The newest capture's git state describes the tree this checkpoint now reflects. + const workspace = freshEvidence?.workspace ?? prior?.evidence?.workspace; + const evidence = merged && workspace && merged.workspace !== workspace ? { ...merged, workspace } : merged; const entries = old.filter((entry) => !sameTurn(entry)); entries.push(fitCheckpoint({ ...next, goal: next.goal.slice(0, HOT_REQUEST_LIMIT), ...(next.goalTruncated || next.goal.length > HOT_REQUEST_LIMIT ? { goalTruncated: true } : {}), @@ -233,6 +246,8 @@ export const selectHotCheckpoints = ( const evidence = evidenceEntries.length ? normalizeTaskEvidence({ version: 1, coverage: evidenceEntries.some(e => e.coverage === "bounded") ? "bounded" : "unavailable", omitted: Math.max(...evidenceEntries.map(e => e.omitted)), sources: evidenceEntries.flatMap(e => e.sources), + omittedSources: evidenceEntries.flatMap(e => e.omittedSources ?? []).reverse(), + workspace: evidenceEntries.find(e => e.workspace)?.workspace, }) : undefined; const seen = new Set([latest.summary]); const earlierFindings = entries.slice(1).filter(entry => { @@ -292,7 +307,15 @@ export const renderHotCheckpointPointer = (entry: SelectedHotCheckpoint, readCom 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 => { +/** Where the reader is now, so saved state can be compared with it. */ +export type HotRenderWorkspace = { root: string; git: WorkspaceGitState | null; memo?: Map }; +const memoized = (here: HotRenderWorkspace, key: string, compute: () => string): string => { + here.memo ??= new Map(); + if (!here.memo.has(key)) here.memo.set(key, compute()); + return here.memo.get(key)!; +}; + +export const renderHotCheckpoints = (entries: SelectedHotCheckpoint[], maxLength = HOT_CONTEXT_LIMIT, here?: HotRenderWorkspace): string => { if (entries.length === 0) return ""; let remaining = maxLength; const parts: string[] = []; @@ -302,7 +325,8 @@ export const renderHotCheckpoints = (entries: SelectedHotCheckpoint[], maxLength // 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`; + const drift = here ? memoized(here, `drift:${JSON.stringify(entry.evidence?.workspace ?? null)}`, () => describeWorkspaceDrift(entry.evidence?.workspace, here.git, here.root)) : ""; + const heading = `${entry.origin === "remember" ? "Explicitly saved memory" : "Hot memory findings"} (${entry.runtime}):\n${drift ? `${drift}\n` : ""}`; // Every selected task gets room; one large history must not silently erase // another selected amendment or task. Unused space flows to later entries. const available = Math.floor(remaining / (entries.length - index)) - heading.length - 1; @@ -316,7 +340,8 @@ export const renderHotCheckpoints = (entries: SelectedHotCheckpoint[], maxLength // may crowd the other out: the finding keeps up to 45% when both are large. 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 evidence = entry.evidence?.sources.length ? renderTaskEvidence(entry.evidence, Math.max(0, shared - findingReserve), entry.goal, + here ? { workspaceRoot: here.root, head: here.git?.head ?? null, fileState: (file, excerpt) => memoized(here, `file:${file}\0${excerpt.slice(0, 1500)}`, () => fileExcerptState(here.root, file, excerpt)) as "missing" | "changed" | "same" } : undefined) : ""; 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); diff --git a/src/runtime/task-evidence.ts b/src/runtime/task-evidence.ts index fb44178..62b2eb9 100644 --- a/src/runtime/task-evidence.ts +++ b/src/runtime/task-evidence.ts @@ -1,6 +1,7 @@ import { createHash } from "crypto"; import { closeSync, fstatSync, openSync, readdirSync, readSync, realpathSync, statSync, readFileSync } from "fs"; import path from "path"; +import { normalizeWorkspaceGitState, sourceFilePath, type WorkspaceGitState } from "./workspace-state"; // Evidence is a quote of an observed source, never a verified claim or a new // instruction. Keep it separate from the assistant's (possibly lossy) finding. @@ -10,13 +11,21 @@ export type TaskSource = { sha256: string; truncated: boolean; observedAt?: string; + /** For command output: the commit it ran at and whether the tree had uncommitted changes. */ + head?: string; + dirty?: boolean; }; export type TaskEvidence = { version: 1; sources: TaskSource[]; coverage: "bounded" | "unavailable"; omitted: number; + /** Sources dropped to fit a bound: their names and digests, without the text. */ + omittedSources?: Array<{ source: string; sha256: string }>; + /** Git state of the workspace when this evidence was captured. */ + workspace?: WorkspaceGitState; }; +const MAX_OMITTED_SOURCES = 8; const MAX_BYTES = 4 * 1024 * 1024; // A checkpoint's request, finding and serialized evidence must together stay @@ -218,6 +227,7 @@ export const normalizeTaskEvidence = (value: unknown): TaskEvidence | undefined let remaining = MAX_TOTAL_CHARS; let omitted = Math.max(0, Math.min(100000, Number(item.omitted) || 0)); const sources: TaskSource[] = []; + const dropped: Array<{ source: string; sha256: string }> = []; for (const raw of item.sources) { const s = object(raw), content = text(s?.text).trim(), source = text(s?.source).slice(0, 1000); if (!content || !source || sensitive.test(source)) continue; @@ -228,13 +238,28 @@ export const normalizeTaskEvidence = (value: unknown): TaskEvidence | undefined if (s?.truncated !== true && suppliedHash && suppliedHash !== digest(content)) { omitted++; continue; } const sha256 = /^[a-f0-9]{64}$/.test(suppliedHash) ? suppliedHash : digest(content); if (sources.some(old => old.sha256 === sha256)) continue; - if (sources.length >= MAX_SOURCES || remaining < 200) { omitted++; continue; } + if (sources.length >= MAX_SOURCES || remaining < 200) { omitted++; dropped.push({ source, sha256 }); continue; } sources.push({ source, text: kept, sha256, truncated: s?.truncated === true || kept.length < content.length, ...(typeof s?.observedAt === "string" && Number.isFinite(Date.parse(s.observedAt)) ? { observedAt: s.observedAt } : {}), + ...(source.startsWith("$ ") && typeof s?.head === "string" && /^[a-f0-9]{40}(?:[a-f0-9]{24})?$/.test(s.head) ? { head: s.head } : {}), + ...(source.startsWith("$ ") && typeof s?.dirty === "boolean" ? { dirty: s.dirty } : {}), }); remaining -= kept.length; } - return { version: 1, sources, coverage: item.coverage === "unavailable" ? "unavailable" : "bounded", omitted }; + const omittedSources = [...(Array.isArray(item.omittedSources) ? item.omittedSources : []), ...dropped].flatMap(raw => { + const entry = object(raw), source = text(entry?.source).slice(0, 160), sha256 = text(entry?.sha256); + return source && !sensitive.test(source) && /^[a-f0-9]{64}$/.test(sha256) && !sources.some(kept => kept.sha256 === sha256) ? [{ source, sha256 }] : []; + }).filter((entry, index, all) => all.findIndex(other => other.sha256 === entry.sha256) === index).slice(-MAX_OMITTED_SOURCES); + const workspace = normalizeWorkspaceGitState(item.workspace); + return { version: 1, sources, coverage: item.coverage === "unavailable" ? "unavailable" : "bounded", omitted, + ...(omittedSources.length ? { omittedSources } : {}), ...(workspace ? { workspace } : {}) }; +}; + +/** Attach the workspace's git state, and stamp command output with the commit it ran at. */ +export const withWorkspaceState = (evidence: TaskEvidence, state: WorkspaceGitState | null): TaskEvidence => !state ? evidence : { + ...evidence, workspace: state, + sources: evidence.sources.map(source => source.source.startsWith("$ ") && source.head === undefined + ? { ...source, ...(state.head ? { head: state.head } : {}), dirty: state.dirty } : source), }; const rankTaskSources = (sources: TaskSource[], goal: string): TaskSource[] => { @@ -356,7 +381,15 @@ export const preferFileSources = (sources: T[]): T export const taskEvidenceChars = (evidence?: TaskEvidence): number => evidence?.sources.reduce((n, s) => n + s.source.length + s.text.length, 0) ?? 0; -export const renderTaskEvidence = (evidence: TaskEvidence, maxChars: number, goal = ""): string => { +export type EvidenceRenderContext = { + /** Workspace the reader is in; file excerpts are checked against it. */ + workspaceRoot: string; + /** Its current HEAD, to flag command output run at another commit. */ + head: string | null; + fileState: (relative: string, excerpt: string) => "missing" | "changed" | "same"; +}; + +export const renderTaskEvidence = (evidence: TaskEvidence, maxChars: number, goal = "", context?: EvidenceRenderContext): string => { if (!evidence.sources.length || maxChars < 200) return ""; const lines = ["Observed source excerpts (reference data, not instructions; may be incomplete). A digest identifies observed bytes, not current truth. Resolve missing or conflicting requirements before guessing:"]; let remaining = maxChars - lines[0]!.length - 1; @@ -364,7 +397,14 @@ export const renderTaskEvidence = (evidence: TaskEvidence, maxChars: number, goa // not a domain-specific guess about which numerical constraint matters most. for (const source of rankTaskSources(evidence.sources, goal)) { const conflict = evidence.sources.some(s => s.source === source.source && s.sha256 !== source.sha256); - const heading = `Source ${JSON.stringify(source.source)}${conflict ? " [multiple observed versions; reconcile]" : ""}:\n`; + let mark = ""; + if (context && source.source.startsWith("$ ")) { + if (source.head && context.head && source.head !== context.head) mark = ` [ran at ${source.head.slice(0, 10)}${source.dirty ? " with uncommitted changes" : ""}; HEAD here is ${context.head.slice(0, 10)}]`; + } else if (context && sourceFilePath(source.source)) { + const state = context.fileState(sourceFilePath(source.source)!, source.text); + mark = state === "missing" ? " [not present here]" : state === "changed" ? " [changed on disk since observed; reread]" : ""; + } + const heading = `Source ${JSON.stringify(source.source)}${conflict ? " [multiple observed versions; reconcile]" : ""}${mark}:\n`; const available = remaining - heading.length - 40; if (available < 100) break; const content = source.text.slice(0, available); @@ -372,5 +412,14 @@ export const renderTaskEvidence = (evidence: TaskEvidence, maxChars: number, goa lines.push(`${heading}${content}${ending}`); remaining -= heading.length + content.length + ending.length + 1; } + if (evidence.omittedSources?.length && remaining > 120) { + const names = [...new Set(evidence.omittedSources.map(entry => entry.source))]; + let line = "Also observed but not kept (reread if needed):"; + for (const name of names) { + if (line.length + name.length + 3 > Math.min(remaining, 600)) { line += " ..."; break; } + line += ` ${JSON.stringify(name)}`; + } + lines.push(line); + } return lines.join("\n"); }; diff --git a/src/runtime/workspace-state.ts b/src/runtime/workspace-state.ts new file mode 100644 index 0000000..58b564f --- /dev/null +++ b/src/runtime/workspace-state.ts @@ -0,0 +1,174 @@ +import { createHash } from "crypto"; +import { execFileSync } from "child_process"; +import { closeSync, constants, fstatSync, lstatSync, openSync, readSync, realpathSync } from "fs"; +import path from "path"; + +// The git state a checkpoint was written in. When the checkpoint is shown in +// another checkout, on another machine or after the tree moved on, the reader +// is told what differs instead of trusting results observed on other bytes. +// Warning only: nothing here restores or rewrites a file. +export type WorkspaceGitState = { + head: string | null; + branch: string | null; + dirty: boolean; + /** Untracked files at capture, with content hashes (bounded). */ + untracked: Array<{ path: string; sha256: string | null }>; + untrackedOmitted?: number; +}; + +const GIT_TIMEOUT_MS = 1500; +const MAX_UNTRACKED = 10; +const MAX_PATH_CHARS = 160; +const MAX_HASH_BYTES = 512 * 1024; +const MAX_EXCERPT_FILE_BYTES = 1024 * 1024; +const MAX_DRIFT_CHARS = 320; +const SHA = /^[a-f0-9]{40}(?:[a-f0-9]{24})?$/; +// Never record names that look like secrets or private host state. +// Untracked names are synced, so this errs toward leaving names out. +const privateName = /(?:^|[/\\.'"_-])(?:env|envrc|secrets?|credentials?|creds?|tokens?|passwords?|passwd|id_rsa|id_ed25519|id_ecdsa|nsec|npmrc|pypirc|netrc|pgpass|htpasswd|kubeconfig)(?:$|[/\\.'"_-])|\.(?:pem|key|p12|pfx|jks|keystore|tfvars|tfstate|ovpn|asc|gpg|kdbx)\b|(?:^|\/)\.(?:git|claude|codex|crosshead|onlybots|ssh|aws|gnupg|kube|docker|azure|gcloud|config)(?:\/|$)/i; +/** A workspace-relative path that stays inside the workspace by its text. */ +const safeRelative = (file: string): boolean => + Boolean(file) && !file.includes("\0") && !path.isAbsolute(file) && !file.split(/[/\\]/).includes(".."); +/** Regular file inside the real workspace root (no symlink escape), or null. */ +const containedFile = (root: string, relative: string): string | null => { + if (!safeRelative(relative)) return null; + try { + const realRoot = realpathSync(root); + const file = path.join(realRoot, relative); + if (!lstatSync(file).isFile()) return null; + const real = realpathSync(file); + const inside = path.relative(realRoot, real); + return inside && !inside.startsWith("..") && !path.isAbsolute(inside) ? real : null; + } catch { return null; } +}; +const exists = (root: string, relative: string): boolean => { + if (!safeRelative(relative)) return false; + try { lstatSync(path.join(root, relative)); return true; } catch { return false; } +}; +/** Read a regular file without following a final symlink or blocking on a FIFO. */ +const readRegular = (file: string, limit: number): Buffer | null => { + let fd: number | undefined; + try { + fd = openSync(file, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0) | (constants.O_NONBLOCK ?? 0)); + const stat = fstatSync(fd); + if (!stat.isFile() || stat.size > limit) return null; + const buffer = Buffer.alloc(stat.size); + readSync(fd, buffer, 0, stat.size, 0); + return buffer; + } catch { return null; } finally { if (fd !== undefined) closeSync(fd); } +}; + +const hashFile = (root: string, relative: string): string | null => { + const file = containedFile(root, relative); + const buffer = file ? readRegular(file, MAX_HASH_BYTES) : null; + return buffer ? createHash("sha256").update(buffer).digest("hex") : null; +}; + +/** Current git state of a workspace, or null when it is not a git checkout, git is missing or too slow. */ +export const readWorkspaceGitState = (workspaceRoot: string): WorkspaceGitState | null => { + let output: string; + try { + output = execFileSync("git", ["-C", workspaceRoot, "status", "--porcelain=v2", "--branch", "-z", "--untracked-files=normal"], { + encoding: "utf8", timeout: GIT_TIMEOUT_MS, stdio: ["ignore", "pipe", "ignore"], maxBuffer: 4 * 1024 * 1024, + env: { ...process.env, GIT_OPTIONAL_LOCKS: "0" }, + }); + } catch { return null; } + let root: string; + try { root = realpathSync(workspaceRoot); } catch { root = workspaceRoot; } + let head: string | null = null, branch: string | null = null, dirty = false; + const untracked: WorkspaceGitState["untracked"] = []; + let untrackedOmitted = 0; + for (const record of output.split("\0")) { + if (record.startsWith("# branch.oid ")) { const oid = record.slice(13).trim(); head = SHA.test(oid) ? oid : null; } + else if (record.startsWith("# branch.head ")) { const name = record.slice(14).trim(); branch = name && name !== "(detached)" ? name.slice(0, 200) : null; } + else if (record.startsWith("? ")) { + dirty = true; + const file = record.slice(2); + if (privateName.test(file)) { untrackedOmitted++; continue; } + if (untracked.length >= MAX_UNTRACKED || file.length > MAX_PATH_CHARS || !safeRelative(file)) { untrackedOmitted++; continue; } + untracked.push({ path: file, sha256: hashFile(root, file) }); + } else if (/^[12u] /.test(record)) dirty = true; + } + return { head, branch, dirty, untracked, ...(untrackedOmitted ? { untrackedOmitted } : {}) }; +}; + +export const normalizeWorkspaceGitState = (value: unknown): WorkspaceGitState | undefined => { + if (!value || typeof value !== "object" || Array.isArray(value)) return undefined; + const item = value as Record; + const head = typeof item.head === "string" && SHA.test(item.head) ? item.head : null; + const branch = typeof item.branch === "string" && item.branch ? item.branch.slice(0, 100) : null; + const untracked = (Array.isArray(item.untracked) ? item.untracked : []).flatMap(entry => { + const file = entry && typeof entry === "object" ? entry as Record : null; + // A synced checkpoint may come from anywhere: only plain workspace-relative names. + if (typeof file?.path !== "string" || file.path.length > MAX_PATH_CHARS || !safeRelative(file.path) || privateName.test(file.path)) return []; + return [{ path: file.path, sha256: typeof file.sha256 === "string" && /^[a-f0-9]{64}$/.test(file.sha256) ? file.sha256 : null }]; + }).slice(0, MAX_UNTRACKED); + const omitted = Number(item.untrackedOmitted); + if (!head && !branch && item.dirty !== true && !untracked.length) return undefined; + return { head, branch, dirty: item.dirty === true, untracked, + ...(Number.isSafeInteger(omitted) && omitted > 0 ? { untrackedOmitted: Math.min(omitted, 100000) } : {}) }; +}; + +const short = (sha: string | null): string => sha ? sha.slice(0, 10) : "an unknown commit"; +const where = (state: WorkspaceGitState): string => `${short(state.head)}${state.branch ? ` on ${state.branch}` : ""}`; + +/** + * One line naming what differs between the tree a checkpoint was written in and + * the tree here now, or "" when nothing differs or nothing can be compared. + * `current` null means this workspace is not a readable git checkout. + */ +/** Whether a file excerpt still appears in the file on disk: "missing", "changed" or "same". */ +export const fileExcerptState = (workspaceRoot: string, relative: string, excerpt: string): "missing" | "changed" | "same" => { + if (!safeRelative(relative)) return "same"; + if (!exists(workspaceRoot, relative)) return "missing"; + const file = containedFile(workspaceRoot, relative); + const buffer = file ? readRegular(file, MAX_EXCERPT_FILE_BYTES) : null; + // Unreadable, too large, or not a regular file: nothing can be said. + if (!buffer) return "same"; + // Compare a bounded prefix of the excerpt: hosts strip gutters and may cut the end. + const probe = excerpt.trim().slice(0, 1500).replace(/\s+/g, " "); + return buffer.toString("utf8").replace(/\s+/g, " ").includes(probe) ? "same" : "changed"; +}; + +/** + * The file a source names, or null when it names none plainly: a path, or a + * single cat/head/tail/sed read whose last argument is the file. + */ +export const sourceFilePath = (source: string): string | null => { + if (source.startsWith("$ ")) return null; + if (!/\s/.test(source)) return safeRelative(source) ? source : null; + if (/[;&|<>`$]/.test(source) || !/^(?:cat|head|tail|sed)\s/.test(source)) return null; + const tokens = source.match(/'[^']*'|"[^"]*"|\S+/g) ?? []; + const last = (tokens[tokens.length - 1] ?? "").replace(/^['"]|['"]$/g, ""); + return tokens.length > 1 && !last.startsWith("-") && /[./]/.test(last) && safeRelative(last) ? last : null; +}; + +export const describeWorkspaceDrift = (then: WorkspaceGitState | undefined, current: WorkspaceGitState | null, workspaceRoot: string | null): string => { + if (!then) return ""; + const notes: string[] = []; + if (!current) { + if (then.head) notes.push(`written at ${where(then)}; no git checkout is readable here`); + } else { + const moved = Boolean(then.head && current.head && then.head !== current.head); + if (moved) notes.push(`written at ${where(then)}; now ${where(current)}`); + else if (then.branch && current.branch && then.branch !== current.branch) notes.push(`written on ${then.branch}; now on ${current.branch}`); + // Same commit and still uncommitted changes here is the same working tree as far as git can tell. + if (then.dirty && (moved || !current.dirty)) notes.push("written with uncommitted changes that are not in this tree, so results observed then may not hold here"); + if (workspaceRoot) { + const missing: string[] = [], changed: string[] = []; + for (const file of then.untracked) { + if (!exists(workspaceRoot, file.path)) { missing.push(file.path); continue; } + // Only a hash taken at capture can show a change; otherwise presence is all that is known. + if (!file.sha256) continue; + const now = hashFile(workspaceRoot, file.path); + if (now !== null && now !== file.sha256) changed.push(file.path); + } + const list = (files: string[]): string => files.slice(0, 3).join(", ") + (files.length > 3 ? ` and ${files.length - 3} more` : ""); + if (missing.length) notes.push(`untracked ${list(missing)} ${missing.length === 1 ? "is" : "are"} not present here`); + if (changed.length) notes.push(`untracked ${list(changed)} changed since then`); + } + } + if (!notes.length) return ""; + const line = `Workspace drift (warning only; reread before relying on saved results): ${notes.join("; ")}.`; + return line.length <= MAX_DRIFT_CHARS ? line : `${line.slice(0, MAX_DRIFT_CHARS - 3)}...`; +}; diff --git a/tests/runtime/workspace-state.test.ts b/tests/runtime/workspace-state.test.ts new file mode 100644 index 0000000..60587be --- /dev/null +++ b/tests/runtime/workspace-state.test.ts @@ -0,0 +1,242 @@ +import { execFileSync } from "node:child_process"; +import { mkdirSync, mkdtempSync, rmSync, symlinkSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { afterEach, describe, expect, it } from "vitest"; + +import { renderHotCheckpoints, updateHotCheckpoints, selectHotCheckpoints, type HotContinuityCheckpoint } from "../../src/runtime/hot-continuity"; +import { normalizeTaskEvidence, withWorkspaceState, type TaskEvidence } from "../../src/runtime/task-evidence"; +import { describeWorkspaceDrift, fileExcerptState, normalizeWorkspaceGitState, readWorkspaceGitState, sourceFilePath } from "../../src/runtime/workspace-state"; +import { buildCapturedContinuityContext, normalizeCapturedContextToContinuityIr, validateContinuityIr } from "../../src/runtime/continuity-ir"; +import { RuntimeLifecycleManager } from "../../src/runtime/lifecycle-engine"; +import { buildContinuityGovernorState } from "../../src/runtime/continuity-governor"; +import { buildDefaultContinuityPolicy } from "../../src/runtime/continuity-policy"; +import { HANDOFF_IMPORT_COMMAND } from "../../src/runtime/handoff-import"; +import { validHotSyncDocument, HOT_SYNC_VERSION } from "../../src/protocol/hot-sync"; +import { retainHotSync } from "../../src/runtime/hot-sync-replica"; +import { chmodSync } from "node:fs"; +import { vi } from "vitest"; +import { generateSecretKey, getPublicKey, nip19 } from "nostr-tools"; +import { readLocalHotMemory } from "../../src/runtime/local-hot-memory"; + +const dirs: string[] = []; +afterEach(() => { for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true }); }); +const git = (root: string, ...args: string[]): string => + execFileSync("git", ["-C", root, "-c", "user.email=t@example.invalid", "-c", "user.name=t", ...args], { encoding: "utf8" }).trim(); +const repo = (): string => { + const root = mkdtempSync(path.join(tmpdir(), "crosshead-git-state-")); + dirs.push(root); + git(root, "init", "-q", "-b", "main"); + writeFileSync(path.join(root, "rules.md"), "Batches hold 37 items.\n"); + git(root, "add", "rules.md"); + git(root, "commit", "-q", "-m", "init"); + return root; +}; +const evidence = (sources: TaskEvidence["sources"] = []): TaskEvidence => ({ version: 1, sources, coverage: "bounded", omitted: 0 }); +const checkpoint = (ev: TaskEvidence): HotContinuityCheckpoint => ({ + runtime: "codex", workspaceId: "repo:/w", sessionId: "s", turnId: "t", goal: "Fix parcel batching", summary: "Tests passed.", occurredAt: "2026-11-23T00:00:00.000Z", evidence: ev, +}); + +describe("checkpoint git state", () => { + it("records head, branch, dirty and untracked files, and skips private names", () => { + const root = repo(); + writeFileSync(path.join(root, "scripts.py"), "print(1)\n"); + writeFileSync(path.join(root, ".env"), "TOKEN=x\n"); + const state = readWorkspaceGitState(root)!; + expect(state.head).toBe(git(root, "rev-parse", "HEAD")); + expect(state.branch).toBe("main"); + expect(state.dirty).toBe(true); + expect(state.untracked.map(file => file.path)).toEqual(["scripts.py"]); + expect(state.untracked[0]!.sha256).toMatch(/^[a-f0-9]{64}$/); + expect(state.untrackedOmitted).toBe(1); + expect(normalizeWorkspaceGitState(JSON.parse(JSON.stringify(state)))).toEqual(state); + }); + + it("returns null outside git and never throws", () => { + const plain = mkdtempSync(path.join(tmpdir(), "crosshead-no-git-")); + dirs.push(plain); + expect(readWorkspaceGitState(plain)).toBeNull(); + expect(readWorkspaceGitState(path.join(plain, "missing"))).toBeNull(); + }); + + it("says nothing in the same checkout and one line after the tree moves", () => { + const root = repo(); + writeFileSync(path.join(root, "tool.py"), "print(1)\n"); + const then = readWorkspaceGitState(root)!; + expect(describeWorkspaceDrift(then, readWorkspaceGitState(root), root)).toBe(""); + rmSync(path.join(root, "tool.py")); + writeFileSync(path.join(root, "rules.md"), "Batches hold 43 items.\n"); + git(root, "commit", "-q", "-am", "change"); + const line = describeWorkspaceDrift(then, readWorkspaceGitState(root), root); + expect(line.split("\n")).toHaveLength(1); + expect(line).toContain(`written at ${then.head!.slice(0, 10)} on main; now ${git(root, "rev-parse", "HEAD").slice(0, 10)}`); + expect(line).toContain("untracked tool.py is not present here"); + expect(line).toContain("uncommitted changes that are not in this tree"); + }); + + it("marks command output run at another commit and file excerpts that changed, in rendered checkpoints", () => { + const root = repo(); + const state = readWorkspaceGitState(root)!; + const stamped = withWorkspaceState(normalizeTaskEvidence(evidence([ + { source: "rules.md", text: "Batches hold 37 items.", sha256: "", truncated: false }, + { source: "$ npm test", text: "42 passing", sha256: "", truncated: false }, + ]))!, state); + expect(stamped.sources[1]!.head).toBe(state.head); + expect(stamped.sources[0]!.head).toBeUndefined(); + const stored = updateHotCheckpoints([], checkpoint(stamped)); + expect(stored[0]!.evidence!.workspace).toEqual(state); + const same = renderHotCheckpoints(selectHotCheckpoints({ scope: "all", scopes: [{ scope: "codex", content: JSON.stringify({ continuityCheckpoints: stored }) }] }, "parcel batching"), 4200, { root, git: readWorkspaceGitState(root) }); + expect(same).not.toContain("Workspace drift"); + expect(same).not.toContain("[changed on disk"); + expect(same).not.toContain("[ran at"); + writeFileSync(path.join(root, "rules.md"), "Batches hold 43 items.\n"); + git(root, "commit", "-q", "-am", "change"); + const moved = renderHotCheckpoints(stored, 4200, { root, git: readWorkspaceGitState(root) }); + expect(moved).toContain("Workspace drift"); + expect(moved).toContain('Source "rules.md" [changed on disk since observed; reread]'); + expect(moved).toContain(`Source "$ npm test" [ran at ${state.head!.slice(0, 10)}`); + }); + + it("keeps the latest git state when a later capture has no sources, and names dropped sources", () => { + const first = normalizeTaskEvidence({ ...evidence([{ source: "a.md", text: "alpha", sha256: "", truncated: false }]), workspace: { head: "a".repeat(40), branch: "main", dirty: false, untracked: [] } })!; + const later = { ...evidence(), workspace: { head: "b".repeat(40), branch: "main", dirty: false, untracked: [] } }; + const stored = updateHotCheckpoints(updateHotCheckpoints([], checkpoint(first)), { ...checkpoint(later), turnId: "t" }); + expect(stored[0]!.evidence!.workspace!.head).toBe("b".repeat(40)); + expect(stored[0]!.evidence!.sources[0]!.source).toBe("a.md"); + const many = normalizeTaskEvidence(evidence(Array.from({ length: 12 }, (_, i) => ({ source: `f${i}.md`, text: `body ${i}`, sha256: "", truncated: false }))))!; + expect(many.omittedSources?.map(entry => entry.source)).toEqual(["f10.md", "f11.md"]); + expect(renderHotCheckpoints([checkpoint(many)])).toContain('Also observed but not kept (reread if needed): "f10.md" "f11.md"'); + }); + + it("older clients' evidence without git state still renders without drift lines", () => { + const old = normalizeTaskEvidence({ version: 1, coverage: "bounded", omitted: 0, sources: [{ source: "x.md", text: "x", sha256: "", truncated: false }] })!; + expect(old.workspace).toBeUndefined(); + expect(renderHotCheckpoints([checkpoint(old)], 4200, { root: "/nonexistent-root", git: null })).not.toContain("Workspace drift"); + }); + + it("emits nothing in the same checkout for shell-read sources, unhashed untracked entries and large files", () => { + const root = repo(); + const outside = mkdtempSync(path.join(tmpdir(), "crosshead-outside-")); + dirs.push(outside); + mkdirSync(path.join(outside, "lib")); + symlinkSync(path.join(outside, "lib"), path.join(root, "linked")); + writeFileSync(path.join(root, "big.bin"), Buffer.alloc(600 * 1024, 1)); + const then = readWorkspaceGitState(root)!; + expect(then.untracked.find(file => file.path.startsWith("linked"))?.sha256 ?? null).toBeNull(); + expect(describeWorkspaceDrift(then, readWorkspaceGitState(root), root)).toBe(""); + const stored = updateHotCheckpoints([], checkpoint(withWorkspaceState(normalizeTaskEvidence(evidence([ + { source: "sed -n 1,5p rules.md", text: "Batches hold 37 items.", sha256: "", truncated: false }, + { source: "head -n 3 rules.md && cat other.md", text: "Batches hold 37 items.\nother", sha256: "", truncated: false }, + ]))!, then))); + const same = renderHotCheckpoints(stored, 4200, { root, git: readWorkspaceGitState(root) }); + expect(same).not.toContain("[not present here]"); + expect(same).not.toContain("Workspace drift"); + expect(sourceFilePath("sed -n 1,5p rules.md")).toBe("rules.md"); + expect(sourceFilePath("head -n 3 rules.md && cat other.md")).toBeNull(); + expect(sourceFilePath("src/a.ts")).toBe("src/a.ts"); + expect(sourceFilePath("../etc/passwd")).toBeNull(); + }); + + it("rejects synced paths that leave the workspace and never reads through them", () => { + const root = repo(); + const normalized = normalizeWorkspaceGitState({ head: "a".repeat(40), branch: "main", dirty: true, untracked: [ + { path: "../../../../etc/hostname", sha256: "b".repeat(64) }, { path: "/etc/hostname", sha256: null }, + { path: "ok.py", sha256: null }, { path: "x\0y", sha256: null }, { path: "deploy/.env.production", sha256: null }, + ] })!; + expect(normalized.untracked.map(file => file.path)).toEqual(["ok.py"]); + expect(fileExcerptState(root, "../../../../etc/hostname", "x")).toBe("same"); + const outside = mkdtempSync(path.join(tmpdir(), "crosshead-outside-")); + dirs.push(outside); + writeFileSync(path.join(outside, "secret.txt"), "outside bytes"); + symlinkSync(path.join(outside, "secret.txt"), path.join(root, "escape.txt")); + expect(fileExcerptState(root, "escape.txt", "different")).toBe("same"); + }); + + it("does not block on a FIFO", () => { + const root = repo(); + execFileSync("mkfifo", [path.join(root, "pipe.txt")]); + const started = Date.now(); + expect(fileExcerptState(root, "pipe.txt", "x")).toBe("same"); + const state = readWorkspaceGitState(root)!; + expect(describeWorkspaceDrift(state, state, root)).toBe(""); + expect(Date.now() - started).toBeLessThan(3000); + }); + + it("returns null quickly when git is not on PATH", () => { + const root = repo(); + const saved = process.env.PATH; + process.env.PATH = "/nonexistent"; + try { expect(readWorkspaceGitState(root)).toBeNull(); } finally { process.env.PATH = saved; } + }); + + it("keeps a large checkpoint with metadata under the sync budget and the drift line short", () => { + const sources = Array.from({ length: 10 }, (_, i) => ({ source: `src/file-${i}.ts`, text: `line ${i}\n`.repeat(900), sha256: "", truncated: false })); + const workspace = { head: "a".repeat(40), branch: "b".repeat(100), dirty: true, + untracked: Array.from({ length: 10 }, (_, i) => ({ path: `${"d".repeat(140)}/${i}.py`, sha256: null })) }; + const ev = normalizeTaskEvidence({ ...evidence(sources), workspace, omittedSources: Array.from({ length: 8 }, (_, i) => ({ source: `${"n".repeat(150)}${i}`, sha256: String(i).repeat(64) })) })!; + const [stored] = updateHotCheckpoints([], { ...checkpoint(ev), goal: "g".repeat(6000), summary: "s".repeat(12000) }); + expect(stored!.goal.length + stored!.summary.length + JSON.stringify(stored!.evidence).length).toBeLessThanOrEqual(29000); + const line = describeWorkspaceDrift(stored!.evidence!.workspace ?? workspace, { head: "c".repeat(40), branch: "x".repeat(100), dirty: false, untracked: [] }, "/nonexistent-root"); + expect(line.length).toBeLessThanOrEqual(320); + }); + + it("gives up on a slow git within its timeout and records nothing", () => { + const root = repo(); + const bin = mkdtempSync(path.join(tmpdir(), "crosshead-slow-git-")); + dirs.push(bin); + writeFileSync(path.join(bin, "git"), "#!/bin/sh\nsleep 5\n"); + chmodSync(path.join(bin, "git"), 0o755); + const saved = process.env.PATH; + process.env.PATH = `${bin}:${saved}`; + const started = Date.now(); + try { expect(readWorkspaceGitState(root)).toBeNull(); } finally { process.env.PATH = saved; } + expect(Date.now() - started).toBeLessThan(3000); + }); + + it("round-trips git state through a synced document that older clients also accept", () => { + const evidence = { version: 1, coverage: "bounded", omitted: 0, sources: [], workspace: { head: "a".repeat(40), branch: "main", dirty: false, untracked: [{ path: "tool.py", sha256: null }] } }; + const document = { version: HOT_SYNC_VERSION, namespace: "n", scope: "s", epoch: 0, checkpoints: [{ + id: "c1", deviceId: "d", runtime: "codex", workspaceId: "repo:/w", occurredAt: "2026-11-23T00:00:00.000Z", goal: "g", summary: "s", evidence, + }] }; + // The wire validator treats evidence as opaque, so a document from this client validates for older ones. + expect(validHotSyncDocument(document)).toBe(true); + const kept = retainHotSync(document as never); + expect(kept.checkpoints[0]!.evidence).toEqual(evidence); + expect(normalizeTaskEvidence(kept.checkpoints[0]!.evidence)?.workspace?.head).toBe("a".repeat(40)); + }); + + it("carries the exporting workspace's git state through a handoff capsule into the imported checkpoint", async () => { + const root = repo(); + const captured = buildCapturedContinuityContext({ runtime: "codex", workspaceRoot: root, workspaceId: "repo:w", sessionId: "s", turnId: "t", + prompt: "Continue", transcript: [{ role: "user", content: "Continue" }], task: { objective: "Continue", openLoops: [] } }); + writeFileSync(path.join(root, "customer-export.csv"), "private\n"); + // Not carried unless the caller opts in (deal handoffs to another party never do). + expect(normalizeCapturedContextToContinuityIr(captured, "claude-code").ir.provenance.workspace).toBeUndefined(); + const ir = normalizeCapturedContextToContinuityIr(captured, "claude-code", { workspaceState: true }).ir; + expect(validateContinuityIr(ir)).toEqual([]); + expect(ir.provenance.workspace?.head).toBe(git(root, "rev-parse", "HEAD")); + expect(ir.provenance.workspace?.dirty).toBe(true); + // A capsule leaves the machine: no untracked names or hashes. + expect(ir.provenance.workspace?.untracked).toEqual([]); + expect(JSON.stringify(ir)).not.toContain("customer-export"); + + const state = mkdtempSync(path.join(tmpdir(), "crosshead-import-state-")); + dirs.push(state); + vi.stubEnv("CROSSHEAD_HOT_SYNC_ENABLED", "false"); + const key = generateSecretKey(), npub = nip19.npubEncode(getPublicKey(key)), nsec = nip19.nsecEncode(key); + const manager = new RuntimeLifecycleManager({ + paths: { state }, hotWriteDebounceMs: 0, loadDefaultProfileName: () => "default", + loadProfile: () => ({ name: "default", apiBase: "http://127.0.0.1:0", npub, memoryMode: "assist", features: { coldSync: false, autoWarmPromotion: false } }), + loadSecret: () => ({ nsec, session: null }), saveSecret: () => {}, loadHealth: () => ({ queueDepth: 0, lastSuccessfulSyncAt: null, lastError: null }), saveHealth: () => {}, + loadContinuityGovernorState: () => buildContinuityGovernorState(buildDefaultContinuityPolicy(), []), writeLog: () => {}, + } as never); + try { + await manager.handleEvent({ eventId: "import-1", runtime: "claude-code", type: "operator.command", workspaceId: "repo:/elsewhere", sessionId: "import", + payload: { command: HANDOFF_IMPORT_COMMAND, goal: "Imported handoff", content: "Imported handoff text.", handoffTurnId: "handoff-x", + taskEvidence: { version: 1, sources: [], coverage: "unavailable", omitted: 0, workspace: ir.provenance.workspace } } }); + const stored = JSON.stringify(readLocalHotMemory(state, "all", { name: "default", apiBase: "http://127.0.0.1:0", npub } as never)); + expect(stored).toContain("handoff-x"); + expect(stored).toContain(ir.provenance.workspace!.head!); + } finally { await manager.stop(); vi.unstubAllEnvs(); } + }); +});