Level 10Lesson 86โฑ๏ธ 60 min

Permissions & Human in the Loop

A write should run because someone decided it should, not because the model asked.

What you will be able to do

  • Put one permission gate in front of every write, and have both engines (raw loop and Agent SDK) share it
  • Decide allow, deny or ask in code, with deny rules checked first so no allow rule can skip a limit
  • Design for the run nobody is watching: queue the proposal, finish the run, and execute later exactly what was approved
  • Make a refusal a result the model can reason about, and make the approval machinery fail closed when it breaks
Companion repo: posixplus/learn2exel-dayflow, tag lesson-86. New: dayflow/permissions.py, an approvals table, dayflow brief --approve ask|queue|auto,dayflow approvals, dayflow approve, dayflow deny. Diff: git diff lesson-85 lesson-86 -- dayflow/loop.py dayflow/sdk_agent.py dayflow/prompts.py.

The problem, in one run

Check out lesson-85 and run dayflow brief. Somewhere in the output you will find a line like this, from a real run:

- **Thu 9/10:** Vendor sign-off to Priya. I added this as a task, because your existing review task isn't due until 9/11.
- **Fri 9/11:** Return the signed field trip permission form. I added this as a task.

[3 steps ยท 6 tool calls ยท 7744 in / 1302 out ยท run 57b034ae09dd]

Nobody asked for those tasks. The model read two emails, judged that each implied an action, and wrote to your task list. Both tasks are reasonable. That is not the point. The point is that the only thing between an email the model misread and an action in your name was the model's own judgement, plus one sentence in the system prompt: "Never create more than two."

For tasks that is tolerable. Lesson 87 connects real Gmail and Calendar, and the next write tool sends email. The gate goes in now, while a mistake still costs a stray to-do item.

๐Ÿ’ก
Two different tools for two different jobs
Lesson 82 gave you --read-only, which removes the write tool from the surface. The model cannot even propose. That is still the stronger control, and it is the right one for actions you never want. This lesson is about actions you want sometimes.

Three answers, decided in code

A policy looks at the tool and at the run so far and returns one of three answers. It is a frozen dataclass with no I/O, so every branch is a unit test:

@dataclass(frozen=True)
class Policy:
    writes: WritesMode = "ask"          # ask | allow | deny
    max_writes_per_run: int = 2         # was a sentence in the prompt until this lesson

    def decide(self, tool: Tool, args: dict, *, writes_so_far: int) -> Decision:
        if tool.kind == "read":
            return Decision("allow", "read tools do not change anything")
        # Deny rules first. An allow rule must never be able to skip a limit.
        if self.writes == "deny":
            return Decision("deny", "this run is read-only", READ_ONLY)
        if writes_so_far >= self.max_writes_per_run:
            return Decision("deny", f"this run already proposed {writes_so_far} writes; ...", WRITE_LIMIT)
        if self.writes == "allow":
            return Decision("allow", "writes were pre-approved for this run (--approve auto)")
        return Decision("ask", f"{tool.name} is a write tool")

Three things to notice. The default is ask: a write runs only if a rule or a person said yes. The kind flag every tool has carried since lesson 82 is what the policy reads. And the order of the if statements is the security property: deny, then limits, then allow.--approve auto cannot get a third write through, andtest_deny_rules_are_checked_before_allow_rules pins that.

โš ๏ธ
The prompt rule was not holding
This lesson deleted "Never create more than two" from the system prompt and moved the number intoPolicy. On the first run without the sentence, the model proposed three tasks. The policy stopped the third, and the audit row says so:denied by policy ยท this run already proposed 2 writes; the limit is 2. A limit in a prompt is a request. A limit in code is a limit.

Who answers "ask": a person at the terminal

An Approver resolves an ask. The first one is for when you are watching. It shows the exact arguments, not a summary of them, because a person cannot approve what they were not shown:

$ dayflow brief --approve ask

