An agent can answer with an old price when its retrieval tool returns both the old and current values. Store the source and effective timestamp with each fact, then define which row is current before passing facts to the model.
This guide uses a price of $4,200 followed by $3,600 as illustrative data. The database determines which value applies to a requested date; the model only turns the returned fact into an answer.
Where the wrong answer comes from
A table containing only a subject and value cannot identify which of two prices applies today. The fact table below therefore also stores learned_at, optional expires_at, and superseded_by. Timestamps use epoch milliseconds, while superseded_by references the replacement row.
Save this complete module as memory-store.ts. Its functions use a database that the caller has already selected and authorised.
import type { Database } from '@delali/sirannon-db'
export interface LearnedFact {
subject: string
predicate: string
value: string
source: string
writtenBy: string
learnedAt: number
expiresAt?: number
}
export interface Belief {
predicate: string
value: string
source: string
}
export const remember = async (db: Database, fact: LearnedFact): Promise<void> => {
if (!Number.isSafeInteger(fact.learnedAt)) throw new Error('The fact needs a valid timestamp')
if (fact.expiresAt !== undefined &&
(!Number.isSafeInteger(fact.expiresAt) || fact.expiresAt <= fact.learnedAt)) {
throw new Error('Expiry must follow the fact timestamp')
}
await db.transaction(async (tx): Promise<void> => {
const current = (await tx.query<{ learned_at: number }>(
'SELECT learned_at FROM fact WHERE subject = ? AND predicate = ? AND superseded_by IS NULL',
[fact.subject, fact.predicate]))[0]
if (current && current.learned_at >= fact.learnedAt) {
throw new Error('Facts must be recorded in increasing timestamp order')
}
const inserted = await tx.execute(
`INSERT INTO fact (subject, predicate, value, source, written_by, learned_at, expires_at)
VALUES (?, ?, ?, ?, ?, ?, ?)`,
[fact.subject, fact.predicate, fact.value, fact.source, fact.writtenBy, fact.learnedAt, fact.expiresAt ?? null])
await tx.execute(
`UPDATE fact SET superseded_by = ?
WHERE subject = ? AND predicate = ? AND superseded_by IS NULL AND id <> ?`,
[inserted.lastInsertRowId, fact.subject, fact.predicate, inserted.lastInsertRowId])
})
}
export const recall = async (db: Database, subject: string, asOf: number): Promise<Belief[]> => {
if (!Number.isSafeInteger(asOf)) throw new Error('The query needs a valid timestamp')
return db.query<Belief>(
`SELECT predicate, value, source FROM fact AS f
WHERE subject = ? AND learned_at <= ?
AND (expires_at IS NULL OR expires_at > ?)
AND (superseded_by IS NULL OR
(SELECT learned_at FROM fact AS newer WHERE newer.id = f.superseded_by) > ?)
ORDER BY predicate`,
[subject, asOf, asOf, asOf])
}
export const forget = async (db: Database, supersededBefore: number): Promise<number> => {
if (!Number.isSafeInteger(supersededBefore)) throw new Error('Retention needs a valid timestamp')
const deleted = await db.execute(
`DELETE FROM fact WHERE superseded_by IN
(SELECT id FROM fact WHERE learned_at < ?)`, [supersededBefore])
return deleted.changes
}Retire the old row when a new value supersedes it
remember() inserts the replacement and updates the earlier row in one transaction. A reader therefore observes the state before or after both writes, with one current value in either state.
The timestamp check rejects out-of-order replacements for the same subject and predicate. This example assumes a trusted fact loader supplies those timestamps. If your application accepts delayed corrections, define their effective dates and conflict policy before changing this query.
Ask for the price that was current on a date you name
recall() returns facts learned at or before asOf whose expiry and replacement are later than that timestamp. Fix asOf in trusted application code when constructing the tool so that the model cannot change the requested reporting date.
Save this complete brain.ts beside memory-store.ts. Its temporary database keeps the demonstration separate from existing data.
import { mkdtemp, rm } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { Sirannon } from '@delali/sirannon-db'
import { betterSqlite3 } from '@delali/sirannon-db/driver/better-sqlite3'
import { forget, recall, remember } from './memory-store.ts'
const directory = await mkdtemp(join(tmpdir(), 'sirannon-memory-'))
const sirannon = new Sirannon({ driver: betterSqlite3() })
const JANUARY = Date.UTC(2026, 0, 12)
const FEBRUARY = Date.UTC(2026, 1, 9)
const MARCH = Date.UTC(2026, 2, 3)
const APRIL = Date.UTC(2026, 3, 1)
try {
const db = await sirannon.open('brain', join(directory, 'brain.db'))
await db.execute(`CREATE TABLE fact (
id INTEGER PRIMARY KEY,
subject TEXT NOT NULL,
predicate TEXT NOT NULL,
value TEXT NOT NULL,
source TEXT NOT NULL,
written_by TEXT NOT NULL,
learned_at INTEGER NOT NULL,
expires_at INTEGER,
superseded_by INTEGER REFERENCES fact(id)
)`)
await db.execute('CREATE INDEX fact_subject ON fact(subject, predicate, learned_at)')
await remember(db, {
subject: 'Tier 2 renewal', predicate: 'list_price', value: '$4,200',
source: 'pricing-sheet', writtenBy: 'pricing-team', learnedAt: JANUARY,
})
await remember(db, {
subject: 'Tier 2 renewal', predicate: 'list_price', value: '$3,600',
source: 'pricing-sheet', writtenBy: 'pricing-team', learnedAt: MARCH,
})
const before = {
current: await recall(db, 'Tier 2 renewal', APRIL),
february: await recall(db, 'Tier 2 renewal', FEBRUARY),
}
const removed = await forget(db, APRIL)
console.log(JSON.stringify({
before,
removed,
after: { current: await recall(db, 'Tier 2 renewal', APRIL), february: await recall(db, 'Tier 2 renewal', FEBRUARY) },
}, (key: string, value: unknown): unknown =>
typeof value === 'number' ? Number(value.toFixed(2)) : value, 2))
} finally {
await sirannon.shutdown()
await rm(directory, { recursive: true, force: true })
}The April query returns $3,600, while the February query returns $4,200. The source remains available alongside each value so that the application can show where the answer came from.
Delete the superseded rows, and lose the history with them
forget() deletes facts whose replacements predate the retention cutoff. It returns the number of deleted rows. Choose that cutoff from your application's history and retention requirements.
After the example deletes the older fact, the current price remains available, but the February query returns no fact. Handle that empty array as unavailable history. A model must receive an explicit instruction to report missing evidence; the database cannot guarantee the model's wording.
Expiry filters retrieval without deleting a row. Deletion removes the row from the active database, while backups and other retained copies require their separate retention policy.
Run it against a real model
The same recall() function can be wrapped as an AI SDK tool. Install ai, valibot, and @ai-sdk/valibot in the application with pnpm add -E ai valibot @ai-sdk/valibot, then save this complete memory-tools.ts beside the store module.
import type { Database } from '@delali/sirannon-db'
import { valibotSchema } from '@ai-sdk/valibot'
import { tool, type ToolSet } from 'ai'
import * as v from 'valibot'
import { type Belief, recall } from './memory-store.ts'
export const brainTools = (database: Database, asOf: number): ToolSet => ({
recall: tool({
description: 'Find the recorded fact for a subject on the reporting date.',
inputSchema: valibotSchema(v.strictObject({ subject: v.pipe(v.string(), v.minLength(1), v.maxLength(200)) })),
execute: async ({ subject }: { subject: string }): Promise<Belief[]> => recall(database, subject, asOf),
}),
})Pass the returned tools to your ToolLoopAgent with an authorised database and reporting date. Configure the model and its credentials through your application's model provider. Model choice and generated wording do not change the database's retrieval rules.
Where to go next
Rewinding memory recovers a database after an unwanted write. Retrieval with Narsil searches facts by meaning, while auditing a fleet records who requested changes.