teamsmith 0.2.0 → 0.3.1

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 (163) hide show
  1. package/README.md +4 -4
  2. package/package.json +1 -1
  3. package/skills/teamsmith/CHANGELOG.md +69 -0
  4. package/skills/teamsmith/SKILL.md +20 -13
  5. package/skills/teamsmith/extension/team-inbox-watch.ts +5 -3
  6. package/skills/teamsmith/extension/team-notify.ts +37 -6
  7. package/skills/teamsmith/extension/team.ts +438 -0
  8. package/skills/teamsmith/references/config.md +39 -6
  9. package/skills/teamsmith/references/migration.md +197 -47
  10. package/skills/teamsmith/references/protocol.md +201 -30
  11. package/skills/teamsmith/references/troubleshooting.md +130 -10
  12. package/skills/teamsmith/references/workflows.md +36 -2
  13. package/skills/teamsmith/scripts/lib/cmd-agents.sh +318 -23
  14. package/skills/teamsmith/scripts/lib/cmd-bootstrap.sh +2 -2
  15. package/skills/teamsmith/scripts/lib/cmd-config.sh +349 -67
  16. package/skills/teamsmith/scripts/lib/cmd-draft.sh +4 -4
  17. package/skills/teamsmith/scripts/lib/cmd-help.sh +677 -0
  18. package/skills/teamsmith/scripts/lib/cmd-init.sh +157 -5
  19. package/skills/teamsmith/scripts/lib/cmd-interrupt.sh +461 -0
  20. package/skills/teamsmith/scripts/lib/cmd-meeting.sh +2 -25
  21. package/skills/teamsmith/scripts/lib/cmd-project.sh +30 -103
  22. package/skills/teamsmith/scripts/lib/cmd-reap.sh +277 -0
  23. package/skills/teamsmith/scripts/lib/cmd-reply.sh +3 -3
  24. package/skills/teamsmith/scripts/lib/cmd-review.sh +182 -32
  25. package/skills/teamsmith/scripts/lib/cmd-status.sh +234 -21
  26. package/skills/teamsmith/scripts/lib/cmd-update.sh +36 -7
  27. package/skills/teamsmith/scripts/lib/cmd-watch.sh +564 -46
  28. package/skills/teamsmith/scripts/lib/common.sh +1004 -245
  29. package/skills/teamsmith/scripts/lib/gate-lock.sh +582 -0
  30. package/skills/teamsmith/scripts/panel/draft-send.sh +11 -1
  31. package/skills/teamsmith/scripts/panel/panel.js +211 -211
  32. package/skills/teamsmith/scripts/panel/src/App.tsx +58 -21
  33. package/skills/teamsmith/scripts/panel/src/clipboard.ts +12 -5
  34. package/skills/teamsmith/scripts/panel/src/compose.ts +6 -3
  35. package/skills/teamsmith/scripts/panel/src/data.ts +51 -5
  36. package/skills/teamsmith/scripts/panel/src/layout.ts +209 -69
  37. package/skills/teamsmith/scripts/panel/src/main.tsx +37 -8
  38. package/skills/teamsmith/scripts/panel/src/strings/en.ts +39 -29
  39. package/skills/teamsmith/scripts/panel/src/strings/zh.ts +41 -31
  40. package/skills/teamsmith/scripts/panel/src/types.ts +28 -3
  41. package/skills/teamsmith/scripts/replies.mjs +4 -1
  42. package/skills/teamsmith/scripts/shim/killall +10 -0
  43. package/skills/teamsmith/scripts/shim/pgrep +10 -0
  44. package/skills/teamsmith/scripts/shim/pidof +10 -0
  45. package/skills/teamsmith/scripts/shim/pkill +10 -0
  46. package/skills/teamsmith/scripts/shim/signal-gate +108 -31
  47. package/skills/teamsmith/scripts/shim/tmux +18 -0
  48. package/skills/teamsmith/scripts/strings/commands.tsv +86 -0
  49. package/skills/teamsmith/scripts/strings/help.en.tsv +503 -0
  50. package/skills/teamsmith/scripts/strings/help.zh.tsv +489 -0
  51. package/skills/teamsmith/scripts/team +19 -6
  52. package/skills/teamsmith/templates/AGENTS.section.md.tmpl +8 -1
  53. package/skills/teamsmith/templates/config.sh.tmpl +20 -1
  54. package/skills/teamsmith/templates/pm-prompt.md.tmpl +21 -0
  55. package/skills/teamsmith/tests/README.md +31 -0
  56. package/skills/teamsmith/tests/bg-ledger-harness.mjs +464 -40
  57. package/skills/teamsmith/tests/bg-ledger.sh +168 -10
  58. package/skills/teamsmith/tests/checkout-shape-probe.sh +83 -54
  59. package/skills/teamsmith/tests/config-cli.sh +184 -32
  60. package/skills/teamsmith/tests/fixtures/delivery-truth-real/scenario.sh +7 -1
  61. package/skills/teamsmith/tests/fixtures/p287/lint-good.sh.in +3 -0
  62. package/skills/teamsmith/tests/fixtures/p287/lint-hardcoded.sh.in +3 -0
  63. package/skills/teamsmith/tests/fixtures/p287/lint-no-ns.sh.in +3 -0
  64. package/skills/teamsmith/tests/fixtures/p55/flip-p49.sh +18 -6
  65. package/skills/teamsmith/tests/flip-m33.sh +5 -3
  66. package/skills/teamsmith/tests/flip-p158.sh +2 -1
  67. package/skills/teamsmith/tests/flip-p308-skip-not-pass.sh +151 -0
  68. package/skills/teamsmith/tests/flip-p310-lock.sh +210 -0
  69. package/skills/teamsmith/tests/flip-p310-socket.sh +125 -0
  70. package/skills/teamsmith/tests/gate-guard.sh +52 -79
  71. package/skills/teamsmith/tests/help-surface.sh +1664 -0
  72. package/skills/teamsmith/tests/install-shape.sh +359 -22
  73. package/skills/teamsmith/tests/key-replies-pty.sh +9 -10
  74. package/skills/teamsmith/tests/key-replies-ui.sh +2 -8
  75. package/skills/teamsmith/tests/key-replies.sh +281 -28
  76. package/skills/teamsmith/tests/ledger-ban.sh +5 -4
  77. package/skills/teamsmith/tests/ledger-claim.sh +2 -1
  78. package/skills/teamsmith/tests/lib/bounded-spin.sh +90 -0
  79. package/skills/teamsmith/tests/lib/model-policy.sh +4 -0
  80. package/skills/teamsmith/tests/lib/model-routing-flips.py +51 -0
  81. package/skills/teamsmith/tests/lib/pty-wait.sh +21 -111
  82. package/skills/teamsmith/tests/lib/reply-fixture.sh +4 -9
  83. package/skills/teamsmith/tests/lib/section-guard.sh +316 -164
  84. package/skills/teamsmith/tests/lib/tmp-root.sh +139 -27
  85. package/skills/teamsmith/tests/lib/tmux-cap.sh +10 -1
  86. package/skills/teamsmith/tests/lib/tmux-iso.sh +31 -13
  87. package/skills/teamsmith/tests/loop-inventory.tsv +83 -77
  88. package/skills/teamsmith/tests/panel-b2.sh +430 -352
  89. package/skills/teamsmith/tests/panel-b3-stub.sh +112 -4
  90. package/skills/teamsmith/tests/panel-b3.sh +314 -62
  91. package/skills/teamsmith/tests/panel-choices.sh +11 -6
  92. package/skills/teamsmith/tests/panel-cpu.sh +43 -130
  93. package/skills/teamsmith/tests/panel-p21.sh +251 -265
  94. package/skills/teamsmith/tests/panel-snapshots.sh +41 -225
  95. package/skills/teamsmith/tests/panel-strings.mjs +33 -18
  96. package/skills/teamsmith/tests/perf.sh +187 -396
  97. package/skills/teamsmith/tests/routes.sh +440 -117
  98. package/skills/teamsmith/tests/seat-interrupt.sh +1012 -0
  99. package/skills/teamsmith/tests/seat-visibility.sh +675 -0
  100. package/skills/teamsmith/tests/section-guard.sh +13 -102
  101. package/skills/teamsmith/tests/section-needs-audit.sh +24 -7
  102. package/skills/teamsmith/tests/section-paths.tsv +32 -18
  103. package/skills/teamsmith/tests/section-select.sh +371 -19
  104. package/skills/teamsmith/tests/signal-gate.sh +249 -27
  105. package/skills/teamsmith/tests/signal-lint-legacy.txt +4 -1
  106. package/skills/teamsmith/tests/slash-team-e2e.sh +323 -0
  107. package/skills/teamsmith/tests/slash-team.sh +617 -0
  108. package/skills/teamsmith/tests/slice-coverage.sh +206 -0
  109. package/skills/teamsmith/tests/smoke.sh +3595 -788
  110. package/skills/teamsmith/tests/task-model-routing.sh +530 -15
  111. package/skills/teamsmith/tests/team-bg-stop.sh +18 -10
  112. package/skills/teamsmith/tests/tmp-hygiene.sh +782 -45
  113. package/skills/teamsmith/tests/tmux-identity-leak.sh +773 -0
  114. package/skills/teamsmith/tests/tmux-lint-legacy.txt +12 -18
  115. package/skills/teamsmith/tests/upgrade-recipe.sh +537 -0
  116. package/skills/teamsmith/tests/workflow-entry.sh +207 -0
  117. package/skills/teamsmith-init/SKILL.md +12 -12
  118. package/skills/teamsmith-init/references/bootstrap.md +3 -3
  119. package/skills/teamsmith/tests/flip-glue.sh +0 -162
  120. package/skills/teamsmith/tests/flip-m12-26c.sh +0 -129
  121. package/skills/teamsmith/tests/flip-m12.sh +0 -185
  122. package/skills/teamsmith/tests/flip-m16.sh +0 -166
  123. package/skills/teamsmith/tests/flip-m17.sh +0 -204
  124. package/skills/teamsmith/tests/flip-m34.sh +0 -96
  125. package/skills/teamsmith/tests/flip-m37.sh +0 -185
  126. package/skills/teamsmith/tests/flip-m4.3.sh +0 -375
  127. package/skills/teamsmith/tests/flip-m43.sh +0 -128
  128. package/skills/teamsmith/tests/flip-m45.sh +0 -244
  129. package/skills/teamsmith/tests/flip-m46.sh +0 -238
  130. package/skills/teamsmith/tests/flip-m48.sh +0 -304
  131. package/skills/teamsmith/tests/flip-m6.2.sh +0 -205
  132. package/skills/teamsmith/tests/flip-m6.3.sh +0 -283
  133. package/skills/teamsmith/tests/flip-m6.4.sh +0 -267
  134. package/skills/teamsmith/tests/flip-m6.5.sh +0 -113
  135. package/skills/teamsmith/tests/flip-m7.1.sh +0 -135
  136. package/skills/teamsmith/tests/flip-m7.2.sh +0 -321
  137. package/skills/teamsmith/tests/flip-p144.sh +0 -112
  138. package/skills/teamsmith/tests/flip-p156.sh +0 -133
  139. package/skills/teamsmith/tests/flip-p160.sh +0 -182
  140. package/skills/teamsmith/tests/flip-p171.sh +0 -249
  141. package/skills/teamsmith/tests/flip-p18.1.sh +0 -95
  142. package/skills/teamsmith/tests/flip-p20.sh +0 -286
  143. package/skills/teamsmith/tests/flip-p201.sh +0 -249
  144. package/skills/teamsmith/tests/flip-p210.sh +0 -239
  145. package/skills/teamsmith/tests/flip-p211.sh +0 -152
  146. package/skills/teamsmith/tests/flip-p217.sh +0 -288
  147. package/skills/teamsmith/tests/flip-p22.sh +0 -123
  148. package/skills/teamsmith/tests/flip-p23.sh +0 -239
  149. package/skills/teamsmith/tests/flip-p25.sh +0 -165
  150. package/skills/teamsmith/tests/flip-p71.sh +0 -184
  151. package/skills/teamsmith/tests/flip-p72.sh +0 -202
  152. package/skills/teamsmith/tests/load-experiment.sh +0 -290
  153. package/skills/teamsmith/tests/panel-cpu-premise.sh +0 -173
  154. package/skills/teamsmith/tests/panel-flip-m54.sh +0 -207
  155. package/skills/teamsmith/tests/panel-flip-p123.sh +0 -278
  156. package/skills/teamsmith/tests/panel-flip-p125.sh +0 -318
  157. package/skills/teamsmith/tests/panel-flip-p128.sh +0 -259
  158. package/skills/teamsmith/tests/panel-keyprobe-stub.sh +0 -41
  159. package/skills/teamsmith/tests/panel-keyprobe.sh +0 -82
  160. package/skills/teamsmith/tests/panel-knobs.sh +0 -83
  161. package/skills/teamsmith/tests/section-budgets.tsv +0 -154
  162. package/skills/teamsmith/tests/team-bg-flip.sh +0 -239
  163. package/skills/teamsmith/tests/team-inbox-watch-flip.sh +0 -191
