feat(memory): add the memory contract and the local mem0 store (P0.3)

@waggle/memory-contract defines MemoryStore: remember (text, or a
conversation to extract facts from), search, list, count, get, update,
forget, forgetMatching and history over personal and workspace scopes,
with kinds, importance, source, origin and session in place of the old
content prefixes and named sessions. It ships an in-memory store and a
compatibility suite that every implementation runs.

@waggle/memory-mem0 implements the contract on mem0ai 3.3.1 in-process:
SQLite files in one directory, scope as mem0's agent_id, Waggle's own
embedder through mem0's langchain provider, fact extraction through any
OpenAI-compatible endpoint. mem0's telemetry and remote notice download
are switched off before the module loads; a test asserts that no request
is made. Memory survives a restart (tested).

New dependencies: mem0ai 3.3.1 (Apache-2.0, pinned exactly) with its
required peers compromise (MIT) and @cloudflare/workers-types (MIT OR
Apache-2.0); transitive openai (Apache-2.0), axios (MIT) and others under
MIT or BSD-2-Clause.
This commit is contained in:
shumeiko.it
2026-10-18 14:28:13 +02:00
parent 5e0c369f55
commit cd6553061b
14 changed files with 1751 additions and 11 deletions

View File

@@ -0,0 +1,19 @@
{
"name": "@waggle/memory-contract",
"version": "0.1.0",
"description": "The interface Waggle uses to reach memory, plus an in-memory implementation for development and tests",
"license": "MIT",
"type": "module",
"exports": {
".": {
"types": "./dist/index.d.ts",
"import": "./dist/index.js"
}
},
"main": "dist/index.js",
"types": "dist/index.d.ts",
"scripts": {
"build": "tsc",
"test": "node ../../node_modules/vitest/vitest.mjs run --root ../.. --config vitest.config.ts packages/memory-contract/tests"
}
}

View File

