06Chapter 6 of 7
Free course11 min read

Add the guardrails.

Every automation that writes data or sends messages needs a guardrail before it ships. This chapter is the config, the thresholds, the approval routes, the kill switch, and the audit trail that turn a working flow into one you can leave running.


A guardrail is not a feature you add at the end. It is the first thing you wire and the last thing you remove. Before an automation writes a row, sends a message, or moves money, something has to stand between the AI decision and the irreversible action, and that something has to be configured, not hoped for.

06.0

What you are actually building

The worked example for this chapter is an invoice auto-approval flow at a 40-person agency. Vendors send PDF invoices to billing@. Routework extracts the line items, matches the PO, and writes the record to the accounting system. Anything under $500 posts straight through. Anything over $500 pauses for a human to approve in Slack before the payment is queued.

The $500 threshold is the headline guardrail, but it is only 1 of 4 guardrails the flow needs. The others are quieter: a confidence threshold on the OCR step, an idempotency key so the same invoice never posts twice, and a kill switch the finance lead can flip without opening a config file. By the end of this chapter you will have configured all 4.

Where guardrails sit in the stack
Extract + decide
AGENT · Routework reads the invoice
extract.ts
Confidence gate
CHECK · OCR score ≥ 0.85
confidence.ts
Amount gate
CHECK · auto vs human, $500 split
amount.ts
Idempotency
CHECK · invoice_id seen before?
idempotent.ts
Approve → post → log
HUMAN → Slack · API → QuickBooks + audit
approve.ts
Guardrails are not a layer. They are checks wired between layers, before each irreversible action.

Notice the order. Confidence is checked before amount. Amount is checked before the idempotency lookup. The lookup runs before the human is paged. Each gate is cheap and each one shrinks the set of invoices the next gate has to think about, by the time finance sees a Slack message, 3 cheaper checks have already passed. This ordering matters: if you put the amount gate before the confidence gate, a blurry invoice parsed as $49.00 sails straight through to auto-post, because it never reached the confidence check. Cheap problems upstream prevent expensive problems downstream.

06.1

The amount gate

The amount gate is the easiest to picture and the easiest to get wrong. The rule reads plainly: if the invoice is over $500, route to a human. Below that, post automatically. The diagram below is the entire decision, drawn the way the runtime sees it.

The $500 approval fork
YesNo
Amount over $500?
Human reviewSlack #finance-approvalsAuto-approvepost to QuickBooks
The amber path costs a person 30 seconds. The olive path costs nothing but trust in the steps above.

Two things about that fork are worth naming. The first is that the threshold itself is a config value, not a constant. It will move. Finance will raise it to $1,000 when they trust the flow, drop it to $250 the week after an incident, and raise it back to $1,000 once the incident is closed. If changing the threshold requires a code deploy, the finance lead will ask engineering to do it, and it will be on the backlog for three days. The threshold has to live somewhere a non-engineer can edit.

The second is that the comparison is on the parsed amount, not the raw OCR text. If the OCR step returned "$1,250.00" as a string and the gate compares it as a string, the gate will think every invoice that starts with a 1 is greater than 500. Parse first, gate second.

Trigger, extraction, and pre-flight gates
invoice-routing.yamlyaml
1name: invoice-auto-approval
2trigger:
3 source: gmail
4 filter: to:billing@agency.com has:attachment
5 
6steps:
7 - id: extract
8 type: ai.ocr
9 model: claude-3-5-sonnet
10 output_schema:
11 invoice_id: string
12 vendor: string
13 amount_cents: integer
14 currency: string
15 line_items: array
16 confidence: number
17 
18 - id: confidence_gate
19 type: check
20 if: extract.confidence < 0.85
21 then:
22 route_to: human_review
23 reason: low_confidence
24 
25 - id: idempotency_gate
26 type: check
27 lookup:
28 table: posted_invoices
29 key: extract.invoice_id
30 if: lookup.found
31 then:
32 halt: true
33 reason: duplicate_invoice_id
Trigger
Watches the billing inbox for messages with attachments. Everything downstream fires per matching email.
OCR extract
Sonnet reads the PDF and emits a typed payload. amount_cents is an integer, no floats anywhere.
Confidence gate
First gate to fire. Anything under 0.85 is routed to a human regardless of dollar value.
Idempotency gate
Looks up the invoice ID before any write. A second occurrence halts the run with a duplicate reason.
Amount fork, human path, and the auto-post action
invoice-routing.yamlyaml
1 - id: amount_gate
2 type: branch
3 if: extract.amount_cents > 50000 # $500.00, integer cents
4 then: human_review
5 else: auto_post
6 
7 - id: human_review
8 type: human_approval
9 channel: slack
10 target: "#finance-approvals"
11 timeout: 24h
12 on_timeout: escalate_to:finance-lead@agency.com
13 
14 - id: auto_post
15 type: action
16 target: quickbooks.bills.create
17 body:
18 vendor: extract.vendor
19 amount_cents: extract.amount_cents
20 reference: extract.invoice_id
Amount fork
Integer cents comparison against 50000 = $500.00. Resolves to human_review or auto_post.
Human path
Posts to a Slack channel and waits 24h. Times out by escalating to the finance lead by email.
Auto-post
The irreversible action, writing a bill to QuickBooks. Body is built from the parsed extract output.

