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 { logger } from '../../../utils/logger.js';
import type { ObservationSearchResult } from '../../sqlite/types.js';
import type { SessionStore } from '../../sqlite/SessionStore.js';
import type { SearchOrchestrator } from '../search/SearchOrchestrator.js';
import { parseStringListField } from '../../sync/string-list-field.js';
import { epochMs } from '../../../shared/epoch-ms.js';
import { CorpusRenderer } from './CorpusRenderer.js';
import { CorpusStore } from './CorpusStore.js';
import type { CorpusFile, CorpusFilter, CorpusObservation, CorpusStats } from './types.js';
function safeParseJsonArray(value: unknown): string[] {
if (Array.isArray(value)) return value.filter((v): v is string => typeof v === 'string');
if (typeof value !== 'string') return [];
try {
const parsed = JSON.parse(value);
return Array.isArray(parsed) ? parsed.filter((v): v is string => typeof v === 'string') : [];
} catch (error) {
if (error instanceof Error) {
logger.warn('WORKER', 'Failed to parse JSON array field', {}, error);
} else {
logger.warn('WORKER', 'Failed to parse JSON array field (non-Error thrown)', { thrownValue: String(error) });
}
return [];
}
}
export class CorpusBuilder {
private renderer: CorpusRenderer;
constructor(
private sessionStore: SessionStore,
private searchOrchestrator: SearchOrchestrator,
private corpusStore: CorpusStore
) {
this.renderer = new CorpusRenderer();
}
async build(
name: string,
description: string,
filter: CorpusFilter,
options: { writeFile?: boolean } = {}
): Promise<CorpusFile> {
logger.debug('WORKER', `Building corpus "${name}" with filter`, { filter });
// A corpus contains observations; unrelated prompts and summaries must
// not consume the semantic search candidate window.
const searchArgs: Record<string, unknown> = { searchType: 'observations', limit: filter.limit ?? 500 };
if (filter.project) searchArgs.project = filter.project;
if (filter.types && filter.types.length > 0) searchArgs.obs_type = filter.types.join(',');
if (filter.concepts && filter.concepts.length > 0) searchArgs.concepts = filter.concepts;
if (filter.files && filter.files.length > 0) searchArgs.files = filter.files;
if (filter.query) searchArgs.query = filter.query;
if (filter.date_start) searchArgs.dateStart = filter.date_start;
if (filter.date_end) searchArgs.dateEnd = filter.date_end;
// The stored filter is the whole definition of a corpus; the 90-day window interactive
// search applies to date-less Chroma queries would shrink it on every rebuild.
searchArgs.ignoreDefaultRecencyWindow = true;
const searchResult = await this.searchOrchestrator.search(searchArgs);
const observationIds = (searchResult.results.observations || []).map(
(obs: { id: number }) => obs.id
);
logger.debug('WORKER', `Search returned ${observationIds.length} observation IDs`);
const hydrateOptions: { orderBy?: 'date_asc' | 'date_desc'; limit?: number; projects?: string[]; type?: string | string[] } = {
orderBy: 'date_asc',
};
// Hydration must retain the same adopted-project scope as selection.
if (filter.project) hydrateOptions.projects = this.sessionStore.getProjectReadKeys([filter.project]);
if (filter.types && filter.types.length > 0) hydrateOptions.type = filter.types;
if (filter.limit) hydrateOptions.limit = filter.limit;
const observationRows = observationIds.length > 0
? this.sessionStore.getObservationsByIds(observationIds, hydrateOptions)
: [];
logger.debug('WORKER', `Hydrated ${observationRows.length} observation records`);
const observations = observationRows.map(row => this.mapObservationToCorpus(row));
const stats = this.calculateStats(observations);
const now = new Date().toISOString();
const corpus: CorpusFile = {
version: 1,
name,
description,
created_at: now,
updated_at: now,
filter,
stats,
system_prompt: '',
session_id: null,
observations,
};
corpus.system_prompt = this.renderer.generateSystemPrompt(corpus);
const renderedText = this.renderer.renderCorpus(corpus);
corpus.stats.token_estimate = this.renderer.estimateTokens(renderedText);
if (options.writeFile !== false) {
this.corpusStore.write(corpus);
}
logger.debug('WORKER', `Corpus "${name}" built with ${observations.length} observations, ~${corpus.stats.token_estimate} tokens`);
return corpus;
}
private mapObservationToCorpus(row: ObservationSearchResult): CorpusObservation {
return {
id: row.id,
type: row.type,
title: row.title || '',
subtitle: row.subtitle || null,
narrative: row.narrative || row.text || null,
facts: parseStringListField(row.facts, 'facts', row.id),
concepts: parseStringListField(row.concepts, 'concepts', row.id),
files_read: safeParseJsonArray(row.files_read),
files_modified: safeParseJsonArray(row.files_modified),
project: row.project,
created_at: row.created_at,
created_at_epoch: row.created_at_epoch,
};
}
private calculateStats(observations: CorpusObservation[]): CorpusStats {
const typeBreakdown: Record<string, number> = Object.create(null);
let earliestEpoch = Infinity;
let latestEpoch = -Infinity;
for (const obs of observations) {
typeBreakdown[obs.type] = (typeBreakdown[obs.type] || 0) + 1;
// Legacy rows may hold seconds (see shared/epoch-ms.ts); raw, one would
// drag the earliest bound back to 1970 and drop out of the latest max.
const epoch = epochMs(obs.created_at_epoch);
if (epoch < earliestEpoch) earliestEpoch = epoch;
if (epoch > latestEpoch) latestEpoch = epoch;
}
const earliest = observations.length > 0
? new Date(earliestEpoch).toISOString()
: new Date().toISOString();
const latest = observations.length > 0
? new Date(latestEpoch).toISOString()
: new Date().toISOString();
return {
observation_count: observations.length,
token_estimate: 0, // Will be updated after rendering
date_range: { earliest, latest },
type_breakdown: typeBreakdown,
};
}
}