@@ -0,0 +1,438 @@
1
+ // teamsmith /team extension
2
+ /**
3
+ * teamsmith · `/team` 斜杠命令(change: slash-team)
4
+ *
5
+ * 用户坐在 Pi 会话里,用 `/team …` 跑项目自己的 `team` CLI:一条命令都不重新实现,把用户打的 token
6
+ * 原样交给子进程(cwd = 项目根),把 stdout/stderr/退出码如实带回对话。这是「前门」,不是第二套 CLI。
7
+ *
8
+ * 结构(design §3.8 的两层):
9
+ * - **纯逻辑**(本文件里不碰任何 Pi API 的部分):白名单表、分词、匹配、菜单、项目根/CLI 解析、
10
+ * `runTeamCommand(deps, argv)`。夹具用假 pi 直接驱动它们。
11
+ * - **Pi 粘合**:文件末尾的默认导出 —— 只 `registerCommand("team", …)` 一次,**从不**注册任何
12
+ * 模型可调用的工具(模型不能自己触发这条命令)
13
+ *
14
+ * 加载方式(design §3.1):`team init`/`bootstrap` 把它装到 `<main worktree>/.pi/extensions/team.ts`
15
+ * (默认软链),Pi 从工作目录自动发现、`/reload` 即生效;**不**用 `pi -e` 注入(那要重启进程)。
16
+ *
17
+ * 零运行时依赖:只有 `node:*` 内建与 `import type`(被擦除),所以 `bun -e "await import(...)"` 能加载。
18
+ */
19
+ import type { ExtensionAPI } from '@earendil-works/pi-coding-agent'
20
+ import { existsSync } from 'node:fs'
21
+ import { dirname, join, resolve } from 'node:path'
22
+ import { fileURLToPath } from 'node:url'
23
+
24
+ // ---------------------------------------------------------------- 文案表(design §3.7)
25
+ // 一行一条、语言是一列:今天只有 zh 一份;P260 若落地 TEAM_LANG,这里加一列而不是改写调用点。
26
+ type StringRow = { key: string; zh: string }
27
+ const STRINGS: StringRow[] = [
28
+ { key: 'menu.title', zh: 'teamsmith /team · 在对话里跑项目自己的 team 命令(输出进对话,退出码照实报)' },
29
+ { key: 'menu.group.read', zh: '读取' },
30
+ { key: 'menu.group.action', zh: '你自己动手' },
31
+ { key: 'menu.footer', zh: '不在上面的命令是 PM / 席位的工具,请到终端跑。' },
32
+ { key: 'refuse.outside', zh: '✗ /team 不认这条命令:{{name}} —— 这是 PM / 席位的命令,请到终端执行(输入 /team 看能用什么)' },
33
+ { key: 'refuse.shape', zh: '✗ /team 不认这个形状:team {{argv}} —— {{path}} 只认自己的形状({{forms}});{{extra}}要跑别的形状(那是 PM / 席位的工具)请到终端。' },
34
+ { key: 'refuse.pm-restart', zh: '✗ /team 不跑 up:这个会话就是 PM 会话,从这里重启会把当前对话一起带走 —— 要重启请到终端跑 team up。' },
35
+ { key: 'refuse.no-project', zh: '✗ /team 找不到项目:当前目录 {{cwd}} 向上没有 .pi/team/config.sh —— 到 teamsmith 项目里再用,或先跑 team init。' },
36
+ { key: 'refuse.no-cli', zh: '✗ /team 找不到 team CLI:{{root}} 下既没有 .pi/skills/teamsmith/scripts/team,也没有可用的 TEAM_CLI —— 跑 team init 装项目本地 skill。' },
37
+ { key: 'refuse.quote', zh: '✗ /team 参数里的引号没有闭合:{{raw}} —— 不猜,什么都不跑(补上引号再来)。' },
38
+ { key: 'refuse.escape', zh: '✗ /team 参数以反斜杠结尾:{{raw}} —— 不猜,什么都不跑。' },
39
+ { key: 'run.header', zh: '$ team {{argv}}' },
40
+ { key: 'run.exit', zh: 'exit {{code}}' },
41
+ { key: 'run.killed', zh: 'killed:超时 {{sec}}s' },
42
+ { key: 'run.stdout', zh: '--- stdout ---' },
43
+ { key: 'run.stderr', zh: '--- stderr ---' },
44
+ { key: 'run.elided', zh: '…(省略 {{lines}} 行 / {{bytes}} 字节;完整输出:在终端跑 team {{argv}})' },
45
+ { key: 'fail.exit', zh: '命令失败:team {{argv}}(exit {{code}})' },
46
+ { key: 'fail.killed', zh: '命令超时被杀:team {{argv}}({{sec}}s 上限)' },
47
+ { key: 'command.description', zh: '跑项目自己的 team 命令(白名单:读取 + 你自己动手的操作)' },
48
+ ]
49
+ const STRING_INDEX: Record<string, string> = (() => {
50
+ const m: Record<string, string> = {}
51
+ for (const row of STRINGS) m[row.key] = row.zh
52
+ return m
53
+ })()
54
+ /** 取文案(今天只有 zh;P260 的 TEAM_LANG 落地后在这里选列)。 */
55
+ export function t(key: string, vars?: Record<string, string>): string {
56
+ let s = STRING_INDEX[key]
57
+ if (s === undefined) return key
58
+ if (vars) for (const k of Object.keys(vars)) s = s.split(`{{${k}}}`).join(vars[k])
59
+ return s
60
+ }
61
+
62
+ // ---------------------------------------------------------------- 白名单:一张表,两种行(design §3.2)
63
+ /** 读行形状里的「一个自由 token」占位符(`<ID>` / `<n>` / `<slug>`)。 */
64
+ export const ARG = '<arg>'
65
+ export type Group = 'read' | 'action'
66
+ export type Row = {
67
+ group: Group
68
+ /** 命令路径(菜单/补全/探针都用它;一行可以有多条路径,例如 pulse 的三个动词)。 */
69
+ paths: string[][]
70
+ /** 读行专有:逐字接受的 token 形状(`ARG` = 恰好一个自由 token)。动行没有它 = 路径 + 自由尾巴。 */
71
+ forms?: string[][]
72
+ /** 菜单里那一句用途。 */
73
+ purpose: string
74
+ }
75
+
76
+ export const TEAM_ROWS: Row[] = [
77
+ { group: 'read', paths: [['status']], forms: [['status'], ['status', ARG]], purpose: '名册 + 任务/report 状态' },
78
+ { group: 'read', paths: [['digest']], forms: [['digest']], purpose: '给 PM 的待办摘要' },
79
+ { group: 'read', paths: [['ps']], forms: [['ps']], purpose: '容量:RAM/swap/还能再跑几个 agent' },
80
+ { group: 'read', paths: [['board']], forms: [['board'], ['board', 'ls']], purpose: '看板(BOARD.md)' },
81
+ { group: 'read', paths: [['reply', 'list']], forms: [['reply', 'list']], purpose: '关键回复列表(JSON)' },
82
+ { group: 'read', paths: [['reply', 'show']], forms: [['reply', 'show', ARG]], purpose: '读第 n 条关键回复' },
83
+ { group: 'read', paths: [['config', 'list']], forms: [['config', 'list']], purpose: '项目契约的每个键与当前值' },
84
+ { group: 'read', paths: [['version']], forms: [['version']], purpose: '磁盘版本 / 本会话加载版本' },
85
+ { group: 'read', paths: [['doctor']], forms: [['doctor']], purpose: '环境自检' },
86
+ { group: 'read', paths: [['meeting', 'inbox']], forms: [['meeting', 'inbox']], purpose: '待回应的会议' },
87
+ { group: 'read', paths: [['meeting', 'read']], forms: [['meeting', 'read', ARG]], purpose: '读一场会议' },
88
+ { group: 'action', paths: [['pulse', 'up'], ['pulse', 'down'], ['pulse', 'status']], purpose: '巡检窗口(起/停/看)' },
89
+ { group: 'action', paths: [['config', 'upgrade-models']], purpose: '模型策略升级(写盘要 --yes)' },
90
+ { group: 'action', paths: [['meeting', 'say']], purpose: '给对面 PM 发言(--intent 必填)' },
91
+ { group: 'action', paths: [['meeting', 'close']], purpose: '结束一场会议' },
92
+ ]
93
+
94
+ /** 表外命令的**具名**前缀(拒绝文案要点名 `dispatch` / `config set` 这样的命令,而不是只报第一个词)。 */
95
+ export const REFUSED_PATHS: string[][] = [
96
+ ['up'], ['dispatch'], ['say'], ['notify'], ['close'], ['teardown'],
97
+ ['config', 'set'], ['smoke'], ['gate'], ['perf'], ['review'], ['change'],
98
+ ['archive'], ['bg'], ['add-agent'], ['init'], ['bootstrap'], ['draft'],
99
+ ['outbox'], ['inbox'], ['thread'], ['monitor'], ['pr'], ['gh'],
100
+ ]
101
+
102
+ // ---------------------------------------------------------------- 分词(design §3.3)
103
+ export type TokenizeResult = { ok: true; tokens: string[] } | { ok: false; error: string }
104
+
105
+ /** 空白分隔;单/双引号;引号外反斜杠转义;未闭合引号(或结尾反斜杠)⇒ 拒绝,什么都不跑。 */
106
+ export function tokenize(raw: string): TokenizeResult {
107
+ const tokens: string[] = []
108
+ let cur = ''
109
+ let started = false
110
+ let i = 0
111
+ while (i < raw.length) {
112
+ const ch = raw[i]
113
+ if (ch === ' ' || ch === '\t' || ch === '\n' || ch === '\r') {
114
+ if (started) { tokens.push(cur); cur = ''; started = false }
115
+ i++
116
+ continue
117
+ }
118
+ started = true
119
+ if (ch === "'") {
120
+ const j = raw.indexOf("'", i + 1)
121
+ if (j < 0) return { ok: false, error: t('refuse.quote', { raw }) }
122
+ cur += raw.slice(i + 1, j)
123
+ i = j + 1
124
+ continue
125
+ }
126
+ if (ch === '"') {
127
+ i++
128
+ let closed = false
129
+ while (i < raw.length) {
130
+ const c = raw[i]
131
+ if (c === '"') { closed = true; i++; break }
132
+ if (c === '\\' && i + 1 < raw.length && (raw[i + 1] === '"' || raw[i + 1] === '\\')) {
133
+ cur += raw[i + 1]; i += 2; continue
134
+ }
135
+ cur += c; i++
136
+ }
137
+ if (!closed) return { ok: false, error: t('refuse.quote', { raw }) }
138
+ continue
139
+ }
140
+ if (ch === '\\') {
141
+ if (i + 1 >= raw.length) return { ok: false, error: t('refuse.escape', { raw }) }
142
+ cur += raw[i + 1]; i += 2; continue
143
+ }
144
+ cur += ch; i++
145
+ }
146
+ if (started) tokens.push(cur)
147
+ return { ok: true, tokens }
148
+ }
149
+
150
+ // ---------------------------------------------------------------- 匹配(design §3.2 / §3.3)
151
+ export type Match =
152
+ | { kind: 'menu' }
153
+ | { kind: 'run'; row: Row; tokens: string[] }
154
+ | { kind: 'refuse'; message: string }
155
+
156
+ function formMatches(form: string[], tokens: string[]): boolean {
157
+ if (form.length !== tokens.length) return false
158
+ for (let i = 0; i < form.length; i++) if (form[i] !== ARG && form[i] !== tokens[i]) return false
159
+ return true
160
+ }
161
+
162
+ function startsWithPath(tokens: string[], path: string[]): boolean {
163
+ if (tokens.length < path.length) return false
164
+ for (let i = 0; i < path.length; i++) if (tokens[i] !== path[i]) return false
165
+ return true
166
+ }
167
+
168
+ function formsText(row: Row): string {
169
+ return (row.forms ?? []).map((f) => 'team ' + f.join(' ')).join(' / ')
170
+ }
171
+
172
+ /** 表外命令的具名前缀:最长匹配(`config set` 优先于 `config`)。 */
173
+ export function refusedName(tokens: string[]): string {
174
+ let best: string[] | null = null
175
+ for (const p of REFUSED_PATHS) {
176
+ if (!startsWithPath(tokens, p)) continue
177
+ if (best === null || p.length > best.length) best = p
178
+ }
179
+ if (best) return best.join(' ')
180
+ return tokens[0] ?? ''
181
+ }
182
+
183
+ export function matchInvocation(tokens: string[]): Match {
184
+ if (tokens.length === 0) return { kind: 'menu' }
185
+ if (tokens.length === 1 && tokens[0] === 'help') return { kind: 'menu' }
186
+ // design §3.2 坑 1:会重启/新建 PM 会话的调用一律拒绝(up 与任何带 --fresh-pm 的调用)。
187
+ if (tokens[0] === 'up' || tokens.indexOf('--fresh-pm') >= 0) {
188
+ return { kind: 'refuse', message: t('refuse.pm-restart') }
189
+ }
190
+ // ① 读行:严格形状,整个 argv 吃完才算命中。
191
+ for (const row of TEAM_ROWS) {
192
+ if (!row.forms) continue
193
+ for (const form of row.forms) if (formMatches(form, tokens)) return { kind: 'run', row, tokens }
194
+ }
195
+ // ② 读行的形状不符(多/少 token):点名那一行与多出来的 token,零副作用。
196
+ for (const row of TEAM_ROWS) {
197
+ if (!row.forms) continue
198
+ if (!startsWithPath(tokens, row.paths[0])) continue
199
+ const extra = tokens.slice(row.paths[0].length).join(' ')
200
+ return {
201
+ kind: 'refuse',
202
+ message: t('refuse.shape', {
203
+ argv: tokens.join(' '),
204
+ path: row.paths[0].join(' '),
205
+ forms: formsText(row),
206
+ extra: extra ? `多出来的 token ${extra} 不原样透传;` : '',
207
+ }),
208
+ }
209
+ }
210
+ // ③ 动行:命令路径 + 用户自己的尾巴(原样透传,由 CLI 校验)。
211
+ for (const row of TEAM_ROWS) {
212
+ if (row.forms) continue
213
+ for (const path of row.paths) if (startsWithPath(tokens, path)) return { kind: 'run', row, tokens }
214
+ }
215
+ // ④ 表外:一个进程都不起。
216
+ return { kind: 'refuse', message: t('refuse.outside', { name: refusedName(tokens) }) }
217
+ }
218
+
219
+ // ---------------------------------------------------------------- 菜单与补全(design §3.2,单真源)
220
+ function rowName(row: Row): string {
221
+ return row.paths.map((p) => p.join(' ')).join(' / ')
222
+ }
223
+
224
+ export function renderMenu(): string {
225
+ const lines: string[] = [t('menu.title')]
226
+ let width = 0
227
+ for (const row of TEAM_ROWS) width = Math.max(width, rowName(row).length)
228
+ for (const group of ['read', 'action'] as Group[]) {
229
+ lines.push('')
230
+ lines.push(t(group === 'read' ? 'menu.group.read' : 'menu.group.action'))
231
+ for (const row of TEAM_ROWS) {
232
+ if (row.group !== group) continue
233
+ const name = rowName(row)
234
+ lines.push(' ' + name + ' '.repeat(width - name.length + 2) + row.purpose)
235
+ }
236
+ }
237
+ lines.push('')
238
+ lines.push(t('menu.footer'))
239
+ return lines.join('\n')
240
+ }
241
+
242
+ export type CompletionItem = { value: string; label: string; description?: string }
243
+
244
+ export function completions(prefix: string): CompletionItem[] {
245
+ const raw = prefix.replace(/^\s+/, '')
246
+ const pt = raw.split(/\s+/).filter((s) => s !== '')
247
+ const items: CompletionItem[] = []
248
+ for (const row of TEAM_ROWS) {
249
+ for (const path of row.paths) {
250
+ let hit = true
251
+ if (pt.length > path.length) hit = false
252
+ for (let i = 0; hit && i < pt.length; i++) {
253
+ if (i === pt.length - 1) { if (!path[i].startsWith(pt[i])) hit = false }
254
+ else if (path[i] !== pt[i]) hit = false
255
+ }
256
+ if (hit) items.push({ value: path.join(' '), label: path.join(' '), description: row.purpose })
257
+ }
258
+ }
259
+ return items
260
+ }
261
+
262
+ // ---------------------------------------------------------------- 项目根与 CLI 解析(design §3.5)
263
+ /** 从 `cwd` 向上找第一个含 `.pi/team/config.sh` 的目录;找不到 = null(不是 teamsmith 项目)。 */
264
+ export function findProjectRoot(cwd: string): string | null {
265
+ let d = resolve(cwd)
266
+ for (;;) {
267
+ if (existsSync(join(d, '.pi', 'team', 'config.sh'))) return d
268
+ const up = dirname(d)
269
+ if (up === d) return null
270
+ d = up
271
+ }
272
+ }
273
+
274
+ /**
275
+ * CLI 路径(顺序有意,design §3.5):项目本地安装永远赢 → `${TEAM_CLI}`(测试/非默认安装旋钮)
276
+ * → 扩展自己的兄弟目录 `<ext-dir>/../scripts/team`(`-e` 或 realpath 解析过的软链形态)→ null。
277
+ */
278
+ export function resolveCli(root: string, env: Record<string, string | undefined>, extDir?: string): string | null {
279
+ const local = join(root, '.pi', 'skills', 'teamsmith', 'scripts', 'team')
280
+ if (existsSync(local)) return local
281
+ const envCli = env['TEAM_CLI']
282
+ if (envCli !== undefined && envCli !== '') return envCli
283
+ if (extDir !== undefined && extDir !== '') {
284
+ const sibling = resolve(extDir, '..', 'scripts', 'team')
285
+ if (existsSync(sibling)) return sibling
286
+ }
287
+ return null
288
+ }
289
+
290
+ // ---------------------------------------------------------------- 执行与输出(design §3.4 / §3.5)
291
+ export const CUSTOM_TYPE = 'teamsmith-team'
292
+ export const WAIT_MS = 60000
293
+ export const SHORT_LINE_MAX = 200
294
+ export const FUSE_LINES = 500
295
+ export const FUSE_BYTES = 64 * 1024
296
+ export const FUSE_HEAD_LINES = 200
297
+ export const FUSE_TAIL_LINES = 100
298
+ /** 唯一一处收紧:剥掉「替用户说 yes」的三个变量(用户自己打的 --yes 照旧到达)。 */
299
+ export const UNSET_VARS = ['TEAM_ASSUME_YES', 'TEAM_UPGRADE_CONFIRMED', 'TEAM_ALLOW_FOREIGN_SESSION']
300
+
301
+ export type ExecOptions = { cwd?: string; timeout?: number }
302
+ export type ExecResult = { stdout: string; stderr: string; code: number; killed: boolean }
303
+ export type ExecFn = (command: string, args: string[], options?: ExecOptions) => Promise<ExecResult>
304
+ export type CustomMessage = { customType: string; content: string; display?: boolean }
305
+ export type Deps = {
306
+ cwd: string
307
+ exec: ExecFn
308
+ sendMessage: (message: CustomMessage) => void
309
+ notify: (message: string, type?: 'info' | 'warning' | 'error') => void
310
+ env?: Record<string, string | undefined>
311
+ extDir?: string
312
+ }
313
+ export type Outcome =
314
+ | { kind: 'menu'; text: string }
315
+ | { kind: 'refused'; message: string }
316
+ | { kind: 'ran'; argv: string[]; code: number; killed: boolean; content: string; short: boolean }
317
+
318
+ /** 剥离包装:`bash -c 'unset …; exec "$0" "$@"' <cli> <tokens…>` —— 只转交,不做二次解析。 */
319
+ export function wrapScript(): string {
320
+ const unset = UNSET_VARS.length > 0 ? `unset ${UNSET_VARS.join(' ')}; ` : ''
321
+ return `${unset}exec "$0" "$@"`
322
+ }
323
+
324
+ function utf8Bytes(s: string): number {
325
+ let n = 0
326
+ for (let i = 0; i < s.length; i++) {
327
+ const c = s.charCodeAt(i)
328
+ if (c < 0x80) n += 1
329
+ else if (c < 0x800) n += 2
330
+ else if (c >= 0xd800 && c <= 0xdbff) { n += 4; i++ }
331
+ else n += 3
332
+ }
333
+ return n
334
+ }
335
+
336
+ /** 保险丝:超过 500 行或 64 KiB(先到先算)时保留前 200 + 后 100 行,中间显式说明去哪看全文。 */
337
+ export function fuseOutput(text: string, argv: string[]): string {
338
+ const lines = text.split('\n')
339
+ const bytes = utf8Bytes(text)
340
+ if (lines.length <= FUSE_LINES && bytes <= FUSE_BYTES) return text
341
+ const head = lines.slice(0, FUSE_HEAD_LINES)
342
+ const tail = lines.slice(lines.length - FUSE_TAIL_LINES)
343
+ const dropped = lines.length - head.length - tail.length
344
+ const droppedBytes = Math.max(0, bytes - utf8Bytes(head.join('\n')) - utf8Bytes(tail.join('\n')))
345
+ const notice = t('run.elided', { lines: String(dropped), bytes: String(droppedBytes), argv: argv.join(' ') })
346
+ return head.concat([notice], tail).join('\n')
347
+ }
348
+
349
+ /** 单行且 ≤ 200 字符(按码点)的成功结果 ⇒ 通知,不进对话。 */
350
+ export function isShortSuccess(res: ExecResult): boolean {
351
+ if (res.killed || res.code !== 0) return false
352
+ const text = (res.stdout ?? '').replace(/^\s+/, '').replace(/\s+$/, '')
353
+ if (text === '' || text.indexOf('\n') >= 0) return false
354
+ return Array.from(text).length <= SHORT_LINE_MAX
355
+ }
356
+
357
+ export function shortText(res: ExecResult): string {
358
+ return (res.stdout ?? '').replace(/^\s+/, '').replace(/\s+$/, '')
359
+ }
360
+
361
+ /** 正文条目:命令行 + 退出码(或被杀原因)+ stdout(+ stderr)。 */
362
+ export function formatEntry(argv: string[], res: ExecResult): string {
363
+ const header = t('run.header', { argv: argv.join(' ') })
364
+ const status = res.killed ? t('run.killed', { sec: String(WAIT_MS / 1000) }) : t('run.exit', { code: String(res.code) })
365
+ let body = t('run.stdout') + '\n' + (res.stdout ?? '')
366
+ if ((res.stderr ?? '') !== '') body += '\n' + t('run.stderr') + '\n' + res.stderr
367
+ return header + '\n' + status + '\n' + fuseOutput(body, argv)
368
+ }
369
+
370
+ export function failureNotice(argv: string[], res: ExecResult): string {
371
+ if (res.killed) return t('fail.killed', { argv: argv.join(' '), sec: String(WAIT_MS / 1000) })
372
+ return t('fail.exit', { argv: argv.join(' '), code: String(res.code) })
373
+ }
374
+
375
+ function refuse(deps: Deps, message: string): Outcome {
376
+ deps.sendMessage({ customType: CUSTOM_TYPE, content: message, display: true })
377
+ return { kind: 'refused', message }
378
+ }
379
+
380
+ /**
381
+ * 纯逻辑入口:拒绝/菜单/执行与落点都在这里。`deps` 是全部外部接触面(exec / sendMessage / notify),
382
+ * 所以假 pi 可以直接驱动它,而它自己不认识任何 Pi API。
383
+ */
384
+ export async function runTeamCommand(deps: Deps, argv: string[]): Promise<Outcome> {
385
+ const m = matchInvocation(argv)
386
+ if (m.kind === 'menu') {
387
+ const text = renderMenu()
388
+ deps.sendMessage({ customType: CUSTOM_TYPE, content: text, display: true })
389
+ return { kind: 'menu', text }
390
+ }
391
+ if (m.kind === 'refuse') return refuse(deps, m.message)
392
+
393
+ const root = findProjectRoot(deps.cwd)
394
+ if (root === null) return refuse(deps, t('refuse.no-project', { cwd: deps.cwd }))
395
+ const cli = resolveCli(root, deps.env ?? {}, deps.extDir)
396
+ if (cli === null) return refuse(deps, t('refuse.no-cli', { root }))
397
+
398
+ const res = await deps.exec('bash', ['-c', wrapScript(), cli, ...m.tokens], { cwd: root, timeout: WAIT_MS })
399
+
400
+ if (isShortSuccess(res)) {
401
+ const text = shortText(res)
402
+ deps.notify(text, 'info')
403
+ return { kind: 'ran', argv: m.tokens, code: res.code, killed: res.killed, content: text, short: true }
404
+ }
405
+ const content = formatEntry(m.tokens, res)
406
+ deps.sendMessage({ customType: CUSTOM_TYPE, content, display: true })
407
+ if (res.killed || res.code !== 0) deps.notify(failureNotice(m.tokens, res), 'error')
408
+ return { kind: 'ran', argv: m.tokens, code: res.code, killed: res.killed, content, short: false }
409
+ }
410
+
411
+ // ---------------------------------------------------------------- Pi 粘合(唯一使用 Pi API 的地方)
412
+ const HERE = (() => {
413
+ try { return dirname(fileURLToPath(import.meta.url)) } catch { return undefined }
414
+ })()
415
+
416
+ /**
417
+ * 默认导出:**只**注册 `/team` 一条命令。不注册任何模型可调用的工具 —— 模型不能自己触发它;
418
+ * 不弹任何自己的确认框 —— 前门不给用户加第二道自己的政策(CLI 的守卫原样生效)。
419
+ */
420
+ export default function teamExtension(pi: ExtensionAPI): void {
421
+ pi.registerCommand('team', {
422
+ description: t('command.description'),
423
+ getArgumentCompletions: (prefix: string) => completions(prefix),
424
+ handler: async (args: string, ctx) => {
425
+ const deps: Deps = {
426
+ cwd: ctx.cwd,
427
+ exec: (command, argv, options) => pi.exec(command, argv, options),
428
+ sendMessage: (message) => pi.sendMessage(message),
429
+ notify: (message, type) => ctx.ui.notify(message, type),
430
+ env: process.env as Record<string, string | undefined>,
431
+ extDir: HERE,
432
+ }
433
+ const parsed = tokenize(args)
434
+ if (!parsed.ok) { refuse(deps, parsed.error); return }
435
+ await runTeamCommand(deps, parsed.tokens)
436
+ },
437
+ })
438
+ }
@@ -40,10 +40,11 @@ literals or simple `$VAR`.
40
40
  | `TEAM_SESSION` | `$TEAM_PROJECT` | tmux session (shared by the PM and every agent) |
41
41
  | `TEAM_PM_WINDOW` | `pm` | the window the PM session lives in; notifications are typed there |
42
42
  | `TEAM_AGENTS` | empty (`init` sets `dev verify`) | roster, space separated; grows only through `team add-agent <a> --register` and shrinks only through `team teardown --agent <a> --register` (both audited; a bare `team add-agent <a>` refuses a seat the roster does not carry and names both routes) |
43
- | `TEAM_TASK_MODELS` | empty (required) | the project's task-category → model map: `routine=provider/light analysis=provider/strong verify=provider/strong`. A **new** dispatch selects the model of the brief's `category:` from it; a complete same-task recovery keeps the model/SID it was already assigned, even after the category leaves the map. One category: `team config set-task-model <category> <model>`; the whole map: `team config set TEAM_TASK_MODELS '<map>' --yes`; breaking migration: `team config upgrade-models` |
43
+ | `TEAM_TASK_MODELS` | empty (required) | the project's task-category → model map: `routine=provider/light analysis=provider/strong verify=provider/strong`. A **new** dispatch selects the model of the brief's `category:` from it; a complete same-task recovery keeps the model/SID it was already assigned, even after the category leaves the map. One category: `team config set-task-model <category> <model>`; the whole map: `team config set TEAM_TASK_MODELS '<map>' --yes`; breaking migration: the next `team up` (startup transaction) or `team config upgrade-models` |
44
44
  | `TEAM_PM_MODEL` | empty (required) | the **independent PM model** — never a fallback to a task model or a worker default. `team up` guards it (a running PM with a different model needs an explicit `--fresh-pm`) |
45
+ | `TEAM_CONFIG_VERSION` | the current shape (written by the tool) | the configuration **shape number** (`refuse` class — the console never writes it). A project without the key is classified by its keys; a number higher than this tool's newest known shape is refused instead of migrated. `init`/`bootstrap` write the current number and the startup transaction writes it when it migrates an old shape |
45
46
 
46
- Categories are the project's own vocabulary (`[a-z][a-z0-9-]*`, unique): routine/analysis/verify are the initial example, not an engine list, and `phase:`/seat never selects a model automatically. The initial suggestion is `routine=opencode-go/deepseek-v4.1-flash`, `analysis`/`verify=openai-codex/gpt-6.1-sol:high`, independent PM the same strong model — examples, not defaults or a provider-availability claim. The retired keys TEAM_AGENT_MODELS / TEAM_DEFAULT_MODEL are no longer read: a project that still carries them is refused by the loader and by init/bootstrap, and migrates through the explicit `team config upgrade-models --task-models '<map>' --pm-model '<model>'` transaction (preview first, then `--yes`) — never through `team init --force`, bootstrap or an inference.
47
+ Categories are the project's own vocabulary (`[a-z][a-z0-9-]*`, unique): routine/analysis/verify are the initial example, not an engine list, and `phase:`/seat never selects a model automatically. The initial suggestion is `routine=opencode-go/deepseek-v4.1-flash`, `analysis`/`verify=openai-codex/gpt-6.1-sol:high`, independent PM the same strong model — examples, not defaults or a provider-availability claim. The retired keys TEAM_AGENT_MODELS / TEAM_DEFAULT_MODEL are no longer read: a project that still carries them is refused by the loader and by init/bootstrap, and migrates on the next `team up` (the startup transaction derives the pairs from the old keys, prints them before → after, backs the file up and writes through the same checked writer) or through the explicit `team config upgrade-models --task-models '<map>' --pm-model '<model>'` transaction (preview first, then `--yes`) — never through `team init --force`, bootstrap or an inference. The refusal advice carries one paste-ready `team config upgrade-models …` command derived from that project's own configuration, or names the obstacle when the derivation is not unambiguous.
47
48
  | `TEAM_MODEL_LIMITS` | `kimi-coding/k3=2` | concurrency limits, `provider/model=N` space separated; `0` = unlimited |
48
49
  | `TEAM_EXTRA_PI_ARGS` | empty | extra arguments passed to pi (space separated, values with spaces are unsupported) |
49
50
 
@@ -56,6 +57,7 @@ Categories are the project's own vocabulary (`[a-z][a-z0-9-]*`, unique): routine
56
57
  | `TEAM_INSTALL_CMD` | empty | install command run after creating a worktree (e.g. `pnpm install --frozen-lockfile`) |
57
58
  | `TEAM_DOCS_DIR` | `docs/team` | directory for briefs/reports/reviews/threads/inbox |
58
59
  | `TEAM_WORKTREES_DIR` | `.worktrees` | long-lived worktree directory (also how "this is an agent session" is recognised) |
60
+ | `TEAM_TMP_ROOT` | empty (resolved) | temp root for fixtures and gates. Resolution happens in exactly one place (`team_tmp_root`): a non-empty `TMPDIR` in the environment wins, then this key, then the platform default `/var/tmp/teamsmith-<project-ns>` — a filesystem, not the memory-backed `/tmp` (fixture writes must not compete with the OOM killer). The two-step order is printed, not guessed: `team status`, the dispatch capacity line and `tmp-hygiene --status` all name the value and its `source=tmpdir|config|default`, and a `TMPDIR` that overrides this key is reported as such. An explicit value that is relative, missing, not a directory or not writable blocks dispatch with the path and a remedy — it is never replaced by another root. Only the default leg is created (0700, first write); explicit roots are never created for you. Rollback to the old behaviour: `TEAM_TMP_ROOT="/tmp"` |
59
61
  | `TEAM_PROTECTED_BRANCH` | `main` | the branch only the PM may advance |
