horo-teamkit 0.2.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. hermes_teamkit/__init__.py +37 -0
  2. hermes_teamkit/audit.py +58 -0
  3. hermes_teamkit/board.py +210 -0
  4. hermes_teamkit/checkpoint.py +110 -0
  5. hermes_teamkit/cli.py +225 -0
  6. hermes_teamkit/config.py +95 -0
  7. hermes_teamkit/gate.py +113 -0
  8. hermes_teamkit/hooks.py +121 -0
  9. hermes_teamkit/review.py +598 -0
  10. hermes_teamkit/setup.py +418 -0
  11. hermes_teamkit/skills/LICENSE-superpowers +21 -0
  12. hermes_teamkit/skills/card-plans/SKILL.md +37 -0
  13. hermes_teamkit/skills/card-writing/SKILL.md +22 -0
  14. hermes_teamkit/skills/owner-ops/SKILL.md +25 -0
  15. hermes_teamkit/skills/research-gates/SKILL.md +27 -0
  16. hermes_teamkit/skills/verify-before-done/SKILL.md +35 -0
  17. hermes_teamkit/templates/custom.md +1 -0
  18. hermes_teamkit/templates/dev/architect.md +1 -0
  19. hermes_teamkit/templates/dev/developer.md +1 -0
  20. hermes_teamkit/templates/dev/ops.md +1 -0
  21. hermes_teamkit/templates/dev/qa.md +4 -0
  22. hermes_teamkit/templates/dev/reviewer.md +4 -0
  23. hermes_teamkit/templates/owner.md +29 -0
  24. hermes_teamkit/templates/research/analyst.md +1 -0
  25. hermes_teamkit/templates/research/critic.md +1 -0
  26. hermes_teamkit/templates/research/engineer.md +1 -0
  27. hermes_teamkit/templates/research/explorer.md +1 -0
  28. hermes_teamkit/templates/research/pi-extra.md +8 -0
  29. hermes_teamkit/templates/research/replicator.md +1 -0
  30. hermes_teamkit/templates/shared.md +24 -0
  31. hermes_teamkit/templates/trio/coder.md +1 -0
  32. hermes_teamkit/templates/trio/verifier.md +4 -0
  33. hermes_teamkit/tools.py +324 -0
  34. hermes_teamkit/web/index.html +162 -0
  35. hermes_teamkit/web.py +246 -0
  36. horo_teamkit-0.2.0.dist-info/METADATA +122 -0
  37. horo_teamkit-0.2.0.dist-info/RECORD +41 -0
  38. horo_teamkit-0.2.0.dist-info/WHEEL +5 -0
  39. horo_teamkit-0.2.0.dist-info/entry_points.txt +2 -0
  40. horo_teamkit-0.2.0.dist-info/licenses/LICENSE +21 -0
  41. horo_teamkit-0.2.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,37 @@
