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
7 changes: 6 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -230,7 +230,12 @@ a fresh session after choosing either setting.
`--allow-stale`.
- Imported text is labelled as an imported handoff, not as something you saved
yourself. It is not promoted to warm memory. Until the project records newer
work (and for at most seven days) it is included in every prompt there.
work (and for at most seven days) it is offered to every session there.
- Within one Claude Code or Codex session, a checkpoint is sent once, not on
every prompt. It is sent again after compaction or when the checkpoint
changes. After a session's first prompt, a checkpoint that shares no words
with the prompt is shown only as a one-line pointer with the command that
reads it.
- `crosshead remember "<fact>"` saves one explicit fact for the current project; new sessions in
either host receive it.
- `crosshead status`, `crosshead doctor` and `crosshead logs` show what the
Expand Down
11 changes: 10 additions & 1 deletion src/runtime/claude-code-hook.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { existsSync, readFileSync } from "fs";
import path from "path";

import { captureHotFinding } from "./hot-continuity";
import { claimSessionStartContext, releaseSessionStartContext } from "./hook-session-context";
import { claimSessionStartContext, releaseSessionStartContext, resetSessionDelivery } from "./hook-session-context";
import { readLastAssistantMessage } from "./hook-transcript";
import { recordTokenUsageHook, tokenUsagePhase } from "./token-usage";

