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 agent can base later decisions and stored work on an unwanted fact. Restore a separate database from a trusted backup point, inspect its rows, and review the later changes before you return the agent to service.

Sirannon restores the stored rows and schema, but it cannot reverse an external action that an agent completes before the restore, such as sending a message or placing an order.

Watch the agent repeat a fact from an untrusted page

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 program below creates that situation with illustrative data. Save the complete folder-destination.ts from the destination guide beside it. The program stores the 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 while loop in learn waits for the clock to pass the last capture's millisecond timestamp so that Sirannon stamps each capture with a distinct timestamp. APPROVED_FACT_IDS contains row 4, because the example treats that warehouse fact as reviewed. In a deployed recovery, approve a change only on evidence from its source.

Inspect the recovery point before restoring

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

A restore stops at a capture boundary, which a failed or delayed capture can place more than one capture interval before the requested timestamp. Inspect restoresTo and the audit record before you choose the recovery point.

When no database is open, call readBackupChains() and planBackupRestore() from the root package, which read the records at the destination without rebuilding a database.

Rebuild the memory beside the live one

restoreBackup() rebuilds the file at a separate path. Inspect that database before you point the application at it. Compare the recovered facts with independent source records, because only those records can show that the recovery succeeded.

For an encrypted chain, enable encryption on the restore driver and supply the key provider for that chain's base.keyId. Open the recovered file with the same key. The encryption guide explains which keys to retain after a key change.

Copy later work back after reviewing its source

Pause the agent's writers and drain the outstanding work before you collect the later facts and switch the agent's database. Review the dependencies between those facts, because a source that looks trusted can contain work derived from an earlier unwanted value.

The example copies one approved row and leaves out the unwanted refund address. A different source label on a row is no evidence that the fact is independent of the unwanted one, so the example copies no row on its label alone.

The example closes both handles before it reopens the repaired file under the logical planner identifier. It leaves the earlier file in place until the finally block removes the temporary directory so that no file changes under an open SQLite connection. A service has to persist its new path and key configuration before it accepts requests again.

Sirannon starts a new backup chain for the repaired database, which the example stores under reviewed-planner-chain. Retain the earlier chain and its keys for as long as your recovery and investigation policy requires, because that chain records the earlier state of the database.

What a restore puts back, and what it does not

A restore returns the database's rows and schema to the selected captured state. Review the external effects separately, including the requests that another service accepts before the restore.

Use registered tools to check identity and row ownership before each write. Use transactional audit events to explain committed changes, and delete backups through backup retention once your recovery window and investigation requirements allow it.