teamsmith 0.4.6 → 0.4.8

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 (91) hide show
  1. package/README.md +6 -6
  2. package/package.json +1 -1
  3. package/skills/teamsmith/CHANGELOG.md +35 -0
  4. package/skills/teamsmith/SKILL.md +43 -30
  5. package/skills/teamsmith/extension/team-bg.ts +5 -3
  6. package/skills/teamsmith/extension/team-inbox-watch.ts +14 -3
  7. package/skills/teamsmith/extension/team-notify.ts +20 -13
  8. package/skills/teamsmith/extension/team-remind.ts +189 -0
  9. package/skills/teamsmith/extension/team-reply.ts +4 -7
  10. package/skills/teamsmith/references/config.md +11 -12
  11. package/skills/teamsmith/references/migration.md +101 -0
  12. package/skills/teamsmith/references/openspec.md +43 -27
  13. package/skills/teamsmith/references/protocol.md +26 -15
  14. package/skills/teamsmith/references/reminders.md +153 -161
  15. package/skills/teamsmith/references/troubleshooting.md +12 -7
  16. package/skills/teamsmith/references/workflows.md +84 -31
  17. package/skills/teamsmith/scripts/lib/cmd-agents.sh +10 -4
  18. package/skills/teamsmith/scripts/lib/cmd-project.sh +88 -6
  19. package/skills/teamsmith/scripts/lib/cmd-remind.sh +88 -2
  20. package/skills/teamsmith/scripts/lib/cmd-review.sh +61 -35
  21. package/skills/teamsmith/scripts/lib/cmd-watch.sh +48 -11
  22. package/skills/teamsmith/scripts/lib/common.sh +83 -13
  23. package/skills/teamsmith/scripts/panel/README.md +35 -33
  24. package/skills/teamsmith/scripts/panel/panel.js +217 -199
  25. package/skills/teamsmith/scripts/panel/src/App.tsx +221 -66
  26. package/skills/teamsmith/scripts/panel/src/data.ts +71 -15
  27. package/skills/teamsmith/scripts/panel/src/layout.ts +159 -310
  28. package/skills/teamsmith/scripts/panel/src/main.tsx +83 -21
  29. package/skills/teamsmith/scripts/panel/src/project-settings.ts +46 -0
  30. package/skills/teamsmith/scripts/panel/src/strings/en.ts +71 -205
  31. package/skills/teamsmith/scripts/panel/src/strings/index.ts +3 -5
  32. package/skills/teamsmith/scripts/panel/src/strings/zh.ts +72 -204
  33. package/skills/teamsmith/scripts/panel/src/types.ts +23 -4
  34. package/skills/teamsmith/scripts/remind-capability.mjs +261 -0
  35. package/skills/teamsmith/scripts/remind-store.mjs +55 -24
  36. package/skills/teamsmith/scripts/remind-tick.mjs +5 -2
  37. package/skills/teamsmith/scripts/reply-capture.mjs +8 -9
  38. package/skills/teamsmith/scripts/state-authority.mjs +72 -6
  39. package/skills/teamsmith/scripts/strings/commands.tsv +1 -1
  40. package/skills/teamsmith/scripts/team +1 -0
  41. package/skills/teamsmith/templates/AGENTS.section.md.tmpl +18 -8
  42. package/skills/teamsmith/templates/DECISIONS.md.tmpl +2 -2
  43. package/skills/teamsmith/templates/OWNERSHIP.md.tmpl +3 -3
  44. package/skills/teamsmith/templates/PROTOCOL.md.tmpl +19 -14
  45. package/skills/teamsmith/templates/memory-seed.md.tmpl +2 -2
  46. package/skills/teamsmith/templates/pm-prompt.md.tmpl +41 -25
  47. package/skills/teamsmith/templates/report.md.tmpl +33 -0
  48. package/skills/teamsmith/tests/bg-ledger-harness.mjs +217 -33
  49. package/skills/teamsmith/tests/bg-ledger.sh +24 -10
  50. package/skills/teamsmith/tests/checkout-shape-probe.sh +7 -6
  51. package/skills/teamsmith/tests/fixtures/remind-adversarial-delay.ts +27 -0
  52. package/skills/teamsmith/tests/fixtures/remind-tool-provider.ts +65 -0
  53. package/skills/teamsmith/tests/help-surface.sh +78 -12
  54. package/skills/teamsmith/tests/install-shape.sh +7 -7
  55. package/skills/teamsmith/tests/isolation-ledger.sh +6 -2
  56. package/skills/teamsmith/tests/key-replies-ui.sh +64 -5
  57. package/skills/teamsmith/tests/key-replies.sh +307 -106
  58. package/skills/teamsmith/tests/lib/main-team-fingerprint.sh +2 -0
  59. package/skills/teamsmith/tests/lib/model-routing-boundary.sh +255 -90
  60. package/skills/teamsmith/tests/lib/model-routing-expansion.sh +181 -61
  61. package/skills/teamsmith/tests/lib/model-routing-roles.sh +125 -67
  62. package/skills/teamsmith/tests/lib/reply-fixture.sh +14 -9
  63. package/skills/teamsmith/tests/lib/routes-pages.sh +243 -0
  64. package/skills/teamsmith/tests/lib/tmp-root.sh +1 -1
  65. package/skills/teamsmith/tests/loop-inventory.tsv +3 -0
  66. package/skills/teamsmith/tests/panel-b2.sh +91 -31
  67. package/skills/teamsmith/tests/panel-b3-stub.sh +9 -2
  68. package/skills/teamsmith/tests/panel-p21.sh +607 -1162
  69. package/skills/teamsmith/tests/panel-strings.mjs +21 -113
  70. package/skills/teamsmith/tests/remind-adversarial-faults.mjs +190 -0
  71. package/skills/teamsmith/tests/remind-adversarial-faults.sh +78 -0
  72. package/skills/teamsmith/tests/remind-adversarial-real.sh +28 -0
  73. package/skills/teamsmith/tests/remind-cli.sh +108 -3
  74. package/skills/teamsmith/tests/remind-delivery-node.mjs +13 -0
  75. package/skills/teamsmith/tests/remind-delivery.sh +123 -35
  76. package/skills/teamsmith/tests/remind-lifecycle.sh +197 -0
  77. package/skills/teamsmith/tests/remind-pulse.sh +199 -0
  78. package/skills/teamsmith/tests/remind-recovery-real.sh +5 -0
  79. package/skills/teamsmith/tests/remind-recovery-unit.sh +118 -0
  80. package/skills/teamsmith/tests/remind-tool-node.mjs +159 -0
  81. package/skills/teamsmith/tests/remind-tool-real.mjs +801 -0
  82. package/skills/teamsmith/tests/remind-tool-real.sh +180 -0
  83. package/skills/teamsmith/tests/reply-capture-real.mjs +93 -2
  84. package/skills/teamsmith/tests/routes.sh +213 -293
  85. package/skills/teamsmith/tests/section-paths.tsv +19 -17
  86. package/skills/teamsmith/tests/smoke.sh +583 -133
  87. package/skills/teamsmith/tests/state-authority.sh +152 -8
  88. package/skills/teamsmith/tests/task-model-routing.sh +57 -26
  89. package/skills/teamsmith/tests/tmp-hygiene.sh +1 -1
  90. package/skills/teamsmith-init/SKILL.md +5 -5
  91. package/skills/teamsmith/tests/fixtures/delivery-truth-real/__pycache__/judge-second.cpython-313.pyc +0 -0