@@ -0,0 +1,114 @@
import {
MEMORY_IMPORTANCE,
MEMORY_KINDS,
MEMORY_SOURCES,
RESERVED_METADATA_KEYS,
type ConversationMessage,
type MemoryFilter,
type MemoryImportance,
type MemoryKind,
type MemoryScope,
type MemorySource,
type RememberInput,
} from './types.js';
export const PERSONAL_SCOPE: MemoryScope = { kind: 'personal' };
export function workspaceScope(workspaceId: string): MemoryScope {
if (!workspaceId.trim()) throw new TypeError('workspaceId must not be empty');
return { kind: 'workspace', workspaceId };
}
/** Stable string form of a scope: 'personal' or 'workspace:<id>'. */
export function scopeKey(scope: MemoryScope): string {
return scope.kind === 'personal' ? 'personal' : `workspace:${scope.workspaceId}`;
}
export function scopeFromKey(key: string): MemoryScope | null {
if (key === 'personal') return PERSONAL_SCOPE;
if (key.startsWith('workspace:') && key.length > 'workspace:'.length) {
return { kind: 'workspace', workspaceId: key.slice('workspace:'.length) };
}
return null;
}
/** Importance levels at or above `min`. */
export function importanceAtLeast(min: MemoryImportance): MemoryImportance[] {
return MEMORY_IMPORTANCE.slice(0, MEMORY_IMPORTANCE.indexOf(min) + 1);
}
export interface NormalizedRememberInput {
readonly scope: MemoryScope;
readonly text: string | null;
readonly conversation: readonly ConversationMessage[] | null;
readonly kind: MemoryKind;
readonly importance: MemoryImportance;
readonly source: MemorySource;
readonly origin: string | null;
readonly sessionId: string | null;
readonly metadata: Readonly<Record<string, unknown>>;
}
/** Validates a `remember` call and fills in the defaults. Throws `TypeError` on bad input. */
export function normalizeRememberInput(input: RememberInput): NormalizedRememberInput {
assertScope(input.scope);
const hasText = input.text !== undefined;
const hasConversation = input.conversation !== undefined;
if (hasText === hasConversation) {
throw new TypeError('remember needs exactly one of text and conversation');
}
const text = hasText ? input.text!.trim() : null;
if (hasText && !text) throw new TypeError('text must not be empty');
if (hasConversation && !input.conversation!.some((m) => m.content.trim())) {
throw new TypeError('conversation must contain at least one non-empty message');
}
const kind = input.kind ?? 'fact';
const importance = input.importance ?? 'normal';
const source = input.source ?? 'agent_inferred';
assertOneOf('kind', kind, MEMORY_KINDS);
assertOneOf('importance', importance, MEMORY_IMPORTANCE);
assertOneOf('source', source, MEMORY_SOURCES);
const metadata = input.metadata ?? {};
assertNoReservedKeys(metadata);
return {
scope: input.scope,
text,
conversation: hasConversation ? input.conversation! : null,
kind,
importance,
source,
origin: input.origin ?? null,
sessionId: input.sessionId ?? null,
metadata,
};
}
export function assertFilter(filter: MemoryFilter): void {
if (filter.scopes.length === 0) throw new TypeError('filter needs at least one scope');
for (const scope of filter.scopes) assertScope(scope);
for (const kind of filter.kinds ?? []) assertOneOf('kind', kind, MEMORY_KINDS);
if (filter.minImportance !== undefined) {
assertOneOf('minImportance', filter.minImportance, MEMORY_IMPORTANCE);
}
}
export function assertNoReservedKeys(metadata: Readonly<Record<string, unknown>>): void {
for (const key of RESERVED_METADATA_KEYS) {
if (key in metadata) throw new TypeError(`metadata key "${key}" is reserved`);
}
}
function assertScope(scope: MemoryScope): void {
if (scope.kind === 'workspace' && !scope.workspaceId?.trim()) {
throw new TypeError('workspace scope needs a workspaceId');
}
if (scope.kind !== 'personal' && scope.kind !== 'workspace') {
throw new TypeError(`unknown scope kind: ${String((scope as { kind: unknown }).kind)}`);
}
}
function assertOneOf<T extends string>(name: string, value: string, allowed: readonly T[]): void {
if (!allowed.includes(value as T)) {
throw new TypeError(`${name} must be one of ${allowed.join(', ')} (got "${value}")`);
}
}

View File

