Compare commits

..

2 Commits

Author SHA1 Message Date
claude-code 602500a4c7 把主線接進派工與注入(inkstone/ISEP#82)
- hooks.json     mainline-focus-guard 掛 Agent+Task(派工的兩個入口都要守);
                 SessionStart 多一條 `scripts/mainline refresh`(0.8s,不輪詢)
- hooks-inventory 54 支/71 條(當場數的)+補人話一列;順手修掉上一版重複的那一行,
                 並把「指向空氣」那格的假警報寫清楚(countdown-milestone-refresh 在 scripts/)
- TESTING        A16(24 條離線)+ A17(要網路的那半怎麼驗)
- plugin.json    描述數字對齊;版本不動,待總管定版
2026-08-28 00:34:07 +00:00
Claude Code ac2f89c610 現在的主線是哪一個,變成一個查得到的事實(inkstone/ISEP#82)
14 個 open milestone 同時亮著,其中「Mira 現代化」同名活在 5 個 repo,
所以 SOP 說的「那個 active milestone」在現場沒有指涉對象。

- hooks/lib/mainline.py        主線的唯一存放處(一個檔放得下一條),從不打網路
- scripts/mainline             show/list/set/clear/refresh/adopt/has
- hooks/mainline-focus-guard.sh 派了不在主線上的票 ⇒ 攔一次,問補收還是跳線
- hooks/lib/countdown.py       ⏱ 那一行的主線改讀「被標定的」,蓋過「期限最近」的猜測
- hooks/countdown-guard.sh     同一個注入點加第二行 🎯(ISEP#63 那半不動)
- 測試 24 條(離線)+ countdown 原有 20 條仍全綠
2026-08-28 00:30:09 +00:00
21 changed files with 26 additions and 2652 deletions
+2 -2
View File
@@ -1,7 +1,7 @@
{
"name": "isep",
"description": "InkStone Environment Plugin —— leo 的 Claude Code 環境唯一真相源:54 支機械閘(71 條註冊,白話盤點見 docs/hooks-inventory.md)、7 支 slash command、2 支 skill、43 支腳本,外加治理規範與標籤真相源。本機與雲端裝同一份,沒有子集。",
"version": "0.13.0",
"description": "InkStone Environment Plugin —— leo 的 Claude Code 環境唯一真相源:54 支機械閘(71 條註冊,白話盤點見 docs/hooks-inventory.md)、7 支 slash command、2 支 skill、36 支腳本,外加治理規範與標籤真相源。本機與雲端裝同一份,沒有子集。",
"version": "0.11.0",
"keywords": [
"inkstone",
"guardrails",
+2 -15
View File
@@ -23,23 +23,10 @@
| | 數量 | 是什麼 |
|---|---|---|
| `hooks/` | 54 支 `hooks.json` | 全部機械閘(PreToolUseStopSubagentStopSessionStartPostToolUse 共 71 條註冊。**一支一行的白話盤點在 `docs/hooks-inventory.md`,那裡才是這兩個數字的家** |
| `hooks/` | 48 `hooks.json` | 全部機械閘(PreToolUseStopSubagentStopSessionStartPostToolUse 共 59 條註冊`ISEP#60` 移除 `claim-verify-police.sh``subagent-claim-worksheet.sh` 這對自造機制,改由 Gitea 原生三格承接見 `ISEP#59` |
| `commands/` | 7 支 | `/wiki-recall` `/ship-check` `/cp-write` … |
| `skills/` | 2 支 | |
| `scripts/` | 38 支 | `ticket``github-arm.sh``gitea-bootstrap.sh`(頂層檔案,不含 `lib/` 等子目錄) |
> 🔴 **這四個數字要用數的,不要用推的**(2026-08-28:上一版寫 485923
> 而真實是 54/71/38——三個都錯,錯了不知道多久)。重數一次:
>
> ```sh
> ls hooks/*.sh | wc -l # hooks
> ls commands/*.md | wc -l ; ls -d skills/*/ | wc -l
> find scripts -maxdepth 1 -type f | wc -l # scripts(頂層)
> python3 -c "import json;h=json.load(open('hooks/hooks.json'));h=h.get('hooks',h);\
> print(sum(len(m.get('hooks',[])) for ev in h.values() for m in ev))" # 註冊條數
> ```
>
> **這是 leo 的驗收介面**——多報就是假綠(`docs/hooks-inventory.md` 開頭記著同一個病)。
| `scripts/` | 23 支 | `ticket``github-arm.sh``gitea-bootstrap.sh` … |
**不放**`.env`(金鑰,違 D36「金鑰只有一個家」)、`wiki/``docs/``_archive/`
——那些是**知識**不是**環境**。
-144
View File
@@ -208,145 +208,6 @@ bash hooks/tests/prod-write-guard.test.sh hooks/prod-write-guard.sh
- 「卡點二」2 條任一紅 ⇒ 「談論它」又被當成「執行它」(同款第八次),
或是剝了內文之後連真的部署都放行了
### A16 — 「總管可以放行」那道門真的打得開:17 條
```
bash hooks/tests/gate-ok.test.sh
```
**該看到**`通過 17 條,失敗 0 條`
**它在守什麼**inkstone/ISEP#90 ④,2026-08-28 實查):三支閘
`prod-write-guard``main-and-prod-push-guard``stage-before-prod-guard`
都是「擋下來、但**總管看過就能放行**」的設計,而**既有測試只驗了擋得住,
一條都沒驗過放得開**。於是這個 bug 活了很久:`stat -f %m` 在 GNU coreutils 上
是「檔案系統資訊」,它一邊回非零一邊吐一整段文字 ⇒ 秒數被污染 ⇒
**在 Linux(=每一個雲端 session)上戳記永遠不被接受** ⇒ 那三支閘在雲端等於純擋,
而閘不會告訴你門是壞的。
**失敗**
- ②⑤(門打得開)紅 ⇒ 逃生口又焊死了,那三支閘在雲端變回純擋
- ⑥⑦⑧(門沒變寬)任一紅 ⇒ **更嚴重**:綁 repo/有效期/空戳記那三條性質是
08-11、08-12 兩次真的被穿透之後才補上的,不准為了「好放行」而鬆掉
- ⑫ 紅 ⇒ `gate-ok` 在解不出 repo 時留下了一枚註定打不開的空戳記,
那會讓人以為門開了(而空戳記本身就是 08-12 那把萬用鑰匙的形狀)
- ⑰ 紅 ⇒ 判準又變回「行為取決於 cwd 裡有沒有一個叫 `%m` 的檔」。
這條是這個 bug 的最後一層:**GNU 的 `-f` 是布林旗標,`%m` 被當成另一個檔名運算元**
⇒ 有那個檔就 `exit 0``||` 連跑都不跑。所以修法不能只是「把順序反過來」,
**每一步都要驗它是不是純數字**
⚠️ 這支會真的寫 `/tmp` 的戳記檔(那是閘寫死的路徑)。**不要在「已經蓋好戳記正要推東西」
的當下跑它**——它會把那枚戳記洗掉。
### A17 — 未推警察不會對雲端的工作分支亂叫:10 條
```
bash hooks/tests/unpushed-police.test.sh
```
**該看到**`通過 10 條,失敗 0 條`。全離線(用本機 bare repo 當「遠端」)。
**它在守什麼**inkstone/ISEP#90 ①):雲端 session 開出來的工作分支天生沒有 upstream,
內容卻等於遠端 main ⇒ 舊判準「沒 upstream=從沒推過」讓**每個雲端 session、每次收工
都被攔一次**08-27 一個 session 五次全是誤報)。
**失敗**
- A 群(①—⑥,不該報)任一紅 ⇒ **誤攔**,比漏擋嚴重:永遠在響的警報=訓練人忽略它,
下一條真的失蹤的分支會混在雜訊裡
- B 群(⑦—⑩,該報)任一紅 ⇒ 為了不吵而改成放行了,那是把閘關掉不是修好
- 特別看 ④:問不到遠端(離線)**不准當成「你沒推」**
### A18 — 信標會講出雲端會壞掉的那三件事:14 條
```
bash hooks/tests/isep-presence-beacon.test.sh
```
**該看到**`通過 14 條,失敗 0 條`。全離線。
**它在守什麼**inkstone/ISEP#90 ②③):信標原本只證明「有一份 plugin 載入了」,
不證明「載入的是哪一份」——08-27 雲端載 0.3.9、main 0.9.0,差 7 個 release
而它照樣是綠的。
**失敗**
- ⑫⑬⑭(信標永遠在)任一紅 ⇒ **最嚴重**:那一行消失=leo 會判定這個 session 零閘
- ③ 紅 ⇒ 版本落差報不出來,`ISEP#67` 那個病又變回看不見
- ⑤⑦ 紅 ⇒ 舊複本遮蔽正門抓不到(`InkStoneCo/scripts/ticket` 那件)
- ⑥ 紅 ⇒ **誤攔**:同步過的複本被念,人就學會忽略它
- ⑪ 紅 ⇒ 內層迴圈變數撞名的回歸(同一個 `.claude` 下第二個殘骸會被靜靜跳過)
### A19 — 下游做完時頂層跟著關:49 條
```
bash scripts/test-ticket-handoff-writeback.sh
```
**該看到**`通過 49 條,失敗 0 條`。**全程離線**——`TICKET_HOST` 指到連不上的位址,
會打 API 的兩段(`_writeback``cmd_subtask`)把 `api()` 換成錄音機跑,
**不打真實 Gitea、不開票、不關票、不留任何測試票**
**它在守什麼**`inkstone/ISEP#92`):
「開在頂層的票,下游做完了卻沒人回來關⋯⋯頂層票會永遠掛著,**而 leo 是看頂層的**。」
四格對應票上的四條驗收條件:
- ①②③ 純函式(`is_loose``writeback_plan``journey_label`)——**判準本身**
不必開真票就驗得動
- ④⑤ `subtask``handoff` 的參數閘:該擋的擋、齊全的放得過
-**完工回寫的接線**(驗收第 2 條):關掉一張下游票之後,它到底對頂層票做了什麼
-**雙向連結的接線**(驗收第 1 條):兩張票互相看得到對方,不是靠人記得補
**失敗**
- ①「open + 從來沒有下游 → 不撈」紅 ⇒ **誤攔**`ticket loose` 會把每一張普通票
都列出來,那張表就變成雜訊,人學會忽略它(本 repo 心法第 2 條)
- ②「還有別的下游沒關 → 只記一筆」紅 ⇒ 母票會在下游還沒做完時被指派回總管,
假綠
- ⑦「沒有去關母票」變綠 ⇒ 回寫從「處理」滑成「自動關掉」。
**默默關掉跟默默留著是同一個病的兩面**——關票要有交付物、要有人看過
- ⑦「留言第一行有身份欄」紅 ⇒ 機器貼的留言看起來像某個人寫的,
下一個讀票的人會去找那個人(`reply-identity-guard` 管的是同一件事)
- ⑧「母子兩端都被貼」剩 1 ⇒ journey 只貼了一端,**聚類時撈得到一半**,
比完全沒貼更危險
- ⑤ 任何一條紅 ⇒ 誤攔,合規的交辦被擋掉等於這條路不能走
🔴 **這支測不到的那一格(要 leo 或總管接手)**`labels.yaml``j/`
**刻意是空的**——旅程怎麼切、叫什麼名字是方向題,不由工具代決。
在有人往那裡加第一條旅程之前,`--journey` 只會擋、不會貼。
機制驗過了,**資料還沒有**。
### A20 — 舊票每天有固定管道被撈出來:47 條
```
bash scripts/test-debt-worklist.sh
```
**該看到**`通過 47 條,失敗 0 條`。**全程離線**:資料走 `ISEP_DEBT_FIXTURE`
時鐘走 `ISEP_DEBT_NOW`、狀態走 `ISEP_DEBT_STATE_DIR`、主線走 `ISEP_COUNTDOWN_STATE_DIR`
——**不打 Gitea、不留測試票、不碰 `$HOME`**。
**它在守什麼**`inkstone/ISEP#83`leo 2026-08-27):
「現在每天都在追新的,所以**要用 Routine 去消化舊的**,可以有多個條件」。
全 org 229 張 open 票,每天在動的只有掛在 open milestone 上的那 56 張;
其餘的不是不重要,是**沒有任何機制會去拿它們**。
🔴 **兩條線各用各的判準,不是二選一**leo 當場訂正總管的誤解):
掛 milestone =緊急線,用「距離目標的遠近」排;沒掛的=還債線,用多條件排
(事故/擋人/承諾/票齡/估工)——後者就是 `scripts/debt-worklist`
**失敗**
- 「驗收 1」那組紅 ⇒ 清單沒有附「我查了哪些 repo」的證明。
**沒有證明的清單分不出「今天真的沒有」與「查詢壞了」**,而後者會靜靜地零產出
- 「驗收 2」紅 ⇒ 空清單默默結束。這是這支工具最貴的失效方式:
它看起來跑完了,於是沒有人再去看那 180 張
- 「驗收 3」紅 ⇒ 領走的票明天又冒出來,這份清單就會變成每天一樣的一坨,人就不看了
- 「成包」兩條紅 ⇒ 互相指著/母子票被拆開領,做到一半才發現卡在另一張
- **「單向引用不成包」紅 ⇒ 這是誤攔的那一面**:第一版用單向引用成包,
結果 190 張裡 121 張黏成一包(大家都會順手引用 hub 票)=**一包沒有人領得動**
- 「接上主線」那組紅 ⇒ 還債線又自己養了一套「哪個是 active」的判斷。
唯一答案在 `hooks/lib/mainline.py``inkstone/ISEP#82`),**兩份必然漂移**。
特別看「沒標主線」那兩條:**沒有答案時要退回保守**(掛 open milestone 的一律不領),
不准猜一條出來
- 最後一組(SessionStart)紅 ⇒ 要嘛沒有人會被提醒去撈,
要嘛那一段偷偷去打網路——**開 session 自動撈就是輪詢**,紅線擋著
**手動驗真實資料**(會打 Gitea,唯讀 GET):
```
python3 scripts/debt-worklist list --top 5
```
**該看到**15 個 repo 逐一列出 issue/PR 數,講得出**現在的主線是哪一條**
(或誠實說沒標),扣除數字講得出來(掛 open milestone 的幾張、等 leo 的幾張、已領走的幾張),
前幾名旁邊看得到「為什麼排這裡」的分項。
**失敗**:前幾名一眼看不出為什麼在那裡 ⇒ 那些權重就是錯的,去改 `score()`
**不要改成「總管覺得」**——這份清單的價值就在於它不靠記憶。
### A5 — 開票前的搜尋是跨 repo 的
```
python3 scripts/ticket where 標籤 模組化
@@ -550,11 +411,6 @@ B2(信標那行)/B3(setup 輸出)/B4(閘的訊息)三個畫面
| **A10 人閘警察準度** | 總管 | ✅ 9/9,連跑三次(2026-08-26),A 群誤攔 0 |
| **A11 派工單只剩票號** | 總管 | ✅ 19/192026-08-27 |
| **A12 留言身份欄(兩道門)** | 總管 | ✅ 11/112026-08-27 |
| **A16 放行的門真的打得開** | 總管 | ✅ 17/172026-08-28inkstone/ISEP#90 |
| **A17 未推警察不誤攔雲端分支** | 總管 | ✅ 10/102026-08-28inkstone/ISEP#90 |
| **A18 信標會報雲端接線缺陷** | 總管 | ✅ 14/142026-08-28inkstone/ISEP#90 |
| **A19 下游做完頂層跟著關** | 總管 | ✅ 49/492026-08-28inkstone/ISEP#92 |
| **A20 舊票有固定管道被撈** | 總管 | ✅ 47/472026-08-28inkstone/ISEP#83)+真實 229 張唯讀實跑 |
| A7 plugin 裝得起來 | 總管 | ✅ |
| **A8 新 session 閘會觸發** | 總管 | 見本版 release note |
| **B1B5 雲端** | **leo** | 還沒跑(機器碰不到 Cloud environment |
-195
View File
@@ -1,195 +0,0 @@
# 雲端 session 的閘為什麼跟地端不一樣(inkstone/ISEP#90
> leo 的目標一句話:**讓雲端 session 跟地端拿到同一組閘、同一組能用的工具。**
雲端不是「地端少幾支閘」,是**同一批閘在雲端的行為不一樣**。四個實例,
每一個都穩定重現,而且每一個都**不會自己喊痛**——這才是它們活這麼久的原因。
---
## 四個缺陷,兩種病
| | 缺陷 | 病 |
|---|---|---|
| ① | 未推警察每個雲端 session 都誤攔 | 判準在雲端**不成立** |
| ② | `scripts/ticket` 在雲端拿不到 token | 跑到的是**另一份**(舊複本) |
| ③ | 已刪除的機制在雲端重生 | 載到的是**另一版**0.3.9 vs 0.9.0 |
| ④ | 總管的「我確認過了」出口打不開 | 判準在雲端**不成立**(平台差異) |
①④ 是同一種病:**閘的判準寫的是地端才成立的假設**。
②③ 是同一種病:**同一個東西有兩份,而雲端跑到的是舊的那份**。
---
## ① 未推警察:判準是「有沒有 upstream」,而雲端的分支天生沒有
雲端 session 開出來的工作分支沒有 upstream,**內容卻等於遠端 main**
```
薄殼 HEAD = 081c547d90dc2d80692485af083ca1f71f2094f2
GitHub 遠端 main = 081c547d90dc2d80692485af083ca1f71f2094f2 ← 同一顆
```
⇒ 每個雲端 session、每次收工都被攔一次(2026-08-27 一個 session 五次全是誤報)。
**修法**:判準改成「**遠端有沒有這顆 commit**」(`git ls-remote`)。
本機的 remote-tracking ref 只答得準「有」——08-28 實測那份 `origin/main` 落後遠端 4 天
——所以答「沒有」的時候才打網路。三態:有/沒有/**問不到**;問不到一律不報。
**順手補的**`$CLAUDE_PROJECT_DIR` 在雲端是**薄殼根**,真身在 `$TOP/InkStoneCo/`
舊的掃描清單四個路徑在雲端一個都不存在 ⇒ **真身有東西沒推,這支閘一輩子不會知道。**
同一支閘在雲端既亂叫、又看不到該看的地方。
---
## ② `scripts/ticket`:跑到的是舊複本,不是 plugin 那一份
- ISEP 的 `scripts/ticket` **早在 2026-08-20 就修好了**(掃所有 remote 環境變數 fallback
- 但雲端 cwd 是真身,那裡有一份 `InkStoneCo/scripts/ticket` 的**舊複本**
取 token 邏輯還停在「只認名叫 `gitea` 的 remote」,而 `bootstrap.sh` 把 Gitea 設成 `origin`
- ⇒ 雲端一律死在「拿不到 gitea token」
🔴 **後果比「一支腳本壞了」嚴重**`scripts/ticket` 是開票/留言的**正門**
它一壞,人就繞過去直接打 Gitea API——**而那正是 `ticket-api-bypass-guard.sh` 在防的事**。
**一道閘把人逼去走它自己禁止的那條路,那道閘就是在製造違規。**
**ISEP 這半的修法**:信標在 session 開頭就點名「專案裡有 ISEP 腳本的舊複本,
而且**內容不同**」。判準不是檔名一樣,是**檔名一樣而內容不同**——同步過的複本不吵。
**真身那半(把那份複本同步或刪掉)不在 ISEP,要在 `inkstone/InkStoneCo` 修。**
---
## ③ 已刪除的機制在雲端重生
```
ISEP main .claude-plugin/plugin.json → 0.9.0
雲端實際載入 → 0.3.9 ← 差 7 個 release
```
0.3.9 裡還活著兩支在 v0.9.0 已整支刪除的 hook ⇒ `.claude/pending-verification/`
被清掉之後又長回來。**一個看不見的版本落差,會讓已經刪掉的機制在別人的工作區裡復活。**
**傳輸那半是 `inkstone/ISEP#67`**(新版到不到得了手上),本票不重複那件。
**ISEP 這半能做的是讓它不再看不見**:信標匿名讀 ISEP main 的 `plugin.json`
(D20 判準下屬於「讀」,不需開閘),落後就講清楚差幾版、怎麼重拍快照;
同時掃 `.claude/` 底下**這一份 plugin 的 hooks/scripts 一個字都沒提到**的目錄,
點名它們是殘骸。判準是「plugin 現在還認不認得它」,**不是關鍵字黑名單**
leo 2026-08-17 已證明那條路 8 次誤攔、0 次正確攔截)。
---
## ④ 「總管可以放行」的門,在雲端是焊死的
三支閘(`prod-write-guard``main-and-prod-push-guard``stage-before-prod-guard`
都是「擋下來、但**總管看過就能放行**」。它們判斷戳記新不新都用同一行:
```sh
MT=$(stat -f %m "$STAMP" 2>/dev/null || stat -c %Y "$STAMP" 2>/dev/null || echo 0)
```
macOSBSD stat)上 `-f %m` 就是 mtime,對的。
**GNU coreutils 的 `-f` 是「顯示檔案系統資訊」**,而且它**一邊回非零、一邊往 stdout
吐一整段區塊**
```
$ stat -f %m /tmp/.probe
stat: cannot read file system information for '%m': No such file or directory ← stderr
File: "/tmp/.probe" ← stdout
ID: 0 Namelen: 255 Type: ext2/ext3
```
`2>/dev/null` 吃掉錯誤訊息、`||` 把正確的秒數接在那堆垃圾**後面**
`case "$NOW$MT" in *[!0-9]*) return 1` 必然命中
**在 Linux(=每一個雲端 session)上,那三支閘的戳記永遠不會被接受。**
### 再往下一層:`-f` 根本不吃格式參數,所以連離開碼都不可靠
總管 2026-08-28 自己驗這一格時量到 `exit=0`,而我量到 `exit=1`
**兩個都是真的**,而分歧本身就是這個 bug 最後一塊拼圖:
**GNU 的 `-f` 是 `--file-system`,它是布林旗標、不接格式字串**
`%m` 不是格式,它被當成**另一個檔名運算元** ⇒ 離開碼取決於
「當前目錄裡有沒有一個叫 `%m` 的檔」:
```
$ cd /tmp/statprobe && touch .mt
# A. 沒有名為 %m 的檔(一般情況)
$ stat -f %m .mt ; echo "exit=$?"
stat: cannot read file system information for '%m': No such file or directory
File: ".mt" … ← 檔案系統資訊照樣印到 stdout
exit=1 ← `||` **會**跑 ⇒ 正確的秒數接在那堆垃圾後面
# B. 剛好有一個叫 %m 的檔
$ touch '%m' && stat -f %m .mt ; echo "exit=$?"
exit=0 ← `||` **不會**跑 ⇒ 整包連一個數字都沒有
```
(實測環境:`stat (GNU coreutils) 9.4`
**兩種情況下閘的結果一模一樣**——`MT` 都不是純數字,
`case "$NOW$MT" in *[!0-9]*) return 1` 都必然命中,戳記都作廢:
```
情況 A:非數字 ⇒ return 1 ⇒ 戳記作廢
情況 B:非數字 ⇒ return 1 ⇒ 戳記作廢
```
🔴 **這一層才是真正該記住的教訓**:舊寫法的 `||` fallback 之所以救不了,
**不是因為它沒跑,而是因為「跑不跑」根本不由這支腳本決定**
——它由「當前目錄裡有沒有一個叫 `%m` 的檔」決定。
一個**行為取決於 cwd 裡有沒有某個檔名**的判斷式,不管跑不跑都是壞的。
⇒ 所以 `lib/mtime.sh` 的修法不是「把順序反過來」而已,是
**每一步都驗它是不是純數字**:這個 bug 的成因正是「命令失敗了卻還是印了東西」,
**只看離開碼會再被騙一次**
📌 這一格的實害(總管 2026-08-28 原話):「我今天為了發一則通知,
用了兩種方式蓋 `prod-write-ok` 都無效,一度以為是權限問題。」
**閘不會告訴你門是壞的**,所以人會往錯的方向查(權限、classifier、設定),
而根因在閘自己身上。
🔴 **後果**:那三支閘在雲端**等於純擋**。總管照著閘自己印的指示做,
做幾次都打不開,**而閘不會告訴他門是壞的**。
**為什麼活這麼久**:既有的三支測試(29/16/10 條)**只驗了「擋得住」,
一條都沒驗過「放得開」**。⇒ 這正是「閘的另外一半從來沒被測過」的代價。
**修法**`hooks/lib/mtime.sh` —— 先 `-c %Y`GNU)再 `-f %m`BSD),
**每一步都驗它是不是純數字**(這個 bug 的成因正是「命令失敗了卻還是印了東西」,
只看離開碼會再被騙一次)。
### 附帶:逃生口收斂成一個入口 `scripts/gate-ok`
原本每支閘的門長得都不一樣,而且藏在被擋下的那則訊息裡:
```
touch /tmp/.prod-write-ok
git rev-parse --show-toplevel > /tmp/.main-push-ok
touch /tmp/.solo-ok-<session_id>
```
兩個後果:**記不住**(抄錯一個字門就打不開),以及**沒有穩定形狀可以事先放行**
——`.claude/settings.json` 的 allow 只能逐條完全比對(現場真的寫著
`Bash(touch /tmp/.prod-write-ok)` 這種一行),多一個 `&&`、換一個 session id
就落在規則之外,然後由權限層自己判斷。
`bash "$CLAUDE_PLUGIN_ROOT/scripts/gate-ok" <閘名> [參數]`**一個名字、一種形狀**
一條前綴規則涵蓋全部,以後新增閘不必再動一次設定。
🔴 **它沒有弱化任何一道閘**:蓋的是同一個檔、同一種語意——單次用完即丟、綁 repo、
綁 session、有效期全部沒動。換掉的只有「怎麼蓋」。
`hooks/tests/gate-ok.test.sh` 的 ⑥⑦⑧ 三條就是在守這件事(那三條性質是 08-11、08-12
兩次真的被穿透之後才補上的)。
---
## 還沒關掉的那兩格(不屬於 ISEP)
| 缺口 | 住在哪 |
|---|---|
| 雲端載到的版本追上 ISEP main | `inkstone/ISEP#67` |
| `InkStoneCo/scripts/ticket` 這份舊複本 | `inkstone/InkStoneCo`(真身) |
ISEP 這一側能做的是**讓它們不再是看不見的**:兩件現在都會在 session 開頭被信標點名。
+2 -18
View File
@@ -42,28 +42,12 @@ case "$ROOT" in
*) SRC="來源不明" ;;
esac
# ── 交給 lib/beacon_report.py 組訊息 ─────────────────────────────────
#
# 🔴 為什麼改成走 python 而不是繼續用 printf 拼 JSONinkstone/ISEP#90):
# 下面要多報三件事(版本落差/舊複本遮蔽正門/退役機制的殘骸),
# 而那三段的內容含引號與換行。**用 shell 內插拼 JSON,一個引號就會把整包 JSON 弄壞,
# 而壞掉的 JSON 讓信標整行消失** —— 那正是本檔要偵測的「零閘狀態」的長相。
# ⇒ 訊息本身可以變複雜,但**序列化這件事不准手拼**。
#
# 🔴 fail-openpython 掛掉、網路不通、什麼都不准讓這行消失。
# 信標消失=leo 會判定這個 session 沒有閘(本檔第 8 行寫的判準),
# 所以組不出加料版就退回原本那一行乾淨的訊息。
MSG="🟢 ISEP v${VER} 已載入(${GATES} 支閘|來源:${SRC}${ROOT}"
FALLBACK="{
printf '%s\n' "{
\"systemMessage\": \"${MSG}\",
\"hookSpecificOutput\": {
\"hookEventName\": \"SessionStart\",
\"additionalContext\": \"${MSG}。這行是 ISEP plugin 自己發的——看得到它就表示閘真的生效了。若某個 session 從頭到尾沒有這行,那個 session 是零閘狀態,先修 plugin 再做事,不要用『跑得動』當證據。\"
}
}"
OUT="$(python3 "$ROOT/hooks/lib/beacon_report.py" "$VER" "$GATES" "$SRC" 2>/dev/null || true)"
case "$OUT" in
\{*) printf '%s\n' "$OUT" ;;
*) printf '%s\n' "$FALLBACK" ;;
esac
-167
View File
@@ -1,167 +0,0 @@
# ── 以下三格是 inkstone/ISEP#90 加的「這一份是不是還有效」自檢 ──────────
# 都**只是報告,不擋任何事**(SessionStart 本來就不該擋),而且每一格拿不到答案就閉嘴。
import json, os, re, subprocess, sys, time, urllib.request
ROOT = os.environ.get("CLAUDE_PLUGIN_ROOT", "")
PROJ = os.environ.get("CLAUDE_PROJECT_DIR") or os.getcwd()
VER = sys.argv[1] if len(sys.argv) > 1 else "未知"
GATES = sys.argv[2] if len(sys.argv) > 2 else "?"
SRC = sys.argv[3] if len(sys.argv) > 3 else "來源不明"
MSG = "🟢 ISEP v%s 已載入(%s 支閘|來源:%s%s" % (VER, GATES, SRC, ROOT)
notes = []
# ══ ① 這一份跟 ISEP main 是不是同一版 ═══════════════════════════════════
#
# 🔴 為什麼要自己查(inkstone/ISEP#902026-08-27 實查):
# ISEP main 的 plugin.json → 0.9.0
# 雲端實際載入 → 0.3.9 ← 中間差 7 個 release
# 而信標**照樣是綠的**——它只證明「有一份 plugin 載入了」,不證明「載入的是哪一份」。
# 後果不是抽象的:0.3.9 裡還活著兩支已經在 v0.9.0 整支刪掉的 hook
# 於是 `.claude/pending-verification/` 在雲端**被清掉之後又長回來**。
# ⇒ 一個看不見的落差,會讓「已經刪掉的機制」在別人的工作區裡復活。
#
# 匿名讀(不帶任何憑證)⇒ D20 判準下屬於「讀」,不需要開閘、不計次。
# 快取 6 小時、逾時 6 秒、任何失敗一律閉嘴——信標不能因為網路而變吵或變慢。
def main_version():
cache = os.path.join(os.environ.get("ISEP_BEACON_CACHE_DIR", "/tmp"), ".isep-main-version")
try:
if time.time() - os.path.getmtime(cache) < 6 * 3600:
v = open(cache, encoding="utf-8").read().strip()
return v or None
except Exception:
pass
url = os.environ.get("ISEP_MAIN_MANIFEST_URL",
"https://git.uncle6.me/inkstone/ISEP/raw/branch/main/.claude-plugin/plugin.json")
try:
with urllib.request.urlopen(url, timeout=6) as r:
v = (json.loads(r.read().decode("utf-8")) or {}).get("version") or ""
except Exception:
v = ""
try:
open(cache, "w", encoding="utf-8").write(v)
except Exception:
pass
return v or None
def vtuple(v):
return tuple(int(x) for x in re.findall(r"\d+", v)[:3]) or (0,)
MAIN = main_version() if os.environ.get("ISEP_BEACON_SKIP_NET") != "1" else os.environ.get("ISEP_FAKE_MAIN_VERSION")
if MAIN and VER != "未知" and MAIN != VER:
if vtuple(MAIN) > vtuple(VER):
notes.append(
"🔴 **這一份落後 ISEP main**(載入 %s main %s)——你現在跑的不是最新那組閘,"
"而且**已經刪掉的機制可能還活著**(0.3.9 就是這樣讓 .claude/pending-verification/ 復活的)。"
"修:本機 `claude plugin update isep@inkstone`;雲端要去動一下 Environment 的 setup script "
"內容逼它重拍快照(快取約 7 天)。追蹤票 inkstone/ISEP#67。" % (VER, MAIN))
else:
notes.append("️ 這一份比 ISEP main 新(載入 %s main %s)——沒發版的改動只在這台機器上。" % (VER, MAIN))
# ══ ② 專案裡有沒有 ISEP 腳本的舊複本在遮蔽正門 ══════════════════════════
#
# 🔴 實例(inkstone/ISEP#90 ②):`InkStoneCo/scripts/ticket` 是 ISEP `scripts/ticket`
# 的**舊複本**,它的取 token 邏輯還停在「只認名叫 gitea 的 remote」,
# 而 bootstrap.sh 在雲端把 Gitea 設成 `origin`
# ⇒ 在雲端跑 `scripts/ticket` 一律死在「拿不到 gitea token」
# ⇒ 人只好繞過正門直接打 API——而那正是 ticket-api-bypass-guard.sh 在防的事。
# **一道閘把人逼去走它自己禁止的那條路,那道閘就是在製造違規。**
#
# 判準不是「檔名一樣」,是「檔名一樣**而內容不同**」——同步過的複本不吵。
def shadow_copies():
out = []
src = os.path.join(ROOT, "scripts")
if not os.path.isdir(src):
return out
roots = [PROJ, os.path.join(PROJ, "InkStoneCo")]
for name in sorted(os.listdir(src)):
a = os.path.join(src, name)
if not os.path.isfile(a):
continue
try:
ab = open(a, "rb").read()
except Exception:
continue
for base in roots:
b = os.path.join(base, "scripts", name)
if os.path.realpath(b) == os.path.realpath(a):
continue
if not os.path.isfile(b):
continue
try:
if open(b, "rb").read() != ab:
out.append(os.path.relpath(b, PROJ))
except Exception:
pass
return out
sh = shadow_copies()
if sh:
notes.append(
"🟡 **專案裡有 ISEP 腳本的舊複本**,而它們排在 plugin 前面被叫到:%s"
"兩份必然漂移,漂移的那份會安靜地騙人——`InkStoneCo/scripts/ticket` 就是這樣"
"在雲端一律死在「拿不到 gitea token」。要嘛刪掉複本改叫 "
"`\"$CLAUDE_PLUGIN_ROOT\"/scripts/<名字>`,要嘛把複本同步回 ISEP。" % "".join(sh))
# ══ ③ 工作區有沒有「已退役機制」留下的產物 ══════════════════════════════
#
# 判準是機械的、而且會自己長大:**plugin 自己的原始碼裡有沒有任何一個字提到這個目錄**。
# 提到了 ⇒ 它是現行機制的產物,正常。
# 一個字都沒提到 ⇒ 產生它的東西已經不在這一份 ISEP 裡了 ⇒ 它是殘骸。
# 刻意**不用關鍵字黑名單**leo 2026-08-17 已證明那條路 8 次誤攔、0 次正確攔截):
# 這裡問的是「plugin 現在還認不認得它」,不是「這個名字看起來像不像壞東西」。
NATIVE = {"hooks", "commands", "skills", "agents", "plugins", "wiki", "cloud-shell",
"projects", "statsig", "shell-snapshots", "todos", "ide", "local", "isep"}
def orphan_artifacts():
out = []
for base in [PROJ, os.path.join(PROJ, "InkStoneCo")]:
d = os.path.join(base, ".claude")
if not os.path.isdir(d):
continue
for name in sorted(os.listdir(d)):
p = os.path.join(d, name)
if not os.path.isdir(p) or name in NATIVE or name.startswith("."):
continue
# 🔴 只搜「會產生東西的那些檔」(hooks/scripts),不搜 docs
# docs 提到一個名字**不會讓那個目錄長出來**,但會讓這一格閉嘴。
# 🔴 也要把本檔排除掉:本檔的註解裡就寫著 `pending-verification` 當例子,
# 第一次跑就因此漏報了真正存在的那一個——**自己提到自己=這格靜音**。
try:
hit = False
for sub in ("hooks", "scripts"):
# 🔴 變數名不要跟外層的 `d`(.claude 那個目錄)撞——撞了會把
# 外層迴圈的基準目錄換掉,第二個名字之後全部被靜靜跳過。
# 第一版就是這樣寫的,實測結果:真的存在的 `verified-claims`
# 一聲不吭地消失了。**假綠不是漏寫檢查,是檢查跑在錯的對象上。**
sd = os.path.join(ROOT, sub)
if not os.path.isdir(sd):
continue
if subprocess.run(["grep", "-rqlF", "--exclude", os.path.basename(__file__),
"--", name, sd],
capture_output=True, timeout=20).returncode == 0:
hit = True
break
except Exception:
hit = True # 問不出來就當它有效,不亂報
if not hit:
out.append(os.path.relpath(p, PROJ))
return out
orph = orphan_artifacts()
if orph:
notes.append(
"🟡 **工作區有已退役機制的產物**%s。這一份 ISEP 裡沒有任何東西提到它們"
"(v0.9.0 已整支刪除產生它的 hook),所以它們是殘骸——"
"**它們還在長,就表示這台機器跑的是舊版**(見上面那格)。確認之後刪掉。" % "".join(orph))
CONTEXT = ("%s。這行是 ISEP plugin 自己發的——看得到它就表示閘真的生效了。"
"若某個 session 從頭到尾沒有這行,那個 session 是零閘狀態,"
"先修 plugin 再做事,不要用『跑得動』當證據。" % MSG)
if notes:
MSG = MSG + "\n" + "\n".join(notes)
CONTEXT = CONTEXT + "\n\n" + "\n".join(notes)
print(json.dumps({"systemMessage": MSG,
"hookSpecificOutput": {"hookEventName": "SessionStart",
"additionalContext": CONTEXT}},
ensure_ascii=False))
-57
View File
@@ -1,57 +0,0 @@
# hooks/lib/mtime.sh — 「這個檔幾點被動的」,跨 macOS/Linux 都問得出來。
# 不是獨立掛的閘(沒進 hooks.json),給那幾支用 /tmp 戳記的閘 `source` 用。
#
# ══ 為什麼要有這支(inkstone/ISEP#90 ④,2026-08-28 實查)═══════════════
#
# 三支閘(prod-write-guard、main-and-prod-push-guard、stage-before-prod-guard
# 的戳記檢查都寫成這一行:
#
# MT=$(stat -f %m "$STAMP" 2>/dev/null || stat -c %Y "$STAMP" 2>/dev/null || echo 0)
#
# 在 macOSBSD stat)上它是對的:`-f %m` 就是 mtime。
# 在 **LinuxGNU coreutils)上 `-f` 是「顯示檔案系統資訊」**,而且它
# **一邊回非零、一邊往 stdout 吐一整段檔案系統的區塊**:
#
# $ stat -f %m /tmp/.probe
# stat: cannot read file system information for '%m': No such file or directory ← stderr
# File: "/tmp/.probe" ← stdout
# ID: 0 Namelen: 255 Type: ext2/ext3
# …
#
# ⇒ `2>/dev/null` 把錯誤訊息吃掉、`||` 接著跑 `stat -c %Y` 把正確的秒數**接在那堆垃圾後面**
# ⇒ `MT` 變成「一段多行文字+一個數字」
# ⇒ 閘下一行的 `case "$NOW$MT" in *[!0-9]*) return 1` 一定命中
# ⇒ **在 Linux 上,那三支閘的戳記永遠不會被接受。**
#
# 🔴 這件事的後果不是「少一個便利功能」:
# 那三支閘都是「擋下來,但**總管看過就可以放行**」的設計。
# 放行的那道門在雲端(Linux)打不開 ⇒ **它們在雲端等於純擋**,
# 總管照著閘自己印的指示做,做幾次都打不開,而閘不會告訴他門是壞的。
# inkstone/InkStoneCo#99 記的「連續四次蓋不出戳記」就是這個形狀。
#
# ── 再往下一層:`-f` 根本不吃格式參數,所以連離開碼都不可靠 ────────────
#
# 2026-08-28 兩個人量這一格,一個量到 `exit=0`、一個量到 `exit=1`。**兩個都是真的**
# 而分歧本身就是最後一塊拼圖:**GNU 的 `-f` 是 `--file-system`,布林旗標、不接格式字串**
# ⇒ `%m` 被當成**另一個檔名運算元** ⇒ 離開碼取決於「cwd 裡有沒有一個叫 `%m` 的檔」:
#
# A. 沒有(一般情況) → exit 1 ⇒ `||` **會**跑 ⇒ 正確的秒數接在垃圾後面
# B. 剛好有 → exit 0 ⇒ `||` **不會**跑 ⇒ 整包連一個數字都沒有
#
# 兩種情況下閘的結果一樣:`MT` 都不是純數字,戳記都作廢。(實測 GNU coreutils 9.4
#
# 🔴 **這才是該記住的教訓**:舊寫法的 `||` fallback 救不了,
# **不是因為它沒跑,而是因為「跑不跑」根本不由這支腳本決定**
# ——它由「cwd 裡有沒有某個檔名」決定。
# 一個**行為取決於 cwd 裡有沒有某個檔**的判斷式,不管跑不跑都是壞的。
#
# 🔴 所以修法不是「把順序反過來」而已:改成先 `-c %Y`(GNU)再 `-f %m`BSD),
# 而且**每一步都驗它是不是純數字**——因為這個 bug 的成因正是
# 「命令失敗了卻還是印了東西出來」,只看離開碼會再被騙一次。
file_mtime() {
_fm=$(stat -c %Y "$1" 2>/dev/null || true)
case "${_fm:-}" in ''|*[!0-9]*) _fm=$(stat -f %m "$1" 2>/dev/null || true) ;; esac
case "${_fm:-}" in ''|*[!0-9]*) _fm=$(python3 -c 'import os,sys; print(int(os.path.getmtime(sys.argv[1])))' "$1" 2>/dev/null || true) ;; esac
case "${_fm:-}" in ''|*[!0-9]*) _fm=0 ;; esac
printf '%s' "$_fm"
}
+2 -16
View File
@@ -74,18 +74,6 @@ esac
# ⇒ 沒有可靠的身分辨識時,改成**正向確認**:推 main 前要有一枚新鮮的戳記。
# subagent 當然造得出那枚戳記——但它得刻意繞過一段明講「不要這樣做」的訊息。
# **閘擋的是無心,不是惡意。** 而現在這個版本連無心都擋不了(它誰都擋)。
# 🔴 戳記的 mtime 一律走 lib/mtime.sh:舊寫法(`stat -f %m || stat -c %Y`)在 Linux 上
# **永遠算不出數字**(GNU 的 `-f` 是「檔案系統資訊」,它一邊回非零一邊吐一整段文字,
# 於是後面接上的秒數被那段垃圾污染)⇒ 這支閘給總管的逃生口在雲端整個焊死,
# 而閘不會告訴他門是壞的(inkstone/ISEP#90 ④,全文見 hooks/lib/mtime.sh)。
# lib 不在時就地補一份同順序的定義——這道門不能因為少一個檔案就再關上一次。
. "$(dirname "$0")/lib/mtime.sh" 2>/dev/null || file_mtime() {
_fm=$(stat -c %Y "$1" 2>/dev/null || true)
case "${_fm:-}" in ''|*[!0-9]*) _fm=$(stat -f %m "$1" 2>/dev/null || true) ;; esac
case "${_fm:-}" in ''|*[!0-9]*) _fm=0 ;; esac
printf '%s' "$_fm"
}
STAMP="/tmp/.main-push-ok"
# 🔴 2026-08-11 這道閘被自己的戳記穿透了,修法寫在這裡:
@@ -99,7 +87,7 @@ STAMP="/tmp/.main-push-ok"
stamp_ok() {
[ -f "$STAMP" ] || return 1
NOW=$(date +%s 2>/dev/null || echo 0)
MT=$(file_mtime "$STAMP")
MT=$(stat -f %m "$STAMP" 2>/dev/null || stat -c %Y "$STAMP" 2>/dev/null || echo 0)
case "$NOW$MT" in *[!0-9]*) return 1 ;; esac
[ "$NOW" -gt 0 ] && [ "$MT" -gt 0 ] || return 1
[ $((NOW - MT)) -lt 900 ] || return 1
@@ -273,9 +261,7 @@ leo 原話:
逐筆看過那些 commit`git log --oneline gitea/main..<branch>`、`git diff --stat`),
確定它們該進 main,再:
bash "$CLAUDE_PLUGIN_ROOT/scripts/gate-ok" main-push <那個 repo 的路徑>
<你的 git push 指令>
(等價的手打法:git rev-parse --show-toplevel > /tmp/.main-push-ok
git rev-parse --show-toplevel > /tmp/.main-push-ok && <你的 git push 指令>
戳記 **綁這個 repo、只能用一次、15 分鐘失效**——它代表「**這一次、這個 repo,我看過了**」。
+3 -19
View File
@@ -68,23 +68,11 @@ CMD=$(printf '%s' "$CMD" | python3 "$(dirname "$0")/lib/strip_""heredoc.py" 2>/d
# **15 分鐘內一條並行的 subagent 把 commit 推上了另一個 repo 的 main**。
# ⇒ **多條 subagent 並行時,「時間窗」本身就是漏洞。** 所以改成單次用完即丟。
# ⇒ 而且只在**真的要擋的那一刻**才檢查——放在檔頭會被任何一條無關指令把戳記燒掉。
# 🔴 戳記的 mtime 一律走 lib/mtime.sh:舊寫法(`stat -f %m || stat -c %Y`)在 Linux 上
# **永遠算不出數字**(GNU 的 `-f` 是「檔案系統資訊」,它一邊回非零一邊吐一整段文字,
# 於是後面接上的秒數被那段垃圾污染)⇒ 這支閘給總管的逃生口在雲端整個焊死,
# 而閘不會告訴他門是壞的(inkstone/ISEP#90 ④,全文見 hooks/lib/mtime.sh)。
# lib 不在時就地補一份同順序的定義——這道門不能因為少一個檔案就再關上一次。
. "$(dirname "$0")/lib/mtime.sh" 2>/dev/null || file_mtime() {
_fm=$(stat -c %Y "$1" 2>/dev/null || true)
case "${_fm:-}" in ''|*[!0-9]*) _fm=$(stat -f %m "$1" 2>/dev/null || true) ;; esac
case "${_fm:-}" in ''|*[!0-9]*) _fm=0 ;; esac
printf '%s' "$_fm"
}
STAMP="/tmp/.prod-write-ok"
stamp_ok() {
[ -f "$STAMP" ] || return 1
NOW=$(date +%s 2>/dev/null || echo 0)
MT=$(file_mtime "$STAMP")
MT=$(stat -f %m "$STAMP" 2>/dev/null || stat -c %Y "$STAMP" 2>/dev/null || echo 0)
case "$NOW$MT" in *[!0-9]*) return 1 ;; esac
[ "$NOW" -gt 0 ] && [ "$MT" -gt 0 ] || return 1
[ $((NOW - MT)) -lt 900 ] || return 1
@@ -124,9 +112,7 @@ leo 原話:
━━━ 你是總管 ━━━
看清楚它會覆蓋什麼(`arcrun_get_workflow` 先撈一份現況存起來,好回滾),確定要推,再:
bash "$CLAUDE_PLUGIN_ROOT/scripts/gate-ok" prod-write # ⚠️ 只放行「下一個」動作,用完即消失
(等價的手打法:touch /tmp/.prod-write-ok。gate-ok 是所有閘共用的同一個入口,
好處是它的形狀固定 ⇒ 一條規則就能事先放行,不會每次被權限層擋在門外)
touch /tmp/.prod-write-ok # ⚠️ 只放行「下一個」動作,用完即消失
戳記 15 分鐘有效。**若這一推會讓封測者/用戶當場拿到東西,那就不是你的層級——要 leo 解保險。**
MSG
@@ -324,9 +310,7 @@ leo 原話:
━━━ 你是總管 ━━━
確認過要推什麼、會蓋掉什麼之後:
bash "$CLAUDE_PLUGIN_ROOT/scripts/gate-ok" prod-write # ⚠️ 只放行「下一個」動作,用完即消失
(等價的手打法:touch /tmp/.prod-write-ok。gate-ok 是所有閘共用的同一個入口,
好處是它的形狀固定 ⇒ 一條規則就能事先放行,不會每次被權限層擋在門外)
touch /tmp/.prod-write-ok # ⚠️ 只放行「下一個」動作,用完即消失
⚠️ `acr recipe push` 另有一道**互動式暴露同意閘**(終端機裡要人親手輸入資源名)。
那道閘擋的是「把資源變成可被外部呼叫」,**本閘的戳記蓋不過它**——那是 leo 的手。
-27
View File
@@ -144,33 +144,6 @@ if [ -f "$MISTAKES_FILE" ] && grep -q 'MISTAKE' "$MISTAKES_FILE" 2>/dev/null; th
echo ""
fi
# ── push 6:還債線今天撈過了沒(inkstone/ISEP#83)──────────────────────────
# 🔴 **這裡不打網路、不撈票**——只看狀態檔的日期,講一句話。
# 要真的撈是人(或這個 session)自己跑那一行;SessionStart 只負責讓它被想起來。
# 「每天都在追新的,所以要用 Routine 去消化舊的」(leo 2026-08-27)——
# 沒有這一句,沒掛 milestone 的那 170 多張永遠不會被任何人拿起來。
DEBT_STATE="${ISEP_DEBT_STATE_DIR:-$HOME/.claude/isep-debt}/claimed.json"
DEBT_LINE=$(python3 - "$DEBT_STATE" <<'PY' 2>/dev/null || true
import json, sys, datetime
try:
d = json.load(open(sys.argv[1]))
except Exception:
d = {}
last = (d.get("last_run") or "")[:10]
today = datetime.datetime.now(datetime.timezone.utc).strftime("%Y-%m-%d")
n = len(d.get("claims") or {})
if last == today:
print(f"✅ 今天撈過了(手上領著 {n} 張)")
else:
print("🔴 今天還沒撈過還債清單" + (f"(手上還領著 {n} 張沒關)" if n else ""))
PY
)
echo "────────────────────────────────────────────────"
echo "🧾 還債線(inkstone/ISEP#83):${DEBT_LINE:-🔴 今天還沒撈過還債清單}"
echo " 撈一次 python3 ${CLAUDE_PLUGIN_ROOT:-.}/scripts/debt-worklist list"
echo " 它排的是「沒掛 milestone 的舊票」——掛著的歸緊急線(milestone)管,兩條線不互搶。"
echo ""
echo "────────────────────────────────────────────────"
echo "以上是 index,不是內容——它只讓你知道「有這件事、去哪裡找」。"
echo "要完整脈絡(decisions / mistakes / SDD)→ 執行 /wiki-recall"
+2 -15
View File
@@ -159,18 +159,6 @@ fi
# ⇒ 改成兩者都認:內容有數字就用內容,沒有就用 mtime(`touch` 因此真的有效)。
#
# 另外認 leo 親手蓋的章(scripts/stage-ok.sh 產生),那是比我自評更強的訊號。
# 🔴 戳記的 mtime 一律走 lib/mtime.sh:舊寫法(`stat -f %m || stat -c %Y`)在 Linux 上
# **永遠算不出數字**(GNU 的 `-f` 是「檔案系統資訊」,它一邊回非零一邊吐一整段文字,
# 於是後面接上的秒數被那段垃圾污染)⇒ 這支閘給總管的逃生口在雲端整個焊死,
# 而閘不會告訴他門是壞的(inkstone/ISEP#90 ④,全文見 hooks/lib/mtime.sh)。
# lib 不在時就地補一份同順序的定義——這道門不能因為少一個檔案就再關上一次。
. "$(dirname "$0")/lib/mtime.sh" 2>/dev/null || file_mtime() {
_fm=$(stat -c %Y "$1" 2>/dev/null || true)
case "${_fm:-}" in ''|*[!0-9]*) _fm=$(stat -f %m "$1" 2>/dev/null || true) ;; esac
case "${_fm:-}" in ''|*[!0-9]*) _fm=0 ;; esac
printf '%s' "$_fm"
}
for STAMP in /tmp/.stage-ok-by-leo /tmp/.stage-verified; do
[ -f "$STAMP" ] || continue
now=$(date +%s)
@@ -184,7 +172,7 @@ for STAMP in /tmp/.stage-ok-by-leo /tmp/.stage-verified; do
# 抽數字會得到天文數字 ⇒ `now - t` 是**負數** ⇒ `< 21600` 成立 ⇒ **永遠放行**。
# ⇒ 只有「不晚於現在」的時間戳才算數;不合理就退回 mtime,別當成通過。
if [ "$t" -eq 0 ] || [ "$t" -gt "$now" ]; then
t=$(file_mtime "$STAMP")
t=$(stat -f %m "$STAMP" 2>/dev/null || stat -c %Y "$STAMP" 2>/dev/null || echo 0)
fi
[ "$t" -gt 0 ] && [ "$((now - t))" -lt 21600 ] && exit 0 # 6 小時內驗過 stage → 放行
done
@@ -208,8 +196,7 @@ cat >&2 <<'EOF'
⚠️ 身分:leo 2026-07-25 令「測試一律用 youlin,別拿 leo21c 當探針(會製造假信號)」
⇒ 部署前先 `acr whoami` 確認身分。
驗過了 ⇒ `bash "$CLAUDE_PLUGIN_ROOT/scripts/gate-ok" stage-verified` 後重送
(等價:`touch /tmp/.stage-verified`),並在回覆裡**貼 stage 的實測輸出**
驗過了 ⇒ `touch /tmp/.stage-verified` 後重送,並在回覆裡**貼 stage 的實測輸出**
(「我測過了」不算——貼指令與它吐出來的東西)。
EOF
exit 2
-88
View File
@@ -1,88 +0,0 @@
#!/usr/bin/env bash
# scripts/gate-ok +「戳記真的打得開門」的迴歸測試(inkstone/ISEP#90 ④)
#
# ══ 這支守的是什麼 ═════════════════════════════════════════════════════
# 三支閘(prod-writemain-and-prod-pushstage-before-prod)都是
# 「擋下來,但**總管看過就可以放行**」的設計。既有的測試只驗了「擋得住」,
# **一條都沒有驗過「放得開」**——於是 2026-08-28 才發現:
# `stat -f %m` 在 GNU coreutils 上是「檔案系統資訊」,它一邊回非零一邊吐一整段文字,
# 把接在後面的秒數污染掉 ⇒ **在 Linux(=每一個雲端 session)上,那三支閘的戳記
# 永遠不會被接受** ⇒ 它們在雲端等於純擋,而閘不會告訴你門是壞的。
#
# 所以這支的第一優先是「門打得開」,第二優先是「門沒有因此變寬」。
#
# 🔴 這支會真的寫 /tmp 的戳記檔(那是閘寫死的路徑,沒有覆寫的開關)。
# 每一條測完就把它刪掉;跑之前若有真的在等的戳記,會被這支洗掉——
# 請不要在「已經蓋好戳記正要推東西」的當下跑它。
set -u
ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" # hooks/
REPO="$(cd "$ROOT/.." && pwd)"
GATEOK="$REPO/scripts/gate-ok"
TMP=$(mktemp -d); trap 'rm -rf "$TMP"; rm -f /tmp/.prod-write-ok /tmp/.main-push-ok /tmp/.stage-verified /tmp/.solo-ok-TESTSID' EXIT
export GIT_CONFIG_GLOBAL="$TMP/gitconfig"; : > "$GIT_CONFIG_GLOBAL"
export GIT_AUTHOR_NAME=t GIT_AUTHOR_EMAIL=t@t GIT_COMMITTER_NAME=t GIT_COMMITTER_EMAIL=t@t
PASS=0; FAIL=0
ok(){ if [ "$2" = "$3" ]; then printf ' ✅ %s\n' "$1"; PASS=$((PASS+1));
else printf ' ❌ %s —— 期望 %s,實得 %s\n' "$1" "$3" "$2"; FAIL=$((FAIL+1)); fi; }
mkrepo(){ d="$TMP/$1"; git init -q -b main "$d"; ( cd "$d" && echo a>a && git add a && git commit -qm x ) >/dev/null 2>&1; printf '%s\n' "$d"; }
fire_prod(){ printf '{"tool_name":"Bash","tool_input":{"command":"acr push x.yaml"}}' \
| bash "$ROOT/prod-write-guard.sh" >/dev/null 2>&1; echo $?; }
fire_push(){ printf '{"tool_name":"Bash","tool_input":{"command":"git push origin main"}}' \
| ( cd "$1" && bash "$ROOT/main-and-prod-push-guard.sh" >/dev/null 2>&1; echo $? ); }
rm -f /tmp/.prod-write-ok /tmp/.main-push-ok /tmp/.stage-verified
echo "── 最重要:門打得開(Linux 上 stat -f %m 那個 bug 的迴歸)──────"
ok "① 沒戳記 → prod-write 擋" "$(fire_prod)" 2
bash "$GATEOK" prod-write >/dev/null
ok "② gate-ok prod-write 之後 → 放行" "$(fire_prod)" 0
ok "③ 單次用完即丟:同一枚不能放行第二次" "$(fire_prod)" 2
R1=$(mkrepo r1); R2=$(mkrepo r2)
ok "④ 沒戳記 → 推 main 擋" "$(fire_push "$R1")" 2
bash "$GATEOK" main-push "$R1" >/dev/null
ok "⑤ gate-ok main-push <repo> 之後 → 放行" "$(fire_push "$R1")" 0
echo "── 門沒有因此變寬 ────────────────────────────────────────────"
bash "$GATEOK" main-push "$R1" >/dev/null
ok "⑥ 替 r1 開的門,r2 走不過(綁 repo 沒鬆)" "$(fire_push "$R2")" 2
rm -f /tmp/.main-push-ok
# 過期的戳記不算數:把 mtime 調到 16 分鐘前
bash "$GATEOK" prod-write >/dev/null
touch -d '16 minutes ago' /tmp/.prod-write-ok 2>/dev/null || touch -A -001600 /tmp/.prod-write-ok 2>/dev/null
ok "⑦ 16 分鐘前的戳記 → 過期,照樣擋" "$(fire_prod)" 2
rm -f /tmp/.prod-write-ok
# 空內容的 main-push 戳記=萬用鑰匙,08-12 那次穿透的形狀,不准復活
: > /tmp/.main-push-ok
ok "⑧ 空內容的 main-push 戳記 → 不算數" "$(fire_push "$R1")" 2
rm -f /tmp/.main-push-ok
echo "── gate-ok 自己:不認得的就要拒絕,別蓋一枚打不開的戳記 ──────"
bash "$GATEOK" nonsense >/dev/null 2>&1; ok "⑨ 不認得的閘名 → 離開碼 2" "$?" 2
bash "$GATEOK" solo >/dev/null 2>&1; ok "⑩ solo 沒帶 session id → 離開碼 2" "$?" 2
bash "$GATEOK" main-push "$TMP" >/dev/null 2>&1; ok "⑪ 不是 git repo → 離開碼 2" "$?" 2
ok "⑫ 而且**沒有**留下一枚註定打不開的空戳記" "$([ -f /tmp/.main-push-ok ] && echo yes || echo no)" no
bash "$GATEOK" solo TESTSID >/dev/null 2>&1
ok "⑬ solo <sid> → 蓋出 /tmp/.solo-ok-<sid>" "$([ -f /tmp/.solo-ok-TESTSID ] && echo yes || echo no)" yes
bash "$GATEOK" stage-verified >/dev/null 2>&1
ok "⑭ stage-verified → 蓋出 /tmp/.stage-verified" "$([ -f /tmp/.stage-verified ] && echo yes || echo no)" yes
echo "── file_mtime 本身:兩個平台的寫法都要答得出純數字 ────────────"
. "$ROOT/lib/mtime.sh"
touch "$TMP/probe"
M=$(file_mtime "$TMP/probe")
case "$M" in ''|*[!0-9]*) R=bad ;; *) R=ok ;; esac
ok "⑮ file_mtime 回純數字(舊寫法在 Linux 上會回一整段文字)" "$R" ok
ok "⑯ 檔案不存在 → 回 0,不是空字串" "$(file_mtime "$TMP/nope")" 0
# 🔴 ⑰ 守的是這個 bug 的最後一層:舊寫法的行為**取決於 cwd 裡有沒有一個叫 `%m` 的檔**
# GNU 的 -f 是布林旗標,`%m` 被當成另一個檔名運算元)。有 ⇒ exit 0 ⇒ `||` 連跑都不跑。
# 一個行為取決於 cwd 有沒有某個檔的判斷式,不管跑不跑都是壞的。
M2=$( cd "$TMP" && touch '%m' && file_mtime "$TMP/probe" )
case "$M2" in ''|*[!0-9]*) R2=bad ;; *) R2=ok ;; esac
ok "⑰ cwd 裡有一個叫 %m 的檔 → 仍要回純數字" "$R2" ok
echo
printf '通過 %s 條,失敗 %s 條\n' "$PASS" "$FAIL"
[ "$FAIL" = 0 ] || exit 1
-117
View File
@@ -1,117 +0,0 @@
#!/usr/bin/env bash
# isep-presence-beacon.sh 的迴歸測試(inkstone/ISEP#90 ②③)
#
# 信標的價值全在鑑別力,所以這支要同時證明兩件相反的事:
# ① 該報的三件真的報得出來(版本落差/舊複本遮蔽正門/退役機制的殘骸)
# ② **不管加多少報告,那行綠色信標永遠在**——它消失=leo 會判定這個 session 零閘。
# 所以連 python 掛掉、網路不通、訊息裡有引號,都要還有一行合法 JSON。
#
# 🔴 全程離線(ISEP_BEACON_SKIP_NET=1,版本用 ISEP_FAKE_MAIN_VERSION 造),
# 造假的 plugin root 與 project dir 都在 TMP 底下,不碰真 repo。
set -u
HOOK="${1:-$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)/isep-presence-beacon.sh}"
REAL_HOOKS="$(cd "$(dirname "$HOOK")" && pwd)"
TMP=$(mktemp -d); trap 'rm -rf "$TMP"' EXIT
export ISEP_BEACON_SKIP_NET=1 ISEP_BEACON_CACHE_DIR="$TMP"
PASS=0; FAIL=0; N=0
# mkplugin <版本> → 造一份假的 plugin root(只放信標真的會讀的東西)
mkplugin() {
d="$TMP/plugin-$1"; mkdir -p "$d/.claude-plugin" "$d/hooks/lib" "$d/scripts"
printf '{"name":"isep","version":"%s"}\n' "$1" > "$d/.claude-plugin/plugin.json"
printf '{"hooks":{"Stop":[{"hooks":[{"command":"hooks/a.sh"},{"command":"hooks/b.sh"}]}]}}\n' \
> "$d/hooks/hooks.json"
cp "$HOOK" "$d/hooks/$(basename "$HOOK")"
cp "$REAL_HOOKS/lib/beacon_report.py" "$d/hooks/lib/beacon_report.py"
printf '#!/bin/sh\necho real\n' > "$d/scripts/ticket"
printf '%s\n' "$d"
}
# run <plugin root> <project dir> → 印出 systemMessageJSON 壞掉就印 __BADJSON__
run() {
CLAUDE_PLUGIN_ROOT="$1" CLAUDE_PROJECT_DIR="$2" bash "$1/hooks/$(basename "$HOOK")" 2>/dev/null \
| python3 -c 'import json,sys
try: print(json.load(sys.stdin)["systemMessage"])
except Exception: print("__BADJSON__")'
}
check() { # check <說明> <輸出> <該出現|!不該出現>...
desc="$1"; out="$2"; shift 2; N=$((N+1)); ok=1; why=""
for w in "$@"; do
case "$w" in
"!"*) if printf '%s' "$out" | grep -qF -- "${w#!}"; then ok=0; why="不該出現卻出現了:${w#!}"; fi ;;
*) if ! printf '%s' "$out" | grep -qF -- "$w"; then ok=0; why="少了:$w"; fi ;;
esac
done
if [ "$ok" = 1 ]; then printf ' ✅ %s\n' "$desc"; PASS=$((PASS+1))
else printf ' ❌ %s —— %s\n' "$desc" "$why"; printf '%s\n' "$out" | sed 's/^/ /'; FAIL=$((FAIL+1)); fi
}
echo "── 基本盤:那行綠色信標永遠在 ────────────────────────────────"
P=$(mkplugin 0.9.0); J="$TMP/proj-clean"; mkdir -p "$J"
out=$(run "$P" "$J")
check "① 乾淨環境:只有一行信標,版本與閘數都在" "$out" \
"🟢 ISEP v0.9.0 已載入" "2 支閘" "!🔴" "!🟡" "!__BADJSON__"
echo "── ①版本落差 ────────────────────────────────────────────────"
out=$(ISEP_FAKE_MAIN_VERSION=0.9.0 run "$P" "$J")
check "② 載入版=main 版 → 不吵" "$out" "🟢 ISEP v0.9.0" "!落後"
P39=$(mkplugin 0.3.9)
out=$(ISEP_FAKE_MAIN_VERSION=0.9.0 run "$P39" "$J")
check "③ 載入 0.3.9、main 0.9.0 → 要說它落後(雲端那個現場)" "$out" \
"🟢 ISEP v0.3.9 已載入" "落後 ISEP main" "0.9.0" "inkstone/ISEP#67"
out=$(ISEP_FAKE_MAIN_VERSION=0.1.0 run "$P" "$J")
check "④ 載入版比 main 新 → 說「沒發版」,不說「落後」" "$out" "比 ISEP main 新" "!落後 ISEP main"
echo "── ②舊複本遮蔽正門 ──────────────────────────────────────────"
J2="$TMP/proj-shadow"; mkdir -p "$J2/scripts"
printf '#!/bin/sh\necho OLD\n' > "$J2/scripts/ticket"
out=$(run "$P" "$J2")
check "⑤ 專案裡有內容不同的同名腳本 → 要點名(ticket 那件)" "$out" \
"舊複本" "scripts/ticket"
J3="$TMP/proj-same"; mkdir -p "$J3/scripts"; cp "$P/scripts/ticket" "$J3/scripts/ticket"
out=$(run "$P" "$J3")
check "⑥ 複本內容一模一樣(同步過的)→ 不吵" "$out" "!舊複本"
J4="$TMP/proj-body"; mkdir -p "$J4/InkStoneCo/scripts"
printf '#!/bin/sh\necho OLD\n' > "$J4/InkStoneCo/scripts/ticket"
out=$(run "$P" "$J4")
check "⑦ 雲端排法:複本在 \$TOP/InkStoneCo/ 底下也要抓到" "$out" \
"舊複本" "InkStoneCo/scripts/ticket"
echo "── ③退役機制的殘骸 ──────────────────────────────────────────"
J5="$TMP/proj-orphan"; mkdir -p "$J5/.claude/pending-verification" "$J5/.claude/hooks"
out=$(run "$P" "$J5")
check "⑧ plugin 的 hooks/scripts 完全沒提到的目錄 → 報殘骸" "$out" \
"已退役機制的產物" ".claude/pending-verification"
check "⑨ Claude Code 自己的目錄(hooks)不算殘骸" "$out" "!.claude/hooks"
# 現行機制的產物不該被報:讓 plugin 的某支 hook 提到它
mkdir -p "$J5/.claude/pending-main-push"
printf '#!/bin/sh\n# 寫到 pending-main-push/\n' > "$P/hooks/x.sh"
out=$(run "$P" "$J5")
check "⑩ hooks 裡有東西提到它 → 那是現行機制的產物,不報" "$out" "!pending-main-push"
# 🔴 這條守的是第一版真的犯過的 bug:內層迴圈的變數名跟外層的 `d` 撞,
# 第二個名字之後全部被靜靜跳過 ⇒ 真的存在的殘骸一聲不吭地消失。
mkdir -p "$J5/.claude/verified-claims"
out=$(run "$P" "$J5")
check "⑪ 同一個 .claude 底下有多個殘骸 → 每一個都要報(變數撞名的迴歸)" "$out" \
".claude/pending-verification" ".claude/verified-claims"
echo "── 最重要:加了報告也不准讓信標消失 ──────────────────────────"
# python 掛掉(把 report 換成一定會爆的內容)→ 仍要有一行合法 JSON 的信標
PB=$(mkplugin 0.9.0); printf 'raise SystemExit(3)\n' > "$PB/hooks/lib/beacon_report.py"
out=$(run "$PB" "$J")
check "⑫ 組訊息的 python 整支掛掉 → 退回乾淨的那一行,不是沉默" "$out" \
"🟢 ISEP v0.9.0 已載入" "!__BADJSON__"
rm -f "$PB/hooks/lib/beacon_report.py"
out=$(run "$PB" "$J")
check "⑬ 連 report 檔都不見 → 一樣要有信標" "$out" "🟢 ISEP v0.9.0 已載入" "!__BADJSON__"
# 訊息裡有引號/換行時 JSON 仍要合法(舊版是 printf 手拼的,這正是它會壞的地方)
J6="$TMP/proj-quote"; mkdir -p "$J6/scripts"
printf '#!/bin/sh\necho "OLD"\n' > "$J6/scripts/ticket"
out=$(run "$P" "$J6")
check "⑭ 報告內容含引號 → JSON 仍然合法" "$out" "🟢 ISEP" "!__BADJSON__"
echo
printf '通過 %s 條,失敗 %s 條(共 %s 條)\n' "$PASS" "$FAIL" "$N"
[ "$FAIL" = 0 ] || exit 1
-137
View File
@@ -1,137 +0,0 @@
#!/usr/bin/env bash
# unpushed-police.sh 的迴歸測試(inkstone/ISEP#90
#
# 這支存在的理由是一個**穩定重現**的誤報:雲端 session 開出來的工作分支
# 天生沒有 upstream,內容卻等於遠端 main ⇒ 每個雲端 session、每次收工都被攔一次。
# 2026-08-27 一個 session 攔五次,五次全是誤報。
#
# 兩個方向都要有證據,而且 **A 群(不該報)比 B 群更重要**:
# 永遠在響的警報=訓練人忽略這個警報,下一條真的失蹤的分支會混在雜訊裡。
#
# 🔴 全程離線:用本機 bare repo 當「遠端」,`git ls-remote` 打的是檔案路徑。
# 不碰任何真 repo、不打網路、不寫 /tmp 的正式快取(走 UNPUSHED_CACHE_DIR)。
set -u
HOOK="${1:-$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)/unpushed-police.sh}"
TMP=$(mktemp -d)
trap 'rm -rf "$TMP"' EXIT
export GIT_CONFIG_GLOBAL="$TMP/gitconfig"; : > "$GIT_CONFIG_GLOBAL"
export GIT_AUTHOR_NAME=t GIT_AUTHOR_EMAIL=t@t GIT_COMMITTER_NAME=t GIT_COMMITTER_EMAIL=t@t
PASS=0; FAIL=0; N=0
# mk <名字> → 造一個「遠端 bare + 本機 clone」的場,印出本機 repo 路徑
mk() {
d="$TMP/$1"; mkdir -p "$d"
git init -q --bare "$d/remote.git"
git init -q -b main "$d/work"
( cd "$d/work"
echo a > a.txt; git add a.txt; git commit -qm first
git remote add origin "$d/remote.git"
git push -q origin main
git branch --unset-upstream 2>/dev/null || true ) >/dev/null 2>&1
printf '%s\n' "$d/work"
}
# fire <repo> <期望 exit> <說明> [期望訊息片段]
fire() {
repo="$1"; want="$2"; desc="$3"; want_msg="${4:-}"
N=$((N+1))
out=$(printf '{}' | CLAUDE_PROJECT_DIR="$repo" UNPUSHED_CACHE_DIR="$TMP/cache-$N" \
bash "$HOOK" 2>&1); rc=$?
mkdir -p "$TMP/cache-$N" 2>/dev/null
ok=1
[ "$rc" -eq "$want" ] || ok=0
if [ -n "$want_msg" ] && ! printf '%s' "$out" | grep -qF "$want_msg"; then ok=0; fi
if [ "$ok" = 1 ]; then
printf ' ✅ %s\n' "$desc"; PASS=$((PASS+1))
else
printf ' ❌ %s —— 期望 exit=%s%s,實得 exit=%s\n' "$desc" "$want" \
"${want_msg:+ 且訊息含「$want_msg}" "$rc"
printf '%s\n' "$out" | sed -n '1,14p' | sed 's/^/ /'
FAIL=$((FAIL+1))
fi
}
# 每個案例先把快取目錄準備好(fire 用的是自己那一格,互不污染)
for i in $(seq 1 40); do mkdir -p "$TMP/cache-$i"; done
echo "── A 群:不該報(誤攔比漏擋更該修)──────────────────────────"
# ① 這就是雲端那個現場:分支沒有 upstream,但它那顆 commit 就是遠端 main 那顆
r=$(mk cloud)
( cd "$r" && git checkout -q -b claude/session-xyz && git branch -D main -q 2>/dev/null
git remote set-head origin -d 2>/dev/null; git update-ref -d refs/remotes/origin/main ) >/dev/null 2>&1
fire "$r" 0 "① 沒 upstream,但遠端就有這顆 commit(雲端每個 session 的現場)"
# ② HEAD 是遠端 main 的**祖先**(遠端已經走在前面)——同樣不是「沒推」
r=$(mk ancestor)
( cd "$r"
echo b > b.txt && git add b.txt && git commit -qm second && git push -q origin main
git checkout -q -b work HEAD~1
git update-ref -d refs/remotes/origin/main ) >/dev/null 2>&1
fire "$r" 0 "② HEAD 是遠端 main 的祖先 → 遠端已經有它"
# ③ 本機的 remote-tracking ref **過期**08-28 實測落後遠端 4 天的那一格)
r=$(mk stale)
( cd "$r"
old=$(git rev-parse HEAD)
echo b > b.txt && git add b.txt && git commit -qm second && git push -q origin main
git update-ref refs/remotes/origin/main "$old" # 本機那份停在舊的
git checkout -q -b claude/session-abc ) >/dev/null 2>&1
fire "$r" 0 "③ 本機 origin/main 過期,但遠端真的有這顆 → 不報"
# ④ 完全問不到遠端(沒有任何 remote)→ **不當成沒推**
r="$TMP/noremote"; git init -q -b main "$r"
( cd "$r" && echo a > a.txt && git add a.txt && git commit -qm only ) >/dev/null 2>&1
fire "$r" 0 "④ 沒有任何 remote=問不到 → 不報(不拿離線當罪證)"
# ⑤ 基準過期時,已經在遠端 main 上的分支不算散落
r=$(mk straystale)
( cd "$r"
old=$(git rev-parse HEAD)
git checkout -q -b feat/done
echo b > b.txt && git add b.txt && git commit -qm done
git push -q origin feat/done:main # 遠端 main 已經含它
git update-ref refs/remotes/origin/main "$old" ) >/dev/null 2>&1
fire "$r" 0 "⑤ 分支已在遠端 main 上,只是本機基準舊 → 不算散落"
# ⑥ stop_hook_active → 一律放行
r=$(mk stopactive)
( cd "$r" && echo x >> a.txt ) >/dev/null 2>&1
N=$((N+1))
out=$(printf '{"stop_hook_active":true}' | CLAUDE_PROJECT_DIR="$r" \
UNPUSHED_CACHE_DIR="$TMP/cache-$N" bash "$HOOK" 2>&1); rc=$?
if [ "$rc" -eq 0 ]; then printf ' ✅ %s\n' "⑥ stop_hook_activetrue → 放行"; PASS=$((PASS+1))
else printf ' ❌ %sexit=%s\n' "⑥ stop_hook_activetrue → 放行" "$rc"; FAIL=$((FAIL+1)); fi
echo "── B 群:該報(不能為了不吵就變成放行)────────────────────"
# ⑦ 真的有遠端沒有的 commit = 真的沒推
r=$(mk unpushed)
( cd "$r"
git checkout -q -b feat/real
echo b > b.txt && git add b.txt && git commit -qm "沒推的那筆" ) >/dev/null 2>&1
fire "$r" 2 "⑦ 分支有遠端沒有的 commit → 要報" "從未推過"
# ⑧ 有改動沒 commit
r=$(mk dirty)
( cd "$r" && echo more >> a.txt ) >/dev/null 2>&1
fire "$r" 2 "⑧ 工作區有未 commit 的改動 → 要報" "未 commit"
# ⑨ 散落分支:本地分支有遠端 main 沒有的東西
r=$(mk stray)
( cd "$r"
git checkout -q -b feat/lost
echo c > c.txt && git add c.txt && git commit -qm "躺著的那筆"
git checkout -q main ) >/dev/null 2>&1
fire "$r" 2 "⑨ 有分支沒併回、遠端也沒有 → 要報散落" "feat/lost"
# ⑩ 判準沒有滑回「有沒有 upstream」:有 upstream 但真的領先,照樣要報
r=$(mk ahead)
( cd "$r"
git branch --set-upstream-to=origin/main main
echo b > b.txt && git add b.txt && git commit -qm "領先一筆" ) >/dev/null 2>&1
fire "$r" 2 "⑩ 有 upstream 且真的領先 → 照樣要報" "領先"
echo
printf '通過 %s 條,失敗 %s 條(共 %s 條)\n' "$PASS" "$FAIL" "$N"
[ "$FAIL" = 0 ] || exit 1
+7 -152
View File
@@ -35,119 +35,10 @@ except Exception: print(False)
' 2>/dev/null)"
[ "$stop_active" = "True" ] && exit 0
# ══════════════════════════════════════════════════════════════════════
# 「遠端到底有沒有這顆 commit」——本檔唯一的判準(inkstone/ISEP#902026-08-28
# ══════════════════════════════════════════════════════════════════════
#
# 🔴 舊判準是「這條分支有沒有 upstream」,而**雲端 session 開出來的工作分支
# 天生就沒有 upstream**,內容卻等於遠端 main
#
# 薄殼 HEAD = 081c547d90dc2d80692485af083ca1f71f2094f2
# GitHub 遠端 main = 081c547d90dc2d80692485af083ca1f71f2094f2 ← 同一顆
#
# ⇒ 每個雲端 session、每次收工都被攔一次。2026-08-27 一個 session 攔五次,
# **五次全是誤報**。而永遠在響的警報=訓練人忽略這個警報
# (本檔第 ③ 段自己在 08-12 就寫過這句,這次是同一個病長在別的判準上)。
#
# 🔴 也不能改成「本機的 remote-tracking ref 有沒有含它」的變體:
# 那份 ref 會過期——08-28 實測本 session 的 `origin/main` 落後遠端整整 4 天。
# 本機只答得準「有」,答不準「沒有」⇒ 答「沒有」的時候要去問遠端。
#
# 三態,不是兩態:0=遠端有 1=遠端沒有 2=問不到(沒 remote/網路不通/沒權限)。
# **2 一律不報。** 誤攔比漏擋更該修(leo 2026-08-17:文字層那些閘 8 次誤攔、
# 0 次正確攔截)——把「離線」當成「你沒推」,就是拿雜訊懲罰謹慎。
# 🔴 戳記的 mtime 一律走 lib/mtime.sh:舊寫法(`stat -f %m || stat -c %Y`)在 Linux 上
# **永遠算不出數字**(GNU 的 `-f` 是「檔案系統資訊」,它一邊回非零一邊吐一整段文字,
# 於是後面接上的秒數被那段垃圾污染)⇒ 這支閘給總管的逃生口在雲端整個焊死,
# 而閘不會告訴他門是壞的(inkstone/ISEP#90 ④,全文見 hooks/lib/mtime.sh)。
# lib 不在時就地補一份同順序的定義——這道門不能因為少一個檔案就再關上一次。
. "$(dirname "$0")/lib/mtime.sh" 2>/dev/null || file_mtime() {
_fm=$(stat -c %Y "$1" 2>/dev/null || true)
case "${_fm:-}" in ''|*[!0-9]*) _fm=$(stat -f %m "$1" 2>/dev/null || true) ;; esac
case "${_fm:-}" in ''|*[!0-9]*) _fm=0 ;; esac
printf '%s' "$_fm"
}
GIT_ASK="env GIT_TERMINAL_PROMPT=0 GIT_ASKPASS=/bin/echo GIT_SSH_COMMAND=ssh\ -oBatchMode=yes"
_TO=""
command -v timeout >/dev/null 2>&1 && _TO="timeout 15"
command -v gtimeout >/dev/null 2>&1 && _TO="gtimeout 15"
# ls_remote_heads <repo> <remote> → 印出「<sha> <ref>」數行;問不到就印空、離開碼 1
# 快取 120 秒:Stop hook 每個回合都跑,同一個遠端不必每回合都打一次網路。
ls_remote_heads() {
_lr_repo="$1"; _lr_rm="$2"
_lr_key="$(printf '%s|%s' "$_lr_repo" "$_lr_rm" | cksum | tr -d ' /')"
# 快取位置可被 UNPUSHED_CACHE_DIR 覆寫——測試要能造「同一個 repo、遠端變了」的場,
# 不能被上一個案例的快取餵到舊答案(那會是假綠)。
_lr_cache="${UNPUSHED_CACHE_DIR:-/tmp}/.unpushed-lsremote-$_lr_key"
if [ -f "$_lr_cache" ]; then
_lr_now=$(date +%s 2>/dev/null || echo 0)
_lr_mt=$(file_mtime "$_lr_cache")
case "$_lr_now$_lr_mt" in *[!0-9]*) _lr_mt=0 ;; esac
if [ "$_lr_mt" -gt 0 ] && [ $((_lr_now - _lr_mt)) -lt 120 ]; then
[ -s "$_lr_cache" ] || return 1
cat "$_lr_cache"; return 0
fi
fi
if _lr_out="$($_TO $GIT_ASK git -C "$_lr_repo" ls-remote --heads "$_lr_rm" 2>/dev/null)" \
&& [ -n "$_lr_out" ]; then
printf '%s\n' "$_lr_out" > "$_lr_cache" 2>/dev/null || true
printf '%s\n' "$_lr_out"
return 0
fi
: > "$_lr_cache" 2>/dev/null || true # 記「這次問不到」,免得每回合都等一次 timeout
return 1
}
# remote_has_commit <repo> <sha> → 0 遠端有/1 遠端沒有/2 問不到
remote_has_commit() {
_rh_repo="$1"; _rh_sha="$2"
[ -n "$_rh_sha" ] || return 2
# ① 本機就答得出「有」:任何 remote-tracking ref 含這顆 ⇒ 一定推過,不必打網路
if [ -n "$(git -C "$_rh_repo" branch -r --contains "$_rh_sha" 2>/dev/null | head -1)" ]; then
return 0
fi
_rh_asked=0
for _rh_rm in $(git -C "$_rh_repo" remote 2>/dev/null); do
_rh_ls="$(ls_remote_heads "$_rh_repo" "$_rh_rm")" || continue
_rh_asked=1
# 遠端某條 head 就是這顆 ⇒ 推過(雲端那個誤報正是落在這一格)
printf '%s\n' "$_rh_ls" | awk '{print $1}' | grep -qx "$_rh_sha" && return 0
# 遠端那顆本機也有時,才問得出祖先關係(本機沒有就只能靠上面的等值比對)
printf '%s\n' "$_rh_ls" | while read -r _rh_rsha _; do
[ -n "$_rh_rsha" ] || continue
git -C "$_rh_repo" cat-file -e "${_rh_rsha}^{commit}" 2>/dev/null || continue
git -C "$_rh_repo" merge-base --is-ancestor "$_rh_sha" "$_rh_rsha" 2>/dev/null && exit 7
done
[ $? = 7 ] && return 0
done
[ "$_rh_asked" = 1 ] && return 1
return 2
}
# remote_sha_of <repo> <遠端名> <分支名> → 印出遠端那顆 sha(拿不到印空)
remote_sha_of() {
ls_remote_heads "$1" "$2" 2>/dev/null \
| awk -v b="refs/heads/$3" '$2 == b { print $1; exit }'
}
TOP="${CLAUDE_PROJECT_DIR:-$(cd "$(dirname "$0")/../.." && pwd)}"
# 掃描對象:頂層 + 各子 repo(存在才掃)。worktree 一併涵蓋(git -C 會自己解)。
#
# 🔴 2026-08-28inkstone/ISEP#90)補雲端那一格:雲端的 `$CLAUDE_PROJECT_DIR`
# 是**薄殼根**,真身被 bootstrap.sh clone 到 `$TOP/InkStoneCo/`,子 repo 在
# `$TOP/InkStoneCo/matrix/arcrun` …。舊清單只認地端那種「頂層就是真身」的排法
# ⇒ **雲端上真身有東西沒推,本閘一輩子不會知道**(它掃的四個路徑一個都不存在)。
# ⇒ 這跟 ① 的誤攔是同一個病的兩面:在雲端,這支閘既亂叫、又看不到該看的地方。
REPOS=""
for _body in "$TOP" "$TOP/InkStoneCo"; do
[ -d "$_body/.git" ] || [ -f "$_body/.git" ] || continue
REPOS="$REPOS $_body $_body/matrix/arcrun $_body/products/arcrun-rag $_body/polaris/mira"
done
[ -n "$REPOS" ] || REPOS="$TOP"
REPOS="$TOP $TOP/matrix/arcrun $TOP/products/arcrun-rag $TOP/polaris/mira"
problems=""
for r in $REPOS; do
@@ -159,33 +50,17 @@ for r in $REPOS; do
staged="$(git -C "$r" diff --cached --shortstat 2>/dev/null | head -1)"
# ② 已 commit 但沒推(**當前分支**
#
unknown=""
# 🔴 判準是「遠端有沒有這顆 commit」,不是「有沒有 upstream」(ISEP#90,見檔頭那段)。
# 有 upstream 時仍照原本的算法報「領先幾筆」——那個數字有用;
# 沒 upstream 時去問遠端,問不到就**不報**。
unpushed=""
br="$(git -C "$r" branch --show-current 2>/dev/null)"
if [ -n "$br" ]; then
head_sha="$(git -C "$r" rev-parse HEAD 2>/dev/null || true)"
up="$(git -C "$r" rev-parse --abbrev-ref "@{upstream}" 2>/dev/null || true)"
if [ -n "$up" ]; then
n="$(git -C "$r" rev-list --count "$up".."$br" 2>/dev/null || echo 0)"
if [ "$n" != "0" ]; then
# upstream 本身可能過期(本機那份 ref 落後遠端 4 天是實測過的)
# ⇒ 先問遠端;遠端已經有這顆就不是「沒推」。
remote_has_commit "$r" "$head_sha"
[ "$?" = 0 ] || unpushed="領先 $up $n"
fi
[ "$n" != "0" ] && unpushed="領先 $up $n"
else
remote_has_commit "$r" "$head_sha"
case "$?" in
1) unpushed="分支 $br **從未推過**(遠端沒有 $(printf '%.7s' "$head_sha")" ;;
# 0=遠端有這顆(雲端 session 的工作分支就是這種)→ 不報
# 2=問不到遠端 → 不報,但這件事本身值得知道,收在下面當脈絡
2) [ -n "$(git -C "$r" rev-list --count HEAD 2>/dev/null)" ] \
&& unknown="分支 $br 問不到遠端(沒有 remote/網路不通)——**不當成沒推**" ;;
esac
# 沒 upstream=這條分支從來沒推過(今天 fix/cis-round3-install 就是這樣)
has_commits="$(git -C "$r" rev-list --count HEAD 2>/dev/null || echo 0)"
[ "$has_commits" != "0" ] && unpushed="分支 $br **從未推過**(無 upstream"
fi
fi
@@ -204,27 +79,9 @@ for r in $REPOS; do
# **這正是同一晚重複八次的那個病:檢查跑了,但檢查的對象是錯的。**
# ⇒ 基準改成「整合分支」:gitea/main > origin/main > main > 當前分支。
base="$br"
base_label=""
for cand in gitea/main origin/main main; do
if git -C "$r" rev-parse --verify -q "$cand" >/dev/null 2>&1; then base="$cand"; break; fi
done
base_label="$base"
# 🔴 2026-08-28inkstone/ISEP#90):**基準的 ref 也會過期。**
# 08-28 實測:本機 `origin/main` 落後遠端整整 4 天 ⇒ 拿它當基準,
# 「已經在遠端 main 上」的分支會被整批報成散落——包括**雲端 session 自己
# 那條工作分支**(它的內容就等於遠端 main)。
# 08-15 那次訂正的是「基準挑錯了分支」,這次是「基準挑對了但那份是舊的」:
# 同一個病的第三面——檢查跑了,但檢查的對象是舊的。
# ⇒ 問一次遠端;拿得到、而且本機真的有那顆 commit(不然算不了祖先),才換過去。
case "$base_label" in
*/*) _base_rm="${base_label%%/*}"; _base_br="${base_label#*/}" ;;
*) _base_rm="origin"; _base_br="$base_label" ;;
esac
_base_fresh="$(remote_sha_of "$r" "$_base_rm" "$_base_br")"
if [ -n "$_base_fresh" ] && git -C "$r" cat-file -e "${_base_fresh}^{commit}" 2>/dev/null; then
base="$_base_fresh"
base_label="$_base_rm/$_base_br(遠端實際那顆 $(printf '%.7s' "$_base_fresh")"
fi
if [ -n "$base" ]; then
for b in $(git -C "$r" for-each-ref --format='%(refname:short)' refs/heads/ 2>/dev/null); do
[ "$b" = "$base" ] && continue
@@ -254,7 +111,7 @@ for r in $REPOS; do
age="$(git -C "$r" log -1 --format='%ad' --date=format:'%m-%d' "$b" 2>/dev/null)"
# 用真實換行累積,不用 \n 逃脫——否則後面的 printf '%b' 會把分支名再解讀一次
stray="$stray
- $b$cnt 筆未併入 $base_label(最後動 $age"
- $b$cnt 筆未併入 $base(最後動 $age"
done
fi
@@ -266,12 +123,10 @@ for r in $REPOS; do
[ -n "$unpushed" ] && line="$line
· $unpushed"
[ -n "$stray" ] && line="$line
· 🔀 **散落分支**(有 commit 沒併回 $base_label):$stray"
· 🔀 **散落分支**(有 commit 沒併回 $br):$stray"
# 刻意保留的分支**不會自己觸發警報**(那正是加它的目的),
# 但這個 repo 若本來就有別的問題要報,就順便把它列出來當脈絡——
# 免得「保留」變成另一種看不見。
[ -n "$line" ] && [ -n "$unknown" ] && line="$line
· ❔ $unknown"
[ -n "$line" ] && [ -n "$held" ] && line="$line
· ⏸️ 刻意保留(不觸發警報,理由在 .claude/branch-holds.md):$held"
[ -n "$line" ] && problems="$problems
-20
View File
@@ -101,26 +101,6 @@ labels:
exclusive: true
description: "雜務、整理、不改行為"
# ── 使用者旅程(正交,`j/` scope)──────────────────
#
# inkstone/ISEP#92:「這件事服務哪個使用者旅程,沒有記錄⋯⋯後面要把相關的票
# 聚成一包時,只能靠人重新讀一遍每張票在講什麼。」
#
# `ticket subtask/handoff --journey <名>` 會把 `j/<名>` **同時貼在母子兩端**
# (只貼一端就聚不起來)。標籤不存在時它會擋下來並指回本檔——
# **「要求標籤在場」,不是「猜哪些名字合法」**。
#
# 🔴 這裡刻意是空的。旅程怎麼切、叫什麼名字,是方向題(四題公式第 4 題),
# 不該由工具或 subagent 代決;隨手造名字會讓同一條旅程長出三個拼法。
# 要新增一條就照這個形狀加一筆,然後跑 scripts/gitea-labels-sync.sh
#
# - name: "j/收件匣"
# color: "fbca04"
# exclusive: false
# description: "🧭 旅程:<一句話講這條旅程的頭和尾>"
#
# (票上明講「對不上就不貼,不硬湊」——沒有對應旅程的票就不要加 --journey。)
# ── 結構(正交)──────────────────────────────────
- name: "hub"
color: "0052cc"
-559
View File
@@ -1,559 +0,0 @@
#!/usr/bin/env python3
"""debt-worklist — 還債線:每天固定撈一次「今天可以領什麼」,整包整包地領。
leo 2026-08-27inkstone/ISEP#83 的來由,他當場訂正總管的誤解):
「這是兩件不同的事,你根本沒搞清楚,距離是在確定有個緊急事件要儘速達成時,
現在每天都在追新的,所以**要用 Routine 去消化舊的**,可以有多個條件」
⇒ **兩條線,各用各的判準**,不是二選一:
緊急線 有事要趕 → 用「距離目標的遠近」排(=掛在 open milestone 上的那些)
還債線 每天消化舊的 → 用多條件排(事故/擋人/承諾/票齡/估工) ← 本工具
病根:全 org 229 張 open 票,每天在動的只有掛在 active milestone 上的那些。
沒掛的不是不重要,是**沒有任何機制會去拿它們**。`worklist-guard.sh` 擋的是
「這一輪已經領到的工作沒做完就收工」——它不會去把舊票撈出來。本工具補的是供給面。
三個動詞:
debt-worklist list 撈一次,排好序印出來(預設動作)
debt-worklist claim <票...> 領走(今天領的,明天就不會再出現在清單上)
debt-worklist forget <票...> 放回去(領錯了、或那條線改方向了)
票的寫法:`owner/repo#N`,例:`inkstone/InkStoneCo#44`
🔴 **不是輪詢。** 這支腳本自己不會醒——是人跑它、或 SessionStart 那一次順手跑。
不准掛 Gitea Actionswebhook fan-outCLAUDE.md 避免再被 flag 的硬規則,
`issue-handle` 明寫「有事才讀」,換成 Gitea 也不放寬)。
離線可測:設 `ISEP_DEBT_FIXTURE=<json 檔>` 就完全不打網路(測試用)。
狀態檔位置可用 `ISEP_DEBT_STATE_DIR` 改(測試用,預設 `~/.claude/isep-debt/`)。
"""
import json
import os
import re
import subprocess
import sys
import urllib.error
import urllib.parse
import urllib.request
from datetime import datetime, timezone
HOST = os.environ.get("TICKET_HOST") or "https://git.uncle6.me"
ORG = os.environ.get("ISEP_DEBT_ORG") or "inkstone"
# ── 「現在的主線是哪一個」只有一份答案(inkstone/ISEP#82 → hooks/lib/mainline.py)──
# 本工具排除的是**緊急線正在管的那些**。在 #82 之前,「哪個是 active」沒有指涉對象
# 14 個 open milestone 同時亮著),所以第一版只能粗暴地「掛 open milestone 就排除」。
# 現在有唯一答案了 ⇒ 接上去,**不要自己養第二套判斷**(兩份必然漂移)。
sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "hooks", "lib"))
try:
import mainline as ML
except Exception: # 拿不到共用零件就退回舊行為(fail-open),不讓還債線整個癱掉
ML = None
# 等 leo 的票不進「可領清單」——不是它們不重要,是**沒有人能替他領**:
# Humanhuman/exec 要他親手批示或動手
# s/stage 已經部到 stage,等他驗(session-start-recall 就是這樣定義的)
# 這些的正確動作是「催」不是「領」,而催辦是 inkstone/ISEP#93 的事。本票是供給面。
WAITING_LEO_LABELS = {"Human", "human/exec", "s/stage"}
# 已經有人在做/已經有 PR 的狀態:這是「答應過人家的」,債比沒開工的還硬。
STARTED_LABELS = {"s/doing", "s/review"}
def die(msg, code=2):
print(msg, file=sys.stderr)
sys.exit(code)
# ── 連線(跟 scripts/ticket 同一套:先找帶憑證的 remote,再退環境變數)────────
def token():
root = os.environ.get("CLAUDE_PROJECT_DIR") or os.getcwd()
host = HOST.split("//")[-1].rstrip("/")
try:
out = subprocess.run(["git", "-C", root, "remote", "-v"],
capture_output=True, text=True, timeout=20).stdout
except Exception:
out = ""
for line in out.splitlines():
if host in line:
m = re.search(r"//[^:/]+:([^@]+)@", line)
if m:
return m.group(1)
for env in ("GITEA_TOKEN_CLAUDE_CODE", "GITEA_TOKEN"):
if os.environ.get(env):
return os.environ[env]
die(f"""🔴 拿不到 {host} 的 token
擇一:
• 讓某個 remote 帶憑證(多數 repo 的 gitea/origin 本來就有)
• 或設環境變數 GITEA_TOKEN_CLAUDE_CODE""")
def api(path):
url = f"{HOST}/api/v1{path}"
req = urllib.request.Request(url, headers={"Authorization": f"token {token()}"})
try:
return json.load(urllib.request.urlopen(req, timeout=60))
except urllib.error.HTTPError as e:
die(f"🔴 Gitea {e.code}{e.read().decode()[:300]}\n path={path}")
except Exception as e:
die(f"🔴 打不到 {HOST}{e}\n path={path}")
# ── 收集:全 org 每個 repo 的 open issue open PR ──────────────────────────
def collect():
"""回 (repos, items)。repos 是「我查了哪些」的證明,items 是原始票。
fixture 模式(測試用):完全不打網路,資料從 json 檔讀。
"""
fx = os.environ.get("ISEP_DEBT_FIXTURE")
if fx:
with open(fx) as f:
data = json.load(f)
return data["repos"], data["items"]
repos, items = [], []
for r in api(f"/orgs/{ORG}/repos?limit=100") or []:
full = r["full_name"]
if not r.get("has_issues", True):
repos.append({"name": full, "issues": 0, "prs": 0, "skipped": "issues 關閉"})
continue
got, page = [], 1
while True:
q = urllib.parse.urlencode({"state": "open", "limit": 50, "page": page})
batch = api(f"/repos/{full}/issues?{q}") or []
got.extend(batch)
if len(batch) < 50:
break
page += 1
if page > 20: # 保險絲:不可能有一千張,有的話是我寫錯了
break
for it in got:
it.setdefault("repository", {"full_name": full})
n_pr = sum(1 for it in got if it.get("pull_request"))
repos.append({"name": full, "issues": len(got) - n_pr, "prs": n_pr})
items.extend(got)
return repos, items
# ── 工具 ───────────────────────────────────────────────────────────────────
def ref_of(it):
return f"{it['repository']['full_name']}#{it['number']}"
def labels_of(it):
return {l["name"] for l in (it.get("labels") or [])}
def is_pr(it):
return bool(it.get("pull_request"))
def parse_ts(s):
if not s:
return None
try:
return datetime.fromisoformat(s.replace("Z", "+00:00"))
except Exception:
return None
def now():
"""時鐘可以被定住——測試要能重現,不能今天跑綠明天跑紅。"""
inj = os.environ.get("ISEP_DEBT_NOW")
if inj:
d = parse_ts(inj)
if d:
return d
return datetime.now(timezone.utc)
def days_since(s):
d = parse_ts(s)
if not d:
return 0.0
return max(0.0, (now() - d).total_seconds() / 86400)
REF_RE = re.compile(r"(?:([\w.-]+)/([\w.-]+))?#(\d+)")
def refs_in(it):
"""從標題+內文抓出它指到的別張票。裸 `#12` 算同 repo。
只認得出「文字上指了誰」——這是零成本的訊號(內文本來就在清單裡)。
Gitea 原生的 dependencies 要一張票打一次 API229 張=229 次,不值得。
"""
owner, repo = it["repository"]["full_name"].split("/")
out = set()
text = f"{it.get('title') or ''}\n{it.get('body') or ''}"
for o, r, n in REF_RE.findall(text):
out.add(f"{o or owner}/{r or repo}#{n}")
out.discard(ref_of(it))
return out
# ── 排序:多個條件,每一條都看得見自己貢獻了幾分 ─────────────────────────────
#
# leo 給的順序(票上原文):出事的 → 擋住別人的 → 答應過人家的 → 放最久的 → 最快做完的。
# 分數只是把這個順序寫成可重現的東西;**每一項都會印在票旁邊**,
# 排出來覺得不對可以直接指著說「這一項給太多」,而不是猜它為什麼在第一名。
def score(it, in_degree):
lab = labels_of(it)
parts = []
if "type/bug" in lab:
parts.append(("事故", 40))
if "p/high" in lab:
parts.append(("高優先", 20))
if "p/low" in lab:
parts.append(("低優先", -12))
blocked = in_degree.get(ref_of(it), 0)
if blocked:
parts.append((f"擋住{blocked}張", min(12 * blocked, 36)))
if is_pr(it):
# 躺著沒結論的 PR 擋的是 merge 那條路(inkstone/ISEP#81 是它的另一半)
parts.append(("PR躺著", 25))
started = lab & STARTED_LABELS
if started:
parts.append((f"已開工({'/'.join(sorted(started))})", 18))
if it.get("assignees") or it.get("assignee"):
parts.append(("有人接了", 12))
ms = it.get("milestone") or {}
if ms and (ms.get("state") or "open") == "open" and ML is not None:
due = ML.due_of(ms)
if due and due < now():
# 掛在**別條**(非主線)而且期限已經過去的 milestone ⇒ 這是承諾過的日期,
# 而那個日期已經過了。它之所以還在這份清單上,正是因為沒有人在管那條線。
parts.append((f"逾期{int((now() - due).total_seconds() // 86400)}天的承諾", 15))
age = days_since(it.get("updated_at"))
if age >= 1:
parts.append((f"擱置{int(age)}天", round(min(age * 0.6, 30), 1)))
body_len = len(it.get("body") or "")
if "type/chore" in lab or body_len < 800:
parts.append(("看起來小", 10))
total = round(sum(p[1] for p in parts), 1)
return total, parts
def pick(items, claimed):
"""把原始票分成三堆:可領的/緊急線的/要 leo 動手的。並回統計。"""
open_refs = {ref_of(it) for it in items}
in_degree = {}
for it in items:
for target in refs_in(it):
if target in open_refs:
in_degree[target] = in_degree.get(target, 0) + 1
ml = ML.load() if ML is not None else None
pool, stats = [], {"milestone": 0, "human": 0, "claimed": 0, "total": len(items),
"other_ms": 0, "mainline": ml}
for it in items:
ref = ref_of(it)
ms = it.get("milestone")
if ms and (ms.get("state") or "open") == "open":
if ml is None:
# 現在沒有主線 ⇒ 分不出哪一條是緊急線在管的。退回保守做法:
# 掛 open milestone 的一律不領(寧可少領,不要跟緊急線搶同一張)。
stats["milestone"] += 1
continue
if ML.belongs(ref, ml, ms.get("title")):
stats["milestone"] += 1 # 這張真的在主線上 ⇒ 緊急線在管,不重複領
continue
# 掛在**別條** milestone 上:那條線現在沒有人在推 ⇒ 它就是債
stats["other_ms"] += 1
if labels_of(it) & WAITING_LEO_LABELS:
stats["human"] += 1 # 沒有人能替 leo 領(催辦是 ISEP#93
continue
if ref in claimed:
stats["claimed"] += 1 # 昨天領走的,今天不再出現
continue
s, parts = score(it, in_degree)
pool.append({"ref": ref, "title": it.get("title") or "", "score": s,
"why": parts, "labels": sorted(labels_of(it)),
"pr": is_pr(it), "url": it.get("html_url"),
"age": round(days_since(it.get("updated_at")), 1),
"refs": sorted(refs_in(it) & open_refs)})
pool.sort(key=lambda d: (-d["score"], d["ref"]))
return pool, stats, in_degree
# ── 成包:互相指著的必然同包(票上原文「相關的票要成包一起領,不要拆散」)──────
#
# 🔴 **只認強訊號,寧可少成包**。第一版用「單向文字引用」成包,結果是
# **前 190 張裡有 121 張黏成一包**——因為大家都會順手引用 hub 票。
# 一包 121 張=沒有人領得動=跟沒分包一樣。所以只認這兩種:
# ① 互相指著(A 的內文提 B,且 B 的內文提 A)——單向不算
# ② Gitea 原生相依(`ticket subtask` 建的母子票就是這個)
# 代價:同一條使用者旅程但沒有互指、也沒建相依的兩張票不會成包。
# 這是誠實的取捨——**寧可漏成包,不要成一包沒人領得動的**。
BUNDLE_CAP = 8 # 一包最多印幾張;超過就說「還有幾張」
DEPS_TOP_K = 25 # 只對前 K 名查原生相依(一張一次 API,不對全部查)
def dep_edges(pool, enabled=True):
"""回 [(a, b)…]:前 K 名的原生相依邊,只留兩端都在 pool 裡的。"""
fx = os.environ.get("ISEP_DEBT_FIXTURE")
if fx:
with open(fx) as f:
deps = (json.load(f).get("deps") or {})
in_pool = {d["ref"] for d in pool}
return [(a, b) for a, bs in deps.items() for b in bs
if a in in_pool and b in in_pool]
if not enabled:
return []
in_pool = {d["ref"] for d in pool}
edges = []
for d in pool[:DEPS_TOP_K]:
owner, rest = d["ref"].split("/", 1)
repo, num = rest.split("#")
try:
got = api(f"/repos/{owner}/{repo}/issues/{num}/dependencies") or []
except SystemExit:
continue
for i in got:
other = f"{i['repository']['full_name']}#{i['number']}"
if other in in_pool:
edges.append((d["ref"], other))
return edges
def mutual_edges(pool):
idx = {d["ref"]: set(d["refs"]) for d in pool}
out = []
for ref, targets in idx.items():
for t in targets:
if t in idx and ref in idx[t] and ref < t:
out.append((ref, t))
return out
def bundle(pool, edges):
idx = {d["ref"]: d for d in pool}
parent = {r: r for r in idx}
def find(x):
while parent[x] != x:
parent[x] = parent[parent[x]]
x = parent[x]
return x
def union(a, b):
ra, rb = find(a), find(b)
if ra != rb:
parent[rb] = ra
for a, b in edges:
if a in idx and b in idx:
union(a, b)
groups = {}
for d in pool:
groups.setdefault(find(d["ref"]), []).append(d)
out = []
for members in groups.values():
members.sort(key=lambda d: (-d["score"], d["ref"]))
out.append({"lead": members[0], "members": members,
"score": members[0]["score"]})
out.sort(key=lambda b: (-b["score"], b["lead"]["ref"]))
return out
# ── 狀態:領走了什麼(明天的清單要看得出昨天領走的不見了)───────────────────
def state_dir():
d = os.environ.get("ISEP_DEBT_STATE_DIR") or os.path.expanduser("~/.claude/isep-debt")
os.makedirs(d, exist_ok=True)
return d
def state_path():
return os.path.join(state_dir(), "claimed.json")
def load_state():
try:
with open(state_path()) as f:
d = json.load(f)
except Exception:
d = {}
d.setdefault("claims", {})
d.setdefault("last_run", None)
return d
def save_state(d):
with open(state_path(), "w") as f:
json.dump(d, f, ensure_ascii=False, indent=1)
# ── 印 ─────────────────────────────────────────────────────────────────────
def print_proof(repos, stats):
scanned = [r for r in repos if not r.get("skipped")]
n_iss = sum(r["issues"] for r in scanned)
n_pr = sum(r["prs"] for r in scanned)
print(f"🔎 查過的 repo{len(repos)} 個({ORG} 全組織)"
f" open issue {n_iss}、open PR {n_pr}")
for r in sorted(repos, key=lambda x: -(x["issues"] + x["prs"])):
mark = f"(跳過:{r['skipped']}" if r.get("skipped") else ""
print(f" · {r['name']} issue {r['issues']}PR {r['prs']} {mark}")
ml = stats.get("mainline")
if ml:
print(f"\n🎯 現在的主線:{ML.ref_of(ml)}「{ml.get('title')}」"
f"(唯一答案來自 scripts/mainline,本工具不自己判)")
print(f" 掛在**別條** milestone 上的 {stats['other_ms']} 張仍算債"
"——那條線現在沒有人在推")
else:
print("\n🎯 現在沒有標主線(`scripts/mainline set …`"
"⇒ 分不出哪條是緊急線在管的,保守起見:掛 open milestone 的一律不領")
print(f"\n 扣掉:掛在 open milestone 上的 {stats['milestone']} 張(那些歸緊急線管)"
f"/等 leo 的 {stats['human']} 張"
f"Human・human/exec・s/stage——那些要催不是要領,見 inkstone/ISEP#93"
f"/已經領走的 {stats['claimed']} 張")
def print_carry(state, items):
"""昨天領走的,今天怎麼了——**這一段就是「看得出領走的不在清單上」**。"""
claims = state.get("claims") or {}
if not claims:
return
open_refs = {ref_of(it) for it in items}
done = [r for r in claims if r not in open_refs]
doing = [r for r in claims if r in open_refs]
print(f"\n📦 之前領走的 {len(claims)} 張:已關 {len(done)}、還開著 {len(doing)}")
for r in sorted(doing):
c = claims[r]
print(f" ◻ {r} {c.get('at', '?')[:10]} 領的){c.get('title', '')[:40]}")
for r in sorted(done):
print(f" ✅ {r} 已關")
if doing:
print(" 🔴 還開著的沒有回到可領清單裡——做完就關票,或 "
"`debt-worklist forget <票>` 把它放回去。")
def print_bundle(i, b, verbose):
lead = b["lead"]
kind = "PR" if lead["pr"] else "票"
print(f"\n {i}. [{lead['score']}] {lead['ref']}{kind}")
print(f" {lead['title'][:72]}")
print(" 為什麼排這裡:" + "、".join(f"{n}{v:+g}" for n, v in lead["why"]))
if lead["labels"]:
print(f" 標籤:{lead['labels']}")
others = b["members"][1:]
if others:
print(f" ↳ 同一包(互相指著/原生相依,要一起領)共 {len(b['members'])} 張:")
shown = others if verbose else others[:BUNDLE_CAP]
for m in shown:
print(f" · [{m['score']}] {m['ref']} {m['title'][:56]}")
if len(others) > len(shown):
print(f" · …另外 {len(others) - len(shown)} 張(`--all` 看全部)")
def cmd_list(argv):
top = int(argv[argv.index("--top") + 1]) if "--top" in argv else 6
verbose = "--all" in argv
as_json = "--json" in argv
repos, items = collect()
state = load_state()
pool, stats, _ = pick(items, set(state.get("claims") or {}))
edges = mutual_edges(pool) + dep_edges(pool, enabled="--no-deps" not in argv)
bundles = bundle(pool, edges)
if as_json:
print(json.dumps({
"at": now().isoformat(), "repos": repos, "stats": stats,
"claimed": sorted(state.get("claims") or {}),
"bundles": [{"score": b["score"],
"members": [{"ref": m["ref"], "score": m["score"],
"title": m["title"], "why": m["why"]}
for m in b["members"]]} for b in bundles],
}, ensure_ascii=False, indent=1))
else:
print(f"🧾 還債清單 {now().strftime('%Y-%m-%d %H:%M UTC')}\n")
print_proof(repos, stats)
print_carry(state, items)
print(f"\n── 今天可以領的:{len(pool)} 張,收斂成 {len(bundles)} 包 "
f"────────────────────")
if not pool:
# 🔴 空清單要說話。默默結束=人分不出「查過沒東西」跟「根本沒查」。
print("\n ✅ **查詢跑過了,結果是零。**"
f"\n {len(repos)} 個 repo 都掃過(見上面那份清單),"
"沒有一張是「沒掛 milestone、沒等 leo、還沒被領走」的。"
"\n 這代表舊債清乾淨了——不是查詢壞掉。")
for i, b in enumerate(bundles[:len(bundles) if verbose else top], 1):
print_bundle(i, b, verbose)
if not verbose and len(bundles) > top:
print(f"\n …另外 {len(bundles) - top} 包(`--top N` 或 `--all` 看更多)")
if pool:
first = " ".join(m["ref"] for m in bundles[0]["members"][:BUNDLE_CAP])
print(f"""
── 領走它 ──────────────────────────────────────────────────
debt-worklist claim {first}
領走 = 今天要做它。領了之後它就不會再出現在這份清單上,
直到你把票關掉、或 `debt-worklist forget` 把它放回去。
🔴 **整包一起領**:同一包是互相指著的,拆開做會做到一半發現卡在另一張。""")
state["last_run"] = now().isoformat()
save_state(state)
return 0
def _titles(items):
return {ref_of(it): (it.get("title") or "") for it in items}
def cmd_claim(argv):
refs = [a for a in argv if not a.startswith("-")]
if not refs:
die("用法:debt-worklist claim <owner/repo#N> [更多…]")
for r in refs:
if not re.match(r"^[\w.-]+/[\w.-]+#\d+$", r):
die(f"🔴 票的寫法是 owner/repo#N,你給的是:{r}")
_, items = collect()
titles = _titles(items)
unknown = [r for r in refs if r not in titles]
if unknown:
die("🔴 這幾張不在 open 清單裡(打錯了?已經關了?):" + "、".join(unknown))
state = load_state()
for r in refs:
state["claims"][r] = {"at": now().isoformat(), "title": titles[r]}
save_state(state)
print(f"📦 領走 {len(refs)} 張,明天的清單不會再出現它們:")
for r in refs:
print(f" · {r} {titles[r][:60]}")
print("\n🔴 領了就是今天要做它。做完關票;改方向就 `debt-worklist forget`。")
return 0
def cmd_forget(argv):
refs = [a for a in argv if not a.startswith("-")]
if not refs:
die("用法:debt-worklist forget <owner/repo#N> [更多…]")
state = load_state()
gone = [r for r in refs if state["claims"].pop(r, None) is not None]
save_state(state)
print(f"↩️ 放回清單 {len(gone)} 張:" + ("、".join(gone) or "(本來就沒領過)"))
return 0
CMDS = {"list": cmd_list, "claim": cmd_claim, "forget": cmd_forget}
if __name__ == "__main__":
if len(sys.argv) < 2:
sys.exit(cmd_list([]))
if sys.argv[1] in ("-h", "--help", "help"):
print(__doc__)
sys.exit(0)
if sys.argv[1] not in CMDS:
print(__doc__)
sys.exit(2)
sys.exit(CMDS[sys.argv[1]](sys.argv[2:]))
-113
View File
@@ -1,113 +0,0 @@
#!/usr/bin/env bash
# gate-ok — 各道閘「總管看過了,放行下一個動作」的**單一入口**inkstone/ISEP#90 ④)
#
# ══ 為什麼要有這支 ═════════════════════════════════════════════════════
#
# 這些閘每一支都留了一道給總管的門,而每一道門長得都不一樣:
# touch /tmp/.prod-write-ok
# git rev-parse --show-toplevel > /tmp/.main-push-ok
# touch /tmp/.stage-verified
# touch /tmp/.solo-ok-<session_id>
# …
# 兩個後果:
# ① **記不住**。門的形狀藏在被擋下的那則訊息裡,每支都不同,
# 而且有兩支還帶參數(綁 repo、綁 session)——照著抄錯一個字,門就打不開。
# ② **放行不了**。逃生口是「一條臨時湊出來的 Bash 指令」,
# 而臨時湊出來的指令**沒有穩定的形狀可以事先放行**:
# `.claude/settings.json` 的 allow 只能逐條寫死
# (現場真的就寫著 `Bash(touch /tmp/.prod-write-ok)` 這種完全比對的一行),
# 多一個 `&&`、換一個檔名、加一個 session id,就落在那條規則之外。
# 2026-08-28inkstone/InkStoneCo#99)總管在雲端連續四次沒能把
# prod-write 的戳記蓋出去 ⇒ **閘留了一道給總管的門,而那道門打不開**
# ⇒ 任何「擋下來、但總管可以放行」的閘,在那個環境裡等於「純擋」。
#
# ⇒ 這支把所有逃生口收斂成**一個名字、一種形狀**:
# bash "$CLAUDE_PLUGIN_ROOT/scripts/gate-ok" <閘名> [參數]
# 一條前綴規則就涵蓋全部,而且以後新增閘不必再動一次設定。
#
# 🔴 這支**不會弱化任何一道閘**:它蓋的戳記跟閘原本認的是同一個檔、同一種語意
# (單次用完即丟、綁 repo、綁 session、有效期都不變)。它換掉的只有「怎麼蓋」。
# 🔴 也**不是給 subagent 用的**:閘擋的是無心不是惡意(見 main-and-prod-push-guard
# 第 76 行)。subagent 照樣造得出戳記,但它得刻意繞過一段明講「不要這樣做」的訊息。
set -eu
usage() {
cat <<'USAGE'
用法:gate-ok <閘名> [參數]
prod-write 改到線上實例(prod-write-guard)——放行下一個動作,用完即消失
main-push [repo 路徑] 推 gitea mainmain-and-prod-push-guard)——綁 repo,預設是 cwd
stage-verified stage 真的驗過了(stage-before-prod-guard)——記得在回覆貼實測輸出
solo <session_id> 這件事真的該自己做(subagent-first-guard)——回覆裡要寫理由
dispatch <session_id> 派工單真的有例外(dispatch-format-guard
ask <session_id> 這題真的是人閘(ask-user-question-guard
kbdb-down KBDB 真的連不上(history-first-guard)——回覆裡要說明
--list 列出目前存在的戳記
🔴 每一枚戳記都是**留痕**:它會出現在指令歷史上,而且多數是單次用完即丟。
蓋之前先確定你真的看過那個動作會改到什麼;蓋完在回覆裡寫一句為什麼。
USAGE
}
stamp() { # stamp <檔> <說明> [內容]
if [ $# -ge 3 ]; then printf '%s\n' "$3" > "$1"; else : >> "$1"; touch "$1"; fi
printf '✅ 已蓋戳記:%s\n %s\n' "$1" "$2"
}
[ $# -ge 1 ] || { usage; exit 2; }
case "$1" in
-h|--help|help) usage; exit 0 ;;
--list)
printf '目前存在的戳記:\n'
ls -la /tmp/.prod-write-ok /tmp/.main-push-ok /tmp/.stage-verified \
/tmp/.kbdb-down /tmp/.solo-ok-* /tmp/.dispatch-ok-* /tmp/.ask-ok-* 2>/dev/null \
|| printf '(一枚都沒有)\n'
exit 0 ;;
esac
GATE="$1"; shift || true
case "$GATE" in
prod-write)
stamp /tmp/.prod-write-ok "只放行**下一個**會改到線上那台的動作,用完即消失(15 分鐘失效)" ;;
main-push)
# 綁 repo:戳記內容要是那個 repo 的 toplevel,閘會拿它跟「push 的目標 repo」比對。
# 🔴 解不出 repo 時**寧可失敗也不蓋空的**——閘明文寫著空內容不算數
# (08-12 那次穿透就是空檔案變成萬用鑰匙),蓋一個註定打不開的戳記
# 只會讓人以為門開了。
D="${1:-$(pwd)}"
TOP="$(git -C "$D" rev-parse --show-toplevel 2>/dev/null || true)"
if [ -z "$TOP" ]; then
printf '❌ %s 不在任何 git repo 裡,解不出要放行哪個 repo。\n' "$D" >&2
printf ' 用法:gate-ok main-push <那個 repo 的路徑>\n' >&2
exit 2
fi
stamp /tmp/.main-push-ok "只放行推 $TOP 的 main,單次、15 分鐘失效" "$TOP" ;;
stage-verified)
stamp /tmp/.stage-verified "stage 驗過了(6 小時)——**記得在回覆裡貼 stage 的實測輸出**" ;;
kbdb-down)
stamp /tmp/.kbdb-down "KBDB 連不上而放行——**回覆裡要說明**,這是留痕不是豁免" ;;
solo|dispatch|ask)
SID="${1:-${CLAUDE_SESSION_ID:-}}"
if [ -z "$SID" ]; then
printf '❌ %s 要綁 session id(閘用它認「是不是同一個 session」)。\n' "$GATE" >&2
printf ' 被擋下的那則訊息裡就有;或 gate-ok %s <session_id>\n' "$GATE" >&2
exit 2
fi
case "$GATE" in
solo) stamp "/tmp/.solo-ok-$SID" "這件事自己做——**回覆裡要寫理由**" ;;
dispatch) stamp "/tmp/.dispatch-ok-$SID" "這張派工單的例外,放行一次" ;;
ask) stamp "/tmp/.ask-ok-$SID" "這題確認是人閘,放行一次" ;;
esac ;;
*)
printf '❌ 不認得的閘名:%s\n\n' "$GATE" >&2
usage >&2
exit 2 ;;
esac
-222
View File
@@ -1,222 +0,0 @@
#!/bin/bash
# 還債清單(scripts/debt-worklist)的測試——inkstone/ISEP#83 的四條驗收條件,一條一組。
#
# 全程離線:資料走 ISEP_DEBT_FIXTURE、時鐘走 ISEP_DEBT_NOW、狀態走 ISEP_DEBT_STATE_DIR。
# **不打 Gitea、不留任何測試票、不碰 $HOME**。
#
# 為什麼要能離線測:這支工具的判斷(誰排前面、誰算緊急線、領走的還在不在)
# 全都是純函式,只有「撈」那一步要網路。把撈的那一步換掉,其餘每一條都測得動——
# 否則就只剩「今天跑起來看起來對」,那不是測試(本 repo 心法:跑過 ≠ 驗過)。
cd "$(dirname "$0")/.." || exit 1
W=scripts/debt-worklist
PASS=0; FAIL=0
T=$(mktemp -d); trap 'rm -rf "$T"' EXIT
NOW=2026-08-28T00:00:00Z
ok(){ # $1=條件 $2=說明
if eval "$1"; then PASS=$((PASS+1)); printf ' ✅ %s\n' "$2"
else FAIL=$((FAIL+1)); printf ' ❌ %s\n 判準:%s\n' "$2" "$1"; fi
}
run(){ # 跑 list(或任何子命令),輸出留在 $OUT,離開碼留在 $RC
# 🔴 ISEP_COUNTDOWN_STATE_DIR 也要指到暫存目錄:主線(hooks/lib/mainline.py)住在那裡,
# 不隔離的話這支測試的結果會取決於「這台機器現在標了哪條主線」——那就不是測試了。
OUT=$(ISEP_DEBT_FIXTURE="$FX" ISEP_DEBT_STATE_DIR="$T/state" ISEP_DEBT_NOW="$NOW" \
ISEP_COUNTDOWN_STATE_DIR="$ML_DIR" python3 "$W" "$@" 2>&1); RC=$?
}
ML_DIR="$T/mainline"; mkdir -p "$ML_DIR"
set_mainline(){ # $1=主線 milestone 標題(空=沒有主線)
if [ -z "$1" ]; then rm -f "$ML_DIR/mainline.json"; return; fi
python3 - "$ML_DIR/mainline.json" "$1" <<'PY'
import json, sys
path, title = sys.argv[1], sys.argv[2]
json.dump({"ref": "inkstone/A#1", "owner": "inkstone", "repo": "A", "id": 1,
"title": title, "members": [], "due_on": ""}, open(path, "w"))
PY
}
# ── 造資料:一份長得像 Gitea 回應的 fixture ─────────────────────────────────
mkfx(){ FX="$T/$1.json"; python3 - "$FX" "$1" <<'PY'
import json, sys
path, which = sys.argv[1], sys.argv[2]
def it(repo, n, title, labels=(), ms=None, ms_state="open", assignees=(),
updated="2026-08-01T00:00:00Z", body="", pr=False):
d = {"number": n, "title": title, "body": body, "updated_at": updated,
"created_at": "2026-07-01T00:00:00Z", "state": "open",
"labels": [{"name": l} for l in labels],
"assignees": [{"login": a} for a in assignees] or None,
"repository": {"full_name": repo},
"html_url": f"https://git.uncle6.me/{repo}/issues/{n}"}
if ms:
d["milestone"] = {"title": ms, "state": ms_state}
if ms == "上個 sprint":
d["milestone"]["due_on"] = "2026-08-10T23:59:59Z" # 已經過了 18 天
if pr:
d["pull_request"] = {"merged": False}
return d
repos = [{"name": "inkstone/A", "issues": 0, "prs": 0},
{"name": "inkstone/B", "issues": 0, "prs": 0}]
deps, items = {}, []
if which == "full":
items = [
# 事故+擋住別人的 → 該排第一
it("inkstone/A", 1, "壞掉了", ["type/bug"], updated="2026-08-20T00:00:00Z",
body="x" * 2000),
it("inkstone/A", 2, "我等 A#1", updated="2026-08-27T00:00:00Z",
body="被 inkstone/A#1 擋住" + "y" * 2000),
it("inkstone/B", 9, "我也等 A#1", updated="2026-08-27T00:00:00Z",
body="要先解 inkstone/A#1" + "y" * 2000),
# 掛在 open milestone 上=緊急線在管,不該出現
it("inkstone/A", 3, "緊急線的票", ["p/high", "type/bug"], ms="這週出貨"),
# 掛在**別條**(非主線)milestone 上,而且期限已經過了
it("inkstone/A", 8, "別條線的票", ms="上個 sprint", body="q" * 2000),
# milestone 已關但票還開著=孤兒,該出現
it("inkstone/A", 4, "孤兒票", ms="上週", ms_state="closed", body="z" * 2000),
# 等 leo 的三種,都不該出現在可領清單
it("inkstone/A", 5, "等 leo 批", ["Human", "p/high", "type/bug"]),
it("inkstone/A", 6, "等 leo 動手", ["human/exec"]),
it("inkstone/A", 7, "等 leo 驗", ["s/stage", "p/high"]),
# 放很久沒人動 vs 昨天才動過:同條件下前者要排前面
it("inkstone/B", 10, "放了很久", updated="2026-06-01T00:00:00Z", body="w" * 2000),
it("inkstone/B", 11, "昨天才動過", updated="2026-08-27T00:00:00Z", body="w" * 2000),
# 躺著的 PR 也是債
it("inkstone/B", 12, "躺著的 PR", pr=True, updated="2026-08-10T00:00:00Z",
body="v" * 2000),
# p/low:往後排
it("inkstone/B", 13, "晚點沒關係", ["p/low"], body="u" * 2000),
# 互相指著=必然同包
it("inkstone/B", 20, "雙胞胎甲", body="跟 inkstone/B#21 是同一件事" + "t" * 2000,
updated="2026-08-05T00:00:00Z"),
it("inkstone/B", 21, "雙胞胎乙", body="見 inkstone/B#20" + "t" * 2000,
updated="2026-08-05T00:00:00Z"),
# 母票/子票:只有原生相依看得出來(內文沒有互指)
it("inkstone/B", 30, "母票", body="s" * 2000, updated="2026-08-05T00:00:00Z"),
it("inkstone/B", 31, "子票", body="s" * 2000, updated="2026-08-05T00:00:00Z"),
]
deps = {"inkstone/B#30": ["inkstone/B#31"]}
elif which == "empty":
items = [it("inkstone/A", 3, "緊急線的票", ["p/high"], ms="這週出貨"),
it("inkstone/A", 5, "等 leo 批", ["Human"])]
elif which == "onedone":
# 「昨天領走的今天關掉了」——它從 open 清單消失
items = [it("inkstone/A", 2, "我等 A#1", body="y" * 2000)]
json.dump({"repos": repos, "items": items, "deps": deps}, open(path, "w"))
PY
}
mkfx full; FULL="$T/full.json"
mkfx empty
mkfx onedone
echo "── 驗收 1:跑一次要吐出排好序的清單+「我查了哪些 repo」的證明 ──"
FX="$FULL"; run list --top 20
ok '[ "$RC" = 0 ]' '離開碼 0'
ok 'grep -q "查過的 repo2 個" <<<"$OUT"' '證明段落列出查過的 repo 數'
ok 'grep -q "inkstone/A" <<<"$OUT" && grep -q "inkstone/B" <<<"$OUT"' '每個 repo 都列名(不是只給總數)'
ok 'grep -q "1\. \[.*\] inkstone/A#1" <<<"$OUT"' '事故+擋住兩張 ⇒ 排第一名'
ok 'grep -q "事故+40" <<<"$OUT"' '每張票旁邊看得到「為什麼排這裡」的分項'
ok 'grep -q "擋住2張" <<<"$OUT"' '「擋住別人的」算得出來(兩張指著 A#1)'
echo "── 驗收 1b:排序的五個條件真的有作用 ──"
pos(){ grep -n "$1" <<<"$OUT" | head -1 | cut -d: -f1; }
ok '[ "$(pos "inkstone/B#10")" -lt "$(pos "inkstone/B#11")" ]' '放最久的排在昨天才動過的前面'
ok '[ "$(pos "inkstone/B#12")" -lt "$(pos "inkstone/B#13")" ]' '躺著的 PR 排在 p/low 前面'
ok 'grep -q "PR躺著+25" <<<"$OUT"' 'PR 被認出來(不是只算 issue'
ok '! grep -q "inkstone/A#3" <<<"$OUT"' '掛 open milestone 的不進清單(那歸緊急線)'
ok 'grep -q "inkstone/A#4" <<<"$OUT"' 'milestone 已關但票還開著 ⇒ 是債,要進清單'
ok '! grep -q "inkstone/A#5" <<<"$OUT" && ! grep -q "inkstone/A#6" <<<"$OUT"' \
'Humanhuman-exec 不進可領清單(沒有人能替 leo 領)'
ok '! grep -q "inkstone/A#7" <<<"$OUT"' 's/stage=等 leo 驗,要催不是要領'
ok 'grep -q "等 leo 的 3 張" <<<"$OUT"' '被扣掉的有講數字,不是靜靜消失'
echo "── 驗收 1c:成包——相關的要一起領,但不准黏成一坨 ──"
ok 'grep -A6 "inkstone/B#20(票)" <<<"$OUT" | grep -q "inkstone/B#21"' '互相指著的成同一包'
ok 'grep -A6 "inkstone/B#30(票)" <<<"$OUT" | grep -q "inkstone/B#31"' '原生相依(母票→子票)成同一包'
ok '! (grep -A6 "inkstone/A#1(票)" <<<"$OUT" | grep -q "同一包")' \
'單向引用不成包(A#2、B#9 都指著 A#1,但 A#1 沒指回來 ⇒ 不能黏成一坨)'
echo "── 接上「現在的主線是哪一個」(inkstone/ISEP#82 的唯一答案)──"
set_mainline ""; FX="$FULL"; run list --top 20
ok 'grep -q "現在沒有標主線" <<<"$OUT"' '沒標主線 ⇒ 照實說,不編一條出來'
ok '! grep -q "inkstone/A#3" <<<"$OUT" && ! grep -q "inkstone/A#8" <<<"$OUT"' \
'沒標主線 ⇒ 保守:掛 open milestone 的一律不領(不跟緊急線搶同一張)'
set_mainline "這週出貨"; run list --top 20
ok 'grep -q "現在的主線" <<<"$OUT" && grep -q "這週出貨" <<<"$OUT"' \
'標了主線 ⇒ 清單上講得出用的是哪一條(判斷來自 scripts/mainline,不是自己算的)'
ok '! grep -q "inkstone/A#3" <<<"$OUT"' '在主線上的票仍然不領(那是緊急線在管的)'
ok 'grep -q "inkstone/A#8" <<<"$OUT"' '掛在別條 milestone 的是債(那條線現在沒人推)'
ok 'grep -q "逾期17天的承諾+15" <<<"$OUT"' '別條 milestone 已逾期 ⇒ 算「答應過人家的」加分'
ok 'grep -q "別條\*\* milestone 上的 1 張仍算債" <<<"$OUT"' '被改判成債的有幾張,講出來'
set_mainline "" # 收回去,後面幾組回到「沒有主線」的世界
echo "── 驗收 2:清單是空的要說話,不能默默結束 ──"
FX="$T/empty.json"; run list
ok '[ "$RC" = 0 ]' '離開碼 0(沒東西可領不是錯誤)'
ok 'grep -q "查詢跑過了,結果是零" <<<"$OUT"' '明講「查過了,結果是零」'
ok 'grep -q "查過的 repo2 個" <<<"$OUT"' '空清單一樣附查詢證明(分得出「沒東西」與「沒查」)'
echo "── 驗收 3:今天領走的,明天不在清單上 ──"
rm -rf "$T/state"; FX="$FULL"
run claim inkstone/B#20 inkstone/B#21
ok '[ "$RC" = 0 ]' '領走兩張成功'
run list --top 20
PICK=$(sed -n '/今天可以領的/,$p' <<<"$OUT")
ok '! grep -q "inkstone/B#21" <<<"$PICK"' '領走的不再出現在可領清單(只看清單那一段)'
ok 'grep -q "之前領走的 2 張" <<<"$OUT"' '第二天看得到「之前領走的」那一段'
ok 'grep -q "還開著 2" <<<"$OUT"' '還開著的照實說(沒關就是還沒做完)'
ok 'grep -q "已經領走的 2 張" <<<"$OUT"' '扣除數字對得上'
echo "── 驗收 3b:領走的票關掉之後,狀態要跟著變 ──"
FX="$T/onedone.json"; run list
ok 'grep -q "已關 2" <<<"$OUT"' '票已經不在 open 清單 ⇒ 認定它做完了'
echo "── 驗收 3c:放回去 ──"
FX="$FULL"; run forget inkstone/B#20 inkstone/B#21
ok '[ "$RC" = 0 ]' 'forget 成功'
run list --top 20
ok 'grep -q "inkstone/B#20" <<<"$OUT"' '放回去之後又回到可領清單'
echo "── 誤用:擋得住,而且說得出怎麼改 ──"
run claim B#20
ok '[ "$RC" = 2 ] && grep -q "owner/repo#N" <<<"$OUT"' '票號寫錯 ⇒ 擋下並示範正確寫法'
run claim inkstone/B#999
ok '[ "$RC" = 2 ]' '領一張不存在/已關的票 ⇒ 擋下'
run claim
ok '[ "$RC" = 2 ] && grep -q "用法" <<<"$OUT"' '沒給票號 ⇒ 印用法'
echo "── 機器可讀(要接進別的東西時不用 parse 中文)──"
run list --json
ok 'python3 -c "import json,sys;d=json.load(sys.stdin);sys.exit(0 if d[\"bundles\"] and d[\"repos\"] else 1)" <<<"$OUT"' \
'--json 吐得出合法 JSON,且有 bundlesrepos'
echo "── 紅線:這支腳本自己不會醒(不准做成輪詢/fan-out)──"
ok '! grep -nE "time\\.sleep|crontab|sched|urlopen.*hooks" '"$W" \
'原始碼裡沒有等待/排程/裝 webhook 的動作(只有註解在談紅線,那不算)'
echo "── SessionStart 那一句:不用有人記得下指令,也不准偷偷打網路 ──"
# 把 session-start-recall.sh 裡「還債線」那一段切出來單獨跑(其餘段落會打雲端,這裡不要)。
FRAG="$T/frag.sh"
sed -n '/push 6:還債線/,/^echo ""$/p' hooks/session-start-recall.sh > "$FRAG"
ok '[ -s "$FRAG" ]' 'session-start-recall.sh 裡真的有那一段(被刪掉就會紅)'
rm -rf "$T/nudge"; mkdir -p "$T/nudge"
OUT=$(set -euo pipefail; ISEP_DEBT_STATE_DIR="$T/nudge" bash "$FRAG" 2>&1); RC=$?
ok '[ "$RC" = 0 ]' '沒有狀態檔也跑得過(第一次開 session)'
ok 'grep -q "今天還沒撈過" <<<"$OUT"' '今天沒撈過 ⇒ 開 session 就會說'
ok 'grep -q "debt-worklist list" <<<"$OUT"' '順手把要跑的那一行給出來'
printf '{"claims":{"a/b#1":{}},"last_run":"%sT00:00:00Z"}' "$(date -u +%Y-%m-%d)" > "$T/nudge/claimed.json"
OUT=$(ISEP_DEBT_STATE_DIR="$T/nudge" bash "$FRAG" 2>&1)
ok 'grep -q "今天撈過了" <<<"$OUT"' '今天撈過了 ⇒ 不再重複催'
ok 'grep -q "手上領著 1 張" <<<"$OUT"' '手上還領著幾張講出來'
ok '! grep -qE "curl|urlopen|http" <<<"$(cat "$FRAG")"' \
'SessionStart 那一段完全不打網路(撈是人決定的動作,不是開機自動去撈)'
echo
echo "通過 $PASS 條,失敗 $FAIL"
[ "$FAIL" = 0 ]
-274
View File
@@ -1,274 +0,0 @@
#!/bin/bash
# 「下游做完時頂層跟著關」的測試(inkstone/ISEP#92
#
# 這支測三件事:
# ① 判準本身(純函式 is_loosewriteback_planjourney_label
# —— 這三支不打網路,所以「撈得對不對」「回寫該做什麼」測得動,
# 不必真的開票、關票來驗。
# ② `subtask``handoff` 的參數閘:該擋的擋、齊全的放得過
# ③ `loose` 這個動詞真的接得上(走到網路那一層才炸)
#
# 怎麼在「不真的動任何票」的前提下分辨擋/放行(沿用 test-ticket-where-seen-guard.sh):
# TICKET_HOST 指到一個連不上的位址(127.0.0.1:9
# 離開碼 2 = 閘擋下(die)
# 離開碼 1 = 閘全部放行,走到網路那一層才炸(Connection refused
# 全程離線、不打真實 Gitea、不產生任何票、不關任何票。
cd "$(dirname "$0")/.." || exit 1
T=scripts/ticket
TMP=$(mktemp -d)
trap 'rm -rf "$TMP"' EXIT
PASS=0; FAIL=0
cat > "$TMP/body.md" <<'MD'
## 目標
測試用內文。
## 驗收條件
離開碼 2 = 被擋;離開碼 1 = 放行(走到網路才炸)。
## deliverable 類型
code
MD
BAD_BODY="$TMP/bad.md"; echo "沒有模板欄位" > "$BAD_BODY"
TITLE="身為看頂層票的人,我要下游做完時頂層跟著關,我才不會看到一堆早就做完的票"
# ── 純函式探針:把 scripts/ticket 當模組載進來問 ────────────────────────
probe() { # probe <python 片段> → 印出結果
python3 - "$1" <<'PY'
import sys, importlib.util as u
from importlib.machinery import SourceFileLoader as L
spec = u.spec_from_loader("t", L("t", "scripts/ticket"))
m = u.module_from_spec(spec); spec.loader.exec_module(m)
print(eval(sys.argv[1], {"m": m}))
PY
}
p() { # p <說明> <want> <python 片段>
got=$(probe "$3" 2>&1)
if [ "$got" = "$2" ]; then PASS=$((PASS+1)); printf ' ✅ '; else FAIL=$((FAIL+1)); printf ' ❌ '; fi
printf 'want=%s got=%s %s\n' "$2" "$got" "$1"
}
O='{"state":"open"}'; C='{"state":"closed"}'
echo "── ① is_loose:「下游都關了、自己還開著」是機械事實 ──"
p "★ open + 下游全關 → 撈得到(票上驗收第 3 條)" "True" "m.is_loose('open',[$C,$C])"
p "open + 還有一張下游開著 → 不撈(它還在跑)" "False" "m.is_loose('open',[$C,$O])"
p "open + 從來沒有下游 → 不撈(它根本不是頂層票)" "False" "m.is_loose('open',[])"
p "closed + 下游全關 → 不撈(自己都關了)" "False" "m.is_loose('closed',[$C,$C])"
p "open 下游全開 → 不撈" "False" "m.is_loose('open',[$O,$O])"
echo
echo "── ② writeback_plan:下游關掉之後,頂層票該被怎麼處理 ──"
p "★ 最後一張下游關掉 → handback(指派回總管+s/review,不默默留著)" \
"('handback', [])" "m.writeback_plan('open',[$C,$C])"
p "還有別的下游沒關 → 只記一筆,別假裝它可以收了" \
"('note', [{'state': 'open'}])" "m.writeback_plan('open',[$C,$O])"
p "頂層票自己已經關了 → skip" \
"('skip', [])" "m.writeback_plan('closed',[$C,$C])"
p "頂層票已關但還有 open 下游 → 一樣 skip(不去吵已關的票)" \
"('skip', [{'state': 'open'}])" "m.writeback_plan('closed',[$O])"
p "防禦:頂層票沒有任何下游(實務上到不了這裡)→ 不會炸" \
"('handback', [])" "m.writeback_plan('open',[])"
echo
echo "── ③ journey_label:只加前綴,不猜名字合不合法 ──"
p "收件匣 → j/收件匣" "j/收件匣" "m.journey_label('收件匣')"
p "已經帶前綴 → 不重複加" "j/收件匣" "m.journey_label('j/收件匣')"
p "前後空白 → 修掉" "j/收件匣" "m.journey_label(' 收件匣 ')"
echo
echo "── ④ subtaskhandoff 的參數閘(該擋)──"
run() { # run <want_rc> <說明> <verb> [參數...]
want=$1; what=$2; verb=$3; shift 3
out=$(TICKET_HOST=http://127.0.0.1:9 GITEA_TOKEN=x \
python3 "$T" "$verb" inkstone/ISEP#92 "$@" 2>&1)
got=$?
LAST_OUT="$out"
if [ "$got" = "$want" ]; then PASS=$((PASS+1)); printf ' ✅ '; else FAIL=$((FAIL+1)); printf ' ❌ '; fi
printf 'want=%s got=%s %s\n' "$want" "$got" "$what"
}
has() { if printf '%s' "$LAST_OUT" | grep -q "$1"; then PASS=$((PASS+1)); printf ' ✅ '
else FAIL=$((FAIL+1)); printf ' ❌ '; fi; printf '訊息裡有「%s」 %s\n' "$1" "$2"; }
run 2 "缺 --title" subtask -F "$TMP/body.md"
run 2 "缺 -F" subtask --title "$TITLE"
run 2 "標題不是 User Story" subtask --title "整理一下票" -F "$TMP/body.md"
run 2 "內文缺模板欄位" subtask --title "$TITLE" -F "$BAD_BODY"
run 2 "指派了人卻沒寫 --next" subtask --title "$TITLE" -F "$TMP/body.md" --assign someone
run 2 "--journey 給了空字串(對不上就不要加這個參數)" \
subtask --title "$TITLE" -F "$TMP/body.md" --journey ""
has "不硬湊" "空 journey 的訊息講的是「不硬湊」,不是叫人隨便填一個"
echo
echo "── ⑤ 齊全就放得過(誤攔比漏擋更該修)──"
run 1 "subtask 齊全 → 走到網路才炸" subtask --title "$TITLE" -F "$TMP/body.md"
run 1 "★ handoff 是同一個動作的別名,一樣放得過" handoff --title "$TITLE" -F "$TMP/body.md" --to arcrun-rag
run 1 "帶 --journey 一樣放得過" subtask --title "$TITLE" -F "$TMP/body.md" --journey 收件匣
run 1 "--assign 有配 --next → 放行" subtask --title "$TITLE" -F "$TMP/body.md" --assign someone --next "先看一眼"
echo
echo "── ⑥ loose 這個動詞接得上 ──"
out=$(TICKET_HOST=http://127.0.0.1:9 GITEA_TOKEN=x python3 "$T" loose 2>&1); got=$?
if [ "$got" = 1 ]; then PASS=$((PASS+1)); printf ' ✅ '; else FAIL=$((FAIL+1)); printf ' ❌ '; fi
printf 'want=1 got=%s loose 走到網路那一層才炸(動詞有註冊、參數不擋)\n' "$got"
out=$(python3 "$T" 2>&1)
if printf '%s' "$out" | grep -q "ticket loose"; then PASS=$((PASS+1)); printf ' ✅ '
else FAIL=$((FAIL+1)); printf ' ❌ '; fi
printf '不帶參數的說明裡列得出 loose(撈不到的東西等於不存在)\n'
echo
echo "── ⑦ 完工回寫的接線(票上驗收第 2 條)──"
echo " 把 api() 換成錄音機跑一次 _writeback,驗它到底打了哪些端點、送了什麼。"
echo " 不打網路、不動任何真票;/blocks 的回應形狀取自 2026-08-28 實查 inkstone/ISEP#75。"
w() { # w <說明> <want> <python 片段(用 rec 這個錄音清單)>
got=$(python3 - "$3" <<'PY' 2>&1
import sys, json, importlib.util as u
from importlib.machinery import SourceFileLoader as L
spec = u.spec_from_loader("t", L("t", "scripts/ticket"))
m = u.module_from_spec(spec); spec.loader.exec_module(m)
SCEN = json.loads(__import__("os").environ["SCEN"])
rec = []
def fake_api(path, payload=None, method=None):
rec.append((method or ("POST" if payload is not None else "GET"), path, payload))
if path.endswith("/blocks"):
return SCEN["blocks"]
if path.endswith("/dependencies"):
return SCEN["deps"]
if "/labels" in path and (method or "GET") == "GET":
return [{"name": n, "id": i} for i, n in enumerate(SCEN.get("labels", []), 1)]
return {}
m.api = fake_api
# _writeback 會把進度印出來——那是給人看的,不是這支測試的判準。
# 判準是**它打了哪些端點、送了什麼**(rec),所以把它的輸出吞掉。
import contextlib, io
buf = io.StringIO()
with contextlib.redirect_stdout(buf), contextlib.redirect_stderr(buf):
m._writeback("inkstone", "arcrun-rag", 143, "https://example/pr/1")
print(eval(sys.argv[1], {"rec": rec, "m": m}))
PY
)
if [ "$got" = "$2" ]; then PASS=$((PASS+1)); printf ' ✅ '; else FAIL=$((FAIL+1)); printf ' ❌ '; fi
printf 'want=%s got=%s %s\n' "$2" "$got" "$1"
}
PARENT='{"number":136,"state":"open","title":"頂層票","labels":[{"name":"s/doing"},{"name":"p/high"}],"repository":{"full_name":"inkstone/arcrun-rag"}}'
LBL='["s/todo","s/doing","s/review","p/high"]'
# 情境 A:這是最後一張下游 → 母票要被指派回總管+改 s/review
export SCEN="{\"blocks\":[$PARENT],\"deps\":[{\"state\":\"closed\",\"number\":143,\"title\":\"x\",\"repository\":{\"full_name\":\"inkstone/arcrun-rag\"}}],\"labels\":$LBL}"
w "★ 有去問子票的 /blocks(誰在等我)" "True" \
"any(p.endswith('/issues/143/blocks') for _,p,_ in rec)"
w "★ 有在母票的時間軸貼回寫留言" "True" \
"any(mm=='POST' and p=='/repos/inkstone/arcrun-rag/issues/136/comments' for mm,p,_ in rec)"
w "★ 留言裡點名了剛關掉的那張下游票" "True" \
"any('arcrun-rag#143' in (pl or {}).get('body','') for _,p,pl in rec if p.endswith('/136/comments'))"
w "★ 留言裡有交付物連結(不是空口說做完了)" "True" \
"any('https://example/pr/1' in (pl or {}).get('body','') for _,p,pl in rec if p.endswith('/136/comments'))"
w "★ 留言第一行有身份欄(機器貼的留言一樣要標)" "True" \
"all((pl or {}).get('body','').startswith('【身份】') for _,p,pl in rec if p.endswith('/136/comments'))"
w "★ 母票被指派回總管(欄位,不是一句話)" "['claude-code']" \
"[(pl or {}).get('assignees') for mm,p,pl in rec if mm=='PATCH' and p=='/repos/inkstone/arcrun-rag/issues/136'][0]"
w "★ 母票的 s/* 換成 s/review,而非 s/* 的標籤留著" "True" \
"[sorted(pl['labels'])==sorted([3,4]) for mm,p,pl in rec if mm=='PUT' and p.endswith('/136/labels')][0]"
w "沒有去關母票(關票要有人驗——默默關掉跟默默留著是同一個病)" "False" \
"any((pl or {}).get('state')=='closed' for _,_,pl in rec)"
# 情境 B:母票還有別的下游沒關 → 只記一筆,不准指派、不准改 tag
export SCEN="{\"blocks\":[$PARENT],\"deps\":[{\"state\":\"closed\",\"number\":143,\"title\":\"x\",\"repository\":{\"full_name\":\"inkstone/arcrun-rag\"}},{\"state\":\"open\",\"number\":150,\"title\":\"還沒做的\",\"repository\":{\"full_name\":\"inkstone/Arcrun\"}}],\"labels\":$LBL}"
w "還有下游沒關 → 只貼留言,不指派" "False" "any(mm=='PATCH' for mm,_,_ in rec)"
w "還有下游沒關 → 不改 tag" "False" "any(mm=='PUT' for mm,_,_ in rec)"
w "留言裡把還沒關的那張列出來(跨 repo 也要列全稱)" "True" \
"any('inkstone/Arcrun#150' in (pl or {}).get('body','') for _,p,pl in rec if p.endswith('/136/comments'))"
# 情境 C:母票自己已經關了 → 完全不動它
PARENT_CLOSED='{"number":136,"state":"closed","title":"頂層票","labels":[],"repository":{"full_name":"inkstone/arcrun-rag"}}'
export SCEN="{\"blocks\":[$PARENT_CLOSED],\"deps\":[{\"state\":\"closed\",\"number\":143,\"title\":\"x\",\"repository\":{\"full_name\":\"inkstone/arcrun-rag\"}}],\"labels\":$LBL}"
w "母票已關 → 一則留言都不貼(不去吵已關的票)" "False" \
"any(p.endswith('/136/comments') for _,p,_ in rec)"
# 情境 D:這張票沒有任何頂層票在等它 → 不要吵
export SCEN="{\"blocks\":[],\"deps\":[],\"labels\":$LBL}"
w "沒有頂層票在等它 → 只問一次 /blocks 就收工" "1" "len(rec)"
unset SCEN
echo
echo "── ⑧ 雙向連結的接線(票上驗收第 1 條)──"
echo " 同樣用錄音機跑一次 subtask:驗「兩張票互相看得到對方」不是靠人記得補。"
b() { # b <說明> <want> <python 片段> [額外 argv...]
what=$1; want=$2; frag=$3; shift 3
got=$(ARGS_JSON=$(printf '%s\n' "$@" | python3 -c "import sys,json;print(json.dumps([l.rstrip('\n') for l in sys.stdin if l.strip()!='']))") \
python3 - "$frag" <<'PY' 2>&1
import sys, os, json, contextlib, io, importlib.util as u
from importlib.machinery import SourceFileLoader as L
spec = u.spec_from_loader("t", L("t", "scripts/ticket"))
m = u.module_from_spec(spec); spec.loader.exec_module(m)
rec = []
def fake_api(path, payload=None, method=None):
rec.append((method or ("POST" if payload is not None else "GET"), path, payload))
if path.endswith("/labels?limit=100"):
return [{"name": n, "id": i} for i, n in
enumerate(["s/todo", "s/review", "p/high", "j/收件匣"], 1)]
if path.endswith("/dependencies"):
return [{"state": "open", "number": 900, "title": "子票",
"repository": {"full_name": "inkstone/arcrun-rag"}}]
if path == "/repos/inkstone/ISEP/issues":
return {"number": 900, "html_url": "https://git.uncle6.me/inkstone/ISEP/issues/900"}
if path == "/repos/inkstone/arcrun-rag/issues":
return {"number": 900, "html_url": "https://git.uncle6.me/inkstone/arcrun-rag/issues/900"}
if path == "/repos/inkstone/ISEP/issues/92":
return {"number": 92, "labels": [{"name": "p/high"}]}
return {}
m.api = fake_api
argv = ["inkstone/ISEP#92"] + json.loads(os.environ["ARGS_JSON"])
buf = io.StringIO()
blocked = False
with contextlib.redirect_stdout(buf), contextlib.redirect_stderr(buf):
try:
m.cmd_subtask(argv)
except SystemExit:
blocked = True # 被閘擋下也是一種結果,不該讓整支測試靜靜掛掉
print(eval(sys.argv[1], {"rec": rec, "m": m, "blocked": blocked, "buf": buf.getvalue()}))
PY
)
if [ "$got" = "$want" ]; then PASS=$((PASS+1)); printf ' ✅ '; else FAIL=$((FAIL+1)); printf ' ❌ '; fi
printf 'want=%s got=%s %s\n' "$want" "$got" "$what"
}
A_BASE=(--title "$TITLE" -F "$TMP/body.md" --to arcrun-rag)
b "★ 子票內文寫著它的頂層票是誰(下游看得到上游)" "True" \
"any('Parent: inkstone/ISEP#92' in (pl or {}).get('body','') for mm,p,pl in rec if p=='/repos/inkstone/arcrun-rag/issues')" \
"${A_BASE[@]}"
b "★ 有掛上 Gitea 原生相依(不是只寫在內文裡)" "True" \
"any(mm=='POST' and p=='/repos/inkstone/ISEP/issues/92/dependencies' for mm,p,pl in rec)" \
"${A_BASE[@]}"
b "★ 頂層票的時間軸上有一則指向下游的留言(上游看得到下游)" "True" \
"any('inkstone/arcrun-rag#900' in (pl or {}).get('body','') for mm,p,pl in rec if p=='/repos/inkstone/ISEP/issues/92/comments')" \
"${A_BASE[@]}"
b "★ 那則留言明講「不會因為轉出去就自動關」(第 2 條的預告)" "True" \
"any('不會因為轉出去就自動關' in (pl or {}).get('body','') for mm,p,pl in rec if p=='/repos/inkstone/ISEP/issues/92/comments')" \
"${A_BASE[@]}"
b "沒給 --journey → 留言裡誠實寫「沒有貼」(不硬湊,也不假裝有)" "True" \
"any('沒有貼' in (pl or {}).get('body','') for mm,p,pl in rec if p=='/repos/inkstone/ISEP/issues/92/comments')" \
"${A_BASE[@]}"
b "沒給 --journey → 不去動任何一端的標籤軸(只設子票的 s/*)" "1" \
"len([1 for mm,p,pl in rec if mm=='PUT' and p.endswith('/labels')])" \
"${A_BASE[@]}"
b "★ 給了 --journey → 母子兩端都被貼(只貼一端就聚不起來)" "2" \
"len([1 for mm,p,pl in rec if mm=='PUT' and p.endswith('/labels') and 4 in pl['labels']])" \
"${A_BASE[@]}" --journey 收件匣
b "★ 貼在頂層票上時保留它原本的標籤(不是整組蓋掉)" "True" \
"any(mm=='PUT' and p=='/repos/inkstone/ISEP/issues/92/labels' and sorted(pl['labels'])==[3,4] for mm,p,pl in rec)" \
"${A_BASE[@]}" --journey 收件匣
b "labels.yaml 沒有的旅程名 → 擋下來(要求標籤在場,不是猜名字合不合法)" "True" \
"blocked" "${A_BASE[@]}" --journey 沒這條旅程
b "擋下來時直接指回 labels.yaml(不叫人自己猜怎麼修)" "True" \
"'labels.yaml' in buf" "${A_BASE[@]}" --journey 沒這條旅程
echo
echo "通過 $PASS 條,失敗 $FAIL"
[ "$FAIL" = 0 ] || exit 1
+6 -295
View File
@@ -21,10 +21,8 @@ leo 2026-08-16 三句話,本工具就是它們的機械化:
三個 Gitea 原生欄位(leo 2026-08-27「這些全部都要」,缺一個就會掉棒):
ticket subtask <母票> --title <US> -F <檔> 討論串裡的一件事 → 看得見的子票+相依
ticket handoff <頂層票> --to <repo> … 同一個動作,換個名字:頂層 → 下游 repo
ticket handback <票> --to <誰> --next <一句> 收工=指派+改 tag+寫下一步,一個動作
ticket mine [--user <誰>] 撈一次:棒子在誰手上、每根下一步是什麼
ticket loose 撈一次:下游都關了、自己還開著的頂層票
票的寫法:`owner/repo#N`,例:`inkstone/InkStoneCo#44`
"""
@@ -454,87 +452,10 @@ def cmd_close(argv):
if deliv:
api(f"/repos/{owner}/{repo}/issues/{num}/comments",
{"body": f"{_identity(owner, repo)}\n\n✅ 結案。交付物:{deliv}"})
{"body": f"{os.environ.get('ISEP_IDENTITY') or f'【身份】總管/{owner}/{repo}-'}\n\n✅ 結案。交付物:{deliv}"})
api(f"/repos/{owner}/{repo}/issues/{num}", {"state": "closed"}, method="PATCH")
print(f"✅ {owner}/{repo}#{num} 已關(交付物:{deliv or ('PR' if has_pr else '票上回報')}")
# ── 完工回寫(inkstone/ISEP#92 最痛的那一格)─────────────────────────
# 關掉一張下游票之後,**同一個動作**回頭處理它的頂層票。
# 不做這件事的後果票上寫得很清楚:「頂層票會永遠掛著,而 leo 是看頂層的」。
_writeback(owner, repo, num, deliv or ("PR" if has_pr else "票上回報"))
def _writeback(owner, repo, num, deliv):
"""子票關掉 → 回頭處理每一張在等它的頂層票。
🔴 失敗要吵。回寫悄悄失敗 = 這格等於沒做,而沒有人會發現
(那正是本票在治的病)。所以任何一張處理失敗就非零離開。
"""
child = f"{owner}/{repo}#{num}"
try:
parents = _blocks(owner, repo, num)
except SystemExit:
print(f"\n⚠️ 撈不到 {child} 的頂層票(/blocks 讀失敗)——"
f"回寫這一格**沒有做**,請手動確認或跑 `ticket loose`", file=sys.stderr)
sys.exit(1)
if not parents:
print("\n📌 這張票沒有任何頂層票在等它(沒有相依邊)⇒ 不需要回寫。")
return
print(f"\n🔗 有 {len(parents)} 張頂層票在等這張票,逐一回寫:")
failed = []
for pt in parents:
pfull = pt["repository"]["full_name"]
po, pr = pfull.split("/")
pn = pt["number"]
try:
pdeps = _deps(po, pr, pn)
action, open_left = writeback_plan(pt.get("state"), pdeps)
if action == "skip":
print(f" · {pfull}#{pn} 已經是 closed ⇒ 不動")
continue
lines = [_identity(po, pr), "",
f"⬇️ **下游完工回寫**`{child}` 已關(交付物:{deliv}"]
if open_left:
lines += ["", f"這張票還在等 {len(open_left)} 張下游(都關了才輪到它):"]
lines += [f"- ◻ {i['repository']['full_name']}#{i['number']} {i['title'][:60]}"
for i in open_left]
lines += ["", "⇒ 本票維持原狀,不要當成可以收了。"]
else:
lines += ["", "**這是最後一張下游——本票的下游已經全部關閉。**", "",
f"{BATON_MARK} → `{HANDBACK_TO}`", "",
"**下一步**:驗一次頂層要的東西真的到齊了,到齊就 "
f"`ticket close {pfull}#{pn} --deliverable <URL>`"
"沒到齊就開下一張下游票,不要把它留在原地。", "",
"(本則由 `ticket close` 的完工回寫自動貼上,"
"機制見 `inkstone/ISEP#92`"]
api(f"/repos/{po}/{pr}/issues/{pn}/comments", {"body": "\n".join(lines)})
if action == "handback":
# 指派 + 改 tag:**欄位**才撈得到,留言撈不到。
# 08-26 那次掉棒就是話有說、欄位沒動,棒子躺在地上 14 小時。
api(f"/repos/{po}/{pr}/issues/{pn}",
{"assignees": [HANDBACK_TO]}, method="PATCH")
cur = [l["name"] for l in (pt.get("labels") or [])]
keep = [n for n in cur if not n.startswith("s/")] + ["s/review"]
_set_labels(po, pr, pn, keep)
print(f" · {pfull}#{pn} 下游全關 ⇒ 已指派 {HANDBACK_TO}s/review(等人驗)")
else:
print(f" · {pfull}#{pn} 還有 {len(open_left)} 張下游沒關 ⇒ 只記一筆")
except SystemExit:
failed.append(f"{pfull}#{pn}")
except Exception as e:
failed.append(f"{pfull}#{pn}{e}")
if failed:
print(f"\n⚠️ 這幾張頂層票**沒有回寫成功**{'、'.join(failed)}\n"
f" 回寫失敗要吵——悄悄失敗等於這格沒做。手動補,或稍後跑 `ticket loose` 對帳。",
file=sys.stderr)
sys.exit(1)
# ── decide ───────────────────────────────────────────────────────────────
@@ -605,10 +526,6 @@ def cmd_decide(argv):
BATON_MARK = "🏃 **棒子交回**"
# 棒子的預設終點:總管。**這是 Gitea 的 assignee 欄位,不是一句話**——
# 撈「指派給你的」一頁就看得到,撈留言看不到。
HANDBACK_TO = os.environ.get("ISEP_HANDBACK_TO") or "claude-code"
def _labels_of(owner, repo):
return {l["name"]: l["id"] for l in api(f"/repos/{owner}/{repo}/labels?limit=100")}
@@ -628,97 +545,6 @@ def _deps(owner, repo, num):
return api(f"/repos/{owner}/{repo}/issues/{num}/dependencies") or []
def _blocks(owner, repo, num):
"""反方向:**誰把這張票當相依**——也就是這張票的頂層票(可能不只一張、可能跨 repo)。
Gitea 原生兩個端點是同一條邊的兩端,方向不可混淆:
/issues/<N>/dependencies 這張票在等誰 → 它的下游
/issues/<N>/blocks 誰在等這張票 → 它的頂層
`subtask` POST 的是**母票的 dependencies**,所以子票這端看到的是 `blocks`。
"""
return api(f"/repos/{owner}/{repo}/issues/{num}/blocks") or []
def _identity(owner, repo):
"""票上的每一則留言第一行要表明身份(規約見 docs/governance/dispatch-and-reply-format.md §3)。
機器自動貼的留言同樣要標——不標的話,回寫留言看起來像某個人寫的,
而下一個讀票的人會去找那個人。
"""
return os.environ.get("ISEP_IDENTITY") or f"【身份】總管/{owner}/{repo}-"
# ══════════════════════════════════════════════════════════════════════════
# inkstone/ISEP#92 — 「下游做完時頂層跟著關」的三格
#
# 票上的原話:「開在頂層的票,下游做完了卻沒人回來關⋯⋯頂層票會永遠掛著,
# 而 leo 是看頂層的。」
#
# 缺的三格,各由下面一段承接:
# ① 雙向連結的強制 → cmd_subtask 一個動作同時掛相依 + 在母票留下指回來的留言
# ② journey 標籤 → journey_label()(對不上就不貼,不硬湊)
# ③ 完工回寫 → writeback_plan() cmd_close 關完子票立刻回頭處理母票
# ④ 撈得出來 → is_loose() cmd_loose(③ 走側門漏掉的,這張網補回來)
#
# 🔴 這四格的判準**全部是機械事實**(相依邊在不在、state 是什麼),
# 沒有一格在猜文字。leo 2026-08-17 已證偽關鍵字黑名單那條路
# (8 次誤攔、0 次正確攔截)。
# ══════════════════════════════════════════════════════════════════════════
JOURNEY_PREFIX = "j/"
def journey_label(name):
"""`--journey 收件匣` → `j/收件匣`。只加前綴,不做語意判斷。
標籤存不存在由 `_set_labels` 去問 Gitea(不存在就擋,並指回 labels.yaml)——
**「要求某個東西在場」,不是「猜哪些名字合法」**。
⇒ 新的一條旅程要先加進 labels.yaml 再 sync,這是刻意的:
journey 是**跨票聚類的軸**,隨手造名字會讓同一條旅程長出三個拼法。
"""
n = (name or "").strip()
if not n:
die("🚫 --journey 後面要接旅程名(例:--journey 收件匣)。\n"
" 對不上任何旅程就**不要加這個參數**——票上明講不硬湊。")
return n if n.startswith(JOURNEY_PREFIX) else JOURNEY_PREFIX + n
def is_loose(state, deps):
"""這張票是不是「下游都關了、自己還開著」的頂層票。
純函式(不打網路)⇒ 判準本身測得動,不必開真的票來驗。
三個條件缺一不可:
· 自己還 open 關掉的票不用管
· 曾經有下游 沒有相依邊 ⇒ 它根本不是頂層票,不要拿它來吵
· 沒有任何 open 下游 有一張還開著就還在跑,不是掉在地上
"""
if state != "open":
return False
if not deps:
return False
return not any(d.get("state") == "open" for d in deps)
def writeback_plan(parent_state, parent_deps):
"""下游關掉之後,它的頂層票該被怎麼處理。**只回計畫,不做副作用**⇒ 離線測得動。
回 (動作, 還開著的下游):
"skip" 頂層票自己已經關了 ⇒ 沒事
"note" 還有別的下游沒關 ⇒ 只在頂層票記一筆,別假裝它可以收了
"handback" 下游全關了 ⇒ 這張票現在**只等人驗**:
指派回總管 + s/review,讓它出現在「指派給你的」
🔴 為什麼不自動關母票:關票要有交付物、要有人看過(`ticket close` 的既有閘)。
票上要的是「不能默默留著」,不是「自動消失」——
默默關掉跟默默留著是同一個病的兩面。
"""
open_left = [d for d in (parent_deps or []) if d.get("state") == "open"]
if parent_state != "open":
return "skip", open_left
return ("note" if open_left else "handback"), open_left
# ── subtask ──────────────────────────────────────────────────────────────
def cmd_subtask(argv):
"""把「討論串裡的一件事」長成看得見的子票,並掛成母票的 Gitea 原生相依。
@@ -739,9 +565,7 @@ def cmd_subtask(argv):
if len(argv) < 1:
die("用法:ticket subtask <母票 owner/repo#N> --title \"<User Story>\" -F <內文檔>\n"
" [--repo <收件 repo,預設跟母票同一個>] [--label <s/xxx,預設 s/todo>]\n"
" [--journey <旅程名>] ← 這件事服務哪條使用者旅程(對不上就不要加)\n"
" [--assign <誰做> --next \"<他第一件事要做什麼>\"] ← 指派了就一定要寫下一步\n"
"\n`ticket handoff` 是同一個動作的別名:頂層票 → 下游 repo)")
" [--assign <誰做> --next \"<他第一件事要做什麼>\"] ← 指派了就一定要寫下一步")
powner, prepo, pnum = parse_ref(argv[0])
def opt(name, default=None):
@@ -761,13 +585,10 @@ def cmd_subtask(argv):
" leo 2026-08-27:『每個事情沒有歷史記錄才是大問題』,\n"
" 而沒寫驗收條件的票,關掉之後就沒有歷史,只剩一個關字)")
# `--to <repo>` 是 `ticket handoff` 那個名字底下比較自然的講法,同一個東西。
# handback 的 `--to` 是「交給誰」,subtask 沒有那個參數,不會撞。)
repo = opt("--repo", opt("--to", prepo))
repo = opt("--repo", prepo)
label = opt("--label", "s/todo")
assign = opt("--assign")
nxt = opt("--next")
jlabel = journey_label(opt("--journey")) if "--journey" in argv else None
if assign and not nxt:
die("🚫 指派了人卻沒寫 --next。\n"
" **有人被指到這張票,他撈到它的第一件事就是問「所以我要做什麼」**——\n"
@@ -776,8 +597,7 @@ def cmd_subtask(argv):
body = (f"Parent: {powner}/{prepo}#{pnum}\n"
f"> 這張票是從母票的討論串裡長出來的一件事。\n"
f"> **它沒關,母票關不掉**(Gitea 原生相依,實測 412 硬擋)。\n"
f"> **它關掉時,母票會收到一則回寫**(`ticket close` 自動做,見 `inkstone/ISEP#92`)。\n\n") + body
f"> **它沒關,母票關不掉**(Gitea 原生相依,實測 412 硬擋)。\n\n") + body
d = api(f"/repos/{ORG}/{repo}/issues", {"title": title, "body": body})
cnum = d["number"]
@@ -799,38 +619,6 @@ def cmd_subtask(argv):
deps = _deps(powner, prepo, pnum)
openn = [i for i in deps if i["state"] == "open"]
print(f" 相依:已掛上 {powner}/{prepo}#{pnum}(它存在、且擋著母票)")
# 🔴 雙向連結:相依邊只長在 Gitea 的側欄,**母票的時間軸上什麼都沒有**。
# 票上的原話:「頂層票寫了『轉去某個 repo』,但那邊的票沒有指回來,
# 從下游那張票看不出它從哪來,脈絡就斷了。」
# ⇒ 兩端各留一個看得見的指標:子票內文的 `Parent:`(上面),母票時間軸的這一則。
# 跨 repo 時尤其重要——側欄的相依很容易被當成同 repo 的東西。
plines = [_identity(powner, prepo), "",
f"➡️ **已轉往下游**`{ORG}/{repo}#{cnum}` {title}", "",
f"{d['html_url']}", "",
f"- 收件 repo`{ORG}/{repo}` tag`{label}`"
+ (f" 旅程:`{jlabel}`" if jlabel else "")
+ (f" 指派:`{assign}`" if assign else " (還沒指派,留在票池等人領)")]
if jlabel is None:
plines += ["- 旅程:**沒有貼**(開票時判定對不上任何一條,不硬湊)"]
plines += ["",
"**這張頂層票不會因為轉出去就自動關**——下游那張關掉時,"
"`ticket close` 會回頭在這裡貼一則回寫;"
"全部下游關完,這張票會被指派回總管等驗。(機制:`inkstone/ISEP#92`"]
api(f"/repos/{powner}/{prepo}/issues/{pnum}/comments", {"body": "\n".join(plines)})
print(f" 回指:已在母票 {powner}/{prepo}#{pnum} 的時間軸貼上指向子票的留言")
# journey 標籤:兩端都貼,聚類才聚得起來(只貼一端=撈不到另一端)
if jlabel:
_set_labels(ORG, repo, cnum, [label, jlabel])
pcur = [l["name"] for l in (api(f"/repos/{powner}/{prepo}/issues/{pnum}")
.get("labels") or [])]
if jlabel not in pcur:
_set_labels(powner, prepo, pnum, pcur + [jlabel])
print(f" 旅程:`{jlabel}`(母子兩端都貼——只貼一端就聚不起來)")
else:
print(" 旅程:沒有貼(沒給 --journey)。對得上就補一次:"
f"`ticket subtask … --journey <旅程名>`;對不上就不要硬湊。")
print(f"\n📌 母票 {powner}/{prepo}#{pnum} 目前有 {len(openn)} 張未關的相依:")
for i in deps:
mark = "◻" if i["state"] == "open" else "☑"
@@ -959,86 +747,9 @@ def _last_next(owner, repo, num):
return None
# ── loose ────────────────────────────────────────────────────────────────
def cmd_loose(argv):
"""撈一次:**下游都關了、自己還開著**的頂層票。
票上的驗收條件第 3、4 條(`inkstone/ISEP#92`):
「撈一次『已經沒有 open 下游票、但自己還開著的頂層票』→ 要撈得出來(現在撈不出來)」
「拿現有的頂層票跑一次 → 要能指出哪幾張是這種情況」
這是 `ticket close` 自動回寫的**補網**:回寫只在走正門(`ticket close`)時發生,
而關票的側門(直接 PATCH `state=closed`)是刻意放行的
(見 `hooks/ticket-api-bypass-guard.sh`:「帶了 ID 的子路徑」一律放行)。
⇒ 側門漏掉的,由這張網撈回來。**不是輪詢**——掛在開場/收工對帳跑一次。
"""
def opt(name, default=None):
return argv[argv.index(name) + 1] if name in argv else default
org = opt("--org", ORG)
only = opt("--repo")
print(f"🔎 掃 `{org}` 的 open 票,找「下游都關了、自己還開著」的頂層票"
+ (f"(只看 {only}" if only else "") + " …")
items, page = [], 1
while page <= 12:
q = urllib.parse.urlencode({"state": "open", "type": "issues",
"limit": 50, "page": page, "owner": org})
got = api(f"/repos/issues/search?{q}") or []
if not got:
break
items += got
page += 1
if only:
items = [i for i in items if i["repository"]["full_name"].split("/")[-1] == only]
print(f" open 票 {len(items)} 張,逐張問它的下游 …")
def probe(it):
full = it["repository"]["full_name"]
o, r = full.split("/")
try:
deps = _deps(o, r, it["number"])
except SystemExit:
return None # 讀不到 ≠ 沒有下游;寧可漏報也不要編一筆出來
except Exception:
return None
return (full, it, deps)
from concurrent.futures import ThreadPoolExecutor
with ThreadPoolExecutor(max_workers=12) as ex:
probed = [x for x in ex.map(probe, items) if x]
parents = [x for x in probed if x[2]]
loose = [x for x in parents if is_loose("open", x[2])]
print(f"\n 有下游相依的頂層票:{len(parents)} 張")
print(f" 其中「下游都關了、自己還開著」:**{len(loose)} 張**\n")
if not loose:
print("✅ 一張都沒有——每張頂層票都還有下游在跑,或已經跟著關了。")
for full, it, deps in loose:
n = it["number"]
st = [l["name"] for l in it.get("labels") or []]
who = [a["login"] for a in (it.get("assignees") or [])] or ["(沒有人)"]
print(f" ● {full}#{n} {st} 指派:{'、'.join(who)}")
print(f" {it['title'][:64]}")
for d in deps:
print(f" ☑ {d['repository']['full_name']}#{d['number']}"
f" {d['title'][:52]}")
print(f" → 驗過就關:ticket close {full}#{n} --deliverable <URL>")
print(f" 還缺東西:ticket subtask {full}#{n} --title \"<US>\" -F <檔>")
print()
print("📌 這張表撈的是**機械事實**(相依邊的 state),不是猜文字。")
print(" 走 `ticket close` 關下游時會自動回寫、這張表就不會長;")
print(" 會長出來的都是走側門關掉的那些。")
return loose
CMDS = {"where": cmd_where, "say": cmd_say, "new": cmd_new, "close": cmd_close,
"decide": cmd_decide, "subtask": cmd_subtask, "handoff": cmd_subtask,
"handback": cmd_handback, "mine": cmd_mine, "loose": cmd_loose}
"decide": cmd_decide, "subtask": cmd_subtask, "handback": cmd_handback,
"mine": cmd_mine}
if __name__ == "__main__":
if len(sys.argv) < 2 or sys.argv[1] not in CMDS: