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
import { requestEvidenceRefs } from './request-evidence-refs.mjs';
// Bun's native SQLite reader; source data is never opened for writing.
import { Database as DatabaseSync } from 'bun:sqlite';
import { readFileSync, statSync } from 'node:fs';
import { homedir } from 'node:os';
import { join } from 'node:path';
import { createHash } from 'node:crypto';
import { readWorkStateRows, reduceWorkState } from './work-state-reduce.mjs';
import { activitySignature, buildAgentView, DEFAULT_RECENT_ACTIVITY_MS, readAgentRecords, readEvidence } from './agent-view.mjs';
import { ledgerSignature, openSuggestions, readLedger } from './request-groups.mjs';
import { recordedFile, bucketFileAvailable, copyCoversSource, servableFile } from './work-product.mjs';
import { buildRules, MY_RULES_LIST } from './my-rules.mjs';
import { readSharedRecords, workStateRowsRevision } from './shared-record-store.mjs';
import { readWorkStateLabels, WORK_STATE_LABELS_FILE } from './work-state-labels.mjs';
import { applySharedProjection, decorateSharedView, isSharedProjectionValue } from './shared-projection.mjs';
import { sharedReviewDescriptor, readSharedReview, sharedSuggestionDescriptor, sharedConflictSuggestions } from './shared-reviews.mjs';
// reduceWorkState lives in work-state-reduce.mjs so my-focus.mjs can replay rows without importing this module.
export { reduceWorkState } from './work-state-reduce.mjs';
// Kept here for the callers that already import it from the data source.
export { readFocus, readFocusAreas } from './my-focus.mjs';
const normalizedKey = (value) => String(value).replace(/[A-Z]/g, (letter) => letter.toLowerCase());
// Compare against the observations used to build the view, not a second stat
// after rendering: a file can change while linked evidence is being read.
// Saved copies also retain the coverage decision for their suppressed source.
function productFilesChanged(files) {
return files.some(({ product, available, coversSource }) => {
const current = product.path ? Boolean(servableFile(product)) : product.deliverable ? bucketFileAvailable(product) : true;
return current !== available || coversSource !== null && copyCoversSource(product, product.sourcePath) !== coversSource;
});
}
// Expand the same inherited read keys as SessionStore.getProjectReadKeys. A
// worktree's older lists may be stored under a previously merged project key.
export function resolveReadScope(database, requestedKeys) {
const keys = [...new Set(requestedKeys.map((key) => key.trim()).filter(Boolean))];
if (!keys.length) return [];
const marks = keys.map(() => '?').join(',');
const queries = [
`SELECT project AS key FROM sdk_sessions WHERE project COLLATE NOCASE IN (${marks})`,
`SELECT project FROM observations WHERE project COLLATE NOCASE IN (${marks})`,
`SELECT merged_into_project FROM observations WHERE merged_into_project COLLATE NOCASE IN (${marks})`,
`SELECT project FROM session_summaries WHERE project COLLATE NOCASE IN (${marks})`,
`SELECT merged_into_project FROM session_summaries WHERE merged_into_project COLLATE NOCASE IN (${marks})`,
`SELECT project FROM observations WHERE merged_into_project COLLATE NOCASE IN (${marks})`,
`SELECT project FROM session_summaries WHERE merged_into_project COLLATE NOCASE IN (${marks})`,
];
// Minimal fixtures and older databases may not have the merge schema. The
// explicit requested projects remain useful without inherited keys.
try {
const rows = database.prepare(queries.join(' UNION ')).all(...queries.flatMap(() => keys));
return [...new Set([...keys, ...rows.map((row) => row.key).filter(Boolean)])];
} catch (error) {
if (/no such (table|column)/i.test(String(error.message))) return keys;
throw error;
}
}
export class WorkStateSource {
constructor({
databasePath = process.env.CLAUDE_MEM_DB ?? join(homedir(), '.claude-mem', 'claude-mem.db'),
currentProject = '',
parentProject = currentProject,
titleCachePath = null,
ledgerDir = null,
pollIntervalMs = 1000,
localDeviceId = '',
} = {}) {
this.databasePath = databasePath;
this.currentProject = currentProject;
this.parentProject = parentProject;
this.pollIntervalMs = pollIntervalMs;
this.localDeviceId = localDeviceId;
this.titleCachePath = titleCachePath;
this.titleCache = {};
this.titleCacheSignature = null;
this.ledgerDir = ledgerDir;
this.ledger = null;
this.ledgerSignature = null;
this.workStateLabels = null;
this.labelsSignature = null;
this.database = null;
this.databaseIdentity = null;
this.cachedState = reduceWorkState([], { currentProject, currentProjectScope: [parentProject, currentProject] });
this.agentView = buildAgentView(this.cachedState, {});
this.productFiles = [];
this.agentRevision = 0;
this.activitySignature = null;
this.activityCheckedAt = null;
this.signature = null;
this.workStateRevision = null;
this.workStateDataVersion = null;
this.sharedState = null;
this.source = {
kind: 'claude-mem-work-state', mode: 'read-only-sqlite', connected: false,
pollIntervalMs, lastCheckedAt: null, lastUpdatedAt: null, error: null,
};
}
openDatabase() {
// stat prevents creating a database if the configured file does not exist.
const stat = statSync(this.databasePath);
const identity = `${stat.dev}:${stat.ino}`;
if (!this.database || identity !== this.databaseIdentity) {
this.close();
this.database = new DatabaseSync(this.databasePath, { readonly: true, create: false });
this.database.exec('PRAGMA query_only = ON');
this.database.exec('PRAGMA busy_timeout = 1500');
this.columns = new Set(this.database.prepare('PRAGMA table_info(work_state_entries)').all().map(column => column.name));
this.databaseIdentity = identity;
this.signature = null;
this.sharedState = null;
this.activitySignature = null;
this.activityCheckedAt = null;
}
return this.database;
}
read({ maxActivityAgeMs = 0 } = {}) {
this.source.lastCheckedAt = new Date().toISOString();
try {
const database = this.openDatabase();
// This connection is read-only: without another connection's commit,
// the aggregate cannot change. Avoid scanning all synced work-state
// rows on every idle poll; data_version also catches edits and deletes.
const dataVersion = database.prepare('PRAGMA data_version').get().data_version;
let revision = this.workStateRevision;
if (!revision || dataVersion !== this.workStateDataVersion) {
revision = workStateRowsRevision(database, { syncRev: this.columns.has('sync_rev') });
this.workStateRevision = revision;
this.workStateDataVersion = dataVersion;
}
const signature = `${revision}:${this.localDeviceId}`;
const previousTitles = this.titleCacheSignature;
const previousLedger = this.ledgerSignature;
const previousLabels = this.labelsSignature;
this.readTitleCache();
this.readLedger();
this.readWorkStateLabels();
if (!this.sharedState || signature !== this.signature) this.sharedState = readSharedRecords(database, { deviceId: this.localDeviceId, validateValue: isSharedProjectionValue, reviewStack: 'exclude' });
const now = Date.now();
// Only background polling opts into this window. Direct reads (including
// review writes) must still notice evidence edits that retain row IDs.
// Owner edits and generated copy bypass it, even during a busy session.
const reuseActivity = this.source.connected && signature === this.signature
&& previousTitles === this.titleCacheSignature && previousLedger === this.ledgerSignature && previousLabels === this.labelsSignature
&& this.activityCheckedAt !== null && now >= this.activityCheckedAt
&& now - this.activityCheckedAt < maxActivityAgeMs;
const activity = reuseActivity ? this.activitySignature
: `${activitySignature(database)}|titles:${this.titleCacheSignature}|ledger:${this.ledgerSignature}|labels:${this.labelsSignature}`;
const filesChanged = !reuseActivity && productFilesChanged(this.productFiles);
if (signature !== this.signature || activity !== this.activitySignature || filesChanged || !this.source.connected) {
database.exec('BEGIN');
try {
// Resolve shared evidence only when rebuilding. A cached poll needs
// no per-object lookup; each fresh build resolves again so a prompt
// or work-state row arriving after its shared reference is visible.
const sharedLedger = applySharedProjection(database, this.sharedState, { ledger: this.ledger, deviceId: this.localDeviceId }).ledger;
if (signature !== this.signature || !this.source.connected) {
const entries = readWorkStateRows(database);
const currentProjectScope = resolveReadScope(database, [this.parentProject, this.currentProject]);
const requested = new Set([this.parentProject, this.currentProject].map(normalizedKey));
// Match worker's scope_project only for directly requested legacy keys.
const scopedEntries = entries.map((entry) => requested.has(normalizedKey(entry.project)) ? { ...entry, scope_project: this.currentProject } : entry);
this.cachedState = reduceWorkState(scopedEntries, { currentProject: this.currentProject, currentProjectScope, localDeviceId: this.localDeviceId });
}
this.agentRevision++;
const records = readAgentRecords(database, { workState: this.cachedState, ledger: sharedLedger });
const shared = applySharedProjection(database, this.sharedState, { ledger: this.ledger, records, deviceId: this.localDeviceId });
const productFiles = [];
this.agentView = { ...decorateSharedView(buildAgentView(this.cachedState, shared.records, {
titleCache: this.titleCache, ledger: shared.ledger, workStateLabels: this.workStateLabels,
onProductFile: (product, available, coversSource) => productFiles.push({ product, available, coversSource }),
}), { ...shared, database, deviceId: this.localDeviceId }), revision: this.agentRevision };
this.projectedLedger = shared.ledger;
this.agentView.sharedState = { revision: this.sharedState.revision, ...shared.diagnostics };
// Hash full linked evidence without sending its potentially large raw
// text in every snapshot. A review covers the source disclosure too.
const evidenceHashes = new Map();
const evidenceRows = new Map();
for (const request of this.agentView.humanRequests) {
const refs = requestEvidenceRefs(request);
request.sourceContentHashes = [...refs].sort(([a], [b]) => a.localeCompare(b)).map(([key, ref]) => {
if (!evidenceHashes.has(key)) {
const evidence = readEvidence(database, ref.kind, ref.id);
evidenceRows.set(key, evidence);
evidenceHashes.set(key, createHash('sha256').update(JSON.stringify(evidence)).digest('hex'));
}
return { ...ref, hash: evidenceHashes.get(key) };
});
if (this.localDeviceId) {
request.sharedReviewDescriptor = sharedReviewDescriptor(database, request, { deviceId: this.localDeviceId, sharedState: this.sharedState, evidenceRows });
request.sharedReview = readSharedReview(this.sharedState, request.sharedReviewDescriptor);
}
}
this.signature = signature;
this.activitySignature = activity;
this.productFiles = productFiles;
database.exec('COMMIT');
} catch (error) {
database.exec('ROLLBACK');
throw error;
}
}
if (!reuseActivity) this.activityCheckedAt = now;
this.source.activityCheckedAt = this.activityCheckedAt === null ? null : new Date(this.activityCheckedAt).toISOString();
this.source.connected = true;
this.source.error = null;
this.source.lastUpdatedAt = this.cachedState.lastUpdatedAt;
} catch (error) {
this.source.connected = false;
// Do not expose paths, SQL, environment, or any raw worker reply.
this.source.error = /ENOENT/.test(String(error.code)) ? 'Local work-state database is unavailable.' : 'Local work-state database could not be read. Retrying.';
this.close();
}
return this.snapshot();
}
/** Rules do not need tool/product discovery or request evidence hashes. */
readRules() {
const checkedAt = new Date().toISOString();
try {
const database = this.openDatabase();
// Only the My Rules list feeds the reducer, read as the story step reads the rejected rules (request-groups.mjs
// dismissedRuleStatements). The shared rows come through the row cache, which parses only rows it has not seen.
const entries = readWorkStateRows(database, { listName: MY_RULES_LIST, columns: this.columns });
let story = null;
let storyError = null;
if (this.ledgerDir) {
try { story = JSON.parse(readFileSync(join(this.ledgerDir, 'story.json'), 'utf8')); }
catch (error) { if (error.code !== 'ENOENT') storyError = error; }
}
const shared = readSharedRecords(database, { deviceId: this.localDeviceId, validateValue: isSharedProjectionValue, reviewStack: 'exclude' });
if (storyError && ![...shared.records.values()].some(record => record.kind === 'story' && record.key === 'current')) throw storyError;
story = applySharedProjection(database, shared, { ledger: { story }, deviceId: this.localDeviceId }).ledger.story;
const state = reduceWorkState(entries, { localDeviceId: this.localDeviceId });
return { ...buildRules(state, { story }), source: { connected: true, error: null, lastCheckedAt: checkedAt } };
} catch {
return { rules: [], source: { connected: false, error: 'Local rules could not be read. Retrying.', lastCheckedAt: checkedAt } };
}
}
/** A known content commit invalidates activity; unrelated database writes still use the bounded window. */
invalidateActivity(workState = false) {
this.activityCheckedAt = null;
if (workState) {
this.signature = null;
this.workStateRevision = null;
}
}
snapshot() {
return {
...this.cachedState, generatedAt: new Date().toISOString(),
agentView: this.agentsSnapshot(),
source: { ...this.source, stale: !this.source.connected && this.cachedState.entryCount > 0 },
};
}
readTitleCache() {
let signature = 'missing';
try {
if (!this.titleCachePath) throw new Error('Cache disabled');
const stat = statSync(this.titleCachePath);
signature = `${stat.dev}:${stat.ino}:${stat.mtimeMs}:${stat.size}`;
if (signature === this.titleCacheSignature) return;
if (stat.size > 1024 * 1024) throw new Error('Cache too large');
const parsed = JSON.parse(readFileSync(this.titleCachePath, 'utf8'));
this.titleCache = parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed : {};
} catch {
this.titleCache = {};
}
this.titleCacheSignature = signature;
}
/** Jev's work-state labels (work-state-labels.mjs), reread when the file changes. Unreadable: no labels, and
* the error is kept on the source so the snapshot reports it instead of showing items as if never labeled. */
readWorkStateLabels() {
let signature = 'disabled';
if (this.ledgerDir) {
try { const stat = statSync(join(this.ledgerDir, WORK_STATE_LABELS_FILE)); signature = `${stat.mtimeMs}:${stat.size}`; }
catch (error) { signature = error?.code === 'ENOENT' ? 'missing' : `unreadable:${error?.code ?? 'error'}`; }
}
if (signature === this.labelsSignature) return;
this.labelsSignature = signature;
this.source.labelsError = null;
try { this.workStateLabels = this.ledgerDir ? readWorkStateLabels(this.ledgerDir) : null; }
catch (error) { this.workStateLabels = null; this.source.labelsError = String(error?.message ?? error).slice(0, 300); }
}
readLedger() {
const signature = this.ledgerDir ? ledgerSignature(this.ledgerDir) : 'disabled';
if (signature === this.ledgerSignature) return;
try { this.ledger = this.ledgerDir ? readLedger(this.ledgerDir) : null; }
catch { this.ledger = null; }
this.ledgerSignature = signature;
}
agentsSnapshot() {
const now = Date.now();
// The judge's suggestions ("Looks like part of <request>"), each on the card of the conversation it is about.
const ledger = this.projectedLedger ?? this.ledger;
const suggestionMap = new Map(openSuggestions(ledger).map(suggestion => [suggestion.conversationKey, suggestion]));
for (const suggestion of sharedConflictSuggestions(this.sharedState)) suggestionMap.set(suggestion.conversationKey, suggestion);
const suggestions = [...suggestionMap.values()].map(suggestion => {
if (!this.localDeviceId) return suggestion;
const descriptor = sharedSuggestionDescriptor(this.sharedState, suggestion.conversationKey);
return { ...suggestion, expectedSuggestionHash: descriptor.hash, sharedConflict: descriptor.conflict };
});
const humanRequests = (this.agentView.humanRequests ?? []).map((request) => {
const suggestion = suggestions.find((entry) => (entry.sharedConflict || entry.requestId !== request.groupId) && (request.conversationKeys ?? []).includes(entry.conversationKey));
return suggestion ? { ...request, suggestion } : request;
});
return {
...this.agentView,
humanRequests,
suggestions,
teamMode: process.env.WORK_STATE_TEAM_MODE === '1',
// Progress reviews and the build story come from the request-progress
// skill; they are assessments, separate from recorded lifecycle.
story: ledger ? { reviews: Object.values(ledger.progress), story: ledger.story, groups: Object.keys(ledger.groups.groups).length } : null,
// The automatic refresh's last run (refresh.json): running, ok, failed or waiting-for-agent.
refresh: ledger?.refresh ?? null,
// Age labels change with the clock without declaring a task or session
// live. Stored session status remains separate from recent activity.
agents: this.agentView.agents.map((agent) => ({ ...agent, presence: {
...agent.presence,
// A recorded finish is evidence, not an age label: the clock never changes it.
status: agent.presence.status === 'finished' ? 'finished' : !agent.presence.lastActivityAt ? 'unknown' : now - Date.parse(agent.presence.lastActivityAt) <= DEFAULT_RECENT_ACTIVITY_MS ? 'recent' : 'quiet',
} })),
source: { ...this.source, kind: 'claude-mem-recorded-agent-activity', lastUpdatedAt: this.agentView.agents[0]?.presence.lastActivityAt ?? null, stale: !this.source.connected && this.agentView.agents.length > 0 },
};
}
evidence(kind, id) {
try { return readEvidence(this.openDatabase(), kind, id); }
catch { return null; }
}
/** The local file a recorded work product names, or null. */
file(kind, id, index, localDeviceId = this.localDeviceId) {
try { return recordedFile((sql, params) => this.openDatabase().prepare(sql).all(...params), kind, id, index, localDeviceId); }
catch { return null; }
}
/** The bucket copy a deliverables row names, while it still exists; null when the row is unknown, the copy is gone, or the table does not exist yet. */
deliverable(id) {
if (!Number.isSafeInteger(id) || id < 1) return null;
try {
const row = this.openDatabase().prepare('SELECT id, title, kind, bucket_path FROM deliverables WHERE id = ?').all(id)[0];
return row && bucketFileAvailable({ bucketPath: row.bucket_path }) ? { id: row.id, title: row.title, kind: row.kind, path: row.bucket_path } : null;
} catch { return null; }
}
close() {
this.database?.close();
this.database = null;
this.databaseIdentity = null;
this.workStateRevision = null;
this.workStateDataVersion = null;
}
}