Gate agent writes on human approval — one exact plan per OK, single-use expiring nonce, crash reconciliation, drafts-only filter. Use before any agent write. Local state file.
---
name: human-in-the-loop
description: Gate agent writes on human approval — one exact plan per OK, single-use expiring nonce, crash reconciliation, drafts-only filter. Use before any agent write. Local state file.
metadata: {"clawdbot":{"emoji":"✋","requires":{"bins":["python3"]},"homepage":"https://openclaw.ai"}}
---
# Human in the Loop
An approval is a narrow, perishable object: it covers one exact action, once, for a limited time. Everything around it is bookkeeping that must survive a crash: the intent is written before the call, success is an id returned by the API, and a doubt is resolved by looking before creating, never by retrying.
## Data, state, and retention — read first
| Item | What this skill does |
|---|---|
| What `scripts/hitl.py` touches | One JSON state file + its `.lock` sidecar, and one run-lock file per external application, all paths you choose, created `0600`, symlinks refused. No network call, no subprocess. |
| What the state file holds | Item id, status, plan fingerprint (sha256), gate names, sha256 of the open nonce, remote id, attempt count, timestamps. Never the plan, the draft, or the nonce itself. |
| Personal data | Business keys and drafts stay in your process memory. They may hold personal data: process them only under the lawful basis of the pipeline that produced them, and prefer opaque references (file number, thread id) over names in item ids and keys. |
| Retention | Keep `applied` items as long as your reconciliation lookups reach back (a pruned item can be re-created as a duplicate). Prune older items on your own schedule. |
| Credentials | One approval secret (≥32 bytes) from an env var or a `0600` file, distinct from every provider credential. Never logged. |
## When to Use
| Situation | Action |
|---|---|
| "ask me before it creates / sends / pays" | §1-§3 with `regime="approval"` |
| "the user said OK, can the agent also fix the other thing?" | No. §1: one plan = one action |
| "the job timed out, did it create the record?" | §4: reconcile, never re-run the creation |
| "two runs of the cron hit the same app" | §5: run lock |
| "the agent only prepares drafts, a human sends them" | §6: `regime="draft_only"`, filter in code |
| Auditing an existing approval flow | Fill the Output Format, one row per rule |
## States and named gates
| State | Meaning | Leaves by |
|---|---|---|
| `proposed` | Plan fingerprinted, nothing asked yet | `open_request`, or apply (draft_only only) |
| `waiting_human` | Blocked on a person; carries named gates | signed decision, expiry, or a new request |
| `approved` | Signed OK redeemed, valid until `approval_exp` | apply, or `approval_stale` |
| `applying` | Intent persisted, API call in flight | recorded id, or `uncertain` |
| `uncertain` | No proof either way | reconciliation only |
| `applied` / `rejected` / `expired` | Final / explicit no / request timed out | new request (not from `applied`) |
Gates are snake_case names the report can count, never prose: `new_record_review`, `possible_duplicate`, `retry_exhausted`, `approval_stale`, `draft_filter`, `workflow_classification_uncertain`, `ambiguous_match`, `missing_document`, `send_required`, `unknown_screen`. When the screen, the data, or the classification does not match the playbook, the answer is `waiting_human` with a gate, not a best guess.
## 1. An OK covers the exact action, never the adjacent
One item = one plan = **one** mutating action. A multi-step job is several items, each approved on its own.
```python
plan = {"action": {"verb": "create_record", "target": "folder/REF-1", "fields": {"amount": 120}},
"business_key": {"client_ref": "REF-1", "party": "Party A"},
"unknowns": []}
propose(store, "REF-1:open", plan, regime="approval")
```
`begin_apply` compares the action about to run with `plan["action"]` as canonical JSON. A different verb, another target, or one extra field ("while I'm here, I also closed the old one") is refused. Approval drift is the common failure: the human reads a one-line summary, says OK, and the agent treats it as a mandate to tidy up around it.
## 2. Approval lifecycle
Token format and threat model (why a reply matching `GO 42` is not an approval, channel identity vs signed nonce) are covered by the `prompt-injection` skill, §5. This section covers what happens to a request over time.
```python
nonce = open_request(store, "REF-1:open", plan, ["new_record_review"], ttl_s=3600)
# show the human: plan summary + fingerprint prefix + buttons carrying the nonce
tok = sign_decision(secret, "REF-1:open", nonce, fingerprint(plan), "owner", "approve") # approval bot side
decide(store, "REF-1:open", tok, secret, plan, {"owner"})
# Output: 'approved'
```
| Rule | Why |
|---|---|
| The request has its own expiry, separate from the token's | A request left open for days turns into a blank cheque; a late tap on an expired request is refused and the item is marked `expired`. |
| A new request supersedes the old one | Only the latest nonce digest is stored; a token for the previous request dies with it. |
| Redeeming clears the nonce in the same locked step | Replay finds no open request. The state file is the ledger. |
| `approval_exp = min(token exp, request exp)` | An OK given on Monday does not authorise a run on Friday: past it, `begin_apply` returns `waiting_human` + `approval_stale` and calls nothing. |
| Clock tolerance 60 s on `iat`, none on `exp` | Two hosts drift; a token dated further ahead than that was not minted by your approver. |
| "No" is signed too | An unsigned "no" is as forgeable as an unsigned "yes"; `rejected` is a state, not an absence of reply. |
| Fingerprint re-checked at decision **and** at apply | A plan edited after the request, or after the OK, is refused at both points. |
| A new OK cannot restart an `applying`/`uncertain` item | Otherwise approval becomes a way around reconciliation. |
## 3. Apply: intent first, success = an id
```python
r = guarded_apply(store, item_id, plan, plan["action"], create=call_api)
# Output: {'status': 'applied'} or {'status': 'uncertain'} or {'status': 'waiting_human', 'gates': [...]}
```
Order inside `guarded_apply`: checks and filters → `applying` persisted with fsync → the call → the result. If the process dies after the remote object exists but before the write-back, the state file still says `applying`, which is what forces §4 on the next run.
| API outcome | Recorded as |
|---|---|
| Response carries a non-empty id | `applied`, id stored |
| Exit 0, `{"ok": true}`, `{}`, `None`, `id: ""`, `id: true`, `id: 0` | `uncertain` |
| Timeout, 5xx, client crash, any exception | `uncertain` (never `failed`: you do not know) |
Keep two counters in the run summary, `skipped` and `technical_failures`: a technical failure is not a skip, and it goes to the top of the report.
## 4. After a crash or timeout: reconcile, never re-create
```python
matches = search_remote(**plan["business_key"]) # YOUR lookup; it must raise on error
reconcile(store, item_id, plan, matches)
# Output: 'applied' | 'waiting_human' (possible_duplicate / retry_exhausted) | 'approved' (one retry)
```
| Lookup result | Outcome |
|---|---|
| `None`, a string, anything not a list of dicts | Refused; stays `uncertain`. A failed search is not "absent". |
| Exactly one candidate whose business-key fields all match (trimmed, case-folded) | `applied`, its id attached |
| Two or more matches, or any candidate missing a key field or an id | `waiting_human` + `possible_duplicate` |
| Zero matches, attempts < 2 | `approved` again (or `proposed` in draft_only): one bounded retry |
| Zero matches after the retry | `waiting_human` + `retry_exhausted`. No third attempt, no auto-reconnect loop. |
Business keys are the fields a human would use to spot a duplicate (reference, parties, date, amount), not the remote id you never received. Re-check candidates in code: remote search is often fuzzy or prefix-based.
## 5. One runner per application
```python
acquire_lock("/var/lib/agent/app.lock", job_id="open-records-am", ttl_s=2700, app_running=probe())
```
| Lock state | Outcome |
|---|---|
| None | Acquired |
| Live (not expired) | `SkipLocked("SKIP_LOCKED")`: do nothing this tick |
| Expired, `app_running is False` (proven stopped) | Taken over |
| Expired, `app_running` True, `None`, `"false"`, `0` | Refused: technical alert, lock left intact |
| Corrupt or symlinked lock file | Refused |
An expired lock means the holder is late, not dead. A UI-driving agent that is still clicking when a second run starts produces the duplicate that §4 then has to untangle.
## 6. Drafts-only regime
When the agent only prepares drafts that a human sends or deletes, the draft **is** the proposal. No one sees it before it exists, so the filters stop being precautions and become the only barrier. They run in code before creation; an instruction in the prompt is not a filter.
```python
dp = {"action": {"verb": "create_draft", "target": "thread-7"},
"business_key": {"thread": "thread-7"}, "unknowns": ["hearing date"]}
propose(store, "thread-7:reply", dp, regime="draft_only") # a send verb is refused here
guarded_apply(store, "thread-7:reply", dp, dp["action"], create=create_draft,
draft={"target": "thread-7", "body": body}, forbidden=[r"(?m)^--\s*$"])
```
| Check | Blocks when |
|---|---|
| Verb | Anything but `create_draft` / `update_draft` |
| Target | Draft target ≠ plan target |
| Markers | A field listed in `unknowns` lacks `[TO COMPLETE: <field>]` verbatim in the visible text: removed, reworded to "(to be confirmed)", lower-cased, or hidden in an HTML comment |
| Templates | An unresolved `{{placeholder}}` |
| Caller rules | A `forbidden` regex matches (e.g. a pre-applied signature block) |
| Body | Empty after stripping comments |
A blocked draft goes to `waiting_human` + `draft_filter` with the reasons, and nothing is created. A human approval does not bypass the filter: fix the draft or the plan. Markers are never softened for style; an unknown shown as prose gets sent.
**Half of the draft tests must prove the filter does not over-block.** A filter that refuses legitimate drafts is switched off within a week, and then there is no barrier. The selftest passes drafts containing "send", "sent", "signature", single braces and JSON, markers inside HTML tags or next to an unrelated HTML comment, accents and non-Latin text, `-- see below --`, extra markers, 20k characters, and the `update_draft` verb.
## Reference module
`scripts/hitl.py` (stdlib, Python 3.9+, POSIX): `fingerprint`, `propose`, `open_request`, `sign_decision`, `decide`, `sweep_expired`, `draft_gate`, `begin_apply`, `record_result`, `reconcile`, `guarded_apply`, `acquire_lock`, `release_lock`, `Store`. Every guard raises `Refused` on absent, empty, null, or wrongly typed input; illegal state transitions raise too.
```bash
python3 scripts/hitl.py --selftest # 118 fixtures (70 must-refuse), exit 1 on any failure
python3 scripts/hitl.py status state.json # read-only: counts, waiting_human gates, uncertain items
# Output: HITL STATUS applied=12 uncertain=1 waiting_human=2
```
Fifteen guards were mutated once each (request expiry, exact-action check, id-as-proof, failed-lookup-as-absent, stale-lock takeover, marker check, HTML-comment stripping, clock tolerance, approver allowlist, incomplete-candidate rule, stale approval, retry bound, reopen of an in-flight item, and two over-blocking filters); the selftest failed every time.
## Output Format
Approval request (one per item):
```
APPROVAL <item_id> — gates: new_record_review — expires <UTC time>
Action : create_record on folder/REF-1 (fields: amount=120)
Plan : fp 3f9a1c07… Duplicate check: 0 match on client_ref+party
[Approve] [Reject] (buttons carry the nonce; typed replies are ignored)
```
Run summary (every run, even when nothing happened):
```
HITL_RUN_SUMMARY <job_id> <UTC time>
applied=3 uncertain=1 waiting_human=2 skipped=0 technical_failures=1
ALERT uncertain: REF-9:open (timeout) -> reconcile next run
waiting_human: REF-4:open [possible_duplicate] thread-7:reply [draft_filter: marker_missing:hearing date]
next_action: human decision on 2 items
```
## Troubleshooting
| Issue | Cause | Fix |
|---|---|---|
| `previous attempt unresolved: reconcile first` | Item left `applying`/`uncertain` by a crash or timeout | Run your lookup, pass it to `reconcile` |
| Approved item returns `approval_stale` | Apply ran after `approval_exp` | Open a new request; do not extend the old one |
| Valid-looking token refused as "older request" | A later `open_request` superseded it | Use the latest request's buttons |
| Every draft goes to `draft_filter` | Model drops or rewrites markers | Tell the drafting step to copy markers verbatim; never relax the check |
| `SKIP_LOCKED` every tick | Lock TTL longer than the cron interval, or a hung runner | TTL ≈ worst-case run time; alert after N skips |
| `stale lock and the application may still be running` | Expired lock, no proof the app stopped | Check the host by hand, then pass `app_running=False` |
| `state corrupt` | Truncated write or manual edit | Stop and inspect; never auto-reset the state |
## Scope
This skill ONLY: binds a human OK to one exact, fingerprinted action for a limited time; persists intent before any write; treats a missing id as `uncertain`; reconciles by business key before any retry; serialises runners per application; blocks drafts in code before creation.
This skill NEVER: infers approval from free text; widens an OK to adjacent actions; re-runs a creation after a crash or timeout without reconciliation; overwrites a lock whose holder may still run; softens a `[TO COMPLETE]` marker; sends what it drafted; stores plan content, drafts, or nonces in its state.
*Alexandre Bloch · ClawHub @alexbloch-ia*
don't have the plugin yet? install it then click "run inline in claude" again.
Gate any agent write on explicit human approval before it hits the remote system. one item = one exact action = one approval, valid for a limited time and redeemed once. if the job crashes mid-write, reconcile by business key instead of retrying. for drafts-only flows (agent prepares, human sends), apply content filters in code before creation. use this skill before any create, update, or send call that touches a live system. the approval is a perishable object: it covers one fingerprinted action, survives a crash via persistent intent, and resolves doubt by looking before creating, never by retry loops.
approval secret: a ≥32-byte random string distinct from provider credentials. pass via env var APPROVAL_SECRET or a file at 0600 permissions. never log it.
state file: a json file (created 0600, no symlinks) holding item metadata: id, status, plan fingerprint, gate names, nonce digest, remote id, attempt count, timestamps. paths you choose. sidecar .lock file created automatically.
run-lock file per application: one lock file per external system to serialize runners. path you choose. created 0600, no symlinks.
store object: Store(state_file_path) from scripts/hitl.py. handles locking, fsync, and state transitions internally.
plan dict: required keys are action (verb, target, fields), business_key (fields a human uses to spot duplicates: ref, parties, date, amount), and unknowns (list of incomplete field names). never store the draft or nonce itself in state; keep both in your process memory.
python 3.9+: stdlib only, posix. scripts/hitl.py provides fingerprint, propose, open_request, sign_decision, decide, begin_apply, record_result, reconcile, guarded_apply, acquire_lock, release_lock, draft_gate, sweep_expired, and Store.
remote lookup callable: your function that searches the remote system by business key fields. must raise on error (a failed search is not "absent"). must return None, or a list of dicts with an id field and all business-key fields. fuzzy or prefix-based remote searches must be re-checked in code.
optional: app-running probe: a callable or env var that returns truthy/falsy to prove the external application is still alive. used to decide if an expired lock can be taken over.
1. propose the item (once per action)
from scripts.hitl import fingerprint, propose, Store
store = Store("/var/lib/agent/state.json")
plan = {
"action": {"verb": "create_record", "target": "folder/REF-1", "fields": {"amount": 120}},
"business_key": {"client_ref": "REF-1", "party": "Party A"},
"unknowns": []
}
propose(store, "REF-1:open", plan, regime="approval")
# output: item created in state with status 'proposed'
input: store object, item_id (a unique slug), plan dict, regime ("approval" or "draft_only"). output: item persisted with status proposed and plan fingerprint recorded.
2. open a request and show the human (approval regime only)
from scripts.hitl import open_request, fingerprint
nonce = open_request(store, "REF-1:open", plan, ["new_record_review"], ttl_s=3600)
# show the human: plan summary, fingerprint prefix (3f9a1c07…), buttons carrying the nonce
# output: nonce (string), item now has status 'waiting_human'
input: store, item_id, plan, list of gate names (e.g. ["new_record_review", "possible_duplicate"]), ttl_s (request lifetime in seconds, default 3600). output: nonce string, stored as sha256 digest only. state changes to waiting_human. the request has its own expiry separate from any token expiry. a new request on the same item_id supersedes the old one.
3. sign the decision (approval bot side, never the human)
from scripts.hitl import sign_decision
secret = os.environ["APPROVAL_SECRET"] # or read from 0600 file
tok = sign_decision(secret, "REF-1:open", nonce, fingerprint(plan), "owner", "approve")
# tok is a jwt signed with the secret
# output: token string
input: secret (bytes or string), item_id, nonce (from step 2), plan fingerprint, approver identifier (e.g. "owner", "alice@example.com"), decision ("approve" or "reject"). output: signed token. token includes iat (issued-at) and exp (expiry) timestamps. never give the human the secret; they click a button carrying the nonce, you sign the token server-side.
4. record the decision (once per approval or rejection)
from scripts.hitl import decide
result = decide(store, "REF-1:open", tok, secret, plan, {"owner"})
# output: 'approved' | 'rejected' | 'expired' | 'waiting_human'
input: store, item_id, signed token, secret, plan (re-checked against token fingerprint), set of allowed approvers. output: status string. if approved, item moves to state approved and nonce is cleared in one locked step (replay-proof). if rejected, item moves to rejected (a signed no). if request expired or token is old, item moves to expired or stays waiting_human with gate approval_stale. clock tolerance: 60s on iat (issued-at), zero on exp.
5. apply the action (only after approved or in draft_only regime)
from scripts.hitl import guarded_apply
def call_api(action):
# YOUR code: verb="create_record", target="folder/REF-1", fields={"amount": 120}
# must return a response with an id field, or raise
response = requests.post("https://api.example.com/records", json=action["fields"])
return {"id": response.json()["record_id"]}
result = guarded_apply(store, "REF-1:open", plan, plan["action"], create=call_api)
# output: {'status': 'applied'} | {'status': 'uncertain'} | {'status': 'waiting_human', 'gates': [...]}
input: store, item_id, plan, action dict (must match plan["action"] exactly as canonical json), create callable. optional: draft dict (for draft_only), forbidden regex list (content filters). output: dict with status and optional gates list. order: validate → check regime and filters → record intent with fsync → call create → record result. if process dies after remote create but before state write, item stays applying and you must reconcile next run (never retry).
6. reconcile after crash or timeout (do not re-create)
from scripts.hitl import reconcile
matches = search_remote(client_ref="REF-1", party="Party A") # YOUR lookup
# matches must be None, or a list of dicts with 'id' field and all business_key fields
reconcile(store, "REF-1:open", plan, matches)
# output: 'applied' | 'waiting_human' | 'approved' (one retry allowed)
input: store, item_id, plan, matches (result from your remote search). output: new status. logic: if exactly one match and all business-key fields match (trimmed, case-folded), mark applied and store its id. if two or more matches or any missing key field, mark waiting_human + gate possible_duplicate. if zero matches and attempts < 2, mark approved again (bounded retry). if zero matches after retry, mark waiting_human + gate retry_exhausted. a failed search (exception, non-list result) is refused; it does not count as "zero matches".
7. serialize runners per application (run at start of job)
from scripts.hitl import acquire_lock, release_lock
acquire_lock("/var/lib/agent/app.lock", job_id="open-records-am", ttl_s=2700, app_running=probe)
# if lock already held and not expired: raises SkipLocked("SKIP_LOCKED")
# output: lock acquired or exception
try:
# your job
pass
finally:
release_lock("/var/lib/agent/app.lock")
input: lock file path, job_id (string), ttl_s (lock lifetime, should be > worst-case run time), app_running (callable or string from env). output: acquired or exception. if lock file is live (not expired), raises SkipLocked. if lock is expired and app_running proves false, lock is taken over. if lock is expired and app_running is true or unknown, refuses with alert (do not take over a lock held by a possibly-live process). if lock is corrupt or a symlink, refuses.
8. filter drafts before creation (draft_only regime only)
from scripts.hitl import draft_gate
body = "To: alice@example.com\nSubject: hello\n\nPlease [TO COMPLETE: hearing date]. Regards."
result = draft_gate(plan, body, forbidden=[r"(?m)^--\s*$"], target="thread-7")
# output: (True, []) | (False, ["marker_missing:hearing date", "forbidden_match:signature"])
input: plan, draft body text, optional forbidden regex list, target (must match plan target). output: tuple (bool, list of reasons). checks: (a) verb is create_draft or update_draft, (b) target matches plan["target"], (c) every field in plan["unknowns"] has [TO COMPLETE: <field>] verbatim in visible text (not reworded, lowercased, or hidden in html comment), (d) no unresolved {{placeholder}} templates, (e) no match against forbidden regexes, (f) body not empty after stripping comments. if any check fails, returns (False, reasons). a blocked draft does not create anything and moves item to waiting_human + gate draft_filter.
9. read status and report (optional, any time)
from scripts.hitl import sweep_expired
sweep_expired(store) # mark timed-out requests as expired
# output: none, state updated
result = store.status()
# output: {'applied': 12, 'uncertain': 1, 'waiting_human': 2, 'gates': {...}}
input: store. output: dict with counts and per-gate breakdown. run sweep_expired before reading status to age out old requests. optionally write a run summary (see output contract).
if regime="approval" (default): item starts proposed, moves to waiting_human on open_request, moves to approved on signed decision, moves to applying on begin_apply, ends at applied or uncertain. a new request supersedes the old one; redeeming clears the nonce in one locked step. approval_exp = min(token exp, request exp). a token with iat further ahead than 60s is rejected (clock drift guard). an unsigned reply, a reply to an old request, or a reply after expiry is refused.
if regime="draft_only": item starts proposed, can skip waiting_human and move straight to applying after filters pass. drafts never need approval; they need only content gates. a draft that fails any check moves to waiting_human + draft_filter and nothing is created. a human approval (via step 4) does not bypass filters.
if status is applying or uncertain: begin_apply and record_result are skipped. reconcile must be called (search remote by business key). do not call create again.
if approval_exp is in the past: begin_apply returns waiting_human + gate approval_stale. open a new request instead of re-using the old one.
if lock is live and not expired: raise SkipLocked. do not run this tick.
if lock is expired and app_running is falsy: take over the lock. proceed.
if lock is expired and app_running is truthy or unknown: refuse with technical alert. do not take over; the application may still write.
if remote lookup raises or returns non-list: reconcile is refused; item stays uncertain. a failed search is not "zero matches".
if remote lookup returns exactly one match: compare all business-key fields (case-fold, trim). if all match, mark applied. if any missing or mismatched, move to waiting_human + possible_duplicate.
if remote lookup returns zero matches: if attempts < 2, mark approved again (one bounded retry). if attempts >= 2, mark waiting_human + retry_exhausted. no third attempt.
if remote lookup returns two or more matches: move to waiting_human + possible_duplicate. do not guess which one.
if create returns a response with a non-empty id: record as applied and store the id.
if create returns exit 0 with no id, empty string id, {"ok": true}, {}, None, or falsy id: record as uncertain. you do not know if the remote object exists.
if create times out, raises, or returns 5xx: record as uncertain, never failed. reconcile on the next run.
if draft body has an unresolved {{placeholder}}: block draft, move to waiting_human + draft_filter: unresolved_template. do not create.
if draft body lacks [TO COMPLETE: <field>] for a field in plan["unknowns"]: block draft, move to waiting_human + draft_filter: marker_missing:<field>. do not create. markers must be exact and visible (not inside html comments, not reworded).
if draft body matches a forbidden regex: block draft, move to waiting_human + draft_filter: forbidden_match. do not create.
if a new request arrives for an item that is applying: reject the new request; do not clear the old nonce. reconciliation must run first.
if a new approval arrives for an item that is applying: reject it. approval cannot restart an in-flight write; it would become a workaround for reconciliation.
item state file: json at the path you chose. one object per item_id, keyed by id. fields: status (string: proposed / waiting_human / approved / applying / uncertain / applied / rejected / expired), plan_fp (sha256 hex of canonical json plan), nonce_digest (sha256 of nonce, only while waiting_human), gates (list of gate names, only if waiting_human), remote_id (the id from create response), attempts (count of reconciliation lookups), ts_proposed (unix timestamp), ts_created (when status changed to applying), ts_resolved (when status changed to applied/rejected/expired), approval_exp (unix timestamp, only if approved or applying). never store the plan, draft, or nonce itself.
lock file: one per application. format: {"holder": "<job_id>", "ts_acquired": <unix timestamp>, "ttl_s": <int>}. created 0600, no symlinks. holder is live if ts_acquired + ttl_s > now. if live, locked. if expired and app_running is falsy, can be overwritten.
run summary (optional, written to log or file):
HITL_RUN_SUMMARY <job_id> <UTC time>
applied=3 uncertain=1 waiting_human=2 skipped=0 technical_failures=1
ALERT uncertain: REF-9:open (timeout) -> reconcile next run
waiting_human: REF-4:open [possible_duplicate] thread-7:reply [draft_filter: marker_missing:hearing date]
next_action: human decision on 2 items
rows: counts (applied, uncertain, waiting_human, skipped, technical_failures), alerts (uncertain items needing reconciliation), gates breakdown (which items are blocked and why), next action summary.
approval request (shown to human, one per item in waiting_human):
APPROVAL <item_id> , gates: new_record_review , expires <UTC time>
Action : create_record on folder/REF-1 (fields: amount=120)
Plan : fp 3f9a1c07… Duplicate check: 0 match on client_ref+party
[Approve] [Reject] (buttons carry the nonce; typed replies are ignored)
include: item_id, gates list, request expiry time, action summary (verb, target, key fields), plan fingerprint prefix (first 8 hex chars), result of your duplicate-check lookup (count of matches), buttons carrying the nonce, rejection of free-text replies.
selftest output:
python3 scripts/hitl.py --selftest
# 118 fixtures (70 must-refuse), all pass -> exit 0
# any failure -> exit 1 and details
status output:
python3 scripts/hitl.py status /var/lib/agent/state.json
# HITL STATUS applied=12 uncertain=1 waiting_human=2
approval approved: human clicks the approve button, token is verified and decision is recorded. item status changes from waiting_human to approved. nonce is cleared. next step can call begin_apply.
action applied: create callable returns a non-empty id. item status changes to applied and id is stored. if the job crashes after this point, the id is in state; next run sees applied and skips create.
action uncertain: create times out, raises, or returns without an id. item status changes to uncertain. the state file still records intent and attempt count. next run must reconcile before retrying.
draft blocked: body fails a