60
62
  | `TEAM_REMOTE` | `origin` | remote name (present even in local mode, used when pushing branches) |
61
63
  | `TEAM_PI_AGENT_DIR` | the directory of `TEAM_PI_SETTINGS_FILE` | where Pi keeps `sessions/` and its model catalog — the only place the session-size guard and the model windows are read from (read-only: `stat` of the session file, the catalog files) |
@@ -64,6 +66,7 @@ Categories are the project's own vocabulary (`[a-z][a-z0-9-]*`, unique): routine
64
66
  | `TEAM_DISPATCH_VERIFY_SEC` | `8` | how long a dispatch waits for the pane's launch proof before it kills the window and retries |
65
67
  | `TEAM_DISPATCH_ALIVE_SEC` | `1` | after the launch proof, how long to observe whether the agent is still in the window (built-in Pi only; `0` = skip the observation). A subsequent exit is reported as a warning, never as a failed dispatch |
66
68
  | `TEAM_SQUASH_LOOKBACK` | `200` | how many commits on the protected branch are scanned when deciding "this branch was already squash-merged" (one tree comparison per agent row; a heuristic, see workflows.md) |
69
+ | `TEAM_UPDATE_CHECK` | `1` | `0` = `team up` makes no npm version lookup at all (no query, no cache read or write). `1` = at most one bounded (≤2 s) lookup per 24 h, cached in `<state>/update-check.env`; every outcome except "local is older than the published version" prints nothing and never changes `team up`'s exit code. The tool never installs itself |
67
70
 