The amount is stored as amount_cents, an integer, and the threshold is written as 50000. No floats, no currency formatting, no string comparisons. Floats in financial logic are the kind of bug that takes 3 weeks to find and one apology email to explain.

✱ Field note
Every threshold in an automation is a future config change waiting to happen. If a non-engineer cannot edit it without a deploy, you have wired it wrong.
06.2

The confidence gate

The confidence gate is the one most teams forget. The OCR step returns a number between 0 and 1 that says how sure it is about the extraction. When that number is high, the parsed invoice is reliable. When it is low, the model is guessing, and a guess that happens to be under $500 will sail through every other check in the flow.

The fix is to put confidence ahead of amount in the gate order. If the model is not sure what the invoice says, the dollar value is not trustworthy enough to gate on. A $42 invoice with a confidence score of 0.6 is more dangerous than a $650 invoice with a score of 0.95, because the $42 one will pass the amount gate without a second glance. Route the low-confidence case to a human regardless of amount.

A low-confidence invoice, what should happen
GmailRouteworkFinanceQuickBooksinvoice.pdf (blurry scan)Routework runs OCR, returns confidence 0.62Slack: low confidence, please checkcorrected + approvedbill.create (verified)bill_id
The confidence check fires before the amount check. A $42 invoice with 0.6 confidence still goes to a human.

Picking the confidence threshold is empirical, not theoretical. Run the flow in shadow mode for a week, extracting every invoice but writing nothing, and compare the model output to ground truth. Plot the confidence score against whether the extraction was correct. The threshold is the point where false positives start outnumbering true positives. For the OCR step on this flow it sat at 0.85; on a different vendor mix it would land somewhere else.

06.3

The idempotency gate

The idempotency gate is the guardrail against the flow itself. Vendors send the same invoice twice. Gmail replays a webhook after a transient error. A retry handler kicks in when it should have stayed quiet. Without idempotency, a $4,200 invoice can post 3 times in a single morning and nobody notices until reconciliation.

Idempotency is a key, not a feeling. Pick a stable identifier, the vendor's invoice number, not the email message ID, not the timestamp, and write it to a lookup table the moment the invoice is processed. Every subsequent run checks the table first. If the key is there, the run halts and logs the duplicate. The reason to use the vendor-supplied invoice number rather than the email ID is that the same invoice can arrive in multiple emails, a forward, a re-send, an automated reminder from the vendor's billing system. The invoice number stays stable across all of them; the email ID does not.

posted-invoices.schema.json
JSON

The flow writes to posted_invoices after a successful QuickBooks post, not before. If the QuickBooks call fails, no row is written and the next retry is allowed to try again. If the QuickBooks call succeeds and the table write fails, the next retry will double-post, which is why the write order is: post first, record the bill ID, then write the idempotency row inside the same transaction as the audit log.

06.4

The kill switch

The kill switch is the guardrail that runs when every other guardrail has failed. It is a single flag in a config store that, when flipped, makes the flow refuse to take any irreversible action. New invoices are still extracted and classified. They are just held in a queue until the flag flips back. The scenario that makes this critical is not exotic: a vendor changes their invoice format, the OCR step starts misreading amounts, the confidence gate is not catching it because the model is still returning scores above the threshold. Someone catches it during Friday's review. The kill switch is the lever that stops the damage in ten seconds while the fix is worked out.

What a working kill switch needs
  1. A single flag in a config store, not a code change.
  2. Editable by the finance lead without opening a deploy pipeline.
  3. Read at the start of every irreversible step, not cached at boot.
  4. Logged when flipped, who, when, and the reason.
  5. A queue that holds paused invoices so nothing is lost while the flag is on.
  6. A daily summary while the flag is on, so it does not get forgotten.

The flag is read at the start of every action step, not at the start of the run. A 4-step flow that boots at 09:00:00 and writes at 09:00:08 should be able to honor a kill switch flipped at 09:00:04. Cache the config for a minute and you have built a guardrail that ignores the most urgent input it receives.

