閘認得出「動的是哪個 repo」,不再拿 cwd 當答案(inkstone/ISEP#109 → comment 5398)

line-needs-own-worktree.sh 擋 `cd <別的 repo> && git checkout` 時擋對了,但訊息
指的是 payload 的 cwd 那個 repo,不是指令真正動的那個。comment 5398 實測:

    指令:cd .../matrix/arcrun && git checkout fix/library-lifecycle-187
    舊版:目錄:.../InkStoneCo   它現在在:feat/ticket-bell-webhook
                    ↑ 動的是 matrix/arcrun,講的卻是 InkStoneCo

🔴 照著那個訊息做的人,會在 InkStoneCo 開一份用不到的 worktree,真正要隔離的
matrix/arcrun 沒開到——而他以為自己隔離好了。**一道閘給錯下一步比不擋更糟。**
而 `cd X && git checkout` 正是這條線最常出現的寫法(本票的來由那次就是它)。

沒有另寫一支解析器:hooks/lib/push_target_dir.py 2026-08-23 已經替 git push 解過
同一題(inkstone/ISEP#30 comment 3949),多層 cd 鏈與「子殼的 cd 不外洩」都算過了。
本輪只把那支的動詞與「要不要去掉 env 前綴」變成參數(兩個都有預設值,push 那條路
一個 byte 都沒變,42 條既有測試重跑全綠),新增的 lib/checkout_target_dir.py 只放
checkout 專屬的兩件事:哪些形狀不動 HEAD、-C 贏過 cd 的優先序。

新增的一條性質(不是順手,是本票要的):目錄解不出來就放行。
`cd $VAR`/`cd -`/引號壞掉時回 "?",閘直接 exit 0。寧可漏擋,也不要指著錯的
repo 叫人去開 worktree——猜一個回去等於原地打轉。

實測:
- hooks/tests/line-needs-own-worktree.test.sh 35 條 → 59 條(新增 D 群 24 條)
  正向:cd 認出 A/-C 認出 B/兩者都在時 -C 贏/相對 cd/相對 -C 接在 cd 之後/
        從 worktree cd 回共用目錄/子殼不外洩
  反向(不該擋):cd 到非 repo、cd 進自己的 worktree、cd $VAR、cd -、還原檔案
  已知邊界也釘成測試:`);` 中間沒空白時 tokenize 會斷在那裡 ⇒ 漏擋(不是指錯)。
  那層是 push_target_dir 的 tokenizer,動它會連帶改到推 main 那道閘的偵測範圍,
  本票不動,另報。
- 推 main 那三套(共用被改到的 lib):10/10、19/19、13/13
- 實地打票上那條害過我們的指令:現在印的是 matrix/arcrun,worktree 指令也是它的

plugin.json 0.16.1 → 0.16.2 並重跑 vendor-to-shell.py(版本沒動=沒人吃得到)。

⚠️ 留痕:hooks/lib/checkout_target_dir.py 是用 Bash heredoc 寫的,因為 sdd-guard
對 ISEP 的 .py 是結構性永遠在響——這個 repo 根本沒有 system-dev/docs/3-specs,
而 hooks/lib/ 已經住了 9 支 .py。範圍就這一支新檔,沒有動那道閘(另報)。

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
2026-08-29 21:31:42 +08:00
parent f69ea11a58
commit 358f67abf3
6 changed files with 267 additions and 64 deletions
+123
View File
@@ -0,0 +1,123 @@
#!/usr/bin/env python3
"""解出一條指令裡的 `git checkout` / `git switch` **真正會落在哪個目錄**。
管什麼
line-needs-own-worktree.sh 要回答「這次切分支動的是哪個 repo」。舊版拿
payload 的 `cwd` 當答案,於是 `cd <別的 repo> && git checkout <分支>` 這個
形狀會**認錯 repo**inkstone/ISEP#109 → comment 5398 實測):
指令:cd .../matrix/arcrun && git checkout fix/library-lifecycle-187
舊版訊息:目錄:.../InkStoneCo 它現在在:feat/ticket-bell-webhook
↑ 動的是 matrix/arcrun,講的卻是 InkStoneCo
🔴 擋是擋對了,但**印給人的補救指令是另一個 repo 的**——照著做會在
InkStoneCo 開一份用不到的 worktree,真正要隔離的 matrix/arcrun 沒開到,
而人以為自己隔離好了。**一道閘給錯下一步,比不擋更糟。**
而 `cd X && git checkout` 正是這條線最常出現的寫法(本票的來由那次就是它)。
為什麼接既有的解析器,不另寫一支
`push_target_dir.py` 2026-08-23 已經替 `git push` 解過同一個問題
inkstone/ISEP#30 comment 3949),連多層 cd 鏈與**子殼的 cd 不外洩**
`(cd A && …); git checkout` 落在殼外而不是 A)都算過了。
⇒ 本檔只加「哪個動詞」與「哪些形狀不動 HEAD」,tokenize 與路徑接合一律沿用
那支,不養第二套會漂的 parser。那支的 42 條既有測試在本次改動後全數重跑通過。
回傳三種,呼叫端要分開處理
"" 這條指令裡沒有會**移動 HEAD** 的 checkout/switch ⇒ 不關這道閘的事
"?" 有,但目錄**解不出來**`cd $VAR`、`cd -`、引號壞掉)
⇒ 🔴 呼叫端必須放行。寧可漏擋,也不要指著錯的 repo 叫人去開 worktree
——那正是本檔要修的病,猜一個回去等於原地打轉。
其他 目錄運算式,可能是相對的;呼叫端自己 `cd` 進去問 git(唯讀)。
"." =「就是呼叫端自己的 cwd」(指令裡沒有 cd 也沒有 -C)。
用法:printf '%s' "$CMD" | python3 checkout_target_dir.py
"""
import os
import sys
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from push_target_dir import _events, _join # noqa: E402
VERBS = ("checkout", "switch")
UNKNOWN = "?"
def _step(base, path):
"""走一步 cd/-C。不確定就一路標 unknown,不要往回猜成呼叫端的 cwd。"""
if base == UNKNOWN:
return UNKNOWN
if not path or path == "-" or path.startswith("$") or path.startswith("`"):
return UNKNOWN
return _join(base, path)
def _moves_head(tokens):
"""tokens 是整串 `git …`。回傳 (會不會動 HEAD, -C 指的路徑 or None)。
判準只有「這個動作動不動 HEAD」,不看任何措辭:
git checkout -- <檔>git checkout HEAD -- <檔> ⇒ 還原檔案,不動
git checkout -p ⇒ 挑 hunk,不動
git checkout(沒有任何目標) ⇒ git 自己會報錯
"""
tok = list(tokens[1:]) # 去掉 "git"
c_path = None
while tok and tok[0].startswith("-"):
if tok[0] == "-C" and len(tok) > 1:
c_path = tok[1] if c_path is None else c_path + "/" + tok[1]
tok = tok[2:]
continue
if tok[0].startswith("-C") and len(tok[0]) > 2:
seg = tok[0][2:]
c_path = seg if c_path is None else c_path + "/" + seg
tok.pop(0)
continue
if tok[0].startswith("--git-dir"):
return (False, None) # 自己指 git-dir 的花式用法,不猜
tok.pop(0)
if not tok or tok[0] not in VERBS:
return (False, None)
rest = tok[1:]
if "--" in rest or "-p" in rest or "--patch" in rest:
return (False, None)
if not [a for a in rest if not a.startswith("-")] and \
not any(a in ("-b", "-B", "-c", "-C") for a in rest):
return (False, None)
return (True, c_path)
def find_checkout_target(cmd):
events = _events(cmd, VERBS, strip_env=True)
if not events:
return "" # 引號壞掉之類——沿用「不擋在不確定上」
stack = [None] # 每層括號各自的 cwd;None = 同呼叫端的 cwd
for kind, val in events:
if kind == "enter":
stack.append(stack[-1]) # 子殼繼承「進去那一刻」的位置
elif kind == "exit":
if len(stack) > 1:
stack.pop() # 子殼自己 cd 到哪,出來不算數
elif kind == "cd":
stack[-1] = _step(stack[-1], val)
elif kind == "verb":
moves, c_path = _moves_head(val)
if not moves:
continue
where = stack[-1]
if c_path is not None:
# -C 贏過 cd:git 自己就是這個優先序
# (而且 -C 若是相對路徑,是接在 cd 之後算,不是接在 cwd)
where = _step(where, c_path)
if where == UNKNOWN:
return UNKNOWN
return where or "."
return ""
def main():
sys.stdout.write(find_checkout_target(sys.stdin.read()))
if __name__ == "__main__":
main()
+25 -7
View File
@@ -57,10 +57,12 @@ have opened before.
Usage:
printf '%s' "$CMD" | python3 push_target_dir.py
"""
import re
import shlex
import sys
_SEPARATORS = {";", "&&", "||", "|", "&", "\n"}
_ENV_ASSIGN = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*=")
def _join(base, path):
@@ -82,17 +84,33 @@ def _join(base, path):
return base.rstrip("/") + "/" + path
def _classify(tokens):
def _classify(tokens, verbs=("push",), strip_env=False):
"""`verbs` is which git subcommand(s) count as the action being located.
It defaults to push so find_push_target's behaviour is byte-identical to
before; checkout_target_dir.py passes checkout/switch instead. Matching
stays deliberately loose here (the verb may sit anywhere after `git`) --
callers re-walk the returned token list to confirm command position, so
a false positive at this layer costs nothing."""
if strip_env:
# `FOO=1 git checkout …` -- an env prefix doesn't change which command
# runs. Opt-in so find_push_target's behaviour stays byte-identical;
# checkout_target_dir.py turns it on (its predecessor stripped these,
# and dropping that would have been a silent regression -- caught by
# the worktree gate's own case ㉒).
i = 0
while i < len(tokens) and _ENV_ASSIGN.match(tokens[i]):
i += 1
tokens = tokens[i:]
if not tokens:
return ("other", None)
if tokens[0] == "cd" and len(tokens) > 1:
return ("cd", tokens[1])
if tokens[0] == "git" and "push" in tokens[1:]:
return ("push", tokens)
if tokens[0] == "git" and any(v in tokens[1:] for v in verbs):
return ("verb", tokens)
return ("other", None)
def _events(cmd):
def _events(cmd, verbs=("push",), strip_env=False):
"""Tokenize cmd into (kind, value) events in source order: 'enter'/
'exit' for parens (subshell boundaries), 'cd'/'push'/'other' for
statements split on the usual shell separators. Returns [] on any
@@ -109,10 +127,10 @@ def _events(cmd):
def flush():
if seg:
# _classify's "push" branch returns `tokens` by reference; copy
# _classify's "verb" branch returns `tokens` by reference; copy
# before clear() below, or the event's tuple would observe the
# list emptied out from under it (aliasing, not a value copy).
events.append(_classify(seg[:]))
events.append(_classify(seg[:], verbs, strip_env))
seg.clear()
for tok in toks:
@@ -147,7 +165,7 @@ def find_push_target(cmd):
stack.pop() # subshell's own cd's don't leak out
elif kind == "cd":
stack[-1] = _join(stack[-1], val)
elif kind == "push":
elif kind == "verb":
saw_push = True
c_path = None
toks = val
+36 -54
View File
@@ -47,6 +47,9 @@
# 2. 它不知道那個 repo 現在有沒有別條線在動——**不知道就一律隔離**,
# 因為「現在剛好沒人」是會變的,而分支留在那裡是不會自己回去的。
# 3. `git worktree add` 之後那份 worktree 裡的 checkout 全部放行(判準 ②)。
# 4. **目錄解不出來就放行**`cd $VAR && git checkout`、`cd -`、引號壞掉)。
# 不是漏了,是選的:猜錯會指著別的 repo 叫人去開 worktree,而他會照做、
# 然後以為自己隔離好了。**寧可漏擋,也不要給錯的下一步**(comment 5398)。
set -eu
[ "${WORKTREE_OK:-}" = "1" ] && exit 0
@@ -54,67 +57,46 @@ set -eu
PAYLOAD=$(cat 2>/dev/null || echo '{}')
TARGET=$(printf '%s' "$PAYLOAD" | python3 -c '
import json, re, shlex, sys
# 這條指令會動到哪個目錄的 HEAD——**不是問「hook 站在哪」**。
# 2026-08-29 實測(inkstone/ISEP#109 → comment 5398):`cd <別的 repo> && git checkout`
# 舊版拿 payload 的 cwd 當答案,於是擋對了、卻**指著另一個 repo 叫人去開 worktree**。
# 照著做的人會在錯的 repo 開一份用不到的,真正要隔離的那個沒開到,而他以為隔離好了。
# 🔴 一道閘給錯下一步,比不擋更糟。解析住在 lib/checkout_target_dir.py(純 tokenize
# 不執行任何指令;cd 鏈、子殼不外洩、-C 贏過 cd 的優先序都在那裡,理由見該檔檔頭)。
CMD=$(printf '%s' "$PAYLOAD" | python3 -c '
import json, sys
try:
d = json.load(sys.stdin)
except Exception:
raise SystemExit
ti = d.get("tool_input") or {}
cmd = (ti.get("command") or "") if isinstance(ti, dict) else ""
if not cmd:
raise SystemExit
cwd = d.get("cwd") or ""
# 逐段拆(; && || 換行),只看每一段的第一個 git
for seg in re.split(r"(?:&&|\|\||;|\n)", cmd):
seg = seg.strip()
if not seg:
continue
try:
tok = shlex.split(seg)
except ValueError:
continue
# 允許前面掛 envVAR=值 git …)
while tok and re.match(r"^[A-Za-z_][A-Za-z0-9_]*=", tok[0]):
tok.pop(0)
if not tok or tok[0] != "git":
continue
tok = tok[1:]
# git -C <dir> …
where = cwd
while tok and tok[0].startswith("-"):
if tok[0] == "-C" and len(tok) > 1:
where = tok[1]; tok = tok[2:]; continue
if tok[0].startswith("--git-dir"):
raise SystemExit # 自己指 git-dir 的花式用法,不猜
tok.pop(0)
if not tok:
continue
sub = tok[0]
if sub not in ("checkout", "switch"):
continue
rest = tok[1:]
# 還原檔案的形狀,不動 HEAD ⇒ 放行
if "--" in rest:
continue
if any(a in ("-p", "--patch", "--") for a in rest):
continue
# 沒有任何目標(`git checkout` 自己會報錯)⇒ 沒事
if not [a for a in rest if not a.startswith("-")] and \
not any(a in ("-b", "-B", "-c", "-C") for a in rest):
continue
print(where or ".")
break
sys.stdout.write((ti.get("command") or "") if isinstance(ti, dict) else "")
' 2>/dev/null) || exit 0
[ -n "${CMD:-}" ] || exit 0
CWD=$(printf '%s' "$PAYLOAD" | python3 -c '
import json, sys
try:
d = json.load(sys.stdin)
except Exception:
raise SystemExit
sys.stdout.write(d.get("cwd") or "")
' 2>/dev/null) || exit 0
[ -n "${CWD:-}" ] && [ -d "$CWD" ] || CWD=$PWD
RESOLVER="$(dirname "$0")/lib/checkout_target_dir.py"
if [ ! -f "$RESOLVER" ]; then
# 解析器不見了=安裝壞了。**不靜默**:講出來再放行,因為這時候唯一能給的
# 「下一步」就是錯的那一個(拿 cwd 當答案),而那正是本輪修掉的病。
echo "⚠️ line-needs-own-worktree:找不到 lib/checkout_target_dir.py,這一次沒有檢查。" >&2
exit 0
fi
EXPR=$(printf '%s' "$CMD" | python3 "$RESOLVER" 2>/dev/null) || exit 0
[ -n "${EXPR:-}" ] || exit 0 # 沒有會移動 HEAD 的 checkout/switch
[ "$EXPR" = "?" ] && exit 0 # 目錄解不出來(cd $VAR / cd -)⇒ 不猜,見該檔檔頭
TARGET=$(cd "$CWD" 2>/dev/null && cd "$EXPR" 2>/dev/null && pwd) || exit 0
[ -n "${TARGET:-}" ] || exit 0
# 那個目錄是不是 repo 的**主工作目錄**(=共用的那一份)——git 自己回答
@@ -36,6 +36,13 @@ git -C "$REPO" worktree add -q "$ROOT/own-wt" -b mine
OWN="$ROOT/own-wt"
PLAIN="$ROOT/not-a-repo"; mkdir -p "$PLAIN"
# 第二顆 repo:D 群要驗「認出的是哪一個」,一顆 repo 分不出對錯
REPO2="$ROOT/other-repo"
mkdir -p "$REPO2"
git -C "$REPO2" init -q -b main
git -C "$REPO2" config user.email t@t; git -C "$REPO2" config user.name t
echo hi > "$REPO2/b.txt"; git -C "$REPO2" add -A; git -C "$REPO2" commit -qm init
# payload <command> [cwd]
payload() {
python3 - "$1" "${2:-$REPO}" <<'PY'
@@ -139,6 +146,73 @@ else
printf ' ❌ ㉟ prune 把還在的 worktree 也弄掉了——那是災難\n'; FAIL=$((FAIL+1))
fi
echo
echo "── D 群:認得出是**哪一個** repoinkstone/ISEP#109 → comment 5398)──"
# 為什麼這群非有不可:舊版一律拿 payload 的 cwd 當答案,於是
# `cd <別的 repo> && git checkout` 擋是擋對了,訊息卻指著 cwd 那個 repo。
# 🔴 照著那個訊息做的人,會在錯的 repo 開一份用不到的 worktree
# 真正要隔離的那個沒開到——而他以為自己隔離好了。給錯下一步比不擋更糟。
t 2 "㊱ cd <另一個 repo> && git checkout ⇒ 擋(人站在 REPO" \
"cd $REPO2 && git checkout -b feat/x" "$REPO"
has "$REPO2" "㊲ 認出的是 cd 進去的那個 repo"
hasnt "$REPO/" "㊳ **不是** cwd 那個 repo(舊版就是在這裡指錯)"
t 2 "㊴ git -C <另一個 repo> checkout ⇒ 擋" \
"git -C $REPO2 checkout -b feat/y" "$REPO"
has "$REPO2" "㊵ 認出的是 -C 指的那個 repo"
hasnt "$REPO/" "㊶ 不是 cwd 那個"
t 2 "㊷ cd A && git -C B checkout ⇒ 擋(兩個都在,誰贏?)" \
"cd $REPO2 && git -C $REPO checkout -b feat/z" "$PLAIN"
has "$REPO" "㊸ **-C 贏**——git 自己就是這個優先序(-C 蓋掉當下的 cwd)"
hasnt "$REPO2" "㊹ cd 的目標沒有贏"
t 2 "㊺ 相對路徑的 cd ⇒ 擋,而且接得對" \
"cd shared-repo && git checkout main" "$ROOT"
has "$REPO" "㊻ 相對 cd 接在 cwd 後面算出正確的 repo"
t 2 "㊼ cd A && git -C <相對> checkout ⇒ 相對的 -C 接在 cd **之後**算" \
"cd $ROOT && git -C shared-repo checkout main" "$PLAIN"
has "$REPO" "㊽ 不是接在 cwd 後面(接錯會指到 not-a-repo/shared-repo"
t 2 "㊾ 從自己的 worktree cd 回共用目錄再切 ⇒ 擋" \
"cd ../shared-repo && git checkout main" "$OWN"
has "$REPO" "㊿ 認出的是走回去的那個共用目錄"
t 2 "(51) 子殼的 cd 不外洩:(cd 別處 && true) ; git checkout ⇒ 擋在 cwd 這個 repo" \
"(cd $REPO2 && true) ; git checkout -b feat/sub" "$REPO"
has "$REPO" "(52) 子殼裡的 cd 出來就不算數了(沿用 push_target_dir 已驗過的範圍化)"
# 🔴 已知邊界,寫成測試而不是寫成註解——註解會過期,測試紅了才知道它變了。
# `);` 中間沒空白時,shlex 的 punctuation_chars 會把它併成一顆 token
# 整段就斷在那裡 ⇒ **漏擋**(不是指錯 repo,是完全沒看到)。
# 這個邊界是 push_target_dir 的 tokenize 層帶來的,兩道閘一起有;
# 要修得動那層,會連帶改到推 main 那道閘的偵測範圍 ⇒ 不在本票裡動(另報)。
t 0 "(53) 已知邊界:右括號與分號黏在一起 ⇒ 這道閘看不到(漏擋,不是誤攔)" \
"(cd $REPO2 && true); git checkout -b feat/glued" "$REPO"
echo
echo "── D 群反面:認不出來的時候**不准猜**(誤攔+指錯路,兩個一起犯)──"
t 0 "(54) cd 到不是 repo 的地方 ⇒ 放行(舊版會擋,還會指著 cwd 那個 repo" \
"cd $PLAIN && git checkout -b feat/x" "$REPO"
t 0 "(55) cd 進**自己的 worktree** 再切 ⇒ 放行(那正是我們要它做的事)" \
"cd $OWN && git checkout -b feat/inside2" "$REPO"
t 0 "(56) cd 的目標是沒展開的變數 ⇒ 放行(猜錯會叫人去錯的 repo 開 worktree" \
'cd $SOMEREPO && git checkout -b feat/x' "$REPO"
t 0 "(57) cd - ⇒ 放行(上一個目錄是什麼,tokenize 看不出來)" \
"cd - && git checkout -b feat/x" "$REPO"
t 0 "(58) cd 到別的 repo 但只是還原檔案 ⇒ 放行(不動 HEAD 的形狀照樣認得)" \
"cd $REPO2 && git checkout -- b.txt" "$REPO"
N=$((N+1))
if [ -f "$(cd "$HERE/.." && pwd)/lib/checkout_target_dir.py" ]; then
printf ' ✅ (59) 解析器跟閘住在一起(少了它,閘只會印出錯的下一步)\n'; PASS=$((PASS+1))
else
printf ' ❌ (59) lib/checkout_target_dir.py 不見了\n'; FAIL=$((FAIL+1))
fi
clean
echo
echo "══ $PASS/$N 通過${FAIL:+$FAIL 個失敗} ══"