Build an agent approval flow that survives a restart
By Flavio
Tagged: AI
Build a local approval queue with exact message previews, expiring decisions, rejection, and crash recovery. Test it safely with a fake email provider.
Say an agent drafts an email and asks you to approve it, then the process restarts before you answer.
When the next process boots up, a bare “the user approved” flag isn’t enough. You need to know the exact email you reviewed, whether your approval is still valid, and whether the send already went out. You also need a way to recover if the process crashes right after the email provider accepts the message, before your app saves the receipt.
Let’s build a small local script that handles all of this. It saves an immutable email proposal in SQLite, waits for your decision, and picks up cleanly in a later process. Instead of calling a real email API, we’ll use a fake provider backed by a second SQLite table that logs accepted messages locally and sends nothing over the network.
Approve an exact operation
Approving “send the reply” is too vague if the agent can edit the message after you say yes. Your approval has to lock in both the operation and the exact content you read.
Each proposal holds the recipient, subject, and body. We serialize those fields, compute a SHA-256 digest, and print that digest alongside the preview. When you run the approval command, you have to pass the same digest back.
Once saved, a proposal can’t be changed. If the agent wants to send a different message, it has to create a new operation ID and ask for a new decision. The SHA-256 digest verifies that the bytes match what you reviewed, while this local script assumes anyone with access to your terminal and filesystem is allowed to approve.
Create the local queue
Grab a current Node LTS release so you have the built-in node:sqlite module available. Create an empty directory and save the script below as approval.mjs.
The database has two tables. proposals tracks the intent and your decision, while accepted acts like an email provider with a stable idempotency key. Because those two writes happen in separate steps, we can simulate a crash right after the provider accepts the email and before our script records the local result:
import { createHash } from 'node:crypto'
import { DatabaseSync } from 'node:sqlite'
const [command, id, argument, seconds = '300'] = process.argv.slice(2)
if (!/^[a-z0-9-]{1,60}$/.test(id ?? '')) {
throw new Error('Pass an operation ID using lowercase letters, digits, or -')
}
const db = new DatabaseSync('approval.sqlite')
db.exec(`
CREATE TABLE IF NOT EXISTS proposals (
id TEXT PRIMARY KEY,
intent TEXT NOT NULL,
digest TEXT NOT NULL,
state TEXT NOT NULL,
approved_digest TEXT,
expires INTEGER
);
CREATE TABLE IF NOT EXISTS accepted (
id TEXT PRIMARY KEY,
digest TEXT NOT NULL,
receipt TEXT NOT NULL
);
`)
const read = () => db.prepare(
'SELECT * FROM proposals WHERE id = ?'
).get(id)
const setState = (state) => db.prepare(
'UPDATE proposals SET state = ? WHERE id = ?'
).run(state, id)
const transaction = (fn) => {
db.exec('BEGIN IMMEDIATE')
try {
const result = fn()
db.exec('COMMIT')
return result
} catch (error) {
db.exec('ROLLBACK')
throw error
}
}
if (command === 'propose') {
if (!argument) throw new Error('Pass the message body')
const intent = JSON.stringify({
to: 'reader@flaviocopes.com',
subject: 'Your draft',
body: argument,
})
const digest = createHash('sha256').update(intent).digest('hex')
db.prepare(`
INSERT INTO proposals (id, intent, digest, state)
VALUES (?, ?, ?, 'pending')
`).run(id, intent, digest)
} else if (command === 'approve') {
const ttl = Number(seconds)
if (!Number.isInteger(ttl) || ttl < 1 || ttl > 3600) {
throw new Error('Approval lifetime must be 1 to 3600 seconds')
}
transaction(() => {
const row = read()
if (!row || row.state !== 'pending' || argument !== row.digest) {
throw new Error('Approval must match the pending proposal digest')
}
db.prepare(`
UPDATE proposals
SET state = 'approved', approved_digest = ?, expires = ?
WHERE id = ?
`).run(argument, Date.now() + ttl * 1000, id)
})
} else if (command === 'reject' || command === 'cancel') {
transaction(() => {
const row = read()
if (!row || !['pending', 'approved'].includes(row.state)) {
throw new Error('Already started or settled: reconcile before cancelling')
}
setState(command === 'reject' ? 'rejected' : 'cancelled')
})
} else if (command === 'run') {
const receipt = transaction(() => {
const row = read()
if (!row) throw new Error('Unknown proposal')
const accepted = db.prepare(
'SELECT * FROM accepted WHERE id = ?'
).get(id)
if (accepted) {
if (accepted.digest !== row.digest) throw new Error('Receipt mismatch')
setState('completed')
return accepted.receipt
}
if (row.state === 'executing') {
throw new Error('Ambiguous operation: investigate before another send')
}
if (row.state !== 'approved' || row.approved_digest !== row.digest) {
throw new Error('No matching approval')
}
if (Date.now() >= row.expires) throw new Error('Approval expired')
setState('executing')
return null
})
if (receipt) {
console.log('Reconciled receipt:', receipt)
} else {
const row = read()
db.prepare(`
INSERT INTO accepted (id, digest, receipt) VALUES (?, ?, ?)
`).run(id, row.digest, `fake-${id}`)
console.log('Fake provider accepted:', id)
if (argument === '--crash') process.exit(23)
setState('completed')
}
} else if (command !== 'show') {
throw new Error('Use propose, show, approve, reject, cancel, or run')
}
console.log(read())
console.log('Accepted messages:', db.prepare(
'SELECT COUNT(*) AS count FROM accepted'
).get().count)
db.close()
Think of approval.mjs as the boundary an AI agent calls when it wants to send mail. You don’t need a live model hooked up to test whether it blocks an unapproved send. Putting these checks in plain application code also keeps the model from talking its way around them or bending the rules mid-run.
Pause and inspect the proposal
Start by creating a draft message:
node approval.mjs propose draft-42 'Your draft is ready for review.'
That command writes the intent to SQLite and exits right away. Whenever you’re ready to review it, start a fresh process and inspect the draft:
node approval.mjs show draft-42
Read the full intent payload and note its digest. You have to pass that exact digest to approve the send, so stash it in a shell variable to avoid pasting mistakes:
read APPROVAL_DIGEST
Paste the digest and hit Enter, then approve the proposal for five minutes:
node approval.mjs approve draft-42 "$APPROVAL_DIGEST" 300
Your decision is now in SQLite, so the original process never had to stay alive and nothing depends on that shell variable once the command finishes. Passing the wrong digest fails, and trying to overwrite draft-42 with another proposal fails too.
Resume, crash, and reconcile
Next, let’s force a crash right after the fake provider accepts the email:
node approval.mjs run draft-42 --crash
The process exits with code 23. At this point, the proposal sits in executing, even though the accepted table already has one message.
Start it again to recover:
node approval.mjs run draft-42
This time the script finds the existing receipt and marks the proposal completed. Running it again keeps the accepted message count at one.
Notice the order of checks during recovery. The script looks for an existing receipt before checking whether the approval expired, because recording a send that already happened won’t trigger a new email. If a proposal is stuck in executing with no receipt at all, the script stops so you can inspect what happened instead of guessing that a retry is safe.
That’s a cautious default on purpose. With a real email service, you can often clear up the uncertainty by querying the provider for the message status or retrying with the same idempotency key, though eventual consistency or an expired idempotency window can still make the answer murky.
Test the decisions that must stop a send
Now test the paths that should block a send. First, create another proposal and reject it:
node approval.mjs propose draft-43 'A reply I do not want to send.'
node approval.mjs reject draft-43
node approval.mjs run draft-43
The final command fails without adding an accepted message. Cancelling a pending or approved proposal behaves the same way:
node approval.mjs propose draft-44 'A reply that is no longer needed.'
node approval.mjs cancel draft-44
node approval.mjs run draft-44
To test expiry, create draft-45, inspect it, and approve its digest with a lifetime of one second. Wait two seconds before running it. The script rejects the expired approval, and the accepted message count doesn’t change.
Rejecting and cancelling are final in this demo, so a new attempt needs another operation ID. The run command also claims execution inside a SQLite transaction, which stops two processes from grabbing the same approved proposal at the same time.
Put a real approval interface around it
Moving this into a web app means authenticating the reviewer on the server, checking whether they’re allowed to approve that specific operation, and storing their identity alongside the decision. Keep that approval endpoint separate from the agent’s tool permissions so the agent can’t approve its own requests.
If you’re using a durable workflow runtime, Cloudflare Workflows can wait for an event, and Workflow SDK can wait on a hook. Both give you a place to pause, while your app still verifies who clicked approve and which exact intent they reviewed before passing the decision back in. I compared those runtimes with Pi Durable in Pi Durable, Cloudflare Workflows, or Vercel Workflow?.
A real email provider also needs its own deduplication contract. Pass the stable operation ID within the provider’s documented scope and retention window. Our accepted table holds onto receipts forever, whereas most external services only honor an idempotency key for a limited time.
Once execution starts, this script refuses cancellation because it can’t guarantee stopping an email the provider already accepted. Show that clearly in your UI: “cancellation requested” and “nothing was sent” are two different states, and you need different proof for each.
Put approval.sqlite and its journal files on persistent storage and keep them out of Git, since the approval queue only survives restarts as long as that file stays intact. When you connect a real send tool in production, add reviewer authentication, database backups, and handling for host failures and provider outages around this queue.
Want me to talk about your product? You can sponsor this site.
Related posts about ai: