teamsmith 0.3.4 → 0.4.0

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 (68) hide show
  1. package/README.md +8 -8
  2. package/package.json +1 -1
  3. package/skills/teamsmith/CHANGELOG.md +30 -0
  4. package/skills/teamsmith/SKILL.md +83 -163
  5. package/skills/teamsmith/extension/team-notify.ts +1 -1
  6. package/skills/teamsmith/extension/team-reply.ts +105 -0
  7. package/skills/teamsmith/references/agent-adapters.md +1 -1
  8. package/skills/teamsmith/references/config.md +20 -11
  9. package/skills/teamsmith/references/migration.md +47 -3
  10. package/skills/teamsmith/references/protocol.md +64 -31
  11. package/skills/teamsmith/references/reminders.md +131 -0
  12. package/skills/teamsmith/references/troubleshooting.md +19 -5
  13. package/skills/teamsmith/references/workflows.md +18 -16
  14. package/skills/teamsmith/scripts/lib/cmd-agents.sh +77 -49
  15. package/skills/teamsmith/scripts/lib/cmd-project.sh +193 -21
  16. package/skills/teamsmith/scripts/lib/cmd-remind.sh +103 -0
  17. package/skills/teamsmith/scripts/lib/cmd-update.sh +7 -4
  18. package/skills/teamsmith/scripts/lib/common.sh +44 -4
  19. package/skills/teamsmith/scripts/lib/outbox.sh +72 -18
  20. package/skills/teamsmith/scripts/remind-store.mjs +529 -0
  21. package/skills/teamsmith/scripts/replies.mjs +9 -3
  22. package/skills/teamsmith/scripts/reply-capture.mjs +596 -0
  23. package/skills/teamsmith/scripts/state-authority.mjs +500 -0
  24. package/skills/teamsmith/scripts/strings/commands.tsv +2 -1
  25. package/skills/teamsmith/scripts/strings/help.en.tsv +16 -2
  26. package/skills/teamsmith/scripts/strings/help.zh.tsv +16 -2
  27. package/skills/teamsmith/scripts/team +1 -0
  28. package/skills/teamsmith/templates/AGENTS.section.md.tmpl +68 -123
  29. package/skills/teamsmith/templates/PROTOCOL.md.tmpl +48 -55
  30. package/skills/teamsmith/templates/pm-prompt.md.tmpl +126 -119
  31. package/skills/teamsmith/tests/checkout-shape-probe.sh +6 -5
  32. package/skills/teamsmith/tests/delivery-truth.sh +82 -47
  33. package/skills/teamsmith/tests/fixtures/delivery-truth-real/README.md +71 -23
  34. package/skills/teamsmith/tests/fixtures/delivery-truth-real/__pycache__/judge-second.cpython-313.pyc +0 -0
  35. package/skills/teamsmith/tests/fixtures/delivery-truth-real/judge-dirty-ab.py +143 -0
  36. package/skills/teamsmith/tests/fixtures/delivery-truth-real/judge-second.py +26 -9
  37. package/skills/teamsmith/tests/fixtures/delivery-truth-real/run-case.sh +92 -20
  38. package/skills/teamsmith/tests/fixtures/delivery-truth-real/scenario.sh +47 -3
  39. package/skills/teamsmith/tests/fixtures/reply-capture-provider.ts +76 -0
  40. package/skills/teamsmith/tests/flip-p410-order2.sh +205 -0
  41. package/skills/teamsmith/tests/frames/README.md +3 -1
  42. package/skills/teamsmith/tests/gate-guard.sh +20 -4
  43. package/skills/teamsmith/tests/help-surface.sh +60 -2
  44. package/skills/teamsmith/tests/install-shape.sh +312 -0
  45. package/skills/teamsmith/tests/key-replies-pty.sh +197 -21
  46. package/skills/teamsmith/tests/key-replies.sh +187 -68
  47. package/skills/teamsmith/tests/ledger-claim.sh +8 -6
  48. package/skills/teamsmith/tests/lib/box-judge.sh +2 -1
  49. package/skills/teamsmith/tests/lib/main-team-fingerprint.sh +104 -0
  50. package/skills/teamsmith/tests/lib/pm-window.sh +127 -0
  51. package/skills/teamsmith/tests/lib/reply-fixture.sh +7 -19
  52. package/skills/teamsmith/tests/lib/reply-guard.sh +188 -0
  53. package/skills/teamsmith/tests/lib/section-calls.pl +171 -0
  54. package/skills/teamsmith/tests/loop-inventory.tsv +7 -5
  55. package/skills/teamsmith/tests/meta-suite.sh +215 -0
  56. package/skills/teamsmith/tests/panel-b3-pty-mouse.py +154 -17
  57. package/skills/teamsmith/tests/panel-b3.sh +33 -4
  58. package/skills/teamsmith/tests/remind-cli.sh +574 -0
  59. package/skills/teamsmith/tests/reply-capture-real.mjs +360 -0
  60. package/skills/teamsmith/tests/reply-capture-real.sh +5 -0
  61. package/skills/teamsmith/tests/reply-capture.mjs +622 -0
  62. package/skills/teamsmith/tests/section-paths.tsv +40 -9
  63. package/skills/teamsmith/tests/section-select.sh +180 -26
  64. package/skills/teamsmith/tests/smoke.sh +1235 -238
  65. package/skills/teamsmith/tests/state-authority-node.mjs +42 -0
  66. package/skills/teamsmith/tests/state-authority.sh +629 -0
  67. package/skills/teamsmith/tests/workflow-entry.sh +123 -3
  68. package/skills/teamsmith-init/SKILL.md +1 -1
package/README.md CHANGED
@@ -39,7 +39,7 @@ you install is the product (this file, `skills/`, `bin/`, `openspec/specs/`), no
39
39
  ```bash
40
40
  npm install -g teamsmith # the `team` CLI: one npm bin entry, checks bash >= 5 and prints the fix if it is missing
41
41
  cd your-project
42
- team init # config + docs skeleton + both skills into the project's .pi/skills/
42
+ team init # config + docs skeleton + all three bundled skills into the project's .pi/skills/
43
43
  ```
44
44
 
45
45
  > First session in that project: Pi asks **“Project is not trusted”** before it will load project resources
@@ -47,7 +47,7 @@ team init # config + docs skeleton + both skills into the pro
47
47
  > answer `pi --approve` (this once) or approve the project in Pi's UI — nothing else is needed, and the skills are
48
48
  > not modified either way.
49
49
 
50
- `team init` installs `teamsmith` and `teamsmith-init` into the project's **`.pi/skills/`** — Pi's project-level
50
+ `team init` installs `teamsmith`, `teamsmith-init` and `handover` into the project's **`.pi/skills/`** — Pi's project-level
51
51
  skill search path — so any session in that project sees the toolkit (the `openspec init` model: per project, and
52
52
  version-lockable). The default is a symlink to the package, so package updates are live; `--copy` copies the files
53
53
  instead (for an ephemeral source such as an `npx` cache, excluding `.git/` and `node_modules/`), and `--no-skills`
@@ -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.3.4 # user level: every project
61
- pi install -l git:git@github.com:Track07-cda/teamsmith@v0.3.4 # project level: recorded in .pi/settings.json
60
+ pi install git:git@github.com:Track07-cda/teamsmith@v0.4.0 # user level: every project
61
+ pi install -l git:git@github.com:Track07-cda/teamsmith@v0.4.0 # 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.3.4`) uses your SSH key and works
67
- whether or not you have a token; the shorthand `git:github.com/Track07-cda/teamsmith@v0.3.4` takes the HTTPS
66
+ - The `git@github.com:` form (or `ssh://git@github.com/Track07-cda/teamsmith@v0.4.0`) uses your SSH key and works
67
+ whether or not you have a token; the shorthand `git:github.com/Track07-cda/teamsmith@v0.4.0` 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`.
@@ -92,8 +92,8 @@ On a non-Pi host, `install.sh` puts the skill **files** where a skill directory
92
92
 
93
93
  ### What the package declares — and what it deliberately does not
94
94
 
95
- The manifest (`package.json`) declares the two skills (`pi.skills: ["./skills"]` loads `teamsmith` and
96
- `teamsmith-init`) and exactly one npm `bin` entry — `team` → `bin/team.mjs`, a transparent wrapper that runs the
95
+ The manifest (`package.json`) declares the three bundled skills (`pi.skills: ["./skills"]` loads `teamsmith`,
96
+ `teamsmith-init` and `handover`) and exactly one npm `bin` entry — `team` → `bin/team.mjs`, a transparent wrapper that runs the
97
97
  bash CLI with your argv, stdio and exit status. The files under `skills/teamsmith/extension/` (`team-notify.ts`, `team-bg.ts`,
98
98
  `team-inbox-watch.ts`) are deliberately **not** in the manifest: teamsmith injects each of them with `-e` when it
99
99
  starts a PM or a worker window, so they exist only inside team windows. Installing the package adds no global
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "teamsmith",
3
- "version": "0.3.4",
3
+ "version": "0.4.0",
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,36 @@
5
5
  > `SKILL.md`/`references/**`/`templates/**`/`extension/**` 在 Pi 里输入 `/reload`(或 `/pi-team-reload`)即生效;
6
6
  > 判断自己是不是旧的:`team mark-loaded`(开局记一次)→ `team version --check`。
7
7
 
8
+ ## v0.4.0(2026-11-04)
9
+
10
+ 升级方式:在 Pi 中执行 `/reload`,或运行 `npm i -g teamsmith@0.4.0`。无配置迁移。
11
+
12
+ ### 行为变更
13
+
14
+ - `team say` 默认直接投递到目标窗口,失败时才进队列。`--now` 已移除,传入该参数会报错并提示替代用法。
15
+ - 关键回复:在回答末行写 `[[team-reply]]`(可带标题),由扩展捕获为编号回复;`team reply post` 仅用于手工补录。该标记在流式输出中短暂可见,最终正文、后续对话、回复页与历史中均不包含。
16
+
17
+ ### 初始化
18
+
19
+ - `team init` 只替换 Teamsmith 标记之间的内容,标记外保持不变,包括项目规则、CRLF 与文件末尾换行;标记不明确时报错退出,不做猜测性修改。
20
+ - 会话名与席位名单优先读取项目已有配置,不再回落到目录名与默认名单。
21
+
22
+ ### 文档体积
23
+
24
+ - PM 启动时读取的三份说明合计减少 16%;`SKILL.md` 334 → 251 行;AGENTS 托管段 167 → 112 行。
25
+ - 删除内容为重复表述、失效的文件引用与与实现不符的描述;规则集合未变。
26
+
27
+ ### 新增
28
+
29
+ - `team remind add|list|show|cancel`:支持绝对时间与 `30s`/`5m`/`2h` 相对写法,可为提醒设置去重键。本版本不投递,不会自动唤醒。
30
+ - 项目状态由命令行、巡检与 Pi 共用一份记录与一把锁;记录损坏或锁不可用时直接报错。
31
+
32
+ ### 测试与工具链
33
+
34
+ - CI 使用当前最新 Pi 版本,不再钉住旧版本。
35
+ - 修正五处测试缺陷:数字 UID 下误判为失败、面板把临时窗口计入基线、滚动判定早于输入完成、隔离检查范围过宽、段落之间残留工作目录。
36
+ - OpenSpec 升级至 1.16;仓库规格校验暂未启用 strict 模式,原因与清理计划见 `docs/team/reviews/release-0.4.0-prep.md`。
37
+
8
38
  ## v0.3.4(2026-10-26)
9
39
 
10
40
  补丁版:**没有破坏性配置迁移、没有新依赖**。这一版主要修通知可靠性,以及三处会让使用者误判状态的缺陷。
@@ -3,7 +3,7 @@ name: teamsmith
3
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.
4
4
  license: MIT
5
5
  metadata:
6
- version: "0.3.4"
6
+ version: "0.4.0"
7
7
  ---
8
8
 
9
9
  # teamsmith · one agent that actually owns the project
@@ -18,31 +18,23 @@ 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 + PR/MR
21
+ review(independent checkout, run gates) ──▶ reports/<ID>-<a>.md (local branch; remote on the PM's route)
22
22
  merge / close ──────────────────▶ BOARD → done
23
23
  ```
24
24
 
25
25
  ## Starting a new project: use the `teamsmith-init` skill
26
26
 
27
- Initialization lives in its own skill: load the **`teamsmith-init`** skill and read its SKILL.md — install the CLI
28
- (`npm install -g teamsmith`) and run `team init`, which writes the config, the `docs/team/` skeleton and both skills
29
- into the project's **`.pi/skills/`** — then the ordered questions to settle with the user,
30
- `bash <teamsmith>/scripts/team bootstrap`, and the handoff back here. A machine-global install (`pi install …`,
31
- `~/.agents/skills` via `install.sh`, or a settings `skills` entry) is the alternative route to the same skill;
32
- everything below is the daily loop, which starts once the project is up.
27
+ Initialization lives in its own skill: read **`teamsmith-init`**'s SKILL.md for the install, the ordered questions to
28
+ settle with the user, `bash <teamsmith>/scripts/team bootstrap` and the handoff back here. Everything below is the
29
+ daily loop, which starts once the project is up.
33
30
 
34
31
  ## Name and compatibility (former name: pi-team)
35
32
 
36
- - Renamed from **`pi-team`** to **`teamsmith`** in v1.13.0 (repo name included).
37
- - **Contracts unchanged**: the command is still **`team`**; project config is still **`.pi/team/config.sh`**;
38
- env vars are still **`TEAM_*`**; team docs are still **`docs/team/**`**. Existing projects need no changes.
39
- - The old path `skills/pi-team` **no longer exists**: the compatibility symlink was removed (M22, the alias period
40
- ended early by the user's call). A project or `settings.json` that hard-codes the old absolute path must change it
41
- to `skills/teamsmith` (or to the installed `~/.agents/skills/teamsmith`) — see `references/migration.md` §2.
42
- - An `AGENTS.md` section marked `<!-- pi-team:begin -->` is migrated in place to the new marker by the next
43
- `team init`/`bootstrap`.
44
- - Hot-reload command in Pi: `/teamsmith-reload` (the old `/pi-team-reload` stays registered as an alias — the
45
- alias is a **command name**, unrelated to the removed path).
33
+ Renamed from **`pi-team`** in v1.13.0; the contracts did not move (command `team`, `.pi/team/config.sh`, `TEAM_*`,
34
+ `docs/team/**`). The `skills/pi-team` alias is **gone**, so a hard-coded old path must become `skills/teamsmith`; an
35
+ `AGENTS.md` carrying the legacy `<!-- pi-team:begin -->` marker is converted in place by an **explicit `team init`**
36
+ (an existing valid config's `team bootstrap` does not refresh it). Renames, removed commands, dependency changes and
37
+ the upgrade recipe: [references/migration.md](references/migration.md) §§1b–4/6.
46
38
 
47
39
  ## Command table
48
40
 
@@ -51,11 +43,11 @@ everything below is the daily loop, which starts once the project is up.
51
43
  | Init / self-check | `team init [--session s] [--agents "a b"] [--vcs local\|remote] --task-models '<category=provider/model …>' --pm-model '<provider/model>' [--copy\|--no-skills]` (fresh projects must pass both model inputs; installs both skills into the project's `.pi/skills/`), `team doctor` (reports that install, warns on drift) |
52
44
  | Observe | `team roster` (windows/branch/dirty/ahead), `team status [ID]`, `team ps` (capacity + model limits + PM/pulse liveness), `team digest` (PM's pending work) |
53
45
  | Inbox | `team inbox [agent] [--ack] [--all]` |
54
- | Key replies | **The outlet for replies written for the user** (a landed milestone, a ruling, a conclusion, an answer, a status or progress report, a decision you ask the user for, a delivery or verification summary — however short, and never held back because it reads like process rather than like a conclusion): publish the complete reply — the substance the user needs to read, not a play-by-play — with `team reply post --from <seat> --title "<short>" --stdin`, then send that same body; a batch of user-facing replies may be one reply. A reply written to the patrol, to another seat or to another project's PM, and a tool receipt, are not for the user and stay out. Distinct from the internal channels: `say`/`notify` carry one-line coordination to a seat or the PM, not the reply itself. A saved receipt means project-local durable publication only — never user delivery, approval, read status or a refreshed console. `team reply list [--before <no>] [--json]`, `team reply show <no> [--json\|--raw]` (readers are observation-only: no mkdir, no writes, no lock; `--raw` exports the original bytes and refuses a TTY). The console's page 5 shows the latest reply plus the numbered history. See `references/protocol.md` §4b |
46
+ | Key replies | **The outlet for replies written for the user** (a landed milestone, a ruling, a conclusion, an answer, a status or progress report, a decision you ask the user for, a delivery or verification summary — however short, and never held back because it reads like process rather than like a conclusion): write the complete reply — the substance the user needs to read, not a play-by-play — in the normal answer and end it with the final control line `[[team-reply]]` (or `[[team-reply:<short title>]]` for a title you choose); the directed PM extension publishes that message's sanitized body to the reply page, and your answer goes out with only that line removed. No temp file or heredoc, and no post-then-repeat: `team reply post --from <seat> --title "<short>" --stdin` is the **manual** publication, backfill and recovery entry only, and an unmarked answer is never published by inference. A batch of user-facing replies may be one reply. A reply written to the patrol, to another seat or to another project's PM, and a tool receipt, are not for the user and stay out. Distinct from the internal channels: `say`/`notify` carry one-line coordination to a seat or the PM, not the reply itself. A saved receipt means project-local durable publication only — never user delivery, approval, read status or a refreshed console. `team reply list [--before <no>] [--json]`, `team reply show <no> [--json\|--raw]` (readers are observation-only: no mkdir, no writes, no lock; `--raw` exports the original bytes and refuses a TTY). The console's page 5 shows the latest reply plus the numbered history. See `references/protocol.md` §4b |
55
47
  | Document contracts | `team task <ID> --title ... --agent a`, `team board add\|assign\|set\|ls`, `team change status <id> [--json]` (readiness view: tasks/evidence, declared vs touched delta files, blockers; exit 0 iff every mapped task is finished), `team thread <a> "..." --from pm --re <ID>`, `team report <ID> <a>` |
56
48
  | Dispatch | `team add-agent <a> [--register] [--create] [--no-install] [--print]`, `team dispatch <a> <ID> <taskfile> [--model m] [--branch <name>] [--fresh] [--allow-overflow] [--force] [--print]` (a new dispatch selects the brief's `category:` model from `TEAM_TASK_MODELS` unless `--model` overrides; same-task recovery keeps the committed model/SID; all pre-launch guards are judged in **one pass**: one refusal lists every blocker, each with a paste-able `修法:<command>` or `改行:<exact line>` and a final count line; `--force` overrides only the guards that carry an override, printed as a warning and logged after a real launch) |
57
- | Collaborate | `team say <a> "<one-line message>" [--no-verify]` (verifies delivery; 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`) |
58
- | 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>`. Every automated sender refuses to type into an input box that already holds a draft: the message is queued in `state/outbox/` and reported as `queued`; 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. `--now` is the audited override that types anyway (`state/outbox/forced.log`). See `references/troubleshooting.md` §3 |
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
+ | 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 |
59
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 |
60
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) |
61
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) |
@@ -87,128 +79,70 @@ when they conflict, the creed wins and the process gets fixed.
87
79
 
88
80
  ## The PM loop (what you actually do)
89
81
 
90
- > On start (or after being woken): `team digest` → `team inbox --ack` → `team resume --dry-run` → `team pulse status`.
91
- > If the pulse is not running and you are not on standby, bringing it up (`team pulse up`) is part of your job; on standby, leave it alone.
92
- > Division of labour: **the pulse is a metronome** ("is there work?" every 15 minutes by default): it wakes you
93
- > only when there is pending work, stays silent otherwise, and does not require you to keep running. Starting,
94
- > stopping and resuming agents, verification and merging are all yours.
95
- > If you have nothing to push or need a human decision: `team standby on --reason "…"` to stand down
96
- > (you will not be woken again until someone runs `team standby off`).
97
-
98
- 1. **Model the work**: `team doctor`, `init` if needed; break the user's request into milestones in `ROADMAP.md`
99
- and write each task as a **self-contained brief** (context / deliverables / boundaries / copy-pasteable
100
- acceptance commands / report requirements) — a routine category usually runs a fast model that will not fix
101
- vague requests, so the brief carries the whole context.
102
- 2. **Dispatch**: `team dispatch <a> <ID> <taskfile>`. Check `team ps` (memory / model concurrency) first. The
103
- brief's `category:` picks the model from `TEAM_TASK_MODELS` (routine for bounded work, analysis for complex
104
- planning/judgment, verify for independent adversarial review — the project may use other category names);
105
- record the rationale in the brief prose when the choice is not obvious.
106
- One long-lived worktree per agent; dispatching again to the same agent resumes its session, use `--fresh` for a
107
- new one. The brief's `change:`/`specs:`/`anchor:`/`deltas:` lines are checked **before the window opens**: one
108
- change id per task (no override), a change-less brief must declare a resolvable anchor, two unfinished tasks of
109
- one change cannot write the same delta file, and a verifier must not be an author of the change — the last three
110
- have `--force` + one audit line, the first does not. A refusal names the offending line, the sibling and the fix;
111
- `team change status <id>` shows the same facts read-only.
112
- 3. **Wait for notifications**: when a worker's turn ends it appends to `inbox/<agent>.md` and knocks on your
113
- window. Do not poll agent screens; read `team inbox --ack` and `team digest`.
114
- 4. **Verify (never skip)**: `team review <ID> --dir <checkout>` — run the gates on a clean, independent checkout
115
- and write `reviews/<ID>.md`. **A report is a claim; your verification is the evidence.** Re-read the diff
116
- yourself against the brief.
117
- 5. **Land the records, then merge** → `team review <ID> --pre-merge` lists every `docs/team/**` file the
118
- task's worktree has **not committed** and exits non-zero while any exist: `git merge --squash` carries only
119
- committed content, so an untracked report would silently stay behind and die with the reused worktree (D45 —
120
- the same shape happened five times in one day). Commit them yourself with the `Agent: <agent>` trailer (the
121
- tool never commits for you). Then run git/forge yourself: squash-merge (with a PR:
122
- `gh pr merge --squash --delete-branch <PR>` first, then `git fetch && git merge --ff-only`) →
123
- `team board set <ID> done` → `team close <ID>`.
124
- **If a late delivery arrives after the merge** (the author lands commits on the branch afterwards), run
125
- `team review <ID> --post-merge` before taking anything: records-only → take them with the printed
126
- `git checkout <branch> -- …`; code (anything outside `docs/team/**`) → it exits non-zero: re-merge and
127
- re-run the gates — the records alone are not enough.
128
- **Fail** → `team thread <a> "<failure evidence + expectation>"` + `team say <a> "<one-line instruction>"` (if the target's input box holds a draft the instruction is queued instead of typed — `team outbox list` shows it, and it is delivered once the box clears).
129
- 6. **Wrap up / report**: update `BOARD.md`, record key decisions in `DECISIONS.md` (with rationale and impact),
130
- and report to the user as "delivered + where the evidence is + next step". Users want conclusions and risk,
131
- not a command log.
132
-
133
- The only reasons to stop and ask the user: **shared-state changes** (merge/push — the skill expresses
134
- authorization with `--yes`), scope changes, and decisions that need the user's call (dispatch a research task
135
- first, then write `DECISIONS.md`).
82
+ > On start (or after a wake-up): `team digest` → `team inbox --ack` → `team resume --dry-run` → `team pulse status`.
83
+ > Bring the pulse up (`team pulse up`) when it is not running and you are not on standby; on standby, leave it alone.
84
+
85
+ 1. **Model the work**: `team doctor`, `init` if needed; milestones in `ROADMAP.md`, and each task as a **self-contained
86
+ brief** (context / deliverables / boundaries / copy-pasteable acceptance commands / report requirements) — a
87
+ routine category usually runs a fast model that will not repair a vague request.
88
+ 2. **Dispatch**: `team dispatch <a> <ID> <taskfile>`, after `team ps` (memory / model concurrency). The brief's
89
+ `category:` picks a new dispatch's model; dispatching again to the same agent resumes its session, and `--fresh` is
90
+ the explicit new-session route. The `change:`/`specs:`/`anchor:`/`deltas:` header is checked **before the window
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.
102
+ 6. **Wrap up / report**: update `BOARD.md`, record decisions in `DECISIONS.md` with rationale and impact, and report to
103
+ the user as "delivered + where the evidence is + next step".
104
+
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.
136
109
 
137
110
  ## Specs (OpenSpec)
138
111
 
139
112
  What the product **must hold** lives in `openspec/specs/<capability>/spec.md` as requirements with falsifiable
140
- scenarios; teamsmith keeps the **evidence** (briefs, reports, reviews, decisions) in `docs/team/`. Do not grow a
141
- second spec system: if a promise belongs to the product it goes into a spec, if it is reasoning or guidance it goes
142
- into `references/`.
113
+ scenarios; teamsmith keeps the **evidence** (briefs, reports, reviews, decisions) in `docs/team/`. Do not grow a second
114
+ spec system: a product promise goes into a spec, reasoning or guidance into `references/`.
143
115
 
144
116
  A change runs as **five phases, one brief each, one owner each**: `opsx-explore` (an explorer) → `opsx-propose` (the
145
117
  same explorer, planning only) → `opsx-apply` (a dev) → `opsx-verify` (a **different** agent) → `opsx-archive` (the
146
118
  PM). Two hard rules: **an `apply` brief starts only after the PM's proposal review is ACCEPTED**
147
119
  (`docs/team/reviews/<change>-proposal.md`), and **the PM never archives without independent verification and the
148
- user's confirmation**. **One change : N tasks** — the change is the dispatch unit and the brief's header maps the
149
- task to it (`team dispatch` refuses more than one `change:` id, a change-less brief without an anchor, two
120
+ user's confirmation**. **One change : N tasks** — the change is the dispatch unit and the brief's header maps the task
121
+ to it (`team dispatch` refuses more than one `change:` id, a change-less brief without a resolvable anchor, two
150
122
  unfinished tasks writing one delta file, and a verifier who authored the change; `team change status <id>` reports
151
- readiness and exits 0 only when every mapped task is finished). `openspec validate --all --strict` is part of
152
- `TEAM_GATES`; the phase table, the gates and the PM's review checklist are in
153
- [references/openspec.md](references/openspec.md), the four guards in [references/protocol.md](references/protocol.md) §5b.
123
+ readiness). `openspec validate --all --strict` is part of `TEAM_GATES`. Phase table, gates and the PM's ten-point review
124
+ checklist: [references/openspec.md](references/openspec.md); the four guards: protocol §5b.
154
125
 
155
- ## Getting skill updates (three paths)
126
+ ## Getting skill updates (loaded text vs. the CLI)
156
127
 
157
- ```bash
158
- bash <skill>/scripts/team mark-loaded # once per PM session: record the version this session loaded
159
- bash <skill>/scripts/team version --check # anytime: disk version vs session version + how to apply
160
- bash <skill>/scripts/team changelog # change history (--since v1.8.0 for recent only)
161
- ```
162
-
163
- | Content | How it takes effect |
164
- |---|---|
165
- | `scripts/**` (CLI) | **Nothing to do**: every call reads from disk |
166
- | `SKILL.md` / `references/**` / `templates/**` | Type **`/reload`** in Pi (or `/teamsmith-reload`, or let the model call the `reload_skills` tool). **Note**: `/reload` refreshes the skill list/descriptions (system prompt) and extensions; **text already read into the conversation history does not change**, so after reloading you must `read <skill>/SKILL.md` again (the extension sends a follow-up prompt that triggers that re-read) |
167
- | `extension/team-notify.ts`, `extension/team-bg.ts`, `extension/team-inbox-watch.ts` | **Restart the process** — the launch paths pass the extensions with `pi -e`, and `-e` modules are read at process start (`/reload` hot-reloads only extensions from Pi's auto-discovery locations, `~/.pi/agent/extensions/` and `.pi/extensions/`). PM: `team up`; worker: `team resume <agent>`. `team version --check` fingerprints them |
168
- | `extension/team.ts` (the `/team` slash command) | **`/reload`** — `team init` installs it into the project's `.pi/extensions/team.ts`, which Pi discovers from the working directory; it is deliberately **not** injected with `-e` (that needs a process restart, and `/reload` is the point) and it is installed only in the main worktree — a worker worktree has no `/team` (seats call the CLI from bash). `team doctor` reports its install state; it is **not** part of the session fingerprint |
169
-
170
- Rationale: Pi's `/reload` rediscovers skills, rebuilds the system prompt and re-imports extensions from its
171
- auto-discovery locations; extensions passed with `-e` (which is how the team launch paths load them) are a
172
- startup argument, so adding or changing one needs a process restart. When `team version --check` says your
173
- session is stale, follow the table above.
128
+ `scripts/**` is read from disk on every call, so a CLI change needs nothing. Text is different: `/reload` refreshes the
129
+ skill list/descriptions and extensions, but **text already read into this conversation does not change** — re-read
130
+ `SKILL.md` after reloading (the extension sends a follow-up prompt that triggers that re-read). Extensions passed with
131
+ `-e` are startup arguments, so a changed `team-notify.ts`/`team-bg.ts` needs a process restart (`team up` for the PM,
132
+ `team resume <agent>` for a worker); `/team` is installed in the project's `.pi/extensions/` and follows `/reload` (a
133
+ worker worktree has none). `team mark-loaded` once per session, `team version --check` to see whether the loaded version
134
+ is current, `team changelog` for history. Upgrade and reload steps:
135
+ [references/migration.md](references/migration.md) §6 step 4; why `-e` needs a restart: troubleshooting §22.
174
136
 
175
137
  ## git and forge: the PM uses the tools; the skill does not wrap them
176
138
 
177
- The skill **does not run** and **does not print recipes for** git/forge operations — that would be wrapping tools
178
- that already exist. The PM uses `git` and whatever forge tooling fits:
179
-
180
- ```bash
181
- # 1) Preparation (one long-lived worktree per agent)
182
- git -C <root> worktree add -b <branch> <root>/.worktrees/<agent> <protected-branch>
183
-
184
- # 2) Before work starts (dispatch only checks, never does it): worktree clean, not on the protected branch
185
- git -C <root>/.worktrees/<agent> status --short
186
-
187
- # 3) Verification (the PM prepares the checkout; the skill only runs gates and writes evidence)
188
- git -C <root> worktree add --detach /tmp/review-<ID> <branch>
189
- team review <ID> --dir /tmp/review-<ID> --strong
190
-
191
- # 3b) Pre-merge: the branch's worktree may hold records that were never committed (`merge --squash` carries
192
- # only committed content — an untracked report stays behind and dies with the reused worktree; D45)
193
- team review <ID> --pre-merge # non-zero + per-file fix command while <docs>/** is uncommitted; silent when clean
194
-
195
- # 3c) Post-merge: the author may keep committing after the merge (`merge --squash` froze the branch at that
196
- # moment — P82's two record-only commits never reached main; D49)
197
- team review <ID> --post-merge # records → take them (checkout fix); code → non-zero: re-merge + re-run gates
198
-
199
- # 4) Merge (with a PR: merge the PR first, then fast-forward locally; without: squash locally)
200
- gh pr merge --squash --delete-branch <PR> # or glab mr merge, or a curl/HTTP call
201
- git -C <root> fetch origin <protected-branch> && git -C <root> merge --ff-only FETCH_HEAD
202
- # no PR: git -C <root> merge --squash <branch> && git -C <root> commit -m "<ID>: <title>"
203
- git -C <root> push origin <protected-branch>
204
-
205
- # 5) Wrap up: mark done only after the code really landed on the protected branch
206
- team board set <ID> done
207
- ```
208
-
209
- Forge-agnostic: GitHub via `gh`, GitLab via `glab`/`curl`, Gitea via `tea`, or the web UI — **the PM decides**;
210
- the skill assumes nothing. Tokens stay in the project's token files (`TEAM_TOKEN_FILE` /
211
- `TEAM_GITLAB_TOKEN_FILE`) and are injected only when the PM calls a tool: never echoed, never logged.
139
+ The skill **does not run** and **does not print recipes for** git/forge operations — that would wrap tools that already
140
+ exist. The PM uses `git` and whatever forge tooling fits (`gh`, `glab`, `tea`, `curl`, the web UI) and decides the
141
+ route: it prepares the worktree and the independent review checkout, merges, and advances the protected branch only on
142
+ the user's authorization. Tokens stay in the project's token files (`TEAM_TOKEN_FILE` / `TEAM_GITLAB_TOKEN_FILE`) and
143
+ are injected only when the PM calls a real tool (`GH_TOKEN="$(< .gh-pat)" gh …`): never echoed, never logged, never
144
+ committed. Exact preparation, merge and wrap-up steps: [references/workflows.md](references/workflows.md) §F; landed
145
+ state: protocol §8e; the boundary: protocol §8h.
212
146
 
213
147
  ## Agent adapters (Pi; the seam is internal and frozen)
214
148
 
@@ -246,44 +180,30 @@ about them). They stay writable so the seam can be maintained and diagnosed; to
246
180
  - Details: [references/meeting.md](references/meeting.md).
247
181
 
248
182
  ## Non-negotiable rules (verified during review)
249
- - **Never claim something passed without having run it.** Reports must include commands and output tails; the PM
183
+ - **Never claim something passed without having run it.** Reports carry the real commands and output tails; the PM
250
184
  re-runs independently.
251
- - **Publish the body before you answer — it is a standing duty.** Whenever the reply is written for the user — an
252
- answer, a status or progress report, a conclusion or a ruling, a delivery or verification summary, a decision you
253
- ask the user for, however short, and never held back because it reads like process rather than like a conclusion —
254
- publish the complete reply (the substance the user needs to read, not a play-by-play) with
255
- `team reply post --from <seat> --title "<short>" --stdin`, then send that same body normally — saved, input error,
256
- storage error, busy or unconfirmed never changes what you send (the failure notice goes to stderr, never into the
257
- answer). A batch of user-facing replies may be one reply. A reply written to the patrol, to another seat or to
258
- another project's PM, and a tool receipt, are not for the user and stay out; when the reader is unclear, ask who
259
- the reply is written for and treat an unsettled case as written for the user. A saved
260
- receipt means project-local durable publication only: not user delivery, not approval, not read status, not a
261
- refreshed console, and it creates no pending work, no outbox/inbox entry and no wake-up. See
262
- `references/protocol.md` §4b.
185
+ - **Mark the reply — publication is a standing duty.** Whenever the answer is written for the user — an answer, a status
186
+ or progress report, a conclusion or a ruling, a delivery or verification summary, a decision you ask the user for,
187
+ however short — write the complete reply as the normal answer and end it with the final control line `[[team-reply]]`
188
+ (or `[[team-reply:<short title>]]`); the directed PM extension publishes the sanitized body and the answer goes out
189
+ with only that line removed. A batch may be one reply; patrol/seat/other-project traffic and tool receipts stay out;
190
+ a saved receipt is project-local publication, not user delivery, approval or read status. No temp file or heredoc, and
191
+ no post-then-repeat: `team reply post --from <seat> --title "<short>" --stdin` is the manual publication, backfill
192
+ and recovery entry only. `references/protocol.md` §4b.
263
193
  - Agents only touch directories they own (`OWNERSHIP.md`); cross-directory needs → write `BLOCKED:` in the report.
264
194
  - Agents must not push the protected branch, force-push, merge PR/MRs, or rebase/delete other people's branches.
265
- - Tokens live in project token files (`TEAM_TOKEN_FILE` / `TEAM_GITLAB_TOKEN_FILE`, gitignored) and are injected by
266
- the PM when calling real tools (`GH_TOKEN="$(< .gh-pat)" gh …`); **never echoed, never written, never committed**.
267
- - Operations that change shared state require `--yes` (meaning the user authorized it): `team meeting open/close/agree`, etc.
268
- git/forge writes do not go through the skill — the PM executes them (they are shared-state changes too, so they need authorization).
269
- - One long-lived worktree per agent: **do not move it** (sessions are keyed by cwd; moving loses the agent's memory).
270
- - Default `TEAM_BRANCH_MODE=task`: **one branch per task** (`task/<ID>-<slug>` cut from the protected branch); the task
271
- is the unit of verification, merge and rollback. Set `agent` for one long-lived branch per agent.
272
- - **The pulse is configured by the PM**: `team pulse up` runs `team monitor` in a `pulse` window **in the
273
- same tmux session** and patrols every 15 minutes (configurable) for pending work. `status` / `logs` / `down` are
274
- supported. There is exactly one backend (the tmux window) — no container, no systemd: fewer moving parts is more
275
- reliable, and if the tmux server dies the PM is gone too, so `team up` rebuilds both.
276
- The name: it was called `watchdog` until v1.36.0 — the old command names, the `watchdog` window name and the
277
- `TEAM_WATCH_*` variables keep working as aliases/fallbacks until v2.0.0 (`team pulse status` names every legacy
278
- variable still in effect; a still-running `watchdog` window is recognized as the backend and `team pulse restart`
279
- swaps it for a `pulse` window). The `state/watchdog.*` file names stay unchanged during the alias period —
280
- never run two patrols side by side.
281
- - **The PM does not need to run continuously**: you are only needed when there is work. Patrols default to every
282
- 15 minutes (`TEAM_PULSE_INTERVAL=900`, 300–3600 recommended): pending work wakes you (if you are not running it
283
- starts you with `pi -c`), otherwise it does nothing. **When there is nothing to do or a human is needed,
284
- `team standby on --reason "…"` stands you down** — no further wake-ups; backlog still lands in
285
- `state/watchdog.log`, and a human runs `team standby off`. Patrols **do not manage tmux layout or agents**;
286
- resuming stopped agents is your call via `team resume`.
195
+ - Tokens live in the project's token files and are injected by the PM when calling real tools: **never echoed, never
196
+ written, never committed**.
197
+ - Operations that change shared state need the user's authorization (`--yes`); git/forge writes do not go through the
198
+ skill — the PM executes them, and they need authorization too.
199
+ - One long-lived worktree per agent: **do not move it** (sessions are keyed by cwd). Default `TEAM_BRANCH_MODE=task`:
200
+ one branch per task (`task/<ID>-<slug>`), the unit of verification, merge and rollback.
201
+ - **The pulse is a metronome, not a daemon**: it wakes you only when work is pending and never manages tmux layout,
202
+ agents or quota — a stopped worker is pending work, not an automatic resume (`team resume` is your call). Nothing to
203
+ do or a human needed: `team standby on --reason "…"` stands you down until a human runs `team standby off`.
204
+ 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.
287
207
 
288
208
  ## Deeper reading (read on demand, not all at once)
289
209
 
@@ -74,7 +74,7 @@ function skillVersion(): string {
74
74
 
75
75
  function run(cmd: string, args: string[], cwd?: string): string {
76
76
  try {
77
- return execFileSync(cmd, args, { cwd, encoding: 'utf8', timeout: 5000 }).trim()
77
+ return execFileSync(cmd, args, { cwd, encoding: 'utf8', timeout: 5000, stdio: ['ignore', 'pipe', 'pipe'] }).trim()
78
78
  } catch {
79
79
  return ''
80
80
  }
@@ -0,0 +1,105 @@
1
+ /** PM-only, explicit live-message capture. No tools, provider hooks, history import, or automatic selection. */
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
+ import { isDeepStrictEqual } from 'node:util'
8
+
9
+ // Captured during module evaluation, never reread later as a claim about loaded code.
10
+ const entry = realpathSync(fileURLToPath(import.meta.url))
11
+ const entryBytes = readFileSync(entry)
12
+ const hash = (bytes: Buffer | string) => createHash('sha256').update(bytes).digest('hex')
13
+ const slot = Symbol.for('teamsmith.reply-capture.owners.v1')
14
+ const owners: Map<string, object> = (globalThis as any)[slot] ??= new Map()
15
+ const moduleURL = (bytes: string) => `data:text/javascript;base64,${Buffer.from(bytes).toString('base64')}`
16
+
17
+ export default async function (pi: ExtensionAPI) {
18
+ const skill = dirname(dirname(entry))
19
+ // Snapshot and evaluate both dependencies on every factory/reload, bypassing native/Jiti dependency caches.
20
+ // This is the same reviewed local code, not generated behaviour or a general module loader.
21
+ const parserBytes = readFileSync(join(skill, 'scripts/reply-capture.mjs'), 'utf8')
22
+ const repliesBytes = readFileSync(join(skill, 'scripts/replies.mjs'), 'utf8')
23
+ const dependency = moduleURL(repliesBytes)
24
+ const parserURL = moduleURL(parserBytes.replace("'./replies.mjs'", JSON.stringify(dependency)))
25
+ const capture = await import(parserURL)
26
+ const fingerprint = capture.captureFingerprint({
27
+ 'extension/team-reply.ts': hash(entryBytes),
28
+ 'scripts/reply-capture.mjs': hash(parserBytes),
29
+ 'scripts/replies.mjs': hash(repliesBytes),
30
+ })
31
+ let engine: any, registration: any, key = '', active = false
32
+ const context = (ctx: ExtensionContext) => ({ cwd: ctx.cwd, sessionId: ctx.sessionManager.getSessionId(), sessionFile: ctx.sessionManager.getSessionFile() })
33
+ const current = () => active && owners.get(key) === registration
34
+ const view = (ctx: ExtensionContext) => ({
35
+ identity: registration,
36
+ leaf: ctx.sessionManager.getLeafId(),
37
+ branch: ctx.sessionManager.getBranch(),
38
+ entry: (id: string) => ctx.sessionManager.getEntry(id),
39
+ })
40
+ const diagnostic = (d: { reason: string; entryId: string; path: string }) => {
41
+ // Never title/body/model text. Diagnostics are separate from the ordinary answer, including print/JSON modes.
42
+ process.stderr.write(`[team-reply] ${d.reason}; source=${d.entryId || 'unbound'}; evidence=${d.path}\n`)
43
+ }
44
+ const runtime = (status: string, reason?: string) => {
45
+ if (!current()) return
46
+ capture.updateRuntime(registration, (previous: any) => {
47
+ if (status !== 'ready' && previous?.generation !== registration.generation) return undefined
48
+ return { ...registration, status, reason, extension: entry, fingerprint, at: new Date().toISOString() }
49
+ })
50
+ }
51
+ pi.on('session_start', (_event, ctx) => {
52
+ active = false
53
+ engine = undefined
54
+ let identity: any
55
+ try { identity = capture.resolvePMIdentity(context(ctx)) }
56
+ catch (e: any) {
57
+ process.stderr.write(`[team-reply] disabled: ${e.message}\n`)
58
+ return // Unproven worker/ordinary/custom/foreign contexts do not mutate messages or register ready.
59
+ }
60
+ key = capture.sessionKey(identity)
61
+ if (owners.has(key)) return // A second loaded path must not sanitize, stage, or register a second owner.
62
+ registration = { ...identity, generation: randomUUID() }
63
+ owners.set(key, registration)
64
+ active = true
65
+ const claimed = registration
66
+ const owns = () => current() && registration === claimed
67
+ const expected = identity
68
+ const verify = () => {
69
+ try {
70
+ const valid = isDeepStrictEqual(expected, capture.resolvePMIdentity(context(ctx)))
71
+ if (!valid) runtime('degraded', 'identity/config changed')
72
+ return valid
73
+ } catch (e: any) {
74
+ try { runtime('degraded', e.message) } catch { /* A failed registry write cannot change identity refusal. */ }
75
+ return false
76
+ }
77
+ }
78
+ engine = new capture.ReplyCapture({ identity, current: owns, verify, owner: { pid: identity.pid, starttime: identity.starttime, generation: registration.generation }, diagnostic,
79
+ writer: (record: any) => capture.runReplyWriter({ team: join(skill, 'scripts/team'), identity, env: { ...process.env } }, record) })
80
+ try { runtime('ready') }
81
+ catch (e: any) { diagnostic({ reason: `runtime:${e.code ?? e.name}`, entryId: '', path: join(identity.state, 'reply-capture/runtime.json') }) }
82
+ engine.recover(view(ctx))
83
+ })
84
+ pi.on('before_agent_start', (_event, ctx) => { if (current()) engine.before(view(ctx)) })
85
+ pi.on('message_start', (event, ctx) => { if (current()) engine.start(event.message, view(ctx)) })
86
+ pi.on('message_end', (event, ctx) => {
87
+ if (!current()) return
88
+ return { message: engine.end(event.message, view(ctx)) }
89
+ })
90
+ pi.on('turn_end', (event, ctx) => { if (current()) engine.turn(event, view(ctx)) })
91
+ pi.on('agent_settled', (event, ctx) => { if (current()) engine.settled(event, view(ctx)) })
92
+ for (const event of ['session_before_switch', 'session_before_fork', 'session_tree'] as const) {
93
+ pi.on(event, () => { if (current()) engine.reset() })
94
+ }
95
+ pi.on('session_shutdown', async () => {
96
+ if (!current()) return
97
+ engine.reset()
98
+ await engine.drain()
99
+ try { runtime('degraded', 'session shutdown') }
100
+ catch (e: any) { diagnostic({ reason: `shutdown-runtime:${e.code ?? e.name}`, entryId: '', path: join(registration.state, 'reply-capture/runtime.json') }) }
101
+ // A delayed old shutdown must not clear a replacement generation.
102
+ if (owners.get(key) === registration) owners.delete(key)
103
+ active = false
104
+ })
105
+ }
@@ -321,7 +321,7 @@ ways, and **the channel is chosen by the target, not by the sender**:
321
321
  | Target | Channel |
