Python's shlex read a comment where bash read a payment
The run I recorded for switchboard goes the way I wanted. The owner of a small studio asks the desk to pay everything due by 2026-11-30, but only what matches its contract. The vendor scout quotes the contracts line by l
The run I recorded for switchboard goes the way I wanted. The owner of a small studio asks the desk to pay everything due by 2026-11-30, but only what matches its contract. The vendor scout quotes the contracts line by line: INV-1041 matches, INV-1042 bills 4 servers when the contract covers 3. The clerk tries to pay INV-1041 and the gate stops it with Approval required: A-29b39a. A person approves it with ./approve A-29b39a (in the recording, the script plays that part). A new session, told only "Continue.", reads the handoff from disk and pays once: PAY-0001.
The full run is 2 min 22 s, here as an MP4.
Before release, an adversarial review read the gate's code looking for ways past it. One of them paid INV-1042, the invoice that did not match its contract, with no approval, using one character. The agents in the demo never tried anything like this. The command came from reading the gate, not from talking to a model.
What the gate is
switchboard is a Claude Code project. CLAUDE.md is a dispatcher that routes work and never does it. Three specialists, ledger-clerk, vendor-scout and calendar-keeper, are markdown files in .claude/agents, each limited to Bash and Read. Work moves as handoffs, one JSON file each on disk, so a session that ends doesn't take the work with it. And every tool call, the dispatcher's and every subagent's, goes through one PreToolUse hook with the matcher *:
"command": "cd \"$CLAUDE_PROJECT_DIR\" && python3 -m switchboard.gate || exit 2"
switchboard/gate.py denies by default. Reads and delegation pass. Bash passes only as python3 tools/<name>.py <args>, and then rules/approvals.toml says allow, approve or deny for that script. pay is set to approve: it stops until a person runs ./approve A-xxxxxx for those exact arguments, then runs once. ./kill makes the gate deny everything. The company, the invoices and the contracts are fictional.
The line that looked careful
The gate has to know that a Bash call is one command and not three. The version that went into review tokenized it with the standard library, shlex.shlex(command, posix=True, punctuation_chars=True), and refused any token made of ;&|<>() outside quotes. punctuation_chars exists for exactly this: it hands back runs of ();<>|& as their own tokens, and shlex deals with the quoting. It felt like the boring, correct choice.
This is the command the review sent:
python3 tools/ledger.py list --due-by x#;python3 tools/pay.py INV-1042 --amount 960.00
The gate saw one call to tools/ledger.py list, which is allowed, and said allow. Bash ran two commands. So did zsh; the review checked both with bash -c and zsh -c. The second command paid INV-1042. These variants got through too:
python3 tools/ledger.py list --due-by x#&&touch PWNED
python3 tools/ledger.py list --due-by x#|sh
python3 tools/ledger.py list --due-by a#>OUT
Two grammars, one string
The shlex class has a commenters attribute, and its default is '#'. The Python docs describe it as the characters recognized as comment beginners, with everything from there to the end of the line ignored. They say nothing about where in a word the # has to sit. So in x#;python3 tools/pay.py ..., shlex reads x, meets a comment, and drops the rest of the line, the ; with it.
Bash only starts a comment at the beginning of a word. x# is a word that happens to contain a #. The ; right after it is a metacharacter, it ends the word and the command, and the payment is simply the next command.
The detail that stings: shlex.split(), the function most people call, turns comments off unless you pass comments=True. The docs say it sets commenters to the empty string. The class, which is what you reach for when you want punctuation_chars, keeps # unless you clear it yourself. I picked the more careful-looking API and got the less careful default.
Why a wrong allow is worse than no gate
Claude Code's hooks documentation says a PreToolUse "allow" skips the permission prompt. Deny and ask rules in settings still apply, and this project has none. Without the hook, that command would have gone through Claude Code's normal permission flow. With it, the gate vouched for the command and the prompt was skipped.
The script didn't save the day either. pay.py refuses a wrong amount and a second payment of the same invoice, but 960.00 is INV-1042's real amount and it had never been paid. The mismatch was with the contract, and only the scout reads contracts.
The fix: stop asking another grammar
The one-line patch was right there: set commenters to an empty string. It would have kept the actual mistake, which was asking a parser with different rules what bash would do. The next disagreement would just be a different character. A gate decides about a string; the shell acts on what that string means to the shell. The gate is exactly as good as the agreement between those two readings.
So the gate stopped trying to understand shell syntax and started refusing most of it. First, on the raw text, anything that expands or escapes even inside double quotes: $, the backtick, the backslash and every control character. With backslashes gone, a quote can only end at its matching quote character, so quote state is unambiguous and a dozen lines can track it:
# Expand or smuggle even inside double quotes: $ ` \ , control characters (newline, CR, tab, ESC...).
EXPANDS = re.compile(r"[`$\\\x00-\x1f\x7f]")
# Outside quotes these chain, pipe, redirect, glob, brace-expand, expand ~ or start a comment.
# Inside quotes they are plain text. With backslashes banned, quote state is unambiguous.
UNQUOTED = set(";&|<>()*?[]{}~#!^")
def unquoted_special(command: str) -> str | None:
"""First shell-special character outside quotes, "unbalanced" for an open quote, else None."""
quote = ""
for ch in command:
if quote:
if ch == quote:
quote = ""
elif ch in ("'", '"'):
quote = ch
elif ch in UNQUOTED:
return ch
return "unbalanced" if quote else None
Outside quotes, # is refused like ;. Inside quotes every one of those characters is text, so an agent can still write a handoff that says "Why 4 servers? [3 in contract] {line 6} ~USD 240 #INV-1042". shlex.split still runs after the scanner to build the argument list, but what reaches it is quoted text and plain words, with comments off, and the test below pins that part to bash.
The scanner is stricter than bash on purpose. A refusal costs an agent one rewrite in plainer words. An allow costs whatever the command does.
A test that asks bash
Agreement is a claim, so it gets a test. It takes allowed commands full of quotes and symbols, lets bash split them by swapping python3 for printf '%s\n', which prints one argument per line, and requires bash's argument list to equal the gate's:
@unittest.skipUnless(shutil.which("bash"), "needs bash")
def test_gate_reads_allowed_commands_the_way_bash_does(self):
allowed = [
"python3 tools/ledger.py list --due-by 2026-11-30",
'python3 tools/handoff.py open --from dispatcher --to ledger-clerk --task "a; b && c | d > e" '
"--context 'line 6: 3 servers (USD 240 each)'",
"python3 tools/handoff.py open --from dispatcher --to vendor-scout --task \"it's\"'\"quoted\"'x",
'python3 tools/handoff.py open --from dispatcher --to ledger-clerk --task "Pay INV-1041 USD 1,840.00"',
]
for cmd in allowed:
self.assertTrue(evaluate(bash(cmd), self.root).allow, cmd)
argv = shlex.split(cmd)
echo = "printf '%s\\n'" + cmd[len("python3"):]
r = subprocess.run(["bash", "-c", echo], capture_output=True, text=True, timeout=10)
self.assertEqual(r.stdout.splitlines(), argv[1:], cmd)
It's four samples and only bash, so it's no proof. But it asks the question that matters, which is whether the gate reads the string the way the shell that runs it does.
When the gate itself breaks
The second hole was quieter. The try/except wrapped only evaluate(). An import error, a payload of [] instead of an object, or an audit log the gate couldn't write made the hook exit 1 with no JSON. The import error isn't hypothetical: on my Mac, /usr/bin/python3 is 3.9.6, which has no tomllib. The hooks docs say exit code 2 blocks a PreToolUse call and any other non-zero code is a non-blocking error, so the call goes ahead. A gate that crashed was a gate that let everything through.
When the gate breaks, it has to block. Now main() starts from a deny and wraps everything from reading stdin onward, a payload that isn't a JSON object is treated as empty, and a decision the gate cannot write to its audit log is a deny. For the case where Python can't even get that far, the hook command ends in || exit 2. A test puts a fake python3 first on the PATH, a shell script that prints ModuleNotFoundError: tomllib and exits 1, and checks that the hook command exits 2.
An id is a label
Approval ids are the first 6 hex characters of a SHA-256 over the tool and every argument. Short on purpose, so a person can read A-29b39a and type it back. That's 24 bits. The gate released any call whose id had a file in granted/, without comparing what that file said had been approved.
An offline search found an argument string for INV-1042 with the same id as the INV-1041 approval. It had room to search because pay.py accepted argparse's abbreviation --amoun and strips commas from the amount, so many different strings still mean 960.00. Once INV-1041 was approved, the gate would have let that string pay INV-1042.
The fix is the comparison that should have been there from the start. Before releasing anything, the gate compares the tool and arguments stored with the approval against the call in front of it. A shared id with different arguments is a deny, and a regression test forces two calls onto the same id to prove it. The id is how a person refers to an approval. The stored arguments are what the person approved, and only those release anything.
Two smaller ones with the same shape
The real run caught one more. I had added an identity check: --by and --from must name the caller, which the gate takes from the hook payload's agent_type. It refused the calendar keeper's schedule.py free --from 2026-11-26, because there --from is a date. Identity is now checked on handoff.py only.
A second review pass caught the last one. argparse accepts abbreviated flags, so --b ledger-clerk meant --by to the script and meant nothing to the gate, which was looking for --by. Same disease as the #: the gate and the thing it guards read the same text two ways. Every script in tools/ now builds its parser with allow_abbrev=False.
What it does not cover
- The gate exists only in sessions that load this project's settings. Start Claude Code without them and there is no gate.
- Identity is whatever Claude Code puts in
agent_type. The gate trusts it. - An approval is spent when the gate lets the call through, even if the script then fails. The gate runs before the script and can't know whether money moved.
- Reads are open.
Read,GlobandGreppass for any path the tools can reach. - The scanner refuses plenty that bash would run safely.
- The scripts are stand-ins.
pay.pywrites to a local ledger and nothing real moves. - The review found three holes by reading the code. That's how many it found, which is a different number from how many there were.
The suite is 61 tests, standard library only, run in CI on Linux and macOS for Python 3.11 to 3.13, and each hole above has its own regression test.
Nobody has to jailbreak the model when they can find the one character your gate and your shell read differently.
The code, the tests and the full run are at github.com/vinimabreu/switchboard. If you find a command the gate allows and bash reads differently, I'd like to see it.
Originally published by Dev.to AI. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.