Keep a durable audit record when your application must explain an agent's earlier actions. Sirannon's change history has a retention period, while query hooks describe statements without proving that their surrounding transaction committed.
For separate agent databases, save an audit event in the same transaction as the action. A collector can copy those events to a central journal and remove each pending event only after the journal accepts it.
Ask an agent what the fleet did
A reporting agent can read a journal through an authorised tool. Include the authenticated actor, event identifier, action, timestamp, and outcome in that journal so that the answer can cite a stored event.
The complete journal.ts below demonstrates collection without requiring a model. Its stock-adjustment threshold is an illustrative application policy, separate from Sirannon's defaults.
import { randomUUID } from 'node:crypto'
import { mkdtemp, rm } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { type Database, HookDeniedError, Sirannon } from '@delali/sirannon-db'
import { betterSqlite3 } from '@delali/sirannon-db/driver/better-sqlite3'
interface AuditEvent {
event_id: string
item: string
quantity: number
recorded_at: number
outcome: string
reason: string | null
}
const INSERT_ACTION = 'INSERT INTO action (event_id, item, quantity, recorded_at) VALUES (?, ?, ?, ?)'
const REVIEW_THRESHOLD = 100
const directory = await mkdtemp(join(tmpdir(), 'sirannon-audit-'))
const sirannon = new Sirannon({ driver: betterSqlite3() })
const observations = new Map<string, number>()
sirannon.onAfterQuery((context): void => {
if (context.sql !== INSERT_ACTION) return
const outcome = context.error === undefined ? 'statement-succeeded' : 'statement-failed'
const key = `${context.databaseId}:${outcome}`
observations.set(key, (observations.get(key) ?? 0) + 1)
})
sirannon.onBeforeQuery((context): void => {
if (context.sql !== INSERT_ACTION || !Array.isArray(context.params)) return
const quantity = context.params[2]
if (typeof quantity === 'number' && Math.abs(quantity) > REVIEW_THRESHOLD) {
throw new HookDeniedError('A stock adjustment above the example threshold requires review')
}
})
const openAgent = async (id: string): Promise<Database> => {
if (id !== 'stock-agent' && id !== 'returns-agent') throw new Error('Unknown agent')
const db = await sirannon.open(id, join(directory, `${id}.db`))
await db.execute(`CREATE TABLE action (
event_id TEXT PRIMARY KEY, item TEXT NOT NULL, quantity INTEGER NOT NULL, recorded_at INTEGER NOT NULL
)`)
await db.execute(`CREATE TABLE audit_outbox (
event_id TEXT PRIMARY KEY, item TEXT NOT NULL, quantity INTEGER NOT NULL,
recorded_at INTEGER NOT NULL, outcome TEXT NOT NULL, reason TEXT
)`)
return db
}
const recordAction = async (db: Database, item: string, quantity: number): Promise<void> => {
if (item.length === 0 || item.length > 200 || !Number.isSafeInteger(quantity)) {
throw new Error('Invalid stock adjustment')
}
const eventId = randomUUID()
const timestamp = Date.now()
try {
await db.transaction(async (tx): Promise<void> => {
await tx.execute(INSERT_ACTION, [eventId, item, quantity, timestamp])
await tx.execute('INSERT INTO audit_outbox VALUES (?, ?, ?, ?, ?, ?)',
[eventId, item, quantity, timestamp, 'committed', null])
})
} catch (error) {
if (!(error instanceof HookDeniedError)) throw error
await db.execute('INSERT INTO audit_outbox VALUES (?, ?, ?, ?, ?, ?)',
[eventId, item, quantity, timestamp, 'refused', error.message])
}
}
const collect = async (source: Database, journal: Database): Promise<void> => {
const PAGE_SIZE = 100
while (true) {
const pending = await source.query<AuditEvent>('SELECT * FROM audit_outbox ORDER BY rowid LIMIT ?', [PAGE_SIZE])
if (pending.length === 0) return
for (const event of pending) {
await journal.execute(
'INSERT INTO journal_entry VALUES (?, ?, ?, ?, ?, ?, ?) ON CONFLICT(agent, event_id) DO NOTHING',
[source.id, event.event_id, event.item, event.quantity, event.recorded_at, event.outcome, event.reason])
await source.execute('DELETE FROM audit_outbox WHERE event_id = ?', [event.event_id])
}
}
}
try {
const journal = await sirannon.open('journal', join(directory, 'journal.db'))
await journal.execute(`CREATE TABLE journal_entry (
agent TEXT NOT NULL, event_id TEXT NOT NULL, item TEXT NOT NULL, quantity INTEGER NOT NULL,
recorded_at INTEGER NOT NULL, outcome TEXT NOT NULL, reason TEXT,
PRIMARY KEY (agent, event_id)
)`)
const stock = await openAgent('stock-agent')
const returns = await openAgent('returns-agent')
await recordAction(stock, 'oat milk', -12)
await recordAction(returns, 'tinned tomatoes', 8)
await recordAction(stock, 'oat milk', -150)
await collect(stock, journal)
await collect(returns, journal)
const entries = await journal.query(
'SELECT agent, item, quantity, outcome FROM journal_entry ORDER BY agent, quantity')
console.log(JSON.stringify(entries, (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 example creates temporary files for demonstration. A service must preserve the agent databases and journal across restart, apply schemas through migrations, and select each database from authenticated application context.
Record every write from one place
The registry's onAfterQuery hook can observe statements across all its databases. Its context includes databaseId, SQL, parameters, duration, and an optional error. Hooks execute synchronously, and Sirannon does not await asynchronous work started by an after-hook.
The example therefore counts statement outcomes in memory while saving durable audit events inside recordAction()'s transaction. A statement can succeed before a later statement causes rollback, so the observation's statement-succeeded label deliberately makes no claim about commit.
The action and pending event commit together. If the journal is unavailable, the collector fails before deleting that event, so a later collection can retry it. If the process stops after the journal insert but before deletion, the journal's unique (agent, event_id) key prevents duplicate entries on retry.
The collector loads at most 100 pending rows per page, which is an example batch size. A deployed collector needs scheduling, failure alerts, and an outbox disk-space policy. It can fall behind while writes continue, so monitor the pending count and oldest pending timestamp.
Every action path that requires an audit record must use the transaction or an equivalent database trigger. The hook's SQL comparison demonstrates the API; a hostile caller with arbitrary SQL access can bypass that comparison. Restrict network access to registered operations.
Record what a rule refused
A before-hook can throw HookDeniedError before a statement executes. onAfterQuery does not report that refused statement, so the application records the refusal after catching the error.
The example waits for the refusal event's insert before completing recordAction(). A crash before that insert can leave no refusal record, so retry or reconcile an interrupted request through your application's request tracking. The committed-action guarantee comes from the transaction; the refusal record uses a separate write after rollback.
Keep credentials and unnecessary personal data out of audit events. Restrict journal reads and writes separately from ordinary agent tools, and apply backup and retention policies to both the journal and pending events. A SQLite journal is editable by anyone with write access to its file, so use additional protected storage if your requirements include tamper evidence.
Where to go next
Continuous backups preserve the journal's recovery history. Rewinding memory rebuilds an agent's earlier database, while hooks and metrics describe statement observations and row metering.