diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.json index bbc8d72..509bbed 100644 --- a/.claude-plugin/plugin.json +++ b/.claude-plugin/plugin.json @@ -1,7 +1,7 @@ { "name": "isep", "description": "InkStone Environment Plugin —— leo 的 Claude Code 環境唯一真相源:62 支機械閘(85 條註冊,白話盤點見 docs/hooks-inventory.md)、7 支 slash command、2 支 skill、7 位有名字的工人(agents/,見 docs/governance/worker-roster.md)、48 支腳本,外加治理規範與標籤真相源。本機與雲端裝同一份,沒有子集。", - "version": "0.16.1", + "version": "0.16.2", "keywords": [ "inkstone", "guardrails", diff --git a/docs/TESTING.md b/docs/TESTING.md index 64a2c49..abba36d 100644 --- a/docs/TESTING.md +++ b/docs/TESTING.md @@ -492,11 +492,17 @@ bash hooks/tests/parallel-lines-cap-guard.test.sh `PostToolUse:Agent` 在**送出後 5 秒**就觸發(不是收工); subagent **不是獨立行程**(`ps` 只有一個 claude-code 行程,所以數行程數不到線)。 -### A24 — 一條線要有自己的工作目錄:35 條 +### A24 — 一條線要有自己的工作目錄:59 條 ``` bash hooks/tests/line-needs-own-worktree.test.sh ``` -**該看到**:`35/35 通過`。離線,每個案例自己開一顆真的 git repo +一份真的 linked worktree。 +**該看到**:`59/59 通過`。離線,每個案例自己開**兩顆**真的 git repo +一份真的 linked worktree。 + +**D 群在守什麼**(comment 5398,2026-08-29 補):不只要擋對,還要**說得出是哪一個 repo**。 +舊版一律拿 payload 的 `cwd` 當答案,於是 `cd <別的 repo> && git checkout` 擋是擋對了, +訊息卻指著 `cwd` 那個 repo ⇒ 照著做的人會在**錯的 repo** 開一份用不到的 worktree, +真正要隔離的那個沒開到,而他以為隔離好了。🔴 **一道閘給錯下一步,比不擋更糟。** +D 群同時釘住反面:認不出來(`cd $VAR`、`cd -`、cd 到不是 repo 的地方)就**放行**,不猜。 **它在守什麼**(inkstone/ISEP#109 → comment 5391,2026-08-29 實撞): 每個 repo 只有**一份**工作目錄,所有線共用。`arcrun-rag#163` 切到自己的分支、交回時沒切回來, diff --git a/hooks/lib/checkout_target_dir.py b/hooks/lib/checkout_target_dir.py new file mode 100644 index 0000000..55dfd3d --- /dev/null +++ b/hooks/lib/checkout_target_dir.py @@ -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() diff --git a/hooks/lib/push_target_dir.py b/hooks/lib/push_target_dir.py index 10effe2..1d4fb28 100644 --- a/hooks/lib/push_target_dir.py +++ b/hooks/lib/push_target_dir.py @@ -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 diff --git a/hooks/line-needs-own-worktree.sh b/hooks/line-needs-own-worktree.sh index 1e13115..b9b8e0b 100755 --- a/hooks/line-needs-own-worktree.sh +++ b/hooks/line-needs-own-worktree.sh @@ -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 - # 允許前面掛 env(VAR=值 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