Compare commits

...

18 Commits

Author SHA1 Message Date
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
27 changed files with 2642 additions and 230 deletions
+2 -2
View File
@@ -1,7 +1,7 @@
{
"name": "isep",
"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 支腳本,外加治理規範與標籤真相源。本機與雲端裝同一份,沒有子集。",
"version": "0.25.0",
"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.29.0",
"keywords": [
"inkstone",
"guardrails",
+2 -2
View File
@@ -23,11 +23,11 @@
| | 數量 | 是什麼 |
|---|---|---|
| `hooks/` | 61 支 `hooks.json` | 全部機械閘(PreToolUseStopSubagentStopSessionStartPostToolUseUserPromptSubmit 共 85 條註冊)。**一支一行的白話盤點在 `docs/hooks-inventory.md`,那裡才是這兩個數字的家** |
| `hooks/` | 61 支 `hooks.json` | 全部機械閘(PreToolUseStopSubagentStopSessionStartPostToolUseUserPromptSubmit 共 86 條註冊)。**一支一行的白話盤點在 `docs/hooks-inventory.md`,那裡才是這兩個數字的家** |
| `agents/` | 7 位 | **工人名單**`inkstone/ISEP#86`)——派工時指名派給誰,規約見 `docs/governance/worker-roster.md` |
| `commands/` | 7 支 | `/wiki-recall` `/wiki-capture` `/cp-write` `/issue-handle` … |
| `skills/` | 2 支 | `ship-check`(東西要出去之前)/`deep-recall`(把散落的枝葉還原成一棵樹)。🔴 **這兩支的內容不一定是在這裡寫的**——誰是真相源查 `docs/file-ownership.tsv` |
| `scripts/` | 60 支 | `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 的驗收介面,多報就是假綠):
+166 -7
View File
@@ -420,12 +420,12 @@ bash hooks/tests/gitea-arm-check.test.sh .
- ①③⑤⑥ 任一紅 ⇒ 收手收得太晚,暫存區已經開始長東西(磁碟風險回來了)
- ② 紅 ⇒ 訊息沒給出走得通的那一行(本票整張票在講的就是這件事)
- ⑧⑨⑩ 任一紅 ⇒ **誤攔/複製錯**:正常用法被弄壞,或複本裡混進了 `hooks/` 以外的東西
### A31 — 雲端工人抓票的規則是機械可判的:48
### A31 — 雲端工人抓票的規則是機械可判的:53
```
bash scripts/test-ticket-pick.sh
```
**該看到**`通過 48 條,失敗 0 條`。**全程離線**:假池子(3 個 repo、3 個 open milestone、
11 張票)餵給換掉的 `api()`,時鐘走 `ISEP_COUNTDOWN_NOW``TICKET_HOST` 指到連不上的位址
**該看到**`通過 53 條,失敗 0 條`。**全程離線**:假池子(3 個 repo、3 個 open milestone、
12 張票、1 條相依邊)餵給換掉的 `api()`,時鐘走 `ISEP_COUNTDOWN_NOW``TICKET_HOST` 指到連不上的位址
——任何一條真的走到網路會當場炸,不會靜靜變成假綠。**不開票、不改票、不留任何東西在 Gitea 上。**
**它在守什麼**`inkstone/ISEP#131`):Routine 08-06 起讀 `journeys.md` 本 sprint 段,
@@ -434,8 +434,10 @@ Gitea 主線里程碑抓票(`inkstone/InkStoneCo#118`),但那是一段給
這一支把規則做成 `scripts/ticket pick``claim` 兩個動詞,規則本體在 `pickable()` 一支純函式:
```
可抓 s/* 恰好是 {s/todo} 沒有 assignee 沒有 Humanhuman/* 不是 hub 里程碑=主線
主線抓盡才抓「逾期的 open 里程碑」;backlog/沒里程碑一律不抓
可抓 s/* 恰好是 {s/todo} 沒有 assignee 沒有 Humanhuman/* 不是 hub 主線
「在主線上」=hub 里程碑裡、或被主線成員當相依(跨 repo 邊,inkstone/ISEP#133);
別 repo 裡同名的里程碑**不算**主線。主線抓盡才抓「逾期的 open 里程碑」(一個里程碑物件一組);
backlog/沒里程碑且沒有邊的一律不抓
認領 claim 指派 + s/doing + 第一行【身份】的留言,一個動作
完成 handback --label s/review(本來就有的那半,不重做)
```
@@ -448,6 +450,8 @@ Gitea 主線里程碑抓票(`inkstone/InkStoneCo#118`),但那是一段給
要嘛抓盡了還回 `Arcrun#8`(既不是主線也沒逾期)
- ②「離開碼 1」紅 ⇒ 「真的沒有票」與「讀不到」被講成同一句——後者要離開碼 2
- ②「沒有主線 → 離開碼 2 且一通 API 都沒打」紅 ⇒ 沒主線時去抓了別的
- ②「ISEP#1 靠相依進主線」/「ISEP#13 同名沒邊 → 不在」任一紅 ⇒ 成員又變回靠名字算
leo 2026-09-07 推翻的那條判準回來了,A41 也會一起紅)
- ③「該擋」六條任一紅 ⇒ 規則只長在 `pick` 這端,手動 `claim` 一張 Human 的票照樣過
- ③「身份名不在名單上 → 一通都沒打」紅 ⇒ 名單以外的名字碰到了 Gitea
- ④ 第一條紅 ⇒ 連不上 Gitea 時回了離開碼 1,雲端會把「斷線」當「沒票」收工
@@ -624,11 +628,35 @@ bash hooks/tests/parallel-lines-cap-guard.test.sh
`PostToolUse:Agent` 在**送出後 5 秒**就觸發(不是收工);
subagent **不是獨立行程**`ps` 只有一個 claude-code 行程,所以數行程數不到線)。
### A24 — 一條線要有自己的工作目錄:59
### A24 — 一條線要有自己的工作目錄:110
```
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**。
舊版一律拿 payload 的 `cwd` 當答案,於是 `cd <別的 repo> && git checkout` 擋是擋對了,
@@ -646,6 +674,10 @@ D 群同時釘住反面:認不出來(`cd $VAR`、`cd -`、cd 到不是 repo
擋掉它們等於線動不了工
- ① 紅 ⇒ 連總管在自己的目錄裡切分支都被擋。那不是嚴格,那是把共用目錄的主人趕出去
- ㉞㉟ 紅 ⇒ `prune` 做錯了。㉞是沒清掉說謊的登記;**㉟是把還在的 worktree 也弄掉了,那是災難**
- (63) 紅 ⇒ 閘印的出路又走不通了——被擋的人不會停下來修閘,他會去找繞過去的方法(6587 當天就是)
- (64)–(67) 任一紅 ⇒ 出路退化成關鍵字:印個字就能過,閘等於沒有
- (75) 紅 ⇒ **閘廢了**#125 原話):剝 heredoc 剝過頭,真的切也放行
- (76) 紅 ⇒ tokenize 那層被改了,回頭跑 (53) 與推 main 的 1019 條
### A25 — `sdd-guard` 退役了,而且退乾淨了:8 條
```
@@ -911,6 +943,128 @@ bash hooks/tests/isep-presence-beacon.test.sh # ㉗–㉝ 那七條
**真實跑(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 的
```
python3 scripts/ticket where 標籤 模組化
@@ -1181,6 +1335,10 @@ B2(信標那行)/B3(setup 輸出)/B4(閘的訊息)三個畫面
| **A12 留言身份欄(兩道門)** | 總管 | ✅ 11/112026-08-27 |
| **A23 同時跑的線有上限** | isep-guard | ✅ 33/332026-08-29inkstone/ISEP#109 |
| **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)+兩條「該紅」方向實跑 |
| **A16 放行的門真的打得開** | 總管 | ✅ 17/172026-08-28inkstone/ISEP#90 |
| **A17 未推警察不誤攔雲端分支** | 總管 | ✅ 10/102026-08-28inkstone/ISEP#90 |
@@ -1194,6 +1352,7 @@ B2(信標那行)/B3(setup 輸出)/B4(閘的訊息)三個畫面
| **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 裝得起來 | 總管 | ✅ |
+1 -1
View File
@@ -167,7 +167,7 @@ leo 09-07:「雲端回覆的問題你首要解決⋯⋯僅有需要依賴 Mac
| 拿不到什麼 | 為什麼 | ISEP 這一半 | 還缺誰 |
|---|---|---|---|
| **主線是哪條** | 主線檔只在本機 `~/.claude` | `hooks/lib/mainline.py`:家目錄沒有就讀 repo 的 `InkStoneCo/system-dev/mainline.json`(雲端形狀:`$CLAUDE_PROJECT_DIR` 是薄殼根、真身在 `InkStoneCo/`);`mainline set``adopt``clear` 兩份一起寫 | 總管 `set` 之後要把 repo 那份 commit/併 main |
| **主線是哪條** | 主線檔只在本機 `~/.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 加那兩個變數 |
+3 -1
View File
@@ -471,6 +471,8 @@ Telegram → 純投影。**Wiki 壞不影響 GiteaGitea 壞不影響 SDD
> 🔴 **排序不是按票號,是按「什麼擋住什麼」**:上面的群沒解,下面的群做了也看不到效果。
> 本節是唯一把六群串起來的地方——Gitea 沒有跨 repo milestone(已查證),
> 各 repo 的同名里程碑都指回這裡。
> 🔴 **「各 repo 同名」這半句 2026-09-07 已被 leo 推翻**`inkstone/ISEP#133`):一條線只有一個
> milestone,別 repo 的票用相依指到 hub 票;`scripts/mainline` 的成員判定改看相依邊,不看名字。
### 13.0 六群一頁看完
@@ -639,7 +641,7 @@ leo 08-17 診斷見公理 308-17 實測:文字層的閘 **8 次誤攔、0
3. **一切要留痕、可量測。** 閘的動作、開場全局、里程碑百分比——leo 看到的畫面就是實況。
4. **進度=舊票關掉幾張。** 版本只是讓閘生效的載具,release note 寫明關了哪張票。
### 15.2 工作順序(六個里程碑,各 repo 同名,內容一經確定不增不減)
### 15.2 工作順序(六個里程碑,內容一經確定不增不減;「各 repo 同名」已於 2026-09-07 推翻——一條線一個 milestone,別 repo 用相依,`inkstone/ISEP#133`
| 順 | 里程碑 | 來源票(由目標遍歷票池而來,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` 的一根寒毛不動、沒推的印分支與路徑。
+19 -5
View File
@@ -7,7 +7,7 @@
## 一句話結論
`hooks/` 底下有 **61 個 `.sh` 檔**`hooks.json` 實際掛上 **85 條註冊**(同一支閘常被多種情境同時掛上);
`hooks/` 底下有 **61 個 `.sh` 檔**`hooks.json` 實際掛上 **86 條註冊**(同一支閘常被多種情境同時掛上);
其中 **3 支檔案存在但沒被掛上**(2 支是待人填的空範本、1 支是刻意留著沒開的止血帶,見下面「未生效」表)。
下面按「你會在什麼時候撞到它」分組,一支一行。
@@ -38,6 +38,20 @@
> **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`,雲端才不會每個正門工具都被分類器擋)。
@@ -129,7 +143,7 @@
| 閘名 | 對你意味著什麼 | 動作 |
|---|---|---|
| `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、永遠只有三張表」。 | 🛑 擋 |
| `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` 打正式環境 → 一定要你親手解鎖。 | 🛑 擋 |
@@ -143,7 +157,7 @@
| `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`)。 | 🛑 擋(同一輪只擋一次) |
| `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 號/票號/網址/貼出來的實測輸出)就擋一次——未經調查的診斷寫在票上會長得像事實,工人會照著它去驗證而不是去查。派過人查、或把出處帶上,都放行;一句短回覆不管。 | 🛑 擋 |
## B. AI 想寫檔案/改程式碼的當下(PreToolUse / Write·Edit·MultiEdit
@@ -196,7 +210,7 @@
| `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"`)不管,那是交件不是派工。 | 🛑 擋(+注入) |
| `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 自己規定的合格寫法曾經被這支閘自己擋下)。 | 🛑 擋(+注入) |
| `parallel-lines-cap-guard.sh` | **同時在跑的線超過上限就派不出下一條**(預設 3`ISEP_MAX_PARALLEL_LINES` 可調),而且訊息會列出現在有哪幾條在跑、各跑了多久。你關心的是:不會再因為一次派七條而讓機器爆掉,也不會再有「同時盯七條線所以派錯、量錯」那種錯。**條數是從 harness 自己寫的檔案數出來的,不是靠誰記得**——所以某一條收工,下一條立刻派得出去,不會卡死。真的非同時不可:`touch /tmp/.parallel-ok-<session_id>`(用一次就消失)。 | 🛑 擋 |
@@ -219,7 +233,7 @@
| `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 注入) |
| `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 就原封不動——**寧可資料舊,不要把主線弄丟**。跑一次就結束,不輪詢。 | 📝 記錄 |
| `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 |
| `wiki-size-guard.sh` | 對話一開始講出「哪幾個 wiki 檔已經沒有人讀得完了」(預設超過 1200 行就點名)。**讀不完的必讀檔,跟沒有那個檔的差別只在於它讓人以為有。** 另一半掛在寫檔上,見 B 組。 | 📝 記錄(context 注入) |
| `skill-deploy-drift-guard.sh` | 如果「全機真正在用的 skill」跟「repo 裡版控的正本」內容對不上,就在開場講出來——避免用著一份沒人知道已經跟正本分家的舊拷貝。 | 📝 記錄 |
+7 -2
View File
@@ -6,7 +6,8 @@
"薄殼 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#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),其餘一字不改。",
@@ -40,6 +41,10 @@
"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 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('')
" 2>/dev/null)
[ -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
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"
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
HIT="git push → githubremote「$RNAME」指向 GitHub"
HIT="git push → github$PUSHDIRremote「$RNAME」指向 GitHub$(printf '%s' "$RURL" | sed 's|//[^@]*@|//<憑證省略>@|g')"
fi
fi
fi
+4
View File
@@ -445,6 +445,10 @@
{
"type": "command",
"command": "${CLAUDE_PLUGIN_ROOT}/hooks/baton-handback-guard.sh"
},
{
"type": "command",
"command": "${CLAUDE_PLUGIN_ROOT}/hooks/line-needs-own-worktree.sh"
}
]
},
+49 -16
View File
@@ -30,13 +30,24 @@
其他 目錄運算式,可能是相對的;呼叫端自己 `cd` 進去問 git(唯讀)。
"." =「就是呼叫端自己的 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 sys
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")
UNKNOWN = "?"
@@ -52,14 +63,19 @@ def _step(base, path):
def _moves_head(tokens):
"""tokens 是整串 `git …`。回傳 (會不會動 HEAD, -C 指的路徑 or None)
"""tokens 是整串 `[NAME=value …] git …`
回傳 (會不會動 HEAD, -C 指的路徑 or None, 前綴賦值清單)。
判準只有「這個動作動不動 HEAD」,不看任何措辭:
git checkout -- <檔>git checkout HEAD -- <檔> ⇒ 還原檔案,不動
git checkout -p ⇒ 挑 hunk,不動
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
while tok and tok[0].startswith("-"):
if tok[0] == "-C" and len(tok) > 1:
@@ -72,24 +88,25 @@ def _moves_head(tokens):
tok.pop(0)
continue
if tok[0].startswith("--git-dir"):
return (False, None) # 自己指 git-dir 的花式用法,不猜
return (False, None, env) # 自己指 git-dir 的花式用法,不猜
tok.pop(0)
if not tok or tok[0] not in VERBS:
return (False, None)
return (False, None, env)
rest = tok[1:]
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 \
not any(a in ("-b", "-B", "-c", "-C") for a in rest):
return (False, None)
return (True, c_path)
return (False, None, env)
return (True, c_path, env)
def find_checkout_target(cmd):
def find_checkout(cmd):
"""回 (目錄運算式, 那條 checkout 的前綴賦值清單)。目錄運算式的三種值見檔頭。"""
events = _events(cmd, VERBS, strip_env=True)
if not events:
return "" # 引號壞掉之類——沿用「不擋在不確定上」
return ("", []) # 引號壞掉之類——沿用「不擋在不確定上」
stack = [None] # 每層括號各自的 cwd;None = 同呼叫端的 cwd
for kind, val in events:
@@ -101,7 +118,7 @@ def find_checkout_target(cmd):
elif kind == "cd":
stack[-1] = _step(stack[-1], val)
elif kind == "verb":
moves, c_path = _moves_head(val)
moves, c_path, env = _moves_head(val)
if not moves:
continue
where = stack[-1]
@@ -110,13 +127,29 @@ def find_checkout_target(cmd):
# (而且 -C 若是相對路徑,是接在 cd 之後算,不是接在 cwd)
where = _step(where, c_path)
if where == UNKNOWN:
return UNKNOWN
return where or "."
return ""
return (UNKNOWN, env)
return (where or ".", env)
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():
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__":
+272 -26
View File
@@ -2,8 +2,9 @@
"""hooks/lib/mainline.py —— 「現在的主線是哪一個」這件事的**唯一存放處**。
這是 helper,不是閘(inkstone/ISEP#40 S7`lib/` 底下的東西不算一支手寫的閘)。
個呼叫者共用它,所以「主線是誰」的答案只有一份:
個呼叫者共用它,所以「主線是誰」「誰在主線上」的答案只有一份:
· `scripts/mainline` —— 人問「現在的主線是哪一個」
· `scripts/ticket pickclaim` —— 雲端工人抓票:抓的是主線的成員
· `hooks/lib/countdown.py` —— 每一則回覆眼前那一行的第二段
· `hooks/mainline-focus-guard.sh` —— 派了一張不屬於主線的票就攔一次
@@ -13,24 +14,43 @@
SOP 說「有 active milestone 時只做該 milestone 的事」——但**「那個」在現場沒有指涉對象**。
leo 的原話是「**14 個里程碑同時亮著卻不知道該看哪個**」。
⇒ 要解的不是「milestone 太多」(跨 repo 同名是既有做法,v0.6.0 §4SOP S7-4),
要解的是「**這一刻我在做哪一條**」沒有答案。
⇒ 所以這個檔的形狀就是答案的形狀:**一個檔,放得下一條**。
沒有清單、沒有優先序、沒有「前三名」——被覆蓋掉的那條就不再是主線。
問「現在的主線是哪一個」永遠只會拿到 0 或 1 個答案,不會拿到 14 個。
── 主線是一個「名字」,錨在一個具體的 milestone 上 ──────────────────
Gitea 的 milestone 不能跨 repo,而同一條線常常同時開在 5 個 repo(票上實查)
所以:
· **錨**anchor)= `owner/repo#<milestone id>`:期限、進度、目標宣告都讀它
· **成員判定** 票所屬 milestone 的**標題**與主線標題相同(不分 repo)
⇒ 「同名跨 repo」照舊能用,而「現在在做哪一條」仍然只有一個答案。
── 一條線在整個 Gitea 只有一個里程碑;別的 repo 用相依指過來(inkstone/ISEP#133──
🔴 本檔第一版寫的是「同名跨 repo 是既有做法,成員=票所屬 milestone 的標題與主線相同」
那不是規則,是當時現場的樣子——而 leo 早在 2026-08-20inkstone/ISEP#30)與 08-27
inkstone/InkStoneCo#44)就定了相反的規則:**一條線一個里程碑,別 repo 的票用相依指到 hub 票**。
工具把現場當規則寫進檔頭,總管 09-07 照它做,還在 arcrun-rag 補建了一個同名的;
leo 當天:「拆,誰說『同名跨 repo 是 mainline 機制的一部分』,早就定了只有一個 milestone,
不同 repo 用指針」。⇒ 檔頭寫的「既有做法」會被當成規則抄走,所以這裡改成規則本身:
── 這支從不打網路 ────────────────────────────────────────────────
它被 `UserPromptSubmit` 用(每一則訊息的關鍵路徑)。在那裡打 HTTP = 每講一句話
· **錨**anchor)= `owner/repo#<milestone id>`:整個 Gitea 只有這一個 milestone 物件。
期限、進度、目標宣告都讀它。
· **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),
本支讀寫 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 os
@@ -75,6 +95,21 @@ def path() -> str:
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 = []
@@ -83,11 +118,7 @@ def repo_candidates():
return [] # 測試用:把「repo 那份」整個拿掉,外界定住
if forced:
out.append(forced)
roots = []
for r in (os.environ.get("CLAUDE_PROJECT_DIR", "").strip(), os.getcwd()):
if r:
roots += [r, os.path.join(r, "InkStoneCo")]
for r in roots:
for r in project_roots():
p = os.path.join(r, REPO_REL)
if p not in out:
out.append(p)
@@ -106,15 +137,100 @@ def repo_path(for_write=False):
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
if not isinstance(d, dict) or not d.get("title"):
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
return d
def load():
@@ -195,6 +311,8 @@ def norm(s) -> str:
🔴 刻意不做同義詞、不做模糊比對:主線是**被指定的**,不是被猜出來的。
猜錯的方向是「把不屬於主線的票放行」,那正是這張票要擋的事。
inkstone/ISEP#133 起標題只用來**查**Gitea 的 `milestones=` 只吃名字),
成員判定看的是 milestone id 與相依邊,不再拿標題當判準。
"""
return "".join((s or "").split()).lower()
@@ -205,27 +323,155 @@ def ref_of(ms) -> str:
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):
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。
None **不知道**(快取裡沒有這張票,而呼叫端也沒查到它的 milestone)
🔴 「不知道」不等於「不屬於」——這條分界就是誤攔與否的分水嶺。
None **不知道**。🔴 「不知道」不等於「不屬於」——這條分界就是誤攔與否的分水嶺
呼叫的閘拿到 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:
return True # 沒有主線 ⇒ 沒有「不屬於主線」這回事
ref = (ticket_ref or "").strip()
if ref and ref in members(ms):
return True
if ticket_milestone_title is not None:
return norm(ticket_milestone_title) == norm(ms.get("title"))
parts = split_ref(ref)
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
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():
"""測試用:把「去 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`) --
callers re-walk the returned token list to confirm command position, so
a false positive at this layer costs nothing."""
body = tokens
if strip_env:
# `FOO=1 git checkout …` -- an env prefix doesn't change which command
# runs. Opt-in so find_push_target's behaviour stays byte-identical;
# checkout_target_dir.py turns it on (its predecessor stripped these,
# and dropping that would have been a silent regression -- caught by
# the worktree gate's own case ㉒).
#
# 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
while i < len(tokens) and _ENV_ASSIGN.match(tokens[i]):
i += 1
tokens = tokens[i:]
if not tokens:
body = tokens[i:]
if not body:
return ("other", None)
if tokens[0] == "cd" and len(tokens) > 1:
return ("cd", tokens[1])
if tokens[0] == "git" and any(v in tokens[1:] for v in verbs):
if body[0] == "cd" and len(body) > 1:
return ("cd", body[1])
if body[0] == "git" and any(v in body[1:] for v in verbs):
return ("verb", tokens)
return ("other", None)
+110 -17
View File
@@ -1,7 +1,13 @@
#!/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。票號說得出「這是哪個任務」,沒有任何東西說得出「這個目錄現在是誰留下的狀態」。
# 誤觸時怎麼關: `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
#
@@ -26,16 +32,28 @@
# 而 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
# /private/tmp/.../scratchpad/wt-180 … prunable ← 目錄被系統清掉了
# /private/tmp/.../scratchpad/wt164 … prunable ← 同上
# /private/tmp/wt167src … prunable
# products/arcrun-rag-wt88 … 完好
# products/arcrun-rag-wt104ingest … 完好
# ISEP 同一天有 **12 筆 prunable**,全部在 /private/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 是收工動作,不是偶爾整理)───────
# 擋下來的同時對那個 repo 跑一次 `git worktree prune`,並把清掉幾筆講出來。
@@ -52,11 +70,69 @@
# 然後以為自己隔離好了。**寧可漏擋,也不要給錯的下一步**(comment 5398)。
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
[ "${CLAUDE_CODE_CHILD_SESSION:-}" = "1" ] || exit 0 # 總管在自己的目錄裡,不管
PAYLOAD=$(cat 2>/dev/null || echo '{}')
# 這條指令會動到哪個目錄的 HEAD——**不是問「hook 站在哪」**。
# 2026-08-29 實測(inkstone/ISEP#109 → comment 5398):`cd <別的 repo> && git checkout`
# 舊版拿 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
[ -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 '
import json, sys
try:
@@ -96,6 +179,11 @@ EXPR=$(printf '%s' "$CMD" | python3 "$RESOLVER" 2>/dev/null) || exit 0
[ -n "${EXPR:-}" ] || exit 0 # 沒有會移動 HEAD 的 checkout/switch
[ "$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
[ -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
NAME=$(basename "$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 '?')
# 驗收條件 7:說謊的登記順手清掉(只刪目錄已經不存在的那些)
@@ -130,17 +220,20 @@ $PRUNED
🔴 票號說得出「這是哪個任務」,**沒有任何東西說得出「這個目錄現在是誰留下的狀態」**。
(那次沒出錯貨——是文案契約閘擋下來的。閘有效,但那是最後一道。)
【現在怎麼做】開一份自己的,然後在裡面做事:
【現在怎麼做】開一份自己的——住在 repo **裡面**的 .worktrees/,然後在裡面做事:
git -C $TOP worktree add $PARENT/$NAME-wt-<票號> -b <你的分支>
cd $PARENT/$NAME-wt-<票號>
python3 $WT_TOOL open <owner/repo#票號> --repo $TOP -b <你的分支>
cd $TOP/.worktrees/<票的 repo 名>-<票號>
🔴 **不要開在 /tmp 底下** 同一天實測:$NAME 的登記簿裡指向 /private/tmp 的
那幾筆全部 prunable(目錄被系統清掉、登記還在),而開在 repo 旁邊的一份都沒掉。
🔴 **不要開在 /tmp 底下**08-29 實測:$NAME 指向 /private/tmp 的登記全部 prunable),
**也不要開在 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-<票號>
git -C $TOP worktree prune
收工時(推了會收掉;沒推會點名,不會靜默留著;你忘了,線收工那一刻這支閘也會替你收)
python3 $WT_TOOL close <owner/repo#票號> --repo $TOP
規約:docs/governance/worktree-placement.md
【真的要在共用目錄裡切(接手、緊急止血)】
WORKTREE_OK=1 git -C $TOP checkout <分支>
+36 -20
View File
@@ -18,8 +18,10 @@
#
# 本閘從頭到尾**不讀派工單的任何一個字義**。它只做兩個查表:
# ① 派工單的【工單】欄位是哪一張票(`hooks/lib/dispatch_parse.py` 解結構,不判語意)
# ② 那張票所屬的 milestone 標題,等不等於被標定的主線標題(字串相等,不是模糊比對)
# 措辭怎麼寫都不影響判決;改的只有「這張票掛在哪」這個 Gitea 上的事實。
# ② 那張票在不在主線上:掛在錨那一個 milestone(同 repo、同 id),或有任何一張主線成員
# 把它當相依(`/blocks`)。判準是 milestone id 與相依邊——**不是標題**:
# 別 repo 裡同名的里程碑不算(leo 2026-09-07inkstone/ISEP#133)。
# 措辭怎麼寫都不影響判決;改的只有「這張票掛在哪、誰指著它」這兩個 Gitea 上的事實。
#
# ── 誤攔的出口全部先關掉(誤攔比漏擋更該修)──────────────────────────
# · **沒有主線 ⇒ 一律放行**(ISEP#82 驗收第 4 條:沒有主線不能整組壞掉)
@@ -92,16 +94,20 @@ for ref in wanted:
if v is None:
unknown.append(ref)
# ② 快取查不到的,去問那張票掛在哪。問不到 ⇒ 放行
# ② 快取查不到的,去問兩件事實:那張票掛在哪個 milestone、誰把它當相依(inkstone/ISEP#133
# 兩件都到手才敢說「不在」;問不到任何一件 ⇒ 放行。
if unknown:
fx = ML.fixture_titles()
if fx is not None: # 測試把外界定住(見 mainline.fixture_titles
learned = [r for r in unknown
if ML.norm(fx.get(r, "")) == ML.norm(ms.get("title"))]
if learned:
if fx is not None: # 測試把外界定住(見 mainline.fixture_lookup
verdicts = {}
for r in unknown:
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
if not any(r in fx for r in unknown):
bail("unreachable") # fixture 沒收錄 ⇒ 等同問不到
if not verdicts or any(v is None for v in verdicts.values()):
bail("unreachable") # fixture 沒收錄/只知一半 ⇒ 等同問不到
else:
try:
T = load("isep_ticket", os.path.join(HERE, "..", "scripts", "ticket"))
@@ -111,28 +117,37 @@ if unknown:
# 那不是 Exception 的子類。只接 Exception 的話,這支會整個死掉而不是放行。
except BaseException:
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
learned = []
undecided = False
for ref in unknown:
parts = ML.split_ref(ref)
if not parts:
continue
try:
owner, rest = ref.split("/", 1)
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))
it = get("/repos/%s/%s/issues/%d" % parts)
reached = True
except Exception:
continue
title = ((it or {}).get("milestone") or {}).get("title") or ""
if ML.norm(title) == ML.norm(ms.get("title")):
try:
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)
elif v is None:
undecided = True
if learned:
ms["members"] = sorted(set(ms.get("members") or []) | set(learned))
ML.save(ms)
print("SKIP:on-mainline-fresh"); raise SystemExit
if not reached:
bail("unreachable") # 一張都問不到 ⇒ 放行
if not reached or undecided:
bail("unreachable") # 問不到/只知一半 ⇒ 放行
# ③ 確定都不在主線上 —— 同一組票只擋一次
import hashlib
@@ -161,7 +176,8 @@ case "$VERDICT" in
printf ' 這次要派的:%s\n\n' "$TICKETS"
printf '**先說是哪一種,再繼續**——兩種都可能是對的,錯的是默默做完:\n\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 ' 直接重送即可(**同一張票只擋一次**),並在回覆講一句為什麼現在要岔開主線\n\n'
printf '為什麼要問:leo 2026-08-27「今天……分心」。分心的前提是有一條主線,\n'
+169 -2
View File
@@ -32,6 +32,10 @@ mkdir -p "$REPO"
git -C "$REPO" init -q -b main
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
# 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
OWN="$ROOT/own-wt"
PLAIN="$ROOT/not-a-repo"; mkdir -p "$PLAIN"
@@ -116,11 +120,13 @@ echo "── C 群:訊息與副作用 ──"
t 2 "㉔ 擋下來(下面幾條檢查這一次的訊息)" "git checkout -b feat/msg"
has "$REPO" "㉕ 說得出是哪個目錄"
has "worktree add" "㉖ 給得出開自己 worktree 的指令"
has "scripts/worktree open" "㉖ 給得出開自己 worktree 的指令scripts/worktree openinkstone/ISEP#147"
has "不要開在 /tmp" "㉗ 講得出不要開在 /tmp08-29 實測:那些全 prunable"
has "WORKTREE_OK=1" "㉘ 講得出逃生門"
has "worktree prune" "㉙ 講得出收工要怎麼收"
has "scripts/worktree close" "㉙ 講得出收工要怎麼收scripts/worktree close"
hasnt '$(' "㉚ 訊息沒有被 shell 展開"
hasnt "worktree add $ROOT/shared-repo-wt-" "㉚b 不再教人開在 repo 旁邊(09-07 那排分身就是這行教出來的)"
has "$REPO/.worktrees/" "㉚c 教的是 repo 裡面的 .worktrees/"
# 驗收條件 7:說謊的登記真的被清掉
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))
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
echo
echo "══ $PASS/$N 通過${FAIL:+$FAIL 個失敗} ══"
+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 ]
+188 -82
View File
@@ -7,15 +7,16 @@ leo 2026-08-27:「**14 個里程碑同時亮著卻不知道該看哪個**」
⇒ SOP 說的「**那個** active milestone」在現場根本沒有指涉對象——
要注入不知道注哪一個,要擋跳線也不知道拿哪一個當基準。
這支不解「milestone 太多」(跨 repo 同名是既有做法,不動它),
它解的是「**這一刻我在做哪一條**」沒有答案:
mainline 現在的主線是哪一個(= show,唯一答案,離線)
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 refresh [--members] 更新進度/期限(SessionStart 跑一次,不輪詢)
mainline adopt <owner/repo#N> 「補收」:把一張票掛進主線(打網路)
mainline refresh [--members] 更新進度/期限(SessionStart 跑一次,不輪詢)--members 順便重收成員
mainline adopt <owner/repo#N> [--via <hub 票>]
「補收」:把一張票掛進主線(打網路)。同 repo ⇒ 掛進 hub 里程碑;
別 repo ⇒ 成為 hub 票的相依。**不建同名里程碑。**
mainline has <owner/repo#N> 這張票在不在主線上(exit 0 =在,1 =不在)
🔴 **`<owner/repo#id>` 的 id 是 milestone 的 id,不是 issue 的號碼。**
@@ -24,21 +25,30 @@ leo 2026-08-27:「**14 個里程碑同時亮著卻不知道該看哪個**」
── 答案為什麼唯一 ─────────────────────────────────────────────────
主線住在一個檔裡(`~/.claude/isep-countdown/mainline.json`),那個檔**放得下一條**。
inkstone/ISEP#130 起它有一份隨 repo 走的鏡像:`InkStoneCo/system-dev/mainline.json`——
雲端沒有家目錄那份,讀的就是它;`set`/`adopt``clear` 兩份一起寫,`refresh` 只寫家目錄。
雲端沒有家目錄那份,讀的就是它;`set`/`adopt``clear` 兩份一起寫,`refresh` 只寫家目錄。
inkstone/ISEP#140 起:兩份都不在時(雲端薄殼 bootstrap 之前的形狀),`refresh` 會去 Gitea
讀 `inkstone/InkStoneCo` main 上那份一次、寫進家目錄——優先序寫在 `hooks/lib/mainline.py` 檔頭。)
沒有清單、沒有優先序、沒有「前三名」——`set` 覆蓋掉的那條就不再是主線。
⇒ 問一次只會拿到 0 或 1 個答案,不會拿到 14 個。
── 主線是一個名字,錨在一個具體的 milestone 上 ────────────────────
Gitea 的 milestone 不能跨 repo,而同一條線常常同時開在 5 個 repo。所以
**錨**(期限/進度/目標宣告都讀它)是 `owner/repo#id`
**成員判定**看的是「票所屬 milestone 的標題與主線標題相同」(不分 repo)。
兩件事都成立:同名跨 repo 照舊能用,而「現在在做哪一條」仍然只有一個答案
── 一條線只有一個里程碑;別的 repo 用相依指過來(inkstone/ISEP#133──────
🔴 這支的第一版檔頭寫「跨 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 票**`set --hub`)= 這條線的載體票。別 repo 的票要進主線 ⇒ 成為它的 dependency。
· **成員** = hub 里程碑裡的票 hub 票,沿 `/dependencies` 邊(跨 repo)收下去
`hooks/lib/mainline.py::collect_members`)。同名里程碑關掉之後成員一張都不會掉——
因為成員從來不是靠名字算的。
· `adopt` 別 repo 的票 ⇒ 在 hub 票上加一條 dependency**不會在那個 repo 建同名里程碑**。
"""
import importlib.machinery
import importlib.util
import os
import sys
import urllib.parse
from datetime import datetime, timezone
HERE = os.path.dirname(os.path.abspath(__file__))
@@ -93,35 +103,35 @@ def org_repos(owner):
return [r["name"] for r in rows if isinstance(r, dict) and r.get("name")]
def issues_in_milestone(owner, repo, title):
q = urllib.parse.urlencode({"state": "all", "type": "issues",
"milestones": title, "limit": 100})
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(ms):
"""成員=hub 里程碑裡的票 + hub 票 + 它們的相依(跨 repo)。判準在 `hooks/lib/mainline.py`。"""
return ML.collect_members(T.api_soft, ms)
def collect_members(owner, title, anchor_repo):
"""跨 repo 收齊「掛在同名 milestone 底下」的票。"""
refs, scanned = [], []
repos = org_repos(owner)
if anchor_repo not in repos:
repos.append(anchor_repo)
for r in repos:
got = issues_in_milestone(owner, r, title)
if got:
scanned.append((r, len(got)))
refs.extend(got)
return sorted(set(refs)), scanned
def members_line(refs, info):
byrepo = {}
for r in refs:
byrepo[r.split("#")[0]] = byrepo.get(r.split("#")[0], 0) + 1
dist = "、".join("%s %d" % (k, v) for k, v in sorted(byrepo.items()))
return (" 成員 %d 張(里程碑裡 %d 相依收到 %d%s" % (
len(refs), len(info.get("milestone") or []), len(info.get("via_deps") or []),
("" + dist) if dist else ""))
def fetch_issue(ref):
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):
@@ -144,6 +154,8 @@ def cmd_show(argv):
print(" 要標一條:`scripts/mainline list` 看有哪些 → `scripts/mainline set <owner/repo#id>`")
print()
print("📌 在標之前,每回合的 🎯 那一行也會照樣講「現在沒有主線」,不會編一條出來。")
print(" 雲端:SessionStart 的 `mainline refresh` 會先去 Gitea 讀 inkstone/InkStoneCo main 的")
print(" system-dev/mainline.json;還是沒有 ⇒ 那份不存在,或這台拿不到 Giteainkstone/ISEP#140)。")
return
c, total, pct = ML.progress(ms)
print("🎯 現在的主線:%s「%s」" % (ML.ref_of(ms), ms.get("title")))
@@ -155,12 +167,16 @@ def cmd_show(argv):
print(" 目標:" + (first[:150] + "…" if len(first) > 150 else first))
print(" 期限:%s" % ML.due_phrase(ms))
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))
byrepo = {}
for r in mem:
byrepo[r.split("#")[0]] = byrepo.get(r.split("#")[0], 0) + 1
print(" 屬於主線的票:%d 張%s" % (
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"):
print(" 標定於:%s" % ms["set_at"])
if ms.get("refreshed_at"):
@@ -195,16 +211,36 @@ def cmd_list(argv):
# ── 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):
need_net()
if not argv:
die("用法:mainline set <owner/repo#milestone_id>")
owner, repo, mid = parse_ms_ref(argv[0])
pos = positional(argv, "--hub")
if not pos:
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)
title = m.get("title")
refs, scanned = collect_members(owner, title, repo)
now = datetime.now(timezone.utc).astimezone().strftime("%Y-%m-%d %H:%M")
ok = ML.save({
hub = opt_of(argv, "--hub")
if hub:
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),
"owner": owner, "repo": repo, "id": mid,
"title": title,
@@ -212,15 +248,22 @@ def cmd_set(argv):
"due_on": m.get("due_on") or "",
"open_issues": m.get("open_issues") or 0,
"closed_issues": m.get("closed_issues") or 0,
"members": refs,
"set_at": now, "refreshed_at": now,
}, mirror=True)
if not ok:
"hub_ticket": hub,
"members": [],
}
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())
print("✅ 主線已標定:%s/%s#%d「%s」" % (owner, repo, mid, title))
if scanned:
print(" 跨 repo 收到同名 milestone 的票 %d 張:%s"
% (len(refs), "、".join("%s %d" % (r, n) for r, n in scanned)))
if hub:
print(" hub 票:%s" % hub)
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()
cmd_show([])
@@ -247,12 +290,43 @@ def cmd_clear(argv):
# ── 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):
"""SessionStart 跑一次。**拿不到就原封不動**——寧可資料舊,不要把主線弄丟。"""
"""SessionStart 跑一次。**拿不到就原封不動**——寧可資料舊,不要把主線弄丟。
inkstone/ISEP#140:家目錄與 repo 那份都不在(雲端薄殼跑 SessionStart 時 `InkStoneCo/`
還沒 clone)⇒ 去 Gitea 讀 `inkstone/InkStoneCo` main 上那份**一次**,寫進家目錄。
之後每一則 UserPromptSubmit 讀的是家目錄,路徑上照舊沒有網路。
讀不到 ⇒ 什麼都不寫,退回現行行為(`countdown.py` 的第二基準)。
"""
ms = ML.load()
if not ms:
return # 沒有主線就沒有東西要更新,安靜結束
d = T.api_soft("/repos/%s/%s/milestones/%s" % (ms["owner"], ms["repo"], ms["id"]))
got = ML.fetch_gitea(token=soft_token) # 傳函式:匿名讀得到就不去碰 token
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"):
return # 讀不到 ≠ 主線不存在
ms.update({
@@ -264,38 +338,66 @@ def cmd_refresh(argv):
"refreshed_at": datetime.now(timezone.utc).astimezone().strftime("%Y-%m-%d %H:%M"),
})
if "--members" in argv:
refs, _ = collect_members(ms["owner"], ms["title"], ms["repo"])
if refs:
# 成員靠相依邊算(inkstone/ISEP#133):hub 里程碑一頁 每張成員一次 /dependencies。
# 真 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
ML.save(ms)
# ── adopt(補收)──────────────────────────────────────────────────────────
def cmd_adopt(argv):
"""補收。同 repo ⇒ 掛進 hub 里程碑(原生欄位);別 repo ⇒ 成為 hub 票的相依。
🔴 不會在別的 repo 建同名里程碑——那是被 leo 推翻的做法(本檔檔頭)。"""
need_net()
if not argv:
die("用法:mainline adopt <owner/repo#N>(把一張票掛進主線=「補收」)")
pos = positional(argv, "--via")
if not pos:
die("用法:mainline adopt <owner/repo#N> [--via <hub 票 owner/repo#N>](把一張票掛進主線=「補收」)")
ms = ML.load()
if not ms:
die("🔴 現在沒有主線,沒有東西可以補收進去。先 `scripts/mainline set …`。")
owner, repo, num = T.parse_ref(argv[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")
owner, repo, num = T.parse_ref(pos[0])
ref = "%s/%s#%d" % (owner, repo, num)
ms["members"] = sorted(set(ms.get("members") or []) | {ref})
if owner == ms["owner"] and repo == ms["repo"]:
T.api("/repos/%s/%s/issues/%d" % (owner, repo, num), {"milestone": ms["id"]}, method="PATCH")
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」(%s/%s#%d" % (ref, ms["title"], owner, repo, mid))
print("✅ 補收:%s → %s" % (ref, how))
print(members_line(ms["members"], info) if info.get("reached") else " (成員清單沿用舊快取+這一張)")
print(mirror_line())
@@ -310,18 +412,22 @@ def cmd_has(argv):
return
v = ML.belongs(ref, ms)
if v is None:
owner, repo, num = T.parse_ref(ref)
it = T.api_soft("/repos/%s/%s/issues/%d" % (owner, repo, num))
title = ((it or {}).get("milestone") or {}).get("title") if isinstance(it, dict) else None
v = ML.belongs(ref, ms, ticket_milestone_title=title or "")
if not isinstance(it, dict):
need_net()
parts, it = fetch_issue(ref)
if not it:
print("⚪ 讀不到 %s,判不出來(讀不到 ≠ 不屬於)。" % ref)
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:
print("✅ %s 在主線「%s」上。" % (ref, ms["title"]))
sys.exit(0)
print("🚧 %s **不在**主線「%s」上。\n"
" 補收 ⇒ `scripts/mainline adopt %s`;真的是插件事 ⇒ 那是跳線,說清楚再做。"
" 補收 ⇒ `scripts/mainline adopt %s`(別 repo 的票會成為 hub 票的相依);"
"真的是插件事 ⇒ 那是跳線,說清楚再做。"
% (ref, ms["title"], ref))
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")
HERE = os.path.dirname(os.path.abspath(__file__))
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():
"""帳本住哪裡。
🔴 **不能住在 plugin 目錄裡**ISEP 是用 marketplace 裝的,
`claude plugin update` 會把那個目錄整個換掉 ⇒ 累積幾個月的帳一次歸零,
而這張票的全部價值就在「累積」。
順序:環境變數 → 這個 session 的專案根底下的 `system-dev/`(總管的跨專案知識庫
帳本本來就屬於那一層)→ 這份原始碼所在 repo 的 `system-dev/` → `~/.claude/`。
inkstone/ISEP#133 實撞:雲端的 `$CLAUDE_PROJECT_DIR` 是薄殼根(沒有 `system-dev/`
上一版於是退到「原始碼所在 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")
if v:
return v
for base in (os.environ.get("CLAUDE_PROJECT_DIR") or "", ROOT):
if base and os.path.isdir(os.path.join(base, "system-dev")):
for base in _project_roots():
if os.path.isdir(os.path.join(base, "system-dev")):
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")
+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 -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 "$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}
return d
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", 3, ["s/todo"], "main", assignees=("someone",)), # 票上第 1 條:有 assignee
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 的形狀:有人在做
}
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", "[]"))) # 測「主線抓盡」用:把某幾張從池子拿掉
def fake_api(path, payload=None, method=None):
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
enumerate(["s/todo", "s/doing", "s/review", "p/high", "Human"], 1)]
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)
if m and (method or "GET") == "GET":
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 "★ --all:主線裡可抓的恰好是 Arcrun#6、ISEP#1 兩張——Humanassigneebacklog 三張都不在" \
"['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 排在主線之後(主線抓盡才輪到)" \
"['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"
@@ -201,6 +222,10 @@ blocked "已指派的 ISEP#3" inkstone/ISEP#3
blocked "backlog 的 ISEP#4" inkstone/ISEP#4
blocked "沒逾期也不是主線的 Arcrun#8" inkstone/Arcrun#8
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" \
"[\"cmd_claim\",\"inkstone/ISEP#2\",\"--mainline\",\"$MAIN\"]"
p "身份名不在名單上 → 在打任何 API 之前就擋(一通都沒打)" "True" "rc==2 and len(rec)==0" \
+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 ]
+98 -35
View File
@@ -132,6 +132,10 @@ def token():
• 或設環境變數 GITEA_TOKEN_CLAUDE_CODE""")
_TOLERATE = () # 這一次呼叫可以吞掉的 HTTP 狀態碼(見 add_dependency
_TOLERATED = object() # api() 吞掉時回的哨兵——不是 None,None 是「回應是 null」
def api(path, payload=None, method=None):
url = path if path.startswith("http") else f"{HOST}/api/v1{path}"
data = json.dumps(payload).encode() if payload is not None else None
@@ -141,6 +145,8 @@ def api(path, payload=None, method=None):
try:
return json.load(urllib.request.urlopen(req, timeout=40))
except urllib.error.HTTPError as e:
if e.code in _TOLERATE:
return _TOLERATED
die(f"🔴 Gitea {e.code}{e.read().decode()[:300]}")
@@ -663,6 +669,31 @@ def _deps(owner, repo, num):
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):
"""反方向:**誰把這張票當相依**——也就是這張票的頂層票(可能不只一張、可能跨 repo)。
@@ -845,7 +876,8 @@ def subtask_example(parent=None, draft=None):
USAGE = {
"pick":
"用法:{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"
" → $CLAUDE_PROJECT_DIR/system-dev/mainline.json\n"
" 離開碼:0 = 有票(印在 stdout);1 = 真的沒有可抓的票;2 = 讀不到(讀不到 ≠ 沒有)",
@@ -966,8 +998,7 @@ def cmd_subtask(argv):
print(f" 下一步:{nxt}")
# 🔴 相依掛不上去 = 這張子票對母票是隱形的 ⇒ 整個動作算失敗,要讓人看到
api(f"/repos/{powner}/{prepo}/issues/{pnum}/dependencies",
{"owner": ORG, "repo": repo, "index": cnum})
add_dependency((powner, prepo, pnum), (ORG, repo, cnum))
deps = _deps(powner, prepo, pnum)
openn = [i for i in deps if i["state"] == "open"]
print(f" 相依:已掛上 {powner}/{prepo}#{pnum}(它存在、且擋著母票)")
@@ -1299,6 +1330,10 @@ def pickable(issue, milestone_title):
# 2026-09-07 實查:ISEP#3135 五張 hub 掛在逾期里程碑上、s/todo、沒人——
# 照欄位規則會被抓走,但它們不是一件可以做完的事。容器不是任務。
return False, "是 hubscope 容器,不是一件可以做完的事)"
if milestone_title is None:
# inkstone/ISEP#133:呼叫端已經用相依邊確認它在主線上(別 repo 的票靠相依進來,
# 本來就不掛 hub 里程碑)⇒ 這一格不看里程碑。
return True, "ok"
ms = (issue.get("milestone") or {}).get("title")
if not ms:
return False, "沒有里程碑(backlog/沒排進 sprint 的不抓)"
@@ -1389,40 +1424,65 @@ def _issues_in(owner, repo, title):
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):
"""依序回 [(組名, 里程碑標題, [可抓的票…])]:第一組是主線,之後是逾期的 open 里程碑
(最逾期的先)。**每一組裡都已經照 pick_order 排好。**"""
(最逾期的先)。**每一組裡都已經照 pick_order 排好。**
主線那一組的成員由相依邊決定(`mainline_members`),**不是**同名里程碑:
別 repo 裡叫同一個名字的里程碑,裡面的票不會被當成主線抓走(inkstone/ISEP#133)。
逾期那幾組是**一個里程碑物件一組**(owner/repo#id),同名不合併。"""
ML = _mainline_lib()
now = now or _now()
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)
opened = _open_milestones(owner, repos)
groups = []
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"]):
overdue = []
for r, m in _open_milestones(owner, repos):
if "%s/%s#%s" % (owner, r, m.get("id")) == anchor:
continue
due = ML.due_of(m)
if due and due < now:
key = ML.norm(m.get("title"))
if key not in overdue or due < overdue[key][0]:
overdue[key] = (due, m.get("title"))
for due, title in sorted(overdue.values()):
groups.append(("逾期里程碑", title, collect(title)))
overdue.append((due, r, m))
for due, r, m in sorted(overdue, key=lambda x: x[0]):
found = []
for it in _issues_in(owner, r, m.get("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
@@ -1496,17 +1556,20 @@ def cmd_claim(argv):
issue = api("/repos/%s/%s/issues/%d" % (owner, repo, num))
issue.setdefault("repository", {"full_name": "%s/%s" % (owner, repo)})
ims = issue.get("milestone") or {}
ok, why = pickable(issue, ims.get("title") or "")
if ok:
on_mainline = ML.norm(ims.get("title")) == ML.norm(ms["title"])
ref = "%s/%s#%d" % (owner, repo, num)
# 在不在主線上:看相依邊與 hub 里程碑(inkstone/ISEP#133),不看標題
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)
if not on_mainline and not (due and due < _now()):
ok, why = False, "里程碑「%s」既不是主線「%s」也還沒逾期" % (ims.get("title"), ms["title"])
if not (due and due < _now()):
ok, why = False, "里程碑「%s」既不是主線「%s」也還沒逾期(別 repo 的同名里程碑不算主線)" % (
ims.get("title"), ms["title"])
if not ok:
die("""🚫 %s/%s#%d 現在不能抓:%s
抓票規則(inkstone/ISEP#131,全部是 Gitea 欄位):
s/* 恰好是 s/todo 沒有 assignee 沒有 Humanhuman/* 里程碑是主線(主線抓盡才抓逾期)
s/* 恰好是 s/todo 沒有 assignee 沒有 Humanhuman/* 在主線上(hub 里程碑或相依;主線抓盡才抓逾期)
出路:`%s pick` 會回一張符合規則的票;這張如果真的該你做,回票上問總管改欄位,不要硬抓。""" % (
owner, repo, num, why, self_path()))
@@ -1515,7 +1578,7 @@ def cmd_claim(argv):
_set_labels(owner, repo, num, keep)
lines = [ident, "",
"🙋 **認領** → `%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/review` `ticket handback`(不推 main、不出貨、不改里程碑)"]
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:]))
+119
View File
@@ -352,3 +352,122 @@ leo 當場:「**這些為什麼不寫到票裡?**」
📌 判準:**送出去之前,先問「我判的是不是我要送的那個東西」**。
工作樹、最新 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/`
- ISEP 的 wiki 只記 ISEP 自己的事,不複製 InkStoneCo 的 wiki 內容(複製即 forkfork 即漂移)。
- 環境(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)。