Persistent Context Across Sessions for Every Agent – Captures everything your agent does during sessions, compresses it with AI, and injects relevant context back into future sessions. Works with Claude Code, OpenClaw, Codex, Gemini, Hermes, Copilot, OpenCode + More
TypeScript aiai-agentsai-memoryanthropicartificial-intelligencechromadbclaudeclaude-agent-sdkclaude-agentsclaude-codeclaude-code-pluginclaude-skillsembeddingslong-term-memorymem0memory-engineopenmemoryragsqlitesupermemory
/**
* The install funnel's Scan step: read every agent's transcripts for the last
* 30 days, store the owner's typed prompts in claude-mem's DB, and report live
* progress. Works the same for a new install (empty DB: everything comes from
* transcripts) and an upgrade (hooks already recorded most prompts: those are
* matched, never stored twice, and counted as `fromMemory`).
*
* One scan runs at a time; a second start returns the running scan's state.
* Reading has no time limit: the scan reports `done` only after every file is read.
* Organizing (the owner's own AI refreshing My Work) does: that refresh covers everything due on this install, which
* on an install with existing memory took 19 minutes at 98% (#6615). The scan waits ORGANIZING_WAIT_MS for it, or
* until the person presses Continue (continueNow), then finishes and leaves the refresh running in the background.
*/
import { logger } from '../../utils/logger.js';
import type { SetupScanPhase } from '../../shared/setup-funnel.js';
import { stripMemoryTags } from '../../utils/tag-stripping.js';
import type { UsableAgent, UsableAgentId } from '../agent-runner/detect.js';
import { observationTokenEconomics, scanTokenUsage, summarizeTokenUsage, type SetupTokenUsage } from './token-usage.js';
import { scanOwnerPrompts, scanWindowStart, type AgentScanSummary, type MemoryPrompt, type OwnerPrompt, type PromptAgentId, type PromptScanOptions, type PromptScanProgress } from './index.js';
/** How far apart the hook's time and the transcript's time may be for one prompt (measured: under 7 s on the owner's Mac). */
export const HOOK_MATCH_WINDOW_MS = 10 * 60_000;
export type { SetupScanPhase };
/**
* How long the scan waits at 98% for the owner's own AI before it finishes and the refresh goes on in the background.
* Measured: a whole first-install setup scan (reading through organizing, not organizing alone) took 174 s on the
* maintainer's install (`Setup prompt scan finished {durationMs=173729}`, 2026-11-06), while the refresh on an
* install with a large backlog took 19–23 minutes (#6615, `durationMs=1393207`). Three minutes lets a typical first
* install finish organizing in place and caps the backlog case. Hitting the limit is logged.
*/
export const ORGANIZING_WAIT_MS = 3 * 60_000;
export interface SetupScanAgent {
id: PromptAgentId;
label: string;
detected: boolean;
/** The owner's prompts in the window: fromMemory + fromTranscripts. */
prompts: number;
/** Already in claude-mem's memory, recorded by its hooks. */
fromMemory: number;
/** Only in the agent's transcripts; stored by this import (now or by an earlier scan). */
fromTranscripts: number;
/**
* Whether this agent can run setup's extraction here (installed, logged in, account accepted), from the agent
* runner's detection. `null` for an agent the runner does not use, or until the check finishes.
*/
canRunSetup: boolean | null;
/** Why it cannot, in the detection's words (e.g. "Gemini is installed, but this Google account can't use it: ..."). */
cannotRunReason: string | null;
/**
* The JSON bytes this tool's prompts add to the hosted upload. The sum over the selected tools is never more than
* the upload's size, so a sum over INTENT_MAX_UPLOAD_BYTES means the upload cannot fit.
*/
uploadBytes: number;
}
export interface SetupScanState {
/** Optional improvement use only; false still runs the complete hosted extraction. */
improveProduct: boolean;
/** Which tools' prompts this scan sent to cmem.ai: null before the person answers, [] when nothing left this machine. */
uploadedAgents: PromptAgentId[] | null;
agents: SetupScanAgent[];
percent: number;
phase: SetupScanPhase;
done: boolean;
windowStart: string | null;
startedAt: string | null;
finishedAt: string | null;
durationMs: number | null;
/** Prompts newly stored by the last scan. */
added: number;
skippedSources: number;
error: string | null;
/** Token Savings: 30-day token totals per agent, read in the same pass. Set when the scan is done. */
usage: SetupTokenUsage | null;
/** Why the token totals could not be read; the prompt scan itself still finished. */
usageError: string | null;
/** Set when hosted extraction did not run (budget/rate limit, or the history exceeds the hosted upload cap) and setup finished locally without it. */
hostedNotice: string | null;
/** The owner's newest typed prompts, newest first, quoted as typed (the Reveal shows them while no agent can extract). */
recentPrompts: SetupRecentPrompt[];
}
export interface SetupRecentPrompt { agent: PromptAgentId; at: string; text: string }
const RECENT_PROMPTS = 5;
const RECENT_PROMPT_CHARACTERS = 280;
/** The SessionStore methods the scan uses. */
export interface SetupScanStore {
listHookRecordedPrompts(sinceEpochMs: number): Array<MemoryPrompt & { project: string }>;
importTranscriptUserPrompt(prompt: {
platformSource: string; contentSessionId: string; project: string; nativePromptId: string; promptText: string;
createdAtEpoch: number; hookTextVariants?: string[]; hookMatchWindowMs: number; claimedHookRowIds: Set<number>;
}): { reason: 'new' | 'already-imported' | 'recorded-by-hook' | 'private' | 'deleted'; hookRowId?: number };
/** claude-mem's observation history, for the Token Savings efficiency percent. */
streamObservationTokenFields(): Iterable<{ title: string | null; subtitle: string | null; narrative: string | null; facts: string | null; discovery_tokens: number | null }>;
}
export interface SetupScanOptions {
getStore: () => SetupScanStore;
scan?: typeof scanOwnerPrompts;
scanOptions?: Omit<PromptScanOptions, 'sinceEpochMs' | 'memoryPrompts' | 'onProgress'>;
readTokenUsage?: typeof scanTokenUsage;
now?: () => number;
/**
* Receives the hook-recorded prompts in the window that the owner did not type (an agent wrote them, or the
* transcripts hold that session without them), so extraction leaves them out.
*/
saveAgentWrittenPromptIds?: (promptIds: number[]) => void;
/** The agent runner's detection (installed, logged in, account usable). Waited for, however long it takes. */
detectAgents?: () => Promise<UsableAgent[]>;
/** Minimum gap between progress notifications while a phase runs. */
progressIntervalMs?: number;
/** How long the scan waits for the owner's own AI before finishing without it. Default ORGANIZING_WAIT_MS. */
organizingWaitMs?: number;
}
/** The agent runner's ids as the scan names those agents. */
const RUNNER_AGENT_IDS: Record<UsableAgentId, PromptAgentId> = { 'claude-code': 'claude-code', codex: 'codex', gemini: 'gemini-cli', opencode: 'opencode' };
const AGENT_LABELS: Array<[PromptAgentId, string]> = [
['claude-code', 'Claude Code'], ['codex', 'Codex'], ['gemini-cli', 'Gemini CLI'], ['antigravity-cli', 'Antigravity CLI'], ['opencode', 'OpenCode'],
];
/** Absence is evidence only when every known source for this session was read. */
function completeTranscript(summary: AgentScanSummary | undefined, sessionId: string): boolean {
return !!summary && summary.sessions.has(sessionId) && !summary.incompleteSessions?.has(sessionId);
}
function idleState(): SetupScanState {
return {
// This preference does not start an upload; discovery still requires the person's confirmation.
improveProduct: true,
uploadedAgents: null,
agents: AGENT_LABELS.map(([id, label]) => ({ id, label, detected: false, prompts: 0, fromMemory: 0, fromTranscripts: 0, canRunSetup: null, cannotRunReason: null, uploadBytes: 0 })),
percent: 0, phase: 'idle', done: false, windowStart: null, startedAt: null, finishedAt: null, durationMs: null,
added: 0, skippedSources: 0, error: null, usage: null, usageError: null, hostedNotice: null, recentPrompts: [],
};
}
export class SetupScan {
private current: SetupScanState = idleState();
private running: Promise<void> | null = null;
private localExtraction: (() => Promise<boolean>) | null = null;
/** The owner's own AI at work, from its start until it ends: a scan waits for it, or finished without it. */
private organizing: Promise<boolean> | null = null;
/** Ends a running wait for the owner's own AI: the page's Continue at 98%, or undefined outside a wait. */
private continueWait: (() => void) | undefined;
private pendingUpload: { ownerPrompts: OwnerPrompt[]; summary: Partial<SetupScanState>; startedAt: number } | null = null;
private listeners = new Set<(state: SetupScanState) => void>();
private lastNotified = 0;
private now: () => number;
private extract: ((prompts: OwnerPrompt[], improveProduct: boolean) => Promise<void>) | null = null;
constructor(private options: SetupScanOptions) {
this.now = options.now ?? Date.now;
}
state(): SetupScanState {
return structuredClone(this.current);
}
subscribe(listener: (state: SetupScanState) => void): () => void {
this.listeners.add(listener);
return () => this.listeners.delete(listener);
}
/** Returns false when the configured inference is unavailable. Only the consent route may then send prompts. */
setLocalExtractor(extract: () => Promise<boolean>): void {
this.localExtraction = extract;
}
/**
* Waits for the owner's own AI: 'finished' or 'unavailable' when it ends in time, 'background' when the wait limit
* passes or the person presses Continue. A refresh an earlier scan left in the background is joined, not started
* again. Its failure rejects only while a scan waits; after that it is logged, and the scan stays finished.
*/
private async organize(): Promise<'finished' | 'unavailable' | 'background'> {
const work = this.organizing ??= (async () => {
try {
return await this.localExtraction!();
} finally {
this.organizing = null;
}
})();
let timer: ReturnType<typeof setTimeout> | undefined;
let release: (() => void) | undefined;
// The person may end the wait themselves: setup must not hold them at 98% (#6615).
const continued = new Promise<'background'>(resolve => { release = () => resolve('background') });
this.continueWait = release;
const waitLimit = new Promise<'background'>(resolve => {
timer = setTimeout(() => resolve('background'), this.options.organizingWaitMs ?? ORGANIZING_WAIT_MS);
});
try {
const outcome = await Promise.race([work.then(finished => finished ? 'finished' as const : 'unavailable' as const), waitLimit, continued]);
if (outcome === 'background') {
logger.info('IMPORT', 'Setup scan finished without waiting for the owner\'s own AI; it continues in the background');
work.catch(error => logger.warn('IMPORT', 'The owner\'s own AI stopped after setup moved on', { error: String(error) }));
}
return outcome;
} finally {
this.continueWait = undefined;
clearTimeout(timer);
}
}
/**
* Ends the 98% wait at once, from the page's Continue, and answers the finished scan. The refresh it waited for
* keeps running in the background, so this never stops the owner's own AI. Outside that wait it answers the state
* as it is, so a stray request never parks on a reading scan, which has no time limit.
*/
async continueNow(): Promise<SetupScanState> {
const release = this.continueWait;
if (release === undefined) return this.state();
release();
// The wait resolves first; the scan's own finish is what the page must see, not the organizing state.
await this.running?.catch(() => {});
return this.state();
}
/** Hosted setup runs for the prompts the owner explicitly selects. */
setExtractor(extract: (prompts: OwnerPrompt[], improveProduct: boolean) => Promise<void>): void {
this.extract = extract;
}
setImproveProduct(improveProduct: boolean): SetupScanState {
if (this.current.phase === 'uploading') throw new Error('The setup upload has already started.');
this.update({ improveProduct }, true);
return this.state();
}
/** Starts a scan unless one is running. Resolves with the state at start. */
start(improveProduct?: boolean): SetupScanState {
// Waiting for the upload choice, or uploading: joining that state keeps a second scan from paying for a second upload.
const held = this.current.phase === 'awaiting-consent' || this.current.phase === 'uploading';
if (held) {
if (improveProduct !== undefined && this.current.phase === 'awaiting-consent') this.setImproveProduct(improveProduct);
} else if (!this.running) {
if (improveProduct !== undefined) this.setImproveProduct(improveProduct);
this.running = this.run().finally(() => { this.running = null; });
}
return this.state();
}
/** Waits for the running scan, if any (tests and the CLI). */
async finished(): Promise<SetupScanState> {
await this.running;
return this.state();
}
private update(changes: Partial<SetupScanState>, force = false): void {
this.current = { ...this.current, ...changes };
const now = this.now();
if (!force && now - this.lastNotified < (this.options.progressIntervalMs ?? 200)) return;
this.lastNotified = now;
const snapshot = this.state();
for (const listener of this.listeners) listener(snapshot);
}
private async tokenSavings(
store: SetupScanStore,
tokenUsage: ReturnType<typeof scanTokenUsage>,
): Promise<{ usage: SetupTokenUsage | null; usageError: string | null }> {
try {
return { usage: summarizeTokenUsage(await tokenUsage, observationTokenEconomics(store.streamObservationTokenFields())), usageError: null };
} catch (error) {
logger.error('IMPORT', 'Setup token usage could not be read', {}, error as Error);
return { usage: null, usageError: error instanceof Error ? error.message : String(error) };
}
}
/** Marks each agent the runner uses as able or unable to run setup here. Detection never throws. */
private async checkRunners(): Promise<void> {
if (!this.options.detectAgents) return;
const runners = await this.options.detectAgents();
this.update({
agents: this.current.agents.map(agent => {
const runner = runners.find(entry => RUNNER_AGENT_IDS[entry.id] === agent.id);
if (!runner) return agent;
const canRunSetup = runner.authenticated && runner.path !== null;
return { ...agent, canRunSetup, cannotRunReason: canRunSetup ? null : runner.reason };
}),
}, true);
}
private finish(summary: Partial<SetupScanState>, startedAt: number): void {
const finishedAt = this.now();
this.update({
...summary, phase: 'done', done: true, percent: 100,
finishedAt: new Date(finishedAt).toISOString(), durationMs: finishedAt - startedAt,
}, true);
logger.info('IMPORT', 'Setup prompt scan finished', { durationMs: finishedAt - startedAt });
}
/** The person's answer to "upload your last 30 days of prompts to cmem.ai?". Declining keeps everything local. */
async confirmUpload(allow: boolean, agents?: PromptAgentId[], improveProduct?: boolean): Promise<SetupScanState> {
const pending = this.pendingUpload;
if (this.current.phase !== 'awaiting-consent' || !pending) throw new Error('The setup scan is not waiting for an upload choice.');
this.pendingUpload = null;
// The sharing choice travels with the consent, so a delayed preference request can never leave a stale value.
if (improveProduct !== undefined) this.current = { ...this.current, improveProduct };
// Only the tools the person left ticked are uploaded; the rest never leave this machine.
const selected = agents ? pending.ownerPrompts.filter(prompt => agents.includes(prompt.agent)) : pending.ownerPrompts;
if (!allow || !selected.length) {
logger.info('IMPORT', 'Setup prompt upload declined; prompts stay on this machine');
this.current = { ...this.current, uploadedAgents: [] };
try {
// An empty hand-off records a finished, local-only extraction without contacting Cloud, so the reveal screen stops waiting.
await this.extract!([], this.current.improveProduct);
this.finish(pending.summary, pending.startedAt);
} catch (error) {
const finishedAt = this.now();
this.update({ phase: 'failed', done: true, error: error instanceof Error ? error.message : String(error), finishedAt: new Date(finishedAt).toISOString(), durationMs: finishedAt - pending.startedAt }, true);
}
return this.state();
}
try {
this.update({ phase: 'uploading', percent: 99, uploadedAgents: [...new Set(selected.map(prompt => prompt.agent))] }, true);
await this.extract!(selected, this.current.improveProduct);
this.finish(pending.summary, pending.startedAt);
} catch (error) {
const code = (error as { code?: string } | null)?.code;
if (code === 'hosted-unavailable' || code === 'hosted-too-large') {
// Preserve setup progress if automatic organization cannot run right now, or can never take a
// history over the upload cap: retrying that scan would fail the same way, so finish locally.
logger.warn('IMPORT', 'Hosted setup unavailable; continuing locally', { reason: (error as Error).message });
try {
await this.extract!([], this.current.improveProduct);
// A refusal of the upload itself arrives after the request was sent; a preflight or cooldown refusal sent nothing.
const sent = (error as { sent?: boolean }).sent !== false;
if (!sent) this.current = { ...this.current, uploadedAgents: [] };
const hostedNotice = code === 'hosted-too-large'
? 'Your recent work is larger than the hosted setup limit, so automatic organization did not run. You can continue setting up Claude-Mem.'
: 'Automatic organization is temporarily unavailable. You can continue setting up Claude-Mem.';
this.finish({ ...pending.summary, hostedNotice }, pending.startedAt);
return this.state();
} catch { /* fall through to the failure below */ }
}
const finishedAt = this.now();
logger.error('IMPORT', 'Setup prompt upload failed', {}, error as Error);
const nothingSent = (error as { sent?: boolean } | null)?.sent === false;
this.update({ phase: 'failed', done: true, error: error instanceof Error ? error.message : String(error), finishedAt: new Date(finishedAt).toISOString(), durationMs: finishedAt - pending.startedAt, ...(nothingSent ? { uploadedAgents: [] } : {}) }, true);
}
return this.state();
}
private async run(): Promise<void> {
const startedAt = this.now();
const windowStart = scanWindowStart(startedAt);
this.current = { ...idleState(), improveProduct: this.current.improveProduct, phase: 'reading', windowStart: new Date(windowStart).toISOString(), startedAt: new Date(startedAt).toISOString() };
this.update({}, true);
try {
const runnerCheck = this.checkRunners();
const store = this.options.getStore();
const memoryPrompts = store.listHookRecordedPrompts(windowStart);
// Token totals are read alongside the prompts, from the same transcripts and window.
const tokenUsage = (this.options.readTokenUsage ?? scanTokenUsage)({
sinceEpochMs: windowStart, homeDirectory: this.options.scanOptions?.homeDirectory, agents: this.options.scanOptions?.agents,
});
tokenUsage.catch(() => {}); // Awaited (and reported) in tokenSavings, after the prompts.
let lastPhase: PromptScanProgress['phase'] = 'reading';
const result = await (this.options.scan ?? scanOwnerPrompts)({
...this.options.scanOptions,
sinceEpochMs: windowStart,
memoryPrompts,
onProgress: progress => {
const share = progress.bytesTotal ? progress.bytesDone / progress.bytesTotal : 1;
const percent = Math.floor(progress.phase === 'reading' ? share * 50 : 50 + share * 45);
const agents = this.current.agents.map(agent => {
const summary = progress.agents.find(entry => entry.id === agent.id);
return summary ? { ...agent, detected: summary.detected, prompts: summary.typed } : agent;
});
this.update({ phase: progress.phase, percent, agents }, progress.phase !== lastPhase);
lastPhase = progress.phase;
},
});
this.update({ phase: 'saving', percent: 95 }, true);
const claimedHookRowIds = new Set<number>();
const fromTranscripts = new Map<string, number>();
const deletedPrompts = new Set<OwnerPrompt>();
let added = 0;
result.ownerPrompts.forEach((prompt: OwnerPrompt, index) => {
let outcome: ReturnType<SetupScanStore['importTranscriptUserPrompt']>;
try {
outcome = store.importTranscriptUserPrompt({
platformSource: prompt.platformSource, contentSessionId: prompt.sessionId, project: prompt.project,
nativePromptId: prompt.nativePromptId, promptText: prompt.text, createdAtEpoch: prompt.at,
hookTextVariants: prompt.hookTextVariants, hookMatchWindowMs: HOOK_MATCH_WINDOW_MS, claimedHookRowIds,
});
} catch (error) {
logger.warn('IMPORT', 'Could not store an imported prompt', { agent: prompt.agent, sessionId: prompt.sessionId, error: String(error) });
return;
}
if (outcome.reason === 'deleted') deletedPrompts.add(prompt);
if (outcome.reason === 'new') added++;
if (outcome.reason === 'new' || outcome.reason === 'already-imported') {
fromTranscripts.set(prompt.agent, (fromTranscripts.get(prompt.agent) ?? 0) + 1);
}
this.update({ percent: 95 + Math.floor((index / Math.max(1, result.ownerPrompts.length)) * 5) });
});
await runnerCheck;
// Hook-recorded prompts count once: matched to a transcript copy, or, when
// the transcripts cannot be completely read for that session, on their own. A hook row in
// a completely read session that did not match was not typed by the owner.
const agents = this.current.agents.map(agent => {
const summary = result.agents.find(entry => entry.id === agent.id);
if (!summary) return { ...agent, prompts: 0, fromMemory: 0, fromTranscripts: 0 };
const fromMemory = memoryPrompts.filter(prompt => prompt.platformSource === summary.platformSource
&& result.ownerMemoryPromptIds.has(prompt.id)
&& (claimedHookRowIds.has(prompt.id) || !completeTranscript(summary, prompt.contentSessionId))).length;
const transcriptOnly = fromTranscripts.get(agent.id) ?? 0;
return { ...agent, detected: summary.detected, fromMemory, fromTranscripts: transcriptOnly, prompts: fromMemory + transcriptOnly };
});
const sessionsByPlatform = new Map(result.agents.map(summary => [summary.platformSource, summary]));
// Prompts whose transcripts are missing or incomplete can still exist in memory; extraction reads them too.
// They get the same tag stripping and current redaction as transcript prompts: they may predate both.
const memoryOnly: OwnerPrompt[] = memoryPrompts.flatMap(prompt => {
const summary = result.agents.find(entry => entry.platformSource === prompt.platformSource);
if (!summary || !result.ownerMemoryPromptIds.has(prompt.id) || claimedHookRowIds.has(prompt.id) || completeTranscript(summary, prompt.contentSessionId)) return [];
const text = stripMemoryTags(prompt.promptText).trim();
if (!text) return [];
return [{ agent: summary.id, platformSource: prompt.platformSource, sessionId: prompt.contentSessionId, nativePromptId: `memory-${prompt.id}`,
at: prompt.createdAtEpoch, cwd: prompt.cwd ?? null, text, project: prompt.project ?? '' }];
});
const ownerPrompts = [...result.ownerPrompts.filter(prompt => !deletedPrompts.has(prompt)), ...memoryOnly];
const uploadBytes = new Map<PromptAgentId, number>();
// One byte more per prompt for the comma that joins it to the next one in the upload's array.
for (const prompt of ownerPrompts) uploadBytes.set(prompt.agent, (uploadBytes.get(prompt.agent) ?? 0) + Buffer.byteLength(JSON.stringify(prompt)) + 1);
const notTyped = memoryPrompts.filter(prompt => !result.ownerMemoryPromptIds.has(prompt.id)
|| (!claimedHookRowIds.has(prompt.id) && completeTranscript(sessionsByPlatform.get(prompt.platformSource), prompt.contentSessionId)));
this.options.saveAgentWrittenPromptIds?.(notTyped.map(prompt => prompt.id));
const { usage, usageError } = await this.tokenSavings(store, tokenUsage);
const recentPrompts = [...ownerPrompts].sort((left, right) => right.at - left.at).slice(0, RECENT_PROMPTS)
.map(prompt => ({ agent: prompt.agent, at: new Date(prompt.at).toISOString(), text: prompt.text.trim().slice(0, RECENT_PROMPT_CHARACTERS) }));
const summary = { agents: agents.map(agent => ({ ...agent, uploadBytes: uploadBytes.get(agent.id) ?? 0 })), added, skippedSources: result.skippedSources.length, usage, usageError, recentPrompts };
if (ownerPrompts.length && this.localExtraction) {
this.update({ phase: 'organizing', percent: 98, ...summary }, true);
const organized = await this.organize();
if (organized !== 'unavailable') {
this.finish(summary, startedAt);
return;
}
}
if (this.extract && !ownerPrompts.length) {
// Nothing to upload, so there is nothing to ask about; the extractor records an empty result without contacting Cloud.
this.update({ phase: 'uploading', percent: 99, ...summary }, true);
await this.extract(ownerPrompts, this.current.improveProduct);
} else if (this.extract) {
// Prompts leave this machine only after an explicit choice. Hold them in memory and wait for confirmUpload().
this.pendingUpload = { ownerPrompts, summary, startedAt };
this.update({ phase: 'awaiting-consent', percent: 98, ...summary }, true);
return;
}
this.finish(summary, startedAt);
} catch (error) {
const finishedAt = this.now();
logger.error('IMPORT', 'Setup prompt scan failed', {}, error as Error);
this.update({ phase: 'failed', done: true, error: error instanceof Error ? error.message : String(error), finishedAt: new Date(finishedAt).toISOString(), durationMs: finishedAt - startedAt }, true);
}
}
}