package/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # teamsmith
2
2
 
3
- **Give one agent real ownership of a project**: it plans, dispatches, verifies independently, merges and keeps the ledger.
3
+ **Give one agent real ownership of a project**: it plans, dispatches, accepts independent verification, merges and keeps the ledger.
4
4
 
5
5
  Runs on Pi; the launch/notify seam is an **internal seam (frozen)** — reserved for a possible future non-Pi adapter, with no compatibility promise (ROADMAP M3.0).
6
6
 
@@ -12,7 +12,7 @@ not "more agents chatting with each other".
12
12
  | Capability | Mechanism |
13
13
  |---|---|
14
14
  | Dispatch | Task briefs are self-contained (context / deliverables / boundaries / copy-pasteable acceptance commands); `team dispatch` puts a worker agent into its own tmux window and git worktree |
15
- | **Independent verification** | The agent's report is a **claim**; the PM runs the gates on an **independent checkout** (`team review <ID> --dir …`) and that becomes the evidence |
15
+ | **Independent verification** | The agent's report is a **claim**; a non-implementer verifier runs `team review <ID> --dir …` on the PM-prepared independent checkout, and the PM accepts that evidence without running the gates |
16
16
  | Ledger | `BOARD.md` (state), `reviews/` (verification evidence), `threads/` (decision trail), `DECISIONS.md` (the "why") |
17
17
  | Not rigid | The watchdog only wakes the owner when there is pending work; the PM can `standby` deliberately; when capacity is tight, work queues instead of thrashing |
18
18
  | Boundaries | Cross-project interaction is discussion only (`team meeting`) — never command; git/forge work stays with the PM's own tools |
@@ -57,14 +57,14 @@ than replaced (`--force` replaces only an entry recognised as this skill).
57
57
  ### As a Pi package (no global CLI)
58
58
 
59
59
  ```bash
60
- pi install git:git@github.com:Track07-cda/teamsmith@v0.4.6 # user level: every project
61
- pi install -l git:git@github.com:Track07-cda/teamsmith@v0.4.6 # project level: recorded in .pi/settings.json
60
+ pi install git:git@github.com:Track07-cda/teamsmith@v0.4.8 # user level: every project
61
+ pi install -l git:git@github.com:Track07-cda/teamsmith@v0.4.8 # project level: recorded in .pi/settings.json
62
62
  ```
63
63
 
64
64
  - **Pin a released tag**: `@v<version>`, the version `team version` prints. Latest tag:
65
65
  `git tag --sort=-v:refname | head -1`.
66
- - The `git@github.com:` form (or `ssh://git@github.com/Track07-cda/teamsmith@v0.4.6`) uses your SSH key and works
67
- whether or not you have a token; the shorthand `git:github.com/Track07-cda/teamsmith@v0.4.6` takes the HTTPS
66
+ - The `git@github.com:` form (or `ssh://git@github.com/Track07-cda/teamsmith@v0.4.8`) uses your SSH key and works
67
+ whether or not you have a token; the shorthand `git:github.com/Track07-cda/teamsmith@v0.4.8` takes the HTTPS
68
68
  route, so it works anonymously on the public repository and asks for credentials if your access is private.
69
69
  - The clone lands in `~/.pi/agent/git/<host>/<path>` (user level) or `.pi/git/<host>/<path>` (project level); the
70
70
  skill directory — the `<skill>` used in every command below — is `<clone>/skills/teamsmith`.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "teamsmith",
3
- "version": "0.4.6",
3
+ "version": "0.4.8",
4
4
  "description": "Turn one agent session into a project owner: self-contained task briefs dispatched to worker agents in their own git worktrees, independent verification on a separate checkout, and an auditable ledger (BOARD / reviews / threads / DECISIONS). Runs on Pi today.",
5
5
  "license": "MIT",
