@particle-academy/prism-graph
v0.3.0
Published
Long-term memory for AI agents, for TypeScript: scoped, trust-labelled, cited facts, hybrid search and erasure. The port of particle-academy/prism-graph.
Readme
@particle-academy/prism-graph
Long-term memory for AI agents, for TypeScript. This is the port of
particle-academy/prism-graph
(PHP, the reference). It is byte-compatible with the reference: chunk ids,
scope ids, embedder fingerprints and the fenced wake block match exactly,
checked against a golden fixture generated by the PHP package.
Node 22.16+, ESM, zero runtime dependencies. Storage is SQLite through
Node's built-in node:sqlite.
What it guarantees
Scope is enforced in SQL, on every query. Scopes are tenant, owner, agent and thread. A reader sees its own level and the levels above it, never sideways, and there is no unscoped read.
Every source records its trust class and writer. Trust is
user,document,agent,tool,subagent,consolidatororsystem. The caller binds both, never a model. A source's trust cannot change later.Facts cite evidence, and a policy decides their status:
- accepted when every cited chunk is user or document text;
- a belief when the evidence is only agent notes;
- a proposal otherwise.
An accepted fact can only be superseded by another accepted one, so tool output cannot overwrite what the user said.
Facts are bi-temporal. There is valid time (supersede) and recorded time (retract,
knownAt).Hybrid search. FTS5 full-text search folds case and accents. Optional vectors are fused by reciprocal rank and partitioned per tenant.
Erasure cascades to chunks, vectors, full-text entries, evidence and orphaned facts, and returns counts.
Every write is all-or-nothing, including inside your own transaction (it runs in a savepoint). Concurrent writes on one connection are serialised.
Recalled text is fenced as data. Hidden characters are shown as
<U+XXXX>, and item text is quoted line by line, so stored text cannot forge a header or close the fence.
Use
import { DatabaseSync } from 'node:sqlite';
import { baseSchema, Graph, GraphStore, MarkdownChunker, NodeSqliteDriver, Origin, Scope, Trust } from '@particle-academy/prism-graph';
const db = new DatabaseSync('memory.db');
// Once, from your own migration tooling (the package never creates tables at runtime):
for (const sql of baseSchema()) db.exec(sql);
const graph = new Graph(new GraphStore(new NodeSqliteDriver(db)));
const memory = graph.scope(Scope.tenant('acme').withOwner('user-7').withAgent('journal'));
await memory.ingest('entry-42', 'journal://42', text, new MarkdownChunker(), new Origin(Trust.User, 'user-7'));
const hits = await memory.search('refund policy'); // verbatim chunks, with trust and sourcebaseSchema() is the complete schema for the default setup, and already
includes the full-text table and its triggers. Do not run fullTextSchema()
as well. Run vectorSchema() only if you store vectors. If a migration rebuilds
the chunks table (which drops its triggers), run repairFullTextSchema().
Give memory a connection of its own
SQLite transactions belong to the connection. Suppose another part of your
app writes on the same DatabaseSync while one of prism-graph's writes is in
progress. That write lands inside prism-graph's savepoint, and is rolled back
with it if prism-graph's write fails. So use a dedicated connection to the same
file (WAL mode is the usual setup), or send every write on the shared
connection through driver.atomic().
Listing sources and chunks
For a memory explorer, list what a scope can see, a page at a time:
const page = await memory.listSources(); // newest first, 50 per page
const next = await memory.listSources(page.nextCursor);
const chunks = await memory.listChunks(sourceId, null, 100);
const { item } = await memory.getSource(chunk.sourceId); // one source by id, or nullEach call returns { contractVersion: 'g282.1', items, nextCursor }, the same shape as the PHP package.
- A source item has
sourceId,title(metadata.title, else the uri),kind(metadata.kind, else null),createdAt,chunkCountandtrust. - A chunk item has
chunkId,sourceId,text,position(its place in the source) andprovenance(uri, sha256, byte and line range, heading path, recipe, trust, writer, recordedAt). - Scoped like every read. A source outside the scope lists as empty.
- Cursors are opaque and only work in the scope and listing that issued them.
- Page size defaults to 50 and is capped at 200. Pass a different cap as
new Graph(store, vectors, embedder, policy, listMax). - Retired sources and chunks are not listed.
getSource(sourceId)returns{ contractVersion: 'g282.1', item }:itemis exactly whatlistSourceswould list, or null wheneverlistSourceswould not list it. Unknown, another scope's and fully retired look the same. It is an optional store capability (FindsSources); a store without it throwsGraphError.
MCP tools on your own server
memoryTools() returns framework-neutral tool definitions: a name, a
description, a JSON Schema for the input, and an async call() that always
resolves to a JSON string and never rejects at the model. They can be
registered on any MCP server, with no MCP SDK dependency. The scope and the
writer are bound by your code, never by the model.
With @particle-academy/prism-mcp-server
(this is the setup the test suite runs over a real MCP exchange):
import { LoopbackHttpTransport, Server, ToolDefinition, type JsonObject } from '@particle-academy/prism-mcp-server';
import { memoryTools } from '@particle-academy/prism-graph';
const server = new Server({ server: 'journal', transport: new LoopbackHttpTransport() });
for (const tool of memoryTools(memory, 'agent:journal')) {
server.register(
new ToolDefinition(tool.name, tool.description, tool.inputSchema as JsonObject),
async (args) => ({ text: await tool.call(args), isError: false }),
);
}
await server.listen();inputSchema is plain JSON Schema, so any MCP server that takes a tool's
JSON Schema as-is can register these tools without converting anything. No
schema library is needed: call() validates its own input either way.
The tools are memory_search, memory_get, memory_facts, memory_timeline
and memory_note:
- No tool asserts, accepts, supersedes or erases. Those are app decisions.
- A note is stored as the agent's own words, so it can only ever be a belief.
- Tool names may not contain the verbs reserved for the human: confirm, approve, accept, reject, deny.
Not yet in this port
- PostgreSQL: the driver interface is ready, but the adapter is not shipped until it is tested here.
- Harness adapters: this port does not include the PHP reference's harness adapters (WakeContext and TurnRecorder).
- Entity graph: typed entities, edges with notes and traversal are planned for both languages together.
Gates
npm run typecheck && npm run build && npx vitest run