Compare commits

..

8 Commits

Author SHA1 Message Date
claude-code d301810fb6 merge main(#98 下游做完時頂層跟著關),我的那節再讓一次編號
衝突只有 docs/TESTING.md 一列:#92 也用了 A19 ⇒ 我改成 A20,並把整節搬到 A19 後面。
(今天 main 上 A16、A17 各被佔兩次、A19 被佔兩次——編號撞是這條線的常態,
  讓號的成本比要求別人改小,所以一律我讓。)

plugin.json 的腳本數在合併後的樹上重數 40 → 43:
  main v0.13.0 那個「40」= `ls scripts | wc -l`(37 檔+3 目錄),
  合併後同一算法 = 43:+2 是本 PR,+1 是 #98 帶進來的 test-ticket-handoff-writeback.sh
  (#98 併進 main 時沒有回頭改這個數字)。版本號沒動(0.13.0)。
2026-08-28 00:58:49 +00:00
claude-code e575786be3 merge main(定版 v0.13.0),衝突只有 plugin.json 一行
版本號取 main 的 0.13.0(我不定版)。description 的腳本數在合併後的樹上重數:
  main 那個「40」= `ls scripts | wc -l`(37 個檔+3 個子目錄)
  合併後同一個算法 = 42(多的兩個是本 PR 的 debt-worklist 與 test-debt-worklist.sh)
  ⇒ 40 → 42。閘的兩個數字沒變(hooks/*.sh = 54、hooks.json "command": = 71,本 PR 沒新增 hook)
2026-08-28 00:55:30 +00:00
claude-code 5d6c4b5d63 Merge pull request '下游做完時頂層跟著關(inkstone/ISEP#92)' (#98) from feat/handoff-writeback-loose into main 2026-08-28 00:54:27 +00:00
claude-code 45adc10a52 併進 main(v0.12.0)並接上「主線唯一答案」(inkstone/ISEP#83)
衝突只有 docs/TESTING.md 一處,兩邊都留:
  main 的 A16(gate-ok)/A17(未推警察)/A18(信標)原樣保留,
  我那節改編號成 A19——main 上 A16、A17 已經被 #90#99 各佔一次,不動別人的。

接上 inkstone/ISEP#82 帶進來的 hooks/lib/mainline.py(不自己養第二套判斷):
  · 有標主線 ⇒ 只排除「屬於主線那一條」的票;掛在**別條** milestone 的仍算債
    (那條線現在沒有人在推,正是它躺著的原因)
  · 沒標主線 ⇒ 退回保守做法:掛 open milestone 的一律不領,並在清單上照實說沒標
  · 別條 milestone 已逾期 ⇒ +15「答應過人家的日期已經過了」

測試 40 → 47 條(+7 條全給主線這段),並把 ISEP_COUNTDOWN_STATE_DIR 也隔離:
不然這支測試的結果會取決於「這台機器現在標了哪條主線」。

盤點數字在合併後的樹上重數:
  hooks/*.sh = 54、hooks.json "command": = 71(本 PR 沒新增 hook,兩個都沒變)
  scripts 一層檔案 = 39(本 PR +2)⇒ plugin.json description 37→39
  版本號沒動(0.12.0,總管統一定版)
2026-08-28 00:51:06 +00:00
claude-code 87678a8a87 Merge pull request '定版 v0.13.0(現在的主線是哪一個,有唯一答案)' (#102) from chore/v0.13.0 into main 2026-08-28 00:49:13 +00:00
claude-code 07cb5e4e55 併進 main(#96 雲端接線/#100 v0.12.0/#99 主線唯一),解 TESTING.md 撞號(inkstone/ISEP#92)
唯一衝突在 docs/TESTING.md:兩條線各自加了一節、**都叫 A16**。
兩邊內容都留,我這一節改成 A19(main 已用掉 A16/A17/A18),
「目前狀態」表的那一列跟著搬到 A18 後面。

main 側本來就有的 A11/A12/A14/A15 重號**沒有動**——那是它兩條線各自編的,
不是這次造成的,動它會把 diff 炸開。

沒有碰的:.claude-plugin/plugin.json(維持 main 的 v0.12.0,版本由總管統一定)、
hooks/hooks.json、docs/hooks-inventory.md——這三個檔本線一個字都沒改,
自動合併拿到的就是 main 那份。

盤點數字在合併後的樹上重數(不是相加、不是抄別人的):
  hooks/*.sh 54 hooks.json 註冊 71 commands 7 skills 2 scripts 頂層 38
docs/hooks-inventory.md 寫的 54/71 **是對的**;README 寫的 48/59/23
**三個都錯**,已改成實數,並把「怎麼重數」的指令寫進去——
這種數字會漂是因為沒人知道它怎麼來的。

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_016ZBu4Sa1cGntKFRBYNZ6xs
2026-08-28 00:48:49 +00:00
claude-code 67f5f0fa5e 舊票每天有固定管道被撈出來(inkstone/ISEP#83)
leo 2026-08-27:「現在每天都在追新的,所以要用 Routine 去消化舊的,可以有多個條件」

兩條線各用各的判準(他當場訂正的那件事):
  緊急線=掛 open milestone 的,用「距離目標的遠近」排
  還債線=沒掛的那 188 張,用多條件排(事故/擋人/承諾/票齡/估工)← 本次做的

新增 scripts/debt-worklist(list/claim/forget):
  · 撈全 org 15 個 repo 的 open issue + open PR,逐一列出當作「我查了哪些」的證明
  · 扣掉掛 open milestone 的(緊急線在管)、等 leo 的(Human/human-exec/s/stage,
    那些要催不是要領,催辦是 inkstone/ISEP#93)、已領走的
  · 每張票旁邊印出「為什麼排這裡」的分項,排錯可以指著某一項說它給太多
  · 成包只認強訊號:互相指著、或 Gitea 原生相依(母子票)。
    第一版用單向引用成包,190 張裡 121 張黏成一坨——一包沒有人領得動
  · 空清單會明講「查詢跑過了,結果是零」,不默默結束
  · claim 之後那些票不再出現在清單上,並在隔天的清單頂端交代它們關了沒

hooks/session-start-recall.sh 加一段(不打網路,只看狀態檔日期):
  今天還沒撈過就說一句,並給出要跑的那一行。開 session 自動去撈=輪詢,紅線擋著。

測試 scripts/test-debt-worklist.sh:40 條全離線,票上四條驗收條件各一組。
真實資料唯讀實跑過:229 張 → 可領 188 張/185 包,領走兩張後隔天清單少掉它們。
2026-08-28 00:38:02 +00:00
claude-code f3a41fba0e 下游做完時頂層跟著關(inkstone/ISEP#92)
票上的病:「開在頂層的票,下游做完了卻沒人回來關⋯⋯頂層票會永遠掛著,
而 leo 是看頂層的。」缺的三格是 journey 標籤、雙向連結的強制、完工回寫。

不重造既有的(票上明列):`ticket where` 戳記+側門閘(查票防重複)、
`comment-carries-task-guard`(留言藏任務)、Gitea 原生 issue dependency
(跨 repo 關聯的載體)——這一版全部長在它們上面。

四格,判準全部是機械事實(相依邊在不在、state 是什麼),沒有一格在猜文字:

① 雙向連結(驗收 1):`subtask`/新別名 `handoff` 一個動作同時掛原生相依
   + 在頂層票的時間軸貼一則指回下游的留言。相依邊只長在側欄,
   時間軸上什麼都沒有,跨 repo 時尤其看不出來。

② 完工回寫(驗收 2,最痛的那格):`ticket close` 關完子票立刻問 `/blocks`
   (誰在等我),對每張還開著的頂層票貼回寫留言;下游全關的那一張再
   指派回總管+改 s/review。**不自動關母票**——關票要有交付物、要有人看過,
   默默關掉跟默默留著是同一個病的兩面。

③ journey 標籤:`--journey <名>` 把 `j/<名>` 同時貼在母子兩端(只貼一端就
   聚不起來)。標籤不存在就擋下並指回 labels.yaml——要求標籤在場,
   不是猜哪些名字合法。labels.yaml 的 `j/` 段刻意留空:旅程怎麼切、叫什麼
   名字是方向題,不由工具代決。

④ 撈得出來(驗收 3、4):新動詞 `ticket loose` 掃 org 的 open 票,撈
   「有下游相依、下游全關、自己還開著」的頂層票。這是 ② 的補網——
   關票的側門(直接 PATCH state=closed)是刻意放行的,漏掉的由這張網撈回來。
   不是輪詢,掛在開場/收工對帳跑一次。

實跑(2026-08-28,唯讀,沒動任何票):245 張 open 票裡 17 張有下游相依,
其中 2 張是「下游都關了、自己還開著」——inkstone/arcrun-rag#136(已 s/review
且指派給 claude-code,正在被處理)與 inkstone/Arcrun#100(沒標籤、沒指派,
就是票上講的那種「永遠掛著」)。

測試:scripts/test-ticket-handoff-writeback.sh,49 條全綠,全程離線
(會打 API 的兩段把 api() 換成錄音機,不開票不關票不留測試票)。
回歸:A13 17/17、A4 24/24、A12 11/11 皆綠。
文件:docs/TESTING.md 新增 A16。

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_016ZBu4Sa1cGntKFRBYNZ6xs
2026-08-28 00:31:35 +00:00
9 changed files with 1493 additions and 9 deletions
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "isep",
"description": "InkStone Environment Plugin —— leo 的 Claude Code 環境唯一真相源:54 支機械閘(71 條註冊,白話盤點見 docs/hooks-inventory.md)、7 支 slash command、2 支 skill、40 支腳本,外加治理規範與標籤真相源。本機與雲端裝同一份,沒有子集。",
"description": "InkStone Environment Plugin —— leo 的 Claude Code 環境唯一真相源:54 支機械閘(71 條註冊,白話盤點見 docs/hooks-inventory.md)、7 支 slash command、2 支 skill、43 支腳本,外加治理規範與標籤真相源。本機與雲端裝同一份,沒有子集。",
"version": "0.13.0",
"keywords": [
"inkstone",
+15 -2
View File
@@ -23,10 +23,23 @@
| | 數量 | 是什麼 |
|---|---|---|
| `hooks/` | 48 `hooks.json` | 全部機械閘(PreToolUseStopSubagentStopSessionStartPostToolUse 共 59 條註冊`ISEP#60` 移除 `claim-verify-police.sh``subagent-claim-worksheet.sh` 這對自造機制,改由 Gitea 原生三格承接見 `ISEP#59` |
| `hooks/` | 54 支 `hooks.json` | 全部機械閘(PreToolUseStopSubagentStopSessionStartPostToolUse 共 71 條註冊。**一支一行的白話盤點在 `docs/hooks-inventory.md`,那裡才是這兩個數字的家** |
| `commands/` | 7 支 | `/wiki-recall` `/ship-check` `/cp-write` … |
| `skills/` | 2 支 | |
| `scripts/` | 23 支 | `ticket``github-arm.sh``gitea-bootstrap.sh` … |
| `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` 開頭記著同一個病)。
**不放**`.env`(金鑰,違 D36「金鑰只有一個家」)、`wiki/``docs/``_archive/`
——那些是**知識**不是**環境**。
+80
View File
@@ -268,6 +268,84 @@ bash hooks/tests/isep-presence-beacon.test.sh
- ⑤⑦ 紅 ⇒ 舊複本遮蔽正門抓不到(`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 的
```
@@ -475,6 +553,8 @@ B2(信標那行)/B3(setup 輸出)/B4(閘的訊息)三個畫面
| **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 |
+27
View File
@@ -144,6 +144,33 @@ 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"
+20
View File
@@ -101,6 +101,26 @@ 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
@@ -0,0 +1,559 @@
#!/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:]))
+222
View File
@@ -0,0 +1,222 @@
#!/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
@@ -0,0 +1,274 @@
#!/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
+295 -6
View File
@@ -21,8 +21,10 @@ 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`
"""
@@ -452,10 +454,87 @@ def cmd_close(argv):
if deliv:
api(f"/repos/{owner}/{repo}/issues/{num}/comments",
{"body": f"{os.environ.get('ISEP_IDENTITY') or f'【身份】總管/{owner}/{repo}-'}\n\n✅ 結案。交付物:{deliv}"})
{"body": f"{_identity(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 ───────────────────────────────────────────────────────────────
@@ -526,6 +605,10 @@ 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")}
@@ -545,6 +628,97 @@ 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 原生相依。
@@ -565,7 +739,9 @@ 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"
" [--assign <誰做> --next \"<他第一件事要做什麼>\"] ← 指派了就一定要寫下一步")
" [--journey <旅程名>] ← 這件事服務哪條使用者旅程(對不上就不要加)\n"
" [--assign <誰做> --next \"<他第一件事要做什麼>\"] ← 指派了就一定要寫下一步\n"
"\n`ticket handoff` 是同一個動作的別名:頂層票 → 下游 repo)")
powner, prepo, pnum = parse_ref(argv[0])
def opt(name, default=None):
@@ -585,10 +761,13 @@ def cmd_subtask(argv):
" leo 2026-08-27:『每個事情沒有歷史記錄才是大問題』,\n"
" 而沒寫驗收條件的票,關掉之後就沒有歷史,只剩一個關字)")
repo = opt("--repo", prepo)
# `--to <repo>` 是 `ticket handoff` 那個名字底下比較自然的講法,同一個東西。
# handback 的 `--to` 是「交給誰」,subtask 沒有那個參數,不會撞。)
repo = opt("--repo", opt("--to", 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"
@@ -597,7 +776,8 @@ def cmd_subtask(argv):
body = (f"Parent: {powner}/{prepo}#{pnum}\n"
f"> 這張票是從母票的討論串裡長出來的一件事。\n"
f"> **它沒關,母票關不掉**(Gitea 原生相依,實測 412 硬擋)。\n\n") + body
f"> **它沒關,母票關不掉**(Gitea 原生相依,實測 412 硬擋)。\n"
f"> **它關掉時,母票會收到一則回寫**(`ticket close` 自動做,見 `inkstone/ISEP#92`)。\n\n") + body
d = api(f"/repos/{ORG}/{repo}/issues", {"title": title, "body": body})
cnum = d["number"]
@@ -619,6 +799,38 @@ 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 "☑"
@@ -747,9 +959,86 @@ 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, "handback": cmd_handback,
"mine": cmd_mine}
"decide": cmd_decide, "subtask": cmd_subtask, "handoff": cmd_subtask,
"handback": cmd_handback, "mine": cmd_mine, "loose": cmd_loose}
if __name__ == "__main__":
if len(sys.argv) < 2 or sys.argv[1] not in CMDS: