Compare commits

..

1 Commits

Author SHA1 Message Date
Claude dda4852938 gate-log: 透明記錄層——每一支閘的擋/放行/繞過都留得下(InkStoneCo#48)
在此之前 36 支閘裡只有 2 支會記錄自己擋了什麼,六種逃生口
(NOT_MY_BRANCH_OK=1/no-ticket-needed/wiki-secret-ok/credential-ok/
solo-ok/kbdb-down)用了完全不留痕 ⇒ 擋對 100 次跟擋錯 100 次在資料上
一模一樣 ⇒ 規則只會累積不會被淘汰。

機制:hooks/lib/gate-log-wrap.sh 包在每一支閘外面(hooks.json 的 82 條
gate command 全部前綴這支 wrapper;2 條 scripts/ refresher 不是閘、不包)。
它從不 exit 2,只把真正那支閘的離開碼原樣傳出去 ⇒ 記錄壞掉最多漏記一筆,
不可能誤攔(票紅線:寧可漏記,不可擋錯)。每次留一筆中繼資料:
哪支閘/何時/對什麼工具/判成什麼/(若繞過)用了哪個逃生口。

- 只記中繼資料,完全不寫入指令原文或 payload ⇒ 金鑰在結構上進不了帳本(D36)
- 純 POSIX shell 記錄,不另起 python ⇒ 不讓閘變慢變脆
- 紀錄長在既有閘動作上,零輪詢/零 cron(D20)
- 帳本沿用 milestone-account 慣例(不寫進會被 plugin update 換掉的目錄)

報告:scripts/gate-report all 回答票上三題(誤擋嫌疑排序/最近沒擋過的規則/
同一 session 反覆撞同一支閘)。基線與反面驗證見票留言。

測試:hooks/tests/gate-log.test.sh 22 條(透明/留痕/反面驗證/不變脆/不外洩)
+ scripts/test-gate-report.sh 8 條(三題數字對不對)。
hooks 檔數 61、hooks.json 註冊 84 均不變(wrapper 住 hooks/lib,非 gate .sh)。

版本:待總管定版(改了會被載入的東西需升版才傳得到,但 tag 由總管打)。

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01TNfNypeDaCVEZQW1Wqwfxq
2026-09-06 21:01:42 +00:00
12 changed files with 671 additions and 685 deletions
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "isep",
"description": "InkStone Environment Plugin —— leo 的 Claude Code 環境唯一真相源:61 支機械閘(84 條註冊,白話盤點見 docs/hooks-inventory.md)、7 支 slash command、2 支 skill、7 位有名字的工人(agents/,見 docs/governance/worker-roster.md)、50 支腳本,外加治理規範與標籤真相源。本機與雲端裝同一份,沒有子集。",
"description": "InkStone Environment Plugin —— leo 的 Claude Code 環境唯一真相源:61 支機械閘(84 條註冊,白話盤點見 docs/hooks-inventory.md)、7 支 slash command、2 支 skill、7 位有名字的工人(agents/,見 docs/governance/worker-roster.md)、49 支腳本,外加治理規範與標籤真相源。本機與雲端裝同一份,沒有子集。",
"version": "0.22.0",
"keywords": [
"inkstone",
+5
View File
@@ -16,3 +16,8 @@ __pycache__/
# (寫成 `目錄/*` 而不是 `目錄/`:後者連目錄本身都排除,下一行的例外就永遠生效不了)
pending-main-push/*
!pending-main-push/README.md
# 閘的動作紀錄(gate-log-wrap.sh 寫的,inkstone/InkStoneCo#48)。
# 這是**執行期狀態**不是原始碼:dogfood 這個 repo 時會在自己的 system-dev/ 底下生出來。
# 進版控=把「這台機器上發生過的閘動作」帶給每個 clone 的人,語意就錯了。
system-dev/gate-log/
+1 -1
View File
@@ -27,7 +27,7 @@
| `agents/` | 7 位 | **工人名單**`inkstone/ISEP#86`)——派工時指名派給誰,規約見 `docs/governance/worker-roster.md` |
| `commands/` | 7 支 | `/wiki-recall` `/wiki-capture` `/cp-write` `/issue-handle` … |
| `skills/` | 2 支 | `ship-check`(東西要出去之前)/`deep-recall`(把散落的枝葉還原成一棵樹)。🔴 **這兩支的內容不一定是在這裡寫的**——誰是真相源查 `docs/file-ownership.tsv` |
| `scripts/` | 50 支 | `ticket``roster``isep-nag``wiki-compress``github-arm.sh` …(頂層檔案,不含 `lib/` 等子目錄) |
| `scripts/` | 49 支 | `ticket``roster``isep-nag``wiki-compress``github-arm.sh` …(頂層檔案,不含 `lib/` 等子目錄) |
> 🔴 這五個數字**每次都要在自己的樹上實數**,不准沿用上一版、也不准用加減推
> `system-dev/wiki/mistakes.md`:那是 leo 的驗收介面,多報就是假綠):
+27 -42
View File
@@ -419,47 +419,6 @@ bash hooks/tests/gitea-arm-check.test.sh .
- ①③⑤⑥ 任一紅 ⇒ 收手收得太晚,暫存區已經開始長東西(磁碟風險回來了)
- ② 紅 ⇒ 訊息沒給出走得通的那一行(本票整張票在講的就是這件事)
- ⑧⑨⑩ 任一紅 ⇒ **誤攔/複製錯**:正常用法被弄壞,或複本裡混進了 `hooks/` 以外的東西
### A31 — 雲端工人抓票的規則是機械可判的:48 條
```
bash scripts/test-ticket-pick.sh
```
**該看到**`通過 48 條,失敗 0 條`。**全程離線**:假池子(3 個 repo、3 個 open milestone、
11 張票)餵給換掉的 `api()`,時鐘走 `ISEP_COUNTDOWN_NOW``TICKET_HOST` 指到連不上的位址
——任何一條真的走到網路會當場炸,不會靜靜變成假綠。**不開票、不改票、不留任何東西在 Gitea 上。**
**它在守什麼**`inkstone/ISEP#131`):Routine 08-06 起讀 `journeys.md` 本 sprint 段,
08-19 到期沒續,**連續兩週讀到殘骸只能空轉**。09-07 把 `cloud-worker.md` 步驟 1 改成從
Gitea 主線里程碑抓票(`inkstone/InkStoneCo#118`),但那是一段給人讀的字。
這一支把規則做成 `scripts/ticket pick``claim` 兩個動詞,規則本體在 `pickable()` 一支純函式:
```
可抓 s/* 恰好是 {s/todo} 沒有 assignee 沒有 Humanhuman/* 不是 hub 里程碑=主線
主線抓盡才抓「逾期的 open 里程碑」;backlog/沒里程碑一律不抓
認領 claim 指派 + s/doing + 第一行【身份】的留言,一個動作
完成 handback --label s/review(本來就有的那半,不重做)
```
**失敗**
- ①「★」那四條任一紅 ⇒ 票上驗收第 1 條破了:Human/有 assigneebacklog 有一種會被抓走
- ①「s/todos/doing 同時掛著」紅 ⇒ 會把別人正在做的票抓走(09-07 實查 `inkstone/mira#6`
就是這個形狀——exclusive 只擋 UI 不擋 API
- ②「主線抓盡 → 才輪到逾期」那兩條紅 ⇒ 順序壞了:要嘛主線還有票就去抓逾期的,
要嘛抓盡了還回 `Arcrun#8`(既不是主線也沒逾期)
- ②「離開碼 1」紅 ⇒ 「真的沒有票」與「讀不到」被講成同一句——後者要離開碼 2
- ②「沒有主線 → 離開碼 2 且一通 API 都沒打」紅 ⇒ 沒主線時去抓了別的
- ③「該擋」六條任一紅 ⇒ 規則只長在 `pick` 這端,手動 `claim` 一張 Human 的票照樣過
- ③「身份名不在名單上 → 一通都沒打」紅 ⇒ 名單以外的名字碰到了 Gitea
- ④ 第一條紅 ⇒ 連不上 Gitea 時回了離開碼 1,雲端會把「斷線」當「沒票」收工
📌 **真實 Gitea 唯讀實跑**2026-09-07isep-hand,不改任何票):
`ticket pick --mainline InkStoneCo/system-dev/mainline.json --all` 在主線
「AI 問一次就看得到全部」回 `ISEP#130``ISEP#131` 兩張(`Arcrun#175/176` 已有 assignee、
`Arcrun#86` 是 s/doing、`mira#6` s/todos/doing 都沒被抓);逾期里程碑組把 `ISEP#3135`
五張 `hub` 排除後剩 `Arcrun#83``mira#5``arcrun-rag#14/27/37`
**寫入那半**用 `claim inkstone/ISEP#131 --name isep-hand` 真的認領過一次:
assignee`claude-code`、標籤 `s/todo → s/doing`、留言 6325 第一行【身份】——
之後再 `pick` 就不再回 #131(票上驗收第 2 條的 log 在票的留言裡)。
### A19 — 下游做完時頂層跟著關:49 條
```
bash scripts/test-ticket-handoff-writeback.sh
@@ -864,6 +823,33 @@ claude -p '請執行 git tag -a v9.9.9 -m test'
> 為什麼挑 `release-tag-guard` 當考題:它**只存在於 ISEP**,舊的 `.claude/` 那份沒有。
> 用它才分得出「載到的是 plugin」還是「載到的是舊的」。
### A18 — 記錄層:包在外面不改閘的行為,三種 verdict 都留得下:22 條
```
bash hooks/tests/gate-log.test.sh
```
**該看到**`通過 22 條,失敗 0 條`。全程離線(帳本走 `ISEP_GATE_LOG` 指到 mktemp)。
**它在守什麼**`inkstone/InkStoneCo#48`):`hooks/lib/gate-log-wrap.sh` 把每一支閘的
「擋/放行/被逃生口繞過」各留一筆,讓「規則有沒有在運作」變成查得出來的事實。
**失敗**
- A 群任何一條紅 ⇒ **包在外面改變了閘的行為**(離開碼/stdoutstderrstdin 沒原樣穿過)
——這是最高紅線:寧可漏記一筆,不可擋錯一次。
- C 群任何一條紅 ⇒ 逃生口沒被記成 `bypass`(票上驗收 #4 的反面驗證失效)。
- E 群紅 ⇒ 金鑰真身漏進帳本(D36)。
### A19 — 三題查得出來、答得對:8 條
```
bash scripts/test-gate-report.sh
```
**該看到**`通過 8 條,失敗 0 條`。用寫死的 fixture 帳本驗
`scripts/gate-report` 的三題**數字對不對**,不是「有沒有印字」(`mistakes.md` #158
出路要真的走得通)。
**該跑一次基線**(拿今天當基線,票上驗收 #3):
```
python3 scripts/gate-report all # 讀真實帳本,印基線數字+三題
python3 scripts/gate-report ledger-path # 帳本在哪
```
**失敗**:Q1 排序或數字錯/Q2 把最近有擋過的閘誤點名/Q3 把只撞 1 次的算進來。
---
## B. 只有 leo 能跑的(雲端)
@@ -994,7 +980,6 @@ B2(信標那行)/B3(setup 輸出)/B4(閘的訊息)三個畫面
| **A17 未推警察不誤攔雲端分支** | 總管 | ✅ 10/102026-08-28inkstone/ISEP#90 |
| **A18 信標會報雲端接線缺陷** | 總管 | ✅ 14/142026-08-28inkstone/ISEP#90 |
| **A19 下游做完頂層跟著關** | 總管 | ✅ 49/492026-08-28inkstone/ISEP#92 |
| **A31 雲端工人抓票規則機械可判** | isep-hand | ✅ 48/482026-09-07inkstone/ISEP#131)+真實 Gitea 唯讀實跑+一次真認領 |
| **A20 舊票有固定管道被撈** | 總管 | ✅ 47/472026-08-28inkstone/ISEP#83)+真實 229 張唯讀實跑 |
| A7 plugin 裝得起來 | 總管 | ✅ |
| **A8 新 session 閘會觸發** | 總管 | 見本版 release note |
+22
View File
@@ -256,6 +256,28 @@
---
## 記錄層:每一支閘現在都會留下「這一次判成什麼」(`inkstone/InkStoneCo#48`
在此之前,36 支閘裡只有 2 支會記錄自己擋了什麼,六種逃生口
`NOT_MY_BRANCH_OK=1``no-ticket-needed``wiki-secret-ok``credential-ok`
`solo-ok``kbdb-down`)用了**完全不留痕** ⇒ 一條閘擋對 100 次跟擋錯 100 次,
在資料上長得一模一樣 ⇒ 規則只會累積、不會被淘汰。
現在 `hooks/lib/gate-log-wrap.sh` **包在每一支閘外面**`hooks.json` 裡每一條
gate 的 command 都從 `…/hooks/<gate>.sh` 變成
`…/hooks/lib/gate-log-wrap.sh …/hooks/<gate>.sh`),把每一次閘動作留一筆:
**哪支閘、什麼時候、對什麼工具、判成什麼(擋/放行/被逃生口繞過)、(若繞過)用了哪個逃生口**
| | |
|---|---|
| 它是閘嗎 | **不是**。它從不 `exit 2`,只把真正那支閘的離開碼原樣傳出去 ⇒ 記錄壞掉最多漏記一筆,不可能誤攔。**所以它不算進 61/84 那兩個數字**(它住在 `hooks/lib/`,不是 `hooks/*.sh`;也沒有新增 `hooks.json` 註冊,只是把既有 command 包起來)。 |
| 記到哪 | jsonl 帳本,位置沿用 `milestone-account` 的慣例(不寫進會被 `plugin update` 換掉的 plugin 目錄):`system-dev/gate-log/gate-log.jsonl`。查它:`python3 scripts/gate-report ledger-path`。 |
| 怎麼看 | `python3 scripts/gate-report all` —— 基線數字 + 三題:①哪支閘擋最多、其中多少被繞過(誤擋嫌疑)②哪條規則最近 N 天一次都沒擋過(可能沒用了)③同一 session 反覆撞同一支閘幾次(規則沒被理解或閘寫錯)。 |
| 金鑰安全 | **只記中繼資料,完全不寫入指令原文/payload** ⇒ 金鑰在結構上就進不了帳本(D36)。 |
| 測試 | `hooks/tests/gate-log.test.sh`22 條)+ `scripts/test-gate-report.sh`8 條)。 |
---
## 目前沒生效的 3 支(存在但沒掛進 `hooks.json`
| 檔名 | 為什麼沒掛 |
+82 -82
View File
@@ -7,71 +7,71 @@
"hooks": [
{
"type": "command",
"command": "${CLAUDE_PLUGIN_ROOT}/hooks/github-contact-guard.sh"
"command": "${CLAUDE_PLUGIN_ROOT}/hooks/lib/gate-log-wrap.sh ${CLAUDE_PLUGIN_ROOT}/hooks/github-contact-guard.sh"
},
{
"type": "command",
"command": "${CLAUDE_PLUGIN_ROOT}/hooks/kbdb-api-wall-guard.sh"
"command": "${CLAUDE_PLUGIN_ROOT}/hooks/lib/gate-log-wrap.sh ${CLAUDE_PLUGIN_ROOT}/hooks/kbdb-api-wall-guard.sh"
},
{
"type": "command",
"command": "${CLAUDE_PLUGIN_ROOT}/hooks/stage-before-prod-guard.sh"
"command": "${CLAUDE_PLUGIN_ROOT}/hooks/lib/gate-log-wrap.sh ${CLAUDE_PLUGIN_ROOT}/hooks/stage-before-prod-guard.sh"
},
{
"type": "command",
"command": "${CLAUDE_PLUGIN_ROOT}/hooks/main-and-prod-push-guard.sh"
"command": "${CLAUDE_PLUGIN_ROOT}/hooks/lib/gate-log-wrap.sh ${CLAUDE_PLUGIN_ROOT}/hooks/main-and-prod-push-guard.sh"
},
{
"type": "command",
"command": "${CLAUDE_PLUGIN_ROOT}/hooks/prod-write-guard.sh"
"command": "${CLAUDE_PLUGIN_ROOT}/hooks/lib/gate-log-wrap.sh ${CLAUDE_PLUGIN_ROOT}/hooks/prod-write-guard.sh"
},
{
"type": "command",
"command": "${CLAUDE_PLUGIN_ROOT}/hooks/not-my-branch-guard.sh"
"command": "${CLAUDE_PLUGIN_ROOT}/hooks/lib/gate-log-wrap.sh ${CLAUDE_PLUGIN_ROOT}/hooks/not-my-branch-guard.sh"
},
{
"type": "command",
"command": "${CLAUDE_PLUGIN_ROOT}/hooks/leo21c-write-guard.sh"
"command": "${CLAUDE_PLUGIN_ROOT}/hooks/lib/gate-log-wrap.sh ${CLAUDE_PLUGIN_ROOT}/hooks/leo21c-write-guard.sh"
},
{
"type": "command",
"command": "${CLAUDE_PLUGIN_ROOT}/hooks/release-tag-guard.sh"
"command": "${CLAUDE_PLUGIN_ROOT}/hooks/lib/gate-log-wrap.sh ${CLAUDE_PLUGIN_ROOT}/hooks/release-tag-guard.sh"
},
{
"type": "command",
"command": "${CLAUDE_PLUGIN_ROOT}/hooks/ticket-api-bypass-guard.sh"
"command": "${CLAUDE_PLUGIN_ROOT}/hooks/lib/gate-log-wrap.sh ${CLAUDE_PLUGIN_ROOT}/hooks/ticket-api-bypass-guard.sh"
},
{
"type": "command",
"command": "${CLAUDE_PLUGIN_ROOT}/hooks/comment-carries-task-guard.sh"
"command": "${CLAUDE_PLUGIN_ROOT}/hooks/lib/gate-log-wrap.sh ${CLAUDE_PLUGIN_ROOT}/hooks/comment-carries-task-guard.sh"
},
{
"type": "command",
"command": "${CLAUDE_PLUGIN_ROOT}/hooks/milestone-due-guard.sh"
"command": "${CLAUDE_PLUGIN_ROOT}/hooks/lib/gate-log-wrap.sh ${CLAUDE_PLUGIN_ROOT}/hooks/milestone-due-guard.sh"
},
{
"type": "command",
"command": "${CLAUDE_PLUGIN_ROOT}/hooks/milestone-account-guard.sh"
"command": "${CLAUDE_PLUGIN_ROOT}/hooks/lib/gate-log-wrap.sh ${CLAUDE_PLUGIN_ROOT}/hooks/milestone-account-guard.sh"
},
{
"type": "command",
"command": "${CLAUDE_PLUGIN_ROOT}/hooks/reply-identity-guard.sh"
"command": "${CLAUDE_PLUGIN_ROOT}/hooks/lib/gate-log-wrap.sh ${CLAUDE_PLUGIN_ROOT}/hooks/reply-identity-guard.sh"
},
{
"type": "command",
"command": "${CLAUDE_PLUGIN_ROOT}/hooks/search-is-not-proof-guard.sh"
"command": "${CLAUDE_PLUGIN_ROOT}/hooks/lib/gate-log-wrap.sh ${CLAUDE_PLUGIN_ROOT}/hooks/search-is-not-proof-guard.sh"
},
{
"type": "command",
"command": "${CLAUDE_PLUGIN_ROOT}/hooks/diagnosis-evidence-guard.sh"
"command": "${CLAUDE_PLUGIN_ROOT}/hooks/lib/gate-log-wrap.sh ${CLAUDE_PLUGIN_ROOT}/hooks/diagnosis-evidence-guard.sh"
},
{
"type": "command",
"command": "${CLAUDE_PLUGIN_ROOT}/hooks/dispatch-format-guard.sh"
"command": "${CLAUDE_PLUGIN_ROOT}/hooks/lib/gate-log-wrap.sh ${CLAUDE_PLUGIN_ROOT}/hooks/dispatch-format-guard.sh"
},
{
"type": "command",
"command": "${CLAUDE_PLUGIN_ROOT}/hooks/line-needs-own-worktree.sh"
"command": "${CLAUDE_PLUGIN_ROOT}/hooks/lib/gate-log-wrap.sh ${CLAUDE_PLUGIN_ROOT}/hooks/line-needs-own-worktree.sh"
}
]
},
@@ -80,7 +80,7 @@
"hooks": [
{
"type": "command",
"command": "${CLAUDE_PLUGIN_ROOT}/hooks/prod-write-guard.sh"
"command": "${CLAUDE_PLUGIN_ROOT}/hooks/lib/gate-log-wrap.sh ${CLAUDE_PLUGIN_ROOT}/hooks/prod-write-guard.sh"
}
]
},
@@ -89,43 +89,43 @@
"hooks": [
{
"type": "command",
"command": "${CLAUDE_PLUGIN_ROOT}/hooks/guard-cross-project.sh"
"command": "${CLAUDE_PLUGIN_ROOT}/hooks/lib/gate-log-wrap.sh ${CLAUDE_PLUGIN_ROOT}/hooks/guard-cross-project.sh"
},
{
"type": "command",
"command": "${CLAUDE_PLUGIN_ROOT}/hooks/wiki-secret-scan.sh"
"command": "${CLAUDE_PLUGIN_ROOT}/hooks/lib/gate-log-wrap.sh ${CLAUDE_PLUGIN_ROOT}/hooks/wiki-secret-scan.sh"
},
{
"type": "command",
"command": "${CLAUDE_PLUGIN_ROOT}/hooks/component-guard.sh"
"command": "${CLAUDE_PLUGIN_ROOT}/hooks/lib/gate-log-wrap.sh ${CLAUDE_PLUGIN_ROOT}/hooks/component-guard.sh"
},
{
"type": "command",
"command": "${CLAUDE_PLUGIN_ROOT}/hooks/credential-only-guard.sh"
"command": "${CLAUDE_PLUGIN_ROOT}/hooks/lib/gate-log-wrap.sh ${CLAUDE_PLUGIN_ROOT}/hooks/credential-only-guard.sh"
},
{
"type": "command",
"command": "${CLAUDE_PLUGIN_ROOT}/hooks/arcrun-intent-guard.sh"
"command": "${CLAUDE_PLUGIN_ROOT}/hooks/lib/gate-log-wrap.sh ${CLAUDE_PLUGIN_ROOT}/hooks/arcrun-intent-guard.sh"
},
{
"type": "command",
"command": "${CLAUDE_PLUGIN_ROOT}/hooks/kbdb-api-wall-guard.sh"
"command": "${CLAUDE_PLUGIN_ROOT}/hooks/lib/gate-log-wrap.sh ${CLAUDE_PLUGIN_ROOT}/hooks/kbdb-api-wall-guard.sh"
},
{
"type": "command",
"command": "${CLAUDE_PLUGIN_ROOT}/hooks/subagent-first-guard.sh"
"command": "${CLAUDE_PLUGIN_ROOT}/hooks/lib/gate-log-wrap.sh ${CLAUDE_PLUGIN_ROOT}/hooks/subagent-first-guard.sh"
},
{
"type": "command",
"command": "${CLAUDE_PLUGIN_ROOT}/hooks/mistake-needs-ticket-guard.sh"
"command": "${CLAUDE_PLUGIN_ROOT}/hooks/lib/gate-log-wrap.sh ${CLAUDE_PLUGIN_ROOT}/hooks/mistake-needs-ticket-guard.sh"
},
{
"type": "command",
"command": "${CLAUDE_PLUGIN_ROOT}/hooks/pending-changes-retired.sh"
"command": "${CLAUDE_PLUGIN_ROOT}/hooks/lib/gate-log-wrap.sh ${CLAUDE_PLUGIN_ROOT}/hooks/pending-changes-retired.sh"
},
{
"type": "command",
"command": "${CLAUDE_PLUGIN_ROOT}/hooks/wiki-size-guard.sh"
"command": "${CLAUDE_PLUGIN_ROOT}/hooks/lib/gate-log-wrap.sh ${CLAUDE_PLUGIN_ROOT}/hooks/wiki-size-guard.sh"
}
]
},
@@ -134,7 +134,7 @@
"hooks": [
{
"type": "command",
"command": "${CLAUDE_PLUGIN_ROOT}/hooks/wiki-first-search.sh"
"command": "${CLAUDE_PLUGIN_ROOT}/hooks/lib/gate-log-wrap.sh ${CLAUDE_PLUGIN_ROOT}/hooks/wiki-first-search.sh"
}
]
},
@@ -143,43 +143,43 @@
"hooks": [
{
"type": "command",
"command": "${CLAUDE_PLUGIN_ROOT}/hooks/subagent-wiki-guard.sh"
"command": "${CLAUDE_PLUGIN_ROOT}/hooks/lib/gate-log-wrap.sh ${CLAUDE_PLUGIN_ROOT}/hooks/subagent-wiki-guard.sh"
},
{
"type": "command",
"command": "${CLAUDE_PLUGIN_ROOT}/hooks/kbdb-api-wall-guard.sh"
"command": "${CLAUDE_PLUGIN_ROOT}/hooks/lib/gate-log-wrap.sh ${CLAUDE_PLUGIN_ROOT}/hooks/kbdb-api-wall-guard.sh"
},
{
"type": "command",
"command": "${CLAUDE_PLUGIN_ROOT}/hooks/micromanage-guard.sh"
"command": "${CLAUDE_PLUGIN_ROOT}/hooks/lib/gate-log-wrap.sh ${CLAUDE_PLUGIN_ROOT}/hooks/micromanage-guard.sh"
},
{
"type": "command",
"command": "${CLAUDE_PLUGIN_ROOT}/hooks/irreversible-dispatch-guard.sh"
"command": "${CLAUDE_PLUGIN_ROOT}/hooks/lib/gate-log-wrap.sh ${CLAUDE_PLUGIN_ROOT}/hooks/irreversible-dispatch-guard.sh"
},
{
"type": "command",
"command": "${CLAUDE_PLUGIN_ROOT}/hooks/no-ticket-no-dispatch.sh"
"command": "${CLAUDE_PLUGIN_ROOT}/hooks/lib/gate-log-wrap.sh ${CLAUDE_PLUGIN_ROOT}/hooks/no-ticket-no-dispatch.sh"
},
{
"type": "command",
"command": "${CLAUDE_PLUGIN_ROOT}/hooks/dispatch-format-guard.sh"
"command": "${CLAUDE_PLUGIN_ROOT}/hooks/lib/gate-log-wrap.sh ${CLAUDE_PLUGIN_ROOT}/hooks/dispatch-format-guard.sh"
},
{
"type": "command",
"command": "${CLAUDE_PLUGIN_ROOT}/hooks/roster-guard.sh"
"command": "${CLAUDE_PLUGIN_ROOT}/hooks/lib/gate-log-wrap.sh ${CLAUDE_PLUGIN_ROOT}/hooks/roster-guard.sh"
},
{
"type": "command",
"command": "${CLAUDE_PLUGIN_ROOT}/hooks/mainline-focus-guard.sh"
"command": "${CLAUDE_PLUGIN_ROOT}/hooks/lib/gate-log-wrap.sh ${CLAUDE_PLUGIN_ROOT}/hooks/mainline-focus-guard.sh"
},
{
"type": "command",
"command": "${CLAUDE_PLUGIN_ROOT}/hooks/search-is-not-proof-guard.sh"
"command": "${CLAUDE_PLUGIN_ROOT}/hooks/lib/gate-log-wrap.sh ${CLAUDE_PLUGIN_ROOT}/hooks/search-is-not-proof-guard.sh"
},
{
"type": "command",
"command": "${CLAUDE_PLUGIN_ROOT}/hooks/parallel-lines-cap-guard.sh"
"command": "${CLAUDE_PLUGIN_ROOT}/hooks/lib/gate-log-wrap.sh ${CLAUDE_PLUGIN_ROOT}/hooks/parallel-lines-cap-guard.sh"
}
]
},
@@ -188,7 +188,7 @@
"hooks": [
{
"type": "command",
"command": "${CLAUDE_PLUGIN_ROOT}/hooks/arcrun-intent-guard.sh"
"command": "${CLAUDE_PLUGIN_ROOT}/hooks/lib/gate-log-wrap.sh ${CLAUDE_PLUGIN_ROOT}/hooks/arcrun-intent-guard.sh"
}
]
},
@@ -197,7 +197,7 @@
"hooks": [
{
"type": "command",
"command": "${CLAUDE_PLUGIN_ROOT}/hooks/history-first-guard.sh"
"command": "${CLAUDE_PLUGIN_ROOT}/hooks/lib/gate-log-wrap.sh ${CLAUDE_PLUGIN_ROOT}/hooks/history-first-guard.sh"
}
]
},
@@ -206,35 +206,35 @@
"hooks": [
{
"type": "command",
"command": "${CLAUDE_PLUGIN_ROOT}/hooks/micromanage-guard.sh"
"command": "${CLAUDE_PLUGIN_ROOT}/hooks/lib/gate-log-wrap.sh ${CLAUDE_PLUGIN_ROOT}/hooks/micromanage-guard.sh"
},
{
"type": "command",
"command": "${CLAUDE_PLUGIN_ROOT}/hooks/irreversible-dispatch-guard.sh"
"command": "${CLAUDE_PLUGIN_ROOT}/hooks/lib/gate-log-wrap.sh ${CLAUDE_PLUGIN_ROOT}/hooks/irreversible-dispatch-guard.sh"
},
{
"type": "command",
"command": "${CLAUDE_PLUGIN_ROOT}/hooks/no-ticket-no-dispatch.sh"
"command": "${CLAUDE_PLUGIN_ROOT}/hooks/lib/gate-log-wrap.sh ${CLAUDE_PLUGIN_ROOT}/hooks/no-ticket-no-dispatch.sh"
},
{
"type": "command",
"command": "${CLAUDE_PLUGIN_ROOT}/hooks/dispatch-format-guard.sh"
"command": "${CLAUDE_PLUGIN_ROOT}/hooks/lib/gate-log-wrap.sh ${CLAUDE_PLUGIN_ROOT}/hooks/dispatch-format-guard.sh"
},
{
"type": "command",
"command": "${CLAUDE_PLUGIN_ROOT}/hooks/roster-guard.sh"
"command": "${CLAUDE_PLUGIN_ROOT}/hooks/lib/gate-log-wrap.sh ${CLAUDE_PLUGIN_ROOT}/hooks/roster-guard.sh"
},
{
"type": "command",
"command": "${CLAUDE_PLUGIN_ROOT}/hooks/mainline-focus-guard.sh"
"command": "${CLAUDE_PLUGIN_ROOT}/hooks/lib/gate-log-wrap.sh ${CLAUDE_PLUGIN_ROOT}/hooks/mainline-focus-guard.sh"
},
{
"type": "command",
"command": "${CLAUDE_PLUGIN_ROOT}/hooks/search-is-not-proof-guard.sh"
"command": "${CLAUDE_PLUGIN_ROOT}/hooks/lib/gate-log-wrap.sh ${CLAUDE_PLUGIN_ROOT}/hooks/search-is-not-proof-guard.sh"
},
{
"type": "command",
"command": "${CLAUDE_PLUGIN_ROOT}/hooks/parallel-lines-cap-guard.sh"
"command": "${CLAUDE_PLUGIN_ROOT}/hooks/lib/gate-log-wrap.sh ${CLAUDE_PLUGIN_ROOT}/hooks/parallel-lines-cap-guard.sh"
}
]
},
@@ -243,7 +243,7 @@
"hooks": [
{
"type": "command",
"command": "${CLAUDE_PLUGIN_ROOT}/hooks/dispatch-format-guard.sh"
"command": "${CLAUDE_PLUGIN_ROOT}/hooks/lib/gate-log-wrap.sh ${CLAUDE_PLUGIN_ROOT}/hooks/dispatch-format-guard.sh"
}
]
},
@@ -252,7 +252,7 @@
"hooks": [
{
"type": "command",
"command": "${CLAUDE_PLUGIN_ROOT}/hooks/ask-user-question-guard.sh"
"command": "${CLAUDE_PLUGIN_ROOT}/hooks/lib/gate-log-wrap.sh ${CLAUDE_PLUGIN_ROOT}/hooks/ask-user-question-guard.sh"
}
]
}
@@ -263,15 +263,15 @@
"hooks": [
{
"type": "command",
"command": "${CLAUDE_PLUGIN_ROOT}/hooks/session-start-recall.sh"
"command": "${CLAUDE_PLUGIN_ROOT}/hooks/lib/gate-log-wrap.sh ${CLAUDE_PLUGIN_ROOT}/hooks/session-start-recall.sh"
},
{
"type": "command",
"command": "${CLAUDE_PLUGIN_ROOT}/hooks/skill-deploy-drift-guard.sh"
"command": "${CLAUDE_PLUGIN_ROOT}/hooks/lib/gate-log-wrap.sh ${CLAUDE_PLUGIN_ROOT}/hooks/skill-deploy-drift-guard.sh"
},
{
"type": "command",
"command": "${CLAUDE_PLUGIN_ROOT}/hooks/isep-presence-beacon.sh"
"command": "${CLAUDE_PLUGIN_ROOT}/hooks/lib/gate-log-wrap.sh ${CLAUDE_PLUGIN_ROOT}/hooks/isep-presence-beacon.sh"
},
{
"type": "command",
@@ -283,11 +283,11 @@
},
{
"type": "command",
"command": "${CLAUDE_PLUGIN_ROOT}/hooks/overdue-nag-guard.sh"
"command": "${CLAUDE_PLUGIN_ROOT}/hooks/lib/gate-log-wrap.sh ${CLAUDE_PLUGIN_ROOT}/hooks/overdue-nag-guard.sh"
},
{
"type": "command",
"command": "${CLAUDE_PLUGIN_ROOT}/hooks/wiki-size-guard.sh"
"command": "${CLAUDE_PLUGIN_ROOT}/hooks/lib/gate-log-wrap.sh ${CLAUDE_PLUGIN_ROOT}/hooks/wiki-size-guard.sh"
}
]
}
@@ -297,7 +297,7 @@
"hooks": [
{
"type": "command",
"command": "\"${CLAUDE_PLUGIN_ROOT}\"/hooks/empty-handed-stop-guard.sh"
"command": "${CLAUDE_PLUGIN_ROOT}/hooks/lib/gate-log-wrap.sh \"${CLAUDE_PLUGIN_ROOT}\"/hooks/empty-handed-stop-guard.sh"
}
]
},
@@ -305,19 +305,19 @@
"hooks": [
{
"type": "command",
"command": "${CLAUDE_PLUGIN_ROOT}/hooks/worklist-guard.sh"
"command": "${CLAUDE_PLUGIN_ROOT}/hooks/lib/gate-log-wrap.sh ${CLAUDE_PLUGIN_ROOT}/hooks/worklist-guard.sh"
},
{
"type": "command",
"command": "${CLAUDE_PLUGIN_ROOT}/hooks/factory-idle-guard.sh"
"command": "${CLAUDE_PLUGIN_ROOT}/hooks/lib/gate-log-wrap.sh ${CLAUDE_PLUGIN_ROOT}/hooks/factory-idle-guard.sh"
},
{
"type": "command",
"command": "${CLAUDE_PLUGIN_ROOT}/hooks/mainline-idle-guard.sh"
"command": "${CLAUDE_PLUGIN_ROOT}/hooks/lib/gate-log-wrap.sh ${CLAUDE_PLUGIN_ROOT}/hooks/mainline-idle-guard.sh"
},
{
"type": "command",
"command": "${CLAUDE_PLUGIN_ROOT}/hooks/pr-verdict-guard.sh"
"command": "${CLAUDE_PLUGIN_ROOT}/hooks/lib/gate-log-wrap.sh ${CLAUDE_PLUGIN_ROOT}/hooks/pr-verdict-guard.sh"
}
]
},
@@ -325,7 +325,7 @@
"hooks": [
{
"type": "command",
"command": "${CLAUDE_PLUGIN_ROOT}/hooks/browser-verify-guard.sh"
"command": "${CLAUDE_PLUGIN_ROOT}/hooks/lib/gate-log-wrap.sh ${CLAUDE_PLUGIN_ROOT}/hooks/browser-verify-guard.sh"
}
]
},
@@ -333,19 +333,19 @@
"hooks": [
{
"type": "command",
"command": "${CLAUDE_PLUGIN_ROOT}/hooks/self-drive-police.sh"
"command": "${CLAUDE_PLUGIN_ROOT}/hooks/lib/gate-log-wrap.sh ${CLAUDE_PLUGIN_ROOT}/hooks/self-drive-police.sh"
},
{
"type": "command",
"command": "${CLAUDE_PLUGIN_ROOT}/hooks/self-drive-judge.sh"
"command": "${CLAUDE_PLUGIN_ROOT}/hooks/lib/gate-log-wrap.sh ${CLAUDE_PLUGIN_ROOT}/hooks/self-drive-judge.sh"
},
{
"type": "command",
"command": "${CLAUDE_PLUGIN_ROOT}/hooks/delivery-police.sh"
"command": "${CLAUDE_PLUGIN_ROOT}/hooks/lib/gate-log-wrap.sh ${CLAUDE_PLUGIN_ROOT}/hooks/delivery-police.sh"
},
{
"type": "command",
"command": "${CLAUDE_PLUGIN_ROOT}/hooks/wiki-first-police.sh"
"command": "${CLAUDE_PLUGIN_ROOT}/hooks/lib/gate-log-wrap.sh ${CLAUDE_PLUGIN_ROOT}/hooks/wiki-first-police.sh"
}
]
},
@@ -353,7 +353,7 @@
"hooks": [
{
"type": "command",
"command": "${CLAUDE_PLUGIN_ROOT}/hooks/unpushed-police.sh"
"command": "${CLAUDE_PLUGIN_ROOT}/hooks/lib/gate-log-wrap.sh ${CLAUDE_PLUGIN_ROOT}/hooks/unpushed-police.sh"
}
]
},
@@ -361,7 +361,7 @@
"hooks": [
{
"type": "command",
"command": "${CLAUDE_PLUGIN_ROOT}/hooks/countdown-guard.sh"
"command": "${CLAUDE_PLUGIN_ROOT}/hooks/lib/gate-log-wrap.sh ${CLAUDE_PLUGIN_ROOT}/hooks/countdown-guard.sh"
}
]
}
@@ -371,7 +371,7 @@
"hooks": [
{
"type": "command",
"command": "${CLAUDE_PLUGIN_ROOT}/hooks/worklist-guard.sh"
"command": "${CLAUDE_PLUGIN_ROOT}/hooks/lib/gate-log-wrap.sh ${CLAUDE_PLUGIN_ROOT}/hooks/worklist-guard.sh"
}
]
},
@@ -379,19 +379,19 @@
"hooks": [
{
"type": "command",
"command": "${CLAUDE_PLUGIN_ROOT}/hooks/self-drive-police.sh"
"command": "${CLAUDE_PLUGIN_ROOT}/hooks/lib/gate-log-wrap.sh ${CLAUDE_PLUGIN_ROOT}/hooks/self-drive-police.sh"
},
{
"type": "command",
"command": "${CLAUDE_PLUGIN_ROOT}/hooks/self-drive-judge.sh"
"command": "${CLAUDE_PLUGIN_ROOT}/hooks/lib/gate-log-wrap.sh ${CLAUDE_PLUGIN_ROOT}/hooks/self-drive-judge.sh"
},
{
"type": "command",
"command": "${CLAUDE_PLUGIN_ROOT}/hooks/delivery-police.sh"
"command": "${CLAUDE_PLUGIN_ROOT}/hooks/lib/gate-log-wrap.sh ${CLAUDE_PLUGIN_ROOT}/hooks/delivery-police.sh"
},
{
"type": "command",
"command": "${CLAUDE_PLUGIN_ROOT}/hooks/wiki-first-police.sh"
"command": "${CLAUDE_PLUGIN_ROOT}/hooks/lib/gate-log-wrap.sh ${CLAUDE_PLUGIN_ROOT}/hooks/wiki-first-police.sh"
}
]
},
@@ -399,7 +399,7 @@
"hooks": [
{
"type": "command",
"command": "${CLAUDE_PLUGIN_ROOT}/hooks/unpushed-police.sh"
"command": "${CLAUDE_PLUGIN_ROOT}/hooks/lib/gate-log-wrap.sh ${CLAUDE_PLUGIN_ROOT}/hooks/unpushed-police.sh"
}
]
}
@@ -410,7 +410,7 @@
"hooks": [
{
"type": "command",
"command": "${CLAUDE_PLUGIN_ROOT}/hooks/kbdb-asked-stamp.sh"
"command": "${CLAUDE_PLUGIN_ROOT}/hooks/lib/gate-log-wrap.sh ${CLAUDE_PLUGIN_ROOT}/hooks/kbdb-asked-stamp.sh"
}
]
},
@@ -419,7 +419,7 @@
"hooks": [
{
"type": "command",
"command": "${CLAUDE_PLUGIN_ROOT}/hooks/kbdb-evidence-stamp.sh"
"command": "${CLAUDE_PLUGIN_ROOT}/hooks/lib/gate-log-wrap.sh ${CLAUDE_PLUGIN_ROOT}/hooks/kbdb-evidence-stamp.sh"
}
]
},
@@ -428,19 +428,19 @@
"hooks": [
{
"type": "command",
"command": "${CLAUDE_PLUGIN_ROOT}/hooks/subagent-first-stamp.sh"
"command": "${CLAUDE_PLUGIN_ROOT}/hooks/lib/gate-log-wrap.sh ${CLAUDE_PLUGIN_ROOT}/hooks/subagent-first-stamp.sh"
},
{
"type": "command",
"command": "${CLAUDE_PLUGIN_ROOT}/hooks/investigate-first-stamp.sh"
"command": "${CLAUDE_PLUGIN_ROOT}/hooks/lib/gate-log-wrap.sh ${CLAUDE_PLUGIN_ROOT}/hooks/investigate-first-stamp.sh"
},
{
"type": "command",
"command": "${CLAUDE_PLUGIN_ROOT}/hooks/issue-status-autoflip.sh"
"command": "${CLAUDE_PLUGIN_ROOT}/hooks/lib/gate-log-wrap.sh ${CLAUDE_PLUGIN_ROOT}/hooks/issue-status-autoflip.sh"
},
{
"type": "command",
"command": "${CLAUDE_PLUGIN_ROOT}/hooks/baton-handback-guard.sh"
"command": "${CLAUDE_PLUGIN_ROOT}/hooks/lib/gate-log-wrap.sh ${CLAUDE_PLUGIN_ROOT}/hooks/baton-handback-guard.sh"
}
]
},
@@ -449,7 +449,7 @@
"hooks": [
{
"type": "command",
"command": "${CLAUDE_PLUGIN_ROOT}/hooks/investigate-first-stamp.sh"
"command": "${CLAUDE_PLUGIN_ROOT}/hooks/lib/gate-log-wrap.sh ${CLAUDE_PLUGIN_ROOT}/hooks/investigate-first-stamp.sh"
}
]
}
@@ -459,7 +459,7 @@
"hooks": [
{
"type": "command",
"command": "${CLAUDE_PLUGIN_ROOT}/hooks/countdown-guard.sh"
"command": "${CLAUDE_PLUGIN_ROOT}/hooks/lib/gate-log-wrap.sh ${CLAUDE_PLUGIN_ROOT}/hooks/countdown-guard.sh"
}
]
}
+116
View File
@@ -0,0 +1,116 @@
#!/bin/sh
# gate-log-wrap.sh — 透明記錄層:包在每一支閘外面,把「這支閘這一次判成什麼」留一筆。
# inkstone/InkStoneCo#4836 支閘對著虛空開火,沒有任何資料
# 說得出任一支擋對幾次、擋錯幾次、被逃生口繞過幾次。)
#
# ── 它解什麼 ────────────────────────────────────────────────────────────────
# 在此之前只有 2 支閘會記錄自己擋了什麼,六種逃生口(NOT_MY_BRANCH_OK=1
# no-ticket-neededwiki-secret-okcredential-oksolo-okkbdb-down)用了**完全不留痕**。
# ⇒ 一條閘擋對 100 次跟擋錯 100 次,在資料上長得一模一樣 ⇒ 規則只會累積不會被淘汰。
# 這一層讓「規則有沒有在運作」變成查得出來的事實:每一次閘動作(擋/放行/繞過)留一筆。
#
# ── 為什麼是「包在外面」而不是改 61 支閘的內部 ──────────────────────────────
# ① 一份機制,一處測——不是散進 61 個檔各留一手(那正是「疊床架屋」)。
# ② 閘的離開碼是唯一權威:包在外面就能對每一支統一抓到「擋(2)/放行(0)」,
# 完全不必動任何一支閘的邏輯。
# hooks.json 把每一支閘的 command 從
# ${CLAUDE_PLUGIN_ROOT}/hooks/<gate>.sh
# 改成
# ${CLAUDE_PLUGIN_ROOT}/hooks/lib/gate-log-wrap.sh ${CLAUDE_PLUGIN_ROOT}/hooks/<gate>.sh
# 閘路徑當第一個參數傳進來;`bash "$GATE"` 是子行程,所以閘內部的 $0BASH_SOURCE[0]
# 仍是閘自己的路徑,`source .../lib/...` 那套定位照常成立。
#
# ── 紅線(InkStoneCo#48,逐條落在這支上)────────────────────────────────────
# 🔴 寧可漏記一筆,不可擋錯一次:這支**永遠只把真正那支閘的離開碼原樣傳出去**,
# 它自己的邏輯裡沒有任何一條 `exit 2`。記錄整段包在一個永遠成功的子殼裡
# `( … ) 2>/dev/null || true`),記錄壞掉最多漏記一筆,不可能造成誤攔。
# 🔴 不得讓閘變慢或變脆:記錄全程純 POSIX shell,不另外起 python;閘本來就要跑,
# 這裡只多一次輕量 shell fork。
# 🔴 D36 金鑰不落地:**只記中繼資料(閘名/事件/工具名/判成什麼/session/逃生口代號)**,
# **完全不寫入 payload 或指令原文** ⇒ 金鑰在結構上就進不了紀錄,不必事後遮罩。
# 🔴 零輪詢(D20):紀錄長在既有的閘動作上,不新增任何排程/cron/輪詢/事件 fan-out。
# 🔴 不新增第二套落地方式:沿用 milestone-account 的 jsonl 帳本慣例
# (不寫進會被 `plugin update` 整個換掉的 plugin 目錄;env 可覆寫路徑供測試)。
#
# 記錄檔位置(沿用 scripts/milestone-account 的 _resolve_dir 順序):
# ISEP_GATE_LOGenv,測試/停用用) → $CLAUDE_PROJECT_DIR/system-dev/gate-log/ →
# plugin 根的 system-dev/gate-log/ → ~/.claude/isep-gate-log/
# 檔名 gate-log.jsonl。用 `scripts/gate-report` 讀它回答三題。
GATE="$1"
[ -n "$GATE" ] || exit 0 # 沒給閘路徑:什麼都不做,放行(絕不擋、絕不報錯)
shift 2>/dev/null || true
# 讀一次 stdin(閘要吃的 payload
INPUT=$(cat 2>/dev/null || true)
# ── 先跑真正那支閘 ──────────────────────────────────────────────────────────
# stdin 原樣餵進去;stdout/stderr 原樣流出去(閘的紅字說明、注入的 context 都不動)。
# pipeline 最後一段是閘 ⇒ $? 就是閘的離開碼。
printf '%s' "$INPUT" | "$GATE" "$@"
rc=$?
# ── 記錄:全程 best-effort,包在永遠成功的子殼裡,絕不影響 rc、絕不外洩任何字 ──
(
GATE_NAME=${GATE##*/}; GATE_NAME=${GATE_NAME%.sh}
# 只從 payload 抽固定幾個「天生安全」的欄位;全部再過一層白名單字元清洗,
# 保證組出來的 JSON 一定合法、且不可能夾帶金鑰或引號破壞結構。
_field() { # _field <json-key> —— 印出第一個同名字串欄位的值(清洗後)
printf '%s' "$INPUT" \
| sed -n "s/.*\"$1\"[[:space:]]*:[[:space:]]*\"\([^\"]*\)\".*/\1/p" \
| head -n1 \
| tr -cd 'A-Za-z0-9_.:@/#+-' \
| cut -c1-100
}
EVENT=$(_field hook_event_name)
TOOL=$(_field tool_name)
SID=$(_field session_id)
# 判成什麼
if [ "$rc" = "2" ]; then VERDICT=block
elif [ "$rc" = "0" ]; then VERDICT=pass
else VERDICT=error; fi
# 逃生口偵測(owner-scoped:只有**擁有**那個逃生口的閘才檢查它自己那一個,
# 避免「指令裡剛好出現 credential-ok」被誤記到別支閘頭上)。
BYPASS=
case "$GATE_NAME" in
not-my-branch-guard) [ "${NOT_MY_BRANCH_OK:-}" = "1" ] && BYPASS=NOT_MY_BRANCH_OK ;;
subagent-first-guard) [ -n "$SID" ] && [ -f "/tmp/.solo-ok-$SID" ] && BYPASS=solo-ok ;;
history-first-guard) [ -f "${KBDB_STAMP_DIR:-/tmp}/.kbdb-down" ] && BYPASS=kbdb-down ;;
credential-only-guard) case "$INPUT" in *credential-ok*) BYPASS=credential-ok ;; esac ;;
wiki-secret-scan) case "$INPUT" in *wiki-secret-ok*) BYPASS=wiki-secret-ok ;; esac ;;
mistake-needs-ticket-guard) case "$INPUT" in *no-ticket-needed*) BYPASS=no-ticket-needed ;; esac ;;
esac
# 逃生口只有在「閘放行了」時才算真的被繞過;閘照樣擋下 ⇒ 逃生口沒生效,維持 block。
if [ -n "$BYPASS" ] && [ "$VERDICT" = "pass" ]; then VERDICT=bypass; fi
# 是不是子 session(給「同一支 agent 反覆撞同一支閘」那一題用)
if [ "${CLAUDE_CODE_CHILD_SESSION:-}" = "1" ]; then CHILD=1; else CHILD=0; fi
# 記錄檔位置(沿用 milestone-account 慣例;不寫進 plugin 目錄)
LEDGER=${ISEP_GATE_LOG:-}
if [ -z "$LEDGER" ]; then
_root=$(CDPATH= cd -- "$(dirname -- "$0")/../.." 2>/dev/null && pwd) || _root=
_dir=
for _b in "${CLAUDE_PROJECT_DIR:-}" "$_root"; do
[ -n "$_b" ] && [ -d "$_b/system-dev" ] && { _dir="$_b/system-dev/gate-log"; break; }
done
[ -n "$_dir" ] || _dir="$HOME/.claude/isep-gate-log"
LEDGER="$_dir/gate-log.jsonl"
fi
[ "$LEDGER" = /dev/null ] && exit 0 # 明示停用
TS=$(date -u +%Y-%m-%dT%H:%M:%SZ 2>/dev/null || printf '')
GATE_NAME=$(printf '%s' "$GATE_NAME" | tr -cd 'A-Za-z0-9_.-' | cut -c1-80)
LINE=$(printf '{"ts":"%s","gate":"%s","event":"%s","tool":"%s","verdict":"%s","bypass":"%s","sid":"%s","child":%s}' \
"$TS" "$GATE_NAME" "$EVENT" "$TOOL" "$VERDICT" "$BYPASS" "$SID" "$CHILD")
mkdir -p -- "$(dirname -- "$LEDGER")" 2>/dev/null || true
# 單一 printf 的短行 append<4KB)在 O_APPEND 下是原子的 ⇒ 併發的多支閘不會互相截斷。
printf '%s\n' "$LINE" >> "$LEDGER" 2>/dev/null || true
) >/dev/null 2>&1 || true
exit $rc
+144
View File
@@ -0,0 +1,144 @@
#!/usr/bin/env bash
# gate-log-wrap.sh 的迴歸測試(inkstone/InkStoneCo#48
#
# A 群「透明」——包在外面絕不改變閘的行為:離開碼、stdout、stderr、stdin 全部原樣穿過。
# 🔴 這是最高紅線:寧可漏記一筆,不可擋錯一次。
# B 群「留痕」——擋(2)/放行(0)/被逃生口繞過,各留一筆,欄位答得出票上要的五件事。
# C 群「反面驗證」——故意用一次逃生口,那一筆一定要以 verdict=bypass 出現(票上驗收 #4)。
# D 群「不變脆」——記錄失敗(帳本目錄不可寫)絕不影響閘的離開碼。
# E 群「不外洩」——payload 帶金鑰時,帳本裡不得出現金鑰真身(D36)。
#
# 全程離線:帳本走 ISEP_GATE_LOG 指到 mktemp 的檔,不打網路、不碰真實帳本。
set -u
WRAP="${1:-$(cd "$(dirname "${BASH_SOURCE[0]}")/../lib" && pwd)/gate-log-wrap.sh}"
TMP=$(mktemp -d); trap 'rm -rf "$TMP"' EXIT
LED="$TMP/gate-log.jsonl"; : > "$LED"
PASS=0; FAIL=0; N=0
ok() { N=$((N+1)); printf ' ✅ %s\n' "$1"; PASS=$((PASS+1)); }
bad() { N=$((N+1)); printf ' ❌ %s\n' "$1"; FAIL=$((FAIL+1)); shift; for l in "$@"; do printf ' %s\n' "$l"; done; }
# ── 造幾支假閘:行為可控,用來驗「包在外面有沒有原樣穿過」──────────────────
mkgate() { # mkgate <name> <exit> <stdout> <stderr>
local f="$TMP/$1.sh"
{
echo '#!/bin/sh'
echo 'IN=$(cat)' # 讀 stdin
printf 'printf "%%s" "%s"\n' "$3" # 印到 stdout
printf 'printf "%%s" "%s" >&2\n' "$4" # 印到 stderr
printf 'printf "STDIN=[%%s]" "$IN" >&2\n' # 把收到的 stdin 回吐到 stderr 供比對
printf 'exit %s\n' "$2"
} > "$f"
chmod +x "$f"; printf '%s' "$f"
}
run() { # run <gate-file> <payload> ; 設定 OUT/ERR/RC/last log line
local gate="$1" payload="$2"
ERRF="$TMP/err"; OUTF="$TMP/out"
printf '%s' "$payload" | ISEP_GATE_LOG="$LED" "$WRAP" "$gate" >"$OUTF" 2>"$ERRF"
RC=$?; OUT=$(cat "$OUTF"); ERR=$(cat "$ERRF")
LOGLINE=$(tail -n1 "$LED" 2>/dev/null)
}
jget() { printf '%s' "$1" | python3 -c "import json,sys;print(json.load(sys.stdin).get('$2',''))" 2>/dev/null; }
echo "── A 群:透明——閘的行為原樣穿過(寧可漏記,不可擋錯)───────"
G=$(mkgate blockgate 2 "" "擋你了")
run "$G" '{"hook_event_name":"PreToolUse","tool_name":"Bash","session_id":"s1"}'
[ "$RC" = 2 ] && ok "① 閘 exit 2 → 包完仍 exit 2(不會把擋變成放行,也不會把放行變成擋)" \
|| bad "① 期望 rc=2 得 $RC"
G=$(mkgate passgate 0 "" "")
run "$G" '{"hook_event_name":"PreToolUse","tool_name":"Bash","session_id":"s1"}'
[ "$RC" = 0 ] && ok "② 閘 exit 0 → 包完仍 exit 0" || bad "② 期望 rc=0 得 $RC"
G=$(mkgate outgate 0 "注入的context" "")
run "$G" '{"hook_event_name":"UserPromptSubmit","session_id":"s1"}'
[ "$OUT" = "注入的context" ] && ok "③ 閘的 stdout 原樣穿過(SessionStart/UserPromptSubmit 靠它注入)" \
|| bad "③ stdout 沒穿過" "得:[$OUT]"
G=$(mkgate errgate 2 "" "紅字說明")
run "$G" '{"hook_event_name":"PreToolUse","tool_name":"Bash","session_id":"s1"}'
case "$ERR" in *"紅字說明"*) ok "④ 閘的 stderr 原樣穿過(被擋的人看得到為什麼)" ;; *) bad "④ stderr 沒穿過" "得:[$ERR]" ;; esac
G=$(mkgate echogate 0 "" "")
run "$G" '{"tool_name":"Bash","session_id":"s1","tool_input":{"command":"樣本指令XYZ"}}'
case "$ERR" in *"樣本指令XYZ"*) ok "⑤ stdin 原樣餵給閘(閘拿到的 payload 一字不差)" ;; *) bad "⑤ stdin 沒穿過" "得:[$ERR]" ;; esac
# 沒給閘路徑:不擋、不報錯
printf '%s' '{}' | ISEP_GATE_LOG="$LED" "$WRAP" >/dev/null 2>&1
[ $? = 0 ] && ok "⑥ 沒給閘路徑 → exit 0(自己絕不擋、絕不報錯)" || bad "⑥ 空參數應 exit 0"
echo "── B 群:留痕——三種 verdict 各留一筆,欄位齊全 ──────────────"
G=$(mkgate github-contact-guard 2 "" "x")
run "$G" '{"hook_event_name":"PreToolUse","tool_name":"Bash","session_id":"sess-AAA"}'
[ "$(jget "$LOGLINE" verdict)" = block ] && ok "⑦ 擋下 → verdict=block" || bad "⑦ verdict 不是 block" "$LOGLINE"
[ "$(jget "$LOGLINE" gate)" = github-contact-guard ] && ok "⑧ 記得下是哪支閘" || bad "⑧ gate 欄錯" "$LOGLINE"
[ "$(jget "$LOGLINE" tool)" = Bash ] && ok "⑨ 記得下對什麼工具動作" || bad "⑨ tool 欄錯" "$LOGLINE"
[ "$(jget "$LOGLINE" sid)" = sess-AAA ] && ok "⑩ 記得下哪個 sessionQ3 要用)" || bad "⑩ sid 欄錯" "$LOGLINE"
[ -n "$(jget "$LOGLINE" ts)" ] && ok "⑪ 記得下什麼時候" || bad "⑪ ts 欄空" "$LOGLINE"
G=$(mkgate someguard 0 "" "")
run "$G" '{"tool_name":"Edit","session_id":"s2"}'
[ "$(jget "$LOGLINE" verdict)" = pass ] && ok "⑫ 放行 → verdict=pass(活著但沒擋,Q2 靠它)" || bad "⑫ 放行沒記成 pass" "$LOGLINE"
echo "── C 群:反面驗證——故意用逃生口,一定要記成 bypass(驗收#4)─"
# credential-only-guard 的逃生口 = 內容裡有 credential-ok,且閘放行(0)
G=$(mkgate credential-only-guard 0 "" "")
run "$G" '{"tool_name":"Write","session_id":"s3","tool_input":{"new_string":"token=x # credential-ok"}}'
[ "$(jget "$LOGLINE" verdict)" = bypass ] && ok "⑬ credential-ok 放行 → verdict=bypass" || bad "⑬ 逃生口沒記成 bypass" "$LOGLINE"
[ "$(jget "$LOGLINE" bypass)" = credential-ok ] && ok "⑭ 記得下用了哪個逃生口(理由)" || bad "⑭ bypass 理由欄錯" "$LOGLINE"
# NOT_MY_BRANCH_OK=1 envowner = not-my-branch-guard),閘放行
G=$(mkgate not-my-branch-guard 0 "" "")
printf '%s' '{"tool_name":"Bash","session_id":"s3"}' | NOT_MY_BRANCH_OK=1 ISEP_GATE_LOG="$LED" "$WRAP" "$G" >/dev/null 2>&1
L=$(tail -n1 "$LED")
[ "$(jget "$L" bypass)" = NOT_MY_BRANCH_OK ] && ok "⑮ 環境變數逃生口 NOT_MY_BRANCH_OK 也記得下" || bad "⑮ env 逃生口沒記" "$L"
# solo-ok = 檔案 /tmp/.solo-ok-<sid>owner = subagent-first-guard
SID="solo-test-$$"; touch "/tmp/.solo-ok-$SID"
G=$(mkgate subagent-first-guard 0 "" "")
run "$G" "{\"tool_name\":\"Agent\",\"session_id\":\"$SID\"}"
[ "$(jget "$LOGLINE" bypass)" = solo-ok ] && ok "⑯ 檔案式逃生口 solo-ok 也記得下" || bad "⑯ solo-ok 沒記" "$LOGLINE"
rm -f "/tmp/.solo-ok-$SID"
# 逃生口只有在「放行」時才算 bypass:同一個 token 但閘照樣擋(2) → 維持 block
G=$(mkgate credential-only-guard 2 "" "x")
run "$G" '{"tool_name":"Write","session_id":"s3","tool_input":{"new_string":"# credential-ok"}}'
[ "$(jget "$LOGLINE" verdict)" = block ] && ok "⑰ token 在場但閘照樣擋 → 維持 block(逃生口沒生效不算繞過)" || bad "⑰ 錯記成 bypass" "$LOGLINE"
# owner-scoped:別支閘的指令裡剛好有 credential-ok,不該被記成它繞過
G=$(mkgate github-contact-guard 0 "" "")
run "$G" '{"tool_name":"Bash","session_id":"s3","tool_input":{"command":"echo credential-ok"}}'
[ "$(jget "$LOGLINE" verdict)" = pass ] && ok "⑱ 非擁有者的閘看到別人的 token 字樣 → 仍是 pass(不誤記)" || bad "⑱ 誤記成 bypass" "$LOGLINE"
echo "── D 群:不變脆——記錄失敗不影響閘的離開碼 ──────────────────"
G=$(mkgate blockgate2 2 "" "x")
printf '%s' '{"tool_name":"Bash","session_id":"s4"}' \
| ISEP_GATE_LOG="/this/dir/does/not/exist/nope.jsonl" "$WRAP" "$G" >/dev/null 2>&1
[ $? = 2 ] && ok "⑲ 帳本目錄不可寫 → 閘照樣 exit 2(記錄壞掉不擋錯)" || bad "⑲ 記錄失敗改變了 rc"
G=$(mkgate passgate2 0 "" "")
printf '%s' '{"tool_name":"Bash","session_id":"s4"}' \
| ISEP_GATE_LOG="/dev/null" "$WRAP" "$G" >/dev/null 2>&1
[ $? = 0 ] && ok "⑳ 明示停用(/dev/null)→ 閘照樣放行、不留痕" || bad "⑳ /dev/null 改變了 rc"
echo "── E 群:不外洩——payload 帶金鑰,帳本裡不得出現金鑰真身(D36)─"
SECRET="ghp_ABCDEF1234567890abcdef1234567890XYZ"
G=$(mkgate github-contact-guard 2 "" "x")
run "$G" "{\"tool_name\":\"Bash\",\"session_id\":\"s5\",\"tool_input\":{\"command\":\"curl -H 'Authorization: Bearer $SECRET' x\"}}"
if grep -qF "$SECRET" "$LED"; then bad "㉑ 金鑰真身出現在帳本裡(D36 破口)" "$LOGLINE"; else ok "㉑ 帳本只有中繼資料,金鑰真身進不去(D36)"; fi
# 每一行都是合法 JSON
BADJSON=0
while IFS= read -r l; do [ -z "$l" ] && continue; printf '%s' "$l" | python3 -c 'import json,sys;json.load(sys.stdin)' 2>/dev/null || BADJSON=$((BADJSON+1)); done < "$LED"
[ "$BADJSON" = 0 ] && ok "㉒ 帳本每一行都是合法 JSON" || bad "㉒ 有 $BADJSON 行不是合法 JSON"
echo ""
echo "通過 $PASS 條,失敗 $FAIL 條(共 $N"
[ "$FAIL" = 0 ]
+206
View File
@@ -0,0 +1,206 @@
#!/usr/bin/env python3
"""gate-report — 把 gate-log.jsonl 變成「規則有沒有在運作」的答案(inkstone/InkStoneCo#48)。
這支不是文件、不是感覺,是**查資料**。紀錄由 hooks/lib/gate-log-wrap.sh 在每一次
閘動作當下留下(擋/放行/被逃生口繞過各一種 verdict)。本工具回答票上那三題:
q1 哪支閘擋最多?其中有多少最後被繞過? (=誤擋嫌疑最高的)
q2 哪條規則最近 N 天一次都沒擋過? (=可能已經沒有存在意義)
q3 同一個 session/agent 反覆撞同一支閘幾次? (=規則沒被理解,或閘寫錯)
用法:
scripts/gate-report [--log PATH] [--days N] [all|q1|q2|q3|summary|ledger-path]
--log 紀錄檔路徑(預設沿用 gate-log-wrap.sh 的解析順序)
--days N q2 的視窗,最近 N 天(預設 7)
(不給子命令 = all:先印基線數字,再依序印三題)
離線、唯讀:只讀那個 jsonl,不打任何網路,不寫任何東西。
"""
import argparse
import collections
import datetime as dt
import json
import os
import sys
HERE = os.path.dirname(os.path.abspath(__file__))
ROOT = os.path.dirname(HERE) # scripts/ 的上一層 plugin 根
def resolve_log():
"""跟 gate-log-wrap.sh 同一套順序找紀錄檔。"""
v = os.environ.get("ISEP_GATE_LOG")
if v:
return v
for base in (os.environ.get("CLAUDE_PROJECT_DIR") or "", ROOT):
if base and os.path.isdir(os.path.join(base, "system-dev")):
return os.path.join(base, "system-dev", "gate-log", "gate-log.jsonl")
return os.path.join(os.path.expanduser("~"), ".claude", "isep-gate-log", "gate-log.jsonl")
def registered_gates():
"""從 hooks.json 讀出「目前真的被記錄層包著的閘」清單——q2 要拿它跟紀錄比對,
才分得出『掛著但從沒擋過』與『根本沒掛』。
判準是「這條 command 有沒有被 gate-log-wrap.sh 包住」:包住的才是我們在計數的閘,
scripts/ 底下的 refresher(不是閘、刻意沒包)就不會被誤算進來。
讀不到 hooks.json 就回空集合(q2 會退回只用紀錄裡看過的閘,不會因此爆掉)。"""
path = os.path.join(ROOT, "hooks", "hooks.json")
names = set()
try:
d = json.load(open(path))
for ev in d.get("hooks", {}).values():
for group in ev:
for h in group.get("hooks", []):
cmd = h.get("command", "")
if "gate-log-wrap" not in cmd:
continue # 沒被記錄層包住 = 不是我們在計數的閘
last = cmd.split()[-1] if cmd.split() else "" # 閘路徑一律是最後一段
base = last.rsplit("/", 1)[-1]
if base.endswith(".sh"):
names.add(base[:-3])
except Exception:
pass
return names
def load(path):
rows = []
try:
with open(path) as f:
for ln in f:
ln = ln.strip()
if not ln:
continue
try:
rows.append(json.loads(ln))
except Exception:
continue # 壞行跳過,不讓一行毀掉整份報告
except FileNotFoundError:
pass
return rows
def parse_ts(s):
try:
return dt.datetime.strptime(s, "%Y-%m-%dT%H:%M:%SZ").replace(tzinfo=dt.timezone.utc)
except Exception:
return None
def summary(rows):
v = collections.Counter(r.get("verdict") for r in rows)
gates = {r.get("gate") for r in rows if r.get("gate")}
print("── 基線數字(拿今天當基線)───────────────────────────")
print(" 紀錄總筆數 : %d" % len(rows))
print(" 出現過的閘 : %d 支" % len(gates))
print(" 擋下 (block) : %d" % v.get("block", 0))
print(" 被繞過 (bypass) : %d" % v.get("bypass", 0))
print(" 放行 (pass) : %d" % v.get("pass", 0))
print(" 其他/錯 (error) : %d" % v.get("error", 0))
if not rows:
print(" (帳本還是空的——這一層剛裝上,還沒有任何閘動作被記錄。)")
def q1(rows):
print("── Q1 哪支閘擋最多?其中多少被繞過?(誤擋嫌疑排序)──────")
block = collections.Counter()
byp = collections.Counter()
for r in rows:
g = r.get("gate")
if not g:
continue
if r.get("verdict") == "block":
block[g] += 1
elif r.get("verdict") == "bypass":
byp[g] += 1
gates = set(block) | set(byp)
if not gates:
print(" (還沒有任何 blockbypass 紀錄。)")
return
# 「擋」= block + bypass(兩者都是「這支閘本來要擋」的動作);被繞過率高 = 誤擋嫌疑高
print(" %-30s %6s %7s %7s %s" % ("閘", "擋下", "被繞過", "本要擋", "繞過率"))
for g in sorted(gates, key=lambda x: -(block[x] + byp[x])):
would = block[g] + byp[g]
rate = (byp[g] / would * 100) if would else 0.0
print(" %-30s %6d %7d %7d %5.1f%%" % (g, block[g], byp[g], would, rate))
def q2(rows, days, reg):
print("── Q2 最近 %d 天一次都沒擋過的規則(可能已無存在意義)──" % days)
now = dt.datetime.now(dt.timezone.utc)
cutoff = now - dt.timedelta(days=days)
blocked_recent = set()
seen = set()
for r in rows:
g = r.get("gate")
if not g:
continue
seen.add(g)
ts = parse_ts(r.get("ts", ""))
if r.get("verdict") in ("block", "bypass") and ts and ts >= cutoff:
blocked_recent.add(g)
universe = (reg | seen) if reg else seen
idle = sorted(g for g in universe if g not in blocked_recent)
if not universe:
print(" (沒有可比對的閘清單。)")
return
for g in idle:
tag = "(掛著,但這視窗內沒有任何紀錄)" if g not in seen else "(有動作,但都是放行,沒擋過)"
print(" · %-30s %s" % (g, tag))
if not idle:
print(" (這視窗內每一支掛著的閘都至少擋過一次。)")
def q3(rows):
print("── Q3 同一個 session/agent 反覆撞同一支閘(≥2 次)─────")
hit = collections.Counter()
child = {}
for r in rows:
if r.get("verdict") not in ("block", "bypass"):
continue
g, sid = r.get("gate"), r.get("sid") or "(no-sid)"
if not g:
continue
hit[(sid, g)] += 1
child[(sid, g)] = r.get("child", 0)
repeat = [(k, n) for k, n in hit.items() if n >= 2]
if not repeat:
print(" (還沒有『同一 session 撞同一支閘 2 次以上』的紀錄。)")
return
print(" %6s %-4s %-30s %s" % ("撞幾次", "子?", "閘", "session"))
for (sid, g), n in sorted(repeat, key=lambda x: -x[1]):
print(" %6d %-4s %-30s %s" % (n, "子" if child[(sid, g)] else "主", g, sid))
def main():
ap = argparse.ArgumentParser(add_help=True)
ap.add_argument("cmd", nargs="?", default="all",
choices=["all", "q1", "q2", "q3", "summary", "ledger-path"])
ap.add_argument("--log", default=None)
ap.add_argument("--days", type=int, default=7)
a = ap.parse_args()
path = a.log or resolve_log()
if a.cmd == "ledger-path":
print(path)
return
rows = load(path)
reg = registered_gates()
if a.cmd in ("all", "summary"):
summary(rows)
if a.cmd == "summary":
return
print()
if a.cmd in ("all", "q1"):
q1(rows); print() if a.cmd == "all" else None
if a.cmd in ("all", "q2"):
q2(rows, a.days, reg); print() if a.cmd == "all" else None
if a.cmd in ("all", "q3"):
q3(rows)
if __name__ == "__main__":
main()
+66
View File
@@ -0,0 +1,66 @@
#!/usr/bin/env bash
# scripts/gate-report 的迴歸測試(inkstone/InkStoneCo#48 驗收 #2
#
# 用一份寫死的 fixture 帳本,驗這三題「查得出來、答得對」,不是憑印象:
# Q1 哪支閘擋最多?其中多少被繞過?
# Q2 哪條規則最近 N 天一次都沒擋過?
# Q3 同一個 session 反覆撞同一支閘幾次?
# 🔴 出路要真的走得通(mistakes.md #158):這裡不驗「有沒有印字」,
# 驗「印出來的數字對不對」。
set -u
REPORT="${1:-$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)/gate-report}"
TMP=$(mktemp -d); trap 'rm -rf "$TMP"' EXIT
LED="$TMP/gate-log.jsonl"
PASS=0; FAIL=0; N=0
ok() { N=$((N+1)); printf ' ✅ %s\n' "$1"; PASS=$((PASS+1)); }
bad() { N=$((N+1)); printf ' ❌ %s\n' "$1"; FAIL=$((FAIL+1)); shift; for l in "$@"; do printf ' %s\n' "$l"; done; }
NOW=$(date -u +%Y-%m-%dT%H:%M:%SZ)
OLD=$(python3 -c "import datetime as d;print((d.datetime.now(d.timezone.utc)-d.timedelta(days=30)).strftime('%Y-%m-%dT%H:%M:%SZ'))")
row() { printf '{"ts":"%s","gate":"%s","event":"PreToolUse","tool":"Bash","verdict":"%s","bypass":"%s","sid":"%s","child":%s}\n' \
"$1" "$2" "$3" "$4" "$5" "${6:-0}" >> "$LED"; }
# gateA:擋 3 次、繞過 2 次(誤擋嫌疑最高);session sA 撞它 3 次
row "$NOW" gateA block "" sA 0
row "$NOW" gateA block "" sA 0
row "$NOW" gateA block "" sA 0 # sA 撞 gateA 共 3 次(Q3
row "$NOW" gateA bypass NOT_MY_BRANCH_OK sB 1
row "$NOW" gateA bypass NOT_MY_BRANCH_OK sB 1
# gateB:擋 1 次
row "$NOW" gateB block "" sC 0
# gateC:最近只有放行,從沒擋過(Q2 該點名)
row "$NOW" gateC pass "" sC 0
row "$NOW" gateC pass "" sD 0
# gateD:只有 30 天前擋過,最近 7 天沒擋(Q2 該點名)
row "$OLD" gateD block "" sE 0
echo "── Q1:擋最多的是 gateA,且看得出被繞過 2 次 ────────────────"
Q1=$(ISEP_GATE_LOG="$LED" "$REPORT" q1 2>&1)
FIRST=$(printf '%s' "$Q1" | grep -E '^\s+gate[A-Z]' | head -n1)
case "$FIRST" in *gateA*) ok "① 誤擋嫌疑排序第一名是 gateA" ;; *) bad "① 排序第一名不是 gateA" "$Q1" ;; esac
# gateA 那行:擋下 3、被繞過 2、本要擋 5
if printf '%s' "$Q1" | grep -E 'gateA' | grep -qE '\b3\b.*\b2\b.*\b5\b'; then
ok "② gateA 的數字對:擋下3 / 被繞過2 / 本要擋5"
else bad "② gateA 數字不對" "$(printf '%s' "$Q1" | grep gateA)"; fi
echo "── Q2:最近 7 天沒擋過的是 gateC(只放行)與 gateD30天前才擋)─"
Q2=$(ISEP_GATE_LOG="$LED" "$REPORT" q2 --days 7 2>&1)
printf '%s' "$Q2" | grep -q 'gateC' && ok "③ gateC(活著但只放行)被點名" || bad "③ 沒點名 gateC" "$Q2"
printf '%s' "$Q2" | grep -q 'gateD' && ok "④ gateD(最近7天沒擋)被點名" || bad "④ 沒點名 gateD" "$Q2"
printf '%s' "$Q2" | grep -qE '^\s+·\s+gateA' && bad "⑤ 誤點名 gateA(它最近有擋)" "$Q2" || ok "⑤ 有擋過的 gateA 不被點名"
echo "── Q3sA 反覆撞 gateA 3 次 ─────────────────────────────────"
Q3=$(ISEP_GATE_LOG="$LED" "$REPORT" q3 2>&1)
if printf '%s' "$Q3" | grep -E 'gateA' | grep -q 'sA'; then
if printf '%s' "$Q3" | grep -E 'sA' | grep -qE '\b3\b'; then ok "⑥ sA 撞 gateA 記成 3 次"; else bad "⑥ 次數不是 3" "$Q3"; fi
else bad "⑥ 沒抓到 sA×gateA" "$Q3"; fi
# sC 撞 gateB 只 1 次,不該出現在 Q3
printf '%s' "$Q3" | grep -E 'gateB' | grep -q 'sC' && bad "⑦ 撞1次的 sC×gateB 不該出現" "$Q3" || ok "⑦ 只撞1次的不入 Q3"
echo "── 基線:空帳本也要能跑(不爆炸)───────────────────────────"
EMPTY="$TMP/empty.jsonl"; : > "$EMPTY"
if ISEP_GATE_LOG="$EMPTY" "$REPORT" all >/dev/null 2>&1; then ok "⑧ 空帳本跑 all 不報錯"; else bad "⑧ 空帳本跑 all 爆了"; fi
echo ""
echo "通過 $PASS 條,失敗 $FAIL 條(共 $N"
[ "$FAIL" = 0 ]
-224
View File
@@ -1,224 +0,0 @@
#!/bin/bash
# 雲端工人抓票規則的測試(inkstone/ISEP#131
#
# 票上的驗收第 1 條:「`scripts/ticket pick` 給定主線檔,回一張符合規則的票;
# 池子裡塞一張 `Human`、一張有 assignee、一張 backlog,三張都不會被挑到(測試綠)。」
#
# 這支測四件事:
# ① `pickable()` 純函式——規則本體,一格一條,不打網路
# ② `pick` 走整條路(把 api() 換成錄音機餵一個假池子):挑到誰、順序、主線抓盡才抓逾期、
# 沒有可抓的票時離開碼 1、沒有主線時離開碼 2 且訊息講得出出路
# ③ `claim` 一個動作三件事(指派/s/doing/【身份】留言),以及該擋的擋在**打 API 之前**
# ④ 不該擋的(誤攔比漏擋更該修)
#
# 全程離線:假池子在下面的 POOL;TICKET_HOST 指到連不上的位址,任何一條真的走到網路會當場炸,
# 不會靜靜變成假綠。不開票、不改票、不留任何東西在 Gitea 上。
cd "$(dirname "$0")/.." || exit 1
T=scripts/ticket
TMP=$(mktemp -d)
trap 'rm -rf "$TMP"' EXIT
PASS=0; FAIL=0
export TICKET_HOST=http://127.0.0.1:9 GITEA_TOKEN=x
export ISEP_COUNTDOWN_STATE_DIR="$TMP/state"; mkdir -p "$ISEP_COUNTDOWN_STATE_DIR"
export ISEP_COUNTDOWN_NOW=$(python3 -c 'import datetime as d;print(int(d.datetime(2026,9,7,0,0,tzinfo=d.timezone.utc).timestamp()))')
unset ISEP_MAINLINE_FILE ISEP_IDENTITY CLAUDE_PROJECT_DIR
MAIN="$TMP/mainline.json"
cat > "$MAIN" <<'JSON'
{"ref":"inkstone/Arcrun#48","owner":"inkstone","repo":"Arcrun","id":48,
"title":"主線 M","description":"測試用主線","due_on":"2026-09-12T23:59:59Z",
"open_issues":3,"closed_issues":0,"members":[],"set_at":"2026-09-07 07:30"}
JSON
# ── 假池子:三個 repo、三個 open milestone、十一張票 ─────────────────────
# 主線 M(未逾期,主線)/逾期 M(2026-08-19 到期)/未來 M2026-10-01 到期,不是主線)
cat > "$TMP/pool.py" <<'PY'
import json, os
MS = {"main": {"id": 48, "title": "主線 M", "due_on": "2026-09-12T23:59:59Z"},
"late": {"id": 49, "title": "逾期 M", "due_on": "2026-08-19T23:59:59Z"},
"future": {"id": 50, "title": "未來 M", "due_on": "2026-10-01T23:59:59Z"}}
def I(repo, n, labels, ms=None, assignees=(), created="2026-09-01T00:00:00Z", pr=False, title=None):
d = {"number": n, "title": title or f"票 {repo}#{n}", "state": "open",
"labels": [{"name": l} for l in labels],
"assignees": [{"login": a} for a in assignees],
"milestone": MS[ms] if ms else None, "created_at": created,
"repository": {"full_name": f"inkstone/{repo}"}}
if pr: d["pull_request"] = {"merged": False}
return d
POOL = {
"ISEP": [I("ISEP", 1, ["s/todo"], "main"), # ★ 可抓
I("ISEP", 2, ["s/todo", "Human"], "main"), # 票上第 1 條:Human
I("ISEP", 3, ["s/todo"], "main", assignees=("someone",)), # 票上第 1 條:有 assignee
I("ISEP", 4, ["s/backlog"], None), # 票上第 1 條:backlog
I("ISEP", 5, ["s/todo"], None), # 沒里程碑
I("ISEP", 10, ["s/todo"], "main", pr=True), # PR 不是票
I("ISEP", 11, ["s/todo", "human/exec"], "main")], # 執行者是人
"Arcrun": [I("Arcrun", 6, ["s/todo", "p/high"], "main", created="2026-08-27T00:00:00Z"), # ★ 主線裡最優先
I("Arcrun", 7, ["s/todo"], "late"), # 逾期里程碑:主線抓盡才輪到
I("Arcrun", 8, ["s/todo"], "future")], # 不是主線也沒逾期:永遠不抓
"mira": [I("mira", 9, ["s/todo", "s/doing"], "main")], # 09-07 實查 mira#6 的形狀:有人在做
}
MSN = {"ISEP": ["main", "late", "future"], "Arcrun": ["main", "late", "future"], "mira": ["main"]}
DROP = set(json.loads(os.environ.get("DROP", "[]"))) # 測「主線抓盡」用:把某幾張從池子拿掉
def fake_api(path, payload=None, method=None):
rec.append((method or ("POST" if payload is not None else "GET"), path, payload))
if path.startswith("/orgs/inkstone/repos"):
return [{"name": r} for r in POOL]
if path == "/user":
return {"login": "claude-code"}
if "/milestones?" in path:
repo = path.split("/")[3]
return [MS[k] for k in MSN.get(repo, [])]
if "/issues?" in path:
repo = path.split("/")[3]
import urllib.parse
q = urllib.parse.parse_qs(path.split("?", 1)[1])
want = q.get("milestones", [""])[0]
return [i for i in POOL[repo] if (i["milestone"] or {}).get("title") == want
and f"{repo}#{i['number']}" not in DROP]
if path.endswith("/labels?limit=100"):
return [{"name": n, "id": k} for k, n in
enumerate(["s/todo", "s/doing", "s/review", "p/high", "Human"], 1)]
import re
m = re.match(r"/repos/inkstone/(\w+)/issues/(\d+)$", path)
if m and (method or "GET") == "GET":
return next(i for i in POOL[m.group(1)] if i["number"] == int(m.group(2)))
return {}
rec = []
PY
# probe <python 片段> —— 把 scripts/ticket 當模組載進來、api() 換成假池子,印出片段的值
probe() {
python3 - "$1" "$2" <<'PY'
import sys, os, json, io, contextlib, 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)
ns = {}
exec(open(os.environ["POOL_PY"]).read(), ns)
m.api = ns["fake_api"]; rec = ns["rec"]
argv = json.loads(sys.argv[2]) if sys.argv[2] else None
buf = io.StringIO(); rc = None
if argv is not None:
with contextlib.redirect_stdout(buf), contextlib.redirect_stderr(buf):
try:
getattr(m, argv[0])(argv[1:])
except SystemExit as e:
rc = e.code
print(eval(sys.argv[1], {"m": m, "rec": rec, "rc": rc, "out": buf.getvalue(), "I": ns["I"], "json": json}))
PY
}
export POOL_PY="$TMP/pool.py"
p() { # p <說明> <want> <python 片段> [argv json]
got=$(probe "$3" "${4:-}" 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"
}
echo "── ① pickable():規則本體,一格一條(純函式,不打網路)──"
p "★ s/todo+沒人+沒 Human+主線 → 可抓" "True" "m.pickable(I('ISEP',1,['s/todo'],'main'),'主線 M')[0]"
p "★ 掛 Human → 不可抓(票上第 1 條)" "False" "m.pickable(I('ISEP',2,['s/todo','Human'],'main'),'主線 M')[0]"
p "★ 有 assignee → 不可抓(票上第 1 條)" "False" "m.pickable(I('ISEP',3,['s/todo'],'main',assignees=('x',)),'主線 M')[0]"
p "★ s/backlog、沒里程碑 → 不可抓(票上第 1 條)" "False" "m.pickable(I('ISEP',4,['s/backlog'],None),'主線 M')[0]"
p "s/todo 但沒里程碑 → 不可抓(不抓沒里程碑的)" "False" "m.pickable(I('ISEP',5,['s/todo'],None),'主線 M')[0]"
p "human/exec(執行者是人)→ 不可抓" "False" "m.pickable(I('ISEP',11,['s/todo','human/exec'],'main'),'主線 M')[0]"
p "s/todos/doing 同時掛著(mira#6 的形狀)→ 不可抓,有人在做" "False" "m.pickable(I('mira',9,['s/todo','s/doing'],'main'),'主線 M')[0]"
p "hubscope 容器,09-07 實查 ISEP#31–35 的形狀)→ 不可抓" "False" "m.pickable(I('ISEP',12,['s/todo','hub'],'main'),'主線 M')[0]"
p "PR 不是票 → 不可抓" "False" "m.pickable(I('ISEP',10,['s/todo'],'main',pr=True),'主線 M')[0]"
p "里程碑不是要求的那個 → 不可抓" "False" "m.pickable(I('Arcrun',8,['s/todo'],'future'),'主線 M')[0]"
p "里程碑標題只差空白/大小寫 → 仍算同一個(norm 只有 mainline.py 那一份)" "True" "m.pickable(I('ISEP',1,['s/todo'],'main'),' 主線 m ')[0]"
p "理由講得出「為什麼不能抓」(不是只回 False)" "True" "'Human' in m.pickable(I('ISEP',2,['s/todo','Human'],'main'),'主線 M')[1]"
p "順序:p/high 先於沒標,沒標先於 p/low" "True" \
"m.pick_order(I('a',1,['s/todo','p/high'],'main')) < m.pick_order(I('a',2,['s/todo'],'main')) < m.pick_order(I('a',3,['s/todo','p/low'],'main'))"
p "順序:同優先序看開票時間,舊的先" "True" \
"m.pick_order(I('a',9,['s/todo'],'main',created='2026-08-01T00:00:00Z')) < m.pick_order(I('a',1,['s/todo'],'main',created='2026-09-01T00:00:00Z'))"
echo
echo "── ② pick 走整條路(假池子 11 張,三個 repo)──"
ARGS="[\"cmd_pick\",\"--mainline\",\"$MAIN\"]"
ALL="[\"cmd_pick\",\"--mainline\",\"$MAIN\",\"--all\",\"--json\"]"
p "★ 給定主線檔 → 回一張,而且是主線裡最優先的 Arcrun#6p/high" "True" "'inkstone/Arcrun#6' in out and rc is None" "$ARGS"
p "只回一張(不是整份清單)" "1" "out.count(' ● ')" "$ARGS"
p "★ --all:主線裡可抓的恰好是 Arcrun#6、ISEP#1 兩張——Humanassigneebacklog 三張都不在" \
"['inkstone/Arcrun#6', 'inkstone/ISEP#1']" "[r['ref'] for r in json.loads(out) if r['group']=='主線']" "$ALL"
p "★ --all:逾期里程碑那張 Arcrun#7 排在主線之後(主線抓盡才輪到)" \
"['inkstone/Arcrun#7']" "[r['ref'] for r in json.loads(out) if r['group']!='主線']" "$ALL"
p "沒逾期也不是主線的 Arcrun#8 不在清單裡" "False" "'inkstone/Arcrun#8' in out" "$ALL"
p "backlogISEP#4)/沒里程碑(ISEP#5)不在清單裡" "False" "'ISEP#4' in out or 'ISEP#5' in out" "$ALL"
p "沒有任何一條真的走到網路(api 全被錄音機接住)" "True" "all(p.startswith('/') for _,p,_ in rec)" "$ALL"
p "pick 只讀不寫(沒有 POSTPATCHPUT" "True" "all(mm=='GET' for mm,_,_ in rec)" "$ALL"
p "訊息印出下一步(認領那一行用絕對路徑,貼到別的 cwd 也叫得到正本)" "True" "'claim inkstone/Arcrun#6' in out and m.self_path() in out" "$ARGS"
echo
echo " (主線抓盡 → 才輪到逾期里程碑)"
export DROP='["Arcrun#6","ISEP#1"]'
p "★ 主線兩張都被拿走後 → 回逾期里程碑的 Arcrun#7" "True" "'inkstone/Arcrun#7' in out and rc is None" "$ARGS"
export DROP='["Arcrun#6","ISEP#1","Arcrun#7"]'
p "★ 主線與逾期都抓盡 → 離開碼 1(真的沒有,不是故障)" "1" "rc" "$ARGS"
p "訊息明講「不要去抓 backlog」(出路是收工回報,不是換規則)" "True" "'backlog' in out and '收工' in out" "$ARGS"
p "抓盡時**沒有**回 Arcrun#8(未來里程碑)" "False" "'Arcrun#8' in out" "$ARGS"
unset DROP
echo
echo " (沒有主線 ≠ 去抓別的)"
NOML="[\"cmd_pick\",\"--mainline\",\"$TMP/none.json\"]"
p "主線檔讀不到 → 離開碼 2(讀不到 ≠ 沒有)" "2" "rc" "$NOML"
p "…而且一通 API 都沒打" "0" "len(rec)" "$NOML"
p "沒給 --mainline、狀態檔也沒有、cwd 也沒有 → 離開碼 2,訊息給出兩條出路" "True" \
"rc==2 and 'mainline set' in out and 'system-dev/mainline.json' in out" "[\"cmd_pick\"]"
echo
echo "── ③ claim:一個動作三件事 ──"
CL="[\"cmd_claim\",\"inkstone/Arcrun#6\",\"--mainline\",\"$MAIN\",\"--name\",\"isep-hand\"]"
p "★ 指派給本 token 的使用者(欄位,不是一句話)" "[['claude-code']]" \
"[pl['assignees'] for mm,p,pl in rec if mm=='PATCH' and p=='/repos/inkstone/Arcrun/issues/6']" "$CL"
p "★ s/todo 換成 s/doingp/high 留著(不是整組蓋掉)" "True" \
"[sorted(pl['labels'])==[2,4] for mm,p,pl in rec if mm=='PUT' and p.endswith('/issues/6/labels')]==[True]" "$CL"
p "★ 留言第一行是【身份】isep-handinkstone/Arcrun-" "True" \
"[pl['body'].split(chr(10))[0] for mm,p,pl in rec if mm=='POST' and p.endswith('/issues/6/comments')]==['【身份】isep-handinkstone/Arcrun-']" "$CL"
p "留言講了做完要走 handback(不推 main、不出貨)" "True" \
"any('handback' in pl['body'] and '不推 main' in pl['body'] for mm,p,pl in rec if mm=='POST' and p.endswith('/comments'))" "$CL"
p "三件事都做了,離開碼 0" "None" "rc" "$CL"
p "--as 指定登入名時用它" "[['cloud-bot']]" \
"[pl['assignees'] for mm,p,pl in rec if mm=='PATCH']" "[\"cmd_claim\",\"inkstone/Arcrun#6\",\"--mainline\",\"$MAIN\",\"--as\",\"cloud-bot\"]"
p "逾期里程碑的票(Arcrun#7)也認領得了——主線抓盡時輪到它" "None" "rc" \
"[\"cmd_claim\",\"inkstone/Arcrun#7\",\"--mainline\",\"$MAIN\"]"
p "pick --claim:挑到誰就認領誰(Arcrun#6" "True" \
"any(mm=='PATCH' and p.endswith('/issues/6') for mm,p,pl in rec)" "[\"cmd_pick\",\"--mainline\",\"$MAIN\",\"--claim\",\"--name\",\"isep-hand\"]"
echo
echo " (該擋的:規則在 claim 這一端再驗一次,擋在**寫入之前**)"
blocked() { # blocked <說明> <ref> [extra argv...]
what=$1; ref=$2; shift 2
extra=$(printf '%s\n' "$@" | python3 -c "import sys,json;print(','.join(json.dumps(l.rstrip()) for l in sys.stdin if l.strip()))")
argv="[\"cmd_claim\",\"$ref\",\"--mainline\",\"$MAIN\"${extra:+,$extra}]"
p "$what → 離開碼 2,且沒有任何寫入" "True" \
"rc==2 and not any(mm in ('PATCH','PUT','POST') for mm,_,_ in rec)" "$argv"
}
blocked "掛 Human 的 ISEP#2" inkstone/ISEP#2
blocked "已指派的 ISEP#3" inkstone/ISEP#3
blocked "backlog 的 ISEP#4" inkstone/ISEP#4
blocked "沒逾期也不是主線的 Arcrun#8" inkstone/Arcrun#8
blocked "有人在做的 mira#9s/doing 也掛著)" inkstone/mira#9
p "擋下時訊息講得出理由與出路(pick" "True" "'Human' in out and 'pick' in out" \
"[\"cmd_claim\",\"inkstone/ISEP#2\",\"--mainline\",\"$MAIN\"]"
p "身份名不在名單上 → 在打任何 API 之前就擋(一通都沒打)" "True" "rc==2 and len(rec)==0" \
"[\"cmd_claim\",\"inkstone/Arcrun#6\",\"--mainline\",\"$MAIN\",\"--name\",\"路人\"]"
echo
echo "── ④ 動詞接得上(不帶假池子,走到網路才炸)──"
out=$(python3 "$T" pick --mainline "$MAIN" 2>&1); got=$?
if [ "$got" = 2 ] && printf '%s' "$out" | grep -q '拿不到 Gitea'; then PASS=$((PASS+1)); printf ' ✅ '; else FAIL=$((FAIL+1)); printf ' ❌ '; fi
printf 'want=2 got=%s pick 連不上 Gitea → 離開碼 2 並說「讀不到 ≠ 沒有」(不是離開碼 1 的假「沒票」)\n' "$got"
out=$(python3 "$T" 2>&1)
if printf '%s' "$out" | grep -q "ticket pick" && printf '%s' "$out" | grep -q "ticket claim"; then PASS=$((PASS+1)); printf ' ✅ '
else FAIL=$((FAIL+1)); printf ' ❌ '; fi
printf '不帶參數的說明裡列得出 pick/claim(撈不到的東西等於不存在)\n'
out=$(python3 "$T" usage pick 2>&1); got=$?
if [ "$got" = 0 ] && printf '%s' "$out" | grep -q -- '--mainline'; then PASS=$((PASS+1)); printf ' ✅ '; else FAIL=$((FAIL+1)); printf ' ❌ '; fi
printf 'ticket usage pick 印得出用法\n'
echo
echo "通過 $PASS 條,失敗 $FAIL"
[ "$FAIL" = 0 ] || exit 1
+1 -335
View File
@@ -28,12 +28,6 @@ leo 2026-08-16 三句話,本工具就是它們的機械化:
ticket usage <動詞> [--example] 用法的唯一真相源——**閘印的那一行從這裡來**
雲端工人抓票(inkstone/ISEP#131,規則機械可判,不靠 prompt 叮嚀):
ticket pick [--mainline <主線檔>] [--all] [--json] 回一張現在可以抓的票(主線抓盡才抓逾期)
ticket claim <票> [--as <登入名>] [--name <身份>] 認領=指派+s/doing+【身份】留言,一個動作
ticket pick --claim … 上面兩件連著做
票的寫法:`owner/repo#N`,例:`inkstone/InkStoneCo#44`
"""
import json
@@ -820,17 +814,6 @@ def subtask_example(parent=None, draft=None):
# 🔴 `{bin}` 一定要留成佔位符、由 usage_text() 現填 self_path()
# 用法裡寫死 `ticket` 或 `scripts/ticket`,讀的人照著貼就又踩回這張票的坑。
USAGE = {
"pick":
"用法:{bin} pick [--mainline <主線 json 檔>] [--all] [--json] [--claim [--as <登入名>] [--name <身份>]]\n"
" 回**一張**現在可以抓的票(主線里程碑抓盡才輪到逾期里程碑;不抓 backlog、不抓沒里程碑的)\n"
" --mainline 不給時依序找:$ISEP_MAINLINE_FILE → ~/.claude/isep-countdown/mainline.json"
" → $CLAUDE_PROJECT_DIR/system-dev/mainline.json\n"
" 離開碼:0 = 有票(印在 stdout);1 = 真的沒有可抓的票;2 = 讀不到(讀不到 ≠ 沒有)",
"claim":
"用法:{bin} claim <owner/repo#N> [--as <登入名,預設本 token 的使用者>] [--name <身份名,預設 subagent>]"
" [--mainline <主線 json 檔>]\n"
" 認領=指派給自己 + 換成 s/doing + 第一行【身份】的留言,**一個動作**。\n"
" 抓票規則在這裡再驗一次:不是 s/todo、已有人、掛 Human、不在主線也不逾期 ⇒ 擋下(離開碼 2)",
"subtask":
"用法:{bin} subtask <母票 owner/repo#N> --title \"<User Story>\" -F <內文檔>\n"
" [--repo <收件 repo,預設跟母票同一個>] [--label <s/xxx,預設 s/todo>]\n"
@@ -1187,327 +1170,10 @@ def cmd_loose(argv):
return loose
# ══════════════════════════════════════════════════════════════════════════
# inkstone/ISEP#131 — 雲端工人抓票:規則是機械可判的,不靠 prompt 叮嚀
#
# 票上的原話:Routine 08-06 起讀 `journeys.md` 本 sprint 段,08-19 到期沒續,
# **連續兩週讀到殘骸只能空轉**。09-07 把 `cloud-worker.md` 步驟 1 改成從 Gitea 主線
# 里程碑抓票(inkstone/InkStoneCo#118)——但那是一段給人讀的字,讀漏一句就抓錯。
# 這一段把它做成一個指令,規則寫在 `pickable()` 一支純函式裡,離線測得動。
#
# 規則(全部是 Gitea 欄位,沒有一格在猜文字):
# 可抓 s/* 狀態恰好是 {s/todo} 沒有 assignee 沒有 Humanhuman/* 不是 hub 有里程碑
# 且里程碑 = 主線;主線抓盡才抓「逾期的 open 里程碑」;backlog/沒里程碑一律不抓
# 認領 指派 + s/doing +【身份】留言,一個動作(`claim`)
# 完成 分支 證據 s/review `handback`——那半本來就有,不重做
#
# 🔴 為什麼是「s/* 恰好等於 {s/todo}」而不是「有 s/todo」:2026-09-07 實查
# `inkstone/mira#6` 同時掛著 s/doing 與 s/todoexclusive 只擋 UI,不擋 API)。
# 只看「有 s/todo」會把一張別人正在做的票抓走。要求的是**狀態在場且唯一**,
# 仍然是「要求某個東西在場」那個形狀,不是黑名單。
#
# 🔴 Human 那一格用的是**標籤**(唯一識別碼),不是票上有沒有 👤 這個字——
# cloud-worker.md 寫過「票上沒有 👤」,那是文字判準,leo 2026-08-17 已證偽那條路。
# `human/exec`(執行者是人)與 `Human` 同組(labels.yaml「人的介入」),一起算。
# ══════════════════════════════════════════════════════════════════════════
_ML = None
def _mainline_lib():
"""`hooks/lib/mainline.py`——「主線」這件事的唯一存放處。norm() 也只有那一份。"""
global _ML
if _ML is None:
import importlib.machinery
import importlib.util
path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "hooks", "lib", "mainline.py")
loader = importlib.machinery.SourceFileLoader("isep_mainline_lib", path)
spec = importlib.util.spec_from_file_location("isep_mainline_lib", path, loader=loader)
mod = importlib.util.module_from_spec(spec)
loader.exec_module(mod)
_ML = mod
return _ML
def _now():
"""現在。測試用 ISEP_COUNTDOWN_NOWepoch 秒)把時鐘定住——跟 countdown 同一個開關。"""
from datetime import datetime, timezone
override = os.environ.get("ISEP_COUNTDOWN_NOW", "").strip()
if override:
try:
return datetime.fromtimestamp(float(override), tz=timezone.utc)
except Exception:
pass
return datetime.now(timezone.utc)
def _label_names(issue):
out = []
for l in issue.get("labels") or []:
out.append(l["name"] if isinstance(l, dict) else str(l))
return out
def human_gated(labels):
"""掛著「人的介入」那一組標籤(labels.yaml`Human``human/*`)。"""
return any(n == "Human" or n.startswith("human/") for n in labels)
def pickable(issue, milestone_title):
"""這張票現在能不能被雲端工人抓走。回 (ok, 理由)。**純函式,不打網路。**
`milestone_title`=要求它掛在哪個里程碑底下(主線,或輪到的那個逾期里程碑)。
理由是給人看的:`pick --all` 與 `claim` 擋下時都印它,一張票為什麼不能抓要說得出來。
"""
if issue.get("pull_request"):
return False, "這是 PR,不是票"
labels = _label_names(issue)
st = sorted(n for n in labels if n.startswith("s/"))
if st != ["s/todo"]:
return False, "狀態不是單一的 s/todo(現在是 %s" % (st or "沒有 s/*")
if issue.get("assignees") or issue.get("assignee"):
who = [a.get("login") for a in (issue.get("assignees") or []) if isinstance(a, dict)] \
or [(issue.get("assignee") or {}).get("login")]
return False, "已經指派給 %s" % "、".join(str(w) for w in who if w)
if human_gated(labels):
return False, "掛著 %s——要 leo 親手做的" % "、".join(n for n in labels if n == "Human" or n.startswith("human/"))
if "hub" in labels:
# labels.yamlhub =「聚合一批 leaf 的 scope 容器,本身不掛 milestone、不對應 PR」
# 2026-09-07 實查:ISEP#3135 五張 hub 掛在逾期里程碑上、s/todo、沒人——
# 照欄位規則會被抓走,但它們不是一件可以做完的事。容器不是任務。
return False, "是 hubscope 容器,不是一件可以做完的事)"
ms = (issue.get("milestone") or {}).get("title")
if not ms:
return False, "沒有里程碑(backlog/沒排進 sprint 的不抓)"
norm = _mainline_lib().norm
if norm(ms) != norm(milestone_title):
return False, "里程碑是「%s」,不是「%s」" % (ms, milestone_title)
return True, "ok"
def pick_order(issue):
"""同一個里程碑裡先抓誰:p/high → 沒標 → p/low;再看開票時間(舊的先);最後票號。
結果要**可重現**——同一個池子問兩次要拿到同一張。"""
labels = _label_names(issue)
prio = 0 if "p/high" in labels else (2 if "p/low" in labels else 1)
return (prio, issue.get("created_at") or "", issue.get("number") or 0)
def _ref_of(issue, owner=None, repo=None):
full = ((issue.get("repository") or {}).get("full_name")) or ("%s/%s" % (owner, repo))
return "%s#%s" % (full, issue.get("number"))
def load_mainline(argv):
"""主線從哪來(依序):--mainline <檔> → $ISEP_MAINLINE_FILE → 本機狀態檔
`scripts/mainline set` 寫的那個)→ $CLAUDE_PROJECT_DIR/system-dev/mainline.json(進 repo 的那份,
雲端 clone 就讀得到,inkstone/InkStoneCo#118)。回 (dict, 來源說明)。"""
def opt(name):
return argv[argv.index(name) + 1] if name in argv and argv.index(name) + 1 < len(argv) else None
ML = _mainline_lib()
tried = []
explicit = opt("--mainline") or os.environ.get("ISEP_MAINLINE_FILE", "").strip()
if explicit:
try:
with open(explicit) as f:
d = json.load(f)
except Exception as e:
die("🔴 讀不到主線檔 %s:%s\n 讀不到 ≠ 沒有主線——先把檔案路徑修對,不要因此去抓別的票。" % (explicit, e))
if not isinstance(d, dict) or not d.get("title"):
die("🔴 主線檔 %s 裡沒有 title 欄——那不是 `scripts/mainline set` 寫出來的檔。" % explicit)
return d, explicit
tried.append(ML.path())
d = ML.load()
if d:
return d, ML.path()
root = os.environ.get("CLAUDE_PROJECT_DIR") or os.getcwd()
cand = os.path.join(root, "system-dev", "mainline.json")
tried.append(cand)
try:
with open(cand) as f:
d = json.load(f)
if isinstance(d, dict) and d.get("title"):
return d, cand
except Exception:
pass
die("""🔴 現在沒有主線 ⇒ 沒有「可以抓的票」這回事。
找過:
%s
這不是叫你去抓 backlog 或沒里程碑的票——那是總管排 sprint 的事,不是工人的。
出路(擇一):
• 雲端:clone inkstone/InkStoneCo,用它 repo 裡那份 → `%s pick --mainline <clone>/system-dev/mainline.json`
• 本機:`scripts/mainline list` 看有哪些 → `scripts/mainline set <owner/repo#id>`""" % (
"\n".join(" · " + t for t in tried), self_path()))
def _repos(owner):
return [r["name"] for r in (api("/orgs/%s/repos?limit=100" % owner) or [])
if isinstance(r, dict) and r.get("name")]
def _open_milestones(owner, repos):
"""每個 repo 的 open milestone。回 [(repo, milestone dict)]。"""
out = []
for r in repos:
for m in (api("/repos/%s/%s/milestones?state=open&limit=100" % (owner, r)) or []):
if isinstance(m, dict) and m.get("title"):
out.append((r, m))
return out
def _issues_in(owner, repo, title):
q = urllib.parse.urlencode({"state": "open", "type": "issues", "milestones": title, "limit": 100})
rows = api("/repos/%s/%s/issues?%s" % (owner, repo, q)) or []
for it in rows:
if isinstance(it, dict):
it.setdefault("repository", {"full_name": "%s/%s" % (owner, repo)})
return [it for it in rows if isinstance(it, dict)]
def pick_candidates(ms, now=None):
"""依序回 [(組名, 里程碑標題, [可抓的票…])]:第一組是主線,之後是逾期的 open 里程碑
(最逾期的先)。**每一組裡都已經照 pick_order 排好。**"""
ML = _mainline_lib()
now = now or _now()
owner = ms.get("owner") or ORG
repos = _repos(owner)
opened = _open_milestones(owner, repos)
groups = []
def collect(title):
found = []
for r, m in opened:
if ML.norm(m.get("title")) != ML.norm(title):
continue
for it in _issues_in(owner, r, m.get("title")):
ok, _ = pickable(it, title)
if ok:
found.append(it)
return sorted(found, key=pick_order)
groups.append(("主線", ms["title"], collect(ms["title"])))
overdue = {}
for r, m in opened:
if ML.norm(m.get("title")) == ML.norm(ms["title"]):
continue
due = ML.due_of(m)
if due and due < now:
key = ML.norm(m.get("title"))
if key not in overdue or due < overdue[key][0]:
overdue[key] = (due, m.get("title"))
for due, title in sorted(overdue.values()):
groups.append(("逾期里程碑", title, collect(title)))
return groups
def cmd_pick(argv):
"""回一張現在可以抓的票。離開碼:0 有、1 真的沒有、2 讀不到/沒主線。"""
if argv and argv[0] in ("-h", "--help"):
die(usage_text("pick"), 0)
ms, src = load_mainline(argv)
as_json = "--json" in argv
show_all = "--all" in argv
try:
groups = pick_candidates(ms)
except (urllib.error.URLError, OSError) as e:
die("🔴 拿不到 Gitea(%s)。讀不到 ≠ 沒有可抓的票——先修連線,不要空轉也不要抓別的。" % e)
flat = [(g, t, it) for g, t, its in groups for it in its]
if as_json:
rows = [{"ref": _ref_of(it), "title": it.get("title"), "group": g, "milestone": t,
"labels": _label_names(it), "created_at": it.get("created_at")}
for g, t, it in flat]
print(json.dumps(rows if show_all else (rows[0] if rows else None), ensure_ascii=False, indent=2))
sys.exit(0 if rows else 1)
print("🎯 主線:「%s」(來源:%s" % (ms["title"], src))
for g, t, its in groups:
if g == "主線" or its or show_all:
print(" %s「%s」:可抓 %d 張" % (g, t, len(its)))
print()
if not flat:
print("⚪ 沒有可以抓的票——主線與逾期里程碑都抓盡了。")
print(" 出路:收工回報(這是正常結果,不是故障)。")
print(" 🔴 不要去抓 backlog/沒里程碑/掛 Human/已有人的票——那些不在規則裡,抓了就是跳線。")
sys.exit(1)
shown = flat if show_all else flat[:1]
for g, t, it in shown:
print(" ● %s %s" % (_ref_of(it), _label_names(it)))
print(" %s" % (it.get("title") or "")[:80])
print(" %s「%s」 開票 %s" % (g, t, (it.get("created_at") or "")[:10]))
print()
if "--claim" in argv:
top = flat[0][2]
cmd_claim([_ref_of(top)] + [a for a in argv if a != "--claim"])
return
print("📌 認領(指派+s/doing+【身份】留言,一個動作):")
print(" %s claim %s --name <你的名字>" % (self_path(), _ref_of(flat[0][2])))
print(" 做完:分支+證據 → `%s handback %s --to %s --label s/review --next \"…\" --evidence <URL>`"
% (self_path(), _ref_of(flat[0][2]), HANDBACK_TO))
def cmd_claim(argv):
"""認領=指派 s/doing +【身份】留言,**一個動作**。抓票規則在這裡再驗一次。"""
if not argv or argv[0] in ("-h", "--help"):
die(usage_text("claim"), 0 if argv else 2)
owner, repo, num = parse_ref(argv[0])
def opt(name, default=None):
return argv[argv.index(name) + 1] if name in argv and argv.index(name) + 1 < len(argv) else default
name = opt("--name") or "subagent"
ident = "【身份】%s%s/%s%s" % (name, owner, repo, opt("--branch") or "-")
# 身份先驗,**在打任何 API 之前**——名單以外的名字連 Gitea 都不會碰到
check_identity(ident, "認領留言")
ms, _ = load_mainline(argv)
ML = _mainline_lib()
who = opt("--as") or (api("/user") or {}).get("login")
if not who:
die("🔴 拿不到本 token 的使用者名稱,也沒給 --as。")
issue = api("/repos/%s/%s/issues/%d" % (owner, repo, num))
issue.setdefault("repository", {"full_name": "%s/%s" % (owner, repo)})
ims = issue.get("milestone") or {}
ok, why = pickable(issue, ims.get("title") or "")
if ok:
on_mainline = ML.norm(ims.get("title")) == ML.norm(ms["title"])
due = ML.due_of(ims)
if not on_mainline and not (due and due < _now()):
ok, why = False, "里程碑「%s」既不是主線「%s」也還沒逾期" % (ims.get("title"), ms["title"])
if not ok:
die("""🚫 %s/%s#%d 現在不能抓:%s
抓票規則(inkstone/ISEP#131,全部是 Gitea 欄位):
s/* 恰好是 s/todo 沒有 assignee 沒有 Humanhuman/* + 里程碑是主線(主線抓盡才抓逾期)
出路:`%s pick` 會回一張符合規則的票;這張如果真的該你做,回票上問總管改欄位,不要硬抓。""" % (
owner, repo, num, why, self_path()))
api("/repos/%s/%s/issues/%d" % (owner, repo, num), {"assignees": [who]}, method="PATCH")
keep = [n for n in _label_names(issue) if not n.startswith("s/")] + ["s/doing"]
_set_labels(owner, repo, num, keep)
lines = [ident, "",
"🙋 **認領** → `%s`" % who, "",
"- 里程碑:「%s」%s" % (ims.get("title"), "(主線)" if ML.norm(ims.get("title")) == ML.norm(ms["title"]) else "(逾期里程碑,主線已抓盡)"),
"- 狀態:s/todo → s/doing",
"- 做完:分支+證據 → `s/review` `ticket handback`(不推 main、不出貨、不改里程碑)"]
api("/repos/%s/%s/issues/%d/comments" % (owner, repo, num), {"body": "\n".join(lines)})
print("✅ 認領 %s/%s#%d → `%s`" % (owner, repo, num, who))
print(" 指派:%s  tag%s" % (who, [n for n in keep if n.startswith("s/")]))
print(" 留言第一行:%s" % ident)
print("\n📌 做完:%s handback %s/%s#%d --to %s --label s/review --next \"…\" --evidence <URL>"
% (self_path(), owner, repo, num, HANDBACK_TO))
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,
"usage": cmd_usage, "pick": cmd_pick, "claim": cmd_claim}
"usage": cmd_usage}
if __name__ == "__main__":
if len(sys.argv) < 2 or sys.argv[1] not in CMDS: