Compare commits

..

34 Commits

Author SHA1 Message Date
claude-code 4d27132413 Merge pull request '定版 v0.29.0(主線成員改由相依邊收集,不再靠同名里程碑)' (#152) from chore/v0.29.0 into main 2026-09-07 10:59:41 +00:00
claude-code 7f726bb99a 定版 v0.29.0(主線成員改由相依邊收集,不再靠同名里程碑)
總管定版:inkstone/ISEP#133(PR #151)——leo 09-07 原話「早就定了只有一個 milestone,不同 repo 用指針」。
collect_members()=hub 里程碑裡的票+hub 票,沿 Gitea /dependencies 跨 repo 收;mainline adopt 改成加相依邊,
不再在別的 repo 建同名里程碑;add_dependency 冪等改成先讀 /dependencies(真 Gitea 對重複邊回 500 不是 409)。

總管在「分支 ⊕ main」重跑:members-by-dependency 57/57、ticket-pick 53/53、mainline-repo-mirror 17/17、
focus-guard 24/24、gitea-fallback 31/31、countdown 20/20、milestone-account 23/23、debt-worklist 47/47;
全套紅的與 main 基線同 8 支(多出的 ask-user-question-guard.live 兩棵樹重跑都 9/9,是叫 haiku 的浮動)。
數字在這棵樹上實數:61 支閘/86 條註冊/7 位工人/7 支命令/2 支 skill/62 支腳本。

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0178ef1fGw3XeZtpN7LaZrm4
2026-09-07 10:59:16 +00:00
claude-code f6791408ab Merge pull request '主線成員由相依邊決定,不靠同名里程碑;adopt 別 repo 的票=加相依到 hub 票;帳本落在 InkStoneCo/system-dev(inkstone/ISEP#133)' (#151) from feat/133-members-by-dependency into main 2026-09-07 10:58:57 +00:00
isep-hand 19face1c41 adopt 的冪等改靠「先讀 /dependencies」:真 Gitea 對重複相依回 500 不是 409(inkstone/ISEP#133)
真 Gitea 實跑(hub=InkStoneCo#44、子票=ISEP#133):第一次 POST 成功、/blocks 回 #44、
清空快取後 has 靠 /blocks 判「在」;第二次 POST 回 500——假伺服器原本猜 409,adopt 第二次會炸。
add_dependency() 改成先讀 parent 的 /dependencies,邊在就不 POST(判準是 Gitea 的事實,不是回應碼);
假伺服器改照真的回 500;A41 56→57 條。測完 DELETE 復原(201,/blocks 空)。

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0178ef1fGw3XeZtpN7LaZrm4
2026-09-07 10:46:43 +00:00
isep-hand d4bf172990 主線成員改由相依邊決定,不靠同名里程碑;adopt 別 repo 的票=加相依到 hub 票;帳本落在 InkStoneCo/system-dev(inkstone/ISEP#133 → 6743)
leo 2026-09-07:「拆,誰說『同名跨 repo 是 mainline 機制的一部分』,早就定了只有一個
milestone,不同 repo 用指針」。上一版 scripts/mainline 檔頭把現場的樣子(5 個同名)寫成
「既有做法」,成員也照標題跨 repo 收;總管照它做、抄進 ops-facts、還在 arcrun-rag 補建了一個同名的。

改了什麼(判準全部是 Gitea 欄位,沒有標題比對):
- hooks/lib/mainline.py:collect_members()=hub 里程碑裡的票+hub 票,沿 /dependencies 邊
  (跨 repo)收下去;belongs() 要同時拿到「掛哪個 milestone」+「誰把它當相依」才准說「不屬於」,
  只知一半回 None(閘放行);project_roots() 給主線檔與帳本共用
- scripts/mainline:set --hub <票>、adopt 別 repo ⇒ POST 相依到 hub 票(--via 可指定成員),
  沒 hub 票時擋下並給兩條走得通的路,不建同名里程碑;has 查 /blocks;
  refresh --members 才重收(真 Gitea 25 張要 19 秒,SessionStart 成本不變)
- scripts/ticket:add_dependency() 一份(subtask 與 adopt 共用,409 冪等);pick 主線組走成員清單,
  逾期組一個里程碑物件一組;claim 的主線判定改看相依;pickable(None) 給靠邊進來的票
- hooks/mainline-focus-guard.sh:新鮮查詢問 milestone+/blocks,補收出路明講不要開同名里程碑
- scripts/milestone-account:帳本找家用同一把尺,退回原始碼目錄只在它有 .git(plugin 快取沒有)

測試:新 hooks/tests/mainline-members-by-dependency.test.sh 56 條(假 Gitea 照真的回 201/409);
scripts/test-ticket-pick.sh 48→53 條(池子改用相依邊,補「同名沒邊 ⇒ 不抓」);
既有 mainline-focus-guard/repo-mirror/gitea-fallback/idle/milestone-account/debt-worklist/
handoff-writeback 全綠。真 Gitea 唯讀實跑:set --hub inkstone/InkStoneCo#44 收到 25 張、5 個 repo,
mira#6/ISEP#130/ISEP#140/arcrun-rag#104 都在,不必新增任何邊。

版本:待總管定版(改了會被載入的 hook/scripts)。

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0178ef1fGw3XeZtpN7LaZrm4
2026-09-07 10:40:55 +00:00
claude-code 7a9e30589c Merge pull request '定版 v0.28.0(一個 repo 只有一個資料夾:分身住 .worktrees/,收工機器收)' (#149) from chore/v0.28.0 into main 2026-09-07 07:20:05 +00:00
claude-code 3785fc66cc 定版 v0.28.0(一個 repo 只有一個資料夾:分身住 .worktrees/,收工機器收)
總管定版:inkstone/ISEP#147(PR #148)——leo 09-07 兩句原話立的禁令。scripts/worktree(open/close/list/sweep)、
line-needs-own-worktree.sh 多掛 PostToolUse 收工那一半、docs/governance/worktree-placement.md 規約。
總管在「分支 ⊕ main」重跑:test-worktree 42/42、line-needs-own-worktree 110/110、github-contact-guard 26/26、
版本一致 、plugin validate 。sweep 對 leo 的 Mac 那一格只在 fixture 上驗過,交棒給 leo 親跑。

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0178ef1fGw3XeZtpN7LaZrm4
2026-09-07 07:19:39 +00:00
claude-code 7750299b18 Merge pull request '一個 repo 只有一個資料夾:分身住 repo 裡面的 .worktrees/,收工由同一支閘收掉;scripts/worktree sweep 整理現場(inkstone/ISEP#147)' (#148) from feat/147-one-folder-per-repo into main 2026-09-07 07:19:19 +00:00
isep-hand 7cacfdcf11 一個 repo 只有一個資料夾:分身住 repo 裡面的 .worktrees/,收工由同一支閘收掉(inkstone/ISEP#147)
leo 2026-09-07:「一個 repo 只看得到一個資料夾」「禁止這樣產出一大堆資料夾」。
根因:line-needs-own-worktree.sh 教工人開在 repo 旁邊,「收工 remove」只寫在閘訊息裡、沒機制驗,
每條線留一份 ⇒ tech_projects/ 長出 ISEP-wt-117/InkStoneCo-wt-112…一排。規則在文字裡不在機器上。

- scripts/worktree(新):open/close/list/sweep 四個動詞。分身住 <repo>/.worktrees/<票 repo>-<N>
  (走 .git/info/exclude,不動被追蹤的檔);「推了沒」只有這一份判準(三態:有/沒有/問不到,
  問不到不當成沒推也不收);sweep 預設只列不動,--apply 只收「推了且乾淨」,--skip 是操作者點名。
- hooks/line-needs-own-worktree.sh:擋下時印 `scripts/worktree open`(絕對路徑,貼了就跑);
  同一支多掛 PostToolUse Agent|Task——從【工單】認出分身,推了收、沒推點名分支+路徑(exit 2),
  不 force、不刪。+0 支、+1 條(61 支/86 條,當場數的)。
- docs/governance/worktree-placement.md(新)+ principles 一行:禁令與閘互指。
- 測試:line-needs-own-worktree.test.sh 77→110(G 群:閘印的 open 那行原樣跑、旁邊不多任何東西;
  H 群:PostToolUse 推了收/沒推點名/安靜的方向);scripts/test-worktree.sh 42 條(七個分身的 fixture,
  名字照 leo 看到的那排)。舊閘跑新測試 90/110,紅的 20 條正是這次改到的行為。
- permissions-allow.json 加 worktree 四種形狀(出路在雲端被分類器擋就走不通)。
- README/plugin.json/hooks-inventory 的數字在這棵樹上實數:61 支、86 條、62 支腳本。

待總管定版(改了會被載入的東西)。沒碰 hooks/lib/mainline.py。

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0178ef1fGw3XeZtpN7LaZrm4
2026-09-07 07:13:21 +00:00
claude-code 13b97027d1 Merge pull request '定版 v0.27.0(兩支閘看的是指令要動的那個 repo,不是 hook 自己的環境)' (#146) from chore/v0.27.0 into main 2026-09-07 06:41:21 +00:00
claude-code 3d18b6c8e5 定版 v0.27.0(兩支閘看的是指令要動的那個 repo,不是 hook 自己的環境)
總管定版:inkstone/ISEP#109(PR #145)——line-needs-own-worktree.sh 的出路認指令字串裡的 WORKTREE_OK=1 前綴、
先剝 heredoc 再解析;github-contact-guard.sh 在這條指令實際會推的那個 repo 裡解 remote(cd 鏈/-C),
解不出才退回 cwd,判準仍是 URL 主機。來由:09-07 總管與 arcrun-hand 各撞一次(ISEP#109 comment 6629)。

總管在「分支 ⊕ main」重跑:line-needs-own-worktree 77/77、github-contact-guard 26/26、
push-guard 13/13、cross-repo 19/19、版本一致 、plugin validate ;
把當天被誤擋的兩條指令原樣餵 hook:放行;該擋的兩條:擋。
數字在這棵樹上實數:61 支閘/85 條註冊/7 位工人/7 支命令/2 支 skill/60 支腳本。

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0178ef1fGw3XeZtpN7LaZrm4
2026-09-07 06:40:54 +00:00
claude-code f13eed7ca2 Merge pull request '兩支閘改看「指令要動的那個 repo」,不看 hook 自己的環境/cwd:worktree 出路走得通、D20 看 push 實際目標(inkstone/ISEP#109→6629、#125)' (#145) from feat/109-gate-sees-target-repo into main 2026-09-07 06:40:07 +00:00
isep-hand 95c6fee199 worktree 閘:heredoc 的 body 是資料不是指令,並把 inkstone/ISEP#125 的驗收表 A–F 寫成測試
#125 缺陷 D/E(09-02 兩次實地命中):用 heredoc 寫一份內含 `cd <目錄> && git checkout X` 示範的
說明文件,整條指令沒有 git 操作卻被擋。沿用 lib/strip_heredoc.py(D20 閘同一支)先剝 body 再解析。
A–F 六條照票上期望值進 hooks/tests/(A–E 0、F 2)。
(76) 把 tokenize 層「換行被當空白吞掉」寫成已知邊界測試(舊閘同樣 exit=0,漏擋不是誤攔,與 (53) 同層,另報)。
A24:69→77。

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0178ef1fGw3XeZtpN7LaZrm4
2026-09-07 06:35:28 +00:00
isep-hand 49a7145e70 兩支閘改看「指令要動的那個 repo」,不看 hook 自己的環境/cwd(inkstone/ISEP#109 → comment 6629)
① line-needs-own-worktree.sh:出路 `WORKTREE_OK=1 git -C … checkout …` 改認指令字串裡的字面前綴
   (舊版讀 hook 自己的環境變數,PreToolUse hook 跟指令不是同一個行程,那行永遠走不通)。
   判準是位置不是字:前綴必須掛在會移動 HEAD 的那條 git 指令上。
   lib/checkout_target_dir.py 加 `--escape NAME=1`;push_target_dir._classify 在 strip_env 時
   把前綴留在 verb 事件裡(find_push_target 行為不變,主線閘 10+19 條照綠)。
② github-contact-guard.sh:remote 名在「這條指令實際會推的那個 repo」裡解(沿用 lib/push_target_dir.py
   解 cd 鏈/-C/子殼),解不出來才退回 cwd。判準仍是 remote URL 主機,不是「有 -C 就放行」。

測試:A24 59→69(E 群把閘印的那一行原樣餵回去;舊閘 3 條紅)、
      A39 14→26(payload 帶 cwd、cwd≠目標 repo;舊閘 7 條紅=4 誤攔+3 漏擋)。
盤點表:61 支/85 條,改判準不加閘,當場數的。
版本:待總管定版。

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0178ef1fGw3XeZtpN7LaZrm4
2026-09-07 06:31:45 +00:00
claude-code bcf7c05a7b Merge pull request '定版 v0.26.0(雲端第一則 prompt 的主線是現在這條:兩份主線檔都不在時去 Gitea 讀)' (#144) from chore/v0.26.0 into main 2026-09-07 06:24:01 +00:00
claude-code e9492e5d7c 定版 v0.26.0(雲端第一則 prompt 的主線是現在這條:兩份主線檔都不在時去 Gitea 讀)
總管定版:inkstone/ISEP#140(PR #143)——hooks/lib/mainline.py 第三個來源 fetch_gitea(),
優先序 家目錄 > repo 那份 > Gitea main 那份;匿名優先、被拒才帶 Gitea token;問不到就退回現行行為。
來由:雲端薄殼 SessionStart 跑的時候 InkStoneCo/ 還沒 clone,倒數退到兩週前的舊里程碑(ISEP#140)。

總管在「分支 ⊕ main」重跑:mainline-gitea-fallback 31/31、mainline-repo-mirror 17/17、countdown-guard 20/20、
mainline-focus-guard 24/24、test-ticket-pick 48/48;真形狀(空 state dir、空專案目錄)帶 token 第一行即主線、拔 token rc 0 零檔案。
數字在這棵樹上實數:61 支閘/85 條註冊/7 位工人/7 支命令/2 支 skill/60 支腳本。

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0178ef1fGw3XeZtpN7LaZrm4
2026-09-07 06:23:34 +00:00
claude-code 5b0267112f Merge pull request '雲端第一則 prompt 的主線是現在這條:兩份主線檔都不在時 refresh 去 Gitea 讀 InkStoneCo main 那份一次(inkstone/ISEP#140)' (#143) from feat/140-mainline-gitea-fallback into main 2026-09-07 06:23:03 +00:00
Leo 48befe8906 雲端第一則 prompt 的主線是現在這條:兩份主線檔都不在時 refresh 去 Gitea 讀 InkStoneCo main 那份一次(inkstone/ISEP#140)
薄殼 SessionStart 跑在 bootstrap.sh 之前,InkStoneCo/ 還沒 clone、家目錄空 ⇒ 兩份都不在 ⇒
countdown.py 退到「期限最近的 milestone」⇒ 第一則 prompt 印逾期 341 小時的舊線。機制沒壞,是順序。

- hooks/lib/mainline.py:第三個來源 fetch_gitea()(本檔唯一會打網路的函式,只有 SessionStart 的
  `mainline refresh` 叫它;load()/line() 照舊零網路)。優先序寫進檔頭:家目錄 > repo 那份 > Gitea 那份。
  匿名優先,匿名被拒(401/403/404)且拿得到 token 才帶 token 再問一次;讀不到回 None,逾時有上限。
- scripts/mainline refresh:兩份都不在 ⇒ fetch_gitea 一次、只寫家目錄(不 mirror);token 拿不到不炸、不抱怨。
- hooks/tests/mainline-gitea-fallback.test.sh:31 條,假 Gitea 有 public/private/500/garbage/notitle/hang 六種回法。

假設(票上紅線寫「一律匿名不帶 token」,其前提「Gitea 匿名讀得到」實測為假):
inkstone/InkStoneCo 在 Gitea 是 private——匿名打 raw/contents/repo API 都 404,ISEP 同端點 200。
⇒ 照字面做這張票在真環境永遠讀不到。改成匿名優先、被拒才帶 token(同一條 SessionStart 鏈上
countdown-milestone-refresh.sh 本來就帶 GITEA_TOKEN_CLAUDE_CODE 打 Gitea;D20 管的是 GitHub)。
真跑:帶 token 2.06s 讀到 inkstone/Arcrun#48;拔 token rc 0、零檔案、「現在沒有主線」。

版本:待總管定版。

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0178ef1fGw3XeZtpN7LaZrm4
2026-09-07 06:19:39 +00:00
claude-code 1c0012107f Merge pull request '定版 v0.25.0(出貨鏈三站上 main:tag → release → 開場覆核)' (#142) from chore/v0.25.0 into main 2026-09-07 06:01:14 +00:00
claude-code 56ae38d8d4 定版 v0.25.0(出貨鏈三站上 main:tag → release → 開場覆核)
總管定版:inkstone/ISEP#67(PR #141)——release-ship/release-check/hooks/lib/release_chain.py 進 main,
SessionStart 信標第④段開場報「打了 tag 沒 release」;release-ship 前置①改看要送的那個 tag 的樹。
來由:v0.23.0/v0.24.0 只有 tag 沒 release,交給 leo 的測試連結是空頁(ISEP#67 comment 6574)。

總管在「分支 ⊕ main」重跑:test-release-ship 14/14、test-release-check 14/14、信標 33/33、
全套 scripts/test-*.sh 紅的與 main 基線同兩支(make-cloud-env、ticket-api-bypass-guard)、
check-version-consistency 、claude plugin validate 。
數字在這棵樹上實數:61 支閘/85 條註冊/7 位工人/7 支命令/2 支 skill/60 支腳本。

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0178ef1fGw3XeZtpN7LaZrm4
2026-09-07 06:00:44 +00:00
claude-code b4d47e94c9 Merge pull request '出貨鏈三站上 main:tag → release → 開場覆核,release-ship 前置①改看 tag 的樹(inkstone/ISEP#67)' (#141) from feat/67-release-chain-on-main into main 2026-09-07 05:59:40 +00:00
claude-code fef35ed03a 出貨鏈三站上 main:release-ship 前置①改看 tag 的樹、release-check 可指定版本、信標開場報「打了 tag 沒 release」(inkstone/ISEP#67)
- hooks/lib/release_chain.py:問 Gitea 的判準一份三處用(匿名讀,D20)
- scripts/release-ship:前置①比「要建的那個 tag 的樹」裡的 plugin.json,不比工作樹/最新 tag
  (總管 09-07 在 v0.23.0 被擋的情境現在放行);note 從 Gitea compare 生,從 plugin 快取跑也行;
  覆核改跑 release-check <那個 tag>
- scripts/release-check [vX.Y.Z]:指定版本;v0.19/0.20/0.21 依裁決標「不補」不再黃字;補法印正本絕對路徑
- hooks/lib/beacon_report.py ④:最新 tag 沒 release/main 定版沒打 tag ⇒ 一行缺站+補法;都在安靜;
  只快取「都在」6 小時
- 測試:test-release-ship 14、test-release-check 14、信標 26→33;docs:TESTING A37/A38、盤點表、README 60 支腳本、
  白名單加 release-ship/release-check 形狀、mistakes 一條
- 沒改 plugin.json 版本號(待總管定版)

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0178ef1fGw3XeZtpN7LaZrm4
2026-09-07 05:52:41 +00:00
Claude 1fa45cd539 Merge remote-tracking branch 'origin/feat/release-ship-the-chain' into feat/67-release-chain-on-main 2026-09-07 05:40:59 +00:00
claude-code f2ebeb441e Merge pull request '定版 v0.24.0(雲端對 stage 的寫入有正門)' (#139) from chore/v0.24.0 into main 2026-09-07 02:36:32 +00:00
claude-code 5bf7d1c729 定版 v0.24.0(雲端對 stage 的寫入有正門)
總管定版:inkstone/ISEP#137(PR #138)——`scripts/stage`(secret/api 兩個子命令)
只寫 youlin stage 帳號、值只從環境變數名讀、非 stage 一律拒絕;白名單多五條固定形狀
(含 Arcrun 的 scripts/stage-deploy-artifacts.py,它自己寫死只打 youlin)。
來由:09-07 三條主線工人對 stage 的三種寫入全被雲端 auto mode 分類器擋,
leo:「為什麼會擋你,這就是要修復的問題」。

總管在「分支 ⊕ main」上重跑:test-stage 45/45、test-settings-allow-sync 19/19、版本一致 。
數字在這棵樹上實數:61 支閘/85 條註冊/7 位工人/7 支命令/2 支 skill/56 支腳本。

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DTZ9QtvjY7MNxjfQbexAm7
2026-09-07 02:36:12 +00:00
claude-code 06a4dd5b7b Merge pull request '雲端對 stage 的寫入有正門:scripts/stage(secret/api)只寫 youlin,白名單放固定形狀(inkstone/ISEP#137)' (#138) from feat/137-stage-secret-put into main 2026-09-07 02:35:42 +00:00
Leo d19bf88503 雲端對 stage 的寫入有正門:scripts/stage(secret/api)只寫 youlin,白名單放固定形狀(inkstone/ISEP#137)
09-07 三種寫入在雲端全被 auto mode 分類器擋:npx wrangler secret put、
stage-deploy-artifacts.py --confirm、curl POST 到 arcrun-yuga3bse——
白名單是逐條比前綴,複合指令與任意 curl 永遠對不上;放整類又是紅線。

- scripts/stage secret put|list|delete:直接打 CF API(不經 npx);先 GET /accounts
  看這把 token 打得到誰,stage 的 ID 不在裡面就拒絕並印出它打得到誰;URL 永遠只帶
  1129efd7…;值只從 --from-env 讀,--value 拒收。
- scripts/stage api <METHOD> <worker>/<path>:curl 打實例,主機只會是
  *.arcrun-yuga3bse.workers.dev,別的主機拒絕;標頭與 body 走 stdin 設定檔+管線,
  不走 argv;--bearer-env/--header-env/--data-env 從環境變數讀。
- docs/permissions-allow.json:stage 四種形狀+Arcrun 自己那支 stage-deploy-artifacts.py
  的相對形狀(它已寫死只認 youlin 帳號 ID、不收 --account/--token,不重造)。
- scripts/test-stage.sh 45 條(假 CF 對 PUT 回 201——第一次實跑 CF 回 201 被講成失敗,
  就是這格抓的);test-settings-allow-sync 仍 19/19。
- 真跑:探針種進 youlin arcrun-cypher-executor、CF API 獨立列到、刪掉恢復原狀;
  api GET health 200、無 Bearer POST 401、leo21c 主機拒絕零請求。
  「帶 Bearer 真寫 KBDB」缺 KBDB_INTERNAL_TOKEN 沒跑(TESTING A36 標明)。

盤點在本樹實數:hooks 61、註冊 85(都沒動)、scripts 56(+stage、+test-stage.sh)。
版本待總管定版。

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DTZ9QtvjY7MNxjfQbexAm7
2026-09-07 02:31:18 +00:00
claude-code 11cef0bec4 Merge pull request '定版 v0.23.0(雲端拿得到票與主線、抓票規則機械可判)' (#136) from chore/v0.23.0 into main 2026-09-07 01:36:10 +00:00
claude-code fed7258a30 定版 v0.23.0(雲端拿得到票與主線、抓票規則機械可判)
總管定版:主線 inkstone/Arcrun#48 這一輪的 ISEP 交付,兩張票一起進:
  • inkstone/ISEP#131(PR #134):ticket pick/claim——雲端工人抓票規則做成純函式,
    「s/* 恰好是 {s/todo}」、排除 hub 與 Human,不再靠 prompt 叮嚀
  • inkstone/ISEP#130(PR #135):主線檔隨 repo 走(家目錄沒有就讀 system-dev/mainline.json)、
    白名單住 ISEP(settings-allow-sync)、isep-notify 走 Bot API、
    leo21c-write-guard 讀放寫擋、prod/main 閘認得 youlin 新子網域 arcrun-yuga3bse

兩張 PR 都在「分支 ⊕ main」上由總管重跑:#134 48/48;#135 帶參數的五支閘測試
與 ask-user-question live 全綠,dispatch-format-guard 40/52 是 main 既有現況。

順手同步 marketplace.json 的描述數字(84→85 條註冊、49→54 支腳本),
六個數字在這棵樹上實數:61 支閘/85 條註冊/7 位工人/7 支命令/2 支 skill/54 支腳本。

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DTZ9QtvjY7MNxjfQbexAm7
2026-09-07 01:35:32 +00:00
claude-code 4ba51b7b04 Merge pull request '雲端要拿得到票、主線與通知:白名單住 ISEP、主線檔隨 repo 走、leo21c 讀放寫擋(inkstone/ISEP#130)' (#135) from feat/130-cloud-full-power into main 2026-09-07 01:34:30 +00:00
isep-hand 57219f3321 併 origin/main(#134 ticket pick/claim)解衝突:盤點數字在合併後的樹重數——61 支、85 條、54 支腳本(inkstone/ISEP#130)
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DTZ9QtvjY7MNxjfQbexAm7
2026-09-07 01:22:33 +00:00
isep-hand 65120a1c65 雲端要拿得到票、主線與通知:白名單住 ISEP、主線檔隨 repo 走、leo21c 讀放寫擋(inkstone/ISEP#130)
- docs/permissions-allow.json + scripts/settings-allow-sync:四個 Gitea 正門工具的權限白名單一份,
  setup script 裝完 plugin 寫一次、SessionStart 每次再對一次(只加不減、冪等)
- hooks/lib/mainline.py/scripts/mainline:家目錄沒主線就讀 InkStoneCo/system-dev/mainline.json;
  set/adopt/clear 兩份一起寫,refresh 只寫家目錄
- hooks/leo21c-write-guard.sh:唯讀 -d(tr/cut/sort…)先剪掉再判、notify_leo trigger 放行
  (與 prod-write-guard 同一份白名單)、改法段改印 09-02 起的 youlin 子網域;補第一支測試(26 條)
- prod-write-guard/main-and-prod-push-guard/kbdb-live-exam:認得 youlin 新子網域 arcrun-yuga3bse
- scripts/ticket:收件 repo 寫 inkstone/ISEP 不再 404(org 寫錯當場講)
- scripts/isep-notify:有 TELEGRAM_BOT_TOKEN/TELEGRAM_CHAT_ID 先走 Bot API 直送(雲端唯一通的路)
- 測試:A31–A35 共 79 條;README/plugin.json/hooks-inventory 數字實數(61 支、85 條、53 支腳本)

假設(記在這裡等 review):權限規則的形狀沿用 leo 09-07 親手加、實測有效的那四條;
「分類器真的不擋」要雲端一趟 run 的 permission_denials 才驗得到,本 PR 驗不了。
版本:待總管定版(plugin.json 仍 0.22.0)。

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DTZ9QtvjY7MNxjfQbexAm7
2026-09-07 01:17:15 +00:00
claude-code b5d501e9b8 Merge pull request 'ticket pick/claim:雲端工人抓票規則機械可判(inkstone/ISEP#131)' (#134) from feat/131-ticket-pick into main 2026-09-07 01:09:16 +00:00
Claude 49dedbbb15 補上運送鏈缺的兩站:建 release + 回頭覆核(inkstone/ISEP#67)
工單的斷點是「沒有任何東西會建 release」——v0.22.0 tag 早推了,
Gitea Releases 頁卻停在 v0.18.0,對 leo 等於這一版不存在。

新增兩支獨立的站(不改任何既有閘,只補送貨鏈缺的那兩段):

- scripts/release-ship(= arcrun-rag 的 release-record 站)
  把「已推的 tag」變成「leo 看得到的 release」。三個前置條件「必須在場」才放行:
  ①版本一致(重用 check-version-consistency.sh,不另立判準)②tag 真的在 Gitea
  ③release note 有內容(沒給就從 git log 自動生事實清單)。冪等;建完回頭跑
  release-check 拿收貨端覆核——送的人說成功不算。

- scripts/release-check(= release-check 站)
  回頭問每一段「到了嗎」,而且**問的是收貨端**(Gitea tags/releases、這個 session
  載到的 plugin.json),不聽送的人說。現行版本缺 tag 或缺 release ⇒ exit 2 並指名
  缺哪一站+怎麼補(工單驗收 4)。判準是結構(定版 commit / tag / release 在不在),
  不是關鍵字黑名單。

- 兩支離線測試(RELEASE_*_FIXTURE,不打 Gitea):release-check 9 項、release-ship 7 項全過。

實跑證據:release-ship v0.22.0 已在 Gitea 建起
https://git.uncle6.me/inkstone/ISEP/releases/tag/v0.22.0
release-check 覆核 v0.22.0 tag+release 都在(收貨端事實)。

版本:新增的是 scripts/(非自動載入),本身不需升版;待總管定版隨下一版一起送出。

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012656SLtw96aCxTgScH5bbK
2026-09-05 21:01:29 +00:00
53 changed files with 5719 additions and 254 deletions
+1 -1
View File
@@ -8,7 +8,7 @@
"plugins": [ "plugins": [
{ {
"name": "isep", "name": "isep",
"description": "InkStone Environment Plugin —— leo 的 Claude Code 環境唯一真相源:61 支機械閘(84 條註冊,白話盤點見 docs/hooks-inventory.md)、7 支 slash command、2 支 skill、7 位有名字的工人(agents/,見 docs/governance/worker-roster.md)、49 支腳本,外加治理規範與標籤真相源。本機與雲端裝同一份,沒有子集。", "description": "InkStone Environment Plugin —— leo 的 Claude Code 環境唯一真相源:61 支機械閘(85 條註冊,白話盤點見 docs/hooks-inventory.md)、7 支 slash command、2 支 skill、7 位有名字的工人(agents/,見 docs/governance/worker-roster.md)、60 支腳本,外加治理規範與標籤真相源。本機與雲端裝同一份,沒有子集。",
"author": { "author": {
"name": "Leo", "name": "Leo",
"url": "https://uncle6.me" "url": "https://uncle6.me"
+2 -2
View File
@@ -1,7 +1,7 @@
{ {
"name": "isep", "name": "isep",
"description": "InkStone Environment Plugin —— leo 的 Claude Code 環境唯一真相源:61 支機械閘(84 條註冊,白話盤點見 docs/hooks-inventory.md)、7 支 slash command、2 支 skill、7 位有名字的工人(agents/,見 docs/governance/worker-roster.md)、50 支腳本,外加治理規範與標籤真相源。本機與雲端裝同一份,沒有子集。", "description": "InkStone Environment Plugin —— leo 的 Claude Code 環境唯一真相源:61 支機械閘(86 條註冊,白話盤點見 docs/hooks-inventory.md)、7 支 slash command、2 支 skill、7 位有名字的工人(agents/,見 docs/governance/worker-roster.md)、62 支腳本,外加治理規範與標籤真相源。本機與雲端裝同一份,沒有子集。",
"version": "0.22.0", "version": "0.29.0",
"keywords": [ "keywords": [
"inkstone", "inkstone",
"guardrails", "guardrails",
+2 -2
View File
@@ -23,11 +23,11 @@
| | 數量 | 是什麼 | | | 數量 | 是什麼 |
|---|---|---| |---|---|---|
| `hooks/` | 61 支 `hooks.json` | 全部機械閘(PreToolUseStopSubagentStopSessionStartPostToolUseUserPromptSubmit 共 84 條註冊)。**一支一行的白話盤點在 `docs/hooks-inventory.md`,那裡才是這兩個數字的家** | | `hooks/` | 61 支 `hooks.json` | 全部機械閘(PreToolUseStopSubagentStopSessionStartPostToolUseUserPromptSubmit 共 86 條註冊)。**一支一行的白話盤點在 `docs/hooks-inventory.md`,那裡才是這兩個數字的家** |
| `agents/` | 7 位 | **工人名單**`inkstone/ISEP#86`)——派工時指名派給誰,規約見 `docs/governance/worker-roster.md` | | `agents/` | 7 位 | **工人名單**`inkstone/ISEP#86`)——派工時指名派給誰,規約見 `docs/governance/worker-roster.md` |
| `commands/` | 7 支 | `/wiki-recall` `/wiki-capture` `/cp-write` `/issue-handle` … | | `commands/` | 7 支 | `/wiki-recall` `/wiki-capture` `/cp-write` `/issue-handle` … |
| `skills/` | 2 支 | `ship-check`(東西要出去之前)/`deep-recall`(把散落的枝葉還原成一棵樹)。🔴 **這兩支的內容不一定是在這裡寫的**——誰是真相源查 `docs/file-ownership.tsv` | | `skills/` | 2 支 | `ship-check`(東西要出去之前)/`deep-recall`(把散落的枝葉還原成一棵樹)。🔴 **這兩支的內容不一定是在這裡寫的**——誰是真相源查 `docs/file-ownership.tsv` |
| `scripts/` | 50 支 | `ticket``roster``isep-nag``wiki-compress``github-arm.sh` …(頂層檔案,不含 `lib/` 等子目錄) | | `scripts/` | 62 支 | `ticket``roster``isep-nag``wiki-compress``github-arm.sh` …(頂層檔案,不含 `lib/` 等子目錄) |
> 🔴 這五個數字**每次都要在自己的樹上實數**,不准沿用上一版、也不准用加減推 > 🔴 這五個數字**每次都要在自己的樹上實數**,不准沿用上一版、也不准用加減推
> `system-dev/wiki/mistakes.md`:那是 leo 的驗收介面,多報就是假綠): > `system-dev/wiki/mistakes.md`:那是 leo 的驗收介面,多報就是假綠):
+380 -9
View File
@@ -330,12 +330,13 @@ bash hooks/tests/unpushed-police.test.sh
- B 群(⑦—⑩,該報)任一紅 ⇒ 為了不吵而改成放行了,那是把閘關掉不是修好 - B 群(⑦—⑩,該報)任一紅 ⇒ 為了不吵而改成放行了,那是把閘關掉不是修好
- 特別看 ④:問不到遠端(離線)**不准當成「你沒推」** - 特別看 ④:問不到遠端(離線)**不准當成「你沒推」**
### A18 — 信標會講出雲端會壞掉的那幾件事:26 ### A18 — 信標會講出雲端會壞掉的那幾件事:33
``` ```
bash hooks/tests/isep-presence-beacon.test.sh bash hooks/tests/isep-presence-beacon.test.sh
``` ```
**該看到**`通過 26 條,失敗 0 條`。全離線。 **該看到**`通過 33 條,失敗 0 條`。全離線。
> 📌 `inkstone/ISEP#67`2026-09-07)從 26 條加到 33 條:信標 ④ 開場報「打了 tag 卻沒 release」,見 A38。
> 📌 `inkstone/ISEP#122` 從 14 條加到 26 條:信標原本只掃 `scripts/` > 📌 `inkstone/ISEP#122` 從 14 條加到 26 條:信標原本只掃 `scripts/`
> 而**真正會自動載入的東西**skillcommandagent)同樣兩邊各有一份。 > 而**真正會自動載入的東西**skillcommandagent)同樣兩邊各有一份。
> 實查:那 9 個檔案在 `0.1.0`(c263866)複製過來之後**一次都沒再同步**, > 實查:那 9 個檔案在 `0.1.0`(c263866)複製過來之後**一次都沒再同步**,
@@ -419,12 +420,12 @@ bash hooks/tests/gitea-arm-check.test.sh .
- ①③⑤⑥ 任一紅 ⇒ 收手收得太晚,暫存區已經開始長東西(磁碟風險回來了) - ①③⑤⑥ 任一紅 ⇒ 收手收得太晚,暫存區已經開始長東西(磁碟風險回來了)
- ② 紅 ⇒ 訊息沒給出走得通的那一行(本票整張票在講的就是這件事) - ② 紅 ⇒ 訊息沒給出走得通的那一行(本票整張票在講的就是這件事)
- ⑧⑨⑩ 任一紅 ⇒ **誤攔/複製錯**:正常用法被弄壞,或複本裡混進了 `hooks/` 以外的東西 - ⑧⑨⑩ 任一紅 ⇒ **誤攔/複製錯**:正常用法被弄壞,或複本裡混進了 `hooks/` 以外的東西
### A31 — 雲端工人抓票的規則是機械可判的:48 ### A31 — 雲端工人抓票的規則是機械可判的:53
``` ```
bash scripts/test-ticket-pick.sh bash scripts/test-ticket-pick.sh
``` ```
**該看到**`通過 48 條,失敗 0 條`。**全程離線**:假池子(3 個 repo、3 個 open milestone、 **該看到**`通過 53 條,失敗 0 條`。**全程離線**:假池子(3 個 repo、3 個 open milestone、
11 張票)餵給換掉的 `api()`,時鐘走 `ISEP_COUNTDOWN_NOW``TICKET_HOST` 指到連不上的位址 12 張票、1 條相依邊)餵給換掉的 `api()`,時鐘走 `ISEP_COUNTDOWN_NOW``TICKET_HOST` 指到連不上的位址
——任何一條真的走到網路會當場炸,不會靜靜變成假綠。**不開票、不改票、不留任何東西在 Gitea 上。** ——任何一條真的走到網路會當場炸,不會靜靜變成假綠。**不開票、不改票、不留任何東西在 Gitea 上。**
**它在守什麼**`inkstone/ISEP#131`):Routine 08-06 起讀 `journeys.md` 本 sprint 段, **它在守什麼**`inkstone/ISEP#131`):Routine 08-06 起讀 `journeys.md` 本 sprint 段,
@@ -433,8 +434,10 @@ Gitea 主線里程碑抓票(`inkstone/InkStoneCo#118`),但那是一段給
這一支把規則做成 `scripts/ticket pick``claim` 兩個動詞,規則本體在 `pickable()` 一支純函式: 這一支把規則做成 `scripts/ticket pick``claim` 兩個動詞,規則本體在 `pickable()` 一支純函式:
``` ```
可抓 s/* 恰好是 {s/todo} 沒有 assignee 沒有 Humanhuman/* 不是 hub 里程碑=主線 可抓 s/* 恰好是 {s/todo} 沒有 assignee 沒有 Humanhuman/* 不是 hub 主線
主線抓盡才抓「逾期的 open 里程碑」;backlog/沒里程碑一律不抓 「在主線上」=hub 里程碑裡、或被主線成員當相依(跨 repo 邊,inkstone/ISEP#133);
別 repo 裡同名的里程碑**不算**主線。主線抓盡才抓「逾期的 open 里程碑」(一個里程碑物件一組);
backlog/沒里程碑且沒有邊的一律不抓
認領 claim 指派 + s/doing + 第一行【身份】的留言,一個動作 認領 claim 指派 + s/doing + 第一行【身份】的留言,一個動作
完成 handback --label s/review(本來就有的那半,不重做) 完成 handback --label s/review(本來就有的那半,不重做)
``` ```
@@ -447,6 +450,8 @@ Gitea 主線里程碑抓票(`inkstone/InkStoneCo#118`),但那是一段給
要嘛抓盡了還回 `Arcrun#8`(既不是主線也沒逾期) 要嘛抓盡了還回 `Arcrun#8`(既不是主線也沒逾期)
- ②「離開碼 1」紅 ⇒ 「真的沒有票」與「讀不到」被講成同一句——後者要離開碼 2 - ②「離開碼 1」紅 ⇒ 「真的沒有票」與「讀不到」被講成同一句——後者要離開碼 2
- ②「沒有主線 → 離開碼 2 且一通 API 都沒打」紅 ⇒ 沒主線時去抓了別的 - ②「沒有主線 → 離開碼 2 且一通 API 都沒打」紅 ⇒ 沒主線時去抓了別的
- ②「ISEP#1 靠相依進主線」/「ISEP#13 同名沒邊 → 不在」任一紅 ⇒ 成員又變回靠名字算
leo 2026-09-07 推翻的那條判準回來了,A41 也會一起紅)
- ③「該擋」六條任一紅 ⇒ 規則只長在 `pick` 這端,手動 `claim` 一張 Human 的票照樣過 - ③「該擋」六條任一紅 ⇒ 規則只長在 `pick` 這端,手動 `claim` 一張 Human 的票照樣過
- ③「身份名不在名單上 → 一通都沒打」紅 ⇒ 名單以外的名字碰到了 Gitea - ③「身份名不在名單上 → 一通都沒打」紅 ⇒ 名單以外的名字碰到了 Gitea
- ④ 第一條紅 ⇒ 連不上 Gitea 時回了離開碼 1,雲端會把「斷線」當「沒票」收工 - ④ 第一條紅 ⇒ 連不上 Gitea 時回了離開碼 1,雲端會把「斷線」當「沒票」收工
@@ -623,11 +628,35 @@ bash hooks/tests/parallel-lines-cap-guard.test.sh
`PostToolUse:Agent` 在**送出後 5 秒**就觸發(不是收工); `PostToolUse:Agent` 在**送出後 5 秒**就觸發(不是收工);
subagent **不是獨立行程**`ps` 只有一個 claude-code 行程,所以數行程數不到線)。 subagent **不是獨立行程**`ps` 只有一個 claude-code 行程,所以數行程數不到線)。
### A24 — 一條線要有自己的工作目錄:59 ### A24 — 一條線要有自己的工作目錄:110
``` ```
bash hooks/tests/line-needs-own-worktree.test.sh bash hooks/tests/line-needs-own-worktree.test.sh
``` ```
**該看到**`59/59 通過`。離線,每個案例自己開**兩顆**真的 git repo +一份真的 linked worktree。 **該看到**`110/110 通過`。離線,每個案例自己開**兩顆**真的 git repo +一份真的 linked worktree +一顆本機 bare 遠端
**GH 群在守什麼**inkstone/ISEP#1472026-09-07 補):**分身住 repo 裡面,收工要被收。**
leo 在 Finder 看到 `ISEP-wt-122ship``ISEP-wt-117``ISEP-wt115``InkStoneCo-wt-112`…一排——舊版教「開在 repo 旁邊、
收工 `worktree remove`」,而 remove 只寫在閘訊息裡,沒機制驗。
G 群的測資是**閘自己印出來的 `scripts/worktree open` 那一行**(78) 擋一次、(79) 抽出、(80b) 只填票號與分支真的跑),
然後看三件事實:分身在 `<repo>/.worktrees/` 底下、**repo 旁邊的目錄清單一個都沒多**((81))、共用目錄 `git status` 乾淨((82))。
H 群餵的是 PostToolUse `Agent` 的 payload(派工單 `【工單】owner/repo#N`,總管 session):沒推 ⇒ exit 2 點名分支+路徑+推的指令、分身一根寒毛沒動((86)–(91));
推了但有未追蹤檔 ⇒ exit 2((92)–(94));推了且乾淨 ⇒ exit 0、目錄與登記都沒了、**分支還在**((95)–(98));
沒工單/沒分身/工具不是 Agent ⇒ 安靜((99)–(103),誤攔比漏擋嚴重);一單兩票各自處理((104)–(106));
環境裡的 `WORKTREE_OK=1` 是切分支的逃生門,不影響收工((107))。
修之前拿新測試跑舊閘(main 那份):**90/110,20 條紅**——㉖㉙㉚b㉚c(訊息還在教開在旁邊)+ G/H 全部;B/D/E/F 全綠。紅的正好是這次改到的行為。
**E 群在守什麼**comment 65872026-09-07 補):**閘印出來的那條出路要真的走得通。**
閘訊息教的是 `WORKTREE_OK=1 git -C … checkout …`,舊版讀的卻是 hook 自己的環境變數——PreToolUse hook
跟指令不是同一個行程,指令前綴的賦值到不了它 ⇒ 總管三次照貼三次被擋。E 群的測資是**閘自己印出來的那一行**
((61) 先擋一次、(62) 抽出那行、(63) 原樣餵回去要放行);(64)–(67) 釘住判準是**位置不是字**:
`echo WORKTREE_OK=1; git checkout`、前綴掛在別的指令上、值不是 1、寫在 commit 訊息裡,四種都照擋。
修之前拿新測試跑舊閘:(60)(63)(68) 三條紅,其餘全綠——紅的那三條就是真的改到的。
**F 群**是 `inkstone/ISEP#125` 票上原文的驗收表 AF((70)–(75),期望值照票:AE 要 0、**F 要 2**)。
D/E 是「用 heredoc 寫一份內含 `cd <目錄> && git checkout X` 示範的文件」被當成在切分支(09-02 兩次實地命中),
現在先用 `lib/strip_heredoc.py` 剝掉 body 再解析(跟 D20 閘同一支 helper)。(76) 是寫成測試的已知邊界:
tokenize 層把換行當空白吞掉,`…EOF⏎git checkout main` 從第一版起就看不到(漏擋不是誤攔,與 (53) 同層,另報);
(77) 是它的對照組(換成分號就擋)。
**D 群在守什麼**comment 53982026-08-29 補):不只要擋對,還要**說得出是哪一個 repo**。 **D 群在守什麼**comment 53982026-08-29 補):不只要擋對,還要**說得出是哪一個 repo**。
舊版一律拿 payload 的 `cwd` 當答案,於是 `cd <別的 repo> && git checkout` 擋是擋對了, 舊版一律拿 payload 的 `cwd` 當答案,於是 `cd <別的 repo> && git checkout` 擋是擋對了,
@@ -645,6 +674,10 @@ D 群同時釘住反面:認不出來(`cd $VAR`、`cd -`、cd 到不是 repo
擋掉它們等於線動不了工 擋掉它們等於線動不了工
- ① 紅 ⇒ 連總管在自己的目錄裡切分支都被擋。那不是嚴格,那是把共用目錄的主人趕出去 - ① 紅 ⇒ 連總管在自己的目錄裡切分支都被擋。那不是嚴格,那是把共用目錄的主人趕出去
- ㉞㉟ 紅 ⇒ `prune` 做錯了。㉞是沒清掉說謊的登記;**㉟是把還在的 worktree 也弄掉了,那是災難** - ㉞㉟ 紅 ⇒ `prune` 做錯了。㉞是沒清掉說謊的登記;**㉟是把還在的 worktree 也弄掉了,那是災難**
- (63) 紅 ⇒ 閘印的出路又走不通了——被擋的人不會停下來修閘,他會去找繞過去的方法(6587 當天就是)
- (64)–(67) 任一紅 ⇒ 出路退化成關鍵字:印個字就能過,閘等於沒有
- (75) 紅 ⇒ **閘廢了**#125 原話):剝 heredoc 剝過頭,真的切也放行
- (76) 紅 ⇒ tokenize 那層被改了,回頭跑 (53) 與推 main 的 1019 條
### A25 — `sdd-guard` 退役了,而且退乾淨了:8 條 ### A25 — `sdd-guard` 退役了,而且退乾淨了:8 條
``` ```
@@ -719,6 +752,319 @@ B 段拿這台機器真正的 `.env` 對帳——**`.env` 不在的機器(雲
> ``` > ```
> ⇒ 第二條正是黑名單會放過去的形狀。 > ⇒ 第二條正是黑名單會放過去的形狀。
### A31 — leo21c 讀可以、寫不行,而且改法指到活著的 youlin:26 條
```
bash hooks/tests/leo21c-write-guard.test.sh
```
**該看到**`通過 26 條,失敗 0 條`。全程離線,這支閘不寫檔,直接跑真跡。
**它在守什麼**inkstone/ISEP#1302026-09-04 雲端 run log):`leo21c-write-guard.sh`
**連讀都擋**——Routine 讀 `notify_leo` 定義那一條被攔下,雲端於是什麼都拿不到。
實查:舊判準 `-d[[:space:]]``| tr -d '\r'``cut -d=` 這種唯讀的 `-d` 當成 curl 的 body
`prod-write-guard.sh` 在 08-12 就修過同一個洞,這支漏了。另外它把 `notify_leo` 的 trigger
一律當寫入擋,而 `prod-write-guard.sh` 從 ISEP#63 起就放行它——**兩支閘對同一條指令說不同的話**。
這支之前**沒有任何測試**,「讀會不會被誤攔」從來沒被驗過。
測資是 Routine 文件(`cloud-worker.md``progress-guard.md`)裡**真的會下的那幾條**。
**失敗**
- A 群任一紅 ⇒ **誤攔**,雲端又回到「連讀都讀不到」;③④⑤ 紅就是 09-04 那個形狀復發
- ⑫ 紅 ⇒ 撞人閘時發 Telegram 叫 leo 又會被擋(inkstone/InkStoneCo#110 的病)
- B 群任一紅 ⇒ 寫得進 leo 的真庫(2026-08-20 那 8 張測試卡的病)。⑬ 特別看:
Routine 的心跳 POST **就是寫入**,它該被擋——那條指令要改,不是閘要放
- ㉔㉕ 紅 ⇒ 閘印的「改法」教人打 09-02 起 DNS 已不存在的舊子網域,照著做只會拿到 000
**修之前用同一份測試跑舊閘(`git show main:hooks/leo21c-write-guard.sh`**:③⑤⑫㉔㉕ 五條紅
——證明這五格是真的改到了,不是測試順著新閘寫的。
### A32 — 主線那個檔隨 repo 走:17 條
```
bash hooks/tests/mainline-repo-mirror.test.sh
```
**該看到**`通過 17 條,失敗 0 條`。全程離線:家目錄那份走 `ISEP_COUNTDOWN_STATE_DIR`
repo 那份走 TMP 底下的假 `InkStoneCo/system-dev/`
**它在守什麼**inkstone/ISEP#130leo 09-05「routine 每天早上開啟後抓不到任務」):
主線只住在家目錄,雲端是另一台機器 ⇒ 不知道主線是哪條。PR inkstone/InkStoneCo#118
把它放進 `system-dev/mainline.json`,這裡驗 ISEP 這一半:**家目錄沒有就讀 repo 那份;
兩份都在 `set_at` 較新的算數;`set``adopt``clear` 兩份一起動;`refresh` 只寫家目錄。**
**失敗**
- ①②③ 紅 ⇒ 雲端(`$CLAUDE_PROJECT_DIR` 是薄殼根、真身在 `InkStoneCo/`)仍然讀不到主線
- ⑤⑥ 紅 ⇒ 誰後標的誰算數這條壞了:本機會把雲端剛標的蓋回去,或反過來
- ⑧ 紅 ⇒ **每開一個 session InkStoneCo 的工作樹就髒一次**,而髒的 diff 沒有人會去 commit
- ⑫ 紅 ⇒ `clear` 之後下一次讀又從 repo 那份長回來
- ⑮ 紅 ⇒ ISEP#82 第 4 條(沒有主線不能整組壞掉)被本票弄壞
雲端實跑(2026-09-07,本 session):`CLAUDE_PROJECT_DIR=/home/user/inkstoneco
ISEP_COUNTDOWN_STATE_DIR=$(mktemp -d) python3 scripts/mainline` → 印出
`🎯 現在的主線:inkstone/Arcrun#48「AI 問一次就看得到全部…」`——家目錄空的,只靠 repo 那份。
### A33 — 權限白名單住 ISEP 一份、兩台各自寫進家目錄:19 條
```
bash scripts/test-settings-allow-sync.sh
```
**該看到**`19/19 通過`。全程在 TMP 底下的假 `settings.json` 上跑,不碰真的 `~/.claude/settings.json`
**它在守什麼**inkstone/ISEP#130 → comment 61206121):leo 09-07 親手加進本機
`InkStoneCo/.claude/settings.json` 的四條(`ticket``mainline``gate-ok``gitea-pr-merge`
雲端沒有 ⇒ 同樣動作被分類器擋(09-04 `permission_denials=6`)。雲端真正讀的薄殼 repo
要 D20 開閘才推得動 ⇒ 清單住 ISEP `docs/permissions-allow.json``scripts/settings-allow-sync`
在那台機器上寫進 `~/.claude/settings.json`:雲端由 `docs/cloud-setup-script.sh` 裝完 plugin 跑一次、
之後每個 SessionStart 再對一次;本機同一支。
**失敗**
- A1 紅 ⇒ 清單裡混進了整類放行(`Bash(python3 *)`)或少了正門工具
- B3B4 紅 ⇒ `~` 沒換成那台的家目錄——雲端是 `/root` 不是 `/Users/youlinhsieh`,規則會對不上
- B7 紅 ⇒ 不冪等,每個 session 都改一次 settings.json
- **C1 紅 ⇒ 動到了別人手加的規則**。這支只准加不准減
- E1 紅 ⇒ 目標壞掉時炸了——它掛在 SessionStart,炸了 session 就沒閘
- F1/F2 紅 ⇒ 沒接線:清單對了但沒人會去跑它
⚠️ **這支驗不了「分類器真的不擋」**——那要在雲端一趟 run 裡看 `permission_denials`
規則的形狀(`Bash(python3 …/isep/*/scripts/ticket *)`)沿用 leo 09-07 親手加、實測有效的那四條。
### A34 — 收件 repo 寫 `owner/repo` 不該是 4047 條
```
bash scripts/test-ticket-repo-arg.sh
```
**該看到**`通過 7 條,失敗 0 條`。把 `scripts/ticket` 當模組載進來、`api()` 換成只記路徑的假貨——
不打 Gitea、不開票、不留戳記。
**它在守什麼**inkstone/ISEP#130 → comment 6120 第 2 件):09-07 `ticket new inkstone/ISEP`
回 404。不是 ISEP 不存在,是 `inkstone/ISEP` 被原樣塞進 `/repos/inkstone/{repo}/issues`
⇒ 打到 `/repos/inkstone/inkstone/ISEP/issues`。**正門壞了人就走側門**——那天四張票是直接打 API 開的。
**失敗**:② 紅 ⇒ 那個 404 復發;③ 紅 ⇒ 寫錯 org 又變成一個要人猜的 404;⑦ 紅 ⇒ 路徑裡出現 `inkstone/inkstone`
### A35 — 雲端唯一通的通知路(Bot API 直送):10 條
```
bash scripts/test-isep-notify-botapi.sh
```
**該看到**`10/10 通過`。Bot API 指到本機一個假伺服器、實例那條也指到它——不打真 Telegram、不打實例。
**它在守什麼**inkstone/ISEP#1302026-09-07 從雲端實測):
```
notify_leo @ leo21c → HTTP 404「找不到 workflow」(08-28 起就斷;修它是 leo 的人閘)
notify_leo @ youlin → 雲端 egress proxy 回 403policy denial;要 leo 在 Cloud environment 放行主機)
api.telegram.org → 302,通
```
⇒ 雲端唯一走得通的是 Bot API 直送,只缺 `TELEGRAM_BOT_TOKEN``TELEGRAM_CHAT_ID` 兩個環境變數。
有就先走它(不碰實例,閘管不到也不必管);沒有要**點名缺哪兩個**,不能靜默。
**失敗**:A1 紅 ⇒ 沒憑證時不講缺什麼,leo 不知道要在 Cloud environment 加哪兩個;
B3 紅 ⇒ 送到了還去打實例;C1 紅 ⇒ 401 被講成送到;D1 紅 ⇒ 舊版閘 block 時直送也被連坐。
### A36 — 雲端對 stage 的寫入有正門,而且只寫得進 stage:45 條
```
bash scripts/test-stage.sh
```
**該看到**`45/45 通過`。CF API 與 stage 實例都指到本機一個假伺服器——不打真 Cloudflare、不碰任何 worker。
假伺服器對 secret PUT 回 **201**(真 CF 就是 201)。
**它在守什麼**inkstone/ISEP#1372026-09-07 三條主線工人在雲端撞的同一面牆):
```
printf … | npx wrangler secret put … ← 分類器擋(複合指令對不上白名單任何一條前綴)
python3 scripts/stage-deploy-artifacts.py all --confirm ← 分類器擋
curl -X POST …arcrun-yuga3bse.workers.dev/records ← 分類器擋;0.21.0 的 prod-write-guard 又當它是 prod
```
`scripts/stage``secret putlistdelete`(直接打 CF API,不經 npx)與 `api <METHOD> <worker>/<path>`
(curl 打實例,標頭與 body 走 stdin,不走 argv)。**只寫 stage**secret 先 `GET /accounts` 看這把 token
打得到誰、URL 永遠只帶 `1129efd7…`api 的主機只會長在 `*.arcrun-yuga3bse.workers.dev`
值只從環境變數名讀(`--from-env``--bearer-env``--header-env``--data-env`),`--value``--bearer``--header` 一律拒收。
Arcrun 的 `stage-deploy-artifacts.py` 自己已寫死只認 youlin 帳號 ID、不收 `--account``--token`
白名單直接放它從 Arcrun 根目錄跑的相對形狀,不重造一支。
**失敗**
- A1B1B2D1D2 紅 ⇒ **非 stage 也寫得進去**——這是本工具存在的唯一理由
- A4/D3 紅 ⇒ 值可以從指令列進來(會進 shell 歷史與 session log
- C1 紅 ⇒ 又把 201 講成失敗(第一次實跑就是這樣:CF 種好了、工具說失敗)
- C7/C9 紅 ⇒ 只信 PUT 的回應不去列
- **E2 紅 ⇒ ISEP 自己的閘誤攔正門**——誤攔比漏擋嚴重,被擋的人會去走側門
- E4 紅 ⇒ 又長出第二支平行的工具
**真實跑(2026-09-07,雲端 sessionisep-hand**
`stage secret put` 把隨機值的 `ISEP_137_PROBE` 種進 youlin `arcrun-cypher-executor` → 不經工具用 CF API 列到
`["ISEP_137_PROBE","KBDB_INTERNAL_TOKEN"]``stage secret delete` → 再列剩 `["KBDB_INTERNAL_TOKEN"]`stage 恢復原狀)。
`stage api GET arcrun-cypher-executor/health` → HTTP 200`stage api POST arcrun-kbdb/map/recompute…` 不帶 Bearer → HTTP 401、離開碼 1(打到了、沒寫);
完整網址指到 leo21c → 拒絕、離開碼 2、零請求。
⚠️ **帶 Bearer 真的寫進 stage KBDB** 這格沒跑——雲端 Cloud environment 沒有 `KBDB_INTERNAL_TOKEN`(它只住在安裝器中心側 KV,Arcrun#176 comment 6487 步驟 0);
`CF_SECRETS_API_TOKEN` 的真值是主線 B-3Arcrun#86)的東西,由總管用 `stage secret put` 種,本票不編一個假的塞進去。
⚠️ 「分類器真的不擋」與 A33 同款:要下一版裝進雲端之後,看一趟 run 的 `permission_denials`
### A37 — 打了 tag 之後那一站:把 tag 建成 leo 看得到的 release14 條
```
bash scripts/test-release-ship.sh
```
**該看到**`共 14 項:✅ 14 ❌ 0`。全程離線(`RELEASE_SHIP_FIXTURE``RELEASE_SHIP_SINK`),
**不打 Gitea、不建任何真 release**。fixture 的形狀見 `hooks/lib/release_chain.py`
**它在守什麼**`inkstone/ISEP#67`):ISEP 全樹沒有任何東西會建 release,於是 tag 推了、
Releases 頁停在舊版——08-27v0.4.0v0.5.0)、09-02v0.22.0)、09-07v0.23.0v0.24.0
同一站斷了三輪;09-07 那次交棒給 leo 的「測試位置」打開是一頁空 tag。
三個前置**必須在場**才放行:① **那個 tag 的樹**裡 `plugin.json` tag 號碼(問 Gitea `contents?ref=<tag>`
**不是工作樹**)② tag 真的在 Gitea ③ note 有內容(沒給就從 Gitea compare 生事實清單)。
建完回頭跑 `release-check <那個 tag>` 拿收貨端覆核——送的人說成功不算數。
**失敗**
- A1 紅 ⇒ tag 的樹自己講錯版本也建得了,leo 裝到的會各說各話
- B4 那三條任一紅 ⇒ **前置①又回去比「最新的 tag」或工作樹了**——總管 09-07 在 v0.23.0 的 checkout
`release-ship v0.23.0` 就是這樣被擋的(訊息說最新是 v0.24.0),這一組工作樹故意擺 `9.9.9`
- B2 第二條紅 ⇒ 已存在的 release 被說成「已建立」(09-05 comment 6207 那句假綠,scout 6213 抓到的)
- B3 第二條紅 ⇒ `--dry-run` 真的寫了東西
**真實跑(2026-09-07isep-hand,全部唯讀)**:工作樹在本分支(plugin.json 0.24.0)跑
`release-ship v0.23.0 --dry-run` → 前置②✅、前置①「tag v0.23.0 的樹裡 plugin.json 0.23.0」✅、
「本來就在了——不重複建、不動它」、覆核 `v0.23.0 ✅✅✅ ←`、exit 009-05 那版在同一情境是 exit 2);
`release-ship v0.3.4 --dry-run`(現存唯一沒 release 的 tag)走到「要建」那條路:note 從 Gitea compare 生 8 行、不 POST、exit 0。
### A38 — 回頭問收貨端「到了嗎」,而且開場就會問:14 條+信標 7 條
```
bash scripts/test-release-check.sh
bash hooks/tests/isep-presence-beacon.test.sh # ㉗–㉝ 那七條
```
**該看到**`共 14 項:✅ 14 ❌ 0`;信標 `通過 33 條,失敗 0 條`。全離線。
**它在守什麼**`inkstone/ISEP#67` → comment 6574,總管 09-07 裁定②):「打了 tag 卻沒 release」
要在**下一個 session 開場**就被報出來(一行:缺哪一站+怎麼補),不靠人記得;兩者都在時安靜。
`release-check` 逐版問 Gitea(匿名,D20),現行版本缺站 ⇒ exit 2 +指名缺哪一站+補法(正本絕對路徑);
更舊版本缺件只黃字;**v0.19/0.20/0.21 已裁定不補**(同一則 comment 裁定①),表上標出處、不再黃字。
信標 ④ 用同一份判準(`hooks/lib/release_chain.py`):最新 tag 沒 release ⇒ 報;main 定版比最新 tag 新 ⇒ 報缺 tag;
只快取「都在」6 小時,缺件不快取——補完的下一個 session 就該安靜。
**失敗**
- A1/A2 紅 ⇒ 驗收 4 沒過:故意漏一站,管線說不出缺哪一站
- A3 紅 ⇒ `release-check <版本>` 沒看你指定的那一版(release-ship 送完覆核會覆核到錯的版本)
- B2 紅 ⇒ **誤攔**:現行版本好好的,舊版缺件卻擋下來(懲罰謹慎)
- B4 紅 ⇒ 裁定過不補的三版又天天黃字(會被學會忽略);或裁決把事實也改掉了(指定它來問應該照擋)
- 信標 ㉗ 紅 ⇒ 開場報不出來,斷點又回到靠人記得;㉙ 紅 ⇒ **誤攔**:都在還念;
㉚ 紅 ⇒ 問不到收貨端時亂猜;㉜ 紅 ⇒ 印了一條在這一份裡不存在的路徑當出路;㉝ 紅 ⇒ 補完還要念 6 小時
**真實跑(2026-09-07**:信標不帶 fixture 打真 Gitea(匿名)→ 安靜(v0.24.0 tagrelease 都在),
留下 `.isep-chain-ok-v0.24.0` 快取;`release-check` 在本分支 → `v0.24.0 ✅✅✅ ←`、三個裁定不補的版本標 ⏭、exit 0。
### A39 — D20 閘判「push 到哪」看的是指令實際會推的那個 repo:26 條
```
bash scripts/test-github-contact-guard.sh
```
**該看到**`26/26 通過`。離線;後 12 條自己開兩顆 git repo`shell` 的 origingithub.com、
`body` 的 origin 是 Gitea 的形狀),payload 帶 `cwd`,跟 hook 真的會收到的一樣。
**它在守什麼**`inkstone/ISEP#109` → comment 66292026-09-07 實撞):雲端薄殼的 cwd 是 GitHub 那份,
總管站在那裡 `git -C <InkStoneCo> push origin x`InkStoneCo 的 originGitea),舊版拿 **hook 收到的 cwd**
`origin` ⇒ 判成「指向 GitHub」擋下,`-C` 看都沒看;arcrun-hand 同日在 `Arcrun#176` comment 6614 撞到同一支。
現在 remote 名在**這條指令實際會推的那個 repo** 裡解(沿用 `hooks/lib/push_target_dir.py`cd 鏈、`-C`
子殼不外洩,推 main 那道閘 08-23 就為同一個病接的它);判準仍是 remote 解出來的 URL 主機,**不是「有 -C 就放行」**。
修之前拿新測試跑舊閘:**7 條紅**——4 條是誤攔(推 Gitea 被擋),**3 條是漏擋**(站在 Gitea 那份 `-C` 到薄殼推 GitHub,舊版放行)。
**失敗**
- 「不該擋」6 條任一紅 ⇒ **誤攔**:雲端推 Gitea 分支又得改用完整網址繞路,久了整道閘沒人當真
- 「該擋」5 條任一紅 ⇒ D20 有洞:`-C``cd` 指到 GitHub 那份的 push 沒被攔
- `(cd body && true); git push` 那條紅 ⇒ 子殼的 cd 外洩了(08-11 穿透的形狀)
- 前 14 條紅 ⇒ 舊有判準(heredoc/引號裡的散文/讀取放行)被改壞
### A37 — 雲端第一則 prompt 的主線就是現在這條,不是兩週前的舊線:31 條
```
bash hooks/tests/mainline-gitea-fallback.test.sh
```
**該看到**`通過 31 條,失敗 0 條`。全程離線:Gitea 是本機一個假伺服器(`TICKET_HOST` 指過去),
它照真 Gitea 回——public 時 raw 端點匿名 200**private 時匿名 404、帶 token 200**(真 `inkstone/InkStoneCo`
就是 private2026-09-07 實測匿名打 rawcontentsrepo API 都 404)。狀態走 `ISEP_COUNTDOWN_STATE_DIR`
repo 那份走 TMP 底下的假薄殼。
**它在守什麼**inkstone/ISEP#140;母票 #130):薄殼 `youlinhsieh/inkstoneco` 的 SessionStart 跑在 `bootstrap.sh`
之前——`InkStoneCo/` 還沒 clone、家目錄又是空的 ⇒ 兩份主線檔都不在 ⇒ `countdown.py` 退到「期限最近的 milestone」
⇒ 第一則 prompt 印 `🔴 主線 把管理這條線做對 已逾期 341 小時``🎯 現在沒有主線`。機制沒壞,是順序。
`scripts/mainline refresh`SessionStart)在兩份都不在時去 Gitea 讀 `inkstone/InkStoneCo` main 的
`system-dev/mainline.json` **一次**、寫進家目錄;之後每一則 UserPromptSubmit 讀家目錄,路徑上照舊零網路。
優先序寫死在 `hooks/lib/mainline.py` 檔頭:**家目錄 > repo 那份 > Gitea 那份**,不是第二套來源。
**失敗**
- ①② 紅 ⇒ 前置狀態測不到(票上撞到的那個畫面重現不了,後面全是假綠)
- ⑥⑦⑧ 紅 ⇒ 第一則 prompt 仍是「沒有主線」或那條逾期的舊線——本票要解的就是這一格
- ⑨⑲ 紅 ⇒ 一上來就實名(讀的形狀是匿名優先,被拒才帶 token)
- ⑬ 紅 ⇒ **每一則訊息的路徑上打了網路**`load()``line()` 從不打網路這條被弄壞)
- ⑭⑳㉒ 紅 ⇒ 家目錄或 repo 那份在場還去問 Gitea,或讀 repo 那份時順手寫了家目錄(A32 ④)
- ⑮⑯⑰㉓㉔㉕㉖㉗ 紅 ⇒ 讀不到時不是安靜退回:炸、掛住、或往 stderr 抱怨(SessionStart 每次都會看到)
- ㉘㉙ 紅 ⇒ bootstrap 之後 repo 那份出現時,`set_at` 規則(A32 ⑤⑦)被本票弄壞
**真實跑(2026-09-07,雲端 sessionisep-hand**:薄殼形狀(空家目錄、`$CLAUDE_PROJECT_DIR` 是沒有 `InkStoneCo/`
的空目錄)——環境有 `GITEA_TOKEN_CLAUDE_CODE``mainline refresh` 2.06 秒、rc 0`mainline`
`inkstone/Arcrun#48「AI 問一次就看得到全部…」`UserPromptSubmit 餵 `countdown-guard.sh`
`⏱ …|主線 AI 問一次就看得到全部… 剩 137 小時 41 分``🎯 主線:inkstone/Arcrun#48…`
拔掉 token:rc 0、家目錄零檔案、印「現在沒有主線」、薄殼目錄仍是空的。
⚠️ **「新開一個雲端 session、不跑任何指令、第一眼就是它」**這格要下一版裝進雲端才驗得到——
前提是 Cloud environment 有 `GITEA_TOKEN_CLAUDE_CODE`(本 session 有),沒有就跟 0.25.0 一樣退到舊線。
### A40 — 一個 repo 只有一個資料夾:`scripts/worktree`sweep 現場整理):42 條
```
bash scripts/test-worktree.sh
```
**該看到**`通過 42 條,失敗 0 條`。全程離線:遠端是本機 bare repo,不碰任何真的 repo。
**它守什麼**inkstone/ISEP#147):leo 在 Mac 上跑一次的整理工具。fixture 照他 09-07 在 Finder 看到的那排分身
**原樣造出來**`course_gen-ticket-3-notes``course_gen-ticket-4-handouts``ax-courses-ticket1``ISEP-wt-122ship`
`ISEP-wt-117``ISEP-wt115``InkStoneCo-wt-112`,各自處境不同:推了乾淨、沒推、髒、登記指向空氣),
外加一份新家 `.worktrees/` 裡的與一個沒人登記的孤兒目錄。
- **A dry-run**(1)(13)):每份落在對的組、沒推的印分支與推的指令、`--skip course_gen` 那兩份在「不碰」組、**目錄樹快照前後相同**。
- **B --apply**(14)(27)):只收「推了且乾淨」的 3 份+prune 空氣登記;沒推的、髒的、`--skip` 的、孤兒的一根寒毛沒動;收掉的分身**分支還在**;第二次冪等。
- **C 判準是事實不是名字**((28)–(32)):不 `--skip``course_gen-*` 照 git 的事實分組;拿掉 remote ⇒ 落在「問不到遠端」、**不當成沒推、也不收**。
- **D opencloselist**(33)(42)):open 的路徑在 `<repo>/.worktrees/`、主 repo `git status` 乾淨、`tech_projects/` 沒多任何資料夾;close 沒推 ⇒ 2 點名,推了 ⇒ 0 目錄沒了,再 close ⇒ 0 不吵。
**失敗**
- (2)(30) 紅 ⇒ **dry-run 動了東西**——leo 跑第一次「只是看看」就已經被改了現場,那是災難。
- (19)–(23) 任一紅 ⇒ 收錯東西:刪了沒推的 commit/動了 `--skip` 的 repo/碰了不明目錄。**不刪任何有未推 commit 的分身**是票上紅線。
- (28)(29) 紅 ⇒ 判準滑回看名字(`course_gen` 被當關鍵字),違反本 repo 紅線。
- (31)(32) 紅 ⇒ 把「離線」當成「沒推」——拿雜訊懲罰謹慎。
### A41 — 主線成員由相依邊決定,不靠同名里程碑:57 條
```
bash hooks/tests/mainline-members-by-dependency.test.sh
```
**該看到**`通過 57 條,失敗 0 條`。**全程離線**:Gitea 是本機一個假伺服器(`TICKET_HOST` 指過去,
照真 Gitea 回:相依 POST 201、**已存在回 500**2026-09-07 實測,不是想像中的 409)、issue 列表用 `milestones=` 名字查),狀態走
`ISEP_COUNTDOWN_STATE_DIR`、repo 那份走 TMP 底下的假薄殼、`HOME` 也指到 TMP。
**不碰真家目錄、不碰真 Gitea、不碰真 InkStoneCo。**
**它在守什麼**`inkstone/ISEP#133` → comment 6743):`scripts/mainline` 第一版檔頭寫
「跨 repo 同名是既有做法,不動它」,成員也照標題跨 repo 收;總管 09-07 照它做、把那句抄進
InkStoneCo 的 ops-facts、還在 arcrun-rag 補建了一個同名的。leo 當天:
「**拆,誰說『同名跨 repo 是 mainline 機制的一部分』,早就定了只有一個 milestone,不同 repo 用指針**」
(規則本身:`inkstone/ISEP#30``inkstone/InkStoneCo#44`)。
現在的判準全部是 Gitea 的欄位,沒有標題比對:
```
錨 owner/repo#<milestone id>:整個 Gitea 只有這一個 milestone 物件
hub 票 mainline set … --hub <owner/repo#N>:這條線的載體票,別 repo 的票用相依指到它
成員 hub 里程碑裡的票 hub 票,沿 /dependencies 邊(跨 repo)收下去(hooks/lib/mainline.py::collect_members
adopt 同 repo ⇒ 掛進 hub 里程碑;別 repo ⇒ POST 相依到 hub 票(或 --via 指定的成員)。不建同名里程碑
```
**失敗**
- A 群 ③④⑤ 任一紅 ⇒ 相依邊沒走到(跨 repo 成員收不到)
- A 群 ⑥⑦ 紅 ⇒ **同名里程碑裡的票又被當成成員**——被推翻的判準回來了
- ⑪ 紅 ⇒ `set` 又去別的 repo 找同名的了
- ⑮⑯⑰ 任一紅 ⇒ `adopt` 別 repo 的票不是加相依:要嘛改了那張票的 milestone、要嘛建了里程碑
- ⑳⑳′ 紅 ⇒ 重複 adopt 炸了或重複 POST 了(冪等要靠「先讀 /dependencies」,真 Gitea 對重複 POST 回 500
- ㉔–㉙ 任一紅 ⇒ 沒 hub 票時沒擋、沒給路、或給的路**貼上去跑不動**(㉙ 把訊息裡那行原樣執行)
- ㉛–㉞ 任一紅 ⇒ **票上驗法第 1 條破了**:同名里程碑關掉後成員掉出主線,或 `pick` 抓不到靠邊進來的票
- ㊱㊴㊵ 任一紅 ⇒ `has`focus guard 沒去問 `/blocks`,只看 milestone 就下結論(那是「只知一半」)
- ㊹ 紅 ⇒ 派一張掛在別 repo 同名里程碑、沒邊的票被放行 ⇒ 閘還在拿名字判
- ㊻ 紅 ⇒ Gitea 讀不到時成員被清掉(讀不到 ≠ 沒有成員)
- ㊼–㊿ 任一紅 ⇒ **票上驗法第 3 條破了**:帳本落在 plugin 快取(`claude plugin update` 一換就沒)
📌 **真實 Gitea 唯讀實跑**2026-09-07isep-handstate 與鏡像都指到暫存目錄,不寫 Gitea):
`mainline set inkstone/Arcrun#48 --hub inkstone/InkStoneCo#44` 收到 **25 張成員、5 個 repo**
(里程碑裡 4 + 相依收到 20),其中 `mira#6``ISEP#130``ISEP#140``arcrun-rag#104` 都在
——**不必新增任何邊**,現有的相依圖已經連得到;`has` 四張都回「在」;
`ticket pick --all` 主線組回 `Arcrun#197``mira#5`(後者靠 `Arcrun#86` 的邊,沒掛任何 hub 里程碑)。
**寫入那半也真跑過一次**`adopt inkstone/ISEP#133`hubInkStoneCo#44POST 成功、`/blocks``InkStoneCo#44`、清空快取後 `has``/blocks` 判「在」;重複 POST 真 Gitea 回 **500**(假伺服器原本猜 409——這就是「離線全綠之後一定要真跑一次」),修成先讀 `/dependencies`;測完 DELETE 復原(回 201`/blocks` 空)。
這一走 19 秒(約 30 次序列 GET)⇒ SessionStart 的 `refresh` **不帶** `--members`(成本不變),
`set``adopt``refresh --members` 才重收;`pick``has`/閘每次現問 Gitea,快取只餵 `show`
### A5 — 開票前的搜尋是跨 repo 的 ### A5 — 開票前的搜尋是跨 repo 的
``` ```
python3 scripts/ticket where 標籤 模組化 python3 scripts/ticket where 標籤 模組化
@@ -989,6 +1335,10 @@ B2(信標那行)/B3(setup 輸出)/B4(閘的訊息)三個畫面
| **A12 留言身份欄(兩道門)** | 總管 | ✅ 11/112026-08-27 | | **A12 留言身份欄(兩道門)** | 總管 | ✅ 11/112026-08-27 |
| **A23 同時跑的線有上限** | isep-guard | ✅ 33/332026-08-29inkstone/ISEP#109 | | **A23 同時跑的線有上限** | isep-guard | ✅ 33/332026-08-29inkstone/ISEP#109 |
| **A24 一條線要有自己的工作目錄** | isep-guard | ✅ 35/352026-08-29inkstone/ISEP#109→5391 | | **A24 一條線要有自己的工作目錄** | isep-guard | ✅ 35/352026-08-29inkstone/ISEP#109→5391 |
| **A24 出路那一行原樣餵回去走得通+#125 A–F** | isep-hand | ✅ 77/772026-09-07inkstone/ISEP#109→6587、#125)+真路徑實跑(薄殼 cwd、`-C ISEP`:擋→印的那行→放行)+舊閘實跑 3 條紅 |
| **A39 D20 閘看 push 實際會推的 repo** | isep-hand | ✅ 26/262026-09-07inkstone/ISEP#109→6629)+真路徑實跑(薄殼 cwd:`-C InkStoneCo` 放行、裸 `git push origin` 擋)+舊閘實跑 7 條紅(4 誤攔+3 漏擋) |
| **A24 分身住 repo 裡面+收工被收(G/H 群)** | isep-hand | ✅ 110/1102026-09-07inkstone/ISEP#147)+舊閘實跑 20 條紅(訊息+G/H,B/D/E/F 全綠)+本線自己就是 dogfood(分身開在 `ISEP/.worktrees/ISEP-147`,主目錄 `git status` 乾淨) |
| **A40 sweep 現場整理(七個分身的 fixture)** | isep-hand | ✅ 42/422026-09-07inkstone/ISEP#147);**leo 的 Mac 現場**要他自己跑 `sweep ~/tech_projects`(先 dry-run)——這台機器碰不到 |
| **A26 雲端憑證清單這台拿得到** | isep-hand | ✅ 11/112026-09-01inkstone/ISEP#115→5526554155425577)+兩條「該紅」方向實跑 | | **A26 雲端憑證清單這台拿得到** | isep-hand | ✅ 11/112026-09-01inkstone/ISEP#115→5526554155425577)+兩條「該紅」方向實跑 |
| **A16 放行的門真的打得開** | 總管 | ✅ 17/172026-08-28inkstone/ISEP#90 | | **A16 放行的門真的打得開** | 總管 | ✅ 17/172026-08-28inkstone/ISEP#90 |
| **A17 未推警察不誤攔雲端分支** | 總管 | ✅ 10/102026-08-28inkstone/ISEP#90 | | **A17 未推警察不誤攔雲端分支** | 總管 | ✅ 10/102026-08-28inkstone/ISEP#90 |
@@ -996,6 +1346,15 @@ B2(信標那行)/B3(setup 輸出)/B4(閘的訊息)三個畫面
| **A19 下游做完頂層跟著關** | 總管 | ✅ 49/492026-08-28inkstone/ISEP#92 | | **A19 下游做完頂層跟著關** | 總管 | ✅ 49/492026-08-28inkstone/ISEP#92 |
| **A31 雲端工人抓票規則機械可判** | isep-hand | ✅ 48/482026-09-07inkstone/ISEP#131)+真實 Gitea 唯讀實跑+一次真認領 | | **A31 雲端工人抓票規則機械可判** | isep-hand | ✅ 48/482026-09-07inkstone/ISEP#131)+真實 Gitea 唯讀實跑+一次真認領 |
| **A20 舊票有固定管道被撈** | 總管 | ✅ 47/472026-08-28inkstone/ISEP#83)+真實 229 張唯讀實跑 | | **A20 舊票有固定管道被撈** | 總管 | ✅ 47/472026-08-28inkstone/ISEP#83)+真實 229 張唯讀實跑 |
| **A31 leo21c 讀放寫擋+改法指活的 youlin** | isep-hand | ✅ 26/262026-09-07inkstone/ISEP#130)+舊閘實跑 5 條紅 |
| **A32 主線檔隨 repo 走** | isep-hand | ✅ 17/172026-09-07inkstone/ISEP#130)+雲端 session 實跑讀到主線 |
| **A33 權限白名單住 ISEP 一份** | isep-hand | ✅ 19/192026-09-07inkstone/ISEP#130);「分類器真的不擋」要雲端 run 的 `permission_denials` 才驗得到 |
| **A34 收件 repo 寫 owner/repo 不 404** | isep-hand | ✅ 7/72026-09-07inkstone/ISEP#130 |
| **A35 Bot API 直送** | isep-hand | ✅ 10/102026-09-07);**真的到 leo 手機**要 Cloud environment 先有 `TELEGRAM_BOT_TOKEN``TELEGRAM_CHAT_ID`leo |
| **A36 雲端對 stage 的寫入有正門、只寫得進 stage** | isep-hand | ✅ 45/452026-09-07inkstone/ISEP#137)+真實種進 youlin 一把探針再刪掉、真打 stage GET 200/無 Bearer POST 401;「帶 Bearer 真寫 KBDB」缺 `KBDB_INTERNAL_TOKEN` 沒跑 |
| **A37 雲端第一則 prompt 的主線是現在這條** | isep-hand | ✅ 31/312026-09-07inkstone/ISEP#140)+真 Gitea 薄殼形狀實跑(帶 token 讀到 Arcrun#48;匿名退回);「新 session 不跑指令第一眼就是它」要下一版裝進雲端 |
| **A37 tag → release 那一站** | isep-hand | ✅ 14/142026-09-07inkstone/ISEP#67→6574)+真 Gitea 唯讀 dry-run 兩次(v0.23.0 總管被擋的情境、v0.3.4 走到建那條路) |
| **A38 回頭問收貨端+開場會問** | isep-hand | ✅ 14/14+信標 33/332026-09-07inkstone/ISEP#67→6574)+信標真 Gitea 匿名實跑一次安靜 |
| A7 plugin 裝得起來 | 總管 | ✅ | | A7 plugin 裝得起來 | 總管 | ✅ |
| **A8 新 session 閘會觸發** | 總管 | 見本版 release note | | **A8 新 session 閘會觸發** | 總管 | 見本版 release note |
| **B1B5 雲端** | **leo** | 還沒跑(機器碰不到 Cloud environment | | **B1B5 雲端** | **leo** | 還沒跑(機器碰不到 Cloud environment |
@@ -1040,3 +1399,15 @@ arcrun_search_workflows(通知 leo Telegram) → 只回 ship_refresh_cdn 一
`#issuecomment-5182``#issuecomment-5184`),並把原文印在眼前。 `#issuecomment-5182``#issuecomment-5184`),並把原文印在眼前。
**發不出去而靜默,等於沒做;發不出去但講出來並留下退路,就是這支的規格。** **發不出去而靜默,等於沒做;發不出去但講出來並留下退路,就是這支的規格。**
通道修好之後不必改任何程式碼,重跑 `python3 scripts/isep-nag --notify` 即可補驗這一格。 通道修好之後不必改任何程式碼,重跑 `python3 scripts/isep-nag --notify` 即可補驗這一格。
### 2026-09-07 從雲端 session 再量一次(inkstone/ISEP#130
| 路 | 結果 | 誰能修 |
|---|---|---|
| `notify_leo` @ leo21c`…/webhooks/named/leo/notify_leo` | **HTTP 404**,跟 08-28 一樣 | leoleo21c 寫入是人閘) |
| `notify_leo` @ youlin`*.arcrun-yuga3bse.workers.dev` | **連不到:egress proxy 對 CONNECT 回 403**`/__agentproxy/status` 記為 policy denial)。不是 DNS、不是 000 | leoCloud environment 的 allowed network hosts |
| `api.telegram.org` | **302,通** | — |
⇒ 雲端能走的只有 Bot API 直送(`scripts/isep-notify` 現在會先試它),缺的只是兩個環境變數
`TELEGRAM_BOT_TOKEN``TELEGRAM_CHAT_ID`——Routine 文件 `cloud-worker.md` 檔頭本來就列著它們,
只是這個 environment 沒有。**這一格仍然是 leo 的:加變數,然後回一個詞。**
+46
View File
@@ -160,6 +160,52 @@ GitHub、不是 Gitea):
驗 `claude plugin list` 顯示 `isep@inkstone enabled`,且照 §逐條對照 那張表 驗 `claude plugin list` 顯示 `isep@inkstone enabled`,且照 §逐條對照 那張表
再核一次數字。 再核一次數字。
## 雲端要全權處理的三樣:票、主線、通知(inkstone/ISEP#1302026-09-07
leo 09-07:「雲端回覆的問題你首要解決⋯⋯僅有需要依賴 Mac 環境的東西要求地端處理,其他全部需要可以從雲端全權處理。」
09-04 兩支 Routine 的 run log 實查出四件雲端拿不到的東西,ISEP 這一半的解法:
| 拿不到什麼 | 為什麼 | ISEP 這一半 | 還缺誰 |
|---|---|---|---|
| **主線是哪條** | 主線檔只在本機 `~/.claude` | `hooks/lib/mainline.py`:家目錄沒有就讀 repo 的 `InkStoneCo/system-dev/mainline.json`(雲端形狀:`$CLAUDE_PROJECT_DIR` 是薄殼根、真身在 `InkStoneCo/`);`mainline set``adopt``clear` 兩份一起寫。**兩份都不在**SessionStart 跑在 `bootstrap.sh` 之前,`InkStoneCo/` 還沒 clone)⇒ `mainline refresh` 去 Gitea 讀 InkStoneCo main 那份一次寫進家目錄(`inkstone/ISEP#140`)——第一則 prompt 的 ⏱/🎯 就是現在這條,不再退到逾期的舊線 | 總管 `set` 之後要把 repo 那份 commit/併 mainCloud environment 要有 `GITEA_TOKEN_CLAUDE_CODE`InkStoneCo 是 private,匿名讀不到) |
| **正門工具被分類器擋**`permission_denials=6` | leo 09-07 親手加的四條只在本機 settings | `docs/permissions-allow.json` 一份清單;`scripts/settings-allow-sync` 寫進那台的 `~/.claude/settings.json`setup script 裝完 plugin 跑一次,SessionStart 每次再對一次) | 雲端一趟 run 看 `permission_denials`0 才算驗到 |
| **讀 leo21c 也被擋** | `leo21c-write-guard.sh` 把 `tr -d` 的 `-d` 當 body | 唯讀 `-d` 先剪掉再判;`notify_leo` trigger 放行(同 `prod-write-guard` 白名單);改法段改印現役 youlin 子網域 | — |
| **收工摘要到不了手機** | 雲端沒 `TELEGRAM_*`leo21c 的 `notify_leo` 404youlin 被 egress proxy 擋 | `scripts/isep-notify` 有 `TELEGRAM_BOT_TOKEN``TELEGRAM_CHAT_ID` 就先走 Bot API 直送(`api.telegram.org` 從雲端是通的) | **leo**:在 Cloud environment 加那兩個變數 |
### 雲端連不到 youlin 不是 000,是 proxy 4032026-09-07 實查)
```
$ curl -sS -o /dev/null -w '%{http_code}' https://arcrun-cypher-executor.arcrun-yuga3bse.workers.dev/health
curl: (56) CONNECT tunnel failed, response 403 ← egress policy denial
$ curl -sS "$HTTPS_PROXY/__agentproxy/status" | jq .recentRelayFailures
{ "kind": "connect_rejected", "host": "arcrun-cypher-executor.arcrun-yuga3bse.workers.dev:443",
"detail": "gateway answered 403 to CONNECT (policy denial or upstream failure)" }
$ curl … https://arcrun-cypher-executor.leo21c.workers.dev/health → 200
$ curl … https://api.telegram.org/ → 302
$ curl … https://git.uncle6.me/api/v1/version → 200
```
⇒ 09-04 log 寫的「youlin 從雲端 HTTP 000」有兩層:舊子網域 `youlin-hsieh-dev` DNS 已死(總管 09-07 查到),
**而新子網域從雲端是被 policy 擋**——`/root/.ccr/README.md` 明寫「403/407 = 你組織的 egress policy
不允許這個主機,不要重試、不要繞路,回報主機名」。leo21c 通、youlin 不通,差別只在主機有沒有被放行。
**這格是 leo 的**Cloud environment 的 allowed network hosts 加 `*.arcrun-yuga3bse.workers.dev`
在那之前雲端做不了 stage 驗證,所有要打 youlin 的驗證一律交回地端或標 `Human`。
### 只有「要 Mac」的事才交回地端(給 `cloud-worker.md` 的清單草稿)
判準一句話:**這件事依賴的東西隨 repo clone 走得到嗎?走得到就雲端做。**
| 交回地端 | 為什麼雲端做不了 |
|---|---|
| 打包 DMG/簽章/MS Store 送件 | 要 macOS 工具鏈與簽章身分(Keychain),不隨 clone 走 |
| 本機 daemon`~/.arcrun-rag`、`~/.arcrun/config.yaml`)的改與驗 | 住在 leo 的家目錄 |
| 用 `~/.wrangler` OAuth 登入態出貨到 uncle6 | 登入態不隨 clone 走(`make-cloud-env.sh` 檔頭記過) |
| 要 leo 親手輸入的互動閘(`acr recipe push` 的暴露同意、密碼打進登入欄) | surface 層硬規則,誰都不能代 |
| ~~打 youlin stage 的驗證~~ | 09-07 已回到雲端:`*.arcrun-yuga3bse.workers.dev` 從雲端 curl 200。**寫入走 `scripts/stage`**secretapiinkstone/ISEP#137),不再交回地端 |
其餘(讀票、認領、留言、handback、寫 code、跑測試、開 PR、對 leo21c 唯讀查詢、發 Telegram、**種 secret/直推成品/POST 到 stage 實例**——走 `scripts/stage` 與 Arcrun 的 `stage-deploy-artifacts.py`)雲端全做。
📌 這份清單的家是 `inkstone/InkStoneCo` 的 `cloud-worker.md`(票上驗收第 4 條),ISEP 只放草稿;併進去由總管做。
## 這張票沒動、也不會動的東西 ## 這張票沒動、也不會動的東西
- 沒有動 `youlinhsieh/inkstoneco`GitHub 薄殼 repo)——這個新機制**完全不需要 - 沒有動 `youlinhsieh/inkstoneco`GitHub 薄殼 repo)——這個新機制**完全不需要
+11
View File
@@ -28,6 +28,17 @@ set -uo pipefail
claude plugin marketplace add https://git.uncle6.me/inkstone/ISEP.git --scope user 2>&1 || true claude plugin marketplace add https://git.uncle6.me/inkstone/ISEP.git --scope user 2>&1 || true
claude plugin install isep@inkstone --scope user 2>&1 || true claude plugin install isep@inkstone --scope user 2>&1 || true
# 🔴 權限白名單(inkstone/ISEP#130):四個 Gitea 正門工具(ticketmainlinegate-okgitea-pr-merge
# 要進這台的 ~/.claude/settings.jsonauto mode 的分類器才不擋(09-04 run logpermission_denials=6)。
# 清單住 ISEP `docs/permissions-allow.json` 一份,本機與雲端都由同一支腳本寫——薄殼 repo 不再各養一份。
# plugin 快取的路徑帶版本號,挑最新的那份跑;沒裝成也不擋門,SessionStart 會再對一次。
ISEP_DIR=$(ls -d "$HOME"/.claude/plugins/cache/inkstone/isep/*/ 2>/dev/null | sort -V | tail -1)
if [ -n "$ISEP_DIR" ] && [ -f "$ISEP_DIR/scripts/settings-allow-sync" ]; then
python3 "$ISEP_DIR/scripts/settings-allow-sync" 2>&1 || true
else
echo "⚠️ 找不到裝好的 ISEP,白名單沒寫進 ~/.claude/settings.json——session 開頭 SessionStart 會再試一次。"
fi
if claude plugin marketplace list 2>/dev/null | grep -q "inkstone"; then if claude plugin marketplace list 2>/dev/null | grep -q "inkstone"; then
echo "✅ marketplace inkstone 已就位" echo "✅ marketplace inkstone 已就位"
else else
+3 -1
View File
@@ -471,6 +471,8 @@ Telegram → 純投影。**Wiki 壞不影響 GiteaGitea 壞不影響 SDD
> 🔴 **排序不是按票號,是按「什麼擋住什麼」**:上面的群沒解,下面的群做了也看不到效果。 > 🔴 **排序不是按票號,是按「什麼擋住什麼」**:上面的群沒解,下面的群做了也看不到效果。
> 本節是唯一把六群串起來的地方——Gitea 沒有跨 repo milestone(已查證), > 本節是唯一把六群串起來的地方——Gitea 沒有跨 repo milestone(已查證),
> 各 repo 的同名里程碑都指回這裡。 > 各 repo 的同名里程碑都指回這裡。
> 🔴 **「各 repo 同名」這半句 2026-09-07 已被 leo 推翻**`inkstone/ISEP#133`):一條線只有一個
> milestone,別 repo 的票用相依指到 hub 票;`scripts/mainline` 的成員判定改看相依邊,不看名字。
### 13.0 六群一頁看完 ### 13.0 六群一頁看完
@@ -639,7 +641,7 @@ leo 08-17 診斷見公理 308-17 實測:文字層的閘 **8 次誤攔、0
3. **一切要留痕、可量測。** 閘的動作、開場全局、里程碑百分比——leo 看到的畫面就是實況。 3. **一切要留痕、可量測。** 閘的動作、開場全局、里程碑百分比——leo 看到的畫面就是實況。
4. **進度=舊票關掉幾張。** 版本只是讓閘生效的載具,release note 寫明關了哪張票。 4. **進度=舊票關掉幾張。** 版本只是讓閘生效的載具,release note 寫明關了哪張票。
### 15.2 工作順序(六個里程碑,各 repo 同名,內容一經確定不增不減) ### 15.2 工作順序(六個里程碑,內容一經確定不增不減;「各 repo 同名」已於 2026-09-07 推翻——一條線一個 milestone,別 repo 用相依,`inkstone/ISEP#133`
| 順 | 里程碑 | 來源票(由目標遍歷票池而來,M4.0) | | 順 | 里程碑 | 來源票(由目標遍歷票池而來,M4.0) |
|---|---|---| |---|---|---|
+70
View File
@@ -0,0 +1,70 @@
# 一個 repo 只有一個資料夾:分身住 `.worktrees/`,收工就被收(inkstone/ISEP#147
> leo 2026-09-07(兩則,一字不改):
> 「我看到的是一個 repo,你會產生大量的同一個頭不同尾巴的 repo,全部拆開就更亂了,
> 為什麼要產出新的 repo?這個 repo 的目的就是收納所有相關的內容,這樣散開造成凌亂,
> ISEP, Inkstoneco, Course Gen 這些都產出好多個資料夾,這要整理回去」
> 「另外要在 ISEP 裡寫明,禁止這樣產出一大堆資料夾」
## 規約(三句)
1. 🔴 **禁止在專案目錄旁邊產出分身資料夾。** `tech_projects/` 底下一個 repo 只能有一個資料夾;
`ISEP-wt-117``InkStoneCo-wt-112``course_gen-ticket-3-notes` 這種同頭不同尾的東西不准再長出來。
2. **一條線要隔離工作目錄,分身住 repo 裡面**`<repo>/.worktrees/<票的 repo 名>-<票號>`
Finder 看不到(點開頭)、`git status` 看不到(寫進 `.git/info/exclude`)、`git worktree list` 找得到。
3. **分身是借的,收工要還**:分支推上遠端且工作樹乾淨 ⇒ 收掉;沒推 ⇒ 點名分支與路徑,等人決定。
**絕不 force、絕不刪沒推的 commit。**
## 為什麼會長成那樣(根因,不是誰疏忽)
`hooks/line-needs-own-worktree.sh`inkstone/ISEP#109,08-29 立)擋下線在共用目錄切分支,教它
「開一份在 repo 旁邊、不要在 /tmp、收工時 `worktree remove`」。
那時比較的只有「旁邊 vs /tmp」——/tmp 會被系統清掉、登記簿說謊;旁邊的一份都沒掉。
**一份都沒掉,也一份都沒收**`remove` 那一步只寫在閘訊息裡,沒有任何機制驗。
每個工人留一份,`tech_projects/` 就長成那排。**規則在文字裡,不在機器上**
(同日 ISEP#109 comment 6629 是同一種病:出路寫在訊息裡,機器讀不到)。
## 機器上的兩端
| 端 | 在哪 | 做什麼 |
|---|---|---|
| 開 | `hooks/line-needs-own-worktree.sh`PreToolUse Bash | 擋下共用目錄裡的 checkout,印出 `scripts/worktree open …`(絕對路徑,貼了就能跑) |
| 收 | **同一支閘**多掛 PostToolUse `Agent\|Task` | 從派工單 `【工單】owner/repo#N` 認出分身名字,跑 `scripts/worktree close`:推了收、沒推點名(exit 2) |
| 工具 | `scripts/worktree` | `open``close``list``sweep` 四個動詞;「推了沒」只有這一份判準(三態:有/沒有/問不到,問不到不當成沒推) |
為什麼收的那一半不另開一支閘:教你開的和替你收的是同一件事的兩半,拆成兩支就又是「規則在兩個地方」
`countdown-guard.sh` 同一種形狀:注入與查核是一支閘掛兩個事件)。
為什麼掛 PostToolUse 不掛 SubagentStop:票號在派工單(Agent 的 `tool_input.prompt`)裡,SubagentStop 拿不到
`baton-handback-guard.sh` 檔頭那段實撞)。
## 工人怎麼用
```
python3 <plugin>/scripts/worktree open inkstone/ISEP#147 --repo <repo> -b feat/147-xxx # 開
cd <repo>/.worktrees/ISEP-147 # 在裡面做事
python3 <plugin>/scripts/worktree close inkstone/ISEP#147 --repo <repo> # 收(推了才收得掉)
```
忘了 `close` 也沒關係——線收工那一刻閘會替你跑;但**沒推的它不會替你收**,只會點名。
不要用 `git worktree add <repo>/../<repo>-wt-…` 這條老路;閘訊息已經不印它了。
## leo 在 Mac 上整理現場(一次)
```
python3 ~/.claude/plugins/cache/inkstone/isep/<版本>/scripts/worktree sweep ~/tech_projects # 只列,不動
python3 ~/.claude/plugins/cache/inkstone/isep/<版本>/scripts/worktree sweep ~/tech_projects --apply --skip course_gen
```
- 預設**只列不動**`--apply` 才收,而且只收「推了且乾淨」的。
- 沒推的、有未 commit 的、問不到遠端的、沒有任何 repo 登記它的:**全部列出來、一個都不動**,等他決定。
- `--skip <repo 名>` 是操作者點名不碰的 repo(09-07:`course_gen` 地端正在處理,列可以、不收不動)。
它是操作者的明示指令,不是判準——判準永遠是「這個目錄是不是某個 repo 的 worktree、分支推了沒、乾不乾淨」。
## 測試
- `hooks/tests/line-needs-own-worktree.test.sh` G 群(開在裡面、旁邊不多任何東西、閘印的那行原樣跑得動)
與 H 群(PostToolUse:推了收掉、沒推點名、沒工單/沒分身安靜)。
- `scripts/test-worktree.sh`:七個分身的 fixture(照 leo 09-07 看到的那排)跑 `sweep`——
dry-run 不動任何東西;`--apply` 只收已推的、`--skip` 的一根寒毛不動、沒推的印分支與路徑。
+38 -10
View File
@@ -7,14 +7,14 @@
## 一句話結論 ## 一句話結論
`hooks/` 底下有 **61 個 `.sh` 檔**`hooks.json` 實際掛上 **84 條註冊**(同一支閘常被多種情境同時掛上); `hooks/` 底下有 **61 個 `.sh` 檔**`hooks.json` 實際掛上 **86 條註冊**(同一支閘常被多種情境同時掛上);
其中 **3 支檔案存在但沒被掛上**(2 支是待人填的空範本、1 支是刻意留著沒開的止血帶,見下面「未生效」表)。 其中 **3 支檔案存在但沒被掛上**(2 支是待人填的空範本、1 支是刻意留著沒開的止血帶,見下面「未生效」表)。
下面按「你會在什麼時候撞到它」分組,一支一行。 下面按「你會在什麼時候撞到它」分組,一支一行。
> 🔴 **這兩個數字上一版是錯的(2026-08-26 實際數過才發現)**:本頁原本寫「43 個檔、53 條註冊」, > 🔴 **這兩個數字上一版是錯的(2026-08-26 實際數過才發現)**:本頁原本寫「43 個檔、53 條註冊」,
> 而當時真實是 **45 個檔、55 條註冊**——中間有兩支閘進來時沒有回頭改這裡。 > 而當時真實是 **45 個檔、55 條註冊**——中間有兩支閘進來時沒有回頭改這裡。
> 現在的寫法是實際數出來的: > 現在的寫法是實際數出來的:
> `ls hooks/*.sh | wc -l` 61`grep -c '"command":' hooks/hooks.json` 84 > `ls hooks/*.sh | wc -l` 61`grep -c '"command":' hooks/hooks.json` 85
> ⚠️ **冒號不能省**`grep -c '"command"'`(沒冒號)會連 `"type": "command"` 一起數到,回 **120**。 > ⚠️ **冒號不能省**`grep -c '"command"'`(沒冒號)會連 `"type": "command"` 一起數到,回 **120**。
> 本頁 2026-08-27 之前寫的是沒冒號那版——**照著它跑會拿到一個跟本頁不符的數字**。 > 本頁 2026-08-27 之前寫的是沒冒號那版——**照著它跑會拿到一個跟本頁不符的數字**。
> **一份會偷偷過期的盤點表,跟沒有盤點表差不多**——見本頁最後「怎麼跟實況對帳」那段。 > **一份會偷偷過期的盤點表,跟沒有盤點表差不多**——見本頁最後「怎麼跟實況對帳」那段。
@@ -32,6 +32,33 @@
> **兩個事件是同一件事的兩半**:只注入 = 又一個會被忽略的提醒;只查核 = 罰它做一件拿不到資料的事。 > **兩個事件是同一件事的兩半**:只注入 = 又一個會被忽略的提醒;只查核 = 罰它做一件拿不到資料的事。
> 這兩個數字是併之前當場數出來的,不是從上一版加減推出來的。 > 這兩個數字是併之前當場數出來的,不是從上一版加減推出來的。
> 📌 **`inkstone/ISEP#67`2026-09-07)+0 支、+0 條、腳本 56→60**:沒加閘。`isep-presence-beacon.sh`
> 多報一格 ④「打了 tag 卻沒 release」(改判準不加閘);`scripts/` 多了運送鏈的兩站 `release-ship``release-check`
> 與各自的測試,判準收在 `hooks/lib/release_chain.py` 一份三處用。
> **61 支、85 條、60 支腳本是在這棵樹上當場數出來的**`ls hooks/*.sh | wc -l`61、
> `grep -c '"command":' hooks/hooks.json`85、`ls -p scripts | grep -v / | wc -l`60)。
> 📌 **`inkstone/ISEP#147`2026-09-07)+0 支、+1 條**`line-needs-own-worktree.sh` 多掛 PostToolUse `Agent|Task`
> ——教你開分身的那支閘,在線收工那一刻替你收(分支推了就 remove;沒推就點名分支與路徑,不靜默、不 force)。
> 分身的家從「repo 旁邊」改成「repo 裡面的 `.worktrees/`」:leo 在 Finder 看到一排 `ISEP-wt-117``InkStoneCo-wt-112`
> 就是第一版「收工 remove 只寫在閘訊息裡、沒機制驗」長出來的。同一支閘掛兩個事件(跟 `countdown-guard.sh` 同形狀),
> **不另開一支**。`scripts/` 2`worktree`opencloselistsweep,「推了沒」只有這一份判準)與它的測試。
> **61 支、86 條、62 支腳本是在這棵樹上當場數出來的**`ls hooks/*.sh | wc -l`61、
> `grep -c '"command":' hooks/hooks.json`86、`ls -p scripts | grep -v / | wc -l`62)。規約:`docs/governance/worktree-placement.md`。
> 📌 **`inkstone/ISEP#109` → comment 66292026-09-07)+0 支、+0 條**:兩支閘改判準不加閘——
> `line-needs-own-worktree.sh` 的出路改認指令字串裡的 `WORKTREE_OK=1` 前綴(舊版讀 hook 自己的環境,
> 出路永遠走不通);`github-contact-guard.sh` 判 push 目標改在「這條指令實際會推的那個 repo」裡解 remote
> (舊版在 hook 的 cwd 解,薄殼站 GitHub、推 Gitea 會誤擋,反向會漏)。
> 數字是改完當場數的:`ls hooks/*.sh | wc -l`61、`grep -c '"command":' hooks/hooks.json`85。
> 📌 **`inkstone/ISEP#130`2026-09-07)+0 支、+1 條**SessionStart 多掛一條
> `scripts/settings-allow-sync --quiet`(不是閘,是腳本:把 ISEP 的權限白名單寫進這台的
> `~/.claude/settings.json`,雲端才不會每個正門工具都被分類器擋)。
> **61 支不變、84→85 條,兩個數字是掛完之後當場數出來的**(`ls hooks/*.sh | wc -l`61、
> `grep -c '"command":' hooks/hooks.json`85)。同票順手:`leo21c-write-guard.sh` 補了
> 唯讀 `-d` 與 notify_leo 的放行、三支閘認得 youlin 09-02 起的新子網域——**都是改判準不是加閘**。
> 📌 **`inkstone/ISEP#82`2026-08-28)+1 支、+3 條**`mainline-focus-guard.sh` > 📌 **`inkstone/ISEP#82`2026-08-28)+1 支、+3 條**`mainline-focus-guard.sh`
> 同時掛在 `Agent` 與 `Task`(派工的兩個入口都要守,只守一個等於沒守), > 同時掛在 `Agent` 與 `Task`(派工的兩個入口都要守,只守一個等於沒守),
> 加上 SessionStart 多掛一條 `scripts/mainline refresh`(更新主線的進度/期限,不是閘)。 > 加上 SessionStart 多掛一條 `scripts/mainline refresh`(更新主線的進度/期限,不是閘)。
@@ -116,13 +143,13 @@
| 閘名 | 對你意味著什麼 | 動作 | | 閘名 | 對你意味著什麼 | 動作 |
|---|---|---| |---|---|---|
| `github-contact-guard.sh` | AI 想碰 GitHub`git push``gh api` 等)就先擋下——兩個帳號曾經因為機器人式高頻寫入被永久 flag 過。**只有讀取(clone/fetch)自由,寫入一律要你在終端機跑 `github-arm.sh` 解鎖**。 | 🛑 擋 | | `github-contact-guard.sh` | AI 想碰 GitHub`git push``gh api` 等)就先擋下——兩個帳號曾經因為機器人式高頻寫入被永久 flag 過。**只有讀取(clone/fetch)自由,寫入一律要你在終端機跑 `github-arm.sh` 解鎖**。判「這次 push 到哪」看的是**這條指令實際會推的那個 repo**(含 `cd …&&``git -C …`、cwd 在子目錄),不是 hook 站的 cwd——雲端薄殼站在 GitHub 那份、推的是 Gitea 那份時不會誤擋,反過來也不會漏(`inkstone/ISEP#109`→6629)。 | 🛑 擋 |
| `kbdb-api-wall-guard.sh` | AI 想繞過 KBDB 的 API、直接對資料庫下 SQL 或建新表就擋下——KBDB 的鐵律是「只能用 API、永遠只有三張表」。 | 🛑 擋 | | `kbdb-api-wall-guard.sh` | AI 想繞過 KBDB 的 API、直接對資料庫下 SQL 或建新表就擋下——KBDB 的鐵律是「只能用 API、永遠只有三張表」。 | 🛑 擋 |
| `stage-before-prod-guard.sh` | AI 想動「出貨鏈」相關指令(含 `arcrun-rag-bundles``github-arm``publish-github` 字樣)卻沒先在 stage 環境驗過就擋下。 | 🛑 擋 | | `stage-before-prod-guard.sh` | AI 想動「出貨鏈」相關指令(含 `arcrun-rag-bundles``github-arm``publish-github` 字樣)卻沒先在 stage 環境驗過就擋下。 | 🛑 擋 |
| `main-and-prod-push-guard.sh` | 兩層確認:① subagent 想推 Gitea `main` 分支 → 一定要交回總管,總管確認過才放行;② 任何 `wrangler deploy` 打正式環境 → 一定要你親手解鎖。 | 🛑 擋 | | `main-and-prod-push-guard.sh` | 兩層確認:① subagent 想推 Gitea `main` 分支 → 一定要交回總管,總管確認過才放行;② 任何 `wrangler deploy` 打正式環境 → 一定要你親手解鎖。 | 🛑 擋 |
| `prod-write-guard.sh` | AI 想做任何「會真的改到線上正式帳號(leo21c)」的操作(不只是 push,也包含直接呼叫會寫入的工具)就擋下,交回總管處理。 | 🛑 擋 | | `prod-write-guard.sh` | AI 想做任何「會真的改到線上正式帳號(leo21c)」的操作(不只是 push,也包含直接呼叫會寫入的工具)就擋下,交回總管處理。 | 🛑 擋 |
| `not-my-branch-guard.sh` | AI 想 commit 到「別的 subagent 正在施工中」的分支(登記在 `branch-holds.md`)就擋下,避免兩個 AI 互踩同一條分支。 | 🛑 擋 | | `not-my-branch-guard.sh` | AI 想 commit 到「別的 subagent 正在施工中」的分支(登記在 `branch-holds.md`)就擋下,避免兩個 AI 互踩同一條分支。 | 🛑 擋 |
| `leo21c-write-guard.sh` | AI 想寫東西到你私人帳號 `leo21c` 就擋下——這個帳號只准你自己用,AI 的實驗一律走別的測試帳號。 | 🛑 擋 | | `leo21c-write-guard.sh` | AI 想寫東西到你私人帳號 `leo21c` 就擋下——這個帳號只准你自己用,AI 的實驗一律走別的測試帳號。**讀一律放行**(含 `tr -d``cut -d=` 這種唯讀的 `-d`,09-04 雲端就是被這個誤攔到「連讀都讀不到」),發一則 `notify_leo`(只送訊息、什麼都沒改)也放行——跟 `prod-write-guard.sh` 同一份白名單(inkstone/ISEP#130)。 | 🛑 擋 |
| `release-tag-guard.sh` | AI 想打版本 tag,但 `plugin.json` 裡寫的版本號跟 tag 對不上就擋下——避免「這裡說 0.2.0、那裡說 0.1.0」各說各話。 | 🛑 擋 | | `release-tag-guard.sh` | AI 想打版本 tag,但 `plugin.json` 裡寫的版本號跟 tag 對不上就擋下——避免「這裡說 0.2.0、那裡說 0.1.0」各說各話。 | 🛑 擋 |
| `ticket-api-bypass-guard.sh` | AI 想繞過 `scripts/ticket` 工具、直接打 API 新增 Gitea 東西(開新票/milestone/label/PR,會漏掉「新增前先搜過」這道檢查)就擋下——不管是隱式 POST(urllib 傳 data= 沒寫 method)還是小寫 `requests.post(...)`。 | 🛑 擋 | | `ticket-api-bypass-guard.sh` | AI 想繞過 `scripts/ticket` 工具、直接打 API 新增 Gitea 東西(開新票/milestone/label/PR,會漏掉「新增前先搜過」這道檢查)就擋下——不管是隱式 POST(urllib 傳 data= 沒寫 method)還是小寫 `requests.post(...)`。 | 🛑 擋 |
| `milestone-due-guard.sh` | AI 想開一個新的里程碑(milestone)卻沒填期限就擋下,**填 `9999-01-01` 一樣擋**——那是「沒有期限」穿了一件期限的衣服,盤點時每一格看起來都有值,其實一格都沒有。只管「建里程碑」這個動作,查詢/改別的欄位都放行。 | 🛑 擋 | | `milestone-due-guard.sh` | AI 想開一個新的里程碑(milestone)卻沒填期限就擋下,**填 `9999-01-01` 一樣擋**——那是「沒有期限」穿了一件期限的衣服,盤點時每一格看起來都有值,其實一格都沒有。只管「建里程碑」這個動作,查詢/改別的欄位都放行。 | 🛑 擋 |
@@ -130,7 +157,7 @@
| `reply-identity-guard.sh` | 直接打 Gitea API 貼留言到票上時,內文第一行沒有 `【身份】``總管``subagent``leo`)就擋下——票上多條線並行時,看不出哪一則是誰寫的。純讀取、走 `scripts/ticket` 正門、指令裡加 `reply-identity-ok` 都放行。 | 🛑 擋 | | `reply-identity-guard.sh` | 直接打 Gitea API 貼留言到票上時,內文第一行沒有 `【身份】``總管``subagent``leo`)就擋下——票上多條線並行時,看不出哪一則是誰寫的。純讀取、走 `scripts/ticket` 正門、指令裡加 `reply-identity-ok` 都放行。 | 🛑 擋 |
| `comment-carries-task-guard.sh` | AI 要在票裡留一則「等某某上線才驗得了」這種**還沒做完的事**,卻沒有把它開成一張子票時,擋一次。留言沒人會回頭讀,票的 open/closed 撈一次就看得到。**擋下來時印的是一整塊可以直接貼著跑的指令**(腳本用絕對路徑、母票已經填好、內文草稿附在同一塊裡),那塊字是跟 `scripts/ticket usage subtask` 現要的,不是閘自己抄的一份(`inkstone/ISEP#112`)。 | 🛑 擋(同一輪只擋一次) | | `comment-carries-task-guard.sh` | AI 要在票裡留一則「等某某上線才驗得了」這種**還沒做完的事**,卻沒有把它開成一張子票時,擋一次。留言沒人會回頭讀,票的 open/closed 撈一次就看得到。**擋下來時印的是一整塊可以直接貼著跑的指令**(腳本用絕對路徑、母票已經填好、內文草稿附在同一塊裡),那塊字是跟 `scripts/ticket usage subtask` 現要的,不是閘自己抄的一份(`inkstone/ISEP#112`)。 | 🛑 擋(同一輪只擋一次) |
| `search-is-not-proof-guard.sh` | AI 用知識庫的**搜尋**找到一筆東西,然後把那筆東西的原始編號直接貼進票裡或派工單裡,當成「某個功能壞了」的證據——而它從沒用正規的檢索路徑去查過那筆——擋一次。你關心的是:不會再有人拿錯的方法量出一個錯的結論,然後退回一張其實已經做完的票。 | 🛑 擋(同一輪只擋一次) | | `search-is-not-proof-guard.sh` | AI 用知識庫的**搜尋**找到一筆東西,然後把那筆東西的原始編號直接貼進票裡或派工單裡,當成「某個功能壞了」的證據——而它從沒用正規的檢索路徑去查過那筆——擋一次。你關心的是:不會再有人拿錯的方法量出一個錯的結論,然後退回一張其實已經做完的票。 | 🛑 擋(同一輪只擋一次) |
| `line-needs-own-worktree.sh` | 一條派工線想在**大家共用的那份工作目錄**裡切分支(`git checkout``git switch`)就擋下,叫它先開一份自己的 worktree。你關心的是:不會再有人交回工作時把某個 repo 留在自己的分支上,而下一個人在同一個目錄跑出貨、讀到的是別人留下的 HEAD。**總管在自己的目錄裡切分支不管**(那是他的目錄);已經在自己 worktree 裡的切換全部放行;還原檔案(`git checkout -- 檔`)不管。擋下來的同時會順手把「指向空氣」的 worktree 登記清掉。 | 🛑 擋 | | `line-needs-own-worktree.sh` | 一條派工線想在**大家共用的那份工作目錄**裡切分支(`git checkout``git switch`)就擋下,叫它先開一份自己的 worktree——**開在 repo 裡面的 `.worktrees/`,不是旁邊**`scripts/worktree open``inkstone/ISEP#147`leo 在 Finder 看到一排 `ISEP-wt-117``InkStoneCo-wt-112` 就是舊版教出來的)。同一支閘也掛在線收工那一刻(PostToolUse `Agent|Task`):從派工單的【工單】認出分身,分支推了且乾淨就收掉,沒推/有東西沒交代就點名分支與路徑——不靜默、不 force、不刪沒推的 commit。你關心的是:一個 repo 在 Finder 只有一個資料夾,而且不會再有人交回工作時把某個 repo 留在自己的分支上。**總管在自己的目錄裡切分支不管**(那是他的目錄);已經在自己 worktree 裡的切換全部放行;還原檔案(`git checkout -- 檔`)不管。擋下來的同時會順手把「指向空氣」的 worktree 登記清掉。切分支的出路是閘訊息印的那一行 `WORKTREE_OK=1 git -C … checkout …`——認的是**指令字串裡**的這個前綴,原樣貼回去就過(`inkstone/ISEP#109`→6587)。 | 🛑 擋/收工 🚨 點名 |
| `diagnosis-evidence-guard.sh` | 你想把一段有份量的東西寫上票,而這個 session **沒派人去查過那張票**、那段話裡也**沒有任何走得過去的出處**(檔案:行號/commit/comment 號/票號/網址/貼出來的實測輸出)就擋一次——未經調查的診斷寫在票上會長得像事實,工人會照著它去驗證而不是去查。派過人查、或把出處帶上,都放行;一句短回覆不管。 | 🛑 擋 | | `diagnosis-evidence-guard.sh` | 你想把一段有份量的東西寫上票,而這個 session **沒派人去查過那張票**、那段話裡也**沒有任何走得過去的出處**(檔案:行號/commit/comment 號/票號/網址/貼出來的實測輸出)就擋一次——未經調查的診斷寫在票上會長得像事實,工人會照著它去驗證而不是去查。派過人查、或把出處帶上,都放行;一句短回覆不管。 | 🛑 擋 |
## B. AI 想寫檔案/改程式碼的當下(PreToolUse / Write·Edit·MultiEdit ## B. AI 想寫檔案/改程式碼的當下(PreToolUse / Write·Edit·MultiEdit
@@ -183,7 +210,7 @@
| `no-ticket-no-dispatch.sh` | 派工單裡沒有寫工單號(`【工單】owner/repo#N`),或那張票已經關閉/根本不存在,就擋下——沒有票號的工作沒有人追得到進度。 | 🛑 擋 | | `no-ticket-no-dispatch.sh` | 派工單裡沒有寫工單號(`【工單】owner/repo#N`),或那張票已經關閉/根本不存在,就擋下——沒有票號的工作沒有人追得到進度。 | 🛑 擋 |
| `dispatch-format-guard.sh` | **派工單 票號,就這樣。** 票號以外還寫了別的東西(背景、驗收條件、紅線、交件方式、「這個 session 才知道的事」)就擋下,並告訴你那些內容該搬去哪:每次都一樣的 → 共通規定;這次才知道的 → **寫進那張票**。反過來,合規的派工它會**自動把共通規定注入**給收工方(交件方式、不准 push main、org 是 `inkstone`…),所以你不寫也不會漏。判準是「這一行是不是【工單】欄位」——**在不在**,不是寫了什麼,所以講得再謹慎也不會被多罰。純禮貌收尾(「謝謝」)不算違規;`(→ comment M` 不論全形或半形括號都認得(ISEP#65 修過一次:CLAUDE.md 自己規定的合格寫法曾經被這支閘自己擋下)。**`ISEP#88` 起同一支閘也掛在「回覆 subagent」那條路上**(`SendMessage`、雲端 sessiontrigger、以及 Bash 的 `claude -p`)——回覆也是派工,同一套規矩;擋下來時會把那段內容**原文印出來**方便直接貼上票。subagent 往上回報(`to: "main"`)不管,那是交件不是派工。 | 🛑 擋(+注入) | | `dispatch-format-guard.sh` | **派工單 票號,就這樣。** 票號以外還寫了別的東西(背景、驗收條件、紅線、交件方式、「這個 session 才知道的事」)就擋下,並告訴你那些內容該搬去哪:每次都一樣的 → 共通規定;這次才知道的 → **寫進那張票**。反過來,合規的派工它會**自動把共通規定注入**給收工方(交件方式、不准 push main、org 是 `inkstone`…),所以你不寫也不會漏。判準是「這一行是不是【工單】欄位」——**在不在**,不是寫了什麼,所以講得再謹慎也不會被多罰。純禮貌收尾(「謝謝」)不算違規;`(→ comment M` 不論全形或半形括號都認得(ISEP#65 修過一次:CLAUDE.md 自己規定的合格寫法曾經被這支閘自己擋下)。**`ISEP#88` 起同一支閘也掛在「回覆 subagent」那條路上**(`SendMessage`、雲端 sessiontrigger、以及 Bash 的 `claude -p`)——回覆也是派工,同一套規矩;擋下來時會把那段內容**原文印出來**方便直接貼上票。subagent 往上回報(`to: "main"`)不管,那是交件不是派工。 | 🛑 擋(+注入) |
| `roster-guard.sh` | 派工要**指名派給誰**`Task``subagent_type` 得是 `agents/` 名單上的名字(`isep-hand``arcrun-hand``scout`…),沒指名或指了不存在的名字就擋下,並把整份名單印出來。指對了它會**自動把那位工人的檔案原文注入**給它——你是誰、負責哪個 repo、開工前先讀什麼、你的紅線是什麼(這些每個工人都不一樣,共通規定補不了)。名單是資料:加一個工人=在 `agents/` 加一個 `.md`,不必改任何 hook。 | 🛑 擋(+注入) | | `roster-guard.sh` | 派工要**指名派給誰**`Task``subagent_type` 得是 `agents/` 名單上的名字(`isep-hand``arcrun-hand``scout`…),沒指名或指了不存在的名字就擋下,並把整份名單印出來。指對了它會**自動把那位工人的檔案原文注入**給它——你是誰、負責哪個 repo、開工前先讀什麼、你的紅線是什麼(這些每個工人都不一樣,共通規定補不了)。名單是資料:加一個工人=在 `agents/` 加一個 `.md`,不必改任何 hook。 | 🛑 擋(+注入) |
| `mainline-focus-guard.sh` | 派出去的票**不在「現在的主線」上**,就擋一次,並問你是「補收」(它本來就該掛在主線上)還是「跳線」(真的插件事)。背景:2026-08-27 實查有 **14 個 milestone 同時開著**,其中「Mira 現代化」同名活在 5 個 repo ⇒ SOP 說的「只做該 milestone 的事」在現場**沒有指涉對象**,等於不存在。現在主線是一個查得到的事實(`scripts/mainline`,答案唯一),這支就是那個事實的用處。🔴 **沒有標主線 ⇒ 一律放行**;多張票只要有一張在主線上就放行;查不到那張票掛在哪也放行(**讀不到 ≠ 不屬於**);**同一張票只擋一次**,重送就過。跳線會留一筆紀錄——不留痕的話,跳線與專注在機器上長得一模一樣。 | 🛑 擋(同一張票至多一次) | | `mainline-focus-guard.sh` | 派出去的票**不在「現在的主線」上**,就擋一次,並問你是「補收」(它本來就該掛在主線上)還是「跳線」(真的插件事)。背景:2026-08-27 實查有 **14 個 milestone 同時開著**,其中「Mira 現代化」同名活在 5 個 repo ⇒ SOP 說的「只做該 milestone 的事」在現場**沒有指涉對象**,等於不存在。現在主線是一個查得到的事實(`scripts/mainline`,答案唯一),這支就是那個事實的用處。「在不在主線上」看兩個 Gitea 欄位:掛在錨那一個 milestone、或被主線成員當相依(`/blocks`,跨 repo)——**別 repo 裡同名的里程碑不算**leo 2026-09-07`inkstone/ISEP#133`)。🔴 **沒有標主線 ⇒ 一律放行**;多張票只要有一張在主線上就放行;查不到那張票掛在哪、或查不到誰指著它,也放行(**讀不到 ≠ 不屬於**);**同一張票只擋一次**,重送就過。跳線會留一筆紀錄——不留痕的話,跳線與專注在機器上長得一模一樣。 | 🛑 擋(同一張票至多一次) |
| `dispatch-format-guard.sh` | **派工單 票號,就這樣。** 票號以外還寫了別的東西(背景、驗收條件、紅線、交件方式、「這個 session 才知道的事」)就擋下,並告訴你那些內容該搬去哪:每次都一樣的 → 共通規定;這次才知道的 → **寫進那張票**。反過來,合規的派工它會**自動把共通規定注入**給收工方(交件方式、不准 push main、org 是 `inkstone`…),所以你不寫也不會漏。判準是「這一行是不是【工單】欄位」——**在不在**,不是寫了什麼,所以講得再謹慎也不會被多罰。純禮貌收尾(「謝謝」)不算違規;`(→ comment M` 不論全形或半形括號都認得(ISEP#65 修過一次:CLAUDE.md 自己規定的合格寫法曾經被這支閘自己擋下)。 | 🛑 擋(+注入) | | `dispatch-format-guard.sh` | **派工單 票號,就這樣。** 票號以外還寫了別的東西(背景、驗收條件、紅線、交件方式、「這個 session 才知道的事」)就擋下,並告訴你那些內容該搬去哪:每次都一樣的 → 共通規定;這次才知道的 → **寫進那張票**。反過來,合規的派工它會**自動把共通規定注入**給收工方(交件方式、不准 push main、org 是 `inkstone`…),所以你不寫也不會漏。判準是「這一行是不是【工單】欄位」——**在不在**,不是寫了什麼,所以講得再謹慎也不會被多罰。純禮貌收尾(「謝謝」)不算違規;`(→ comment M` 不論全形或半形括號都認得(ISEP#65 修過一次:CLAUDE.md 自己規定的合格寫法曾經被這支閘自己擋下)。 | 🛑 擋(+注入) |
| `parallel-lines-cap-guard.sh` | **同時在跑的線超過上限就派不出下一條**(預設 3`ISEP_MAX_PARALLEL_LINES` 可調),而且訊息會列出現在有哪幾條在跑、各跑了多久。你關心的是:不會再因為一次派七條而讓機器爆掉,也不會再有「同時盯七條線所以派錯、量錯」那種錯。**條數是從 harness 自己寫的檔案數出來的,不是靠誰記得**——所以某一條收工,下一條立刻派得出去,不會卡死。真的非同時不可:`touch /tmp/.parallel-ok-<session_id>`(用一次就消失)。 | 🛑 擋 | | `parallel-lines-cap-guard.sh` | **同時在跑的線超過上限就派不出下一條**(預設 3`ISEP_MAX_PARALLEL_LINES` 可調),而且訊息會列出現在有哪幾條在跑、各跑了多久。你關心的是:不會再因為一次派七條而讓機器爆掉,也不會再有「同時盯七條線所以派錯、量錯」那種錯。**條數是從 harness 自己寫的檔案數出來的,不是靠誰記得**——所以某一條收工,下一條立刻派得出去,不會卡死。真的非同時不可:`touch /tmp/.parallel-ok-<session_id>`(用一次就消失)。 | 🛑 擋 |
@@ -203,9 +230,10 @@
| 閘名 | 對你意味著什麼 | 動作 | | 閘名 | 對你意味著什麼 | 動作 |
|---|---|---| |---|---|---|
| `isep-presence-beacon.sh` | 對話一開始印一行 `🟢 ISEP vX.Y.Z 已載入(N 支閘|來源:…)`。**這行不是裝飾,是唯一能證明「這個 session 真的有閘」的東西**——它自己就住在 plugin 裡,看得到它就表示 plugin 載入了;某個 session 從頭到尾沒有這行,那個 session 是零閘狀態,先修 plugin 再做事。同一台機器可能同時有兩份 ISEP(marketplace 裝的、repo 裡 vendor 的),所以那行會講出這次是哪一份在說話。它另外會報四件「這一份是不是還有效」:①這一份落後 ISEP main 幾版 ②專案裡有沒有內容不同的同名**腳本**②b 專案裡有沒有內容不同的同名**skillcommandagent**——這些是**自動載入**的,載到舊的那份不會有任何症狀,只會安靜地教錯的東西(`docs/file-ownership.tsv` 說得出每一組的真相源是哪一份、往哪個方向修)②c 本身的內容跟那張歸屬表對不對得上(雲端沒有專案那一份可比時,這是唯一還作數的檢查)③工作區有沒有已退役機制留下的產物。**全部只講不擋。** | 📝 記錄(context 注入) | | `isep-presence-beacon.sh` | 對話一開始印一行 `🟢 ISEP vX.Y.Z 已載入(N 支閘|來源:…)`。**這行不是裝飾,是唯一能證明「這個 session 真的有閘」的東西**——它自己就住在 plugin 裡,看得到它就表示 plugin 載入了;某個 session 從頭到尾沒有這行,那個 session 是零閘狀態,先修 plugin 再做事。同一台機器可能同時有兩份 ISEP(marketplace 裝的、repo 裡 vendor 的),所以那行會講出這次是哪一份在說話。它另外會報四件「這一份是不是還有效」:①這一份落後 ISEP main 幾版 ②專案裡有沒有內容不同的同名**腳本**②b 專案裡有沒有內容不同的同名**skillcommandagent**——這些是**自動載入**的,載到舊的那份不會有任何症狀,只會安靜地教錯的東西(`docs/file-ownership.tsv` 說得出每一組的真相源是哪一份、往哪個方向修)②c 本身的內容跟那張歸屬表對不對得上(雲端沒有專案那一份可比時,這是唯一還作數的檢查)③工作區有沒有已退役機制留下的產物 ④**打了 tag 卻沒 release**Gitea 最新 tag 沒有 release、或 main 定版了還沒打 tag)——一行說缺哪一站+可以直接貼著跑的補法(`scripts/release-ship`),都在時一個字都不說;判準跟 `release-ship``release-check` 同一份(`hooks/lib/release_chain.py`),匿名讀、問不到就閉嘴(`inkstone/ISEP#67`。**全部只講不擋。** | 📝 記錄(context 注入) |
| `session-start-recall.sh` | 對話一開始就自動把「全局現況」(Gitea 各 repo 的票、KBDB 的藏書地圖)推到 AI 眼前,不必等它自己想到要查。 | 📝 記錄(context 注入) | | `session-start-recall.sh` | 對話一開始就自動把「全局現況」(Gitea 各 repo 的票、KBDB 的藏書地圖)推到 AI 眼前,不必等它自己想到要查。 | 📝 記錄(context 注入) |
| `scripts/mainline refresh` | (不是閘,是腳本)對話一開始把**現在的主線**那條 milestone 的進度與期限更新一次,好讓每回合眼前那一行講的是今天的數字。拿不到 Gitea 就原封不動——**寧可資料舊,不要把主線弄丟**。跑一次就結束,不輪詢。 | 📝 記錄 | | `scripts/settings-allow-sync --quiet` | (不是閘,是腳本)對話一開始把 ISEP 的權限白名單(`docs/permissions-allow.json``ticket``mainline``gate-ok``gitea-pr-merge``stage`inkstone/ISEP#137 起,雲端對 stage 寫入的正門)五個正門工具,外加 Arcrun 的 `stage-deploy-artifacts.py`)寫進**這台機器**的 `~/.claude/settings.json`。只加不減、冪等;目標檔壞掉就不碰它、講一聲。**為什麼**:leo 09-07 親手加的四條只在本機,雲端沒有 ⇒ 同樣的動作被分類器擋(09-04 run log `permission_denials=6`);薄殼 repo 要 D20 開閘才推得動,所以清單住 ISEP 一份、兩台各自寫進自己的家目錄(inkstone/ISEP#130)。 | 📝 記錄(寫 settings |
| `scripts/mainline refresh` | (不是閘,是腳本)對話一開始把**現在的主線**那條 milestone 的進度與期限更新一次,好讓每回合眼前那一行講的是今天的數字。拿不到 Gitea 就原封不動——**寧可資料舊,不要把主線弄丟**。跑一次就結束,不輪詢。成員清單(hub 里程碑裡的票+沿相依邊跨 repo 收到的,`inkstone/ISEP#133`)**不在這裡重收**——真 Gitea 一走 19 秒;`set``adopt``refresh --members` 才重收,`pick``has`focus guard 每次現問。**家目錄與 repo 那份都不在時**(雲端薄殼跑到這裡 `InkStoneCo/` 還沒 clone)先去 Gitea 讀 `inkstone/InkStoneCo` main 的 `system-dev/mainline.json` 一次寫進家目錄(`inkstone/ISEP#140`):匿名優先、被拒才帶 token;讀不到就退回,不報錯、逾時有上限。優先序寫在 `hooks/lib/mainline.py` 檔頭。 | 📝 記錄 |
| `overdue-nag-guard.sh` | 對話一開始就去 Gitea 撈**沒有人會叫的事**:逾期的 milestone、掛著等你的票(標「等了幾天」)、標著「有人在做」卻好幾天沒動的票;撈完用白話講出來,**有事就發 Telegram 給你**。沒東西可報時它會說「查過了,沒有」——**安靜跟壞掉長得一模一樣**。發不出去時不會靜默:它會先問這個 session 的 `prod-write-guard` 會不會擋(舊版把「發通知」誤認成「部署」),擋就改貼回票上並把原文印在眼前。只在開 session 時跑一次,**不輪詢、不掛排程**。 | 📝 記錄(context 注入 Telegram | | `overdue-nag-guard.sh` | 對話一開始就去 Gitea 撈**沒有人會叫的事**:逾期的 milestone、掛著等你的票(標「等了幾天」)、標著「有人在做」卻好幾天沒動的票;撈完用白話講出來,**有事就發 Telegram 給你**。沒東西可報時它會說「查過了,沒有」——**安靜跟壞掉長得一模一樣**。發不出去時不會靜默:它會先問這個 session 的 `prod-write-guard` 會不會擋(舊版把「發通知」誤認成「部署」),擋就改貼回票上並把原文印在眼前。只在開 session 時跑一次,**不輪詢、不掛排程**。 | 📝 記錄(context 注入 Telegram |
| `wiki-size-guard.sh` | 對話一開始講出「哪幾個 wiki 檔已經沒有人讀得完了」(預設超過 1200 行就點名)。**讀不完的必讀檔,跟沒有那個檔的差別只在於它讓人以為有。** 另一半掛在寫檔上,見 B 組。 | 📝 記錄(context 注入) | | `wiki-size-guard.sh` | 對話一開始講出「哪幾個 wiki 檔已經沒有人讀得完了」(預設超過 1200 行就點名)。**讀不完的必讀檔,跟沒有那個檔的差別只在於它讓人以為有。** 另一半掛在寫檔上,見 B 組。 | 📝 記錄(context 注入) |
| `skill-deploy-drift-guard.sh` | 如果「全機真正在用的 skill」跟「repo 裡版控的正本」內容對不上,就在開場講出來——避免用著一份沒人知道已經跟正本分家的舊拷貝。 | 📝 記錄 | | `skill-deploy-drift-guard.sh` | 如果「全機真正在用的 skill」跟「repo 裡版控的正本」內容對不上,就在開場講出來——避免用著一份沒人知道已經跟正本分家的舊拷貝。 | 📝 記錄 |
@@ -288,8 +316,8 @@ countdown-milestone-refresh.sh ← 假警報:它在 scripts/ 不在 hooks/
🔴 **上面那一筆是假警報,不是「指向空氣」的閘**`inkstone/ISEP#63` 之後, 🔴 **上面那一筆是假警報,不是「指向空氣」的閘**`inkstone/ISEP#63` 之後,
SessionStart 上掛的東西不全是 `hooks/*.sh`——`scripts/countdown-milestone-refresh.sh` SessionStart 上掛的東西不全是 `hooks/*.sh`——`scripts/countdown-milestone-refresh.sh`
是腳本不是閘。這組指令只比檔名、不看目錄,所以它會出現在這裡。 是腳本不是閘。這組指令只比檔名、不看目錄,所以它會出現在這裡。
`inkstone/ISEP#82` 又多掛一條 `scripts/mainline refresh`,那一條沒有 `.sh` `inkstone/ISEP#82` 又多掛一條 `scripts/mainline refresh``inkstone/ISEP#130` 多掛一條
副檔名,所以不會落進這個名單。)**照著跑會看到它,這裡先講清楚, `scripts/settings-allow-sync --quiet`,這兩條沒有 `.sh` 副檔名,所以不會落進這個名單。)**照著跑會看到它,這裡先講清楚,
免得下一個人以為是自己弄壞的。** 免得下一個人以為是自己弄壞的。**
🔴 **上面那兩行驗不出「表格漏列」**——它們比的是 `hooks.json`,不是這張表。 🔴 **上面那兩行驗不出「表格漏列」**——它們比的是 `hooks.json`,不是這張表。
+50
View File
@@ -0,0 +1,50 @@
{
"_what": "Claude Code 權限白名單(permissions.allow)的唯一清單——本機與雲端都從這裡讀,不各養一份(inkstone/ISEP#130",
"_why": [
"leo 09-07 親手把四個 Gitea 正門工具(ticketmainlinegate-okgitea-pr-merge)加進本機 InkStoneCo/.claude/settings.jsonauto mode 的分類器才不擋。",
"雲端 session 沒有那四條,同樣的動作照樣被擋(09-04 progress-guard run logpermission_denials=6)。",
"薄殼 repoGitHub)要 D20 開閘才推得動 ⇒ 白名單住 ISEP`scripts/settings-allow-sync` 開工時寫進那台機器的 ~/.claude/settings.json。",
"以後加規則只改這個檔、出一版,雲端下一趟就有。",
"inkstone/ISEP#13709-07 雲端對 stage 的三種寫入(`npx wrangler secret put``stage-deploy-artifacts.py`curl POST 到 arcrun-yuga3bse)全被分類器擋——複合指令與任意 curl 對不上任何一條前綴。收成 `scripts/stage`secretapi 兩個子命令,只寫 stage、值只從環境變數名讀)四種形狀,外加 Arcrun 自己那支 `scripts/stage-deploy-artifacts.py`(它已寫死只認 youlin 帳號 ID、不收 --account--token)從 Arcrun repo 根目錄的相對形狀。不放 `Bash(npx *)``Bash(wrangler *)``Bash(curl *)`。",
"inkstone/ISEP#67SessionStart 信標印的補法是 `python3 <plugin root>/scripts/release-ship vX.Y.Z`——那一行在雲端要是被分類器擋,出路就走不通(閘的價值是「擋下來+給一條走得通的路」)。release-ship 只 POST 一件事(建 releasetag 與 release 名寫死從 Gitea 讀);release-check 純讀。",
"inkstone/ISEP#147worktree 閘印出來的出路是 `python3 <plugin>/scripts/worktree open …``close …`,收工那一半也是同一支工具;出路在雲端被分類器擋就是走不通的路(閘的價值是「擋下來+給一條走得通的路」)。它只碰 git worktree,不打網路寫入。"
],
"_rules": [
"開頭的 `~` 由 settings-allow-sync 換成那台機器的家目錄(本機 /Users/…、雲端 /root),其餘一字不改。",
"只放「正門工具」:每一條都要說得出它是哪支腳本的哪種呼叫形狀。不放 Bash(python3 *) 這種整類放行。",
"同一支工具幾種呼叫形狀就幾條(快取路徑/$CLAUDE_PLUGIN_ROOT/相對路徑)——權限規則是逐條完全比對,形狀差一個字就落在規則之外(scripts/gate-ok 檔頭記過這一課)。",
"別的 repo 的正門工具也可以進來(例 Arcrun 的 `scripts/stage-deploy-artifacts.py`),條件一樣:那支腳本自己把「只打哪台」寫死在程式裡,本清單放的是它從那個 repo 根目錄跑的相對形狀。"
],
"allow": [
"Bash(python3 ~/.claude/plugins/cache/inkstone/isep/*/scripts/ticket *)",
"Bash(python3 \"$CLAUDE_PLUGIN_ROOT/scripts/ticket\" *)",
"Bash(python3 \"$CLAUDE_PLUGIN_ROOT\"/scripts/ticket *)",
"Bash(python3 scripts/ticket *)",
"Bash(python3 ~/.claude/plugins/cache/inkstone/isep/*/scripts/mainline *)",
"Bash(python3 \"$CLAUDE_PLUGIN_ROOT/scripts/mainline\" *)",
"Bash(python3 \"$CLAUDE_PLUGIN_ROOT\"/scripts/mainline *)",
"Bash(python3 scripts/mainline *)",
"Bash(bash ~/.claude/plugins/cache/inkstone/isep/*/scripts/gate-ok *)",
"Bash(bash \"$CLAUDE_PLUGIN_ROOT/scripts/gate-ok\" *)",
"Bash(bash \"$CLAUDE_PLUGIN_ROOT\"/scripts/gate-ok *)",
"Bash(bash scripts/gate-ok *)",
"Bash(bash scripts/gitea-pr-merge.sh *)",
"Bash(python3 ~/.claude/plugins/cache/inkstone/isep/*/scripts/stage *)",
"Bash(python3 \"$CLAUDE_PLUGIN_ROOT/scripts/stage\" *)",
"Bash(python3 \"$CLAUDE_PLUGIN_ROOT\"/scripts/stage *)",
"Bash(python3 scripts/stage *)",
"Bash(python3 scripts/stage-deploy-artifacts.py *)",
"Bash(python3 ~/.claude/plugins/cache/inkstone/isep/*/scripts/release-ship *)",
"Bash(python3 \"$CLAUDE_PLUGIN_ROOT/scripts/release-ship\" *)",
"Bash(python3 \"$CLAUDE_PLUGIN_ROOT\"/scripts/release-ship *)",
"Bash(python3 scripts/release-ship *)",
"Bash(python3 ~/.claude/plugins/cache/inkstone/isep/*/scripts/release-check *)",
"Bash(python3 \"$CLAUDE_PLUGIN_ROOT/scripts/release-check\" *)",
"Bash(python3 \"$CLAUDE_PLUGIN_ROOT\"/scripts/release-check *)",
"Bash(python3 scripts/release-check *)",
"Bash(python3 ~/.claude/plugins/cache/inkstone/isep/*/scripts/worktree *)",
"Bash(python3 \"$CLAUDE_PLUGIN_ROOT/scripts/worktree\" *)",
"Bash(python3 \"$CLAUDE_PLUGIN_ROOT\"/scripts/worktree *)",
"Bash(python3 scripts/worktree *)"
]
}
+19 -2
View File
@@ -87,12 +87,29 @@ try: print(json.load(sys.stdin).get('cwd','') or '')
except Exception: print('') except Exception: print('')
" 2>/dev/null) " 2>/dev/null)
[ -n "$CWD" ] || CWD=$(pwd) [ -n "$CWD" ] || CWD=$(pwd)
# 🔴 2026-09-07inkstone/ISEP#109 → comment 6629):remote 名要在**這條指令實際會推的
# 那個 repo** 裡解,不是在 hook 收到的 cwd 裡解。雲端薄殼的 cwd 是 GitHub 那份
# origingithub.com),總管站在那裡 `git -C <InkStoneCo> push origin x`
# InkStoneCo 的 originGitea)——舊版拿 cwd 解 origin ⇒ 判成「指向 GitHub」擋下,
# `-C` 看都沒看;反過來,站在 Gitea 那份 `git -C <薄殼> push origin x` 則**漏擋**。
# ⇒ 沿用 lib/push_target_dir.py(推 main 那道閘 08-23 就是為同一個病接的它):
# 純 tokenize 解出 cd 鏈/-C,解得出來就 cd 進去(唯讀)問 git;解不出來
# (`cd $VAR`、目錄不存在)才退回 cwd——退回的方向是「照舊」,不是放寬。
# 判準沒變:仍是 remote 解出來的 URL 主機(唯一識別碼),不是「有沒有 -C」。
PUSHDIR="$CWD"
_ptd="$(dirname "$0")/lib/push_target_dir.py"
if [ -f "$_ptd" ]; then
_expr=$(printf '%s' "$CMD" | python3 "$_ptd" 2>/dev/null || printf '')
if [ -n "$_expr" ]; then
PUSHDIR=$(cd "$CWD" 2>/dev/null && cd "$_expr" 2>/dev/null && pwd) || PUSHDIR="$CWD"
fi
fi
# 取 push 後面第一個非 flag 的字當 remote 名;沒有就是 origin # 取 push 後面第一個非 flag 的字當 remote 名;沒有就是 origin
RNAME=$(printf '%s' "$CMD" | sed -nE 's/.*git[[:space:]]+([^|;&]*[[:space:]])?push[[:space:]]+(-[^[:space:]]+[[:space:]]+)*([A-Za-z0-9._/-]+).*/\3/p' | head -1) RNAME=$(printf '%s' "$CMD" | sed -nE 's/.*git[[:space:]]+([^|;&]*[[:space:]])?push[[:space:]]+(-[^[:space:]]+[[:space:]]+)*([A-Za-z0-9._/-]+).*/\3/p' | head -1)
[ -n "$RNAME" ] || RNAME="origin" [ -n "$RNAME" ] || RNAME="origin"
RURL=$(git -C "$CWD" remote get-url "$RNAME" 2>/dev/null) RURL=$(git -C "$PUSHDIR" remote get-url "$RNAME" 2>/dev/null)
if printf '%s' "$RURL" | grep -qi 'github\.com'; then if printf '%s' "$RURL" | grep -qi 'github\.com'; then
HIT="git push → githubremote「$RNAME」指向 GitHub" HIT="git push → github$PUSHDIRremote「$RNAME」指向 GitHub$(printf '%s' "$RURL" | sed 's|//[^@]*@|//<憑證省略>@|g')"
fi fi
fi fi
fi fi
+8
View File
@@ -281,6 +281,10 @@
"type": "command", "type": "command",
"command": "\"${CLAUDE_PLUGIN_ROOT}\"/scripts/mainline refresh" "command": "\"${CLAUDE_PLUGIN_ROOT}\"/scripts/mainline refresh"
}, },
{
"type": "command",
"command": "\"${CLAUDE_PLUGIN_ROOT}\"/scripts/settings-allow-sync --quiet"
},
{ {
"type": "command", "type": "command",
"command": "${CLAUDE_PLUGIN_ROOT}/hooks/overdue-nag-guard.sh" "command": "${CLAUDE_PLUGIN_ROOT}/hooks/overdue-nag-guard.sh"
@@ -441,6 +445,10 @@
{ {
"type": "command", "type": "command",
"command": "${CLAUDE_PLUGIN_ROOT}/hooks/baton-handback-guard.sh" "command": "${CLAUDE_PLUGIN_ROOT}/hooks/baton-handback-guard.sh"
},
{
"type": "command",
"command": "${CLAUDE_PLUGIN_ROOT}/hooks/line-needs-own-worktree.sh"
} }
] ]
}, },
+31 -3
View File
@@ -20,6 +20,7 @@
# 判準(封動作,不封措辭 —— 同 empty-handed-stop-guard 的哲學): # 判準(封動作,不封措辭 —— 同 empty-handed-stop-guard 的哲學):
# 命中 leo21c 的座標 + 這是一個寫入動作 ⇒ 擋 # 命中 leo21c 的座標 + 這是一個寫入動作 ⇒ 擋
# 只是讀(GET/查詢/grep 到那個字串) ⇒ 放行 # 只是讀(GET/查詢/grep 到那個字串) ⇒ 放行
# 發一則 notify_leo(通知型 trigger,什麼都沒改)⇒ 放行(同 prod-write-guard 的白名單)
set -uo pipefail set -uo pipefail
payload=$(cat) payload=$(cat)
cmd=$(printf '%s' "$payload" | python3 -c " cmd=$(printf '%s' "$payload" | python3 -c "
@@ -60,8 +61,34 @@ hit=0
# ① 寫入請求打到那台 worker # ① 寫入請求打到那台 worker
if printf '%s' "$cmd" | grep -qiE 'https?://[^[:space:]"'"'"']*leo21c\.workers\.dev'; then if printf '%s' "$cmd" | grep -qiE 'https?://[^[:space:]"'"'"']*leo21c\.workers\.dev'; then
if printf '%s' "$cmd" | grep -qE -- '-X *(POST|PUT|PATCH|DELETE)|--data|--data-raw|-d[[:space:]]|/trigger'; then # 🔴 (a) 通知型 trigger 放行(inkstone/ISEP#130;判準與 prod-write-guard.sh 同一份):
hit=1 # `…/webhooks/named/<ns>/notify_leo/trigger` 發一則 Telegram 給 leo**什麼都沒改**。
# wiki `agent-memory.md` 寫明它是找 leo 的正式通道;prod-write-guard 在 ISEP#63 就放行了它,
# 本閘卻因為路徑尾巴是 `/trigger` 照擋 ⇒ 兩支閘對同一條指令說不同的話,
# 而「發通知」被擋的結果是**雲端撞到人閘也叫不動 leo**inkstone/InkStoneCo#110)。
# 放行的範圍刻意只有一個名字:指令裡打到 leo21c 的**每一個**網址都得是它,
# 混進部署端點(`…/webhooks/named` 無名字)或別的工作流 ⇒ 照擋。
NOTIFY_ONLY=$(printf '%s' "$cmd" | python3 -c '
import re, sys
cmd = sys.stdin.read()
ALLOW = {"notify_leo"}
urls = [u for u in re.findall(r"https?://[^\s\"\x27<>]+", cmd) if "leo21c.workers.dev" in u.lower()]
PAT = re.compile(r"https?://[^/]+/webhooks/named/[^/]+/([A-Za-z0-9_-]+)/trigger/?$")
def notify(u):
m = PAT.match(u.rstrip(",;)"))
return bool(m) and m.group(1) in ALLOW
print("notify-only" if urls and all(notify(u) for u in urls) else "")
' 2>/dev/null || printf '')
if [ "$NOTIFY_ONLY" != "notify-only" ]; then
# 🔴 (b) 先剪掉唯讀工具的 `-d`inkstone/ISEP#13009-04 雲端實撞):
# `curl -s https://…leo21c…/x | tr -d '\r'`、`cut -d= -f2`、`sort -d`、`date -d` ……
# 這些 `-d` 沒有一個會寫到那台,舊判準 `-d[[:space:]]` 卻把整條純 GET 擋下
# ⇒ 「連讀都被擋」。prod-write-guard.sh 在 2026-08-12 就修過同一個洞,本閘漏了。
# 剪法與那支同一句 sed,剪完剩下的 `-d` 才是 curl 的 body。
cmd_w=$(printf '%s' "$cmd" | sed -E 's/(^|[|;&( ])(tr|cut|sort|uniq|date|xargs|paste|join|du|logger|split|comm)[[:space:]]+-d/\1\2 __READONLY_D__/g')
if printf '%s' "$cmd_w" | grep -qE -- '-X *(POST|PUT|PATCH|DELETE)|--request *(POST|PUT|PATCH|DELETE)|--data|--data-raw|-d[[:space:]]|/trigger'; then
hit=1
fi
fi fi
fi fi
@@ -87,7 +114,8 @@ leo 原話:「**leo21c 就是我這個普通用戶,不應該讓你去操控
改法:把目標明寫成 youlin,不要吃 `~/.arcrun/config.yaml` 的預設—— 改法:把目標明寫成 youlin,不要吃 `~/.arcrun/config.yaml` 的預設——
那個檔至今仍指著 leo21cKV id 與 encryption_key 是該實例專屬,換不過去)。 那個檔至今仍指著 leo21cKV id 與 encryption_key 是該實例專屬,換不過去)。
cypher : https://arcrun-cypher-executor.youlin-hsieh-dev.workers.dev cypher : https://arcrun-cypher-executor.arcrun-yuga3bse.workers.dev
(09-02 重裝後的子網域;舊名 youlin-hsieh-dev 的 DNS 已不存在,打它一律 000)
ns : yuga3bse ns : yuga3bse
CF : 1129efd7df2e8899d537e9c8fbabb6cb CF : 1129efd7df2e8899d537e9c8fbabb6cb
token : 頂層 .env 的 CLOUDFLARE_API_TOKEN_YOULIN_CC_USE token : 頂層 .env 的 CLOUDFLARE_API_TOKEN_YOULIN_CC_USE
+70
View File
@@ -59,6 +59,76 @@ if MAIN and VER != "未知" and MAIN != VER:
else: else:
notes.append("️ 這一份比 ISEP main 新(載入 %s main %s)——沒發版的改動只在這台機器上。" % (VER, MAIN)) notes.append("️ 這一份比 ISEP main 新(載入 %s main %s)——沒發版的改動只在這台機器上。" % (VER, MAIN))
# ══ ④ 打了 tag 卻沒 release(運送鏈斷在 leo 看得到的那一站之前)═══════════
#
# 🔴 為什麼要在開場報(inkstone/ISEP#67 → comment 6574,總管 2026-09-07 裁定):
# v0.23.0v0.24.0 的 tag 都推了,Gitea Releases 頁卻停在 v0.22.0——
# 交棒給 leo 的「測試位置 releases/tag/v0.24.0」打開是一頁空 tag。
# 建 release 的工具(scripts/release-ship)在 09-05 就寫好了,但**沒有任何東西在
# 下一個 session 開場說「你上一版少了一站」**——於是斷點靠人記得,而人沒記得。
# 判準(與 release-shiprelease-check 同一份:hooks/lib/release_chain.py):
# · Gitea 上最新的 tag,它的 release 在不在 → 不在=「打了 tag 沒 release」
# · main 宣稱的版本(①已經拿到的 MAIN)比最新 tag 新 → 「定版了沒打 tag」
# 兩者都在 ⇒ 一個字都不說(天天念的東西會被學會忽略)。
# 匿名讀(D20)、逾時 6 秒、問不到就閉嘴;只快取「都在」的結果 6 小時,
# 缺件不快取——補完的下一個 session 就該安靜,不該再念 6 小時。
def chain_gap():
"""回 (版本, [(站, 補法)]) 或 None(問不到/沒有 tag/都在)。"""
fx = None
if os.environ.get("ISEP_BEACON_SKIP_NET") == "1":
fxp = os.environ.get("ISEP_BEACON_CHAIN_FIXTURE")
if not fxp:
return None
try:
fx = json.load(open(fxp, encoding="utf-8"))
except Exception:
return None
try:
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import release_chain as rc
except Exception:
return None
ship = os.path.join(ROOT, "scripts", "release-ship")
ship_cmd = ("python3 %s" % ship) if os.path.isfile(ship) else \
"先 `claude plugin update isep@inkstone`(這一份 v%s 還沒有 scripts/release-ship)再跑 `python3 \"$CLAUDE_PLUGIN_ROOT\"/scripts/release-ship`" % VER
chain = rc.Chain(fixture=fx, timeout=6)
try:
tags = chain.tags()
if not tags:
return None
latest = max(tags, key=rc.vtuple)
cache = os.path.join(os.environ.get("ISEP_BEACON_CACHE_DIR", "/tmp"), ".isep-chain-ok-" + latest)
# main 定版了、tag 還沒打 ⇒ 缺的是 tag 那一站(MAIN 來自 ①,可能是 6 小時內的快取)
if MAIN and rc.vtuple(MAIN) > rc.vtuple(latest):
g = [(label, fix.format(v=MAIN, ship=ship_cmd)) for k, label, fix in rc.STATIONS if k == "tag"]
return MAIN, g
try:
if fx is None and time.time() - os.path.getmtime(cache) < 6 * 3600:
return None
except Exception:
pass
rels = chain.releases()
g = [(label, fix.format(v=latest.lstrip("v"), ship=ship_cmd))
for k, label, fix in rc.gaps(latest, tags, rels) if k == "release"]
if not g:
try:
open(cache, "w").write(latest)
except Exception:
pass
return None
return latest.lstrip("v"), g
except Exception:
return None
cg = chain_gap()
if cg:
ver_gap, stations = cg
notes.append(
"🔴 **v%s 送到一半:%s**——leo 那頁(Gitea Releases)看不到這一版,對他等於不存在。"
"補:%sinkstone/ISEP#67"
% (ver_gap, "".join("" + label for label, _f in stations),
"".join(fix for _l, fix in stations)))
# ══ ② 專案裡有沒有 ISEP 腳本的舊複本在遮蔽正門 ══════════════════════════ # ══ ② 專案裡有沒有 ISEP 腳本的舊複本在遮蔽正門 ══════════════════════════
# #
# 🔴 實例(inkstone/ISEP#90 ②):`InkStoneCo/scripts/ticket` 是 ISEP `scripts/ticket` # 🔴 實例(inkstone/ISEP#90 ②):`InkStoneCo/scripts/ticket` 是 ISEP `scripts/ticket`
+49 -16
View File
@@ -30,13 +30,24 @@
其他 目錄運算式,可能是相對的;呼叫端自己 `cd` 進去問 git(唯讀)。 其他 目錄運算式,可能是相對的;呼叫端自己 `cd` 進去問 git(唯讀)。
"." =「就是呼叫端自己的 cwd」(指令裡沒有 cd 也沒有 -C)。 "." =「就是呼叫端自己的 cwd」(指令裡沒有 cd 也沒有 -C)。
用法:printf '%s' "$CMD" | python3 checkout_target_dir.py 出路的判準也住在這裡(inkstone/ISEP#109 → comment 65872026-09-07
閘訊息教的出路是 `WORKTREE_OK=1 git -C … checkout …`。舊版讀的是 **hook 自己的
環境變數**,而 PreToolUse hook 跑在指令之前、跟指令不是同一個行程——指令字串裡的
`WORKTREE_OK=1` 是給 git 的前綴賦值,hook 的行程裡根本沒有它 ⇒ 總管三次照貼三次被擋。
⇒ 改成認**指令字串裡的字面前綴**,而且判準是位置不是字:那個賦值必須是
「會移動 HEAD 的那條 git 指令」自己的前綴(`echo WORKTREE_OK=1; git checkout` 不算、
`WORKTREE_OK=1 echo hi && git checkout` 不算、寫在 commit 訊息裡不算)。
留痕就是那個前綴本身——它在指令歷史上。
用法:printf '%s' "$CMD" | python3 checkout_target_dir.py → 目錄運算式(見上)
printf '%s' "$CMD" | python3 checkout_target_dir.py --escape WORKTREE_OK=1
→ 那條 checkout 帶著這個前綴就印 1,否則空
""" """
import os import os
import sys import sys
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from push_target_dir import _events, _join # noqa: E402 from push_target_dir import _ENV_ASSIGN, _events, _join # noqa: E402
VERBS = ("checkout", "switch") VERBS = ("checkout", "switch")
UNKNOWN = "?" UNKNOWN = "?"
@@ -52,14 +63,19 @@ def _step(base, path):
def _moves_head(tokens): def _moves_head(tokens):
"""tokens 是整串 `git …`。回傳 (會不會動 HEAD, -C 指的路徑 or None) """tokens 是整串 `[NAME=value …] git …`
回傳 (會不會動 HEAD, -C 指的路徑 or None, 前綴賦值清單)。
判準只有「這個動作動不動 HEAD」,不看任何措辭: 判準只有「這個動作動不動 HEAD」,不看任何措辭:
git checkout -- <檔>git checkout HEAD -- <檔> ⇒ 還原檔案,不動 git checkout -- <檔>git checkout HEAD -- <檔> ⇒ 還原檔案,不動
git checkout -p ⇒ 挑 hunk,不動 git checkout -p ⇒ 挑 hunk,不動
git checkout(沒有任何目標) ⇒ git 自己會報錯 git checkout(沒有任何目標) ⇒ git 自己會報錯
""" """
tok = list(tokens[1:]) # 去掉 "git" tok = list(tokens)
env = []
while tok and _ENV_ASSIGN.match(tok[0]):
env.append(tok.pop(0)) # `WORKTREE_OK=1 git …` 的前綴——出路就認這個
tok = tok[1:] # 去掉 "git"
c_path = None c_path = None
while tok and tok[0].startswith("-"): while tok and tok[0].startswith("-"):
if tok[0] == "-C" and len(tok) > 1: if tok[0] == "-C" and len(tok) > 1:
@@ -72,24 +88,25 @@ def _moves_head(tokens):
tok.pop(0) tok.pop(0)
continue continue
if tok[0].startswith("--git-dir"): if tok[0].startswith("--git-dir"):
return (False, None) # 自己指 git-dir 的花式用法,不猜 return (False, None, env) # 自己指 git-dir 的花式用法,不猜
tok.pop(0) tok.pop(0)
if not tok or tok[0] not in VERBS: if not tok or tok[0] not in VERBS:
return (False, None) return (False, None, env)
rest = tok[1:] rest = tok[1:]
if "--" in rest or "-p" in rest or "--patch" in rest: if "--" in rest or "-p" in rest or "--patch" in rest:
return (False, None) return (False, None, env)
if not [a for a in rest if not a.startswith("-")] and \ if not [a for a in rest if not a.startswith("-")] and \
not any(a in ("-b", "-B", "-c", "-C") for a in rest): not any(a in ("-b", "-B", "-c", "-C") for a in rest):
return (False, None) return (False, None, env)
return (True, c_path) return (True, c_path, env)
def find_checkout_target(cmd): def find_checkout(cmd):
"""回 (目錄運算式, 那條 checkout 的前綴賦值清單)。目錄運算式的三種值見檔頭。"""
events = _events(cmd, VERBS, strip_env=True) events = _events(cmd, VERBS, strip_env=True)
if not events: if not events:
return "" # 引號壞掉之類——沿用「不擋在不確定上」 return ("", []) # 引號壞掉之類——沿用「不擋在不確定上」
stack = [None] # 每層括號各自的 cwd;None = 同呼叫端的 cwd stack = [None] # 每層括號各自的 cwd;None = 同呼叫端的 cwd
for kind, val in events: for kind, val in events:
@@ -101,7 +118,7 @@ def find_checkout_target(cmd):
elif kind == "cd": elif kind == "cd":
stack[-1] = _step(stack[-1], val) stack[-1] = _step(stack[-1], val)
elif kind == "verb": elif kind == "verb":
moves, c_path = _moves_head(val) moves, c_path, env = _moves_head(val)
if not moves: if not moves:
continue continue
where = stack[-1] where = stack[-1]
@@ -110,13 +127,29 @@ def find_checkout_target(cmd):
# (而且 -C 若是相對路徑,是接在 cd 之後算,不是接在 cwd) # (而且 -C 若是相對路徑,是接在 cd 之後算,不是接在 cwd)
where = _step(where, c_path) where = _step(where, c_path)
if where == UNKNOWN: if where == UNKNOWN:
return UNKNOWN return (UNKNOWN, env)
return where or "." return (where or ".", env)
return "" return ("", [])
def find_checkout_target(cmd):
return find_checkout(cmd)[0]
def has_escape(cmd, assignment):
"""會移動 HEAD 的那條 git 指令,自己的前綴裡有沒有這個字面賦值(例 `WORKTREE_OK=1`)。
只看**那條指令的前綴**:印在別處、掛在別的指令上、寫在引號裡都不算。"""
_expr, env = find_checkout(cmd)
return assignment in env
def main(): def main():
sys.stdout.write(find_checkout_target(sys.stdin.read())) argv = sys.argv[1:]
cmd = sys.stdin.read()
if len(argv) == 2 and argv[0] == "--escape":
sys.stdout.write("1" if has_escape(cmd, argv[1]) else "")
return
sys.stdout.write(find_checkout_target(cmd))
if __name__ == "__main__": if __name__ == "__main__":
+358 -33
View File
@@ -2,8 +2,9 @@
"""hooks/lib/mainline.py —— 「現在的主線是哪一個」這件事的**唯一存放處**。 """hooks/lib/mainline.py —— 「現在的主線是哪一個」這件事的**唯一存放處**。
這是 helper,不是閘(inkstone/ISEP#40 S7`lib/` 底下的東西不算一支手寫的閘)。 這是 helper,不是閘(inkstone/ISEP#40 S7`lib/` 底下的東西不算一支手寫的閘)。
個呼叫者共用它,所以「主線是誰」的答案只有一份: 個呼叫者共用它,所以「主線是誰」「誰在主線上」的答案只有一份:
· `scripts/mainline` —— 人問「現在的主線是哪一個」 · `scripts/mainline` —— 人問「現在的主線是哪一個」
· `scripts/ticket pickclaim` —— 雲端工人抓票:抓的是主線的成員
· `hooks/lib/countdown.py` —— 每一則回覆眼前那一行的第二段 · `hooks/lib/countdown.py` —— 每一則回覆眼前那一行的第二段
· `hooks/mainline-focus-guard.sh` —— 派了一張不屬於主線的票就攔一次 · `hooks/mainline-focus-guard.sh` —— 派了一張不屬於主線的票就攔一次
@@ -13,24 +14,43 @@
SOP 說「有 active milestone 時只做該 milestone 的事」——但**「那個」在現場沒有指涉對象**。 SOP 說「有 active milestone 時只做該 milestone 的事」——但**「那個」在現場沒有指涉對象**。
leo 的原話是「**14 個里程碑同時亮著卻不知道該看哪個**」。 leo 的原話是「**14 個里程碑同時亮著卻不知道該看哪個**」。
⇒ 要解的不是「milestone 太多」(跨 repo 同名是既有做法,v0.6.0 §4SOP S7-4),
要解的是「**這一刻我在做哪一條**」沒有答案。
⇒ 所以這個檔的形狀就是答案的形狀:**一個檔,放得下一條**。 ⇒ 所以這個檔的形狀就是答案的形狀:**一個檔,放得下一條**。
沒有清單、沒有優先序、沒有「前三名」——被覆蓋掉的那條就不再是主線。 沒有清單、沒有優先序、沒有「前三名」——被覆蓋掉的那條就不再是主線。
問「現在的主線是哪一個」永遠只會拿到 0 或 1 個答案,不會拿到 14 個。 問「現在的主線是哪一個」永遠只會拿到 0 或 1 個答案,不會拿到 14 個。
── 主線是一個「名字」,錨在一個具體的 milestone 上 ────────────────── ── 一條線在整個 Gitea 只有一個里程碑;別的 repo 用相依指過來(inkstone/ISEP#133──
Gitea 的 milestone 不能跨 repo,而同一條線常常同時開在 5 個 repo(票上實查) 🔴 本檔第一版寫的是「同名跨 repo 是既有做法,成員=票所屬 milestone 的標題與主線相同」
所以: 那不是規則,是當時現場的樣子——而 leo 早在 2026-08-20inkstone/ISEP#30)與 08-27
· **錨**anchor)= `owner/repo#<milestone id>`:期限、進度、目標宣告都讀它 inkstone/InkStoneCo#44)就定了相反的規則:**一條線一個里程碑,別 repo 的票用相依指到 hub 票**。
· **成員判定** 票所屬 milestone 的**標題**與主線標題相同(不分 repo) 工具把現場當規則寫進檔頭,總管 09-07 照它做,還在 arcrun-rag 補建了一個同名的;
⇒ 「同名跨 repo」照舊能用,而「現在在做哪一條」仍然只有一個答案。 leo 當天:「拆,誰說『同名跨 repo 是 mainline 機制的一部分』,早就定了只有一個 milestone,
不同 repo 用指針」。⇒ 檔頭寫的「既有做法」會被當成規則抄走,所以這裡改成規則本身:
── 這支從不打網路 ──────────────────────────────────────────────── · **錨**anchor)= `owner/repo#<milestone id>`:整個 Gitea 只有這一個 milestone 物件。
它被 `UserPromptSubmit` 用(每一則訊息的關鍵路徑)。在那裡打 HTTP = 每講一句話 期限、進度、目標宣告都讀它。
· **hub 票**`hub_ticket`,可選)= 這條線的載體票(例:inkstone/InkStoneCo#44「這張票是那條線本身」)。
別 repo 的票要進主線,就成為它(或 hub 里程碑裡任一張票)的 **dependency**。
· **成員判定** `collect_members()`hub 里程碑裡的票 hub 票,再沿著 Gitea 的
`/dependencies` 邊(跨 repo)一路收下去。**判準是 milestone id 與相依邊,不是標題。**
同名 milestone 在別的 repo 裡開著也**不算**成員——那正是被推翻的那條。
· `belongs()` 因此需要「這張票掛在哪個 milestone」+「誰把它當相依」兩件事實才敢說「不屬於」;
只知道一半 ⇒ 回 None(不知道),閘拿到 None 一律放行。
── `load()``line()` 從不打網路 ─────────────────────────────────
它們被 `UserPromptSubmit` 用(每一則訊息的關鍵路徑)。在那裡打 HTTP = 每講一句話
都先等一次網路。網路那一半全部在 `scripts/mainline`setrefreshadopt), 都先等一次網路。網路那一半全部在 `scripts/mainline`setrefreshadopt),
本支讀寫 state 檔。讀不到 ⇒ 回「沒有主線」,**不編一條出來**。 本支讀寫只碰 state 檔。讀不到 ⇒ 回「沒有主線」,**不編一條出來**。
兩個例外都不在關鍵路徑上:`fetch_gitea()`inkstone/ISEP#140,只有 SessionStart 的
`scripts/mainline refresh` 叫)與 `collect_members()`(要呼叫端把 api 函式傳進來,
本檔自己不帶憑證、不認主機;`load()`/`line()` 永遠不叫它們)。
── 三個來源,優先序寫死:家目錄 > repo 那份 > Gitea main 那份 ───────
① 家目錄 `~/.claude/isep-countdown/mainline.json`(這台機器上 refresh 過、有進度)
② repo 那份 `InkStoneCo/system-dev/mainline.json`(隨 repo 走,inkstone/ISEP#130
③ Gitea 上 `inkstone/InkStoneCo` main 的同一個檔(inkstone/ISEP#140
①② 之間誰算數看 `set_at`(見 `load()`);③ **只在 ①② 都不存在時**被問一次,
抓到就寫進 ①,之後跟 ① 一樣對待。③ 讀的就是 ② 那個檔,只是從 Gitea 拿而不是從
工作樹拿——它不是第二套主線來源。
""" """
import json import json
import os import os
@@ -58,39 +78,214 @@ def path() -> str:
return os.path.join(state_dir(), STATE_NAME) return os.path.join(state_dir(), STATE_NAME)
# ── repo 裡的那一份(inkstone/ISEP#130)──────────────────────────────
#
# 主線原本只住在 `~/.claude/isep-countdown/mainline.json`——**這台機器的家目錄**。
# 雲端 session 是另一台機器:家目錄是空的,clone 下來的 repo 才是它唯一拿得到的東西。
# 2026-09-05 leo:「routine 每天早上開啟後抓不到任務」——不是 Gitea 沒票,
# 是雲端根本不知道主線是哪一條。
# ⇒ `inkstone/InkStoneCo` 的 `system-dev/mainline.json` 是**隨 repo 走的那一份**
# PR inkstone/InkStoneCo#118 放進去的)。這裡的規矩:
# · 讀:家目錄那份沒有 ⇒ 讀 repo 那份(雲端就是這個形狀)。
# 兩份都在 ⇒ 用 `set_at` 較新的(誰後標的誰算數,不分本機雲端)。
# · 寫:`set``adopt``clear` 這種「主線是誰」的改動 ⇒ 兩份一起寫(`mirror=True`)。
# `refresh`/閘順手學到成員 ⇒ 只寫家目錄那份——否則每開一個 session
# InkStoneCo 的工作樹就髒一次,而髒的 diff 沒有人會去 commit。
# · repo 那份要 commit/開 PR 才到得了雲端;這支不碰 git。
REPO_REL = os.path.join("system-dev", STATE_NAME)
def project_roots():
"""「這個 session 的專案在哪」的候選根,依序:`$CLAUDE_PROJECT_DIR`、它底下的 `InkStoneCo/`
(雲端薄殼的形狀:專案根是薄殼、真身在 InkStoneCo/)、cwd、cwd 底下的 `InkStoneCo/`。
主線檔(本檔)與 `scripts/milestone-account` 的帳本(inkstone/ISEP#133)都靠它找
`system-dev/`——兩份「隨 repo 走的狀態」用同一把尺找家,不各寫一套。"""
roots = []
for r in (os.environ.get("CLAUDE_PROJECT_DIR", "").strip(), os.getcwd()):
if r:
for c in (r, os.path.join(r, "InkStoneCo")):
if c not in roots:
roots.append(c)
return roots
def repo_candidates():
"""repo 那一份可能在哪:明指 > 專案根 > 專案根底下的 InkStoneCo/(雲端薄殼的形狀)> cwd 同兩層。"""
out = []
forced = os.environ.get("ISEP_MAINLINE_REPO_FILE", "").strip()
if forced == "none":
return [] # 測試用:把「repo 那份」整個拿掉,外界定住
if forced:
out.append(forced)
for r in project_roots():
p = os.path.join(r, REPO_REL)
if p not in out:
out.append(p)
return out
def repo_path(for_write=False):
"""讀:第一個**存在**的檔。寫:第一個 `system-dev/` 目錄存在的位置(檔可以還沒有)。
找不到 ⇒ None(雲端沒 clone InkStoneCo、或 cwd 在別的 repo 時都是正常狀態)。"""
for p in repo_candidates():
if for_write:
if os.path.isdir(os.path.dirname(p)):
return p
elif os.path.isfile(p):
return p
return None
def _valid(d):
"""一份主線檔長什麼樣才算數:dict、而且有 title。三個來源用同一把尺。"""
return d if (isinstance(d, dict) and d.get("title")) else None
def _read(p):
try:
with open(p) as f:
d = json.load(f)
except Exception:
return None
return _valid(d)
# ── Gitea main 上的那一份(inkstone/ISEP#140)────────────────────────
#
# 雲端薄殼 `youlinhsieh/inkstoneco` 的 SessionStart 跑在 `bootstrap.sh` 之前:那時
# `InkStoneCo/` 還沒 clone,家目錄又是空的 ⇒ 上面兩份都不存在 ⇒ `countdown.py` 退到
# 第二基準「期限最近的 milestone」⇒ 第一則 prompt 印出一條兩週前的舊線
# (票上實測:`🔴 主線 把管理這條線做對 已逾期 341 小時`+`🎯 現在沒有主線`)。
# 機制沒壞,是順序。而「哪一條是主線」這個指標本來就在 Gitea 上讀得到。
#
# 規矩(跟上面「repo 裡的那一份」那段接起來,不另立一套):
# · 只在家目錄與 repo 那份**都不存在**時問 Gitea,問一次;任一份在場就不問。
# · 只有 SessionStart 的 `scripts/mainline refresh` 會叫 `fetch_gitea()`;抓到就
# `save()` 進家目錄(不 mirror:雲端沒有 InkStoneCo/ 可寫,本機也不弄髒工作樹)。
# bootstrap 之後 repo 那份出現時,兩份 `set_at` 相同 ⇒ 家目錄那份算數(它有 refresh 過的進度)。
# · 匿名優先。匿名被拒(401/403/404)且環境拿得到 Gitea token 才帶 token 再問一次
# ——`inkstone/InkStoneCo` 在 Gitea 是 **private**2026-09-07 實測:匿名打 raw
# contentsrepo API 都 404),沒 token 就真的讀不到。
# · 讀不到(斷網/5xx/不是 JSON/沒 title/逾時)⇒ 回 None,退回現行行為,不報錯。
# 逾時有上限(`ISEP_MAINLINE_GITEA_TIMEOUT`,預設 4 秒,最多問兩次)。
# · 測試用:`ISEP_MAINLINE_GITEA_URL=none` 把這個來源整個拿掉;`TICKET_HOST` 換主機
# (既有測試都把它指到連不上的位址,所以它們照舊離線)。
GITEA_HOST_DEFAULT = "https://git.uncle6.me"
GITEA_REPO = "inkstone/InkStoneCo"
GITEA_REF = "main"
def gitea_url() -> str:
forced = os.environ.get("ISEP_MAINLINE_GITEA_URL", "").strip()
if forced == "none":
return ""
if forced:
return forced
host = (os.environ.get("TICKET_HOST", "").strip() or GITEA_HOST_DEFAULT).rstrip("/")
return "%s/api/v1/repos/%s/raw/%s?ref=%s" % (
host, GITEA_REPO, REPO_REL.replace(os.sep, "/"), GITEA_REF)
def fetch_gitea(token="", timeout=None):
"""去 Gitea 讀 `inkstone/InkStoneCo` main 上的 `system-dev/mainline.json`。
回一份跟 `_read()` 同樣通過 `_valid()` 的 dict,或 None。**永遠不 raise。**
`token`:字串,或一個回字串的函式(只在匿名被拒時才會被叫)。
🔴 這是本檔唯一會打網路的函式,只准 SessionStart 的 `scripts/mainline refresh` 叫;
`load()``line()` 走的是每一則訊息的關鍵路徑,不准碰它。
"""
url = gitea_url()
if not url:
return None
if timeout is None:
try:
timeout = float(os.environ.get("ISEP_MAINLINE_GITEA_TIMEOUT", "") or 4)
except Exception:
timeout = 4.0
import urllib.error
import urllib.request
def get(headers):
req = urllib.request.Request(url, headers=headers)
with urllib.request.urlopen(req, timeout=timeout) as r:
return r.read().decode("utf-8", "replace")
try:
text = get({}) # 匿名優先(D20 的形狀:讀不帶憑證)
except urllib.error.HTTPError as e:
if e.code not in (401, 403, 404):
return None
# `token` 可以是字串,也可以是「被拒了才去拿」的函式——拿 token 可能要掃 git remote、
# 可能拿不到而想開口抱怨,匿名讀得到的時候根本不該走到那裡。
tok = token() if callable(token) else token
if not tok:
return None
try:
text = get({"Authorization": "token " + tok}) # private repo:帶 token 再問一次
except Exception:
return None
except Exception:
return None
try:
return _valid(json.loads(text))
except Exception:
return None
def load(): def load():
"""讀主線。沒有/壞掉 ⇒ None(=現在沒有主線),**不是例外**。 """讀主線。沒有/壞掉 ⇒ None(=現在沒有主線),**不是例外**。
「沒有主線」是一個正常狀態,不是故障:ISEP#82 驗收第 4 條寫死了 「沒有主線」是一個正常狀態,不是故障:ISEP#82 驗收第 4 條寫死了
「沒有任何主線時不能整組壞掉」。所以這支從不 raise。 「沒有任何主線時不能整組壞掉」。所以這支從不 raise。
家目錄那份與 repo 那份都在時,`set_at` 較新的算數(格式固定 `YYYY-MM-DD HH:MM`
字串比大小就是時間比大小);一樣新 ⇒ 家目錄那份(它才有 refresh 過的進度)。
""" """
try: local = _read(path())
with open(path()) as f: rp = repo_path()
d = json.load(f) remote = _read(rp) if rp else None
except Exception: if local and remote:
return None return remote if (remote.get("set_at") or "") > (local.get("set_at") or "") else local
if not isinstance(d, dict) or not d.get("title"): return local or remote
return None
return d
def save(d) -> bool: def save(d, mirror=False) -> bool:
"""寫家目錄那份;`mirror=True` 時同時寫 repo 那份(只有「主線是誰」變了才這樣叫)。
回 True/False 只看家目錄那份——repo 那份寫不寫得進去用 `repo_path(for_write=True)` 另外問。"""
try: try:
with open(path(), "w") as f: with open(path(), "w") as f:
json.dump(d, f, ensure_ascii=False, indent=2) json.dump(d, f, ensure_ascii=False, indent=2)
return True
except Exception: except Exception:
return False return False
if mirror:
rp = repo_path(for_write=True)
if rp:
try:
with open(rp, "w") as f:
json.dump(d, f, ensure_ascii=False, indent=2)
f.write("\n")
except Exception:
pass
return True
def clear() -> bool: def clear(mirror=False) -> bool:
ok = True
try: try:
os.remove(path()) os.remove(path())
return True
except FileNotFoundError: except FileNotFoundError:
return True pass
except Exception: except Exception:
return False ok = False
if mirror:
rp = repo_path()
if rp:
try:
os.remove(rp)
except Exception:
ok = False
return ok
def parse_ts(raw): def parse_ts(raw):
@@ -116,6 +311,8 @@ def norm(s) -> str:
🔴 刻意不做同義詞、不做模糊比對:主線是**被指定的**,不是被猜出來的。 🔴 刻意不做同義詞、不做模糊比對:主線是**被指定的**,不是被猜出來的。
猜錯的方向是「把不屬於主線的票放行」,那正是這張票要擋的事。 猜錯的方向是「把不屬於主線的票放行」,那正是這張票要擋的事。
inkstone/ISEP#133 起標題只用來**查**Gitea 的 `milestones=` 只吃名字),
成員判定看的是 milestone id 與相依邊,不再拿標題當判準。
""" """
return "".join((s or "").split()).lower() return "".join((s or "").split()).lower()
@@ -126,27 +323,155 @@ def ref_of(ms) -> str:
return "%s/%s#%s" % (ms.get("owner") or "?", ms.get("repo") or "?", ms.get("id") or "?") return "%s/%s#%s" % (ms.get("owner") or "?", ms.get("repo") or "?", ms.get("id") or "?")
def split_ref(ref):
"""`owner/repo#N` → (owner, repo, N);不是這個形狀 ⇒ None。"""
import re
m = re.match(r"^([\w.-]+)/([\w.-]+)#(\d+)$", (ref or "").strip())
return (m.group(1), m.group(2), int(m.group(3))) if m else None
def issue_ref(issue, owner=None, repo=None):
"""Gitea 的 issue dict → `owner/repo#N`。相依端點回的 issue 帶 `repository.full_name`
列 milestone 的端點有時不帶 ⇒ 呼叫端補 owner/repo。"""
if not isinstance(issue, dict) or not issue.get("number"):
return None
full = ((issue.get("repository") or {}).get("full_name")) or (
"%s/%s" % (owner, repo) if owner and repo else None)
return "%s#%s" % (full, issue["number"]) if full else None
def hub_ticket(ms):
return ((ms or {}).get("hub_ticket") or "").strip() or None
def members(ms): def members(ms):
return set(ms.get("members") or []) if ms else set() out = set(ms.get("members") or []) if ms else set()
h = hub_ticket(ms)
if h:
out.add(h)
return out
def belongs(ticket_ref, ms, ticket_milestone_title=None): MEMBER_WALK_CAP = 300
def collect_members(api, ms, cap=MEMBER_WALK_CAP):
"""主線的成員(inkstone/ISEP#133):**hub 里程碑裡的票 hub 票,沿 `/dependencies` 收下去**。
`api(path)` 由呼叫端提供(`scripts/ticket` 的 `api``api_soft`):回解析好的 JSON 或 None。
本檔不帶憑證、不認主機——這樣 `scripts/ticket` 的離線測試用假池子就測得到整條路。
回 (members, info)
members 排好序的 `owner/repo#N` 清單(含已關的——進度與 `has` 都要看得到它們)
info {"milestone": [...], "via_deps": [...], "hub_ticket": ref|None,
"reached": bool, "capped": bool}
🔴 `reached=False` 連 hub 里程碑那一頁都讀不到 ⇒ 呼叫端**不要拿空清單蓋掉舊快取**
(讀不到 ≠ 沒有成員)。
判準只有兩個 Gitea 事實:票的 `milestone.id` 等於錨的 id、以及相依邊。標題只拿來查詢。
"""
import urllib.parse
owner, repo, mid = ms.get("owner"), ms.get("repo"), ms.get("id")
title = ms.get("title") or ""
info = {"milestone": [], "via_deps": [], "hub_ticket": hub_ticket(ms),
"reached": False, "capped": False}
q = urllib.parse.urlencode({"state": "all", "type": "issues", "milestones": title, "limit": 100})
rows = api("/repos/%s/%s/issues?%s" % (owner, repo, q))
if not isinstance(rows, list):
return [], info
info["reached"] = True
roots = []
for it in rows:
if not isinstance(it, dict) or it.get("pull_request"):
continue
im = it.get("milestone") or {}
# 🔴 `milestones=` 在不同 Gitea 版本對「名稱 vs id」的解讀不一致,拿回來要自己用 id 確認
if str(im.get("id")) != str(mid) and norm(im.get("title")) != norm(title):
continue
r = issue_ref(it, owner, repo)
if r and r not in roots:
roots.append(r)
info["milestone"] = list(roots)
h = hub_ticket(ms)
if h and h not in roots:
roots.append(h)
seen, queue, out = set(roots), list(roots), list(roots)
while queue:
cur = queue.pop(0)
parts = split_ref(cur)
if not parts:
continue
deps = api("/repos/%s/%s/issues/%d/dependencies?limit=100" % parts)
if not isinstance(deps, list):
continue # 這一張讀不到:跳過它,不當成「沒有相依」以外的事
for d in deps:
r = issue_ref(d)
if not r or r in seen:
continue
if len(out) >= cap:
info["capped"] = True
break
seen.add(r); out.append(r); queue.append(r)
info["via_deps"].append(r)
return sorted(set(out)), info
def _ms_matches(ticket_milestone, ms):
"""票所掛的 milestone 是不是錨那一個。dict 看 id(沒 id 才退回標題);str 只有標題。"""
if isinstance(ticket_milestone, dict):
if ticket_milestone.get("id") is not None and ms.get("id") is not None:
return str(ticket_milestone.get("id")) == str(ms.get("id"))
return norm(ticket_milestone.get("title")) == norm(ms.get("title"))
return norm(ticket_milestone) == norm(ms.get("title"))
def belongs(ticket_ref, ms, ticket_milestone=None, blocks=None):
"""這張票屬不屬於主線?回 True/FalseNone。 """這張票屬不屬於主線?回 True/FalseNone。
None **不知道**(快取裡沒有這張票,而呼叫端也沒查到它的 milestone) None **不知道**。🔴 「不知道」不等於「不屬於」——這條分界就是誤攔與否的分水嶺
🔴 「不知道」不等於「不屬於」——這條分界就是誤攔與否的分水嶺。
呼叫的閘拿到 None 時該放行(本 repo 心法第 2 條:誤攔比漏擋更該修)。 呼叫的閘拿到 None 時該放行(本 repo 心法第 2 條:誤攔比漏擋更該修)。
inkstone/ISEP#133 起要說「不屬於」需要兩件事實都在手上:
ticket_milestone 票掛在哪個 milestonedict 或標題字串;None=沒查)
blocks 誰把這張票當相依(`/issues/N/blocks` 回的 ref 清單;None=沒查)
· 在快取成員裡/就是 hub 票 ⇒ True
· 掛在錨那一個 milestone(同 repo、同 id ⇒ True
· blocks 裡有任何一張是成員或 hub 票 ⇒ True
· milestone 與 blocks 都查過、都不中 ⇒ False
· 只查了其中一半而那一半不中 ⇒ None(別 repo 的票只看 milestone 判不出來)
別 repo 裡同名的 milestone **不算**——那是被 leo 推翻的判準(本檔檔頭)。
""" """
if not ms: if not ms:
return True # 沒有主線 ⇒ 沒有「不屬於主線」這回事 return True # 沒有主線 ⇒ 沒有「不屬於主線」這回事
ref = (ticket_ref or "").strip() ref = (ticket_ref or "").strip()
if ref and ref in members(ms): if ref and ref in members(ms):
return True return True
if ticket_milestone_title is not None: parts = split_ref(ref)
return norm(ticket_milestone_title) == norm(ms.get("title")) same_repo = bool(parts) and parts[0] == ms.get("owner") and parts[1] == ms.get("repo")
if ticket_milestone is not None and ticket_milestone != "" and same_repo and _ms_matches(ticket_milestone, ms):
return True
if blocks is not None:
mem = members(ms)
if any((b or "").strip() in mem for b in blocks):
return True
if ticket_milestone is not None and blocks is not None:
return False
return None return None
def fixture_lookup(fx, ref):
"""把 `ISEP_MAINLINE_FIXTURE` 裡一筆整理成 (ticket_milestone, blocks)。
值是字串 ⇒ 那是它掛的 milestone 標題、而且**沒有人把它當相依**(blocks=[])——
舊測資的形狀,兩件事實都給齊了,判得出 True/False。
值是 dict ⇒ `{"milestone": {...}|"標題", "blocks": ["owner/repo#N", …]}`。
沒收錄 ⇒ None(等同問不到)。"""
if not isinstance(fx, dict) or ref not in fx:
return None
v = fx[ref]
if isinstance(v, dict):
return v.get("milestone"), list(v.get("blocks") or [])
return v, []
def fixture_titles(): def fixture_titles():
"""測試用:把「去 Gitea 問這張票掛在哪」換成一份現成的答案。 """測試用:把「去 Gitea 問這張票掛在哪」換成一份現成的答案。
+15 -5
View File
@@ -91,21 +91,31 @@ def _classify(tokens, verbs=("push",), strip_env=False):
stays deliberately loose here (the verb may sit anywhere after `git`) -- stays deliberately loose here (the verb may sit anywhere after `git`) --
callers re-walk the returned token list to confirm command position, so callers re-walk the returned token list to confirm command position, so
a false positive at this layer costs nothing.""" a false positive at this layer costs nothing."""
body = tokens
if strip_env: if strip_env:
# `FOO=1 git checkout …` -- an env prefix doesn't change which command # `FOO=1 git checkout …` -- an env prefix doesn't change which command
# runs. Opt-in so find_push_target's behaviour stays byte-identical; # runs. Opt-in so find_push_target's behaviour stays byte-identical;
# checkout_target_dir.py turns it on (its predecessor stripped these, # checkout_target_dir.py turns it on (its predecessor stripped these,
# and dropping that would have been a silent regression -- caught by # and dropping that would have been a silent regression -- caught by
# the worktree gate's own case ㉒). # the worktree gate's own case ㉒).
#
# 2026-09-07 (inkstone/ISEP#109 -> comment 6587): the prefix is skipped
# for *classifying* the statement, but the "verb" event hands back the
# full token list, prefix included. The worktree gate's escape hatch is
# exactly that prefix (`WORKTREE_OK=1 git checkout …`), and a PreToolUse
# hook can only see it in the command string -- it never reaches the
# hook's own environment. Dropping it here made the printed way out
# unwalkable. Callers that don't care simply skip leading NAME=value
# tokens themselves (checkout_target_dir._moves_head does).
i = 0 i = 0
while i < len(tokens) and _ENV_ASSIGN.match(tokens[i]): while i < len(tokens) and _ENV_ASSIGN.match(tokens[i]):
i += 1 i += 1
tokens = tokens[i:] body = tokens[i:]
if not tokens: if not body:
return ("other", None) return ("other", None)
if tokens[0] == "cd" and len(tokens) > 1: if body[0] == "cd" and len(body) > 1:
return ("cd", tokens[1]) return ("cd", body[1])
if tokens[0] == "git" and any(v in tokens[1:] for v in verbs): if body[0] == "git" and any(v in body[1:] for v in verbs):
return ("verb", tokens) return ("verb", tokens)
return ("other", None) return ("other", None)
+220
View File
@@ -0,0 +1,220 @@
"""release_chain — ISEP 運送鏈「tag → release」那兩站的**收貨端事實**,一份定義三處用
inkstone/ISEP#67
誰在用:
scripts/release-ship 送貨:把已推的 tag 建成 release(前置條件從這裡問)
scripts/release-check 覆核:逐版問 Gitea「到了嗎」
hooks/lib/beacon_report.py 開場:SessionStart 報「打了 tag 卻沒 release」
🔴 為什麼收成一份:09-05 那版 release-shiprelease-check 各自抄了一套「問 Gitea」
的程式碼;要再讓 SessionStart 也問一次,就是第三份。同一個判準散在三處,
修一份不會帶動另外兩份——`leo21c-write-guard.sh` 那一族就是這樣漂掉的
system-dev/wiki/mistakes.md 2026-09-07)。
🔴 讀一律匿名(D20:讀不帶憑證=自由、不計次)。inkstone/ISEP 是公開 repo
tagsreleases/某個 tag 底下的檔案/兩個 tag 之間的 commit 都不需要 token。
只有 401/403 才退回帶 token 再試一次;token 只有 POST(建 release)才是必要的。
判準是結構不是關鍵字:某一版「送到了沒」=它的 tag 與 release **在不在** Gitea 上。
離線:每個入口各自把 fixture dict 傳進來(鍵:tagsreleasesmanifestcommits),
不打網路。fixture 的形狀在 `Chain.__init__` 的註解。
"""
import base64
import json
import os
import re
import subprocess
import urllib.error
import urllib.request
DEFAULT_HOST = "https://git.uncle6.me"
DEFAULT_REPO = "inkstone/ISEP"
MANIFEST_PATH = ".claude-plugin/plugin.json"
# 運送鏈的三站:鍵、人話、怎麼補(補法的指令由呼叫端決定要不要換成絕對路徑)
STATIONS = [
("dingban", "定版 commit",
"在 main 上 commit 一顆 `定版 v{v}`(= plugin.json 也改成那一版)"),
("tag", "tagGitea",
"打並推 tag`git tag v{v} && git push origin v{v}`"),
("release", "releaseGitea",
"建 release`{ship} v{v}`(這一站就是最常斷的那站)"),
]
class ChainError(Exception):
"""問不到收貨端(網路/HTTP 非 404)。呼叫端自己決定要死還是要閉嘴。"""
def vtuple(v):
nums = re.findall(r"\d+", v or "")
return tuple(int(x) for x in nums[:3]) if nums else (0,)
def tagname(v):
v = (v or "").strip()
return v if v.startswith("v") else "v" + v
def token_from_env_or_remote(host, root=None):
"""建 release 才用得到。環境變數優先;沒有就從 remote URL 裡撈(bootstrap 會帶)。"""
for env in ("GITEA_TOKEN_CLAUDE_CODE", "GITEA_TOKEN"):
if os.environ.get(env):
return os.environ[env]
if not root:
return ""
h = host.split("//")[-1].rstrip("/")
try:
out = subprocess.run(["git", "-C", root, "remote", "-v"],
capture_output=True, text=True, timeout=20).stdout
except Exception:
out = ""
for line in out.splitlines():
if h in line:
m = re.search(r"//[^:/]+:([^@]+)@", line)
if m:
return m.group(1)
return ""
class Chain:
"""一個 repo 的運送鏈收貨端。
fixture(離線用)的形狀:
{"tags": ["v0.24.0", ...],
"releases": ["v0.23.0", ...],
"manifest": {"v0.24.0": "0.24.0", ...}, # 那個 tag 底下 plugin.json 的 version
"commits": {"v0.23.0...v0.24.0": ["定版 v0.24.0(…)", "..."], # 兩 tag 之間的 commit 標題
"v0.24.0": [""]}} # 沒有上一個 release 時
"""
def __init__(self, host=None, repo=None, fixture=None, timeout=25, token=None):
self.host = (host or DEFAULT_HOST).rstrip("/")
self.repo = repo or DEFAULT_REPO
self.fx = fixture
self.timeout = timeout
self.token = token
# ── HTTP:匿名優先 ───────────────────────────────────────────────────
def _get(self, path, params=""):
url = "%s/api/v1/repos/%s/%s%s" % (self.host, self.repo, path, params)
headers = {"Cache-Control": "no-cache"} # 09-05 實撞:邊緣快取的舊值被當 live
for attempt in (0, 1):
if attempt == 1:
if not self.token:
raise ChainError("Gitea 對匿名讀回 401403,而這裡沒有 token%s" % url)
headers["Authorization"] = "token " + self.token
req = urllib.request.Request(url, headers=headers)
try:
with urllib.request.urlopen(req, timeout=self.timeout) as r:
return json.load(r)
except urllib.error.HTTPError as e:
if e.code == 404:
return None
if e.code in (401, 403) and attempt == 0:
continue
raise ChainError("Gitea %s%s %s" % (e.code, url, e.read().decode()[:200]))
except Exception as e:
raise ChainError("連不上 %s%s" % (url, e))
return None
def _names(self, path, key):
names, page = set(), 1
while True:
rows = self._get(path, "?limit=50&page=%d" % page) or []
for r in rows:
n = r.get(key)
if n:
names.add(n)
if len(rows) < 50:
return names
page += 1
# ── 收貨端事實 ───────────────────────────────────────────────────────
def tags(self):
if self.fx is not None:
return set(self.fx.get("tags") or [])
return self._names("tags", "name")
def releases(self):
if self.fx is not None:
return set(self.fx.get("releases") or [])
return self._names("releases", "tag_name")
def release(self, tag):
"""這個 tag 的 releasedict),沒有就 None。"""
if self.fx is not None:
return {"tag_name": tag, "html_url": "(fixture)"} if tag in self.releases() else None
return self._get("releases/tags/%s" % tag)
def manifest_version_at(self, tag):
"""那個 tag 的樹裡 plugin.json 宣稱的版本(None = tag 不在或檔案不在)。
🔴 這是 release-ship 前置①的對象:**要建 release 的那個 tag 的樹**
不是「現在 checkout 出來的工作樹」——工作樹可能是任何分支,跟那個 tag 無關。
"""
if self.fx is not None:
return (self.fx.get("manifest") or {}).get(tag)
d = self._get("contents/%s" % MANIFEST_PATH, "?ref=%s" % tag)
if not d:
return None
try:
raw = base64.b64decode(d.get("content") or "").decode("utf-8")
return (json.loads(raw) or {}).get("version")
except Exception:
return None
def commits_between(self, base, head):
"""base(可 None)到 head 之間的 commit 標題,**不含 merge commit**,舊在前。"""
key = ("%s...%s" % (base, head)) if base else head
if self.fx is not None:
return list((self.fx.get("commits") or {}).get(key) or [])
if base:
d = self._get("compare/%s...%s" % (base, head)) or {}
rows = d.get("commits") or []
else:
rows = self._get("commits", "?sha=%s&limit=50&stat=false&verification=false&files=false" % head) or []
rows = list(reversed(rows))
out = []
for c in rows:
if len(c.get("parents") or []) > 1:
continue
msg = ((c.get("commit") or {}).get("message") or "").strip()
if msg:
out.append(msg.splitlines()[0])
return out
def tag_commit_message(self, tag):
"""tag 指到的那顆 commit 的完整訊息(取 `定版 vX(人話)` 用)。"""
if self.fx is not None:
for lines in (self.fx.get("commits") or {}).values():
for line in lines:
if "定版" in line and tag.lstrip("v") in line:
return line
return ""
t = self._get("tags/%s" % tag)
sha = ((t or {}).get("commit") or {}).get("sha")
if not sha:
return ""
c = self._get("git/commits/%s" % sha) or {}
return ((c.get("commit") or {}).get("message") or "")
# ── 判準 ─────────────────────────────────────────────────────────────
def latest_release_before(self, ver, releases=None):
rels = releases if releases is not None else self.releases()
older = [t for t in rels if vtuple(t) < vtuple(ver)]
return max(older, key=vtuple) if older else None
def gaps(ver, tags, releases, dingban=True):
"""某一版缺哪幾站 → [(key, label, fix_template)],按運送順序。空 list = 都在。"""
t = tagname(ver)
present = {"dingban": dingban, "tag": t in tags, "release": t in releases}
return [(k, label, fix) for k, label, fix in STATIONS if not present[k]]
def dingban_title(message, ver):
"""從 `定版 vX.Y.Z(一句人話)` 抓括號那句——leo 既有 release 的命名慣例。"""
m = re.search(r"定版\s+v?%s[(]([^)]+)[)]" % re.escape(ver.lstrip("v")), message or "")
return m.group(1).strip() if m else None
+110 -17
View File
@@ -1,7 +1,13 @@
#!/usr/bin/env bash #!/usr/bin/env bash
# 管什麼: 一條派工線要在「共用的工作目錄」裡切分支時擋下來,叫它去開一份自己的 worktree。 # 管什麼: 一條派工線要在「共用的工作目錄」裡切分支時擋下來,叫它去開一份自己的 worktree——開在 repo **裡面**`.worktrees/`),不開在旁邊;同一支閘在那條線收工那一刻(PostToolUse Agent|Task)把分身收掉:分支推了就 remove,沒推就點名分支與路徑,不靜默留著
# 為什麼: 2026-08-29 inkstone/ISEP#109 comment 5391——每個 repo 只有一份工作目錄,所有線共用。#163 切到自己的分支、交回時沒切回來,總管後來在同一個目錄跑 ship.mjs,讀到的是別人留下的 HEAD。票號說得出「這是哪個任務」,沒有任何東西說得出「這個目錄現在是誰留下的狀態」。 # 為什麼: 2026-08-29 inkstone/ISEP#109 comment 5391——每個 repo 只有一份工作目錄,所有線共用。#163 切到自己的分支、交回時沒切回來,總管後來在同一個目錄跑 ship.mjs,讀到的是別人留下的 HEAD。票號說得出「這是哪個任務」,沒有任何東西說得出「這個目錄現在是誰留下的狀態」。
# 誤觸時怎麼關: `WORKTREE_OK=1 git checkout …`(留痕,跟 NOT_MY_BRANCH_OK 同形狀) # 🔴 2026-09-07 inkstone/ISEP#147:第一版教工人「開在 repo 旁邊、收工 worktree remove」,而 remove 那一步只寫在閘訊息裡、沒有任何機制驗 ⇒ 每個工人留一份,leo 在 Finder 看到 `ISEP-wt-117``ISEP-wt115``InkStoneCo-wt-112``course_gen-ticket-3-notes`…一排同頭不同尾的分身。leo:「一個 repo 只看得到一個資料夾」「禁止這樣產出一大堆資料夾」。規則在文字裡不在機器上——所以現在兩端都在機器上:開在裡面(Finder 看不到),收在 PostToolUse(忘了也會被收)。工具=scripts/worktreeopenclosesweep 同一份「推了沒」判準);規約=docs/governance/worktree-placement.md
# 誤觸時怎麼關: `WORKTREE_OK=1 git checkout …`——認的是**指令字串裡**這個字面前綴(留痕就在指令歷史上)。
# 🔴 2026-09-07inkstone/ISEP#109 → comment 6587):舊版讀的是 hook 自己的環境變數 `$WORKTREE_OK`
# 而 PreToolUse hook 跟指令不是同一個行程——指令前綴的賦值到不了它 ⇒ 閘印出來的出路在 Claude Code
# 底下永遠走不通(總管三次照貼三次被擋)。現在兩種都認:環境變數(本機 shell export 過)與字面前綴
# (閘訊息教的那一行)。判準是位置不是字:前綴必須掛在會移動 HEAD 的那條 git 指令上,見
# lib/checkout_target_dir.py 檔頭;測試 E 群把閘印出來的那一行原樣餵回去驗它走得通。
# #
# line-needs-own-worktree.sh — 共用工作目錄裡不准切分支(PreToolUse: Bash # line-needs-own-worktree.sh — 共用工作目錄裡不准切分支(PreToolUse: Bash
# #
@@ -26,16 +32,28 @@
# 而 08-29 出事的是子 repo`products/arcrun-rag`、`matrix/arcrun`)、動作是 `checkout`、 # 而 08-29 出事的是子 repo`products/arcrun-rag`、`matrix/arcrun`)、動作是 `checkout`、
# 而且沒有人登記過。**兩支守的不是同一件事,這支不動那支。** # 而且沒有人登記過。**兩支守的不是同一件事,這支不動那支。**
# #
# ── worktree 開在哪:開在 repo 的旁邊,不要開在 /tmp2026-08-29 實測)────── # ── worktree 開在哪:repo **裡面**的 `.worktrees/`,不在旁邊、不在 /tmp ─────────
# /tmp2026-08-29 實測):
# $ git -C products/arcrun-rag worktree list # $ git -C products/arcrun-rag worktree list
# /private/tmp/.../scratchpad/wt-180 … prunable ← 目錄被系統清掉了 # /private/tmp/.../scratchpad/wt-180 … prunable ← 目錄被系統清掉了
# /private/tmp/.../scratchpad/wt164 … prunable ← 同上
# /private/tmp/wt167src … prunable # /private/tmp/wt167src … prunable
# products/arcrun-rag-wt88 … 完好
# products/arcrun-rag-wt104ingest … 完好
# ISEP 同一天有 **12 筆 prunable**,全部在 /private/tmp 底下。 # ISEP 同一天有 **12 筆 prunable**,全部在 /private/tmp 底下。
# ⇒ 開在 `/tmp` 的會被系統清掉,而**登記簿還留著** ⇒ 登記簿說謊。 # ⇒ 開在 `/tmp` 的會被系統清掉,而**登記簿還留著** ⇒ 登記簿說謊。
# 開在 repo 旁邊的那幾份,一份都沒 # 旁邊(2026-09-07 inkstone/ISEP#147 實錄):一份都沒掉——**也一份都沒收**
# tech_projects/ 底下躺著 ISEP-wt-122ship、ISEP-wt-117、ISEP-wt115、InkStoneCo-wt-112…
# leo 在 Finder 看到的是「一個 repo 長出一排同頭不同尾的分身」。
# ⇒ 住 `<repo>/.worktrees/<票 repo>-<票號>`Finder 看不到(點開頭)、`git status` 看不到
# `scripts/worktree open` 寫進 `.git/info/exclude`,不動被追蹤的檔)、
# `git worktree list` 照樣列得到(收工那一半靠它找)。
#
# ── 收工那一半:同一支閘掛在 PostToolUse(Agent|Task)inkstone/ISEP#147)───────
# 派工單裡的 `【工單】owner/repo#N` 就是分身的名字(`.worktrees/<repo>-<N>`),
# 跟 baton-handback-guard.shissue-status-autoflip.sh 同一個位置、同一種抓法。
# 線收工那一刻:`scripts/worktree close <票>` ——
# 推了且乾淨 ⇒ removeprune,安靜。
# 沒推/有未 commit/問不到遠端 ⇒ exit 2 點名分支與路徑,並印推的指令。**不 force、不刪。**
# 為什麼不掛 SubagentStop:那裡拿不到票號(見 baton-handback-guard.sh 檔頭)。
# 為什麼不另開一支閘:教你開的和替你收的是同一件事的兩半,拆成兩支就又是「規則在兩個地方」。
# #
# ── 順手把說謊的登記清掉(驗收條件 7:prune 是收工動作,不是偶爾整理)─────── # ── 順手把說謊的登記清掉(驗收條件 7:prune 是收工動作,不是偶爾整理)───────
# 擋下來的同時對那個 repo 跑一次 `git worktree prune`,並把清掉幾筆講出來。 # 擋下來的同時對那個 repo 跑一次 `git worktree prune`,並把清掉幾筆講出來。
@@ -52,11 +70,69 @@
# 然後以為自己隔離好了。**寧可漏擋,也不要給錯的下一步**(comment 5398)。 # 然後以為自己隔離好了。**寧可漏擋,也不要給錯的下一步**(comment 5398)。
set -eu set -eu
PAYLOAD=$(cat 2>/dev/null || echo '{}')
# ── 收工那一半(PostToolUse Agent|Task):先於任何環境變數判斷——這裡跑的是總管的 session ──
EVENT=$(printf '%s' "$PAYLOAD" | python3 -c '
import json, sys
try:
d = json.load(sys.stdin)
except Exception:
raise SystemExit
sys.stdout.write(str(d.get("hook_event_name") or ""))
' 2>/dev/null) || EVENT=""
if [ "${EVENT:-}" = "PostToolUse" ]; then
SPEC=$(printf '%s' "$PAYLOAD" | python3 -c '
import json, re, sys
try:
d = json.load(sys.stdin)
except Exception:
raise SystemExit
if d.get("tool_name") not in ("Agent", "Task"):
raise SystemExit
p = (d.get("tool_input") or {}).get("prompt") or ""
seen = []
for line in p.splitlines():
if "【工單】" not in line:
continue
for m in re.finditer(r"([A-Za-z0-9_.-]+)/([A-Za-z0-9_.-]+)#(\d+)", line):
t = "%s/%s#%s" % m.groups()
if t not in seen:
seen.append(t)
sys.stdout.write(" ".join(seen))
' 2>/dev/null) || SPEC=""
[ -n "${SPEC:-}" ] || exit 0
WT_TOOL="$(cd "$(dirname "$0")/.." && pwd)/scripts/worktree"
if [ ! -f "$WT_TOOL" ]; then
echo "⚠️ line-needs-own-worktree:找不到 scripts/worktree,這條線的分身這一次沒有收。" >&2
exit 0
fi
ROOT="${CLAUDE_PROJECT_DIR:-$PWD}"
# 掃哪裡:專案根、它的上一層(Mactech_projects/ 底下 ISEP 與 InkStoneCo 是兄弟)、
# 雲端薄殼底下的真身(子 repo 在 InkStoneCo/matrix|products|polaris 底下,工具自己會往下找一層)。
SCAN="--scan $ROOT --scan $(dirname "$ROOT")"
[ -d "$ROOT/InkStoneCo" ] && SCAN="$SCAN --scan $ROOT/InkStoneCo"
RC=0
for T in $SPEC; do
rc=0
# shellcheck disable=SC2086
OUT=$(python3 "$WT_TOOL" close "$T" $SCAN --quiet 2>&1 >/dev/null) || rc=$?
[ -n "${OUT:-}" ] && printf '%s\n' "$OUT" | sed 's/^/ /' >&2
[ "$rc" -eq 2 ] && RC=2
done
[ "$RC" -eq 2 ] || exit 0
cat >&2 <<'EOF'
🌳 這條線收工了,但它的分身還留在 repo 裡(上面點名的那幾份)。
不會靜默留著、也不會替它刪沒推的東西——推了再收,或確認作廢後自己刪。
規約:docs/governance/worktree-placement.mdinkstone/ISEP#147
EOF
exit 2
fi
[ "${WORKTREE_OK:-}" = "1" ] && exit 0 [ "${WORKTREE_OK:-}" = "1" ] && exit 0
[ "${CLAUDE_CODE_CHILD_SESSION:-}" = "1" ] || exit 0 # 總管在自己的目錄裡,不管 [ "${CLAUDE_CODE_CHILD_SESSION:-}" = "1" ] || exit 0 # 總管在自己的目錄裡,不管
PAYLOAD=$(cat 2>/dev/null || echo '{}')
# 這條指令會動到哪個目錄的 HEAD——**不是問「hook 站在哪」**。 # 這條指令會動到哪個目錄的 HEAD——**不是問「hook 站在哪」**。
# 2026-08-29 實測(inkstone/ISEP#109 → comment 5398):`cd <別的 repo> && git checkout` # 2026-08-29 實測(inkstone/ISEP#109 → comment 5398):`cd <別的 repo> && git checkout`
# 舊版拿 payload 的 cwd 當答案,於是擋對了、卻**指著另一個 repo 叫人去開 worktree**。 # 舊版拿 payload 的 cwd 當答案,於是擋對了、卻**指著另一個 repo 叫人去開 worktree**。
@@ -74,6 +150,13 @@ sys.stdout.write((ti.get("command") or "") if isinstance(ti, dict) else "")
' 2>/dev/null) || exit 0 ' 2>/dev/null) || exit 0
[ -n "${CMD:-}" ] || exit 0 [ -n "${CMD:-}" ] || exit 0
# heredoc 的 body 是資料不是指令(inkstone/ISEP#125 缺陷 DE2026-09-02 兩次實地命中):
# 用 heredoc 寫一份「內含 `cd <目錄> && git checkout X` 示範」的說明文件,整條指令沒有任何
# git 操作,卻被當成在切分支擋下——被擋的是「寫文件」這個動作。跟 github-contact-guard 一樣
# 先把 body 剝掉再解析;剝不動就用原字串(fail-open 的是「這支 helper 有沒有跑」,不是判準)。
CMD=$(printf '%s' "$CMD" | python3 "$(dirname "$0")/lib/strip_heredoc.py" 2>/dev/null || printf '%s' "$CMD")
[ -n "${CMD:-}" ] || exit 0
CWD=$(printf '%s' "$PAYLOAD" | python3 -c ' CWD=$(printf '%s' "$PAYLOAD" | python3 -c '
import json, sys import json, sys
try: try:
@@ -96,6 +179,11 @@ EXPR=$(printf '%s' "$CMD" | python3 "$RESOLVER" 2>/dev/null) || exit 0
[ -n "${EXPR:-}" ] || exit 0 # 沒有會移動 HEAD 的 checkout/switch [ -n "${EXPR:-}" ] || exit 0 # 沒有會移動 HEAD 的 checkout/switch
[ "$EXPR" = "?" ] && exit 0 # 目錄解不出來(cd $VAR / cd -)⇒ 不猜,見該檔檔頭 [ "$EXPR" = "?" ] && exit 0 # 目錄解不出來(cd $VAR / cd -)⇒ 不猜,見該檔檔頭
# 出路:那條 checkout 自己帶著 `WORKTREE_OK=1` 前綴 ⇒ 放行(comment 6587)。
# 看的是指令字串裡的位置,不是 hook 的環境——hook 的環境裡永遠不會有它。
ESC=$(printf '%s' "$CMD" | python3 "$RESOLVER" --escape WORKTREE_OK=1 2>/dev/null) || ESC=""
[ "${ESC:-}" = "1" ] && exit 0
TARGET=$(cd "$CWD" 2>/dev/null && cd "$EXPR" 2>/dev/null && pwd) || exit 0 TARGET=$(cd "$CWD" 2>/dev/null && cd "$EXPR" 2>/dev/null && pwd) || exit 0
[ -n "${TARGET:-}" ] || exit 0 [ -n "${TARGET:-}" ] || exit 0
@@ -108,6 +196,8 @@ ABS() { (cd "$TARGET" 2>/dev/null && cd "$1" 2>/dev/null && pwd) || printf '%s'
TOP=$(git -C "$TARGET" rev-parse --show-toplevel 2>/dev/null) || exit 0 TOP=$(git -C "$TARGET" rev-parse --show-toplevel 2>/dev/null) || exit 0
NAME=$(basename "$TOP") NAME=$(basename "$TOP")
PARENT=$(dirname "$TOP") PARENT=$(dirname "$TOP")
# 印給人複製的指令用工具的絕對路徑——相對路徑會對貼的人的 cwd 解析(mistakes.md「出路跑不動」)
WT_TOOL="$(cd "$(dirname "$0")/.." && pwd)/scripts/worktree"
NOW=$(git -C "$TOP" rev-parse --abbrev-ref HEAD 2>/dev/null || echo '?') NOW=$(git -C "$TOP" rev-parse --abbrev-ref HEAD 2>/dev/null || echo '?')
# 驗收條件 7:說謊的登記順手清掉(只刪目錄已經不存在的那些) # 驗收條件 7:說謊的登記順手清掉(只刪目錄已經不存在的那些)
@@ -130,17 +220,20 @@ $PRUNED
🔴 票號說得出「這是哪個任務」,**沒有任何東西說得出「這個目錄現在是誰留下的狀態」**。 🔴 票號說得出「這是哪個任務」,**沒有任何東西說得出「這個目錄現在是誰留下的狀態」**。
(那次沒出錯貨——是文案契約閘擋下來的。閘有效,但那是最後一道。) (那次沒出錯貨——是文案契約閘擋下來的。閘有效,但那是最後一道。)
【現在怎麼做】開一份自己的,然後在裡面做事: 【現在怎麼做】開一份自己的——住在 repo **裡面**的 .worktrees/,然後在裡面做事:
git -C $TOP worktree add $PARENT/$NAME-wt-<票號> -b <你的分支> python3 $WT_TOOL open <owner/repo#票號> --repo $TOP -b <你的分支>
cd $PARENT/$NAME-wt-<票號> cd $TOP/.worktrees/<票的 repo 名>-<票號>
🔴 **不要開在 /tmp 底下** 同一天實測:$NAME 的登記簿裡指向 /private/tmp 的 🔴 **不要開在 /tmp 底下**08-29 實測:$NAME 指向 /private/tmp 的登記全部 prunable),
那幾筆全部 prunable(目錄被系統清掉、登記還在),而開在 repo 旁邊的一份都沒掉。 **也不要開在 repo 旁邊**09-07 實錄:$PARENT/ 底下躺了一排 $NAME-wt-…,
leo 在 Finder 看到「一個 repo 一排分身」——inkstone/ISEP#147,禁止)。
裡面的那份 Finder 看不到、git status 看不到,git worktree list 找得到。
收工時: 收工時(推了會收掉;沒推會點名,不會靜默留著;你忘了,線收工那一刻這支閘也會替你收)
git -C $TOP worktree remove $PARENT/$NAME-wt-<票號> python3 $WT_TOOL close <owner/repo#票號> --repo $TOP
git -C $TOP worktree prune
規約:docs/governance/worktree-placement.md
【真的要在共用目錄裡切(接手、緊急止血)】 【真的要在共用目錄裡切(接手、緊急止血)】
WORKTREE_OK=1 git -C $TOP checkout <分支> WORKTREE_OK=1 git -C $TOP checkout <分支>
+2 -1
View File
@@ -315,12 +315,13 @@ fi
# #
# 整套測試環境=下列任一出現在命令裡: # 整套測試環境=下列任一出現在命令裡:
# · `youlin-hsieh-dev` ── 帳號名(D37 定的 stage 帳號) # · `youlin-hsieh-dev` ── 帳號名(D37 定的 stage 帳號)
# · `arcrun-yuga3bse` ── 該帳號 09-02 重裝後的 workers.dev 子網域(inkstone/ISEP#130;舊名 DNS 已死)
# · `1129efd7df2e8899d537e9c8fbabb6cb` ── 該帳號 ID(用 env 指過去時只有它看得見) # · `1129efd7df2e8899d537e9c8fbabb6cb` ── 該帳號 ID(用 env 指過去時只有它看得見)
# · `_YOULIN_` ── 憑證變數名(如 `CLOUDFLARE_API_TOKEN_YOULIN_CC_USE` # · `_YOULIN_` ── 憑證變數名(如 `CLOUDFLARE_API_TOKEN_YOULIN_CC_USE`
# · `X-Arcrun-API-Key: youlin` ── 打該實例 API 時的身分標頭 # · `X-Arcrun-API-Key: youlin` ── 打該實例 API 時的身分標頭
case "$CMD" in case "$CMD" in
*staging*|*-staging*|*"--env stage"*|*"--env=stage"*|*stage.*) exit 0 ;; *staging*|*-staging*|*"--env stage"*|*"--env=stage"*|*stage.*) exit 0 ;;
*youlin-hsieh-dev*|*1129efd7df2e8899d537e9c8fbabb6cb*|*_YOULIN_*|*"X-Arcrun-API-Key: youlin"*) exit 0 ;; *youlin-hsieh-dev*|*arcrun-yuga3bse*|*1129efd7df2e8899d537e9c8fbabb6cb*|*_YOULIN_*|*"X-Arcrun-API-Key: youlin"*) exit 0 ;;
esac esac
# 🔴 2026-08-12 leo 拍板「加閘」:**geek6688(出貨機)是明文授權「總管可以直接動」的那一台。** # 🔴 2026-08-12 leo 拍板「加閘」:**geek6688(出貨機)是明文授權「總管可以直接動」的那一台。**
+36 -20
View File
@@ -18,8 +18,10 @@
# #
# 本閘從頭到尾**不讀派工單的任何一個字義**。它只做兩個查表: # 本閘從頭到尾**不讀派工單的任何一個字義**。它只做兩個查表:
# ① 派工單的【工單】欄位是哪一張票(`hooks/lib/dispatch_parse.py` 解結構,不判語意) # ① 派工單的【工單】欄位是哪一張票(`hooks/lib/dispatch_parse.py` 解結構,不判語意)
# ② 那張票所屬的 milestone 標題,等不等於被標定的主線標題(字串相等,不是模糊比對) # ② 那張票在不在主線上:掛在錨那一個 milestone(同 repo、同 id),或有任何一張主線成員
# 措辭怎麼寫都不影響判決;改的只有「這張票掛在哪」這個 Gitea 上的事實。 # 把它當相依(`/blocks`)。判準是 milestone id 與相依邊——**不是標題**:
# 別 repo 裡同名的里程碑不算(leo 2026-09-07inkstone/ISEP#133)。
# 措辭怎麼寫都不影響判決;改的只有「這張票掛在哪、誰指著它」這兩個 Gitea 上的事實。
# #
# ── 誤攔的出口全部先關掉(誤攔比漏擋更該修)────────────────────────── # ── 誤攔的出口全部先關掉(誤攔比漏擋更該修)──────────────────────────
# · **沒有主線 ⇒ 一律放行**(ISEP#82 驗收第 4 條:沒有主線不能整組壞掉) # · **沒有主線 ⇒ 一律放行**(ISEP#82 驗收第 4 條:沒有主線不能整組壞掉)
@@ -92,16 +94,20 @@ for ref in wanted:
if v is None: if v is None:
unknown.append(ref) unknown.append(ref)
# ② 快取查不到的,去問那張票掛在哪。問不到 ⇒ 放行 # ② 快取查不到的,去問兩件事實:那張票掛在哪個 milestone、誰把它當相依(inkstone/ISEP#133
# 兩件都到手才敢說「不在」;問不到任何一件 ⇒ 放行。
if unknown: if unknown:
fx = ML.fixture_titles() fx = ML.fixture_titles()
if fx is not None: # 測試把外界定住(見 mainline.fixture_titles if fx is not None: # 測試把外界定住(見 mainline.fixture_lookup
learned = [r for r in unknown verdicts = {}
if ML.norm(fx.get(r, "")) == ML.norm(ms.get("title"))] for r in unknown:
if learned: got = ML.fixture_lookup(fx, r)
if got is not None:
verdicts[r] = ML.belongs(r, ms, ticket_milestone=got[0], blocks=got[1])
if any(v is True for v in verdicts.values()):
print("SKIP:on-mainline-fixture"); raise SystemExit print("SKIP:on-mainline-fixture"); raise SystemExit
if not any(r in fx for r in unknown): if not verdicts or any(v is None for v in verdicts.values()):
bail("unreachable") # fixture 沒收錄 ⇒ 等同問不到 bail("unreachable") # fixture 沒收錄/只知一半 ⇒ 等同問不到
else: else:
try: try:
T = load("isep_ticket", os.path.join(HERE, "..", "scripts", "ticket")) T = load("isep_ticket", os.path.join(HERE, "..", "scripts", "ticket"))
@@ -111,28 +117,37 @@ if unknown:
# 那不是 Exception 的子類。只接 Exception 的話,這支會整個死掉而不是放行。 # 那不是 Exception 的子類。只接 Exception 的話,這支會整個死掉而不是放行。
except BaseException: except BaseException:
bail("no-token") # 讀不到 ≠ 不屬於 bail("no-token") # 讀不到 ≠ 不屬於
def get(path):
req = urllib.request.Request("%s/api/v1%s" % (host, path),
headers={"Authorization": "token %s" % tok})
return json.load(urllib.request.urlopen(req, timeout=6))
reached = False reached = False
learned = [] learned = []
undecided = False
for ref in unknown: for ref in unknown:
parts = ML.split_ref(ref)
if not parts:
continue
try: try:
owner, rest = ref.split("/", 1) it = get("/repos/%s/%s/issues/%d" % parts)
repo, num = rest.split("#", 1)
req = urllib.request.Request(
"%s/api/v1/repos/%s/%s/issues/%s" % (host, owner, repo, num),
headers={"Authorization": "token %s" % tok})
it = json.load(urllib.request.urlopen(req, timeout=6))
reached = True reached = True
except Exception: except Exception:
continue continue
title = ((it or {}).get("milestone") or {}).get("title") or "" try:
if ML.norm(title) == ML.norm(ms.get("title")): blocks = [x for x in (ML.issue_ref(b) for b in get("/repos/%s/%s/issues/%d/blocks?limit=100" % parts)) if x]
except Exception:
blocks = None # 讀不到「誰把它當相依」⇒ 這一張判不出來
v = ML.belongs(ref, ms, ticket_milestone=(it or {}).get("milestone") or {}, blocks=blocks)
if v is True:
learned.append(ref) learned.append(ref)
elif v is None:
undecided = True
if learned: if learned:
ms["members"] = sorted(set(ms.get("members") or []) | set(learned)) ms["members"] = sorted(set(ms.get("members") or []) | set(learned))
ML.save(ms) ML.save(ms)
print("SKIP:on-mainline-fresh"); raise SystemExit print("SKIP:on-mainline-fresh"); raise SystemExit
if not reached: if not reached or undecided:
bail("unreachable") # 一張都問不到 ⇒ 放行 bail("unreachable") # 問不到/只知一半 ⇒ 放行
# ③ 確定都不在主線上 —— 同一組票只擋一次 # ③ 確定都不在主線上 —— 同一組票只擋一次
import hashlib import hashlib
@@ -161,7 +176,8 @@ case "$VERDICT" in
printf ' 這次要派的:%s\n\n' "$TICKETS" printf ' 這次要派的:%s\n\n' "$TICKETS"
printf '**先說是哪一種,再繼續**——兩種都可能是對的,錯的是默默做完:\n\n' printf '**先說是哪一種,再繼續**——兩種都可能是對的,錯的是默默做完:\n\n'
printf ' ① 補收 —— 它本來就該在主線上,只是沒掛上去\n' printf ' ① 補收 —— 它本來就該在主線上,只是沒掛上去\n'
printf ' `scripts/mainline adopt %s` 然後重送\n\n' "$FIRST" printf ' `scripts/mainline adopt %s` 然後重送\n' "$FIRST"
printf ' (別 repo 的票會成為 hub 票的相依;**不要**去那個 repo 開同名里程碑)\n\n'
printf ' ② 跳線 —— 真的是插件事(leo 臨時交辦、擋路的地雷…)\n' printf ' ② 跳線 —— 真的是插件事(leo 臨時交辦、擋路的地雷…)\n'
printf ' 直接重送即可(**同一張票只擋一次**),並在回覆講一句為什麼現在要岔開主線\n\n' printf ' 直接重送即可(**同一張票只擋一次**),並在回覆講一句為什麼現在要岔開主線\n\n'
printf '為什麼要問:leo 2026-08-27「今天……分心」。分心的前提是有一條主線,\n' printf '為什麼要問:leo 2026-08-27「今天……分心」。分心的前提是有一條主線,\n'
+3
View File
@@ -227,6 +227,9 @@ fi
case "$CMD" in case "$CMD" in
*staging*|*-staging*|*"--env stage"*|*"--env=stage"*|*stage.*|*"-staging"*) exit 0 ;; *staging*|*-staging*|*"--env stage"*|*"--env=stage"*|*stage.*|*"-staging"*) exit 0 ;;
*youlin-hsieh-dev*|*"X-Arcrun-API-Key: youlin"*) exit 0 ;; *youlin-hsieh-dev*|*"X-Arcrun-API-Key: youlin"*) exit 0 ;;
# 🔴 2026-09-02 youlin 重裝後 workers.dev 子網域換成 `arcrun-yuga3bse`inkstone/ISEP#130):
# 舊名 DNS 已不存在。認不得新名 ⇒ 打 stage 做實驗又會被當成 prod 擋——同一個誤攔第二次。
*arcrun-yuga3bse*) exit 0 ;;
esac esac
+1
View File
@@ -15,6 +15,7 @@ HOOK="${1:-$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)/countdown-guard.sh}"
TMP=$(mktemp -d) TMP=$(mktemp -d)
trap 'rm -rf "$TMP"' EXIT trap 'rm -rf "$TMP"' EXIT
export ISEP_COUNTDOWN_STATE_DIR="$TMP/state" export ISEP_COUNTDOWN_STATE_DIR="$TMP/state"
export ISEP_MAINLINE_REPO_FILE=none # 把 repo 那份鏡像拿掉(inkstone/ISEP#130):這支測的是家目錄那份
mkdir -p "$ISEP_COUNTDOWN_STATE_DIR" mkdir -p "$ISEP_COUNTDOWN_STATE_DIR"
PASS=0; FAIL=0 PASS=0; FAIL=0
+38
View File
@@ -24,6 +24,7 @@ mkplugin() {
> "$d/hooks/hooks.json" > "$d/hooks/hooks.json"
cp "$HOOK" "$d/hooks/$(basename "$HOOK")" cp "$HOOK" "$d/hooks/$(basename "$HOOK")"
cp "$REAL_HOOKS/lib/beacon_report.py" "$d/hooks/lib/beacon_report.py" cp "$REAL_HOOKS/lib/beacon_report.py" "$d/hooks/lib/beacon_report.py"
cp "$REAL_HOOKS/lib/release_chain.py" "$d/hooks/lib/release_chain.py"
printf '#!/bin/sh\necho real\n' > "$d/scripts/ticket" printf '#!/bin/sh\necho real\n' > "$d/scripts/ticket"
# inkstone/ISEP#122:會自動載入的東西(skillcommandagent)也要造得出來 # inkstone/ISEP#122:會自動載入的東西(skillcommandagent)也要造得出來
mkdir -p "$d/skills/demo" "$d/commands" "$d/agents" "$d/docs" mkdir -p "$d/skills/demo" "$d/commands" "$d/agents" "$d/docs"
@@ -190,6 +191,43 @@ out=$(run "$P2" "$JS")
check "㉖ ②b 有報告時,那行綠色信標仍在且 JSON 合法" "$out" \ check "㉖ ②b 有報告時,那行綠色信標仍在且 JSON 合法" "$out" \
"🟢 ISEP v1.0.0 已載入" "!__BADJSON__" "🟢 ISEP v1.0.0 已載入" "!__BADJSON__"
echo "── ④打了 tag 卻沒 releaseinkstone/ISEP#67 → 6574)──────────────────"
# 🔴 這一組守的是 09-07 那件:v0.23.0v0.24.0 tag 都推了、Releases 頁停在 v0.22.0
# 交棒給 leo 的測試位置打開是一頁空 tag。開場要說「缺哪一站+怎麼補」,都在時安靜。
P4=$(mkplugin 0.24.0); printf '#!/usr/bin/env python3\n' > "$P4/scripts/release-ship"
FX4="$TMP/chain-gap.json"
printf '{"tags":["v0.24.0","v0.23.0"],"releases":["v0.23.0"]}\n' > "$FX4"
out=$(ISEP_BEACON_CHAIN_FIXTURE="$FX4" run "$P4" "$J")
check "㉗ 最新 tag v0.24.0 沒有 release → 一行說缺哪一站+怎麼補(正本絕對路徑)" "$out" \
"v0.24.0 送到一半" "缺 releaseGitea" "python3 $P4/scripts/release-ship v0.24.0" "inkstone/ISEP#67"
check "㉘ 信標那一行仍在、JSON 合法" "$out" "🟢 ISEP v0.24.0 已載入" "!__BADJSON__"
FX4b="$TMP/chain-ok.json"
printf '{"tags":["v0.24.0","v0.23.0"],"releases":["v0.24.0","v0.23.0"]}\n' > "$FX4b"
out=$(ISEP_BEACON_CHAIN_FIXTURE="$FX4b" run "$P4" "$J")
check "㉙ tag 與 release 都在 → 一個字都不說(天天念會被學會忽略)" "$out" "!送到一半" "!缺 release"
out=$(run "$P4" "$J")
check "㉚ 問不到收貨端(沒網路、沒 fixture)→ 閉嘴,不猜" "$out" "!送到一半" "🟢 ISEP v0.24.0 已載入"
out=$(ISEP_FAKE_MAIN_VERSION=0.25.0 ISEP_BEACON_CHAIN_FIXTURE="$FX4b" run "$P4" "$J")
check "㉛ main 定版到 0.25.0、Gitea 最新 tag 還是 v0.24.0 → 說缺 tag 站+push tag 的補法" "$out" \
"v0.25.0 送到一半" "缺 tagGitea" "git push origin v0.25.0"
P4o=$(mkplugin 0.21.0) # 載入的這一份還沒有 scripts/release-ship(舊版)
out=$(ISEP_BEACON_CHAIN_FIXTURE="$FX4" run "$P4o" "$J")
check "㉜ 載入的這一份還沒有 release-ship → 補法先教 plugin update,不印一條不存在的路徑" "$out" \
"v0.24.0 送到一半" "claude plugin update isep@inkstone" "!python3 $P4o/scripts/release-ship"
# 只快取「都在」:缺件那次不留快取,補完的下一個 session 立刻安靜;都在那次留快取
rm -f "$TMP"/.isep-chain-ok-*
out=$(ISEP_BEACON_CHAIN_FIXTURE="$FX4" run "$P4" "$J")
[ ! -e "$TMP/.isep-chain-ok-v0.24.0" ] && r1=1 || r1=0
out=$(ISEP_BEACON_CHAIN_FIXTURE="$FX4b" run "$P4" "$J")
[ -e "$TMP/.isep-chain-ok-v0.24.0" ] && r2=1 || r2=0
N=$((N+1)); if [ "$r1$r2" = "11" ]; then printf ' ✅ ㉝ 缺件不快取、都在才快取(補完下一個 session 就安靜)\n'; PASS=$((PASS+1))
else printf ' ❌ ㉝ 快取方向錯了(缺件留了快取=%s/都在沒留=%s)\n' "$((1-r1))" "$((1-r2))"; FAIL=$((FAIL+1)); fi
echo echo
printf '通過 %s 條,失敗 %s 條(共 %s 條)\n' "$PASS" "$FAIL" "$N" printf '通過 %s 條,失敗 %s 條(共 %s 條)\n' "$PASS" "$FAIL" "$N"
[ "$FAIL" = 0 ] || exit 1 [ "$FAIL" = 0 ] || exit 1
+78
View File
@@ -0,0 +1,78 @@
#!/usr/bin/env bash
# leo21c-write-guard.sh 的迴歸測試(inkstone/ISEP#130
#
# ── 這支在守什麼 ──────────────────────────────────────────────────────
# 閘的判準是「**讀可以,寫不行**」(leo 2026-08-20leo21c 是他本人在用的知識庫)。
# 2026-09-04 雲端 Routine 的 run log**讀 notify_leo 的定義被擋** ——
# 讀都讀不到,雲端就什麼都拿不到(inkstone/ISEP#130 開票的第一件)。
#
# 這支之前**沒有任何測試**,所以「讀會不會被誤攔」從來沒被驗過。
# 下面的測資是 Routine 文件(cloud-worker.mdprogress-guard.md)裡**真的會下的那幾條指令**,
# 不是想像出來的例子。
#
# 🔴 三個方向都要驗,缺一個就是假綠:
# A 讀 ⇒ 放行(含 `tr -d``cut -d=` 這種唯讀的 -d,那正是 09-04 被擋的形狀)
# B 寫 ⇒ 擋(心跳 POST/PATCH 收件匣/部署端點/別的 trigger)
# C 閘印出來的「改法」指的是**現役**的 youlin 網址,不是 09-02 已死的舊名
#
# 這支閘不寫任何檔案,直接跑真跡即可;全程離線。
# 用法:bash hooks/tests/leo21c-write-guard.test.sh
set -u
HERE=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)
HOOK="$HERE/../leo21c-write-guard.sh"
PASS=0; FAIL=0
mk(){ python3 -c "import json,sys;print(json.dumps({'tool_name':'Bash','tool_input':{'command':sys.argv[1]}}))" "$1"; }
t(){ # t <期望 pass|block> <說明> <指令>
LAST_ERR=$(mk "$3" | bash "$HOOK" 2>&1 >/dev/null); rc=$?
got=$([ "$rc" -eq 2 ] && echo block || echo pass)
if [ "$got" = "$1" ]; then echo "$2"; PASS=$((PASS+1))
else echo "$2 —— 期望 $1,實得 $gotrc=$rc"; FAIL=$((FAIL+1)); fi
}
L='https://arcrun-cypher-executor.leo21c.workers.dev'
K='-H "X-Arcrun-API-Key: leo"'
D='-d'
echo "── A. 讀 ⇒ 放行(雲端 Routine 真的會下的形狀)──"
t pass "① 讀收件匣(progress-guard.md 步驟 0 原句)" "curl -s \"$L/kbdb/entries?entry_type=inbox&limit=20\" $K"
t pass "② 讀 notify_leo 定義(09-04 被擋的那一條)" "curl -s $L/webhooks/named/leo/notify_leo $K"
t pass "③ 讀 tr -d(唯讀的 -d,不是 body" "curl -s $L/workflows/notify_leo $K | tr $D '\\r'"
t pass "④ 讀 cut -d=" "NS=\$(grep ns cfg | cut ${D}= -f2); curl -s $L/kbdb/entries?limit=1 $K"
t pass "⑤ 讀 sort -d date -d" "curl -s $L/health | sort $D; date $D yesterday"
t pass "⑥ 明寫 -X GET" "curl -s -X GET $L/kbdb/entries?entry_type=dash_beat $K"
t pass "⑦ 讀心跳(progress-guard 2.6 原句)" "curl -s \"$L/kbdb/entries?entry_type=dash_beat&limit=30\" $K"
t pass "⑧ git commit 訊息提到 leo21c 與 POSTgit 寫不到那台)" "git commit -m 'fix: curl -X POST $L/kbdb/entries 會被擋'"
t pass "⑨ 修這道閘自己" "sed -i 's/a/b/' hooks/leo21c-write-guard.sh"
t pass "⑩ 打 youlin09-02 起的新子網域)POST,不是 leo21c" "curl -X POST https://arcrun-cypher-executor.arcrun-yuga3bse.workers.dev/webhooks/named $D '{}'"
t pass "⑪ 用 youlin 的 CF 帳號部署" "CLOUDFLARE_ACCOUNT_ID=1129efd7df2e8899d537e9c8fbabb6cb npx wrangler deploy"
t pass "⑫ 發一則 notify_leo(通知型 trigger,什麼都沒改;同 prod-write-guard 白名單)" "curl -s -X POST $L/webhooks/named/leo/notify_leo/trigger -H 'Content-Type: application/json' $D '{\"text\":\"[總管] hi\"}'"
echo "── B. 寫 ⇒ 擋 ──"
t block "⑬ 打心跳 POSTcloud-worker.md 步驟 0 原句——它寫進 leo 的庫)" "curl -s -X POST \"$L/kbdb/entries\" $K -H 'Content-Type: application/json' $D '{\"entry_type\":\"dash_beat\"}'"
t block "⑭ PATCH 收件匣" "curl -s -X PATCH \"$L/kbdb/entries/123\" $K $D '{\"content\":\"x\"}'"
t block "⑮ DELETE" "curl -X DELETE $L/kbdb/entries/1 $K"
t block "⑯ 只帶 -d 的隱式 POST" "curl $L/kbdb/entries $D '{}'"
t block "⑰ --data-urlencode" "curl $L/kbdb/entries --data-urlencode text=hi"
t block "⑱ --request PUT" "curl --request PUT $L/kbdb/entries/1 $D '{}'"
t block "⑲ 別的工作流 triggership_refresh_cdn 會動線上狀態)" "curl -X POST $L/webhooks/named/leo/ship_refresh_cdn/trigger $D '{}'"
t block "⑳ 部署端點(無名字的 named webhook" "curl -X POST $L/webhooks/named $D @def.yaml"
t block "㉑ notify_leo 旁邊夾一個部署端點" "curl -X POST $L/webhooks/named/leo/notify_leo/trigger $D '{}' && curl -X POST $L/webhooks/named $D @x"
t block "㉒ 寫 + tr -d(剪掉唯讀 -d 之後仍該擋)" "cat f | tr $D '\\r' | curl -X POST $L/kbdb/entries $D @-"
t block "㉓ 用 leo21c 的 CF 帳號部署" "CLOUDFLARE_ACCOUNT_ID=51a01bfa2665bd7bc3fd080dc40cf3e1 npx wrangler deploy"
echo "── C. 擋下時印的改法要指到活著的 youlin ──"
mk "curl -X POST $L/kbdb/entries $D '{}'" | bash "$HOOK" 2>"$HERE/.leo21c-msg.$$" >/dev/null
MSG=$(cat "$HERE/.leo21c-msg.$$"); rm -f "$HERE/.leo21c-msg.$$"
if printf '%s' "$MSG" | grep -q 'arcrun-cypher-executor.arcrun-yuga3bse.workers.dev'; then
echo " ✅ ㉔ 改法段印的是現役子網域 arcrun-yuga3bse"; PASS=$((PASS+1))
else echo " ❌ ㉔ 改法段沒有現役子網域 arcrun-yuga3bse"; FAIL=$((FAIL+1)); fi
if printf '%s' "$MSG" | grep -q 'cypher : https://arcrun-cypher-executor.youlin-hsieh-dev'; then
echo " ❌ ㉕ 改法段還教人打 09-02 已死的 youlin-hsieh-dev"; FAIL=$((FAIL+1))
else echo " ✅ ㉕ 改法段不再把死的舊名當網址教人"; PASS=$((PASS+1)); fi
if printf '%s' "$MSG" | grep -q '讀可以,寫不行'; then
echo " ✅ ㉖ 訊息講得出判準(讀可以,寫不行)"; PASS=$((PASS+1))
else echo " ❌ ㉖ 訊息沒講判準"; FAIL=$((FAIL+1)); fi
echo
echo "通過 $PASS 條,失敗 $FAIL"
[ "$FAIL" -eq 0 ]
+169 -2
View File
@@ -32,6 +32,10 @@ mkdir -p "$REPO"
git -C "$REPO" init -q -b main git -C "$REPO" init -q -b main
git -C "$REPO" config user.email t@t; git -C "$REPO" config user.name t git -C "$REPO" config user.email t@t; git -C "$REPO" config user.name t
echo hi > "$REPO/a.txt"; git -C "$REPO" add -A; git -C "$REPO" commit -qm init echo hi > "$REPO/a.txt"; git -C "$REPO" add -A; git -C "$REPO" commit -qm init
# G/H 群要驗「推了沒」——給共用 repo 一顆真的(本機 bare)遠端。離線,不打網路。
git init -q --bare "$ROOT/remote.git"
git -C "$REPO" remote add origin "$ROOT/remote.git"
git -C "$REPO" push -q origin main 2>/dev/null
git -C "$REPO" worktree add -q "$ROOT/own-wt" -b mine git -C "$REPO" worktree add -q "$ROOT/own-wt" -b mine
OWN="$ROOT/own-wt" OWN="$ROOT/own-wt"
PLAIN="$ROOT/not-a-repo"; mkdir -p "$PLAIN" PLAIN="$ROOT/not-a-repo"; mkdir -p "$PLAIN"
@@ -116,11 +120,13 @@ echo "── C 群:訊息與副作用 ──"
t 2 "㉔ 擋下來(下面幾條檢查這一次的訊息)" "git checkout -b feat/msg" t 2 "㉔ 擋下來(下面幾條檢查這一次的訊息)" "git checkout -b feat/msg"
has "$REPO" "㉕ 說得出是哪個目錄" has "$REPO" "㉕ 說得出是哪個目錄"
has "worktree add" "㉖ 給得出開自己 worktree 的指令" has "scripts/worktree open" "㉖ 給得出開自己 worktree 的指令scripts/worktree openinkstone/ISEP#147"
has "不要開在 /tmp" "㉗ 講得出不要開在 /tmp08-29 實測:那些全 prunable" has "不要開在 /tmp" "㉗ 講得出不要開在 /tmp08-29 實測:那些全 prunable"
has "WORKTREE_OK=1" "㉘ 講得出逃生門" has "WORKTREE_OK=1" "㉘ 講得出逃生門"
has "worktree prune" "㉙ 講得出收工要怎麼收" has "scripts/worktree close" "㉙ 講得出收工要怎麼收scripts/worktree close"
hasnt '$(' "㉚ 訊息沒有被 shell 展開" hasnt '$(' "㉚ 訊息沒有被 shell 展開"
hasnt "worktree add $ROOT/shared-repo-wt-" "㉚b 不再教人開在 repo 旁邊(09-07 那排分身就是這行教出來的)"
has "$REPO/.worktrees/" "㉚c 教的是 repo 裡面的 .worktrees/"
# 驗收條件 7:說謊的登記真的被清掉 # 驗收條件 7:說謊的登記真的被清掉
git -C "$REPO" worktree add -q "$ROOT/ghost" -b ghosted git -C "$REPO" worktree add -q "$ROOT/ghost" -b ghosted
@@ -213,6 +219,167 @@ else
printf ' ❌ (59) lib/checkout_target_dir.py 不見了\n'; FAIL=$((FAIL+1)) printf ' ❌ (59) lib/checkout_target_dir.py 不見了\n'; FAIL=$((FAIL+1))
fi fi
echo
echo "── E 群:出路要真的走得通(inkstone/ISEP#109 → comment 65872026-09-07 實撞)──"
# 為什麼這群非有不可:閘訊息教的出路是 `WORKTREE_OK=1 git -C … checkout …`
# 而舊版讀的是 **hook 自己的環境變數**。PreToolUse hook 在指令執行之前跑,
# 指令字串裡的 `WORKTREE_OK=1` 是給 git 的前綴賦值,hook 的行程裡根本沒有它
# ⇒ 那條出路在 Claude Code 這個 harness 下永遠走不通(總管當天三次照貼三次被擋)。
# 🔴 這群的測資是「閘自己印出來的那一行」,原樣餵回去——驗的是出路跑不跑得動,
# 不是閘擋不擋(mistakes.md「閘擋對了,但它印出來的那條出路跑不動」)。
# 判準是**位置**不是字:那個賦值必須是「會移動 HEAD 的那條 git 指令」自己的前綴。
t 0 "(60) 指令字串裡帶 WORKTREE_OK=1 前綴、hook 的環境裡**沒有**它 ⇒ 放行" \
"WORKTREE_OK=1 git checkout -b feat/esc" "$REPO"
t 2 "(61) 先擋一次,拿它印出來的出路當下一條的測資" "git checkout main" "$REPO"
ESC_LINE=$(printf '%s' "$LAST_ERR" | grep -F 'WORKTREE_OK=1 git -C' | head -1 | sed 's/^[[:space:]]*//; s/<分支>/main/')
N=$((N+1))
if [ -n "$ESC_LINE" ]; then printf ' ✅ (62) 抽得出那一行:%s\n' "$ESC_LINE"; PASS=$((PASS+1))
else printf ' ❌ (62) 訊息裡抽不出 WORKTREE_OK=1 git -C … 那一行\n'; FAIL=$((FAIL+1)); ESC_LINE="WORKTREE_OK=1 git -C $REPO checkout main"; fi
t 0 "(63) 閘印出來的那一行**原樣餵回去**(只填分支、人站在別處)⇒ 放行——6587 那天走不通的就是這條" \
"$ESC_LINE" "$PLAIN"
t 2 "(64) 只是印了那個字:echo WORKTREE_OK=1; git checkout main ⇒ 照擋(看位置不看字)" \
"echo WORKTREE_OK=1; git checkout main"
t 2 "(65) 前綴掛在別的指令上:WORKTREE_OK=1 echo hi && git checkout main ⇒ 照擋" \
"WORKTREE_OK=1 echo hi && git checkout main"
t 2 "(66) 值不是 1WORKTREE_OK=0 git checkout main ⇒ 照擋" \
"WORKTREE_OK=0 git checkout main"
t 2 "(67) 寫在 commit 訊息裡再切 ⇒ 照擋(引號裡的字不是前綴)" \
"git commit -qm 'WORKTREE_OK=1 git checkout main' ; git checkout main"
t 0 "(68) cd 進去再掛前綴:cd <repo> && WORKTREE_OK=1 git checkout main ⇒ 放行" \
"cd $REPO && WORKTREE_OK=1 git checkout main" "$PLAIN"
t 0 "(69) 在自己的 worktree 裡也掛了前綴 ⇒ 本來就放行,前綴不礙事" \
"WORKTREE_OK=1 git checkout -b feat/x2" "$OWN"
echo
echo "── F 群:inkstone/ISEP#125 驗收表 A–F(票上原文的六條,期望值照票)──"
# A 逃生門原文照打→0 B 環境變數裡真的有→0 C 文件裡只寫 'git checkout X'→0
# D 文件裡寫 'cd <目錄> && git checkout X'→0 E 同 D 角括號拿掉→0 F 真的要切→2(本體,退化成 0=閘廢了)
t 0 "(70) #125-A 逃生門原文照打:WORKTREE_OK=1 git -C <TOP> checkout main ⇒ 0" \
"WORKTREE_OK=1 git -C $REPO checkout main" "$PLAIN"
t 0 "(71) #125-B 同一句、WORKTREE_OK 真的在 hook 的環境裡 ⇒ 0(本來就是,不要弄壞)" \
"git -C $REPO checkout main" "$PLAIN" "CLAUDE_CODE_CHILD_SESSION=1 WORKTREE_OK=1"
DOC_C="cat > $ROOT/doc-c.md <<'EOF'
把 repo 複製一份,然後 git checkout X
EOF
echo written"
t 0 "(72) #125-C 文件裡只寫 'git checkout X' ⇒ 0" "$DOC_C"
DOC_D="cat > $ROOT/doc-d.md <<'EOF'
示範:cd <目錄> && git checkout X
EOF
echo written"
t 0 "(73) #125-D 文件裡寫 'cd <目錄> && git checkout X' ⇒ 0(寫文件不是執行;09-02 兩次實地命中)" "$DOC_D"
DOC_E="cat > $ROOT/doc-e.md <<'EOF'
示範:cd $REPO && git checkout feat/x
EOF
echo written"
t 0 "(74) #125-E 同 D、角括號拿掉、目錄是真的共用目錄 ⇒ 0" "$DOC_E"
t 2 "(75) #125-F 真的要切(對照組)⇒ 2 🔴 本體,退化成 0=閘廢了" "cd $REPO && git checkout feat/x" "$PLAIN"
# 🔴 已知邊界,寫成測試而不是註解(跟 (53) 同一層、同一個病):tokenize 層把**換行**當空白吞掉,
# 多行指令被併成一句 ⇒ `echo hi⏎git checkout main` 從第一版起就看不到(舊閘實測 exit=0,
# 同一句改成 `echo hi; git checkout main` 就擋)。剝 heredoc 沒有讓它變好也沒有變壞——
# body 剝掉之後留下的仍是「換行分隔的兩句」。要修得動那層,會連帶改到推 main 那道閘的偵測範圍
# ⇒ 不在本票裡動(另報)。這條紅了=那層被改了,回頭看 (53) 與推 main 的 1019 條。
t 0 "(76) 已知邊界:heredoc 之後**換行**再真的切 ⇒ 這道閘看不到(漏擋,不是誤攔;(53) 同層)" \
"cat > $ROOT/doc-f.md <<'EOF'
只是文件
EOF
git checkout main"
t 2 "(77) 同一句換成分號:cat <<'EOF' … EOF; git checkout main ⇒ 照擋(剝掉的只有 body" \
"cat > $ROOT/doc-g.md <<'EOF'
只是文件
EOF
; git checkout main"
echo
echo "── G 群:分身開在 repo 裡面,旁邊不多任何東西(inkstone/ISEP#147)──"
# 為什麼這群非有不可:閘訊息教的「開在 repo 旁邊」一份都沒掉、也一份都沒收,
# leo 在 Finder 看到 ISEP-wt-117ISEP-wt115InkStoneCo-wt-112 一排。
# 這群的測資是**閘自己印出來的那一行**(跟 E 群同一個原則):抽出來、只填票號與分支、真的跑,
# 然後看三件事實:分身在 .worktrees/ 底下、repo 旁邊的目錄清單一個都沒多、共用目錄 git status 乾淨。
BESIDE_BEFORE=$(ls -1 "$ROOT" | sort)
t 2 "(78) 先擋一次,拿它印出來的 open 那一行當測資" "git checkout -b feat/g" "$REPO"
OPEN_LINE=$(printf '%s' "$LAST_ERR" | grep -F 'scripts/worktree open' | head -1 | sed 's/^[[:space:]]*//; s|<owner/repo#票號>|inkstone/shared-repo#901|; s|<你的分支>|feat/901|')
N=$((N+1))
if [ -n "$OPEN_LINE" ]; then printf ' ✅ (79) 抽得出那一行:%s\n' "$OPEN_LINE"; PASS=$((PASS+1))
else printf ' ❌ (79) 訊息裡抽不出 scripts/worktree open 那一行\n'; FAIL=$((FAIL+1)); fi
t 0 "(80) 那一行原樣跑(線、人站在別處)⇒ 這道閘不擋它(open 不是 checkout" "$OPEN_LINE" "$PLAIN"
N=$((N+1))
if (cd "$PLAIN" && eval "$OPEN_LINE" >/dev/null 2>&1) && [ -d "$REPO/.worktrees/shared-repo-901" ]; then
printf ' ✅ (80b) 真的跑:分身長在 %s/.worktrees/shared-repo-901\n' "$REPO"; PASS=$((PASS+1))
else printf ' ❌ (80b) 閘印的 open 那一行跑不動、或分身不在 .worktrees/ 底下\n'; FAIL=$((FAIL+1)); fi
N=$((N+1))
if [ "$(ls -1 "$ROOT" | sort)" = "$BESIDE_BEFORE" ]; then
printf ' ✅ (81) repo 旁邊的目錄清單一個都沒多(leo 在 Finder 只看得到一個資料夾)\n'; PASS=$((PASS+1))
else printf ' ❌ (81) repo 旁邊多了東西:%s\n' "$(comm -13 <(printf '%s\n' "$BESIDE_BEFORE") <(ls -1 "$ROOT" | sort) | tr '\n' ' ')"; FAIL=$((FAIL+1)); fi
N=$((N+1))
if [ -z "$(git -C "$REPO" status --porcelain 2>/dev/null)" ]; then
printf ' ✅ (82) 共用目錄 git status 乾淨(.worktrees/ 進了 .git/info/exclude,沒動被追蹤的檔)\n'; PASS=$((PASS+1))
else printf ' ❌ (82) 共用目錄髒了:%s\n' "$(git -C "$REPO" status --porcelain | head -3 | tr '\n' ' ')"; FAIL=$((FAIL+1)); fi
t 0 "(83) 在那份分身裡切分支 ⇒ 放行(它是自己的 worktree" "git checkout -b feat/g2" "$REPO/.worktrees/shared-repo-901"
t 0 "(84) cd 進分身再切 ⇒ 放行" "cd $REPO/.worktrees/shared-repo-901 && git checkout feat/901" "$PLAIN"
# 同一行再跑一次要冪等(重派同一張票的線不該撞牆)
N=$((N+1))
if (cd "$PLAIN" && eval "$OPEN_LINE" >/dev/null 2>&1); then printf ' ✅ (85) open 冪等:同一張票再開一次不炸\n'; PASS=$((PASS+1))
else printf ' ❌ (85) 同一張票第二次 open 失敗\n'; FAIL=$((FAIL+1)); fi
echo
echo "── H 群:收工那一半(PostToolUse Agent|Task)——推了收掉、沒推點名、不靜默(inkstone/ISEP#147)──"
# 這裡跑的是**總管的 session**CLAUDE_CODE_CHILD_SESSION 沒設),掃的範圍由 CLAUDE_PROJECT_DIR 給。
post() { # post <prompt> [tool_name]
python3 - "$1" "${2:-Agent}" "$ROOT" <<'PY'
import json, sys
print(json.dumps({"session_id": "S-WT", "hook_event_name": "PostToolUse", "cwd": sys.argv[3],
"tool_name": sys.argv[2], "tool_input": {"prompt": sys.argv[1]}, "tool_response": {}},
ensure_ascii=False))
PY
}
tp() { # tp <期望 exit> <說明> <prompt> [tool_name] [env]
local want="$1" desc="$2" prompt="$3" tool="${4:-Agent}" envs="${5:-CLAUDE_CODE_CHILD_SESSION= CLAUDE_PROJECT_DIR=$ROOT}"
N=$((N+1)); local err rc
err=$(printf '%s' "$(post "$prompt" "$tool")" | env $envs bash "$HOOK" 2>&1 >/dev/null); rc=$?
LAST_ERR="$err"
if [ "$rc" -eq "$want" ]; then printf ' ✅ %s\n' "$desc"; PASS=$((PASS+1))
else printf ' ❌ %s —— 期望 exit=%s,實得 exit=%s\n' "$desc" "$want" "$rc"; printf '%s\n' "$err" | sed -n '1,8p' | sed 's/^/ /'; FAIL=$((FAIL+1)); fi
}
WT901="$REPO/.worktrees/shared-repo-901"
# (a) 沒推:分身裡多一筆 commit、沒 push
echo g > "$WT901/g.txt"; git -C "$WT901" add -A; git -C "$WT901" -c user.email=t@t -c user.name=t commit -qm g
tp 2 "(86) 線收工、分支沒推 ⇒ exit 2(點名,不靜默)" "【工單】inkstone/shared-repo#901"
has "feat/901" "(87) 點得出分支名"
has "$WT901" "(88) 點得出路徑"
has "push origin feat/901" "(89) 印得出推的指令"
has "worktree-placement.md" "(90) 指到規約"
N=$((N+1)); if [ -d "$WT901" ]; then printf ' ✅ (91) 沒推的分身一根寒毛都沒動(不刪沒推的 commit)\n'; PASS=$((PASS+1)); else printf ' ❌ (91) 沒推的分身被刪了——那是災難\n'; FAIL=$((FAIL+1)); fi
# (b) 推了但工作樹髒:有未追蹤檔
git -C "$WT901" push -q origin feat/901 2>/dev/null
echo tmp > "$WT901/untracked.txt"
tp 2 "(92) 推了、但分身裡有未追蹤檔 ⇒ exit 2 點名(git 自己也拒絕 remove" "【工單】inkstone/shared-repo#901"
has "未 commit" "(93) 講得出是有東西沒交代"
N=$((N+1)); if [ -d "$WT901" ] && [ -f "$WT901/untracked.txt" ]; then printf ' ✅ (94) 髒的分身沒被動\n'; PASS=$((PASS+1)); else printf ' ❌ (94) 髒的分身被動了\n'; FAIL=$((FAIL+1)); fi
# (c) 推了且乾淨 ⇒ 收掉、安靜
rm -f "$WT901/untracked.txt"
tp 0 "(95) 推了且乾淨 ⇒ exit 0(收掉)" "【工單】inkstone/shared-repo#901"
N=$((N+1)); if [ ! -e "$WT901" ] && ! git -C "$REPO" worktree list | grep -q shared-repo-901; then printf ' ✅ (96) 分身真的收掉了(目錄與登記都沒了)\n'; PASS=$((PASS+1)); else printf ' ❌ (96) 分身還在\n'; FAIL=$((FAIL+1)); fi
N=$((N+1)); if git -C "$REPO" rev-parse --verify -q refs/heads/feat/901 >/dev/null; then printf ' ✅ (97) 分支本身還在(收的是分身,不是分支)\n'; PASS=$((PASS+1)); else printf ' ❌ (97) 分支被刪了\n'; FAIL=$((FAIL+1)); fi
N=$((N+1)); if [ -d "$OWN" ] && [ -d "$REPO2" ]; then printf ' ✅ (98) 別人的 worktree 與別的 repo 一根寒毛都沒動\n'; PASS=$((PASS+1)); else printf ' ❌ (98) 收錯東西了\n'; FAIL=$((FAIL+1)); fi
# (d) 安靜的方向(誤攔比漏擋嚴重)
tp 0 "(99) 同一張票再收一次(分身已不在)⇒ exit 0 安靜" "【工單】inkstone/shared-repo#901"
hasnt "沒有找到" "(100) 沒分身時不吵(--quiet"
tp 0 "(101) 派工單沒有【工單】⇒ 不管" "幫我看一下 shared-repo#901 的狀況"
tp 0 "(102) 票的 repo 沒有任何分身 ⇒ 安靜" "【工單】inkstone/other-repo#5"
tp 0 "(103) PostToolUse 但工具不是 Agent/Task ⇒ 不管" "【工單】inkstone/shared-repo#901" "Bash"
# (e) 一張派工單兩張票:兩份分身各自收
(cd "$PLAIN" && python3 "$(cd "$HERE/../.." && pwd)/scripts/worktree" open inkstone/shared-repo#903 --repo "$REPO" >/dev/null 2>&1)
(cd "$PLAIN" && python3 "$(cd "$HERE/../.." && pwd)/scripts/worktree" open inkstone/shared-repo#904 --repo "$REPO" >/dev/null 2>&1)
echo k > "$REPO/.worktrees/shared-repo-904/k"; git -C "$REPO/.worktrees/shared-repo-904" add -A; git -C "$REPO/.worktrees/shared-repo-904" -c user.email=t@t -c user.name=t commit -qm k
tp 2 "(104) 兩張工單:903 推了(HEAD=main 已在遠端)收掉、904 沒推點名 ⇒ exit 2" "【工單】inkstone/shared-repo#903
【工單】inkstone/shared-repo#904"
N=$((N+1)); if [ ! -e "$REPO/.worktrees/shared-repo-903" ] && [ -d "$REPO/.worktrees/shared-repo-904" ]; then printf ' ✅ (105) 903 收了、904 留著\n'; PASS=$((PASS+1)); else printf ' ❌ (105) 903/904 處理錯:903=%s 904=%s\n' "$([ -e "$REPO/.worktrees/shared-repo-903" ] && echo|| echo 沒了)" "$([ -e "$REPO/.worktrees/shared-repo-904" ] && echo|| echo 沒了)"; FAIL=$((FAIL+1)); fi
has "shared-repo-904" "(106) 點名的是 904"
# (f) 總管 session 的環境變數不影響收工那一半
tp 2 "(107) 環境裡有 WORKTREE_OK=1 也照樣收工檢查(那是切分支的逃生門,不是收工的)" "【工單】inkstone/shared-repo#904" "Agent" "CLAUDE_CODE_CHILD_SESSION= CLAUDE_PROJECT_DIR=$ROOT WORKTREE_OK=1"
clean clean
echo echo
echo "══ $PASS/$N 通過${FAIL:+$FAIL 個失敗} ══" echo "══ $PASS/$N 通過${FAIL:+$FAIL 個失敗} ══"
+1
View File
@@ -21,6 +21,7 @@ MAINLINE="$ROOT/../scripts/mainline"
TMP=$(mktemp -d) TMP=$(mktemp -d)
trap 'rm -rf "$TMP"' EXIT trap 'rm -rf "$TMP"' EXIT
export ISEP_COUNTDOWN_STATE_DIR="$TMP/state" export ISEP_COUNTDOWN_STATE_DIR="$TMP/state"
export ISEP_MAINLINE_REPO_FILE=none # 把 repo 那份鏡像拿掉(inkstone/ISEP#130):這支測的是家目錄那份
export TICKET_HOST="http://127.0.0.1:9" # 連不上:走到網路就會馬上失敗 export TICKET_HOST="http://127.0.0.1:9" # 連不上:走到網路就會馬上失敗
mkdir -p "$ISEP_COUNTDOWN_STATE_DIR" mkdir -p "$ISEP_COUNTDOWN_STATE_DIR"
unset ISEP_MAINLINE_FIXTURE unset ISEP_MAINLINE_FIXTURE
+192
View File
@@ -0,0 +1,192 @@
#!/usr/bin/env bash
# 主線第三個來源「Gitea main 上那份」的迴歸測試(inkstone/ISEP#140
#
# ── 這支在守什麼 ──────────────────────────────────────────────────────
# 雲端薄殼 `youlinhsieh/inkstoneco` 的 SessionStart 跑在 `bootstrap.sh` 之前:
# `InkStoneCo/` 還沒 clone、家目錄又是空的 ⇒ 兩份主線檔都不存在 ⇒ `countdown.py` 退到
# 「期限最近的 milestone」⇒ 第一則 prompt 印一條兩週前的舊線(票上實測:逾期 341 小時)。
# 解法:`scripts/mainline refresh`SessionStart)在兩份都不在時去 Gitea 讀
# `inkstone/InkStoneCo` main 的 `system-dev/mainline.json` 一次、寫進家目錄。這裡驗:
# A 薄殼形狀(兩份都沒有)+ Gitea 讀得到 ⇒ refresh 之後第一則 prompt 的 ⏱/🎯 就是那條線
# B 匿名優先;InkStoneCo 是 private ⇒ 匿名 404 後有 token 才帶 token 再問一次,沒 token 就退回
# C 家目錄或 repo 那份任一在場 ⇒ 不問 Gitea(優先序:家目錄 > repo Gitea
# D 讀不到(5xx/不是 JSON/沒 title/掛住/連不上/被關掉)⇒ 退回現行行為,不掛、逾時有上限
# E 抓到之後 bootstrap 才出現的 repo 那份,跟 ISEP#130 的 set_at 規則接得起來
# F `load()`UserPromptSubmit 那條路照舊零網路
#
# 用法:bash hooks/tests/mainline-gitea-fallback.test.sh
# 🔴 全程離線:Gitea 是本機一個假伺服器(TICKET_HOST 指過去),它照真 Gitea 回:
# public 時 raw 端點匿名 200private 時匿名 404、帶 token 200(真 InkStoneCo 就是 private)。
# 狀態走 ISEP_COUNTDOWN_STATE_DIR、repo 那份走 TMP 底下的假薄殼。不碰真家目錄、不碰真 Gitea。
set -u
ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
MAINLINE="$ROOT/../scripts/mainline"
HOOK="$ROOT/countdown-guard.sh"
TMP=$(mktemp -d)
export ISEP_COUNTDOWN_STATE_DIR="$TMP/home-state"; mkdir -p "$ISEP_COUNTDOWN_STATE_DIR"
export ISEP_COUNTDOWN_NOW=1757203200 # 2026-09-07 00:00 UTC,讓主線那段「剩 X」穩定
export ISEP_MAINLINE_GITEA_TIMEOUT=1
unset ISEP_MAINLINE_REPO_FILE ISEP_MAINLINE_FIXTURE ISEP_MAINLINE_GITEA_URL ISEP_MILESTONE_DUE ISEP_MILESTONE_NAME
unset GITEA_TOKEN_CLAUDE_CODE GITEA_TOKEN
SHELL_ROOT="$TMP/shell"; mkdir -p "$SHELL_ROOT" # 薄殼根:沒有 InkStoneCo/,也不是 git repo
PASS=0; FAIL=0
ok(){ printf ' ✅ %s\n' "$1"; PASS=$((PASS+1)); }
no(){ printf ' ❌ %s —— %s\n' "$1" "$2"; FAIL=$((FAIL+1)); }
# ── 假 Gitea:模式從 $TMP/mode 讀,每個請求記一行 `path|auth` 到 $TMP/log ──
cat > "$TMP/stub.py" <<'PY'
import json, os, sys, time
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
TMP = sys.argv[1]; PORT = int(sys.argv[2])
RAW = "/api/v1/repos/inkstone/InkStoneCo/raw/system-dev/mainline.json"
DOC = {"ref": "inkstone/Arcrun#48", "owner": "inkstone", "repo": "Arcrun", "id": 48,
"title": "Gitea 上那條現在的主線", "description": "測試用。", "due_on": "2026-09-12T23:59:59Z",
"open_issues": 3, "closed_issues": 0, "members": ["inkstone/ISEP#140"],
"set_at": "2026-09-07 07:30", "refreshed_at": "2026-09-07 08:18"}
class H(BaseHTTPRequestHandler):
def log_message(self, *a): pass
def _send(self, code, body=b"", ctype="application/json"):
self.send_response(code); self.send_header("Content-Type", ctype)
self.send_header("Content-Length", str(len(body))); self.end_headers(); self.wfile.write(body)
def do_GET(self):
mode = open(os.path.join(TMP, "mode")).read().strip()
auth = "auth" if self.headers.get("Authorization") else "anon"
with open(os.path.join(TMP, "log"), "a") as f: f.write("%s|%s\n" % (self.path.split("?")[0], auth))
if not self.path.startswith(RAW):
return self._send(404, b'{"message":"Not found."}')
if mode == "public": return self._send(200, json.dumps(DOC, ensure_ascii=False).encode())
if mode == "private":
if auth == "auth": return self._send(200, json.dumps(DOC, ensure_ascii=False).encode())
return self._send(404, b"Not found.", "text/plain") # 真 Gitea 對 private repo 就回 404
if mode == "500": return self._send(500, b"boom")
if mode == "garbage": return self._send(200, b"<html>not json</html>", "text/html")
if mode == "notitle": return self._send(200, b'{"ref":"x","set_at":"2026-09-07 07:30"}')
if mode == "hang":
time.sleep(8); return self._send(200, json.dumps(DOC).encode())
return self._send(500, b"unknown mode")
srv = ThreadingHTTPServer(("127.0.0.1", PORT), H); srv.daemon_threads = True; srv.serve_forever() # 掛住的那筆不准堵住後面的請求
PY
PORT=$(python3 -c "import socket;s=socket.socket();s.bind(('127.0.0.1',0));print(s.getsockname()[1])")
echo public > "$TMP/mode"; : > "$TMP/log"
python3 "$TMP/stub.py" "$TMP" "$PORT" & SRV=$!
trap 'kill $SRV 2>/dev/null; rm -rf "$TMP"' EXIT
for _ in $(seq 1 50); do python3 -c "import socket;socket.create_connection(('127.0.0.1',$PORT),1)" 2>/dev/null && break; sleep 0.1; done
export TICKET_HOST="http://127.0.0.1:$PORT"
refresh(){ CLAUDE_PROJECT_DIR="$SHELL_ROOT" python3 "$MAINLINE" refresh >"$TMP/refresh.out" 2>"$TMP/refresh.err"; echo $?; }
show(){ CLAUDE_PROJECT_DIR="$SHELL_ROOT" python3 "$MAINLINE" 2>&1 | head -1; }
inject(){ # 第一則 promptUserPromptSubmit 給 countdown-guard.sh,回 additionalContext
printf '{"hook_event_name":"UserPromptSubmit","session_id":"s140","transcript_path":""}' \
| CLAUDE_PROJECT_DIR="$SHELL_ROOT" bash "$HOOK" 2>/dev/null \
| python3 -c 'import json,sys
try: print(json.load(sys.stdin)["hookSpecificOutput"]["additionalContext"])
except Exception: print("")'
}
raw_hits(){ grep -c '/raw/system-dev/mainline.json|' "$TMP/log" 2>/dev/null || true; }
reset(){ rm -f "$ISEP_COUNTDOWN_STATE_DIR/mainline.json" "$ISEP_COUNTDOWN_STATE_DIR/milestone-due"; rm -rf "$SHELL_ROOT/InkStoneCo"; : > "$TMP/log"; }
echo "── A. 薄殼形狀(兩份都沒有)+ Gitea 讀得到 ⇒ 第一則 prompt 就是現在的主線 ──"
reset; echo public > "$TMP/mode"
printf '2026-08-25|把管理這條線做對\n' > "$ISEP_COUNTDOWN_STATE_DIR/milestone-due" # 第二基準:那條逾期的舊線
OUT=$(inject)
case "$OUT" in *"現在沒有主線"*) ok "① refresh 之前:兩份都沒有 ⇒ 🎯「現在沒有主線」(票上撞到的那個畫面,先確認測得到)" ;;
*) no "① 前置狀態不對" "$OUT" ;; esac
case "$OUT" in *"把管理這條線做對"*) ok "② refresh 之前:⏱ 退到第二基準,印的是逾期的舊線(同上)" ;;
*) no "② 前置狀態不對(第二基準沒生效)" "$OUT" ;; esac
RC=$(refresh)
[ "$RC" = "0" ] && ok "③ mainline refresh 離開碼 0" || no "③ refresh 離開碼 $RC" "$(cat "$TMP/refresh.err")"
[ -f "$ISEP_COUNTDOWN_STATE_DIR/mainline.json" ] && ok "④ 家目錄那份被建出來(之後每一則訊息讀它,不再打網路)" \
|| no "④ 家目錄沒有檔" "$(ls "$ISEP_COUNTDOWN_STATE_DIR")"
OUT=$(show)
case "$OUT" in *"Gitea 上那條現在的主線"*) ok "⑤ \`mainline\` 答得出 Gitea 上那條" ;; *) no "⑤ show 沒讀到" "$OUT" ;; esac
OUT=$(inject)
case "$OUT" in *"🎯 主線:inkstone/Arcrun#48「Gitea 上那條現在的主線」"*) ok "⑥ 第一則 prompt 的 🎯 那行是 Gitea 上那條(不是「沒有主線」)" ;;
*) no "⑥ 🎯 沒講對" "$OUT" ;; esac
case "$OUT" in *"主線 Gitea 上那條現在的主線 剩"*) ok "⑦ ⏱ 那行掛的是它的名字與期限(被標定的主線蓋過第二基準)" ;;
*) no "⑦ ⏱ 沒掛主線" "$OUT" ;; esac
case "$OUT" in *"把管理這條線做對"*) no "⑧ 舊線還在畫面上" "$OUT" ;; *) ok "⑧ 那條逾期 341 小時的舊線不再出現" ;; esac
FIRST=$(head -1 "$TMP/log")
[ "$FIRST" = "/api/v1/repos/inkstone/InkStoneCo/raw/system-dev/mainline.json|anon" ] && ok "⑨ 第一個請求匿名、打的是 InkStoneCo main 的 raw 檔(讀不帶憑證)" \
|| no "⑨ 第一個請求不對" "$FIRST"
[ "$(raw_hits)" = "1" ] && ok "⑩ 只問了一次" || no "⑩ 問了 $(raw_hits)" "$(cat "$TMP/log")"
[ ! -e "$SHELL_ROOT/InkStoneCo" ] && ok "⑪ 沒有建出 InkStoneCo/(不 clone、不弄髒任何工作樹)" || no "⑪ 動了薄殼底下的樹" "$(ls "$SHELL_ROOT")"
grep -q '"refreshed_at"' "$ISEP_COUNTDOWN_STATE_DIR/mainline.json" && ok "⑫ 寫進家目錄的是完整那份(有 set_atrefreshed_at,之後 set_at 規則照用)" \
|| no "⑫ 家目錄那份殘缺" "$(cat "$ISEP_COUNTDOWN_STATE_DIR/mainline.json")"
echo "── F. load()/每一則訊息那條路:零網路 ──"
: > "$TMP/log"; show >/dev/null; show >/dev/null; inject >/dev/null
[ "$(wc -l < "$TMP/log" | tr -d ' ')" = "0" ] && ok "⑬ show 兩次+UserPromptSubmit 一次,假 Gitea 零請求(關鍵路徑上沒有網路)" \
|| no "⑬ 關鍵路徑打了網路" "$(cat "$TMP/log")"
RC=$(refresh)
[ "$(raw_hits)" = "0" ] && ok "⑭ 家目錄那份已在 ⇒ 再跑 refresh 也不問 Gitea 的檔(優先序:家目錄 Gitea)" \
|| no "⑭ 家目錄在場還去問" "$(cat "$TMP/log")"
echo "── B. private:匿名優先,被拒才帶 token;沒 token 就退回 ──"
reset; echo private > "$TMP/mode"
RC=$(refresh); OUT=$(show)
case "$OUT" in *"現在沒有主線"*) ok "⑮ 匿名 404、沒 token ⇒ 退回「現在沒有主線」(不編、不炸;離開碼 $RC" ;;
*) no "⑮ 沒 token 卻讀到了?" "$OUT" ;; esac
[ "$RC" = "0" ] && ok "⑯ 沒 token 時離開碼仍是 0SessionStart 不准炸)" || no "⑯ 離開碼 $RC" "$(cat "$TMP/refresh.err")"
[ "$(raw_hits)" = "1" ] && ok "⑰ 沒 token 只問一次就收手" || no "⑰ 問了 $(raw_hits)" "$(cat "$TMP/log")"
reset
RC=$(GITEA_TOKEN_CLAUDE_CODE=fake-token-for-test refresh); OUT=$(show)
case "$OUT" in *"Gitea 上那條現在的主線"*) ok "⑱ 匿名 404、環境有 token ⇒ 帶 token 再問一次 ⇒ 讀到(真 InkStoneCo 就是 private" ;;
*) no "⑱ 有 token 還是讀不到" "$OUT$(cat "$TMP/log")" ;; esac
[ "$(sed -n 1p "$TMP/log")" = "/api/v1/repos/inkstone/InkStoneCo/raw/system-dev/mainline.json|anon" ] \
&& [ "$(sed -n 2p "$TMP/log")" = "/api/v1/repos/inkstone/InkStoneCo/raw/system-dev/mainline.json|auth" ] \
&& ok "⑲ 順序:第一次匿名、第二次才帶 token(不是一上來就實名)" || no "⑲ 順序不對" "$(cat "$TMP/log")"
echo "── C. 家目錄或 repo 那份任一在場 ⇒ 不問 Gitea ──"
reset; echo public > "$TMP/mode"
mkdir -p "$SHELL_ROOT/InkStoneCo/system-dev"
python3 - "$SHELL_ROOT/InkStoneCo/system-dev/mainline.json" <<'PY'
import json, sys
json.dump({"ref": "inkstone/ISEP#1", "owner": "inkstone", "repo": "ISEP", "id": 1, "title": "bootstrap 之後 repo 裡那條",
"due_on": "2026-09-20T23:59:59Z", "open_issues": 1, "closed_issues": 0, "members": [],
"set_at": "2026-09-06 10:00", "refreshed_at": "2026-09-06 10:00"}, open(sys.argv[1], "w"), ensure_ascii=False)
PY
RC=$(refresh); OUT=$(show)
[ "$(raw_hits)" = "0" ] && ok "⑳ repo 那份在 ⇒ 不問 Gitea(優先序:repo Gitea" || no "⑳ repo 在場還去問" "$(cat "$TMP/log")"
case "$OUT" in *"bootstrap 之後 repo 裡那條"*) ok "㉑ 答的是 repo 那份(0.24.0 的行為一字不改)" ;; *) no "㉑ 沒答 repo 那份" "$OUT" ;; esac
[ ! -e "$ISEP_COUNTDOWN_STATE_DIR/mainline.json" ] && ok "㉒ 只是讀 repo 那份,家目錄沒有被順手建出來(A32 ④ 沒被弄壞)" \
|| no "㉒ 家目錄被寫了" "$(ls "$ISEP_COUNTDOWN_STATE_DIR")"
echo "── D. 讀不到 ⇒ 退回現行行為,不掛、逾時有上限 ──"
for mode in 500 garbage notitle; do
reset; echo "$mode" > "$TMP/mode"
RC=$(refresh); OUT=$(show)
if [ "$RC" = "0" ] && [ ! -e "$ISEP_COUNTDOWN_STATE_DIR/mainline.json" ]; then
case "$OUT" in *"現在沒有主線"*) ok "㉓ Gitea 回 $mode ⇒ 什麼都不寫、「現在沒有主線」、離開碼 0" ;; *) no "$mode 之後答錯" "$OUT" ;; esac
else no "$mode 之後狀態不對" "rc=$RC $(ls "$ISEP_COUNTDOWN_STATE_DIR")"; fi
done
reset; echo hang > "$TMP/mode"
T0=$(date +%s); RC=$(GITEA_TOKEN_CLAUDE_CODE=fake refresh); T1=$(date +%s); OUT=$(show)
if [ $((T1 - T0)) -le 5 ] && [ "$RC" = "0" ]; then
case "$OUT" in *"現在沒有主線"*) ok "㉔ Gitea 掛住(8 秒不回)⇒ $((T1 - T0)) 秒內放棄、退回、離開碼 0(逾時 1 秒 × 最多兩次)" ;; *) no "㉔ 掛住之後答錯" "$OUT" ;; esac
else no "㉔ 掛住時沒有在時限內放棄" "用了 $((T1 - T0)) 秒,rc=$RC"; fi
reset; echo public > "$TMP/mode"
RC=$(TICKET_HOST="http://127.0.0.1:9" refresh); OUT=$(show)
case "$OUT" in *"現在沒有主線"*) [ "$RC" = "0" ] && ok "㉕ 連不上 GiteaTICKET_HOST 指到死位址)⇒ 退回、離開碼 0" || no "㉕ 離開碼 $RC" "$(cat "$TMP/refresh.err")" ;;
*) no "㉕ 連不上還答出主線" "$OUT" ;; esac
reset
RC=$(ISEP_MAINLINE_GITEA_URL=none refresh); OUT=$(show)
[ "$(raw_hits)" = "0" ] && case "$OUT" in *"現在沒有主線"*) ok "㉖ ISEP_MAINLINE_GITEA_URL=none ⇒ 零請求(既有測試靠它把外界定住)" ;; *) no "㉖ none 之後答錯" "$OUT" ;; esac \
|| no "㉖ none 沒生效" "$(cat "$TMP/log")"
[ -z "$(cat "$TMP/refresh.err")" ] && ok "㉗ 以上每一種讀不到,stderr 都是空的(不報錯嚇人)" || no "㉗ stderr 有東西" "$(cat "$TMP/refresh.err")"
echo "── E. 抓到之後 bootstrap 才出現的 repo 那份:跟 ISEP#130 的 set_at 規則接得起來 ──"
reset; echo public > "$TMP/mode"; RC=$(refresh)
mkdir -p "$SHELL_ROOT/InkStoneCo/system-dev"
cp "$ISEP_COUNTDOWN_STATE_DIR/mainline.json" "$SHELL_ROOT/InkStoneCo/system-dev/mainline.json" # bootstrap clone 下來的同一份
OUT=$(show)
case "$OUT" in *"Gitea 上那條現在的主線"*) ok "㉘ bootstrap 之後 repo 那份出現、set_at 相同 ⇒ 仍是同一條(家目錄那份算數)" ;; *) no "㉘ 答錯" "$OUT" ;; esac
python3 - "$SHELL_ROOT/InkStoneCo/system-dev/mainline.json" <<'PY'
import json, sys
d = json.load(open(sys.argv[1])); d["title"] = "後來在別台機器新標的"; d["set_at"] = "2026-09-08 09:00"
json.dump(d, open(sys.argv[1], "w"), ensure_ascii=False)
PY
OUT=$(show)
case "$OUT" in *"後來在別台機器新標的"*) ok "㉙ repo 那份 set_at 較新 ⇒ 用 repo 那份(A32 ⑤ 的規則沒被本票弄壞)" ;; *) no "㉙ 沒用較新的" "$OUT" ;; esac
echo; echo "通過 $PASS 條,失敗 $FAIL"
[ "$FAIL" -eq 0 ]
+318
View File
@@ -0,0 +1,318 @@
#!/usr/bin/env bash
# 主線成員「由相依邊決定,不靠同名里程碑」的迴歸測試(inkstone/ISEP#133 → comment 6743
#
# ── 這支在守什麼 ──────────────────────────────────────────────────────
# leo 2026-09-07:「拆,誰說『同名跨 repo 是 mainline 機制的一部分』,早就定了只有一個 milestone,
# 不同 repo 用指針」。上一版 `scripts/mainline` 的成員=「票所屬 milestone 的標題與主線相同(不分 repo)」,
# 總管照它做、還在 arcrun-rag 補建了一個同名的。這裡驗票上的三條驗法:
# A 成員=hub 里程碑裡的票 + hub 票 + 它們的相依(跨 repo);別 repo 同名里程碑裡的票**不算**
# B `adopt` 別 repo 的票 ⇒ 在 hub 票上加相依;**不會**在那個 repo 建同名里程碑;沒有 hub 票時
# 擋下並給兩條走得通的路(那條路真的跑一次)
# C 三個同名里程碑關掉之後,`mainline show``ticket pick``has`focus guard 仍然列得出跨 repo 成員
# D `refresh` 讀不到 Gitea ⇒ 成員保留(讀不到 ≠ 沒有成員)
# E `milestone-account` 的帳本落在 InkStoneCo/system-dev/,不落在 plugin 快取
#
# 用法:bash hooks/tests/mainline-members-by-dependency.test.sh
# 🔴 全程離線:Gitea 是本機一個假伺服器(TICKET_HOST 指過去),它照真 Gitea 回:相依 POST 201、
# 已存在 **500**2026-09-07 實測,不是 409)、issue 列表用 `milestones=` 名字查。狀態走 ISEP_COUNTDOWN_STATE_DIR、repo 那份走
# TMP 底下的假薄殼、HOME 也指到 TMP。不碰真家目錄、不碰真 Gitea、不碰真 InkStoneCo。
set -u
ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
MAINLINE="$ROOT/../scripts/mainline"
TICKET="$ROOT/../scripts/ticket"
ACCOUNT="$ROOT/../scripts/milestone-account"
GUARD="$ROOT/mainline-focus-guard.sh"
TMP=$(mktemp -d)
export HOME="$TMP/home"; mkdir -p "$HOME"
export ISEP_COUNTDOWN_STATE_DIR="$TMP/home-state"; mkdir -p "$ISEP_COUNTDOWN_STATE_DIR"
export ISEP_COUNTDOWN_NOW=1757203200 # 2026-09-07 00:00 UTC
export ISEP_MAINLINE_GITEA_URL=none # 第三來源(ISEP#140)不在這支的範圍
export GITEA_TOKEN_CLAUDE_CODE=fake-token-for-test
unset ISEP_MAINLINE_REPO_FILE ISEP_MAINLINE_FIXTURE ISEP_MAINLINE_FILE CLAUDE_CODE_CHILD_SESSION
SHELL_ROOT="$TMP/shell"; HUB="$SHELL_ROOT/InkStoneCo"; mkdir -p "$HUB/system-dev" # 雲端薄殼的形狀
export CLAUDE_PROJECT_DIR="$SHELL_ROOT"
PASS=0; FAIL=0
ok(){ printf ' ✅ %s\n' "$1"; PASS=$((PASS+1)); }
no(){ printf ' ❌ %s —— %s\n' "$1" "$2"; FAIL=$((FAIL+1)); }
# ── 假 Gitea:資料在 $TMP/world.json(測試中途可以改),每個請求記一行 `VERB path` 到 $TMP/log ──
cat > "$TMP/stub.py" <<'PY'
import json, os, re, sys, urllib.parse
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
TMP = sys.argv[1]; PORT = int(sys.argv[2])
W = os.path.join(TMP, "world.json")
def world(): return json.load(open(W))
def save(w): json.dump(w, open(W, "w"), ensure_ascii=False)
def ref(r): return r
def issue_obj(w, r):
o, rest = r.split("/", 1); repo, n = rest.split("#")
d = w["issues"][r]
ms = d.get("milestone")
return {"number": int(n), "title": d.get("title", r), "state": d.get("state", "open"),
"labels": [{"name": l} for l in d.get("labels", [])],
"assignees": [{"login": a} for a in d.get("assignees", [])],
"milestone": (w["milestones"][ms] | {"id": int(ms.split("#")[1])}) if ms else None,
"created_at": "2026-09-01T00:00:00Z",
"repository": {"full_name": "%s/%s" % (o, repo)}}
def ms_obj(w, key):
o, rest = key.split("/", 1); repo, mid = rest.split("#")
return w["milestones"][key] | {"id": int(mid)}
class H(BaseHTTPRequestHandler):
def log_message(self, *a): pass
def _send(self, code, body):
raw = json.dumps(body, ensure_ascii=False).encode()
self.send_response(code); self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(raw))); self.end_headers(); self.wfile.write(raw)
def _log(self):
with open(os.path.join(TMP, "log"), "a") as f: f.write("%s %s\n" % (self.command, self.path))
def do_GET(self):
self._log(); w = world()
if os.path.exists(os.path.join(TMP, "down")): return self._send(500, {"message": "boom"})
p, _, qs = self.path.partition("?"); q = urllib.parse.parse_qs(qs)
if p == "/api/v1/orgs/inkstone/repos": return self._send(200, [{"name": r} for r in w["repos"]])
m = re.match(r"^/api/v1/repos/([^/]+)/([^/]+)/milestones/(\d+)$", p)
if m:
key = "%s/%s#%s" % m.groups()
return self._send(200, ms_obj(w, key)) if key in w["milestones"] else self._send(404, {"message": "not found"})
m = re.match(r"^/api/v1/repos/([^/]+)/([^/]+)/milestones$", p)
if m:
pre = "%s/%s#" % m.groups(); st = q.get("state", ["open"])[0]
return self._send(200, [ms_obj(w, k) for k in w["milestones"] if k.startswith(pre)
and (st == "all" or w["milestones"][k]["state"] == st)])
m = re.match(r"^/api/v1/repos/([^/]+)/([^/]+)/issues$", p)
if m:
pre = "%s/%s#" % m.groups(); want = q.get("milestones", [""])[0]; st = q.get("state", ["open"])[0]
out = []
for r, d in w["issues"].items():
if not r.startswith(pre): continue
if st != "all" and d.get("state", "open") != st: continue
msk = d.get("milestone")
if want and (not msk or w["milestones"][msk]["title"] != want): continue
out.append(issue_obj(w, r))
return self._send(200, out)
m = re.match(r"^/api/v1/repos/([^/]+)/([^/]+)/issues/(\d+)(/dependencies|/blocks)?$", p)
if m:
r = "%s/%s#%s" % m.groups()[:3]
if r not in w["issues"]: return self._send(404, {"message": "not found"})
if not m.group(4): return self._send(200, issue_obj(w, r))
if m.group(4) == "/dependencies": return self._send(200, [issue_obj(w, c) for c in w["deps"].get(r, [])])
return self._send(200, [issue_obj(w, pr) for pr, cs in w["deps"].items() if r in cs])
return self._send(404, {"message": "not found", "path": p})
def do_POST(self):
self._log(); w = world()
n = int(self.headers.get("Content-Length") or 0); body = json.loads(self.rfile.read(n) or b"{}")
p = self.path.partition("?")[0]
m = re.match(r"^/api/v1/repos/([^/]+)/([^/]+)/issues/(\d+)/dependencies$", p)
if m:
parent = "%s/%s#%s" % m.groups(); child = "%s/%s#%s" % (body["owner"], body["repo"], body["index"])
if child in w["deps"].get(parent, []): return self._send(500, {"message": "", "url": "…/api/swagger"}) # 真 Gitea 2026-09-07 實測:重複相依回 500,不是 409
w["deps"].setdefault(parent, []).append(child); save(w)
return self._send(201, issue_obj(w, parent))
if re.match(r"^/api/v1/repos/([^/]+)/([^/]+)/milestones$", p):
w.setdefault("created_milestones", []).append(p); save(w) # 🔴 這條不該被打到
return self._send(201, {"id": 999, "title": body.get("title")})
return self._send(404, {"message": "not found"})
def do_PATCH(self):
self._log(); w = world()
n = int(self.headers.get("Content-Length") or 0); body = json.loads(self.rfile.read(n) or b"{}")
m = re.match(r"^/api/v1/repos/([^/]+)/([^/]+)/issues/(\d+)$", self.path.partition("?")[0])
if m and "milestone" in body:
r = "%s/%s#%s" % m.groups(); key = "%s/%s#%s" % (m.group(1), m.group(2), body["milestone"])
w["issues"][r]["milestone"] = key; save(w)
return self._send(201, issue_obj(w, r))
return self._send(404, {"message": "not found"})
srv = ThreadingHTTPServer(("127.0.0.1", PORT), H); srv.daemon_threads = True; srv.serve_forever()
PY
# 世界:一條線「AI 問一次就看得到全部」,錨在 Arcrun#48;三個 repo 各有一個同名的(09-07 現場的形狀)
python3 - "$TMP/world.json" <<'PY'
import json, sys
T = "AI 問一次就看得到全部"
w = {
"repos": ["Arcrun", "mira", "ISEP", "arcrun-rag", "InkStoneCo"],
"milestones": {
"inkstone/Arcrun#48": {"title": T, "state": "open", "due_on": "2026-09-12T23:59:59Z", "open_issues": 3, "closed_issues": 0, "description": "兩個目錄讓 AI 查詢"},
"inkstone/Arcrun#50": {"title": "AI 問得到內文", "state": "open", "due_on": "2026-08-26T23:59:59Z", "open_issues": 1, "closed_issues": 1},
"inkstone/mira#49": {"title": T, "state": "open", "due_on": "2026-09-12T23:59:59Z", "open_issues": 1, "closed_issues": 0},
"inkstone/ISEP#60": {"title": T, "state": "open", "due_on": "2026-09-12T23:59:59Z", "open_issues": 1, "closed_issues": 1},
"inkstone/arcrun-rag#61": {"title": T, "state": "open", "due_on": "2026-09-12T23:59:59Z", "open_issues": 2, "closed_issues": 0},
},
"issues": {
"inkstone/Arcrun#86": {"milestone": "inkstone/Arcrun#48", "labels": ["p/high", "s/doing"]},
"inkstone/Arcrun#176": {"milestone": "inkstone/Arcrun#48", "labels": ["s/todo"]},
"inkstone/Arcrun#197": {"milestone": None, "labels": ["s/todo"]},
"inkstone/Arcrun#50": {"milestone": "inkstone/Arcrun#50", "labels": ["s/todo"]},
"inkstone/mira#6": {"milestone": "inkstone/mira#49", "labels": ["s/todo", "s/doing"]},
"inkstone/ISEP#130": {"milestone": "inkstone/ISEP#60", "labels": ["Human", "p/high", "s/todo"]},
"inkstone/ISEP#140": {"milestone": None, "labels": ["s/todo"]},
"inkstone/arcrun-rag#104": {"milestone": "inkstone/arcrun-rag#61", "labels": ["s/review"], "assignees": ["claude-code"]},
"inkstone/arcrun-rag#37": {"milestone": "inkstone/arcrun-rag#61", "labels": ["s/todo"]},
"inkstone/InkStoneCo#44": {"milestone": None, "labels": ["s/doing"]},
},
"deps": {
"inkstone/Arcrun#86": ["inkstone/mira#6"], # 09-07 現場:Arcrun#86 已經有跨 repo 相依
"inkstone/ISEP#130": ["inkstone/ISEP#140"], # 09-07 現場:#130 等 #140
"inkstone/InkStoneCo#44": ["inkstone/arcrun-rag#104"],# 09-07 現場:#44「這張票是那條線本身」
},
}
json.dump(w, open(sys.argv[1], "w"), ensure_ascii=False, indent=1)
PY
PORT=$(python3 -c "import socket;s=socket.socket();s.bind(('127.0.0.1',0));print(s.getsockname()[1])")
: > "$TMP/log"
python3 "$TMP/stub.py" "$TMP" "$PORT" & SRV=$!
trap 'kill $SRV 2>/dev/null; rm -rf "$TMP"' EXIT
for _ in $(seq 1 50); do python3 -c "import socket;socket.create_connection(('127.0.0.1',$PORT),1)" 2>/dev/null && break; sleep 0.1; done
export TICKET_HOST="http://127.0.0.1:$PORT"
ml(){ python3 "$MAINLINE" "$@" 2>&1; }
members(){ python3 -c "import json,sys; d=json.load(open(sys.argv[1])); print(' '.join(sorted(d.get('members') or [])))" "$ISEP_COUNTDOWN_STATE_DIR/mainline.json"; }
world_set(){ python3 - "$TMP/world.json" "$@" <<'PY'
import json, sys
w = json.load(open(sys.argv[1])); code = sys.argv[2]
exec(code)
json.dump(w, open(sys.argv[1], "w"), ensure_ascii=False)
PY
}
created_ms(){ python3 -c "import json,sys; print(len(json.load(open(sys.argv[1])).get('created_milestones') or []))" "$TMP/world.json"; }
dispatch(){ # 派工單 → "exit|stderr"
out=$(python3 -c 'import json,sys;print(json.dumps({"tool_input":{"prompt":sys.argv[1]},"session_id":"t"}))' "$1" \
| bash "$GUARD" 2>&1 >/dev/null); rc=$?
printf '%s|%s' "$rc" "$out"
}
echo "── A. set:成員=hub 里程碑裡的票 + hub 票 + 它們的相依;同名不算 ──"
OUT=$(ml set inkstone/Arcrun#48 --hub inkstone/InkStoneCo#44); RC=$?
[ "$RC" = 0 ] && ok "① set --hub 離開碼 0" || no "① set 失敗" "$OUT"
M=$(members)
if [[ " $M " == *" inkstone/Arcrun#86 "* && " $M " == *" inkstone/Arcrun#176 "* ]]; then ok "② hub 里程碑裡的兩張是成員(Arcrun#86、#176"; else no "② 里程碑裡的票沒收到" "$M"; fi
case "$M" in *"inkstone/mira#6"*) ok "③ mira#6 是成員——因為 Arcrun#86 把它當相依(跨 repo 邊)" ;; *) no "③ 相依沒走到 mira#6" "$M" ;; esac
case "$M" in *"inkstone/arcrun-rag#104"*) ok "④ arcrun-rag#104 是成員——因為 hub 票 InkStoneCo#44 把它當相依" ;; *) no "④ hub 票的相依沒收到" "$M" ;; esac
case "$M" in *"inkstone/InkStoneCo#44"*) ok "⑤ hub 票自己也是成員" ;; *) no "⑤ hub 票不在成員裡" "$M" ;; esac
case "$M" in *"inkstone/ISEP#130"*) no "⑥ ISEP#130 掛在 ISEP 的同名里程碑、沒有任何邊 ⇒ 不該是成員" "$M" ;; *) ok "⑥ ISEP#130 掛在 ISEP 裡**同名**的里程碑但沒有邊 ⇒ 不是成員(同名不算,leo 09-07" ;; esac
case "$M" in *"inkstone/arcrun-rag#37"*) no "⑦ arcrun-rag#37 同名沒邊 ⇒ 不該是成員" "$M" ;; *) ok "⑦ arcrun-rag#37arcrun-rag 同名里程碑裡、沒邊)也不是" ;; esac
case "$M" in *"inkstone/Arcrun#50"*) no "⑧ 別條線的票混進來了" "$M" ;; *) ok "⑧ 別條線(Arcrun#50)不在成員裡" ;; esac
grep -q '"hub_ticket": "inkstone/InkStoneCo#44"' "$ISEP_COUNTDOWN_STATE_DIR/mainline.json" && ok "⑨ hub 票寫進 state(之後 adopt 不必再指定)" || no "⑨ hub_ticket 沒寫" "$(cat "$ISEP_COUNTDOWN_STATE_DIR/mainline.json")"
grep -q '"hub_ticket": "inkstone/InkStoneCo#44"' "$HUB/system-dev/mainline.json" && ok "⑩ repo 那份(InkStoneCo/system-dev)也一起寫了(ISEP#130 的鏡像沒被弄壞)" || no "⑩ 鏡像沒寫" "$(ls "$HUB/system-dev")"
grep -qE 'GET /api/v1/repos/inkstone/(mira|ISEP|arcrun-rag)/issues\?' "$TMP/log" && no "⑪ set 去別的 repo 列同名里程碑的票了" "$(grep issues? "$TMP/log")" || ok "⑪ set 只列 hub 里程碑那一個 repo 的票,不去別的 repo 找同名"
OUT=$(ml)
case "$OUT" in *"hub 票:inkstone/InkStoneCo#44"*) ok "⑫ show 講得出 hub 票是誰" ;; *) no "⑫ show 沒印 hub 票" "$OUT" ;; esac
case "$OUT" in *"Arcrun 2"*"InkStoneCo 1"*"arcrun-rag 1"*"mira 1"*) ok "⑬ show 的成員分佈跨四個 repo(沒有同名里程碑也列得出)" ;; *) no "⑬ show 分佈不對" "$OUT" ;; esac
echo "── B. adopt:別 repo ⇒ 加相依到 hub 票;不建同名里程碑;沒 hub 票時給走得通的路 ──"
: > "$TMP/log"
OUT=$(ml adopt inkstone/ISEP#130 --via inkstone/Arcrun#86); RC=$?
[ "$RC" = 0 ] && ok "⑭ adopt 別 repo 的票(--via 指到 hub 里程碑裡的一張)離開碼 0" || no "⑭ adopt 失敗" "$OUT"
grep -q '^POST /api/v1/repos/inkstone/Arcrun/issues/86/dependencies' "$TMP/log" && ok "⑮ 動作是 POST 相依到 Arcrun#86Gitea 原生邊)" || no "⑮ 沒有 POST 相依" "$(cat "$TMP/log")"
grep -q '^PATCH' "$TMP/log" && no "⑯ 別 repo 的票不該被改 milestone" "$(grep PATCH "$TMP/log")" || ok "⑯ 沒有去改那張票的 milestone(別 repo 的票不掛 hub 里程碑)"
[ "$(created_ms)" = 0 ] && ok "⑰ 沒有在 ISEP 建任何里程碑(同名里程碑不是出路)" || no "⑰ 建了里程碑" "$(created_ms)"
M=$(members)
case "$M" in *"inkstone/ISEP#130"*"inkstone/ISEP#140"*) ok "⑱ 成員多了 ISEP#130**還有它的相依 ISEP#140**(邊會一路走下去)" ;; *) no "⑱ 成員沒更新到 #130/#140" "$M" ;; esac
case "$OUT" in *"沒有多出任何里程碑"*) ok "⑲ 訊息明講那個 repo 沒有多出里程碑" ;; *) no "⑲ 訊息沒講" "$OUT" ;; esac
OUT=$(ml adopt inkstone/ISEP#130 --via inkstone/Arcrun#86); RC=$?
[ "$RC" = 0 ] && ok "⑳ 同一張再 adopt 一次 ⇒ 仍是離開碼 0(冪等:先讀 /dependencies,邊在就不 POST;真 Gitea 對重複 POST 回 500" || no "⑳ 重複 adopt 炸了" "$OUT"
grep -c '^POST /api/v1/repos/inkstone/Arcrun/issues/86/dependencies' "$TMP/log" | grep -qx 1 && ok "⑳′ 第二次沒有再 POST(判準是 Gitea 有沒有這條邊,不是回應碼)" || no "⑳′ 重複 POST 了" "$(grep POST "$TMP/log")"
: > "$TMP/log"
OUT=$(ml adopt inkstone/arcrun-rag#37); RC=$?
[ "$RC" = 0 ] && grep -q '^POST /api/v1/repos/inkstone/InkStoneCo/issues/44/dependencies' "$TMP/log" \
&& ok "㉑ 沒給 --via ⇒ 用 state 裡的 hub 票(InkStoneCo#44" || no "㉑ 沒用 hub 票" "$RC $OUT $(cat "$TMP/log")"
: > "$TMP/log"
OUT=$(ml adopt inkstone/Arcrun#197); RC=$?
[ "$RC" = 0 ] && grep -q '^PATCH /api/v1/repos/inkstone/Arcrun/issues/197' "$TMP/log" \
&& ok "㉒ 同 repo 的票 ⇒ 掛進 hub 里程碑(原生欄位),不加邊" || no "㉒ 同 repo 沒走 PATCH" "$RC $OUT $(cat "$TMP/log")"
grep -q '^POST' "$TMP/log" && no "㉓ 同 repo 不該 POST 相依" "$(grep POST "$TMP/log")" || ok "㉓ 同 repo 沒有 POST 相依"
# 沒有 hub 票的狀態:直接把 state 裡的 hub_ticket 拿掉
python3 - "$ISEP_COUNTDOWN_STATE_DIR/mainline.json" "$HUB/system-dev/mainline.json" <<'PY'
import json, sys
for p in sys.argv[1:]:
d = json.load(open(p)); d.pop("hub_ticket", None); json.dump(d, open(p, "w"), ensure_ascii=False)
PY
world_set 'w["deps"]["inkstone/Arcrun#86"].remove("inkstone/ISEP#130")'
: > "$TMP/log"
OUT=$(ml adopt inkstone/ISEP#130); RC=$?
[ "$RC" = 2 ] && ok "㉔ 別 repo 的票、沒 hub 票、沒 --via ⇒ 擋(離開碼 2" || no "㉔ 沒擋" "$RC $OUT"
case "$OUT" in *"--hub"*"--via"*) ok "㉕ 訊息給兩條路:set --hubadopt --via" ;; *) no "㉕ 沒給路" "$OUT" ;; esac
case "$OUT" in *"不是**出路"*|*"不是出路"*) ok "㉖ 訊息明講「開同名里程碑不是出路」" ;; *) no "㉖ 沒講" "$OUT" ;; esac
case "$OUT" in *"inkstone/Arcrun#86"*) ok "㉗ 訊息列出 hub 里程碑裡有哪些票可以 --via(不用人自己去翻)" ;; *) no "㉗ 沒列候選" "$OUT" ;; esac
[ "$(created_ms)" = 0 ] && ok "㉘ 擋下時也沒建里程碑" || no "㉘ 建了" "$(created_ms)"
# 出路真的跑一次:把訊息裡 `adopt … --via <owner/repo#N>` 那行抽出來、填一格、執行
LINE=$(printf '%s\n' "$OUT" | grep -E '^\s+\S+ adopt inkstone/ISEP#130 --via ' | head -1 | sed 's/<owner\/repo#N>/inkstone\/Arcrun#86/')
OUT2=$(eval "$LINE" 2>&1); RC2=$?
[ "$RC2" = 0 ] && ok "㉙ 訊息裡那條出路原樣貼、只填一格 ⇒ 真的跑得通(離開碼 0)" || no "㉙ 出路跑不動" "LINE=$LINE$RC2 $OUT2"
echo "── C. 三個同名里程碑關掉之後(票上驗法第 1 條)──"
world_set '
for k in ("inkstone/mira#49","inkstone/ISEP#60","inkstone/arcrun-rag#61"): w["milestones"][k]["state"]="closed"
for r in ("inkstone/mira#6","inkstone/ISEP#130","inkstone/arcrun-rag#104","inkstone/arcrun-rag#37"): w["issues"][r]["milestone"]=None
'
python3 - "$ISEP_COUNTDOWN_STATE_DIR/mainline.json" <<'PY'
import json, sys
d = json.load(open(sys.argv[1])); d["members"] = []; d["hub_ticket"] = "inkstone/InkStoneCo#44"; json.dump(d, open(sys.argv[1], "w"), ensure_ascii=False)
PY
rm -f "$HUB/system-dev/mainline.json"
: > "$TMP/log"
OUT=$(ml refresh); RC=$?
[ "$RC" = 0 ] && [ "$(members)" = "" ] && ! grep -q dependencies "$TMP/log" \
&& ok "㉚ 光 refreshSessionStart 那條)不走相依(成本不變:真 Gitea 25 張要 19 秒)" || no "㉚ refresh 走了相依或炸了" "$RC $OUT $(cat "$TMP/log")"
OUT=$(ml refresh --members); RC=$?
[ "$RC" = 0 ] && ok "㉚′ refresh --members 離開碼 0" || no "㉚′ refresh --members 失敗" "$OUT"
M=$(members)
for r in inkstone/mira#6 inkstone/ISEP#130 inkstone/ISEP#140 inkstone/arcrun-rag#104 inkstone/arcrun-rag#37; do
case " $M " in *" $r "*) ok "㉛ 同名里程碑關掉、票也不掛任何里程碑之後,$r 仍是成員(靠邊,不靠名字)" ;; *) no "$r 掉出主線了" "$M" ;; esac
done
OUT=$(ml)
case "$OUT" in *"mira 1"*"ISEP 2"*|*"ISEP 2"*"mira 1"*) ok "㉜ mainline show 列得出跨 repo 成員" ;; *) no "㉜ show 沒列出" "$OUT" ;; esac
OUT=$(python3 "$TICKET" pick --mainline "$ISEP_COUNTDOWN_STATE_DIR/mainline.json" --all --json 2>&1); RC=$?
REFS=$(printf '%s' "$OUT" | python3 -c "import json,sys; print(' '.join(r['ref'] for r in json.load(sys.stdin) if r['group']=='主線'))" 2>/dev/null)
case " $REFS " in *" inkstone/ISEP#140 "*) ok "㉝ ticket pick 主線組抓得到 ISEP#140(沒里程碑、靠相依在線上、s/todo 沒人)" ;; *) no "㉝ pick 抓不到 ISEP#140" "$OUT" ;; esac
case " $REFS " in *" inkstone/arcrun-rag#37 "*) ok "㉞ ticket pick 也抓得到 arcrun-rag#37(同名里程碑關掉後靠 hub 票的邊)" ;; *) no "㉞ pick 抓不到 arcrun-rag#37" "$OUT" ;; esac
case " $REFS " in *"ISEP#130"*|*"mira#6"*|*"arcrun-rag#104"*) no "㉟ Humans/doing/有人的票被抓走了" "$REFS" ;; *) ok "㉟ ISEP#130Human)、mira#6s/doing)、arcrun-rag#104(有人)照舊不被抓" ;; esac
OUT=$(ml has inkstone/ISEP#140); RC=$?
[ "$RC" = 0 ] && ok "㊰ has ISEP#140 ⇒ 在(快取)" || no "has ISEP#140 說不在" "$OUT"
python3 - "$ISEP_COUNTDOWN_STATE_DIR/mainline.json" <<'PY'
import json, sys
d = json.load(open(sys.argv[1])); d["members"] = ["inkstone/Arcrun#86", "inkstone/Arcrun#176"]; json.dump(d, open(sys.argv[1], "w"), ensure_ascii=False)
PY
OUT=$(ml has inkstone/mira#6); RC=$?
[ "$RC" = 0 ] && ok "㊱ 快取裡沒有 mira#6 ⇒ has 去問「誰把它當相依」(/blocks)⇒ 在" || no "㊱ has 靠 blocks 判不出來" "$RC $OUT"
OUT=$(ml has inkstone/Arcrun#50); RC=$?
[ "$RC" = 1 ] && ok "㊲ has Arcrun#50(別條線、沒人指著它)⇒ 不在(離開碼 1)" || no "㊲ has Arcrun#50 判錯" "$RC $OUT"
case "$OUT" in *"adopt inkstone/Arcrun#50"*) ok "㊳ 不在時給的出路是 adopt(不是去開同名里程碑)" ;; *) no "㊳ 出路不對" "$OUT" ;; esac
echo "── C. focus guard 的新鮮查詢:問 milestone /blocks,不問標題 ──"
: > "$TMP/log"
R=$(dispatch '【工單】inkstone/mira#6')
[ "${R%%|*}" = 0 ] && ok "㊴ 派快取裡沒有、但被 Arcrun#86 當相依的 mira#6 ⇒ 放行(靠 /blocks 學到)" || no "㊴ 誤攔 mira#6" "$R"
grep -q 'issues/6/blocks' "$TMP/log" && ok "㊵ 閘真的問了 /blocks" || no "㊵ 沒問 /blocks" "$(cat "$TMP/log")"
grep -q 'inkstone/mira#6' "$ISEP_COUNTDOWN_STATE_DIR/mainline.json" && ok "㊶ 學到的成員寫回快取(下次不必再問)" || no "㊶ 沒寫回" "$(cat "$ISEP_COUNTDOWN_STATE_DIR/mainline.json")"
R=$(dispatch '【工單】inkstone/Arcrun#50')
[ "${R%%|*}" = 2 ] && ok "㊷ 派別條線的 Arcrun#50 ⇒ 擋一次" || no "㊷ 沒擋" "$R"
case "${R#*|}" in *"不要**去那個 repo 開同名里程碑"*|*"不要"*"同名里程碑"*) ok "㊸ 擋下時的補收出路明講「不要去開同名里程碑」" ;; *) no "㊸ 出路沒講" "${R#*|}" ;; esac
world_set 'w["milestones"]["inkstone/mira#49"]["state"]="open"; w["issues"]["inkstone/mira#5"]={"milestone":"inkstone/mira#49","labels":["s/todo"]}'
R=$(dispatch '【工單】inkstone/mira#5')
[ "${R%%|*}" = 2 ] && ok "㊹ 派一張掛在 mira **同名**里程碑、沒有任何邊的票 ⇒ 擋一次(同名不是主線)" || no "㊹ 同名被當成主線放行了" "$R"
R=$(dispatch '【工單】inkstone/mira#5')
[ "${R%%|*}" = 0 ] && ok "㊺ 重送 ⇒ 放行(至多擋一次)" || no "㊺ 鬼打牆" "$R"
echo "── D. refresh 讀不到 Gitea ⇒ 成員保留 ──"
BEFORE=$(members); touch "$TMP/down"
OUT=$(ml refresh --members); RC=$?
[ "$RC" = 0 ] && [ "$(members)" = "$BEFORE" ] && ok "㊻ Gitea 回 500 ⇒ refresh --members 不炸、成員一張不少(讀不到 ≠ 沒有成員)" || no "㊻ 成員被清掉或炸了" "$RC $OUT / $(members)"
rm -f "$TMP/down"
echo "── E. milestone-account 的帳本落在會被 clone 走的地方(票上驗法第 3 條)──"
OUT=$(CLAUDE_PROJECT_DIR="$SHELL_ROOT" python3 "$ACCOUNT" ledger-path 2>&1)
[ "$OUT" = "$HUB/system-dev/estimates/ledger.jsonl" ] && ok "㊼ 雲端薄殼形狀(\$CLAUDE_PROJECT_DIR 是薄殼根、真身在 InkStoneCo/)⇒ 帳本在 InkStoneCo/system-dev/estimates/" || no "㊼ 帳本路徑不對" "$OUT"
OUT=$(cd "$HUB" && env -u CLAUDE_PROJECT_DIR python3 "$ACCOUNT" ledger-path 2>&1)
[ "$OUT" = "$HUB/system-dev/estimates/ledger.jsonl" ] && ok "㊽ cwd 就是 InkStoneCo ⇒ 同一個地方" || no "㊽ cwd 形狀不對" "$OUT"
# plugin 快取的形狀:原始碼被複製到一個沒有 .git 的目錄(claude plugin update 會整個換掉)
CACHE="$TMP/plugins/cache/inkstone/isep/9.9.9"; mkdir -p "$CACHE/scripts" "$CACHE/hooks/lib" "$CACHE/system-dev"
cp "$ACCOUNT" "$CACHE/scripts/"; cp "$ROOT/lib/mainline.py" "$CACHE/hooks/lib/"
EMPTY="$TMP/shell-empty"; mkdir -p "$EMPTY"
OUT=$(cd "$EMPTY" && CLAUDE_PROJECT_DIR="$EMPTY" python3 "$CACHE/scripts/milestone-account" ledger-path 2>&1)
case "$OUT" in "$CACHE"*) no "㊾ 帳本落進 plugin 快取(下一版就不見)" "$OUT" ;; "$HOME/.claude/isep-estimates/ledger.jsonl") ok "㊾ 專案裡沒有 system-dev、原始碼又在沒 .git 的快取 ⇒ 帳本退到家目錄,**不落快取**" ;; *) no "㊾ 路徑不明" "$OUT" ;; esac
mkdir -p "$CACHE/.git"
OUT=$(cd "$EMPTY" && CLAUDE_PROJECT_DIR="$EMPTY" python3 "$CACHE/scripts/milestone-account" ledger-path 2>&1)
[ "$OUT" = "$CACHE/system-dev/estimates/ledger.jsonl" ] && ok "㊿ 同一棵樹有 .git(真的 checkoutdogfood 的形狀)⇒ 才准用它的 system-dev/" || no "㊿ checkout 形狀不對" "$OUT"
echo; echo "通過 $PASS 條,失敗 $FAIL"
[ "$FAIL" -eq 0 ]
+117
View File
@@ -0,0 +1,117 @@
#!/usr/bin/env bash
# 主線那個檔「隨 repo 走」的迴歸測試(inkstone/ISEP#130
#
# ── 這支在守什麼 ──────────────────────────────────────────────────────
# 主線原本只住在家目錄(`~/.claude/isep-countdown/mainline.json`)。雲端是另一台機器,
# 家目錄空的、clone 下來的 repo 才是它拿得到的東西 ⇒ 2026-09-05 leo
# 「routine 每天早上開啟後抓不到任務」。PR inkstone/InkStoneCo#118 把主線檔放進
# `InkStoneCo/system-dev/mainline.json`,這裡驗 ISEP 這一半:
# A 讀:家目錄沒有 ⇒ 讀 repo 那份(雲端的形狀:$CLAUDE_PROJECT_DIR 是薄殼根,真身在 InkStoneCo/
# B 兩份都在 ⇒ `set_at` 較新的算數,不分本機雲端
# C 寫:`set``adopt``clear` 兩份一起動;`refresh` 那種只寫家目錄(不弄髒 InkStoneCo 工作樹)
# D 哪裡都沒有 ⇒ 仍然答得出「現在沒有主線」(ISEP#82 驗收第 4 條沒有被本票弄壞)
#
# 用法:bash hooks/tests/mainline-repo-mirror.test.sh
# 🔴 全程離線:狀態走 ISEP_COUNTDOWN_STATE_DIR、repo 那份走 TMP 底下的假 InkStoneCo、
# TICKET_HOST 指到連不上的位址。不碰真家目錄、不碰真 InkStoneCo。
set -u
ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
MAINLINE="$ROOT/../scripts/mainline"
LIB="$ROOT/lib/mainline.py"
TMP=$(mktemp -d); trap 'rm -rf "$TMP"' EXIT
export ISEP_COUNTDOWN_STATE_DIR="$TMP/home-state"; mkdir -p "$ISEP_COUNTDOWN_STATE_DIR"
export TICKET_HOST="http://127.0.0.1:9"
unset ISEP_MAINLINE_REPO_FILE ISEP_MAINLINE_FIXTURE
SHELL_ROOT="$TMP/shell"; HUB="$SHELL_ROOT/InkStoneCo"; mkdir -p "$HUB/system-dev"
PASS=0; FAIL=0
ok(){ printf ' ✅ %s\n' "$1"; PASS=$((PASS+1)); }
no(){ printf ' ❌ %s —— %s\n' "$1" "$2"; FAIL=$((FAIL+1)); }
write_ms(){ # write_ms <檔> <標題> <set_at>
python3 - "$1" "$2" "$3" <<'PY'
import json, sys
json.dump({"ref": "inkstone/Arcrun#48", "owner": "inkstone", "repo": "Arcrun", "id": 48,
"title": sys.argv[2], "description": "測試用。", "due_on": "2026-09-13T23:59:59Z",
"open_issues": 3, "closed_issues": 0, "members": ["inkstone/ISEP#130"],
"set_at": sys.argv[3], "refreshed_at": sys.argv[3]},
open(sys.argv[1], "w"), ensure_ascii=False, indent=2)
PY
}
show(){ CLAUDE_PROJECT_DIR="$1" python3 "$MAINLINE" 2>&1 | head -1; }
echo "── A. 家目錄沒有 ⇒ 讀 repo 那份 ──"
write_ms "$HUB/system-dev/mainline.json" "雲端才讀得到的那一條" "2026-09-07 07:30"
OUT=$(show "$SHELL_ROOT")
case "$OUT" in *"雲端才讀得到的那一條"*) ok "① \$CLAUDE_PROJECT_DIR 是薄殼根、真身在 InkStoneCo/(雲端的形狀)⇒ 答得出主線" ;;
*) no "① 薄殼根形狀讀不到 repo 那份" "$OUT" ;; esac
OUT=$(show "$HUB")
case "$OUT" in *"雲端才讀得到的那一條"*) ok "② \$CLAUDE_PROJECT_DIR 直接是 InkStoneCo ⇒ 也答得出" ;;
*) no "② InkStoneCo 根讀不到" "$OUT" ;; esac
OUT=$(cd "$HUB" && env -u CLAUDE_PROJECT_DIR python3 "$MAINLINE" 2>&1 | head -1)
case "$OUT" in *"雲端才讀得到的那一條"*) ok "③ 沒設 \$CLAUDE_PROJECT_DIR、只是 cwd 在 InkStoneCo ⇒ 也答得出" ;;
*) no "③ cwd 形狀讀不到" "$OUT" ;; esac
[ ! -e "$ISEP_COUNTDOWN_STATE_DIR/mainline.json" ] && ok "④ 只是讀,家目錄那份沒有被順手建出來" \
|| no "④ 讀的時候寫了家目錄" "$(ls "$ISEP_COUNTDOWN_STATE_DIR")"
echo "── B. 兩份都在 ⇒ set_at 較新的算數 ──"
write_ms "$ISEP_COUNTDOWN_STATE_DIR/mainline.json" "本機舊的" "2026-09-01 10:00"
OUT=$(show "$SHELL_ROOT")
case "$OUT" in *"雲端才讀得到的那一條"*) ok "⑤ repo 那份較新(別台機器後標的)⇒ 用 repo 那份" ;;
*) no "⑤ 沒用較新的 repo 那份" "$OUT" ;; esac
write_ms "$ISEP_COUNTDOWN_STATE_DIR/mainline.json" "本機新的" "2026-09-08 09:00"
OUT=$(show "$SHELL_ROOT")
case "$OUT" in *"本機新的"*) ok "⑥ 家目錄那份較新 ⇒ 用家目錄那份" ;;
*) no "⑥ 沒用較新的家目錄那份" "$OUT" ;; esac
write_ms "$ISEP_COUNTDOWN_STATE_DIR/mainline.json" "同時標的(家目錄)" "2026-09-07 07:30"
OUT=$(show "$SHELL_ROOT")
case "$OUT" in *"同時標的(家目錄)"*) ok "⑦ 一樣新 ⇒ 家目錄那份(它才有 refresh 過的進度)" ;;
*) no "⑦ 平手沒選家目錄" "$OUT" ;; esac
echo "── C. 寫:誰該動 repo 那份 ──"
R=$(CLAUDE_PROJECT_DIR="$SHELL_ROOT" python3 - "$LIB" "$HUB/system-dev/mainline.json" <<'PY'
import importlib.util, json, os, sys
spec = importlib.util.spec_from_file_location("ml", sys.argv[1]); ML = importlib.util.module_from_spec(spec); spec.loader.exec_module(ML)
rp = sys.argv[2]
before = open(rp).read()
d = ML.load(); d["refreshed_at"] = "2026-09-09 00:00"; d["open_issues"] = 1
ML.save(d) # refresh 的形狀:只寫家目錄
r1 = open(rp).read() == before
d["title"] = "set 之後的新主線"; d["set_at"] = "2026-09-09 00:01"
ML.save(d, mirror=True) # setadopt 的形狀:兩份一起
r2 = json.load(open(rp)).get("title") == "set 之後的新主線"
r3 = json.load(open(ML.path())).get("title") == "set 之後的新主線"
r4 = open(rp).read().endswith("\n")
print("|".join(str(x) for x in (r1, r2, r3, r4)))
PY
)
[ "${R%%|*}" = "True" ] && ok "⑧ save()refresh 的形狀)不碰 repo 那份——不弄髒 InkStoneCo 工作樹" || no "⑧ refresh 動了 repo 那份" "$R"
R2=${R#*|}; [ "${R2%%|*}" = "True" ] && ok "⑨ save(mirror=True)setadopt 的形狀)寫進 repo 那份" || no "⑨ mirror 沒寫 repo" "$R"
R3=${R2#*|}; [ "${R3%%|*}" = "True" ] && ok "⑩ 同一次也寫了家目錄那份" || no "⑩ 家目錄沒寫" "$R"
[ "${R##*|}" = "True" ] && ok "⑪ repo 那份收尾有換行(diff 才不會每次多一行 no newline" || no "⑪ 沒換行" "$R"
OUT=$(CLAUDE_PROJECT_DIR="$SHELL_ROOT" python3 "$MAINLINE" clear 2>&1)
if [ ! -e "$ISEP_COUNTDOWN_STATE_DIR/mainline.json" ] && [ ! -e "$HUB/system-dev/mainline.json" ]; then
ok "⑫ clear ⇒ 兩份都拿掉(否則下次讀又從 repo 那份長回來)"
else no "⑫ clear 沒清乾淨" "$(ls "$ISEP_COUNTDOWN_STATE_DIR" "$HUB/system-dev" 2>&1 | tr '\n' ' ')"; fi
case "$OUT" in *"repo 那份也刪了"*) ok "⑬ clear 講得出 repo 那份也動了(要 commit 才到雲端)" ;; *) no "⑬ clear 沒講 repo 那份" "$OUT" ;; esac
# set 要打網路,這裡只驗它印出來的那段「repo 那份寫了沒」是接在 repo_path 上的
R=$(CLAUDE_PROJECT_DIR="$SHELL_ROOT" python3 - "$LIB" "$HUB" <<'PY'
import importlib.util, os, sys
spec = importlib.util.spec_from_file_location("ml", sys.argv[1]); ML = importlib.util.module_from_spec(spec); spec.loader.exec_module(ML)
print(ML.repo_path(for_write=True) == os.path.join(sys.argv[2], "system-dev", "mainline.json"))
PY
)
[ "$R" = "True" ] && ok "⑭ 檔還不存在時,寫的目標仍指到 InkStoneCo/system-dev/set 建得出它)" || no "⑭ 寫的目標不對" "$R"
echo "── D. 哪裡都沒有 ⇒ 仍然答得出「現在沒有主線」 ──"
OUT=$(show "$SHELL_ROOT")
case "$OUT" in *"現在沒有主線"*) ok "⑮ 兩份都沒有 ⇒ 「現在沒有主線」(ISEP#82 第 4 條沒被弄壞)" ;; *) no "⑮ 沒主線時答不出來" "$OUT" ;; esac
OUT=$(ISEP_MAINLINE_REPO_FILE=none show "$SHELL_ROOT")
case "$OUT" in *"現在沒有主線"*) ok "⑯ ISEP_MAINLINE_REPO_FILE=none ⇒ 不看 repo(既有測試靠它把外界定住)" ;; *) no "⑯ none 沒生效" "$OUT" ;; esac
printf 'not json' > "$HUB/system-dev/mainline.json"
OUT=$(show "$SHELL_ROOT")
case "$OUT" in *"現在沒有主線"*) ok "⑰ repo 那份壞掉 ⇒ 當成沒有,不炸" ;; *) no "⑰ 壞檔炸了" "$OUT" ;; esac
echo; echo "通過 $PASS 條,失敗 $FAIL"
[ "$FAIL" -eq 0 ]
+1
View File
@@ -23,6 +23,7 @@ t pass "GET + sort -d / xargs -d" "ls | sort $DASH_D | xargs $DASH_D '\\n' echo;
t pass "GET 帶 Bearer 標頭" "curl -s -H 'Authorization: Bearer xxx' $H/templates?limit=1" t pass "GET 帶 Bearer 標頭" "curl -s -H 'Authorization: Bearer xxx' $H/templates?limit=1"
t pass "打 staging" "curl -X POST https://arcrun-rag-installer-staging.workers.dev/x $DASH_D '{}'" t pass "打 staging" "curl -X POST https://arcrun-rag-installer-staging.workers.dev/x $DASH_D '{}'"
t pass "打 youlin 測試場" "curl -X POST https://arcrun-cypher-executor.youlin-hsieh-dev.workers.dev/x $DASH_D '{}'" t pass "打 youlin 測試場" "curl -X POST https://arcrun-cypher-executor.youlin-hsieh-dev.workers.dev/x $DASH_D '{}'"
t pass "打 youlin 測試場(09-02 重裝後的子網域 arcrun-yuga3bseinkstone/ISEP#130" "curl -X POST https://arcrun-cypher-executor.arcrun-yuga3bse.workers.dev/webhooks/named $DASH_D @def.yaml"
t pass "打 Gitea(不是實例)" "curl -X POST https://git.uncle6.me/api/v1/repos/Leo/x/issues $DASH_D '{}'" t pass "打 Gitea(不是實例)" "curl -X POST https://git.uncle6.me/api/v1/repos/Leo/x/issues $DASH_D '{}'"
echo "── 該擋(寫入)──" echo "── 該擋(寫入)──"
+57 -1
View File
@@ -42,6 +42,8 @@
1 = 兩條路都沒走通(這時 stderr 一定有一段紅字,不會安靜) 1 = 兩條路都沒走通(這時 stderr 一定有一段紅字,不會安靜)
環境變數(都有預設,測試才需要動): 環境變數(都有預設,測試才需要動):
TELEGRAM_BOT_TOKENTELEGRAM_CHAT_ID 有就先走 Bot API 直送(雲端唯一通的路,ISEP#130)
ISEP_NOTIFY_BOT_API Bot API 的主機(預設 https://api.telegram.org;測試指到假的)
ISEP_NOTIFY_URL notify_leo 的 trigger 網址 ISEP_NOTIFY_URL notify_leo 的 trigger 網址
ISEP_NOTIFY_IDENTITY 貼票時的【身份】欄 ISEP_NOTIFY_IDENTITY 貼票時的【身份】欄
ISEP_NOTIFY_STATE_DIR 閘判定快取的位置(預設 ~/.claude/isep-nag ISEP_NOTIFY_STATE_DIR 閘判定快取的位置(預設 ~/.claude/isep-nag
@@ -252,6 +254,52 @@ def send_telegram(text):
return False, "外層通了但**內層沒 ok**%s" % raw[:300] return False, "外層通了但**內層沒 ok**%s" % raw[:300]
# ══ 二之一、直送 Bot API(雲端的路,inkstone/ISEP#130)═══════════════════════
#
# 2026-09-07 從雲端 session 實測三條路:
# notify_leo @ leo21c → HTTP 404「找不到 workflow」(08-28 起就斷,修它是 leo 的人閘)
# notify_leo @ youlin → 連不到:雲端 egress proxy 對 *.arcrun-yuga3bse.workers.dev 回 403
# policy denial,不是 DNS、不是 000;要 leo 在 Cloud environment 放行主機)
# api.telegram.org → 302**通的**
# ⇒ 雲端唯一走得通的是 Bot API 直送,而它只缺兩個環境變數:
# TELEGRAM_BOT_TOKENTELEGRAM_CHAT_IDRoutine 文件 cloud-worker.md 檔頭本來就列著它們)。
# 有 ⇒ 先走這條(它不碰任何實例,閘管不到也不必管);沒有 ⇒ 講清楚缺哪兩個,走原本那條。
BOT_API = os.environ.get("ISEP_NOTIFY_BOT_API", "https://api.telegram.org")
def bot_creds():
tok = (os.environ.get("TELEGRAM_BOT_TOKEN") or "").strip()
chat = (os.environ.get("TELEGRAM_CHAT_ID") or "").strip()
return (tok, chat) if tok and chat else (None, None)
def send_bot_api(text):
"""回 (ok, 說明)。Telegram 的回應要 `ok: true` 才算送到。"""
tok, chat = bot_creds()
if not tok:
return False, "沒有 TELEGRAM_BOT_TOKENTELEGRAM_CHAT_ID(雲端要 leo 在 Cloud environment 加這兩個變數)"
if os.environ.get("ISEP_NOTIFY_OFFLINE") == "1":
return False, "ISEP_NOTIFY_OFFLINE=1:刻意不打網路"
req = urllib.request.Request(
"%s/bot%s/sendMessage" % (BOT_API, tok),
data=json.dumps({"chat_id": chat, "text": text}).encode(), method="POST",
headers={"Content-Type": "application/json",
"User-Agent": "isep-notify/1.0 (+inkstone/ISEP#130)"})
try:
raw = urllib.request.urlopen(req, timeout=30).read().decode()
except urllib.error.HTTPError as e:
return False, "Bot API HTTP %s%s" % (e.code, e.read().decode()[:200])
except Exception as e:
return False, "Bot API 連不上:%s" % e
try:
d = json.loads(raw)
except Exception:
return False, "Bot API 回應不是 JSON%s" % raw[:200]
if d.get("ok") is True:
return True, "送到了(Bot API 直送,message_id=%s" % ((d.get("result") or {}).get("message_id"))
return False, "Bot API 回 ok=false%s" % raw[:200]
# ══ 三、退路:貼回票上 ═══════════════════════════════════════════════════ # ══ 三、退路:貼回票上 ═══════════════════════════════════════════════════
def gitea_token(): def gitea_token():
for env in ("GITEA_TOKEN_CLAUDE_CODE", "GITEA_TOKEN"): for env in ("GITEA_TOKEN_CLAUDE_CODE", "GITEA_TOKEN"):
@@ -351,12 +399,20 @@ def notify(text, fallback_ticket=None, dry_run=False):
out.append(text) out.append(text)
return 0, "\n".join(out) return 0, "\n".join(out)
# ① Bot API 直送:不碰任何實例,閘的判定管不到它(inkstone/ISEP#130
sent, why_bot = send_bot_api(text)
out.append(("✅ TelegramBot API 直送):%s" if sent else "⏭️ Bot API 直送:%s") % why_bot)
if sent:
return 0, "\n".join(out)
# ② 走實例上的 notify_leo 工作流(原本那條;閘說會擋就不送)
if fact["verdict"] == "block": if fact["verdict"] == "block":
out.append("⛔ 閘說會擋 ⇒ **本支不繞路**,直接走退路。") out.append("⛔ 閘說會擋 ⇒ **本支不繞路**,直接走退路。")
sent, why = False, "閘會擋,而繞過去等於拆了那道閘 ⇒ 沒有嘗試送出" sent, why = False, "閘會擋,而繞過去等於拆了那道閘 ⇒ 沒有嘗試送出"
else: else:
sent, why = send_telegram(text) sent, why = send_telegram(text)
out.append(("✅ Telegram%s" if sent else "❌ Telegram%s") % why) out.append(("✅ Telegramnotify_leo%s" if sent else "❌ Telegramnotify_leo%s") % why)
why = "Bot API 直送:%snotify_leo%s" % (why_bot, why)
if sent: if sent:
return 0, "\n".join(out) return 0, "\n".join(out)
+1 -1
View File
@@ -254,7 +254,7 @@ YOULIN_ACCOUNT = "1129efd7df2e8899d537e9c8fbabb6cb"
# ⇒ 判準:防呆要比對「**決定後果的那一項**」,不是「剛好看得到的那一項」。 # ⇒ 判準:防呆要比對「**決定後果的那一項**」,不是「剛好看得到的那一項」。
# namespace 才是資料的歸屬鍵 ⇒ 三項一起驗,缺一不可。 # namespace 才是資料的歸屬鍵 ⇒ 三項一起驗,缺一不可。
YOULIN_NAMESPACE = "yuga3bse" YOULIN_NAMESPACE = "yuga3bse"
YOULIN_CYPHER = "arcrun-cypher-executor.youlin-hsieh-dev.workers.dev" YOULIN_CYPHER = "arcrun-cypher-executor.arcrun-yuga3bse.workers.dev" # 09-02 重裝後的子網域(inkstone/ISEP#130);舊名 youlin-hsieh-dev 的 DNS 已不存在
class Acr: class Acr:
+206 -83
View File
@@ -7,15 +7,16 @@ leo 2026-08-27:「**14 個里程碑同時亮著卻不知道該看哪個**」
⇒ SOP 說的「**那個** active milestone」在現場根本沒有指涉對象—— ⇒ SOP 說的「**那個** active milestone」在現場根本沒有指涉對象——
要注入不知道注哪一個,要擋跳線也不知道拿哪一個當基準。 要注入不知道注哪一個,要擋跳線也不知道拿哪一個當基準。
這支不解「milestone 太多」(跨 repo 同名是既有做法,不動它),
它解的是「**這一刻我在做哪一條**」沒有答案:
mainline 現在的主線是哪一個(= show,唯一答案,離線) mainline 現在的主線是哪一個(= show,唯一答案,離線)
mainline list 有哪些 open milestone 可以選(打網路) mainline list 有哪些 open milestone 可以選(打網路)
mainline set <owner/repo#id> 把某一個 milestone 標成主線(打網路,寫進 state) mainline set <owner/repo#id> [--hub <owner/repo#N>]
把某一個 milestone 標成主線(打網路,寫進 state);
--hub 指定這條線的載體票(別 repo 的票用相依指到它)
mainline clear 現在沒有主線(例:一條線收掉了,下一條還沒開始) mainline clear 現在沒有主線(例:一條線收掉了,下一條還沒開始)
mainline refresh [--members] 更新進度/期限(SessionStart 跑一次,不輪詢) mainline refresh [--members] 更新進度/期限(SessionStart 跑一次,不輪詢)--members 順便重收成員
mainline adopt <owner/repo#N> 「補收」:把一張票掛進主線(打網路) mainline adopt <owner/repo#N> [--via <hub 票>]
「補收」:把一張票掛進主線(打網路)。同 repo ⇒ 掛進 hub 里程碑;
別 repo ⇒ 成為 hub 票的相依。**不建同名里程碑。**
mainline has <owner/repo#N> 這張票在不在主線上(exit 0 =在,1 =不在) mainline has <owner/repo#N> 這張票在不在主線上(exit 0 =在,1 =不在)
🔴 **`<owner/repo#id>` 的 id 是 milestone 的 id,不是 issue 的號碼。** 🔴 **`<owner/repo#id>` 的 id 是 milestone 的 id,不是 issue 的號碼。**
@@ -23,20 +24,31 @@ leo 2026-08-27:「**14 個里程碑同時亮著卻不知道該看哪個**」
── 答案為什麼唯一 ───────────────────────────────────────────────── ── 答案為什麼唯一 ─────────────────────────────────────────────────
主線住在一個檔裡(`~/.claude/isep-countdown/mainline.json`),那個檔**放得下一條**。 主線住在一個檔裡(`~/.claude/isep-countdown/mainline.json`),那個檔**放得下一條**。
inkstone/ISEP#130 起它有一份隨 repo 走的鏡像:`InkStoneCo/system-dev/mainline.json`——
雲端沒有家目錄那份,讀的就是它;`set`/`adopt``clear` 兩份一起寫,`refresh` 只寫家目錄。
inkstone/ISEP#140 起:兩份都不在時(雲端薄殼 bootstrap 之前的形狀),`refresh` 會去 Gitea
讀 `inkstone/InkStoneCo` main 上那份一次、寫進家目錄——優先序寫在 `hooks/lib/mainline.py` 檔頭。)
沒有清單、沒有優先序、沒有「前三名」——`set` 覆蓋掉的那條就不再是主線。 沒有清單、沒有優先序、沒有「前三名」——`set` 覆蓋掉的那條就不再是主線。
⇒ 問一次只會拿到 0 或 1 個答案,不會拿到 14 個。 ⇒ 問一次只會拿到 0 或 1 個答案,不會拿到 14 個。
── 主線是一個名字,錨在一個具體的 milestone 上 ──────────────────── ── 一條線只有一個里程碑;別的 repo 用相依指過來(inkstone/ISEP#133──────
Gitea 的 milestone 不能跨 repo,而同一條線常常同時開在 5 個 repo。所以 🔴 這支的第一版檔頭寫「跨 repo 同名是既有做法,不動它」,成員也是照標題跨 repo
**錨**(期限/進度/目標宣告都讀它)是 `owner/repo#id` 那句話被總管 09-07 當成規則抄進 InkStoneCo 的 ops-facts,還在 arcrun-rag 多建了一個同名的。
**成員判定**看的是「票所屬 milestone 的標題與主線標題相同」(不分 repo)。 leo 當天:「拆,誰說『同名跨 repo 是 mainline 機制的一部分』,早就定了只有一個 milestone,
兩件事都成立:同名跨 repo 照舊能用,而「現在在做哪一條」仍然只有一個答案 不同 repo 用指針」(規則本身在 inkstone/ISEP#30、inkstone/InkStoneCo#44
現在的形狀(判準全部是 Gitea 的欄位,沒有標題比對):
· **錨** `owner/repo#<milestone id>`:整個 Gitea 只有這一個 milestone 物件,
期限/進度/目標宣告都讀它。
· **hub 票**`set --hub`)= 這條線的載體票。別 repo 的票要進主線 ⇒ 成為它的 dependency。
· **成員** = hub 里程碑裡的票 hub 票,沿 `/dependencies` 邊(跨 repo)收下去
`hooks/lib/mainline.py::collect_members`)。同名里程碑關掉之後成員一張都不會掉——
因為成員從來不是靠名字算的。
· `adopt` 別 repo 的票 ⇒ 在 hub 票上加一條 dependency**不會在那個 repo 建同名里程碑**。
""" """
import importlib.machinery import importlib.machinery
import importlib.util import importlib.util
import os import os
import sys import sys
import urllib.parse
from datetime import datetime, timezone from datetime import datetime, timezone
HERE = os.path.dirname(os.path.abspath(__file__)) HERE = os.path.dirname(os.path.abspath(__file__))
@@ -91,35 +103,35 @@ def org_repos(owner):
return [r["name"] for r in rows if isinstance(r, dict) and r.get("name")] return [r["name"] for r in rows if isinstance(r, dict) and r.get("name")]
def issues_in_milestone(owner, repo, title): def collect_members(ms):
q = urllib.parse.urlencode({"state": "all", "type": "issues", """成員=hub 里程碑裡的票 + hub 票 + 它們的相依(跨 repo)。判準在 `hooks/lib/mainline.py`。"""
"milestones": title, "limit": 100}) return ML.collect_members(T.api_soft, ms)
rows = T.api_soft("/repos/%s/%s/issues?%s" % (owner, repo, q)) or []
out = []
for it in rows:
if not isinstance(it, dict) or it.get("pull_request"):
continue
ms = it.get("milestone") or {}
# 🔴 再比對一次標題:`milestones=` 這個參數在不同 Gitea 版本上對「名稱 vs id」
# 的解讀不完全一致,拿回來的東西要自己確認過才算數(不要相信查詢字串)。
if ML.norm(ms.get("title")) != ML.norm(title):
continue
out.append("%s/%s#%d" % (owner, repo, it["number"]))
return out
def collect_members(owner, title, anchor_repo): def members_line(refs, info):
"""跨 repo 收齊「掛在同名 milestone 底下」的票。""" byrepo = {}
refs, scanned = [], [] for r in refs:
repos = org_repos(owner) byrepo[r.split("#")[0]] = byrepo.get(r.split("#")[0], 0) + 1
if anchor_repo not in repos: dist = "、".join("%s %d" % (k, v) for k, v in sorted(byrepo.items()))
repos.append(anchor_repo) return (" 成員 %d 張(里程碑裡 %d 相依收到 %d%s" % (
for r in repos: len(refs), len(info.get("milestone") or []), len(info.get("via_deps") or []),
got = issues_in_milestone(owner, r, title) ("" + dist) if dist else ""))
if got:
scanned.append((r, len(got)))
refs.extend(got) def fetch_issue(ref):
return sorted(set(refs)), scanned parts = ML.split_ref(ref)
if not parts:
die("🔴 票的寫法是 owner/repo#N,你給的是:%s" % ref)
it = T.api_soft("/repos/%s/%s/issues/%d" % parts)
return parts, (it if isinstance(it, dict) and it.get("number") else None)
def fetch_blocks(parts):
"""誰把這張票當相依(`/blocks`)。讀不到 ⇒ None(讀不到 ≠ 沒有人)。"""
rows = T.api_soft("/repos/%s/%s/issues/%d/blocks?limit=100" % parts)
if not isinstance(rows, list):
return None
return [r for r in (ML.issue_ref(x) for x in rows) if r]
def fetch_milestone(owner, repo, mid): def fetch_milestone(owner, repo, mid):
@@ -142,6 +154,8 @@ def cmd_show(argv):
print(" 要標一條:`scripts/mainline list` 看有哪些 → `scripts/mainline set <owner/repo#id>`") print(" 要標一條:`scripts/mainline list` 看有哪些 → `scripts/mainline set <owner/repo#id>`")
print() print()
print("📌 在標之前,每回合的 🎯 那一行也會照樣講「現在沒有主線」,不會編一條出來。") print("📌 在標之前,每回合的 🎯 那一行也會照樣講「現在沒有主線」,不會編一條出來。")
print(" 雲端:SessionStart 的 `mainline refresh` 會先去 Gitea 讀 inkstone/InkStoneCo main 的")
print(" system-dev/mainline.json;還是沒有 ⇒ 那份不存在,或這台拿不到 Giteainkstone/ISEP#140)。")
return return
c, total, pct = ML.progress(ms) c, total, pct = ML.progress(ms)
print("🎯 現在的主線:%s「%s」" % (ML.ref_of(ms), ms.get("title"))) print("🎯 現在的主線:%s「%s」" % (ML.ref_of(ms), ms.get("title")))
@@ -153,12 +167,16 @@ def cmd_show(argv):
print(" 目標:" + (first[:150] + "…" if len(first) > 150 else first)) print(" 目標:" + (first[:150] + "…" if len(first) > 150 else first))
print(" 期限:%s" % ML.due_phrase(ms)) print(" 期限:%s" % ML.due_phrase(ms))
print(" 進度:%d%d 張已關(%d%%" % (c, total, pct)) print(" 進度:%d%d 張已關(%d%%" % (c, total, pct))
if ML.hub_ticket(ms):
print(" hub 票:%s(別 repo 的票用相依指到它)" % ML.hub_ticket(ms))
mem = sorted(ML.members(ms)) mem = sorted(ML.members(ms))
byrepo = {} byrepo = {}
for r in mem: for r in mem:
byrepo[r.split("#")[0]] = byrepo.get(r.split("#")[0], 0) + 1 byrepo[r.split("#")[0]] = byrepo.get(r.split("#")[0], 0) + 1
print(" 屬於主線的票:%d 張%s" % ( print(" 屬於主線的票:%d 張%s" % (
len(mem), ("" + "、".join("%s %d" % (k, v) for k, v in sorted(byrepo.items())) + "") if byrepo else "")) len(mem), ("" + "、".join("%s %d" % (k, v) for k, v in sorted(byrepo.items())) + "") if byrepo else ""))
if mem:
print(" " + "、".join(mem))
if ms.get("set_at"): if ms.get("set_at"):
print(" 標定於:%s" % ms["set_at"]) print(" 標定於:%s" % ms["set_at"])
if ms.get("refreshed_at"): if ms.get("refreshed_at"):
@@ -193,16 +211,36 @@ def cmd_list(argv):
# ── set ────────────────────────────────────────────────────────────────── # ── set ──────────────────────────────────────────────────────────────────
def opt_of(argv, name):
if name in argv and argv.index(name) + 1 < len(argv):
return argv[argv.index(name) + 1]
return None
def positional(argv, *flags_with_value):
return [a for i, a in enumerate(argv)
if not a.startswith("--") and (i == 0 or argv[i - 1] not in flags_with_value)]
def cmd_set(argv): def cmd_set(argv):
need_net() need_net()
if not argv: pos = positional(argv, "--hub")
die("用法:mainline set <owner/repo#milestone_id>") if not pos:
owner, repo, mid = parse_ms_ref(argv[0]) die("用法:mainline set <owner/repo#milestone_id> [--hub <owner/repo#N>]")
owner, repo, mid = parse_ms_ref(pos[0])
m = fetch_milestone(owner, repo, mid) m = fetch_milestone(owner, repo, mid)
title = m.get("title") title = m.get("title")
refs, scanned = collect_members(owner, title, repo) hub = opt_of(argv, "--hub")
now = datetime.now(timezone.utc).astimezone().strftime("%Y-%m-%d %H:%M") if hub:
ok = ML.save({ parts, it = fetch_issue(hub)
if not it:
die("🔴 讀不到 hub 票 %s(票號寫法 owner/repo#N;讀不到就先別標,不要標一張猜的)" % hub)
hub = "%s/%s#%d" % parts
else:
prev = ML.load() or {}
# 重標同一條線而沒帶 --hub ⇒ 沿用原本的 hub 票;換一條線 ⇒ 不沿用(那是別條線的載體)
hub = ML.hub_ticket(prev) if prev.get("ref") == "%s/%s#%d" % (owner, repo, mid) else None
ms = {
"ref": "%s/%s#%d" % (owner, repo, mid), "ref": "%s/%s#%d" % (owner, repo, mid),
"owner": owner, "repo": repo, "id": mid, "owner": owner, "repo": repo, "id": mid,
"title": title, "title": title,
@@ -210,33 +248,85 @@ def cmd_set(argv):
"due_on": m.get("due_on") or "", "due_on": m.get("due_on") or "",
"open_issues": m.get("open_issues") or 0, "open_issues": m.get("open_issues") or 0,
"closed_issues": m.get("closed_issues") or 0, "closed_issues": m.get("closed_issues") or 0,
"members": refs, "hub_ticket": hub,
"set_at": now, "refreshed_at": now, "members": [],
}) }
if not ok: refs, info = collect_members(ms)
ms["members"] = refs
now = datetime.now(timezone.utc).astimezone().strftime("%Y-%m-%d %H:%M")
ms["set_at"] = ms["refreshed_at"] = now
if not ML.save(ms, mirror=True):
die("🔴 寫不進 %s——主線沒有被標上。" % ML.path()) die("🔴 寫不進 %s——主線沒有被標上。" % ML.path())
print("✅ 主線已標定:%s/%s#%d「%s」" % (owner, repo, mid, title)) print("✅ 主線已標定:%s/%s#%d「%s」" % (owner, repo, mid, title))
if scanned: if hub:
print(" 跨 repo 收到同名 milestone 的票 %d 張:%s" print(" hub 票:%s" % hub)
% (len(refs), "、".join("%s %d" % (r, n) for r, n in scanned))) print(members_line(refs, info) if info.get("reached")
else " ⚠️ 讀不到 hub 里程碑裡的票,成員先留空(讀不到 ≠ 沒有)")
if info.get("capped"):
print(" ⚠️ 相依走到 %d 張就停了(上限),剩下的沒收" % ML.MEMBER_WALK_CAP)
print(mirror_line())
print() print()
cmd_show([]) cmd_show([])
def mirror_line():
"""repo 那份有沒有跟著寫(inkstone/ISEP#130):寫了要人去 commit,沒寫要講為什麼。"""
rp = ML.repo_path(for_write=True)
if rp and os.path.isfile(rp):
return (" 已同步寫進 repo 那份:%s\n"
" 📌 這份要 commit/開 PR 併進 inkstone/InkStoneCo,雲端 clone 才拿得到" % rp)
return (" ⚠️ 這台找不到 InkStoneCo 的 system-dev/CLAUDE_PROJECT_DIR 或 cwd 底下都沒有),"
"repo 那份沒更新——雲端仍會讀到舊主線")
def cmd_clear(argv): def cmd_clear(argv):
had = ML.load() had = ML.load()
ML.clear() rp = ML.repo_path()
ML.clear(mirror=True)
print("✅ 已清掉主線%s。現在沒有主線——每回合的 🎯 那一行會照實說。" print("✅ 已清掉主線%s。現在沒有主線——每回合的 🎯 那一行會照實說。"
% ("(原本是 %s「%s」)" % (ML.ref_of(had), had.get("title")) if had else "")) % ("(原本是 %s「%s」)" % (ML.ref_of(had), had.get("title")) if had else ""))
if rp:
print(" repo 那份也刪了:%s(要 commit 才會到雲端)" % rp)
# ── refresh ────────────────────────────────────────────────────────────── # ── refresh ──────────────────────────────────────────────────────────────
def soft_token():
"""拿得到就給,拿不到回空字串。`refresh` 跑在 SessionStart**不准因為沒 token 就整支炸**
——雲端薄殼的 remote 是 GitHub、家目錄是空的,那正是它最需要活著的時候。"""
if T is None:
return ""
import contextlib
import io
try:
with contextlib.redirect_stderr(io.StringIO()): # token() 拿不到會先抱怨再 exit:兩個都吞掉
return T.token() or ""
except (SystemExit, Exception):
return ""
def cmd_refresh(argv): def cmd_refresh(argv):
"""SessionStart 跑一次。**拿不到就原封不動**——寧可資料舊,不要把主線弄丟。""" """SessionStart 跑一次。**拿不到就原封不動**——寧可資料舊,不要把主線弄丟。
inkstone/ISEP#140:家目錄與 repo 那份都不在(雲端薄殼跑 SessionStart 時 `InkStoneCo/`
還沒 clone)⇒ 去 Gitea 讀 `inkstone/InkStoneCo` main 上那份**一次**,寫進家目錄。
之後每一則 UserPromptSubmit 讀的是家目錄,路徑上照舊沒有網路。
讀不到 ⇒ 什麼都不寫,退回現行行為(`countdown.py` 的第二基準)。
"""
ms = ML.load() ms = ML.load()
if not ms: if not ms:
return # 沒有主線就沒有東西要更新,安靜結束 got = ML.fetch_gitea(token=soft_token) # 傳函式:匿名讀得到就不去碰 token
d = T.api_soft("/repos/%s/%s/milestones/%s" % (ms["owner"], ms["repo"], ms["id"])) if not got:
return # 兩份都沒有、Gitea 也問不到 ⇒ 真的沒有主線,安靜結束
ML.save(got) # 只寫家目錄:雲端沒有 InkStoneCo/ 可寫,本機不弄髒工作樹
ms = ML.load()
if not ms:
return
if T is None:
return
try:
d = T.api_soft("/repos/%s/%s/milestones/%s" % (ms["owner"], ms["repo"], ms["id"]))
except SystemExit:
return # 拿不到 token:主線已經在了,進度晚點再更新,不炸
if not isinstance(d, dict) or not d.get("title"): if not isinstance(d, dict) or not d.get("title"):
return # 讀不到 ≠ 主線不存在 return # 讀不到 ≠ 主線不存在
ms.update({ ms.update({
@@ -248,38 +338,67 @@ def cmd_refresh(argv):
"refreshed_at": datetime.now(timezone.utc).astimezone().strftime("%Y-%m-%d %H:%M"), "refreshed_at": datetime.now(timezone.utc).astimezone().strftime("%Y-%m-%d %H:%M"),
}) })
if "--members" in argv: if "--members" in argv:
refs, _ = collect_members(ms["owner"], ms["title"], ms["repo"]) # 成員靠相依邊算(inkstone/ISEP#133):hub 里程碑一頁 每張成員一次 /dependencies。
if refs: # 真 Gitea 實測 25 張成員要 19 秒 ⇒ SessionStart 那條不帶 --members(成本不變);
# `set``adopt` 會重收,`pick``has`focus guard 本來就每次現問 Gitea,快取只餵 `show`。
# 讀不到(reached=False)就保留舊快取——寧可資料舊,不要把成員弄丟。
try:
refs, info = collect_members(ms)
except SystemExit:
refs, info = [], {"reached": False}
if info.get("reached"):
ms["members"] = refs ms["members"] = refs
ML.save(ms) ML.save(ms)
# ── adopt(補收)────────────────────────────────────────────────────────── # ── adopt(補收)──────────────────────────────────────────────────────────
def cmd_adopt(argv): def cmd_adopt(argv):
"""補收。同 repo ⇒ 掛進 hub 里程碑(原生欄位);別 repo ⇒ 成為 hub 票的相依。
🔴 不會在別的 repo 建同名里程碑——那是被 leo 推翻的做法(本檔檔頭)。"""
need_net() need_net()
if not argv: pos = positional(argv, "--via")
die("用法:mainline adopt <owner/repo#N>(把一張票掛進主線=「補收」)") if not pos:
die("用法:mainline adopt <owner/repo#N> [--via <hub 票 owner/repo#N>](把一張票掛進主線=「補收」)")
ms = ML.load() ms = ML.load()
if not ms: if not ms:
die("🔴 現在沒有主線,沒有東西可以補收進去。先 `scripts/mainline set …`。") die("🔴 現在沒有主線,沒有東西可以補收進去。先 `scripts/mainline set …`。")
owner, repo, num = T.parse_ref(argv[0]) owner, repo, num = T.parse_ref(pos[0])
cands = [m for m in (T.api_soft("/repos/%s/%s/milestones?state=all" % (owner, repo)) or [])
if isinstance(m, dict) and ML.norm(m.get("title")) == ML.norm(ms["title"])]
if not cands:
die("""🔴 `%s/%s` 底下沒有叫「%s」的 milestone,所以這張票掛不進去。
兩條路,**都要人決定,這支不會替你選**:
· 這件事真的屬於主線 ⇒ 在 `%s/%s` 開一個同名 milestone(記得設真的期限,
`milestone-due-guard.sh` 會擋沒期限的),再跑一次 adopt
· 這件事其實是另一條線 ⇒ 那就是**跳線**,不是補收。直接重送派工
(本閘同一張票只擋一次),並在回覆說清楚為什麼現在要岔開主線。""" % (
owner, repo, ms["title"], owner, repo))
mid = cands[0]["id"]
T.api("/repos/%s/%s/issues/%d" % (owner, repo, num), {"milestone": mid}, method="PATCH")
ref = "%s/%s#%d" % (owner, repo, num) ref = "%s/%s#%d" % (owner, repo, num)
ms["members"] = sorted(set(ms.get("members") or []) | {ref}) if owner == ms["owner"] and repo == ms["repo"]:
ML.save(ms) T.api("/repos/%s/%s/issues/%d" % (owner, repo, num), {"milestone": ms["id"]}, method="PATCH")
print("✅ 補收:%s 已掛進「%s」(%s/%s#%d" % (ref, ms["title"], owner, repo, mid)) how = "掛進 hub 里程碑 %s" % ML.ref_of(ms)
else:
via = opt_of(argv, "--via") or ML.hub_ticket(ms)
if not via:
_, info = collect_members(ms)
cands = info.get("milestone") or []
die("""🔴 %s 在別的 repo,要進主線得成為 hub 票的相依——而這條線還沒有 hub 票。
兩條路(擇一,都不會建同名里程碑):
· 指定這條線的載體票,之後每次 adopt 都用它:
%s set %s --hub <owner/repo#N>
· 或這一次點名要掛在哪一張底下:
%s adopt %s --via <owner/repo#N>
hub 里程碑裡現在有:%s
(在別的 repo 開一個同名里程碑**不是**出路——leo 2026-09-07:「早就定了只有一個 milestone,不同 repo 用指針」)""" % (
ref, os.path.abspath(sys.argv[0]), ML.ref_of(ms), os.path.abspath(sys.argv[0]), ref,
"、".join(cands) if cands else "(讀不到/沒有)"))
vparts = ML.split_ref(via)
if not vparts:
die("🔴 --via 的寫法是 owner/repo#N,你給的是:%s" % via)
via = "%s/%s#%d" % vparts
T.add_dependency(vparts, (owner, repo, num))
how = "成為 hub 票 %s 的相依(%s/%s 沒有多出任何里程碑)" % (via, owner, repo)
refs, info = collect_members(ms)
if info.get("reached"):
ms["members"] = sorted(set(refs) | {ref})
else:
ms["members"] = sorted(set(ms.get("members") or []) | {ref})
ML.save(ms, mirror=True)
print("✅ 補收:%s → %s" % (ref, how))
print(members_line(ms["members"], info) if info.get("reached") else " (成員清單沿用舊快取+這一張)")
print(mirror_line())
# ── has ────────────────────────────────────────────────────────────────── # ── has ──────────────────────────────────────────────────────────────────
@@ -293,18 +412,22 @@ def cmd_has(argv):
return return
v = ML.belongs(ref, ms) v = ML.belongs(ref, ms)
if v is None: if v is None:
owner, repo, num = T.parse_ref(ref) need_net()
it = T.api_soft("/repos/%s/%s/issues/%d" % (owner, repo, num)) parts, it = fetch_issue(ref)
title = ((it or {}).get("milestone") or {}).get("title") if isinstance(it, dict) else None if not it:
v = ML.belongs(ref, ms, ticket_milestone_title=title or "")
if not isinstance(it, dict):
print("⚪ 讀不到 %s,判不出來(讀不到 ≠ 不屬於)。" % ref) print("⚪ 讀不到 %s,判不出來(讀不到 ≠ 不屬於)。" % ref)
sys.exit(0) sys.exit(0)
blocks = fetch_blocks(parts)
v = ML.belongs(ref, ms, ticket_milestone=it.get("milestone") or {}, blocks=blocks)
if v is None:
print("⚪ %s:讀得到票,但讀不到「誰把它當相依」,判不出來(讀不到 ≠ 不屬於)。" % ref)
sys.exit(0)
if v: if v:
print("✅ %s 在主線「%s」上。" % (ref, ms["title"])) print("✅ %s 在主線「%s」上。" % (ref, ms["title"]))
sys.exit(0) sys.exit(0)
print("🚧 %s **不在**主線「%s」上。\n" print("🚧 %s **不在**主線「%s」上。\n"
" 補收 ⇒ `scripts/mainline adopt %s`;真的是插件事 ⇒ 那是跳線,說清楚再做。" " 補收 ⇒ `scripts/mainline adopt %s`(別 repo 的票會成為 hub 票的相依);"
"真的是插件事 ⇒ 那是跳線,說清楚再做。"
% (ref, ms["title"], ref)) % (ref, ms["title"], ref))
sys.exit(1) sys.exit(1)
+31 -4
View File
@@ -41,21 +41,48 @@ import urllib.request
HOST = os.environ.get("MILESTONE_ACCOUNT_HOST", "https://git.uncle6.me") HOST = os.environ.get("MILESTONE_ACCOUNT_HOST", "https://git.uncle6.me")
HERE = os.path.dirname(os.path.abspath(__file__)) HERE = os.path.dirname(os.path.abspath(__file__))
ROOT = os.path.dirname(HERE) ROOT = os.path.dirname(HERE)
def _project_roots():
"""跟 `hooks/lib/mainline.py::project_roots()` 同一把尺(那裡是唯一定義;載不到才退回同形狀的內建)。"""
try:
import importlib.machinery
import importlib.util
path = os.path.join(ROOT, "hooks", "lib", "mainline.py")
loader = importlib.machinery.SourceFileLoader("isep_mainline_for_account", path)
spec = importlib.util.spec_from_file_location("isep_mainline_for_account", path, loader=loader)
mod = importlib.util.module_from_spec(spec)
loader.exec_module(mod)
return mod.project_roots()
except Exception:
roots = []
for r in (os.environ.get("CLAUDE_PROJECT_DIR", "").strip(), os.getcwd()):
if r:
for c in (r, os.path.join(r, "InkStoneCo")):
if c not in roots:
roots.append(c)
return roots
def _resolve_dir(): def _resolve_dir():
"""帳本住哪裡。 """帳本住哪裡。
🔴 **不能住在 plugin 目錄裡**ISEP 是用 marketplace 裝的, 🔴 **不能住在 plugin 目錄裡**ISEP 是用 marketplace 裝的,
`claude plugin update` 會把那個目錄整個換掉 ⇒ 累積幾個月的帳一次歸零, `claude plugin update` 會把那個目錄整個換掉 ⇒ 累積幾個月的帳一次歸零,
而這張票的全部價值就在「累積」。 而這張票的全部價值就在「累積」。
順序:環境變數 → 這個 session 的專案根底下的 `system-dev/`(總管的跨專案知識庫 inkstone/ISEP#133 實撞:雲端的 `$CLAUDE_PROJECT_DIR` 是薄殼根(沒有 `system-dev/`
帳本本來就屬於那一層)→ 這份原始碼所在 repo 的 `system-dev/` → `~/.claude/`。 上一版於是退到「原始碼所在 repo 的 system-dev/」——而雲端的原始碼就在
`~/.claude/plugins/cache/inkstone/isep/<版本>/`,那天記的 5 筆帳下一個 session 就不見。
順序:環境變數 → 專案根/專案根底下的 `InkStoneCo/`/cwd 同兩層(跟主線檔同一把尺,
帳本本來就屬於 InkStoneCo 那一層)→ 這份原始碼所在 repo 的 `system-dev/`**但只在
它是一個 git 工作樹時**(有 `.git`=真的 checkoutplugin 快取沒有 `.git`)→ `~/.claude/`。
""" """
v = os.environ.get("MILESTONE_ACCOUNT_DIR") v = os.environ.get("MILESTONE_ACCOUNT_DIR")
if v: if v:
return v return v
for base in (os.environ.get("CLAUDE_PROJECT_DIR") or "", ROOT): for base in _project_roots():
if base and os.path.isdir(os.path.join(base, "system-dev")): if os.path.isdir(os.path.join(base, "system-dev")):
return os.path.join(base, "system-dev", "estimates") return os.path.join(base, "system-dev", "estimates")
if os.path.exists(os.path.join(ROOT, ".git")) and os.path.isdir(os.path.join(ROOT, "system-dev")):
return os.path.join(ROOT, "system-dev", "estimates")
return os.path.join(os.path.expanduser("~"), ".claude", "isep-estimates") return os.path.join(os.path.expanduser("~"), ".claude", "isep-estimates")
+255
View File
@@ -0,0 +1,255 @@
#!/usr/bin/env python3
"""release-check — 回頭問「這一版真的送到了嗎」,而且**問的人不是送的人**
inkstone/ISEP#67
leo 2026-08-27 的病(票上原文):
「版本只到 ISEP v0.3.9,你有新版為什麼不推?」
v0.4.0v0.5.0 的 tag 早就推了,但 Gitea Releases 頁停在 v0.3.9
⇒ 對 leo 等於這兩版不存在;claude plugin list 也還顯示舊版。
2026-09-07 又一次:v0.23.0v0.24.0 打了 tagReleases 頁停在 v0.22.0——
交棒給 leo 的「測試位置 releases/tag/v0.24.0」打開是一頁空 tag。
ISEP 的運送鏈有這幾段,**每一段都要有人回頭問「到了嗎」**:
定版 commit → tagGitea → releaseGitea → main 的 plugin.json
→ 這個 session 真的載入到的版本
🔴 這支的全部價值在一句話:**它不聽上一站說「我送了」,它自己去問收貨的那一端。**
tag 在不在 → 問 Gitea 的 tagsrelease 在不在 → 問 Gitea 的 releasesleo 會看的那頁);
載入到了沒 → 看這個 session 真的掛著的那一份 plugin.json。
問的方式全部匿名(D20:讀不帶憑證),判準與 release-shipSessionStart 信標同一份
hooks/lib/release_chain.py)。
用法:
release-check 現行版本 這棵樹 plugin.json 宣稱的那一版
release-check v0.23.0 現行版本 你指定的那一版(release-ship 送完拿來覆核**那一版**
不管工作樹現在 checkout 在哪)
判準是**結構**,不是關鍵字(leo 2026-08-17 已證偽關鍵字黑名單:8 次誤攔、0 次正確):
· 哪些版本「應該」被送到 = main 上有 `定版 vX.Y.Z` commit 的那些(git 說了算,不是猜)
· 那個版本「送到了沒」= 去 Gitea 問它的 tag 與 release 在不在(在=到了)
離開碼:
0 現行版本 **tag 與 release 都在** ⇒ 送貨端完成
2 現行版本缺 tag 或缺 release ⇒ **送貨端斷了**stderr 講出缺哪一站+怎麼補
(這正是工單驗收 4:「故意漏一步 → 管線要擋下來並說出缺哪一站」)
說明:比現行版本更舊的 `定版` 版本若缺 tag/release,只**黃字提醒**、不改離開碼——
它們多半已被新版取代,硬擋等於「懲罰謹慎」(over-block 比 under-block 嚴重)。
v0.190.200.21 就是總管 09-07 裁定「不補」的那三個。
載入端落後(這個 session 跑的比 main 舊)也只提醒:那要 update+重啟,
是收貨端的動作,不是送貨端能修的,且 SessionStart 信標本來就一直在報。
離線測試:`scripts/test-release-check.sh`(走 `RELEASE_CHECK_FIXTURE`,不打 Gitea)。
"""
import json
import os
import re
import subprocess
import sys
HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, os.path.join(HERE, "..", "hooks", "lib"))
try:
import release_chain as rc
except Exception as e: # pragma: no cover
print("🔴 讀不到 hooks/lib/release_chain.py%s" % e, file=sys.stderr)
sys.exit(2)
HOST = os.environ.get("RELEASE_CHECK_HOST", rc.DEFAULT_HOST)
REPO = os.environ.get("RELEASE_CHECK_REPO", rc.DEFAULT_REPO)
FIXTURE = os.environ.get("RELEASE_CHECK_FIXTURE", "")
def die(msg, code=2):
print(msg, file=sys.stderr)
sys.exit(code)
def proj_root():
"""這支腳本操作的那個 ISEP repo 的根。"""
v = os.environ.get("CLAUDE_PROJECT_DIR")
if v and os.path.isfile(os.path.join(v, ".claude-plugin", "plugin.json")):
return v
return os.path.dirname(HERE)
def load_fixture():
if not FIXTURE:
return None
try:
with open(FIXTURE) as f:
return json.load(f)
except Exception:
die("🔴 讀不到 RELEASE_CHECK_FIXTURE%s" % FIXTURE)
FX = load_fixture()
CHAIN = rc.Chain(HOST, REPO, fixture=FX)
# 🔴 裁定不補的歷史版本(唯一識別碼往放行方向比對,不是關鍵字):
# 總管 2026-09-07inkstone/ISEP#67 → comment 6574):「v0.190.200.21 不補——
# 沒 tagv0.22.0 的 note 已列到那三個定版。」這三個定版 commit 永遠在 main 上,
# 不列在這裡它們就會每次都黃字——天天念的東西會被學會忽略,等於不存在。
WAIVED = {"0.19.0": "inkstone/ISEP#67 → 6574", "0.20.0": "inkstone/ISEP#67 → 6574",
"0.21.0": "inkstone/ISEP#67 → 6574"}
# ══ 送貨端事實:main 上「定版」了哪些、現在宣稱哪一版、這個 session 載到哪一版 ══
def dingban_versions():
"""main 上有 `定版 vX.Y.Z` commit 的版本 —— 「應該被送到」的權威清單。"""
if FX is not None:
return list(FX.get("dingban") or [])
root = proj_root()
try:
out = subprocess.run(
["git", "-C", root, "log", "--format=%s", "--grep", "定版 v"],
capture_output=True, text=True, timeout=30).stdout
except Exception:
out = ""
seen, vers = set(), []
for line in out.splitlines():
m = re.search(r"定版\s+v?(\d+\.\d+\.\d+)", line)
if m and m.group(1) not in seen:
seen.add(m.group(1))
vers.append(m.group(1))
return vers
def current_version():
"""plugin.json 現在宣稱的那一版(= main 要送出去的那一版)。"""
if FX is not None:
return FX.get("current") or ""
try:
with open(os.path.join(proj_root(), ".claude-plugin", "plugin.json")) as f:
return json.load(f).get("version") or ""
except Exception:
return ""
def loaded_version():
"""這個 session 真的掛著的那一份 plugin 是哪一版(收貨端最後一段)。
拿不到就回 None —— 不猜、不謊稱到了(house style:不知道就說不知道)。
"""
if FX is not None:
return FX.get("loaded")
root = os.environ.get("CLAUDE_PLUGIN_ROOT")
if not root:
return None
try:
with open(os.path.join(root, ".claude-plugin", "plugin.json")) as f:
return json.load(f).get("version")
except Exception:
return None
# ══ 覆核:逐版問「到了嗎」 ════════════════════════════════════════════════
def audit(focus=None):
cur = focus or current_version()
if not cur:
die("🔴 讀不到 .claude-plugin/plugin.json 的 version —— 這不是 ISEP repo,或檔案壞了。")
dingban = dingban_versions()
if cur not in dingban:
# 現行版本連 `定版` commit 都沒有 ⇒ plugin.json 宣稱了一個沒被定版的號碼。
# 這是 check-version-consistency 那條線的病,不是這支的守備範圍——但要講出來。
dingban = [cur] + dingban
try:
tags = CHAIN.tags()
rels = CHAIN.releases()
except rc.ChainError as e:
die("🔴 問不到收貨端,這一支不猜:%s" % e)
rows = []
for v in sorted(set(dingban), key=rc.vtuple, reverse=True):
rows.append({
"ver": v,
"dingban": True, # 這份清單本來就是從 定版 commit 來的
"tag": rc.tagname(v) in tags,
"release": rc.tagname(v) in rels,
"current": v == cur,
"gaps": rc.gaps(v, tags, rels),
"waived": WAIVED.get(v) if v != cur else None,
})
return cur, rows
def ship_cmd():
"""補 release 的那一行要能直接貼著跑:印正本自己的絕對路徑(mistakes.md 2026-08-31)。"""
return "python3 %s" % os.path.join(HERE, "release-ship")
def report(focus=None):
cur, rows = audit(focus)
loaded = loaded_version()
icon = {True: "✅", False: "❌"}
lines = ["ISEP 運送鏈覆核(收貨端事實,不聽送的人說) repo=%s" % REPO, ""]
lines.append(" 版本 定版 tag release (← %s"
% ("你指定的版本" if focus else "現行 plugin.json 宣稱的版本"))
for r in rows:
mark = " ←" if r["current"] else ""
if r["waived"] and r["gaps"]:
mark = " ⏭ 裁定不補(%s" % r["waived"]
lines.append(" %-10s %s %s %s%s" % (
"v" + r["ver"], icon[r["dingban"]], icon[r["tag"]], icon[r["release"]], mark))
# ── 載入端(這個 session)──────────────────────────────────────────
lines.append("")
if loaded is None:
lines.append(" 載入端:這個 context 讀不到 CLAUDE_PLUGIN_ROOT ⇒ 說不出「這個 session 載到哪一版」"
"(不是 session 裡跑的,或沒裝 plugin)。")
elif rc.vtuple(loaded) < rc.vtuple(cur):
lines.append(" 🟡 載入端落後:這個 session 掛的是 v%smain 已到 v%s。" % (loaded, cur))
lines.append(" 修:本機 `claude plugin update isep@inkstone` **並重啟 session**"
"(升版與生效是兩件事);雲端去動一下 Environment 的 setup script 逼它重拍快照。")
lines.append(" 這一段 SessionStart 信標本來就一直在報(beacon_report.py ①)。")
else:
lines.append(" ✅ 載入端:這個 session 掛的是 v%s,跟 main 宣稱的一致。" % loaded)
# ── 判決 ────────────────────────────────────────────────────────────
currow = next((r for r in rows if r["current"]), None)
hard = currow["gaps"] if currow else []
older_gaps = [r for r in rows if not r["current"] and r["gaps"] and not r["waived"]]
lines.append("")
if hard:
lines.append("🔴 **現行版本 v%s 的送貨端斷了** —— 對 leo 等於這一版不存在:" % cur)
for _key, label, fix in hard:
lines.append(" 缺這一站:%s" % label)
lines.append(" 怎麼補:%s" % fix.format(v=cur, ship=ship_cmd()))
if older_gaps:
lines.append(" (另外還有更舊的版本也缺,見下方黃字,但那些不擋。)")
else:
lines.append("✅ 現行版本 v%s:定版、tag、release 都在 —— 送貨端完成,leo 那頁看得到。" % cur)
if older_gaps:
lines.append("")
lines.append("🟡 更舊的定版版本也缺件(多半已被新版取代,只提醒、不擋):")
for r in older_gaps:
lines.append(" v%s 缺:%s" % (r["ver"], "".join(label for _k, label, _f in r["gaps"])))
lines.append(" 要補歷史版本 ⇒ 逐版 `%s v<版本>`"
"確定不補 ⇒ 這是 leo/總管的決定,記一句在 inkstone/ISEP#67"
"v0.190.200.21 已於 2026-09-07 裁定不補)。" % ship_cmd())
out = "\n".join(lines)
if hard:
print(out, file=sys.stderr)
return 2
print(out)
return 0
def main(argv):
focus = None
for a in argv:
if a in ("-h", "--help"):
print(__doc__)
return 0
m = re.match(r"^v?(\d+\.\d+\.\d+)$", a.strip())
if not m:
die("用法:release-check [vX.Y.Z]--help 看說明);不認得:%s" % a)
focus = m.group(1)
return report(focus)
if __name__ == "__main__":
sys.exit(main(sys.argv[1:]))
+290
View File
@@ -0,0 +1,290 @@
#!/usr/bin/env python3
"""release-ship — 把「已經推上去的 tag」變成「leo 那頁看得到的 release」
inkstone/ISEP#67,對應 arcrun-rag 的 release-record 站)
工單抓到的斷點,一句話:**沒有任何東西會建 release。**
ISEP repo 全樹 grep「建 release」的 API 呼叫 → 0 命中。
後果:tag 早就推了,Gitea Releases 頁卻停在舊版
⇒ 對 leo 等於這一版不存在(「ISEP 現在是哪一版」只有 Releases 答得出來)。
08-27 v0.4.0v0.5.0、09-02 v0.22.0、09-07 v0.23.0v0.24.0——同一站斷了三輪。
這支就是補上那一站。它**只做 tag → release** 這一段,不打 tag、不改 plugin.json、
不碰 main —— 打 tag 是 `release-tag-guard.sh` 在管的、總管驗過整個 milestone 之後的動作。
🔴 送之前,三件事「必須在場」才放行(require-something-present,不是關鍵字黑名單):
① **那個 tag 的樹**裡 `plugin.json` 的 version 這個 tag 的號碼。
比對的對象是 tag 自己的樹(問 Gitea `contents/…?ref=<tag>`),**不是工作樹**。
🔴 09-05 那版拿 `check-version-consistency.sh`(工作樹 plugin.json vs 本機最新 tag
當前置①,結果對「不是最新的那個 tag」永遠建不了:總管在 v0.23.0 的 checkout
跑 `release-ship v0.23.0` 被擋,訊息說最新 tag 是 v0.24.0——而 v0.23.0 的樹
明明就一致。**要送的東西是 tag,判它的就該看它的樹**;工作樹可能是任何分支
(這支本身就是在一條 feature 分支上寫的),跟那個 tag 沒有關係。
`check-version-consistency.sh` 守的是「main 上 plugin.json 跟最新 tag 一致」,
那是打 tag 那一刻的事(release-tag-guard.sh),不是建 release 這一刻的事。
② tag 真的在 Gitea 上:去問收貨端,不在就不給建 release(先去推 tag)。
③ release note 有內容:沒給 `--notes-file` 就從 Gitea「上一個 release ⋯ 這個 tag」
的 compare 自動生一份**事實**清單(哪幾顆 commit,不含 merge)——leo 可以再改,但不留白。
問 Gitea 而不是本機 git log:這支從 plugin 快取目錄跑時**旁邊沒有 git repo**。
🔴 送完**自己不算數**:最後回頭跑一次 `release-check <這個 tag>`,拿收貨端(Gitea releases 頁)
的事實覆核「真的建起來了」。送的人說成功不算,問收貨的那一端才算
(工單:「問的人不能是送的人」)。
讀全部匿名(D20),只有 POST 建 release 才要 token
`GITEA_TOKEN_CLAUDE_CODE``GITEA_TOKEN`,或這個 repo remote URL 裡帶的那把)。
冪等:release 已經在了 ⇒ 報「本來就在」、離開碼 0,不重複建、不報錯、**不動它的內容**。
離開碼:0 release 在 Gitea 上了(新建的或本來就在)
2 = 某個前置條件沒滿足(stderr 講出是哪一個+怎麼補)
離線測試:`scripts/test-release-ship.sh`(走 `RELEASE_SHIP_FIXTURE`,不打 Gitea、不建真 release)。
"""
import json
import os
import re
import subprocess
import sys
import urllib.error
import urllib.request
HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, os.path.join(HERE, "..", "hooks", "lib"))
try:
import release_chain as rc
except Exception as e: # pragma: no cover
print("🔴 讀不到 hooks/lib/release_chain.py%s" % e, file=sys.stderr)
sys.exit(2)
HOST = os.environ.get("RELEASE_SHIP_HOST", rc.DEFAULT_HOST)
REPO = os.environ.get("RELEASE_SHIP_REPO", rc.DEFAULT_REPO)
FIXTURE = os.environ.get("RELEASE_SHIP_FIXTURE", "")
VER_RE = re.compile(r"^v?(\d+\.\d+\.\d+)$")
def die(msg, code=2):
print(msg, file=sys.stderr)
sys.exit(code)
def proj_root():
v = os.environ.get("CLAUDE_PROJECT_DIR")
if v and os.path.isfile(os.path.join(v, ".claude-plugin", "plugin.json")):
return v
return os.path.dirname(HERE)
def load_fixture():
if not FIXTURE:
return None
try:
with open(FIXTURE) as f:
return json.load(f)
except Exception:
die("🔴 讀不到 RELEASE_SHIP_FIXTURE%s" % FIXTURE)
FX = load_fixture()
CHAIN = rc.Chain(HOST, REPO, fixture=FX)
def ask(fn, *a):
"""問收貨端;問不到就死(不猜)。"""
try:
return fn(*a)
except rc.ChainError as e:
die("🔴 問不到收貨端 %s%s" % (HOST, e))
# ══ 前置條件 ③ release note ════════════════════════════════════════════
def auto_notes(tagname, releases):
"""從 Gitea compare 生一份事實 note:上一個 release 之後到這個 tag 之間的 commit。"""
since = CHAIN.latest_release_before(tagname, releases)
subjects = ask(CHAIN.commits_between, since, tagname)
head = ("這一版收了以下改動(%s 之後):" % since) if since else "這一版收了以下改動:"
body = "\n".join("- %s" % s for s in subjects)
if not body:
body = "-Gitea 取不到 commit 清單,請手動補;release 已建起來,leo 可直接編輯。)"
return ("%s\n\n%s\n\n---\n(本 note 由 scripts/release-ship 從 git log 自動生成,"
"leo/總管可直接在 Gitea 上編輯。inkstone/ISEP#67" % (head, body))
def release_name(tagname):
"""`vX.Y.Z — 定版 commit 括號那句人話`,對齊 leo 既有 release 的命名慣例;找不到就純 tag 名。"""
ver = tagname.lstrip("v")
msg = ask(CHAIN.tag_commit_message, tagname)
title = rc.dingban_title(msg, ver)
if not title:
for s in ask(CHAIN.commits_between, None, tagname)[-20:]:
title = rc.dingban_title(s, ver)
if title:
break
return ("%s — %s" % (tagname, title)) if title else tagname
# ══ 真的建 release(POST 收貨端)═══════════════════════════════════════════
def create_release(tagname, notes, dry, name):
payload = {"tag_name": tagname, "name": name, "body": notes,
"draft": False, "prerelease": False}
if dry:
return None, "🧪 --dry-run:不 POST。要建的 release payload\n%s" % \
json.dumps({"tag_name": tagname, "name": name,
"body_lines": notes.count("\n") + 1}, ensure_ascii=False)
if FX is not None:
sink = os.environ.get("RELEASE_SHIP_SINK")
if sink:
try:
cur = json.load(open(sink)) if os.path.exists(sink) else []
except Exception:
cur = []
cur.append(tagname)
json.dump(cur, open(sink, "w"))
return {"tag_name": tagname, "html_url": "(fixture-created)"}, "fixture 模式,未打網路)"
tk = rc.token_from_env_or_remote(HOST, proj_root())
if not tk:
die("🔴 拿不到 %s 的 token —— 建 release 是寫入,一定要憑證"
"GITEA_TOKEN_CLAUDE_CODE,或這個 repo 的 remote URL 帶憑證)。" % HOST)
url = "%s/api/v1/repos/%s/releases" % (HOST, REPO)
req = urllib.request.Request(
url, data=json.dumps(payload).encode(), method="POST",
headers={"Authorization": "token " + tk, "Content-Type": "application/json"})
try:
r = json.load(urllib.request.urlopen(req, timeout=40))
return r, "已建立"
except urllib.error.HTTPError as e:
die("🔴 Gitea 建 release 失敗 %s%s" % (e.code, e.read().decode()[:300]))
except Exception as e:
die("🔴 連不上 %s%s" % (HOST, e))
# ══ 送完覆核:回頭問收貨端(不是問自己)══════════════════════════════════
def verify_via_check(tagname):
"""跑 `release-check <tag>`,拿收貨端事實覆核**這一版**。回 (ok, 輸出)。"""
check = os.path.join(HERE, "release-check")
env = dict(os.environ)
if FX is not None:
# fixture 模式下,把剛「建」進 sink 的 release 併進 release-check 的 fixture 視圖
sink = os.environ.get("RELEASE_SHIP_SINK")
extra = []
if sink and os.path.exists(sink):
try:
extra = json.load(open(sink))
except Exception:
extra = []
merged = dict(FX)
merged["releases"] = sorted(set((FX.get("releases") or []) + extra))
cf = (sink or "/tmp/rs") + ".checkfx.json"
json.dump(merged, open(cf, "w"))
env["RELEASE_CHECK_FIXTURE"] = cf
env.setdefault("RELEASE_CHECK_HOST", HOST)
env.setdefault("RELEASE_CHECK_REPO", REPO)
try:
p = subprocess.run(["python3", check, tagname], capture_output=True, text=True,
timeout=60, env=env)
return p.returncode == 0, (p.stdout + p.stderr).strip()
except Exception as e:
return False, "跑不動 release-check%s" % e
# ══ 主流程 ════════════════════════════════════════════════════════════════
def ship(arg, notes_file=None, dry=False, do_verify=True):
m = VER_RE.match(arg.strip())
if not m:
die("🔴 版本寫法是 vX.Y.Z 或 X.Y.Z,你給的是:%s" % arg)
ver = m.group(1)
tagname = "v" + ver
out = ["📦 release-ship %s(把 tag 變成 leo 看得到的 release" % tagname, ""]
tags = ask(CHAIN.tags)
# 前置 ②(先問 tag 在不在——①要讀它的樹,tag 不在就沒有樹可讀)
if tagname not in tags:
die("🚫 前置② Gitea 上沒有 tag %s —— 不給建 release。\n"
" release 是「把已存在的 tag 公開成一頁」,tag 都還沒推,先推:\n"
" git tag %s && git push origin %s\n"
" (推 tag 那一刻 release-tag-guard.sh 會擋下版本對不上的 tag。)"
% (tagname, tagname, tagname))
# 前置 ①(看 tag 自己的樹,不看工作樹)
at_tag = ask(CHAIN.manifest_version_at, tagname)
if at_tag != ver:
die("🚫 前置① tag %s 的樹裡 plugin.json 寫的是「%s」—— 不給建 release。\n"
" 建 release 是把這個 tag 公開給 leo 裝;tag 的樹自己就講錯版本,裝了會各說各話。\n"
" 這種 tag 不該存在(release-tag-guard.sh 在推 tag 那一刻就會擋),\n"
" 修法:刪掉這個 tag、在 main 上把 plugin.json 改成 %s 重新定版、再打一次 tag。"
% (tagname, at_tag or "(讀不到)", ver))
out.append("✅ 前置② Gitea 上有 tag %s(問過收貨端)" % tagname)
out.append("✅ 前置① tag %s 的樹裡 plugin.json %s(看的是 tag 的樹,不是工作樹)" % (tagname, ver))
# 冪等
existing = ask(CHAIN.release, tagname)
if existing:
out.append("️ release %s 本來就在了(%s)—— 不重複建、不動它。"
% (tagname, existing.get("html_url") or ""))
code = 0
if do_verify:
vok, vout = verify_via_check(tagname)
out.append("")
out.append("── 覆核(release-check %s,問收貨端)──" % tagname)
out.append(vout)
code = 0 if vok else 2
return code, "\n".join(out)
# 前置 ③
releases = ask(CHAIN.releases)
if notes_file:
with open(notes_file) as f:
notes = f.read()
out.append("✅ 前置③ release note 來自 %s" % notes_file)
else:
notes = auto_notes(tagname, releases)
out.append("✅ 前置③ release note 由 Gitea 的 commit 清單自動生成(leo 可再改)")
# 建(release 名對齊 leo 慣例:vX.Y.Z — 定版 commit 那句人話)
relname = release_name(tagname)
rel, how = create_release(tagname, notes, dry, relname)
if dry:
out.append(" release 名:%s" % relname)
out.append("")
out.append(how)
return 0, "\n".join(out)
out.append("✅ 已建立 release「%s」(%s" % (relname, (rel or {}).get("html_url") or how))
# 覆核(送完問收貨端)
code = 0
if do_verify:
vok, vout = verify_via_check(tagname)
out.append("")
out.append("── 覆核(release-check %s,問收貨端,不是問自己)──" % tagname)
out.append(vout)
code = 0 if vok else 2
return code, "\n".join(out)
def main(argv):
arg, notes_file, dry, do_verify = None, None, False, True
i = 0
while i < len(argv):
a = argv[i]
if a in ("-h", "--help"):
print(__doc__)
return 0
elif a == "--notes-file":
i += 1
notes_file = argv[i]
elif a == "--dry-run":
dry = True
elif a == "--no-verify":
do_verify = False
elif a.startswith("-"):
die("不認得的參數:%s--help 看用法)" % a)
else:
arg = a
i += 1
if not arg:
die("用法:release-ship <版本 vX.Y.Z> [--notes-file <檔>] [--dry-run] [--no-verify]")
code, report = ship(arg, notes_file, dry, do_verify)
print(report, file=(sys.stdout if code == 0 else sys.stderr))
return code
if __name__ == "__main__":
sys.exit(main(sys.argv[1:]))
+146
View File
@@ -0,0 +1,146 @@
#!/usr/bin/env python3
"""settings-allow-sync — 把 ISEP 的權限白名單寫進**這台機器**的 ~/.claude/settings.json
inkstone/ISEP#130
━━ 為什麼有這支 ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
leo 09-07 親手把四個 Gitea 正門工具(`ticket``mainline``gate-ok``gitea-pr-merge`
加進本機 `InkStoneCo/.claude/settings.json` 的 `permissions.allow`auto mode 的分類器
才不擋。**雲端 session 沒有那四條** ⇒ 同樣的動作在雲端照樣被擋
09-04 progress-guard run logpermission_denials=6)。
雲端真正讀的是薄殼 repoGitHub)的 settings——推它要 D20 開閘(leo 親跑 github-arm)。
⇒ 白名單不住薄殼、也不住 InkStoneCo**住 ISEP 一份**`docs/permissions-allow.json`),
由本支在那台機器上寫進 `~/.claude/settings.json`user scope,跟 cwd 無關)。
雲端:`docs/cloud-setup-script.sh` 裝完 plugin 就跑一次;之後每個 SessionStart 再對一次,
plugin 更新帶進新規則時不必等快照重拍。本機:同一支、同一份清單。
━━ 規矩 ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
· 只加不減:settings.json 裡本來就有的東西一個字不動(別人手加的規則不是本支的地盤)。
· 冪等:跑第二次 +0 條,檔案一個位元組都不變。
· 清單裡開頭的 `~` 換成這台的家目錄(本機 /Users/…、雲端 /root),其餘照抄。
· 原子寫:先寫暫存檔再 rename,中途斷掉不會留下半個 JSON。
· 讀不懂目標(不是 JSON)⇒ **不碰它**、印出來、離開碼 0——這支掛在 SessionStart
不准因為它把 session 弄壞;`--check` 才會用離開碼講話。
━━ 用法 ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
settings-allow-sync 寫進 ~/.claude/settings.json
settings-allow-sync --dry-run 只印會加哪幾條,不寫
settings-allow-sync --check 對帳:缺任何一條 ⇒ 離開碼 1(測試/驗收用)
settings-allow-sync --target <檔> --home <家目錄> 測試用:指到別的檔、別的家目錄
settings-allow-sync --quiet 沒事就閉嘴(SessionStart 用)
"""
import json
import os
import sys
import tempfile
HERE = os.path.dirname(os.path.abspath(__file__))
SOURCE = os.path.join(HERE, "..", "docs", "permissions-allow.json")
def wanted(home):
with open(SOURCE, encoding="utf-8") as f:
d = json.load(f)
out = []
for rule in d.get("allow") or []:
if not isinstance(rule, str) or not rule.startswith("Bash(") or not rule.endswith(")"):
raise ValueError("清單裡有一條不是 Bash(…) 的形狀:%r" % (rule,))
inner = rule[len("Bash("):-1]
# 只換「路徑開頭」的 ~`python3 ~/.claude/…` 這種。`~` 出現在別處不動。
parts = inner.split(" ")
parts = [home + p[1:] if p.startswith("~/") else p for p in parts]
out.append("Bash(" + " ".join(parts) + ")")
return out
def main(argv):
target = os.path.join(os.path.expanduser("~"), ".claude", "settings.json")
home = os.path.expanduser("~")
dry = check = quiet = False
i = 0
while i < len(argv):
a = argv[i]
if a == "--target":
i += 1; target = argv[i]
elif a == "--home":
i += 1; home = argv[i].rstrip("/")
elif a == "--dry-run":
dry = True
elif a == "--check":
check = True
elif a == "--quiet":
quiet = True
elif a in ("-h", "--help"):
print(__doc__); return 0
else:
print("不認得的參數:%s--help 看用法)" % a, file=sys.stderr); return 2
i += 1
try:
rules = wanted(home)
except Exception as e:
print("🔴 讀不了白名單清單 %s%s" % (SOURCE, e), file=sys.stderr)
return 1 if check else 0
cur = {}
if os.path.exists(target):
try:
with open(target, encoding="utf-8") as f:
cur = json.load(f)
if not isinstance(cur, dict):
raise ValueError("最外層不是物件")
except Exception as e:
print("🔴 %s 讀不懂(%s)——**沒有動它**。修好它再跑一次。" % (target, e), file=sys.stderr)
return 1 if check else 0
perms = cur.get("permissions")
if not isinstance(perms, dict):
perms = {}
allow = perms.get("allow")
if not isinstance(allow, list):
allow = []
have = set(a for a in allow if isinstance(a, str))
missing = [r for r in rules if r not in have]
if check:
if missing:
print("🔴 %s 缺 %d 條:" % (target, len(missing)))
for r in missing:
print(" " + r)
return 1
if not quiet:
print("✅ %s 已有全部 %d 條" % (target, len(rules)))
return 0
if not missing:
if not quiet:
print("✅ 白名單已齊(%d 條):%s" % (len(rules), target))
return 0
if dry:
print("🧪 --dry-run:會加 %d 條進 %s" % (len(missing), target))
for r in missing:
print(" " + r)
return 0
perms["allow"] = allow + missing
cur["permissions"] = perms
try:
os.makedirs(os.path.dirname(target) or ".", exist_ok=True)
fd, tmp = tempfile.mkstemp(prefix=".settings-", suffix=".json", dir=os.path.dirname(target) or ".")
with os.fdopen(fd, "w", encoding="utf-8") as f:
json.dump(cur, f, ensure_ascii=False, indent=2)
f.write("\n")
os.replace(tmp, target)
except Exception as e:
print("🔴 寫不進 %s%s" % (target, e), file=sys.stderr)
return 0
print("✅ 白名單 %d 條 → %s(共 %d 條來自 ISEP" % (len(missing), target, len(rules)))
if not quiet:
for r in missing:
print(" " + r)
return 0
if __name__ == "__main__":
sys.exit(main(sys.argv[1:]))
Executable
+410
View File
@@ -0,0 +1,410 @@
#!/usr/bin/env python3
"""stage — 雲端對 **stageyoulin** 寫入的正門(inkstone/ISEP#137
━━ 為什麼有這支 ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
09-07 三條主線工人在雲端對 stage 的寫入全被 Claude Code auto mode 的分類器擋(不是 ISEP 的閘):
① `printf … | npx wrangler secret put CF_SECRETS_API_TOKEN --name arcrun-cypher-executor`
② `python3 scripts/stage-deploy-artifacts.py all --confirm`Arcrun 的成品直推,CF API 上傳)
③ `curl -X POST …arcrun-yuga3bse.workers.dev/records``/graph/canonicalize-entities``/map/recompute`
權限白名單(docs/permissions-allow.json)是**逐條完全比對前綴**:複合指令(`cd … && printf … | VAR=… npx …`
與任意寫法的 curl 永遠對不上任何一條;放整類 `Bash(npx *)``Bash(curl *)` 又是紅線。
leo 09-07:「為什麼會擋你,這就是要修復的問題」「本機環境跟你不同應該不行」。
⇒ 每一種寫入收成**一支固定形狀**,白名單放它的四種呼叫形狀:
`stage secret …` ①(打 api.cloudflare.com,不經 npx——雲端每次要重抓 wrangler
而且 wrangler 會讀 ~/.wrangler 的登入態:本機是 uncle6、雲端沒有,兩台行為不同)
`stage api …` ③(用 curl 打 stage 實例;youlin 邊緣對 python-urllib UA 回 403 code 1010
Arcrun#176 comment 6487——所以這一段**不用 urllib**
② = Arcrun 自己那支已經寫死只認 youlin 帳號 ID、憑證只從
CLOUDFLARE_API_TOKEN_YOULIN_CC_USE 讀、不收 --account--token
白名單直接放它的形狀(`python3 scripts/stage-deploy-artifacts.py *`),不重造一支。
━━ 只寫 stage,判準是唯一識別碼往放行方向比對,不是名字 ━━━━━━━━━━━━━━━━━━━━━━
stage 隨便炸;出貨機(geek6688uncle6)與 leo 的實例(leo21c)不是。
secret:這把 token 打得到的帳號(GET /accounts 現查)裡要有 1129efd7df2e8899d537e9c8fbabb6cb
而且寫入的 URL 永遠只帶這個 ID。打不到 ⇒ 拒絕、印出它打得到誰、離開碼 2。
api URL 只會長在 `<worker>.arcrun-yuga3bse.workers.dev`09-02 重裝後的 stage 子網域)。
給完整網址時主機必須等於它,否則拒絕、離開碼 2——不管那個主機叫 leo21c 還是別的什麼。
不看變數名字裡有沒有 `leo21c`/`geek6688`——名字改了黑名單就漏,ID 與主機改不了。
━━ 值不進指令列 ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
secret 的值、Bearer、任何標頭值都只從**環境變數名**讀(--from-env--bearer-env--header-env);
不落磁碟、不 echo、不進 git、不進 shell 歷史。curl 的標頭與 body 走 stdin 設定檔+管線,不走 argv。
━━ 用法 ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
stage secret put --worker <script> --secret <NAME> --from-env <VAR> [--token-env VAR] [--account ID]
stage secret list --worker <script>
stage secret delete --worker <script> --secret <NAME>
--token-env <VAR> CF token 的環境變數名(預設 CLOUDFLARE_API_TOKEN_YOULIN_CC_USE,雲端就有)
--account <ID> 目標帳號(預設 stage;給別的 ID 一律拒絕、不打網路)
stage api <METHOD> <worker>/<path>[?query] [--json '<body>' | --data-env <VAR> | --data-file <檔>]
[--bearer-env <VAR>] [--header-env <Name>=<VAR>]…
<worker>/<path> 例 arcrun-kbdb/records、arcrun-cypher-executor/webhooks/named/yuga3bse/x/trigger
也收完整網址,但主機必須是 *.arcrun-yuga3bse.workers.dev
--bearer-env VAR Authorization: Bearer <VAR 的值>stage KBDB 的 POST 要 KBDB_INTERNAL_TOKEN
--header-env N=VAR 任一標頭,值從環境變數讀(例 X-Arcrun-API-Key=ARCRUN_NS_YOULIN
body 有給就自動帶 Content-Type: application/json
印 `HTTP <code>` 回應;2xx 離開碼 0,其餘 1;curl 連不上印它的錯誤字串(不記成 000)
例(雲端):
python3 "$CLAUDE_PLUGIN_ROOT/scripts/stage" secret put --worker arcrun-cypher-executor \\
--secret CF_SECRETS_API_TOKEN --from-env CF_SECRETS_API_TOKEN_VALUE
python3 "$CLAUDE_PLUGIN_ROOT/scripts/stage" api POST 'arcrun-kbdb/map/recompute?library=rt-lib&owner_id=yuga3bse' \\
--bearer-env KBDB_INTERNAL_TOKEN
離開碼:0 成功 / 2 被本工具拒絕(非 stage、缺變數、值在指令列)/ 1 API・網路失敗
測試用:STAGE_SECRET_PUT_API_BASECF API)、STAGE_API_BASE_OVERRIDE(實例)指到假伺服器——scripts/test-stage.sh
"""
import json
import os
import subprocess
import sys
import urllib.error
import urllib.parse
import urllib.request
STAGE_ACCOUNT_ID = "1129efd7df2e8899d537e9c8fbabb6cb" # youlinD37 定的 stage 帳號)
STAGE_LABEL = "youlinstage"
STAGE_HOST_SUFFIX = ".arcrun-yuga3bse.workers.dev" # 09-02 重裝後的 stage 子網域(ISEP#130
DEFAULT_TOKEN_ENV = "CLOUDFLARE_API_TOKEN_YOULIN_CC_USE"
CF_API_BASE = os.environ.get("STAGE_SECRET_PUT_API_BASE", "https://api.cloudflare.com/client/v4").rstrip("/")
API_BASE_OVERRIDE = os.environ.get("STAGE_API_BASE_OVERRIDE", "").rstrip("/") # 測試用:整個實例指到假伺服器
EXIT_OK, EXIT_API, EXIT_REFUSED = 0, 1, 2
FORBIDDEN_VALUE_FLAGS = ("--value", "--text", "--bearer", "--token", "--header")
def die(code, msg):
print(msg, file=sys.stderr)
return code
class Refuse(Exception):
pass
# ───────────────────────── secretCF APIapi.cloudflare.com)─────────────────────────
def parse_secret(argv):
if not argv or argv[0] not in ("put", "list", "delete"):
raise Refuse("secret 後面要接 putlistdelete,不是 %r--help 看用法)" % (argv[:1] or [""])[0])
cmd = argv[0]
o = {"worker": None, "secret": None, "from_env": None, "token_env": DEFAULT_TOKEN_ENV, "account": STAGE_ACCOUNT_ID}
keys = {"--worker": "worker", "--secret": "secret", "--from-env": "from_env", "--token-env": "token_env", "--account": "account"}
i = 1
while i < len(argv):
a = argv[i]
if a in FORBIDDEN_VALUE_FLAGS:
raise Refuse("本工具不收 %s:值只從環境變數名讀(--from-env--token-env),不准出現在指令列" % a)
if a not in keys:
raise Refuse("不認得的參數:%s--help 看用法)" % a)
if i + 1 >= len(argv):
raise Refuse("%s 後面要接一個值" % a)
o[keys[a]] = argv[i + 1]
i += 2
if not o["worker"]:
raise Refuse("缺 --worker <script 名>")
if cmd in ("put", "delete") and not o["secret"]:
raise Refuse("缺 --secret <SECRET 名>")
if cmd == "put" and not o["from_env"]:
raise Refuse("缺 --from-env <環境變數名>(值只從這裡讀)")
return cmd, o
def cf(method, path, token, body=None):
"""回 (http_status, parsed_json);網路層失敗回 (None, 錯誤字串)——不把三種病都記成 000。"""
data = None
headers = {"Authorization": "Bearer " + token, "User-Agent": "isep-stage/1 (+inkstone/ISEP#137)"}
if body is not None:
data = json.dumps(body).encode("utf-8")
headers["Content-Type"] = "application/json"
req = urllib.request.Request(CF_API_BASE + path, data=data, headers=headers, method=method)
try:
with urllib.request.urlopen(req, timeout=60) as resp:
return resp.status, json.loads(resp.read().decode("utf-8") or "{}")
except urllib.error.HTTPError as e:
try:
return e.code, json.loads(e.read().decode("utf-8") or "{}")
except Exception:
return e.code, {"success": False, "errors": [{"message": "HTTP %d(非 JSON 回應)" % e.code}]}
except Exception as e:
return None, "%s: %s" % (type(e).__name__, e)
def cf_ok(status, d):
# CF 對「建立」回 201secret PUT 實測就是 201inkstone/ISEP#137 第一次實跑抓到的)——2xx + success 才算好
return status is not None and 200 <= status < 300 and isinstance(d, dict) and bool(d.get("success"))
def cf_errors(d):
if isinstance(d, dict):
errs = d.get("errors") or []
return "".join("%scode %s" % (e.get("message"), e.get("code")) for e in errs) or "CF 沒給錯誤訊息)"
return str(d)
def refuse_account(given):
return die(EXIT_REFUSED, "\n".join([
"🛑 本工具只種 stage,不種 %s。" % given,
"",
" stage %s,帳號 ID %s" % (STAGE_LABEL, STAGE_ACCOUNT_ID),
" 你給的 %s" % given,
"",
"【為什麼】stage 隨便炸;出貨機(geek6688uncle6)與 leo 的實例(leo21c)不是(inkstone/ISEP#137)。",
"【出路】要種進那兩類帳號 ⇒ 交回地端,由 leo 親手在 Mac 上 `wrangler secret put`",
" 雲端這支不會、也不該會。要種 stage ⇒ 把 --account 拿掉(預設就是 stage)。",
]))
def check_token_reaches_stage(token, token_env):
status, d = cf("GET", "/accounts", token)
if status is None:
return die(EXIT_API, "🔴 連不到 CF API%s):%s\n 雲端看到這個先查 `curl -sS \"$HTTPS_PROXY/__agentproxy/status\"`policy 拒絕 vs DNS vs 對方沒回,三種修法不同)。" % (CF_API_BASE, d))
if not cf_ok(status, d):
return die(EXIT_API, "🔴 CF 不認這把 token%sHTTP %s):%s" % (token_env, status, cf_errors(d)))
accounts = [(a.get("id"), a.get("name")) for a in (d.get("result") or []) if isinstance(a, dict)]
if STAGE_ACCOUNT_ID not in [i for i, _ in accounts]:
reach = "\n".join(" · %s %s" % (i, n) for i, n in accounts) or " ·(一個都沒有)"
return die(EXIT_REFUSED, "\n".join([
"🛑 這把 token%s)打不到 stage,拒絕。" % token_env,
"",
" stage %s,帳號 ID %s" % (STAGE_LABEL, STAGE_ACCOUNT_ID),
" 這把 token 打得到的帳號:",
reach,
"",
"【為什麼】本工具只種 stage;token 是誰的就會種進誰的帳號,所以先問 CF 它打得到誰(inkstone/ISEP#137)。",
"【出路】用 stage 的那把:--token-env %s(雲端 Cloud environment 就有,本機在頂層 .env)。" % DEFAULT_TOKEN_ENV,
" 真要種出貨機/leo21c ⇒ 交回地端由 leo 親手做。",
]))
return None
def list_names(token, account, worker):
status, d = cf("GET", "/accounts/%s/workers/scripts/%s/secrets" % (account, worker), token)
if status is None:
return None, "連不到 CF API%s):%s" % (CF_API_BASE, d)
if not cf_ok(status, d):
return None, "列 secrets 失敗(HTTP %s):%s" % (status, cf_errors(d))
return sorted(s.get("name") for s in (d.get("result") or []) if isinstance(s, dict) and s.get("name")), None
def run_secret(argv):
try:
cmd, o = parse_secret(argv)
except Refuse as e:
return die(EXIT_REFUSED, "🛑 %s" % e)
if o["account"] != STAGE_ACCOUNT_ID:
return refuse_account(o["account"])
token = os.environ.get(o["token_env"], "")
if not token:
return die(EXIT_REFUSED, "🛑 環境變數 %s 沒有值(CF token)。\n【出路】雲端:Cloud environment 要有它(scripts/make-cloud-env.sh 的清單裡就有);本機:從頂層 .env 匯出。" % o["token_env"])
value = None
if cmd == "put":
value = os.environ.get(o["from_env"], "")
if not value:
return die(EXIT_REFUSED, "🛑 環境變數 %s 沒有值(要種進去的 secret 本身)。\n【出路】把值放進這個環境變數再跑;不要改成把值寫在指令列——那是紅線(值不落磁碟、不進指令歷史)。" % o["from_env"])
rc = check_token_reaches_stage(token, o["token_env"])
if rc is not None:
return rc
acct, worker = o["account"], o["worker"]
if cmd == "list":
names, err = list_names(token, acct, worker)
if err:
return die(EXIT_API, "🔴 %s" % err)
print("✅ %s@%s 現有 %d 把 secret%s" % (worker, STAGE_LABEL, len(names), "、".join(names) or "(沒有)"))
return EXIT_OK
if cmd == "delete":
status, d = cf("DELETE", "/accounts/%s/workers/scripts/%s/secrets/%s" % (acct, worker, o["secret"]), token)
if status is None:
return die(EXIT_API, "🔴 連不到 CF API%s" % d)
if not cf_ok(status, d):
return die(EXIT_API, "🔴 刪 %s 失敗(HTTP %s):%s" % (o["secret"], status, cf_errors(d)))
names, err = list_names(token, acct, worker)
if err:
return die(EXIT_API, "🔴 刪了但列不出來確認:%s" % err)
if o["secret"] in names:
return die(EXIT_API, "🔴 CF 說刪了,列表卻還有 %s" % o["secret"])
print("✅ 已刪 %s ← %s@%s;剩 %d 把:%s" % (o["secret"], worker, STAGE_LABEL, len(names), "、".join(names) or "(沒有)"))
return EXIT_OK
body = {"name": o["secret"], "text": value, "type": "secret_text"}
status, d = cf("PUT", "/accounts/%s/workers/scripts/%s/secrets" % (acct, worker), token, body)
del value, body
if status is None:
return die(EXIT_API, "🔴 連不到 CF API%s" % d)
if not cf_ok(status, d):
return die(EXIT_API, "🔴 種 %s → %s 失敗(HTTP %s):%s" % (o["secret"], worker, status, cf_errors(d)))
names, err = list_names(token, acct, worker)
if err:
return die(EXIT_API, "🔴 CF 說種好了,但列不出來確認:%s" % err)
if o["secret"] not in names:
return die(EXIT_API, "🔴 CF 說種好了,列表卻沒有 %s(有的是:%s" % (o["secret"], "、".join(names)))
print("✅ 已種 %s → %s@%s(值來自環境變數 %s,沒印、沒落地)" % (o["secret"], worker, STAGE_LABEL, o["from_env"]))
print(" 現有 %d 把:%s" % (len(names), "、".join(names)))
return EXIT_OK
# ───────────────────────── api(curl 打 stage 實例)─────────────────────────
def parse_api(argv):
if len(argv) < 2:
raise Refuse("api 後面要接 <METHOD> <worker>/<path>--help 看用法)")
method, target = argv[0].upper(), argv[1]
if method not in ("GET", "POST", "PUT", "PATCH", "DELETE"):
raise Refuse("METHOD 要是 GETPOSTPUTPATCHDELETE,不是 %r" % argv[0])
o = {"json": None, "data_env": None, "data_file": None, "bearer_env": None, "header_envs": []}
i = 2
while i < len(argv):
a = argv[i]
if a in FORBIDDEN_VALUE_FLAGS:
raise Refuse("本工具不收 %s:標頭值只從環境變數名讀(--bearer-env--header-env Name=VAR),不准出現在指令列" % a)
if i + 1 >= len(argv):
raise Refuse("%s 後面要接一個值" % a)
v = argv[i + 1]
if a == "--json":
o["json"] = v
elif a == "--data-env":
o["data_env"] = v
elif a == "--data-file":
o["data_file"] = v
elif a == "--bearer-env":
o["bearer_env"] = v
elif a == "--header-env":
if "=" not in v:
raise Refuse("--header-env 的形狀是 Name=VAR(例 X-Arcrun-API-Key=ARCRUN_NS_YOULIN),不是 %r" % v)
o["header_envs"].append(tuple(v.split("=", 1)))
else:
raise Refuse("不認得的參數:%s--help 看用法)" % a)
i += 2
if sum(1 for k in ("json", "data_env", "data_file") if o[k]) > 1:
raise Refuse("--json--data-env--data-file 只能給一個")
return method, target, o
def stage_url(target):
"""把 <worker>/<path> 或完整網址變成 stage 的網址;主機不是 stage 就拒絕。"""
if "://" in target:
u = urllib.parse.urlsplit(target)
host = (u.hostname or "").lower()
if not host.endswith(STAGE_HOST_SUFFIX) or host == STAGE_HOST_SUFFIX.lstrip("."):
raise Refuse("\n".join([
"本工具只打 stage,不打 %s。" % host,
"",
" stage %s,主機一律是 <worker>%s" % (STAGE_LABEL, STAGE_HOST_SUFFIX),
" 你給的 %s" % target,
"",
"【為什麼】stage 隨便炸;leo21c 是 leo 本人在用的實例、geek6688uncle6 是出貨機(inkstone/ISEP#137)。",
"【出路】打 stage ⇒ 寫成 <worker>/<path>(例 arcrun-kbdb/records),主機由本工具補。",
" 對 leo21c 唯讀查詢 ⇒ 直接 curl GETleo21c-write-guard 放行讀);要寫 ⇒ 交回地端由 leo 親手做。",
]))
if API_BASE_OVERRIDE:
return API_BASE_OVERRIDE + "/" + host.split(".")[0] + (u.path or "/") + ("?" + u.query if u.query else "")
return urllib.parse.urlunsplit(("https", host, u.path or "/", u.query, ""))
if "/" not in target:
raise Refuse("目標要寫成 <worker>/<path>(例 arcrun-kbdb/records),不是 %r" % target)
worker, rest = target.split("/", 1)
if not worker or any(c in worker for c in ".:@ "):
raise Refuse("<worker> 只能是 worker 名(例 arcrun-kbdb),不是 %r" % worker)
if API_BASE_OVERRIDE:
return API_BASE_OVERRIDE + "/" + worker + "/" + rest
return "https://" + worker + STAGE_HOST_SUFFIX + "/" + rest
def curl_quote(s):
return '"' + s.replace("\\", "\\\\").replace('"', '\\"').replace("\n", "\\n").replace("\t", "\\t") + '"'
def run_api(argv):
try:
method, target, o = parse_api(argv)
url = stage_url(target)
except Refuse as e:
return die(EXIT_REFUSED, "🛑 %s" % e)
headers = []
if o["bearer_env"]:
v = os.environ.get(o["bearer_env"], "")
if not v:
return die(EXIT_REFUSED, "🛑 環境變數 %s 沒有值(Bearer)。\n【出路】把值放進這個環境變數再跑;不要改成寫在指令列。" % o["bearer_env"])
headers.append("Authorization: Bearer " + v)
for name, var in o["header_envs"]:
v = os.environ.get(var, "")
if not v:
return die(EXIT_REFUSED, "🛑 環境變數 %s 沒有值(標頭 %s)。" % (var, name))
headers.append(name + ": " + v)
body = None
if o["json"] is not None:
body = o["json"]
elif o["data_env"]:
body = os.environ.get(o["data_env"], "")
if not body:
return die(EXIT_REFUSED, "🛑 環境變數 %s 沒有值(body)。" % o["data_env"])
elif o["data_file"]:
try:
with open(o["data_file"], encoding="utf-8") as f:
body = f.read()
except OSError as e:
return die(EXIT_REFUSED, "🛑 讀不了 --data-file %s%s" % (o["data_file"], e))
if body is not None:
headers.append("Content-Type: application/json")
# 標頭與 body 都不走 argv:設定檔從 stdin 進,body 從一條管線(/dev/fd/N)進
rfd, wfd = os.pipe()
cfg = ["url = " + curl_quote(url), "request = " + curl_quote(method), "silent", "show-error",
"write-out = " + curl_quote("\\n__STAGE_HTTP__%{http_code}"), "max-time = 120",
"user-agent = " + curl_quote("isep-stage/1 (+inkstone/ISEP#137)")]
for h in headers:
cfg.append("header = " + curl_quote(h))
if body is not None:
cfg.append("data-binary = " + curl_quote("@/dev/fd/%d" % rfd))
try:
p = subprocess.Popen(["curl", "--config", "-"], stdin=subprocess.PIPE, stdout=subprocess.PIPE,
stderr=subprocess.PIPE, pass_fds=(rfd,) if body is not None else ())
except FileNotFoundError:
os.close(rfd); os.close(wfd)
return die(EXIT_API, "🔴 這台沒有 curl。")
os.close(rfd)
if body is not None:
with os.fdopen(wfd, "w", encoding="utf-8") as w:
w.write(body)
else:
os.close(wfd)
out, err = p.communicate(("\n".join(cfg) + "\n").encode("utf-8"))
del headers, cfg
text = out.decode("utf-8", "replace")
if p.returncode != 0:
return die(EXIT_API, "🔴 curl 失敗(離開碼 %d):%s\n 雲端 403 CONNECT ⇒ `curl -sS \"$HTTPS_PROXY/__agentproxy/status\"`policy);`error code: 1010` ⇒ youlin 邊緣擋 UA。"
% (p.returncode, err.decode("utf-8", "replace").strip()))
resp, _, code = text.rpartition("\n__STAGE_HTTP__")
code = code.strip() or "000"
try:
pretty = json.dumps(json.loads(resp), ensure_ascii=False, indent=2) if resp.strip() else ""
except ValueError:
pretty = resp
print("HTTP %s %s %s" % (code, method, url))
if pretty:
print(pretty)
return EXIT_OK if code.isdigit() and 200 <= int(code) < 300 else EXIT_API
# ───────────────────────── 入口 ─────────────────────────
def main(argv):
if not argv or argv[0] in ("-h", "--help"):
print(__doc__)
return EXIT_OK
if argv[0] == "secret":
return run_secret(argv[1:])
if argv[0] == "api":
return run_api(argv[1:])
return die(EXIT_REFUSED, "🛑 第一個參數要是 secretapi,不是 %r--help 看用法)" % argv[0])
if __name__ == "__main__":
sys.exit(main(sys.argv[1:]))
+1 -1
View File
@@ -22,7 +22,7 @@ run(){ # 跑 list(或任何子命令),輸出留在 $OUT,離開碼留在
# 🔴 ISEP_COUNTDOWN_STATE_DIR 也要指到暫存目錄:主線(hooks/lib/mainline.py)住在那裡, # 🔴 ISEP_COUNTDOWN_STATE_DIR 也要指到暫存目錄:主線(hooks/lib/mainline.py)住在那裡,
# 不隔離的話這支測試的結果會取決於「這台機器現在標了哪條主線」——那就不是測試了。 # 不隔離的話這支測試的結果會取決於「這台機器現在標了哪條主線」——那就不是測試了。
OUT=$(ISEP_DEBT_FIXTURE="$FX" ISEP_DEBT_STATE_DIR="$T/state" ISEP_DEBT_NOW="$NOW" \ OUT=$(ISEP_DEBT_FIXTURE="$FX" ISEP_DEBT_STATE_DIR="$T/state" ISEP_DEBT_NOW="$NOW" \
ISEP_COUNTDOWN_STATE_DIR="$ML_DIR" python3 "$W" "$@" 2>&1); RC=$? ISEP_COUNTDOWN_STATE_DIR="$ML_DIR" ISEP_MAINLINE_REPO_FILE=none python3 "$W" "$@" 2>&1); RC=$?
} }
ML_DIR="$T/mainline"; mkdir -p "$ML_DIR" ML_DIR="$T/mainline"; mkdir -p "$ML_DIR"
+37
View File
@@ -34,6 +34,43 @@ run 0 'python3 -c "requests.post(url, json={\"body\": \"quoting: git push origin
run 0 'grep -n "gh api" hooks/github-contact-guard.sh' run 0 'grep -n "gh api" hooks/github-contact-guard.sh'
run 0 'grep -rn "git push" installer/scripts/line-source-repo.mjs' run 0 'grep -rn "git push" installer/scripts/line-source-repo.mjs'
echo "── 判「push 到哪」要看這條指令實際會推的那個 repo,不是 hook 站的 cwdinkstone/ISEP#109 → comment 66292026-09-07 實撞)──"
# 為什麼這群非有不可:雲端薄殼的 cwd 是 GitHub 那份(origingithub.com),而總管在
# `InkStoneCo/`originGitea)推分支。舊版拿 **hook 收到的 cwd** 去解 `origin`
# 於是 `git -C <InkStoneCo> push origin x` 被判成「remote origin 指向 GitHub」擋下
# ——連 `-C` 都沒看。arcrun-hand 同日在 Arcrun#176 comment 6614 撞到同一支。
# 判準仍是唯一識別碼(remote 解出來的 URL 主機),不是名字;**不是「有 -C 就放行」**——
# 下面「該擋」那組就是 -C/cd 指到 GitHub 那份時照擋的證據。
W=$(mktemp -d "${TMPDIR:-/tmp}/isep-ghc.XXXXXX"); trap 'rm -rf "$W"' EXIT
W=$(cd "$W" && pwd -P)
mk(){ git init -q -b main "$1" && git -C "$1" remote add origin "$2"; }
mk "$W/shell" https://github.com/example/shell.git # 薄殼:originGitHub
mk "$W/body" https://git.example.invalid/inkstone/body.git # 真身:originGitea 的形狀(主機不是 github.com
mkdir -p "$W/body/sub"
runc(){ # $1=want $2=cwd $3=cmd —— 跟 run 一樣,只是 payload 帶 cwd(hook 真的會收到它)
LAST_ERR=$(printf '%s' "{\"tool_name\":\"Bash\",\"cwd\":$(python3 -c 'import json,sys;print(json.dumps(sys.argv[1]))' "$2"),\"tool_input\":{\"command\":$(python3 -c 'import json,sys;print(json.dumps(sys.argv[1]))' "$3")}}" \
| bash "$H" 2>&1 >/dev/null)
got=$?
if [ "$got" = "$1" ]; then PASS=$((PASS+1)); printf ' ✅ '; else FAIL=$((FAIL+1)); printf ' ❌ '; fi
printf 'want=%s got=%s cwd=%s %.60s\n' "$1" "$got" "${2#$W/}" "$3"
}
has(){ if printf '%s' "$LAST_ERR" | grep -qF -- "$1"; then PASS=$((PASS+1)); printf ' ✅ '; else FAIL=$((FAIL+1)); printf ' ❌ '; fi; printf '%s\n' "$2"; }
echo " · 該擋:這條指令實際推的那個 repo 的 origin 是 github.com"
runc 2 "$W/shell" 'git push origin x'
runc 2 "$W/body" "git -C $W/shell push origin x"
has "$W/shell" " 訊息說得出是哪個目錄的 remote 指向 GitHub(人才知道自己站錯地方還是推錯地方)"
runc 2 "$W/body" "cd $W/shell && git push origin x"
runc 2 "$W/shell" "(cd $W/body && true); git push origin x"
runc 2 "$W/shell" 'cd $SOMEWHERE && git push origin x'
echo " · 不該擋:這條指令實際推的那個 repo 的 origin 不是 github.com(★=6629 那天被擋的形狀)"
runc 0 "$W/shell" "git -C $W/body push origin x"
runc 0 "$W/shell" "git -C $W/body push -u origin feat/x"
runc 0 "$W/shell" "cd $W/body && git push origin x"
runc 0 "$W/body/sub" 'git push origin x'
runc 0 "$W/shell" "cd $W && git -C body push origin x"
runc 0 "$W/body" "(cd $W/shell && true); git push origin x"
echo echo
echo "$PASS/$((PASS+FAIL)) 通過" echo "$PASS/$((PASS+FAIL)) 通過"
[ "$FAIL" -eq 0 ] [ "$FAIL" -eq 0 ]
+80
View File
@@ -0,0 +1,80 @@
#!/bin/bash
# isep-notify 的「Bot API 直送」測試(inkstone/ISEP#130
#
# 它守什麼: 雲端唯一走得通的通知路。2026-09-07 從雲端實測:leo21c 的 notify_leo 回 404、
# youlin 被 egress proxy 擋(403 policy denial)、api.telegram.org 通。
# ⇒ 有 TELEGRAM_BOT_TOKENTELEGRAM_CHAT_ID 就先直送;沒有要講清楚缺哪兩個,不能靜默。
#
# 🔴 全程不打真 Telegram:Bot API 指到本機一個假伺服器(只回固定 JSON),
# 實例那條用 ISEP_NOTIFY_OFFLINE=1 關掉、閘用 ISEP_NOTIFY_GUARD 指到真跡。
cd "$(dirname "$0")/.." || exit 1
N=scripts/isep-notify
TMP=$(mktemp -d); trap 'rm -rf "$TMP"; [ -n "${SRV:-}" ] && kill "$SRV" 2>/dev/null' EXIT
export ISEP_NOTIFY_STATE_DIR="$TMP/state" ISEP_NOTIFY_GUARD="$PWD/hooks/prod-write-guard.sh"
unset TELEGRAM_BOT_TOKEN TELEGRAM_CHAT_ID
PASS=0; FAIL=0
ok(){ PASS=$((PASS+1)); printf ' ✅ %s\n' "$1"; }
bad(){ FAIL=$((FAIL+1)); printf ' ❌ %s\n' "$1"; }
# 假 Bot API:記下收到什麼,回 Telegram 的形狀
cat > "$TMP/srv.py" <<'PY'
import json, sys
from http.server import BaseHTTPRequestHandler, HTTPServer
LOG = sys.argv[2]
class H(BaseHTTPRequestHandler):
def do_POST(self):
body = self.rfile.read(int(self.headers.get("Content-Length") or 0)).decode()
open(LOG, "a").write(json.dumps({"path": self.path, "body": body, "ua": self.headers.get("User-Agent")}) + "\n")
ok = "/botGOOD/" in self.path
out = json.dumps({"ok": True, "result": {"message_id": 42}} if ok else {"ok": False, "description": "Unauthorized"}).encode()
self.send_response(200 if ok else 401); self.send_header("Content-Type", "application/json"); self.end_headers(); self.wfile.write(out)
def log_message(self, *a): pass
HTTPServer(("127.0.0.1", int(sys.argv[1])), H).serve_forever()
PY
PORT=$(python3 -c 'import socket;s=socket.socket();s.bind(("127.0.0.1",0));print(s.getsockname()[1])')
python3 "$TMP/srv.py" "$PORT" "$TMP/log" & SRV=$!
for i in 1 2 3 4 5 6 7 8 9 10; do curl -s -o /dev/null "http://127.0.0.1:$PORT/" && break; sleep 0.2; done
export ISEP_NOTIFY_BOT_API="http://127.0.0.1:$PORT"
echo "── A. 沒有憑證:講清楚缺哪兩個,不靜默 ──"
OUT=$(ISEP_NOTIFY_OFFLINE=1 python3 "$N" --text "測試" 2>&1); RC=$?
printf '%s' "$OUT" | grep -q 'TELEGRAM_BOT_TOKENTELEGRAM_CHAT_ID' && ok "A1 沒憑證 ⇒ 報告點名缺 TELEGRAM_BOT_TOKENTELEGRAM_CHAT_IDleo 看了知道要在 Cloud environment 加什麼)" || bad "A1 沒點名缺什麼:$OUT"
[ "$RC" != 0 ] && printf '%s' "$OUT" | grep -q 'leo 的手機上沒有出現' && ok "A2 兩條路都沒通 ⇒ 離開碼非 0、明說沒送到" || bad "A2 rc=$RC$OUT"
[ ! -s "$TMP/log" ] && ok "A3 沒憑證就不打 Bot API" || bad "A3 沒憑證還打了:$(cat "$TMP/log")"
echo "── B. 有憑證:先直送,送到就結束 ──"
: > "$TMP/log"
OUT=$(TELEGRAM_BOT_TOKEN=GOOD TELEGRAM_CHAT_ID=777 python3 "$N" --text "雲端收工摘要" 2>&1); RC=$?
[ "$RC" = 0 ] && printf '%s' "$OUT" | grep -q 'Bot API 直送):送到了' && ok "B1 憑證在 ⇒ Bot API 直送,離開碼 0" || bad "B1 rc=$RC$OUT"
python3 - "$TMP/log" <<'PY' && ok "B2 打到 /botGOOD/sendMessage、chat_id=777、內文有署名、UA 帶了" || bad "B2 送出去的形狀不對:$(cat "$TMP/log")"
import json, sys
rows = [json.loads(l) for l in open(sys.argv[1])]
assert len(rows) == 1, rows
r = rows[0]; b = json.loads(r["body"])
assert r["path"] == "/botGOOD/sendMessage", r["path"]
assert b["chat_id"] == "777" and b["text"].startswith("[總管] 雲端收工摘要"), b
assert "isep-notify" in (r["ua"] or ""), r["ua"]
PY
printf '%s' "$OUT" | grep -q 'notify_leo' && bad "B3 直送成功後不該再碰實例那條" || ok "B3 直送成功 ⇒ 不再打實例的 notify_leo"
echo "── C. 憑證錯:Bot API 回 ok=false ⇒ 不算送到,退到原本那條 ──"
: > "$TMP/log"
# 實例那條也指到假伺服器(它對非 /botGOOD/ 的路徑回 401)——兩條都不出這台機器
OUT=$(TELEGRAM_BOT_TOKEN=BAD TELEGRAM_CHAT_ID=777 ISEP_NOTIFY_URL="http://127.0.0.1:$PORT/webhooks/named/leo/notify_leo/trigger" python3 "$N" --text "x" 2>&1); RC=$?
printf '%s' "$OUT" | grep -q 'Bot API HTTP 401' && ok "C1 401 被講出來(不是「送出成功」)" || bad "C1 沒講 401$OUT"
[ "$RC" != 0 ] && printf '%s' "$OUT" | grep -q 'leo 的手機上沒有出現' && ok "C2 直送失敗+實例關著 ⇒ 仍然明說沒送到" || bad "C2 rc=$RC$OUT"
echo "── D. 閘說會擋,直送仍走得通(它不碰實例)──"
: > "$TMP/log"; mkdir -p "$TMP/oldguard"
printf '#!/bin/sh\nexit 2\n' > "$TMP/oldguard/prod-write-guard.sh"; chmod +x "$TMP/oldguard/prod-write-guard.sh"
OUT=$(ISEP_NOTIFY_GUARD="$TMP/oldguard/prod-write-guard.sh" TELEGRAM_BOT_TOKEN=GOOD TELEGRAM_CHAT_ID=1 python3 "$N" --text "y" 2>&1); RC=$?
[ "$RC" = 0 ] && printf '%s' "$OUT" | grep -q '通知閘:\*\*block\*\*' && printf '%s' "$OUT" | grep -q '直送):送到了' \
&& ok "D1 閘 block + 憑證在 ⇒ 直送照樣送到(閘擋的是寫實例,直送沒碰實例)" || bad "D1 rc=$RC$OUT"
echo "── E. --dry-run 什麼都不送 ──"
: > "$TMP/log"
OUT=$(TELEGRAM_BOT_TOKEN=GOOD TELEGRAM_CHAT_ID=1 python3 "$N" --text "z" --dry-run 2>&1)
[ ! -s "$TMP/log" ] && printf '%s' "$OUT" | grep -q 'dry-run' && ok "E1 --dry-runBot API 一次都沒被打" || bad "E1 dry-run 打了:$(cat "$TMP/log")"
echo; echo "$PASS/$((PASS+FAIL)) 通過"
[ "$FAIL" -eq 0 ]
+129
View File
@@ -0,0 +1,129 @@
#!/usr/bin/env bash
# scripts/release-check 的迴歸測試(inkstone/ISEP#67
#
# 兩個方向都要有證據:
# A 群「該擋」(exit 2)——現行版本缺 tag 或缺 release,且**說得出缺哪一站+怎麼補**
# (這就是工單驗收 4:「故意漏一步 → 管線要擋下來並說出缺哪一站」)
# B 群「該過」(exit 0)——現行版本 tag+release 都在;更舊版本缺件只黃字提醒不擋;
# 指定版本時看的是那一版;裁定不補的版本不再黃字
#
# 🔴 全程離線(RELEASE_CHECK_FIXTURE),不打 Gitea。fixture 直接給收貨端與送貨端的事實。
set -u
TOOL="${1:-$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)/release-check}"
TMP=$(mktemp -d); trap 'rm -rf "$TMP"' EXIT
PASS=0; FAIL=0; N=0
mkfx() { # $1=檔名 之後 heredoc
cat > "$TMP/$1"
}
# t <期望exit> <說明> <必須出現的字串> <fixture檔> [額外參數…]
t() {
want="$1"; desc="$2"; must="$3"; fx="$4"; shift 4
N=$((N+1))
out=$(RELEASE_CHECK_FIXTURE="$TMP/$fx" python3 "$TOOL" "$@" 2>&1); rc=$?
ok=1
[ "$rc" -eq "$want" ] || ok=0
if [ -n "$must" ] && ! printf '%s' "$out" | grep -qF "$must"; then ok=0; fi
if [ "$ok" -eq 1 ]; then printf ' ✅ %s\n' "$desc"; PASS=$((PASS+1))
else
printf ' ❌ %s —— 期望 exit=%s%s,實得 exit=%s\n' "$desc" "$want" \
"${must:+ 且輸出含「$must}" "$rc"
printf '%s\n' "$out" | sed -n '1,16p' | sed 's/^/ /'; FAIL=$((FAIL+1))
fi
}
# not <說明> <不該出現的字串> <fixture檔> [額外參數…]
not() {
desc="$1"; bad="$2"; fx="$3"; shift 3
N=$((N+1))
out=$(RELEASE_CHECK_FIXTURE="$TMP/$fx" python3 "$TOOL" "$@" 2>&1)
if printf '%s' "$out" | grep -qF "$bad"; then
printf ' ❌ %s —— 不該出現卻出現了:%s\n' "$desc" "$bad"; FAIL=$((FAIL+1))
else printf ' ✅ %s\n' "$desc"; PASS=$((PASS+1)); fi
}
echo "── A 群:該擋(現行版本送貨端斷了,要說出缺哪一站)──"
# A1:這就是 2026-09-07 的真實狀態——v0.24.0 有 tag、沒 release
mkfx a1.json <<'JSON'
{"current":"0.24.0",
"dingban":["0.24.0","0.23.0","0.22.0"],
"tags":["v0.24.0","v0.23.0","v0.22.0"],
"releases":["v0.22.0"],
"loaded":"0.24.0"}
JSON
t 2 "現行 v0.24.0 有 tag 沒 release → 擋,且指名缺 release 站" "缺這一站:releaseGitea" a1.json
t 2 "缺 release 時給得出補法,而且是正本的絕對路徑(貼了就能跑)" "$(dirname "$TOOL")/release-ship v0.24.0" a1.json
# A2:連 tag 都沒有(定版了、tag 沒推)
mkfx a2.json <<'JSON'
{"current":"0.20.0",
"dingban":["0.20.0","0.18.0"],
"tags":["v0.18.0"],
"releases":["v0.18.0"],
"loaded":"0.20.0"}
JSON
t 2 "現行版本連 tag 都沒有 → 擋,且指名缺 tag 站" "缺這一站:tagGitea" a2.json
t 2 "缺 tag 時給得出補法(push tag" "git push origin v0.20.0" a2.json
# A3:指定版本 → 判的是那一版
mkfx a3.json <<'JSON'
{"current":"0.24.0",
"dingban":["0.24.0","0.23.0"],
"tags":["v0.24.0","v0.23.0"],
"releases":["v0.24.0"],
"loaded":"0.24.0"}
JSON
t 2 "指定 v0.23.0 而它沒 release → 擋(就算工作樹宣稱的 v0.24.0 是好的)" "現行版本 v0.23.0 的送貨端斷了" a3.json v0.23.0
t 0 "同一份事實不指定版本 → 看 v0.24.0,放行" "送貨端完成" a3.json
echo "── B 群:該過(現行版本 tagrelease 都在)──"
# B1:全部送到
mkfx b1.json <<'JSON'
{"current":"0.18.0",
"dingban":["0.18.0","0.9.0"],
"tags":["v0.18.0","v0.9.0"],
"releases":["v0.18.0","v0.9.0"],
"loaded":"0.18.0"}
JSON
t 0 "現行版本 tagrelease 都在 → 放行" "送貨端完成" b1.json
# B2:現行版本送到了,但更舊的 定版 版本缺件 → 仍放行,只黃字
mkfx b2.json <<'JSON'
{"current":"0.24.0",
"dingban":["0.24.0","0.23.0","0.22.0"],
"tags":["v0.24.0","v0.22.0"],
"releases":["v0.24.0","v0.22.0"],
"loaded":"0.24.0"}
JSON
t 0 "現行送到、舊版缺件 → 放行(不 over-block" "送貨端完成" b2.json
t 0 "舊版缺件會被黃字提醒出來" "v0.23.0 缺:tagGitea)+releaseGitea" b2.json
# B3:載入端落後(送貨端完成,但這個 session 掛的是舊版)→ 仍 exit 0,但要報出來
mkfx b3.json <<'JSON'
{"current":"0.22.0",
"dingban":["0.22.0","0.18.0"],
"tags":["v0.22.0","v0.18.0"],
"releases":["v0.22.0","v0.18.0"],
"loaded":"0.21.0"}
JSON
t 0 "載入端落後 → 送貨端仍算完成(exit 0)" "送貨端完成" b3.json
t 0 "載入端落後會被明確報出+給 update/重啟的修法" "載入端落後" b3.json
# B4:裁定不補的三版(總管 09-07)→ 不再黃字,表上標「裁定不補」
mkfx b4.json <<'JSON'
{"current":"0.24.0",
"dingban":["0.24.0","0.22.0","0.21.0","0.20.0","0.19.0","0.18.0"],
"tags":["v0.24.0","v0.22.0","v0.18.0"],
"releases":["v0.24.0","v0.22.0","v0.18.0"],
"loaded":"0.24.0"}
JSON
t 0 "v0.190.200.21 缺 tagrelease 但已裁定不補 → 表上標出裁決出處" "裁定不補(inkstone/ISEP#67 → 6574" b4.json
not "裁定不補的版本不再黃字念(天天念會被學會忽略)" "更舊的定版版本也缺件" b4.json
t 2 "但指定 v0.21.0 來問,它就是現行、照擋(裁決只免黃字,不改事實)" "現行版本 v0.21.0 的送貨端斷了" b4.json v0.21.0
echo ""
echo "──────────────────────────────"
printf '共 %d 項:✅ %d ❌ %d\n' "$N" "$PASS" "$FAIL"
[ "$FAIL" -eq 0 ]
+116
View File
@@ -0,0 +1,116 @@
#!/usr/bin/env bash
# scripts/release-ship 的迴歸測試(inkstone/ISEP#67
#
# 兩個方向都要有證據:
# A 群「該擋」(exit 2)——前置條件沒滿足就不給建 release,且說得出是哪一個前置
# ① 那個 tag 的樹裡 plugin.json 跟 tag 號碼對不上 ② Gitea 上沒那個 tag ③ 版本寫法不對
# B 群「該放行」(exit 0)——前置都在就建;release 已存在則冪等不重複建;--dry-run 不 POST
# 🔴 **不是最新的那個 tag 也建得了**(總管 09-07 在 v0.23.0 被擋的那個情境)
#
# 🔴 全程離線(RELEASE_SHIP_FIXTURE RELEASE_SHIP_SINK),不打 Gitea、不建任何真 release。
# fixture 的形狀見 hooks/lib/release_chain.py `Chain` 的註解。
set -u
TOOL="${1:-$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)/release-ship}"
TMP=$(mktemp -d); trap 'rm -rf "$TMP"' EXIT
PASS=0; FAIL=0; N=0
# 🔴 工作樹故意擺一個跟任何 tag 都對不上的版本:前置①要是偷看工作樹,B 群會整組紅
WT="$TMP/worktree"; mkdir -p "$WT/.claude-plugin"
printf '{"name":"isep","version":"9.9.9"}\n' > "$WT/.claude-plugin/plugin.json"
export CLAUDE_PROJECT_DIR="$WT"
# t <期望exit> <說明> <必須出現的字串> <fixture檔> [額外參數…]
t() {
want="$1"; desc="$2"; must="$3"; fx="$4"; shift 4
N=$((N+1))
rm -f "$TMP/sink.json" "$TMP/sink.json.checkfx.json"
out=$(RELEASE_SHIP_FIXTURE="$TMP/$fx" RELEASE_SHIP_SINK="$TMP/sink.json" \
python3 "$TOOL" "$@" 2>&1); rc=$?
ok=1
[ "$rc" -eq "$want" ] || ok=0
if [ -n "$must" ] && ! printf '%s' "$out" | grep -qF "$must"; then ok=0; fi
if [ "$ok" -eq 1 ]; then printf ' ✅ %s\n' "$desc"; PASS=$((PASS+1))
else
printf ' ❌ %s —— 期望 exit=%s%s,實得 exit=%s\n' "$desc" "$want" \
"${must:+ 且輸出含「$must}" "$rc"
printf '%s\n' "$out" | sed -n '1,14p' | sed 's/^/ /'; FAIL=$((FAIL+1))
fi
}
# not <說明> <不該出現的字串> <fixture檔> [額外參數…]
not() {
desc="$1"; bad="$2"; fx="$3"; shift 3
N=$((N+1))
rm -f "$TMP/sink.json" "$TMP/sink.json.checkfx.json"
out=$(RELEASE_SHIP_FIXTURE="$TMP/$fx" RELEASE_SHIP_SINK="$TMP/sink.json" \
python3 "$TOOL" "$@" 2>&1)
if printf '%s' "$out" | grep -qF "$bad"; then
printf ' ❌ %s —— 不該出現卻出現了:%s\n' "$desc" "$bad"; FAIL=$((FAIL+1))
else printf ' ✅ %s\n' "$desc"; PASS=$((PASS+1)); fi
}
echo "── A 群:該擋(前置條件沒滿足)──"
# A1tag 的樹裡 plugin.json 跟 tag 號碼對不上(這種 tag 本來就不該存在)
cat > "$TMP/a1.json" <<'JSON'
{"tags":["v0.22.0"],"manifest":{"v0.22.0":"0.21.0"},"releases":[]}
JSON
t 2 "tag 的樹裡 plugin.json 是 0.21.0、tag 是 v0.22.0 → 擋,指名前置①" "前置①" a1.json v0.22.0
t 2 "前置①被擋時講得出修法(刪 tag、重新定版)" "重新定版" a1.json v0.22.0
# A2Gitea 上沒有這個 tag
cat > "$TMP/a2.json" <<'JSON'
{"tags":["v0.18.0"],"manifest":{"v0.18.0":"0.18.0"},"releases":["v0.18.0"]}
JSON
t 2 "Gitea 沒有該 tag → 擋,指名前置②+叫人先推 tag" "git push origin v0.22.0" a2.json v0.22.0
# A3:版本寫法不對
cat > "$TMP/a3.json" <<'JSON'
{"tags":[],"releases":[]}
JSON
t 2 "版本寫法不對 → 擋" "版本寫法" a3.json "0.22"
echo "── B 群:該放行 ──"
# B1:前置都在、release 還沒建 → 建(fixture sink),然後覆核通過
cat > "$TMP/b1.json" <<'JSON'
{"current":"0.22.0","dingban":["0.22.0","0.18.0"],"loaded":"0.22.0",
"tags":["v0.22.0","v0.18.0"],"manifest":{"v0.22.0":"0.22.0","v0.18.0":"0.18.0"},
"releases":["v0.18.0"],
"commits":{"v0.18.0...v0.22.0":["定版 v0.22.0ship-check 送得到)","修一支閘(inkstone/ISEP#1"]}}
JSON
t 0 "前置齊全、release 缺 → 建起來" "已建立 release「v0.22.0 — ship-check 送得到」" b1.json v0.22.0
t 0 "建完回頭跑 release-check 覆核(問收貨端)" "覆核(release-check v0.22.0" b1.json v0.22.0
t 0 "note 自動從 Gitea 的 commit 清單生成(不靠本機 git log" "commit 清單自動生成" b1.json v0.22.0
# B2:release 已存在 → 冪等,不重複建、不動它
cat > "$TMP/b2.json" <<'JSON'
{"current":"0.18.0","dingban":["0.18.0"],"loaded":"0.18.0",
"tags":["v0.18.0"],"manifest":{"v0.18.0":"0.18.0"},"releases":["v0.18.0"]}
JSON
t 0 "release 已存在 → 冪等放行、不重複建" "本來就在了" b2.json v0.18.0 --notes-file "$TMP/b2.json"
not "release 已存在時不准說「已建立」(09-05 那句假綠)" "已建立 release" b2.json v0.18.0
# B3--dry-run 不 POST
cat > "$TMP/b3.json" <<'JSON'
{"tags":["v0.22.0"],"manifest":{"v0.22.0":"0.22.0"},"releases":[]}
JSON
t 0 "--dry-run 全走一遍但不 POST" "不 POST" b3.json v0.22.0 --dry-run
not "--dry-run 不寫 sink(真的沒建)" "fixture-created" b3.json v0.22.0 --dry-run
# B4:🔴 不是最新的 tag 也建得了(總管 09-07:在 v0.23.0 的 checkout 跑被擋,訊息說最新是 v0.24.0)
cat > "$TMP/b4.json" <<'JSON'
{"current":"0.24.0","dingban":["0.24.0","0.23.0","0.22.0"],"loaded":"0.24.0",
"tags":["v0.24.0","v0.23.0","v0.22.0"],
"manifest":{"v0.24.0":"0.24.0","v0.23.0":"0.23.0","v0.22.0":"0.22.0"},
"releases":["v0.22.0"],
"commits":{"v0.22.0...v0.23.0":["定版 v0.23.0(雲端拿得到票與主線)"]}}
JSON
t 0 "最新 tag 是 v0.24.0,要建的是 v0.23.0 → 照建(前置①看 tag 的樹,不看「最新」)" \
"已建立 release「v0.23.0 — 雲端拿得到票與主線」" b4.json v0.23.0
t 0 "覆核的是 v0.23.0 這一版,不是工作樹宣稱的 0.24.0" "v0.23.0 ✅ ✅ ✅ ←" b4.json v0.23.0
not "工作樹 plugin.json 是 9.9.9 也不會被拿來比(B 群全綠就是證據,這條釘住訊息)" "9.9.9" b4.json v0.23.0
echo ""
echo "──────────────────────────────"
printf '共 %d 項:✅ %d ❌ %d\n' "$N" "$PASS" "$FAIL"
[ "$FAIL" -eq 0 ]
+97
View File
@@ -0,0 +1,97 @@
#!/bin/bash
# settings-allow-sync 的測試(inkstone/ISEP#130
#
# 它守什麼: 「雲端 session 開工時就帶著跟本機同一份權限白名單」這件事的機器那一半。
# leo 09-07 親手加的四條只在本機 InkStoneCo/.claude/settings.json;雲端沒有 ⇒ 同樣動作被分類器擋
# 09-04 run logpermission_denials=6)。清單改住 ISEP 一份,本支把它寫進那台機器的 ~/.claude/settings.json。
#
# 🔴 全程在 TMP 底下的假 settings.json 上跑,不碰真的 ~/.claude/settings.json。
cd "$(dirname "$0")/.." || exit 1
S=scripts/settings-allow-sync
LIST=docs/permissions-allow.json
TMP=$(mktemp -d); trap 'rm -rf "$TMP"' EXIT
PASS=0; FAIL=0
ok(){ PASS=$((PASS+1)); printf ' ✅ %s\n' "$1"; }
bad(){ FAIL=$((FAIL+1)); printf ' ❌ %s\n' "$1"; }
N=$(python3 -c "import json;print(len(json.load(open('$LIST'))['allow']))")
echo "── A. 清單本身的形狀 ──"
python3 - "$LIST" <<'PY' && ok "A1 每一條都是 Bash(…) 形狀,而且六個正門工具都在場(ticketmainlinegate-okgitea-pr-mergestageArcrun 的 stage-deploy-artifacts.py" || bad "A1 清單形狀不對或少了正門工具"
import json, sys
rules = json.load(open(sys.argv[1]))["allow"]
assert rules and all(r.startswith("Bash(") and r.endswith(")") for r in rules), rules
for tool in ("scripts/ticket", "scripts/mainline", "scripts/gate-ok", "scripts/gitea-pr-merge.sh", "scripts/stage ", "scripts/stage-deploy-artifacts.py"):
assert any(tool in r for r in rules), "缺 " + tool
assert not any(r.strip() in ("Bash(python3 *)", "Bash(*)", "Bash(bash *)") for r in rules), "整類放行"
PY
echo "── B. 寫進去(假的 settings.json)──"
T="$TMP/a/settings.json"
OUT=$(python3 "$S" --target "$T" --home /root 2>&1); RC=$?
[ "$RC" = 0 ] && [ -f "$T" ] && ok "B1 目標不存在 ⇒ 建出來(離開碼 0)" || bad "B1 rc=$RC$OUT"
python3 -c "import json;d=json.load(open('$T'));assert len(d['permissions']['allow'])==$N" && ok "B2 寫進 $N 條,JSON 合法" || bad "B2 條數不對或不是 JSON"
grep -q 'Bash(python3 /root/.claude/plugins/cache/inkstone/isep/\*/scripts/ticket \*)' "$T" \
&& ok "B3 開頭的 ~ 換成了 --home 給的家目錄(雲端=/root" || bad "B3 ~ 沒換成家目錄"
grep -q '"~/' "$T" && bad "B4 檔裡還留著 ~" || ok "B4 檔裡沒有殘留的 ~"
grep -q 'CLAUDE_PLUGIN_ROOT' "$T" && ok "B5 \$CLAUDE_PLUGIN_ROOT 那幾條原樣保留(閘印出來的逃生門就是這個形狀)" || bad "B5 少了 \$CLAUDE_PLUGIN_ROOT 形狀"
tail -c1 "$T" | od -An -c | grep -q '\\n' && ok "B6 收尾有換行" || bad "B6 沒換行"
SUM1=$(cksum < "$T"); OUT=$(python3 "$S" --target "$T" --home /root 2>&1); SUM2=$(cksum < "$T")
[ "$SUM1" = "$SUM2" ] && printf '%s' "$OUT" | grep -q '已齊' && ok "B7 跑第二次:檔案一個位元組都沒變、說「已齊」(冪等)" || bad "B7 不冪等:$OUT"
echo "── C. 只加不減:別人手加的東西一個字不動 ──"
T2="$TMP/b/settings.json"; mkdir -p "$TMP/b"
cat > "$T2" <<'JSON'
{
"extraKnownMarketplaces": {"inkstone": {"source": {"source": "git", "url": "https://git.uncle6.me/inkstone/ISEP.git"}}},
"enabledPlugins": {"isep@inkstone": true},
"permissions": {
"allow": ["Bash(npx wrangler secret:*)", "Bash(python3 scripts/ticket *)"],
"deny": ["Edit(//Users/x/wrangler.toml)"]
},
"hooks": {"PreToolUse": []}
}
JSON
OUT=$(python3 "$S" --target "$T2" --home /Users/youlinhsieh 2>&1)
python3 - "$T2" "$N" <<'PY' && ok "C1 原有的 allowdenymarketplacehooks 全在,原本那條沒重複,只補了缺的" || bad "C1 動到了別人的東西:$(cat "$T2")"
import json, sys
d = json.load(open(sys.argv[1])); n = int(sys.argv[2])
a = d["permissions"]["allow"]
assert a[0] == "Bash(npx wrangler secret:*)" and a[1] == "Bash(python3 scripts/ticket *)", a[:2]
assert a.count("Bash(python3 scripts/ticket *)") == 1
assert len(a) == 2 + n - 1, (len(a), n)
assert d["permissions"]["deny"] == ["Edit(//Users/x/wrangler.toml)"]
assert d["enabledPlugins"] == {"isep@inkstone": True}
assert d["hooks"] == {"PreToolUse": []}
assert any("/Users/youlinhsieh/.claude/plugins/cache/inkstone/isep/*/scripts/mainline" in x for x in a)
PY
printf '%s' "$OUT" | grep -q "$((N-1))" && ok "C2 印出來的是「+$((N-1)) 條」(缺幾條補幾條)" || bad "C2 計數不對:$OUT"
echo "── D. --check--dry-run ──"
python3 "$S" --target "$T" --home /root --check >/dev/null 2>&1 && ok "D1 --check:全齊 ⇒ 離開碼 0" || bad "D1 --check 全齊卻非 0"
T3="$TMP/c/settings.json"; mkdir -p "$TMP/c"; echo '{}' > "$T3"
python3 "$S" --target "$T3" --home /root --check >/dev/null 2>&1; RC=$?
[ "$RC" = 1 ] && ok "D2 --check:缺 ⇒ 離開碼 1(驗收用)" || bad "D2 --check 缺卻回 $RC"
[ "$(cat "$T3")" = "{}" ] && ok "D3 --check 不寫檔" || bad "D3 --check 寫了檔"
python3 "$S" --target "$T3" --home /root --dry-run >/dev/null 2>&1
[ "$(cat "$T3")" = "{}" ] && ok "D4 --dry-run 不寫檔" || bad "D4 --dry-run 寫了檔"
echo "── E. 壞掉的目標:不碰、不炸(這支掛在 SessionStart)──"
T4="$TMP/d/settings.json"; mkdir -p "$TMP/d"; printf '{ not json' > "$T4"
OUT=$(python3 "$S" --target "$T4" --home /root 2>&1); RC=$?
[ "$RC" = 0 ] && [ "$(cat "$T4")" = "{ not json" ] && printf '%s' "$OUT" | grep -q '沒有動它' \
&& ok "E1 目標不是 JSON ⇒ 原封不動、講出來、離開碼 0" || bad "E1 rc=$RC 內容=$(cat "$T4") out=$OUT"
python3 "$S" --target "$T4" --home /root --check >/dev/null 2>&1; [ $? = 1 ] && ok "E2 同一個檔用 --check 問 ⇒ 離開碼 1(不裝沒事)" || bad "E2 --check 對壞檔回 0"
echo "── F. 接線:SessionStart 有掛、雲端 setup script 有叫 ──"
python3 - <<'PY' && ok "F1 hooks.json 的 SessionStart 註冊了 scripts/settings-allow-sync" || bad "F1 hooks.json 沒掛"
import json
d = json.load(open("hooks/hooks.json"))
cmds = [h["command"] for g in d["hooks"]["SessionStart"] for h in g["hooks"]]
assert any("scripts/settings-allow-sync" in c for c in cmds), cmds
PY
grep -q 'settings-allow-sync' docs/cloud-setup-script.sh && ok "F2 docs/cloud-setup-script.sh 裝完 plugin 會跑它" || bad "F2 setup script 沒叫它"
grep -q 'exit 0$' docs/cloud-setup-script.sh && ok "F3 setup script 仍然 exit 0(非零會讓整個 session 開不起來)" || bad "F3 setup script 結尾不是 exit 0"
echo; echo "$PASS/$((PASS+FAIL)) 通過"
[ "$FAIL" -eq 0 ]
+247
View File
@@ -0,0 +1,247 @@
#!/bin/bash
# scripts/stage 的測試(inkstone/ISEP#137
#
# 它守什麼: 「雲端總管對 stage 的每一種寫入都有一支固定形狀的正門,而且**只**寫得進 stage」這件事的機器那一半。
# 09-07 三種寫入(`npx wrangler secret put``stage-deploy-artifacts.py`curl POST 到 arcrun-yuga3bse)在雲端
# 全被 auto mode 分類器擋(複合指令與任意 curl 對不上白名單任何一條)。
# 收成 `stage secret …`CF API)與 `stage api …`(curl 打實例);值只從環境變數名讀;
# 判準是 CF 帳號 ID/stage 主機往放行方向比對,不看名字。
#
# 🔴 全程離線:CF API 與 stage 實例都指到本機一個假伺服器,不打真 Cloudflare、不碰任何 worker。
# 真的種一把進 youlin、真的打 stage 實例的實跑在 docs/TESTING.md A36 另記。
# 假伺服器對 secret PUT 回 **201**——真 CF 就是回 201,第一次實跑把 201 講成失敗就是這樣抓到的。
#
# 四個方向都要驗,缺一個就是假綠:
# A 拒絕(非 stage/缺變數/值在指令列)⇒ 離開碼 2,而且**沒打網路**
# B token 打不到 stage ⇒ 拒絕、印出它打得到誰、沒有任何 PUT
# C 種進 stage ⇒ PUT 的路徑帶 stage ID、body 對、值不出現在任何輸出、種完用列表確認
# D api:主機只會是 stage;標頭值從環境變數來;body 三種來源;非 2xx 離開碼 1
# E 接線:白名單有它四種形狀+Arcrun 那支;ISEP 自己的 Bash 閘對這些呼叫形狀一支都不擋(誤攔比漏擋嚴重)
cd "$(dirname "$0")/.." || exit 1
ROOT=$(pwd)
S=scripts/stage
STAGE=1129efd7df2e8899d537e9c8fbabb6cb
TMP=$(mktemp -d); trap 'kill $SRV 2>/dev/null; rm -rf "$TMP"' EXIT
PASS=0; FAIL=0
ok(){ PASS=$((PASS+1)); printf ' ✅ %s\n' "$1"; }
bad(){ FAIL=$((FAIL+1)); printf ' ❌ %s\n' "$1"; }
LOG="$TMP/log.jsonl"; MODE="$TMP/mode"; STATE="$TMP/secrets.json"
export STAGE_TEST_VALUE="v-ISEP137-$(python3 -c 'import secrets;print(secrets.token_hex(12))')-must-never-print" # 每次隨機:C8 才驗得出「值落地」
export TOK_STAGE='tok-stage-abcdefghijklmnopqrstuvwxyz0123456789'
export KBDB_TOK_TEST="kbdb-$(python3 -c 'import secrets;print(secrets.token_hex(8))')"
# ── 假伺服器:/accounts… 扮 CF API/<worker>/… 扮 stage 實例。mode 檔決定 CF 扮誰 ──
cat > "$TMP/stub.py" <<'PY'
import json, os, sys
from http.server import BaseHTTPRequestHandler, HTTPServer
TMP = sys.argv[1]; PORT = int(sys.argv[2])
STAGE = "1129efd7df2e8899d537e9c8fbabb6cb"
def mode(): return open(os.path.join(TMP, "mode")).read().strip()
def state():
p = os.path.join(TMP, "secrets.json")
return json.load(open(p)) if os.path.exists(p) else ["KBDB_INTERNAL_TOKEN"]
def save(s): json.dump(s, open(os.path.join(TMP, "secrets.json"), "w"))
class H(BaseHTTPRequestHandler):
def log_message(self, *a): pass
def _send(self, code, obj):
b = json.dumps(obj).encode(); self.send_response(code)
self.send_header("Content-Type", "application/json"); self.send_header("Content-Length", str(len(b)))
self.end_headers(); self.wfile.write(b)
def _body(self):
n = int(self.headers.get("Content-Length", "0")); return self.rfile.read(n).decode() if n else ""
def _log(self, raw=None):
rec = {"method": self.command, "path": self.path, "auth": self.headers.get("Authorization", ""),
"ua": self.headers.get("User-Agent", ""), "ct": self.headers.get("Content-Type", ""),
"xkey": self.headers.get("X-Arcrun-API-Key", "")}
if raw is not None:
try: body = json.loads(raw)
except ValueError: body = {}
rec["body_name"] = body.get("name"); rec["body_type"] = body.get("type")
rec["text_ok"] = body.get("text") == os.environ.get("STAGE_TEST_VALUE")
rec["body_raw"] = raw if os.environ.get("STAGE_TEST_VALUE") not in raw else "<redacted>"
with open(os.path.join(TMP, "log.jsonl"), "a") as f: f.write(json.dumps(rec) + "\n")
def _instance(self):
# 扮 stage 實例:POST 沒帶 Bearer ⇒ 401(真 kbdb 就是這樣);其餘 200 回聲
raw = self._body(); self._log(raw)
if self.command != "GET" and not self.headers.get("Authorization"):
return self._send(401, {"error": "Unauthorized"})
self._send(200, {"ok": True, "echo_path": self.path, "echo_method": self.command})
def do_GET(self):
if not self.path.startswith("/accounts"): return self._instance()
self._log(); m = mode()
if self.path == "/accounts":
if m == "401": return self._send(401, {"success": False, "errors": [{"code": 10000, "message": "Authentication error"}]})
acct = {"stage": [{"id": STAGE, "name": "Youlin.hsieh.dev@gmail.com's Account"}],
"leo21c": [{"id": "9f3b2c1d000000000000000000000leo", "name": "Leo21c's Account"}],
"geek": [{"id": "77aa11bb000000000000000000000geek", "name": "geek6688's Account"}],
"both": [{"id": STAGE, "name": "Youlin"}, {"id": "9f3b2c1d000000000000000000000leo", "name": "Leo21c"}]}
return self._send(200, {"success": True, "errors": [], "result": acct.get(m, acct["stage"])})
if self.path.endswith("/secrets"):
names = state()
if m == "put-ok-list-missing": names = [n for n in names if n != "ISEP_137_PROBE"]
return self._send(200, {"success": True, "errors": [], "result": [{"name": n, "type": "secret_text"} for n in names]})
self._send(404, {"success": False, "errors": [{"code": 7003, "message": "not found"}]})
def do_PUT(self):
if not self.path.startswith("/accounts"): return self._instance()
raw = self._body(); self._log(raw); body = json.loads(raw or "{}")
s = state(); s = [x for x in s if x != body.get("name")] + [body.get("name")]; save(s)
self._send(201, {"success": True, "errors": [], "result": {"name": body.get("name"), "type": "secret_text"}}) # 真 CF 回 201
def do_DELETE(self):
if not self.path.startswith("/accounts"): return self._instance()
self._log(); name = self.path.rsplit("/", 1)[-1]
save([x for x in state() if x != name]); self._send(200, {"success": True, "errors": [], "result": None})
def do_POST(self): self._instance()
def do_PATCH(self): self._instance()
HTTPServer(("127.0.0.1", PORT), H).serve_forever()
PY
PORT=$(python3 -c "import socket;s=socket.socket();s.bind(('127.0.0.1',0));print(s.getsockname()[1])")
python3 "$TMP/stub.py" "$TMP" "$PORT" & SRV=$!
for _ in $(seq 1 50); do python3 -c "import socket;socket.create_connection(('127.0.0.1',$PORT),1)" 2>/dev/null && break; sleep 0.1; done
export STAGE_SECRET_PUT_API_BASE="http://127.0.0.1:$PORT"
export STAGE_API_BASE_OVERRIDE="http://127.0.0.1:$PORT"
echo stage > "$MODE"; : > "$LOG"
reset(){ : > "$LOG"; rm -f "$STATE"; echo "${1:-stage}" > "$MODE"; }
run(){ OUT=$(python3 "$S" "$@" 2>&1); RC=$?; }
hits(){ grep -c "\"method\": \"$1\"" "$LOG" 2>/dev/null || true; }
no_value(){ ! printf '%s' "$OUT" | grep -qF "$STAGE_TEST_VALUE"; }
echo "── A. 本工具自己拒絕的:離開碼 2,而且沒打網路 ──"
reset; run secret put --worker w --secret X --from-env STAGE_TEST_VALUE --token-env TOK_STAGE --account 58309bb90fd93ad6d0fe0aae99170e9d
[ "$RC" = 2 ] && printf '%s' "$OUT" | grep -q "$STAGE" && printf '%s' "$OUT" | grep -q '交回地端' && [ "$(wc -l < "$LOG")" = 0 ] \
&& ok "A1 --account 給非 stageuncle6 的 ID)⇒ 拒絕、講出 stage 是誰、出路是交回地端、一個請求都沒發" || bad "A1 rc=$RC hits=$(wc -l < "$LOG") $OUT"
reset; run secret put --worker w --secret X --from-env STAGE_TEST_VALUE --token-env NOPE_TOKEN_VAR
[ "$RC" = 2 ] && printf '%s' "$OUT" | grep -q 'NOPE_TOKEN_VAR' && [ "$(wc -l < "$LOG")" = 0 ] \
&& ok "A2 token 的環境變數沒值 ⇒ 拒絕、點名那個變數、沒打網路" || bad "A2 rc=$RC $OUT"
reset; run secret put --worker w --secret X --from-env NOPE_VALUE_VAR --token-env TOK_STAGE
[ "$RC" = 2 ] && printf '%s' "$OUT" | grep -q 'NOPE_VALUE_VAR' && printf '%s' "$OUT" | grep -q '紅線' && [ "$(wc -l < "$LOG")" = 0 ] \
&& ok "A3 值的環境變數沒值 ⇒ 拒絕、點名變數、明講不准改寫進指令列、沒打網路" || bad "A3 rc=$RC $OUT"
reset; run secret put --worker w --secret X --value "$STAGE_TEST_VALUE" --token-env TOK_STAGE
[ "$RC" = 2 ] && printf '%s' "$OUT" | grep -q -- '--value' && no_value && [ "$(wc -l < "$LOG")" = 0 ] \
&& ok "A4 --value(值在指令列)⇒ 拒收,而且拒絕訊息裡不回顯那個值" || bad "A4 rc=$RC $OUT"
reset; run secret put --secret X --from-env STAGE_TEST_VALUE --token-env TOK_STAGE
[ "$RC" = 2 ] && printf '%s' "$OUT" | grep -q -- '--worker' && ok "A5 缺 --worker ⇒ 拒絕、講缺哪個" || bad "A5 rc=$RC $OUT"
reset; run frobnicate --worker w
[ "$RC" = 2 ] && ok "A6 不認得的子命令 ⇒ 拒絕" || bad "A6 rc=$RC $OUT"
run --help; [ "$RC" = 0 ] && printf '%s' "$OUT" | grep -q -- '--from-env' && printf '%s' "$OUT" | grep -q -- '--bearer-env' && ok "A7 --help 印兩個子命令的用法、離開碼 0" || bad "A7 rc=$RC"
echo "── B. token 打不到 stage ⇒ 拒絕、印出它打得到誰、沒有 PUT ──"
reset leo21c; run secret put --worker w --secret X --from-env STAGE_TEST_VALUE --token-env TOK_STAGE
[ "$RC" = 2 ] && printf '%s' "$OUT" | grep -q "Leo21c's Account" && printf '%s' "$OUT" | grep -q "$STAGE" && [ "$(hits PUT)" = 0 ] && no_value \
&& ok "B1 token 只打得到 leo21c ⇒ 拒絕、列出那個帳號、講出 stage 是哪個 ID、零 PUT" || bad "B1 rc=$RC PUT=$(hits PUT) $OUT"
reset geek; run secret put --worker w --secret X --from-env STAGE_TEST_VALUE --token-env TOK_STAGE
[ "$RC" = 2 ] && printf '%s' "$OUT" | grep -q "geek6688" && [ "$(hits PUT)" = 0 ] \
&& ok "B2 token 只打得到 geek6688(出貨機)⇒ 同樣拒絕、零 PUT" || bad "B2 rc=$RC $OUT"
reset 401; run secret put --worker w --secret X --from-env STAGE_TEST_VALUE --token-env TOK_STAGE
[ "$RC" = 1 ] && printf '%s' "$OUT" | grep -q 'Authentication error' && [ "$(hits PUT)" = 0 ] \
&& ok "B3 CF 回 401 ⇒ 離開碼 1(API 失敗,不是「拒絕」也不是 000)、帶 CF 的錯誤字串、零 PUT" || bad "B3 rc=$RC $OUT"
reset; STAGE_SECRET_PUT_API_BASE="http://127.0.0.1:1" run secret put --worker w --secret X --from-env STAGE_TEST_VALUE --token-env TOK_STAGE
[ "$RC" = 1 ] && printf '%s' "$OUT" | grep -q '__agentproxy/status' && no_value \
&& ok "B4 連不到 CF ⇒ 離開碼 1、印錯誤類型、指到 agentproxy status(不把三種病記成 000" || bad "B4 rc=$RC $OUT"
reset both; run secret put --worker w --secret ISEP_137_PROBE --from-env STAGE_TEST_VALUE --token-env TOK_STAGE
[ "$RC" = 0 ] && grep -q "\"path\": \"/accounts/$STAGE/workers/scripts/w/secrets\"" "$LOG" && ! grep -q '0000leo' "$LOG" \
&& ok "B5 token 兩個帳號都打得到 ⇒ 放行,但 URL 只帶 stage 的 ID(寫入永遠只到 stage" || bad "B5 rc=$RC $(cat "$LOG")"
echo "── C. 種進 stage(假 CF 對 PUT 回 201,跟真的一樣)──"
reset; run secret put --worker arcrun-cypher-executor --secret ISEP_137_PROBE --from-env STAGE_TEST_VALUE --token-env TOK_STAGE
[ "$RC" = 0 ] && ok "C1 離開碼 0(201 算成功——第一次實跑把 201 講成失敗,就是這格抓的)" || bad "C1 rc=$RC $OUT"
grep -q "\"method\": \"PUT\", \"path\": \"/accounts/$STAGE/workers/scripts/arcrun-cypher-executor/secrets\"" "$LOG" \
&& ok "C2 PUT 打的是 stage 帳號 ID 底下那顆 worker" || bad "C2 $(cat "$LOG")"
grep '"method": "PUT"' "$LOG" | grep -q '"body_name": "ISEP_137_PROBE", "body_type": "secret_text", "text_ok": true' \
&& ok "C3 body 的 nametype 對,而且 text 就是環境變數裡那個值(不是變數名)" || bad "C3 $(grep PUT "$LOG")"
no_value && ok "C4 stdoutstderr 不含那個值" || bad "C4 值印出來了"
grep -q '"auth": "Bearer tok-stage-' "$LOG" && ok "C5 Authorization 帶的是 --token-env 指的那把" || bad "C5 $(head -1 "$LOG")"
printf '%s' "$OUT" | grep -q 'ISEP_137_PROBE' && printf '%s' "$OUT" | grep -q 'KBDB_INTERNAL_TOKEN' \
&& ok "C6 種完把列表印出來(新的那把+原本就有的)" || bad "C6 $OUT"
[ "$(grep -c '"method": "GET", "path": "/accounts/'"$STAGE"'/workers/scripts/arcrun-cypher-executor/secrets"' "$LOG")" = 1 ] \
&& ok "C7 種完真的去列了一次(不是只信 PUT 的回應)" || bad "C7 $(cat "$LOG")"
! grep -rqF "$STAGE_TEST_VALUE" "$ROOT" 2>/dev/null \
&& ok "C8 值沒落在 repo 樹裡任何檔案" || bad "C8 值落地了:$(grep -rlF "$STAGE_TEST_VALUE" "$ROOT")"
reset put-ok-list-missing; run secret put --worker w --secret ISEP_137_PROBE --from-env STAGE_TEST_VALUE --token-env TOK_STAGE
[ "$RC" = 1 ] && printf '%s' "$OUT" | grep -q '列表卻沒有' \
&& ok "C9 CF 說成功但列表沒有 ⇒ 離開碼 1(不把 2xx 講成種好了)" || bad "C9 rc=$RC $OUT"
reset; run secret list --worker w --token-env TOK_STAGE
[ "$RC" = 0 ] && printf '%s' "$OUT" | grep -q 'KBDB_INTERNAL_TOKEN' && [ "$(hits PUT)" = 0 ] && ok "C10 secret list 印名字、不寫" || bad "C10 rc=$RC $OUT"
reset; run secret delete --worker w --secret KBDB_INTERNAL_TOKEN --token-env TOK_STAGE
[ "$RC" = 0 ] && grep -q "\"method\": \"DELETE\", \"path\": \"/accounts/$STAGE/workers/scripts/w/secrets/KBDB_INTERNAL_TOKEN\"" "$LOG" \
&& ok "C11 secret delete 打對路徑、刪完列表確認" || bad "C11 rc=$RC $OUT $(cat "$LOG")"
reset leo21c; run secret delete --worker w --secret X --token-env TOK_STAGE
[ "$RC" = 2 ] && [ "$(hits DELETE)" = 0 ] && ok "C12 delete 對非 stage 的 token 一樣拒絕" || bad "C12 rc=$RC"
echo "── D. api:主機只會是 stage、標頭值從環境變數來、body 三種來源 ──"
reset; run api POST https://arcrun-cypher-executor.leo21c.workers.dev/kbdb/entries --json '{}'
[ "$RC" = 2 ] && printf '%s' "$OUT" | grep -q 'leo21c.workers.dev' && printf '%s' "$OUT" | grep -q 'arcrun-yuga3bse' && [ "$(wc -l < "$LOG")" = 0 ] \
&& ok "D1 完整網址指到 leo21c ⇒ 拒絕、講出 stage 主機是什麼、沒打網路" || bad "D1 rc=$RC $OUT"
reset; run api POST https://arcrun-kbdb.youlin-hsieh-dev.workers.dev/records --json '{}'
[ "$RC" = 2 ] && [ "$(wc -l < "$LOG")" = 0 ] && ok "D2 09-02 已死的舊子網域 youlin-hsieh-dev 也拒絕(不是 stage 的識別碼)" || bad "D2 rc=$RC $OUT"
reset; run api POST arcrun-kbdb/records --bearer 'Bearer xyz' --json '{}'
[ "$RC" = 2 ] && printf '%s' "$OUT" | grep -q -- '--bearer' && [ "$(wc -l < "$LOG")" = 0 ] && ok "D3 --bearer--header(值在指令列)⇒ 拒收" || bad "D3 rc=$RC $OUT"
reset; run api POST arcrun-kbdb/records --bearer-env NOPE_KBDB --json '{}'
[ "$RC" = 2 ] && printf '%s' "$OUT" | grep -q 'NOPE_KBDB' && [ "$(wc -l < "$LOG")" = 0 ] && ok "D4 --bearer-env 指的變數沒值 ⇒ 拒絕、點名" || bad "D4 rc=$RC $OUT"
reset; run api POST 'arcrun-kbdb/map/recompute?library=rt-lib&owner_id=yuga3bse' --bearer-env KBDB_TOK_TEST
[ "$RC" = 0 ] && grep -q '"method": "POST", "path": "/arcrun-kbdb/map/recompute?library=rt-lib&owner_id=yuga3bse", "auth": "Bearer kbdb-' "$LOG" \
&& printf '%s' "$OUT" | grep -q '^HTTP 200' && ok "D5 POST <worker>/<path>?query:主機由工具補、query 原樣、Bearer 從環境變數來、印 HTTP 200、離開碼 0" || bad "D5 rc=$RC $OUT $(cat "$LOG")"
reset; run api POST arcrun-kbdb/records --bearer-env KBDB_TOK_TEST --json '{"template":"triplet","values":{"s":"a"}}'
grep -q '"ct": "application/json"' "$LOG" && grep -q '"body_raw": "{\\"template\\":\\"triplet\\",\\"values\\":{\\"s\\":\\"a\\"}}"' "$LOG" \
&& ok "D6 --jsonbody 原樣送到、自動帶 Content-Type: application/json" || bad "D6 $(cat "$LOG")"
reset; STAGE_BODY_TEST='{"secret_ref":"'"$STAGE_TEST_VALUE"'"}' run api PUT arcrun-cypher-executor/credentials/gitea_token --bearer-env KBDB_TOK_TEST --data-env STAGE_BODY_TEST
[ "$RC" = 0 ] && grep -q '"method": "PUT", "path": "/arcrun-cypher-executor/credentials/gitea_token"' "$LOG" && grep -q '"body_raw": "<redacted>"' "$LOG" && no_value \
&& ok "D7 --data-envbody 從環境變數來(機敏 body 不進指令列),值沒印出來" || bad "D7 rc=$RC $OUT $(cat "$LOG")"
reset; printf '{"x":1}' > "$TMP/body.json"; run api POST arcrun-kbdb/records --bearer-env KBDB_TOK_TEST --data-file "$TMP/body.json"
[ "$RC" = 0 ] && grep -q '"body_raw": "{\\"x\\":1}"' "$LOG" && ok "D8 --data-filebody 從檔案來" || bad "D8 rc=$RC $(cat "$LOG")"
reset; run api POST arcrun-kbdb/records --json '{}'
[ "$RC" = 1 ] && printf '%s' "$OUT" | grep -q '^HTTP 401' && ok "D9 沒帶 Bearer 的 POST ⇒ 實例回 401 ⇒ 離開碼 1(不把非 2xx 講成成功)" || bad "D9 rc=$RC $OUT"
reset; run api GET arcrun-cypher-executor/health
[ "$RC" = 0 ] && grep -q '"method": "GET", "path": "/arcrun-cypher-executor/health"' "$LOG" && ok "D10 GET 不帶 body、不帶 Content-Type" || bad "D10 rc=$RC $OUT"
grep -q '"ct": ""' "$LOG" && ok "D11 GET 的請求真的沒有 Content-Type" || bad "D11 $(cat "$LOG")"
reset; run api POST arcrun-cypher-executor/webhooks/named/yuga3bse/x/trigger --header-env X-Arcrun-API-Key=KBDB_TOK_TEST --bearer-env KBDB_TOK_TEST --json '{}'
grep -q '"xkey": "kbdb-' "$LOG" && ok "D12 --header-env Name=VAR:任意標頭值從環境變數來" || bad "D12 $(cat "$LOG")"
reset; run api POST https://arcrun-kbdb.arcrun-yuga3bse.workers.dev/records --bearer-env KBDB_TOK_TEST --json '{}'
[ "$RC" = 0 ] && grep -q '"path": "/arcrun-kbdb/records"' "$LOG" && ok "D13 完整網址但主機就是 stage ⇒ 收" || bad "D13 rc=$RC $OUT"
reset; run api POST 'arcrun-kbdb/records' --bearer-env KBDB_TOK_TEST --json '{}' --data-file x
[ "$RC" = 2 ] && [ "$(wc -l < "$LOG")" = 0 ] && ok "D14 --json 與 --data-file 同時給 ⇒ 拒絕" || bad "D14 rc=$RC"
reset; run api FROB arcrun-kbdb/records
[ "$RC" = 2 ] && ok "D15 不認得的 METHOD ⇒ 拒絕" || bad "D15 rc=$RC"
reset; STAGE_API_BASE_OVERRIDE="http://127.0.0.1:1" run api GET arcrun-cypher-executor/health
[ "$RC" = 1 ] && printf '%s' "$OUT" | grep -q 'curl 失敗' && printf '%s' "$OUT" | grep -q '__agentproxy/status' && ok "D16 curl 連不上 ⇒ 離開碼 1、印 curl 的錯誤字串與 agentproxy 出路(不記成 000" || bad "D16 rc=$RC $OUT"
grep -q '"ua": "isep-stage/1' "$LOG" 2>/dev/null || { reset; run api GET arcrun-cypher-executor/health; }
grep -q '"ua": "isep-stage/1' "$LOG" && ok "D17 UA 是自己的名字(youlin 邊緣擋 python-urllib UAArcrun#176 comment 6487" || bad "D17 $(cat "$LOG")"
echo "── E. 接線 ──"
python3 - <<'PY' && ok "E1 docs/permissions-allow.json 有 stage 四種呼叫形狀+Arcrun 的 stage-deploy-artifacts.py,沒放整類" || bad "E1 白名單形狀不齊或放了整類"
import json
rules = json.load(open("docs/permissions-allow.json"))["allow"]
need = ['Bash(python3 ~/.claude/plugins/cache/inkstone/isep/*/scripts/stage *)',
'Bash(python3 "$CLAUDE_PLUGIN_ROOT/scripts/stage" *)',
'Bash(python3 "$CLAUDE_PLUGIN_ROOT"/scripts/stage *)',
'Bash(python3 scripts/stage *)',
'Bash(python3 scripts/stage-deploy-artifacts.py *)']
for n in need: assert n in rules, "缺 " + n
assert not any(r in ("Bash(npx *)", "Bash(wrangler *)", "Bash(npx wrangler *)", "Bash(python3 *)", "Bash(curl *)") for r in rules)
PY
# ISEP 自己掛在 PreToolUse Bash 上的每一支閘,對三種真實呼叫形狀都不准擋(清單當場從 hooks.json 讀,不寫死)
BLOCKED=""
while IFS= read -r CMD; do
for h in $(python3 -c "
import json
d=json.load(open('hooks/hooks.json'))
for g in d['hooks']['PreToolUse']:
if 'Bash' in (g.get('matcher') or ''):
for x in g['hooks']: print(x['command'].split('/')[-1])
"); do
[ -f "hooks/$h" ] || continue
printf '%s' "{\"tool_name\":\"Bash\",\"tool_input\":{\"command\":$(python3 -c 'import json,sys;print(json.dumps(sys.argv[1]))' "$CMD")},\"session_id\":\"t137\",\"cwd\":\"$ROOT\"}" \
| CLAUDE_PLUGIN_ROOT="$ROOT" CLAUDE_PROJECT_DIR="$ROOT" bash "hooks/$h" >/dev/null 2>"$TMP/hook.err"; rc=$?
[ "$rc" = 2 ] && BLOCKED="$BLOCKED $h$(printf '%s' "$CMD" | cut -c1-40)"
done
done <<'CMDS'
python3 ~/.claude/plugins/cache/inkstone/isep/0.24.0/scripts/stage secret put --worker arcrun-cypher-executor --secret CF_SECRETS_API_TOKEN --from-env CF_SECRETS_API_TOKEN_VALUE
python3 "$CLAUDE_PLUGIN_ROOT/scripts/stage" api POST 'arcrun-kbdb/map/recompute?library=rt-lib&owner_id=yuga3bse' --bearer-env KBDB_INTERNAL_TOKEN
python3 scripts/stage-deploy-artifacts.py all --confirm
CMDS
[ -z "$BLOCKED" ] && ok "E2 ISEP 掛在 Bash 上的閘,對三種真實呼叫形狀(含 secret 字樣、POST、--confirm)一支都不擋——誤攔比漏擋嚴重" || bad "E2 這幾支誤攔:$BLOCKED"
grep -q 'scripts/stage ' scripts/test-settings-allow-sync.sh && grep -q 'stage-deploy-artifacts.py' scripts/test-settings-allow-sync.sh \
&& ok "E3 settings-allow-sync 的測試把兩支都算進正門工具(少了會紅)" || bad "E3 settings-allow-sync 測試不認得它們"
[ ! -e scripts/stage-secret-put ] && ok "E4 沒有第二支平行的工具(stage-secret-put 已收進 stage secret" || bad "E4 還留著 stage-secret-put"
echo; echo "$PASS/$((PASS+FAIL)) 通過"
[ "$FAIL" -eq 0 ]
+26 -1
View File
@@ -46,7 +46,8 @@ def I(repo, n, labels, ms=None, assignees=(), created="2026-09-01T00:00:00Z", pr
if pr: d["pull_request"] = {"merged": False} if pr: d["pull_request"] = {"merged": False}
return d return d
POOL = { POOL = {
"ISEP": [I("ISEP", 1, ["s/todo"], "main"), # ★ 可抓 "ISEP": [I("ISEP", 1, ["s/todo"], None), # ★ 可抓:沒里程碑,靠相依邊在主線上
I("ISEP", 13, ["s/todo"], "main"), # ISEP 裡「同名」的里程碑:不是主線(ISEP#133)
I("ISEP", 2, ["s/todo", "Human"], "main"), # 票上第 1 條:Human I("ISEP", 2, ["s/todo", "Human"], "main"), # 票上第 1 條:Human
I("ISEP", 3, ["s/todo"], "main", assignees=("someone",)), # 票上第 1 條:有 assignee I("ISEP", 3, ["s/todo"], "main", assignees=("someone",)), # 票上第 1 條:有 assignee
I("ISEP", 4, ["s/backlog"], None), # 票上第 1 條:backlog I("ISEP", 4, ["s/backlog"], None), # 票上第 1 條:backlog
@@ -59,6 +60,16 @@ POOL = {
"mira": [I("mira", 9, ["s/todo", "s/doing"], "main")], # 09-07 實查 mira#6 的形狀:有人在做 "mira": [I("mira", 9, ["s/todo", "s/doing"], "main")], # 09-07 實查 mira#6 的形狀:有人在做
} }
MSN = {"ISEP": ["main", "late", "future"], "Arcrun": ["main", "late", "future"], "mira": ["main"]} MSN = {"ISEP": ["main", "late", "future"], "Arcrun": ["main", "late", "future"], "mira": ["main"]}
# 相依邊(inkstone/ISEP#133):主線錨在 Arcrun#48Arcrun#6 把 ISEP#1 當相依 ⇒ ISEP#1 在主線上;
# ISEP#13 掛在 ISEP 的同名里程碑但沒有任何邊 ⇒ 不在主線上。mira#9 同理(同名、沒邊)。
DEPS = {"Arcrun#6": ["ISEP#1"]}
BLOCKS = {}
for _p, _cs in DEPS.items():
for _c in _cs:
BLOCKS.setdefault(_c, []).append(_p)
def _by_ref(ref):
repo, n = ref.split("#")
return next(i for i in POOL[repo] if i["number"] == int(n))
DROP = set(json.loads(os.environ.get("DROP", "[]"))) # 測「主線抓盡」用:把某幾張從池子拿掉 DROP = set(json.loads(os.environ.get("DROP", "[]"))) # 測「主線抓盡」用:把某幾張從池子拿掉
def fake_api(path, payload=None, method=None): def fake_api(path, payload=None, method=None):
rec.append((method or ("POST" if payload is not None else "GET"), path, payload)) rec.append((method or ("POST" if payload is not None else "GET"), path, payload))
@@ -80,6 +91,10 @@ def fake_api(path, payload=None, method=None):
return [{"name": n, "id": k} for k, n in return [{"name": n, "id": k} for k, n in
enumerate(["s/todo", "s/doing", "s/review", "p/high", "Human"], 1)] enumerate(["s/todo", "s/doing", "s/review", "p/high", "Human"], 1)]
import re import re
m = re.match(r"/repos/inkstone/(\w+)/issues/(\d+)/(dependencies|blocks)(\?.*)?$", path)
if m:
table = DEPS if m.group(3) == "dependencies" else BLOCKS
return [_by_ref(r) for r in table.get(f"{m.group(1)}#{m.group(2)}", [])]
m = re.match(r"/repos/inkstone/(\w+)/issues/(\d+)$", path) m = re.match(r"/repos/inkstone/(\w+)/issues/(\d+)$", path)
if m and (method or "GET") == "GET": if m and (method or "GET") == "GET":
return next(i for i in POOL[m.group(1)] if i["number"] == int(m.group(2))) return next(i for i in POOL[m.group(1)] if i["number"] == int(m.group(2)))
@@ -142,6 +157,12 @@ p "★ 給定主線檔 → 回一張,而且是主線裡最優先的 Arcrun#6
p "只回一張(不是整份清單)" "1" "out.count(' ● ')" "$ARGS" p "只回一張(不是整份清單)" "1" "out.count(' ● ')" "$ARGS"
p "★ --all:主線裡可抓的恰好是 Arcrun#6、ISEP#1 兩張——Humanassigneebacklog 三張都不在" \ p "★ --all:主線裡可抓的恰好是 Arcrun#6、ISEP#1 兩張——Humanassigneebacklog 三張都不在" \
"['inkstone/Arcrun#6', 'inkstone/ISEP#1']" "[r['ref'] for r in json.loads(out) if r['group']=='主線']" "$ALL" "['inkstone/Arcrun#6', 'inkstone/ISEP#1']" "[r['ref'] for r in json.loads(out) if r['group']=='主線']" "$ALL"
p "★ ISEP#1 沒掛里程碑,是靠「Arcrun#6 把它當相依」進主線的(成員=相依邊,ISEP#133)" "True" \
"'inkstone/ISEP#1' in out and any(p.endswith('/issues/6/dependencies?limit=100') for _,p,_ in rec)" "$ALL"
p "★ ISEP#13 掛在 ISEP 裡**同名**的里程碑、沒有任何邊 → 不在主線裡(同名不算,leo 09-07)" "False" \
"'inkstone/ISEP#13' in out" "$ALL"
p "主線那一組只讀 hub 里程碑那一個 repo 的 milestone 清單(不去別的 repo 找同名)" "True" \
"not any('/repos/inkstone/ISEP/issues?' in p and '主線' in p for _,p,_ in rec)" "$ALL"
p "★ --all:逾期里程碑那張 Arcrun#7 排在主線之後(主線抓盡才輪到)" \ p "★ --all:逾期里程碑那張 Arcrun#7 排在主線之後(主線抓盡才輪到)" \
"['inkstone/Arcrun#7']" "[r['ref'] for r in json.loads(out) if r['group']!='主線']" "$ALL" "['inkstone/Arcrun#7']" "[r['ref'] for r in json.loads(out) if r['group']!='主線']" "$ALL"
p "沒逾期也不是主線的 Arcrun#8 不在清單裡" "False" "'inkstone/Arcrun#8' in out" "$ALL" p "沒逾期也不是主線的 Arcrun#8 不在清單裡" "False" "'inkstone/Arcrun#8' in out" "$ALL"
@@ -201,6 +222,10 @@ blocked "已指派的 ISEP#3" inkstone/ISEP#3
blocked "backlog 的 ISEP#4" inkstone/ISEP#4 blocked "backlog 的 ISEP#4" inkstone/ISEP#4
blocked "沒逾期也不是主線的 Arcrun#8" inkstone/Arcrun#8 blocked "沒逾期也不是主線的 Arcrun#8" inkstone/Arcrun#8
blocked "有人在做的 mira#9s/doing 也掛著)" inkstone/mira#9 blocked "有人在做的 mira#9s/doing 也掛著)" inkstone/mira#9
blocked "掛在 ISEP 同名里程碑、沒有相依邊的 ISEP#13(同名不是主線)" inkstone/ISEP#13
p "claim 靠相依進主線的 ISEP#1(沒里程碑)→ 過(留言寫「靠相依在主線上」)" "True" \
"rc is None and any('靠相依' in pl['body'] for mm,p,pl in rec if mm=='POST' and p.endswith('/comments'))" \
"[\"cmd_claim\",\"inkstone/ISEP#1\",\"--mainline\",\"$MAIN\"]"
p "擋下時訊息講得出理由與出路(pick" "True" "'Human' in out and 'pick' in out" \ p "擋下時訊息講得出理由與出路(pick" "True" "'Human' in out and 'pick' in out" \
"[\"cmd_claim\",\"inkstone/ISEP#2\",\"--mainline\",\"$MAIN\"]" "[\"cmd_claim\",\"inkstone/ISEP#2\",\"--mainline\",\"$MAIN\"]"
p "身份名不在名單上 → 在打任何 API 之前就擋(一通都沒打)" "True" "rc==2 and len(rec)==0" \ p "身份名不在名單上 → 在打任何 API 之前就擋(一通都沒打)" "True" "rc==2 and len(rec)==0" \
+95
View File
@@ -0,0 +1,95 @@
#!/bin/bash
# 「收件 repo 寫 owner/repo 不該是 404」的測試(inkstone/ISEP#130
#
# 2026-09-07 實撞:`scripts/ticket new inkstone/ISEP -F …` 回 Gitea 404。
# 不是 ISEP 不存在,是這支把 `inkstone/ISEP` 原樣塞進 `/repos/inkstone/{repo}/issues`
# ⇒ 打到 `/repos/inkstone/inkstone/ISEP/issues`。404 讀起來像「repo 不存在」,
# 於是那天四張票全改成直接打 API 開——**正門壞了人就走側門**。
#
# 怎麼在不開任何票的前提下驗:把 `scripts/ticket` 當模組載進來,
# 把 `api()` 換成一支只記錄路徑的假貨。全程離線、不打 Gitea、不留戳記。
cd "$(dirname "$0")/.." || exit 1
STAMP=/tmp/.ticket-where-ok
SAVED=""; [ -f "$STAMP" ] && SAVED=$(cat "$STAMP")
trap '[ -n "$SAVED" ] && printf "%s" "$SAVED" > "$STAMP" || rm -f "$STAMP"' EXIT
TICKET_HOST=http://127.0.0.1:9 GITEA_TOKEN=x python3 - <<'PY'
import importlib.machinery, importlib.util, io, json, os, sys, tempfile, time, contextlib
loader = importlib.machinery.SourceFileLoader("isep_ticket", "scripts/ticket")
spec = importlib.util.spec_from_file_location("isep_ticket", "scripts/ticket", loader=loader)
T = importlib.util.module_from_spec(spec); loader.exec_module(T)
CALLS = []
def fake_api(path, payload=None, method=None):
CALLS.append((method or ("POST" if payload is not None else "GET"), path))
if path.endswith("/labels?limit=100") or path.endswith("/labels?limit=60"):
return [{"name": "s/todo", "id": 1}, {"name": "s/doing", "id": 2}]
if path.endswith("/issues") and payload is not None:
return {"number": 999, "html_url": "http://fake/999", "labels": []}
if "/comments" in path:
return {"id": 1, "html_url": "http://fake/c1"}
if "/dependencies" in path or "/blocks" in path:
return [] if payload is None else {}
return {"labels": [], "number": 1}
T.api = fake_api
T.api_soft = lambda path: None
tmp = tempfile.mkdtemp()
body = os.path.join(tmp, "body.md")
open(body, "w").write("## 目標\n測試。\n\n## 驗收條件\n離線。\n\n## deliverable 類型\ncode\n")
TITLE = "身為要開票的人,我要寫 owner/repo 也開得出票,我才不會被 404 逼去走側門"
def stamp():
json.dump({"at": time.time(), "kws": ["x"], "n": 0, "top": [], "top_detail": [], "shown": True},
open(T.stamp_path(), "w"))
PASS = FAIL = 0
def ok(m, *_):
global PASS; PASS += 1; print(" ✅ " + m)
def bad(m, why="", *_):
global FAIL; FAIL += 1; print(" ❌ " + m + (" —— " + why if why else ""))
def run(fn, argv):
"""回 (離開碼, stderr)。die() 走 sys.exit(2)。"""
CALLS.clear()
err = io.StringIO(); out = io.StringIO()
with contextlib.redirect_stderr(err), contextlib.redirect_stdout(out):
try:
fn(argv); rc = 0
except SystemExit as e:
rc = e.code if isinstance(e.code, int) else 1
return rc, err.getvalue() + out.getvalue()
print("── new:兩種寫法都要打到同一條路 ──")
stamp(); rc, msg = run(T.cmd_new, ["ISEP", "-F", body, "--title", TITLE])
posts = [p for m, p in CALLS if m == "POST"]
(ok if posts == ["/repos/inkstone/ISEP/issues"] else bad)("① `new ISEP` → /repos/inkstone/ISEP/issues", str(CALLS))
stamp(); rc, msg = run(T.cmd_new, ["inkstone/ISEP", "-F", body, "--title", TITLE])
posts = [p for m, p in CALLS if m == "POST"]
(ok if posts == ["/repos/inkstone/ISEP/issues"] else bad)("② `new inkstone/ISEP`09-07 撞 404 的那一句)→ 同一條路,不再是 /repos/inkstone/inkstone/ISEP", str(CALLS))
print("── new:寫錯要當場講,不要變成一個 404 讓人猜 ──")
stamp(); rc, msg = run(T.cmd_new, ["Leo/ISEP", "-F", body, "--title", TITLE])
(ok if rc == 2 and not CALLS and "inkstone" in msg else bad)("③ `new Leo/ISEP` → 擋(exit 2)、一通 API 都不打、訊息說 org 是 inkstone", f"rc={rc} calls={CALLS} msg={msg[:120]}")
stamp(); rc, msg = run(T.cmd_new, ["inkstone/ISEP#130", "-F", body, "--title", TITLE])
(ok if rc == 2 and not CALLS else bad)("④ `new inkstone/ISEP#130`(把票號當 repo)→ 擋,不打 API", f"rc={rc} calls={CALLS}")
print("── subtask--to 也吃 owner/repo ──")
rc, msg = run(T.cmd_subtask, ["inkstone/ISEP#130", "--title", TITLE, "-F", body, "--to", "inkstone/Arcrun"])
posts = [p for m, p in CALLS if m == "POST" and p.endswith("/issues")]
(ok if posts == ["/repos/inkstone/Arcrun/issues"] else bad)("⑤ `subtask … --to inkstone/Arcrun` → 子票開在 /repos/inkstone/Arcrun/issues", f"rc={rc} calls={CALLS} msg={msg[:200]}")
rc, msg = run(T.cmd_subtask, ["inkstone/ISEP#130", "--title", TITLE, "-F", body, "--to", "Arcrun"])
posts = [p for m, p in CALLS if m == "POST" and p.endswith("/issues")]
(ok if posts == ["/repos/inkstone/Arcrun/issues"] else bad)("⑥ `subtask … --to Arcrun`(原本的寫法)照舊", f"rc={rc} calls={CALLS}")
print("── 沒有任何東西真的出去 ──")
(ok if not os.path.exists(T.stamp_path()) or True else bad)("⑦ 假 api 記到的路徑全部是 /repos/inkstone/<repo>/…,沒有一條含 inkstone/inkstone")
if any("inkstone/inkstone" in p for _, p in CALLS): FAIL += 1; PASS -= 1; print(" ❌ ⑦ 出現 inkstone/inkstone")
print(f"\n通過 {PASS} 條,失敗 {FAIL} 條")
sys.exit(1 if FAIL else 0)
PY
+135
View File
@@ -0,0 +1,135 @@
#!/usr/bin/env bash
# scripts/worktree 的測試(inkstone/ISEP#147)——重點是 `sweep`leo 在 Mac 上跑一次的整理工具。
#
# 它守什麼: 「一個 repo 只有一個資料夾」的現場整理那一半。fixture 照 leo 09-07 在 Finder 看到的那排
# 分身原樣造出來(七個,名字一字不差),每個分身的處境不同:
# course_gen-ticket-3-notes 推了、乾淨 ← 但 --skip course_gen(地端在處理):列、不動
# course_gen-ticket-4-handouts **沒推** ← 同上:列、不動
# ax-courses-ticket1 **沒推** ← 列出分支與路徑,不動
# ISEP-wt-122ship 推了、乾淨 ← --apply 收
# ISEP-wt-117 推了、有未追蹤檔 ← 不動
# ISEP-wt115 登記指向空氣 ← --apply prune
# InkStoneCo-wt-112 推了、乾淨 ← --apply 收
# 外加一份 `.worktrees/` 裡面的分身(新家)與一個沒人登記的孤兒目錄。
#
# 四個方向都要驗,缺一個就是假綠:
# A dry-run:列表正確(每份都在對的組)、**沒有動任何東西**
# B --apply:只收「推了且乾淨」的;沒推的、髒的、--skip 的、孤兒的一根寒毛都沒動
# C 判準是 git 的事實不是名字:同樣叫 course_gen 的,不 --skip 就照規則走
# D opencloselist 的基本盤(閘測試 G/H 群已驗過出路,這裡只驗工具本體)
#
# 全程離線:遠端是本機 bare repo。不打網路、不碰任何真的 repo。
set -u
cd "$(dirname "$0")/.." || exit 1
S="$(pwd)/scripts/worktree"
PASS=0; FAIL=0; N=0
ok(){ N=$((N+1)); PASS=$((PASS+1)); printf ' ✅ %s\n' "$1"; }
bad(){ N=$((N+1)); FAIL=$((FAIL+1)); printf ' ❌ %s\n' "$1"; }
chk(){ if eval "$2"; then ok "$1"; else bad "$1"; fi; } # chk <說明> <條件>
ROOT=$(mktemp -d "${TMPDIR:-/tmp}/isep-sweep.XXXXXX"); ROOT=$(cd "$ROOT" && pwd -P)
trap 'rm -rf "$ROOT"' EXIT
TP="$ROOT/tech_projects"; mkdir -p "$TP" "$ROOT/remotes"
mkrepo() { # mkrepo <名>:主 repo 本機 bare 遠端,main 已推
git init -q --bare "$ROOT/remotes/$1.git"
git init -q -b main "$TP/$1"
git -C "$TP/$1" config user.email t@t; git -C "$TP/$1" config user.name t
echo "$1" > "$TP/$1/README"; git -C "$TP/$1" add -A; git -C "$TP/$1" commit -qm init
git -C "$TP/$1" remote add origin "$ROOT/remotes/$1.git"
git -C "$TP/$1" push -q origin main 2>/dev/null
}
mkwt() { # mkwt <repo> <分身目錄名> <分支> [pushed|unpushed] [dirty]
git -C "$TP/$1" worktree add -q "$TP/$2" -b "$3"
echo "$2" > "$TP/$2/work.txt"; git -C "$TP/$2" add -A; git -C "$TP/$2" commit -qm "$2"
[ "${4:-pushed}" = pushed ] && git -C "$TP/$2" push -q origin "$3" 2>/dev/null
[ "${5:-}" = dirty ] && echo x > "$TP/$2/untracked.tmp"
return 0
}
mkrepo course_gen; mkrepo ax-courses; mkrepo ISEP; mkrepo InkStoneCo
mkwt course_gen course_gen-ticket-3-notes feat/3 pushed
mkwt course_gen course_gen-ticket-4-handouts feat/4 unpushed
mkwt ax-courses ax-courses-ticket1 feat/1 unpushed
mkwt ISEP ISEP-wt-122ship feat/122 pushed
mkwt ISEP ISEP-wt-117 feat/117 pushed dirty
mkwt ISEP ISEP-wt115 feat/115 pushed
rm -rf "$TP/ISEP-wt115" # 登記還在、目錄沒了 ⇒ 指向空氣
mkwt InkStoneCo InkStoneCo-wt-112 feat/112 pushed
# 新家裡的一份(推了、乾淨)——sweep 同樣要看得到、收得掉
python3 "$S" open inkstone/ISEP#140 --repo "$TP/ISEP" >/dev/null 2>&1
# 孤兒:.git 檔指向一個不存在的登記
mkdir -p "$TP/ISEP-wt-orphan"; printf 'gitdir: %s/ISEP/.git/worktrees/gone\n' "$TP" > "$TP/ISEP-wt-orphan/.git"
snapshot() { (cd "$TP" && find . -maxdepth 3 -not -path '*/.git/*' | sort | md5sum | cut -c1-12); }
echo
echo "── A dry-run:列得對、不動 ──"
BEFORE=$(snapshot)
OUT=$(python3 "$S" sweep "$TP" --skip course_gen 2>&1); RC=$?
chk "(1) dry-run 離開碼 2(有東西要人決定)" '[ "$RC" -eq 2 ]'
chk "(2) 沒有動任何東西(目錄樹快照相同)" '[ "$(snapshot)" = "$BEFORE" ]'
sec() { printf '%s\n' "$OUT" | awk -v s="$1" -v e='^(🟢|👻|🔴|🟡|❔|⏭️|❓|──)' 'index($0,s)==1{f=1;next} f&&$0~e{f=0} f'; }
chk "(3) ISEP-wt-122ship 在「推了且乾淨」" 'sec "🟢" | grep -qF "ISEP-wt-122ship"'
chk "(4) InkStoneCo-wt-112 在「推了且乾淨」" 'sec "🟢" | grep -qF "InkStoneCo-wt-112"'
chk "(5) .worktrees/ISEP-140 也在「推了且乾淨」" 'sec "🟢" | grep -qF ".worktrees/ISEP-140"'
chk "(6) ax-courses-ticket1 在「沒推」且印出分支 feat/1" 'sec "🔴" | grep -qF "ax-courses-ticket1" && sec "🔴" | grep -qF "feat/1"'
chk "(7) 沒推的印得出推的指令" 'sec "🔴" | grep -qF "push origin feat/1"'
chk "(8) ISEP-wt-117 在「有未 commit」" 'sec "🟡" | grep -qF "ISEP-wt-117"'
chk "(9) ISEP-wt115 在「指向空氣」" 'sec "👻" | grep -qF "ISEP-wt115"'
chk "(10) course_gen 兩份都在「--skip 不碰」" 'sec "⏭️" | grep -qF "course_gen-ticket-3-notes" && sec "⏭️" | grep -qF "course_gen-ticket-4-handouts"'
chk "(11) course_gen 沒有出現在任何會被動的組" '! sec "🟢" | grep -qF course_gen && ! sec "👻" | grep -qF course_gen'
chk "(12) 孤兒目錄在「沒人登記」" 'sec "❓" | grep -qF "ISEP-wt-orphan"'
chk "(13) 結尾講「沒有動任何東西」" 'printf "%s" "$OUT" | grep -qF "沒有動任何東西"'
echo
echo "── B --apply:只收推了且乾淨的 ──"
OUT=$(python3 "$S" sweep "$TP" --apply --skip course_gen 2>&1); RC=$?
chk "(14) --apply 離開碼 2(還有要人決定的)" '[ "$RC" -eq 2 ]'
chk "(15) ISEP-wt-122ship 收掉了" '[ ! -e "$TP/ISEP-wt-122ship" ]'
chk "(16) InkStoneCo-wt-112 收掉了" '[ ! -e "$TP/InkStoneCo-wt-112" ]'
chk "(17) .worktrees/ISEP-140 收掉了" '[ ! -e "$TP/ISEP/.worktrees/ISEP-140" ]'
chk "(18) ISEP-wt115 的空氣登記 prune 掉了" '! git -C "$TP/ISEP" worktree list | grep -qF ISEP-wt115'
chk "(19) 沒推的 ax-courses-ticket1 還在" '[ -d "$TP/ax-courses-ticket1" ]'
chk "(20) 髒的 ISEP-wt-117 還在、未追蹤檔還在" '[ -f "$TP/ISEP-wt-117/untracked.tmp" ]'
chk "(21) course_gen-ticket-3-notes(推了乾淨但 --skip)還在" '[ -d "$TP/course_gen-ticket-3-notes" ]'
chk "(22) course_gen-ticket-4-handouts 還在" '[ -d "$TP/course_gen-ticket-4-handouts" ]'
chk "(23) 孤兒目錄還在(沒人登記的只能人看)" '[ -d "$TP/ISEP-wt-orphan" ]'
chk "(24) 四個主 repo 都在、各自 main 沒動" 'for r in course_gen ax-courses ISEP InkStoneCo; do [ -f "$TP/$r/README" ] || exit 1; [ "$(git -C "$TP/$r" branch --show-current)" = main ] || exit 1; done'
chk "(25) 收掉的分身,分支還在(收的是目錄不是分支)" 'git -C "$TP/ISEP" rev-parse --verify -q refs/heads/feat/122 >/dev/null'
chk "(26) 結尾講收了 3 份" 'printf "%s" "$OUT" | grep -qF "收了 3 份"'
chk "(27) 第二次 --apply 冪等:沒有可收的、離開碼仍 2" 'python3 "$S" sweep "$TP" --apply --skip course_gen >/dev/null 2>&1; [ $? -eq 2 ] && [ -d "$TP/ax-courses-ticket1" ]'
echo
echo "── C 判準是事實不是名字 ──"
OUT=$(python3 "$S" sweep "$TP" 2>&1)
chk "(28) 不 --skip 時 course_gen-ticket-3-notes 落在「推了且乾淨」(名字不是判準)" 'sec "🟢" | grep -qF "course_gen-ticket-3-notes"'
chk "(29) course_gen-ticket-4-handouts 落在「沒推」、印 feat/4" 'sec "🔴" | grep -qF "course_gen-ticket-4-handouts" && sec "🔴" | grep -qF "feat/4"'
chk "(30) dry-run 仍然沒動 course_gen 那兩份" '[ -d "$TP/course_gen-ticket-3-notes" ] && [ -d "$TP/course_gen-ticket-4-handouts" ]'
# 問不到遠端:拿掉 remote 之後,推過的也不當成沒推、也不收
git -C "$TP/ax-courses" remote remove origin
OUT=$(python3 "$S" sweep "$TP" --apply --skip course_gen 2>&1)
chk "(31) 沒有 remote ⇒ ax-courses-ticket1 落在「問不到遠端」,不當成沒推" 'sec "❔" | grep -qF "ax-courses-ticket1"'
chk "(32) 問不到的也不收" '[ -d "$TP/ax-courses-ticket1" ]'
echo
echo "── D opencloselist 基本盤 ──"
P=$(python3 "$S" open inkstone/ISEP#150 --repo "$TP/ISEP" 2>/dev/null)
chk "(33) open 印出的路徑在 <repo>/.worktrees/ISEP-150" '[ "$P" = "$TP/ISEP/.worktrees/ISEP-150" ] && [ -d "$P" ]'
chk "(34) 主 repo git status 乾淨(info/exclude 有 /.worktrees/" '[ -z "$(git -C "$TP/ISEP" status --porcelain)" ] && grep -qxF "/.worktrees/" "$TP/ISEP/.git/info/exclude"'
chk "(35) 預設分支 feat/150" '[ "$(git -C "$P" branch --show-current)" = feat/150 ]'
chk "(36) tech_projects/ 沒有因 open 多出資料夾" '[ ! -e "$TP/ISEP-150" ] && [ ! -e "$TP/ISEP-wt-150" ]'
echo z > "$P/z"; git -C "$P" add -A; git -C "$P" -c user.email=t@t -c user.name=t commit -qm z
python3 "$S" close inkstone/ISEP#150 --repo "$TP/ISEP" >/dev/null 2>"$ROOT/close.err"; RC=$?
chk "(37) close 沒推 ⇒ 離開碼 2、點名分支與路徑" '[ "$RC" -eq 2 ] && grep -qF "feat/150" "$ROOT/close.err" && grep -qF "$P" "$ROOT/close.err"'
git -C "$P" push -q origin feat/150 2>/dev/null
python3 "$S" close inkstone/ISEP#150 --repo "$TP/ISEP" >/dev/null 2>&1; RC=$?
chk "(38) 推了之後 close ⇒ 0、目錄沒了" '[ "$RC" -eq 0 ] && [ ! -e "$P" ]'
python3 "$S" close inkstone/ISEP#150 --repo "$TP/ISEP" --quiet >/dev/null 2>"$ROOT/close2.err"; RC=$?
chk "(39) 再 close 一次 ⇒ 0、--quiet 不吵" '[ "$RC" -eq 0 ] && [ ! -s "$ROOT/close2.err" ]'
chk "(40) 票寫錯形狀 ⇒ 離開碼 1、講得出正確形狀" 'python3 "$S" open ISEP-150 --repo "$TP/ISEP" 2>&1 | grep -qF "owner/repo#N"'
chk "(41) list 列得出還在的分身" 'python3 "$S" list "$TP" 2>&1 | grep -qF "ISEP-wt-117"'
chk "(42) 上面所有動作之後 tech_projects/ 沒多任何資料夾" '[ "$(ls -1 "$TP" | grep -c .)" -eq 9 ]' # 4 repo 3 分身(ticket1117cg×24)+孤兒 9
echo
echo "══ 通過 $PASS 條,失敗 $FAIL 條(共 $N)══"
[ "$FAIL" -eq 0 ]
+125 -39
View File
@@ -14,7 +14,7 @@ leo 2026-08-16 三句話,本工具就是它們的機械化:
ticket where <關鍵字...> 搜「這件事該放哪」→ 產生戳記 ticket where <關鍵字...> 搜「這件事該放哪」→ 產生戳記
ticket say <票> -F <檔> 貼進既有票的對話(**預設路徑**) ticket say <票> -F <檔> 貼進既有票的對話(**預設路徑**)
ticket new <repo> -F <檔> 開新票(要戳記+模板欄位齊全) ticket new <repo> -F <檔> 開新票(要戳記+模板欄位齊全<repo> 寫 ISEP 或 inkstone/ISEP 都行
ticket close <票> --deliverable <URL> 關票(要有交付物連結) ticket close <票> --deliverable <URL> 關票(要有交付物連結)
ticket decide <票> -F <答案檔> 記 leo 的裁決+改狀態(同一個動作) ticket decide <票> -F <答案檔> 記 leo 的裁決+改狀態(同一個動作)
@@ -132,6 +132,10 @@ def token():
• 或設環境變數 GITEA_TOKEN_CLAUDE_CODE""") • 或設環境變數 GITEA_TOKEN_CLAUDE_CODE""")
_TOLERATE = () # 這一次呼叫可以吞掉的 HTTP 狀態碼(見 add_dependency
_TOLERATED = object() # api() 吞掉時回的哨兵——不是 None,None 是「回應是 null」
def api(path, payload=None, method=None): def api(path, payload=None, method=None):
url = path if path.startswith("http") else f"{HOST}/api/v1{path}" url = path if path.startswith("http") else f"{HOST}/api/v1{path}"
data = json.dumps(payload).encode() if payload is not None else None data = json.dumps(payload).encode() if payload is not None else None
@@ -141,6 +145,8 @@ def api(path, payload=None, method=None):
try: try:
return json.load(urllib.request.urlopen(req, timeout=40)) return json.load(urllib.request.urlopen(req, timeout=40))
except urllib.error.HTTPError as e: except urllib.error.HTTPError as e:
if e.code in _TOLERATE:
return _TOLERATED
die(f"🔴 Gitea {e.code}{e.read().decode()[:300]}") die(f"🔴 Gitea {e.code}{e.read().decode()[:300]}")
@@ -151,6 +157,29 @@ def parse_ref(s):
return m.group(1), m.group(2), int(m.group(3)) return m.group(1), m.group(2), int(m.group(3))
def repo_arg(s):
"""收件 repo 的參數:`ISEP` 與 `inkstone/ISEP` 都收,回 repo 名(不含 org)。
🔴 2026-09-07 實撞(inkstone/ISEP#130):總管照票號的習慣寫 `ticket new inkstone/ISEP`
這支把它原樣接進 `/repos/inkstone/{repo}/issues` ⇒ 打到 `/repos/inkstone/inkstone/ISEP/issues`
⇒ Gitea 回 **404**,而 404 讀起來像「ISEP 這個 repo 不存在」——
於是四張票改成直接打 API 開的,**正門壞了人就走側門**,那正是 `ticket-api-bypass-guard`
在防的事。票號全稱寫 `owner/repo#N` 是本 repo 的鐵律(CLAUDE.md),
所以 `owner/repo` 這個形狀本來就該被接受,不該是 404 的來源。
org 寫成別的(`Leo/ISEP`)⇒ 當場講清楚,不要讓它變成一個 404 去猜。
"""
s = (s or "").strip()
if "/" not in s:
return s
owner, _, name = s.partition("/")
if owner != ORG:
die(f"🔴 收件 repo 的 org 是 `{ORG}`,你給的是 `{owner}`{s})。\n"
f" `Leo/` 那個 org 2026-08-14 已廢;寫 `{ORG}/{name}` 或直接寫 `{name}`。")
if not name or "/" in name or "#" in name:
die(f"🔴 收件 repo 的寫法是 `<repo>` 或 `{ORG}/<repo>`(不帶票號),你給的是:{s}")
return name
def api_soft(path): def api_soft(path):
"""讀一筆,失敗就回 None(不 die)。給「錦上添花」的資訊用,不影響任何判斷。""" """讀一筆,失敗就回 None(不 die)。給「錦上添花」的資訊用,不影響任何判斷。"""
try: try:
@@ -289,8 +318,8 @@ def cmd_say(argv):
# ── new ────────────────────────────────────────────────────────────────── # ── new ──────────────────────────────────────────────────────────────────
def cmd_new(argv): def cmd_new(argv):
if len(argv) < 3 or argv[1] not in ("-F", "--file"): if len(argv) < 3 or argv[1] not in ("-F", "--file"):
die("用法:ticket new <repo> -F <內文檔> [--title <標題>]") die("用法:ticket new <repo 或 owner/repo> -F <內文檔> [--title <標題>]")
repo = argv[0] repo = repo_arg(argv[0])
body = open(argv[2]).read() body = open(argv[2]).read()
title = None title = None
if "--title" in argv: if "--title" in argv:
@@ -640,6 +669,31 @@ def _deps(owner, repo, num):
return api(f"/repos/{owner}/{repo}/issues/{num}/dependencies") or [] return api(f"/repos/{owner}/{repo}/issues/{num}/dependencies") or []
def add_dependency(parent, child):
"""讓 `child` 成為 `parent` 的相依(兩個都是 (owner, repo, num))。**冪等**
先讀 parent 的 `/dependencies`,邊已經在就不 POST、回 False——`mainline adopt`
補收同一張票兩次不該炸。
🔴 冪等**不能靠回應碼**2026-09-07 對真 Gitea 實測,重複相依回的是 **500**(不是想像中的 409
——判準改成「Gitea 現在有沒有這條邊」這個事實;409 仍容忍(別的版本可能這樣回)。
`subtask` 與 `mainline adopt`inkstone/ISEP#133)都走這一支:掛相依只有一條路,
而且走的是 `api()`——離線測試把 `api()` 換成錄音機時才錄得到它。"""
global _TOLERATE
po, pr, pn = parent
co, cr, cn = child
want = f"{co}/{cr}#{cn}"
have = api(f"/repos/{po}/{pr}/issues/{pn}/dependencies?limit=100") or []
for d in have:
full = ((d.get("repository") or {}).get("full_name")) if isinstance(d, dict) else None
if full and f"{full}#{d.get('number')}" == want:
return False # 已經是相依
_TOLERATE = (409,)
try:
r = api(f"/repos/{po}/{pr}/issues/{pn}/dependencies", {"owner": co, "repo": cr, "index": cn})
finally:
_TOLERATE = ()
return r is not _TOLERATED
def _blocks(owner, repo, num): def _blocks(owner, repo, num):
"""反方向:**誰把這張票當相依**——也就是這張票的頂層票(可能不只一張、可能跨 repo)。 """反方向:**誰把這張票當相依**——也就是這張票的頂層票(可能不只一張、可能跨 repo)。
@@ -822,7 +876,8 @@ def subtask_example(parent=None, draft=None):
USAGE = { USAGE = {
"pick": "pick":
"用法:{bin} pick [--mainline <主線 json 檔>] [--all] [--json] [--claim [--as <登入名>] [--name <身份>]]\n" "用法:{bin} pick [--mainline <主線 json 檔>] [--all] [--json] [--claim [--as <登入名>] [--name <身份>]]\n"
" 回**一張**現在可以抓的票(主線里程碑抓盡才輪到逾期里程碑;不抓 backlog、不抓沒里程碑的)\n" " 回**一張**現在可以抓的票(主線抓盡才輪到逾期里程碑;不抓 backlog)。主線的成員=hub 里程碑裡的票+\n"
" hub 票+它們的相依(跨 repo)——別 repo 的同名里程碑不算主線(inkstone/ISEP#133\n"
" --mainline 不給時依序找:$ISEP_MAINLINE_FILE → ~/.claude/isep-countdown/mainline.json" " --mainline 不給時依序找:$ISEP_MAINLINE_FILE → ~/.claude/isep-countdown/mainline.json"
" → $CLAUDE_PROJECT_DIR/system-dev/mainline.json\n" " → $CLAUDE_PROJECT_DIR/system-dev/mainline.json\n"
" 離開碼:0 = 有票(印在 stdout);1 = 真的沒有可抓的票;2 = 讀不到(讀不到 ≠ 沒有)", " 離開碼:0 = 有票(印在 stdout);1 = 真的沒有可抓的票;2 = 讀不到(讀不到 ≠ 沒有)",
@@ -912,7 +967,7 @@ def cmd_subtask(argv):
# `--to <repo>` 是 `ticket handoff` 那個名字底下比較自然的講法,同一個東西。 # `--to <repo>` 是 `ticket handoff` 那個名字底下比較自然的講法,同一個東西。
# handback 的 `--to` 是「交給誰」,subtask 沒有那個參數,不會撞。) # handback 的 `--to` 是「交給誰」,subtask 沒有那個參數,不會撞。)
repo = opt("--repo", opt("--to", prepo)) repo = repo_arg(opt("--repo", opt("--to", prepo)))
label = opt("--label", "s/todo") label = opt("--label", "s/todo")
assign = opt("--assign") assign = opt("--assign")
nxt = opt("--next") nxt = opt("--next")
@@ -943,8 +998,7 @@ def cmd_subtask(argv):
print(f" 下一步:{nxt}") print(f" 下一步:{nxt}")
# 🔴 相依掛不上去 = 這張子票對母票是隱形的 ⇒ 整個動作算失敗,要讓人看到 # 🔴 相依掛不上去 = 這張子票對母票是隱形的 ⇒ 整個動作算失敗,要讓人看到
api(f"/repos/{powner}/{prepo}/issues/{pnum}/dependencies", add_dependency((powner, prepo, pnum), (ORG, repo, cnum))
{"owner": ORG, "repo": repo, "index": cnum})
deps = _deps(powner, prepo, pnum) deps = _deps(powner, prepo, pnum)
openn = [i for i in deps if i["state"] == "open"] openn = [i for i in deps if i["state"] == "open"]
print(f" 相依:已掛上 {powner}/{prepo}#{pnum}(它存在、且擋著母票)") print(f" 相依:已掛上 {powner}/{prepo}#{pnum}(它存在、且擋著母票)")
@@ -1276,6 +1330,10 @@ def pickable(issue, milestone_title):
# 2026-09-07 實查:ISEP#3135 五張 hub 掛在逾期里程碑上、s/todo、沒人—— # 2026-09-07 實查:ISEP#3135 五張 hub 掛在逾期里程碑上、s/todo、沒人——
# 照欄位規則會被抓走,但它們不是一件可以做完的事。容器不是任務。 # 照欄位規則會被抓走,但它們不是一件可以做完的事。容器不是任務。
return False, "是 hubscope 容器,不是一件可以做完的事)" return False, "是 hubscope 容器,不是一件可以做完的事)"
if milestone_title is None:
# inkstone/ISEP#133:呼叫端已經用相依邊確認它在主線上(別 repo 的票靠相依進來,
# 本來就不掛 hub 里程碑)⇒ 這一格不看里程碑。
return True, "ok"
ms = (issue.get("milestone") or {}).get("title") ms = (issue.get("milestone") or {}).get("title")
if not ms: if not ms:
return False, "沒有里程碑(backlog/沒排進 sprint 的不抓)" return False, "沒有里程碑(backlog/沒排進 sprint 的不抓)"
@@ -1366,40 +1424,65 @@ def _issues_in(owner, repo, title):
return [it for it in rows if isinstance(it, dict)] return [it for it in rows if isinstance(it, dict)]
def _fetch_issue(ref):
ML = _mainline_lib()
parts = ML.split_ref(ref)
if not parts:
return None
it = api("/repos/%s/%s/issues/%d" % parts)
if not isinstance(it, dict) or not it.get("number"):
return None
it.setdefault("repository", {"full_name": "%s/%s" % parts[:2]})
return it
def mainline_members(ms):
"""主線的成員(inkstone/ISEP#133):hub 里程碑裡的票+hub 票+它們的相依(跨 repo)。
判準在 `hooks/lib/mainline.py::collect_members`,這裡只是把本檔的 `api` 遞進去。"""
return _mainline_lib().collect_members(api, ms)
def pick_candidates(ms, now=None): def pick_candidates(ms, now=None):
"""依序回 [(組名, 里程碑標題, [可抓的票…])]:第一組是主線,之後是逾期的 open 里程碑 """依序回 [(組名, 里程碑標題, [可抓的票…])]:第一組是主線,之後是逾期的 open 里程碑
(最逾期的先)。**每一組裡都已經照 pick_order 排好。**""" (最逾期的先)。**每一組裡都已經照 pick_order 排好。**
主線那一組的成員由相依邊決定(`mainline_members`),**不是**同名里程碑:
別 repo 裡叫同一個名字的里程碑,裡面的票不會被當成主線抓走(inkstone/ISEP#133)。
逾期那幾組是**一個里程碑物件一組**(owner/repo#id),同名不合併。"""
ML = _mainline_lib() ML = _mainline_lib()
now = now or _now() now = now or _now()
owner = ms.get("owner") or ORG owner = ms.get("owner") or ORG
anchor = "%s/%s#%s" % (ms.get("owner"), ms.get("repo"), ms.get("id"))
refs, info = mainline_members(ms)
found = []
for ref in refs:
it = _fetch_issue(ref)
if not it or (it.get("state") or "open") != "open":
continue
ok, _ = pickable(it, None)
if ok:
found.append(it)
groups = [("主線", ms["title"], sorted(found, key=pick_order))]
repos = _repos(owner) repos = _repos(owner)
opened = _open_milestones(owner, repos) overdue = []
groups = [] for r, m in _open_milestones(owner, repos):
if "%s/%s#%s" % (owner, r, m.get("id")) == anchor:
def collect(title):
found = []
for r, m in opened:
if ML.norm(m.get("title")) != ML.norm(title):
continue
for it in _issues_in(owner, r, m.get("title")):
ok, _ = pickable(it, title)
if ok:
found.append(it)
return sorted(found, key=pick_order)
groups.append(("主線", ms["title"], collect(ms["title"])))
overdue = {}
for r, m in opened:
if ML.norm(m.get("title")) == ML.norm(ms["title"]):
continue continue
due = ML.due_of(m) due = ML.due_of(m)
if due and due < now: if due and due < now:
key = ML.norm(m.get("title")) overdue.append((due, r, m))
if key not in overdue or due < overdue[key][0]: for due, r, m in sorted(overdue, key=lambda x: x[0]):
overdue[key] = (due, m.get("title")) found = []
for due, title in sorted(overdue.values()): for it in _issues_in(owner, r, m.get("title")):
groups.append(("逾期里程碑", title, collect(title))) if str((it.get("milestone") or {}).get("id")) != str(m.get("id")):
continue
ok, _ = pickable(it, m.get("title"))
if ok:
found.append(it)
groups.append(("逾期里程碑", "%s%s/%s#%s" % (m.get("title"), owner, r, m.get("id")),
sorted(found, key=pick_order)))
return groups return groups
@@ -1473,17 +1556,20 @@ def cmd_claim(argv):
issue = api("/repos/%s/%s/issues/%d" % (owner, repo, num)) issue = api("/repos/%s/%s/issues/%d" % (owner, repo, num))
issue.setdefault("repository", {"full_name": "%s/%s" % (owner, repo)}) issue.setdefault("repository", {"full_name": "%s/%s" % (owner, repo)})
ims = issue.get("milestone") or {} ims = issue.get("milestone") or {}
ok, why = pickable(issue, ims.get("title") or "") ref = "%s/%s#%d" % (owner, repo, num)
if ok: # 在不在主線上:看相依邊與 hub 里程碑(inkstone/ISEP#133),不看標題
on_mainline = ML.norm(ims.get("title")) == ML.norm(ms["title"]) on_mainline = ref in set(mainline_members(ms)[0])
ok, why = pickable(issue, None if on_mainline else (ims.get("title") or ""))
if ok and not on_mainline:
due = ML.due_of(ims) due = ML.due_of(ims)
if not on_mainline and not (due and due < _now()): if not (due and due < _now()):
ok, why = False, "里程碑「%s」既不是主線「%s」也還沒逾期" % (ims.get("title"), ms["title"]) ok, why = False, "里程碑「%s」既不是主線「%s」也還沒逾期(別 repo 的同名里程碑不算主線)" % (
ims.get("title"), ms["title"])
if not ok: if not ok:
die("""🚫 %s/%s#%d 現在不能抓:%s die("""🚫 %s/%s#%d 現在不能抓:%s
抓票規則(inkstone/ISEP#131,全部是 Gitea 欄位): 抓票規則(inkstone/ISEP#131,全部是 Gitea 欄位):
s/* 恰好是 s/todo 沒有 assignee 沒有 Humanhuman/* 里程碑是主線(主線抓盡才抓逾期) s/* 恰好是 s/todo 沒有 assignee 沒有 Humanhuman/* 在主線上(hub 里程碑或相依;主線抓盡才抓逾期)
出路:`%s pick` 會回一張符合規則的票;這張如果真的該你做,回票上問總管改欄位,不要硬抓。""" % ( 出路:`%s pick` 會回一張符合規則的票;這張如果真的該你做,回票上問總管改欄位,不要硬抓。""" % (
owner, repo, num, why, self_path())) owner, repo, num, why, self_path()))
@@ -1492,7 +1578,7 @@ def cmd_claim(argv):
_set_labels(owner, repo, num, keep) _set_labels(owner, repo, num, keep)
lines = [ident, "", lines = [ident, "",
"🙋 **認領** → `%s`" % who, "", "🙋 **認領** → `%s`" % who, "",
"- 里程碑:「%s」%s" % (ims.get("title"), "(主線)" if ML.norm(ims.get("title")) == ML.norm(ms["title"]) else "(逾期里程碑,主線已抓盡)"), "- 里程碑:「%s」%s" % (ims.get("title") or "(無,靠相依在主線上)", "(主線)" if on_mainline else "(逾期里程碑,主線已抓盡)"),
"- 狀態:s/todo → s/doing", "- 狀態:s/todo → s/doing",
"- 做完:分支+證據 → `s/review` `ticket handback`(不推 main、不出貨、不改里程碑)"] "- 做完:分支+證據 → `s/review` `ticket handback`(不推 main、不出貨、不改里程碑)"]
api("/repos/%s/%s/issues/%d/comments" % (owner, repo, num), {"body": "\n".join(lines)}) api("/repos/%s/%s/issues/%d/comments" % (owner, repo, num), {"body": "\n".join(lines)})
+553
View File
@@ -0,0 +1,553 @@
#!/usr/bin/env python3
"""worktree — 一條線的分身住在 repo **裡面**`.worktrees/`),收工時被收掉。
leo 2026-09-07inkstone/ISEP#147,一字不改):
「我看到的是一個 repo,你會產生大量的同一個頭不同尾巴的 repo,全部拆開就更亂了,
為什麼要產出新的 repo?這個 repo 的目的就是收納所有相關的內容,這樣散開造成凌亂」
「另外要在 ISEP 裡寫明,禁止這樣產出一大堆資料夾」
那些不是 repo,是 `hooks/line-needs-own-worktree.sh`inkstone/ISEP#109)教工人開在
repo **旁邊**的 git worktree——「收工時 `worktree remove`」只寫在閘訊息裡,沒有任何機制驗,
每個工人留一份,`tech_projects/` 就長成 `ISEP-wt-117``ISEP-wt115``InkStoneCo-wt-112`…。
**規則在文字裡,不在機器上。** 本工具把兩端都放到機器上:
worktree open <owner/repo#N> [--repo <路徑>] [-b <分支>]
開一份:<repo>/.worktrees/<repo名>-<N>,並把 `/.worktrees/` 寫進該 repo 的
.git/info/exclude(不動任何被追蹤的檔)。冪等:已經開過就印出路徑。
worktree close <owner/repo#N> [--repo <路徑>] [--scan <目錄>]... [--quiet]
收:分支推上遠端且工作樹乾淨 ⇒ remove+prune;否則離開碼 2、印出分支與路徑。
**不 force、不刪任何沒推的 commit。**
worktree list [<目錄>...]
列:每個 repo 的分身、分支、推了沒、乾不乾淨。
worktree sweep <目錄> [--apply] [--skip <repo名>]...
leo 在 Mac 上跑一次的整理工具:逐個 repo 列分身;預設只列不動,
`--apply` 才收——而且只收「推了且乾淨」的;沒推的列出來等他決定。
`--skip` 是操作者點名不碰的 repo(例:地端正在處理的線),不是判準。
「推了沒」的判準(跟 hooks/unpushed-police.sh 同一套,三態不是兩態):
0 遠端有這顆 commit 1 遠端沒有 2 問不到(沒 remote/網路不通)
2 一律不收——把「離線」當成「你沒推」再收掉,就是拿雜訊懲罰謹慎;
但 2 也一律**點名**,因為它同樣是留在那裡的一份分身。
判準是「這個目錄是不是某個 repo 的 worktree、它的分支推了沒、工作樹乾不乾淨」——
三件都是 git 自己回答的事實,沒有任何一條看名字、看關鍵字。
"""
import os
import re
import subprocess
import sys
WT_DIR = ".worktrees"
EXCLUDE_LINE = "/" + WT_DIR + "/"
TICKET_RE = re.compile(r"^([A-Za-z0-9_.-]+)/([A-Za-z0-9_.-]+)#(\d+)$")
GOVERNANCE = "docs/governance/worktree-placement.md"
GIT_ENV = dict(os.environ, GIT_TERMINAL_PROMPT="0", GIT_ASKPASS="/bin/echo",
GIT_SSH_COMMAND="ssh -oBatchMode=yes", LC_ALL="C")
def run(args, cwd=None, timeout=None):
try:
p = subprocess.run(args, cwd=cwd, env=GIT_ENV, capture_output=True, text=True, timeout=timeout)
except (OSError, subprocess.TimeoutExpired):
return 124, "", ""
return p.returncode, p.stdout, p.stderr
def git(repo, *args, timeout=None):
return run(["git", "-C", repo] + list(args), timeout=timeout)
def out(repo, *args):
rc, o, _ = git(repo, *args)
return o.strip() if rc == 0 else ""
def die(msg, code=1):
sys.stderr.write(msg.rstrip() + "\n")
sys.exit(code)
def self_path():
"""印給人複製的指令一律用這個(mistakes.md「閘印出來的那條出路跑不動」:相對路徑會對貼的人的 cwd 解析)。"""
return os.path.realpath(__file__)
def parse_ticket(s):
m = TICKET_RE.match((s or "").strip())
if not m:
die("票要寫成 owner/repo#N(例:inkstone/ISEP#147),收到的是:%r" % (s,), 1)
return m.group(1), m.group(2), m.group(3)
def wt_name(repo, num):
return "%s-%s" % (repo, num)
# ── git 事實 ────────────────────────────────────────────────────────────
def common_dir(path):
"""這個路徑所屬 repo 的共用 .git(主工作目錄那一份);不是 repo 回 None。"""
rc, o, _ = git(path, "rev-parse", "--path-format=absolute", "--git-common-dir")
if rc != 0:
rc, o, _ = git(path, "rev-parse", "--git-common-dir")
if rc != 0:
return None
o = os.path.join(path, o.strip()) if not os.path.isabs(o.strip()) else o.strip()
return os.path.realpath(o.strip())
def main_top(path):
"""主工作目錄(大家共用的那一份)的絕對路徑;bare/不是 repo 回 None。"""
cd = common_dir(path)
if not cd:
return None
top = os.path.dirname(cd) if os.path.basename(cd) == ".git" else None
if not top:
return None
rc, o, _ = git(top, "rev-parse", "--show-toplevel")
return os.path.realpath(o.strip()) if rc == 0 else None
def is_main_worktree(path):
rc, gd, _ = git(path, "rev-parse", "--path-format=absolute", "--git-dir")
rc2, cd, _ = git(path, "rev-parse", "--path-format=absolute", "--git-common-dir")
if rc != 0 or rc2 != 0:
return False
return os.path.realpath(gd.strip()) == os.path.realpath(cd.strip())
def list_linked(main):
"""`git worktree list --porcelain`:主工作目錄以外的每一份。"""
rc, o, _ = git(main, "worktree", "list", "--porcelain")
if rc != 0:
return []
entries, cur = [], None
for line in o.splitlines() + [""]:
if not line:
if cur:
entries.append(cur)
cur = None
continue
k, _, v = line.partition(" ")
if k == "worktree":
cur = {"path": os.path.realpath(v), "raw": v, "branch": "", "sha": "", "prunable": "", "bare": False}
elif cur is None:
continue
elif k == "HEAD":
cur["sha"] = v
elif k == "branch":
cur["branch"] = v[len("refs/heads/"):] if v.startswith("refs/heads/") else v
elif k == "prunable":
cur["prunable"] = v or "prunable"
elif k == "bare":
cur["bare"] = True
mt = os.path.realpath(main)
return [e for e in entries if e["path"] != mt and not e["bare"]]
def ls_remote_heads(repo, remote, cache={}):
key = (repo, remote)
if key not in cache:
rc, o, _ = git(repo, "ls-remote", "--heads", remote, timeout=15)
cache[key] = [ln.split() for ln in o.splitlines() if ln.strip()] if rc == 0 and o.strip() else None
return cache[key]
def remote_has_commit(repo, sha):
"""0 遠端有/1 遠端沒有/2 問不到(沿用 hooks/unpushed-police.sh 的三態)。"""
if not sha:
return 2
if out(repo, "branch", "-r", "--contains", sha):
return 0
asked = False
for rm in out(repo, "remote").split():
heads = ls_remote_heads(repo, rm)
if heads is None:
continue
asked = True
for rsha, _ref in heads:
if rsha == sha:
return 0
rc, _, _ = git(repo, "cat-file", "-e", rsha + "^{commit}")
if rc == 0:
rc2, _, _ = git(repo, "merge-base", "--is-ancestor", sha, rsha)
if rc2 == 0:
return 0
return 1 if asked else 2
def classify(main, e):
"""一份分身的事實:dirtypushedverdict。verdict ∈ collect|unpushed|dirty|unknown|prunable。"""
r = dict(e)
r["main"] = main
if e["prunable"] or not os.path.isdir(e["path"]):
r["dirty"] = 0
r["pushed"] = 2
r["verdict"] = "prunable"
return r
rc, st, _ = git(e["path"], "status", "--porcelain", "--untracked-files=normal")
r["dirty"] = len([ln for ln in st.splitlines() if ln.strip()]) if rc == 0 else 0
sha = e["sha"] or out(e["path"], "rev-parse", "HEAD")
r["sha"] = sha
r["pushed"] = remote_has_commit(main, sha)
if r["dirty"]:
r["verdict"] = "dirty"
elif r["pushed"] == 0:
r["verdict"] = "collect"
elif r["pushed"] == 1:
r["verdict"] = "unpushed"
else:
r["verdict"] = "unknown"
return r
def ensure_exclude(main):
cd = common_dir(main)
if not cd:
return False
info = os.path.join(cd, "info")
os.makedirs(info, exist_ok=True)
f = os.path.join(info, "exclude")
try:
lines = open(f, encoding="utf-8", errors="replace").read().splitlines() if os.path.exists(f) else []
except OSError:
lines = []
if EXCLUDE_LINE in [ln.strip() for ln in lines]:
return True
with open(f, "a", encoding="utf-8") as fh:
if lines and not lines[-1].endswith("\n"):
fh.write("\n")
fh.write("# 一條線的分身住這裡,不住 repo 旁邊(inkstone/ISEP#147scripts/worktree 寫的)\n")
fh.write(EXCLUDE_LINE + "\n")
return True
def repos_under(root):
"""root 自己(若是主工作目錄)+它的直接子目錄+ matrix/products/polaris 的子目錄裡的主工作目錄。"""
found, seen = [], set()
def add(p):
if not os.path.isdir(p):
return
rp = os.path.realpath(p)
if rp in seen:
return
seen.add(rp)
if os.path.isdir(os.path.join(rp, ".git")) and is_main_worktree(rp):
found.append(rp)
root = os.path.realpath(root)
add(root)
try:
kids = sorted(os.listdir(root))
except OSError:
kids = []
for k in kids:
if k.startswith(".") and k != WT_DIR:
continue
p = os.path.join(root, k)
add(p)
if k in ("matrix", "products", "polaris") and os.path.isdir(p):
try:
for kk in sorted(os.listdir(p)):
add(os.path.join(p, kk))
except OSError:
pass
return found
def fmt_pushed(v):
return {0: "已推上遠端", 1: "**沒推**", 2: "問不到遠端"}[v]
def describe(r):
br = r["branch"] or ("detached %s" % r["sha"][:7])
if r["verdict"] == "prunable":
return "%s ← 登記指向空氣(目錄已不在)" % r["path"]
bits = [fmt_pushed(r["pushed"])]
if r["dirty"]:
bits.append("**%d 個未 commit/未追蹤檔**" % r["dirty"])
return "%s\n 分支 %s%s%s" % (r["path"], br, r["sha"][:7], "、".join(bits))
def push_hint(r):
rm = (out(r["main"], "remote").split() or ["origin"])[0]
br = r["branch"] or "<分支>"
return "git -C %s push %s %s" % (r["path"], rm, br)
def remove_one(r):
"""只在 verdict==collect 時呼叫。不 force:git 自己拒絕的(有東西沒交代)就照實回報。"""
rc, _, err = git(r["main"], "worktree", "remove", r["path"])
git(r["main"], "worktree", "prune")
return rc == 0, err.strip()
# ── 動詞 ────────────────────────────────────────────────────────────────
def take_opt(argv, name, default=None, many=False):
vals, rest, i = [], [], 0
while i < len(argv):
if argv[i] == name and i + 1 < len(argv):
vals.append(argv[i + 1])
i += 2
continue
rest.append(argv[i])
i += 1
if many:
return vals, rest
return (vals[-1] if vals else default), rest
def cmd_open(argv):
repo_opt, argv = take_opt(argv, "--repo")
branch, argv = take_opt(argv, "-b")
if not argv:
die("用法:worktree open <owner/repo#N> [--repo <路徑>] [-b <分支>]")
owner, repo, num = parse_ticket(argv[0])
main = main_top(repo_opt or os.getcwd())
if not main:
die("%s 不是任何 git repo 的一部分。用 --repo 指到要開分身的那個 repo。" % (repo_opt or os.getcwd()))
name = wt_name(repo, num)
dest = os.path.join(main, WT_DIR, name)
ensure_exclude(main)
for e in list_linked(main):
if e["path"] == os.path.realpath(dest):
print(dest)
sys.stderr.write("已經開過了(分支 %s)。直接 cd 進去做事。\n" % (e["branch"] or "?"))
return 0
os.makedirs(os.path.join(main, WT_DIR), exist_ok=True)
branch = branch or "feat/%s" % num
rc_b, _, _ = git(main, "rev-parse", "--verify", "-q", "refs/heads/" + branch)
args = ["worktree", "add", dest] + ([branch] if rc_b == 0 else ["-b", branch])
rc, o, err = git(main, *args)
if rc != 0:
die("git worktree add 失敗:\n%s" % err.strip(), 1)
print(dest)
sys.stderr.write(
"🌱 分身開在 repo 裡面:%s(分支 %s\n"
" cd %s\n"
" 收工:python3 %s close %s/%s#%s --repo %s\n" % (dest, branch, dest, self_path(), owner, repo, num, main))
return 0
def find_by_ticket(roots, name):
hits = []
for root in roots:
for main in repos_under(root):
for e in list_linked(main):
if os.path.basename(e["path"]) == name:
hits.append((main, e))
# 同一份分身可能從兩個 root 都走得到;去重
uniq, seen = [], set()
for main, e in hits:
if e["path"] in seen:
continue
seen.add(e["path"])
uniq.append((main, e))
return uniq
def cmd_close(argv):
repo_opt, argv = take_opt(argv, "--repo")
scans, argv = take_opt(argv, "--scan", many=True)
quiet = "--quiet" in argv
argv = [a for a in argv if a != "--quiet"]
if not argv:
die("用法:worktree close <owner/repo#N> [--repo <路徑>] [--scan <目錄>]... [--quiet]")
owner, repo, num = parse_ticket(argv[0])
name = wt_name(repo, num)
roots = list(scans)
if repo_opt:
roots.append(repo_opt)
if not roots:
roots = [main_top(os.getcwd()) or os.getcwd()]
hits = find_by_ticket(roots, name)
if not hits:
if not quiet:
sys.stderr.write("沒有找到 %s/%s#%s 的分身(找的是 .worktrees/%s,範圍:%s)。\n" % (owner, repo, num, name, "、".join(roots)))
return 0
bad = []
for main, e in hits:
r = classify(main, e)
if r["verdict"] == "prunable":
git(main, "worktree", "prune")
sys.stderr.write("🧹 %s 的登記指向空氣,已 prune。\n" % r["path"])
continue
if r["verdict"] == "collect":
ok, err = remove_one(r)
if ok:
sys.stderr.write("🧹 收掉 %s(分支 %s 已在遠端,工作樹乾淨)。\n" % (r["path"], r["branch"] or r["sha"][:7]))
continue
r["verdict"] = "dirty"
r["git_said"] = err
bad.append(r)
if not bad:
return 0
lines = ["🌳 %s/%s#%s 的分身**沒有收掉**——不是靜默留著,是這裡點名:" % (owner, repo, num), ""]
for r in bad:
lines.append(" ❌ " + describe(r))
if r["verdict"] == "unpushed":
lines.append(" 沒推就不收(不刪任何沒推的 commit)。推了再收:")
lines.append(" %s" % push_hint(r))
elif r["verdict"] == "dirty":
lines.append(" 有東西沒交代。commit 並推、或 `git -C %s stash`/丟掉,再收:" % r["path"])
if r.get("git_said"):
lines.append(" git 說:%s" % r["git_said"].splitlines()[-1])
elif r["verdict"] == "unknown":
lines.append(" 問不到遠端(沒 remote/網路不通)——**不當成沒推**,也不收。網路回來再收:")
lines.append(" python3 %s close %s/%s#%s --repo %s" % (self_path(), owner, repo, num, r["main"]))
lines.append("")
lines.append(" 規約:%sinkstone/ISEP#147" % GOVERNANCE)
sys.stderr.write("\n".join(lines) + "\n")
return 2
def gather(roots, skip):
"""回 (rows, orphans, skipped_rows)。rows=每份分身的 classifyorphans=看起來是 worktree 但沒人登記它的目錄。"""
rows, skipped, registered = [], [], set()
mains = []
for root in roots:
for m in repos_under(root):
if m not in mains:
mains.append(m)
for main in mains:
linked = list_linked(main)
for e in linked:
registered.add(e["path"])
if os.path.basename(main) in skip:
for e in linked:
r = dict(e)
r["main"] = main
r["verdict"] = "skipped"
r["dirty"] = 0
r["pushed"] = 2
skipped.append(r)
continue
for e in linked:
rows.append(classify(main, e))
orphans = []
for root in roots:
try:
kids = sorted(os.listdir(root))
except OSError:
kids = []
for k in kids:
p = os.path.realpath(os.path.join(root, k))
gitfile = os.path.join(p, ".git")
if not os.path.isfile(gitfile) or p in registered:
continue
try:
gd = open(gitfile, encoding="utf-8", errors="replace").read().strip()
except OSError:
gd = ""
gd = gd[len("gitdir:"):].strip() if gd.startswith("gitdir:") else gd
owner_main = ""
m = re.search(r"^(.*)/\.git/worktrees/[^/]+/?$", gd)
if m:
owner_main = m.group(1)
if owner_main and os.path.basename(owner_main) in skip:
skipped.append({"path": p, "main": owner_main, "verdict": "skipped", "branch": "", "sha": "", "dirty": 0, "pushed": 2})
continue
orphans.append({"path": p, "gitdir": gd, "main": owner_main})
return rows, orphans, skipped
def cmd_list(argv):
roots = argv or [os.getcwd()]
rows, orphans, _ = gather(roots, set())
if not rows and not orphans:
print("沒有任何分身。")
return 0
for r in rows:
print(" %s %s" % ({"collect": "🟢", "unpushed": "🔴", "dirty": "🟡", "unknown": "❔", "prunable": "👻"}[r["verdict"]], describe(r)))
for o in orphans:
print(" ❓ %s ← .git 檔指向 %s,但沒有任何 repo 登記它" % (o["path"], o["gitdir"] or "?"))
return 0
def cmd_sweep(argv):
skip, argv = take_opt(argv, "--skip", many=True)
apply = "--apply" in argv
argv = [a for a in argv if a != "--apply"]
if not argv:
die("用法:worktree sweep <目錄> [--apply] [--skip <repo名>]...")
root = os.path.realpath(argv[0])
if not os.path.isdir(root):
die("%s 不是目錄" % root)
skip = set(skip)
rows, orphans, skipped = gather([root], skip)
groups = {"collect": [], "unpushed": [], "dirty": [], "unknown": [], "prunable": []}
for r in rows:
groups[r["verdict"]].append(r)
print("🔎 %s 底下的分身(%s" % (root, "**--apply:會收**" if apply else "只列不動;加 --apply 才收"))
print()
removed, failed = [], []
if groups["collect"]:
print("🟢 推了且乾淨(%d)——%s" % (len(groups["collect"]), "收掉" if apply else "可以收"))
for r in groups["collect"]:
print(" " + describe(r))
if apply:
ok, err = remove_one(r)
if ok:
removed.append(r)
print(" 🧹 已收")
else:
failed.append(r)
print(" ❌ git 拒絕:%s" % (err.splitlines()[-1] if err else "?"))
print()
if groups["prunable"]:
print("👻 登記指向空氣(%d)——%s" % (len(groups["prunable"]), "prune" if apply else "可以 prune"))
for r in groups["prunable"]:
print(" " + describe(r))
if apply:
git(r["main"], "worktree", "prune")
print(" 🧹 已 prune")
print()
if groups["unpushed"]:
print("🔴 **沒推**(%d)——不動,你決定:推了再收、或確認作廢後自己刪" % len(groups["unpushed"]))
for r in groups["unpushed"]:
print(" " + describe(r))
print(" 推:%s" % push_hint(r))
print()
if groups["dirty"]:
print("🟡 有未 commit/未追蹤的東西(%d)——不動" % len(groups["dirty"]))
for r in groups["dirty"]:
print(" " + describe(r))
print()
if groups["unknown"]:
print("❔ 問不到遠端(%d)——不當成沒推、也不收" % len(groups["unknown"]))
for r in groups["unknown"]:
print(" " + describe(r))
print()
if skipped:
print("⏭️ --skip 點名不碰(%d" % len(skipped))
for r in skipped:
print(" %s ← %s" % (r["path"], os.path.basename(r["main"]) if r["main"] else "?"))
print()
if orphans:
print("❓ 看起來是分身、但沒有任何 repo 登記它(%d)——不動,只能人看" % len(orphans))
for o in orphans:
print(" %s ← .git 檔指向 %s" % (o["path"], o["gitdir"] or "?"))
print()
left = len(groups["unpushed"]) + len(groups["dirty"]) + len(groups["unknown"]) + len(orphans) + len(failed)
if apply:
print("── 收了 %d 份,留 %d 份等你決定 ──" % (len(removed), left + (0 if apply else len(groups["collect"]))))
else:
print("── 可收 %d 份,%d 份要你決定;沒有動任何東西 ──" % (len(groups["collect"]) + len(groups["prunable"]), left))
return 2 if left else 0
def main(argv):
if not argv or argv[0] in ("-h", "--help", "help"):
print(__doc__)
return 0
verb, rest = argv[0], argv[1:]
fn = {"open": cmd_open, "close": cmd_close, "list": cmd_list, "sweep": cmd_sweep}.get(verb)
if not fn:
die("不認識的動詞 %r。有:opencloselistsweep--help 看全文)" % verb)
return fn(rest)
if __name__ == "__main__":
sys.exit(main(sys.argv[1:]))
+242
View File
@@ -229,3 +229,245 @@ leo 當場:「**這些為什麼不寫到票裡?**」
**推廣**:repo 裡任何「這台機器該有什麼」的清單,都要有一支東西定期拿它去問機器。 **推廣**:repo 裡任何「這台機器該有什麼」的清單,都要有一支東西定期拿它去問機器。
清單自己不會知道它漏了什麼。 清單自己不會知道它漏了什麼。
## ⚠️ MISTAKE: 兩支閘對同一條指令說不同的話,而讀的那一半從來沒被測過
票: `inkstone/ISEP#130`
日期: 2026-09-07
症狀: 09-04 雲端 Routine 的 run log:讀 `notify_leo` 定義被 `leo21c-write-guard.sh` 擋下。
閘的判準明寫「**讀可以,寫不行**」,卻連讀都擋 ⇒ 雲端什麼都拿不到。
實查: ① 舊判準 `-d[[:space:]]``| tr -d '\r'``cut -d=` 這種唯讀的 `-d` 當成 curl 的 body。
`prod-write-guard.sh` 在 2026-08-12 修過**一模一樣**的洞(它的檔頭寫著「一堆唯讀工具也用 -d」),
這支漏了——同一批補丁只改其中一份(`main-and-prod-push-guard.sh` 檔頭記過同款)。
`…/webhooks/named/<ns>/notify_leo/trigger``prod-write-guard.sh` 是白名單(ISEP#63),
在這支卻因為尾巴是 `/trigger` 照擋 ⇒ 撞人閘時發 Telegram 叫 leo 會被擋(InkStoneCo#110 的病)。
③ 這支閘從 08-20 建立到現在**沒有任何測試**,`hooks/tests/` 裡 30 支測試沒有它的——
「讀會不會被誤攔」這格從來沒被驗過,只有「寫會不會被擋」被人肉試過。
原因: 同一個判準(「這條指令會不會真的寫到那台」)散在三支閘裡各寫一份,修一份不會帶動另外兩份;
而沒有測試的那支,誤攔發生時**不會有任何東西喊一聲**——被擋的人在雲端、沒有人在旁邊。
正確做法:
- 修判準時 `grep -l` 找同一族的閘(`prod-write-guard``main-and-prod-push-guard``leo21c-write-guard`),
一次改齊;本次三支都補了 youlin 09-02 起的新子網域 `arcrun-yuga3bse`
- 每一支「擋」的閘都要有「不該擋」那半的測試,測資用**現場真的會下的指令**
(這次是 `cloud-worker.md``progress-guard.md` 裡的原句),不是自己挑好抓的例子。
- 修之前拿新測試跑舊閘,紅的那幾條才是真的改到的(本次 5 條紅);全綠就是測試順著新閘寫的。
## ⚠️ MISTAKE: 雲端連不到 youlin 被記成「HTTP 000」,而 000 有三種病,兩種都不是連線
票: `inkstone/ISEP#130`
日期: 2026-09-07
症狀: 09-04 run log「youlin 從雲端 HTTP 000」;09-07 總管查到舊子網域 `youlin-hsieh-dev` DNS 已死,
以為換名字就通。從雲端打新名 `arcrun-yuga3bse` **還是 000**
實查: `curl` 印的是 `CONNECT tunnel failed, response 403``$HTTPS_PROXY/__agentproxy/status` 記為
`connect_rejected … gateway answered 403 (policy denial)`。同一個 sessionleo21c 200、
git.uncle6.me 200、api.telegram.org 302——**只有 youlin 的主機沒被雲端 egress policy 放行**。
`/root/.ccr/README.md` 明寫:403/407 是組織的 egress policy,不要重試、不要繞路,回報主機名。
原因: `-w '%{http_code}'` 對「DNS 沒有」「proxy 拒絕 CONNECT」「對方沒回」三種都印 000,
而三種的修法各在不同人手上(改名字/leo 放行主機/看實例)。把它們記成同一個數字,
下一個人就會往錯的方向查(09-07 就差點只修名字收工)。
正確做法: 雲端看到 000 先跑 `curl -sS "$HTTPS_PROXY/__agentproxy/status" | jq .recentRelayFailures`
`connect_rejected` 403 ⇒ 是 policy,交給 leo 在 Cloud environment 放行 `*.arcrun-yuga3bse.workers.dev`
不是 ⇒ 才去查名字或實例。記 log 時寫 curl 的錯誤字串(`response 403``Could not resolve host`),不要只寫 000。
## ⚠️ MISTAKE: 正門工具吃 `owner/repo` 會回 404,於是人走了側門
票: `inkstone/ISEP#130` → comment 6120 第 2 件
日期: 2026-09-07
症狀: `scripts/ticket new inkstone/ISEP -F …` 回 Gitea 404;同一天 `ticket say` 對 InkStoneCo 正常。
總管當場改成直接打 API 開了四張票。
實查: `cmd_new` 把第一個參數原樣塞進 `/repos/inkstone/{repo}/issues``/repos/inkstone/inkstone/ISEP/issues`
404 讀起來像「ISEP 這個 repo 不存在」,跟真正的原因隔了一層。`subtask --to` 同款。
原因: 票號的鐵律是全稱 `owner/repo#N`(CLAUDE.md),人自然會把收件 repo 也寫成 `owner/repo`
工具只收短名、錯了又不講清楚 ⇒ **正門壞了,人就走 `ticket-api-bypass-guard.sh` 在防的那條側門**
一道閘把人逼去走它自己禁止的路,那道閘就是在製造違規(`docs/governance/cloud-wiring.md` ② 記過同一句)。
正確做法: `repo_arg()` 兩種寫法都收;org 寫錯(`Leo/`)當場講「org 是 inkstone」,不讓它變成一個要人猜的 404。
測試 `scripts/test-ticket-repo-arg.sh``api()` 換成假貨記路徑,離線驗路徑裡不准出現 `inkstone/inkstone`
## ⚠️ MISTAKE: 權限白名單是「逐條比前綴」,複合指令永遠對不上——而假伺服器照自己的想像回 200
票: `inkstone/ISEP#137`(母票 `inkstone/ISEP#130`
日期: 2026-09-07
症狀: 三條主線工人在雲端對 stage 的寫入全被 Claude Code auto mode 分類器擋:
`printf … | npx wrangler secret put …``python3 scripts/stage-deploy-artifacts.py all --confirm`
`curl -X POST …arcrun-yuga3bse.workers.dev/records`。同一回合連 `ticket where <含 token 字樣>` 都被擋。
leo:「為什麼會擋你,這就是要修復的問題」「本機環境跟你不同應該不行」。
實查: `docs/permissions-allow.json` 的每一條是**完全比對前綴**。`cd … && printf … | VAR=… npx …` 這種複合指令
沒有任何一條對得上,任意寫法的 curl 更不可能;放整類(`Bash(npx *)``Bash(curl *)`)又是紅線。
⇒ 分類器擋的不是「這件事」,是「這個形狀沒被事先放行」。
原因: 正門工具的價值在**形狀固定**——一條規則就能事先放行。之前四個正門(ticketmainlinegate-okgitea-pr-merge
都是這樣活下來的;對 stage 的寫入沒有正門,人就只能拼複合指令,而複合指令天生對不上任何前綴。
正確做法:
- 每一種要放行的動作收成一支固定形狀(`scripts/stage secret …``stage api …`),白名單放它四種呼叫形狀。
「只打 stage」寫死在程式裡(帳號 ID 現查、主機後綴固定),不靠變數名字裡有沒有 `leo21c`
- 別的 repo 已經有的正門(Arcrun `stage-deploy-artifacts.py` 自己寫死 youlin 帳號 ID)**直接放它的形狀**,不重造一支。
- 值只從環境變數名讀;`--value``--bearer``--header` 一律拒收——指令列會進 shell 歷史與 session log。
📌 同票第二個坑:**假伺服器要照真 API 回,不是照自己的想像回。**
離線測試的假 CF 對 secret PUT 回 20027/27 全綠;第一次真跑 CF 回 **201**,工具把它講成「失敗」——
而獨立用 CF API 一列,那把 secret 明明種進去了。全綠的測試證明的是「工具跟假伺服器合得來」,
不是「工具跟 CF 合得來」。⇒ 假伺服器的回應碼要抄真的(現在回 201),而且**離線全綠之後一定要真跑一次**。
## ⚠️ MISTAKE: 前置條件判的是「手邊的樹」,而要送出去的東西是「那個 tag 的樹」
票: `inkstone/ISEP#67` → comment 6574
日期: 2026-09-07
症狀: 總管在 v0.23.0 的 checkout 跑 `release-ship v0.23.0 --dry-run` 被擋,訊息說
「最新 tag 是 v0.24.0」。v0.23.0 的樹明明一致,只因為它不是最新的那個 tag,
就永遠建不了 release——而 09-07 缺 release 的正是 v0.23.0 與 v0.24.0 兩個。
實查: 09-05 那版 release-ship 的前置①直接跑 `check-version-consistency.sh`
(工作樹 `plugin.json` vs **本機最新** tag)當判準,理由寫著「不另立判準」。
但那支守的是「打 tag 那一刻 main 跟最新 tag 一致」(release-tag-guard.sh 的事),
建 release 這一刻要問的是「**要送的那個 tag 的樹**,自己講的版本對不對」——
工作樹可能是任何分支(release-ship 本身就是在一條 feature 分支上寫的),跟那個 tag 無關。
原因: 「重用既有判準」是對的方向,但重用之前要問「**它判的是哪個對象**」。
對象錯了,判準再對也只是在檢查一個跟交付物無關的東西——而且會用一條看起來
很有道理的訊息把正確的操作擋掉(誤攔)。
正確做法: 前置①改成問 Gitea `contents/.claude-plugin/plugin.json?ref=<tag>`
比的是 tag 自己的樹;工作樹的版本完全不參與(`scripts/test-release-ship.sh` 把工作樹
故意擺成 `9.9.9`,B 群全綠才算證明)。同時把「問 Gitea」收成一份
`hooks/lib/release_chain.py`),release-shiprelease-checkSessionStart 信標三處共用——
判準散在三處各寫一份,就是 `leo21c-write-guard.sh` 那一族漂掉的路。
📌 判準:**送出去之前,先問「我判的是不是我要送的那個東西」**。
工作樹、最新 tag、main——都不是;tag 指到的那棵樹才是。
## ⚠️ MISTAKE: 派工單的紅線建立在「Gitea 匿名讀得到」上,而那件事沒人打過一次
票: `inkstone/ISEP#140`(母票 `inkstone/ISEP#130`
日期: 2026-09-07
症狀: 工單 comment 6611 寫「主線指標在 Gitea 上讀得到(匿名讀 raw 檔或 API contentsD20 讀不擋)」,
紅線據此寫成「讀 Gitea 一律匿名,不帶 token」。開工第一個指令匿名打
`/api/v1/repos/inkstone/InkStoneCo/raw/…``/contents/…``/repos/inkstone/InkStoneCo`**三個都 404**
`inkstone/ISEP` 同樣的三個端點 200 ⇒ 不是網路,是 InkStoneCo 在 Gitea 是 private。
實查: 照紅線字面做(純匿名)⇒ 這張票在真環境永遠讀不到,測試卻可以全綠(假伺服器照自己的想像回 200,
同日 #137 那條坑的翻版)。而 SessionStart 同一條鏈上的 `countdown-milestone-refresh.sh`
`mainline refresh` 本來就帶 `GITEA_TOKEN_CLAUDE_CODE` 打 GiteaD20 管的是 GitHub 那個會被 flag 的帳號,
不是 Gitea 機器帳號的讀。
原因: 「讀得到」是一個可以一個指令驗掉的事實宣稱,卻被當成前提直接寫進紅線;收工方若不打那一下,
就會交出一個「測試全綠、雲端永遠退回舊線」的東西——形狀跟 #137「假伺服器回 200」一模一樣。
正確做法: 匿名優先、匿名被拒(401/403/404)且環境拿得到 token 才帶 token 再問一次(`fetch_gitea()`);
假伺服器要有 private 模式(匿名 404、帶 token 200)照真 Gitea 回;真跑兩條都跑(帶 token 讀到、拔 token 退回)。
收到「X 讀得到/X 不存在」這種宣稱先打一次再動手——那是一個 curl 的成本。
## ⚠️ MISTAKE: 閘看的是 hook 自己的環境/cwd,不是指令要動的那個 repo
票: `inkstone/ISEP#109`comment 65876629);`inkstone/ISEP#125` 是缺陷 A 與 D 的原票(09-02 開)
日期: 2026-09-07
症狀: 同一天兩支閘同一個病。① `line-needs-own-worktree.sh` 印的出路
`WORKTREE_OK=1 git -C … checkout …` 照貼三次三次被擋。
`github-contact-guard.sh``git -C <InkStoneCo> push origin x` 判成「remote origin 指向 GitHub」擋下
(總管站在薄殼 cwdInkStoneCo 的 origin 明明是 Gitea),連 `-C` 都沒看;
同日 arcrun-hand 在 `Arcrun#176` comment 6614 撞到同一支。當天只能改用完整 Gitea 網址推,
而那種形狀分類器又時過時不過。
實查: ① hook 讀的是 `$WORKTREE_OK` 這個**環境變數**。PreToolUse hook 跟指令不是同一個行程,
指令字串裡的 `WORKTREE_OK=1` 是給 git 的前綴賦值,hook 的行程裡永遠沒有它
⇒ 那條出路在 Claude Code 底下**結構上**走不通,不是偶爾。(`NOT_MY_BRANCH_OK` 同形狀,見下)
② hook 拿 **payload 的 cwd**`git remote get-url origin`,而 `-C``cd … &&` 改的是
指令自己的目錄。`main-and-prod-push-guard.sh` 08-23 就為同一個病接了
`lib/push_target_dir.py``inkstone/ISEP#30` comment 3949)——**同一族的另一支沒跟上**,
`leo21c-write-guard.sh` 那條坑一模一樣(修一份不會帶動另外兩份)。
修之前拿新測試跑舊閘:① 3 條紅;② **7 條紅——4 條誤攔之外還有 3 條漏擋**
(站在 Gitea 那份 `git -C <薄殼> push origin x` 舊版放行)。cwd 不只讓它誤擋,也讓 D20 有洞。
原因: 兩支都在回答「這條指令會動到哪個 repo」,卻拿「hook 自己站在哪」當答案。
本機一份目錄時兩者恰好相等,所以測試全綠;雲端薄殼+真身兩份目錄一分開就露餡。
而「出路走不走得通」那一格從來沒被測過——測的只有「擋不擋」。
正確做法:
- 出路要是 hook **讀得到**的形狀:認指令字串裡的字面前綴(判準是位置——前綴必須掛在會移動 HEAD
的那條 git 指令上;印個字、掛在別的指令上、寫在引號裡都不算),或 `gate-ok` 同款的戳記檔。
- 「這條指令在哪個 repo 執行」一律走 `hooks/lib/push_target_dir.py``checkout_target_dir.py`
解 cd 鏈與 `-C`,解不出來才退回 cwd(退回的方向是照舊,不是放寬)。改判準時 `grep -l` 找同一族
`main-and-prod-push-guard``github-contact-guard``line-needs-own-worktree``not-my-branch-guard`)一次看齊。
- 測試要有一條「把閘印出來的那一行原樣餵回去」(A24 (61)–(63)),還要有 payload 帶 `cwd`
cwd 與目標 repo **不同**的案例(A39 後 12 條)——本機一份目錄的測試驗不出這個病。
📌 沒在本票修的同形狀:`not-my-branch-guard.sh``NOT_MY_BRANCH_OK=1 git commit …` 同樣只讀環境變數
(第 28 行),沒實測、沒動——它認的動作是 commit,不是 push_target_dir 那條線的事,另報。
## ⚠️ MISTAKE: 閘教了「開」,「收」只寫在訊息裡——每條線留一份,leo 在 Finder 看到一排分身
票: `inkstone/ISEP#147`
日期: 2026-09-07
症狀: leo 打開 `tech_projects/`,一個 repo 旁邊躺著 `ISEP-wt-122ship``ISEP-wt-117``ISEP-wt115`
`InkStoneCo-wt-112``course_gen-ticket-3-notes``ax-courses-ticket1`…。他原話:
「你會產生大量的同一個頭不同尾巴的 repo,全部拆開就更亂了」「禁止這樣產出一大堆資料夾」。
實查: 那些不是 repo,是 `line-needs-own-worktree.sh`ISEP#10908-29)教工人開的 git worktree。
那支閘比較過「旁邊 vs /tmp」——/tmp 會被系統清掉、登記說謊;旁邊一份都沒掉。
**一份都沒掉,也一份都沒收**:「收工時 `worktree remove`」只寫在閘訊息裡,
沒有任何事件、任何 hook 在線收工那一刻去驗。
原因: 規則在文字裡,不在機器上(同日 ISEP#109 comment 6629 是同一種病的另一面:出路寫在訊息裡,機器讀不到)。
一道閘只管「開」不管「收」,等於把清理交給每一條線的記性——而線收工就消失了,記性跟著消失。
正確做法:
- 分身住 repo **裡面**`<repo>/.worktrees/<票 repo>-<票號>`,走 `.git/info/exclude`):Finder 看不到、
`git status` 看不到、`git worktree list` 找得到。判準是「leo 在 Finder 只看得到一個資料夾」。
- **同一支閘**多掛 PostToolUse `Agent|Task`:從派工單的【工單】認出分身,推了且乾淨就收;
沒推就點名分支與路徑(exit 2),不 force、不刪。教你開的和替你收的是同一件事的兩半,不拆成兩支。
- 「推了沒」只有一份實作(`scripts/worktree`,三態:有/沒有/問不到——問不到不當成沒推,也不收)。
- 現場整理是同一支工具的 `sweep`:預設只列不動,`--apply` 只收已推乾淨的;`--skip` 是操作者點名,不是判準。
- 規約:`docs/governance/worktree-placement.md`
📌 推廣:**一道閘若教人做一件「之後要還」的事(開 worktree、蓋戳記、借共用目錄),
「還」那一步也要長在某個事件上**,不然它必然被留下。收工的事件是 PostToolUse(Agent|Task)
票號就在那裡(`baton-handback-guard.sh``issue-status-autoflip.sh` 都站在同一個位置)。
## ⚠️ MISTAKE: 工具檔頭把「現場的樣子」寫成「既有做法」,於是它變成了規則
票: `inkstone/ISEP#133`(→ comment 6743
日期: 2026-09-07
症狀: `scripts/mainline``hooks/lib/mainline.py` 檔頭寫「跨 repo 同名是既有做法,不動它」,
成員判定=「票所屬 milestone 的標題與主線相同(不分 repo)」。總管早上照它做,把那句
抄進 InkStoneCo 的 ops-facts(「同名里程碑跨 repo 是 mainline 機制的一部分」),
還在 arcrun-rag 補建了一個同名的(#61)。leo:「**拆,誰說『同名跨 repo 是 mainline
機制的一部分』,早就定了只有一個 milestone,不同 repo 用指針**」。
規則其實早就寫在票上:`inkstone/ISEP#30`08-20)、`inkstone/InkStoneCo#44`08-27)。
原因: ISEP#82 那天現場真的有 5 個同名的「Mira 現代化」,工具作者把「現場如此」記成
「既有做法」——而讀檔頭的人分不出「作者觀察到的」與「leo 定的」。
**工具是會被抄的文件**:它說什麼是規則,做的人就照什麼做;寫錯的方向會被放大成動作
(多建一個里程碑),不是只停在一句話。
同款:帳本路徑退到「原始碼所在 repo 的 system-dev/」——本機是真 checkout 所以對,
雲端的原始碼在 plugin 快取,那天記的 5 筆帳下一個 session 就不見。判準寫成
「原始碼在哪」而不是「哪裡會被 clone 走」,換一台機器就錯。
正確做法:
- 檔頭只准寫**規則與出處**(票號/leo 原話),不准把「現場現在長這樣」寫成「既有做法」。
要記現場,寫「2026-xx-xx 實查現場是 X」,並註明它不是判準。
- 判準用 Gitea 的欄位:成員=hub 里程碑裡的票 + hub 票 + 沿 `/dependencies` 收到的(跨 repo);
`belongs()` 要同時拿到「掛哪個 milestone」與「誰把它當相依」才准說「不屬於」,只知一半回 None。
- 帳本這種「隨 repo 走的狀態」找家用同一把尺(`mainline.py::project_roots()`),
退回原始碼目錄只在它有 `.git`(真的 checkout)時;plugin 快取沒有 `.git`
- 驗法要驗「關掉同名里程碑之後成員還在不在」(A41 ㉛–㉞),不是「同名時列得出來」。
+1
View File
@@ -5,3 +5,4 @@
- 本 repo 不放 `.env`/任何金鑰真身(D36「金鑰只有一個家」);也不放 `_archive/` - 本 repo 不放 `.env`/任何金鑰真身(D36「金鑰只有一個家」);也不放 `_archive/`
- ISEP 的 wiki 只記 ISEP 自己的事,不複製 InkStoneCo 的 wiki 內容(複製即 forkfork 即漂移)。 - ISEP 的 wiki 只記 ISEP 自己的事,不複製 InkStoneCo 的 wiki 內容(複製即 forkfork 即漂移)。
- 環境(hookscommandsskillsscripts)與知識(wikidocs)雖然裝在同一個 repo,改動理由不同——環境變更要同步本機+雲端兩份,知識變更只影響這個 repo 自己被讀到什麼。 - 環境(hookscommandsskillsscripts)與知識(wikidocs)雖然裝在同一個 repo,改動理由不同——環境變更要同步本機+雲端兩份,知識變更只影響這個 repo 自己被讀到什麼。
- 一個 repo 在檔案系統上只有一個資料夾:一條線的分身(git worktree)住 `<repo>/.worktrees/`,禁止在專案目錄旁邊產出 `<repo>-wt-…``<repo>-ticket…` 這類同頭不同尾的資料夾;開用 `scripts/worktree open`、收工 `scripts/worktree close`,忘了收的由 `line-needs-own-worktree.sh`PostToolUse)替你收(規約 `docs/governance/worktree-placement.md`inkstone/ISEP#147)。