Dayflow wants to run create_task  (create_task is a write tool)
    title: "Confirm vendor sign-off to Priya (procurement)"
    due: "2026-09-10"
    idempotency_key: "vendor-signoff-priya-2026-09-10"
  approve? [y]es / [n]o / [a]lways this run: y

Dayflow wants to run create_task  (create_task is a write tool)
    title: "Send edits on partnership one-pager to Sam"
    due: "2026-09-08"
    idempotency_key: "sam-onepager-edits-2026-09-08"
  approve? [y]es / [n]o / [a]lways this run: n
  reason (optional, the agent will see it): Sam and I settled this on a call

Three small decisions in TtyApprover matter more than they look:

  • Enter means no. The safe answer is the default answer. So is a closed stdin: EOFError is treated as a refusal, never as consent.
  • a approves this tool for the rest of this run, and only this run. It is the honest version of "stop asking me", and it still cannot pass the write limit.
  • A refusal carries a reason, and the reason goes to the model.

That last one changed the output. The same run finished its brief like this:

## Needs a reply
- **Sam (partnership one-pager):** He plans to send it to their exec team Wednesday.
  Suggested reply: "Thanks Sam. Per our call, no edits needed, so go ahead."

## Task actions
- Created: "Confirm vendor sign-off to Priya" (due 9/10) and "Return signed field trip permission form" (due 9/11).
- Declined: you said no to a task for Sam's one-pager edits because you settled it on a call. I won't retry.

The model did not just skip the task. It rewrote the suggested reply to Sam using what you told it. A denial with a reason is context, and good context. Hold on to the other side of that thought until lesson 88: anything that reaches the model is also a way to steer it.

Who answers "ask": nobody is there

A morning brief is meant to run at 6 a.m. from a scheduler. There is no terminal. Three designs are possible, and two of them are wrong:

DesignWhat happens at 6 a.m.
Block on input()The run hangs until someone notices. The brief never arrives.
Treat silence as yesYou have built --approve auto with extra steps.
Queue the proposalThe write is recorded and not run. The run finishes. You decide later.

So the default is not a mode you pick. gate_for() asks at a terminal and queues everywhere else (sys.stdin.isatty()). A cron job cannot end up waiting on a prompt by accident. Here is the same brief, unattended:

$ dayflow brief < /dev/null
...
## Waiting for your approval
- ap_71bc12: Create the task "Confirm vendor sign-off to Priya (procurement)", due 2026-09-10.
- ap_aea88a: Create the task "Send edits on partnership one-pager to Sam", due 2026-09-08.

Not created: a task to return the field trip permission form (due Sep 11). A write limit blocked it,
so consider adding it yourself.

2 write(s) waiting for approval: `dayflow approvals`, then `dayflow approve <id>` or `dayflow deny <id>`  [ap_71bc12 ap_aea88a]

[3 steps ยท 7 tool calls ยท 8391 in / 1429 out ยท run ea6146d3f952]

Two lines there tell you about the proposals, and they come from different places. The "Waiting for your approval" section is the model, following the prompt. The line starting "2 write(s) waiting" is printed by main.py from the approvals table. It does not depend on the model remembering to mention anything. When something needs a human, say so from code.

$ dayflow approvals
ap_71bc12  pending  create_task  run ea6146d3f952  2026-11-13T03:42:05+00:00
    title: 'Confirm vendor sign-off to Priya (procurement)'
    due: '2026-09-10'
    idempotency_key: 'signoff-priya-vendor-2026-09-10'
ap_aea88a  pending  create_task  run ea6146d3f952  2026-11-13T03:42:05+00:00
    ...

$ dayflow approve ap_71bc12
approved ap_71bc12: {'id': 't5', 'title': 'Confirm vendor sign-off to Priya (procurement)', 'due': '2026-09-10', 'done': False, 'created': True}
$ dayflow approve ap_71bc12        # again
approved ap_71bc12: {'id': 't5', ... 'created': True}      # the stored result; nothing ran twice