@@ -0,0 +1,179 @@
import { randomUUID } from 'node:crypto';
import {
assertFilter,
assertNoReservedKeys,
importanceAtLeast,
normalizeRememberInput,
scopeKey,
} from './helpers.js';
import {
MemoryCapabilityError,
MemoryNotFoundError,
type MemoryCapabilities,
type MemoryChange,
type MemoryFilter,
type MemoryHistoryEntry,
type MemoryHit,
type MemoryQuery,
type MemoryRecord,
type MemoryStore,
type MemoryUpdate,
type RememberInput,
} from './types.js';
const CAPABILITIES: MemoryCapabilities = {
extraction: false,
semanticSearch: false,
history: true,
knowledgeGraph: false,
};
/**
* A `MemoryStore` that keeps everything in process memory. Search ranks by
* shared words. Meant for development and tests; nothing survives a restart.
*/
export function createInMemoryMemoryStore(): MemoryStore {
const records = new Map<string, MemoryRecord>();
const histories = new Map<string, MemoryHistoryEntry[]>();
let closed = false;
const ensureOpen = (): void => {
if (closed) throw new Error('memory store is closed');
};
const log = (id: string, entry: MemoryHistoryEntry): void => {
histories.set(id, [...(histories.get(id) ?? []), entry]);
};
const matching = (filter: MemoryFilter): MemoryRecord[] => {
assertFilter(filter);
const scopes = new Set(filter.scopes.map(scopeKey));
const importance = filter.minImportance ? new Set(importanceAtLeast(filter.minImportance)) : null;
return [...records.values()].filter((r) =>
scopes.has(scopeKey(r.scope))
&& (!filter.kinds || filter.kinds.includes(r.kind))
&& (!importance || importance.has(r.importance))
&& (filter.origin === undefined || r.origin === filter.origin)
&& (filter.sessionId === undefined || r.sessionId === filter.sessionId)
&& (filter.since === undefined || r.createdAt >= filter.since)
&& (filter.until === undefined || r.createdAt <= filter.until));
};
const newestFirst = (a: MemoryRecord, b: MemoryRecord): number =>
b.createdAt.localeCompare(a.createdAt);
const forget = (id: string): boolean => {
const current = records.get(id);
if (!current) return false;
records.delete(id);
log(id, { event: 'deleted', previousText: current.text, text: null, at: new Date().toISOString() });
return true;
};
return {
capabilities: CAPABILITIES,
async remember(input: RememberInput): Promise<MemoryChange[]> {
ensureOpen();
const normalized = normalizeRememberInput(input);
if (normalized.conversation) throw new MemoryCapabilityError('extraction');
const text = normalized.text!;
const existing = [...records.values()].find((r) =>
r.text === text && scopeKey(r.scope) === scopeKey(normalized.scope));
if (existing) return [{ event: 'unchanged', record: existing }];
const record: MemoryRecord = {
id: randomUUID(),
text,
scope: normalized.scope,
kind: normalized.kind,
importance: normalized.importance,
source: normalized.source,
origin: normalized.origin,
sessionId: normalized.sessionId,
createdAt: new Date().toISOString(),
updatedAt: null,
metadata: { ...normalized.metadata },
};
records.set(record.id, record);
log(record.id, { event: 'added', previousText: null, text, at: record.createdAt });
return [{ event: 'added', record }];
},
async search(text: string, query: MemoryQuery): Promise<MemoryHit[]> {
ensureOpen();
const queryWords = words(text);
return matching(query)
.map((r) => ({ ...r, score: overlap(queryWords, words(r.text)) }))
.filter((hit) => hit.score > 0)
.sort((a, b) => b.score - a.score || newestFirst(a, b))
.slice(0, query.limit ?? 10);
},
async list(query: MemoryQuery): Promise<MemoryRecord[]> {
ensureOpen();
return matching(query).sort(newestFirst).slice(0, query.limit ?? 50);
},
async count(filter: MemoryFilter): Promise<number> {
ensureOpen();
return matching(filter).length;
},
async get(id: string): Promise<MemoryRecord | null> {
ensureOpen();
return records.get(id) ?? null;
},
async update(id: string, change: MemoryUpdate): Promise<MemoryRecord> {
ensureOpen();
const current = records.get(id);
if (!current) throw new MemoryNotFoundError(id);
if (change.metadata) assertNoReservedKeys(change.metadata);
const text = change.text?.trim() || current.text;
const updated: MemoryRecord = {
...current,
text,
kind: change.kind ?? current.kind,
importance: change.importance ?? current.importance,
metadata: { ...current.metadata, ...change.metadata },
updatedAt: new Date().toISOString(),
};
records.set(id, updated);
log(id, { event: 'updated', previousText: current.text, text, at: updated.updatedAt! });
return updated;
},
async forget(id: string): Promise<boolean> {
ensureOpen();
return forget(id);
},
async forgetMatching(filter: MemoryFilter): Promise<number> {
ensureOpen();
const doomed = matching(filter);
for (const record of doomed) forget(record.id);
return doomed.length;
},
async history(id: string): Promise<MemoryHistoryEntry[]> {
ensureOpen();
return histories.get(id) ?? [];
},
async close(): Promise<void> {
closed = true;
},
};
}
function words(text: string): Set<string> {
return new Set(text.toLowerCase().match(/[\p{L}\p{N}]{2,}/gu) ?? []);
}
/** Cosine similarity of two word sets. */
function overlap(a: Set<string>, b: Set<string>): number {
if (a.size === 0 || b.size === 0) return 0;
let shared = 0;
for (const word of a) if (b.has(word)) shared += 1;
return shared / Math.sqrt(a.size * b.size);
}

View File

