Skip to content

armgit / peach

Public Imported from GitHub
0

Peach: Local-first video metadata scraper and media manager.

feat(release): 会话收尾自动问一次该不该发版,两家智能体共用

longmeidao0007f6d80819
diff --git a/.claude/settings.json b/.claude/settings.json
index a08a2c2c0..d97eb6423 100644
--- a/.claude/settings.json
+++ b/.claude/settings.json
@@ -6,7 +6,10 @@
]
},
"hooks": {
- "Stop": [{"hooks": [{"type": "command", "command": "${CLAUDE_PROJECT_DIR}/.venv/Scripts/python.exe", "args": ["${CLAUDE_PROJECT_DIR}/scripts/job_status.py", "--write", "--hook-event"], "timeout": 30}]}],
+ "Stop": [{"hooks": [
+ {"type": "command", "command": "${CLAUDE_PROJECT_DIR}/.venv/Scripts/python.exe", "args": ["${CLAUDE_PROJECT_DIR}/scripts/job_status.py", "--write", "--hook-event"], "timeout": 30},
+ {"type": "command", "command": "${CLAUDE_PROJECT_DIR}/.venv/Scripts/python.exe", "args": ["${CLAUDE_PROJECT_DIR}/scripts/release_due.py", "--hook-event"], "timeout": 30}
+ ]}],
"StopFailure": [{"hooks": [{"type": "command", "command": "${CLAUDE_PROJECT_DIR}/.venv/Scripts/python.exe", "args": ["${CLAUDE_PROJECT_DIR}/scripts/job_status.py", "--write", "--hook-event"], "timeout": 30}]}],
"SessionEnd": [{"hooks": [{"type": "command", "command": "${CLAUDE_PROJECT_DIR}/.venv/Scripts/python.exe", "args": ["${CLAUDE_PROJECT_DIR}/scripts/job_status.py", "--write", "--hook-event"], "timeout": 30}]}]
}
diff --git a/.codex/hooks.json b/.codex/hooks.json
new file mode 100644
index 000000000..a13b39c94
--- /dev/null
+++ b/.codex/hooks.json
@@ -0,0 +1,7 @@
+{
+ "hooks": {
+ "Stop": [{"hooks": [
+ {"type": "command", "command": ".venv/Scripts/python.exe scripts/release_due.py --hook-event", "timeout": 30}
+ ]}]
+ }
+}
diff --git a/docs/OPERATIONS.md b/docs/OPERATIONS.md
index 105955eed..44c4c47e9 100644
--- a/docs/OPERATIONS.md
+++ b/docs/OPERATIONS.md
@@ -183,6 +183,7 @@ curl -s --noproxy '*' -o /dev/null -w '%{http_code}\n' https://peach.local/healt
- 中途停下(网络断、CI 还在跑、等超时)就再跑一次同一条命令:每一步都先看当下状态再决定做不做,已提交的不重提,已推送的不重推,Test 没绿绝不打标签。
- `scripts/agent_worktree.py integrate` 不碰版本号,只在结果里报当前值;主线上跑着的是哪一份由 commit 与 `build-info.json` 认定。
- 「什么时候该发」也不靠人判断:`integrate` 的输出带一个 `release` 字段(`changelog.due()`),`due` 为真时智能体在收尾照 `why` 提出来。节奏是每周一次、攒够提前、破坏性变化与安全修复不等周期(`DUE_DAYS = 7`、`DUE_ENTRIES = 10`)。判据只数使用者看得见的条目,不数提交:一百个重构提交对使用者是零,那正是这份判据要跟「集成了多少次」分开的地方。
+- 同一份判断还挂在每次会话收尾上:`scripts/release_due.py --hook-event` 由 Claude 的 `.claude/settings.json` 与 Codex 的 `.codex/hooks.json` 里的 `Stop` 钩子调用。两家的钩子约定一致——stdin 收 JSON、stdout 回 `systemMessage`、退出码 0,所以一个脚本供两边。挂在这里才覆盖得到「一周没集成」的那几天,而那正是最容易忘的时候。四道门先挡住不该出声的场合:不在主检出、不在 master、工作区不干净、这个 master sha 已经问过;四条全过且 `due` 为真才说话,其余情形一个字都不打印。闩记在 `<数据根>/state/release-due.json`,master 前进了才会再问。人手查用不带参数的 `python scripts/release_due.py`,那条只读,不动闩。钩子命令里写的是 `.venv/Scripts/python.exe`,在 macOS 上要换成 `.venv/bin/python` 才跑得起来。
- 时间那一半有先例可依(Firefox 四周、Ubuntu 与 GNOME 半年都把「要不要发」交给日历);条数那一半没有可靠样本。已发四版各带 6、8、6、9 条,但那是「每次集成推一格」时期的产物,反映的是那三天写了多少代码,不是多少变化值得让人下载一次。`DUE_ENTRIES` 是没有样本时的保守起点,`due()` 每次都报出实际条目数与分组,积累几次真实发布之后拿那几个数回来校准,别再拿旧机制的数字当依据。
- PyInstaller 的资源直接位于 `sys._MEIPASS`,没有源码树的 `src/` 层;打包后的 `migrate`、Web 与品牌资源必须从这里解析,不能对 `config.py` 固定取 `parents[2]`。
- 创建 Win32 窗口前必须启用 Per-Monitor V2 DPI;正常动作不弹模态 MessageBox,更新检查在后台线程执行并用 pystray 原生非模态通知反馈。
diff --git a/scripts/release_due.py b/scripts/release_due.py
new file mode 100644
index 000000000..01554f519
--- /dev/null
+++ b/scripts/release_due.py
@@ -0,0 +1,149 @@
+#!/usr/bin/env python3
+# -*- coding: utf-8 -*-
+r"""会话收尾时问一次:该发下一版了吗。不该发就一个字都不说。
+
+判据本身住在 `changelog.due()`,这里只管「什么时候问、问给谁听、问几次」。挂在会话
+结束这个时刻,是因为发版的时机没有任何自动触发点:它既不属于某次提交,也不属于某次
+集成,全靠人某天想起来去数变更日志。`integrate` 的输出里已经带了同一份判断,但那要
+恰好有分支落地才会出现,一周没集成的那几天正是最容易忘的时候。
+
+四道门先挡住不该出声的场合,任何一道不成立就静默退出:
+
+1. **不在主检出**:隔离工作树里的工作者不发版,提醒他等于提醒错人。
+2. **不在 master**:发布只从主线走,站在别的分支上收到提醒也动不了手。
+3. **工作区不干净**:此刻发不了版;等这轮改动落地、下一次收尾时再问。
+4. **这一版已经问过**:闩住 master 的 sha,同一个 sha 只问一次。master 前进了就是
+ 又攒了新东西,那时再问一次是对的。
+
+用法(`--hook-event` 是给 Claude 与 Codex 的 Stop 钩子用的,人手查用不带参数那条):
+
+ python scripts/release_due.py # 打印判断,读-only,不动闩
+ python scripts/release_due.py --hook-event # 从 stdin 收 hook JSON,回 systemMessage
+"""
+from __future__ import annotations
+
+import argparse
+import json
+import subprocess
+import sys
+from datetime import datetime, timezone
+from pathlib import Path
+
+if not __package__:
+ sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
+ __package__ = "scripts"
+
+_SRC = Path(__file__).resolve().parents[1] / "src"
+if str(_SRC) not in sys.path:
+ sys.path.insert(0, str(_SRC))
+
+from peach.config import PROJECT_ROOT, STATE_DIR
+
+from . import changelog
+
+#: 发布只从主线走,`release_tag.py` 也只认这一条。
+MAIN_BRANCH = "master"
+
+#: 闩:上一次问过的 master sha。落在 `peach-data/state/`,不进 Git——它是这台机器
+#: 的记忆,跟进度产物一样每次现写,进了 Git 只会让工作区永远是 modified。
+LATCH = STATE_DIR / "release-due.json"
+
+ADVICE = ("起草:`python scripts/release_tag.py --bump auto --apply`,"
+ "措辞定了再 `--ship --apply`。这次不发就不用管,master 前进后会再问一次。")
+
+
+def git(root: Path, *args: str) -> str | None:
+ """仓库里的一条只读 git;命令不成立时是 None,调用方一律当作「说不清」。"""
+ done = subprocess.run(["git", "-C", str(root), *args], capture_output=True,
+ text=True, encoding="utf-8", errors="replace")
+ return done.stdout.strip() if done.returncode == 0 else None
+
+
+def is_main_checkout(root: Path) -> bool:
+ """主检出的 git 目录就是共用的那个;隔离工作树的在 `.git/worktrees/<名字>` 下。
+
+ 判据不看目录名:工作树被回收后目录会原地留着,名字仍然像个工作树,里面的 git 却
+ 已经作用于主检出,只按名字判会把两种相反的情形认成同一种。
+ """
+ own = git(root, "rev-parse", "--git-dir")
+ shared = git(root, "rev-parse", "--git-common-dir")
+ if own is None or shared is None:
+ return False
+ return (root / own).resolve() == (root / shared).resolve()
+
+
+def spoken(latch: Path) -> str:
+ """闩里记着的那个 sha;文件不在、读不出、内容不认得,都当作没问过。"""
+ try:
+ remembered = json.loads(latch.read_text(encoding="utf-8"))
+ except (OSError, ValueError):
+ return ""
+ return str(remembered.get("sha") or "") if isinstance(remembered, dict) else ""
+
+
+def remember(latch: Path, sha: str) -> None:
+ latch.parent.mkdir(parents=True, exist_ok=True)
+ latch.write_text(json.dumps(
+ {"sha": sha, "at": datetime.now(timezone.utc).isoformat(timespec="seconds")},
+ ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
+
+
+def verdict(root: Path, latch: Path) -> dict:
+ """这一轮该说什么。`say` 为空就是不出声,`sha` 是要闩住的那个提交。"""
+ quiet = {"say": "", "sha": ""}
+ if not is_main_checkout(root):
+ return quiet
+ if git(root, "rev-parse", "--abbrev-ref", "HEAD") != MAIN_BRANCH:
+ return quiet
+ if git(root, "status", "--porcelain") != "":
+ return quiet
+ head = git(root, "rev-parse", "HEAD")
+ if not head or spoken(latch) == head:
+ return quiet
+ reasons = changelog.due(root)
+ if not reasons["due"]:
+ return quiet
+ return {"say": "该发下一版了:" + ";".join(reasons["why"]) + "。" + ADVICE,
+ "sha": head}
+
+
+def payload() -> dict:
+ """钩子从 stdin 递来的那个对象;两家的形状一致,都带 `cwd`。"""
+ try:
+ received = json.load(sys.stdin)
+ except (ValueError, OSError):
+ return {}
+ return received if isinstance(received, dict) else {}
+
+
+def main(argv=None) -> int:
+ parser = argparse.ArgumentParser(
+ description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
+ parser.add_argument("--hook-event", action="store_true",
+ help="从 stdin 收 Claude 或 Codex 的 hook JSON,按钩子约定回话")
+ parser.add_argument("--repo", type=Path, default=PROJECT_ROOT)
+ parser.add_argument("--latch", type=Path, default=LATCH)
+ args = parser.parse_args(argv)
+
+ try:
+ root = args.repo
+ if args.hook_event:
+ # 钩子的 `cwd` 才是这次会话真正待的地方:工作树里的会话由它认出来。
+ root = Path(payload().get("cwd") or root)
+ answer = verdict(root, args.latch)
+ if not answer["say"]:
+ return 0
+ if args.hook_event:
+ # 只有钩子问过才动闩。人手查是只读的,不该顺手把钩子的嘴堵上。
+ remember(args.latch, answer["sha"])
+ print(json.dumps({"systemMessage": answer["say"]}, ensure_ascii=False))
+ else:
+ print(answer["say"])
+ return 0
+ except Exception as exc: # noqa: BLE001 —— 钩子里出的错要看得见,但不该挡住收尾
+ print(f"发版时机检查失败:{exc}", file=sys.stderr)
+ return 1
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/scripts/test_runner.py b/scripts/test_runner.py
index 063370141..07d8e36bb 100644
--- a/scripts/test_runner.py
+++ b/scripts/test_runner.py
@@ -68,7 +68,7 @@ SCOPES: dict[str, tuple[str, ...]] = {
"tooling": ("test_scripts.py", "test_auth.py", "test_access.py", "test_cli.py", "test_script_policy.py",
"test_scan.py", "test_onboarding.py", "test_configuration_sources.py", "test_folder_picker.py", "test_ledger_backups.py",
"test_agent_worktree.py", "test_test_evidence.py", "test_dependency_policy.py",
- "test_version_bump.py", "test_changelog.py",
+ "test_version_bump.py", "test_changelog.py", "test_release_due.py",
"test_restart_windows_tray.py", "test_deploy_windows_tray.py",
"test_buildinfo.py", "test_versioning.py",
"test_windows_update.py", "test_release_updates.py", "test_standalone_update.py", "test_certs.py", "test_config.py",
diff --git a/tests/test_release_due.py b/tests/test_release_due.py
new file mode 100644
index 000000000..0cd69de4d
--- /dev/null
+++ b/tests/test_release_due.py
@@ -0,0 +1,192 @@
+"""收尾时那句「该发版了」:什么时候该出声,什么时候一个字都不能说。
+
+提醒最容易坏在「说得太多」上:每轮回话都触发一次的钩子,只要有一次判错就变成每分钟
+一条的噪音,人会连同真正该看的那一条一起划过去。所以这里的断言大半是在证明它闭嘴。
+"""
+import io
+import json
+import subprocess
+import tempfile
+import unittest
+from pathlib import Path
+from unittest import mock
+
+from scripts import release_due
+
+#: 版本号的唯一来源在测试仓库里的最小复刻。
+VERSION_SEED = '"""Peach application package."""\n\n__version__ = "0.7.14"\n'
+
+
+def git(root: Path, *args: str) -> str:
+ done = subprocess.run(["git", "-C", str(root), *args], capture_output=True,
+ text=True, encoding="utf-8", check=True)
+ return done.stdout.strip()
+
+
+def commit(root: Path, subject: str) -> None:
+ note = root / "note.txt"
+ note.write_text(subject, encoding="utf-8")
+ git(root, "add", "note.txt")
+ git(root, "commit", "-m", subject)
+
+
+class ReleaseDueCase(unittest.TestCase):
+ def setUp(self):
+ self.tmp = tempfile.TemporaryDirectory()
+ self.addCleanup(self.tmp.cleanup)
+ # 先 resolve:CI runner 的临时目录都是别名,git 报回来的是真实路径,拿未
+ # resolve 的路径去比对会本机全绿、CI 全红。
+ self.root = Path(self.tmp.name).resolve()
+ self.repo = self.root / "repo"
+ self.repo.mkdir()
+ self.latch = self.root / "state" / "release-due.json"
+ subprocess.run(["git", "init", "-b", "master", str(self.repo)], check=True,
+ stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
+ git(self.repo, "config", "user.email", "[email protected]")
+ git(self.repo, "config", "user.name", "Peach Test")
+ package = self.repo / "src" / "peach"
+ package.mkdir(parents=True)
+ (package / "__init__.py").write_text(VERSION_SEED, encoding="utf-8")
+ git(self.repo, "add", "src/peach/__init__.py")
+ git(self.repo, "commit", "-m", "chore: 起底")
+
+ def pile_up_user_facing_work(self, count: int = 10) -> None:
+ """攒够「不必等满周期」那道判据要的条目数。"""
+ for index in range(count):
+ commit(self.repo, f"feat(review): 复核加第 {index} 项")
+
+ def say(self) -> str:
+ return release_due.verdict(self.repo, self.latch)["say"]
+
+
+class SpeakingTests(ReleaseDueCase):
+ def test_a_release_worth_of_user_facing_changes_gets_said(self):
+ self.pile_up_user_facing_work()
+ said = self.say()
+ self.assertIn("该发下一版了", said)
+ self.assertIn("release_tag.py", said)
+
+ def test_the_same_master_is_only_asked_about_once(self):
+ """闩住 sha,不是闩住会话。
+
+ 每轮回话结束都会触发一次,按会话闩的话,同一个 master 在下一个会话里又会被
+ 问一遍;按 sha 闩,master 前进了才再问,那时确实是又攒了新东西。
+ """
+ self.pile_up_user_facing_work()
+ first = release_due.verdict(self.repo, self.latch)
+ release_due.remember(self.latch, first["sha"])
+ self.assertEqual(self.say(), "")
+ commit(self.repo, "feat(follow): 关注页加筛选")
+ self.assertIn("该发下一版了", self.say())
+
+ def test_a_latch_that_cannot_be_read_counts_as_never_asked(self):
+ """闩坏了要退回「再问一次」,不能退回「永远闭嘴」。
+
+ 反过来的话,一次写坏的文件会让这条提醒从此消失,而且没有任何迹象。
+ """
+ self.pile_up_user_facing_work()
+ self.latch.parent.mkdir(parents=True, exist_ok=True)
+ self.latch.write_text("{ 半个 json", encoding="utf-8")
+ self.assertIn("该发下一版了", self.say())
+
+
+class SilenceTests(ReleaseDueCase):
+ def test_work_no_user_can_see_says_nothing(self):
+ for subject in ("chore: 收拾脚本", "test: 补断言", "refactor(web): 收口",
+ "docs: 记一笔"):
+ commit(self.repo, subject)
+ self.assertEqual(self.say(), "")
+
+ def test_a_worker_worktree_is_never_asked_to_release(self):
+ """工作树里的工作者不发版,提醒他等于提醒错人。"""
+ self.pile_up_user_facing_work()
+ worker = self.root / "worker"
+ git(self.repo, "worktree", "add", "-b", "agent/test/x", str(worker))
+ self.assertEqual(release_due.verdict(worker.resolve(), self.latch)["say"], "")
+ self.assertFalse(release_due.is_main_checkout(worker.resolve()))
+ self.assertTrue(release_due.is_main_checkout(self.repo))
+
+ def test_standing_on_another_branch_says_nothing(self):
+ self.pile_up_user_facing_work()
+ git(self.repo, "checkout", "-q", "-b", "agent/test/y")
+ self.assertEqual(self.say(), "")
+
+ def test_a_dirty_checkout_says_nothing(self):
+ """此刻发不了版,问了也动不了手;等这轮落地,下一次收尾时再问。"""
+ self.pile_up_user_facing_work()
+ (self.repo / "note.txt").write_text("还没提交", encoding="utf-8")
+ self.assertEqual(self.say(), "")
+
+ def test_somewhere_that_is_not_a_repository_says_nothing(self):
+ outside = self.root / "outside"
+ outside.mkdir()
+ self.assertEqual(release_due.verdict(outside, self.latch)["say"], "")
+
+
+class HookTests(ReleaseDueCase):
+ def run_hook(self, cwd: Path) -> tuple[int, str]:
+ received = json.dumps({"hook_event_name": "Stop", "cwd": str(cwd)})
+ with mock.patch("sys.stdin", io.StringIO(received)), \
+ mock.patch("sys.stdout", io.StringIO()) as out:
+ code = release_due.main(["--hook-event", "--latch", str(self.latch)])
+ return code, out.getvalue()
+
+ def test_the_answer_is_the_shape_both_agents_read(self):
+ """Claude 与 Codex 的 Stop 钩子读的是同一个字段,所以一个脚本供两边。"""
+ self.pile_up_user_facing_work()
+ code, out = self.run_hook(self.repo)
+ self.assertEqual(code, 0)
+ self.assertIn("该发下一版了", json.loads(out)["systemMessage"])
+
+ def test_nothing_to_say_prints_nothing_at_all(self):
+ """不该发时连「不用发」也不说:钩子每轮都跑,多一个字就是每轮多一行。"""
+ commit(self.repo, "chore: 收拾脚本")
+ code, out = self.run_hook(self.repo)
+ self.assertEqual(code, 0)
+ self.assertEqual(out, "")
+
+ def test_the_hook_reads_the_session_directory_from_the_event(self):
+ """钩子里的仓库位置只能听事件的 `cwd`。
+
+ Claude 的 `${CLAUDE_PROJECT_DIR}` 在进入工作树后仍指着会话启动时的那个项目
+ 根,照它判的话,工作树里的工作者会话会被当成主检出,收到一条他动不了手的提醒。
+ """
+ self.pile_up_user_facing_work()
+ worker = self.root / "worker"
+ git(self.repo, "worktree", "add", "-b", "agent/test/z", str(worker))
+ self.assertEqual(self.run_hook(worker.resolve()), (0, ""))
+
+ def test_only_the_hook_moves_the_latch(self):
+ """人手查是只读的,不该顺手把钩子的嘴堵上。"""
+ self.pile_up_user_facing_work()
+ with mock.patch("sys.stdout", io.StringIO()):
+ release_due.main(["--repo", str(self.repo), "--latch", str(self.latch)])
+ self.assertFalse(self.latch.exists())
+ self.run_hook(self.repo)
+ self.assertTrue(self.latch.exists())
+
+
+class WiringTests(unittest.TestCase):
+ """判断写好了却没人调用,等于没写。"""
+
+ ROOT = Path(__file__).resolve().parents[1]
+
+ def test_the_claude_stop_hook_runs_the_check(self):
+ settings = json.loads((self.ROOT / ".claude" / "settings.json")
+ .read_text(encoding="utf-8"))
+ commands = [" ".join([entry["command"], *entry.get("args", [])])
+ for group in settings["hooks"]["Stop"] for entry in group["hooks"]]
+ self.assertTrue(any("scripts/release_due.py" in line and "--hook-event" in line
+ for line in commands), commands)
+
+ def test_the_codex_stop_hook_runs_the_same_check(self):
+ hooks = json.loads((self.ROOT / ".codex" / "hooks.json")
+ .read_text(encoding="utf-8"))
+ commands = [entry["command"]
+ for group in hooks["hooks"]["Stop"] for entry in group["hooks"]]
+ self.assertTrue(any("scripts/release_due.py" in line and "--hook-event" in line
+ for line in commands), commands)
+
+
+if __name__ == "__main__":
+ unittest.main()