$ dayflow deny ap_aea88a -m "already handled in Slack"
denied ap_aea88a

What you approve is what runs

Look at what approve does and, more to the point, what it does not do:

def approve(store: Store, approval_id: str) -> dict:
    row = store.get_approval(approval_id)
    if row["status"] == "approved":
        return json.loads(row["result"])                 # second call: the stored result
    if row["status"] != "pending":
        raise ApprovalError(f"approval {approval_id} is {row['status']}, not pending")
    if store.is_expired(row):
        store.decide_approval(approval_id, status="expired", decided_by="policy", reason="older than its TTL")
        raise ApprovalError(f"approval {approval_id} expired at {row['expires_at']}; run the brief again ...")
    envelope = dispatch(row["tool"], json.loads(row["args"]))   # the recorded bytes, straight to the tool
    result = json.loads(envelope)
    if not result["ok"]:
        raise ApprovalError(...)                         # human said yes, tool said no: stays pending
    store.decide_approval(approval_id, status="approved", decided_by="human", ..., result=envelope)
    return result

There is no model call in that function. The arguments you saw in dayflow approvals are the arguments that reach dispatch(). The alternative, which many agent frameworks reach for first, is to pause the run and resume the model once you approve. Then the thing you approved and the thing that executes are separated by another model turn, and the model is free to "improve" the call. Security people call that gap time-of-check to time-of-use. The fix is the same here as anywhere: act on what was checked.

  • Approvals expire. After DAYFLOW_APPROVAL_TTL_HOURS (24 by default) a proposal is refused and marked expired. Friday's proposal to reply to a thread is wrong by Monday. Run the brief again and get a fresh one.
  • Approving twice writes once. The second call returns the stored result. And if the process dies between running the tool and recording that it ran, the write's own idempotency_key from lesson 82 makes the retry a no-op. Two lessons, one guarantee.
  • Every write decision is a row. dayflow approvals --all shows what was allowed, denied, queued, approved or expired, and whether policy or a human decided. When someone asks why a task exists, the answer is a query.

A refusal is a result, not an exception

The loop change is one line: dispatch(name, args) became gate.call(name, args). The gate returns the same envelope lesson 82 defined, so the loop does not know or care whether a human was involved:

{"ok": false, "error": {"code": "pending_approval", "retryable": false,
  "message": "Not executed. Queued for the user's approval as ap_71bc12. Do not retry. List it in the brief under 'Waiting for your approval'."}}
CodeWho said noWhat the model should do
pending_approvalNobody yetList it with its id. Never say it was done.
denied_by_userA personSay so in one line. Do not argue or try another route.
write_limitPolicyOffer it as a suggestion instead.
read_onlyPolicyOffer it as a suggestion instead.

All four are ok: false and retryable: false. The first matters because the action did not happen, and a model that sees ok: true next to the word "queued" will tell you the task was created. The second matters because the answer to "the human said no" must never be "ask again in a loop". The system prompt gained seven lines saying what each code means, ending with: Never describe a task as created, added or done unless its result was ok:true.

โ„น๏ธ
Did it hold?
Across the queued runs made for this lesson, the brief never claimed a pending task had been created, and always cited the approval id. That is a handful of runs, not a measurement. Lesson 89 turns exactly this claim into an eval that runs on every change.

The SDK engine: a hook, and a second lock

Lesson 84 promised that PreToolUse would become the gate. It calls the same Gateobject, so the two engines cannot drift apart:

async def ask_gate(hook_input, _tool_use_id, _ctx):
    name = _short(hook_input["tool_name"])
    outcome = await gate.acheck(name, hook_input["tool_input"])
    return {"hookSpecificOutput": {
        "hookEventName": "PreToolUse",
        "permissionDecision": "allow" if outcome.allowed else "deny",
        "permissionDecisionReason": "allowed by the Dayflow gate" if outcome.allowed else outcome.envelope,
    }}

