When an AI agent waits six hours for approval

Execution leases, durable human approval, and claim-time revalidation in Rails—why releasing compute while waiting is only half the problem.

During a six-hour approval wait, RubyLLM can store the question and release the worker. On resume, the host must check who is acting and what the action would do now. If the consequences have changed materially, show the difference and ask again.

My previous post covered evaluation jobs and tool approvals. Put those examples side by side and a practical question follows. When a person returns hours later, what is still waiting, and what needs to be checked again?

Consider this hypothetical case: at 09:00, an in-app assistant proposes deleting a draft newsletter campaign or activating a sequence. The app creates an approval request and pauses. The user gets pulled into meetings and does not click Approve until 15:00. In those six hours, a deploy replaced every worker process, an admin changed team roles, and a teammate edited the draft campaign into a scheduled broadcast.

That single six-hour pause actually raises four separate questions: Is any worker still running? Is the approval still valid? Who can resume it? Does the proposed action still match reality?

A worker can lose its lease without losing a user's approval. Conversely, a user can approve an operation that is no longer safe to execute. Those two failure modes look similar in a chat interface, but they belong to different state machines.

My previous post discussed 30-minute evaluation leases in ActiveAgent #614 and #715 alongside in-app tool approvals in Lewsnetter #53. Connecting those two timers is completely natural—and they are not the same clock:

  • ActiveAgent's 30-minute evaluation leases guard active background scoring and replay jobs; they are not human approval deadlines.
  • In RubyLLM's persisted Rails path, a waiting approval persists its question and returns, releasing ordinary execution ownership until a human answers.
  • Lewsnetter #53 builds on RubyLLM's persisted questions and rechecks authorization when the user decides and when the tool runs.
  • The RubyLLM AG-UI 1.0.0 adapter adds its own configurable interrupt expiry (900 seconds by default), separate from RubyLLM's execution lease.

In the design I propose, the server checks current permissions and business facts before acting. If a change alters what the person would be agreeing to, show the difference and ask again. If the action is now forbidden, stop.

4 clocksexecution lease, progress timeout, approval TTL, and business validity
3 machinesrun lifecycle, approval lifecycle, and tool execution lifecycle
4 layersActiveAgent, RubyLLM 2.2.3 docs, Lewsnetter, and AG-UI compared
34 casesproposed concurrency, TOCTOU, and recovery invariants (T01–T34)

If you only have a minute, this image is the whole post:

Summary of the post: When an AI agent waits six hours for approval. Four separate clocks: execution lease, progress timeout, approval TTL, and business validity. Comparison of ActiveAgent, RubyLLM Rails 2.2.3 docs, Lewsnetter #53/#80, and AG-UI 1.0.0. Three-part stale-intent model: automatic server-side revalidation, human-visible before/after diff with fresh consent when material facts change, and an atomic TOCTOU mutation boundary.
The post in one image. Open it full size to save or share it.

For the implementation details, start with the four-layer comparison below. The later campaign diff and test matrix are proposals for a host application.

Four clocks and three kinds of state

Half the confusion around long-lived agents comes from calling four different timers "the timeout." Before comparing frameworks, separate the clocks:

Track the active worker, the runtime’s progress limit, the approval window and the current business conditions separately. Record a human decision independently of the tool’s execution outcome.

ClockWhat it limitsTypical ownerWhat expiry means
Execution leaseTemporary ownership of an active execution attemptRuntime / workerAnother attempt may be allowed to acquire ownership
Execution deadline / progress timeoutDuration or progress of active workRuntime / queue / providerAbort, interrupt, or classify the attempt as failed
Approval TTLHow long a human decision request may be answered or redeemedApplication / approval protocolReject or replace the expired request
Business validityWhether the proposed operation is still appropriate nowDomain model / applicationBlock, recompute, or request a new approval

A hard execution deadline limits total elapsed time. A progress timeout measures time since the last sign of progress, so a long run can remain healthy. Neither measures how long a person may consider a proposal.

A fifth concept—retention—governs audit history and storage cleanup, not permission validity. External provider conversation state and OAuth token lifetimes can also impose their own limits independently of your app's clocks.

Three orthogonal state machines

In a durable agent design, three lifecycles move independently and should never be collapsed into one column:

  • Run lifecycle: queued → executing → waiting_for_input → queued/resuming → executing → terminal.
  • Approval lifecycle: pending → approved | declined | expired | cancelled | superseded. A human decision can be persisted before continuation work is scheduled or claimed.
  • Tool execution lifecycle: not_started → claimed → running → succeeded | failed | outcome_uncertain.

Three practical rules follow immediately from separating them: never collapse approved into executed; never treat a parked waiting_for_input record as a crashed running job; and when a pending or approved request is superseded, keep the original decision intact for audit and issue a fresh request with a new identity rather than mutating the original consent. Nor should you use an unrelated record's updated_at as a proxy for authorization freshness.