The kill switch config
kill-switch.yamlyaml
1# Reads at the top of every action step.
2# Stored in the same config store as thresholds — finance edits it
3# from the Routework dashboard, not from git.
4 
5flow: invoice-auto-approval
6 
7paused: false
8paused_at: null
9paused_by: null
10paused_reason: null
11 
12on_pause:
13 hold_in_queue: pending_review
14 notify:
15 - "#finance-approvals"
16 - finance-lead@agency.com
17 daily_summary_at: "09:00 America/New_York"
18 
19on_resume:
20 drain_queue: serial
21 rate_limit_per_minute: 10
22 notify:
23 - "#finance-approvals"
Where it lives
Sits in the same config store finance already uses for thresholds. No git, no deploy.
Flag + audit
paused is the single source of truth, with stamps for who flipped it, when, and why.
On pause
New invoices land in pending_review. Finance gets a Slack ping plus a 09:00 daily reminder so the pause is never forgotten.
On resume
Drains the queue in serial at 10/min so a backlog flush does not flood QuickBooks all at once.
06.5

What each guardrail catches

The 4 guardrails do not all catch the same thing. Mapping them against the failures they prevent makes it obvious why the flow needs all 4 and not just the famous one.

Which guardrail catches which failure
AmountConfidenceIdempotencyKill switch
Large invoice mis-paid✓◐✗✓
Garbled OCR sent live✗✓✗✓
Duplicate post on retry✗✗✓✓
Vendor compromise◐✗✗✓
New regulation rollout✗✗✗✓
A flow with only an amount gate misses 3 of these 5 failure modes. Each gate is doing distinct work.

The kill switch is the only one that catches all 5. That is not because it is the best guardrail, it is because it is the most blunt. The amount gate, confidence gate, and idempotency gate handle the predictable failures cheaply and silently. The kill switch handles the unpredictable ones loudly and at a cost, the cost being that nothing posts until the flag is cleared. You want all 4 because the cheap ones save the expensive one for cases it actually deserves. If every invoice requires a kill-switch intervention, the flow has deeper problems; the kill switch should be used a handful of times a year at most.

06.6

Wiring it before you ship it

The order in which you wire the guardrails matters as much as the configuration itself. Ship them in the wrong order and the flow either blocks every invoice or ships none of the protection. The order that works is the order they execute in: idempotency table first, confidence gate second, amount gate third, kill switch last.

Stand up the idempotency table before the flow handles a single real invoice, even in staging. The duplicate-attempts log is the highest-signal report you will have in the first week, if you are seeing duplicates in staging, you will see them in production. After that, run the confidence gate in shadow mode for 5 days while you set the threshold from real data. Add the amount gate next, starting with a low threshold ($100) and raising it as confidence in the flow grows. The kill switch goes in last because it is the only one you can wire blind, it does not need data to be correct.

✱ Field note
A guardrail you have not tested against a failure is a label, not a guardrail. The first thing you do after wiring each gate is feed it the case it is supposed to catch.

Before the flow is allowed to write to QuickBooks for real, every gate gets a failing test invoice. A confidence test that scans a deliberately blurry PDF. An amount test with a $501 invoice and a $499 invoice, run back-to-back. An idempotency test that submits the same invoice ID twice. A kill switch test that flips the flag, sends an invoice, and verifies it lands in the queue instead of QuickBooks. 4 gates, 4 deliberate failures, 4 green test runs before anything ships.

KEY TAKEAWAYS
  1. Wire guardrails before the action they protect, not after the first incident.
  2. Compare on parsed integer values, never on the raw OCR string. Store money as cents.
  3. Put the confidence gate before the amount gate, a low-confidence cheap invoice is still untrustworthy.
  4. Use a stable vendor-supplied identifier for idempotency, not the email message ID or timestamp.
  5. Read the kill switch flag at the top of every irreversible step, not once at boot.
  6. Test every guardrail against the failure it claims to catch before you let it write to a real system.
  7. Thresholds belong in a config store a non-engineer can edit, not in code that needs a deploy.

End · Chapter 6 of 7

Mark it complete and it’s ticked off on your route.

Rivet, the product security agent for software teams, free to start. Human-led pentests and design review when you need them. AI agents are our specialty.

or get a free Rivet scan

BASEDChicago, IL · remote

FIELD NOTES

ONE SHORT EMAIL A MONTH

© 2026 ROUTEWORK — ALL RIGHTS RESERVED

Claude and Mythos are trademarks of Anthropic. RouteWork is not affiliated with Anthropic.