Expand Down Expand Up @@ -402,6 +402,13 @@ export const runOnlyBotsClaudeCodeHookCli = async (
const event = normalizedEventName.replace(/_/g, "");
// Older Claude Code releases send child auto-compactions with the exact
// parent payload. Only the manual trigger identifies a parent compaction.
const compactSessionId = pickString(payload, ["session_id", "sessionId", "session.id", "conversation_id", "conversationId"]);
if (event === "precompact" || event === "postcompact" || (event === "sessionstart" && pickString(payload, ["source", "payload.source"]) === "compact")) {
// Any compaction, including the automatic ones skipped below, drops what the
// session held, so its checkpoints are sent again. A child compaction that
// reuses the parent's id only costs the parent one repeat.
if (compactSessionId) resetSessionDelivery(runtimeHome, "claude-code", { sessionId: compactSessionId });
}
if ((event === "precompact" || event === "postcompact") && pickCompactionTrigger(payload) !== "manual") return;
if (event === "sessionstart" && pickString(payload, ["source", "payload.source"]) === "compact") return;
const viaPlugin = isPluginHookInvocation(flags);
Expand Down Expand Up @@ -513,6 +520,8 @@ export const runOnlyBotsClaudeCodeHookCli = async (
pickString(payload, ["session_id", "sessionId", "session.id", "conversation_id", "conversationId"]) ??
state.sessionId ??
buildSyntheticSessionId();
// A (re)started session holds none of the checkpoints a reused session id recorded.
resetSessionDelivery(runtimeHome, "claude-code", { sessionId });
await adapter.sessionStarted({
workspaceRoot,
workspaceId,
Expand Down
6 changes: 5 additions & 1 deletion src/runtime/codex-hook.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ import {
import { ensureRuntimeHomeLayout } from "./local-runtime";
import { compactContinuitySummary } from "./summary-compaction";
import { captureHotFinding } from "./hot-continuity";
import { claimSessionStartContext, releaseSessionStartContext } from "./hook-session-context";
import { claimSessionStartContext, releaseSessionStartContext, resetSessionDelivery } from "./hook-session-context";
import { readLastAssistantMessage } from "./hook-transcript";
import { recordTokenUsageHook, tokenUsagePhase } from "./token-usage";
import { loadProfile, writeJsonFile } from "./runtime-persistence";
Expand Down Expand Up @@ -496,6 +496,8 @@ export const runOnlyBotsCodexHookCli = async (
pickString(payload, ["session_id", "sessionId", "session.id", "conversation_id", "conversationId"]) ??
state.sessionId ??
buildSyntheticSessionId();
// A (re)started session holds none of the checkpoints a reused session id recorded.
resetSessionDelivery(runtimeHome, "codex", { sessionId });
await adapter.sessionStarted({
workspaceRoot,
workspaceId,
Expand Down Expand Up @@ -528,6 +530,8 @@ export const runOnlyBotsCodexHookCli = async (
pickString(payload, ["turn_id", "turnId", "event_id", "eventId", "id", "message_id", "messageId"]) ??
state.turnId ??
null;
// Compaction drops what the session held; its checkpoints are sent again.
if (requestedSessionId) resetSessionDelivery(runtimeHome, "codex", { sessionId: requestedSessionId });
const turnState = selectHookTurnState(state, requestedSessionId, requestedTurnId);
const sessionId = turnState.sessionId ?? requestedSessionId ?? buildSyntheticSessionId();
const turnId = turnState.turnId ?? requestedTurnId ?? null;
Expand Down
78 changes: 77 additions & 1 deletion src/runtime/hook-session-context.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { existsSync, readFileSync } from "fs";
import { createHash } from "crypto";
import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync, statSync } from "fs";
import path from "path";
import { ensureRuntimeHomeLayout } from "./local-runtime";
import { writeJsonFile } from "./runtime-persistence";
Expand Down Expand Up @@ -32,10 +33,85 @@ export const claimSessionStartContext = (runtimeHome: string, host: string, work

/** After compaction the host has dropped earlier context, so the next prompt is a fresh start. */
export const releaseSessionStartContext = (runtimeHome: string, host: string, workspaceId: string): void => {
resetSessionDelivery(runtimeHome, host, { workspaceId });
try {
const file = markerFile(runtimeHome, host), marker = readMarker(file);
if (!Object.hasOwn(marker, workspaceId)) return;
delete marker[workspaceId];
writeJsonFile(file, marker);
} catch { /* A missed release only costs the larger budget once. */ }
};

// Which hot checkpoints each host session has already been given. A checkpoint
// the session already holds is not sent again on every prompt; compaction, a
// session start or a changed checkpoint (a new digest) sends it again.
// Local state only, never synced: one file per host session, so a compaction
// reset (deleting the file) cannot be undone by another session's write.
const deliveryDir = (runtimeHome: string): string => path.join(ensureRuntimeHomeLayout(runtimeHome).state, "context-delivery");
const deliveryFile = (runtimeHome: string, host: string, sessionId: string): string =>
path.join(deliveryDir(runtimeHome), `${host}-${createHash("sha256").update(sessionId).digest("hex").slice(0, 24)}.json`);
// A safety net for compactions no hook reports: after this many prompts the
// session receives its checkpoints again.
export const HOT_REDELIVERY_PROMPTS = 25;
const MAX_DELIVERY_SESSIONS = 64;
const MAX_DELIVERY_DIGESTS = 48;

type DeliveryRecord = { workspaceId: string; digests: string[]; prompts: number; updatedAt: string };

const readDelivery = (file: string): DeliveryRecord | null => {
try {
const item = JSON.parse(readFileSync(file, "utf8")) as Partial<DeliveryRecord> | null;
return item && typeof item === "object" && Array.isArray(item.digests) && typeof item.prompts === "number"
? { workspaceId: String(item.workspaceId ?? ""), digests: item.digests.filter((d): d is string => typeof d === "string"), prompts: item.prompts, updatedAt: String(item.updatedAt ?? "") }
: null;
} catch { return null; }
};

/**
* What this session already received. `refresh` is true when it must be treated
* as holding nothing: no record (new session, or reset by compaction) or the
* redelivery interval has passed.
*/
export const readSessionDelivery = (runtimeHome: string, host: string, sessionId: string): { delivered: Set<string>; refresh: boolean } => {
try {
const record = readDelivery(deliveryFile(runtimeHome, host, sessionId));
if (!record || record.prompts >= HOT_REDELIVERY_PROMPTS) return { delivered: new Set(), refresh: true };
return { delivered: new Set(record.digests), refresh: false };
} catch { return { delivered: new Set(), refresh: true }; }
};

/** Record this prompt's deliveries. `refresh` starts a new record; otherwise digests are added. */
export const recordSessionDelivery = (runtimeHome: string, host: string, workspaceId: string, sessionId: string, digests: string[], refresh: boolean): void => {
try {
const file = deliveryFile(runtimeHome, host, sessionId);
const previous = refresh ? null : readDelivery(file);
const merged = [...new Set([...(previous?.digests ?? []), ...digests])].slice(-MAX_DELIVERY_DIGESTS);
mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
writeJsonFile(file, { workspaceId, digests: merged, prompts: (previous?.prompts ?? 0) + 1, updatedAt: new Date().toISOString() });
if (refresh) pruneDeliveries(runtimeHome);
} catch { /* A lost record only means a checkpoint is sent again. */ }
};

const pruneDeliveries = (runtimeHome: string): void => {
const dir = deliveryDir(runtimeHome);
const files = readdirSync(dir).filter(name => name.endsWith(".json")).map(name => {
const file = path.join(dir, name);
try { return { file, at: statSync(file).mtimeMs }; } catch { return null; }
}).filter((entry): entry is { file: string; at: number } => entry !== null).sort((a, b) => b.at - a.at);
for (const stale of files.slice(MAX_DELIVERY_SESSIONS)) rmSync(stale.file, { force: true });
};

/** Compaction dropped what the session held: forget its deliveries (one session, or every session in a workspace). */
export const resetSessionDelivery = (runtimeHome: string, host: string, target: { sessionId?: string | null; workspaceId?: string | null }): void => {
try {
if (target.sessionId) rmSync(deliveryFile(runtimeHome, host, target.sessionId), { force: true });
if (!target.workspaceId) return;
const dir = deliveryDir(runtimeHome);
if (!existsSync(dir)) return;
for (const name of readdirSync(dir)) {
if (!name.startsWith(`${host}-`) || !name.endsWith(".json")) continue;
const file = path.join(dir, name);
if (readDelivery(file)?.workspaceId === target.workspaceId) rmSync(file, { force: true });
}
} catch { /* A failed reset can only withhold a repeat; the redelivery interval bounds that. */ }
};
66 changes: 60 additions & 6 deletions src/runtime/host-adapter-base.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,8 @@ export { filterHotMemorySnapshotForWorkspace } from "./workspace-memory";
import { existsSync } from "fs";
import { nowIso, renderInjectedPrompt, shellQuote } from "./adapter-utils";
import path from "path";
import { HOT_CONTEXT_LIMIT, HOT_FULL_RENDER_LIMIT, renderHotCheckpoints, selectHotCheckpoints } from "./hot-continuity";
import { HOT_CONTEXT_LIMIT, HOT_FULL_RENDER_LIMIT, hotCheckpointDigest, renderHotCheckpointPointer, renderHotCheckpoints, selectHotCheckpoints, type SelectedHotCheckpoint } from "./hot-continuity";
import { readSessionDelivery, recordSessionDelivery } from "./hook-session-context";
import { CHECKPOINT_PAGE_CHARS, inlineCheckpointPages, paginateCheckpoint, saveCheckpointPages } from "./checkpoint-pages";
import { resolveRuntimeHome } from "./local-runtime";
import { evidenceFromToolCall, readTaskEvidence, taskEvidenceCaptureEnabled, type TaskEvidence } from "./task-evidence";
Expand Down Expand Up @@ -235,18 +236,66 @@ export abstract class HostRuntimeAdapterBase {
* Whenever more is saved than is shown, the pages are stored and the text ends
* with the exact command that prints them, so an agent never has to stop or
* guess because a note was cut off.
*
* On Claude Code and Codex, a checkpoint the session already received is not
* sent again (compaction or a changed checkpoint sends it again), and after
* the first prompt a checkpoint that shares no terms with the prompt is
* reduced to a one-line pointer. `refresh` is true when the session holds no
* earlier delivery: its first prompt, or the first after compaction.
*/
protected renderHotContext(snapshot: unknown, prompt: string, workspaceId: string, sessionStart: boolean): string | undefined {
protected renderHotContext(snapshot: unknown, prompt: string, workspaceId: string, sessionStart: boolean, sessionId?: string): { text: string | undefined; refresh: boolean } {
const home = this.config.runtimeHome;
const host = this.identity.runtimeId as string;
const tracked = Boolean(home && sessionId && (host === "claude-code" || host === "codex"));
const delivery = tracked ? readSessionDelivery(home!, host, sessionId!) : null;
const refresh = sessionStart || !delivery || delivery.refresh;
const record = (digests: string[]): void => {
if (tracked) recordSessionDelivery(home!, host, workspaceId, sessionId!, digests, refresh);
};
const command = this.bridgeCommand();
if (!command || !this.config.runtimeHome) return undefined;
const selected = selectHotCheckpoints(snapshot, prompt, this.config.workspaceOnly ? workspaceId : undefined);
if (!selected.length) return undefined;
if (!tracked) {
if (!command || !home || !selected.length) return { text: undefined, refresh };
return { text: this.renderSelectedHotContext(selected, workspaceId, sessionStart, command, home), refresh };
}
const delivered = refresh ? new Set<string>() : delivery!.delivered;
const items = selected.map(entry => {
const digest = hotCheckpointDigest(entry);
// A session that holds nothing yet (first prompt, after compaction) gets every selected checkpoint in full.
const mode: "full" | "pointer" = !refresh && entry.match === "unrelated" ? "pointer" : "full";
return { entry, mode, full: `${digest}:full`, pointer: `${digest}:pointer` };
}).filter(item => !delivered.has(item.full) && !(item.mode === "pointer" && delivered.has(item.pointer)) &&
// The session wrote its own checkpoints; until compaction it still holds that work.
(refresh || !item.entry.sessionId || item.entry.sessionId !== sessionId));
if (!items.length) {
record([]);
return { text: selected.length ? "" : undefined, refresh };
}
const full = items.filter(item => item.mode === "full").map(item => item.entry);
const pointers = items.filter(item => item.mode === "pointer").map(item => {
let read: string | null = null;
if (command) {
const pages = paginateCheckpoint(renderHotCheckpoints([item.entry], HOT_FULL_RENDER_LIMIT));
read = `${command.replace("%PAGE%", " 1")} --key ${saveCheckpointPages(home!, host, workspaceId, pages)}`;
}
return renderHotCheckpointPointer(item.entry, read);
});
const body = !full.length ? "" : command
? this.renderSelectedHotContext(full, workspaceId, sessionStart, command, home!)
: renderHotCheckpoints(full, HOT_CONTEXT_LIMIT);
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);
const inline = sessionStart ? inlineCheckpointPages(this.identity.runtimeId) : 0;
if (full.length <= (sessionStart ? CHECKPOINT_PAGE_CHARS * inline : HOT_CONTEXT_LIMIT)) return full;
const pages = paginateCheckpoint(full);
if (sessionStart && pages.length <= inline) return full;
const key = saveCheckpointPages(this.config.runtimeHome, this.identity.runtimeId, workspaceId, pages);
const key = saveCheckpointPages(home, this.identity.runtimeId, workspaceId, pages);
const read = (page: number): string => `${command.replace("%PAGE%", ` ${page}`)} --key ${key}`;
const shown = inline === 1 ? "page 1" : `pages 1 to ${inline}`;
const remaining = pages.length - inline === 1 ? `page ${pages.length}` : `pages ${inline + 1} to ${pages.length}, one page number per call`;
Expand Down Expand Up @@ -370,6 +419,9 @@ export abstract class HostRuntimeAdapterBase {
});
// The daemon supplies verified archive excerpts through a dedicated field.
// The hosted pack's context text, metadata and diagnostics stay outside the prompt.
const hot = input.prompt.trim()
? this.renderHotContext(preTurnHotMemory, input.prompt, workspaceId, input.sessionStart === true, input.sessionId)
: { text: undefined, refresh: true };
let contextText = input.prompt.trim() ? renderRuntimeStartupContext({
runtime: this.identity.runtimeId,
profileName,
Expand All @@ -387,7 +439,9 @@ export abstract class HostRuntimeAdapterBase {
freshness,
hotMemorySnapshot: preTurnHotMemory,
goal: input.prompt,
hotContextText: this.renderHotContext(preTurnHotMemory, input.prompt, workspaceId, input.sessionStart === true),
hotContextText: hot.text,
// The capture contract is long; a session that already received it keeps it until compaction.
captureGuidance: hot.refresh,
}) : "";
if (input.prompt.trim()) contextText = appendVerifiedArchiveContext(contextText, contextPack);
const supportsSubagents = this.identity.runtimeId === "codex" || this.identity.runtimeId === "claude-code";
Expand Down
Loading
Loading