6
6
  "bin": {
@@ -5,6 +5,41 @@
5
5
  > `SKILL.md`/`references/**`/`templates/**`/`extension/**` 在 Pi 里输入 `/reload`(或 `/pi-team-reload`)即生效;
6
6
  > 判断自己是不是旧的:`team version --check`(按 PM 启动时刻与 skill 文件时间推导)。
7
7
 
8
+ ## v0.4.8(2026-11-23)
9
+
10
+ PM 在已授权范围内自行推进;Pulse 项目设置和消息页更容易使用;测试减少重复工作。
11
+
12
+ - 默认 `AGENTS.md` 明确 PM 可自行查证、派工、返修和安排独立复核,不为小事反复请示。只要求方案时不实施;现有合并、发布和生产操作授权要求不变。
13
+ - Pulse 项目设置优先显示常用项,名称与说明改用用户能直接理解的用语。消息页显示延后队列的受阻数量、原因和最近发现时间,普通待发消息不误报。
14
+ - `team board add` 帮助补上必填标题;复验记录区分检查未启动、确实排队超时和检查执行后失败。
15
+ - 配置、帮助、粘贴、模型参数和关键回复等检查减少重复准备、执行或等待;两份提醒测试会清理默认临时文件,保留明确指定的记录。没有新的整套耗时读数。
16
+
17
+ 升级:`npm i -g teamsmith@0.4.8`。已有项目的 `AGENTS.md` 不会自动刷新;采用新规则前按 [现有项目刷新说明](references/migration.md#1b-the-agents-managed-block-what-an-explicit-refresh-does-and-what-it-does-not) 操作。
18
+
19
+ ## v0.4.7(2026-11-13)
20
+
21
+ PM 可以用自然语言创建提醒,到点后继续处理;通知、关键回复与只读诊断完成一轮修复。
22
+
23
+ ### 提醒
24
+
25
+ - PM 可通过 `team_remind` 创建、查看和取消提醒;到点后由巡检送入会话并触发新的模型回合。
26
+ - 周期检查由 PM 在醒后自行续排;同一 key 在前一条确认后释放,新提醒使用新的 ID。停止指令会取消尚未到点的提醒。
27
+ - PM 或巡检停止后,到点未处理的提醒会恢复投递。待命期间仍允许提醒叫醒;确认进入会话后才退出待命,失败或结果未知不会提前退出。
28
+ - `team init` 生成的配置可直接加载提醒工具;配置不匹配会在 `team doctor` 显示具体原因。`team paths` 显示 `flock_runner`,缺失、不可执行或文件系统不支持锁时明确失败,不无锁写入。
29
+
30
+ ### 通知与关键回复
31
+
32
+ - 后台作业按发起会话归属,即使在独立检出执行也不会丢失;新的最终交付提交会再次叫醒 PM,同一提交的重复通知仍合并。
33
+ - PM 收不到新通知时,按看板、报告和提交记录核对实际状态,不把旧提交或合并通知当成未完成。
34
+ - 关键回复时间统一按本地时区显示;修改模型配置不再停止捕获;内部诊断只写日志,不再出现在 Pi 会话中。
35
+
36
+ ### 流程与诊断
37
+
38
+ - OpenSpec 验证与归档由非实现者席位执行,PM 负责审阅、合并与关闭;合并后由同一验证者复核最终提交。
39
+ - `team doctor` 只读检查不再创建调用方指定的临时目录。
40
+
41
+ 升级方式:`npm i -g teamsmith@0.4.7`,重启 PM。
42
+
8
43
  ## v0.4.6(2026-11-06)
9
44
 
10
45
  提醒到点会真的叫醒 PM;`team say` 插在对方下一次调用模型之前;详情页不再拒绝项目内的软链。
@@ -1,16 +1,16 @@
1
1
  ---
2
2
  name: teamsmith
3
- description: teamsmith gives one agent real ownership of a project — it plans, writes self-contained task briefs, dispatches worker agents into their own tmux windows and git worktrees, verifies their work on an independent checkout, merges, and keeps an auditable ledger (BOARD/reviews/threads/DECISIONS). A pulse window (the periodic patrol) wakes the owner only when there is pending work, and the owner can deliberately stand down. Works with Pi; the launch/notify seam is an internal seam (frozen) reserved for a possible future non-Pi adapter, with no compatibility promise. Use when the user wants an agent to own a project end to end, dispatch tasks to worker agents, run agents in parallel in tmux with git worktree isolation, act as a PM/orchestrator over other agents, review an agent's work independently, run the patrol (`pulse`) as a tmux window, wake the PM only when there is pending work, or resume and coordinate a multi-agent project. To start a new project, use the teamsmith-init skill.
3
+ description: teamsmith gives one agent real ownership of a project — it plans, writes self-contained task briefs, dispatches worker agents into their own tmux windows and git worktrees, accepts non-implementer verification on an independent checkout, merges, and keeps an auditable ledger (BOARD/reviews/threads/DECISIONS). A pulse window (the periodic patrol) wakes the owner only when there is pending work, and the owner can deliberately stand down. Works with Pi; the launch/notify seam is an internal seam (frozen) reserved for a possible future non-Pi adapter, with no compatibility promise. Use when the user wants an agent to own a project end to end, dispatch tasks to worker agents, run agents in parallel in tmux with git worktree isolation, act as a PM/orchestrator over other agents, review an agent's work independently, run the patrol (`pulse`) as a tmux window, wake the PM only when there is pending work, or resume and coordinate a multi-agent project. To start a new project, use the teamsmith-init skill.
4
4
  license: MIT
5
5
  metadata:
6
- version: "0.4.6"
6
+ version: "0.4.8"
7
7
  ---
8
8
 
9
9
  # teamsmith · one agent that actually owns the project
10
10
 
11
11
  teamsmith turns "one PM session + several worker agents" into a one-command setup: the PM writes task briefs and
12
- dispatches them, workers implement in parallel inside their own worktrees, the PM verifies on an independent
13
- checkout, then merges. **You usually are that PM**: when the user asks to "set up a team / dispatch tasks /
12
+ dispatches them, workers implement in parallel inside their own worktrees, a non-implementer verifier executes the
13
+ gates on the PM-prepared independent checkout, then the PM accepts the evidence and merges. **You usually are that PM**: when the user asks to "set up a team / dispatch tasks /
14
14
  run agents in parallel", follow the PM loop below.
15
15
 
16
16
  ```
@@ -18,8 +18,8 @@ PM(this session, tmux <session>:pm) worker agents(each in .worktrees/<agent>
18
18
  task / dispatch ──────────────────▶ pi --session-id <s>-<a> (interactive, watchable)
19
19
  digest / inbox ◀── auto-notify on turn end ── extension/team-notify.ts → inbox + tmux wake-up
20
20
  long gate: team_bg_run → turn ends → woken once → team_bg_wait (extension/team-bg.ts, both sides)
21
- review(independent checkout, run gates) ──▶ reports/<ID>-<a>.md (local branch; remote on the PM's route)
22
- merge / close ──────────────────▶ BOARD → done
21
+ prepare checkout ──▶ verifier: team review (run gates + central record/log)
22
+ accept evidence / merge ──▶ same verifier checks merged SHA ──▶ BOARD → done / close
23
23
  ```
24
24
 
25
25
  ## Starting a new project: use the `teamsmith-init` skill
@@ -49,12 +49,12 @@ the upgrade recipe: [references/migration.md](references/migration.md) §§1b–
49
49
  | Collaborate | `team say <a> "<one-line message>" [--no-verify]` (prefers a live inbox watcher: durable inbox + wake spool, zero keys; with no usable watcher it makes one audited immediate attempt typed straight into the window, even over a draft — an attempt, not a model receipt — and falls back to the inbox when the agent is not running), `team notify <a> "<one line>" [--from <sender>]` (agent → PM; the sender comes from the runtime directory — an unresolved sender is refused, never recorded as `pm`) |
50
50
  | Draft / deferred delivery | `team draft [pm]` opens an editor window on `state/draft-pm.md` (nothing automated ever types into it; save+quit enqueues through the guarded path and prints the ack there), `team draft send [<file>] [--now]` (headless form), `team outbox [list]` (what is waiting, with `held` reasons), `team outbox flush [--now]`, `team outbox drop <n\|all>`. Protected senders (notify knocks, wake lines, meeting knocks, ordinary `draft send`, ordinary queued pane delivery) refuse to type into an input box that already holds a draft: the message is queued in `state/outbox/` and reported as `queued`. Default `team say` is the named exception: watch first, otherwise one audited immediate attempt even over a draft (`state/outbox/forced.log`), never a receipt; a `geometry-untrusted` read (the supported Pi layout cannot be established) or three trusted-empty drains with no progress (`queue-stalled`) hold the entry durably with its reason and **exit non-zero**, never promising an automatic delivery. `draft send --now` / `outbox flush --now` remain the audited human overrides that type anyway (`state/outbox/forced.log`). See `references/troubleshooting.md` §3 |
51
51
  | Long gate (background job) | **tool calls in the session** (not `team` subcommands): `team_bg_run` starts a detached job (id + pid at once, `state/bg/<id>.log`), `team_bg_wait <id>` harvests it (exit code + log tail inline). One merged wake-up per finished batch, silence once harvested, one `settled-with-unharvested=<n>` line per turn end in `state/bg.log`. Injected on both built-in Pi paths; a custom template opts in with `{bg_ext}`. The lane's records are readable and stoppable from the CLI: `team bg list` (one row per record, signals nothing), `team bg stop <id>` (signals only the recorded job — the `(pid, start-time)` pair is the identity, a reused pid is refused). Inside a window `pkill`/`killall` are the signal gate and refuse every name/pattern selection with exit 64. See `references/workflows.md` §E2 |
52
- | Verify | `team review <ID> --dir <PM-prepared independent checkout> [--no-gates] [--strong] [--allow-unresolved-branch]` → `reviews/<ID>.md` (runs gates + writes evidence; refuses a dirty or `.gitignore`d checkout / an unresolvable `--branch` unless the matching `TEAM_REVIEW_ALLOW_*` override is used and recorded; `--strong` structurally checks flip evidence + a path to an independent package) |
52
+ | Verify | The PM prepares a clean detached checkout; the assigned non-implementer verifier invokes `team review <ID> --dir <checkout> [--branch <sha>] [--no-gates] [--strong] [--allow-unresolved-branch]` from its own worktree → the tool writes only the brief-named main-checkout `reviews/<ID>.md` + `<ID>-verify.log` ledger exception, with the actual executor and reviewed SHA (the verifier's report stays on its branch; refuses a dirty or `.gitignore`d checkout / an unresolvable `--branch` unless the matching `TEAM_REVIEW_ALLOW_*` override is used and recorded; `--strong` structurally checks flip evidence + a path to an independent package) |
53
53
  | Wrap up | `team close <ID> [--keep-window]` (BOARD/state/window only, never git), `team teardown --agent a [--purge] [--register]` (explicit cleanup; `--register` removes the seat from the roster through the audited writer first) |
54
54
  | Bootstrap | `team bootstrap [--agents "dev verify"] --task-models '<map>' --pm-model '<model>' [--print]` (recommended; both model inputs are required on a fresh project, a valid policy is kept on re-entry, a legacy config is refused before any side effect and points at `team config upgrade-models`), `team init`, `team doctor` |
55
55
  | Patrol (pulse) | `team pulse up\|down\|restart\|status\|logs` (a `pulse` window in the same session runs the monitor + periodic patrol; single backend). Renamed from `watchdog` in v1.36.0: `team watchdog …`, `watchdog-status`, `install-watchdog`, `uninstall-watchdog` still work as aliases until v2.0.0 (they print a one-line deprecation notice first). `team watch [--once]` (foreground patrol) |
56
56
  | Monitor | `team monitor [--once] [--activity]` (**serves the current tmux session only**: who is running / tasks / pending / capacity; `--activity` adds per-agent activity streams, off by default), `team panel` reuses it. The TUI's own preferences live in `state/panel.conf` (language, page, activity, mouse, density, theme) — runtime state, not project config, and `--print`/`--json` never read it |
57
- | Project settings | `team config list [--json]` / `team config set <KEY> <VALUE> [--dry-run] [--fingerprint <sha256>] [--actor <name>] [--allow-danger]` / `team config log [N]` / `team config set-task-model <category> <model>` / `team config upgrade-models --task-models '<map>' --pm-model '<model>' [--dry-run\|--yes]`: the only writer of `.pi/team/config.sh` (comment/order preserving, single-quote form, value validation, danger list, sha256 CAS, one audit line per attempt in `state/config.log`). Model policy is the task-category map plus the independent PM model; the retired seat front doors (`set-agent-model`, `add-agent --model`) refuse and point here. The console's project-settings view (settings overlay → `项目设置`) lists every key with its effect class (`apply`/`restart`/`refuse`) and edits through this command; see `references/config.md` §5 |
57
+ | Project settings | `team config list [--json]` / `team config set <KEY> <VALUE> [--dry-run] [--fingerprint <sha256>] [--actor <name>] [--allow-danger]` / `team config log [N]` / `team config set-task-model <category> <model>` / `team config upgrade-models --task-models '<map>' --pm-model '<model>' [--dry-run\|--yes]`: the only writer of `.pi/team/config.sh` (comment/order preserving, single-quote form, value validation, danger list, sha256 CAS, one audit line per attempt in `state/config.log`). Model policy is the task-category map plus the independent PM model; the retired seat front doors (`set-agent-model`, `add-agent --model`) refuse and point here. The console's project-settings view (settings overlay → `项目设置`) selects model and automatic-check operations, with `项目命令` / `Project commands` and read-only `模型记录` / `Model records` entries; full keys remain in the CLI and all edits still use these owning commands; see `references/config.md` §5 |
58
58
  | PM/agent lifecycle | `team up [--agents]` (recover the PM), `team resume` (PM's tool: continue stopped agents), `team standby on\|off` (PM deliberately stands down) |
59
59
  | Cross-project meetings | `team meeting open/say/read/list/inbox/propose/agree/close` (PM-to-PM peer exchange: interface work, advice, problem reports; **not a command channel** — consensus needs both sides) |
60
60
  | Updates | `team mark-loaded` (record the version at session start), `team version --check` (should I reload?), `team changelog [--since X]`, `team reload` |
@@ -89,23 +89,33 @@ when they conflict, the creed wins and the process gets fixed.
89
89
  `category:` picks a new dispatch's model; dispatching again to the same agent resumes its session, and `--fresh` is
90
90
  the explicit new-session route. The `change:`/`specs:`/`anchor:`/`deltas:` header is checked **before the window
91
91
  opens**, and a refusal names the offending line, the sibling and the fix.
92
- 3. **Wait for notifications**: when a worker's turn ends it appends to `inbox/<agent>.md` and knocks on your window.
93
- Do not poll agent screens; read `team inbox --ack` and `team digest`.
94
- 4. **Verify (never skip)**: `team review <ID> --dir <checkout>` runs the gates on a clean, independent checkout and
95
- writes `reviews/<ID>.md`. **A report is a claim; your verification is the evidence.** Re-read the diff against the
96
- brief, and read each finding for what it changed.
97
- 5. **Land the records, then merge**: `team review <ID> --pre-merge` first — it lists every `docs/team/**` file the
98
- task's worktree has **not committed**, and a squash carries only committed content (an untracked report dies with
99
- the reused worktree). Commit them yourself with the `Agent: <agent>` trailer, then run git yourself: squash-merge
100
- (with a PR: merge it, then `fetch && merge --ff-only`) → `team board set <ID> done` → `team close <ID>`. A late
101
- delivery after the merge goes through `team review <ID> --post-merge` before you take anything.
92
+ 3. **Wait with notifications first and files as the authority**: when a worker's turn ends it appends to
93
+ `inbox/<agent>.md` and knocks on your window; read `team inbox --ack` and `team digest`. Before repeating an
94
+ unchanged waiting report, reconcile the digest, BOARD, task-branch report and task-worktree `git log`/`status`.
95
+ Use `git show <task-branch>:docs/team/reports/<ID>-<agent>.md` without switching branches; an uncommitted report
96
+ is a draft. An old tip, no new notice or a merged line does not prove unfinished work. Recognize a committed
97
+ final report through the existing acceptance route, keep a live job without one on wait/harvest, do not poll
98
+ agent screens, and do not rerun the assigned non-implementer verifier's acceptance tests yourself.
99
+ 4. **Delegate verification (never skip)**: prepare a clean, independent checkout; a non-implementer verifier runs
100
+ `team review <ID> --dir <checkout>` and the tool writes the named central record/log. **A report is a claim; the
101
+ verifier's execution is the evidence; your evidence/diff review is acceptance, not a gate run.** Re-read the diff
102
+ against the brief, and read each finding for what it changed.
103
+ 5. **Land the records, merge, then verify the merge**: `team review <ID> --pre-merge` first — it lists every
104
+ `docs/team/**` file the task's worktree has **not committed**, and a squash carries only committed content (an
105
+ untracked report dies with the reused worktree). Commit them yourself with the `Agent: <agent>` trailer, then run
106
+ git yourself: squash-merge (with a PR: merge it, then `fetch && merge --ff-only`). Resume the same verifier on a
107
+ clean checkout pinned to the merged SHA; accept its passing gates and OpenSpec assessment before `team board set
108
+ <ID> done` → `team close <ID>`. `team review <ID> --post-merge` remains an inspection of late delivery, never the
109
+ merged-revision verification run.
102
110
  6. **Wrap up / report**: update `BOARD.md`, record decisions in `DECISIONS.md` with rationale and impact, and report to
103
111
  the user as "delivered + where the evidence is + next step".
104
112
 
105
- Stop and ask the user only for **shared-state changes** (merge/push — the skill expresses authorization with `--yes`),
106
- scope changes, and decisions that need their call (dispatch a research task first, then write `DECISIONS.md`). Exact
107
- sequences: [references/workflows.md](references/workflows.md) §§B–F; patrol: protocol §8, workflows §§D/§I; the gate and
108
- its queue: protocol §9b-2.
113
+ Follow **PM — proceed within authorization** under **Roles and reading order** in `AGENTS.md`. Get the user's decision
114
+ on new product trade-offs or changes in scope; dispatch a research task when needed and record the decision in
115
+ `DECISIONS.md`. Obtain any missing authorization before changing shared state, including merges and pushes. Where a
116
+ `team` command requires `--yes`, it expresses authorization already given; it does not grant authorization or apply
117
+ to direct git/forge writes. Exact sequences: [references/workflows.md](references/workflows.md) §§B–F; patrol: protocol
118
+ §8, workflows §§D/§I; the gate and its queue: protocol §9b-2.
109
119
 
110
120
  ## Specs (OpenSpec)
111
121
 
@@ -114,10 +124,11 @@ scenarios; teamsmith keeps the **evidence** (briefs, reports, reviews, decisions
114
124
  spec system: a product promise goes into a spec, reasoning or guidance into `references/`.
115
125
 
116
126
  A change runs as **five phases, one brief each, one owner each**: `opsx-explore` (an explorer) → `opsx-propose` (the
117
- same explorer, planning only) → `opsx-apply` (a dev) → `opsx-verify` (a **different** agent) → `opsx-archive` (the
118
- PM). Two hard rules: **an `apply` brief starts only after the PM's proposal review is ACCEPTED**
119
- (`docs/team/reviews/<change>-proposal.md`), and **the PM never archives without independent verification and the
120
- user's confirmation**. **One change : N tasks** — the change is the dispatch unit and the brief's header maps the task
127
+ same explorer, planning only) → `opsx-apply` (a dev) → `opsx-verify` (a **different** agent) → `opsx-archive` (a
128
+ non-implementer worker, possibly that verifier). Two hard rules: **an `apply` brief starts only after the PM's
129
+ proposal review is ACCEPTED** (`docs/team/reviews/<change>-proposal.md`), and **the PM never authorizes archive without
130
+ the same verifier's accepted merged-revision evidence and valid confirmation**. The user confirms, or the PM records a
131
+ narrowly qualified proxy confirmation (small, reversible and already covered by the approved approach). **One change : N tasks** — the change is the dispatch unit and the brief's header maps the task
121
132
  to it (`team dispatch` refuses more than one `change:` id, a change-less brief without a resolvable anchor, two
122
133
  unfinished tasks writing one delta file, and a verifier who authored the change; `team change status <id>` reports
123
134
  readiness). `openspec validate --all --strict` is part of `TEAM_GATES`. Phase table, gates and the PM's ten-point review
@@ -180,8 +191,8 @@ about them). They stay writable so the seam can be maintained and diagnosed; to
180
191
  - Details: [references/meeting.md](references/meeting.md).
181
192
 
182
193
  ## Non-negotiable rules (verified during review)
183
- - **Never claim something passed without having run it.** Reports carry the real commands and output tails; the PM
184
- re-runs independently.
194
+ - **Never claim something passed without having run it.** Reports carry the real commands and output tails; the
195
+ assigned non-implementer verifier re-runs independently, and the PM reviews that evidence without executing it.
185
196
  - **Mark the reply — publication is a standing duty.** Whenever the answer is written for the user — an answer, a status
186
197
  or progress report, a conclusion or a ruling, a delivery or verification summary, a decision you ask the user for,
187
198
  however short — write the complete reply as the normal answer and end it with the final control line `[[team-reply]]`
@@ -202,8 +213,10 @@ about them). They stay writable so the seam can be maintained and diagnosed; to
202
213
  agents or quota — a stopped worker is pending work, not an automatic resume (`team resume` is your call). Nothing to
