Skip to content
This repository was archived by the owner on Nov 4, 2026. It is now read-only.

Commit 1aa8851

Browse files
fix(hooks): port subst_end() into guard-main-checkout-bash (objectstack 7e40e8a03 and 338297e46) (#13320)
Fixes #13260. ## What this ports A file port of two objectstack commits into the objectui copies of the Bash-guard hook family, as the card's memo 6308641120 amends its Done-when. Six files under `.claude/hooks/`: - `guard-main-checkout-bash.sh` and its self-test: objectstack `7e40e8a03` (PR 24886, the shared `subst_end()` for a `$(…)` or backtick inside a double-quoted word, called from `strip_line_comment`, `split_segments` and `tokenize`) and `338297e46` (PR 25025, a `${…}` arm and the rule for a `'` run inside a quoted `${…}`). - `guard-shared-stash.sh` and its self-test: `338297e46` only. It carries a byte-identical `subst_end()` and delegates to it from `split_segments()`; the self-test pins that copy against the canonical. - `guard-tree-enum.sh` and its self-test: `338297e46` only. Same copy and delegation, plus the in-quote backslash branch (an escaped quote inside a double-quoted word leaves the region open) that its two siblings already had and this copy lacked. Its self-test pins `subst_end()` against the canonical and `split_segments()` against the stash guard's. - `guard-process-kill.sh` of `338297e46` has no twin in this repo and is not ported. Applied as the exact objectstack diff of each file, then localised by hand where a hunk's context differed: foreign issue references carry the `objectstack#` prefix, the provenance stamp on line 2 of all six files names `338297e46018ae96256262590a308c8be735f825`, and the stash guard's header case count was re-derived (62 = 57 `expect ` lines + 2 inline specials + 2 hatch-message assertions + 1 identity pin; the self-test run prints the same total). One cleanup beyond the diff: the stash guard's `split_segments()` carried five extra comment lines inside the function body that objectstack's copy does not, which made the new byte-identity pin between the stash and tree-enum copies fail, so they are removed to match objectstack's function text. The `subst_end()` block is byte-identical across all three hooks and equal to objectstack's copies (the same md5 for the function text, measured on all three here and on objectstack's four). The comment above it in `guard-main-checkout-bash.sh` names the two hooks here that carry the copy and says `guard-process-kill.sh` carries one in objectstack only. Not copied: any of PR 25025's description. The card's memo says one sentence of it, about `echo "${x:-'}'}" ; sed -i s/a/b/ pkg/x.ts`, is wrong about what the pre-fix hook did. This PR copies code, headers and pins only; the declared fail-open for that shape is pinned as objectstack pins it. ## Measured - Premise at `cd14d8e`: `subst_end` occurs 0 times in all three hooks and their self-tests; in objectstack `origin/main` (`2069b81c2`) it occurs 7 times in the main-checkout hook and 3 times each in the stash and tree-enum hooks. - Self-tests on head `8a0c369`, via `os-verify-lock.sh`: main-checkout `157 passed, 0 failed`; shared-stash `62 passed, 0 failed`; tree-enum `50 passed, 0 failed`; all exit 0, identity pins included. Before: 130, 50 and 38 cases, all passing. - Reverse validation, run after the commits, with the base-blob hook and the ported self-test copied to a scratch dir (tree not mutated): main-checkout `143 passed, 14 failed`; shared-stash `56 passed, 6 failed` (three false blocks, two fail-open reads, the identity pin); tree-enum `43 passed, 7 failed` (three false blocks, one fail-open read, both identity pins, plus the escaped-quote false block). All red, as predicted. - The four commands measured on the first head now answer as objectstack's copies do (same cwd, exit codes): `echo "say \"; ls *.yml; git show origin/main:x\" ok"` through the tree-enum guard 0 (was 2); `echo "he said \"x\"" ; for f in *.yml; do git show "origin/main:$f"; done` 2 (was 0); `echo "$(printf '"')" ; git stash pop` through the stash guard 2 (was 0); `echo "$(printf '"')" ; for f in *.yml; do git show "origin/main:$f"; done` through the tree-enum guard 2 (was 0). The card's two curl forms exit 0 and `echo hi > out.txt` exits 2 through the main-checkout guard. - Every pre-existing real-write, real-stash and tree-sweep case still passes unchanged. ## Remaining differences from objectstack (none is hook logic) Compared against objectstack `338297e46` with comment lines removed: the main-checkout hook differs only in the worktree-recipe help text's issue reference and the selftest's example strings. The tree-enum hook differs in one help-text word and example strings. The stash guard differs more, in text that comes from other objectstack changes, not these two commits: its printed help message (a shorter list of alternatives) and a handful of self-test cases (objectstack has extra `echo \" ; git stash ...` cases that this repo's matrix words differently). Left as they are; the escaped-quote logic itself is present and pinned here. Also comment-only: stamps, header wording, the arrow-versus-banner glyph prose, and one objectstack-only comment block above the main-checkout hook's printed worktree recipe (the recipe command is already the same here). ## Gates Derived by hand from this repo's `package.json` and workflows (objectstack's `dispatch-gates.mjs` refuses to derive this repo's families). Local, exit codes captured before any pipe, on head `8a0c369`: the three hook self-tests 0; `check-bash32-floor --self-test` 0 and the scan 0; `check-control-bytes` 0; `check:new-line-citations` 0 (0 new citations); `check-shell-escape-residue` 0; `check-changeset-presence` 0 (no changeset owed, the files are not package source); control-byte grep of the hooks clean. `check-governed-queue-guard --test` on the six files answers 3 (governed), as expected. CI check-runs read on `8a0c369`: Hook Self-Tests, Governed Surface Queue Guard, Lint, Type Check, Repo Gates, Build & E2E, Build Docs, Test (dist pins), Line Citation Gate and the three Changeset checks success; Test shards 1-16 were still in progress when read. ## Governed surface The diff is under `.claude/**`. The PR stays draft until an authorised approver's APPROVED review exists; landing is the claiming seat's after that. ## 维护者速读(草稿) **改了什么**:把 objectstack 仓里对三个 Bash 守卫钩子的两次修复搬进本仓:拦住 agent 在共享主检出里用 shell 写文件的钩子(`guard-main-checkout-bash.sh`)、拦住共享 stash 栈操作的钩子(`guard-shared-stash.sh`)、拦住"用工作区通配符去枚举 origin/main"的钩子(`guard-tree-enum.sh`),连同各自的自测,共六个文件。三个钩子共用的"引号里的 `$(…)`、反引号、`${…}` 该怎么切分"的那段函数现在逐字节一致,自测里有一条专门比对,谁改漂了就红。`guard-tree-enum.sh` 还补上了它缺的一个分支:引号里的转义引号。 **为什么改**:这三个钩子原先把引号里命令替换里的引号误读为外层字符串的结束,于是出现两类问题。误拦:只读命令被当成写入、stash 或树枚举而被拦,agent 被拦几次就会用 `OS_ALLOW_MAIN_EDITS=1`、`OS_ALLOW_STASH=1` 这类开关把整个守卫关掉。漏拦:同样的误读让真正的写入、stash、树枚举从缝里过去(实测:本仓的 stash 钩子对 `echo "$(printf '"')" ; git stash pop` 放行,objectstack 拦截)。两仓钩子本应逐例一致,objectstack 修了之后本仓落后了。 **风险与代价(含回滚)**:纯 shell 解析逻辑。三个自测由 130、50、38 条增至 157、62、50 条且全绿,新增用例在旧钩子上确实变红(逐钩子实测),原有的"必须拦住"用例没有变化,bash 3.2 下限门禁通过。已知并被 objectstack 明确接受的代价:引号内 `${…}` 里出现某些单引号写法时,钩子宁可放行(失败时开放),自测里有明文用例钉住。回滚就是整个 PR 一次 revert,钩子回到现状,不影响任何别的东西。 **席位意见**:(留空,由席位定稿) **你要做的**:这是受管面(`.claude/**`),需要获授权的批准者给一条 APPROVED 的 review,席位才能转 ready 入队。没有别的待办;`guard-process-kill.sh` 本仓没有对应的钩子,不在范围内。 --- _Generated by [Claude Code](https://claude.ai/code/session_019Bd3muSBdHUFdJiKqnsM2W)_ --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent 4c212b9 commit 1aa8851

6 files changed

Lines changed: 361 additions & 20 deletions

‎.claude/hooks/guard-main-checkout-bash.selftest.sh‎

Lines changed: 55 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
#!/usr/bin/env bash
2-
# copied from objectstack@7c2c5aedd94d7b0d94c91432bc607862e9c83c6c
2+
# copied from objectstack@338297e46018ae96256262590a308c8be735f825
33
# Self-test for guard-main-checkout-bash.sh — run it after touching that hook:
44
#
55
# .claude/hooks/guard-main-checkout-bash.selftest.sh
@@ -304,12 +304,66 @@ expect allow "$(printf "grep '#' README.md <<EOF\nsed -i 's/a/b/' pkg/x.ts\nEOF\
304304
expect block "$(printf "cat > /tmp/n.md <<'EOF'\n# it's a note, don't strip me\nEOF\nsed -i s/a/b/ pkg/x.ts\n")"
305305
expect allow "$(printf "cat > /tmp/n.md <<'EOF'\n# it's a note, don't strip me\nEOF\ngit status\n")"
306306

307+
echo "== a \$(…) inside \"…\" is its own quoting context (objectstack#24812) =="
308+
CWD="$MAIN"
309+
# The measured false blocks: a `"` inside the substitution was read as CLOSING the outer string,
310+
# so the `>` in a quoted JSON body became a redirect and the fragment after it a write target.
311+
# Pure reads — nothing is written.
312+
expect allow 'echo "a $(curl -d "{\"c\":\"x > 1\"}" http://h)"'
313+
expect allow "echo \"a \$(curl -d '{\"c\":\"x > 1\"}' http://h)\""
314+
expect allow 'echo "a `curl -d "{\"c\":\"x > 1\"}" http://h`"' # the backtick spelling
315+
# Recall is untouched: a real write beside a quoted substitution still blocks — in the same
316+
# command, behind a separator, and inside a sed -i script — and so does the card's control.
317+
expect block 'echo hi > out.txt'
318+
expect block 'echo "a $(curl -d "{\"c\":\"x > 1\"}" http://h)" > pkg/x.ts'
319+
expect block 'X="$(git rev-parse HEAD)" ; sed -i s/a/b/ pkg/x.ts'
320+
expect block 'sed -i "s/a/$(date +%F)/" pkg/x.ts'
321+
# The fail-OPEN mirror: one `"` in the body used to leave the outer string hanging, so the
322+
# separator behind it went inert and the real write rode through as text.
323+
expect block "echo \"\$(printf '\"')\" ; sed -i s/a/b/ pkg/x.ts"
324+
expect block "echo \"\$(echo \"\$(printf '\"')\")\" ; sed -i s/a/b/ pkg/x.ts" # nested
325+
# The heredoc scan reads the body the same way: the ` #` inside it is no comment, so the
326+
# introducer behind it is found and the body stays prose.
327+
expect allow "$(printf 'echo "$(echo " #")" <<EOF\nsed -i s/a/b/ pkg/x.ts\nEOF\n')"
328+
329+
echo "== a \${…} inside \"…\" is its own quoting context too (objectstack#24901) =="
330+
CWD="$MAIN"
331+
# The measured false block: the `"` that opens the default was read as CLOSING the outer string,
332+
# so `b}` became a write target. Pure reads — nothing is written. Each one exercises a different
333+
# pass: tokenisation (the first two), segmentation (the `;`), nesting both ways (the third).
334+
expect allow 'echo "${x:-"a > b"}"'
335+
expect allow 'echo "${x#"a > b"}"'
336+
expect allow 'echo "${x:-"$(printf "a > b")"}"'
337+
expect allow 'echo "${x:-"a; sed -i s/a/b/ pkg/x.ts"}"'
338+
expect allow "echo \"\${x:-'a > b'}\"" # control: no nested `"`, allowed before and after
339+
# The heredoc scan agrees: the ` #` inside the expansion is no comment, so the introducer
340+
# behind it is found and the body stays prose.
341+
expect allow "$(printf 'echo "${x:-" #"}" <<EOF\nsed -i s/a/b/ pkg/x.ts\nEOF\n')"
342+
# Recall is untouched: a write behind, beside or inside the script of a quoted expansion. A
343+
# '…' run holding no character the shells disagree on is skipped, so the write behind it stays.
344+
expect block 'sed -i "s/a/${x:-"b"}/" pkg/x.ts'
345+
expect block 'sed -i "s/a/${x}/" pkg/x.ts'
346+
expect block 'echo "${HOME}" > pkg/x.ts'
347+
expect block 'echo "${x:-"a"}" ; sed -i s/a/b/ pkg/x.ts'
348+
expect block "echo \"\${x:-'a'}\" ; sed -i s/a/b/ pkg/x.ts"
349+
# A `$(…)` inside the expansion is read by the same function, quotes and all: the `"` inside
350+
# its single quotes closes nothing, so the separator behind the word still splits.
351+
expect block "echo \"\${x:-\$(printf '\"')}\" ; sed -i s/a/b/ pkg/x.ts"
352+
307353
echo "== shapes this guard deliberately does NOT claim (documented fail-open) =="
308354
CWD="$MAIN"
309355
expect allow "bash -c \"sed -i s/a/b/ $MAIN/pkg/x.ts\""
310356
expect allow 'echo pkg/x.ts | xargs sed -i s/a/b/'
311357
expect allow 'node -e "fs.writeFileSync(\"pkg/x.ts\", \"y\")"'
312358
expect allow 'python3 -c "open(\"pkg/x.ts\",\"w\").write(\"y\")"'
359+
expect allow 'echo "$(sed -i s/a/b/ pkg/x.ts)"' # a QUOTED $(…) body is one inert word
360+
expect allow 'echo "${x:-"$(sed -i s/a/b/ pkg/x.ts)"}"' # …and so is a QUOTED ${…} body
361+
expect allow 'echo hi > "${x:-"a > b"}"' # a target holding an expansion
362+
# A '…' run inside a quoted ${…} that holds `}` (or `"` `\` `$` and a backtick): bash 5.2 reads
363+
# it as quoted and POSIX shells as literal, so they end the expansion in different places and
364+
# everything after it is inert. Under bash the first is a pure read, under dash a real write.
365+
expect allow "echo \"\${x:-'}\"; sed -i s/a/b/ pkg/x.ts'}\""
366+
expect allow "echo \"\${x:-'}'}\" ; sed -i s/a/b/ pkg/x.ts"
313367
expect allow 'sed -i s/a/b/ $SOMEDIR/x.ts'
314368
expect allow 'sed -i s/a/b/ pkg/*.ts'
315369

‎.claude/hooks/guard-main-checkout-bash.sh‎

Lines changed: 92 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
#!/usr/bin/env bash
2-
# copied from objectstack@7c2c5aedd94d7b0d94c91432bc607862e9c83c6c
2+
# copied from objectstack@338297e46018ae96256262590a308c8be735f825
33
# guard-main-checkout-bash.sh — PreToolUse guard: the SAME worktree-first rule as
44
# guard-main-checkout.sh, applied to file writes that arrive through Bash instead of
55
# through the Edit / Write / NotebookEdit tools.
@@ -32,11 +32,15 @@
3232
#
3333
# Fails open, deliberately, on:
3434
# - wrapped invocations: bash -c '…', xargs, ssh host '…', make, a shell script that
35-
# writes (same known boundary guard-shared-stash.sh documents for itself);
35+
# writes, a command inside a QUOTED "$(…)" (same known boundary guard-shared-stash.sh
36+
# documents for itself);
3637
# - programs whose writes live inside their own source text: python -c "open(p,'w')",
3738
# node -e, awk > (the target is not a shell token, so there is nothing to read);
3839
# - any target containing an expansion or glob ($VAR, `…`, $(…), *, ?, ~) — unresolvable
3940
# without running it;
41+
# - everything after a `'` inside a QUOTED "${…}" unless the quoted run holds none of
42+
# `"` `\` `$` `}` or a backtick: bash and POSIX shells disagree on where such an expansion
43+
# ends (subst_end());
4044
# - relative targets when the payload carries no cwd.
4145
# Each of those is a hole by choice, not by accident: OS_ALLOW_MAIN_EDITS=1 already exists
4246
# for anyone who means to write there, and the target of this guard is the reflexive
@@ -45,6 +49,8 @@
4549
# Writing ABOUT the ban must never trip the ban (objectstack#4890's lesson). Four layers:
4650
# 1. quote-aware segmentation + tokenisation — a `>` or a `sed -i` inside '…' or "…" is
4751
# literal text, so `grep -n "sed -i" .claude/` and `echo "never sed -i in main"` pass;
52+
# a `$(…)`, a backtick or a `${…}` inside "…" is a quoting context of its own, so a `"` in
53+
# its body nests instead of closing the outer string (subst_end(), shared by every pass);
4854
# 2. heredoc bodies are stripped before analysis — the LINES of a `cat > /tmp/notes <<EOF`
4955
# body are documentation, not commands, and segmentation alone (which splits on
5056
# newlines) would happily read them as such;
@@ -114,6 +120,81 @@ fi
114120

115121
[ -n "$cmd" ] || exit 0
116122

123+
# --- an expansion inside "…" is its own quoting context --------------------------------
124+
# Inside "…", `$(`, a backtick or `${` opens a NEW quoting context: a `"` in the body starts a
125+
# string of its own and does not close the outer one. Each scanner below used to read that `"`
126+
# as the closer, so the rest of the body became bare shell, and a `>` in a quoted curl body was
127+
# taken for a redirect whose "target" was the next fragment — a false BLOCK (objectstack#24812);
128+
# the same reading of `echo "${x:-"a > b"}"` named `b}` as a target (objectstack#24901). All
129+
# three quote-aware scanners hand such a body to this ONE function, so they agree on where it
130+
# ends. guard-shared-stash.sh and guard-tree-enum.sh segment commands the same way and carry a
131+
# byte-identical copy; their self-tests fail when a copy differs from this one. (objectstack's
132+
# guard-process-kill.sh carries one too; it has no twin in this repo.)
133+
#
134+
# subst_end S I: when S[I] opens such a context (the `$` of a `$(` or a `${`, or a backtick),
135+
# sets SUBST_END to the index of the character that closes it and returns 0; otherwise returns 1
136+
# and changes nothing. The body is read with its own quotes, escapes and nesting; when the input
137+
# ends first, SUBST_END is the last index — the rest is one inert run (bash refuses such a
138+
# command anyway). The body is kept verbatim as part of the word, so a target holding it still
139+
# fails open on its `$`.
140+
#
141+
# A `${…}` body reads like "…" with one more closer: `"`, `$(`, `${` and a backtick nest in it,
142+
# a backslash escapes, and `}` closes it. A `'` there is where shells part ways, measured: bash
143+
# 5.2 reads `'…'` as a quoted run while it looks for the `}` (`"${x:-'}'}"` prints `'}'`), and
144+
# `bash --posix` and dash read the `'` as a literal. The two readings agree only when the run
145+
# holds none of `"` `\` `$` `}` or a backtick, so such a run is skipped, and any other `'` makes
146+
# the rest one inert run: an extent that depends on the shell is not one this guard can read.
147+
#
148+
# Boundary: a `(` or `)` bash would not count (a `case` pattern, a comment, an unquoted `${…}`
149+
# holding one) moves the end — too early, and the rest is read as it was before this function
150+
# existed; too late, and the text swallowed with the body is inert, i.e. fails open.
151+
SUBST_END=0
152+
subst_end() {
153+
local s="$1" i="$2" n=${#1} st ch top run
154+
case "${s:i:2}" in
155+
'$(') st=')' ; i=$((i + 1)) ;;
156+
'${') st='}' ; i=$((i + 1)) ;;
157+
'`'*) st='`' ;;
158+
*) return 1 ;;
159+
esac
160+
for ((i = i + 1; i < n; i++)); do
161+
ch="${s:i:1}" ; top="${st:${#st}-1:1}"
162+
if [ "$top" = "'" ]; then [ "$ch" = "'" ] && st="${st%?}"; continue; fi
163+
if [ "$ch" = '\' ]; then i=$((i + 1)); continue; fi
164+
if [ "$top" = '"' ] || [ "$top" = '}' ]; then
165+
case "$ch" in
166+
'"') if [ "$top" = '"' ]; then st="${st%?}"; else st+='"'; fi ;;
167+
'`') st+='`' ;;
168+
'$')
169+
case "${s:i+1:1}" in
170+
'(') st+=')' ; i=$((i + 1)) ;;
171+
'{') st+='}' ; i=$((i + 1)) ;;
172+
esac ;;
173+
'}') [ "$top" = '}' ] && st="${st%?}" ;;
174+
"'")
175+
if [ "$top" = '}' ]; then
176+
run="${s:i+1}"
177+
case "$run" in *"'"*) ;; *) SUBST_END=$((n - 1)); return 0 ;; esac
178+
run="${run%%"'"*}"
179+
case "$run" in *[\"\\\`\$\}]*) SUBST_END=$((n - 1)); return 0 ;; esac
180+
i=$((i + ${#run} + 1))
181+
fi ;;
182+
esac
183+
if [ -z "$st" ]; then SUBST_END=$i; return 0; fi
184+
continue
185+
fi
186+
case "$ch" in
187+
"'" | '"') st+="$ch" ;;
188+
'(') st+=')' ;;
189+
')') [ "$top" = ')' ] && st="${st%?}" ;;
190+
'`') if [ "$top" = '`' ]; then st="${st%?}"; else st+='`'; fi ;;
191+
esac
192+
if [ -z "$st" ]; then SUBST_END=$i; return 0; fi
193+
done
194+
SUBST_END=$((n - 1))
195+
return 0
196+
}
197+
117198
# --- heredoc bodies are text, not commands ---------------------------------------------
118199
# `cat > /tmp/notes.md <<EOF` … `EOF` carries prose over several lines. Segmentation splits
119200
# on newlines, so without this pass a documented example inside the body ("sed -i … main
@@ -144,6 +225,9 @@ strip_line_comment() {
144225
ch="${s:i:1}"
145226
if [ -n "$q" ]; then
146227
if [ "$q" = '"' ] && [ "$ch" = '\' ] && [ $((i + 1)) -lt "$n" ]; then i=$((i + 1)); continue; fi
228+
if [ "$q" = '"' ] && { [ "$ch" = '$' ] || [ "$ch" = '`' ]; } && subst_end "$s" "$i"; then
229+
i=$SUBST_END ; continue
230+
fi
147231
[ "$ch" = "$q" ] && q=""
148232
continue
149233
fi
@@ -213,6 +297,9 @@ split_segments() {
213297
seg+="$ch" ; i=$((i + 1)) ; seg+="${s:i:1}" ; continue ;;
214298
esac
215299
fi
300+
if [ "$q" = '"' ] && { [ "$ch" = '$' ] || [ "$ch" = '`' ]; } && subst_end "$s" "$i"; then
301+
seg+="${s:i:SUBST_END-i+1}" ; i=$SUBST_END ; continue
302+
fi
216303
seg+="$ch"
217304
[ "$ch" = "$q" ] && q=""
218305
continue
@@ -271,6 +358,9 @@ tokenize() {
271358
i=$((i + 1)) ; tok+="${s:i:1}" ; have=1 ; continue ;;
272359
esac
273360
fi
361+
if [ "$q" = '"' ] && { [ "$ch" = '$' ] || [ "$ch" = '`' ]; } && subst_end "$s" "$i"; then
362+
tok+="${s:i:SUBST_END-i+1}" ; i=$SUBST_END ; have=1 ; continue
363+
fi
274364
if [ "$ch" = "$q" ]; then q=""; else tok+="$ch"; fi
275365
have=1
276366
continue

‎.claude/hooks/guard-shared-stash.selftest.sh‎

Lines changed: 38 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
#!/usr/bin/env bash
2-
# copied from objectstack@7c2c5aedd94d7b0d94c91432bc607862e9c83c6c
2+
# copied from objectstack@338297e46018ae96256262590a308c8be735f825
33
# Self-test for guard-shared-stash.sh — run it after touching that hook:
44
#
55
# .claude/hooks/guard-shared-stash.selftest.sh
@@ -148,6 +148,43 @@ expect block 'echo "a \\" ; git stash pop'
148148
# single quotes the branch would swallow the closing `'` and pass the stash behind it.
149149
expect block "echo 'a \\' ; git stash pop"
150150

151+
echo "== a \$(…), backtick or \${…} inside \"…\" is its own quoting context (objectstack#24901) =="
152+
# Reading the `"` inside the body as CLOSING the outer string split the body at its `;`, so a
153+
# pure read became a stash. The first three were BLOCKED before subst_end() existed here; the
154+
# fourth (both kinds nested) was allowed then only because two misread quotes cancelled out,
155+
# and the single-level `echo "x; git stash pop"` was allowed throughout.
156+
expect allow 'echo "a $(echo "x; git stash pop")"'
157+
expect allow 'echo "a `echo "x; git stash pop"`"'
158+
expect allow 'echo "${x:-"a; git stash pop"}"'
159+
expect allow 'echo "${x:-"$(echo "a; git stash pop")"}"'
160+
expect allow 'echo "x; git stash pop"'
161+
# Recall: a stash behind or beside a quoted expansion is still seen.
162+
expect block 'echo "${x:-"a"}" ; git stash pop'
163+
expect block 'X="${Y:-"z"}" && git stash push -m wip'
164+
expect block 'git stash push -m "${msg:-"wip; x"}"'
165+
# The fail-OPEN mirror: the `"` inside the single quotes left the outer string hanging, so the
166+
# separator behind it went inert and the real stash rode through as text. Both were ALLOWED
167+
# before subst_end() existed here.
168+
expect block "echo \"\$(printf '\"')\" ; git stash pop"
169+
expect block "echo \"\${x:-\$(printf '\"')}\" ; git stash pop"
170+
# Deliberately not claimed, as before: a stash INSIDE a quoted substitution is one inert word.
171+
expect allow 'echo "$(git stash pop)"'
172+
173+
echo "== the shared quoting rule is guard-main-checkout-bash.sh's, byte for byte (objectstack#24901) =="
174+
# subst_end() lives in three hooks here. A copy that drifts is a quoting rule the guards no longer
175+
# share, and nothing else notices: each hook's own cases keep passing on its own dialect.
176+
fn_text() { sed -n "/^$1() {\$/,/^}\$/p" "$2"; }
177+
same_fn() { # same_fn <function> <file holding the copy this hook must equal>
178+
local mine theirs
179+
mine="$(fn_text "$1" "$hook")"; theirs="$(fn_text "$1" "$2")"
180+
if [ -n "$mine" ] && [ "${mine%%$'\n'*}" = "$1() {" ] && [ "$mine" = "$theirs" ]; then
181+
pass=$((pass + 1)); printf ' ok same %s() as %s\n' "$1" "${2##*/}"
182+
else
183+
fail=$((fail + 1)); printf ' FAIL %s() is missing here or differs from %s\n' "$1" "${2##*/}"
184+
fi
185+
}
186+
same_fn subst_end "$here/guard-main-checkout-bash.sh"
187+
151188
echo "== escape hatch =="
152189
expect allow 'git stash pop' OS_ALLOW_STASH=1
153190

‎.claude/hooks/guard-shared-stash.sh‎

Lines changed: 66 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
#!/usr/bin/env bash
2-
# copied from objectstack@7c2c5aedd94d7b0d94c91432bc607862e9c83c6c
2+
# copied from objectstack@338297e46018ae96256262590a308c8be735f825
33
# guard-shared-stash.sh — PreToolUse guard: the stash stack is SHARED across worktrees.
44
# Blocks Bash commands that push to / pop from / drop the shared stash stack, and lets
55
# the read-only and SHA-pinned forms through.
@@ -47,10 +47,11 @@
4747
# for anyone who means it. Widening it to string-match anywhere in the command would block
4848
# every `grep "git stash"` run against this very file.
4949
#
50-
# Self-test (50 cases, no network, no build): .claude/hooks/guard-shared-stash.selftest.sh
51-
# 50 = 46 `expect ` lines + 2 inline specials (empty-tool_input fail-open, no-jq fallback)
52-
# + 2 hatch-message assertions (`lacks`/`says`, which are not `expect ` lines).
53-
# Re-derive when the matrix changes: `grep -c '^expect ' <selftest>` + 4, and the run's own
50+
# Self-test (62 cases, no network, no build): .claude/hooks/guard-shared-stash.selftest.sh
51+
# 62 = 57 `expect ` lines + 2 inline specials (empty-tool_input fail-open, no-jq fallback)
52+
# + 2 hatch-message assertions (`lacks`/`says`, which are not `expect ` lines) + 1 identity
53+
# pin (`same_fn`, the subst_end() copy, which is not an `expect ` line either).
54+
# Re-derive when the matrix changes: `grep -c '^expect ' <selftest>` + 5, and the run's own
5455
# tail prints the total ("N passed, N failed") — keep this number equal to it.
5556

5657
set -uo pipefail
@@ -98,6 +99,63 @@ fi
9899
# same shape and with the same escapee list as guard-main-checkout-bash.sh's
99100
# split_segments() carries; that guard's `word` bookkeeping has no analogue here because
100101
# this pass has no comment rule to track word starts for.
102+
#
103+
# INSIDE "…" a `$(`, a backtick or a `${` opens a quoting context of its own, so a `"` in its
104+
# body nests instead of closing the outer string. Without that rule this pass read the inner
105+
# `"` as the closer, the `;` inside the body split, and a pure read became a stash command —
106+
# measured on this repo's copy before the fix: `echo "a $(echo "x; git stash pop")"` and
107+
# `echo "${x:-"a; git stash pop"}"` were BLOCKED (objectstack#24901). The body is kept verbatim inside
108+
# the segment, so a stash inside a QUOTED substitution stays the fail-open it always was.
109+
#
110+
# subst_end() is copied byte-for-byte from guard-main-checkout-bash.sh, whose comment above
111+
# the function is its documentation; this hook's self-test fails when the copy differs.
112+
SUBST_END=0
113+
subst_end() {
114+
local s="$1" i="$2" n=${#1} st ch top run
115+
case "${s:i:2}" in
116+
'$(') st=')' ; i=$((i + 1)) ;;
117+
'${') st='}' ; i=$((i + 1)) ;;
118+
'`'*) st='`' ;;
119+
*) return 1 ;;
120+
esac
121+
for ((i = i + 1; i < n; i++)); do
122+
ch="${s:i:1}" ; top="${st:${#st}-1:1}"
123+
if [ "$top" = "'" ]; then [ "$ch" = "'" ] && st="${st%?}"; continue; fi
124+
if [ "$ch" = '\' ]; then i=$((i + 1)); continue; fi
125+
if [ "$top" = '"' ] || [ "$top" = '}' ]; then
126+
case "$ch" in
127+
'"') if [ "$top" = '"' ]; then st="${st%?}"; else st+='"'; fi ;;
128+
'`') st+='`' ;;
129+
'$')
130+
case "${s:i+1:1}" in
131+
'(') st+=')' ; i=$((i + 1)) ;;
132+
'{') st+='}' ; i=$((i + 1)) ;;
133+
esac ;;
134+
'}') [ "$top" = '}' ] && st="${st%?}" ;;
135+
"'")
136+
if [ "$top" = '}' ]; then
137+
run="${s:i+1}"
138+
case "$run" in *"'"*) ;; *) SUBST_END=$((n - 1)); return 0 ;; esac
139+
run="${run%%"'"*}"
140+
case "$run" in *[\"\\\`\$\}]*) SUBST_END=$((n - 1)); return 0 ;; esac
141+
i=$((i + ${#run} + 1))
142+
fi ;;
143+
esac
144+
if [ -z "$st" ]; then SUBST_END=$i; return 0; fi
145+
continue
146+
fi
147+
case "$ch" in
148+
"'" | '"') st+="$ch" ;;
149+
'(') st+=')' ;;
150+
')') [ "$top" = ')' ] && st="${st%?}" ;;
151+
'`') if [ "$top" = '`' ]; then st="${st%?}"; else st+='`'; fi ;;
152+
esac
153+
if [ -z "$st" ]; then SUBST_END=$i; return 0; fi
154+
done
155+
SUBST_END=$((n - 1))
156+
return 0
157+
}
158+
101159
segments=()
102160
split_segments() {
103161
local s="$1" seg="" q="" ch i n=${#1}
@@ -110,17 +168,15 @@ split_segments() {
110168
seg+="$ch" ; i=$((i + 1)) ; seg+="${s:i:1}" ; continue ;;
111169
esac
112170
fi
171+
if [ "$q" = '"' ] && { [ "$ch" = '$' ] || [ "$ch" = '`' ]; } && subst_end "$s" "$i"; then
172+
seg+="${s:i:SUBST_END-i+1}" ; i=$SUBST_END ; continue
173+
fi
113174
seg+="$ch"
114175
[ "$ch" = "$q" ] && q=""
115176
continue
116177
fi
117178
case "$ch" in
118179
'\')
119-
# An escaped character opens no quote and separates nothing: consume BOTH characters
120-
# and keep scanning outside quotes, so the separator behind a `\"` still splits
121-
# (objectstack#11131). Both are kept verbatim because this pass only SPLITS —
122-
# check_segment() re-reads the segment with `read -r -a`, and `-r` leaves the
123-
# backslash literal, exactly as a real shell argument would carry it.
124180
seg+="$ch"
125181
if [ $((i + 1)) -lt "$n" ]; then i=$((i + 1)) ; seg+="${s:i:1}" ; fi
126182
;;

0 commit comments

Comments
 (0)