options = ClaudeAgentOptions(
    ...
    allowed_tools=preapproved_tools(kinds),      # reads only. create_task is NOT on this list.
    hooks={
        "PreToolUse":  [HookMatcher(matcher="mcp__dayflow__.*", hooks=[ask_gate])],
        "PostToolUse": [HookMatcher(matcher="mcp__dayflow__.*", hooks=[record_step])],
    },
)

The second change is the one lesson 84 flagged with "lesson 86 narrows this". The write tool comes off allowed_tools. Six small experiments, each one real call to Haiku, show how the two settings combine:

Write in allowed_tools?Hook saysWhat happened
No(no hook)Refused by the harness: "Claude requested permissions to use mcp__dayflow__create_task, but you haven't granted it yet."
NoallowRan. A hook's allow is enough on its own.
NodenyRefused, with our envelope as the reason.
YesdenyRefused. A hook's deny beats the allow-list.
Yes(hook raises an exception)Ran. A crashed hook is not a deny. The allow-list let it through.
No(hook raises an exception)Refused by the harness, same message as row one.

The last two rows are why the write is off the list. A hook that throws does not block anything by itself. With the write on the list, a broken hook means the write runs unasked. With it off, a broken hook means the write is refused. That difference was tested by accident while writing this lesson. The first version of the hook ran the whole check in a worker thread, so that a person thinking at the prompt would not freeze the event loop. SQLite objected:

sqlite3.ProgrammingError: SQLite objects created in a thread can only be used in that same thread.
Error in hook callback hook_0: ...

## Waiting for your approval
- I couldn't create these tasks because permission to use create_task wasn't granted.
  Nothing was created, so please add them yourself or grant access.

The hook crashed on every write. Nothing was written, nothing was queued, and the brief said so. That is what failing closed looks like, and it only happened because of the second lock. The fix is inGate.acheck(): only the approver goes to a thread, the store stays on the thread that opened it, and test_async_check_keeps_the_store_on_its_own_thread keeps it that way.

โš ๏ธ
The envelope does not survive the SDK intact
On a hook deny, the model does not receive your reason verbatim. It receivesPreToolUse:mcp__dayflow__create_task hook error: {"ok": false, ...} withis_error set. The JSON is there, behind a prefix the harness adds. The model read through it in every run here, but the raw loop and the SDK engine are no longer sending identical bytes for a refusal, and you should know that before you write a parser that assumes they do. The finalResultMessage.permission_denials lists every refused call if you want it from code.

The numbers

Same fixtures, same date, Sonnet 5.5, small inbox. One run each, so read them as sizes, not as averages.

raw loop
  lesson-85                 3 steps ยท 6 tool calls ยท 7744 in / 1302 out     2 tasks written, nobody asked
  lesson-86 --approve auto  3 steps ยท 7 tool calls ยท 8371 in / 1369 out     2 written, 1 stopped by the limit
  lesson-86 --approve queue 3 steps ยท 7 tool calls ยท 8391 in / 1429 out     0 written, 2 queued, 1 stopped by the limit

Agent SDK
  lesson-85                 7 turns ยท $0.0249
  lesson-86 --approve auto  6 turns ยท $0.0218
  lesson-86 --approve queue 8 turns ยท $0.0224
  1. The gate costs no extra model calls. Three steps before, three steps after. A refusal comes back in the same turn a result would have.
  2. It costs about 8% more input tokens on the raw loop, roughly 600 per run. Most of that is the seven new prompt lines, sent on each of three steps, plus one more tool call. The SDK numbers move by less than their own run-to-run noise.
  3. The real cost is yours. Two prompts answered, or two ids approved later. That is the price of the control, and whether it is worth paying depends on the tool. For create_taskyou may well decide --approve auto is fine. For the email tool in lesson 87 you will not.
๐Ÿ–ฅ๏ธHANDS-ON EXERCISEโฑ 30 min

Approve, refuse, queue, and then break the gate