322
322
  |---|---|
323
323
  | a Pi session that loaded `extension/team-inbox-watch.ts` (both built-in launch paths pass it with `-e`; a custom Pi-shaped template can add `-e {skill_dir}/extension/team-inbox-watch.ts`) | **inbox watch**: a durable inbox line plus one pointer line in `state/inbox-watch/<key>.wake`; the session's own extension calls `pi.sendMessage({customType:'team-inbox'}, {triggerTurn:true, deliverAs:'followUp'})`. **The input box is never read and never typed into.** |
324
- | everything else — a custom adapter, a Pi session without the extension, a dead or foreign registration — and the explicit escape hatch (`--now`) | **paste path**: the delivery guard reads the box, defers while it holds a draft, types, verifies the submission in the conversation above the box, and retracts or leaves residue honestly (`references/troubleshooting.md` §3) |
324
+ | everything else — a custom adapter, a Pi session without the extension, a dead or foreign registration — and any default `team say` that finds no usable watcher (it attempts the direct send at once, audited in `state/outbox/forced.log`), plus the human's explicit override (`team draft send --now` / `team outbox flush --now`) | **paste path**: the delivery guard reads the box, defers while it holds a draft, types, verifies the submission in the conversation above the box, and retracts or leaves residue honestly (`references/troubleshooting.md` §3) |
325
325
 
326
326
  Readiness is proven by the session itself: the extension writes `state/inbox-watch/<key>.reg`
327
327
  (`target=<session>:<window>`, `inbox=<name>`, `pid`, `cwd`, `started`, `heartbeat`), and a sender routes to the