@@ -0,0 +1,4 @@
// @waggle/memory-contract
export * from './types.js';
export * from './helpers.js';
export { createInMemoryMemoryStore } from './in-memory-store.js';

View File

@@ -0,0 +1,182 @@
/**
* The memory contract: everything Waggle may ask of memory (ADR-0002, ADR-0007).
*
* Code outside a memory implementation talks to memory only through
* `MemoryStore` and never queries a memory database directly.
*/
/** Where a memory lives. Personal memory follows the user across workspaces. */
export type MemoryScope =
| { readonly kind: 'personal' }
| { readonly kind: 'workspace'; readonly workspaceId: string };
/** What a memory is about. Replaces the content prefixes of the old frame store. */
export const MEMORY_KINDS = [
'fact',
'event',
'preference',
'profile',
'decision',
'summary',
'note',
] as const;
export type MemoryKind = (typeof MEMORY_KINDS)[number];
/** Ordered from most to least important. */
export const MEMORY_IMPORTANCE = ['critical', 'important', 'normal', 'temporary'] as const;
export type MemoryImportance = (typeof MEMORY_IMPORTANCE)[number];
export const MEMORY_SOURCES = [
'user_stated',
'tool_verified',
'agent_inferred',
'import',
'system',
] as const;
export type MemorySource = (typeof MEMORY_SOURCES)[number];
export interface MemoryRecord {
/** Unique across all scopes. */
readonly id: string;
readonly text: string;
readonly scope: MemoryScope;
readonly kind: MemoryKind;
readonly importance: MemoryImportance;
readonly source: MemorySource;
/** Producer of the memory, e.g. 'chat', 'agent-run', 'loop'. */
readonly origin: string | null;
/** Chat session the memory came from, when there is one. */
readonly sessionId: string | null;
/** ISO 8601. */
readonly createdAt: string;
/** ISO 8601, or null if the memory was never changed. */
readonly updatedAt: string | null;
/** Caller-defined fields (title, tags, status…). Never repeats the fields above. */
readonly metadata: Readonly<Record<string, unknown>>;
}
export interface MemoryHit extends MemoryRecord {
/** Relevance to the query; higher is better. Comparable within one result list only. */
readonly score: number;
}
export interface ConversationMessage {
readonly role: 'user' | 'assistant';
readonly content: string;
}
export interface RememberInput {
readonly scope: MemoryScope;
/** Store this text as one memory. Exactly one of `text` and `conversation` is required. */
readonly text?: string;
/**
* Let the store extract facts from these turns with a model.
* Requires `capabilities.extraction`.
*/
readonly conversation?: readonly ConversationMessage[];
/** Default 'fact'. */
readonly kind?: MemoryKind;
/** Default 'normal'. */
readonly importance?: MemoryImportance;
/** Default 'agent_inferred'. */
readonly source?: MemorySource;
readonly origin?: string;
readonly sessionId?: string;
/** Must not use the reserved keys in `RESERVED_METADATA_KEYS`. */
readonly metadata?: Readonly<Record<string, unknown>>;
}
export interface MemoryChange {
/** 'unchanged' means the same text already existed in the scope; nothing was written. */
readonly event: 'added' | 'unchanged';
readonly record: MemoryRecord;
}
export interface MemoryFilter {
/** Scopes to read from; results of all of them are merged. At least one. */
readonly scopes: readonly MemoryScope[];
readonly kinds?: readonly MemoryKind[];
/** Lowest importance to include: 'important' returns critical and important. */
readonly minImportance?: MemoryImportance;
readonly origin?: string;
readonly sessionId?: string;
/** Inclusive ISO 8601 bounds on `createdAt`. */
readonly since?: string;
readonly until?: string;
}
export interface MemoryQuery extends MemoryFilter {
readonly limit?: number;
}
export interface MemoryUpdate {
readonly text?: string;
readonly kind?: MemoryKind;
readonly importance?: MemoryImportance;
/** Merged into the existing metadata. */
readonly metadata?: Readonly<Record<string, unknown>>;
}
export interface MemoryHistoryEntry {
readonly event: 'added' | 'updated' | 'deleted';
readonly previousText: string | null;
readonly text: string | null;
/** ISO 8601. */
readonly at: string;
}
export interface MemoryCapabilities {
/** `remember({ conversation })` extracts facts with a model. */
readonly extraction: boolean;
/** `search` ranks by meaning, not only by shared words. */
readonly semanticSearch: boolean;
/** `history` returns the change log. */
readonly history: boolean;
/** Entities and relations between memories. Not part of v1 (ADR-0002). */
readonly knowledgeGraph: boolean;
}
export interface MemoryStore {
readonly capabilities: MemoryCapabilities;
/** Write memory. Identical text in the same scope is not written twice. */
remember(input: RememberInput): Promise<MemoryChange[]>;
/** Most relevant first. Default limit 10. */
search(text: string, query: MemoryQuery): Promise<MemoryHit[]>;
/** Newest first. Default limit 50. */
list(query: MemoryQuery): Promise<MemoryRecord[]>;
count(filter: MemoryFilter): Promise<number>;
get(id: string): Promise<MemoryRecord | null>;
/** Throws `MemoryNotFoundError` when the id is unknown. */
update(id: string, change: MemoryUpdate): Promise<MemoryRecord>;
/** Returns false when the id is unknown. */
forget(id: string): Promise<boolean>;
/** Deletes every memory matching the filter and returns how many. */
forgetMatching(filter: MemoryFilter): Promise<number>;
/** Oldest first. Empty when `capabilities.history` is false. */
history(id: string): Promise<MemoryHistoryEntry[]>;
/** Releases resources. The store must not be used afterwards. */
close(): Promise<void>;
}
/** Metadata keys a caller may not set: they hold the record's own fields. */
export const RESERVED_METADATA_KEYS = [
'kind',
'importance',
'source',
'origin',
'session_id',
] as const;
export class MemoryNotFoundError extends Error {
constructor(readonly memoryId: string) {
super(`Memory not found: ${memoryId}`);
this.name = 'MemoryNotFoundError';
}
}
export class MemoryCapabilityError extends Error {
constructor(readonly capability: keyof MemoryCapabilities) {
super(`This memory store does not support ${capability}`);
this.name = 'MemoryCapabilityError';
}
}

