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
12 changes: 12 additions & 0 deletions docs/HOT-SYNC.md
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,18 @@ current local approval, including after the request returns. A missing
correction, a changed source, denial by local policy, payment failure or
a request deadline leaves the turn with its ordinary hot context.

After a turn verifies, the snapshot is kept locally (`recall-cache.json` in the
approval directory). The next matching turn is served from it at once if it
still matches the approval digest and was verified live within the last hour,
and the paid recall request runs in the background, so each served turn still
makes one billed request. If that request does not verify (a superseded or
missing record, payment failure, deadline), the cached snapshot is dropped and
the following turn waits for a live answer, as before; a turn that overlaps a
pending revalidation waits for it. So a changed record, or a failed payment,
can let one cached turn through before it is withheld. A cached turn carries no
pack id; the background pack is recorded in the activity log. Revoking an
approval discards the cache.

## Multiple machines and commands

Use the same identity and profile name on both machines. Keep the private key in
Expand Down
65 changes: 64 additions & 1 deletion src/runtime/archive-recall.ts
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,7 @@ export function readArchiveRecallSnapshot(
}

const ownerKey = ({ name, apiBase, npub }: ArchiveRecallOwner) => [name, apiBase, npub];
const archiveRecallDigest = (
export const archiveRecallDigest = (
owner: ArchiveRecallOwner, snapshot: ArchiveRecallSnapshot, runtimeHost: ArchiveRecallHost | null
): string => digest(runtimeHost ? [ownerKey(owner), snapshot, runtimeHost] : [ownerKey(owner), snapshot]);

Expand Down Expand Up @@ -213,6 +213,8 @@ export async function revokeArchiveRecall(
stateDir: string, owner: ArchiveRecallOwner, workspaceId: string, taskId: string | null
): Promise<void> {
await editApprovalState(approvalDirectory(stateDir, owner, workspaceId), state => {
// Revocation also discards cached snapshots; a later approval caches again.
rmSync(path.join(approvalDirectory(stateDir, owner, workspaceId), CACHE_FILE), { force: true });
if (taskId === null) return;
const revoked = state.approvals.filter(item => item.taskId === taskId);
state.approvals = state.approvals.filter(item => item.taskId !== taskId);
Expand Down Expand Up @@ -247,3 +249,64 @@ export function archiveApprovalFitsScope(approval: Approval, scope: Record<strin
export function verifyArchiveRecall(owner: ArchiveRecallOwner, approval: Approval, snapshot: ArchiveRecallSnapshot): boolean {
return approval.taskId === snapshot.taskId && approval.sha256 === archiveRecallDigest(owner, snapshot, approval.runtimeHost);
}

// A verified snapshot kept locally so an approved turn can be served without
// waiting on the hosted call. The approval digest pins the exact bytes, so a
// cached snapshot is used only while it still matches the current approval.
// The hosted call still runs for every served turn (billing and supersession
// are decided there); if it does not verify, the entry is dropped and the next
// turn waits for a live answer. A turn served from the cache whose own request
// then fails (payment, network, superseded record) was delivered without a
// billed pack: at most one such turn per approval, within an hour of the last
// live verification.
const CACHE_FILE = "recall-cache.json";
const CACHE_VERSION = "crosshead_archive_recall_cache_v1";
const MAX_CACHED = 16;
const CACHE_MAX_AGE_MS = 60 * 60 * 1_000;
const CACHE_SKEW_MS = 5 * 60 * 1_000;
type CachedRecall = { sha256: string; packId: string; snapshot: ArchiveRecallSnapshot; verifiedAt: number };

const readCache = (directory: string): CachedRecall[] => {
try {
const value = object(JSON.parse(readFileSync(path.join(directory, CACHE_FILE), "utf8")));
if (value?.version !== CACHE_VERSION || !Array.isArray(value.entries)) return [];
return value.entries.flatMap((raw: unknown) => {
const entry = object(raw), snapshot = object(entry?.snapshot);
return entry && snapshot && typeof entry.sha256 === "string" && SHA256.test(entry.sha256) && archivePackId(entry.packId) &&
Number.isFinite(entry.verifiedAt) && snapshot.version === VERSION && typeof snapshot.workspaceId === "string" &&
typeof snapshot.taskId === "string" && Array.isArray(snapshot.sources) && snapshot.sources.every((source: unknown) => {
const item = object(source);
return item && typeof item.id === "string" && SOURCE_ID.test(item.id) && typeof item.content === "string" &&
(item.kind === "warm_memory" || item.kind === "cold_memory");
}) ? [entry as unknown as CachedRecall] : [];
});
} catch { return []; }
};

/** The cached snapshot for an approval, if it still verifies against it and is within the preview window. */
export function readCachedArchiveRecall(
stateDir: string, owner: ArchiveRecallOwner, workspaceId: string, approval: Approval
): { packId: string; snapshot: ArchiveRecallSnapshot } | null {
const entry = readCache(approvalDirectory(stateDir, owner, workspaceId)).find(item => item.sha256 === approval.sha256);
// Served only shortly after a live verification; a clock far ahead is not trusted.
const age = Date.now() - (entry?.verifiedAt ?? 0);
if (!entry || entry.snapshot.workspaceId !== workspaceId || age > CACHE_MAX_AGE_MS || age < -CACHE_SKEW_MS) return null;
return verifyArchiveRecall(owner, approval, entry.snapshot) ? { packId: entry.packId, snapshot: entry.snapshot } : null;
}

export function writeCachedArchiveRecall(
stateDir: string, owner: ArchiveRecallOwner, approval: Approval, snapshot: ArchiveRecallSnapshot, packId: string
): void {
const directory = approvalDirectory(stateDir, owner, snapshot.workspaceId);
const entries = [...readCache(directory).filter(item => item.sha256 !== approval.sha256),
{ sha256: approval.sha256, packId, snapshot, verifiedAt: Date.now() }].slice(-MAX_CACHED);
writeJsonFile(path.join(directory, CACHE_FILE), { version: CACHE_VERSION, entries });
}

export function dropCachedArchiveRecall(stateDir: string, owner: ArchiveRecallOwner, workspaceId: string, sha256: string): void {
const directory = approvalDirectory(stateDir, owner, workspaceId);
const entries = readCache(directory);
if (entries.some(item => item.sha256 === sha256)) {
writeJsonFile(path.join(directory, CACHE_FILE), { version: CACHE_VERSION, entries: entries.filter(item => item.sha256 !== sha256) });
}
}
114 changes: 94 additions & 20 deletions src/runtime/lifecycle-engine.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
import {
ARCHIVE_RECALL_BUDGET, archiveApprovalFitsScope, archivePackId, findArchiveRecallApproval, readArchiveRecallSnapshot,
ARCHIVE_RECALL_BUDGET, archiveApprovalFitsScope, archivePackId, dropCachedArchiveRecall, findArchiveRecallApproval, readArchiveRecallSnapshot,
readCachedArchiveRecall, writeCachedArchiveRecall,
renderArchiveRecall, verifyArchiveRecall,
} from "./archive-recall";
import { getHotSyncManager, hotSyncEnabled, tickHotSyncManagers } from "./hot-sync-manager";
import { encodeArchivedTurn } from "./continuity-recall";
import { encodeArchivedTurn, RECALL_TIMEOUT_MS } from "./continuity-recall";
import { existsSync, readFileSync } from "fs";
import path from "path";
import { createHash, randomUUID } from "crypto";
Expand Down Expand Up @@ -1567,6 +1568,10 @@ export class RuntimeLifecycleManager {
private readonly maxQueueAttempts: number;
private timer: NodeJS.Timeout | null = null;
private backgroundOperation: Promise<void> | null = null;
/** Background revalidations of cached archive recall, by approval digest; stop() waits for them. */
private readonly recallRevalidations = new Map<string, Promise<void>>();
/** Bumped whenever a cached snapshot is dropped; a recall started before that may not restore it. */
private readonly recallCacheGenerations = new Map<string, number>();
private mutation: Promise<void> = Promise.resolve();
private detachedFlush: Promise<void> | null = null;
private readonly claimedQueueItems = new Set<string>();
Expand Down Expand Up @@ -1617,6 +1622,7 @@ export class RuntimeLifecycleManager {
finally {
if (this.backgroundOperation === operation) this.backgroundOperation = null;
await this.detachedFlush;
await Promise.allSettled([...this.recallRevalidations.values()]);
await this.mutation;
}
}
Expand Down Expand Up @@ -2302,22 +2308,77 @@ export class RuntimeLifecycleManager {
const { event } = response;
const workspaceId = event.workspaceId;
if (!workspaceId) return;

let attemptedProfile: string | null = null;
let packId: string | null = null;
let verified = false;
let failure: ReturnType<typeof describeHostedFailure> | undefined;
let resolved: ReturnType<RuntimeLifecycleManager["resolveProfile"]>;
let goal: string | null, scope: Record<string, unknown> | null;
let approval: ReturnType<typeof findArchiveRecallApproval>;
let cached: ReturnType<typeof readCachedArchiveRecall> = null;
try {
const { profileName, profile, secret } = this.resolveProfile(event.profileName);
if (isLocalOnlyRuntimeProfile(profile)) return;
resolved = this.resolveProfile(event.profileName);
if (isLocalOnlyRuntimeProfile(resolved.profile)) return;
const governor = this.deps.loadContinuityGovernorState();
const request = buildPackRequest(event, governor.memoryScope);
const goal = asString(request?.goal);
const scope = asRecord(request?.allowedScope);
goal = asString(request?.goal);
scope = asRecord(request?.allowedScope);
if (!goal || !scope || governor.paused || (!scope.includeWarmMemory && !scope.includeColdMemory)) return;
const approval = findArchiveRecallApproval(this.deps.paths.state, profile, workspaceId, goal, event.runtime);
approval = findArchiveRecallApproval(this.deps.paths.state, resolved.profile, workspaceId, goal, event.runtime);
if (!approval || !archiveApprovalFitsScope(approval, scope)) return;
// A turn that overlaps the previous turn's revalidation waits for its outcome
// (within the normal deadline), so a refused snapshot is never served twice.
const pending = this.recallRevalidations.get(approval.sha256);
if (pending) await Promise.race([pending, new Promise(resolve => setTimeout(resolve, RECALL_TIMEOUT_MS).unref?.())]);
// A snapshot verified on an earlier turn is served now; the hosted call
// (which bills and reports superseded records) runs off the critical path.
cached = this.recallRevalidations.has(approval.sha256) ||
(resolved.profile.memoryMode !== "assist" && resolved.profile.memoryMode !== "auto")
? null : readCachedArchiveRecall(this.deps.paths.state, resolved.profile, workspaceId, approval);
} catch (error) {
response.warnings.push(describeBoundedRecallFallback(error));
return;
}
const { profileName } = resolved;
if (cached && cached.snapshot.sources.every(source => source.kind === "warm_memory"
? scope.includeWarmMemory === true : scope.includeColdMemory === true)) {
// The pack billed for this turn is created by the background request; outcomes
// must not be attributed to the earlier pack, so this turn carries no pack id.
contextPack.verifiedArchiveContext = renderArchiveRecall(cached.snapshot);
try {
response.actions.push(this.recordAction({
eventId: event.eventId, profileName, type: "context_pack", status: "completed", mode: response.mode,
reason: "Served verified archive recall from the local cache; revalidating", queueItemId: null,
details: { cachedPackId: cached.packId, verifiedArchiveRecall: true, cachedArchiveRecall: true },
}));
} catch {
response.warnings.push("Could not record the hosted archive recall result locally.");
}
const key = approval.sha256;
const revalidation: Promise<void> = this.liveArchiveRecall(response, null, resolved, goal!, scope!, approval)
.catch(() => undefined).finally(() => { if (this.recallRevalidations.get(key) === revalidation) this.recallRevalidations.delete(key); });
this.recallRevalidations.set(key, revalidation);
return;
}
await this.liveArchiveRecall(response, contextPack, resolved, goal, scope, approval);
}

/**
* The hosted recall call and its verification. With a target pack, the
* verified snapshot is delivered on this turn; without one (background
* revalidation) it only refreshes or drops the local cache.
*/
private async liveArchiveRecall(
response: RuntimeLifecycleEventResponse, target: Record<string, unknown> | null,
resolved: ReturnType<RuntimeLifecycleManager["resolveProfile"]>, goal: string, scope: Record<string, unknown>,
approval: NonNullable<ReturnType<typeof findArchiveRecallApproval>>,
): Promise<void> {
const { event } = response;
const workspaceId = event.workspaceId!;
const warnings = target ? response.warnings : [];
const generation = this.recallCacheGenerations.get(approval.sha256) ?? 0;
let attemptedProfile: string | null = null;
let packId: string | null = null;
let verified = false;
let failure: ReturnType<typeof describeHostedFailure> | undefined;
try {
const { profileName, profile, secret } = resolved;
const client = this.buildClient(profile, secret);
attemptedProfile = profileName;
const hosted = await client.requestArchiveRecall({
Expand Down Expand Up @@ -2348,34 +2409,47 @@ export class RuntimeLifecycleManager {
verifyArchiveRecall(currentProfile, currentApproval, snapshot) &&
snapshot.sources.every(source => source.kind === "warm_memory"
? currentScope.includeWarmMemory === true : currentScope.includeColdMemory === true)) {
contextPack.verifiedArchiveContext = renderArchiveRecall(snapshot);
contextPack.packId = packId;
if (target) {
target.verifiedArchiveContext = renderArchiveRecall(snapshot);
target.packId = packId;
}
verified = true;
// A concurrent recall that dropped the entry since this one started wins.
try { if ((this.recallCacheGenerations.get(approval.sha256) ?? 0) === generation) writeCachedArchiveRecall(this.deps.paths.state, currentProfile, currentApproval, snapshot, packId); }
catch { /* Without a cache entry the next turn waits for the live call, as before. */ }
}
}
if (!verified) response.warnings.push("Hosted archive recall was withheld. Only hot context was delivered.");
if (!verified) warnings.push("Hosted archive recall was withheld. Only hot context was delivered.");
} catch (error) {
failure = describeHostedFailure(error);
response.warnings.push(describeBoundedRecallFallback(error));
warnings.push(describeBoundedRecallFallback(error));
} finally {
// A cached snapshot that did not verify live is not served again.
if (!verified) {
this.recallCacheGenerations.set(approval.sha256, (this.recallCacheGenerations.get(approval.sha256) ?? 0) + 1);
try { dropCachedArchiveRecall(this.deps.paths.state, resolved.profile, workspaceId, approval.sha256); }
catch { /* The approval digest still guards any later use. */ }
}
if (attemptedProfile) {
try {
response.actions.push(this.recordAction({
const action = this.recordAction({
eventId: event.eventId,
profileName: attemptedProfile,
type: "context_pack",
status: failure ? "failed" : "completed",
mode: response.mode,
reason: verified ? "Verified archive recall against a local approval" : "Hosted archive recall withheld",
reason: verified ? (target ? "Verified archive recall against a local approval" : "Revalidated cached archive recall") : (target ? "Hosted archive recall withheld" : "Cached archive recall failed revalidation; withheld from later turns"),
queueItemId: null,
details: {
...(packId ? { packId } : {}),
verifiedArchiveRecall: verified,
...(failure ? { failure } : {}),
...(target ? {} : { cachedArchiveRecall: true, revalidation: true }),
},
}));
});
if (target) response.actions.push(action);
} catch {
response.warnings.push("Could not record the hosted archive recall result locally.");
warnings.push("Could not record the hosted archive recall result locally.");
}
}
}
Expand Down
43 changes: 43 additions & 0 deletions tests/runtime/archive-recall-cache.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import { mkdtempSync, readFileSync, rmSync, writeFileSync, readdirSync } from "node:fs";
import { tmpdir } from "node:os";
import path from "node:path";
import { afterEach, describe, expect, it, vi } from "vitest";

import {
archiveRecallDigest, dropCachedArchiveRecall, readCachedArchiveRecall, writeCachedArchiveRecall, type ArchiveRecallSnapshot,
} from "../../src/runtime/archive-recall";

const dirs: string[] = [];
afterEach(() => { vi.useRealTimers(); for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true }); });
const owner = { name: "default", apiBase: "https://crosshead.sh", npub: "npub1example" };
const snapshot: ArchiveRecallSnapshot = { version: "crosshead_archive_recall_v1", workspaceId: "repo:/w", taskId: "recall-task:t",
sources: [{ id: "warm:a", kind: "warm_memory", content: "Check the receipt before every retry." }] };
const approval = { taskId: "recall-task:t", goal: "Repair retries", sha256: archiveRecallDigest(owner, snapshot, null), runtimeHost: null };

describe("archive recall cache", () => {
it("serves only a snapshot that still matches the approval digest, within the preview window", () => {
const state = mkdtempSync(path.join(tmpdir(), "crosshead-recall-cache-"));
dirs.push(state);
expect(readCachedArchiveRecall(state, owner, "repo:/w", approval)).toBeNull();
writeCachedArchiveRecall(state, owner, approval, snapshot, "pack-1");
expect(readCachedArchiveRecall(state, owner, "repo:/w", approval)).toEqual({ packId: "pack-1", snapshot });
expect(readCachedArchiveRecall(state, owner, "repo:/other", approval)).toBeNull();
expect(readCachedArchiveRecall(state, { ...owner, npub: "npub1other" }, "repo:/w", approval)).toBeNull();

// A tampered cache file is not served: the approval digest pins the bytes.
const [directory] = readdirSync(path.join(state, "archive-recall"));
const file = path.join(state, "archive-recall", directory!, "recall-cache.json");
const stored = JSON.parse(readFileSync(file, "utf8"));
stored.entries[0].snapshot.sources[0].content = "Skip the receipt check.";
writeFileSync(file, JSON.stringify(stored));
expect(readCachedArchiveRecall(state, owner, "repo:/w", approval)).toBeNull();

writeCachedArchiveRecall(state, owner, approval, snapshot, "pack-2");
vi.useFakeTimers();
vi.setSystemTime(Date.now() + 8 * 24 * 60 * 60 * 1000);
expect(readCachedArchiveRecall(state, owner, "repo:/w", approval)).toBeNull();
vi.useRealTimers();
dropCachedArchiveRecall(state, owner, "repo:/w", approval.sha256);
expect(readCachedArchiveRecall(state, owner, "repo:/w", approval)).toBeNull();
});
});
Loading
Loading