現在的主線是哪一個,變成一個查得到的事實(inkstone/ISEP#82)

14 個 open milestone 同時亮著,其中「Mira 現代化」同名活在 5 個 repo,
所以 SOP 說的「那個 active milestone」在現場沒有指涉對象。

- hooks/lib/mainline.py        主線的唯一存放處(一個檔放得下一條),從不打網路
- scripts/mainline             show/list/set/clear/refresh/adopt/has
- hooks/mainline-focus-guard.sh 派了不在主線上的票 ⇒ 攔一次,問補收還是跳線
- hooks/lib/countdown.py       ⏱ 那一行的主線改讀「被標定的」,蓋過「期限最近」的猜測
- hooks/countdown-guard.sh     同一個注入點加第二行 🎯(ISEP#63 那半不動)
- 測試 24 條(離線)+ countdown 原有 20 條仍全綠
This commit is contained in:
Claude Code
2026-08-28 00:30:09 +00:00
committed by Claude
parent dbd7c8c874
commit 21971ea83e
7 changed files with 1020 additions and 12 deletions
+18 -3
View File
@@ -64,12 +64,27 @@ try:
except Exception:
raise SystemExit(0) # 算不出來就不出聲,不要讓它變成噪音
# 第二行:現在的主線是哪一個(inkstone/ISEP#82)。
# 同一個注入點的兩行,來源不同:⏱ 算時間,🎯 讀被標定的主線。
# 算不出來也一定回一句話(「現在沒有主線」),所以這裡不需要 fallback;
# 真的整支壞掉(import 失敗)才留白——一行注入不該讓整個 session 停下來。
try:
ml = cd._mainline().line()
except Exception:
ml = ""
ctx = (
stamp + "\n\n"
"🔴 這一行是 ISEP 的倒數(inkstone/ISEP#63)。**把它原樣放在你這則回覆的最前面**,"
stamp + "\n"
+ (ml + "\n" if ml else "")
+ "\n"
"🔴 第一行是 ISEP 的倒數(inkstone/ISEP#63)。**把它原樣放在你這則回覆的最前面**,"
"數字不要自己重算、也不要改寫措辭——它是機器算的,你算的會漂。\n"
"leo 整天上課、一天只看兩眼:沒有這行,他就不知道『這件事還來得及嗎』。\n"
"收工前這一回合若沒有戴上它,Stop 那一半會擋一次要你補。"
"收工前這一回合若沒有戴上它,Stop 那一半會擋一次要你補。\n\n"
"🎯 第二行是**現在的主線**inkstone/ISEP#82)——leo:「14 個里程碑同時亮著"
"卻不知道該看哪個」。它是你這回合的判準:**手上這件事在不在那條線上**。\n"
"不在,就當場說清楚是『補收』(它本來就該在主線上)還是『跳線』(真的插件事),"
"不要默默做完。主線的名字已經在第一行的倒數裡,戴上倒數=主線也一起到了 leo 眼前。"
)
print(json.dumps({
"hookSpecificOutput": {
+46 -6
View File
@@ -27,6 +27,13 @@ leo 2026-08-28 07:40:「今天我整天上課……**下午四點左右**希
從快取檔讀,**這支從不打網路**UserPromptSubmit 走在每一則訊息的關鍵路徑上,
在那裡打網路 = 每一句話都先等一次 HTTP。快取由 SessionStart 那支負責更新
`scripts/countdown-milestone-refresh.sh`),拿不到就整段不顯示,不編數字。
🔴 **來源有兩個,優先序寫死(inkstone/ISEP#82**
① **被標定的主線**`hooks/lib/mainline.py``scripts/mainline set` 寫的)—— 優先
② 期限最近的那一個(`milestone-due` 快取,`countdown-milestone-refresh.sh` 寫的)
② 是**猜**出來的(「最近到期的大概就是在做的那個」),而 ISEP#82 的整件事就是
「那個 active milestone」在 14 個裡沒有指涉對象。⇒ 一旦有人真的標了主線,
就不准再用猜的那個蓋過它。兩個都沒有 ⇒ 整段不顯示。
"""
import json
import os
@@ -137,10 +144,40 @@ def deadline(now: datetime) -> datetime:
return d
def milestone() -> "tuple[str, datetime] | None":
"""主線 milestone 的期限。快取檔一行:`YYYY-MM-DD|<名稱>`。沒有就沒有。"""
def _mainline():
"""借 `hooks/lib/mainline.py` 讀「被標定的主線」。拿不到就當沒有(fail-open)。
刻意用檔案路徑載入而不是 `import mainline`:本檔自己也是被
`spec_from_file_location` 載進去的,`sys.path` 裡沒有 `hooks/lib`。
"""
try:
import importlib.util
p = os.path.join(os.path.dirname(os.path.abspath(__file__)), "mainline.py")
spec = importlib.util.spec_from_file_location("isep_mainline", p)
mod = importlib.util.module_from_spec(spec)
spec.loader.exec_module(mod)
return mod
except Exception:
return None
def milestone() -> "tuple[str, datetime | None] | None":
"""主線 milestone 的期限。優先讀被標定的主線,其次讀「期限最近」的快取。
快取檔一行:`YYYY-MM-DD|<名稱>`。兩個都沒有就沒有(回 None,整段不顯示)。
期限可能是 None(被標定的主線沒設期限)——那時只說名字,不編一個日期。
"""
raw = os.environ.get("ISEP_MILESTONE_DUE", "").strip()
name = os.environ.get("ISEP_MILESTONE_NAME", "").strip()
if not raw:
mod = _mainline()
if mod is not None:
try:
seg = mod.countdown_segment()
except Exception:
seg = None
if seg:
return seg
if not raw:
p = os.path.join(state_dir(), "milestone-due")
try:
@@ -184,11 +221,14 @@ def line(session_id: str, transcript_path: str) -> str:
ms = milestone()
if ms:
name, due = ms
gap = due - now
if gap.total_seconds() >= 0:
parts.append("主線 %s%s" % (name, human(gap)))
if due is None:
parts.append("主線 %s(沒設期限)" % name)
else:
parts.append("🔴 主線 %s 已逾期 %s" % (name, human(gap)))
gap = due - now
if gap.total_seconds() >= 0:
parts.append("主線 %s%s" % (name, human(gap)))
else:
parts.append("🔴 主線 %s 已逾期 %s" % (name, human(gap)))
return "".join(parts)
+248
View File
@@ -0,0 +1,248 @@
#!/usr/bin/env python3
"""hooks/lib/mainline.py —— 「現在的主線是哪一個」這件事的**唯一存放處**。
這是 helper,不是閘(inkstone/ISEP#40 S7`lib/` 底下的東西不算一支手寫的閘)。
三個呼叫者共用它,所以「主線是誰」的答案只有一份:
· `scripts/mainline` —— 人問「現在的主線是哪一個」
· `hooks/lib/countdown.py` —— 每一則回覆眼前那一行的第二段
· `hooks/mainline-focus-guard.sh` —— 派了一張不屬於主線的票就攔一次
── 為什麼要有這個檔(inkstone/ISEP#82)──────────────────────────────
2026-08-27 實查:`GET /repos/inkstone/*/milestones?state=open` 回 **14 個**
其中「Mira 現代化」這個名字同時活在 5 個 repo,還有 5 個已經逾期。
SOP 說「有 active milestone 時只做該 milestone 的事」——但**「那個」在現場沒有指涉對象**。
leo 的原話是「**14 個里程碑同時亮著卻不知道該看哪個**」。
⇒ 要解的不是「milestone 太多」(跨 repo 同名是既有做法,v0.6.0 §4SOP S7-4),
要解的是「**這一刻我在做哪一條**」沒有答案。
⇒ 所以這個檔的形狀就是答案的形狀:**一個檔,放得下一條**。
沒有清單、沒有優先序、沒有「前三名」——被覆蓋掉的那條就不再是主線。
問「現在的主線是哪一個」永遠只會拿到 0 或 1 個答案,不會拿到 14 個。
── 主線是一個「名字」,錨在一個具體的 milestone 上 ──────────────────
Gitea 的 milestone 不能跨 repo,而同一條線常常同時開在 5 個 repo(票上實查)。
所以:
· **錨**anchor)= `owner/repo#<milestone id>`:期限、進度、目標宣告都讀它
· **成員判定** 票所屬 milestone 的**標題**與主線標題相同(不分 repo)
⇒ 「同名跨 repo」照舊能用,而「現在在做哪一條」仍然只有一個答案。
── 這支從不打網路 ────────────────────────────────────────────────
它被 `UserPromptSubmit` 用(每一則訊息的關鍵路徑)。在那裡打 HTTP = 每講一句話
都先等一次網路。網路那一半全部在 `scripts/mainline`setrefreshadopt),
本支只讀寫 state 檔。讀不到 ⇒ 回「沒有主線」,**不編一條出來**。
"""
import json
import os
from datetime import datetime, timedelta, timezone
TAIPEI = timezone(timedelta(hours=8))
MARKER = "🎯"
STATE_NAME = "mainline.json"
JUMP_LOG = "mainline-jumps.jsonl"
def state_dir() -> str:
"""與倒數共用同一個狀態目錄——兩行字是同一個注入點的兩半,狀態不該分家。"""
d = os.environ.get("ISEP_COUNTDOWN_STATE_DIR", "").strip()
if not d:
d = os.path.join(os.path.expanduser("~"), ".claude", "isep-countdown")
try:
os.makedirs(d, exist_ok=True)
except Exception:
pass
return d
def path() -> str:
return os.path.join(state_dir(), STATE_NAME)
def load():
"""讀主線。沒有/壞掉 ⇒ None(=現在沒有主線),**不是例外**。
「沒有主線」是一個正常狀態,不是故障:ISEP#82 驗收第 4 條寫死了
「沒有任何主線時不能整組壞掉」。所以這支從不 raise。
"""
try:
with open(path()) as f:
d = json.load(f)
except Exception:
return None
if not isinstance(d, dict) or not d.get("title"):
return None
return d
def save(d) -> bool:
try:
with open(path(), "w") as f:
json.dump(d, f, ensure_ascii=False, indent=2)
return True
except Exception:
return False
def clear() -> bool:
try:
os.remove(path())
return True
except FileNotFoundError:
return True
except Exception:
return False
def parse_ts(raw):
if not isinstance(raw, str) or not raw.strip():
return None
s = raw.strip().replace("Z", "+00:00")
try:
dt = datetime.fromisoformat(s)
except Exception:
try:
dt = datetime.fromisoformat(s + "T23:59:59+08:00")
except Exception:
return None
return dt if dt.tzinfo else dt.replace(tzinfo=timezone.utc)
def due_of(ms):
return parse_ts((ms or {}).get("due_on") or "")
def norm(s) -> str:
"""比對標題用。只做「看不見的差異」的正規化——大小寫與空白。
🔴 刻意不做同義詞、不做模糊比對:主線是**被指定的**,不是被猜出來的。
猜錯的方向是「把不屬於主線的票放行」,那正是這張票要擋的事。
"""
return "".join((s or "").split()).lower()
def ref_of(ms) -> str:
if not ms:
return ""
return "%s/%s#%s" % (ms.get("owner") or "?", ms.get("repo") or "?", ms.get("id") or "?")
def members(ms):
return set(ms.get("members") or []) if ms else set()
def belongs(ticket_ref, ms, ticket_milestone_title=None):
"""這張票屬不屬於主線?回 True/FalseNone。
None = **不知道**(快取裡沒有這張票,而呼叫端也沒查到它的 milestone)。
🔴 「不知道」不等於「不屬於」——這條分界就是誤攔與否的分水嶺。
呼叫的閘拿到 None 時該放行(本 repo 心法第 2 條:誤攔比漏擋更該修)。
"""
if not ms:
return True # 沒有主線 ⇒ 沒有「不屬於主線」這回事
ref = (ticket_ref or "").strip()
if ref and ref in members(ms):
return True
if ticket_milestone_title is not None:
return norm(ticket_milestone_title) == norm(ms.get("title"))
return None
def fixture_titles():
"""測試用:把「去 Gitea 問這張票掛在哪」換成一份現成的答案。
`ISEP_MAINLINE_FIXTURE` 指向一個 JSON`{"owner/repo#N": "milestone 標題"}`。
設了它,閘就不打網路,直接拿這份當事實。
🔴 這與 `ISEP_COUNTDOWN_NOW`(把時鐘定住)是同一個性質的東西:
**把外界定住,讓閘能離線、可重複地被測**。正式環境不會設它;
沒設 ⇒ 這支回 None,判決完全走真實的 Gitea。
"""
p = os.environ.get("ISEP_MAINLINE_FIXTURE", "").strip()
if not p:
return None
try:
with open(p) as f:
d = json.load(f)
return d if isinstance(d, dict) else None
except Exception:
return None
def record_jump(ticket_ref, ms):
"""把「派了一張不在主線上的票」記一筆。**只留痕,不判罪。**
跳線本身常常是對的(補收、真的插件事)。留痕是為了讓「這條線今天被岔開幾次」
事後數得出來——沒有紀錄的話,跳線與專注在機器上長得一模一樣。
"""
try:
with open(os.path.join(state_dir(), JUMP_LOG), "a") as f:
f.write(json.dumps({
"at": datetime.now(timezone.utc).isoformat(),
"ticket": ticket_ref,
"mainline": ref_of(ms),
"mainline_title": (ms or {}).get("title"),
}, ensure_ascii=False) + "\n")
except Exception:
pass
def _human(delta: timedelta) -> str:
days = int(abs(delta).total_seconds()) // 86400
if days >= 1:
return "%d" % days
hours = int(abs(delta).total_seconds()) // 3600
return "%d 小時" % hours
def due_phrase(ms, now=None) -> str:
"""期限那一段。沒設期限就說沒設——不准編一個日期出來。"""
dt = due_of(ms)
if not dt:
return "沒設期限"
now = now or datetime.now(timezone.utc)
day = dt.astimezone(TAIPEI).strftime("%Y-%m-%d")
gap = dt - now
if gap.total_seconds() >= 0:
return "%s(剩 %s" % (day, _human(gap))
return "%s(🔴 已逾期 %s" % (day, _human(gap))
def progress(ms):
o = int((ms or {}).get("open_issues") or 0)
c = int((ms or {}).get("closed_issues") or 0)
total = o + c
pct = int(round(c * 100.0 / total)) if total else 0
return c, total, pct
def line(now=None) -> str:
"""注入用的那一行(倒數那一行的第二行)。**沒有主線時也要回一句話。**
ISEP#82 驗收第 4 條:沒有主線不能整組壞掉,要講得出「現在沒有主線」。
⇒ 這支永遠回一個非空字串,永遠不 raise。
"""
ms = load()
if not ms:
return ("%s 現在沒有主線——沒有任何 milestone 被標成「現在在做的那一條」。"
"要標:`scripts/mainline set <owner/repo#milestone_id>`"
"(先看有哪些:`scripts/mainline list`" % MARKER)
c, total, pct = progress(ms)
head = "%s 主線:%s%s」|%s%d%d 張已關(%d%%" % (
MARKER, ref_of(ms), ms.get("title") or "?", due_phrase(ms, now), c, total, pct)
goal = (ms.get("description") or "").strip().splitlines()
if goal:
head += "\n 目標:" + goal[0].strip()[:120]
return head
def countdown_segment(now=None):
"""給 `countdown.py` 用的 (名稱, 期限) ——讓 ⏱ 那一行說得出主線是誰。
為什麼要塞進 ⏱ 那一行:⏱ 那一行**已經有一支 Stop 閘在查它有沒有被戴上**
inkstone/ISEP#63)。主線的名字掛在那一行上,就跟著那道已經驗過的閘一起
到 leo 眼前——不必為了同一件事再立第二道會擋人的閘。
"""
ms = load()
if not ms:
return None
return (ms.get("title") or "主線", due_of(ms))
+176
View File
@@ -0,0 +1,176 @@
#!/usr/bin/env bash
# mainline-focus-guard.sh — 派了一張不在主線上的票,就當場問清楚(inkstone/ISEP#82
#
# ── 補的是哪一格 ────────────────────────────────────────────────
# leo 2026-08-27:「**14 個里程碑同時亮著卻不知道該看哪個**」「今天……分心」。
# SOP 說「有 active milestone 時只做該 milestone 的事」——但現場 14 個 open milestone
# 「那個」沒有指涉對象 ⇒ **那條規則在機器上等於不存在**(同款第 N 次:
# history-firstKBDB-firststage-first 全是「規則被讀到了,卻沒有機制驗證有沒有照做」)。
#
# ISEP#82 把「現在在做哪一條」變成一個查得到的事實(`scripts/mainline`),
# 本閘是那個事實的**用處**:派工的票號不在主線上,就當場說是補收還是跳線,
# 不要默默做完——分心不是「做了壞事」,是「岔開了而沒有人注意到」。
#
# ── 🔴 這不是關鍵字黑名單(leo 2026-08-17 已證偽那條路)────────────────
# 「自然語言的變體是無限的,blacklist 永遠追不完……封路哲學之所以有效,
# 是因為它封的是**動作**——動作有限且可枚舉,文字不是。」
# 當日實測:文字層的閘 8 次誤攔、0 次正確攔截。
#
# 本閘從頭到尾**不讀派工單的任何一個字義**。它只做兩個查表:
# ① 派工單的【工單】欄位是哪一張票(`hooks/lib/dispatch_parse.py` 解結構,不判語意)
# ② 那張票所屬的 milestone 標題,等不等於被標定的主線標題(字串相等,不是模糊比對)
# 措辭怎麼寫都不影響判決;改的只有「這張票掛在哪」這個 Gitea 上的事實。
#
# ── 誤攔的出口全部先關掉(誤攔比漏擋更該修)──────────────────────────
# · **沒有主線 ⇒ 一律放行**(ISEP#82 驗收第 4 條:沒有主線不能整組壞掉)
# · 派工單裡沒有票號 ⇒ 放行(那是 no-ticket-no-dispatch.sh 的地盤,
# 兩支閘同時開口,收工方會拿到兩份打架的教學)
# · 多張票只要**有一張**在主線上 ⇒ 放行(那次派工有在推主線)
# · 快取裡查不到,就**打一次網路去問那張票**;問不到 ⇒ 放行
# (🔴「讀不到」不等於「不屬於」——把這兩件事講成同一句是最貴的錯)
# · 子 session 不查:主線是**派工者**手上的判準(CLAUDE.md:「critical path 是
# 你用來盯 subagent 的判準」),不是收工方要背的東西
# · **同一張票只擋一次**:擋完就落一個戳記,重送即放行 ⇒ 不會鬼打牆
# · 內部出錯一律放行——這是節拍器不是安全閘,它壞掉不該讓派工停擺
set -uo pipefail
INPUT="$(cat)"
HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
# 子 session 不查(見上)
[ "${CLAUDE_CODE_CHILD_SESSION:-}" = "1" ] && exit 0
VERDICT=$(printf '%s' "$INPUT" | ISEP_HOOKS_DIR="$HERE" python3 -c '
import importlib.machinery, importlib.util, json, os, sys, urllib.request
HERE = os.environ["ISEP_HOOKS_DIR"]
def load(name, path):
ldr = importlib.machinery.SourceFileLoader(name, path)
spec = importlib.util.spec_from_file_location(name, path, loader=ldr)
mod = importlib.util.module_from_spec(spec)
ldr.exec_module(mod)
return mod
def bail(why):
print("SKIP:" + why); raise SystemExit
try:
d = json.load(sys.stdin)
except Exception:
bail("bad-json")
prompt = (d.get("tool_input") or {}).get("prompt") or ""
if not prompt.strip():
bail("no-prompt")
try:
dp = load("isep_dispatch_parse", os.path.join(HERE, "lib", "dispatch_parse.py"))
ML = load("isep_mainline", os.path.join(HERE, "lib", "mainline.py"))
except Exception:
bail("lib-unavailable")
try:
refs = dp.parse_dispatch(prompt).get("refs") or []
except Exception:
bail("parse-failed")
if not refs:
bail("no-ticket") # no-ticket-no-dispatch 的地盤
ms = ML.load()
if not ms:
bail("no-mainline") # 沒有主線 ⇒ 沒有「不屬於主線」這回事
wanted = ["%s/%s#%d" % (r["owner"], r["repo"], r["num"]) for r in refs]
# ① 離線先問快取:有一張在主線上就放行
unknown = []
for ref in wanted:
v = ML.belongs(ref, ms)
if v is True:
print("SKIP:on-mainline"); raise SystemExit
if v is None:
unknown.append(ref)
# ② 快取查不到的,去問那張票掛在哪。問不到 ⇒ 放行。
if unknown:
fx = ML.fixture_titles()
if fx is not None: # 測試把外界定住(見 mainline.fixture_titles
learned = [r for r in unknown
if ML.norm(fx.get(r, "")) == ML.norm(ms.get("title"))]
if learned:
print("SKIP:on-mainline-fixture"); raise SystemExit
if not any(r in fx for r in unknown):
bail("unreachable") # fixture 沒收錄 ⇒ 等同問不到
else:
try:
T = load("isep_ticket", os.path.join(HERE, "..", "scripts", "ticket"))
tok = T.token()
host = T.HOST
# 🔴 BaseException 不是筆誤:`scripts/ticket` 拿不到憑證時是 sys.exitSystemExit),
# 那不是 Exception 的子類。只接 Exception 的話,這支會整個死掉而不是放行。
except BaseException:
bail("no-token") # 讀不到 ≠ 不屬於
reached = False
learned = []
for ref in unknown:
try:
owner, rest = ref.split("/", 1)
repo, num = rest.split("#", 1)
req = urllib.request.Request(
"%s/api/v1/repos/%s/%s/issues/%s" % (host, owner, repo, num),
headers={"Authorization": "token %s" % tok})
it = json.load(urllib.request.urlopen(req, timeout=6))
reached = True
except Exception:
continue
title = ((it or {}).get("milestone") or {}).get("title") or ""
if ML.norm(title) == ML.norm(ms.get("title")):
learned.append(ref)
if learned:
ms["members"] = sorted(set(ms.get("members") or []) | set(learned))
ML.save(ms)
print("SKIP:on-mainline-fresh"); raise SystemExit
if not reached:
bail("unreachable") # 一張都問不到 ⇒ 放行
# ③ 確定都不在主線上 —— 同一組票只擋一次
import hashlib
key = hashlib.sha1(("|".join(sorted(wanted)) + "@" + ML.ref_of(ms)).encode()).hexdigest()[:16]
stamp = os.path.join(ML.state_dir(), "jump-ok-" + key)
if os.path.exists(stamp):
print("SKIP:already-asked"); raise SystemExit
try:
open(stamp, "w").close()
except Exception:
pass
ML.record_jump(",".join(wanted), ms)
print("BLOCK:%s\t%s\t%s" % (",".join(wanted), ML.ref_of(ms), ms.get("title") or "?"))
' 2>/dev/null || echo "SKIP:crash")
case "$VERDICT" in
BLOCK:*)
PAYLOAD="${VERDICT#BLOCK:}"
TICKETS=$(printf '%s' "$PAYLOAD" | cut -f1)
MREF=$(printf '%s' "$PAYLOAD" | cut -f2)
MTITLE=$(printf '%s' "$PAYLOAD" | cut -f3)
FIRST=$(printf '%s' "$TICKETS" | cut -d, -f1)
{
printf '🎯 這張票不在主線上(inkstone/ISEP#82\n\n'
printf ' 現在的主線:%s「%s」\n' "$MREF" "$MTITLE"
printf ' 這次要派的:%s\n\n' "$TICKETS"
printf '**先說是哪一種,再繼續**——兩種都可能是對的,錯的是默默做完:\n\n'
printf ' ① 補收 —— 它本來就該在主線上,只是沒掛上去\n'
printf ' `scripts/mainline adopt %s` 然後重送\n\n' "$FIRST"
printf ' ② 跳線 —— 真的是插件事(leo 臨時交辦、擋路的地雷…)\n'
printf ' 直接重送即可(**同一張票只擋一次**),並在回覆講一句為什麼現在要岔開主線\n\n'
printf '為什麼要問:leo 2026-08-27「今天……分心」。分心的前提是有一條主線,\n'
printf '而分心本身不是做了壞事,是**岔開了而沒有人注意到**。這一問就是那個「注意到」。\n\n'
printf '想確認主線是誰:`scripts/mainline`(唯一答案)。\n'
} >&2
exit 2
;;
*)
exit 0
;;
esac
+8 -3
View File
@@ -145,12 +145,17 @@ case "$CTX" in
esac
# milestone:沒有快取就整段不出現(不准編一個日期出來)
case "$CTX" in
*"主線"*) no "⑨ 沒有 milestone 快取 ⇒ 那一段不出現" "實得:$CTX" ;;
# 🔴 只比對**第一行**(那條 ⏱ 倒數本身)。inkstone/ISEP#82 之後,同一個注入點還帶著
# 第二行「🎯 主線……」與一段說明,那段文字裡本來就會出現「主線」兩個字
# ——拿整段去比對會把說明當成數字,變成一條**測不到重點的假紅**。
# 這一格要驗的一直都是「⏱ 那一行有沒有多長出一段編出來的期限」。
STAMP_LINE_ONLY=$(printf '%s\n' "$CTX" | head -1)
case "$STAMP_LINE_ONLY" in
*"主線"*) no "⑨ 沒有 milestone 快取 ⇒ 那一段不出現" "實得:$STAMP_LINE_ONLY" ;;
*) ok "⑨ 沒有 milestone 快取 ⇒ 那一段不出現(不編數字)" ;;
esac
printf '2026-08-30|Sprint 8-28\n' > "$ISEP_COUNTDOWN_STATE_DIR/milestone-due"
CTX=$(inject s-ms "$TMP/a5.jsonl" "$T0")
CTX=$(printf '%s\n' "$(inject s-ms "$TMP/a5.jsonl" "$T0")" | head -1)
case "$CTX" in
*"主線 Sprint 8-28 剩"*) ok "⑩ 有 milestone 快取 ⇒ 期限那一段出現" ;;
*) no "⑩ 有 milestone 快取 ⇒ 期限那一段出現" "實得:$CTX" ;;
+202
View File
@@ -0,0 +1,202 @@
#!/usr/bin/env bash
# 主線那一條線的迴歸測試(inkstone/ISEP#82
#
# 票上四條驗收,這裡一條一群:
# A 「現在的主線是哪一個」→ 一個指令答得出來,而且答案唯一
# B 標了主線之後開新回合 → 目標宣告自己出現(不用人去翻)
# C 派一張不屬於主線的票 → 攔一次,並問是補收還是跳線
# D 沒有任何主線 → 不能整組壞掉,要講得出「現在沒有主線」
# E 不該擋的(誤攔比漏擋更該修)
#
# 用法:hooks/tests/mainline-focus-guard.test.sh
# 🔴 全程離線:狀態走 ISEP_COUNTDOWN_STATE_DIR、時鐘走 ISEP_COUNTDOWN_NOW、
# 「那張票掛在哪」走 ISEP_MAINLINE_FIXTURE,並把 TICKET_HOST 指到一個
# 連不上的位址——**任何一條真的走到網路,就會在那裡當場失敗,不會靜靜地變成假綠**。
set -u
ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
GUARD="$ROOT/mainline-focus-guard.sh"
COUNTDOWN="$ROOT/countdown-guard.sh"
MAINLINE="$ROOT/../scripts/mainline"
TMP=$(mktemp -d)
trap 'rm -rf "$TMP"' EXIT
export ISEP_COUNTDOWN_STATE_DIR="$TMP/state"
export TICKET_HOST="http://127.0.0.1:9" # 連不上:走到網路就會馬上失敗
mkdir -p "$ISEP_COUNTDOWN_STATE_DIR"
unset ISEP_MAINLINE_FIXTURE
PASS=0; FAIL=0
ok(){ printf ' ✅ %s\n' "$1"; PASS=$((PASS+1)); }
no(){ printf ' ❌ %s —— %s\n' "$1" "$2"; FAIL=$((FAIL+1)); }
T0=$(python3 -c 'import datetime as d;print(int(d.datetime(2026,8,28,0,0,tzinfo=d.timezone.utc).timestamp()))')
# set_mainline <標題> <成員 ref...> —— 直接寫 state(離線;`mainline set` 那半要網路)
set_mainline(){
python3 - "$ISEP_COUNTDOWN_STATE_DIR/mainline.json" "$@" <<'PY'
import json, sys
path, title = sys.argv[1], sys.argv[2]
json.dump({"ref": "inkstone/ISEP#57", "owner": "inkstone", "repo": "ISEP", "id": 57,
"title": title, "description": "把 SOP 變成閘:規則要長在機器上,不是長在誰的記性上。",
"due_on": "2026-08-31T15:59:59+08:00",
"open_issues": 12, "closed_issues": 1,
"members": list(sys.argv[3:]), "set_at": "2026-08-28 08:00"},
open(path, "w"), ensure_ascii=False)
PY
}
clear_mainline(){ rm -f "$ISEP_COUNTDOWN_STATE_DIR/mainline.json"; }
# dispatch <派工單內文> → "exit|訊息"
dispatch(){
out=$(python3 -c '
import json,sys; print(json.dumps({"tool_input":{"prompt":sys.argv[1]},"session_id":"t"}))' "$1" \
| CLAUDE_CODE_CHILD_SESSION= bash "$GUARD" 2>&1); rc=$?
printf '%s|%s' "$rc" "$(printf '%s' "$out" | tr '\n' ' ')"
}
# inject <now> → UserPromptSubmit 注入的內容
inject(){
printf '{"hook_event_name":"UserPromptSubmit","session_id":"s","transcript_path":"%s"}' "$TMP/none.jsonl" \
| ISEP_COUNTDOWN_NOW="$1" bash "$COUNTDOWN" 2>/dev/null \
| python3 -c 'import json,sys
try: print(json.load(sys.stdin)["hookSpecificOutput"]["additionalContext"])
except Exception: print("")'
}
echo "── A 群:「現在的主線是哪一個」一個指令答得出來,答案唯一(驗收 1)──"
clear_mainline
OUT=$(python3 "$MAINLINE" 2>&1); RC=$?
[ "$RC" = 0 ] && ok "① 沒標過主線 ⇒ 指令仍然回答得出來(exit 0,不是壞掉)" \
|| no "① 沒標過主線 ⇒ exit 0" "實得 exit=$RC"
case "$OUT" in
*"現在沒有主線"*) ok "② 沒標過主線 ⇒ 答案是「現在沒有主線」(驗收 4)" ;;
*) no "② 沒標過 ⇒ 說「現在沒有主線」" "實得:$OUT" ;;
esac
set_mainline "SOP 變成閘" "inkstone/ISEP#82" "inkstone/ISEP#57"
OUT=$(python3 "$MAINLINE" 2>&1)
N=$(printf '%s\n' "$OUT" | grep -c "現在的主線")
[ "$N" = 1 ] && ok "③ 標了之後 ⇒ 只有一個答案(「現在的主線」出現 1 次,不是 14 個)" \
|| no "③ 答案唯一" "「現在的主線」出現 $N"
case "$OUT" in
*"SOP 變成閘"*) ok "④ 答案指名道姓(標題印出來了)" ;;
*) no "④ 答案指名道姓" "實得:$OUT" ;;
esac
set_mainline "換一條線" "inkstone/ISEP#82"
# 🔴 只看標題那一行:描述欄裡本來就會提到舊標題(它是同一份測資),
# 拿整份輸出去比對會**因為描述而誤判**——那不是「舊的還是主線」。
OUT=$(python3 "$MAINLINE" 2>&1 | head -1)
case "$OUT" in
*"SOP 變成閘"*) no "⑤ 換標一條 ⇒ 舊的不再是主線" "舊標題還在:$OUT" ;;
*"換一條線"*) ok "⑤ 換標一條 ⇒ 舊的當場不再是主線(一個檔放得下一條)" ;;
*) no "⑤ 換標一條" "實得:$OUT" ;;
esac
echo "── B 群:標了之後開新回合,目標宣告自己出現(驗收 2)──────────"
set_mainline "SOP 變成閘" "inkstone/ISEP#82"
CTX=$(inject "$T0")
case "$CTX" in
*"🎯 主線:"*) ok "⑥ 什麼都沒交代 ⇒ 注入裡有 🎯 主線那一行" ;;
*) no "⑥ 注入裡有 🎯 主線那一行" "實得:$CTX" ;;
esac
case "$CTX" in
*"SOP 變成閘"*) ok "⑦ 注入裡有主線的名字" ;;
*) no "⑦ 注入裡有主線的名字" "實得:$CTX" ;;
esac
case "$CTX" in
*"目標:把 SOP 變成閘"*) ok "⑧ 注入裡有**目標宣告**(milestone 的描述),不用人去翻" ;;
*) no "⑧ 注入裡有目標宣告" "實得:$CTX" ;;
esac
# ⏱ 那一行是**已經有 Stop 閘在查**的那一行(ISEP#63)。主線的名字掛在它上面,
# 就跟著那道驗過的閘一起到 leo 眼前——不必為了同一件事再立第二道會擋人的閘。
FIRST=$(printf '%s\n' "$CTX" | head -1)
case "$FIRST" in
*"⏱"*"主線 SOP 變成閘"*) ok "⑨ 被查核的那一行(⏱)也帶著主線名字 ⇒ 主線會到 leo 眼前" ;;
*) no "⑨ ⏱ 那一行帶主線名字" "實得:$FIRST" ;;
esac
# 被標定的主線要蓋過「期限最近的那個」快取——後者是猜的,前者是被指定的
printf '2026-08-29|某個期限更近的\n' > "$ISEP_COUNTDOWN_STATE_DIR/milestone-due"
FIRST=$(inject "$T0" | head -1)
case "$FIRST" in
*"主線 SOP 變成閘"*) ok "⑩ 標定的主線蓋過「期限最近」的猜測(不准用猜的蓋過指定的)" ;;
*) no "⑩ 標定的主線優先" "實得:$FIRST" ;;
esac
rm -f "$ISEP_COUNTDOWN_STATE_DIR/milestone-due"
clear_mainline
CTX=$(inject "$T0")
case "$CTX" in
*"現在沒有主線"*) ok "⑪ 沒有主線 ⇒ 注入照樣講得出「現在沒有主線」(驗收 4,不編一條)" ;;
*) no "⑪ 沒有主線 ⇒ 注入講「現在沒有主線」" "實得:$CTX" ;;
esac
echo "── C 群:派了不在主線上的票 ⇒ 攔一次並問清楚(驗收 3)──────────"
set_mainline "SOP 變成閘" "inkstone/ISEP#82" "inkstone/ISEP#57"
printf '{"inkstone/Arcrun#50":"AI 問得到內文"}\n' > "$TMP/fx.json"
export ISEP_MAINLINE_FIXTURE="$TMP/fx.json"
R=$(dispatch '【工單】inkstone/ISEP#82')
[ "${R%%|*}" = 0 ] && ok "⑫ 派主線上的票 ⇒ 放行" || no "⑫ 派主線上的票 ⇒ 放行" "實得 exit=${R%%|*}"
R=$(dispatch '【工單】inkstone/Arcrun#50')
[ "${R%%|*}" = 2 ] && ok "⑬ 派不在主線上的票 ⇒ 擋" || no "⑬ 派不在主線上的票 ⇒ 擋" "實得 exit=${R%%|*}"
case "${R#*|}" in
*"補收"*"跳線"*) ok "⑭ 擋下時問的是「補收還是跳線」,兩條路都給了指令" ;;
*) no "⑭ 訊息問補收/跳線" "實得:${R#*|}" ;;
esac
case "${R#*|}" in
*"SOP 變成閘"*) ok "⑮ 擋下時說得出現在的主線是誰(不是只說「你錯了」)" ;;
*) no "⑮ 訊息說出主線是誰" "實得:${R#*|}" ;;
esac
R=$(dispatch '【工單】inkstone/Arcrun#50')
[ "${R%%|*}" = 0 ] && ok "⑯ 同一張票重送 ⇒ 放行(至多擋一次,不鬼打牆)" \
|| no "⑯ 重送 ⇒ 放行" "實得 exit=${R%%|*}"
J=$(wc -l < "$ISEP_COUNTDOWN_STATE_DIR/mainline-jumps.jsonl" 2>/dev/null || echo 0)
[ "$J" -ge 1 ] && ok "⑰ 跳線留痕(mainline-jumps.jsonl 記了一筆)——不留痕的話跳線與專注長得一樣" \
|| no "⑰ 跳線留痕" "jumps 檔有 $J"
R=$(dispatch '【工單】inkstone/Arcrun#50
【工單】inkstone/ISEP#82')
[ "${R%%|*}" = 0 ] && ok "⑱ 多張票只要有一張在主線上 ⇒ 放行(那次派工有在推主線)" \
|| no "⑱ 多張票有一張在主線 ⇒ 放行" "實得 exit=${R%%|*}"
echo "── D/E 群:不該擋(誤攔比漏擋更該修)──────────────────────────"
clear_mainline
R=$(dispatch '【工單】inkstone/Arcrun#50')
[ "${R%%|*}" = 0 ] && ok "⑲ 沒有主線 ⇒ 一律放行(驗收 4:不能整組壞掉)" \
|| no "⑲ 沒有主線 ⇒ 放行" "實得 exit=${R%%|*}"
set_mainline "SOP 變成閘" "inkstone/ISEP#82"
R=$(dispatch '幫我看一下這個 repo 的狀況')
[ "${R%%|*}" = 0 ] && ok "⑳ 派工單裡沒有票號 ⇒ 放行(那是 no-ticket-no-dispatch 的地盤)" \
|| no "⑳ 沒有票號 ⇒ 放行" "實得 exit=${R%%|*}"
out=$(python3 -c '
import json;print(json.dumps({"tool_input":{"prompt":"【工單】inkstone/Arcrun#50"},"session_id":"t"}))' \
| CLAUDE_CODE_CHILD_SESSION=1 bash "$GUARD" 2>&1); rc=$?
[ "$rc" = 0 ] && ok "㉑ 子 session ⇒ 放行(主線是派工者手上的判準,不是收工方要背的)" \
|| no "㉑ 子 session ⇒ 放行" "實得 exit=$rc"
unset ISEP_MAINLINE_FIXTURE
R=$(dispatch '【工單】inkstone/mira#999')
[ "${R%%|*}" = 0 ] && ok "㉒ 問不到那張票掛在哪(沒 fixture、網路也不通)⇒ 放行:讀不到 ≠ 不屬於" \
|| no "㉒ 問不到 ⇒ 放行" "實得 exit=${R%%|*}"
printf 'not json {{{\n' > "$ISEP_COUNTDOWN_STATE_DIR/mainline.json"
R=$(dispatch '【工單】inkstone/Arcrun#50')
[ "${R%%|*}" = 0 ] && ok "㉓ state 檔壞掉 ⇒ 放行(節拍器壞掉不該讓派工停擺)" \
|| no "㉓ state 壞掉 ⇒ 放行" "實得 exit=${R%%|*}"
OUT=$(python3 "$MAINLINE" 2>&1); RC=$?
[ "$RC" = 0 ] && ok "㉔ state 檔壞掉 ⇒ 指令仍然回答得出來(當成「現在沒有主線」)" \
|| no "㉔ state 壞掉 ⇒ 指令不崩" "實得 exit=$RC$OUT"
echo
echo "結果:通過 $PASS 條,失敗 $FAIL"
[ "$FAIL" -eq 0 ] || exit 1
+322
View File
@@ -0,0 +1,322 @@
#!/usr/bin/env python3
"""mainline — 「現在的主線是哪一個」這個問題的**唯一指令**inkstone/ISEP#82)。
leo 2026-08-27:「**14 個里程碑同時亮著卻不知道該看哪個**」。
當天實查 `GET /repos/inkstone/*/milestones?state=open` 回 14 個,其中「Mira 現代化」
這個名字同時活在 5 個 repo,另有 5 個已經逾期。
⇒ SOP 說的「**那個** active milestone」在現場根本沒有指涉對象——
要注入不知道注哪一個,要擋跳線也不知道拿哪一個當基準。
這支不解「milestone 太多」(跨 repo 同名是既有做法,不動它),
它解的是「**這一刻我在做哪一條**」沒有答案:
mainline 現在的主線是哪一個(= show,唯一答案,離線)
mainline list 有哪些 open milestone 可以選(打網路)
mainline set <owner/repo#id> 把某一個 milestone 標成主線(打網路,寫進 state)
mainline clear 現在沒有主線(例:一條線收掉了,下一條還沒開始)
mainline refresh [--members] 更新進度/期限(SessionStart 跑一次,不輪詢)
mainline adopt <owner/repo#N> 「補收」:把一張票掛進主線(打網路)
mainline has <owner/repo#N> 這張票在不在主線上(exit 0 =在,1 =不在)
🔴 **`<owner/repo#id>` 的 id 是 milestone 的 id,不是 issue 的號碼。**
兩者在 Gitea 是兩套獨立編號,`mainline list` 印出來的就是可以直接貼的那一個。
── 答案為什麼唯一 ─────────────────────────────────────────────────
主線住在一個檔裡(`~/.claude/isep-countdown/mainline.json`),那個檔**放得下一條**。
沒有清單、沒有優先序、沒有「前三名」——`set` 覆蓋掉的那條就不再是主線。
⇒ 問一次只會拿到 0 或 1 個答案,不會拿到 14 個。
── 主線是一個名字,錨在一個具體的 milestone 上 ────────────────────
Gitea 的 milestone 不能跨 repo,而同一條線常常同時開在 5 個 repo。所以
**錨**(期限/進度/目標宣告都讀它)是 `owner/repo#id`
**成員判定**看的是「票所屬 milestone 的標題與主線標題相同」(不分 repo)。
兩件事都成立:同名跨 repo 照舊能用,而「現在在做哪一條」仍然只有一個答案。
"""
import importlib.machinery
import importlib.util
import os
import sys
import urllib.parse
from datetime import datetime, timezone
HERE = os.path.dirname(os.path.abspath(__file__))
def _load(name, path):
"""把一個檔載進來當模組。`scripts/ticket` 沒有 `.py` 副檔名,所以要明著給 loader
`spec_from_file_location` 只靠副檔名認不出它,會回 None)。"""
loader = importlib.machinery.SourceFileLoader(name, path)
spec = importlib.util.spec_from_file_location(name, path, loader=loader)
mod = importlib.util.module_from_spec(spec)
loader.exec_module(mod)
return mod
# 憑證怎麼拿、API 怎麼打、票號怎麼解析——**全部沿用 `scripts/ticket` 那一份**。
# 🔴 刻意不自己再寫一份 token():金鑰的取得只准有一條路(頂層 CLAUDE.md 金鑰鐵律
# 2026-07-29 t145 的實害——同一把金鑰兩種寫法並存,必然漂移)。
ML = _load("isep_mainline", os.path.join(HERE, "..", "hooks", "lib", "mainline.py"))
try:
T = _load("isep_ticket", os.path.join(HERE, "ticket"))
except Exception:
# 🔴 載不到就只是「打不了網路的那幾個動作不能用」,不是整支壞掉。
# ISEP#82 驗收第 4 條要的是「沒有主線也不能整組壞掉」,同一個道理:
# `show` 是離線的,它不該因為別的零件壞了而回答不出來。
T = None
def die(msg, code=2):
print(msg, file=sys.stderr)
sys.exit(code)
def need_net():
if T is None:
die("🔴 載不到 `scripts/ticket`(憑證與 API 都沿用它),這個動作打不了網路。\n"
" `scripts/mainline show` 仍然可以用——它是離線的。")
def parse_ms_ref(s):
"""`owner/repo#<milestone id>`。與票號同形,所以錯手貼票號會拿到 404,訊息要講清楚。"""
import re
m = re.match(r"^([\w.-]+)/([\w.-]+)#(\d+)$", (s or "").strip())
if not m:
die("🔴 寫法是 owner/repo#<milestone id>,你給的是:%s\n"
"(先跑 `scripts/mainline list` 看有哪些,那裡印的就是可以直接貼的)" % s)
return m.group(1), m.group(2), int(m.group(3))
def org_repos(owner):
rows = T.api_soft("/orgs/%s/repos?limit=100" % owner) or []
return [r["name"] for r in rows if isinstance(r, dict) and r.get("name")]
def issues_in_milestone(owner, repo, title):
q = urllib.parse.urlencode({"state": "all", "type": "issues",
"milestones": title, "limit": 100})
rows = T.api_soft("/repos/%s/%s/issues?%s" % (owner, repo, q)) or []
out = []
for it in rows:
if not isinstance(it, dict) or it.get("pull_request"):
continue
ms = it.get("milestone") or {}
# 🔴 再比對一次標題:`milestones=` 這個參數在不同 Gitea 版本上對「名稱 vs id」
# 的解讀不完全一致,拿回來的東西要自己確認過才算數(不要相信查詢字串)。
if ML.norm(ms.get("title")) != ML.norm(title):
continue
out.append("%s/%s#%d" % (owner, repo, it["number"]))
return out
def collect_members(owner, title, anchor_repo):
"""跨 repo 收齊「掛在同名 milestone 底下」的票。"""
refs, scanned = [], []
repos = org_repos(owner)
if anchor_repo not in repos:
repos.append(anchor_repo)
for r in repos:
got = issues_in_milestone(owner, r, title)
if got:
scanned.append((r, len(got)))
refs.extend(got)
return sorted(set(refs)), scanned
def fetch_milestone(owner, repo, mid):
d = T.api_soft("/repos/%s/%s/milestones/%d" % (owner, repo, mid))
if not isinstance(d, dict) or not d.get("title"):
die("🔴 讀不到 %s/%s#%d 這個 milestone。\n"
" · id 是 milestone 的 id,不是 issue 的號碼(`scripts/mainline list` 會印對的)\n"
" · 或是這台機器現在拿不到 Gitea(那就先別標,不要標一個猜的)" % (owner, repo, mid))
return d
# ── show ─────────────────────────────────────────────────────────────────
def cmd_show(argv):
"""離線。**永遠回一個答案**,包括「現在沒有主線」(ISEP#82 驗收第 4 條)。"""
ms = ML.load()
if not ms:
print("🎯 現在沒有主線。")
print()
print(" 這不是故障——沒有人標過,或上一條收掉了。")
print(" 要標一條:`scripts/mainline list` 看有哪些 → `scripts/mainline set <owner/repo#id>`")
print()
print("📌 在標之前,每回合的 🎯 那一行也會照樣講「現在沒有主線」,不會編一條出來。")
return
c, total, pct = ML.progress(ms)
print("🎯 現在的主線:%s「%s」" % (ML.ref_of(ms), ms.get("title")))
desc = (ms.get("description") or "").strip()
if desc:
print(" 目標:" + desc.splitlines()[0].strip())
print(" 期限:%s" % ML.due_phrase(ms))
print(" 進度:%d%d 張已關(%d%%" % (c, total, pct))
mem = sorted(ML.members(ms))
byrepo = {}
for r in mem:
byrepo[r.split("#")[0]] = byrepo.get(r.split("#")[0], 0) + 1
print(" 屬於主線的票:%d 張%s" % (
len(mem), ("" + "、".join("%s %d" % (k, v) for k, v in sorted(byrepo.items())) + "") if byrepo else ""))
if ms.get("set_at"):
print(" 標定於:%s" % ms["set_at"])
if ms.get("refreshed_at"):
print(" 最後更新:%s" % ms["refreshed_at"])
print()
print("📌 這是唯一答案——主線住在一個檔裡,那個檔放得下一條:%s" % ML.path())
# ── list ─────────────────────────────────────────────────────────────────
def cmd_list(argv):
need_net()
owner = argv[0] if argv else T.ORG
rows = []
for r in org_repos(owner):
for m in (T.api_soft("/repos/%s/%s/milestones?state=open" % (owner, r)) or []):
if not isinstance(m, dict):
continue
rows.append((owner, r, m))
if not rows:
die("🔴 一個 open milestone 都沒讀到——多半是拿不到 Gitea,不是真的沒有。\n"
"(讀不到 ≠ 不存在。先修連線,不要因此標一個猜的主線。)", 1)
now = datetime.now(timezone.utc)
cur = ML.load()
print("open milestone 共 %d 個(%s):\n" % (len(rows), owner))
for o, r, m in sorted(rows, key=lambda x: (ML.due_of(x[2]) or datetime.max.replace(tzinfo=timezone.utc))):
c, total, pct = ML.progress(m)
mark = " ← 現在的主線" if cur and ML.ref_of(cur) == "%s/%s#%s" % (o, r, m.get("id")) else ""
print(" %-28s %-24s %3d%% 期限 %s%s" % (
"%s/%s#%s" % (o, r, m.get("id")), (m.get("title") or "")[:24],
pct, ML.due_phrase(m, now), mark))
print("\n📌 貼左邊那一欄:`scripts/mainline set <owner/repo#id>`")
# ── set ──────────────────────────────────────────────────────────────────
def cmd_set(argv):
need_net()
if not argv:
die("用法:mainline set <owner/repo#milestone_id>")
owner, repo, mid = parse_ms_ref(argv[0])
m = fetch_milestone(owner, repo, mid)
title = m.get("title")
refs, scanned = collect_members(owner, title, repo)
now = datetime.now(timezone.utc).astimezone().strftime("%Y-%m-%d %H:%M")
ok = ML.save({
"ref": "%s/%s#%d" % (owner, repo, mid),
"owner": owner, "repo": repo, "id": mid,
"title": title,
"description": m.get("description") or "",
"due_on": m.get("due_on") or "",
"open_issues": m.get("open_issues") or 0,
"closed_issues": m.get("closed_issues") or 0,
"members": refs,
"set_at": now, "refreshed_at": now,
})
if not ok:
die("🔴 寫不進 %s——主線沒有被標上。" % ML.path())
print("✅ 主線已標定:%s/%s#%d「%s」" % (owner, repo, mid, title))
if scanned:
print(" 跨 repo 收到同名 milestone 的票 %d 張:%s"
% (len(refs), "、".join("%s %d" % (r, n) for r, n in scanned)))
print()
cmd_show([])
def cmd_clear(argv):
had = ML.load()
ML.clear()
print("✅ 已清掉主線%s。現在沒有主線——每回合的 🎯 那一行會照實說。"
% ("(原本是 %s「%s」)" % (ML.ref_of(had), had.get("title")) if had else ""))
# ── refresh ──────────────────────────────────────────────────────────────
def cmd_refresh(argv):
"""SessionStart 跑一次。**拿不到就原封不動**——寧可資料舊,不要把主線弄丟。"""
ms = ML.load()
if not ms:
return # 沒有主線就沒有東西要更新,安靜結束
d = T.api_soft("/repos/%s/%s/milestones/%s" % (ms["owner"], ms["repo"], ms["id"]))
if not isinstance(d, dict) or not d.get("title"):
return # 讀不到 ≠ 主線不存在
ms.update({
"title": d.get("title") or ms["title"],
"description": d.get("description") or ms.get("description") or "",
"due_on": d.get("due_on") or ms.get("due_on") or "",
"open_issues": d.get("open_issues") or 0,
"closed_issues": d.get("closed_issues") or 0,
"refreshed_at": datetime.now(timezone.utc).astimezone().strftime("%Y-%m-%d %H:%M"),
})
if "--members" in argv:
refs, _ = collect_members(ms["owner"], ms["title"], ms["repo"])
if refs:
ms["members"] = refs
ML.save(ms)
# ── adopt(補收)──────────────────────────────────────────────────────────
def cmd_adopt(argv):
need_net()
if not argv:
die("用法:mainline adopt <owner/repo#N>(把一張票掛進主線=「補收」)")
ms = ML.load()
if not ms:
die("🔴 現在沒有主線,沒有東西可以補收進去。先 `scripts/mainline set …`。")
owner, repo, num = T.parse_ref(argv[0])
cands = [m for m in (T.api_soft("/repos/%s/%s/milestones?state=all" % (owner, repo)) or [])
if isinstance(m, dict) and ML.norm(m.get("title")) == ML.norm(ms["title"])]
if not cands:
die("""🔴 `%s/%s` 底下沒有叫「%s」的 milestone,所以這張票掛不進去。
兩條路,**都要人決定,這支不會替你選**:
· 這件事真的屬於主線 ⇒ 在 `%s/%s` 開一個同名 milestone(記得設真的期限,
`milestone-due-guard.sh` 會擋沒期限的),再跑一次 adopt
· 這件事其實是另一條線 ⇒ 那就是**跳線**,不是補收。直接重送派工
(本閘同一張票只擋一次),並在回覆說清楚為什麼現在要岔開主線。""" % (
owner, repo, ms["title"], owner, repo))
mid = cands[0]["id"]
T.api("/repos/%s/%s/issues/%d" % (owner, repo, num), {"milestone": mid}, method="PATCH")
ref = "%s/%s#%d" % (owner, repo, num)
ms["members"] = sorted(set(ms.get("members") or []) | {ref})
ML.save(ms)
print("✅ 補收:%s 已掛進「%s」(%s/%s#%d" % (ref, ms["title"], owner, repo, mid))
# ── has ──────────────────────────────────────────────────────────────────
def cmd_has(argv):
if not argv:
die("用法:mainline has <owner/repo#N>")
ms = ML.load()
ref = argv[0].strip()
if not ms:
print("🎯 現在沒有主線 ⇒ 沒有「不屬於主線」這回事。")
return
v = ML.belongs(ref, ms)
if v is None:
owner, repo, num = T.parse_ref(ref)
it = T.api_soft("/repos/%s/%s/issues/%d" % (owner, repo, num))
title = ((it or {}).get("milestone") or {}).get("title") if isinstance(it, dict) else None
v = ML.belongs(ref, ms, ticket_milestone_title=title or "")
if not isinstance(it, dict):
print("⚪ 讀不到 %s,判不出來(讀不到 ≠ 不屬於)。" % ref)
sys.exit(0)
if v:
print("✅ %s 在主線「%s」上。" % (ref, ms["title"]))
sys.exit(0)
print("🚧 %s **不在**主線「%s」上。\n"
" 補收 ⇒ `scripts/mainline adopt %s`;真的是插件事 ⇒ 那是跳線,說清楚再做。"
% (ref, ms["title"], ref))
sys.exit(1)
CMDS = {"show": cmd_show, "list": cmd_list, "set": cmd_set, "clear": cmd_clear,
"refresh": cmd_refresh, "adopt": cmd_adopt, "has": cmd_has}
if __name__ == "__main__":
if len(sys.argv) < 2:
cmd_show([])
sys.exit(0)
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)
CMDS[sys.argv[1]](sys.argv[2:])