View File

@@ -0,0 +1,206 @@
/**
* Behaviour every `MemoryStore` implementation must show. Each implementation's
* test file calls `describeMemoryStoreContract` with a factory for a fresh store.
*/
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
import {
MemoryCapabilityError,
MemoryNotFoundError,
PERSONAL_SCOPE,
workspaceScope,
type MemoryStore,
} from '../src/index.js';
const ALPHA = workspaceScope('alpha');
const BETA = workspaceScope('beta');
const tick = (): Promise<void> => new Promise((resolve) => setTimeout(resolve, 15));
export function describeMemoryStoreContract(name: string, open: () => Promise<MemoryStore>): void {
describe(`${name} — memory contract`, () => {
let store: MemoryStore;
beforeEach(async () => {
store = await open();
});
afterEach(async () => {
await store.close();
});
async function add(text: string, extra: Record<string, unknown> = {}) {
const [change] = await store.remember({ scope: ALPHA, text, ...extra });
return change.record;
}
it('remembers text with defaults and reads it back by id', async () => {
const [change] = await store.remember({ scope: ALPHA, text: ' The launch is on Friday ' });
expect(change.event).toBe('added');
const stored = await store.get(change.record.id);
expect(stored).toMatchObject({
id: change.record.id,
text: 'The launch is on Friday',
scope: ALPHA,
kind: 'fact',
importance: 'normal',
source: 'agent_inferred',
origin: null,
sessionId: null,
updatedAt: null,
metadata: {},
});
expect(Number.isNaN(Date.parse(stored!.createdAt))).toBe(false);
expect(await store.get('no-such-id')).toBeNull();
});
it('keeps the record fields and caller metadata', async () => {
const record = await add('Use the blue logo on slides', {
kind: 'decision',
importance: 'important',
source: 'user_stated',
origin: 'chat',
sessionId: 'session-1',
metadata: { title: 'Logo', tags: ['brand'] },
});
expect(await store.get(record.id)).toMatchObject({
kind: 'decision',
importance: 'important',
source: 'user_stated',
origin: 'chat',
sessionId: 'session-1',
metadata: { title: 'Logo', tags: ['brand'] },
});
});
it('does not write identical text twice in one scope', async () => {
const first = await add('The office is in Belgrade');
const [again] = await store.remember({ scope: ALPHA, text: 'The office is in Belgrade' });
expect(again.event).toBe('unchanged');
expect(again.record.id).toBe(first.id);
const [elsewhere] = await store.remember({ scope: BETA, text: 'The office is in Belgrade' });
expect(elsewhere.event).toBe('added');
expect(await store.count({ scopes: [ALPHA, BETA] })).toBe(2);
});
it('keeps scopes apart in list, count and search', async () => {
await add('Alpha uses PostgreSQL');
await store.remember({ scope: BETA, text: 'Beta uses PostgreSQL too' });
await store.remember({ scope: PERSONAL_SCOPE, text: 'I like PostgreSQL' });
expect((await store.list({ scopes: [ALPHA] })).map((r) => r.text)).toEqual(['Alpha uses PostgreSQL']);
expect(await store.count({ scopes: [BETA] })).toBe(1);
expect(await store.count({ scopes: [ALPHA, PERSONAL_SCOPE] })).toBe(2);
const hits = await store.search('PostgreSQL', { scopes: [PERSONAL_SCOPE] });
expect(hits.map((h) => h.text)).toEqual(['I like PostgreSQL']);
});
it('ranks a memory first when the query repeats its words', async () => {
await add('The team offsite is in Lisbon in May');
await add('The user prefers tea over coffee');
await add('The budget for the Paris trip is 2000 euros');
const hits = await store.search('budget Paris trip euros', { scopes: [ALPHA], limit: 2 });
expect(hits.length).toBeGreaterThan(0);
expect(hits.length).toBeLessThanOrEqual(2);
expect(hits[0].text).toBe('The budget for the Paris trip is 2000 euros');
expect(typeof hits[0].score).toBe('number');
});
it('filters by kind, importance, origin and session', async () => {
await add('Ship the beta', { kind: 'decision', importance: 'critical', origin: 'chat', sessionId: 's1' });
await add('Weekly sync moved to Tuesday', { kind: 'event', importance: 'normal', origin: 'loop' });
await add('Prefers short answers', { kind: 'preference', importance: 'important', origin: 'chat', sessionId: 's2' });
const texts = async (filter: Record<string, unknown>) =>
(await store.list({ scopes: [ALPHA], ...filter })).map((r) => r.text).sort();
expect(await texts({ kinds: ['decision', 'event'] })).toEqual(['Ship the beta', 'Weekly sync moved to Tuesday']);
expect(await texts({ minImportance: 'important' })).toEqual(['Prefers short answers', 'Ship the beta']);
expect(await texts({ origin: 'loop' })).toEqual(['Weekly sync moved to Tuesday']);
expect(await texts({ sessionId: 's2' })).toEqual(['Prefers short answers']);
const hits = await store.search('beta', { scopes: [ALPHA], kinds: ['event'] });
expect(hits.every((h) => h.kind === 'event')).toBe(true);
});
it('filters by creation time', async () => {
const early = await add('Early note');
await tick();
const late = await add('Late note');
expect((await store.list({ scopes: [ALPHA], since: late.createdAt })).map((r) => r.text)).toEqual(['Late note']);
expect((await store.list({ scopes: [ALPHA], until: early.createdAt })).map((r) => r.text)).toEqual(['Early note']);
});
it('lists newest first and honours the limit', async () => {
await add('First');
await tick();
await add('Second');
await tick();
await add('Third');
expect((await store.list({ scopes: [ALPHA] })).map((r) => r.text)).toEqual(['Third', 'Second', 'First']);
expect((await store.list({ scopes: [ALPHA], limit: 2 })).map((r) => r.text)).toEqual(['Third', 'Second']);
});
it('updates text and importance and merges metadata', async () => {
const record = await add('Draft due Monday', { metadata: { status: 'open', owner: 'nik' } });
const updated = await store.update(record.id, {
text: 'Draft due Tuesday',
importance: 'important',
metadata: { status: 'done' },
});
expect(updated).toMatchObject({
id: record.id,
text: 'Draft due Tuesday',
importance: 'important',
metadata: { status: 'done', owner: 'nik' },
});
expect(updated.updatedAt).not.toBeNull();
expect(await store.get(record.id)).toMatchObject({ text: 'Draft due Tuesday', importance: 'important' });
await expect(store.update('no-such-id', { text: 'x' })).rejects.toBeInstanceOf(MemoryNotFoundError);
});
it('forgets one memory and reports unknown ids', async () => {
const record = await add('Temporary note');
expect(await store.forget(record.id)).toBe(true);
expect(await store.get(record.id)).toBeNull();
expect(await store.forget(record.id)).toBe(false);
});
it('forgets everything matching a filter', async () => {
await add('Loop result one', { origin: 'loop' });
await add('Loop result two', { origin: 'loop' });
await add('Chat fact', { origin: 'chat' });
await store.remember({ scope: BETA, text: 'Loop result in beta', origin: 'loop' });
expect(await store.forgetMatching({ scopes: [ALPHA], origin: 'loop' })).toBe(2);
expect((await store.list({ scopes: [ALPHA] })).map((r) => r.text)).toEqual(['Chat fact']);
expect(await store.count({ scopes: [BETA] })).toBe(1);
});
it('keeps a change history when it supports one', async () => {
const record = await add('Version one');
await store.update(record.id, { text: 'Version two' });
const history = await store.history(record.id);
if (!store.capabilities.history) {
expect(history).toEqual([]);
return;
}
expect(history.map((h) => h.event)).toEqual(['added', 'updated']);
expect(history[1]).toMatchObject({ previousText: 'Version one', text: 'Version two' });
});
it('rejects malformed input', async () => {
await expect(store.remember({ scope: ALPHA })).rejects.toThrow(TypeError);
await expect(store.remember({ scope: ALPHA, text: ' ' })).rejects.toThrow(TypeError);
await expect(store.remember({ scope: ALPHA, text: 'x', metadata: { kind: 'event' } })).rejects.toThrow(TypeError);
await expect(store.list({ scopes: [] })).rejects.toThrow(TypeError);
await expect(store.remember({ scope: { kind: 'workspace', workspaceId: '' }, text: 'x' })).rejects.toThrow(TypeError);
});
it('refuses conversations when it cannot extract facts', async () => {
if (store.capabilities.extraction) return;
await expect(store.remember({
scope: ALPHA,
conversation: [{ role: 'user', content: 'My name is Ana' }],
})).rejects.toBeInstanceOf(MemoryCapabilityError);
});
it('does not claim a knowledge graph', () => {
expect(store.capabilities.knowledgeGraph).toBe(false);
});
});
}

View File

@@ -0,0 +1,4 @@
import { createInMemoryMemoryStore } from '../src/index.js';
import { describeMemoryStoreContract } from './contract-suite.js';
describeMemoryStoreContract('in-memory store', async () => createInMemoryMemoryStore());

View File

@@ -0,0 +1,21 @@
{
"compilerOptions": {
"target": "ES2022",
"module": "ESNext",
"moduleResolution": "bundler",
"lib": ["ES2022"],
"outDir": "dist",
"rootDir": "src",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true,
"resolveJsonModule": true,
"declaration": true,
"declarationMap": true,
"sourceMap": true,
"composite": true
},
"include": ["src/**/*.ts"],
"exclude": ["node_modules", "dist", "tests"]
}