203
214
  do or a human needed: `team standby on --reason "…"` stands you down until a human runs `team standby off`.
204
215
  Mechanism and boundaries: protocol §8; patrol steps: workflows §§D/§I.
205
- - **Four separate adoption gates** — changing the project's contract, launching a fresh PM, landing source on a shared
206
- branch/skill path, and adopting a shared source: preview the exact command and get authorization per operation.
216
+ - **For a Teamsmith tool-source upgrade**, keep four steps separately recorded: private source verification; landing
217
+ validated source on a shared/protected tree; writing the project's configuration and the first fresh PM launch that
218
+ reads it; and adopting a changed shared skill/copy source. Preview the exact command and obtain authorization for
219
+ each command, including both the configuration write and the first fresh launch.
207
220
 
208
221
  ## Deeper reading (read on demand, not all at once)
209
222
 
@@ -27,6 +27,7 @@ type Job = {
27
27
  root: string // 起作业时解析到的车道根 —— 账本/记录/wait 行都落它下面(会话中途换 cwd 也不漂)
28
28
  pid: number
29
29
  command: string
30
+ sessionCwd: string // 发起会话的目录;cwd 可以是独立执行检出,不能顶替发起身份
30
31
  cwd: string
31
32
  log: string
32
33
  startedAt: number
@@ -195,7 +196,7 @@ function writeJobRecord(root: string, job: Job): void {
195
196
  const { pgid, start } = procStat(job.pid)
196
197
  const one = job.command.replace(/[\r\n]+/g, ' ')
197
198
  writeFileSync(join(dir, `${job.id}.job`),
198
- `id=${job.id}\npid=${job.pid}\npgid=${pgid}\nstart=${start}\ncwd=${job.cwd}\nlog=${job.log}\ncmd=${one}\n`)
199
+ `id=${job.id}\npid=${job.pid}\npgid=${pgid}\nstart=${start}\nsession_cwd=${job.sessionCwd}\ncwd=${job.cwd}\nlog=${job.log}\ncmd=${one}\n`)
199
200
  } catch {
200
201
  /* 记录写不进去 = 这个作业停不了(fail-closed,且 team bg list 里可见);作业本身照常跑 */
201
202
  }
