Business operating system for Claude Code — 57 skills, 21 agents, smart daemon. Unified inbox (WhatsApp/Email/Slack/Telegram), autonomous PR merge, full-AWS monitoring, revenue (Stripe+RevenueCat), e-commerce (Shopify), marketing (Klaviyo/Meta/GA4), voice (Bland/ElevenLabs), APM (Datadog/NewRelic/OTEL), YOLO mode.
Shell agent-teamsai-agentai-automationanthropicautonomous-agentawsbusiness-operationsclaudeclaude-codeclaude-code-plugindevopsecommerceinbox-zeroklaviyomarketingmcpmorning-briefingpr-automationshopifyterminal
fix(outbound-guard): ship the reservation-v2 guard, ok and hook the Node twin already expects (#965)
Aurora Capital282c15719fc4
diff --git a/claude-ops/scripts/outbound-guard/README.md b/claude-ops/scripts/outbound-guard/README.mdindex 5b33ab8f..fc161e4f 100644--- a/claude-ops/scripts/outbound-guard/README.md+++ b/claude-ops/scripts/outbound-guard/README.md@@ -32,29 +32,53 @@ The guard it delegates to is the installed one at`~/.claude/scripts/hooks/outbound_guard.py` (override with `OUTBOUND_GUARD_PY`); when itcannot be reached, the Node side fails closed.-The copy of `outbound_guard.py` in this directory is still the older count-based version-and is not yet a valid delegate — bringing it forward also means migrating the `ok`-script off the retired `mint <n> <ttl>` call. The historical count schema is described-below for that reason.+The copy of `outbound_guard.py` in this directory **is** that guard, and `ok` here is its+companion. Both were shipped forward together, because half a migration is not one: a+reservation-schema Node twin delegating to a count-schema Python guard fails closed on+every send, and a bash `ok` calling the retired `mint <n> <ttl>` arms nothing a+reservation guard will honour.-Historically both sides kept their own copy of one file:+## What an approval is++An approval is a **signature on one exact message**, never a bearer credit.```/tmp/.claude-outbound-guard.json-{"remaining": 3, "minted": 1786732800, "ttl": 900, "spent": {"<fingerprint>": 1786732801}}+{"minted": 1786732800, "ttl": 900,+ "approved": {"<fp>": {"ts": ..., "recipient": "...", "preview": "..."}},+ "inflight": {"<fp>|<tool>": 1786732801},+ "reservations": {"<fp>": {"at": ..., "recipient": "...", "tool": "...",+ "session_id": "...", "meta": {...}}}}```-A message is identified by recipient plus content:-`sha256(recipient|whitespace-normalised body, first 400 chars)`, first 32 hex chars.-Both languages compute it identically, which is what the test suite checks first.--When a guard sees a fingerprint it has already recorded within `SPENT_WINDOW_SEC`-(120s), that is the same message arriving at a second layer. It passes and nothing is-deducted. So one message costs exactly one unit no matter how many guards it crosses,-and the approval count means what it says.+A message is identified by recipient plus content: `sha256(recipient|body)`, first 32 hex+chars, with the body normalised only by stripping trailing whitespace per line and the+trailing newline. Node and Python compute it identically, which is what the test suite+checks first.++The old schema hashed a whitespace-collapsed body truncated at 400 characters, so two+materially different messages sharing a prefix collided and an approval for one satisfied+the other. It also minted a bare count, which any session could spend on any recipient.+Neither is true any more:++- **`ok` mints a set of fingerprints**, read from the drafts this session already showed+ and queued under `~/.claude/state/outbound-pending/<session>.json`. It verifies every+ record against its own stored fingerprint before minting any of them.+- **`consume()` allows only a send whose fingerprint is in that set.** A different+ recipient or one changed byte finds nothing.+- **A delivered fingerprint is refused forever** by an append-only ledger at+ `~/.claude/state/outbound-sent.jsonl`, written the moment approval is granted. An+ ambiguous delivery leaves a paper trail that blocks a silent duplicate.+- **`inflight`** (120s, keyed on fingerprint *plus tool*) is the only free pass, and it+ covers exactly one case: one message crossing both guards in the same PreToolUse cycle.++`reservations` is phase one of a two-phase commit: the approval is held, not spent, while+the send is attempted, and `commit()` / `release()` settle it. A reservation that outlives+its TTL (`OUTBOUND_RESERVATION_TTL`, 180s) expires rather than stranding the approval. So+a send that never happened does not silently burn the owner's yes.If the shared file is absent, both sides fall back to the old single-use token so a-partially migrated environment keeps working rather than failing open or shut.+partially migrated environment keeps working rather than failing open.## Keeping the installed twin in sync@@ -86,13 +110,18 @@ id a rank in `schema_rank()`.## Arming```-ok 1 message, 2 minute window-ok 3 3 messages, 15 minute window-ok all 10 messages, 15 minute window (also: ok these)+ok approve the pending draft+ok 2 approve the second draft in the queue+ok all approve every draft this session has queued```-`all` is capped, not unlimited. Every draft is still shown to the owner individually-before it goes; the counter only removes the need to retype the approval per message.+`ok` never invents an approval. It reads the queue of drafts this session already showed,+mints exactly those fingerprints, and refuses when the queue is empty, stale, malformed,+or when a record does not match its own fingerprint. So `ok all` is not "ten free sends":+it is a yes to the specific drafts on screen, and nothing else can spend it.++`ok` finds the guard module via `OUTBOUND_GUARD_PY`, else a sibling `outbound_guard.py`+next to it, else the installed hook at `~/.claude/scripts/hooks/outbound_guard.py`.## Two rules for anyone adding a send pathdiff --git a/claude-ops/scripts/outbound-guard/block-outbound-comms.py b/claude-ops/scripts/outbound-guard/block-outbound-comms.pyindex e430b203..18c05bd0 100755--- a/claude-ops/scripts/outbound-guard/block-outbound-comms.py+++ b/claude-ops/scripts/outbound-guard/block-outbound-comms.py@@ -16,6 +16,7 @@ import base64import jsonimport osimport re+import shleximport sysimport time@@ -137,6 +138,33 @@ def _load_approved_recipients() -> set:return out+def _load_approved_whatsapp() -> set:+ """Return the set of WhatsApp recipients Sam has pre-approved (lowercased).++ Read from the same outbound-approvals.json, under a SEPARATE key so an email+ address can never silently authorise a WhatsApp send or the reverse:+ {"approved_whatsapp": ["[email protected]", "157788609228927@lid"]}++ Entries may be full JIDs or bare numbers; both the raw value and its local+ part (before '@') are indexed so one entry covers a contact whichever JID+ form a given account happens to address them by. Missing/empty/malformed+ file → empty set → nothing is auto-approved (strict default, gate stays armed).+ """+ out = set()+ try:+ with open(OUTBOUND_APPROVALS_PATH) as f:+ cfg = json.load(f)+ for v in cfg.get("approved_whatsapp") or []:+ s = str(v).strip().lower()+ if not s:+ continue+ out.add(s)+ out.add(s.split('@', 1)[0])+ except (OSError, json.JSONDecodeError):+ pass+ return out++def _load_broken_aliases() -> set:"""Send-as aliases whose mail bounces with a 'Send mail as' misconfiguration.@@ -167,6 +195,7 @@ SELF_JIDS = _load_self_jids()SELF_IMESSAGE_HANDLES = _load_self_imessage_handles()SELF_TELEGRAM_OWNERS = _load_self_telegram_owners()APPROVED_RECIPIENTS = _load_approved_recipients()+APPROVED_WHATSAPP = _load_approved_whatsapp()def _telegram_recipient_is_self(cmd: str) -> bool:@@ -242,13 +271,24 @@ def _bash_recipient_is_self(cmd: str) -> bool:# --body, --reply-to-message-id) so that merely MENTIONING a send command inside# a Python heredoc, shell comment, grep query, or audit script doesn't trip.BASH_PATTERNS = [- (r'(?:^|[\s;&|`/])gog\s+gmail\s+send\b[^#\n]{0,400}?--(?:to|body|body-file|reply-to-message-id|subject|from|cc|bcc)\b', 'gog gmail send'),- (r'(?:^|[\s;&|`/])gog\s+send\b[^#\n]{0,400}?--(?:to|body|body-file|reply-to-message-id|subject|from|cc|bcc)\b', 'gog send (alias)'),+ # The gap between `send` and its first flag deliberately allows newlines.+ # Until 2026-09-09 it was [^#\n], so a send written over several lines --+ # the readable form, and the form every worked example in these files uses --+ # matched NO pattern at all. detect_outbound_bash then returned None, the+ # hook exited 0, and the mail left with no gate, no ledger row, and Sam's+ # approval left unspent, so his next `ok` re-armed an already-sent body.+ # Measured against a real multi-line `gog gmail send` that slipped through+ # ungated on 2026-09-09. Newlines are joined by _join_continuations() as well;+ # the class is widened too so a quoted multi-line argument cannot hide a+ # send either. Over-detection here costs a needless approval prompt;+ # under-detection costs an ungated send.+ (r'(?:^|[\s;&|`/])gog(?:\s+-{1,2}[\w-]+(?:[=\s]+[^\s;&|]+)?)*\s+(?:gmail|mail|email)(?:\s+(?:mail|email|messages?|msgs?))?\s+send\b[^#]{0,400}?--(?:to|body|body-file|reply-to-message-id|subject|from|cc|bcc)\b', 'gog gmail send'),+ (r'(?:^|[\s;&|`/])gog\s+send\b[^#]{0,400}?--(?:to|body|body-file|reply-to-message-id|subject|from|cc|bcc)\b', 'gog send (alias)'),# Both `drafts` and `draft` are valid gog subcommands, and sending a draft is# still sending. The old rule only caught the singular. A real draft id must# follow (e.g. r2782687644185019208), otherwise the rule also fires on a commit# message or documentation that merely names the command.- (r'(?:^|[\s;&|`/])gog\s+gmail\s+drafts?\s+send\s+[\w-]{3,}', 'gog gmail drafts send'),+ (r'(?:^|[\s;&|`/])gog(?:\s+-{1,2}[\w-]+(?:[=\s]+[^\s;&|]+)?)*\s+(?:gmail|mail|email)(?:\s+(?:mail|email|messages?|msgs?))?\s+drafts?\s+send\s+[\w-]{3,}', 'gog gmail drafts send'),# The WhatsApp bridge runs locally and had no rule at all. A curl to it sends a# real message to a real person, and went past the guard unseen. Multi-account# installs use one port per account, hence the 80xx range.@@ -379,8 +419,18 @@ def _strip_full_line_comments(cmd: str) -> str:return "\n".join(l for l in cmd.splitlines() if not l.lstrip().startswith("#"))+def _join_continuations(cmd: str) -> str:+ """Undo shell line continuations, exactly as the shell itself does.++ `gog ... send \\\n --to ...` is ONE command. Matching it line by line means+ matching something the shell never runs. Joining first makes the text the+ patterns see the text that will actually execute.+ """+ return re.sub(r'\\\n[ \t]*', ' ', cmd)++def detect_outbound_bash(cmd: str):- scan = _strip_full_line_comments(cmd)+ scan = _join_continuations(_strip_full_line_comments(cmd))for pat, label in BASH_PATTERNS:if re.search(pat, scan, re.IGNORECASE):return label@@ -478,6 +528,77 @@ def _native_route(addr: str) -> str:return ''+def _bash_gmail_message(cmd: str) -> tuple:+ """The (recipient, body) of a `gog gmail send` written as a shell command.++ Without this the fingerprint for a Bash send was computed over the whole+ shell line -- PATH exports, `cd`, the lot -- and could never equal the+ sha256(recipient|body) that outbound-humanize queued and `ok` minted. Every+ email routed through Bash was therefore unapprovable, and gog exposes no MCP+ send tool, so Bash is the only email route on this machine. The effect was a+ guard that could not be satisfied, which is not a stricter guard: it is the+ one people work around.++ Returns ('', '') when the message cannot be read literally -- an unbalanced+ quote, a body built by command substitution, a --body-file not on disk. The+ caller then keeps the old whole-command fingerprint, so an unreadable send+ stays unapprovable rather than quietly matching something.++ A --body-file is read from disk here and read again by the sending process a+ moment later. A third process could swap it in between. That window is+ inherent to checking a file rather than a value, and is the same window the+ approve-then-send cycle already has; it is not widened here.+ """+ if 'gmail' not in cmd or 'send' not in cmd:+ return ('', '')+ try:+ toks = shlex.split(cmd)+ except ValueError:+ return ('', '')++ def _val(names):+ for i, t in enumerate(toks):+ for n in names:+ if t == n and i + 1 < len(toks):+ return toks[i + 1]+ if t.startswith(n + '='):+ return t[len(n) + 1:]+ return None++ to = _val(['--to'])+ if not to:+ return ('', '')+ # De hele ontvangersgroep is de identiteit van het bericht. Tot 8 september+ # 2026 stond hier een refusal op een cc, een bcc of een komma, waardoor een+ # mail aan twee mensen niet goed te keuren was. Zie+ # outbound_guard.canonical_recipients: to, cc en bcc worden samen tot één+ # genormaliseerde sleutel, dus 'a,b' en to=a cc=b zijn hetzelfde bericht, en+ # een adres toevoegen of weglaten verandert de afdruk en wordt geweigerd.+ try:+ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))+ import outbound_guard as _og+ to = _og.canonical_recipients(to, _val(['--cc']) or '', _val(['--bcc']) or '')+ except Exception:+ return ('', '')+ if not to:+ return ('', '')++ body = _val(['--body'])+ if body is None:+ bf = _val(['--body-file'])+ if not bf or bf == '-':+ return ('', '')+ try:+ body = open(os.path.expanduser(bf)).read()+ except OSError:+ return ('', '')+ # Anything the shell would still expand means the text checked is not the+ # text sent. Refuse to fingerprint it.+ if re.search(r'\$\(|`|\$\{?[A-Za-z_]', body):+ return ('', '')+ return (to.strip(), body)++def _identify(tool_name: str, tool_input: dict, cmd: str = '') -> tuple[str, str]:"""Recipient and text of this message, whatever shape it arrives in.@@ -485,37 +606,55 @@ def _identify(tool_name: str, tool_input: dict, cmd: str = '') -> tuple[str, strfingerprint. A Bash command has no proxy side, so its fingerprint is simply uniqueper command."""if isinstance(tool_input, dict) and tool_input:- rcpt = ''- for k in ('recipient', 'jid', 'chat_jid', 'chat_id', 'to', 'channel_id'):- v = tool_input.get(k)- if isinstance(v, str) and v.strip():- rcpt = v.strip()- break- if isinstance(v, list) and v:- rcpt = str(v[0]).strip()- break- body = ''- for k in ('message', 'text', 'body', 'payload', 'content'):- v = tool_input.get(k)- if isinstance(v, str) and v.strip():- body = v- break+ # The key lists this used to hold inline now live in+ # outbound_guard.identify_args(), so the MCP proxy derives the SAME+ # (recipient, body) from the SAME arguments instead of keeping a second+ # list that agreed only by coincidence. Behaviour here is unchanged; if+ # the shared module cannot be imported we fall back to the original+ # inline logic rather than losing the fingerprint entirely.+ try:+ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))+ import outbound_guard as _og_ident+ rcpt, body = _og_ident.identify_args(tool_input)+ except Exception:+ rcpt = ''+ for k in ('recipient', 'jid', 'chat_jid', 'chat_id', 'to', 'channel_id'):+ v = tool_input.get(k)+ if isinstance(v, str) and v.strip():+ rcpt = v.strip()+ break+ if isinstance(v, list) and v:+ rcpt = str(v[0]).strip()+ break+ body = ''+ for k in ('message', 'text', 'body', 'payload', 'content'):+ v = tool_input.get(k)+ if isinstance(v, str) and v.strip():+ body = v+ breakif rcpt or body:return (rcpt, body)+ if tool_name == 'Bash' and cmd:+ r, b = _bash_gmail_message(cmd)+ if r and b:+ return (r, b)return ('', cmd or '')-def check_token(recipient: str = '', body: str = '') -> bool:+def check_token(recipient: str = '', body: str = '', tool: str = '', session_id: str = '') -> bool:"""Ask the shared store in outbound_guard for approval.- That store is the only place counting, for every CLI. It identifies a message by- recipient plus content, so the same message crossing several guards costs one unit.- If the import fails this hook falls back to the old single-use token: better the- older, stricter rule than accidentally allowing everything."""+ That store now binds approval to the exact (recipient, body) Sam approved, not+ to a bare count — see outbound_guard.py for why. `tool` and `session_id` are+ passed through so the guard can (a) give a short free pass to a second guard+ checking the SAME not-yet-dispatched call, and (b) never let one session's+ approval be spent by another session's message. If the import fails this hook+ falls back to the old single-use token: better the older, stricter rule than+ accidentally allowing everything."""try:sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))import outbound_guard- return outbound_guard.consume(recipient, body)+ return outbound_guard.consume(recipient, body, session_id=session_id, tool=tool)except Exception:passtry:@@ -531,6 +670,27 @@ def check_token(recipient: str = '', body: str = '') -> bool:return True+def _consent_audit(event: str, **kw):+ """Best-effort evidence line. Must never be able to break a tool call."""+ try:+ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))+ import consent_audit+ consent_audit.record(event, **kw)+ except Exception:+ pass+++def _consent_fp(recipient: str, body: str) -> str:+ """The same fingerprint the approval binds to, so the audit joins on it.+ Falls back to '' rather than inventing a different hash."""+ try:+ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))+ import outbound_guard+ return outbound_guard.fingerprint(recipient, body)+ except Exception:+ return ''++def audit(verdict: str, tool_name: str, reason: str, cmd_snippet: str = ''):try:with open(AUDIT_LOG, 'a') as f:@@ -568,6 +728,41 @@ def _email_all_recipients_approved(tool_name: str, tool_input: dict, cmd: str) -return all(t in APPROVED_RECIPIENTS for t in targets)+def _whatsapp_all_recipients_approved(tool_name: str, tool_input: dict, cmd: str) -> bool:+ """True iff this is a WhatsApp TEXT send whose every recipient is on the+ persistent approved-whatsapp allowlist.++ Deliberately narrow:+ * Scope is WhatsApp only, keyed off `approved_whatsapp` — the email+ allowlist grants nothing here, and this grants nothing to email.+ * Text messages only. send_file and send_audio_message are never+ auto-approved: attachments carry content the allowlist never reviewed.+ * Group JIDs (@g.us) are never auto-approved, even if listed. A group is+ an audience, not the contact Sam signed off on.+ * An empty recipient set returns False, so a parse miss can never+ blanket-allow a send.+ """+ if not APPROVED_WHATSAPP:+ return False+ targets = []+ if re.search(r'whatsapp[a-z0-9_-]*__send_message$', tool_name) and isinstance(tool_input, dict):+ v = tool_input.get('recipient')+ if isinstance(v, str) and v.strip():+ targets.append(v.strip().lower())+ elif tool_name == 'Bash' and cmd:+ if re.search(r'(?:127\.0\.0\.1|localhost):80\d\d/api/send\b', cmd):+ for m in re.finditer(r'"recipient"\s*:\s*"([^"]+)"', cmd):+ targets.append(m.group(1).strip().lower())+ if not targets:+ return False+ if any(t.endswith('@g.us') for t in targets):+ return False+ return all(+ (t in APPROVED_WHATSAPP) or (t.split('@', 1)[0] in APPROVED_WHATSAPP)+ for t in targets+ )++# Tool this invocation is inspecting. Recorded as soon as it is known so the# crash handler at the bottom can tell a plain shell call from a real send._CURRENT_TOOL = ''@@ -689,35 +884,72 @@ def main():audit('ALLOWED_APPROVED', tool_name, reason, cmd_snippet)sys.exit(0)+ # Same prior-approval principle for WhatsApp, kept on its own allowlist and+ # its own audit tag so an approved WhatsApp send is never mistaken for an+ # approved email one. Text to a listed 1:1 contact only; files, audio and+ # groups still fall through to the gate.+ if _whatsapp_all_recipients_approved(tool_name, tool_input if isinstance(tool_input, dict) else {}, cmd):+ audit('ALLOWED_APPROVED_WA', tool_name, reason, cmd_snippet)+ sys.exit(0)+# Pass recipient and text so the shared store can recognise this message when# another guard sees it too. Without them the same message would cost a unit at- # every layer.+ # every layer. Also pass tool name and session id: the guard uses them to bind+ # approval to the exact message from the exact session that was shown to Sam,+ # not a bare count any session can spend (fixed 2026-09-02)._rcpt, _body = _identify(tool_name, tool_input if isinstance(tool_input, dict) else {}, cmd)- if check_token(_rcpt, _body):+ _session_id = str(data.get('session_id') or data.get('sessionId') or '')+ if check_token(_rcpt, _body, tool=str(tool_name), session_id=_session_id):audit('ALLOWED', tool_name, reason, cmd_snippet)sys.exit(0)audit('BLOCKED', tool_name, reason, cmd_snippet)+ # Evidence line for the refusal too, same shape and same file as the+ # AUTHORIZED one, so `grep <fp>` on the consent audit tells the whole story+ # of a message including the attempts that did NOT go out.+ _consent_audit(+ 'BLOCKED',+ recipient=_rcpt,+ body=_body,+ fp=_consent_fp(_rcpt, _body),+ session_id=_session_id,+ tool=str(tool_name),+ send_result='blocked',+ reason=reason,+ )+ # NAME COLLISION FIXED 2026-09-08. This used to instruct `! ok`, which is a+ # shell escape that runs `touch /tmp/.claude-send-ok`. But ~/.local/bin/ok+ # is a DIFFERENT program -- the one that mints a body-bound approval from+ # the pending queue. Sam typed the wrong one four times in one day, and the+ # advice was pointing at the weaker mechanism anyway.+ #+ # The primary path is now the word. Saying `ok` in the conversation mints+ # approval bound to fingerprint(recipient, body) for the drafts this session+ # already showed him -- which is the evidence his policy actually asks for.+ # The bare token stays documented last, as the fallback it is, for sends+ # that cannot go through a humanizer pass.msg = (f'BLOCKED: outbound-comms guardrail tripped ({reason}).\n\n'- f"Sam's policy: ONE send per explicit approval. Claude (and claude-ops daemon,\n"- f'subagents, any session) may NEVER send email / Slack / WhatsApp / SMS /\n'- f'voice calls / team pings without Sam reviewing the FINAL proposed message\n'- f'FOR THIS SPECIFIC SEND and authorizing THIS specific send.\n\n'- f'Required workflow — repeat for EACH message, no batching:\n'- f' 1. Show the FINAL draft for ONE message (to, cc, bcc, subject, full body)\n'- f' 2. Wait for Sam to explicitly say send / approve for this exact draft\n'- f' 3. Ask Sam to authorize OUTSIDE Claude — via the `!` prompt prefix:\n'- f' ! ok (shorthand for: touch /tmp/.claude-send-ok)\n'- f' 4. Retry this tool call within 120 seconds — the token is single-use.\n'- f' 5. For the NEXT message, repeat steps 1-4 with its own approval + token.\n\n'- f'Batch sending is forbidden: one token = one send. `--dangerously-skip-permissions`\n'- f'does NOT bypass this guardrail. Audit log: /tmp/claude-outbound-audit.log\n\n'- f'Persistent prior-approval (email only): to let an already-approved\n'- f'recipient send without a token every time, Sam adds the address to\n'- f'"approved_recipients" in ~/.claude/state/outbound-approvals.json. Any\n'- f'email to a NON-approved address still requires the per-send token above.'+ f"Sam's policy: ONE send per explicit approval, and the approval must be\n"+ f'bound to the exact text. No session may send email / Slack / WhatsApp /\n'+ f'SMS / voice without Sam seeing the FINAL body for THIS send and\n'+ f'approving THAT send to THAT recipient.\n\n'+ f'Normal path — no token needed:\n'+ f' 1. printf \'%s\' "$DRAFT" | outbound-humanize --to \'RECIPIENT\'\n'+ f' (rewrites, reads the thread, queues the exact body, stamps it)\n'+ f' 2. Show Sam that exact stdout, in full.\n'+ f' 3. Sam replies with one word in the conversation: ok / ja / stuur /\n'+ f' send / go. That mints approval bound to (recipient, body).\n'+ f' His Telegram DM works too.\n'+ f' 4. Retry this same tool call. One approval = one successful send.\n\n'+ f'Do NOT ask him for `! ok`: that is the bare token, it binds to no text,\n'+ f'and `ok` in the shell is a different program from the `!` escape.\n\n'+ f'Fallback for sends with no humanizer pass (rare): Sam runs\n'+ f'`touch /tmp/.claude-send-ok` himself, valid 120s, single use. That is\n'+ f'weaker evidence and is logged as approval_route=legacy-token.\n\n'+ f'Consent audit: ~/.claude/state/outbound-consent-audit.jsonl\n'+ f'Gate audit: /tmp/claude-outbound-audit.log')print(msg, file=sys.stderr)sys.exit(2)diff --git a/claude-ops/scripts/outbound-guard/ok b/claude-ops/scripts/outbound-guard/okindex 6b21c714..01580712 100755--- a/claude-ops/scripts/outbound-guard/ok+++ b/claude-ops/scripts/outbound-guard/ok@@ -1,60 +1,375 @@-#!/usr/bin/env bash-# Approve outbound messages. The owner types `! ok` inside the CLI, which runs this in-# their own shell, outside the agent's reach.-#-# ok 1 message, 2 minute window-# ok 3 3 messages, 15 minute window-# ok all 10 messages, 15 minute window (also: ok these)-#-# There is one approval store: /tmp/.claude-outbound-guard.json, managed by-# outbound_guard.py and read by every CLI that goes through the MCP proxy. Each guard-# used to keep its own file, so this script had to write two and the counts drifted.-#-# One message costs exactly one unit even when it crosses several guards: it is-# identified by recipient plus content, and a guard that sees a fingerprint another-# guard already charged lets it through for free.-#-# A counter never replaces per-draft approval. The agent still shows every draft and-# waits for a yes. This only saves retyping the approval for each message.-set -euo pipefail--# The counter lives next to this script so it works wherever the plugin is installed.-# OUTBOUND_GUARD_PY overrides that for installs that split the files up.-GUARD="${OUTBOUND_GUARD_PY:-$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)/outbound_guard.py}"-LEGACY_SINGLE=/tmp/.claude-send-ok-LEGACY_BATCH=/tmp/.claude-send-ok-all-AUDIT="${OUTBOUND_OK_AUDIT:-$HOME/.claude/state/ok-token-audit.log}"-MAXN=10--arg="${1:-1}"-case "$arg" in- all|these) n=$MAXN ;;- ''|*[!0-9]*) echo "usage: ok [N|all]" >&2; exit 2 ;;- *) n="$arg" ;;-esac-[ "$n" -lt 1 ] && n=1-if [ "$n" -gt "$MAXN" ]; then- echo "capped at $MAXN per approval, reduced from $n." >&2- n=$MAXN-fi--if [ "$n" -eq 1 ]; then ttl=120; window="2 min"; else ttl=900; window="15 min"; fi--python3 "$GUARD" mint "$n" "$ttl" >/dev/null--# Fallback for guards that have not been migrated yet. The canonical state wins; these-# exist only so an older code path does not suddenly block everything.-: >"$LEGACY_SINGLE"-printf '%s' "$n" >"$LEGACY_BATCH"-chmod 600 "$LEGACY_SINGLE" "$LEGACY_BATCH"--mkdir -p "$(dirname "$AUDIT")"-printf '%s armed=%s window=%s ppid=%s tty=%s\n' \- "$(date -u '+%Y-%m-%dT%H:%M:%SZ')" "$n" "$window" "$PPID" "$(tty 2>/dev/null || echo none)" >>"$AUDIT"--if [ "$n" -eq 1 ]; then- echo "outbound approval armed for ONE send. Window: $window."-else- echo "outbound approval armed for $n sends. Window: $window."- echo "Every draft is still shown to you individually before it goes."-fi+#!/usr/bin/env python3+"""Keur de wachtende concepten van DEZE sessie goed. Sam typt `! ok` in Claude+Code; dit draait in zijn eigen shell, buiten het model om.++SECURITY FIX 2026-09-02 (companion to outbound_guard.py's rewrite).++The old `ok` minted a bare count: `mint <n> <ttl>`, "N sends, whatever recipient,+whatever body." outbound_guard.py's consume() now refuses that call outright+(see its own header) because a count is not a signature on a specific message.+`ok` has no access to the draft text itself, so it cannot compute a fingerprint+on its own -- the fingerprint has to come from somewhere that already saw and+committed to the exact text Sam is looking at.++The design: outbound-humanize is the one mandatory step before every send (see+~/.claude/rules/outbound-humanizer-gate.md). Its stdout is the exact body shown+to Sam, and it appends a PENDING record before printing that stdout:++ ~/.claude/state/outbound-pending/<session_id>.json+ [{"recipient": "...", "channel": "...", "body": "...", "fp": "...",+ "ts": 1786732800, "session_id": "..."}, ...]++`ok` reads that queue and mints approval for EXACTLY those fingerprints,+nothing else. The security property this preserves: the assistant can only get+approval for a body it has already committed to in writing before Sam ever+runs this command. It cannot show Sam text Y and then send text X --+outbound_guard.consume() hashes the actual send and refuses anything that does+not match, one character of difference included.++PER SESSION, since 2026-09-02. The file used to be one shared slot for the+whole machine, so two sessions drafting at once overwrote each other and `! ok`+armed whichever landed last -- not the one Sam was reading. That happened: a+WhatsApp bubble was on screen and an unrelated email got armed. Nothing wrong+could have been *sent* (the fingerprint stops that), but showing Sam one draft+and arming another is its own defect. Splitting by session removes it.++BATCH APPROVAL IS BACK, and safe this time. The old `ok N` minted a bare count+-- "N sends, whatever recipient, whatever body" -- which is a bearer credit,+not a signature. What `ok` mints now is a SET of fingerprints, each bound to+one exact (recipient, body) that Sam saw printed above the prompt. So "doe maar+alle vijf" costs one keystroke and still cannot approve a sixth message, a+different recipient, or one edited character.++ ok every draft this session queued, each one listed first+ ok all the same+ ok #2 only draft 2; the rest stay queued+ ok 2 REFUSED -- ambiguous between "two sends" and "draft two"++Refuses, loudly, with a reason, when the queue is:+ - missing -> run outbound-humanize first+ - older than PENDING_TTL_SEC -> ask for a fresh outbound-humanize pass+ - malformed / missing a field -> named explicitly, never silently ignored+ - internally inconsistent -> an fp does not match its own body++Never touches /tmp/.claude-send-ok. That file is Sam's own manual escape+hatch (`! touch /tmp/.claude-send-ok`, typed by him, not by this script) and+stays exactly as it was.+"""+from __future__ import annotations++import importlib.machinery+import importlib.util+import json+import os+import sys+import time+from pathlib import Path++HOME = Path.home()++# Overridable via env for the regression test suite only; production defaults+# below are what actually runs on this machine.+def _session_id() -> str:+ return (os.environ.get("CLAUDE_CODE_SESSION_ID")+ or os.environ.get("CLAUDE_SESSION_ID") or "no-session")+++# Per session, matching outbound-humanize. See its comment for why: one shared+# slot meant `! ok` could arm a draft from a different session than the one Sam+# was reading.+PENDING_DIR = Path(+ os.environ.get("OUTBOUND_PENDING_DIR")+ or (HOME / ".claude" / "state" / "outbound-pending")+)+PENDING_PATH = Path(+ os.environ.get("OUTBOUND_PENDING_PATH")+ or (PENDING_DIR / f"{_session_id()}.json")+)+LEGACY_PENDING = HOME / ".claude" / "state" / "outbound-pending.json"+# Matched to the humanizer stamp's own 30-minute life, not chosen loosely. A+# pending record that outlives its stamp is worthless anyway: the send is+# blocked for want of a stamp long before this window matters. The old 600s+# was strictly tighter than the gate behind it, which only meant Sam had to+# ask for the same draft twice when he stepped away for a coffee.+PENDING_TTL_SEC = int(os.environ.get("OUTBOUND_PENDING_TTL_SEC") or 1800)+# Widened from 120s to 900s on 2026-09-05. What makes an approval safe is that+# it is bound to one exact (recipient, body) fingerprint and is spent once and+# ledgered forever -- not that it expires quickly. A 120s window was sized for a+# human typing `ok` and hitting send in the same breath; an agent's next turn+# routinely takes longer than that, so the window expired between the approval+# and the send it was given for, and the answer to a legitimate approval was no.+# A gate that says no to the approved case is not a stricter gate.+MINT_TTL_SEC = int(os.environ.get("OUTBOUND_MINT_TTL_SEC") or 900)+# With a batch, each extra message adds a minute, up to this ceiling. An+# approval that outlives the conversation it was given in is a stale approval.+MINT_TTL_MAX_SEC = int(os.environ.get("OUTBOUND_MINT_TTL_MAX_SEC") or 1800)+def _resolve_guard_py() -> Path:+ """Where the guard module lives, most specific first.++ An explicit OUTBOUND_GUARD_PY always wins. Otherwise prefer a copy sitting+ next to this script: that is how the plugin ships the pair, and it keeps a+ checkout self-consistent instead of silently deciding against an installed+ copy on a different schema. Only when there is no sibling do we fall back to+ the installed hook path, which is where a bare `ok` on ~/.local/bin finds it.+ """+ explicit = os.environ.get("OUTBOUND_GUARD_PY")+ if explicit:+ return Path(explicit)+ sibling = Path(__file__).resolve().parent / "outbound_guard.py"+ if sibling.exists():+ return sibling+ return HOME / ".claude" / "scripts" / "hooks" / "outbound_guard.py"+++GUARD_PY = _resolve_guard_py()+AUDIT = Path(+ os.environ.get("OUTBOUND_OK_AUDIT")+ or (HOME / ".claude" / "state" / "ok-token-audit.log")+)+++def _audit(line: str) -> None:+ try:+ AUDIT.parent.mkdir(parents=True, exist_ok=True)+ with open(AUDIT, "a") as f:+ f.write(time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()) + " " + line + "\n")+ except OSError:+ pass+++def _die(msg: str, code: int = 2) -> None:+ print(msg, file=sys.stderr)+ _audit("REFUSED " + msg.replace("\n", " ")[:300])+ sys.exit(code)+++def _load_guard():+ if not GUARD_PY.exists():+ _die(f"ok: guard module not found at {GUARD_PY}; refusing rather than guessing.")+ loader = importlib.machinery.SourceFileLoader("outbound_guard_live", str(GUARD_PY))+ spec = importlib.util.spec_from_loader(loader.name, loader)+ mod = importlib.util.module_from_spec(spec)+ try:+ loader.exec_module(mod)+ except Exception as e: # noqa: BLE001 - a broken guard module must refuse, not crash unclearly+ _die(f"ok: could not load {GUARD_PY}: {type(e).__name__}: {e}")+ return mod+++def _read_queue() -> list[dict]:+ """This session's pending drafts, oldest first.++ Every entry is validated before it can be shown or approved. A malformed+ entry kills the whole call rather than being skipped: silently dropping one+ draft out of five while approving the rest is how Sam ends up approving a+ set he did not read."""+ try:+ st = PENDING_PATH.stat()+ except FileNotFoundError:+ extra = ""+ if LEGACY_PENDING.exists():+ extra = (+ f"\n\nNote: the old shared file {LEGACY_PENDING} still exists.\n"+ "It predates the per-session split and is ignored on purpose.\n"+ "Ask the assistant to re-run outbound-humanize in THIS session."+ )+ _die(+ "ok: no pending draft to approve.\n"+ f"Expected one at {PENDING_PATH}, written by outbound-humanize before it\n"+ "shows you a draft. Nothing has been proposed to approve yet." + extra+ )+ except OSError as e:+ _die(f"ok: cannot read pending drafts ({e}): {PENDING_PATH}")++ age = time.time() - st.st_mtime+ if age > PENDING_TTL_SEC:+ _die(+ f"ok: pending drafts are {int(age)}s old, older than the {PENDING_TTL_SEC}s "+ "approval window.\nAsk the assistant to run outbound-humanize again for a "+ "fresh draft before approving."+ )++ try:+ raw = PENDING_PATH.read_text()+ except OSError as e:+ _die(f"ok: cannot read pending drafts ({e}): {PENDING_PATH}")++ try:+ data = json.loads(raw)+ except json.JSONDecodeError as e:+ _die(f"ok: pending drafts are malformed (invalid JSON: {e}): {PENDING_PATH}")++ if not isinstance(data, list):+ _die(+ "ok: pending drafts are malformed (expected a JSON list): "+ f"{PENDING_PATH}\nThis file may have been written by an older "+ "outbound-humanize. Re-run it for a fresh draft."+ )+ if not data:+ _die(f"ok: the pending queue is empty: {PENDING_PATH}")++ for i, rec in enumerate(data, 1):+ if not isinstance(rec, dict):+ _die(f"ok: pending draft {i} is malformed (not a JSON object): {PENDING_PATH}")+ for field in ("recipient", "body", "fp"):+ val = rec.get(field)+ if not isinstance(val, str) or not val:+ _die(+ f"ok: pending draft {i} is malformed (missing or empty "+ f"{field!r}): {PENDING_PATH}"+ )++ return data+++USAGE = (+ "usage:\n"+ " ok approve every draft this session has queued\n"+ " ok all the same thing, spelled out\n"+ " ok #2 approve only draft 2 from the list, leave the rest queued\n"+ "\n"+ "A bare number is refused on purpose: `ok 5` used to mean 'five sends' and\n"+ "now reads as 'draft five', and guessing which one Sam meant is not a thing\n"+ "an approval command gets to do. Write `ok #5` for the draft, `ok` for all."+)+++def _select(argv: list[str], queue: list[dict]) -> list[dict]:+ """Which drafts this invocation approves. Refuses anything ambiguous."""+ if not argv:+ return queue++ arg = argv[0].strip().lower()+ if len(argv) > 1:+ _die(USAGE + f"\n\nunexpected extra arguments: {argv[1:]!r}")++ if arg in ("all", "alles", "these", "allemaal"):+ return queue++ if arg.startswith("#") and arg[1:].isdigit():+ idx = int(arg[1:])+ if not 1 <= idx <= len(queue):+ _die(+ f"ok: there is no draft {idx}; this session has {len(queue)} "+ "queued.\nRun `ok` with no arguments to see and approve them all."+ )+ return [queue[idx - 1]]++ if arg.isdigit():+ _die(+ f"ok: refusing the bare number {arg!r} -- it is ambiguous.\n\n" + USAGE+ )++ _die(USAGE + f"\n\nunexpected argument: {argv[0]!r}")+ return [] # unreachable; _die exits+++def main() -> int:+ queue = _read_queue()+ selected = _select(sys.argv[1:], queue)++ guard = _load_guard()++ # Verify every record against its own stored fingerprint BEFORE minting any+ # of them. A partially-minted set would leave Sam having approved messages+ # he was never shown.+ for i, rec in enumerate(selected, 1):+ real_fp = guard.fingerprint(rec["recipient"], rec["body"])+ if real_fp != rec["fp"]:+ _die(+ f"ok: draft {i}'s stored fingerprint does not match its own\n"+ "(recipient, body). This should never happen from a genuine\n"+ "outbound-humanize run -- refusing rather than trusting a record\n"+ "that may have been tampered with or written by something else."+ )++ fps: dict[str, dict] = {}+ plural = "s" if len(selected) != 1 else ""+ print(f"Approving {len(selected)} send{plural}:")+ for i, rec in enumerate(selected, 1):+ body = rec["body"]+ lines = body.splitlines()+ first_line = lines[0] if lines else "(empty)"+ nbytes = len(body.encode("utf-8"))+ print(f"\n [{i}] to: {rec['recipient']}")+ print(f" channel: {rec.get('channel') or '(unknown channel)'}")+ print(f" first line: {first_line}")+ print(f" bytes: {nbytes}")+ # Provenance, same three fields the UserPromptSubmit hook carries. Until+ # 2026-09-09 this lane minted only recipient+preview, so an approval+ # given in the shell reached the guard with shown_at, route and channel+ # empty, and the AUTHORIZED line in the consent audit could not say when+ # Sam was shown the text or how he said yes. The send was still bound to+ # the exact body -- the fingerprint never depended on these -- but the+ # evidence trail did, and half a trail is what makes an incident+ # unreconstructable afterwards.+ # shown_at is the record's OWN queue-write time: outbound-humanize+ # writes the queue before it prints the body Sam reads.+ fps[rec["fp"]] = {+ "recipient": rec["recipient"],+ "preview": body[:200],+ "shown_at": rec.get("ts", ""),+ "route": "shell-ok",+ "channel": rec.get("channel", ""),+ }++ if len(fps) != len(selected):+ _die(+ "ok: two selected drafts share a fingerprint, so approving them\n"+ "would arm fewer sends than shown. Refusing rather than guessing."+ )++ # Each extra message gets its own slice of time -- five sends cannot+ # realistically be dispatched inside the window sized for one -- but the+ # ceiling keeps an approval from lingering for an hour.+ ttl = min(MINT_TTL_SEC + 60 * (len(selected) - 1), MINT_TTL_MAX_SEC)++ approved = guard.mint(fps, ttl)+ if set(approved.keys()) != set(fps):+ _die(+ "ok: mint did not return exactly the selected fingerprints and\n"+ "nothing else; refusing rather than leaving an ambiguous approval set."+ )++ # One-shot per draft: drop what was just approved, keep the rest queued so+ # `ok #2` does not throw away the drafts Sam has not decided on yet.+ remaining = [rec for rec in queue if rec["fp"] not in fps]+ try:+ if remaining:+ tmp = PENDING_PATH.with_suffix(PENDING_PATH.suffix + ".tmp")+ tmp.write_text(json.dumps(remaining))+ os.chmod(tmp, 0o600)+ os.replace(tmp, PENDING_PATH)+ else:+ PENDING_PATH.unlink()+ except OSError:+ pass++ for rec in selected:+ _audit(+ f"APPROVED fp={rec['fp']} to={rec['recipient']!r} "+ f"channel={rec.get('channel') or ''} "+ f"bytes={len(rec['body'].encode('utf-8'))} "+ f"session={_session_id()} ppid={os.getppid()} "+ f"tty={os.environ.get('SSH_TTY') or ''}"+ )++ # NOTE 2026-09-05: an earlier fix here also wrote /tmp/.claude-send-ok,+ # on the theory that the PreToolUse guard only read that file. It does not:+ # it calls outbound_guard.consume(), which matches the fingerprint minted+ # above. The real defect was in the guard's _identify(), which could not+ # read the recipient and body out of a Bash `gog gmail send` and so+ # fingerprinted the whole shell line instead. That is fixed in+ # block-outbound-comms.py. Writing the legacy token here is now not merely+ # redundant but harmful: it is a bearer credential any message can spend,+ # which is exactly the defect the 2026-09-02 rewrite removed. Removed.++ print(f"\noutbound approval armed for {len(selected)} send{plural}. Window: {ttl}s.")+ if remaining:+ left = len(remaining)+ print(f"{left} draft{'s' if left != 1 else ''} still queued, not approved.")+ return 0+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/claude-ops/scripts/outbound-guard/outbound_guard.py b/claude-ops/scripts/outbound-guard/outbound_guard.pyindex a213a45d..99af32d0 100644--- a/claude-ops/scripts/outbound-guard/outbound_guard.py+++ b/claude-ops/scripts/outbound-guard/outbound_guard.py@@ -1,57 +1,242 @@#!/usr/bin/env python3-"""One approval store for outbound messages, shared by every CLI that can send.+"""Eén kaartjesbureau voor alle uitgaande berichten, ongeacht welke CLI het vraagt.-There used to be two independent guards, each with its own token file: the PreToolUse-hook (/tmp/.claude-send-ok) and the MCP proxy ledger (/tmp/.claude-send-ok-all). A-single message crossed both, so arming an approval meant writing two files and hoping-the counts stayed in step. Any other CLI on the same proxy saw a third picture.+Waarom dit bestaat. Er waren twee onafhankelijke wachters met elk hun eigen kaartje:+de PreToolUse-hook van Claude Code (/tmp/.claude-send-ok) en de mcp-proxy+(/tmp/.claude-send-ok-all). Eén bericht passeerde ze allebei, dus `ok` moest twee+bestanden schrijven en de tellingen liepen uiteen. Codex en Grok gaan langs dezelfde+proxy en hadden weer een ander beeld.-Now there is one state file, one expiry and one counter:+SECURITY FIX 2026-09-02, after a near-miss on a real deal thread. Two defects in the old+design:++1. Approval was a bearer credit ("remaining: N"), not a signature on a specific+ message. `mint(count, ttl)` set a count with no idea what it was for, and+ `consume(recipient, body)` would debit that count for ANY recipient and ANY+ body. Session A's approved draft could be spent by session B on a different+ message to a different person. Fixed: `mint()` now takes the exact set of+ fingerprints Sam is approving — sha256(recipient|normalized body) — and+ `consume()` only allows a send whose fingerprint is in that approved set.+2. A sent message became free to resend. The old "spent" dict let a second+ guard see the same fingerprint and pass for free, correctly avoiding a+ double-charge when ONE message crosses two layers (this Python hook and the+ Node mcp-proxy in outbound-guard.mjs) for the SAME PreToolUse cycle. But it+ never distinguished that from an unrelated session replaying the identical+ text later — a byte-identical resend inside the window went through free+ even with zero approval remaining. Fixed: split into two mechanisms.+ a. A short-lived in-flight set keyed on fingerprint + tool name (still+ 120s, per Sam's instruction to keep the existing TTL) — this is the+ "two guards, one call" free pass, nothing more.+ b. A PERMANENT append-only ledger at ~/.claude/state/outbound-sent.jsonl.+ Once a fingerprint is in the ledger, every future consume() for it is+ refused, forever — not TTL'd. This is what stops a retry (or a second+ session) from silently duplicating a message whose actual delivery+ outcome was never confirmed. Since the two-phase commit below, the row+ is written by commit() rather than by consume(), and an abandoned+ reservation is COMMITTED on expiry — so an ambiguous outcome still+ leaves a paper trail that blocks a silent duplicate rather than a+ transparent one.++Normalisation stays conservative on purpose: strip trailing whitespace per+line and the trailing newline, nothing else. The old code collapsed all+whitespace AND truncated to 400 characters before hashing, which meant two+materially different messages sharing the same first 400 normalised+characters got the identical fingerprint — an approval for one could satisfy+the other. Fixed by hashing the full (lightly normalised) body./tmp/.claude-outbound-guard.json- {"remaining": 3, "minted": 1786732800, "ttl": 900, "spent": {"<fingerprint>": 1786732801}}--And one rule that rules out double counting: a message is identified by recipient plus-content. When a second guard sees a fingerprint already recorded within-SPENT_WINDOW_SEC, that is the same message, already paid for. It passes and nothing is-deducted. One message costs exactly one unit no matter how many layers it crosses.--The Node twin lives at ../outbound-guard.mjs. `sync-installed-copy.sh` mirrors it,-verbatim and on every session start, to ~/.claude/mcp-proxy/outbound-guard.mjs so the-MCP proxy always runs the current schema instead of a copy frozen at whatever this-file looked like when someone last installed it by hand. Both copies read and write-this same file with the same rules, and the test suite asserts both sides agree on-the fingerprint.+ {"minted": 1786732800, "ttl": 900,+ "approved": {"<fp>": {"ts": 1786732800, "recipient": "...", "preview": "..."}},+ "inflight": {"<fp>|<tool>": 1786732801},+ "reservations": {"<fp>": {"at": 1786732801, "recipient": "...", "tool": "...",+ "session_id": "...", "meta": {...}}}}++`reservations` is phase one of the two-phase commit added 2026-09-11; see+RESERVATION_TTL_SEC below for why the approval is no longer spent on the+attempt.++Compatibility note: `ok` and the Node twin were on the OLD count-based shape+(`mint <n> <ttl>`, `{"remaining":..., "spent":...}`) when this file was first+written, and both have since been migrated. `ok` mints a SET of fingerprints+read from the pending queue; the Node twin no longer keeps a store at all and+delegates every decision here. The CLI below still refuses the old 2-int-arg+`mint` call loudly instead of silently doing nothing (or blocking on stdin), so+any caller left on the retired shape fails fast rather than hanging a shell.++Het Node-equivalent staat naast dit bestand als outbound-guard.mjs en, geinstalleerd,+op ~/.claude/mcp-proxy/outbound-guard.mjs. Het draagt een+`// outbound-guard-schema:` marker en sync-installed-copy.sh weigert een+installatie terug te zetten naar een ouder schema. Beide kanten hier houden+dezelfde fingerprint aan; de testsuite toetst dat eerst."""from __future__ import annotations+import fcntlimport hashlibimport jsonimport osimport time-STATE = "/tmp/.claude-outbound-guard.json"-# Window in which the same message reaching a second guard is treated as already paid.-# Generous enough for a slow MCP round trip, short enough that a genuinely new message-# never rides in free.-SPENT_WINDOW_SEC = 120-# Legacy single-use token. Kept working while not every CLI has moved over; the-# canonical state above wins whenever it exists.+# Overridable via env for the regression test suite only; production paths are+# the defaults below and unaffected when the env vars are unset.+STATE = os.environ.get("OUTBOUND_GUARD_STATE") or "/tmp/.claude-outbound-guard.json"+LOCK_FILE = os.environ.get("OUTBOUND_GUARD_LOCK") or "/tmp/.claude-outbound-guard.lock"+# Ledger of fingerprints that have actually been granted approval-to-send.+# Permanent, never pruned by TTL: "sent is sent forever."+LEDGER = os.environ.get("OUTBOUND_GUARD_LEDGER") or os.path.expanduser("~/.claude/state/outbound-sent.jsonl")++# Same single call crossing two guards (this Python PreToolUse hook and the+# Node mcp-proxy layer) for the SAME not-yet-dispatched message. Kept at the+# value Sam asked to preserve. This is intentionally narrow: it forgives a+# second GUARD checking the identical (fingerprint, tool) pair, not a second+# SEND. Once the ledger has the fingerprint, a request outside this window —+# including from a different tool, a different session, or after the window+# lapses — is refused outright regardless of this set.+INFLIGHT_TTL_SEC = 120++# TWO-PHASE COMMIT (2026-09-11, task 53). consume() used to spend the approval+# on the ATTEMPT: it deleted the fingerprint from `approved`, appended the+# ledger and drained the pending queue before the tool had run. That is correct+# only if this hook is the last gate. It is not. The MCP outbound guard+# (~/.claude/mcp-proxy/outbound-guard-proxy.mjs) runs AFTER every PreToolUse+# hook and independently demands a per-call owner approval id. When it refuses,+# nothing is sent -- but Sam's approval is already burnt and the draft is gone+# from the queue, so the retry needs a fresh `ok`, which is burnt the same way.+# An unbreakable loop. Live on 2026-09-11: fp 1d3023ffa1b26deb731bde199aef6c41+# is AUTHORIZED and ledgered at 07:21:30Z for a WhatsApp message that never+# left, and the ledger now refuses that exact body forever.+#+# So consume() now RESERVES. The approval leaves `approved`, so nothing else+# can spend it, but it is not ledgered and the queue is not drained until a+# PostToolUse step says the tool actually ran (commit) or reports an error or a+# downstream block (release). Nothing about WHAT is approved changed: the+# fingerprint check, the ledger check, the per-approval clock and the refusal+# of anything unapproved are byte-for-byte the same.+#+# A reservation is short-lived on purpose. If no PostToolUse outcome arrives+# within RESERVATION_TTL_SEC the reservation is COMMITTED, not released: an+# attempt whose outcome nobody reported may well have gone out, and the whole+# point of the permanent ledger is that an ambiguous outcome must block a+# silent duplicate rather than invite one. So an abandoned reservation leaves a+# spent approval and a ledger row, never a live approval lying around.+RESERVATION_TTL_SEC = int(os.environ.get("OUTBOUND_RESERVATION_TTL") or 180)++# Oude bestanden. Blijven werken zolang niet elke CLI over is, maar de canonieke+# toestand hierboven wint als die er is. Dit pad blijft ONGEWIJZIGD: Sam's eigen+# `! ok` (touch /tmp/.claude-send-ok, buiten het model om) is de noodrem en mag+# niet worden aangeraakt.LEGACY_SINGLE = "/tmp/.claude-send-ok"LEGACY_SINGLE_TTL = 120-def fingerprint(recipient: str, body: str) -> str:- """Identity of a message: who it goes to, and what it says.+def _normalize_body(body: str) -> str:+ """Strip trailing whitespace per line, collapse the trailing newline. Nothing+ else. The old normaliser collapsed ALL whitespace (spaces, newlines) into+ single spaces and truncated to 400 characters, which let two different+ messages that merely start the same way hash identically. Over-normalising+ is exactly what lets a materially different body match; this stays narrow+ on purpose."""+ lines = (body or "").split("\n")+ lines = [ln.rstrip() for ln in lines]+ return "\n".join(lines).rstrip("\n")- Channel is deliberately excluded. The same mail arriving via the hook and via the- proxy must hash identically, even when the two layers name the channel differently.++def canonical_recipients(*groups: str) -> str:+ """Eén sleutel voor de hele ontvangersgroep van één bericht.++ Tot 8 september 2026 weigerde de poort elke send met een cc, een bcc of een+ komma in --to: één afdruk dekte één adres. Dat maakte een mail aan twee+ mensen onverzendbaar in plaats van apart goed te keuren, en dat is precies+ het soort poort waar mensen omheen gaan werken. Nu telt de hele groep als de+ identiteit van het bericht.++ De sleutel is genormaliseerd zodat --to 'a,b' en --to a --cc b hetzelfde+ bericht zijn: adressen worden gesplitst op komma's, getrimd, verkleind,+ ontdubbeld en gesorteerd. Sorteren is nodig omdat de volgorde waarin iemand+ de adressen typt niets over het bericht zegt.++ De veiligheidseigenschap blijft ongewijzigd: een goedkeuring hangt aan+ precies deze groep. Er een adres bij zetten of er een af halen verandert de+ sleutel en dus de afdruk, en de send wordt geweigerd. Voor één ontvanger is+ de uitkomst identiek aan de oude berekening, dus bestaande stempels en+ wachtrijen blijven geldig."""+ seen = []+ for group in groups:+ for part in (group or "").split(","):+ addr = part.strip().lower()+ if addr and addr not in seen:+ seen.append(addr)+ return ",".join(sorted(seen))+++def fingerprint(recipient: str, body: str) -> str:+ """Identiteit van een bericht: aan wie, met welke tekst.++ Kanaal bewust niet meegenomen: dezelfde mail die via de hook en via de proxy komt+ moet dezelfde afdruk krijgen, ook als de twee lagen het kanaal anders benoemen.+ The full normalised body is hashed (not truncated) so two messages sharing a+ long common prefix do not collide."""r = (recipient or "").strip().lower()- b = " ".join((body or "").split())[:400]+ b = _normalize_body(body)return hashlib.sha256(f"{r}|{b}".encode("utf-8")).hexdigest()[:32]+# Key order is load-bearing, not cosmetic. These two tuples ARE the definition of+# "who is this to" and "what does it say" for a structured tool call, and they+# were duplicated: block-outbound-comms.py:_identify() had this list, while the+# Node proxy's approvalInput() in outbound-policy.mjs had a DIFFERENT one+# (recipient/chat_jid only; text before message; no `payload`). Two lists means+# two fingerprints for one message, and a fingerprint the other side has never+# seen can never be matched -- which is precisely how the proxy came to demand+# its own second approval for a message Sam had already approved. One list, one+# derivation, both gates.+IDENT_RECIPIENT_KEYS = ("recipient", "jid", "chat_jid", "chat_id", "to", "channel_id")+IDENT_BODY_KEYS = ("message", "text", "body", "payload", "content")+++def identify_args(tool_input: dict) -> tuple[str, str]:+ """(recipient, body) of a structured tool call, or ('', '') if it is neither.++ Extracted verbatim from block-outbound-comms.py:_identify() so the two gates+ share one derivation instead of two that agree by coincidence. The caller+ decides what an empty answer means: the PreToolUse hook falls back to+ parsing a Bash command, the proxy falls back to refusing.+ """+ if not isinstance(tool_input, dict) or not tool_input:+ return ("", "")+ rcpt = ""+ for k in IDENT_RECIPIENT_KEYS:+ v = tool_input.get(k)+ if isinstance(v, str) and v.strip():+ rcpt = v.strip()+ break+ if isinstance(v, list) and v:+ rcpt = str(v[0]).strip()+ break+ body = ""+ for k in IDENT_BODY_KEYS:+ v = tool_input.get(k)+ if isinstance(v, str) and v.strip():+ body = v+ break+ return (rcpt, body)+++def _lock():+ os.makedirs(os.path.dirname(LOCK_FILE), exist_ok=True) if os.path.dirname(LOCK_FILE) else None+ fh = open(LOCK_FILE, "a+")+ fcntl.flock(fh.fileno(), fcntl.LOCK_EX)+ return fh+++def _unlock(fh) -> None:+ try:+ fcntl.flock(fh.fileno(), fcntl.LOCK_UN)+ finally:+ fh.close()++def _read() -> dict | None:try:with open(STATE) as f:@@ -60,9 +245,6 @@ def _read() -> dict | None:return Noneif not isinstance(d, dict):return None- if time.time() - d.get("minted", 0) > d.get("ttl", 0):- _clear()- return Nonereturn d@@ -85,78 +267,748 @@ def _clear() -> None:pass-def mint(count: int, ttl: int) -> None:- """Called by `ok`. Sets the counter; never adds to what was already there."""- _write({"remaining": int(count), "minted": int(time.time()),- "ttl": int(ttl), "spent": {}})+def _ledger_has(fp: str) -> bool:+ try:+ with open(LEDGER) as f:+ for line in f:+ line = line.strip()+ if not line:+ continue+ try:+ row = json.loads(line)+ except json.JSONDecodeError:+ continue+ if row.get("fp") == fp:+ return True+ except (FileNotFoundError, OSError):+ return False+ return False+++def _consent_audit(event: str, **kw) -> None:+ """Best-effort. The audit must never be able to block or break a send."""+ try:+ import os as _os+ import sys as _sys+ _sys.path.insert(0, _os.path.dirname(_os.path.abspath(__file__)))+ import consent_audit+ consent_audit.record(event, **kw)+ except Exception:+ pass+++def _ledger_append(fp: str, recipient: str, tool: str, session_id: str) -> None:+ os.makedirs(os.path.dirname(LEDGER), exist_ok=True)+ row = {+ "ts": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),+ "fp": fp,+ "recipient": (recipient or "")[:200],+ "tool": (tool or "")[:120],+ "session_id": (session_id or "")[:120],+ }+ try:+ with open(LEDGER, "a") as f:+ f.write(json.dumps(row) + "\n")+ os.chmod(LEDGER, 0o600)+ except OSError:+ pass+++PENDING_DIR = os.environ.get("OUTBOUND_PENDING_DIR") or os.path.expanduser(+ "~/.claude/state/outbound-pending"+)+++def _drain_pending(fp: str) -> None:+ """Remove a delivered fingerprint from every session's pending queue.++ WHY (2026-09-09): a send is spent in three places and until today only two+ of them were written. consume() removed the fingerprint from `approved` and+ appended it to the ledger, but the DRAFT stayed in+ ~/.claude/state/outbound-pending/<session>.json as though it still had to+ go. Sam's next approval word re-derived that record, found it valid, and+ minted a fresh approval for a body that was already in the recipient's inbox.+ The ledger check in consume() then refused the second send -- so nothing+ duplicated -- but Sam had been shown an armed approval for delivered text,+ which is a lie about the state of the world and exactly the kind of thing+ that makes him stop trusting the gate.++ Best-effort by design: a queue that cannot be rewritten must never be able+ to stop a send that is already authorised. The ledger remains the hard+ guarantee against a duplicate; this only keeps the queue honest.+ """+ if not fp:+ return+ try:+ names = os.listdir(PENDING_DIR)+ except OSError:+ return+ for name in names:+ if not name.endswith(".json"):+ continue+ path = os.path.join(PENDING_DIR, name)+ try:+ with open(path) as f:+ queue = json.load(f)+ if not isinstance(queue, list):+ continue+ kept = [r for r in queue+ if not (isinstance(r, dict) and r.get("fp") == fp)]+ if len(kept) == len(queue):+ continue+ tmp = path + ".tmp"+ with open(tmp, "w") as f:+ json.dump(kept, f)+ os.chmod(tmp, 0o600)+ os.replace(tmp, path)+ except (OSError, ValueError):+ continue+++def _expire_due(d: dict, now: float) -> list:+ """Split `reservations` into live and expired. Mutates d in place.++ A malformed entry is dropped and reported as expired: an unreadable+ reservation is a state this code cannot reason about, and the refusing+ direction is to treat the approval as spent, never to hand it back.+ """+ res = d.get("reservations")+ if not isinstance(res, dict):+ d["reservations"] = {}+ return []+ live, dead = {}, []+ for fp, rec in res.items():+ if not isinstance(rec, dict):+ dead.append((fp, {}))+ continue+ try:+ at = float(rec.get("at", 0))+ except (TypeError, ValueError):+ at = 0.0+ if now - at > RESERVATION_TTL_SEC:+ dead.append((fp, rec))+ else:+ live[fp] = rec+ d["reservations"] = live+ for fp, _rec in dead:+ _drop_inflight(d, fp)+ return dead+++def _finalise_expired(dead: list) -> None:+ """Ledger every reservation that ran out of time. See RESERVATION_TTL_SEC."""+ for fp, rec in dead:+ if not fp or _ledger_has(fp):+ continue+ _ledger_append(fp, rec.get("recipient", ""), rec.get("tool", ""),+ rec.get("session_id", ""))+ _drain_pending(fp)+ meta = rec.get("meta") if isinstance(rec.get("meta"), dict) else {}+ _consent_audit(+ "RESERVATION_EXPIRED",+ recipient=rec.get("recipient", ""),+ fp=fp,+ body_sha256=rec.get("body_sha256", ""),+ body_chars=rec.get("body_chars", 0),+ shown_at=meta.get("shown_at", ""),+ approved_at=meta.get("ts", ""),+ approval_route=meta.get("route", "") or "word",+ channel=meta.get("channel", ""),+ session_id=rec.get("session_id", ""),+ tool=rec.get("tool", ""),+ send_result="unknown",+ reason=f"no PostToolUse outcome within {RESERVATION_TTL_SEC}s; "+ f"ledgered so a retry cannot silently duplicate",+ )+++def _drop_inflight(d: dict, fp: str) -> None:+ """End the "two guards, one call" free pass for this fingerprint.++ That window (INFLIGHT_TTL_SEC) exists for one reason: a second guard+ inspecting the SAME not-yet-dispatched call must not be charged twice. The+ moment the call is finished -- committed, released or expired -- there is no+ such call left to forgive, and leaving the key would let a byte-identical+ resend on the same tool sail past both the ledger and the approved set for+ the rest of the window. Dropping it here is what makes "one approval, one+ successful send" true for a retry inside 120 seconds as well.+ """+ d["inflight"] = {k: v for k, v in (d.get("inflight") or {}).items()+ if not str(k).startswith(fp + "|")}+++def _persist(d: dict) -> None:+ """Write, or clear the file when there is genuinely nothing left to keep."""+ if d.get("approved") or d.get("inflight") or d.get("reservations"):+ _write(d)+ else:+ _clear()+++def reservations_for(session_id: str = "", tool: str = "") -> list:+ """Live reservations this session made with this tool, newest last.++ The PostToolUse hook has the same session_id and tool_name the PreToolUse+ gate had, and a reservation only exists between those two moments, so this+ pairing identifies the call without the hook having to re-derive the body+ from the tool input (and risk deriving it differently).++ Reaps expired reservations as a side effect, so the TTL applies even in a+ session that never sends again.+ """+ lockfh = _lock()+ try:+ d = _read()+ if d is None:+ return []+ dead = _expire_due(d, time.time())+ rows = [+ dict(rec, fp=fp)+ for fp, rec in (d.get("reservations") or {}).items()+ if (not session_id or rec.get("session_id") == session_id)+ and (not tool or rec.get("tool") == tool)+ ]+ _persist(d)+ finally:+ _unlock(lockfh)+ _finalise_expired(dead)+ rows.sort(key=lambda r: r.get("at", 0))+ return rows+++def claim_reservation(recipient: str = "", body: str = "", guard: str = "",+ session_id: str = "", tool: str = "") -> bool:+ """May a SECOND guard let this exact message through on the approval that+ gate 1 already spent for it? True only if gate 1 holds a live reservation+ for this exact (recipient, body) and this guard has not ridden it before.++ WHY THIS EXISTS (Sam, 2026-09-11). Sam's outbound gate is the primary lock.+ The MCP outbound guard used to be a second, independent lock demanding its+ own per-call owner approval id, and after the two-phase commit landed the+ two locks deadlocked: gate 1's consume() RESERVES the fingerprint, and+ consume() refuses a fingerprint that is already reserved (it is a second+ send of an approval still being spent). The proxy calls consume() under a+ different tool label, so it misses the "two guards, one call" in-flight+ window keyed on fp|tool, lands on the reservation branch, and mints a fresh+ approval id for a message Sam had already approved. Reproduced in a sandbox:+ mint, gate-1 reserve, then the proxy answers outbound_guard_approval_required.++ This does NOT grant anything. It reports that gate 1 already granted, and it+ cannot be the thing that turns an unapproved message into an approved one:++ * No live reservation for this fingerprint -> False. That covers an+ unapproved body, a one-byte-different body, the same body to a+ different recipient (all different fingerprints) and an approval that+ was never spent by gate 1 at all.+ * A reservation whose clock ran out is reaped by _expire_due() before the+ lookup, so it is ledgered as an unknown outcome and NOT claimable.+ * One claim per reservation per guard, recorded in the reservation itself+ under `guard_claims`. So the proxy rides a reservation once, not once+ per call for as long as the reservation lives, and "one approval, one+ send" survives unchanged.+ * The ledger still wins: a fingerprint that has already been sent is+ refused even if a reservation somehow lingers.++ commit() and release() both pop the whole reservation, so `guard_claims`+ dies with it. A retry after a downstream block therefore gets a fresh+ reservation off Sam's restored approval and a fresh claim, which is what+ makes one `ok` cover the retry.++ Nothing here is written to ~/.claude/state/outbound-approvals.json, and no+ approval is minted on any path.+ """+ if not guard:+ # An unnamed guard cannot be held to one claim, so it gets none.+ return False+ fp = fingerprint(recipient, body)+ if not fp:+ return False++ claimed = False+ rec = None+ lockfh = _lock()+ try:+ d = _read()+ if d is None:+ return False+ now = time.time()+ dead = _expire_due(d, now)+ res = (d.get("reservations") or {}).get(fp)+ if isinstance(res, dict) and not _ledger_has(fp):+ claims = res.get("guard_claims")+ if not isinstance(claims, dict):+ claims = {}+ if guard not in claims:+ claims[guard] = now+ res["guard_claims"] = claims+ d["reservations"][fp] = res+ claimed = True+ rec = res+ _persist(d)+ finally:+ _unlock(lockfh)+ _finalise_expired(dead)++ if claimed:+ meta = rec.get("meta") if isinstance(rec.get("meta"), dict) else {}+ _consent_audit(+ "RESERVATION_CLAIMED",+ recipient=rec.get("recipient", ""),+ fp=fp,+ body_sha256=rec.get("body_sha256", ""),+ body_chars=rec.get("body_chars", 0),+ shown_at=meta.get("shown_at", ""),+ approved_at=meta.get("ts", ""),+ approval_route=meta.get("route", "") or "word",+ channel=meta.get("channel", ""),+ session_id=rec.get("session_id", "") or session_id,+ tool=rec.get("tool", "") or tool,+ send_result="pending",+ reason=f"second guard {guard} rode the reservation gate 1 already "+ f"spent for this exact (recipient, body); no new approval minted",+ )+ return claimed+++def commit(fp: str, session_id: str = "", tool: str = "", result: str = "ok") -> bool:+ """Phase two, success: the tool ran, so the approval is really spent.++ This is where the ledger row, the queue drain and the AUTHORIZED evidence+ line now happen -- everything consume() used to do on the attempt. True+ when a live reservation was found and closed; False when there was none+ (already committed, released, or expired), and False is never an error: it+ only means this outcome has nothing left to close.+ """+ if not fp:+ return False+ lockfh = _lock()+ try:+ d = _read()+ if d is None:+ return False+ dead = _expire_due(d, time.time())+ rec = (d.get("reservations") or {}).pop(fp, None)+ if isinstance(rec, dict):+ _drop_inflight(d, fp)+ _persist(d)+ finally:+ _unlock(lockfh)+ _finalise_expired(dead)+ if not isinstance(rec, dict):+ return False+ meta = rec.get("meta") if isinstance(rec.get("meta"), dict) else {}+ recipient = rec.get("recipient", "")+ if not _ledger_has(fp):+ _ledger_append(fp, recipient, rec.get("tool", "") or tool,+ rec.get("session_id", "") or session_id)+ _drain_pending(fp)+ _consent_audit(+ "AUTHORIZED",+ recipient=recipient,+ fp=fp,+ body_sha256=rec.get("body_sha256", ""),+ body_chars=rec.get("body_chars", 0),+ shown_at=meta.get("shown_at", ""),+ approved_at=meta.get("ts", ""),+ approval_route=meta.get("route", "") or "word",+ channel=meta.get("channel", ""),+ session_id=rec.get("session_id", "") or session_id,+ tool=rec.get("tool", "") or tool,+ send_result=result or "ok",+ reason="post-tool outcome: the send ran",+ )+ return True+++def release(fp: str, session_id: str = "", tool: str = "", reason: str = "") -> bool:+ """Phase two, failure: nothing went out, so Sam's approval stands.++ The approval goes back into `approved` with its ORIGINAL timestamp and TTL.+ A release is not a re-approval and must not extend his clock: if the window+ has already passed, the restored entry is dead on arrival and consume()+ refuses it exactly as it would have.++ The in-flight free pass for this fingerprint is dropped at the same time.+ Leaving it would let the retry sail past the approved-set check on the+ 120-second window instead of properly spending the restored approval, which+ would put the approval right back in the state this fix exists to prevent:+ live, unspent, with a send already gone.+ """+ if not fp:+ return False+ lockfh = _lock()+ try:+ d = _read()+ if d is None:+ return False+ now = time.time()+ dead = _expire_due(d, now)+ rec = (d.get("reservations") or {}).pop(fp, None)+ restored = False+ if isinstance(rec, dict) and not _ledger_has(fp):+ meta = rec.get("meta") if isinstance(rec.get("meta"), dict) else None+ if isinstance(meta, dict):+ approved = dict(d.get("approved") or {})+ approved[fp] = meta+ d["approved"] = approved+ _drop_inflight(d, fp)+ restored = True+ _persist(d)+ finally:+ _unlock(lockfh)+ _finalise_expired(dead)+ if not isinstance(rec, dict):+ return False+ meta = rec.get("meta") if isinstance(rec.get("meta"), dict) else {}+ _consent_audit(+ "RELEASED",+ recipient=rec.get("recipient", ""),+ fp=fp,+ body_sha256=rec.get("body_sha256", ""),+ body_chars=rec.get("body_chars", 0),+ shown_at=meta.get("shown_at", ""),+ approved_at=meta.get("ts", ""),+ approval_route=meta.get("route", "") or "word",+ channel=meta.get("channel", ""),+ session_id=rec.get("session_id", "") or session_id,+ tool=rec.get("tool", "") or tool,+ send_result="blocked",+ reason=(reason or "post-tool outcome: the send did not happen")[:200],+ )+ return restored+++def mint(fingerprints: dict[str, dict] | list[str] | set[str], ttl: int) -> dict:+ """Door `ok` (of de nieuwe wrapper eromheen) aangeroepen. Vervangt de hele+ goedgekeurde set — niet optellen bij wat er stond, zelfde semantiek als de+ oude count-based mint.++ `fingerprints` is either a dict {fp: meta} (meta may carry a human-readable+ "recipient"/"preview" for the confirmation Sam sees) or a plain iterable of+ fingerprints, in which case meta is empty. Returns the approved dict that+ was written, so a caller can print it back to Sam for a last visual check+ against what he read."""+ if isinstance(fingerprints, dict):+ approved = {+ fp: {+ "ts": int(time.time()),+ "recipient": (meta or {}).get("recipient", ""),+ "preview": (meta or {}).get("preview", ""),+ # Consent evidence, carried through to the audit line at spend+ # time. `shown_at` is when the body was written to the pending+ # queue, which is before it was printed to Sam, so it dates the+ # moment he was shown this exact text. `route` is how he said+ # yes. Neither is used to decide anything -- the fingerprint+ # does that -- they exist so the send can be PROVEN afterwards.+ "shown_at": (meta or {}).get("shown_at", ""),+ "route": (meta or {}).get("route", ""),+ "channel": (meta or {}).get("channel", ""),+ }+ for fp, meta in fingerprints.items()+ }+ else:+ approved = {+ fp: {"ts": int(time.time()), "recipient": "", "preview": ""}+ for fp in fingerprints+ }+ # Each approval carries its own clock. Before 2026-09-05 this wrote the+ # approved set wholesale and consume() judged everything against one batch+ # clock, so on a machine running many sessions at once (11 pending queues is+ # normal here) one session's `ok` silently erased another's approvals. Sam+ # approved three emails and a parallel session's WhatsApp approval wiped all+ # three seconds later; consume() then refused them with no explanation. A+ # gate that says no to the approved case is the kind operators route around.+ # Merging is not a loosening: every entry is still bound to one exact+ # (recipient, body), still spent once, still ledgered forever.+ now = int(time.time())+ for meta in approved.values():+ meta["ttl"] = int(ttl)+ lockfh = _lock()+ try:+ d = _read() or {}+ kept = {}+ for fp, meta in (d.get("approved") or {}).items():+ if not isinstance(meta, dict):+ continue+ age = now - int(meta.get("ts", 0))+ if age <= int(meta.get("ttl", d.get("ttl", 0))):+ kept[fp] = meta+ kept.update(approved)+ # `reservations` is carried across verbatim. A mint replaces the+ # APPROVED set; it has no business finishing or forgetting a send that+ # is in flight, and dropping the key here would silently un-spend one.+ _write({+ "minted": now,+ "ttl": int(ttl),+ "approved": kept,+ "inflight": d.get("inflight") or {},+ "reservations": d.get("reservations") if isinstance(d.get("reservations"), dict) else {},+ })+ finally:+ _unlock(lockfh)+ # Only what THIS call approved: `ok` asserts the returned set equals the+ # fingerprints it selected, and must not see a sibling session's entries.+ return approveddef peek() -> tuple[int, int]:- """(remaining, seconds still valid). (0, 0) when nothing is armed."""+ """(aantal goedgekeurde berichten, seconden geldig). (0, 0) als er niets is."""d = _read()if not d:return (0, 0)- left = int(d.get("ttl", 0) - (time.time() - d.get("minted", 0)))- return (int(d.get("remaining", 0)), max(0, left))+ now = time.time()+ live = []+ for meta in (d.get("approved") or {}).values():+ if not isinstance(meta, dict):+ continue+ left = int(meta.get("ttl", d.get("ttl", 0))) - int(now - int(meta.get("ts", 0)))+ if left > 0:+ live.append(left)+ if not live:+ return (0, 0)+ return (len(live), max(live))++def consume(recipient: str = "", body: str = "", session_id: str = "", tool: str = "") -> bool:+ """True als DIT specifieke bericht (deze ontvanger, deze tekst) mag.-def consume(recipient: str = "", body: str = "") -> bool:- """True when this message may go. Deducts at most one unit.+ Volgorde, met een bestandslock zodat twee echte gelijktijdige processen niet+ allebei kunnen winnen:+ 1. In-flight venster (fingerprint + tool, 120s): dezelfde nog-niet-verzonden+ oproep die een tweede wachter ziet, gratis door.+ 2. Permanent ledger: dit exacte bericht is ooit al goedgekeurd om te+ verzenden. Geweigerd, punt uit — ook binnen het in-flight venster als tool+ of sessie afwijkt, en altijd buiten dat venster. Zo laat een onduidelijke+ verzenduitkomst een retry weigeren in plaats van stilzwijgend dupliceren.+ 2b. Lopende reservering: deze afdruk wordt op dit moment al verzonden door+ een andere tool of een andere sessie. Geweigerd; het in-flight venster+ hierboven heeft de "twee wachters, één aanroep"-uitzondering al gehad.+ 3. Goedgekeurde set uit mint(): bestaat de fingerprint daar en is de batch+ nog niet verlopen, dan wint deze aanroep — de fingerprint wordt verwijderd+ (eenmalig), als RESERVERING vastgelegd, en het in-flight venster wordt+ gezet zodat een tweede wachter op DEZELFDE aanroep gratis door mag.- The same fingerprint inside the window is the same message, already charged at an- earlier guard, so it passes for free.+ Sinds 11 september 2026 schrijft deze functie NIET meer naar de ledger en+ leegt zij de wachtrij niet. Dat gebeurt in commit(), na de tool-call, omdat+ alleen daar bekend is of er echt iets is verstuurd. Wat hier wordt+ goedgekeurd is onveranderd."""fp = fingerprint(recipient, body)- d = _read()- if d:+ key = f"{fp}|{tool or ''}"++ lockfh = _lock()+ try:+ d = _read()+ if d is None:+ # Geen canonieke toestand: val terug op het losse eenmalige kaartje,+ # ONGEWIJZIGD — Sam's `! ok` noodrem buiten het model om.+ try:+ st = os.stat(LEGACY_SINGLE)+ except OSError:+ return False+ if time.time() - st.st_mtime > LEGACY_SINGLE_TTL:+ return False+ try:+ os.remove(LEGACY_SINGLE)+ except OSError:+ pass+ # Recorded as its own route precisely because it is WEAKER evidence:+ # the bare token binds to nothing -- not to this recipient and not+ # to this text -- so a line with approval_route=legacy-token proves+ # only that someone with shell access allowed *a* send within 120s.+ # It is kept for sends that cannot go through a humanizer pass, and+ # it is auditable as the exception it is.+ _consent_audit(+ "AUTHORIZED",+ recipient=recipient,+ body=body,+ fp=fp,+ approval_route="legacy-token",+ session_id=session_id,+ tool=tool,+ send_result="authorized",+ reason="no canonical guard state; bare token path",+ )+ return True+now = time.time()- spent = {k: v for k, v in (d.get("spent") or {}).items()- if now - v < SPENT_WINDOW_SEC}- if fp in spent:- d["spent"] = spent+ # Finalised while the lock is held: none of these touch this lock, and+ # consume() returns from a dozen places, so deferring them past the+ # unlock would mean a reap that silently never happens on most paths.+ _finalise_expired(_expire_due(d, now))+ inflight = {k: v for k, v in (d.get("inflight") or {}).items()+ if now - v < INFLIGHT_TTL_SEC}++ if key in inflight:+ d["inflight"] = inflight_write(d)return True- remaining = int(d.get("remaining", 0))- if remaining > 0:- remaining -= 1- spent[fp] = now- if remaining <= 0 and not spent:- _clear()- else:- d["remaining"] = remaining- d["spent"] = spent- _write(d)- return True- # Counter at zero but still inside the window. Only a repeat of an- # already-paid message may pass, and that was handled above.- return False- # No canonical state: fall back to the old single-use token so a CLI that has not- # been migrated keeps behaving as before.- try:- st = os.stat(LEGACY_SINGLE)- except OSError:- return False- if time.time() - st.st_mtime > LEGACY_SINGLE_TTL:- return False- try:- os.remove(LEGACY_SINGLE)- except OSError:- pass- return True+ if _ledger_has(fp):+ # Verzonden is verzonden. Geen vers "approved" item redt dit meer.+ d["inflight"] = inflight+ _write(d)+ return False++ if fp in (d.get("reservations") or {}):+ # Reserved by another tool or another guard in this same cycle, and+ # the in-flight test above already gave the same-call case its free+ # pass. Anything else asking for a reserved fingerprint is a second+ # send of an approval that is still being spent. Refuse.+ d["inflight"] = inflight+ _write(d)+ return False++ approved = dict(d.get("approved") or {})+ meta = approved.get(fp)+ if not isinstance(meta, dict):+ d["inflight"] = inflight+ _write(d)+ return False++ # This approval's own clock, not the batch's. A later mint by another+ # session refreshes "minted" and must not extend or expire this entry.+ if now - int(meta.get("ts", 0)) > int(meta.get("ttl", d.get("ttl", 0))):+ del approved[fp]+ d["approved"] = approved+ d["inflight"] = inflight+ _write(d)+ return False++ # Winnaar: eenmalig RESERVEREN, in-flight zetten voor de tweede wachter+ # op dezelfde aanroep. De ledger-regel, het legen van de wachtrij en de+ # AUTHORIZED-bewijsregel verhuizen naar commit(), want die weet pas of+ # de send echt is gebeurd. Zie RESERVATION_TTL_SEC bovenaan.+ del approved[fp]+ inflight[key] = now+ reservations = dict(d.get("reservations") or {})+ reservations[fp] = {+ "at": now,+ "recipient": (recipient or "")[:200],+ "tool": (tool or "")[:120],+ "session_id": (session_id or "")[:120],+ # Which text this was, without keeping the text. The AUTHORIZED+ # line used to carry body_sha256 because consume() had the body in+ # hand; commit() does not, so the digest is carried instead. A hash+ # is the evidence; the body on disk would only be a second copy of+ # something already queued and already approved.+ "body_sha256": hashlib.sha256((body or "").encode("utf-8", "replace")).hexdigest(),+ "body_chars": len(body or ""),+ "meta": meta,+ }+ d["approved"] = approved+ d["inflight"] = inflight+ d["reservations"] = reservations+ # 2026-09-09: used to _clear() the whole state file whenever `approved`+ # emptied out here, which also discarded the `inflight` entry just set+ # above for THIS message -- the exact record the mcp-proxy twin (Node+ # outbound-guard.mjs) needs to read within its own consume() to grant+ # the same approval for the same PreToolUse cycle. That silently made+ # every proxied send (Slack/WhatsApp/etc via mcp-proxy) fail closed+ # whenever this was the last outstanding approval. Clear only when+ # there is truly nothing left to preserve.+ _persist(d)+ # THE EVIDENCE LINE for phase one. This is still the single choke point+ # where a body-bound approval leaves the approved set, so it is the only+ # place that can honestly assert "Sam saw this exact body and approved+ # this send". What it no longer asserts is that the send happened --+ # that claim belongs to commit(), which is the only thing that can know+ # it. RESERVED, AUTHORIZED and RELEASED on one fingerprint therefore+ # read as the true story of one attempt.+ _consent_audit(+ "RESERVED",+ recipient=recipient,+ body=body,+ fp=fp,+ shown_at=meta.get("shown_at", ""),+ approved_at=meta.get("ts", ""),+ approval_route=meta.get("route", "") or "word",+ channel=meta.get("channel", ""),+ session_id=session_id,+ tool=tool,+ send_result="reserved",+ reason=f"pre-tool reservation, {RESERVATION_TTL_SEC}s to a post-tool outcome",+ )+ return True+ finally:+ _unlock(lockfh)if __name__ == "__main__":import sys+cmd = sys.argv[1] if len(sys.argv) > 1 else "peek"+if cmd == "mint":- mint(int(sys.argv[2]), int(sys.argv[3]) if len(sys.argv) > 3 else 900)- print("minted", *peek())+ # New shape: `mint <ttl>`, JSON list of {"recipient":..., "body":...} on+ # stdin. Deliberately NOT the old `mint <n> <ttl>` shape: that call+ # cannot express which message is being approved, which is the whole+ # defect this rewrite closes. Detect and refuse the old shape loudly and+ # immediately (no stdin read attempted) so a stale caller (the current+ # ~/.local/bin/ok) fails fast instead of hanging on a JSON read that+ # will never come from an interactive shell.+ if len(sys.argv) == 4 and sys.argv[2].isdigit() and sys.argv[3].isdigit():+ sys.stderr.write(+ "outbound_guard mint: the old `mint <n> <ttl>` count-based call is "+ "retired. Approval must now be bound to the exact (recipient, body) "+ "being sent. Update the caller to:\n"+ " mint <ttl_seconds> with a JSON list on stdin:\n"+ ' [{"recipient": "...", "body": "..."}]\n'+ "~/.local/bin/ok and ~/.claude/mcp-proxy/outbound-guard.mjs still use "+ "the old shape and need a companion update before this file is "+ "installed.\n"+ )+ sys.exit(2)+ if len(sys.argv) < 3:+ sys.stderr.write("usage: outbound_guard.py mint <ttl_seconds> (JSON list on stdin)\n")+ sys.exit(2)+ ttl = int(sys.argv[2])+ try:+ pairs = json.load(sys.stdin)+ except json.JSONDecodeError as e:+ sys.stderr.write(f"outbound_guard mint: invalid JSON on stdin: {e}\n")+ sys.exit(2)+ if not isinstance(pairs, list) or not pairs:+ sys.stderr.write("outbound_guard mint: expected a non-empty JSON list on stdin\n")+ sys.exit(2)+ fps = {}+ for p in pairs:+ if not isinstance(p, dict):+ continue+ r = p.get("recipient", "")+ b = p.get("body", "")+ fp = fingerprint(r, b)+ fps[fp] = {"recipient": str(r)[:200], "preview": str(b)[:200]}+ approved = mint(fps, ttl)+ print(f"minted {len(approved)} fingerprint(s) ttl={ttl}s")+ for fp, meta in approved.items():+ print(f" {fp} -> to={meta['recipient']!r} body[:60]={meta['preview'][:60]!r}")elif cmd == "consume":- ok = consume(sys.argv[2] if len(sys.argv) > 2 else "",- sys.argv[3] if len(sys.argv) > 3 else "")+ recipient = sys.argv[2] if len(sys.argv) > 2 else ""+ body = sys.argv[3] if len(sys.argv) > 3 else ""+ tool = sys.argv[4] if len(sys.argv) > 4 else ""+ session_id = sys.argv[5] if len(sys.argv) > 5 else (os.environ.get("CLAUDE_CODE_SESSION_ID") or "")+ ok = consume(recipient, body, session_id=session_id, tool=tool)print("allow" if ok else "deny", *peek())sys.exit(0 if ok else 1)+ elif cmd in ("commit", "release"):+ # Phase two. `fp` first so a caller that already knows the fingerprint+ # never has to hand the body to another process.+ fp = sys.argv[2] if len(sys.argv) > 2 else ""+ tool = sys.argv[3] if len(sys.argv) > 3 else ""+ session_id = sys.argv[4] if len(sys.argv) > 4 else (os.environ.get("CLAUDE_CODE_SESSION_ID") or "")+ reason = sys.argv[5] if len(sys.argv) > 5 else ""+ if cmd == "commit":+ done = commit(fp, session_id=session_id, tool=tool)+ else:+ done = release(fp, session_id=session_id, tool=tool, reason=reason)+ print(f"{cmd} {'done' if done else 'nothing-to-do'} {fp}")+ sys.exit(0 if done else 1)+ elif cmd == "reservations":+ tool = sys.argv[2] if len(sys.argv) > 2 else ""+ session_id = sys.argv[3] if len(sys.argv) > 3 else ""+ for row in reservations_for(session_id=session_id, tool=tool):+ print(json.dumps({k: v for k, v in row.items() if k != "meta"}))else:r, t = peek()- print(f"remaining={r} valid_for={t}s")+ print(f"approved={r} valid_for={t}s")diff --git a/claude-ops/tests/outbound-guard/test-broken-alias.py b/claude-ops/tests/outbound-guard/test-broken-alias.pyindex 4bfbb605..092b4342 100755--- a/claude-ops/tests/outbound-guard/test-broken-alias.py+++ b/claude-ops/tests/outbound-guard/test-broken-alias.py@@ -43,11 +43,34 @@ def disarm():os.remove(p)-def arm(home):- """Mint a real approval so the test proves the block outranks the token."""- subprocess.run([sys.executable, os.path.join(SRC, "outbound_guard.py"),- "mint", "5", "900"],- capture_output=True, timeout=30, env=dict(os.environ, HOME=home))+def arm(home, cmd):+ """Mint a real approval for EXACTLY this command, so the test proves the+ alias block outranks a genuine approval rather than an absent one.++ An approval is a signature on one (recipient, body), not a count. The old+ `mint 5 900` call is retired and now refuses loudly, which silently turned+ every "armed" case in this test into an unarmed one: the send was blocked+ for want of approval and the assertion read as if the alias logic had+ changed. So derive the pair the hook itself will derive, from the hook's own+ code, and mint that fingerprint.+ """+ import importlib.machinery+ import importlib.util++ loader = importlib.machinery.SourceFileLoader(+ "guard_under_test", os.path.join(SRC, "outbound_guard.py"))+ guard = importlib.util.module_from_spec(+ importlib.util.spec_from_loader(loader.name, loader))+ loader.exec_module(guard)++ hook_loader = importlib.machinery.SourceFileLoader("hook_under_test", HOOK)+ hook = importlib.util.module_from_spec(+ importlib.util.spec_from_loader(hook_loader.name, hook_loader))+ hook_loader.exec_module(hook)++ recipient, body = hook._identify("Bash", {"command": cmd}, cmd)+ fp = guard.fingerprint(recipient, body)+ guard.mint({fp: {"recipient": recipient, "preview": body[:80]}}, 900)def main() -> int:@@ -61,8 +84,9 @@ def main() -> int:try:disarm()- arm(home)- rc, err = run(f"{G} send --to [email protected] --from {BROKEN} --body hi", home)+ cmd = f"{G} send --to [email protected] --from {BROKEN} --body hi"+ arm(home, cmd)+ rc, err = run(cmd, home)ok = rc == 2 and "misconfigured" in errfail += not okprint(f" {'ok ' if ok else 'FAIL'} broken alias blocked despite approval (exit={rc})")@@ -71,15 +95,17 @@ def main() -> int:fail += not okprint(f" {'ok ' if ok else 'FAIL'} block message names the repair")- arm(home)- rc, _ = run(f"{G} send --to [email protected] --from {HEALTHY} --body hi", home)+ cmd = f"{G} send --to [email protected] --from {HEALTHY} --body hi"+ arm(home, cmd)+ rc, _ = run(cmd, home)ok = rc == 0fail += not okprint(f" {'ok ' if ok else 'FAIL'} healthy alias still allowed (exit={rc})")# No sender flag at all uses the account default, which cannot be broken this way.- arm(home)- rc, _ = run(f"{G} send --to [email protected] --body hi", home)+ cmd = f"{G} send --to [email protected] --body hi"+ arm(home, cmd)+ rc, _ = run(cmd, home)ok = rc == 0fail += not okprint(f" {'ok ' if ok else 'FAIL'} default sender unaffected (exit={rc})")@@ -115,8 +141,9 @@ def main() -> int:# An empty list must not block anything, or a machine that never ran the# refresh script would have every send refused.os.remove(os.path.join(home, ".claude", "state", "broken-send-aliases.json"))- arm(home)- rc, _ = run(f"{G} send --to [email protected] --from {BROKEN} --body hi", home)+ cmd = f"{G} send --to [email protected] --from {BROKEN} --body hi"+ arm(home, cmd)+ rc, _ = run(cmd, home)ok = rc == 0fail += not okprint(f" {'ok ' if ok else 'FAIL'} no alias list means no extra blocking (exit={rc})")