AI agents

Rewinding memory

Inspect a backup restore point, rebuild an agent database separately, and copy only later facts that an operator has approved.

An unwanted fact can affect later agent decisions and stored work. Restore a separate database from a trusted backup point, inspect its rows, and review later changes before returning the agent to service.

A database restore repairs stored state. It cannot reverse external actions that an agent already completed, such as sending a message or placing an order.

Watch the agent repeat what the page told it

Suppose a freight agent stores a replacement refund address from an untrusted page. A retrieval query that always selects the newest fact can return that address even though an earlier row contains the approved one.

The complete rewind.ts example creates that situation with illustrative data. Save the complete folder-destination.ts from the destination guide beside it. The example stores backup pieces in a temporary directory and removes only that directory when it finishes.

rewind.ts
import { mkdtemp, rm } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { setTimeout } from 'node:timers/promises'
import { Sirannon } from '@delali/sirannon-db'
import { restoreBackup } from '@delali/sirannon-db/backup'
import { betterSqlite3 } from '@delali/sirannon-db/driver/better-sqlite3'
import { folderDestination } from './folder-destination.ts'
 
interface Fact {
  id: number
  subject: string
  value: string
  source: string
  learned_at: number
}
 
const directory = await mkdtemp(join(tmpdir(), 'sirannon-rewind-'))
const sirannon = new Sirannon({ driver: betterSqlite3() })
const destination = folderDestination(join(directory, 'pieces'))
 
try {
  const db = await sirannon.open('planner', join(directory, 'planner.db'), {
    backups: {
      destination, intervalMs: 0,
      onError: (error): void => console.error('Backup failed', error),
    },
  })
  await db.execute(`CREATE TABLE fact (
    id INTEGER PRIMARY KEY, subject TEXT NOT NULL, value TEXT NOT NULL,
    source TEXT NOT NULL, learned_at INTEGER NOT NULL
  )`)
  let lastCapture = 0
  const learn = async (subject: string, value: string, source: string): Promise<number> => {
    while (Date.now() <= lastCapture) await setTimeout(1)
    await db.execute('INSERT INTO fact (subject, value, source, learned_at) VALUES (?, ?, ?, ?)',
      [subject, value, source, Date.now()])
    await db.captureBackupChanges()
    const latest = (await db.backupChain())[0]?.changes.at(-1)
    if (!latest) throw new Error('The capture is missing')
    lastCapture = latest.capturedAt
    return lastCapture
  }
 
  await learn('refund requests', 'accounts@freight.example', 'finance-policy')
  const trustedTimestamp = await learn('Leeds warehouse', 'closes at 17:00', 'warehouse-policy')
  await learn('refund requests', 'finance@untrusted.example', 'fetched-page')
  await learn('Antwerp warehouse', 'closes at 16:00', 'warehouse-policy')
 
  const plan = await db.backupRestorePlan(trustedTimestamp)
  const recoveredPath = join(directory, 'reviewed-planner.db')
  await restoreBackup({
    destination,
    driver: betterSqlite3(),
    destPath: recoveredPath,
    moment: trustedTimestamp,
  })
  const recovered = await sirannon.open('reviewed-planner', recoveredPath)
  const before = await recovered.query<Fact>('SELECT * FROM fact ORDER BY id')
 
  const APPROVED_FACT_IDS = [4]
  for (const id of APPROVED_FACT_IDS) {
    const fact = await db.queryOne<Fact>('SELECT * FROM fact WHERE id = ? AND learned_at > ?', [id, plan.restoresTo])
    if (!fact) throw new Error('An approved later fact is missing')
    await recovered.execute('INSERT INTO fact (subject, value, source, learned_at) VALUES (?, ?, ?, ?)',
      [fact.subject, fact.value, fact.source, fact.learned_at])
  }
 
  await sirannon.close('reviewed-planner')
  await sirannon.close('planner')
  const promoted = await sirannon.open('planner', recoveredPath, {
    backups: {
      destination, chainName: 'reviewed-planner-chain', intervalMs: 0,
      onError: (error): void => console.error('Backup failed', error),
    },
  })
  console.log(JSON.stringify({
    plannedChanges: plan.changes.length,
    restoredSubjects: before.map((fact: Fact): string => fact.subject),
    approvedFacts: await promoted.query('SELECT subject, value, source FROM fact ORDER BY id'),
  }, (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 clock check gives each explicit capture a distinct millisecond timestamp. The approved fact list contains row 4 because this demonstration treats that warehouse fact as reviewed. A deployed recovery process needs evidence for every approved change.

Inspect the recovery point before restoring

backupRestorePlan(timestamp) selects a full copy and the ordered change files through the requested timestamp. Its restoresTo identifies the latest captured state that the plan can reconstruct.

A restore stops at a capture boundary. Failed or delayed captures can make that boundary older than the configured capture interval, so inspect restoresTo and the audit record before choosing the recovery point.

You can also use readBackupChains() and planBackupRestore() from the root package when no database is open. Those functions inspect the records at the destination without rebuilding a database.

Rebuild the memory beside the live one

restoreBackup() reconstructs the file at a separate path. Inspect that database before changing the application's active database mapping. Compare the recovered facts with independent source records; a model's plausible answer does not prove that recovery succeeded.

For an encrypted chain, enable encryption on the restore driver and supply the key provider for that chain's base.keyId. Reopening the recovered file requires the same key. The encryption guide explains key retention after rotation.

Keep later work after reviewing its source

Pause the agent's writers and drain outstanding work before collecting later facts and changing its active database. Review dependencies between those facts, because an apparently trusted source can contain work derived from an earlier unwanted value.

The example copies an explicit approved row while excluding the unwanted refund address. Copying every row with a different source label would provide no proof that those later facts are independent.

The example closes both handles before reopening the repaired file under the logical planner identifier. It retains the earlier file until temporary-directory cleanup, avoiding a file replacement while SQLite connections are open. A service must persist its new path and key configuration before accepting requests again.

The repaired database starts a new backup chain. Retain the earlier chain and keys according to the recovery and investigation policy; the old chain remains a record of the earlier database state.

What a restore puts back, and what it does not

A restore changes the database's rows and schema to the selected captured state. Review external effects separately, including requests already accepted by another service.

Use registered tools to enforce identity and row ownership before writes. Use transactional audit events to explain committed changes, and apply backup retention after the recovery window and investigation requirements permit deletion.