@@ -291,7 +292,8 @@ export default function (pi: ExtensionAPI) {
291
292
  additionalProperties: false,
292
293
  } as any,
293
294
  async execute(_toolCallId: string, params: any, _signal: any, _onUpdate: any, ctx: any) {
294
- const root = findRoot(String(ctx?.cwd ?? process.cwd()))
295
+ const sessionCwd = resolve(String(ctx?.cwd ?? process.cwd()))
296
+ const root = findRoot(sessionCwd)
295
297
  if (!root) throw new Error('team_bg_run: not a teamsmith project (no .pi/team/config.sh found)')
296
298
  const command = String(params?.command ?? '')
297
299
  if (!command.trim()) throw new Error('team_bg_run: empty command')
@@ -310,7 +312,7 @@ export default function (pi: ExtensionAPI) {
310
312
  closeSync(fd)
311
313
  }
312
314
  const job: Job = {
313
- id, root, pid: child.pid ?? 0, command, cwd, log, startedAt: Date.now(),
315
+ id, root, pid: child.pid ?? 0, command, sessionCwd, cwd, log, startedAt: Date.now(),
314
316
  done: false, exitCode: null, harvested: false, notified: false, waiters: [],
315
317
  }
316
318
  jobs.set(id, job)
@@ -1255,7 +1255,7 @@ export default function (pi: ExtensionAPI) {
1255
1255
  /** 读 spool 的新行并合并成一条唤醒(同一拍收到的多行只叫一次)。
1256
1256
  * 日志写不进去时 `deliverNormal` 返回 blocked:offset 不动,行保持未读(下一拍重读)。 */
1257
1257
  const flush = (): void => {
1258
- if (!spool) return
1258
+ if (!spool || (reminderOnly && !reminderReleased)) return
1259
1259
  try { runRetryTick() } catch { /* ignore */ }
1260
1260
  try { runRecoveryTick() } catch { /* ignore */ }
1261
1261
  const res = readNewLines(spool, offset)
@@ -1334,6 +1334,8 @@ export default function (pi: ExtensionAPI) {
1334
1334
  let remindModule: any = null
1335
1335
  let remindBusy = false
1336
1336
  let remindWarned = ''
1337
+ let reminderOnly = false
1338
+ let reminderReleased = false
1337
1339
 
1338
1340
  const reminderPollMs = (): number => {
1339
1341
  const n = Number(process.env.TEAM_REMIND_POLL_MS ?? NaN)
@@ -1423,6 +1425,7 @@ export default function (pi: ExtensionAPI) {
1423
1425
  try {
1424
1426
  const res = await remindAuthority.request({ cwd: remindRoot, mainRoot: remindRoot, stateRoot: remindState || defaultStateRoot() }, {
1425
1427
  op: 'remind-observe', id: String(details.batchId), nonce: String(details.nonce ?? ''), session: remindSession,
1428
+ members: Array.isArray(details.members) ? details.members.map((id: unknown) => String(id)) : null,
1426
1429
  })
1427
1430
  if (!res?.ok) {
1428
1431
  appendLedger(root, `reminder observation refused (${res?.refusal ?? 'unknown'}): ${oneLine(String(res?.reason ?? ''), 200)}`)
@@ -1430,6 +1433,11 @@ export default function (pi: ExtensionAPI) {
1430
1433
  appendLedger(root, `reminder duplicate event batch=${res.batch}(right 已花掉;未再退待命)`)
1431
1434
  } else {
1432
1435
  appendLedger(root, `reminder observed batch=${res.batch} standby=${res.standby} generation=${res.generation} ids=${(res.ids ?? []).join('|')}`)
1436
+ if (reminderOnly && !reminderReleased && res.outcome === 'observed' && (res.standby === 'auto-off' || res.standby === 'already-off')) {
1437
+ reminderReleased = true
1438
+ appendLedger(root, `reminder-only released batch=${res.batch} standby=${res.standby}(普通 watcher 恢复;启动前 backlog 仍按基线处理)`)
1439
+ flush()
1440
+ }
1433
1441
  }
1434
1442
  } catch (error) {
1435
1443
  appendLedger(root, `reminder observation failed: ${oneLine(shortError(error), 200)}`)
@@ -1438,6 +1446,8 @@ export default function (pi: ExtensionAPI) {
1438
1446
 
1439
1447
  pi.on('session_start', async (_event: any, ctx: any) => {
1440
1448
  stopAll()
1449
+ reminderOnly = process.env.TEAM_REMINDER_ONLY_RECOVERY === '1'
1450
+ reminderReleased = !reminderOnly
1441
1451
  root = findRoot(String(ctx?.cwd ?? process.cwd()))
1442
1452
  if (!root) return
1443
1453
  noteIdentityFileConflicts(root)
@@ -1535,7 +1545,8 @@ export default function (pi: ExtensionAPI) {
1535
1545
  }
1536
1546
  maybeCompact()
1537
1547
  baselineSwallowed()
1538
- runRecoveryTick()
1548
+ if (!reminderOnly) runRecoveryTick()
1549
+ else appendLedger(root, 'reminder-only ordinary delivery held(等待匹配的 Reminder 观察;不重放普通 recovery/backlog)')
1539
1550
  // M53 · 失败不再静默:errno + 额度观察 + 轮询间隔进账本,并写一条耐久降级记录(读的人看 pid+cwd)。
1540
1551
  // 夹具旋钮强制失败时同样走这条路径(evidence 里带 forced=1,免得测试事故被当成真事故)。
1541
1552
  const forced = forcedWatchErrno()
@@ -1571,6 +1582,6 @@ export default function (pi: ExtensionAPI) {
1571
1582
  journalPath = ''; journalEntries = new Map(); retryQueue = new Map(); recoveryQueue = new Map()
1572
1583
  delivered = new Set(); floorTs = null; floorId = ''; journalRecords = 0; abortAt = ''
1573
1584
  remindRoot = ''; remindState = ''; remindSession = ''; remindAuthority = null; remindModule = null
1574
- remindBusy = false; remindWarned = ''
1585
+ remindBusy = false; remindWarned = ''; reminderOnly = false; reminderReleased = false
1575
1586
  })
1576
1587
  }
@@ -205,20 +205,26 @@ function ownedSessionPaths(cwd: string, worktree: string): Set<string> {
205
205
  return owned
206
206
  }
207
207
 
208
- /** P236 · 归属判据:作业记录里的 `cwd`(作业启动时的工作目录,也就是拥有它的那个席位的工作树)
209
- * 解析到本会话自己的工作树/cwd(真实路径相等)才算「我的作业」。缺 `cwd`、相对路径、解析失败、
210
- * 或指向别人的工作树 → 都不算(fail-closed)。 */
208
+ /** 新记录只看发起会话的 `session_cwd`;执行目录可以是独立 clone,不能顶替发起身份。
209
+ * 旧记录没有该字段时才走有界兼容:`cwd` 必须恰好解析到席位工作树,不能是会话恰好所在的子目录。 */
211
210
  function isOwnedCwd(jobCwd: string, owned: Set<string>): boolean {
212
211
  const real = realPathOf(jobCwd)
213
212
  return real !== '' && owned.has(real)
214
213
  }
215
214
 
215
+ function isOwnedJob(fields: Record<string, string>, owned: Set<string>, legacyWorktree: string): boolean {
216
+ if (Object.prototype.hasOwnProperty.call(fields, 'session_cwd')) {
217
+ return isOwnedCwd(fields.session_cwd ?? '', owned)
218
+ }
219
+ const real = realPathOf(fields.cwd ?? '')
220
+ return real !== '' && real === legacyWorktree
221
+ }
222
+
216
223
  /** 在跑作业集合:读车道目录下的 `bg/*.job`,逐条做 (pid, start-time) 活体验证(与 `team bg list`
217
- * 同一条身份规则),再按 `cwd` 只留**本会话自己的**作业(P236 归属范围 —— 同一车道目录里的记录
218
- * 可能属于别的席位,把别人的长作业算成自己挂起会污染 `awaiting=`)。任何一条失败都**跳过**
219
- * (目录/记录读不了、软链-FIFO 记录、pid 非正整数、start 缺失、/proc 读不到、指纹不符、cwd 缺失
220
- * 或不属于本会话)—— fail-closed:判定的不确定方向永远是「不挂起」,绝不假造挂起(design 决策 4)。 */
221
- function runningLaneJobs(laneDir: string, owned: Set<string>): string[] {
224
+ * 同一条身份规则),再按发起身份只留**本会话自己的**作业(同一车道目录里的记录可能属于别的席位)。
225
+ * 任何一条失败都**跳过**(目录/记录读不了、软链-FIFO 记录、pid 非正整数、start 缺失、/proc 读不到、
226
+ * 指纹不符、发起目录缺失或不属于本会话)—— fail-closed:绝不假造挂起。 */
227
+ function runningLaneJobs(laneDir: string, owned: Set<string>, legacyWorktree: string): string[] {
222
228
  if (!laneDir || owned.size === 0) return []
223
229
  let names: string[]
224
230
  try {
@@ -243,7 +249,7 @@ function runningLaneJobs(laneDir: string, owned: Set<string>): string[] {
243
249
  const start = fields.start ?? ''
244
250
  if (!Number.isInteger(pid) || pid <= 0 || !start) continue
245
251
  if (procStartTime(pid) !== start) continue // 死进程 / pid 复用 / /proc 读不到:都不算在跑
246
- if (!isOwnedCwd(fields.cwd ?? '', owned)) continue // P236:别人的作业不算自己挂起
252
+ if (!isOwnedJob(fields, owned, legacyWorktree)) continue // 别人的作业不算自己挂起
247
253
  ids.push(id)
248
254
  } catch {
249
255
  continue // 读不了:不算在跑
@@ -561,15 +567,16 @@ export default function (pi: ExtensionAPI) {
561
567
  // 逐条 (pid, start-time) 验活、再按 cwd 只留**本会话自己的**作业;判定失败一律退回非挂起形状
562
568
  // (fail-closed)——既不假造挂起,也不拿 notify 自己的 root 顶替车道目录(两侧分歧时它只负责把
563
569
  // 这件事记进日志)。
564
- // P236(缺陷现场):同一车道目录里的记录可能属于**别的席位** —— 只看「项目里有活作业」会把别人的
565
- // 长作业算成自己挂起。归属判据 = 作业的 cwd 与本会话自己的工作树/cwd 解析到同一个真实路径。
570
+ // 同一车道目录里的记录可能属于**别的席位**。新记录按 session_cwd 认发起会话,执行 cwd 可指向
571
+ // 独立 clone;只有旧记录才按恰好等于席位工作树的 cwd 兼容,其它路径一律不收养。
566
572
  const laneDir = laneStateDir(cwd)
567
573
  const ownDir = notifyStateDir(root)
568
574
  if (laneDir && ownDir && laneDir !== ownDir) {
569
575
  log(`suspend check reads the lane's directory ${laneDir} (notify's own root would be ${ownDir})`, cfg)
570
576
  }
571
- const owned = ownedSessionPaths(cwd, join(wtPrefix, agent))
572
- const running = runningLaneJobs(laneDir, owned)
577
+ const worktree = join(wtPrefix, agent)
578
+ const owned = ownedSessionPaths(cwd, worktree)
579
+ const running = runningLaneJobs(laneDir, owned, realPathOf(worktree))
573
580
  const awaiting = running.length > 0 ? `awaiting=${running.join(',')}` : ''
574
581
  const suspended = completed && running.length > 0
575
582
 
@@ -0,0 +1,189 @@
1
+ /** Directed PM-only team_remind tool. Ordinary Pi and workers never receive an active tool. */
2
+ import type { ExtensionAPI, ExtensionContext } from '@earendil-works/pi-coding-agent'
3
+ import { createHash, randomUUID } from 'node:crypto'
4
+ import { readFileSync, realpathSync } from 'node:fs'
5
+ import { dirname, join } from 'node:path'
6
+ import { fileURLToPath } from 'node:url'
7
+
8
+ const entry = realpathSync(fileURLToPath(import.meta.url))
9
+ const skill = dirname(dirname(entry))
10
+ const hash = (bytes: Buffer | string) => createHash('sha256').update(bytes).digest('hex')
11
+ const moduleURL = (bytes: string) => `data:text/javascript;base64,${Buffer.from(bytes).toString('base64')}`
12
+
13
+ export default async function (pi: ExtensionAPI) {
14
+ // Bypass dependency caches on reload: registration and the doctor fingerprint describe this loaded source.
15
+ const capabilityBytes = readFileSync(join(skill, 'scripts/remind-capability.mjs'), 'utf8')
16
+ const identityBytes = readFileSync(join(skill, 'scripts/reply-capture.mjs'), 'utf8')
17
+ const repliesBytes = readFileSync(join(skill, 'scripts/replies.mjs'), 'utf8')
18
+ const repliesURL = moduleURL(repliesBytes)
19
+ const identityURL = moduleURL(identityBytes.replace("'./replies.mjs'", JSON.stringify(repliesURL)))
20
+ const capabilityURL = moduleURL(capabilityBytes.replace("'./reply-capture.mjs'", JSON.stringify(identityURL)))
21
+ const capability = await import(capabilityURL)
22
+ const extensionVersion = capability.remindCapabilityFingerprint({
23
+ 'extension/team-remind.ts': hash(readFileSync(entry)),
24
+ 'scripts/remind-capability.mjs': hash(capabilityBytes),
25
+ 'scripts/reply-capture.mjs': hash(identityBytes),
26
+ 'scripts/replies.mjs': hash(repliesBytes),
27
+ })
28
+ const context = (ctx: ExtensionContext) => ({
29
+ cwd: ctx.cwd,
30
+ sessionId: ctx.sessionManager.getSessionId(),
31
+ sessionFile: ctx.sessionManager.getSessionFile(),
32
+ })
33
+
34
+ let active = false
35
+ let expected: any = null
36
+ let generation = randomUUID()
37
+ let heartbeat: ReturnType<typeof setInterval> | null = null
38
+ const stopHeartbeat = () => { if (heartbeat) { clearInterval(heartbeat); heartbeat = null } }
39
+ const removeFromModel = () => {
40
+ if (typeof (pi as any).getActiveTools === 'function' && typeof (pi as any).setActiveTools === 'function') {
41
+ ;(pi as any).setActiveTools((pi as any).getActiveTools().filter((name: string) => name !== 'team_remind'))
42
+ }
43
+ }
44
+ const hide = (reason = 'session or PM identity changed') => {
45
+ const previous = expected
46
+ active = false
47
+ stopHeartbeat()
48
+ pi.registerTool({ ...definition('hidden'), defaultActive: false } as any)
49
+ removeFromModel()
50
+ if (previous) {
51
+ // Doctor must stop reporting ready in the same switch/fork/reload, not one TTL later. Evidence
52
+ // withdrawal is best effort: a failed write leaves the old record freshness-bounded.
53
+ try { capability.publishRemindCapability(previous, { generation, extensionVersion, status: 'hidden', exposure: 'hidden', reason }) }
54
+ catch { /* the previous evidence still expires by its existing TTL */ }
55
+ }
56
+ }
57
+ const publish = (status: string, exposure: string, reason: string | null = null) => {
58
+ if (!expected) throw new Error('team_remind: no verified identity for capability evidence')
59
+ capability.publishRemindCapability(expected, { generation, extensionVersion, status, exposure, reason })
60
+ }
61
+
62
+ const activate = (ctx: ExtensionContext): boolean => {
63
+ let candidate: any
64
+ try { candidate = capability.resolveRemindIdentity(context(ctx), process.env) }
65
+ catch (e: any) {
66
+ try {
67
+ // A valid current PM with invalid generated config gets an explicit load error. This bypasses
68
+ // only the config comparison for evidence; the tool remains hidden and no Reminder state is touched.
69
+ expected = capability.resolveRemindIdentity(context(ctx), process.env, { checkConfiguration: false })
70
+ pi.registerTool({ ...definition('hidden'), defaultActive: false } as any)
71
+ removeFromModel()
72
+ publish('error', 'hidden', e?.message ?? String(e))
73
+ } catch {
74
+ // Missing/forged PM evidence, or evidence that cannot be written, stays unknown.
75
+ expected = null
76
+ }
77
+ return false
78
+ }
79
+ expected = candidate
80
+ try {
81
+ pi.registerTool(definition('direct') as any)
82
+ publish('registered', 'direct')
83
+ active = true
84
+ stopHeartbeat()
85
+ heartbeat = setInterval(() => refresh(ctx), 5000)
86
+ heartbeat.unref()
87
+ return true
88
+ } catch (e: any) {
89
+ active = false
90
+ stopHeartbeat()
91
+ pi.registerTool({ ...definition('hidden'), defaultActive: false } as any)
92
+ removeFromModel()
93
+ // A bootstrap failure after valid identity is explicit only while this launch evidence remains fresh.
94
+ publish('error', 'hidden', e?.message ?? String(e))
95
+ return false
96
+ }
97
+ }
98
+
99
+ const refresh = (ctx: ExtensionContext): boolean => {
100
+ if (!active || !expected) return false
101
+ try {
102
+ const current = capability.resolveRemindIdentity(context(ctx), process.env)
103
+ if (expected.launchNonce === null && current.launchNonce !== null) expected = current
104
+ if (!capability.sameRemindIdentity(expected, current)) { hide('PM project/process/tmux/session/launch identity changed'); return false }
105
+ publish('registered', 'direct')
106
+ return true
107
+ } catch {
108
+ hide('PM identity could not be revalidated')
109
+ return false
110
+ }
111
+ }
112
+
113
+ const verify = (ctx: ExtensionContext) => {
114
+ if (!active && !activate(ctx)) throw new Error('team_remind: refused before Reminder-state access (not a verified current PM session)')
115
+ const current = capability.resolveRemindIdentity(context(ctx), process.env, { requireLaunch: true })
116
+ if (expected.launchNonce === null && current.launchNonce !== null) expected = current
117
+ if (!capability.sameRemindIdentity(expected, current)) {
118
+ hide('PM project/process/tmux/session/launch identity changed')
119
+ throw new Error('team_remind: PM project/process/tmux/session/launch identity changed; refused before Reminder-state access')
120
+ }
121
+ try { publish('registered', 'direct') }
122
+ catch (e: any) {
123
+ hide()
124
+ throw new Error(`team_remind: capability evidence could not be refreshed; refused before Reminder-state access: ${e.message}`)
125
+ }
126
+ return expected
127
+ }
128
+
129
+ function definition(exposure: 'direct' | 'hidden') {
130
+ return {
131
+ name: 'team_remind',
132
+ label: 'PM self-reminder',
133
+ description: 'Create, list, inspect or cancel one-shot reminders for this project PM. The current verified PM is always the owner; full message text is preserved.',
134
+ promptSnippet: 'team_remind: schedule or inspect a durable one-shot reminder for this PM',
135
+ promptGuidelines: ['Use team_remind when this PM decides to revisit work at a future time; after an observed wake, create the next one-shot reminder with the same key when appropriate.'],
136
+ exposure,
137
+ executionMode: 'sequential',
138
+ parameters: {
139
+ type: 'object',
140
+ properties: {
141
+ action: { type: 'string', enum: ['add', 'list', 'show', 'cancel'] },
142
+ at: { type: 'string', description: 'RFC 3339 date-time with Z or a numeric offset; exactly one of at/after for add' },
143
+ after: { type: 'string', description: 'Positive integer plus s, m or h; exactly one of at/after for add' },
144
+ key: { type: 'string', description: 'Optional logical key for active-request idempotency' },
145
+ task: { type: 'string', description: 'Optional existing task reference' },
146
+ message: { type: 'string', description: 'Complete reminder text for add; never truncated' },
147
+ id: { type: 'string', description: 'Reminder ID for show or cancel' },
148
+ all: { type: 'boolean', description: 'For list, include retained terminal history' },
149
+ },
150
+ required: ['action'],
151
+ additionalProperties: false,
152
+ },
153
+ async execute(_toolCallId: string, params: any, signal: AbortSignal | undefined, _onUpdate: any, ctx: ExtensionContext) {
154
+ const identity = verify(ctx)
155
+ const result = await capability.runReminderAuthority({ identity, skill, action: params.action, params, signal })
156
+ return {
157
+ content: [{ type: 'text', text: JSON.stringify(result, null, 2) }],
158
+ details: result,
159
+ ...(result.ok ? {} : { isError: true }),
160
+ }
161
+ },
162
+ }
163
+ }
164
+
165
+ // A discovered/global copy starts unreachable. Only session_start can prove a directed PM and activate it.
166
+ pi.registerTool({ ...definition('hidden'), defaultActive: false } as any)
167
+ pi.on('session_start', (_event, ctx) => {
168
+ hide('session reloaded or replaced')
169
+ expected = null
170
+ generation = randomUUID()
171
+ hide()
172
+ activate(ctx)
173
+ })
174
+ for (const event of ['session_before_switch', 'session_before_fork'] as const) {
175
+ pi.on(event, () => { if (expected) hide(event === 'session_before_fork' ? 'session forked' : 'session switched') })
176
+ }
177
+ pi.on('before_agent_start', (_event, ctx) => { if (!active) activate(ctx) })
178
+ pi.on('session_shutdown', () => {
179
+ stopHeartbeat()
180
+ active = false
181
+ if (expected) {
182
+ try { capability.removeRemindCapability(expected, generation) }
183
+ catch (e: any) {
184
+ if (e?.code !== 'ENOENT') process.stderr.write(`[team-remind] capability cleanup failed: ${e?.message ?? e}\n`)
185
+ }
186
+ }
187
+ expected = null
188
+ })
189
+ }