Six-hour durable approval timeline across two workers and a human decision Conceptual durable sequence across four lifelines: Worker A, Durable state, Human, and Worker B. At 09:00 Worker A claims an execution attempt, persists a pending tool call and approval request, and releases its execution claim on normal pause. Six hours pass with no active execution worker needed. At 15:00 the human submits a decision, which the app authorizes and atomically records in durable state, then schedules resumable work. Worker B acquires a fresh execution claim, rechecks current authorization and business preconditions, executes the tool, records the outcome, and releases its claim. Worker A (09:00) Durable state (DB) Human (15:00) Worker B (15:00) 1. Claim attempt 2. Persist pending approval 3. Release claim on pause Six hours pass (deploys, role edits, record edits) — no worker held by this turn 4. Authorize & record decision 5. Schedule / discover resumable work 6. Acquire fresh execution claim 7. Recheck permissions and business state 8. Execute, record outcome, release claim
Figure 1. Conceptual durable approval timeline (design model, not the literal code path of every framework—for example, Lewsnetter #53 resumes via ActionCable rather than a background job, and ActiveAgent's lower-level checkpoint API leaves persistence to the host).

What the 30-minute ActiveAgent leases actually do

Two of my ActiveAgent PRs added fixed leases to evaluation jobs. Each lease covers a specific piece of active work.

ActiveAgent's 30-minute leases in #614 and #715 guard active evaluation judge and replay jobs with owner tokens and fenced writes; they are not human-approval timers, and fencing protects database writes rather than remote billing.

Judge scoring: ActiveAgent #614

In ActiveAgent #614 (merged October 30, 2026; diff), duplicate evaluation judge jobs could both invoke the scoring LLM because an earlier timestamp-based claim was not enough to keep overlapping deliveries apart.

The fix introduced migration 030 (add_evaluation_scoring_leases, with a pre-migration fallback) and a time-limited owner token. A worker acquires the lease in a short database write, runs the LLM scoring request outside any database lock, and guards both success and failure writes with its owner token so a displaced worker cannot clobber its successor's result.

One recovery detail in the merged PR matters: when a duplicate delivery sees a live lease, you should reschedule it for lease expiry rather than silently dropping it. If the original process died hard and the queue already redelivered the job once, dropping the duplicate strands the work—expiry by itself never enqueues a retry.

The lease window is a fixed 30 minutes. A scoring call that genuinely runs longer can still be invoked again after 30 minutes. In the PR, 61 focused test runs (484 assertions) passed, while PostgreSQL/MySQL and live queue/provider concurrency were explicitly noted as unverified. The architectural lesson is narrow and clear: token fencing protects database writes, not provider billing or remote exactly-once execution.

Replay fan-out: ActiveAgent #715

ActiveAgent #715 (merged November 17, 2026; diff) solved a sibling problem in ScenarioEvaluationRunner#replay_scenario!. Previously, the runner checked whether a replay result existed, executed the agent, and only then locked the run to store the result. Two competing deliveries could both call the provider and tools before one threw its work away.

#715 added a per-scenario/provider/model claim token and 30-minute REPLAY_LEASE_DURATION inside scores["_fan_out"]["replays"], acquired under update_fan_out_state! while keeping external work outside the transaction. A duplicate delivery hitting a live owner reschedules with wait_until: the lease expiry and rechecks whether a result has already been stored; an expired claim can be taken over, and result storage, release, and failure bookkeeping are fenced by owner token. The PR describes regression tests for duplicate delivery, expiry, late owners, and judge-enqueue errors. Its mutation checks are reported separately from the committed tests.

As the PR itself notes, a replay that exceeds 30 minutes can still overlap, and a worker that dies after the provider responds but before persisting can replay the provider call. Because replay evaluation can invoke tools, evals need controlled fixtures or side-effect-free tools. Either way, none of this is an approval scheduler.

Atomic claims are not automatically leases

Two other merged PRs I wrote in ActiveAgent draw the line even more sharply:

  • ActiveAgent #664 (diff) adds a conditional transition to claim a pending agent run before execution. That prevents duplicate deliveries from both starting the same run, but by itself it does not add an expiring lease or dead-worker recovery for ordinary runs.
  • ActiveAgent #713 (diff) claims a pending evaluation run before sequential or fanned-out replay—a separate guard from the pair-level replay and judge leases above.

Keep three distinct protections separate in your head: claim before work (stops duplicate starts), lease expiry (permits a new attempt to take over), and token fencing after work (stops late owners from overwriting newer state).

Fixed-duration lease takeover and owner-token fencing Timeline from T0 to T+31m showing Worker A claiming a 30-minute lease at T0 and still running past T+30m when the lease expires. At T+31m Worker B claims a new owner token and starts. When Worker A attempts a late database write, the token fence rejects it while Worker B stores its result under the new token. A note clarifies that fencing protects database writes, not already-issued HTTP requests. T0 T+30M (LEASE EXPIRES) T+31M+ Worker A token: a1 Claims lease · runs LLM / tool Still running… Late write rejected (a1 ≠ b2) Worker B token: b2 Takes over · runs Stores result fenced by b2 A late write can be fenced. An HTTP request already sent can still take effect.
Figure 2. Lease takeover and owner-token fencing in the eval jobs. Times are illustrative and spacing is schematic.

ActiveAgent: checkpoint and resume, not a sleeping job

ActiveAgent's actual human-in-the-loop pause mechanism lives in a different part of the codebase—upstream work by other ActiveAgent contributors starting from issue #539 and implemented across PR #550 and PR #556 (diff).

ActiveAgent's upstream checkpoint flow (#550/#556) parks a serialized checkpoint instead of sleeping a worker, and #672 makes waiting runs atomically cancellable—leaving persistence and approval expiry policy to the host.

Rather than parking a thread or sleeping a background job, the framework emits an InputRequest and a serialized checkpoint capturing the conversation and waiting tool calls (including which calls require approval). Answers are passed into execution state rather than leaked into model-authored tool arguments. When the human responds:

  • Generation#resume_now(checkpoint:, answers:) reconstructs the action's tools and instructions and dispatches the resumed calls with the answer in execution state.
  • Generation#resume_later(checkpoint:, answers:, **job_options) validates the answers and enqueues GenerationJob with resume:. Notably, it rejects answers to secret input requests because queue arguments may be stored unencrypted—turning off parameter logging does not encrypt your queue table.

One nuance matters if you are wiring this into production: a checkpoint serialization API is not automatically durable storage in every host. You still need to verify which run-backed paths persist the checkpoint for you and which require your application to store, version, and restore it across deploys.

Cancellation while waiting: ActiveAgent #672

Because waiting for human input is a first-class lifecycle state, it has to be cancellable safely. In ActiveAgent #672 (my own PR, merged November 6, 2026; diff), run cancellation performs a conditional update restricted to pending, running, and awaiting_input. If the transition wins, pending input requests are cancelled in the same transaction; otherwise a reload reflects the terminal state so a stale browser tab or delayed job cannot overwrite a completed run.

So what happens in ActiveAgent after six hours? A properly persisted checkpoint can sit parked without holding a worker—the cited PRs do not impose a universal 30-minute deadline on human input. Whether it still succeeds six hours later depends on the host's persistence, expiry policy, deploy compatibility, and whether the actor and tools remain valid. (Racing approval against cancellation and duplicate resume jobs are separate concurrency edges that still deserve host-level tests; #672 fixes cancellation transitions, not every resume race.)

RubyLLM: the persisted chat owns the continuation

The 2.2.0 release introduced the upstream feature. For the behavior below I used the 2.2.3 tool guide and background-job guide.

In RubyLLM's documented Rails integration, pausing for approval releases active execution ownership while persisting pending questions; the 60-second lease (renewed every 15s) belongs only to active execution, and interrupted tools are not blindly replayed.

The durable approval path

In RubyLLM's persisted Rails integration (acts_as_chat), a tool declares requires_approval or pauses interactively for input. Questions and answers live on persisted tool-call records:

  • chat.pending_questions surfaces waiting questions without instantiating tools or opening MCP connections; chat.waiting? tells you the chat is parked.
  • ask and complete return once human input is required, releasing ordinary execution ownership. (In a multi-tool round, other eligible calls may run before the turn parks, so do not assume every tool in the round freezes instantaneously.)
  • One process can create the question, a web request can record the answer, and a third worker after a deployment can load the chat via its agent class and continue. That durability belongs to the persisted Rails integration—not to a plain in-memory Ruby chat object.
  • chat.answer(question_id, ...) records a first decision, whereas approve is intentionally able to revise an earlier decline. For ordinary approval UIs, stick to first-decision semantics unless changing minds is an explicit product feature. Declining a tool call that is already running can raise RubyLLM::ToolCallRunningError, and sending another user message while tool calls are unresolved raises RubyLLM::PendingToolCallsError unless your host explicitly declines or supersedes them first.

For interactive tools that call ask mid-method, code before the question can run again on resume—keep that prefix free of side effects. If the tool asks a different question on replay, RubyLLM can re-prompt rather than applying an old answer to a mismatched question. Useful safeguard, yes—comprehensive domain-state validation, no.

The 60-second lease belongs to active work

In RubyLLM 2.2.3, the ordinary persisted execution claim lasts one minute and the worker attempts renewal every 15 seconds. Normal return clears the claim. A live process can also lose it if renewals fail or the run stops making progress. The guide documents an exception for calls made inside an application transaction: renewal from a separate connection cannot see the claim, so the lease uses max_run_time. Run these methods outside your own transaction.

Operational details matter here: seeing a claim_token in the database does not by itself mean a worker is alive (the documented running? predicate checks lease validity); heartbeat renewals consume database connections and depend on synchronized clocks; and under SQLite write contention, renewal behavior deserves its own testing rather than assumptions carried over from PostgreSQL.

Six hours later—and what if a worker crashes mid-mutation?

Put those two halves together and the six-hour question has a clean answer at the RubyLLM layer: when the chat parks for approval, it returns and clears its active claim. No six-hour heartbeat runs. Six hours later—assuming the host still allows the approval and the persisted records remain compatible—a continuation attempt acquires a fresh execution claim and proceeds. The cited 2.2.3 docs do not define a general approval TTL, though that is never a guarantee that every provider session or host integration accepts arbitrarily old approvals.

RubyLLM persists questions, decisions, and execution ownership; it does not verify that your underlying ActiveRecord target, recipient list, or authorization rules stayed unchanged over those six hours, nor does it render a business-state diff. That belongs to your host application.

And what if a worker crashes after sending an email or calling Stripe, but before persisting the tool result? RubyLLM's documented interrupted-tool handling deliberately avoids blindly replaying a call that may already have caused a side effect, instead signaling to the model that the tool may have partially executed. That is the opposite of eval replay in ActiveAgent #715—and rightly so. Still, suppressing retries does not produce distributed exactly-once execution: you still need a stable domain idempotency key, an operation ledger, external status reconciliation, and human escalation when outcomes remain uncertain.

Lewsnetter: a real Rails product on top of the runtime

Frameworks give you primitives; real products expose the seams between layers. Here is what happened when I wired approvals, scopes, and claim-time revalidation into Lewsnetter, an open-source Rails email-marketing app (all PRs below are my own merged contributions).

Lewsnetter separates server-side approval (#53), OAuth scopes (#35), MCP host hints (#54), send claims (#61), and claim-time business revalidation (#80)—showing both what already works and where a generic semantic-diff UI is still new design.

In-app tool approvals in the chat channel: PR #53

Lewsnetter #53 (merged November 16, 2026; diff) gates destructive operations and sequence activation behind server-side approval in the tool adapter (Chats::ToolAdapter#requires_approval?), describing the proposed operation and affected record rather than showing an opaque tool name.

The lockfile at the merge of #53 pins RubyLLM 2.2.0. The in-app chat uses RubyLLM's persisted tool-call questions, rebuilding pending approval cards on reconnect. In ChatChannel, the decision handler (#decide) runs still_authorized?—crucial on a long-lived ActionCable websocket whose subscription-time permissions can go stale—locates the pending question by ID, records approvals via @chat.answer(question) (preserving first-decision semantics) and declines via @chat.decline, broadcasts the outcome, rebuilds tool context, and calls @chat.complete through run_turn. Tool ability is checked again when the tool actually invokes.

Notice two boundaries of #53 so we don't romanticize it: first, resumption runs directly inside the channel rather than enqueuing a durable ActiveJob continuation (so a disconnect or restart mid-resumption is a different failure mode than a job-backed worker); second, #53 adds no wall-clock approval TTL of its own, and opposing approve/decline race broadcasts still warrant dedicated UI-sync verification even when database first-decision storage is safe.

Approval and authorization in PR #35 and PR #54

Two adjacent PRs keep permission layers from bleeding into each other:

  • Lewsnetter #35 (diff) enforces mcp:read OAuth scope on the server at the tool boundary. Human approval can never grant a write tool to a read-only token.
  • Lewsnetter #54 (diff) adds read-only and destructive MCP tool annotations for external hosts. Annotations are client hints—never server-side authorization—and external MCP clients follow a separate dispatch and consent surface from the in-app chat gate.

Claim-time revalidation: the deeper analogy in PR #80

The clearest real-world lesson for stale approvals actually came from scheduled email sends, not chat. Lewsnetter #61 (diff) added an atomic claim before a campaign begins sending so competing workers cannot double-send. Then issue #79 surfaced the harder bug: a campaign was legitimately scheduled when the job was enqueued, then postponed, cancelled, or changed before the queued job ran.

Lewsnetter #80 (merged November 22, 2026; diff) fixed that by tagging scheduler-origin jobs (from_scheduler: true) and rechecking scheduled status, due time, and segment or all-subscriber confirmation under the claim lock before sending.

Be careful with the attribution here: #80 fixes scheduled campaign sends; it does not implement generic stale-approval detection or a semantic-diff UI. It is the exact structural analogy, though. A human approval recorded at 09:00 is also a previously valid decision sitting idle until execution time. If that draft newsletter becomes a scheduled production broadcast before 15:00, team membership and tool ability can both still pass while the real-world consequence of delete_campaign(id: 42) has completely changed.

RubyLLM AG-UI: when an interrupt expires

The RubyLLM AG-UI 1.0.0 adapter sets an interrupt expiry of 900 seconds (15 minutes) by default. The run accepts an expires_in: override. This is a setting of this Ruby implementation.

The RubyLLM AG-UI 1.0.0 adapter adds an explicit interrupt TTL (900s default), single-redemption decision recording, and a server-held argument digest—separate from RubyLLM's execution lease, though expired interrupts still require host reconciliation and current-state checks.

At default TTL, a six-hour-old AG-UI interrupt is rejected on resume. First redemption records the decision and competing submissions are rejected by the store; cancellation records a denial; and the server checks the original pending tool-call ID and its arguments before applying the decision. Even with a longer expires_in:, two boundaries remain the host's job:

  • Layer reconciliation: rejecting an expired AG-UI interrupt can leave an underlying RubyLLM pending tool call waiting unless your host explicitly declines, cancels, or replaces it—and you must ensure no direct host endpoint bypasses the interrupt TTL. Survival across restarts also depends on using a durable interrupt store rather than a process-local one.
  • Same arguments, different meaning: the adapter compares the digest of the host’s currently pending call with the digest saved at interrupt creation. The same arguments still match after campaign #42 becomes scheduled.

Comparing the four layers without conflating them

Compact comparison of ActiveAgent, RubyLLM Rails (2.2.3 docs), Lewsnetter #53/#80, and AG-UI (1.0.0 security guide), scoped strictly to the cited versions and PRs.

AspectActiveAgentRubyLLM Rails (2.2.3 docs)Lewsnetter #53 / #80AG-UI (1.0.0 guide)
Primary scopeAgent framework & evalsPersisted chat & tool runtimeProduct approvals & domain guardsInteraction protocol & interrupt store
Durable pauseCheckpoint + InputRequest (host persistence varies)Questions on tool-call recordsUses persisted RubyLLM chatInterrupt store (durability depends on store)
Worker during waitNo sleeping worker in checkpoint flowNo active completion workerNo waiting completion callInterrupt parks interaction
Execution leaseFixed 30m in eval judge/replay (#614/#715)60s active claims, renewed every 15sUnderlying RubyLLMUnderlying runtime (separate from TTL)
Approval TTLNot established by cited PRsNot established by cited docsNone added in #53900s default, configurable
Auth after waitHost responsibilityHost responsibilityRe-checked in channel & toolHost responsibility
Domain freshnessHost responsibilityHost responsibility#80 analogy for scheduled sendsArgument digest only; domain state is host's job
Semantic diff & reapprovalNot established by cited PRsNot established by cited docsNot established by #53/#80Not established; host policy & UI needed

The actual design challenge: stale intent

Suppose the same person, with the same role, approves the same tool arguments six hours later. Has the operation itself changed? The campaign example shows why an argument check can pass even when fresh consent is warranted.

In the proposed design, Automatically recheck authorization, decision binding, and domain preconditions on the server; if material facts changed and the new action is still permitted, supersede the request, show the meaningful before/after diff, and require fresh consent; guard the final mutation against TOCTOU.

Everything in this section is a proposed Rails design combining the lessons above—not an assertion that any cited library already implements it end-to-end. First, look at the nine things that can go sideways while an approval sits idle:

Change while waitingWhy checking approval alone failsProposed treatment
User loses team accessDecision was once legitimate; current actor is unauthorizedReject at decision and execution
Target record changes materiallyOriginal action's meaning or blast radius shiftedSupersede and request fresh approval
Tool arguments are modifiedConsent does not cover the altered callBind decision to server-side canonical intent
Tool semantics change in a deploySame name and args can behave differentlyVersion tool semantics or invalidate on breaking deploy
Another actor already did the workRe-running can duplicate an irreversible side effectReconcile existing outcome with idempotency
Approval arrives past TTLStale browser tab still displays an active buttonAtomically reject expired decision and refresh UI
Decision saved, job never enqueuedDurable consent exists, but work is strandedTransactional outbox or recoverable poller
Worker loses lease mid-mutationRemote effect may already have occurredFence local writes; reconcile remote status
Provider / MCP session expiresLocal approval is valid, remote call cannot resumeRe-establish safe state or re-propose; never silently substitute

An approval envelope, not a boolean flag

To detect stale intent and explain it to a human, store immutable proposal identity separately from mutable decision and execution state (illustrative schema, not RubyLLM's or ActiveAgent's tables):

approval_requests
  id, tenant_id, requester_id, run_id, tool_call_id
  tool_name, tool_semantic_version, canonical_arguments_digest
  target_type, target_id, expected_lock_version (optional)
  proposal_snapshot_ref, semantic_fingerprint, fingerprint_schema_version
  materiality_policy_version, effect_summary, decision_snapshot_ref (optional)
  status, requested_at, expires_at (nullable)
  decided_by_id, decided_at, decision_reason
  superseded_by_id, consumed_at
  invalidation_reason, invalidated_at (preserve original decision)

execution_attempts
  id, run_id, tool_call_id, owner_token, lease_expires_at
  started_at, finished_at, outcome
  stable_operation_key, external_reference

Notice why both a semantic_fingerprint and a redacted proposal_snapshot_ref exist. A hash digest alone can tell your code that something changed, but it cannot tell a human what changed. Conversely, storing a full unredacted copy of sensitive records creates a data-leak hazard. Store only the minimum decision-relevant facts, scope snapshot reads to the currently authorized viewer, and keep secrets out of client payloads and logs.

In this proposed Rails design, the approval and outbox share a transactional database. The submitted revision identifies the proposal the person saw. For an approval, the host also compares the proposal with current decision-relevant facts under a lock or equivalent version check. A material change invalidates that proposal and requires a fresh review.

# Web request. The server accepts only :approve or :decline.
ApprovalRequest.transaction do
  approval.lock!
  authorize_decision!(actor, approval)
  next approval.decision if approval.decided? # return the stored winner

  approval.require_pending_and_unexpired!(now: Time.current)
  approval.check_displayed_revision!(submitted_revision)
  if decision == :approve
    check = approval.check_current_intent_under_lock(actor)
    next approval.supersede_with!(check.new_proposal) if check.needs_fresh_consent?
    next approval.record_noop! if check.already_satisfied?
    check.require_permitted_and_current!
  end
  approval.require_pending_and_unexpired!(now: Time.current)
  approval.record_first_decision!(decision, actor: actor, now: Time.current)
  OutboxEvent.create!(kind: "decision_recorded", subject_id: approval.id)
end

# The outbox has a unique index on [kind, subject_id].
# Its consumer reads the stored decision. On decline it closes the tool
# request without running it. Only an effective approval can start work.
# Continuation worker:
# 1. Acquire runtime execution claim separately.
# 2. In a short domain transaction, reload target, re-authorize, check binding,
#    expiry policy, and domain preconditions, and reserve a durable operation key.
# 3. Never hold a DB lock across remote HTTP/LLM I/O.
# 4. Invoke external work with the stable operation key (and If-Match where supported).
# 5. Persist outcome under owner-token fencing; reconcile uncertain outcomes.

An after_commit enqueue leaves a crash window between database commit and queue submission. Writing the outbox event in the decision transaction makes a committed decision discoverable after a crash. A dispatcher retries delivery, and its consumer must tolerate duplicates. On a repeated or conflicting click, return the stored decision to the caller. Be equally explicit about whether your TTL governs when a decision may be submitted, when execution may start, or both—once an irreversible side effect has begun, TTL expiry is not retroactive undo.

From automatic revalidation to renewed human consent

Automatic checks and human-visible diffs operate at different boundaries and are never interchangeable:

BoundaryAutomatic server responsibilityHuman-facing behavior
Proposal creationAuthorize visibility; capture canonical intent and decision-relevant facts from a consistent readShow target, parameters, expected effect, scope, and conditions
Opening an old cardRefresh current facts and authorization; compute preliminary materiality checkShow current status, changes, expiry, and whether the card is still answerable
Approval submissionAuthorize actor; verify request ID and displayed revision; atomically reject stale or expired consentIf materially changed, supersede and ask for fresh review—never accept a stale tab click
Worker claim / resumeAcquire execution claim; load authoritative policy and domain state; check binding, revocation, expirySurface executing, blocked, or superseded status without assuming a live browser
Final mutationRe-verify and reserve/mutate under the relevant lock or conditional writeIf state shifted again mid-flight, stop and trigger a fresh review if still permitted
Completion / reconciliationPersist outcome, deduplicate events, reconcile uncertain external effectsShow what actually happened—not merely that approval succeeded earlier

Never treat a cached UI diff, an LLM-written summary, or an earlier authorize! call as an execution guarantee. And classify changes by consequences, not blindly by updated_at or lock_version:

ClassificationExamplePolicy outcome
ImmaterialAn unrelated metadata timestamp changes; decision-relevant facts matchContinue after checks—no needless human round trip
Material, still permittedCampaign #42 moved from Draft (0 recipients) to Scheduled (1,280 recipients), and policy still allows deletionSupersede old request; create fresh proposal showing what changed
Forbidden or impossibleActor lost permission, target was deleted, or policy forbids deleting scheduled campaignsBlock outright—never offer an approve button that overrides policy
Already satisfiedAnother teammate already completed the intended operationReconcile or return a domain no-op—never repeat blindly
Unknown / unavailablePolicy service or target cannot be read, or external outcome is uncertainFail closed for new mutations; retry validation or reconcile

Materiality rules should be domain-owned, deterministic, reviewable, and versioned. An LLM can help summarize a verified before/after diff in plain English, but it must never be the authority deciding authorization or materiality.

Context-aware approval UX: show the change, not just the error

Take an illustrative scenario (not observed Lewsnetter UI): at 09:00, the agent proposes delete_campaign(id: 42) on an unused draft. At 15:00, campaign #42 is scheduled for 1,280 recipients. The arguments are byte-for-byte identical, yet the risk is completely different:

Decision-relevant fieldOriginal proposal (09:00)Current state (15:00)Why it matters
Campaign#42#42Same record ID does not mean same intent
StatusDraftScheduledDeletion now disrupts a planned send
Recipient scope01,280Potential blast radius expanded
Record version79Technical evidence, not the primary explanation
Proposed consequenceRemove unused draftCancel & remove scheduled broadcastRequires a new decision if policy allows it

Instead of a cryptic 409 Conflict toast or a silent failure, show plain-language copy backed by an authoritative server proposal revision:

“This request is no longer current. Campaign #42 was a draft when deletion was proposed. It is now scheduled for 1,280 recipients. The original request cannot be used. Review the updated operation before deciding.”

If current policy allows deletion, present an explicit next step (Review updated deletion → Approve updated request / Decline) bound to a new request ID and proposal revision, keeping the original decision immutable for audit and non-redeemable. If policy forbids deleting scheduled campaigns, show the blocked explanation with no approve button. Never leak fields the viewer is no longer authorized to read, never rely on color alone to convey diffs, and make stale browser tabs reject old revisions cleanly rather than broadcasting a misleading success.

TOCTOU: the last check is part of the mutation

Even fresh approval does not end concurrency. A teammate can edit campaign #42 from version 9 to version 10 in the milliseconds between a human clicking Approve updated request and the worker executing the deletion. That is classic time-of-check/time-of-use (TOCTOU).

  • Local Rails database mutations: combine fresh authorization and domain preconditions with the write in a short transaction using a concurrency strategy that matches the invariant—pessimistic locking (with_lock) when writers coordinate on the locked row, or optimistic locking (lock_version) / conditional updates checking affected row counts. Watch out for multi-record invariants: adding 500 subscribers to a segment does not necessarily bump the parent campaign's lock_version. Protect the actual predicate (consistent lock ordering, database constraints, coordinated version counters, or serializable transactions with retries where supported), and test PostgreSQL and SQLite isolation assumptions separately.
  • External API mutations: never hold a Rails database transaction across network I/O. Reserve a durable operation identity under validated local conditions, then send a conditional request (such as an HTTP If-Match ETag or resource version) alongside a stable idempotency key when the downstream API supports both. Remember that an idempotency key prevents duplicate effects—it does not enforce freshness. Where a remote API lacks conditional writes, disclose that residual uncertainty instead of pretending a local check guarantees remote immutability.
Automatic revalidation and renewed human consent state flow Conceptual flowchart starting from Resume request. Step 1 checks if actor and tenant are authorized; if No, block without reapproval. Step 2 checks if the decision is valid and bound to canonical intent; if No, reject expired or superseded request. Step 3 acquires a fresh execution claim; if unavailable, return or retry per runtime policy. Step 4 reads authoritative domain state. An already confirmed effect ends the attempt without another mutation. For outstanding work, it evaluates policy and preconditions with four branches: Forbidden blocks without reapproval; Unknown stops and fails closed to retry or reconcile; Material change but permitted supersedes the old request, releases the claim, shows a meaningful diff and new proposal, waits without a worker, and loops back on fresh approval or ends without mutation on decline; Valid and same intent proceeds to atomically validate and reserve or mutate, looping back to reread domain state on concurrent TOCTOU conflict, or completing and reconciling external effects on commit. Resume request 1. Actor & tenant still authorized? Yes 2. Decision valid & bound to intent? Yes 3. Acquire fresh execution claim No Block (no reapproval) No Reject stale / expired Claimed 4. Read authoritative domain state & classify current policy / preconditions If the effect is already confirmed, record it and stop here. FORBIDDEN Block outright Release claim UNKNOWN Fail closed Retry or reconcile MATERIAL · PERMITTED Supersede & release Show before/after diff Wait for fresh consent SAME INTENT Atomic validate & reserve / mutate Conflict → recheck Fresh approve → Step 1 Decline → end safely Execute & reconcile Stable op key + fence Key invariant Never carry an old decision onto a superseded proposal; bound retries to avoid reapproval loops.
Figure 3. Conceptual state flow uniting automatic server-side revalidation, visible change disclosure for fresh human consent, and an atomic mutation boundary (proposed design, not a literal implementation in any cited library).

Approval as a conditional grant

Put simply, an approval is permission from a specified actor for a specified proposed effect under specified conditions, within a defined policy and time scope. It does not grant authority the actor lacks, freeze a business object, or confer runtime ownership. The runtime helps persist and resume the decision; your domain owns the conditions.

A lease establishes who may execute. Authorization establishes what is permitted. Approval captures human intent. Revalidation establishes whether that intent still applies.

Concurrency, recovery, and observability: the tests that matter

An architecture diagram is cheap until you try to break it with deterministic concurrency barriers and crash injection. The matrix below lists 34 proposed test invariants (proposed experiments, not newly executed benchmark results) covering everything from six-hour restarts to TOCTOU races and redacted diffs.

Turn the design into verifiable guarantees with deterministic barriers across preview, decision, claim, and commit—testing lease expiry, opposing decisions, revoked membership, material vs. immaterial diffs, TOCTOU, and uncertain external outcomes (T01–T34).

Start with one test on each side of the approval: revoke the actor’s permission before execution (T11), then change the recipient set while the actor stays authorized (T27). The first should block the mutation. The second should detect a material change even if the parent row version stays the same.

  • Pin versions and adapters: record exact gem lockfiles, Rails version, database (test PostgreSQL and SQLite separately—do not generalize from one), and queue adapter. Use fake LLM providers and mock downstream APIs, counting calls received by the fake independently of stored tool results.
  • Use barriers instead of sleeps: place deterministic synchronization barriers at preview, decision persistence, worker claim, and final domain commit, mutating target state or permissions at each barrier across separate database connections/processes.
  • Mutation-test your own guards: temporarily delete the conditional claim, owner-token fence, expiry check, authorization recheck, semantic fingerprint, or domain lock—confirm the matching test actually fails.
Open the full 34-scenario verification matrix (T01–T34)
IDScenarioInvariant to verifyTarget
T01Pause, advance 6h, resume in new processDurable pending input; no worker held by this turn; one continuation if still permittedRubyLLM / AA / Lewsnetter
T02Normal pause vs. hard kill mid-persistenceNormal claim cleared; dead active claim expires; pending state recoveredRubyLLM
T03Duplicate delivery while active claim validNo competing active attempt inside claim windowRubyLLM / AA #614/#715
T04Fixed eval lease expires while work still runsTakeover allowed; stale DB writes fenced; external overlap acknowledgedAA #614/#715
T05Two simultaneous approval submissionsOne effective decision; at most one permitted mutationRubyLLM / Lewsnetter / AG-UI
T06Approve vs. decline concurrentlyConsistent stored winner and UI; no mutation on effective declineLewsnetter / RubyLLM / AG-UI
T07Approve vs. cancel concurrentlyNo impossible terminal state; clear cutoff once mutation startsAA #672 / host
T08Submission right at TTL boundaryAtomic expiry/decision rule with explicit inclusive/exclusive edgeAG-UI / host
T09Expired interrupt leaves backend question pendingExplicit reconciliation or replacement; no unintended executionAG-UI + RubyLLM
T10Team membership revoked after pauseDecision and mutation authorization reject stale actorLewsnetter #53
T11Permission revoked after answer, before tool runNo unauthorized side effectLewsnetter / host
T12Target content, status, or recipients changeMaterial change invalidates approval or triggers fresh confirmationProposed host (#80 analogy)
T13User sends new message while approval waitsExplicit supersession or pending-call error policyLewsnetter / RubyLLM
T14Worker dies after external action, before DB writeNo blind replay; uncertain outcome reconciledRubyLLM + host
T15Answer committed; queue enqueue failsWork stays discoverable; recovery consumer is idempotentProposed outbox
T16Deploy changes tool schema or checkpointFail closed or migrate explicitly; no silent reinterpretationAll persisted paths
T17Mixed round: one tool completes, one waitsCompleted results retained; prior side effects not repeatedRubyLLM / AA
T18Client disconnects and reconnects during waitRestores durable approval and authoritative state, not stale UILewsnetter / AG-UI
T19Heartbeat blocked by DB contention or clock skewObserve lease behavior and stale-owner fencingRubyLLM
T20Remote MCP approval expires at provider/sessionReject or re-propose safely; never substitute another tool callRubyLLM remote approvals
T21Trace records tool failure or denialDistinguish requested, approved, declined, executed, failedAA #665 / telemetry
T22Only irrelevant metadata changes while waitingNo needless reapproval when semantic conditions stay validProposed host
T23Material, permitted change with identical argsNo mutation under old consent; new request + diff + fresh approvalProposed host / RubyLLM
T24Material change makes action forbiddenNo executable replacement approval and no side effectProposed host
T25Old browser tab submits superseded revisionStale revision rejected; new request stays undecided; accurate UIProposed host / AG-UI
T26Domain changes again after fresh approval (TOCTOU)Atomic domain guard fails; re-validate or re-review; no stale mutationProposed Rails host
T27Recipient membership changes without bumping parent versionAggregate/predicate change detected; parent version not trusted aloneProposed Rails host
T28Auth revoked between diff generation and decision/runNo unauthorized disclosure or mutationProposed host
T29Validator dependency unavailable, then recoversFail closed while unknown; durable retry or visible blocked stateProposed host
T30Remote resource version changes after local reservationConditional request (If-Match) rejects stale write where supportedProposed external tool
T31Reapproval issued, client drops, or outbox redeliversOld request stays non-redeemable; new request discoverableProposed host / AG-UI
T32External op succeeds, local completion write failsReconcile by stable operation key—never re-ask consent as substituteProposed host / RubyLLM
T33Diff includes fields approver cannot currently viewRedact or block display; zero leakage in UI, logs, or eventsProposed host
T34Policy/materiality rule or tool semantics change on deployExplicit migration or invalidation; no silent consent-scope shiftProposed host

Observability that does not cry wolf

Correlate run_id, approval_id, tool_call_id, attempt_id, tenant, and stable_operation_key across structured logs and traces without dumping secrets or raw sensitive diffs. Track waiting approval age separately from queue latency and active execution duration. Alert on answered-but-not-resumed work and stuck active runs—never merely because a human legitimately took six hours to reply. Break out revalidation outcomes (unchanged, immaterial, material_superseded, forbidden, unavailable), stale-client conflicts, conditional-write conflicts, lease takeovers, heartbeat failures, and unresolved external outcomes.

(For capturing tool execution boundaries cleanly, ActiveAgent #665 shows why recording client-side MCP dispatch and soft errors matters alongside ordinary Ruby tool calls; extending traces to full approval-lifecycle telemetry is a natural host-level next step, not something #665 itself implements.)

Conclusion: approval is a durable decision, not a durable lock

Fixed eval leases expire on active work; durable approval pauses release compute and persist decisions separately; preserving consent over six hours requires automatic revalidation, visible diffs for material changes, and an atomic mutation boundary.

For a Rails application that parks tool calls, I would make two decisions explicit:

  • Does the lease expire while an approval sits for hours? A fixed evaluation lease (#614, #715) can expire while active work is still running, which is why fencing and rescheduling exist. A normal durable approval pause (RubyLLM's persisted Rails path, ActiveAgent's persisted checkpoint flow, Lewsnetter #53) returns and relinquishes active execution ownership; a later continuation acquires a fresh claim rather than stretching a six-hour worker lease. The RubyLLM AG-UI adapter layers an explicit, configurable interrupt expiry on top.
  • Do you recheck preconditions automatically, or show the approver what changed? Both. Recheck authorization, decision binding, and business preconditions automatically on the server at execution time; block forbidden actions outright; let immaterial changes pass; and when material facts shift while the action stays permitted, supersede the old consent, show a meaningful before/after diff, require fresh approval, and guard the final mutation against TOCTOU.

An agent can remember what a person approved. It must still establish whether doing it now is allowed—and whether it is still the same action.

Read this with an AI

This post is long and structured on purpose so you can walk through it with an AI or apply its design directly inside your own Rails repo. A plain Markdown copy lives at /blog/when-ai-agents-wait-for-approval.md.

A plain Markdown copy lives at /blog/when-ai-agents-wait-for-approval.md. The full post includes copyable prompts for auditing leases, approval TTL, and TOCTOU guards in your own repo.

Or paste one of these prompts into Cursor, Claude Code, or Codex:

  1. Audit our approval & resume flow

    Read https://www.wangyaodi.com/blog/when-ai-agents-wait-for-approval.md. Inspect how this codebase handles human-in-the-loop tool approvals, background leases, and resumption. Report (with exact file paths and lines): (1) whether compute is released during waits, (2) whether approval is conflated with authorization or execution, (3) whether business state is revalidated under a lock at mutation time, and (4) what happens if the worker crashes after an external side effect.

  2. Design a semantic fingerprint & diff

    Read https://www.wangyaodi.com/blog/when-ai-agents-wait-for-approval.md. For our most sensitive AI tool in this repo, propose: (1) which domain fields and aggregates belong in a semantic fingerprint, (2) which changes are immaterial vs. material vs. forbidden, (3) what plain-language before/after diff the UI should show, and (4) the exact Rails locking/conditional-update guard to close TOCTOU.

  3. Write barrier concurrency tests

    Read https://www.wangyaodi.com/blog/when-ai-agents-wait-for-approval.md and look at its verification matrix (T01–T34). Propose the 5 highest-value deterministic concurrency tests for our current Rails stack (PostgreSQL/SQLite + our job adapter) using synchronization barriers rather than sleeps, and show what guard each test breaks if removed.

How this post was made

I wrote this post with AI, and every post here says how it was made:

Sources
My merged PRs in ActiveAgent (#614, #664, #665, #672, #713, #715) and Lewsnetter (#35, #53, #54, #61, #80); upstream ActiveAgent issues/PRs (#539, #550, #556); RubyLLM 2.2.0 release notes and 2.2.3 stable guides; AG-UI 1.0.0 security guide; Rails locking/transaction API docs; and my previous post.
Draft
Structured from an editorial research dossier and drafted with Antigravity, including the three inline SVG diagrams, comparison tables, and share cards.
Checks
On 27 November 2026 Codex checked the cited GitHub PR records, Lewsnetter’s lockfile at #53, the RubyLLM 2.2.3 guides, and RubyLLM AG-UI 1.0.0 source. T01–T34 are proposed experiments.
Original publication
Reviewed and approved for publication by Andy Wang.
Revision
1 December 2026. Revised the proposed approval example to distinguish repeat clicks, declines and approvals. The state diagram now shows where an already-completed action stops. The 34 scenarios remain a proposed test matrix.

If you spot a version drift, a misread edge case, or a cleaner Rails pattern, tell me on X and I will update this post.

References

Prior post, merged PRs across ActiveAgent and Lewsnetter, RubyLLM 2.2.x docs, AG-UI 1.0.0 guide, and Rails locking/transaction API references.