1
+ from __future__ import annotations
2
+
3
+ import logging
4
+ from importlib import resources
5
+ from pathlib import Path
6
+
7
+ from . import checkpoint, cli, config, hooks, setup, tools
8
+
9
+ __version__ = "0.2.0"
10
+
11
+ TOOLSET = "teamkit"
12
+ SKILLS = ("card-writing", "owner-ops", "research-gates")
13
+
14
+
15
+ def superpowers_on() -> bool:
16
+ try:
17
+ from hermes_cli.kanban_db import get_current_board
18
+
19
+ cfg = config.load(get_current_board())
20
+ return bool(cfg and cfg.get("superpowers") and config.current_profile() in cfg["roles"])
21
+ except Exception:
22
+ return False
23
+
24
+
25
+ def register(ctx) -> None:
26
+ problem = setup.host_problem()
27
+ if problem:
28
+ logging.getLogger(__name__).warning("teamkit: %s", problem)
29
+ for name, schema in tools.SCHEMAS.items():
30
+ ctx.register_tool(name=name, toolset=TOOLSET, schema=schema, handler=tools.HANDLERS[name])
31
+ ctx.register_hook("pre_tool_call", hooks.pre_tool_call)
32
+ ctx.register_hook("transform_tool_result", checkpoint.on_command_result)
33
+ ctx.register_hook("kanban_task_blocked", hooks.on_task_blocked)
34
+ ctx.register_cli_command("teamkit", "多 profile 看板團隊工具", cli.setup_parser, cli.handle)
35
+ root = Path(str(resources.files("hermes_teamkit").joinpath("skills")))
36
+ for skill in SKILLS + (setup.SUPERPOWERS_SKILLS if superpowers_on() else ()):
37
+ ctx.register_skill(skill, root / skill / "SKILL.md")
@@ -0,0 +1,58 @@
1
+ from __future__ import annotations
2
+
3
+ import os
4
+ from contextlib import closing
5
+ from typing import Any
6
+
7
+ from . import board as board_ops
8
+ from . import config, gate, review
9
+
10
+
11
+ def audit(board: str, rerun: bool = True) -> dict[str, Any]:
12
+ cfg = config.load(board)
13
+ if cfg is None:
14
+ raise ValueError(f"看板 {board} 沒有 teamkit.yaml")
15
+ checks = list(cfg.get("checks") or [])
16
+ events = review.read_events(board)
17
+ passes: dict[str, list[dict[str, Any]]] = {}
18
+ for e in events:
19
+ if e.get("type") == "gate_pass" and e.get("task"):
20
+ passes.setdefault(e["task"], []).append(e)
21
+ with closing(board_ops.connect(board)) as conn:
22
+ rows = conn.execute(
23
+ "SELECT id, title, assignee, completed_at, workspace_path FROM tasks "
24
+ "WHERE status = 'done' AND (created_by IS NULL OR created_by != ?) ORDER BY completed_at",
25
+ (config.CREATED_BY,),
26
+ ).fetchall()
27
+ cards, findings = [], []
28
+ for task_id, title, assignee, completed_at, path in rows:
29
+ before = [e for e in passes.get(task_id, []) if not completed_at or e["at"] <= completed_at + 5]
30
+ card: dict[str, Any] = {"id": task_id, "title": title, "assignee": assignee, "gate_passed": bool(before)}
31
+ if checks and not before:
32
+ findings.append(f"{task_id} 完成前沒有通過閘門的紀錄({title})")
33
+ recorded = before[-1].get("checks") if before else None
34
+ if recorded is not None and recorded != checks:
35
+ findings.append(f"{task_id} 通過閘門時的檢查清單和現在不同:{recorded} → {checks}")
36
+ if rerun and checks and path and os.path.isdir(path):
37
+ failure = gate.run_checks(path, checks, int(cfg.get("gate_timeout") or 600))
38
+ card["rerun"] = "pass" if failure is None else f"fail: {failure['check']}"
39
+ if failure:
40
+ findings.append(f"{task_id} 現在重跑 `{failure['check']}` 沒通過(指紋 {failure['fingerprint']})")
41
+ cards.append(card)
42
+ waived = list(cfg.get("gate_waivers") or [])
43
+ return {"board": board, "checks": checks, "waivers": waived, "cards": cards, "findings": findings,
44
+ "blocked": sum(1 for e in events if e.get("type") in ("gate_fail", "gate_silenced"))}
45
+
46
+
47
+ def render(data: dict[str, Any]) -> str:
48
+ lines = [f"看板 {data['board']}:檢查 {data['checks'] or '(未設定)'},完成卡 {len(data['cards'])} 張,"
49
+ f"閘門擋下 {data['blocked']} 次"]
50
+ if data["waivers"]:
51
+ lines.append(f"例外卡:{', '.join(data['waivers'])}")
52
+ lines += [f"- {f}" for f in data["findings"]] or ["沒有發現問題。"]
53
+ return "\n".join(lines)
54
+
55
+
56
+ def exit_code(data: dict[str, Any]) -> int:
57
+ return 1 if data["findings"] else 0
58
+
@@ -0,0 +1,210 @@
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ import time
5
+ from contextlib import closing
6
+ from typing import Any, Optional
7
+
8
+ from . import config
9
+
10
+ ACTIVE = ("ready", "running", "review")
11
+ WAITING = ("triage", "todo", "scheduled", "blocked")
12
+ CLOSED = ("done", "archived")
13
+
14
+
15
+ def connect(board: str):
16
+ from hermes_cli.kanban_db_connect import connect as kb_connect
17
+
18
+ return kb_connect(board=board)
19
+
20
+
21
+ def _owner_card(conn, board: str, cfg: dict[str, Any], *, title: str, body: str, key: str) -> Optional[str]:
22
+ from hermes_cli.kanban_db import create_task
23
+
24
+ return create_task(
25
+ conn,
26
+ title=title[:200],
27
+ body=body,
28
+ assignee=cfg["owner"],
29
+ created_by=config.CREATED_BY,
30
+ idempotency_key=key,
31
+ max_runtime_seconds=cfg["max_runtime_seconds"],
32
+ board=board,
33
+ )
34
+
35
+
36
+ def escalate_block(board: str, task_id: str, run_id: Optional[int], reason: Optional[str],
37
+ cfg: dict[str, Any]) -> Optional[str]:
38
+ from hermes_cli.kanban_db import get_task
39
+
40
+ if not cfg.get("owner"):
41
+ return None
42
+ with closing(connect(board)) as conn:
43
+ task = get_task(conn, task_id)
44
+ if task is None or task.created_by == config.CREATED_BY or task.assignee == cfg["owner"]:
45
+ return None
46
+ kind = getattr(task, "block_kind", None) or "untyped"
47
+ open_card = conn.execute(
48
+ "SELECT id FROM tasks WHERE created_by=? AND idempotency_key LIKE ? "
49
+ "AND status NOT IN ('done','archived') LIMIT 1",
50
+ (config.CREATED_BY, f"teamkit-block:{task_id}:%"),
51
+ ).fetchone()
52
+ if open_card:
53
+ from hermes_cli.kanban_db import add_comment
54
+
55
+ add_comment(conn, open_card[0], config.CREATED_BY,
56
+ f"{task_id} 又被擋住(run {run_id},kind {kind}):{reason or '(未提供)'}")
57
+ return open_card[0]
58
+ body = "\n".join([
59
+ f"## 目的\n處理被擋住的卡 {task_id}({task.title})。",
60
+ "## 已知事實",
61
+ f"- assignee: {task.assignee}",
62
+ f"- block kind: {kind}",
63
+ f"- run: {run_id}",
64
+ f"- 原因: {reason or '(未提供)'}",
65
+ "## 做法\n依 block kind 處理:transient 重派一次;dependency 補 parent;"
66
+ "capability 換人或拆掉做不到的部分;needs_input 有授權就決定並寫明,沒有就升級給指示者。",
67
+ f"## 完成條件\n{task_id} 已重新可推進,或已升級並說明需要的決定。",
68
+ "## 回報\n留言在原卡與頂層卡。",
69
+ ])
70
+ return _owner_card(conn, board, cfg, title=f"Owner: {task_id} blocked ({kind}) — {task.title}",
71
+ body=body, key=f"teamkit-block:{task_id}:{run_id or 0}")
72
+
73
+
74
+ def _counts(conn) -> dict[str, int]:
75
+ rows = conn.execute("SELECT status, COUNT(*) FROM tasks GROUP BY status").fetchall()
76
+ return {row[0]: row[1] for row in rows}
77
+
78
+
79
+ FAILED = ("crashed", "gave_up", "timed_out")
80
+
81
+
82
+ def _failed(conn, owner: str) -> list[tuple]:
83
+ rows = conn.execute(
84
+ "SELECT t.id, r.id, r.outcome, t.last_failure_error FROM tasks t "
85
+ "JOIN task_runs r ON r.id = (SELECT MAX(id) FROM task_runs WHERE task_id=t.id) "
86
+ "WHERE t.status='blocked' AND (t.created_by IS NULL OR t.created_by != ?) AND t.assignee != ? "
87
+ f"AND r.outcome IN ({','.join('?' * len(FAILED))})",
88
+ (config.CREATED_BY, owner, *FAILED),
89
+ ).fetchall()
90
+ return [r for r in rows if not conn.execute(
91
+ "SELECT 1 FROM tasks WHERE created_by=? AND (idempotency_key=? OR "
92
+ "(idempotency_key LIKE ? AND status NOT IN ('done','archived'))) LIMIT 1",
93
+ (config.CREATED_BY, f"teamkit-block:{r[0]}:{r[1]}", f"teamkit-block:{r[0]}:%"),
94
+ ).fetchone()]
95
+
96
+
97
+ def tick(board: str, cfg: dict[str, Any], now: Optional[float] = None) -> dict[str, Any]:
98
+ now = time.time() if now is None else now
99
+ result: dict[str, Any] = {"board": board, "action": "none"}
100
+ record_tick(board, now)
101
+ if not cfg.get("owner"):
102
+ result["reason"] = "no owner configured"
103
+ return result
104
+ with closing(connect(board)) as conn:
105
+ failed = _failed(conn, cfg["owner"])
106
+ if failed:
107
+ cards = [escalate_block(board, task_id, run_id,
108
+ f"worker {outcome} 後被 dispatcher 擋下;先看 `hermes kanban log {task_id}` 與該 "
109
+ f"profile 的 logs/managed-worker.log。最後錯誤:{(error or '(無)')[:300]}", cfg)
110
+ for task_id, run_id, outcome, error in failed]
111
+ result.update(action="owner_card", task_ids=[c for c in cards if c])
112
+ return result
113
+ with closing(connect(board)) as conn:
114
+ counts = _counts(conn)
115
+ result["counts"] = counts
116
+ if any(counts.get(s, 0) for s in ACTIVE):
117
+ result["reason"] = "board active"
118
+ return result
119
+ if not any(counts.get(s, 0) for s in WAITING):
120
+ result["reason"] = "nothing waiting"
121
+ return result
122
+ open_owner = conn.execute(
123
+ "SELECT id FROM tasks WHERE assignee=? AND created_by=? AND status NOT IN ('done','archived') LIMIT 1",
124
+ (cfg["owner"], config.CREATED_BY),
125
+ ).fetchone()
126
+ if open_owner:
127
+ result["reason"] = f"owner card {open_owner[0]} still open"
128
+ return result
129
+ last = conn.execute(
130
+ "SELECT e.id, e.created_at FROM task_events e JOIN tasks t ON t.id=e.task_id "
131
+ "WHERE t.created_by IS NOT ? ORDER BY e.id DESC LIMIT 1",
132
+ (config.CREATED_BY,),
133
+ ).fetchone()
134
+ if last is None:
135
+ result["reason"] = "no activity yet"
136
+ return result
137
+ key = f"teamkit-idle:{board}:{last[0]}"
138
+ notified = conn.execute("SELECT id FROM tasks WHERE idempotency_key=? LIMIT 1", (key,)).fetchone()
139
+ if notified:
140
+ result["reason"] = f"this idle period already handled by {notified[0]}"
141
+ return result
142
+ idle_for = now - float(last[1])
143
+ if idle_for < cfg["idle_seconds"]:
144
+ result["reason"] = f"idle {int(idle_for)}s < {cfg['idle_seconds']}s"
145
+ return result
146
+ waiting = ", ".join(f"{s}={counts[s]}" for s in WAITING if counts.get(s))
147
+ body = "\n".join([
148
+ "## 目的\n看板閒置,檢查有沒有該推進的工作。",
149
+ f"## 已知事實\n- 閒置 {int(idle_for)} 秒\n- 等待中: {waiting or '無'}",
150
+ "## 做法\n先補審查通過但還沒驗收的變更與逾時卡的交接,再推進開著的目標卡;沒有目標卡就完成本卡。",
151
+ "## 完成條件\n每張等待中的卡都有下一步,或已寫明為何等待。",
152
+ "## 回報\n完成摘要列出推進了哪些卡。",
153
+ ])
154
+ task_id = _owner_card(conn, board, cfg, title=f"Owner: board {board} is idle", body=body,
155
+ key=key)
156
+ result.update(action="owner_card", task_id=task_id)
157
+ return result
158
+
159
+
160
+ def tick_record_path(board: str):
161
+ return config.board_path(board) / "teamkit-tick.json"
162
+
163
+
164
+ def record_tick(board: str, now: float) -> None:
165
+ path = tick_record_path(board)
166
+ path.parent.mkdir(parents=True, exist_ok=True)
167
+ path.write_text(json.dumps({"at": now}), encoding="utf-8")
168
+
169
+
170
+ def last_tick(board: str) -> Optional[float]:
171
+ try:
172
+ return float(json.loads(tick_record_path(board).read_text(encoding="utf-8"))["at"])
173
+ except (OSError, ValueError, KeyError, TypeError):
174
+ return None
175
+
176
+
177
+ def status(board: str, cfg: Optional[dict[str, Any]], now: Optional[float] = None) -> dict[str, Any]:
178
+ now = time.time() if now is None else now
179
+ out: dict[str, Any] = {"board": board, "configured": cfg is not None}
180
+ if cfg is not None:
181
+ out.update(owner=cfg.get("owner"), reviewer=cfg.get("reviewer"),
182
+ card_creators=sorted(config.creators(cfg)), roles=list(cfg.get("roles") or []))
183
+ with closing(connect(board)) as conn:
184
+ out["counts"] = _counts(conn)
185
+ out["running"] = [
186
+ {"id": r[0], "assignee": r[1], "minutes": int((now - (r[2] or now)) / 60), "title": r[3]}
187
+ for r in conn.execute(
188
+ "SELECT id, assignee, started_at, title FROM tasks WHERE status='running' ORDER BY started_at")
189
+ ]
190
+ out["blocked"] = [
191
+ {"id": r[0], "assignee": r[1], "kind": r[2], "title": r[3]}
192
+ for r in conn.execute("SELECT id, assignee, block_kind, title FROM tasks WHERE status='blocked'")
193
+ ]
194
+ stale_review = []
195
+ for r in conn.execute("SELECT id, assignee, title FROM tasks WHERE status='review'"):
196
+ ev = conn.execute("SELECT kind, created_at FROM task_events WHERE task_id=? ORDER BY id DESC LIMIT 1",
197
+ (r[0],)).fetchone()
198
+ if ev and now - float(ev[1]) > 1800:
199
+ stale_review.append({"id": r[0], "assignee": r[1], "last_event": ev[0],
200
+ "minutes": int((now - float(ev[1])) / 60), "title": r[2]})
201
+ out["stale_review"] = stale_review
202
+ if cfg is not None:
203
+ allowed = config.creators(cfg) | {config.CREATED_BY, "user", None}
204
+ out["foreign_cards"] = [
205
+ {"id": r[0], "created_by": r[1], "title": r[2]}
206
+ for r in conn.execute("SELECT id, created_by, title FROM tasks WHERE status NOT IN ('done','archived')")
207
+ if r[1] not in allowed
208
+ ]
209
+ out["last_tick"] = last_tick(board)
210
+ return out
@@ -0,0 +1,110 @@
1
+ from __future__ import annotations
2
+
3
+ import hashlib
4
+ import json
5
+ import re
6
+ from typing import Any, Optional
7
+
8
+ from . import config, review
9
+
10
+ NUMBERS = re.compile(r"\d+")
11
+ HEX = re.compile(r"\b[0-9a-f]{7,}\b")
12
+
13
+
14
+ def failure_signature(output: str) -> str:
15
+ lines = [l.strip() for l in output.strip().splitlines() if l.strip()][-3:]
16
+ text = "\n".join(lines)
17
+ return HEX.sub("#", NUMBERS.sub("#", text))
18
+
19
+
20
+ def fingerprint(text: str) -> str:
21
+ return hashlib.sha1(text.encode("utf-8")).hexdigest()[:12]
22
+
23
+
24
+ def repeats(board: str, task: Optional[str], fp: str) -> int:
25
+ return sum(1 for e in review.read_events(board)
26
+ if e.get("type") in ("command_fail", "gate_fail") and e.get("task") == task
27
+ and e.get("fingerprint") == fp)
28
+
29
+
30
+ def limit(cfg: dict[str, Any]) -> int:
31
+ return max(int(cfg.get("checkpoint_repeats") or 0), 0)
32
+
33
+
34
+ def notice(count: int, fp: str, owner: Optional[str], on_card: bool = True) -> str:
35
+ head = f"teamkit 檢查點:同一個失敗已經出現 {count} 次(指紋 {fp})。不要再用同一條路重試。"
36
+ if not on_card:
37
+ return head + ("下一步二選一:1) 寫下新的假設與根據,再換做法;"
38
+ "2) 停下來回報做不到,附上錯誤輸出與已經試過的做法。")
39
+ return head + (f"下一步三選一:1) 在卡片留言寫下新的假設與根據,再換做法;"
40
+ f"2) 用 kanban_block 擋住這張卡,附上錯誤輸出與已經試過的做法;"
41
+ f"3) 交給 {owner or 'owner'} 決定。" + ("已通知 owner。" if owner else ""))
42
+
43
+
44
+ def escalate(board: str, cfg: dict[str, Any], task: Optional[str], fp: str, count: int, sample: str) -> None:
45
+ from contextlib import closing
46
+
47
+ from . import board as board_ops
48
+
49
+ if not cfg.get("owner") or not task or task != config.current_task():
50
+ return
51
+ body = "\n".join([
52
+ f"## 目的\n決定卡片 {task} 的下一步:同一個失敗重複了 {count} 次。",
53
+ "## 已知事實",
54
+ f"- 失敗指紋:{fp}",
55
+ f"- 最後的錯誤:\n```\n{sample[-1500:]}\n```",
56
+ "## 做法\n判斷這是實作錯、規格錯,還是環境或架構根本做不到。做得到就寫下新做法給原 worker;"
57
+ "做不到就擋住原卡並升級給指示者,附上證據。",
58
+ f"## 完成條件\n{task} 有明確的下一步(換做法、擋住或升級),並寫明理由。",
59
+ "## 回報\n留言在原卡與頂層卡。",
60
+ ])
61
+ with closing(board_ops.connect(board)) as conn:
62
+ board_ops._owner_card(conn, board, cfg, title=f"Owner: {task} 同一個失敗重複 {count} 次", body=body,
63
+ key=f"teamkit-checkpoint:{task}:{fp}")
64
+
65
+
66
+ def on_command_result(tool_name: str = "", args: Optional[dict[str, Any]] = None, result: Any = None,
67
+ session_id: Optional[str] = None, **_: Any) -> Optional[str]:
68
+ if tool_name != "terminal" or not isinstance(result, str):
69
+ return None
70
+ board = config.current_board(args if isinstance(args, dict) else None)
71
+ cfg = config.load(board)
72
+ if cfg is None or not limit(cfg):
73
+ return None
74
+ try:
75
+ data = json.loads(result)
76
+ except ValueError:
77
+ return None
78
+ if not isinstance(data, dict) or data.get("exit_code") in (0, None):
79
+ return None
80
+ output = f"{data.get('output') or ''}\n{data.get('error') or ''}"
81
+ fp = fingerprint(failure_signature(output))
82
+ task = config.checkpoint_key(session_id)
83
+ review.log_event(board, type="command_fail", profile=config.current_profile(), task=task, fingerprint=fp)
84
+ count = repeats(board, task, fp)
85
+ if count < limit(cfg):
86
+ return None
87
+ if count == limit(cfg):
88
+ review.log_event(board, type="checkpoint", profile=config.current_profile(), task=task, fingerprint=fp,
89
+ count=count)
90
+ escalate(board, cfg, task, fp, count, output)
91
+ data["teamkit_checkpoint"] = notice(count, fp, cfg.get("owner"), on_card=config.current_task() is not None)
92
+ return json.dumps(data, ensure_ascii=False)
93
+
94
+
95
+ def halted(board: str, cfg: dict[str, Any], task: Optional[str]) -> Optional[str]:
96
+ n = limit(cfg)
97
+ if not n or not task:
98
+ return None
99
+ counts: dict[str, int] = {}
100
+ for e in review.read_events(board):
101
+ if e.get("type") in ("command_fail", "gate_fail") and e.get("task") == task:
102
+ counts[e["fingerprint"]] = counts.get(e["fingerprint"], 0) + 1
103
+ worst = max(counts.items(), key=lambda kv: kv[1], default=(None, 0))
104
+ if worst[1] < 2 * n:
105
+ return None
106
+ if task != config.current_task():
107
+ return (f"teamkit 檢查點:同一個失敗已經出現 {worst[1]} 次(指紋 {worst[0]}),暫停執行指令。"
108
+ f"停下來回報做不到,附上錯誤輸出與已經試過的做法。")
109
+ return (f"teamkit 檢查點:同一個失敗已經出現 {worst[1]} 次(指紋 {worst[0]}),這張卡暫停執行指令。"
110
+ f"用 kanban_block 擋住並附上錯誤與已試過的做法,或在卡片留言等 owner 決定。")
hermes_teamkit/cli.py ADDED
@@ -0,0 +1,225 @@
1
+ from __future__ import annotations
2
+
3
+ import argparse
4
+ import json
5
+ import sys
6
+ import time
7
+
8
+ from . import board as board_ops
9
+ from . import config, review, setup
10
+
11
+
12
+ def setup_parser(parser: argparse.ArgumentParser) -> None:
13
+ sub = parser.add_subparsers(dest="teamkit_command", required=True)
14
+
15
+ init = sub.add_parser("init", help="建立看板、profile、SOUL 與 teamkit.yaml(預設只列計畫)")
16
+ init.add_argument("--board", required=True)
17
+ init.add_argument("--preset", choices=sorted(setup.PRESETS), default="dev")
18
+ init.add_argument("--prefix", default="", help="profile 名稱前綴,例如 rea-")
19
+ init.add_argument("--workdir", help="看板預設工作目錄")
20
+ init.add_argument("--force-soul", action="store_true", help="已有內容的 SOUL.md 也覆寫(先備份)")
21
+ init.add_argument("--no-default-home", action="store_true", help="不改預設 home 的 config.yaml")
22
+ init.add_argument("--check", action="append", dest="checks", metavar="CMD",
23
+ help="完成或送審前在卡片工作目錄跑的檢查指令,可重複;沒通過就擋下(閘門)")
24
+ init.add_argument("--superpowers", action=argparse.BooleanOptionalAction, default=None,
25
+ help="啟用改寫自 obra/superpowers 的 skill(預設沿用看板目前的設定,新看板關閉)")
26
+ init.add_argument("--yes", action="store_true", help="照計畫寫入")
27
+
28
+ add = sub.add_parser("add-role", help="加一個角色 profile 並登記到看板(預設只列計畫)")
29
+ add.add_argument("--board", required=True)
30
+ add.add_argument("--name", required=True, help="新 profile 名稱")
31
+ add.add_argument("--like", help="照這個角色的範本產生 SOUL,例如 explorer;省略時開頭要自己寫")
32
+ add.add_argument("--creator", action="store_true", help="允許這個角色開卡")
33
+ add.add_argument("--force-soul", action="store_true", help="已有內容的 SOUL.md 也覆寫(先備份)")
34
+ add.add_argument("--yes", action="store_true", help="照計畫寫入")
35
+
36
+ au = sub.add_parser("audit", help="查證已完成的卡:完成前有沒有通過閘門、現在重跑檢查還過不過")
37
+ au.add_argument("--board", required=True)
38
+ au.add_argument("--no-rerun", action="store_true", help="只看紀錄,不重跑檢查")
39
+ au.add_argument("--json", action="store_true")
40
+ sp = sub.add_parser("superpowers", help="打開或關掉改寫自 obra/superpowers 的 skill(預設只列計畫)")
41
+ sp.add_argument("state", choices=["on", "off"])
42
+ sp.add_argument("--board", required=True)
43
+ sp.add_argument("--yes", action="store_true", help="照計畫寫入")
44
+
45
+ doctor = sub.add_parser("doctor", help="檢查看板與各 profile 的設定")
46
+ doctor.add_argument("--board", required=True)
47
+
48
+ status = sub.add_parser("status", help="看板一覽")
49
+ status.add_argument("--board", required=True)
50
+ status.add_argument("--json", action="store_true")
51
+
52
+ tick = sub.add_parser("tick", help="看板閒置時開 owner 卡;交給 cron 或 launchd 定時跑")
53
+ tick.add_argument("--board", required=True)
54
+
55
+ ui = sub.add_parser("ui", help="本機網頁:團隊總覽、SOUL 編輯、360 回顧")
56
+ ui.add_argument("--board", required=True)
57
+ ui.add_argument("--host", default="127.0.0.1")
58
+ ui.add_argument("--port", type=int, default=8765)
59
+
60
+ rv = sub.add_parser("review", help="360 回顧")
61
+ rv_sub = rv.add_subparsers(dest="review_command", required=True)
62
+ start = rv_sub.add_parser("start", help="開一輪回顧卡(會用模型跑)")
63
+ start.add_argument("--board", required=True)
64
+ start.add_argument("--peers", type=int, default=3, help="每人最多評幾位合作者")
65
+ show = rv_sub.add_parser("show", help="看一輪回顧的進度、疑點與建議")
66
+ show.add_argument("--board", required=True)
67
+ show.add_argument("--cycle", help="預設最近一輪")
68
+ show.add_argument("--json", action="store_true")
69
+ apply = rv_sub.add_parser("apply", help="套用 leader 對某位成員的 SOUL 建議(先備份)")
70
+ apply.add_argument("--board", required=True)
71
+ apply.add_argument("--cycle", required=True)
72
+ apply.add_argument("--subject", required=True)
73
+ apply.add_argument("--force", action="store_true", help="SOUL 在建議之後被改過也照樣套用")
74
+
75
+
76
+ def handle(args: argparse.Namespace) -> int:
77
+ command = args.teamkit_command
78
+ if command == "init":
79
+ return _init(args)
80
+ if command == "add-role":
81
+ try:
82
+ plan = setup.plan_add_role(args.board, args.name, args.like, creator=args.creator,
83
+ force_soul=args.force_soul)
84
+ except ValueError as exc:
85
+ print(f"teamkit: {exc}", file=sys.stderr)
86
+ return 2
87
+ if not _run_plan(plan, args.yes):
88
+ return 0
89
+ print(f"\n完成。{args.name} 自己設定 model、fallback_providers 與 .env,再跑 hermes teamkit doctor --board {args.board}。")
90
+ return 0
91
+ if command == "audit":
92
+ from . import audit
93
+
94
+ try:
95
+ data = audit.audit(args.board, rerun=not args.no_rerun)
96
+ except ValueError as exc:
97
+ print(f"teamkit: {exc}", file=sys.stderr)
98
+ return 2
99
+ print(json.dumps(data, ensure_ascii=False, indent=2) if args.json else audit.render(data))
100
+ return audit.exit_code(data)
101
+ if command == "superpowers":
102
+ try:
103
+ plan = setup.plan_superpowers(args.board, args.state == "on")
104
+ except ValueError as exc:
105
+ print(f"teamkit: {exc}", file=sys.stderr)
106
+ return 2
107
+ if _run_plan(plan, args.yes):
108
+ print("\n完成。正在跑的 worker 不受影響,下一次派工才會載入。")
109
+ return 0
110
+ if command == "doctor":
111
+ findings = setup.doctor(args.board)
112
+ for f in findings:
113
+ print(f"[{f.level}] {f.message}")
114
+ return 1 if any(f.level == "FAIL" for f in findings) else 0
115
+ if command == "status":
116
+ data = board_ops.status(args.board, config.load(args.board))
117
+ print(json.dumps(data, ensure_ascii=False, indent=2) if args.json else render_status(data))
118
+ return 0
119
+ if command == "tick":
120
+ cfg = config.load(args.board)
121
+ if cfg is None:
122
+ print(f"teamkit: {args.board} 沒有 teamkit.yaml", file=sys.stderr)
123
+ return 1
124
+ print(json.dumps(board_ops.tick(args.board, cfg), ensure_ascii=False))
125
+ return 0
126
+ if command == "ui":
127
+ from . import web
128
+
129
+ web.serve(args.board, args.host, args.port)
130
+ return 0
131
+ if command == "review":
132
+ try:
133
+ return _review(args)
134
+ except ValueError as exc:
135
+ print(f"teamkit: {exc}", file=sys.stderr)
136
+ return 2
137
+ return 2
138
+
139
+
140
+ def _review(args: argparse.Namespace) -> int:
141
+ if args.review_command == "start":
142
+ cfg = config.load(args.board)
143
+ if cfg is None:
144
+ raise ValueError(f"{args.board} 沒有 teamkit.yaml")
145
+ meta = review.start_cycle(args.board, cfg, peers=args.peers)
146
+ print(f"{meta['cycle']}: 開了 {len(meta['assignments'])} 張評價卡,彙整卡 {meta['synthesis_task']}")
147
+ for a in meta["assignments"]:
148
+ print(f" {a['task_id']} {a['reviewer']} → {a['subject']} ({a['kind']}{', 同模型' if a['same_model'] else ''})")
149
+ return 0
150
+ if args.review_command == "apply":
151
+ record = review.apply(args.board, args.cycle, args.subject, force=args.force)
152
+ print(f"{record['subject']}/SOUL.md 已套用 {record['cycle']} 的建議(舊版已備份)")
153
+ return 0
154
+ cycle = args.cycle or next((c["cycle"] for c in review.list_cycles(args.board)), None)
155
+ if cycle is None:
156
+ raise ValueError("還沒有回顧")
157
+ view = review.cycle_view(args.board, cycle)
158
+ if args.json:
159
+ print(json.dumps(view, ensure_ascii=False, indent=2))
160
+ return 0
161
+ done = sum(1 for t in view["tasks"].values() if t["status"] == "done")
162
+ print(f"== {cycle}: {done}/{len(view['tasks'])} 張卡完成 ==")
163
+ for f in view["flags"]:
164
+ print(f" ⚠ {f['message']}")
165
+ for r in view["reviews"]:
166
+ kinds = [i["kind"] for i in r["items"]]
167
+ print(f" {r['reviewer']} → {r['subject']}: 優點 {kinds.count('strength')} 問題 {kinds.count('problem')}")
168
+ for p in view["proposals"]:
169
+ state = "已套用" if p.get("applied") else ("SOUL 已被改過" if p.get("stale") else "待決定")
170
+ print(f"\n[建議] {p['subject']}({state})\n{p['rationale']}\n{p['diff']}")
171
+ return 0
172
+
173
+
174
+ def _init(args: argparse.Namespace) -> int:
175
+ plan = setup.plan_init(args.board, args.preset, args.prefix, args.workdir, force_soul=args.force_soul,
176
+ enable_default=not args.no_default_home, superpowers=args.superpowers,
177
+ checks=args.checks)
178
+ if not _run_plan(plan, args.yes):
179
+ return 0
180
+ print(f"\n完成。接著:\n 1. 每個 profile 設定 model、fallback_providers 與 .env\n"
181
+ f" 2. hermes teamkit doctor --board {args.board}\n"
182
+ f" 3. 定時跑 hermes teamkit tick --board {args.board}(例如 crontab: */5 * * * *)\n"
183
+ f" 4. 重啟 gateway 讓 dispatcher 載入 teamkit")
184
+ return 0
185
+
186
+
187
+ def _run_plan(plan: setup.Plan, yes: bool) -> bool:
188
+ for note in plan.notes:
189
+ print(f"說明: {note}")
190
+ if not plan.steps:
191
+ print("已是最新,不用改。")
192
+ return False
193
+ for i, step in enumerate(plan.steps, 1):
194
+ print(f"{i}. {step.describe}")
195
+ if not yes:
196
+ print("\n只列出計畫;確認後加 --yes 執行。改動前會備份成 *.bak-teamkit-<時間>。")
197
+ return False
198
+ for step in plan.steps:
199
+ step.apply()
200
+ return True
201
+
202
+
203
+ def render_status(data: dict) -> str:
204
+ lines = [f"== teamkit status: {data['board']} @ {time.strftime('%Y-%m-%d %H:%M')} =="]
205
+ if not data["configured"]:
206
+ lines.append(" (沒有 teamkit.yaml)")
207
+ else:
208
+ lines.append(f" owner={data['owner']} reviewer={data['reviewer']} 可開卡: {', '.join(data['card_creators'])}")
209
+ lines.append(f" 成員: {', '.join(data['roles'])}")
210
+ counts = data["counts"]
211
+ lines.append(" " + " ".join(f"{k}={v}" for k, v in sorted(counts.items())) if counts else " (沒有卡)")
212
+ for title, key, fmt in (
213
+ ("執行中", "running", "{id} {assignee} {minutes}m {title}"),
214
+ ("被擋住", "blocked", "{id} {assignee} kind={kind} {title}"),
215
+ ("久停在 review(可能要 reassign none 再 reassign 回 reviewer)", "stale_review",
216
+ "{id} {assignee} {minutes}m last={last_event} {title}"),
217
+ ("非授權者開的卡", "foreign_cards", "{id} by={created_by} {title}"),
218
+ ):
219
+ rows = data.get(key) or []
220
+ if rows:
221
+ lines.append(f"[{title}]")
222
+ lines += [" " + fmt.format(**row) for row in rows]
223
+ tick = data.get("last_tick")
224
+ lines.append("[tick] " + (time.strftime("%Y-%m-%d %H:%M", time.localtime(tick)) if tick else "從未執行"))
225
+ return "\n".join(lines)