Why this matters
An advertising error costs real money within minutes: one misplaced zero on a daily budget or one unreviewed campaign launch can drain a small business's monthly marketing cash before breakfast. Letting an AI agent or an invited marketer mutate Meta or Google accounts directly turns a prompt bug, a stale report or a typo into an irreversible bill. This repository therefore puts a hard human-in-the-loop gate in front of every spend, campaign, tracking and safeguarded-payment action. This lesson explains how proposals are bound cryptographically to their previews, checked against layered ceilings, executed with read-before-write and read-back verification, and recovered safely after crashes without blind retries.
The ideas
Why nobody — human marketer or AI — executes directly
Small-business owners routinely work with external freelancers, agencies and AI recommendations, yet only the owner bears the credit-card bill when ad spend jumps unexpectedly. Product rules R4 and N2 establish one simple invariant: no external or financial mutation ever executes directly without an explicit human approval. Every automation mode honours this boundary — in disabled and observe, AI diagnostics cannot even draft proposals, and in copilot (the default), AI can only submit a pending proposal for the owner to read and decide.
Everyday actions are grouped into three risk tiers so the owner stays protected without suffering approval fatigue:
- Reversible acts (archiving a note or moving an unsent CRM lead stage) apply immediately with an undo message.
- Binding acts (changing a Meta or Google daily budget, publishing or pausing a campaign, changing a workspace tracking destination, or releasing a safeguarded payment milestone) always pass through Propose → Approve → Atomic Verify & Execute.
- Irreversible acts (revoking a marketer, cancelling a subscription, deleting a workspace or erasing customer data) require a plain-language consequence confirmation.
Propose, approve, verify and execute
Separating drafting from decision and from execution creates three clear checkpoints:
1. PROPOSE (workspace member, marketer or AI diagnostic)
| complete 4-field intent + closed payload allow-list + preview binding
| guardrail check + canonical SHA-256 preview hash + expiry (24h / 4h)
v
[pending] (database trigger locks all intent columns permanently)
|
| owner reviews exact diff in Approval Drawer (+ step-up MFA if needed)
v
2. APPROVE (owner decides before expires_at)
| pins approved_payload_sha256 + decided_by_user_id + decided_at
v
[approved] (owner may still withdraw to [cancelled] before claim)
|
| auto-execute on approval for META_UPDATE_BUDGET & TRACKING_UPDATE_DESTINATION
v
3. ATOMIC VERIFY & EXECUTE
| re-check preview hash, expiry, kill switch, guardrails, step-up & aggregate ceiling
| single-use DB claim: approved -> [executing] (starts 120s write budget)
| read-before-write -> commit write marker -> external write -> read-back
v
[executed] (verified receipt) OR [failed] / released to [approved] if no write startedIn plain words
Exact-diff previews, intent binding and SHA-256 pinning
A vague approval card saying "Raise budget" is almost as dangerous as no approval at all. Every approval request carries both a human-readable change preview and a machine-readable action payload for one allowed action type, locked together by five strict rules:
- Complete budget intent: Any budget proposal must state all four integer figures — current daily budget, proposed daily budget, lira delta and basis-point step — and the server verifies that
proposed - current === deltaand that the step matches exact arithmetic. Leaving out even one field fails withBUDGET_INTENT_INCOMPLETE. - Intent binding: Intent binding proves that the human preview summary, the top-level intent columns and the executable payload agree on every single number and target. Any discrepancy fails immediately with
PAYLOAD_PREVIEW_MISMATCH. - Closed payload allow-list: Each action type permits only a fixed recursive payload allow-list of keys. Any unrecognised key — such as smuggling
status: "ACTIVE"inside a budget payload — is rejected withPAYLOAD_KEY_NOT_ALLOWED. - Canonical SHA-256 preview hash: The server serialises the payload deterministically (sorted keys, exact integers) and computes its 64-character preview hash. Approval pins that hash, and execution recomputes it from scratch and aborts (
HASH_MISMATCH) if even a single byte differs. - Approval expiry: Every proposal carries a hard expiry: 24 hours by default, tightened to 4 hours whenever a budget move exceeds 25 percent. Expired rows can neither be approved nor executed (
APPROVAL_EXPIRED).
Layered ceilings, guardrails and step-up verification
Every proposal — and every execution — passes through an ordered guardrail pipeline where the most protective failure always wins deterministically with HTTP 422:
| Guardrail | Default limit or rule | What it stops |
|---|---|---|
| Kill switch | Workspace emergency stop (kill_switch_active) | Blocks all budget changes, campaign launches and tracking updates — even already-approved ones — while still allowing META_PAUSE_ENTITY |
| Protected entity | Owner-maintained list of locked target_ref values | Prevents anyone from altering flagship campaigns until explicitly unprotected |
| Paused by default | New campaigns must carry initial_status: "PAUSED" | Stops newly published campaigns from spending money before the owner switches them on |
| Step cap | 2000 basis points (20 percent of current budget) | Prevents sudden runaway spend and avoids resetting platform learning phases; binds every proposer, including workspace owners (OD-19) |
| Daily budget ceiling | 500_000 kuruş (5,000 lira per day) | Stops typos such as turning 500 lira into 50,000 lira |
| Aggregate ceiling | Workspace-wide total across all active committed budgets, checked under a database lock | Stops ten separate 5,000-lira campaigns from stacking to 50,000 lira per day |
| Step-up threshold | Budget delta above 100_000 kuruş (1,000 lira), plus every tracking destination update and safeguarded payment milestone release | Ensures a stolen session cookie or unattended browser cannot authorise high-impact spend or reroute conversion data |
Pay special attention to signed ceiling rounding inside the step cap. Standard half-up or floor rounding turns a +20.004% increase into 2000 basis points, sneaking an out-of-bounds spend jump under a 2000 wall. Using pure BigInt ceiling rounding away from zero maps +20.001% to +2001 (and -20.001% to -2001), keeping the boundary mathematically watertight.
Notice also how execute on approval interacts with bulk decision. When an owner individually approves a META_UPDATE_BUDGET or TRACKING_UPDATE_DESTINATION proposal from the approval drawer, the approve endpoint runs the executor immediately so the response already confirms whether the change took effect. By contrast, bulk decisions are capped at 20 rows and deliberately skip every request that requires step-up verification, trips a guardrail or auto-executes, ensuring one bulk click can never silently fire live ad-account mutations.
Guarded executors: test accounts, read-before-write and read-back
Even after an owner approves a valid, unexpired, hash-pinned proposal, the executor still treats the outside platform as untrusted and mutable:
- Test-account boundary: Until the project owners explicitly configure the live execution acknowledgement environment value (
EXECUTION_LIVE_ACKNOWLEDGED=owners-signed-off-OD-05), the Meta executor refuses any ad account unless the owner has explicitly set its test account flag (execution_test_account = true). - Read-before-write: Immediately before modifying anything, the executor fetches the live ad set from Meta Graph API and checks that it belongs to the connected account, uses the exact expected currency (
CURRENCY_MISMATCHotherwise) and still holds the exactcurrent_daily_budget_minorshown in the preview (PROVIDER_STATE_CHANGEDotherwise). If somebody already edited the budget directly inside Meta Ads Manager, the executor stops without writing. - Write and read-back: After recording the write marker and posting the budget update to Meta, the executor fetches the ad set a second time to verify that Meta actually stored the exact approved integer budget. If the live value shows provider drift (rounding, partial write or stale value), execution is marked
EXECUTION_UNVERIFIEDinstead of falsely claiming success. - Execution receipt: Every attempt stores a structured JSON receipt (
execution_receipt_jsonb) with its outcome code, observed before-and-after values and whether any remote write occurred. If an executed change later proves undesirable, the rollback helper drafts a brand-new compensating proposal back to the previous value — rollbacks are never autonomous.
The eight-state machine and crash recovery with two clocks
Every approval request moves through eight strict approval statuses enforced both in TypeScript and in PostgreSQL triggers:
- Active states:
pending,approved,executing. - Terminal states (never transition again):
executed,failed,rejected,cancelled,expired.
Database triggers enforce immutable intent columns once a row exists, and restrict withdrawing an approval from approved to cancelled strictly to workspace owners so an outside marketer cannot cancel an owner's decision.
The hardest engineering problem in safe automation is a process crash mid-execution. Suppose an API worker wins the single-use execution claim (approved -> executing) and then dies suddenly from an out-of-memory kill. Did it crash while reading Meta's current budget (zero external effect — safe to retry), or did it crash two milliseconds after sending the HTTP POST that raised the budget (unknown external effect — blind retry could double-apply or conflict)?
This repository solves crash recovery with one durable database marker and two separated clocks:
t = 0s Worker wins execution claim (approved -> executing)
| Read-before-write runs against Meta (still zero remote write)
|
t <= 120s WRITE BUDGET (EXECUTION_WRITE_BUDGET_SECONDS = 120s)
| Worker calls beginProviderWrite() -> commits execution_write_started_at
| (If worker arrives after 120s, DB refuses with EXECUTION_CLAIM_LOST;
| worker aborts cleanly with ZERO external write.)
| Only AFTER commit succeeds does worker send Meta HTTP write.
|
| <--- 780-second safety gap: live worker and recovery NEVER overlap --->
|
t >= 900s STUCK THRESHOLD (EXECUTION_STUCK_AFTER_SECONDS = 900s, DB floor 300s)
60-second recovery sweep inspects rows still in [executing]:
- execution_write_started_at IS NULL -> release to [approved] (EXECUTION_INTERRUPTED)
- execution_write_started_at IS NOT NULL -> terminal [failed] (EXECUTION_STATE_UNKNOWN)That design gives a rock-solid guarantee:
- Before the write marker (
execution_write_started_at) is committed, zero external write has happened, so stuck-execution recovery can safely release the claim back toapproved(EXECUTION_INTERRUPTED). - Once the write marker is committed, a PostgreSQL trigger forbids moving
executingback toapprovedever again; if the process dies, recovery ends the row permanently asfailed(EXECUTION_STATE_UNKNOWN) so a human verifies Meta Ads Manager first. - Because the write budget (
120seconds) is far shorter than the stuck threshold (900seconds, hard database floor300seconds), a stalled executor that wakes up late failsbeginProviderWritewithEXECUTION_CLAIM_LOSTlong before the recovery sweep can ever touch the row.
Finally, approval creation accepts a caller-supplied idempotency key so retrying a timed-out HTTP proposal request does not create duplicate pending rows. Following owner decision OD-22, idempotency keys belong to each workspace independently so Workspace A's key can never collide with or reveal Workspace B's key.
How this repository does it
Pure domain package versus database and API executors
Keeping approval rules in a zero-I/O package lets unit and fuzz tests prove every boundary before touching PostgreSQL or network mocks:
- Guardrails and intent checks:
guardrails.tsimplementsevaluateApprovalGuardrails, complete 4-field budget intent checks, preview-payload intent binding, signed ceiling rounding (computeBudgetStepBpsExact), kill switch, protected entities, paused-by-default, step cap, daily ceiling, tracking-health gate and step-up MFA thresholds. - Closed payload allow-list:
payload-allowlist.tsvalidates every nested key per action type (APPROVAL_PAYLOAD_KEY_ALLOWLIST). - Canonical hash and state machine:
canonical-hash.tscomputes deterministic SHA-256 digests,state-machine.tsenforces the 8-state transitions and verify-and-execute checks,aggregate-ceiling.tssums workspace committed budgets,execution-errors.tsseparates retryable pre-write errors from terminal unknown-state errors, androllback.tsdrafts compensating proposals withautonomousRollbackAllowed: false. - Hysteresis and simulation:
action-gateway-hysteresis.tsholds editable-field allow-lists, diff re-signing, remote version locks and delayed-conversion hysteresis (1.50/2.20ROAS dead band, 24h dwell, 12h cooldown, 3-in-7d flap breaker), whilepolicy-simulator.tsreplays candidate actions dry-run.
Migrations, routes and executors
Three additive database migrations harden the approval ledger below the API:
0003_approval_intent_integrity.sql: Locks immutable intent columns (BEFORE UPDATEtrigger) and prevents tampering with approved proposals.0013_real_approval_execution.sql: Addsexecution_test_accounton ad-account connections, restrictsapproved -> cancelledwithdrawals to owners, adds the per-workspace idempotency index and extends execution receipt support.0014_execution_progress_and_recovery.sql: Addsexecution_write_started_at, enforces the300-second SQL floor on stuck recovery, blocksexecuting -> approvedonce a write started, and definesrecover_stuck_approval_executions.
In the API layer, approvals.ts handles propose, approve (auto-executing META_UPDATE_BUDGET and TRACKING_UPDATE_DESTINATION), reject, cancel/withdraw and execute; approvals-bulk.ts enforces the 20-item anti-rubber-stamp bulk route; approvals-execution-account.ts toggles the owner test-account flag; meta-executor.ts runs test-account checking, read-before-write, beginProviderWrite, Meta Graph API update and read-back verification; tracking-executor.ts applies approved tracking destination updates inside PostgreSQL; and execution-recovery.ts runs the 60-second stuck-execution sweep.
Not built yet
What went wrong once
Adversarial reviews and integration audits across Waves 45 through 48 uncovered real edge cases in the approval engine, each closed with dedicated tests and migrations.
- Missing budget intent fields silently skipped the step cap. Earlier proposal validation checked
budget_step_bpsonly if the caller supplied it, allowing a partial budget payload to bypass the 20 percent wall. Closing this gap mandated all four intent fields and exact cross-checking (BUDGET_INTENT_INCOMPLETE). - A benign preview could wrap a mismatched executable payload. Without explicit cross-checks between
preview_summary_jsonbandaction_payload_jsonb, a crafted request could show+100lira on screen while executing a larger value. Adding strict intent binding (PAYLOAD_PREVIEW_MISMATCH) and closed per-action key allow-lists (PAYLOAD_KEY_NOT_ALLOWED) closed both preview-spoofing and extra-parameter smuggling. - Database triggers were missing below the TypeScript state machine. Before migration
0003, immutability of approved payloads lived only in application code, meaning a buggyUPDATEquery could alter an approved row. Adding the PostgreSQLBEFORE UPDATEtrigger made intent immutability impossible to bypass from SQL. - Standard rounding let
20.004%sneak under a2000bps cap, and single-campaign ceilings could be split across parallel proposals. Switching step math toBigIntsigned ceiling rounding fixed the boundary (20.001% -> 2001), and addingaggregate-ceiling.tsunder a workspace lock stopped concurrent multi-campaign proposals from breaching the workspace daily limit (AGGREGATE_DAILY_CEILING_EXCEEDED). - Tracking destination changes initially bypassed the approval ledger. Changing
meta_dataset_idor Google destination routing directly from a settings endpoint meant a single compromised session could silently redirect conversion signals. Moving tracking destination edits ontoTRACKING_UPDATE_DESTINATIONwith mandatory step-up MFA put tracking changes under the exact same audit trail as spend changes. - Non-owners could cancel an already-approved request, and mid-write crashes risked double execution. Migration
0013restrictedapproved -> cancelledstrictly to workspace owners so marketers cannot undo an owner's approval, and migration0014introduced the120swrite budget,900sstuck threshold andexecution_write_started_attrigger so crashes after a write starts can never be retried blindly.
Try it yourself
Every step below runs locally against pure in-memory approval suites — no running API server, no PostgreSQL port and zero external Meta or Google calls.
Step 1: Run the core approvals state-machine, hash-pinning and guardrail tests
This verifies preview hashing, expiry, kill-switch precedence, paused-by-default launches, protected entities and step-up thresholds.
node --test packages/approvals/test/approvals.test.mjsConfirm all tests pass and check that tampering with a single payload field triggers HASH_MISMATCH.
Step 2: Run the intent-binding and closed payload allow-list suite
This proves that incomplete 4-field budget intents, preview-versus-payload mismatches and smuggled extra JSON keys are rejected deterministically.
node --test packages/approvals/test/intent-binding.test.tsObserve how BUDGET_INTENT_INCOMPLETE, PAYLOAD_PREVIEW_MISMATCH and PAYLOAD_KEY_NOT_ALLOWED fire before any proposal can enter the queue.
Step 3: Run the Wave 48 approval gap tests (signed ceiling rounding, aggregate ceiling and step-cap parity)
This exercises OD-19 (step cap binding workspace owners too), 20.001% -> 2001 signed ceiling rounding and workspace-wide aggregate ceilings.
node --test packages/approvals/test/wave48-approval-gaps.test.tsConfirm that an owner proposal above the step cap and split proposals exceeding the aggregate daily ceiling are both blocked.
Step 4: Run the Action Gateway hysteresis and diff re-signing suite
This tests the 1.50 / 2.20 ROAS dead band, 24-hour dwell time, 12-hour cooldown, 3-in-7-day flap breaker and retired-hash rejection after edits.
node --test packages/approvals/test/action-gateway-hysteresis.test.tsNotice that even when every hysteresis gate passes, the output only recommends a proposal and never executes autonomously.
Check yourself
0 / 6An API worker claims an approved Meta budget change (approved -> executing), commits execution_write_started_at via beginProviderWrite, sends the HTTP write to Meta, and crashes before reading the reply. What happens 15 minutes later when the recovery job runs?
Why must the 120-second write budget stay strictly shorter than the 900-second stuck threshold (and its 300-second database floor)?
A workspace has a 5,000-lira daily budget ceiling and a 20 percent (2000 bps) step cap. A workspace owner tries to propose raising Campaign A's daily budget from 1,000 lira to 1,201 lira (a 20.1% increase). What happens?
An owner activates the workspace kill switch after discovering a broken checkout page. One budget increase was already in approved status and one pause proposal (META_PAUSE_ENTITY) is submitted. What does the system allow?
An owner selects 5 pending requests in the Approvals queue and clicks Bulk Approve. Two of them are META_UPDATE_BUDGET requests, one is a TRACKING_UPDATE_DESTINATION request (which requires step-up MFA), and two are low-risk non-auto-executing proposals. What does POST .../approvals/bulk-decision do?
Before updating a Meta ad set's daily budget from 1,000 lira to 1,200 lira, the Meta executor reads the live ad set from Meta Graph API and discovers its current daily budget is already 1,400 lira because someone edited it directly in Meta Ads Manager. What does the executor do?
Words to know
36Go deeper
In this repository
- Operator runbook and owner decisions:
Approve Meta Test Budget Change Runbook,Owner Decisions(OD-05,OD-19,OD-22),Wave 48 B ReportandWave 48 E Report. - Database migrations enforcing intent immutability and crash recovery:
0003_approval_intent_integrity.sql,0013_real_approval_execution.sqland0014_execution_progress_and_recovery.sql. - Companion lessons: Lesson 3 (Data, PostgreSQL triggers and locks), Lesson 5 (Cryptography and preview hashes) and Lesson 7 (Measurement and tracking endpoints).
- Archived lessons absorbed by this chapter:
Archived lesson 05 (AI governance and action boundaries),Archived lesson 15 (Distributed state machines and idempotency),Archived lesson 22 (Spend guardrails and cross-route fuzzing),Archived lesson 23 (Bounded autonomy and assurance)andArchived lesson 29 (Rollout readiness and operational SLAs).