68
71
  ### agent adapter (the internal seam (frozen); leave all four empty for the built-in Pi behaviour)
69
72
 
@@ -149,7 +152,7 @@ empty panel reported as success.
149
152
  |---|---|---|
150
153
  | `TEAM_MIN_FREE_SWAP_MB` | `1024` | **floor**: below this much free swap the dispatch is refused (a full swap gets processes killed by the OOM killer) |
151
154
  | `TEAM_MIN_TOTAL_MB` | `512` | the absolute RAM+swap floor |
152
- | `TEAM_TMP_MIN_FREE_MB` | `1024` | **floor**: below this much free space the dispatch is refused — judged on the filesystems a worker writes to (the temp root `${TMPDIR:-/tmp}` **and** the worktree filesystem). Derivation: one gate round's root measured 95 MB / 11,797 files, a killed `config-cli` root 99 MB / 10,954 files, so 1 GiB leaves ~10 gate rounds of headroom |
155
+ | `TEAM_TMP_MIN_FREE_MB` | `1024` | **floor**: below this much free space the dispatch is refused — judged on the filesystems a worker writes to (the **resolved** temp root — `TMPDIR` → `TEAM_TMP_ROOT` → `/var/tmp/teamsmith-<ns>`, named with its `source=` — **and** the worktree filesystem). Derivation: one gate round's root measured 95 MB / 11,797 files, a killed `config-cli` root 99 MB / 10,954 files, so 1 GiB leaves ~10 gate rounds of headroom |
153
156
  | `TEAM_TMP_MIN_FREE_INODES` | `100000` | **floor**: the same filesystems' free inodes (judged only where the filesystem reports an inode table). Derivation: the same 10,954-file roots → ~9 roots of headroom; the tmpfs died with 4,645 of 3,811,434 inodes free |
154
157
  | `TEAM_WARN_AVAIL_MB` | `2048` | below this much available RAM: warn only (slowness is acceptable), never refuse |
155
158
  | `TEAM_AGENT_MEM_MB` | `6144` | empirical footprint of one agent, used by `team ps` for its "how many more fit" estimate |
@@ -157,9 +160,34 @@ empty panel reported as success.
157
160
  | `TEAM_NOTIFY_DEDUP_SEC` | `20` | deduplication window (seconds); `0` = no deduplication |
158
161
  | `TEAM_INBOX_MAX_CHARS` | `150` | truncation length of the agent's last message inside a briefing |
159
162
  | `TEAM_NOTIFY_LOG` | `/tmp/<project>-teamsmith-notify.log` | extension debug log (look here when notifications misbehave) |