About fifteen cents of API calls. Delete dayflow.db between steps when you want a clean task list.

  1. Run `pytest`. 58 pass. Read tests/test_permissions.py top to bottom: it is the specification. Find the test that proves --approve auto cannot exceed the write limit.
  2. Run `dayflow brief` in a terminal. Approve one write and refuse one with a reason. Read the brief: where did your reason end up? Then run `dayflow approvals --all` and match each row to an answer you gave.
  3. Run `dayflow brief < /dev/null`. No prompt appears, because stdin is not a terminal. Find the two places the pending proposals are reported and say which one would still appear if the model forgot.
  4. Run `dayflow approvals`, approve one id twice and deny the other. Check `dayflow approvals --all`. Then run `sqlite3 dayflow.db "select title, idempotency_key from tasks"` and confirm the approved task exists exactly once.
  5. Expiry: run `DAYFLOW_APPROVAL_TTL_HOURS=0 dayflow brief --approve queue`, then try to approve one of the ids. Read the error, then look at its row with --all.
  6. Run `dayflow brief --engine sdk --approve queue -v`. Watch for the โœ‹ lines. Compare the brief with the raw-loop one from step 3: same sections, same codes, different engine.
  7. Break the hook on purpose: in dayflow/sdk_agent.py make ask_gate raise an exception on its first line, and run the SDK brief again. Nothing is written and the brief says permission was not granted. Now also change allowed_tools back to tool_names(kinds) and run once more. Count the tasks. Revert both changes.
  8. TypeScript: `cd ts && npm run brief -- --approve queue`, then `npm run approvals` and `npm run approve -- <id>`. Diff ts/src/permissions.ts against dayflow/permissions.py: the order of the checks in Policy.decide must be identical.

What this lesson deliberately does not do

  • Pause a run and resume it after approval. The run finishes and the proposal executes later from its stored arguments. That keeps "what was approved" and "what ran" identical. Lesson 91 covers resuming runs; this is the case where you should not.
  • Let you edit a proposal before approving it. The SDK supports rewriting a tool's input on allow. Dayflow does not use it: an edited proposal is a new proposal. Deny it with a reason and let the next run propose again.
  • Notify you. The queue is only useful if you look at it. A push or chat message when a proposal lands belongs with deployment in the capstone.
  • Write rules about arguments. The policy looks at the tool's kind and the run's write count. "Never email anyone outside this domain" is an argument rule, and it arrives with the tool that needs it in lessons 87 and 88.
  • Protect you from an injected proposal. A human approving a write is only as good as their attention. If a hostile email talks the model into proposing something plausible, the gate will dutifully show it to you. Lesson 88 is about that, and about why the approval prompt shows raw arguments.
Lesson 86 Quick Reference
Policy

Pure code: allow, deny or ask. Reads allow. Writes ask by default. Deny rules and limits are checked before any allow rule.

Approver

Resolves an ask. TtyApprover asks at the terminal (Enter and closed stdin mean no). QueueApprover records the proposal and returns without running it.

Gate

Policy + approver + audit + dispatch. gate.call() in the raw loop, gate.acheck() inside the SDK PreToolUse hook. One object, both engines.

Default mode

ask if stdin is a terminal, queue otherwise. A scheduled run can never block on input.

Approve = replay

dayflow approve runs the stored arguments through dispatch(). No model call. What you saw is what executes.

Expiry

Pending proposals are refused after DAYFLOW_APPROVAL_TTL_HOURS (default 24) and marked expired.

Refusal codes

pending_approval, denied_by_user, write_limit, read_only. All ok:false, all retryable:false. The prompt says what to do with each.

Two locks (SDK)

Write tools are off allowed_tools AND gated by the hook. A missing or crashing hook refuses the write. It failed closed for real while this lesson was written.

Audit

Every write decision is a row in approvals: status, decided_by (policy or human), reason. dayflow approvals --all.

Unlocks in ~15 min of reading