65120a1c65
- docs/permissions-allow.json + scripts/settings-allow-sync:四個 Gitea 正門工具的權限白名單一份, setup script 裝完 plugin 寫一次、SessionStart 每次再對一次(只加不減、冪等) - hooks/lib/mainline.py/scripts/mainline:家目錄沒主線就讀 InkStoneCo/system-dev/mainline.json; set/adopt/clear 兩份一起寫,refresh 只寫家目錄 - hooks/leo21c-write-guard.sh:唯讀 -d(tr/cut/sort…)先剪掉再判、notify_leo trigger 放行 (與 prod-write-guard 同一份白名單)、改法段改印 09-02 起的 youlin 子網域;補第一支測試(26 條) - prod-write-guard/main-and-prod-push-guard/kbdb-live-exam:認得 youlin 新子網域 arcrun-yuga3bse - scripts/ticket:收件 repo 寫 inkstone/ISEP 不再 404(org 寫錯當場講) - scripts/isep-notify:有 TELEGRAM_BOT_TOKEN/TELEGRAM_CHAT_ID 先走 Bot API 直送(雲端唯一通的路) - 測試:A31–A35 共 79 條;README/plugin.json/hooks-inventory 數字實數(61 支、85 條、53 支腳本) 假設(記在這裡等 review):權限規則的形狀沿用 leo 09-07 親手加、實測有效的那四條; 「分類器真的不擋」要雲端一趟 run 的 permission_denials 才驗得到,本 PR 驗不了。 版本:待總管定版(plugin.json 仍 0.22.0)。 Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01DTZ9QtvjY7MNxjfQbexAm7
328 lines
13 KiB
Python
328 lines
13 KiB
Python
#!/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 §4/SOP S7-4),
|
||
要解的是「**這一刻我在做哪一條**」沒有答案。
|
||
|
||
⇒ 所以這個檔的形狀就是答案的形狀:**一個檔,放得下一條**。
|
||
沒有清單、沒有優先序、沒有「前三名」——被覆蓋掉的那條就不再是主線。
|
||
問「現在的主線是哪一個」永遠只會拿到 0 或 1 個答案,不會拿到 14 個。
|
||
|
||
── 主線是一個「名字」,錨在一個具體的 milestone 上 ──────────────────
|
||
Gitea 的 milestone 不能跨 repo,而同一條線常常同時開在 5 個 repo(票上實查)。
|
||
所以:
|
||
· **錨**(anchor)= `owner/repo#<milestone id>`:期限、進度、目標宣告都讀它
|
||
· **成員判定**= 票所屬 milestone 的**標題**與主線標題相同(不分 repo)
|
||
⇒ 「同名跨 repo」照舊能用,而「現在在做哪一條」仍然只有一個答案。
|
||
|
||
── 這支從不打網路 ────────────────────────────────────────────────
|
||
它被 `UserPromptSubmit` 用(每一則訊息的關鍵路徑)。在那裡打 HTTP = 每講一句話
|
||
都先等一次網路。網路那一半全部在 `scripts/mainline`(set/refresh/adopt),
|
||
本支只讀寫 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)
|
||
|
||
|
||
# ── repo 裡的那一份(inkstone/ISEP#130)──────────────────────────────
|
||
#
|
||
# 主線原本只住在 `~/.claude/isep-countdown/mainline.json`——**這台機器的家目錄**。
|
||
# 雲端 session 是另一台機器:家目錄是空的,clone 下來的 repo 才是它唯一拿得到的東西。
|
||
# 2026-09-05 leo:「routine 每天早上開啟後抓不到任務」——不是 Gitea 沒票,
|
||
# 是雲端根本不知道主線是哪一條。
|
||
# ⇒ `inkstone/InkStoneCo` 的 `system-dev/mainline.json` 是**隨 repo 走的那一份**
|
||
# (PR inkstone/InkStoneCo#118 放進去的)。這裡的規矩:
|
||
# · 讀:家目錄那份沒有 ⇒ 讀 repo 那份(雲端就是這個形狀)。
|
||
# 兩份都在 ⇒ 用 `set_at` 較新的(誰後標的誰算數,不分本機雲端)。
|
||
# · 寫:`set`/`adopt`/`clear` 這種「主線是誰」的改動 ⇒ 兩份一起寫(`mirror=True`)。
|
||
# `refresh`/閘順手學到成員 ⇒ 只寫家目錄那份——否則每開一個 session
|
||
# InkStoneCo 的工作樹就髒一次,而髒的 diff 沒有人會去 commit。
|
||
# · repo 那份要 commit/開 PR 才到得了雲端;這支不碰 git。
|
||
REPO_REL = os.path.join("system-dev", STATE_NAME)
|
||
|
||
|
||
def repo_candidates():
|
||
"""repo 那一份可能在哪:明指 > 專案根 > 專案根底下的 InkStoneCo/(雲端薄殼的形狀)> cwd 同兩層。"""
|
||
out = []
|
||
forced = os.environ.get("ISEP_MAINLINE_REPO_FILE", "").strip()
|
||
if forced == "none":
|
||
return [] # 測試用:把「repo 那份」整個拿掉,外界定住
|
||
if forced:
|
||
out.append(forced)
|
||
roots = []
|
||
for r in (os.environ.get("CLAUDE_PROJECT_DIR", "").strip(), os.getcwd()):
|
||
if r:
|
||
roots += [r, os.path.join(r, "InkStoneCo")]
|
||
for r in roots:
|
||
p = os.path.join(r, REPO_REL)
|
||
if p not in out:
|
||
out.append(p)
|
||
return out
|
||
|
||
|
||
def repo_path(for_write=False):
|
||
"""讀:第一個**存在**的檔。寫:第一個 `system-dev/` 目錄存在的位置(檔可以還沒有)。
|
||
找不到 ⇒ None(雲端沒 clone InkStoneCo、或 cwd 在別的 repo 時都是正常狀態)。"""
|
||
for p in repo_candidates():
|
||
if for_write:
|
||
if os.path.isdir(os.path.dirname(p)):
|
||
return p
|
||
elif os.path.isfile(p):
|
||
return p
|
||
return None
|
||
|
||
|
||
def _read(p):
|
||
try:
|
||
with open(p) as f:
|
||
d = json.load(f)
|
||
except Exception:
|
||
return None
|
||
if not isinstance(d, dict) or not d.get("title"):
|
||
return None
|
||
return d
|
||
|
||
|
||
def load():
|
||
"""讀主線。沒有/壞掉 ⇒ None(=現在沒有主線),**不是例外**。
|
||
|
||
「沒有主線」是一個正常狀態,不是故障:ISEP#82 驗收第 4 條寫死了
|
||
「沒有任何主線時不能整組壞掉」。所以這支從不 raise。
|
||
|
||
家目錄那份與 repo 那份都在時,`set_at` 較新的算數(格式固定 `YYYY-MM-DD HH:MM`,
|
||
字串比大小就是時間比大小);一樣新 ⇒ 家目錄那份(它才有 refresh 過的進度)。
|
||
"""
|
||
local = _read(path())
|
||
rp = repo_path()
|
||
remote = _read(rp) if rp else None
|
||
if local and remote:
|
||
return remote if (remote.get("set_at") or "") > (local.get("set_at") or "") else local
|
||
return local or remote
|
||
|
||
|
||
def save(d, mirror=False) -> bool:
|
||
"""寫家目錄那份;`mirror=True` 時同時寫 repo 那份(只有「主線是誰」變了才這樣叫)。
|
||
回 True/False 只看家目錄那份——repo 那份寫不寫得進去用 `repo_path(for_write=True)` 另外問。"""
|
||
try:
|
||
with open(path(), "w") as f:
|
||
json.dump(d, f, ensure_ascii=False, indent=2)
|
||
except Exception:
|
||
return False
|
||
if mirror:
|
||
rp = repo_path(for_write=True)
|
||
if rp:
|
||
try:
|
||
with open(rp, "w") as f:
|
||
json.dump(d, f, ensure_ascii=False, indent=2)
|
||
f.write("\n")
|
||
except Exception:
|
||
pass
|
||
return True
|
||
|
||
|
||
def clear(mirror=False) -> bool:
|
||
ok = True
|
||
try:
|
||
os.remove(path())
|
||
except FileNotFoundError:
|
||
pass
|
||
except Exception:
|
||
ok = False
|
||
if mirror:
|
||
rp = repo_path()
|
||
if rp:
|
||
try:
|
||
os.remove(rp)
|
||
except Exception:
|
||
ok = False
|
||
return ok
|
||
|
||
|
||
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/False/None。
|
||
|
||
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))
|