163
+ | `TEAM_NOTIFY_DETAIL_MAX` | `2048` | events a turn-end notification's detail file (`state/notify.log`) may hold before it is rotated to `state/notify.log.1` (one generation kept; a rotation is named in the extension log) |
160
164
  | `TEAM_DEFER_TTL` | `300` | delivery guard: seconds a queued message may wait before it is moved to `state/outbox/held/` (holding never types anything; the payload is already in the recipient's inbox). A backstop, not the first symptom: an untrusted geometry holds immediately and three trusted-empty drains with no progress hold as `queue-stalled` |
161
165
  | `TEAM_OUTBOX_MAX` | `200` | delivery guard: maximum active queue entries; beyond it the oldest entry is escalated to `held/` |
162
166
 
167
+ ### Orphan seat processes (`seat-visibility`)
168
+
169
+ A seat's liveness is judged **by its window**: a process whose tmux window is gone is invisible to `team status`
170
+ and `team resume` while still holding memory (one host had seven such processes summing to ~4 GB). `team ps`,
171
+ `team status` and `team up` therefore append a **host-side census** read from `/proc` — a process is a seat when
172
+ its own environment carries teamsmith's identity (`TEAM_MAIN_ROOT`/`TEAM_ROOT`) and its command line names the
173
+ project's configured agent or PM executable. A seat is an orphan exactly when it has **no live pane**, judged on
174
+ the tmux server the process itself names; when that server cannot be queried the process is left **unjudged** and
175
+ is never called an orphan. Only this project's orphans are named (each with a copy-pasteable `team reap <pid>
176
+ --yes`); another project's orphans and identity-less processes are reported as a count and a **floor** (`≥`) only,
177
+ because the reading is meant to be copied into the ledger. The census writes nothing and signals nothing.
178
+
179
+ | Key | Default | Purpose |
180
+ |---|---|---|
181
+ | `TEAM_ORPHAN_WARN_MB` | `1024` | when the host-wide orphan total is at or above this many MB, `team digest`'s capacity line carries one hint (total, this project's share, the cleanup command). `0` = never hint (needs `--allow-danger`). It never changes the exit code |
182
+ | `TEAM_ORPHAN_SCAN` | `1` | whether the host-side census runs at all. `0` = read no process's environment: `team ps`, `team status` and `team up` print one named skip line instead of the reading, `team digest` adds no hint, and `team reap --orphans` refuses (exit 2) — cleanup then needs an explicit pid (`team reap <pid> --yes`). It exists for hosts where reading another process's environment is refused; the reading — and the cleanup plan it feeds — needs the default `1` |
183
+ | `TEAM_ORPHAN_PROC_ROOT` | `/proc` | fixture-only: the proc root the census reads, so the unreadable / vanished / empty-environment / missing-field edges can be built deterministically. Not writable from the console |
184
+
185
+ Cleanup is never automatic: `team reap --orphans` prints the plan and signals nothing, and `team reap --orphans
186
+ --yes` (or `team reap <pid> --yes`) re-verifies every target immediately before signalling it — still this
187
+ project's seat, still without a live pane, and the same process start time the plan recorded — then sends
188
+ `SIGTERM`, waits a bounded 5 s and only then `SIGKILL`. Every signal appends one line to `state/reap.log`.
189
+ `--yes` is the only authorization: no configuration key, environment variable or inherited value turns it on.
190
+
163
191
  ### Deferred delivery (`delivery-guard`)
164
192
 
165
193
  Automatic senders never type into an input box that already holds a draft: the message is queued in
@@ -313,7 +341,7 @@ see it.
313
341
  | `TEAM_MIN_FREE_SWAP_MB` | temporarily override the disk swap floor |
314
342
  | `TEAM_MEMINFO_FILE` | point at another meminfo file (for containers/tests without `/proc/meminfo`) |
315
343
  | `TEAM_DISK_STATS_FILE` | the disk-reading fixture (`TEAM_MEMINFO_FILE`'s sibling): rows `path<TAB>total_kb<TAB>avail_kb<TAB>itotal<TAB>ifree`, longest matching path prefix wins; a path with no row reads as unreadable — tests only |
316
- | `TMPDIR` | the temp root every fixture's root resolves to (`${TMPDIR:-/tmp}`); `TMPDIR=D bash tests/config-cli.sh` is the shape of the temp-root flip, and no fixture template may hardcode `/tmp` |
344
+ | `TMPDIR` | the **first** source of the temp root (`team_tmp_root`): a non-empty value wins over `TEAM_TMP_ROOT` and the disk default `/var/tmp/teamsmith-<ns>`; `TMPDIR=D bash tests/config-cli.sh` is the shape of the temp-root flip, the override is printed as `source=tmpdir`, and no fixture template may hardcode `/tmp` |
317
345
 
318
346
  Environment-only temp-root knobs are deliberately **not** part of the config surface (no schema row, not writable into
319
347
  `.pi/team/config.sh`): they live in `references/protocol.md` §9b-2 and `references/troubleshooting.md` §25 —
@@ -389,7 +417,8 @@ under its domain with the committed console bundle, and no group list exists any
389
417
  never reaches a running process (the measured `TEAM_MONITOR_ACTIVITY` case).
390
418
  * A `'` inside the value is written `'\''`. A line break or a `#` is refused (the notify extension's flat reader
391
419
  cuts at ` #`). On the eight keys that reader parses — `TEAM_SESSION`, `TEAM_PM_WINDOW`, `TEAM_WORKTREES_DIR`,
392
- `TEAM_DOCS_DIR`, `TEAM_NOTIFY_TMUX`, `TEAM_NOTIFY_DEDUP_SEC`, `TEAM_INBOX_MAX_CHARS`, `TEAM_NOTIFY_LOG` — a `'`
420
+ `TEAM_DOCS_DIR`, `TEAM_NOTIFY_TMUX`, `TEAM_NOTIFY_DEDUP_SEC`, `TEAM_INBOX_MAX_CHARS`, `TEAM_NOTIFY_LOG`,
421
+ `TEAM_NOTIFY_DETAIL_MAX` — a `'`
393
422
  is refused too (that reader has no escape).
394
423
  * Every byte the write does not change survives: comments, blank lines, the order of the keys and the changed
395
424
  line's own inline comment. A key the file lacks is appended on a line of its own (a missing final newline is
@@ -432,7 +461,11 @@ model. `team config upgrade-models --task-models '<map>' --pm-model '<model>'` i
432
461
  transaction: it previews with `--dry-run`, writes only with `--yes`, replaces the four model keys (the two retired
433
462
  worker keys are removed, the two new keys upserted) and keeps every other byte; its relevant-line grammar
434
463
  (top-level unique literal assignments, optional inline comments) refuses export/duplicate/multiline/dynamic shapes
435
- with the file and line named, and the repair is a hand-normalized literal line. The retired `set-agent-model`
464
+ with the file and line named, and the repair is a hand-normalized literal line. The startup path calls the same
465
+ transaction (`team up`, actor `up-migration`): it derives the pairs from the old keys with the same table the
466
+ refusals use, writes `TEAM_CONFIG_VERSION`, prints every pair before → after with the backup path and the restore
467
+ command, and re-enters itself so later steps read the new bytes; `team up --print` writes nothing and `team up
468
+ --no-migrate` refuses instead of writing. The retired `set-agent-model`
436
469
  route exits 5 pointing at these; `team add-agent --model` is retired too (a seat is a name in the roster, not a
437
470
  model identity).
438
471