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 current Node twin; stop the SessionStart sync from silently downgrading it (#960)
Aurora Capital78ec568f7a6e
diff --git a/claude-ops/scripts/outbound-guard/README.md b/claude-ops/scripts/outbound-guard/README.mdindex 88c999ed..5b33ab8f 100644--- a/claude-ops/scripts/outbound-guard/README.md+++ b/claude-ops/scripts/outbound-guard/README.md@@ -25,8 +25,19 @@ Three failures came out of that on 2026-08-15:## The design-`outbound_guard.py` and `outbound-guard.mjs` are the same logic in two languages,-reading and writing one file:+`outbound-guard.mjs` is the Node twin used by the MCP proxy. It no longer reimplements+the store: it hands every decision to `outbound_guard.py` over stdin, because two+implementations of "which message is this, and was it approved" is exactly what drifted.+The guard it delegates to is the installed one at+`~/.claude/scripts/hooks/outbound_guard.py` (override with `OUTBOUND_GUARD_PY`); when it+cannot 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.++Historically both sides kept their own copy of one file:```/tmp/.claude-outbound-guard.json@@ -45,6 +56,33 @@ and the approval count means what it says.If the shared file is absent, both sides fall back to the old single-use token so apartially migrated environment keeps working rather than failing open or shut.+## Keeping the installed twin in sync++`sync-installed-copy.sh` mirrors `outbound-guard.mjs` to+`~/.claude/mcp-proxy/outbound-guard.mjs`. `scripts/setup.sh` runs it on every+SessionStart.++It used to be an unconditional overwrite, and that was a defect in its own right. On one+machine the installed copy was the current reservation-schema guard while the shipped+copy was still the old count-schema one, so every session start tried to **downgrade a+security guard** — silently, because setup.sh called it with `|| true` and stderr on+`/dev/null`. It fails closed, so nothing leaked, but the two-phase commit for+MCP-proxy-routed sends stops working and approvals are never redeemed. The only thing+holding it back was a hand-set `chflags uchg` on the installed file, and 304 leaked+`.tmp.<pid>` files were the evidence that the script had been failing unseen for weeks.++So the sync is now a guarded, one-directional upgrade:++- Both files carry a `// outbound-guard-schema: <id>` marker. Unmarked files are placed+ by content (delegating guard vs. own count store).+- An installed copy whose schema cannot be placed is **refused**, on stderr, non-zero.+- An installed copy newer than the source is refused: sync forward only.+- `--force` / `OUTBOUND_GUARD_SYNC_FORCE=1` is the deliberate override for a repair.+- A failed sync cleans up its own temp file (`trap ... EXIT`).++Bump the marker whenever the contract with `outbound_guard.py` changes, and give the new+id a rank in `schema_rank()`.+## Arming```@@ -107,7 +145,8 @@ gog --access-token "$(gog-sa-token [email protected] send)" -a [email protected]## Tests```-bash claude-ops/tests/outbound-guard/test-shared-guard.sh # cross-language agreement+bash claude-ops/tests/outbound-guard/test-shared-guard.sh # Node -> Python delegation contract+bash claude-ops/tests/outbound-guard/test-installed-copy-sync.sh # sync refuses downgradespython3 claude-ops/tests/outbound-guard/test-hook-matrix.py # block/pass per send pathpython3 claude-ops/tests/outbound-guard/test-broken-alias.py # broken alias outranks approval```diff --git a/claude-ops/scripts/outbound-guard/outbound-guard.mjs b/claude-ops/scripts/outbound-guard/outbound-guard.mjsindex 06cc3ccf..a3dc0cf4 100644--- a/claude-ops/scripts/outbound-guard/outbound-guard.mjs+++ b/claude-ops/scripts/outbound-guard/outbound-guard.mjs@@ -1,103 +1,155 @@-// Node side of the shared approval store. Reads and writes exactly the file managed by-// outbound_guard.py, with the same rules.+// Node side of the shared approval store.//-// Identical rather than "roughly the same" on purpose: if the two layers identify a-// message differently, one message either pays twice or not at all. The fingerprint is-// therefore literally the same computation: sha256(recipient|body), body normalised on-// whitespace and truncated to 400 chars, first 32 hex chars.+// Until 2026-09-10 this file kept its OWN copy of the store logic and read two+// fields -- `remaining` (a count) and `spent` (a fingerprint map) -- that the+// Python side stopped writing on 2026-09-02. `mint()` writes+// {minted, ttl, approved, inflight}. So `Number(d.remaining ?? 0)` was 0 and+// `spent` was {} on every single call, and this guard refused EVERY message Sam+// had actually approved. The only sends that got through did so because+// read() returned null and the legacy /tmp/.claude-send-ok fallback fired.+//+// The fingerprint had drifted too: this file collapsed all whitespace and+// truncated the body to 400 chars, while outbound_guard.py hashes the full body+// with a narrow per-line rstrip. Two normalisers means two different messages,+// so a match was impossible even with the right field names.+//+// Rather than re-implement the store a third time and wait for the next drift,+// the decision is now DELEGATED to outbound_guard.py itself. That module owns+// the lock, the approved set, the in-flight window, the permanent ledger and the+// consent audit line. One implementation, one answer, no twin to keep in sync.+//+// The payload goes over stdin, never argv, so a body containing quotes or+// newlines cannot alter the command.+// SCHEMA MARKER. sync-installed-copy.sh reads this line out of both the repo+// source and the installed copy and refuses to overwrite a copy whose schema it+// cannot place. Bump it whenever the contract with outbound_guard.py changes.+// outbound-guard-schema: reservation-v2import crypto from 'node:crypto';import fs from 'node:fs';+import os from 'node:os';+import { spawnSync } from 'node:child_process';-export const STATE = '/tmp/.claude-outbound-guard.json';+export const SCHEMA = 'reservation-v2';+export const STATE = process.env.OUTBOUND_GUARD_STATE || '/tmp/.claude-outbound-guard.json';export const SPENT_WINDOW_SEC = 120;const LEGACY_SINGLE = '/tmp/.claude-send-ok';const LEGACY_SINGLE_TTL_SEC = 120;+const GUARD_PY = process.env.OUTBOUND_GUARD_PY || `${os.homedir()}/.claude/scripts/hooks/outbound_guard.py`;+const PYTHON = process.env.OUTBOUND_GUARD_PYTHON || 'python3';++// Same computation as outbound_guard.py:fingerprint(). Kept here only so callers+// can label a message; the allow/deny decision uses the Python one, so the two+// can no longer disagree about which message is which.export function fingerprint(recipient, body) {const r = String(recipient ?? '').trim().toLowerCase();const b = String(body ?? '')- .split(/\s+/)- .filter(Boolean)- .join(' ')- .slice(0, 400);+ .split('\n')+ .map((ln) => ln.replace(/\s+$/, ''))+ .join('\n')+ .replace(/\n+$/, '');return crypto.createHash('sha256').update(`${r}|${b}`).digest('hex').slice(0, 32);}-function read() {- let d;- try {- d = JSON.parse(fs.readFileSync(STATE, 'utf8'));- } catch {- return null;- }- if (!d || typeof d !== 'object') return null;- const now = Date.now() / 1000;- if (now - (d.minted ?? 0) > (d.ttl ?? 0)) {- clear();- return null;- }- return d;-}+const BRIDGE = `+import json, sys, importlib.util+path, fn = sys.argv[1], sys.argv[2]+spec = importlib.util.spec_from_file_location("outbound_guard", path)+mod = importlib.util.module_from_spec(spec)+spec.loader.exec_module(mod)+payload = json.load(sys.stdin)+if fn == "consume":+ out = {"ok": bool(mod.consume(payload.get("recipient", ""), payload.get("body", ""),+ payload.get("session_id", ""), payload.get("tool", "")))}+elif fn == "peek":+ n, left = mod.peek()+ out = {"remaining": int(n), "validForSec": int(left)}+elif fn == "claim":+ # The (recipient, body) is derived HERE, by the same function the PreToolUse+ # gate uses, from the same arguments object. Deriving it on the Node side+ # would be a second implementation of the one thing that must not differ.+ r = payload.get("recipient", "")+ b = payload.get("body", "")+ args = payload.get("args")+ if isinstance(args, dict) and args:+ r2, b2 = mod.identify_args(args)+ if r2 or b2:+ r, b = r2, b2+ out = {"ok": bool(mod.claim_reservation(r, b, payload.get("guard", ""),+ payload.get("session_id", ""),+ payload.get("tool", "")))}+else:+ raise SystemExit(2)+sys.stdout.write(json.dumps(out))+`;-function write(d) {- const tmp = `${STATE}.tmp`;+// Null means "could not reach the guard at all" -- distinct from a guard that+// answered "no". Only the first case may fall back to anything.+function callGuard(fn, payload) {try {- fs.writeFileSync(tmp, JSON.stringify(d), { mode: 0o600 });- fs.renameSync(tmp, STATE);+ if (!fs.existsSync(GUARD_PY)) return null;+ const r = spawnSync(PYTHON, ['-c', BRIDGE, GUARD_PY, fn], {+ input: JSON.stringify(payload),+ encoding: 'utf8',+ timeout: 15000,+ });+ if (r.error || r.status !== 0) return null;+ const parsed = JSON.parse(r.stdout);+ return parsed && typeof parsed === 'object' ? parsed : null;} catch {- /* best effort, same as the Python side */+ return null;}}-function clear() {- for (const p of [STATE, `${STATE}.tmp`]) {- try {- fs.unlinkSync(p);- } catch {- /* already gone */- }- }+export function peek() {+ const out = callGuard('peek', {});+ if (!out) return { remaining: 0, validForSec: 0 };+ return {+ remaining: Number(out.remaining ?? 0),+ validForSec: Math.max(0, Number(out.validForSec ?? 0)),+ };}-export function peek() {- const d = read();- if (!d) return { remaining: 0, validForSec: 0 };- const left = (d.ttl ?? 0) - (Date.now() / 1000 - (d.minted ?? 0));- return { remaining: Number(d.remaining ?? 0), validForSec: Math.max(0, Math.floor(left)) };+// True when Sam's own outbound gate ALREADY approved this exact message and is+// holding a live reservation for it -- i.e. this guard is the second lock on one+// call, not the first lock on a new one. Nothing is minted and nothing is spent+// here; the reservation is still committed or released by the PostToolUse step.+//+// Fails closed on every uncertainty. If the Python guard cannot be reached at+// all we return false, with NO legacy-token fallback: consume() may fall back+// because a bare token is Sam's deliberate escape hatch for a send, but "gate 1+// already approved this" is a claim about state, and a claim about state we+// cannot read is not a claim we may make.+export function claimReservation({ args, recipient = '', body = '', guard = '', sessionId = '', tool = '' } = {}) {+ if (!guard) return false;+ const out = callGuard('claim', {+ args: args && typeof args === 'object' ? args : null,+ recipient: String(recipient ?? ''),+ body: String(body ?? ''),+ guard: String(guard),+ session_id: String(sessionId ?? process.env.CLAUDE_SESSION_ID ?? ''),+ tool: String(tool ?? ''),+ });+ return out ? out.ok === true : false;}-// True when this message may go. Deducts at most one unit. The same fingerprint inside-// the window is the same message, already charged at another guard.-export function consume(recipient = '', body = '') {- const fp = fingerprint(recipient, body);- const d = read();- if (d) {- const now = Date.now() / 1000;- const spent = Object.fromEntries(Object.entries(d.spent ?? {}).filter(([, t]) => now - t < SPENT_WINDOW_SEC));- if (fp in spent) {- d.spent = spent;- write(d);- return true;- }- let remaining = Number(d.remaining ?? 0);- if (remaining > 0) {- remaining -= 1;- spent[fp] = now;- if (remaining <= 0 && Object.keys(spent).length === 0) {- clear();- } else {- d.remaining = remaining;- d.spent = spent;- write(d);- }- return true;- }- return false;- }+// True when this message may go. The Python guard decides: it checks the+// in-flight window, then the permanent ledger, then the approved set minted for+// this exact (recipient, body), spends the approval once and writes the audit+// line. `tool` reaches the ledger so a retry from a different tool is refused.+export function consume(recipient = '', body = '', opts = {}) {+ const out = callGuard('consume', {+ recipient: String(recipient ?? ''),+ body: String(body ?? ''),+ session_id: String(opts.sessionId ?? process.env.CLAUDE_SESSION_ID ?? ''),+ tool: String(opts.tool ?? ''),+ });+ if (out) return out.ok === true;- // No canonical state: fall back to the old single-use token.+ // The guard itself was unreachable (no python3, module gone, crash). Only then+ // does the old single-use token still count, and otherwise this fails closed.try {const st = fs.statSync(LEGACY_SINGLE);if (Date.now() / 1000 - st.mtimeMs / 1000 > LEGACY_SINGLE_TTL_SEC) return false;diff --git a/claude-ops/scripts/outbound-guard/sync-installed-copy.sh b/claude-ops/scripts/outbound-guard/sync-installed-copy.shindex 481639d9..5765f5ad 100755--- a/claude-ops/scripts/outbound-guard/sync-installed-copy.sh+++ b/claude-ops/scripts/outbound-guard/sync-installed-copy.sh@@ -3,18 +3,29 @@## outbound_guard.py documents that the Node side "lives at ../outbound-guard.mjs# (and, when installed, at ~/.claude/mcp-proxy/outbound-guard.mjs)" and that it-# "reads and writes this same file with the same rules". Nothing enforced that:-# there was no install step and no refresh step, so a machine either had no-# installed copy at all, or — worse — had one copied in once and never touched-# again. Every later change to outbound-guard.mjs (a new field on the state file,-# a rule change) would silently NOT reach the installed copy, so the two-# "identical" implementations the README promises would drift onto different-# schemas without either side failing loudly.+# "reads and writes this same file with the same rules". Nothing enforced that,+# so a machine either had no installed copy at all or had one copied in once and+# never touched again, drifting onto a different schema without either side+# failing loudly. This script is the refresh step.#-# This script makes the installed copy a straight, idempotent mirror of the repo-# source. It only ever OVERWRITES the installed file with the current repo-# content — there is no partial-merge logic to drift, so re-running it is always-# safe and always converges to whatever ships in this checkout.+# It used to be an unconditional overwrite, and that was the real defect: a+# security guard was replaced, on every single SessionStart, by whatever bytes+# happened to sit in the checkout, with no check that those bytes were newer or+# even compatible. On a machine whose installed copy was the current+# reservation-schema guard and whose checkout still carried the old count-schema+# one, this silently DOWNGRADED the guard. It fails closed, so nothing leaks,+# but the two-phase commit for MCP-proxy-routed sends stops working and Sam's+# approvals are never redeemed. Nothing said a word, because setup.sh called+# this with `|| true` and stderr on /dev/null.+#+# So: the sync is now a guarded, one-directional upgrade.+# * Both files carry a `// outbound-guard-schema: <id>` marker.+# * An installed copy whose schema cannot be placed is REFUSED, loudly, on+# stderr, with a non-zero exit. A file we do not understand is never+# something to overwrite on a hunch.+# * An installed copy NEWER than the source is refused too. Sync forward only.+# * Equal schemas, or a known-legacy installed copy, sync normally.+# * Override for a deliberate repair: --force / OUTBOUND_GUARD_SYNC_FORCE=1.set -euo pipefailHERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"@@ -22,16 +33,93 @@ SRC="$HERE/outbound-guard.mjs"DEST_DIR="${HOME}/.claude/mcp-proxy"DEST="$DEST_DIR/outbound-guard.mjs"+FORCE="${OUTBOUND_GUARD_SYNC_FORCE:-0}"+for arg in "$@"; do+ case "$arg" in+ --force) FORCE=1 ;;+ *) echo "sync-installed-copy: unknown argument '$arg'" >&2; exit 2 ;;+ esac+done+if [ ! -f "$SRC" ]; thenecho "sync-installed-copy: source missing at $SRC" >&2exit 1fi+# Schema of a guard file. The marker is authoritative. Unmarked files predate the+# marker, so fall back to recognising them by the one thing that defines their+# contract with outbound_guard.py: whether they delegate the decision, or keep+# their own copy of the count/spent store.+detect_schema() {+ local f="$1" m+ m="$(sed -n 's|^[[:space:]]*//[[:space:]]*outbound-guard-schema:[[:space:]]*\([A-Za-z0-9._-]\{1,\}\).*$|\1|p' "$f" | head -1)"+ if [ -n "$m" ]; then printf '%s\n' "$m"; return 0; fi+ if grep -q 'claimReservation' "$f" && grep -q 'OUTBOUND_GUARD_PY\|outbound_guard\.py' "$f"; then+ printf 'reservation-unversioned\n'; return 0+ fi+ if grep -q 'd\.remaining\|remaining = Number' "$f" && grep -q 'SPENT_WINDOW_SEC' "$f"; then+ printf 'count-legacy\n'; return 0+ fi+ printf 'unknown\n'+}++# Rank orders the known schemas so the sync can only ever move forward. An+# unknown schema has no rank on purpose: it is refused, not compared. Versioned+# reservation schemas rank by their own number, so a future reservation-v3 on+# disk is recognised as NEWER by a v2 checkout rather than mistaken for garbage.+schema_rank() {+ case "$1" in+ count-legacy) printf '1\n' ;;+ reservation-unversioned) printf '2\n' ;;+ reservation-v[0-9]*) printf '%s\n' "$(( 100 + ${1#reservation-v} ))" ;;+ *) printf '0\n' ;;+ esac+}++SRC_SCHEMA="$(detect_schema "$SRC")"+SRC_RANK="$(schema_rank "$SRC_SCHEMA")"+if [ "$SRC_RANK" = "0" ]; then+ echo "sync-installed-copy: REFUSED — repo source $SRC has an unrecognised schema ('$SRC_SCHEMA')." >&2+ echo " Add a '// outbound-guard-schema: <id>' marker and give it a rank in schema_rank()." >&2+ exit 3+fi++if [ -f "$DEST" ]; then+ DEST_SCHEMA="$(detect_schema "$DEST")"+ DEST_RANK="$(schema_rank "$DEST_SCHEMA")"++ if [ "$DEST_RANK" = "0" ] && [ "$FORCE" != "1" ]; then+ echo "sync-installed-copy: REFUSED — installed copy has an unrecognised schema." >&2+ echo " installed: $DEST (schema '$DEST_SCHEMA')" >&2+ echo " source: $SRC (schema '$SRC_SCHEMA')" >&2+ echo " Overwriting a guard this script cannot identify risks downgrading a" >&2+ echo " security gate. Inspect the installed file. If replacing it is correct," >&2+ echo " re-run with --force (or OUTBOUND_GUARD_SYNC_FORCE=1)." >&2+ exit 4+ fi++ if [ "$DEST_RANK" -gt "$SRC_RANK" ] && [ "$FORCE" != "1" ]; then+ echo "sync-installed-copy: REFUSED — installed copy is newer than the source." >&2+ echo " installed: $DEST (schema '$DEST_SCHEMA')" >&2+ echo " source: $SRC (schema '$SRC_SCHEMA')" >&2+ echo " Syncing would DOWNGRADE the outbound guard. Update the checkout" >&2+ echo " instead; use --force only to deliberately roll back." >&2+ exit 5+ fi++ if cmp -s "$SRC" "$DEST"; then+ echo "outbound-guard: installed copy already current ($DEST_SCHEMA)"+ exit 0+ fi+fi+mkdir -p "$DEST_DIR"# Copy-then-rename: never leaves a half-written file at $DEST for a proxy-# process to read mid-write.+# process to read mid-write. The trap matters — 304 leaked .tmp.<pid> files on+# one machine were the first visible symptom of this script failing in the dark.tmp="$DEST.tmp.$$"+trap 'rm -f "$tmp"' EXITcp "$SRC" "$tmp"mv "$tmp" "$DEST"-echo "outbound-guard: synced installed copy -> $DEST"+echo "outbound-guard: synced installed copy -> $DEST ($SRC_SCHEMA)"diff --git a/claude-ops/scripts/setup.sh b/claude-ops/scripts/setup.shindex 73507a74..b4153c8b 100755--- a/claude-ops/scripts/setup.sh+++ b/claude-ops/scripts/setup.sh@@ -47,11 +47,20 @@ fi# ─── Keep the installed outbound-guard Node twin current ───────────# outbound_guard.py documents an installed copy at ~/.claude/mcp-proxy/outbound-guard.mjs-# that shares its state file and rules. Without a refresh step that copy silently drifts-# onto an old schema every time outbound-guard.mjs changes in the repo. Re-run on every-# session start; the sync script is an idempotent overwrite so this is always safe.-if [ -f "$PLUGIN_ROOT/scripts/outbound-guard/sync-installed-copy.sh" ]; then- bash "$PLUGIN_ROOT/scripts/outbound-guard/sync-installed-copy.sh" >/dev/null 2>&1 || true+# that shares its state file and rules. Without a refresh step that copy drifts onto an+# old schema every time outbound-guard.mjs changes in the repo.+#+# The sync is no longer an unconditional overwrite: it refuses to replace an installed+# guard whose schema it cannot place, or one newer than the checkout. `|| true` with+# stderr on /dev/null hid exactly that refusal, which is how a silent downgrade of a+# security guard became possible. A refusal must not abort session start, but it must be+# SEEN, so only stdout is discarded and the diagnosis is printed.+SYNC_GUARD="$PLUGIN_ROOT/scripts/outbound-guard/sync-installed-copy.sh"+if [ -f "$SYNC_GUARD" ]; then+ if ! SYNC_ERR="$(bash "$SYNC_GUARD" 2>&1 >/dev/null)"; then+ echo " ✗ ops: outbound-guard sync refused — installed copy left untouched" >&2+ [ -n "$SYNC_ERR" ] && printf '%s\n' "$SYNC_ERR" >&2+ fifi# ─── Report only problems ───────────────────────────────────────────diff --git a/claude-ops/tests/outbound-guard/test-installed-copy-sync.sh b/claude-ops/tests/outbound-guard/test-installed-copy-sync.shindex 645290df..06553d92 100755--- a/claude-ops/tests/outbound-guard/test-installed-copy-sync.sh+++ b/claude-ops/tests/outbound-guard/test-installed-copy-sync.sh@@ -1,15 +1,18 @@#!/usr/bin/env bash-# Defect: outbound_guard.py's docstring claims the Node twin is "installed at-# ~/.claude/mcp-proxy/outbound-guard.mjs" and "reads and writes this same file with-# the same rules" as the repo copy. Nothing in the repo ever creates or refreshes that-# installed copy, so on a real machine the claim is either false (no file at all) or,-# worse, true-but-stale: a copy installed once and never updated again drifts onto an-# outdated schema every time outbound-guard.mjs changes in the repo, silently-# disagreeing with outbound_guard.py about state-file shape.+# Defect: sync-installed-copy.sh overwrote ~/.claude/mcp-proxy/outbound-guard.mjs+# unconditionally, on every SessionStart, with whatever outbound-guard.mjs the checkout+# carried — no check that those bytes were newer or even compatible, stdout and stderr on+# /dev/null, `|| true` in setup.sh. On a machine whose installed guard was the current+# reservation-schema version and whose plugin copy was still the old count-schema one,+# that silently DOWNGRADED a security guard. It fails closed, so nothing leaks, but the+# two-phase commit for MCP-proxy-routed sends stops working and approvals are never+# redeemed. The only thing that stopped it on the affected machine was a hand-set `uchg`+# flag, and 304 leaked .tmp.<pid> files were the evidence that the script had been+# failing in the dark for a long time.#-# This test proves scripts/outbound-guard/sync-installed-copy.sh keeps that installed-# copy byte-identical to the repo source, including refreshing a copy that was already-# there under an old (stale) schema.+# This test proves the sync is now a guarded, one-directional upgrade: it still refreshes+# a stale copy, it REFUSES an installed copy whose schema it cannot place, it refuses to+# move backwards, and it never leaves a .tmp.* file behind when it fails.## Run: bash claude-ops/tests/outbound-guard/test-installed-copy-sync.shset -u@@ -19,35 +22,86 @@ SYNC="$SRC/sync-installed-copy.sh"MJS="$SRC/outbound-guard.mjs"fail=0-chk(){ if [ "$2" = "$3" ]; then echo " ok $1"; else echo " FAIL $1: got '$2', expected '$3'"; fail=$((fail+1)); fi; }+ok(){ echo " ok $1"; }+bad(){ echo " FAIL $1"; fail=$((fail+1)); }+chk(){ if [ "$2" = "$3" ]; then ok "$1"; else bad "$1: got '$2', expected '$3'"; fi; }TMPHOME="$(mktemp -d)"trap 'rm -rf "$TMPHOME"' EXIT+INSTALLED="$TMPHOME/.claude/mcp-proxy/outbound-guard.mjs"+no_tmp(){ [ -z "$(find "$TMPHOME/.claude/mcp-proxy" -name 'outbound-guard.mjs.tmp.*' 2>/dev/null)" ]; }echo "1. sync script exists and is executable"-if [ -x "$SYNC" ]; then echo " ok sync script present"; else echo " FAIL sync script missing at $SYNC"; fail=$((fail+1)); fi+if [ -x "$SYNC" ]; then ok "sync script present"; else bad "sync script missing at $SYNC"; fi-echo "2. fresh install: no installed copy yet -> sync creates one matching the repo"-HOME="$TMPHOME" bash "$SYNC" >/dev/null 2>&1-INSTALLED="$TMPHOME/.claude/mcp-proxy/outbound-guard.mjs"-if [ -f "$INSTALLED" ]; then echo " ok installed copy created"; else echo " FAIL installed copy not created at $INSTALLED"; fail=$((fail+1)); fi-if diff -q "$MJS" "$INSTALLED" >/dev/null 2>&1; then- echo " ok installed copy byte-identical to repo"+echo "2. the shipped source carries a recognised schema marker"+marker="$(sed -n 's|^[[:space:]]*//[[:space:]]*outbound-guard-schema:[[:space:]]*\([A-Za-z0-9._-]\{1,\}\).*$|\1|p' "$MJS" | head -1)"+if [ -n "$marker" ]; then ok "source schema marker: $marker"; else bad "source has no // outbound-guard-schema: marker"; fi++echo "3. the shipped source is the delegating guard, not the old count store"+if grep -q 'claimReservation' "$MJS" && grep -q 'outbound_guard\.py' "$MJS"; then+ ok "source exposes claimReservation() and delegates to outbound_guard.py"else- echo " FAIL installed copy differs from repo source"- fail=$((fail+1))+ bad "source is not the current reservation-schema guard"fi--echo "3. stale copy: an old schema on disk must be refreshed, not left alone"-echo "// old, pre-consolidation schema — must NOT survive a sync" > "$INSTALLED"-HOME="$TMPHOME" bash "$SYNC" >/dev/null 2>&1-if diff -q "$MJS" "$INSTALLED" >/dev/null 2>&1; then- echo " ok stale installed copy refreshed to current schema"+if grep -v '^[[:space:]]*//' "$MJS" | grep -q 'd\.remaining'; then+ bad "source code still reads the dead d.remaining field"else- echo " FAIL stale installed copy was NOT refreshed (still on old schema)"- fail=$((fail+1))+ ok "no live read of d.remaining (the field outbound_guard.py stopped writing)"fi+echo "4. fresh install: no installed copy yet -> sync creates one matching the repo"+HOME="$TMPHOME" bash "$SYNC" >/dev/null 2>&1+chk "exit 0 on fresh install" "$?" "0"+if [ -f "$INSTALLED" ]; then ok "installed copy created"; else bad "installed copy not created at $INSTALLED"; fi+if diff -q "$MJS" "$INSTALLED" >/dev/null 2>&1; then ok "installed copy byte-identical to repo"; else bad "installed copy differs from repo source"; fi+if no_tmp; then ok "no .tmp.* left behind"; else bad ".tmp.* leaked"; fi++echo "5. re-run is idempotent and says so"+out="$(HOME="$TMPHOME" bash "$SYNC" 2>&1)"; rc=$?+chk "exit 0 on re-run" "$rc" "0"+case "$out" in *"already current"*) ok "reports already current" ;; *) bad "expected 'already current', got: $out" ;; esac++echo "6. stale legacy copy: an older known schema is refreshed, not left alone"+cat > "$INSTALLED" <<'OLD'+// old pre-consolidation guard+export const SPENT_WINDOW_SEC = 120;+export function consume(){ const d = read(); let remaining = Number(d.remaining ?? 0); return remaining > 0; }+OLD+out="$(HOME="$TMPHOME" bash "$SYNC" 2>&1)"; rc=$?+chk "exit 0 syncing over a legacy copy" "$rc" "0"+if diff -q "$MJS" "$INSTALLED" >/dev/null 2>&1; then ok "legacy copy upgraded to current schema"; else bad "legacy copy was NOT refreshed"; fi++echo "7. UNRECOGNISED installed schema is refused, loudly, and left untouched"+printf '// hand-edited guard nobody can place\nexport function mystery(){ return true; }\n' > "$INSTALLED"+before="$(cat "$INSTALLED")"+err="$(HOME="$TMPHOME" bash "$SYNC" 2>&1 >/dev/null)"; rc=$?+if [ "$rc" -ne 0 ]; then ok "non-zero exit ($rc)"; else bad "refusal must not exit 0"; fi+case "$err" in *REFUSED*unrecognised*|*unrecognised*REFUSED*) ok "stderr names the refusal and the reason" ;; *) bad "stderr unclear: $err" ;; esac+chk "installed file untouched" "$(cat "$INSTALLED")" "$before"+if no_tmp; then ok "no .tmp.* left behind by the refusal"; else bad ".tmp.* leaked on refusal"; fi++echo "8. --force is the deliberate escape hatch for case 7"+HOME="$TMPHOME" bash "$SYNC" --force >/dev/null 2>&1+chk "exit 0 with --force" "$?" "0"+if diff -q "$MJS" "$INSTALLED" >/dev/null 2>&1; then ok "--force replaced the unknown copy"; else bad "--force did not sync"; fi++echo "9. a NEWER installed copy is refused: the sync only moves forward"+sed 's|// outbound-guard-schema: .*|// outbound-guard-schema: reservation-v99|' "$MJS" > "$INSTALLED"+before="$(cat "$INSTALLED")"+err="$(HOME="$TMPHOME" bash "$SYNC" 2>&1 >/dev/null)"; rc=$?+if [ "$rc" -ne 0 ]; then ok "non-zero exit ($rc)"; else bad "downgrade must not exit 0"; fi+case "$err" in *DOWNGRADE*|*newer*) ok "stderr says it would downgrade" ;; *) bad "stderr unclear: $err" ;; esac+chk "newer installed file untouched" "$(cat "$INSTALLED")" "$before"++echo "10. a failed sync leaves no .tmp.* behind (trap on EXIT)"+rm -f "$INSTALLED"+SHIM="$TMPHOME/shim"; mkdir -p "$SHIM"+printf '#!/bin/sh\nexit 1\n' > "$SHIM/mv"; chmod +x "$SHIM/mv"+HOME="$TMPHOME" PATH="$SHIM:$PATH" bash "$SYNC" >/dev/null 2>&1; rc=$?+if [ "$rc" -ne 0 ]; then ok "sync failed as arranged ($rc)"; else bad "mv shim did not make the sync fail"; fi+if no_tmp; then ok "no .tmp.* left behind after a mid-sync failure"; else bad ".tmp.* leaked: $(find "$TMPHOME/.claude/mcp-proxy" -name 'outbound-guard.mjs.tmp.*')"; fi+echo[ "$fail" -eq 0 ] && echo "ALL GOOD" || echo "$fail FAIL"exit $faildiff --git a/claude-ops/tests/outbound-guard/test-shared-guard.sh b/claude-ops/tests/outbound-guard/test-shared-guard.shindex 13d9c80c..acda409f 100755--- a/claude-ops/tests/outbound-guard/test-shared-guard.sh+++ b/claude-ops/tests/outbound-guard/test-shared-guard.sh@@ -1,56 +1,168 @@#!/bin/bash-# Checks that the Python and Node sides see the same approval store.+# Checks the contract between the Node twin and the Python guard it delegates to.+#+# This test used to assert that outbound-guard.mjs and the bundled outbound_guard.py+# agreed about a count-based store: mint 3, spend 3, deny the 4th. It passed because BOTH+# files were on that schema. It could not catch the actual failure, which was the two+# implementations drifting apart, because it only ever compared them with each other.+#+# outbound-guard.mjs no longer implements the store. It hands every decision to+# outbound_guard.py over stdin (OUTBOUND_GUARD_PY), precisely so there is one+# implementation of the approved set, the in-flight window and the ledger instead of two+# to keep in step. So the thing to test is the contract, not a second copy of the logic:+# does the Node side pass the message through unchanged, does it answer what the guard+# answered, and does it fail CLOSED when the guard cannot be reached.+#+# The delegate here is a stub, on purpose. A stub pins the contract without dragging in+# the real guard's locking, ledger and audit file.## Run: bash claude-ops/tests/outbound-guard/test-shared-guard.sh-# Requires python3 and node. Only touches /tmp/.claude-outbound-guard.json.+# Requires python3 and node. Touches /tmp/.claude-send-ok (legacy token path).set -uHERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"SRC="$(cd "$HERE/../../scripts/outbound-guard" && pwd)"-PY="$SRC/outbound_guard.py"MJS="$SRC/outbound-guard.mjs"-S=/tmp/.claude-outbound-guard.json+REPO_PY="$SRC/outbound_guard.py"+TOKEN=/tmp/.claude-send-ok+fail=0-chk(){ if [ "$2" = "$3" ]; then echo " ok $1"; else echo " FAIL $1: got '$2', expected '$3'"; fail=$((fail+1)); fi; }-left(){ python3 "$PY" peek | sed 's/.*remaining=\([0-9]*\).*/\1/'; }--rm -f "$S" /tmp/.claude-send-ok--echo "1. fingerprint identical in both languages"-A=$(python3 -c "import sys;sys.path.insert(0,'$SRC');import outbound_guard as g;print(g.fingerprint('[email protected]','Hallo daar\n\nSam'))")-B=$(node --input-type=module -e "import {fingerprint} from '$MJS'; console.log(fingerprint('[email protected]','Hallo daar\n\nSam'))")-chk "same fingerprint" "$A" "$B"--echo "2. mint 3, then three different messages"-python3 "$PY" mint 3 900 >/dev/null-python3 "$PY" consume "[email protected]" "een" >/dev/null; r1=$?-python3 "$PY" consume "[email protected]" "twee" >/dev/null; r2=$?-python3 "$PY" consume "[email protected]" "drie" >/dev/null; r3=$?-python3 "$PY" consume "[email protected]" "vier" >/dev/null; r4=$?-chk "1st allowed" "$r1" "0"-chk "2nd allowed" "$r2" "0"-chk "3rd allowed" "$r3" "0"-chk "4th denied" "$r4" "1"--echo "3. same message across two layers costs one unit"-rm -f "$S"; python3 "$PY" mint 2 900 >/dev/null-python3 "$PY" consume "[email protected]" "zelfde tekst" >/dev/null-L1=$(left)-node --input-type=module -e "import {consume} from '$MJS'; process.exit(consume('[email protected]','zelfde tekst')?0:1)"; rn=$?-L2=$(left)-chk "node allows" "$rn" "0"-chk "counter after python" "$L1" "1"-chk "counter unchanged" "$L2" "1"--echo "4. node does deduct for a different message"-node --input-type=module -e "import {consume} from '$MJS'; process.exit(consume('[email protected]','ander bericht')?0:1)" >/dev/null; rn2=$?-chk "different message allowed" "$rn2" "0"-chk "counter now 0" "$(left)" "0"--echo "5. empty means deny"-python3 "$PY" consume "[email protected]" "nog een" >/dev/null; r5=$?-chk "denied at zero" "$r5" "1"--rm -f "$S" /tmp/.claude-send-ok+ok(){ echo " ok $1"; }+bad(){ echo " FAIL $1"; fail=$((fail+1)); }+chk(){ if [ "$2" = "$3" ]; then ok "$1"; else bad "$1: got '$2', expected '$3'"; fi; }++TD="$(mktemp -d)"+trap 'rm -rf "$TD"; rm -f "$TOKEN"' EXIT+STUB="$TD/stub_guard.py"+LOG="$TD/calls.jsonl"++cat > "$STUB" <<'PYEOF'+"""Stub delegate. Answers yes or no on command and records what it was asked."""+import hashlib, json, os++SPENT_WINDOW_SEC = 120+_ANSWER = os.environ.get("STUB_ANSWER", "1") == "1"+_LOG = os.environ.get("STUB_LOG", "")++if os.environ.get("STUB_MODE") == "crash":+ raise RuntimeError("stub guard refuses to load")+++def _log(fn, **kw):+ if _LOG:+ with open(_LOG, "a") as fh:+ fh.write(json.dumps({"fn": fn, **kw}) + "\n")+++def fingerprint(recipient: str, body: str) -> str:+ r = str(recipient or "").strip().lower()+ b = "\n".join(ln.rstrip() for ln in str(body or "").split("\n")).rstrip("\n")+ return hashlib.sha256(f"{r}|{b}".encode()).hexdigest()[:32]+++def identify_args(tool_input: dict):+ return str(tool_input.get("to", "")), str(tool_input.get("body", ""))+++def peek():+ return (2, 300)+++def consume(recipient="", body="", session_id="", tool=""):+ _log("consume", recipient=recipient, body=body, session_id=session_id, tool=tool)+ return _ANSWER+++def claim_reservation(recipient="", body="", guard="", session_id="", tool=""):+ _log("claim", recipient=recipient, body=body, guard=guard,+ session_id=session_id, tool=tool)+ return _ANSWER+PYEOF++node_consume(){ # $1 recipient $2 body+ node --input-type=module -e "import {consume} from '$MJS'; process.exit(consume(process.argv[1], process.argv[2], {tool:'Bash', sessionId:'s-1'})?0:1)" -- "$1" "$2"+}+node_claim(){ # stdin: JSON opts+ node --input-type=module -e "import {claimReservation} from '$MJS'; let b=''; process.stdin.on('data',d=>b+=d).on('end',()=>process.exit(claimReservation(JSON.parse(b))?0:1))"+}++echo "1. the Node fingerprint is the per-line rstrip one, byte for byte"+# The drifted version collapsed ALL whitespace and truncated to 400 chars. A body with+# trailing spaces, interior blank lines and more than 400 chars separates the two.+B="$(printf 'Hallo daar \n\nSam\n')$(python3 -c 'print("x"*500)')"+export B+FP_PY=$(python3 -c "import sys,os;sys.path.insert(0,'$TD');import stub_guard as g;print(g.fingerprint('[email protected] ',os.environ['B']))")+FP_JS=$(node --input-type=module -e "import {fingerprint} from '$MJS'; console.log(fingerprint('[email protected] ', process.env.B))")+chk "same fingerprint in both languages" "$FP_PY" "$FP_JS"+OLD=$(node --input-type=module -e "+import crypto from 'node:crypto';+const r='[email protected]', b=process.env.B.split(/\s+/).filter(Boolean).join(' ').slice(0,400);+console.log(crypto.createHash('sha256').update(r+'|'+b).digest('hex').slice(0,32));")+if [ "$FP_JS" = "$OLD" ]; then bad "still using the drifted collapse+truncate normaliser"; else ok "differs from the drifted collapse+truncate normaliser"; fi++echo "2. a yes from the guard is a yes, and the message reaches it unchanged"+rm -f "$LOG" "$TOKEN"+OUTBOUND_GUARD_PY="$STUB" STUB_ANSWER=1 STUB_LOG="$LOG" node_consume "[email protected]" "$(printf 'regel een\nregel twee')"+chk "consume allowed" "$?" "0"+got_r=$(python3 -c "import json,sys;print(json.loads(open('$LOG').readline())['recipient'])" 2>/dev/null || echo MISSING)+got_b=$(python3 -c "import json;print(repr(json.loads(open('$LOG').readline())['body']))" 2>/dev/null || echo MISSING)+got_t=$(python3 -c "import json;print(json.loads(open('$LOG').readline())['tool'])" 2>/dev/null || echo MISSING)+chk "recipient passed through" "$got_r" "[email protected]"+chk "body passed through with its newline" "$got_b" "'regel een\nregel twee'"+chk "tool reaches the ledger" "$got_t" "Bash"++echo "3. a no from the guard is a no, and a fresh legacy token does NOT rescue it"+touch "$TOKEN"+OUTBOUND_GUARD_PY="$STUB" STUB_ANSWER=0 node_consume "[email protected]" "geweigerd"+chk "consume denied" "$?" "1"+if [ -f "$TOKEN" ]; then ok "legacy token untouched by a refusal"; else bad "refusal ate the legacy token"; fi++echo "4. guard unreachable: the legacy token is the ONLY fallback, once"+rm -f "$TOKEN"; touch "$TOKEN"+OUTBOUND_GUARD_PY="$TD/does-not-exist.py" node_consume "[email protected]" "via token"+chk "allowed on a fresh token" "$?" "0"+if [ -f "$TOKEN" ]; then bad "token not spent"; else ok "token spent (single use)"; fi+OUTBOUND_GUARD_PY="$TD/does-not-exist.py" node_consume "[email protected]" "via token"+chk "second send denied" "$?" "1"++echo "5. guard crashes on load: treated as unreachable, and deny without a token"+rm -f "$TOKEN"+OUTBOUND_GUARD_PY="$STUB" STUB_MODE=crash node_consume "[email protected]" "crash"+chk "denied when the guard cannot load and no token exists" "$?" "1"++echo "6. claimReservation fails closed on every uncertainty"+printf '{"recipient":"[email protected]","body":"b","sessionId":"s-1","tool":"Bash"}' | OUTBOUND_GUARD_PY="$STUB" STUB_ANSWER=1 node_claim+chk "no guard name -> false" "$?" "1"+printf '{"guard":"mcp-proxy","recipient":"[email protected]","body":"b"}' | OUTBOUND_GUARD_PY="$STUB" STUB_ANSWER=1 node_claim+chk "guard says yes -> true" "$?" "0"+printf '{"guard":"mcp-proxy","recipient":"[email protected]","body":"b"}' | OUTBOUND_GUARD_PY="$STUB" STUB_ANSWER=0 node_claim+chk "guard says no -> false" "$?" "1"+touch "$TOKEN"+printf '{"guard":"mcp-proxy","recipient":"[email protected]","body":"b"}' | OUTBOUND_GUARD_PY="$TD/does-not-exist.py" node_claim+chk "guard unreachable -> false even with a fresh token" "$?" "1"+if [ -f "$TOKEN" ]; then ok "claim never spends the legacy token"; else bad "claim spent the legacy token"; fi+rm -f "$TOKEN"++echo "7. the reservation is identified from the tool arguments by the GUARD, not by Node"+rm -f "$LOG"+printf '{"guard":"mcp-proxy","args":{"to":"[email protected]","body":"uit args"},"recipient":"[email protected]","body":"verkeerd"}' \+ | OUTBOUND_GUARD_PY="$STUB" STUB_ANSWER=1 STUB_LOG="$LOG" node_claim+chk "claim allowed" "$?" "0"+got=$(python3 -c "import json;d=json.loads(open('$LOG').readline());print(d['recipient'],'|',d['body'])" 2>/dev/null || echo MISSING)+chk "identify_args() output wins over the Node-side pair" "$got" "[email protected] | uit args"++echo "8. note: the bundled outbound_guard.py is NOT yet a valid delegate"+# Informational, not a failure. The repo copy is still the retired count-based CLI+# (`mint <n> <ttl>`), while the guard the installed twin delegates to lives at+# ~/.claude/scripts/hooks/outbound_guard.py and is reservation-based. Bringing the+# bundled copy forward also means migrating `scripts/outbound-guard/ok`, which is a+# separate change; until then the Node twin delegates to the installed guard, and fails+# closed if it is absent.+if grep -q 'def claim_reservation' "$REPO_PY"; then+ echo " note bundled outbound_guard.py now exposes claim_reservation() — point test 1 at it and drop this note"+else+ echo " note bundled outbound_guard.py is still count-based; the delegate is the installed guard (see README)"+fi+echo[ "$fail" -eq 0 ] && echo "ALL GOOD" || echo "$fail FAIL"exit $fail