Skip to content
Merged
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
27 changes: 24 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -151,9 +151,30 @@ a fresh session after choosing either setting.
response field is injected into an agent prompt. Only locally signature-
verified hot memory remains available automatically; hosted recall can be
inspected explicitly until a client-verifiable aggregation protocol exists.
- Handoff capsules are signed, verified, and stored by the local runtime. Share
the capsule JSON for cross-machine imports; the private key is never sent to
the handoff service.
- Handoff capsules are signed, verified, and stored by the local runtime; the
private key is never sent to the handoff service. To move work to another
machine, write the capsule to a file and import it there:

```sh
crosshead handoff export --source claude-code --target claude-code \
--session-id <id> --prompt "<what to continue>" --output capsule.json
crosshead handoff import --target claude-code --file capsule.json
```

Export works with no network; it leaves out hosted memory references it
cannot read and says so. `--output` will not replace an existing file unless
you pass `--force`, and the file is readable only by you. Import saves the
handoff to hot memory for the project that contains the current directory, so
the next session there starts with it. Importing the same capsule again
replaces the earlier copy instead of adding another. Without `--target`, export addresses the other host (Codex
to Claude Code, or the reverse).
- Import accepts a capsule signed by the profile's own key. A valid signature
from any other key is rejected unless you pass `--allow-signer <npub>` for a
key you trust. Capsules older than 30 days are rejected unless you pass
`--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.
- `crosshead status`, `crosshead doctor` and `crosshead logs` show what the
runtime is doing. Local state lives in `~/.crosshead/state/`.

Expand Down
103 changes: 83 additions & 20 deletions src/runtime/claude-code-adapter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import { spawn } from "child_process";

import type { OperatorWorkspaceManifest } from "./operator-policy";
import { LocalRuntimeClient } from "./local-client";
import { handoffAgeRejection, handoffImportIds, handoffSignerRejection, importedHandoffGoal, optionalHostedRead, renderImportedHandoffMemory } from "./handoff-import";
import {
ONLYBOTS_RUNTIME_CORE_VERSION,
ensureRuntimeHomeLayout,
Expand Down Expand Up @@ -194,7 +195,7 @@ export type ClaudeCodeContinuityCapture = ContinuityCaptureBase & {

export type ClaudeCodeAdapterHandoffCreateRequest = Omit<ClaudeCodeContinuityCapture, "runtime"> & {
profileName?: string;
targetRuntime?: "codex";
targetRuntime?: "codex" | "claude-code";
maxBytes?: number;
};

Expand All @@ -205,6 +206,8 @@ export type ClaudeCodeAdapterHandoffCreateResult = {
plainTextSummary: string;
restatementComparison: ContinuityRestatementComparison;
record: HandoffStoredRecord;
/** Parts of the export that could not be read, such as hosted memory references while offline. */
warnings: string[];
};

export type ClaudeCodeAdapterHandoffImportRequest = {
Expand All @@ -218,6 +221,10 @@ export type ClaudeCodeAdapterHandoffImportRequest = {
sessionId: string;
accepted?: boolean;
note?: string;
/** Signers accepted in addition to this profile's own key. */
allowedSigners?: string[];
/** Import a capsule older than the age limit. */
allowStale?: boolean;
};

export type ClaudeCodeAdapterHandoffImportResult = {
Expand All @@ -230,6 +237,12 @@ export type ClaudeCodeAdapterHandoffImportResult = {
restatementComparison: ContinuityRestatementComparison | null;
receipt: HandoffReceipt | null;
record: HandoffStoredRecord | null;
/** True when the handoff was saved to hot memory for the next session in the workspace. */
savedToHotMemory?: boolean;
/** The workspace the import was saved under; sessions see it only when their hooks use the same one. */
savedWorkspaceId?: string;
/** Why nothing was written, when savedToHotMemory is false. */
notSavedReason?: string;
};

type CommandCaptureResult = {
Expand Down Expand Up @@ -959,10 +972,13 @@ export class ClaudeCodeRuntimeAdapter extends HostRuntimeAdapterBase {
const needsIdentity = !input.identity?.npub;
const needsPolicyRef = !input.policy?.policyRef;

const targetRuntime = input.targetRuntime ?? "codex";
const targetLabel = targetRuntime === "codex" ? "Codex" : "Claude Code";
const warnings: string[] = [];
const [hot, warm, judgment, status] = await Promise.all([
needsHotSummary ? this.client.readHotMemory(profileName) : Promise.resolve(null),
needsWarmIds ? this.client.listWarmMemory(profileName, { status: "active" }) : Promise.resolve(null),
needsJudgment ? this.client.inspectContinuityJudgment(profileName) : Promise.resolve(null),
optionalHostedRead(needsWarmIds, () => this.client.listWarmMemory(profileName, { status: "active" }), "Warm memory", warnings),
optionalHostedRead(needsJudgment, () => this.client.inspectContinuityJudgment(profileName), "Continuity judgment", warnings),
needsIdentity || needsPolicyRef ? this.client.status(profileName) : Promise.resolve(null),
]);

Expand Down Expand Up @@ -1023,7 +1039,7 @@ export class ClaudeCodeRuntimeAdapter extends HostRuntimeAdapterBase {
unresolvedRisks:
input.reasoning?.unresolvedRisks ?? (projectModel ? summarizeJudgmentEntries(projectModel.unresolvedRisks) : []),
portabilityNotes: input.reasoning?.portabilityNotes ?? [
"Exported from the live Claude Code runtime so Codex can resume with explicit continuity gaps.",
`Exported from the live Claude Code runtime so ${targetLabel} can resume with explicit continuity gaps.`,
],
nextAction: input.reasoning?.nextAction ?? null,
},
Expand All @@ -1047,9 +1063,9 @@ export class ClaudeCodeRuntimeAdapter extends HostRuntimeAdapterBase {
delegation: {
whyTransfer:
input.delegation?.whyTransfer ??
"Continue execution in Codex while preserving the current Crosshead continuity state.",
`Continue execution in ${targetLabel} while preserving the current Crosshead continuity state.`,
requestedCapabilities: input.delegation?.requestedCapabilities ?? ["repo_execution", "tool_use"],
recommendedTarget: "codex",
recommendedTarget: targetRuntime,
},
economics: {
budgetRemainingSats: input.economics?.budgetRemainingSats ?? null,
Expand All @@ -1064,10 +1080,10 @@ export class ClaudeCodeRuntimeAdapter extends HostRuntimeAdapterBase {
};

const capture = claudeCodeContinuityTranslationContract.captureContext(enrichedCapture);
const translation = claudeCodeContinuityTranslationContract.normalizeToContinuityIr(capture, input.targetRuntime ?? "codex");
const materialization = claudeCodeContinuityTranslationContract.materializeFromContinuityIr(translation, "codex");
const plainTextSummary = buildPlainTextContinuationSummary(translation, "codex");
const restatementComparison = compareContinuityRestatement(materialization.startupContext, translation, "codex");
const translation = claudeCodeContinuityTranslationContract.normalizeToContinuityIr(capture, targetRuntime);
const materialization = claudeCodeContinuityTranslationContract.materializeFromContinuityIr(translation, targetRuntime);
const plainTextSummary = buildPlainTextContinuationSummary(translation, targetRuntime);
const restatementComparison = compareContinuityRestatement(materialization.startupContext, translation, targetRuntime);
const created = (await this.client.createHandoff({
translation,
maxBytes: input.maxBytes,
Expand All @@ -1084,35 +1100,43 @@ export class ClaudeCodeRuntimeAdapter extends HostRuntimeAdapterBase {
plainTextSummary,
restatementComparison,
record,
warnings,
};
}

async importHandoff(input: ClaudeCodeAdapterHandoffImportRequest): Promise<ClaudeCodeAdapterHandoffImportResult> {
const workspaceRoot = String(input.workspaceRoot ?? "").trim();
const rawWorkspaceRoot = String(input.workspaceRoot ?? "").trim();
// Hooks key memory by absolute project path, so a relative root would save where no session looks.
const workspaceRoot = rawWorkspaceRoot ? path.resolve(rawWorkspaceRoot) : "";
const workspaceId = input.workspaceId ?? `repo:${workspaceRoot}`;
const sessionId = String(input.sessionId ?? "").trim();
const handoffId = sanitizeString(input.handoffId);
const accepted = input.accepted !== false;
const rejectionReason = (reason: string): string => (input.note ? `${reason} ${input.note}` : reason);

const rejectStoredHandoff = async (reason: string): Promise<ClaudeCodeAdapterHandoffImportResult> => {
const rejectStoredHandoff = async (reason: string, known?: { verification?: HandoffVerificationResult; sourceRuntime?: string }): Promise<ClaudeCodeAdapterHandoffImportResult> => {
const baseVerification: HandoffVerificationResult = {
valid: false,
signatureValid: false,
payloadHashMatches: false,
withinBudget: false,
errors: [reason],
warnings: [],
sourceRuntime: "codex",
sourceRuntime: (known?.sourceRuntime ?? "codex") as HandoffVerificationResult["sourceRuntime"],
targetRuntime: "claude-code",
signedBy: null,
sizeBytes: null,
};
// A capsule that verified but was refused keeps its real verification details, marked invalid
// for this import with the reason, so JSON callers never see accepted: false beside valid: true.
const refusedVerification: HandoffVerificationResult = known?.verification
? { ...known.verification, valid: false, errors: [...known.verification.errors, reason] }
: baseVerification;
const baseInspection: HandoffInspection = {
handoffId: handoffId ?? "unknown",
capsuleVersion: "unknown",
capsuleKind: "unknown",
sourceRuntime: "codex",
sourceRuntime: (known?.sourceRuntime ?? "codex") as HandoffInspection["sourceRuntime"],
targetRuntime: "claude-code",
signedBy: "",
createdAt: nowIso(),
Expand Down Expand Up @@ -1157,7 +1181,7 @@ export class ClaudeCodeRuntimeAdapter extends HostRuntimeAdapterBase {
return {
handoffId: null,
accepted: false,
verification: baseVerification,
verification: refusedVerification,
inspection: baseInspection,
materialization: null,
plainTextSummary: null,
Expand All @@ -1184,7 +1208,7 @@ export class ClaudeCodeRuntimeAdapter extends HostRuntimeAdapterBase {
return {
handoffId,
accepted: false,
verification: updated.validation,
verification: known?.verification ? refusedVerification : updated.validation,
inspection: updated.inspection,
materialization: null,
plainTextSummary: null,
Expand Down Expand Up @@ -1229,11 +1253,23 @@ export class ClaudeCodeRuntimeAdapter extends HostRuntimeAdapterBase {
if (!verification.valid) {
return rejectStoredHandoff(`Claude Code handoff import rejected an invalid capsule: ${verification.errors.join(" | ")}`);
}
if (capsule.sourceRuntime !== "codex") {
return rejectStoredHandoff(`Claude Code import only accepts Codex-origin handoffs, received ${capsule.sourceRuntime}`);
}
if (capsule.targetRuntime !== "claude-code") {
return rejectStoredHandoff(`Claude Code import requires targetRuntime=claude-code, received ${capsule.targetRuntime}`);
return rejectStoredHandoff(`Claude Code import requires targetRuntime=claude-code, received ${capsule.targetRuntime}`, { verification, sourceRuntime: capsule.sourceRuntime });
}
// The signature shows the capsule is intact. Whose capsule it is must be checked separately.
const ownNpub = await this.client.status(input.profileName ?? this.config.profileName).then(
(status) => (status?.profile && typeof status.profile === "object" && !Array.isArray(status.profile)
? sanitizeString((status.profile as Record<string, unknown>).npub) : null),
() => null
);
const signerRejection = handoffSignerRejection(verification.signedBy, ownNpub, input.allowedSigners ?? []);
const known = { verification, sourceRuntime: capsule.sourceRuntime };
if (accepted && signerRejection) {
return rejectStoredHandoff(`Claude Code handoff import rejected the signer: ${signerRejection}`, known);
}
const ageRejection = handoffAgeRejection(capsule.createdAt, new Date(), undefined, input.allowStale === true);
if (accepted && ageRejection) {
return rejectStoredHandoff(`Claude Code handoff import rejected a stale capsule: ${ageRejection}`, known);
}
if (!accepted) {
return rejectStoredHandoff(input.note?.trim().length ? input.note.trim() : "Operator rejected the handoff during Claude Code import.");
Expand All @@ -1251,6 +1287,30 @@ export class ClaudeCodeRuntimeAdapter extends HostRuntimeAdapterBase {
const materialization = claudeCodeContinuityTranslationContract.materializeFromContinuityIr(translation, "claude-code");
const plainTextSummary = buildPlainTextContinuationSummary(translation, "claude-code");
const restatementComparison = compareContinuityRestatement(materialization.startupContext, translation, "claude-code");
// Printing the state is not delivery. Saving it to hot memory is what makes the next session
// in this workspace start with it, on this machine or after sync. It is saved before the handoff
// is acknowledged, so a failed save never leaves a record that says the import succeeded.
const ids = handoffImportIds(capsule.capsuleId, workspaceId, "claude-code", input.profileName ?? this.config.profileName);
const saved = await this.saveImportedHandoff({
profileName: input.profileName,
workspaceId,
sessionId,
hostVersion: input.hostVersion,
...ids,
goal: importedHandoffGoal({ sourceRuntime: capsule.sourceRuntime, objective: capsule.continuityIr.task.objective, createdAt: capsule.createdAt }),
content: renderImportedHandoffMemory({
sourceRuntime: capsule.sourceRuntime,
signedBy: verification.signedBy,
ownNpub,
startupContext: materialization.startupContext,
}),
});
// A capsule that was not saved has not been handed off: refuse it (the operator can retry once
// memory can be written), so neither the record nor the exit status claims success.
if (!saved.saved) {
return rejectStoredHandoff(`Claude Code handoff import could not save the handoff: ${saved.notSavedReason ?? "hot memory was not written"}`, known);
}

const updated =
handoffId === null
? null
Expand All @@ -1274,6 +1334,9 @@ export class ClaudeCodeRuntimeAdapter extends HostRuntimeAdapterBase {
return {
handoffId,
accepted: true,
savedToHotMemory: saved.saved,
savedWorkspaceId: workspaceId,
...(saved.notSavedReason ? { notSavedReason: saved.notSavedReason } : {}),
verification,
inspection,
materialization,
Expand Down
49 changes: 46 additions & 3 deletions src/runtime/claude-code-bridge.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,10 +57,28 @@ const parseBooleanFlag = (value: string | boolean | undefined): boolean | undefi
return undefined;
};

// The injected context names capabilities with underscores, and the Codex bridge uses the
// memory-* spellings. Accept the same names here so one instruction works on both hosts.
const canonicalCommand = (command: string): string => {
switch (command) {
case "memory_hot": return "memory-hot";
case "memory_warm": return "memory-warm";
case "memory_search":
case "memory-search": return "search-memory";
case "inbox_state": return "inbox-state";
case "inbox_replay": return "inbox-replay";
case "inbox_ack": return "inbox-ack";
case "inbox_resolve": return "inbox-resolve";
case "session_end": return "session-end";
case "turn_failed": return "turn-failed";
default: return command;
}
};

export const runOnlyBotsClaudeCodeBridgeCli = async (argv: string[] = process.argv.slice(2)): Promise<void> => {
assertSecureNodeRuntimeVersion();
const { positionals, flags } = parseArgs(argv);
const command = positionals[0] ?? "help";
const command = canonicalCommand(positionals[0] ?? "help");
if (command === "checkpoint-page") {
runCheckpointPageCommand("claude-code", positionals, flags);
return;
Expand All @@ -78,7 +96,9 @@ export const runOnlyBotsClaudeCodeBridgeCli = async (argv: string[] = process.ar
"crosshead-claude-code task-changed --workspace-root <path> --session-id <id> --task-title <text>",
"crosshead-claude-code turn-completed --workspace-root <path> --session-id <id> --turn-id <id> --summary <text> [--goal <text>] [--pack-id <id>]",
"crosshead-claude-code remember --workspace-root <path> --session-id <id> --content <text> [--entry-type fact]",
"crosshead-claude-code search-memory --query <text> [--top-k 10]",
"crosshead-claude-code memory-hot [--profile <name>] [--scope all|shared|codex|claude-code]",
"crosshead-claude-code memory-warm [--profile <name>] [--type <type>] [--status <status>] [--include-system]",
"crosshead-claude-code memory-search --query <text> [--top-k 10]",
"crosshead-claude-code inbox-state [--profile <name>] [--unread-only true|false] [--include-terminal true|false] [--limit <n>]",
"crosshead-claude-code inbox-replay (--inbox-id <id>|--message-event-id <id>) [--profile <name>] [--note <text>]",
"crosshead-claude-code inbox-ack (--inbox-id <id>|--message-event-id <id>) [--profile <name>] [--actor-runtime-host <host>] [--note <text>]",
Expand Down Expand Up @@ -249,9 +269,32 @@ export const runOnlyBotsClaudeCodeBridgeCli = async (argv: string[] = process.ar
return;
}

if (command === "memory-hot") {
const result = await adapter.readHotMemory(
typeof flags.profile === "string" ? flags.profile : undefined,
typeof flags.scope === "string" && flags.scope.length > 0 ? flags.scope : "all"
);
process.stdout.write(`${JSON.stringify(result, null, 2)}\n`);
return;
}

if (command === "memory-warm") {
const result = await adapter.listWarmMemory(typeof flags.profile === "string" ? flags.profile : undefined, {
type: typeof flags.type === "string" ? flags.type : undefined,
status: typeof flags.status === "string" ? flags.status : undefined,
includeSystemMemory: flags["include-system"] === true || flags.includeSystem === true,
});
process.stdout.write(`${JSON.stringify(result, null, 2)}\n`);
return;
}

if (command === "search-memory") {
const query = typeof flags.query === "string" ? flags.query : positionals.slice(1).join(" ").trim();
if (query.length === 0) {
throw new Error("memory-search requires --query <text> or a positional query");
}
const result = await adapter.searchMemory(
String(flags.query ?? ""),
query,
typeof flags.profile === "string" ? flags.profile : undefined,
typeof flags["top-k"] === "string" ? Number(flags["top-k"]) : 10,
false,
Expand Down
Loading
Loading