teamsmith 0.4.6 → 0.4.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (91) hide show
  1. package/README.md +6 -6
  2. package/package.json +1 -1
  3. package/skills/teamsmith/CHANGELOG.md +35 -0
  4. package/skills/teamsmith/SKILL.md +43 -30
  5. package/skills/teamsmith/extension/team-bg.ts +5 -3
  6. package/skills/teamsmith/extension/team-inbox-watch.ts +14 -3
  7. package/skills/teamsmith/extension/team-notify.ts +20 -13
  8. package/skills/teamsmith/extension/team-remind.ts +189 -0
  9. package/skills/teamsmith/extension/team-reply.ts +4 -7
  10. package/skills/teamsmith/references/config.md +11 -12
  11. package/skills/teamsmith/references/migration.md +101 -0
  12. package/skills/teamsmith/references/openspec.md +43 -27
  13. package/skills/teamsmith/references/protocol.md +26 -15
  14. package/skills/teamsmith/references/reminders.md +153 -161
  15. package/skills/teamsmith/references/troubleshooting.md +12 -7
  16. package/skills/teamsmith/references/workflows.md +84 -31
  17. package/skills/teamsmith/scripts/lib/cmd-agents.sh +10 -4
  18. package/skills/teamsmith/scripts/lib/cmd-project.sh +88 -6
  19. package/skills/teamsmith/scripts/lib/cmd-remind.sh +88 -2
  20. package/skills/teamsmith/scripts/lib/cmd-review.sh +61 -35
  21. package/skills/teamsmith/scripts/lib/cmd-watch.sh +48 -11
  22. package/skills/teamsmith/scripts/lib/common.sh +83 -13
  23. package/skills/teamsmith/scripts/panel/README.md +35 -33
  24. package/skills/teamsmith/scripts/panel/panel.js +217 -199
  25. package/skills/teamsmith/scripts/panel/src/App.tsx +221 -66
  26. package/skills/teamsmith/scripts/panel/src/data.ts +71 -15
  27. package/skills/teamsmith/scripts/panel/src/layout.ts +159 -310
  28. package/skills/teamsmith/scripts/panel/src/main.tsx +83 -21
  29. package/skills/teamsmith/scripts/panel/src/project-settings.ts +46 -0
  30. package/skills/teamsmith/scripts/panel/src/strings/en.ts +71 -205
  31. package/skills/teamsmith/scripts/panel/src/strings/index.ts +3 -5
  32. package/skills/teamsmith/scripts/panel/src/strings/zh.ts +72 -204
  33. package/skills/teamsmith/scripts/panel/src/types.ts +23 -4
  34. package/skills/teamsmith/scripts/remind-capability.mjs +261 -0
  35. package/skills/teamsmith/scripts/remind-store.mjs +55 -24
  36. package/skills/teamsmith/scripts/remind-tick.mjs +5 -2
  37. package/skills/teamsmith/scripts/reply-capture.mjs +8 -9
  38. package/skills/teamsmith/scripts/state-authority.mjs +72 -6
  39. package/skills/teamsmith/scripts/strings/commands.tsv +1 -1
  40. package/skills/teamsmith/scripts/team +1 -0
  41. package/skills/teamsmith/templates/AGENTS.section.md.tmpl +18 -8
  42. package/skills/teamsmith/templates/DECISIONS.md.tmpl +2 -2
  43. package/skills/teamsmith/templates/OWNERSHIP.md.tmpl +3 -3
  44. package/skills/teamsmith/templates/PROTOCOL.md.tmpl +19 -14
  45. package/skills/teamsmith/templates/memory-seed.md.tmpl +2 -2
  46. package/skills/teamsmith/templates/pm-prompt.md.tmpl +41 -25
  47. package/skills/teamsmith/templates/report.md.tmpl +33 -0
  48. package/skills/teamsmith/tests/bg-ledger-harness.mjs +217 -33
  49. package/skills/teamsmith/tests/bg-ledger.sh +24 -10
  50. package/skills/teamsmith/tests/checkout-shape-probe.sh +7 -6
  51. package/skills/teamsmith/tests/fixtures/remind-adversarial-delay.ts +27 -0
  52. package/skills/teamsmith/tests/fixtures/remind-tool-provider.ts +65 -0
  53. package/skills/teamsmith/tests/help-surface.sh +78 -12
  54. package/skills/teamsmith/tests/install-shape.sh +7 -7
  55. package/skills/teamsmith/tests/isolation-ledger.sh +6 -2
  56. package/skills/teamsmith/tests/key-replies-ui.sh +64 -5
  57. package/skills/teamsmith/tests/key-replies.sh +307 -106
  58. package/skills/teamsmith/tests/lib/main-team-fingerprint.sh +2 -0
  59. package/skills/teamsmith/tests/lib/model-routing-boundary.sh +255 -90
  60. package/skills/teamsmith/tests/lib/model-routing-expansion.sh +181 -61
  61. package/skills/teamsmith/tests/lib/model-routing-roles.sh +125 -67
  62. package/skills/teamsmith/tests/lib/reply-fixture.sh +14 -9
  63. package/skills/teamsmith/tests/lib/routes-pages.sh +243 -0
  64. package/skills/teamsmith/tests/lib/tmp-root.sh +1 -1
  65. package/skills/teamsmith/tests/loop-inventory.tsv +3 -0
  66. package/skills/teamsmith/tests/panel-b2.sh +91 -31
  67. package/skills/teamsmith/tests/panel-b3-stub.sh +9 -2
  68. package/skills/teamsmith/tests/panel-p21.sh +607 -1162
  69. package/skills/teamsmith/tests/panel-strings.mjs +21 -113
  70. package/skills/teamsmith/tests/remind-adversarial-faults.mjs +190 -0
  71. package/skills/teamsmith/tests/remind-adversarial-faults.sh +78 -0
  72. package/skills/teamsmith/tests/remind-adversarial-real.sh +28 -0
  73. package/skills/teamsmith/tests/remind-cli.sh +108 -3
  74. package/skills/teamsmith/tests/remind-delivery-node.mjs +13 -0
  75. package/skills/teamsmith/tests/remind-delivery.sh +123 -35
  76. package/skills/teamsmith/tests/remind-lifecycle.sh +197 -0
  77. package/skills/teamsmith/tests/remind-pulse.sh +199 -0
  78. package/skills/teamsmith/tests/remind-recovery-real.sh +5 -0
  79. package/skills/teamsmith/tests/remind-recovery-unit.sh +118 -0
  80. package/skills/teamsmith/tests/remind-tool-node.mjs +159 -0
  81. package/skills/teamsmith/tests/remind-tool-real.mjs +801 -0
  82. package/skills/teamsmith/tests/remind-tool-real.sh +180 -0
  83. package/skills/teamsmith/tests/reply-capture-real.mjs +93 -2
  84. package/skills/teamsmith/tests/routes.sh +213 -293
  85. package/skills/teamsmith/tests/section-paths.tsv +19 -17
  86. package/skills/teamsmith/tests/smoke.sh +583 -133
  87. package/skills/teamsmith/tests/state-authority.sh +152 -8
  88. package/skills/teamsmith/tests/task-model-routing.sh +57 -26
  89. package/skills/teamsmith/tests/tmp-hygiene.sh +1 -1
  90. package/skills/teamsmith-init/SKILL.md +5 -5
  91. package/skills/teamsmith/tests/fixtures/delivery-truth-real/__pycache__/judge-second.cpython-313.pyc +0 -0
@@ -0,0 +1,801 @@
1
+ #!/usr/bin/env node
2
+ // P442 private real Pi + private tmux + controlled loopback provider. No live team, credentials or model.
3
+ import assert from 'node:assert/strict'
4
+ import { createServer } from 'node:http'
5
+ import { spawn, spawnSync } from 'node:child_process'
6
+ import { once } from 'node:events'
7
+ import { appendFileSync, cpSync, existsSync, mkdirSync, readFileSync, readdirSync, rmSync, writeFileSync } from 'node:fs'
8
+ import { constants } from 'node:os'
9
+ import { dirname, join } from 'node:path'
10
+ import { fileURLToPath } from 'node:url'
11
+ import { setImmediate as immediate, setTimeout as delay } from 'node:timers/promises'
12
+
13
+ const tests = dirname(fileURLToPath(import.meta.url)), skill = dirname(tests)
14
+ // Direct Node calls (including the recovery entry) use the same owner as the shell.
15
+ if (!process.env._P442_WORK) {
16
+ const owner = spawn('bash', [join(tests, 'remind-tool-real.sh'), ...process.argv.slice(2)], {
17
+ env: { ...process.env, _P442_NODE: process.execPath }, stdio: 'inherit',
18
+ })
19
+ for (const signal of ['SIGINT', 'SIGTERM']) process.on(signal, () => owner.kill(signal))
20
+ const [code, signal] = await once(owner, 'exit')
21
+ process.exit(code ?? 128 + constants.signals[signal])
22
+ }
23
+
24
+ let stopSignal
25
+ for (const signal of ['SIGINT', 'SIGTERM']) process.on(signal, () => { stopSignal ??= signal })
26
+ function checkStop() {
27
+ if (stopSignal) process.exit(128 + constants.signals[stopSignal])
28
+ }
29
+ async function stopPoint() {
30
+ // Cross a poll turn even if the command returned in an I/O callback before this turn's check phase.
31
+ await immediate()
32
+ await immediate()
33
+ checkStop()
34
+ }
35
+ async function runSync(bin, args, options) {
36
+ checkStop()
37
+ try { return spawnSync(bin, args, options) }
38
+ finally { await stopPoint() }
39
+ }
40
+
41
+ const selection = (process.argv.find(a => a.startsWith('--select='))?.slice(9) ?? 'pm,large,identity,doctor').split(',')
42
+ const { _P442_WORK: temporary, _P442_EVIDENCE: evidence, _P442_SOCKET: socket, _P442_PATH: privatePath,
43
+ _P442_PI: pi, _P442_SCENES: launchedScenes } = process.env
44
+ console.log(`remind-tool-real: pi=${pi}`)
45
+ mkdirSync(join(temporary, 'driver-home'))
46
+ const base = { HOME: join(temporary, 'driver-home'), PATH: privatePath, LANG: 'C.UTF-8',
47
+ TERM: 'xterm-256color', USER: process.env.USER ?? 'fixture', LOGNAME: process.env.LOGNAME ?? 'fixture', TMPDIR: temporary }
48
+ const sh = value => `'${value.replaceAll("'", "'\\''")}'`
49
+ async function command(bin, args, options = {}) {
50
+ const result = await runSync(bin, args, { encoding: 'utf8', env: base, ...options })
51
+ assert.equal(result.error, undefined, `${bin}: ${result.error}`)
52
+ assert.equal(result.status, 0, `${bin} ${args.join(' ')}: ${result.stderr}\n${result.stdout}`)
53
+ return result.stdout
54
+ }
55
+ const tmux = (...args) => command('tmux', ['-S', socket, '-f', '/dev/null', ...args])
56
+ const json = path => JSON.parse(readFileSync(path, 'utf8'))
57
+ const jsonl = path => existsSync(path) ? readFileSync(path, 'utf8').trim().split('\n').filter(Boolean).map(line => JSON.parse(line)) : []
58
+ const snapshot = state => json(join(state, 'reminders/state.json'))
59
+ const events = info => jsonl(join(info.dir, 'events.jsonl'))
60
+ const requests = info => jsonl(join(info.dir, 'requests.jsonl'))
61
+ const plans = new Map()
62
+ let server, passed = 0, failed = 0
63
+ async function until(test, label) {
64
+ const end = Date.now() + 90000 // Fixture watchdog, not a product latency claim.
65
+ let last
66
+ for (;;) {
67
+ checkStop()
68
+ try { if (test()) return } catch (e) { last = e } // A snapshot/process may not exist on the first poll.
69
+ if (Date.now() > end) throw new Error(`watchdog: ${label}: ${last?.message ?? 'condition stayed false'}`)
70
+ await delay(50)
71
+ }
72
+ }
73
+ function sse(res, { text = '', tool = null, name }) {
74
+ res.writeHead(200, { 'Content-Type': 'text/event-stream', 'Cache-Control': 'no-cache', Connection: 'keep-alive' })
75
+ const emit = (delta, finish = null) => res.write(`data: ${JSON.stringify({ id: `p442-${name}`, object: 'chat.completion.chunk',
76
+ created: 1, model: 'controlled', choices: [{ index: 0, delta, finish_reason: finish }] })}\n\n`)
77
+ emit({ role: 'assistant', content: '' })
78
+ if (text) emit({ content: text })
79
+ if (tool) {
80
+ emit({ tool_calls: [{ index: 0, id: `p442-call-${tool.n}`, type: 'function',
81
+ function: { name: 'team_remind', arguments: JSON.stringify(tool.input) } }] }, 'tool_calls')
82
+ } else emit({}, 'stop')
83
+ res.end('data: [DONE]\n\n')
84
+ }
85
+ server = createServer(async (req, res) => {
86
+ let raw = ''; for await (const chunk of req) raw += chunk
87
+ const body = JSON.parse(raw), name = req.url.split('/')[1], plan = plans.get(name)
88
+ if (!plan) { res.writeHead(404); res.end(); return }
89
+ checkStop()
90
+ const n = plan.requests++
91
+ appendFileSync(join(plan.dir, 'requests.jsonl'), JSON.stringify(body) + '\n')
92
+ if (n === (plan.gateN ?? 0) && plan.gate) await plan.gate
93
+ checkStop()
94
+ await plan.respond({ body, n, res, plan })
95
+ })
96
+ await new Promise(resolve => server.listen(0, '127.0.0.1', resolve))
97
+ checkStop()
98
+ const port = server.address().port
99
+ async function publishLaunch(info) {
100
+ const source = `source ${sh(join(info.skill, 'scripts/lib/common.sh'))}; source ${sh(join(info.skill, 'scripts/lib/cmd-config.sh'))}; team_load_config; team_pm_metadata_publish p442-${info.name}`
101
+ await command('bash', ['-c', source], { cwd: info.root, env: info.env })
102
+ }
103
+ async function doctor(info) {
104
+ const result = await runSync('bash', [join(info.skill, 'scripts/team'), '--root', info.root, 'doctor'],
105
+ { cwd: info.root, env: { ...info.env, TMUX: `${socket},${info.serverPid},0`, TMUX_PANE: info.pane }, encoding: 'utf8' })
106
+ const output = result.stdout + result.stderr
107
+ writeFileSync(join(info.dir, `doctor-${Date.now()}.txt`), output)
108
+ return output
109
+ }
110
+ async function start(name, respond, opts = {}) {
111
+ checkStop()
112
+ const dir = join(evidence, name), root = join(temporary, name), home = join(root, 'home'), state = join(root, '.pi/team/state'), config = join(root, '.pi/team/config.sh')
113
+ for (const path of [dir, home, join(home, '.pi/agent')]) mkdirSync(path, { recursive: true })
114
+ const runSkill = opts.skillCopy ? join(root, 'skill') : skill
115
+ if (opts.skillCopy) cpSync(skill, runSkill, { recursive: true })
116
+ if (opts.mutate) opts.mutate(runSkill)
117
+ writeFileSync(join(home, '.pi/agent/settings.json'), JSON.stringify({ retry: { enabled: false }, compaction: { enabled: false } }))
118
+ await command('git', ['init', '-q', '-b', 'main'], { cwd: root })
119
+ const session = `p442-${name}`, fixture = join(tests, 'fixtures/remind-tool-provider.ts')
120
+ const extra = `--offline --no-extensions --no-skills --no-context-files -e ${sh(fixture)}`
121
+ await command('bash', [join(skill, 'scripts/team'), 'init', '--no-skills', '--session', session,
122
+ '--agents', 'dev', '--vcs', 'local', '--gates', 'true', '--pm-model', 'p442/controlled',
123
+ '--task-models', 'routine=p442/controlled analysis=p442/controlled verify=p442/controlled code=p442/controlled'], { cwd: root, env: base })
124
+ writeFileSync(join(dir, 'config.generated.sh'), readFileSync(config))
125
+ for (const path of [state, join(root, 'docs/team/tasks'), join(root, 'docs/team/inbox'), join(root, 'docs/team/outbox')]) mkdirSync(path, { recursive: true })
126
+ const prompt = join(state, 'pm-prompt.md'); writeFileSync(prompt, `CASE ${name}\n`)
127
+ const env = { ...base, HOME: home, PI_CODING_AGENT_DIR: join(home, '.pi/agent'), P442_EVIDENCE: dir,
128
+ P442_ENDPOINT: `http://127.0.0.1:${port}/${name}/v1`, TEAM_REMIND_POLL_MS: '200',
129
+ TEAM_PI_BIN: pi, TEAM_PM_EXTRA_PI_ARGS: extra, ...(opts.env ?? {}) }
130
+ const manualLaunch = ['ordinary', 'worker'].includes(opts.invalid)
131
+ const receiptPath = manualLaunch ? 'home/.fixture-pi.pid' : '.pi/team/state/pm.pid.spawn'
132
+ const spawnReceipt = join(root, receiptPath)
133
+ const info = { name, dir, root, home, state, config, session, env, skill: runSkill, pane: '', spawnReceipt, done: join(dir, 'done') }
134
+ let launch
135
+ if (manualLaunch) {
136
+ let cwd = root
137
+ if (opts.invalid === 'worker') {
138
+ cwd = join(root, 'worker'); writeFileSync(join(root, 'README'), 'fixture'); await command('git', ['add', 'README'], { cwd: root })
139
+ await command('git', ['-c', 'user.name=fixture', '-c', 'user.email=fixture@example.invalid', 'commit', '-qm', 'fixture'], { cwd: root })
140
+ await command('git', ['worktree', 'add', '-q', '--detach', cwd, 'HEAD'], { cwd: root })
141
+ }
142
+ // These two cases bypass team_pm_launch_cmd; record the same pre-exec PID for cleanup.
143
+ launch = `cd ${sh(cwd)} && printf '%s\\n' "$$" > ${sh(spawnReceipt)} && exec ${sh(pi)} --provider p442 --model controlled -e ${sh(join(runSkill, 'extension/team-remind.ts'))} ${extra} @${sh(prompt)}`
144
+ } else {
145
+ const sourceScript = `source ${sh(join(runSkill, 'scripts/lib/common.sh'))}; source ${sh(join(runSkill, 'scripts/lib/cmd-config.sh'))}; team_load_config; team_pm_launch_cmd ${sh(prompt)} ${sh(spawnReceipt)}`
146
+ launch = await command('bash', ['-c', sourceScript], { cwd: root, env })
147
+ if (opts.invalid === 'no-entry') launch = launch.replace(` -e ${join(runSkill, 'extension/team-remind.ts')}`, '')
148
+ }
149
+ // Mutate after computing the directed launch so its environment still belongs to the real pane.
150
+ // The extension then rejects the changed file, matching a live config edit rather than a forged launch.
151
+ if (opts.configure) opts.configure(config)
152
+ if (opts.earlierHandler) {
153
+ const watcher = join(runSkill, 'extension/team-inbox-watch.ts')
154
+ const earlier = join(runSkill, 'tests/fixtures/remind-adversarial-delay.ts')
155
+ assert(launch.includes(`-e ${watcher}`), 'the real PM launch names the production watcher')
156
+ launch = launch.replace(`-e ${watcher}`, `-e ${earlier} -e ${watcher}`)
157
+ }
158
+ writeFileSync(join(dir, 'launch.txt'), launch + '\n')
159
+ if (!opts.invalid) assert.equal((launch.match(/extension\/team-remind\.ts/g) ?? []).length, 1, 'one directed Reminder extension')
160
+ let release
161
+ const gate = opts.deferFirstResponse ? new Promise(resolve => { release = resolve }) : null
162
+ plans.set(name, { requests: 0, dir, state, respond, gate })
163
+ const window = opts.invalid === 'forged' ? 'not-pm' : 'pm'
164
+ await tmux('new-session', '-d', '-s', session, '-n', window, '-c', root, 'sleep 600')
165
+ await tmux('set-option', '-t', session, 'remain-on-exit', 'on')
166
+ const pane = (await tmux('display-message', '-p', '-t', `${session}:${window}`, '#{pane_id}')).trim(); info.pane = pane
167
+ info.serverPid = (await tmux('display-message', '-p', '-t', pane, '#{pid}')).trim()
168
+ const script = join(root, 'launch.sh')
169
+ const assignments = Object.entries(env).map(([key, value]) => `export ${key}=${sh(value)};`).join('\n')
170
+ const launchError = join(dir, 'launch-stderr.txt')
171
+ writeFileSync(script, `#!/usr/bin/env bash\n${assignments}\nunset TEAM_ROOT TEAM_MAIN_ROOT TEAM_CONFIG_FILE TEAM_STATE_DIR\nbash -c ${sh(launch)} 2>${sh(launchError)}\nrc=$?; printf '%s\\n' "$rc" >${sh(info.done)}\nsleep 600\n`)
172
+ // Tell the owner before requesting the launch, even if interrupted before Pi can log session_start.
173
+ appendFileSync(launchedScenes, `${name}\t${receiptPath}\n`)
174
+ await tmux('respawn-pane', '-k', '-t', pane, `bash ${sh(script)}`)
175
+ await until(() => existsSync(join(dir, 'session-start')) || existsSync(info.done), `${name} session_start`)
176
+ if (existsSync(info.done) && !existsSync(join(dir, 'session-start'))) {
177
+ const output = await tmux('capture-pane', '-p', '-t', pane, '-S', '-')
178
+ writeFileSync(join(dir, 'launch-output.txt'), output)
179
+ throw new Error(`${name} Pi exited before session_start: rc=${readFileSync(info.done, 'utf8').trim()}\n${readFileSync(launchError, 'utf8')}${output}`)
180
+ }
181
+ if (!['ordinary', 'worker', 'forged', 'no-entry'].includes(opts.invalid)) await publishLaunch(info)
182
+ if (release) release()
183
+ if (opts.invalid === 'no-entry' && release) release()
184
+ const tick = async () => {
185
+ if (['ordinary', 'worker', 'forged', 'no-entry'].includes(opts.invalid)) return
186
+ await stopPoint()
187
+ await runSync(process.execPath, [join(runSkill, 'scripts/remind-tick.mjs'), '--root', root, '--state-dir', state,
188
+ '--pulse-started', new Date().toISOString(), '--json'], { cwd: root, env, stdio: 'ignore' })
189
+ }
190
+ const armTicker = () => setInterval(tick, 250)
191
+ info.ticker = opts.pauseTicker ? null : armTicker()
192
+ info.armTicker = () => { if (!info.ticker) info.ticker = armTicker() }
193
+ return info
194
+ }
195
+ async function stopPi(info) {
196
+ clearInterval(info.ticker)
197
+ if (!existsSync(info.done)) {
198
+ const pid = Number(readFileSync(join(info.dir, 'session-start'), 'utf8').trim())
199
+ const alive = () => { try { process.kill(pid, 0); return true } catch { return false } }
200
+ await tmux('send-keys', '-t', info.pane, '-l', '/p442-control stop'); await tmux('send-keys', '-t', info.pane, 'Enter')
201
+ // team_pm_start restarts do not use launch.sh, so they have no `done` receipt. Wait for either
202
+ // that receipt or the actual process exit; a stuck private fixture is killed by its recorded pid.
203
+ for (let n = 0; n < 200 && !existsSync(info.done) && alive(); n++) {
204
+ await delay(50)
205
+ checkStop()
206
+ }
207
+ if (!existsSync(info.done) && alive()) {
208
+ console.error(`CLEANUP ${info.name}: graceful shutdown did not exit; killing private Pi pid ${pid}`)
209
+ process.kill(pid, 'SIGKILL')
210
+ }
211
+ await until(() => existsSync(info.done) || !alive(), `${info.name} process reaped`)
212
+ }
213
+ }
214
+ async function stop(info) {
215
+ const alive = await runSync('tmux', ['-S', socket, '-f', '/dev/null', 'has-session', '-t', info.session], { env: base, encoding: 'utf8' })
216
+ if (alive.status === 0) {
217
+ await stopPi(info)
218
+ await tmux('kill-session', '-t', info.session)
219
+ } else clearInterval(info.ticker)
220
+ }
221
+ async function team(info, args, label = 'team') {
222
+ const result = await runSync('bash', [join(info.skill, 'scripts/team'), '--root', info.root, ...args], {
223
+ cwd: info.root, env: { ...info.env, TMUX: `${socket},${info.serverPid},0`, TMUX_PANE: info.pane }, encoding: 'utf8' })
224
+ writeFileSync(join(info.dir, `${label}.txt`), (result.stdout ?? '') + (result.stderr ?? ''))
225
+ return result
226
+ }
227
+ async function recover(info) {
228
+ // tmux respawn inherits the private server's environment, not spawnSync's. Publish the same
229
+ // controlled fixture environment the initial launch.sh supplied explicitly.
230
+ for (const [key, value] of Object.entries(info.env)) await tmux('set-environment', '-t', info.session, key, String(value))
231
+ const source = `source ${sh(join(info.skill, 'scripts/lib/common.sh'))}; source ${sh(join(info.skill, 'scripts/lib/cmd-config.sh'))}; source ${sh(join(info.skill, 'scripts/lib/cmd-remind.sh'))}; team_load_config; team_remind_recovery`
232
+ const result = await runSync('bash', ['-c', source], { cwd: info.root,
233
+ env: { ...info.env, TMUX: `${socket},${info.serverPid},0`, TMUX_PANE: info.pane }, encoding: 'utf8' })
234
+ writeFileSync(join(info.dir, `recovery-${Date.now()}.txt`), (result.stdout ?? '') + (result.stderr ?? ''))
235
+ return result
236
+ }
237
+ async function control(info, action) {
238
+ await tmux('send-keys', '-t', info.pane, '-l', `/p442-control ${action}`)
239
+ await tmux('send-keys', '-t', info.pane, 'Enter')
240
+ }
241
+ async function hardStop(info) {
242
+ const pid = Number(readFileSync(join(info.dir, 'session-start'), 'utf8').trim())
243
+ assert(Number.isSafeInteger(pid) && pid > 1, `real Pi pid in ${info.name}`)
244
+ process.kill(pid, 'SIGKILL')
245
+ await until(() => existsSync(info.done), `${info.name} hard death`)
246
+ }
247
+ async function restartDirect(info) {
248
+ // An outstanding intent is deliberately not eligible for team_remind_recovery (that path never
249
+ // resends). Restart the same stopped PM through the production prompt-free start primitive instead.
250
+ rmSync(info.done, { force: true })
251
+ delete info.env.P444_KILL_AT
252
+ for (const [key, value] of Object.entries(info.env)) await tmux('set-environment', '-t', info.session, key, String(value))
253
+ const script = join(info.root, 'launch.sh')
254
+ writeFileSync(script, readFileSync(script, 'utf8').replace(/^export P444_KILL_AT=.*;$/m, 'unset P444_KILL_AT;'))
255
+ const before = events(info).filter(e => e.type === 'session_start').length
256
+ const source = `source ${sh(join(info.skill, 'scripts/lib/common.sh'))}; source ${sh(join(info.skill, 'scripts/lib/cmd-config.sh'))}; team_load_config; TEAM_REMINDER_ONLY_RECOVERY=1 team_pm_start`
257
+ const result = await runSync('bash', ['-c', source], { cwd: info.root,
258
+ env: { ...info.env, TMUX: `${socket},${info.serverPid},0`, TMUX_PANE: info.pane }, encoding: 'utf8' })
259
+ writeFileSync(join(info.dir, `restart-${Date.now()}.txt`), (result.stdout ?? '') + (result.stderr ?? ''))
260
+ assert.equal(result.status, 0, `prompt-free restart after death: ${result.stdout}${result.stderr}`)
261
+ await until(() => events(info).filter(e => e.type === 'session_start').length > before && !existsSync(info.done),
262
+ `${info.name} restart after death`)
263
+ }
264
+ async function restartForeign(info) {
265
+ await hardStop(info)
266
+ rmSync(info.done, { force: true })
267
+ const before = events(info).filter(e => e.type === 'session_start').length
268
+ const oldSession = events(info).filter(e => e.type === 'session_start').at(-1).sessionId
269
+ const launch = readFileSync(join(info.dir, 'launch.txt'), 'utf8').trim()
270
+ .replace(' -c --offline', ' --offline').replace(/ @\S*pm-prompt\.md\s*$/, '')
271
+ const script = join(info.root, 'launch-foreign.sh')
272
+ const assignments = Object.entries(info.env).map(([key, value]) => `export ${key}=${sh(value)};`).join('\n')
273
+ writeFileSync(script, `#!/usr/bin/env bash\n${assignments}\nunset TEAM_ROOT TEAM_MAIN_ROOT TEAM_CONFIG_FILE TEAM_STATE_DIR\nbash -c ${sh(launch)} 2>${sh(join(info.dir, 'launch-stderr.txt'))}\nrc=$?; printf '%s\\n' "$rc" >${sh(info.done)}\nsleep 600\n`)
274
+ // The old Pi has exited. Do not let its receipt stand in for a replacement still starting.
275
+ rmSync(info.spawnReceipt, { force: true })
276
+ await tmux('respawn-pane', '-k', '-t', info.pane, `bash ${sh(script)}`)
277
+ await until(() => events(info).filter(e => e.type === 'session_start').length > before &&
278
+ events(info).filter(e => e.type === 'session_start').at(-1).sessionId !== oldSession, 'actual foreign process/session')
279
+ }
280
+ async function addReal(info, message, key, label = 'add-adversarial') {
281
+ const args = ['remind', 'add', '--after', '1s', '--message', message]
282
+ if (key) args.push('--key', key)
283
+ const result = await team(info, args, label)
284
+ assert.equal(result.status, 0, `${label}: ${result.stdout}${result.stderr}`)
285
+ }
286
+ function lastBatch(info) { return snapshot(info.state).batches.at(-1) }
287
+ function replayPayload(info, name = 'replay') {
288
+ const event = events(info).find(e => e.type === 'delay_enter' && e.message?.customType === 'team-reminder')
289
+ assert(event?.message?.content && event.message.details?.members, 'a real earlier-handler event supplied the replay payload')
290
+ const file = join(info.dir, `${name}.json`)
291
+ writeFileSync(file, JSON.stringify(event.message))
292
+ return file
293
+ }
294
+ async function replay(info, file, label) {
295
+ const sends = events(info).filter(e => e.type === 'fixture_send').length
296
+ await control(info, `send ${file}`)
297
+ await until(() => events(info).filter(e => e.type === 'fixture_send').length > sends, `${label} actual Pi send`)
298
+ }
299
+ async function test(name, body) {
300
+ try { await body(); await stopPoint(); console.log(`PASS real Pi ${name}`); passed++ }
301
+ catch (e) { await stopPoint(); failed++; console.error(`FAIL real Pi ${name}: ${e.stack}`) }
302
+ }
303
+ const add = (after, message, key) => ({ action: 'add', after, message, ...(key ? { key } : {}) })
304
+ const final = text => ({ text })
305
+ const large = `${'x'.repeat(64 * 1024)}\n`
306
+ const hasExact = (value, target) => value === target || (Array.isArray(value) ? value.some(item => hasExact(item, target))
307
+ : value && typeof value === 'object' ? Object.values(value).some(item => hasExact(item, target)) : false)
308
+ const mismatchGeneratedSession = config => {
309
+ const source = readFileSync(config, 'utf8')
310
+ const changed = source.replace(/^TEAM_SESSION=.*$/m, "TEAM_SESSION='p442-not-the-directed-session'")
311
+ assert.notEqual(changed, source, 'change only the generated TEAM_SESSION line')
312
+ writeFileSync(config, changed)
313
+ }
314
+ async function assertConfigMismatch(info) {
315
+ const evidence = join(info.state, 'remind-tool/current.json')
316
+ assert(existsSync(evidence), 'mismatched config leaves visible error evidence')
317
+ const record = json(evidence)
318
+ assert.equal(record.status, 'error', 'mismatched config records status=error')
319
+ assert.equal(record.exposure, 'hidden', 'mismatched config never exposes the tool')
320
+ assert.match(record.reason, /PM config TEAM_SESSION does not match the directed launch/, 'error evidence names the mismatched key')
321
+ const started = events(info).filter(e => e.type === 'session_start').at(-1)
322
+ assert.equal(started.reminderTools[0]?.exposure, 'hidden', 'real Pi registers only the hidden tool')
323
+ assert(!started.activeTools.includes('team_remind'), 'real Pi active tools exclude team_remind')
324
+ assert.match(await doctor(info), /PM 提醒工具\s+.*error PM config TEAM_SESSION does not match the directed launch/,
325
+ 'doctor reports the configuration error instead of unknown or ready')
326
+ assert(!existsSync(join(info.state, 'reminders/state.json')), 'rejected config touches no Reminder state')
327
+ }
328
+
329
+ try {
330
+ if (selection.includes('pm')) await test('PM add/list/show/cancel, retry, observed same-key renewal and no-key IDs', async () => {
331
+ let firstId = '', firstDue = ''
332
+ const info = await start('pm', async ({ n, res, plan }) => {
333
+ const ids = () => snapshot(plan.state).reminders.map(record => record.id)
334
+ if (n === 0) return sse(res, { name: 'pm', tool: { n, input: add('1s', 'same body\n', 'cycle') } })
335
+ if (n === 1) return sse(res, { name: 'pm', tool: { n, input: add('1s', 'same body\n', 'cycle') } })
336
+ if (n === 2) return sse(res, { name: 'pm', ...final('active retry recorded') })
337
+ if (n === 3) return sse(res, { name: 'pm', tool: { n, input: add('1s', 'same body\n', 'cycle') } })
338
+ if (n === 4) return sse(res, { name: 'pm', tool: { n, input: add('1h', 'identical no key') } })
339
+ if (n === 5) return sse(res, { name: 'pm', tool: { n, input: add('1h', 'identical no key') } })
340
+ if (n === 6) return sse(res, { name: 'pm', tool: { n, input: { action: 'show', id: ids()[1] } } })
341
+ if (n === 7) return sse(res, { name: 'pm', tool: { n, input: { action: 'cancel', id: ids()[1] } } })
342
+ if (n === 8) return sse(res, { name: 'pm', tool: { n, input: { action: 'cancel', id: ids()[2] } } })
343
+ if (n === 9) return sse(res, { name: 'pm', tool: { n, input: { action: 'cancel', id: ids()[3] } } })
344
+ return sse(res, { name: 'pm', ...final('PM reminder tool sequence complete') })
345
+ }, { deferFirstResponse: true })
346
+ const generated = readFileSync(info.config, 'utf8')
347
+ assert.match(generated, /^TEAM_SESSION=.*\s+# tmux session name/m, 'fixture keeps the generated TEAM_SESSION trailing comment')
348
+ assert.match(generated, /^TEAM_PM_WINDOW=.*\s+# window running the PM/m, 'fixture keeps the generated TEAM_PM_WINDOW trailing comment')
349
+ try {
350
+ await until(() => requests(info).length >= 3 && events(info).some(e => e.type === 'agent_settled'), 'initial add and retry settle')
351
+ let snap = snapshot(info.state)
352
+ assert.equal(snap.reminders.length, 1, 'active retry does not allocate another reminder')
353
+ firstId = snap.reminders[0].id; firstDue = snap.reminders[0].dueAt
354
+ assert.equal(snap.reminders[0].source, 'pm-tool')
355
+ assert.equal(snap.reminders[0].message, 'same body\n')
356
+ const toolEnds = events(info).filter(e => e.type === 'tool_end')
357
+ assert(toolEnds.length >= 2 && toolEnds.every(e => !e.isError), 'real PM tool calls succeed')
358
+ assert(events(info).some(e => e.type === 'before_agent_start' && e.activeTools.includes('team_remind') && e.reminderTools[0]?.exposure === 'direct'), 'PM tool is direct and active')
359
+ await until(() => events(info).some(e => e.type === 'custom_start' && e.customType === 'team-reminder') && snapshot(info.state).reminders[0].phase === 'observed', 'first real Reminder wake observed')
360
+ await until(() => requests(info).length >= 11 && snapshot(info.state).reminders.length === 4, 'post-wake same-key and no-key sequence')
361
+ snap = snapshot(info.state)
362
+ assert.equal(snap.reminders[0].id, firstId); assert.equal(snap.reminders[0].dueAt, firstDue)
363
+ assert.equal(snap.reminders[0].phase, 'observed')
364
+ assert.equal(snap.reminders[1].seq, 2); assert.notEqual(snap.reminders[1].id, firstId)
365
+ assert.equal(snap.reminders[1].key, 'cycle'); assert.equal(snap.reminders[1].phase, 'cancelled')
366
+ assert.equal(snap.reminders[2].message, 'identical no key'); assert.equal(snap.reminders[3].message, 'identical no key')
367
+ assert.notEqual(snap.reminders[2].id, snap.reminders[3].id)
368
+ assert(snap.reminders.every(record => record.source === 'pm-tool'))
369
+ const output = await doctor(info); assert.match(output, /PM 提醒工具\s+.*ready extension reported registered\/active/)
370
+ const capability = json(join(info.state, 'remind-tool/current.json'))
371
+ assert(capability.launchNonce && capability.sessionId && capability.starttime && capability.extensionVersion)
372
+ writeFileSync(join(info.dir, 'receipt.json'), JSON.stringify({ firstId, firstDue, final: snap, capability }, null, 2))
373
+ } finally { await stop(info) }
374
+ assert(!existsSync(join(info.state, 'remind-tool/current.json')), 'shutdown removes only its own capability evidence')
375
+ assert.match(await doctor(info), /PM 提醒工具\s+.*not-running/)
376
+ })
377
+
378
+ if (selection.includes('large')) await test('64 KiB plus final newline through real PM tool add/show/list/cancel', async () => {
379
+ const info = await start('large', async ({ n, res, plan }) => {
380
+ if (n === 0) return sse(res, { name: 'large', tool: { n, input: add('1h', large) } })
381
+ if (n === 1) return sse(res, { name: 'large', tool: { n, input: { action: 'show', id: snapshot(plan.state).reminders[0].id } } })
382
+ if (n === 2) return sse(res, { name: 'large', tool: { n, input: { action: 'list', all: true } } })
383
+ if (n === 3) return sse(res, { name: 'large', tool: { n, input: { action: 'cancel', id: snapshot(plan.state).reminders[0].id } } })
384
+ return sse(res, { name: 'large', ...final('large complete') })
385
+ }, { deferFirstResponse: true })
386
+ // The server closure starts after info is assigned; its first response is gated by session_start.
387
+ try {
388
+ await until(() => requests(info).length >= 5 && events(info).some(e => e.type === 'agent_settled'), 'large add/show/list/cancel')
389
+ const snap = snapshot(info.state)
390
+ assert.equal(snap.reminders[0].message, large)
391
+ assert.equal(Buffer.byteLength(snap.reminders[0].message, 'utf8'), 65537)
392
+ assert.equal(snap.reminders[0].phase, 'cancelled')
393
+ assert(requests(info).some(request => (request.messages ?? []).some(message => {
394
+ if (message.role !== 'tool' || typeof message.content !== 'string') return false
395
+ try { return hasExact(JSON.parse(message.content), large) } catch { return false }
396
+ })), 'large full text is returned to the controlled provider, not truncated')
397
+ } finally { await stop(info) }
398
+ })
399
+
400
+ if (selection.includes('identity')) {
401
+ for (const invalid of ['ordinary', 'worker', 'forged']) await test(`${invalid}: globally loaded copy stays hidden with zero Reminder state`, async () => {
402
+ const info = await start(invalid, async ({ n, res }) => sse(res, { name: invalid, ...final(`invalid ${invalid}`) }), { invalid })
403
+ try {
404
+ await until(() => events(info).some(e => e.type === 'agent_settled'), `${invalid} response`)
405
+ assert(events(info).every(e => !e.activeTools?.includes('team_remind')))
406
+ assert(requests(info).every(request => !(request.tools ?? []).some(tool => tool.function?.name === 'team_remind')))
407
+ assert(!existsSync(join(info.state, 'reminders/state.json')))
408
+ } finally { await stop(info) }
409
+ })
410
+ await test('reload into an invalid pane hides all actions without changing Reminder state', async () => {
411
+ const info = await start('reload', async ({ n, res }) => {
412
+ if (n === 0) return sse(res, { name: 'reload', tool: { n, input: add('1h', 'before invalid reload') } })
413
+ return sse(res, { name: 'reload', ...final(`reload response ${n}`) })
414
+ }, { deferFirstResponse: true })
415
+ try {
416
+ await until(() => snapshot(info.state).reminders.length === 1 && events(info).some(e => e.type === 'agent_settled'), 'pre-reload add')
417
+ const before = readFileSync(join(info.state, 'reminders/state.json'), 'utf8')
418
+ await tmux('rename-window', '-t', info.pane, 'not-pm')
419
+ await tmux('send-keys', '-t', info.pane, '-l', '/p442-control reload'); await tmux('send-keys', '-t', info.pane, 'Enter')
420
+ await until(() => events(info).filter(e => e.type === 'session_start').length >= 2 && requests(info).length >= 2, 'invalid reload response')
421
+ const current = events(info).filter(e => e.type === 'session_start').at(-1)
422
+ assert.equal(current.reminderTools[0]?.exposure, 'hidden'); assert.equal(current.activeTools.length, 0)
423
+ assert.equal(readFileSync(join(info.state, 'reminders/state.json'), 'utf8'), before)
424
+ assert.match(await doctor(info), /PM 提醒工具\s+.*not-running/) // configured PM pane is gone; no ready claim follows the stale evidence
425
+ } finally { await stop(info) }
426
+ })
427
+ }
428
+
429
+ if (selection.includes('recovery')) await test('stopped PM resumes without a generic prompt; Reminder arrives before ordinary backlog', async () => {
430
+ const info = await start('recovery', async ({ n, res }) => sse(res, { name: 'recovery', ...final(`controlled response ${n}`) }), { deferFirstResponse: true })
431
+ try {
432
+ await until(() => requests(info).length === 1 && events(info).some(e => e.type === 'agent_settled'), 'seed PM response')
433
+ const seedSession = events(info).find(e => e.type === 'session_start').sessionId
434
+ await stopPi(info)
435
+ const before = requests(info).length
436
+ const promptBefore = readFileSync(join(info.state, 'pm-prompt.md'), 'utf8')
437
+ const wrapper = join(info.dir, 'pi-argv-wrapper.sh'), argvBytes = join(info.dir, 'argv.bin')
438
+ writeFileSync(wrapper, `#!/usr/bin/env bash\nprintf '%s\\0' "$@" >${sh(argvBytes)}\nexec ${sh(pi)} "$@"\n`)
439
+ await command('chmod', ['+x', wrapper])
440
+ writeFileSync(info.config, readFileSync(info.config, 'utf8').replace(/^TEAM_PI_BIN=.*$/m, `TEAM_PI_BIN=${sh(wrapper)}`))
441
+ // team_load_config gives environment overrides precedence; recover() also publishes info.env to tmux.
442
+ info.env.TEAM_PI_BIN = wrapper
443
+ let result = await team(info, ['notify', 'pm', 'P443_ORDINARY_BACKLOG'], 'ordinary-backlog')
444
+ assert.equal(result.status, 0, 'ordinary backlog is pending before recovery')
445
+ result = await team(info, ['standby', 'on', '--reason', 'P443 stopped recovery'], 'standby-on')
446
+ assert.equal(result.status, 0, 'Standby on succeeds')
447
+ result = await team(info, ['remind', 'add', '--after', '1s', '--message', 'P443_RECOVERY_ONLY', '--key', 'recovery'], 'add-recovery')
448
+ assert.equal(result.status, 0, 'recovery Reminder is created')
449
+ await delay(1200)
450
+ result = await recover(info)
451
+ assert.equal(result.status, 0, `prompt-free recovery: ${result.stdout}${result.stderr}`)
452
+ assert.match(result.stdout, /result=started/)
453
+ await delay(500)
454
+ const pane = await runSync('tmux', ['-S', socket, '-f', '/dev/null', 'capture-pane', '-p', '-t', `${info.session}:pm`, '-S', '-100'], { env: base, encoding: 'utf8' })
455
+ writeFileSync(join(info.dir, 'recovery-pane.txt'), (pane.stdout ?? '') + (pane.stderr ?? ''))
456
+ const pid = readFileSync(join(info.state, 'pm.pid'), 'utf8').trim()
457
+ const argv = readFileSync(argvBytes).toString('utf8').split('\0').filter(Boolean)
458
+ writeFileSync(join(info.dir, 'recovery-argv.json'), JSON.stringify(argv, null, 2))
459
+ assert(!argv.some(arg => arg.startsWith('@') || arg.includes('pm-prompt')), 'actual PM argv has no generic or replacement initial prompt')
460
+ assert((argv.includes('-c') || argv.includes('--continue')) && argv.some(arg => arg.endsWith('team-inbox-watch.ts')) && argv.some(arg => arg.endsWith('team-remind.ts')))
461
+ assert.equal(readFileSync(join(info.state, 'pm-prompt.md'), 'utf8'), promptBefore, 'the previous prompt file is untouched')
462
+ await until(() => snapshot(info.state).reminders[0]?.phase === 'observed' && requests(info).length === before + 1 &&
463
+ events(info).filter(e => e.type === 'agent_settled').length >= 2, 'Reminder observation and one controlled response')
464
+ assert.equal(snapshot(info.state).standby.on, false, 'only the correlated wake exits Standby')
465
+ const newRequests = requests(info).slice(before)
466
+ assert.equal(newRequests.length, 1, 'there is no generic startup model turn before the Reminder')
467
+ assert(newRequests.every(request => JSON.stringify(request).includes('P443_RECOVERY_ONLY')))
468
+ assert(newRequests.every(request => !JSON.stringify(request).includes('P443_ORDINARY_BACKLOG')), 'ordinary backlog did not run first')
469
+ assert(events(info).filter(e => e.type === 'custom_start').every(e => e.customType === 'team-reminder'), 'no ordinary inbox wake preceded the Reminder')
470
+ const recoveredSession = events(info).filter(e => e.type === 'session_start').at(-1).sessionId
471
+ assert.equal(recoveredSession, seedSession, 'usual resume arguments preserve the PM session')
472
+
473
+ // A second Reminder holds the controlled response open. Recovery during that busy turn must not respawn.
474
+ const plan = plans.get('recovery')
475
+ plan.gateN = plan.requests
476
+ let releaseBusy
477
+ plan.gate = new Promise(resolve => { releaseBusy = resolve; info.releaseBusy = resolve })
478
+ result = await team(info, ['remind', 'add', '--after', '1s', '--message', 'P443_BUSY_FOLLOW_UP'], 'add-busy')
479
+ assert.equal(result.status, 0)
480
+ await delay(1200)
481
+ result = await recover(info)
482
+ assert.equal(result.status, 0)
483
+ assert.match(result.stdout, /result=running/)
484
+ await until(() => requests(info).length === plan.gateN + 1, 'busy controlled response is pending')
485
+ const restartsBeforeBusyCheck = readFileSync(join(info.state, 'pm-restarts.log'), 'utf8')
486
+ result = await recover(info)
487
+ assert.equal(result.status, 0)
488
+ assert.doesNotMatch(result.stdout, /result=started/, 'an in-flight Reminder never causes another PM start')
489
+ assert.equal(readFileSync(join(info.state, 'pm-restarts.log'), 'utf8'), restartsBeforeBusyCheck)
490
+ assert.equal(readFileSync(join(info.state, 'pm.pid'), 'utf8').trim(), pid, 'running/busy recovery keeps the same PM process')
491
+ releaseBusy()
492
+ await until(() => snapshot(info.state).reminders[1]?.phase === 'observed', 'busy follow-up observation')
493
+ writeFileSync(join(info.dir, 'recovery-receipt.json'), JSON.stringify({ pid, argv, seedSession, recoveredSession,
494
+ genericTurns: 0, ordinaryBacklogTurns: 0, final: snapshot(info.state) }, null, 2))
495
+ } finally { info.releaseBusy?.(); await stop(info) }
496
+ })
497
+
498
+ if (selection.includes('adversarial') || selection.some(name => name.startsWith('adversarial-'))) {
499
+ const adversarialCase = name => selection.includes('adversarial') || selection.includes(`adversarial-${name}`)
500
+ if (adversarialCase('batch')) await test('A+B exact event, duplicate/member/foreign-session replay preserve a fresh generation', async () => {
501
+ const info = await start('adversarial-batch', async ({ n, res }) => sse(res, { name: 'adversarial-batch', ...final(`batch response ${n}`) }),
502
+ { deferFirstResponse: true, earlierHandler: true, pauseTicker: true, env: { P444_DELAY: '1' } })
503
+ try {
504
+ await until(() => requests(info).length === 1 && events(info).some(e => e.type === 'agent_settled'), 'batch initial response')
505
+ assert.equal((await team(info, ['standby', 'on', '--reason', 'P444 G1'], 'batch-g1')).status, 0)
506
+ await addReal(info, 'P444_A first line\nsecond line\n', 'batch-a', 'add-a')
507
+ await addReal(info, 'P444_B full text', 'batch-b', 'add-b')
508
+ await delay(1100) // Both one-second Reminders are actually due before admission is allowed to run.
509
+ info.armTicker()
510
+ await until(() => lastBatch(info)?.phase === 'intent' && events(info).some(e => e.type === 'delay_enter'), 'A+B real event paused in earlier handler')
511
+ const frozen = lastBatch(info)
512
+ assert.equal(frozen.generation, 1); assert.equal(frozen.members.length, 2)
513
+ const delayed = events(info).find(e => e.type === 'delay_enter')
514
+ assert(delayed.message.content.includes('P444_A first line\nsecond line\n'))
515
+ assert(delayed.message.content.includes('P444_B full text'))
516
+ assert.deepEqual(delayed.message.details.members, frozen.members)
517
+ const original = replayPayload(info, 'original-batch')
518
+ writeFileSync(join(info.dir, 'release-event'), 'release')
519
+ await until(() => lastBatch(info)?.phase === 'observed', 'A+B observed')
520
+ let snap = snapshot(info.state)
521
+ assert.equal(snap.standby.on, false); assert.equal(lastBatch(info).outcome.standby, 'auto-off')
522
+ assert.equal(lastBatch(info).rightSpentBy, 'wake')
523
+ const audits = snap.audit.filter(a => a.op === 'remind-observed')
524
+ assert.equal(audits.length, 1); assert.deepEqual(audits[0].ids, frozen.members)
525
+ assert.deepEqual(audits[0].sources, ['cli', 'cli'])
526
+ await until(() => requests(info).filter(r => JSON.stringify(r).includes('P444_A') && JSON.stringify(r).includes('P444_B')).length === 1,
527
+ 'the frozen A+B batch caused one controlled model request')
528
+ assert.equal(requests(info).filter(r => JSON.stringify(r).includes('P444_A') && JSON.stringify(r).includes('P444_B')).length, 1)
529
+
530
+ assert.equal((await team(info, ['standby', 'on', '--reason', 'P444 fresh G2'], 'batch-g2')).status, 0)
531
+ const malformed = join(info.dir, 'wrong-members.json')
532
+ writeFileSync(malformed, JSON.stringify({ ...delayed.message, details: { ...delayed.message.details, members: [] } }))
533
+ await replay(info, malformed, 'wrong members')
534
+ await until(() => readFileSync(join(info.state, 'inbox-watch.log'), 'utf8').includes('member-mismatch'), 'member mismatch is visible')
535
+ assert.equal(snapshot(info.state).standby.generation, 2); assert.equal(snapshot(info.state).standby.on, true)
536
+ await replay(info, original, 'duplicate')
537
+ await until(() => readFileSync(join(info.state, 'inbox-watch.log'), 'utf8').includes('reminder duplicate event'), 'duplicate handled')
538
+ snap = snapshot(info.state)
539
+ assert.equal(snap.standby.on, true); assert.equal(snap.standby.generation, 2)
540
+ assert.equal(snap.audit.filter(a => a.op === 'remind-observed').length, 1)
541
+
542
+ await restartForeign(info)
543
+ const foreignSession = events(info).filter(e => e.type === 'session_start').at(-1).sessionId
544
+ assert.notEqual(foreignSession, frozen.target.session)
545
+ await replay(info, original, 'foreign session')
546
+ await until(() => readFileSync(join(info.state, 'inbox-watch.log'), 'utf8').includes('session-mismatch'), 'foreign session rejected')
547
+ snap = snapshot(info.state)
548
+ assert.equal(snap.standby.on, true); assert.equal(snap.standby.generation, 2)
549
+ assert.equal(snap.audit.filter(a => a.op === 'remind-observed').length, 1)
550
+ writeFileSync(join(info.dir, 'receipt.json'), JSON.stringify({ frozen, foreignSession, final: snap,
551
+ sends: events(info).filter(e => e.type === 'fixture_send') }, null, 2))
552
+ } finally { writeFileSync(join(info.dir, 'release-event'), 'release'); await stop(info) }
553
+ })
554
+
555
+ if (adversarialCase('event-first')) await test('event before manual off/on G2 stays ambiguous and Standby commands do not wait for Pi', async () => {
556
+ const info = await start('adversarial-event-first', async ({ n, res }) => sse(res, { name: 'adversarial-event-first', ...final(`event first ${n}`) }),
557
+ { deferFirstResponse: true, earlierHandler: true, env: { P444_DELAY: '1' } })
558
+ try {
559
+ await until(() => events(info).some(e => e.type === 'agent_settled'), 'event-first initial response')
560
+ await team(info, ['standby', 'on', '--reason', 'G1'], 'event-first-g1')
561
+ await addReal(info, 'P444_EVENT_BEFORE_G2', 'event-first')
562
+ await until(() => events(info).some(e => e.type === 'delay_enter') && lastBatch(info)?.phase === 'intent', 'real event arrived before G2')
563
+ assert.equal((await team(info, ['standby', 'off'], 'event-first-off')).status, 0)
564
+ assert.equal((await team(info, ['standby', 'on', '--reason', 'G2'], 'event-first-g2')).status, 0)
565
+ assert.equal(snapshot(info.state).standby.generation, 2)
566
+ assert.equal(lastBatch(info).phase, 'intent', 'paused earlier handler has not committed observation')
567
+ assert(!events(info).some(e => e.type === 'delay_exit'), 'both Standby commands completed while Pi handler was paused')
568
+ writeFileSync(join(info.dir, 'release-event'), 'release')
569
+ await until(() => lastBatch(info)?.phase === 'observed', 'event-first observation')
570
+ assert.equal(lastBatch(info).outcome.standby, 'generation-ambiguous')
571
+ assert.equal(snapshot(info.state).standby.on, true); assert.equal(snapshot(info.state).standby.generation, 2)
572
+ writeFileSync(join(info.dir, 'receipt.json'), JSON.stringify({ final: snapshot(info.state),
573
+ timeline: events(info).filter(e => ['delay_enter', 'delay_exit', 'custom_start'].includes(e.type)) }, null, 2))
574
+ } finally { writeFileSync(join(info.dir, 'release-event'), 'release'); await stop(info) }
575
+ })
576
+
577
+ if (adversarialCase('event-after')) await test('busy follow-up emitted after manual G2 keeps the unprovable order boundary', async () => {
578
+ const info = await start('adversarial-event-after', async ({ n, res }) => sse(res, { name: 'adversarial-event-after', ...final(`event after ${n}`) }),
579
+ { deferFirstResponse: true })
580
+ try {
581
+ await until(() => events(info).some(e => e.type === 'agent_settled'), 'event-after initial response')
582
+ const plan = plans.get('adversarial-event-after')
583
+ plan.gateN = plan.requests
584
+ let releaseBusy
585
+ plan.gate = new Promise(resolve => { releaseBusy = resolve; info.releaseBusy = resolve })
586
+ await control(info, 'busy')
587
+ await until(() => requests(info).length === plan.gateN + 1, 'unrelated controlled turn is busy')
588
+ await team(info, ['standby', 'on', '--reason', 'G1'], 'event-after-g1')
589
+ await addReal(info, 'P444_EVENT_AFTER_G2', 'event-after')
590
+ await until(() => lastBatch(info)?.phase === 'intent' && readFileSync(join(info.state, 'inbox-watch.log'), 'utf8').includes('intent-sent'),
591
+ 'busy follow-up call returned with durable intent')
592
+ assert(!events(info).some(e => e.type === 'custom_start' && e.customType === 'team-reminder'), 'no message event before the busy turn ends')
593
+ assert.equal(lastBatch(info).phase, 'intent', 'sendMessage returning is not a wake')
594
+ assert.equal((await team(info, ['standby', 'off'], 'event-after-off')).status, 0)
595
+ assert.equal((await team(info, ['standby', 'on', '--reason', 'G2'], 'event-after-g2')).status, 0)
596
+ releaseBusy()
597
+ await until(() => lastBatch(info)?.phase === 'observed', 'busy follow-up observed after G2')
598
+ await until(() => events(info).some(e => e.type === 'custom_start' && e.customType === 'team-reminder'), 'busy follow-up event recorded after G2')
599
+ assert.equal(lastBatch(info).outcome.standby, 'generation-ambiguous')
600
+ assert.equal(snapshot(info.state).standby.on, true); assert.equal(snapshot(info.state).standby.generation, 2)
601
+ writeFileSync(join(info.dir, 'receipt.json'), JSON.stringify({ final: snapshot(info.state),
602
+ reminderRequests: requests(info).filter(r => JSON.stringify(r).includes('P444_EVENT_AFTER_G2')).length,
603
+ timeline: events(info).filter(e => ['custom_start', 'fixture_send', 'agent_settled'].includes(e.type)) }, null, 2))
604
+ } finally { info.releaseBusy?.(); await stop(info) }
605
+ })
606
+
607
+ if (adversarialCase('generations')) await test('G2 committed before intent exits once; manual off before the event is already-off', async () => {
608
+ const bound = await start('adversarial-g2-bound', async ({ n, res }) => sse(res, { name: 'adversarial-g2-bound', ...final(`G2 bound ${n}`) }), { deferFirstResponse: true })
609
+ try {
610
+ await until(() => events(bound).some(e => e.type === 'agent_settled'), 'G2-bound initial response')
611
+ await team(bound, ['standby', 'on', '--reason', 'G1'], 'bound-g1')
612
+ await team(bound, ['standby', 'off'], 'bound-off1')
613
+ await team(bound, ['standby', 'on', '--reason', 'G2'], 'bound-g2')
614
+ await addReal(bound, 'P444_G2_BOUND', 'g2-bound')
615
+ await until(() => lastBatch(bound)?.phase === 'observed', 'G2-bound observation')
616
+ assert.equal(lastBatch(bound).generation, 2); assert.equal(lastBatch(bound).outcome.standby, 'auto-off')
617
+ assert.equal(snapshot(bound.state).standby.on, false)
618
+ writeFileSync(join(bound.dir, 'receipt.json'), JSON.stringify({ final: snapshot(bound.state) }, null, 2))
619
+ } finally { await stop(bound) }
620
+
621
+ const manual = await start('adversarial-manual-off', async ({ n, res }) => sse(res, { name: 'adversarial-manual-off', ...final(`manual off ${n}`) }),
622
+ { deferFirstResponse: true, earlierHandler: true, env: { P444_DELAY: '1' } })
623
+ try {
624
+ await until(() => events(manual).some(e => e.type === 'agent_settled'), 'manual-off initial response')
625
+ await team(manual, ['standby', 'on', '--reason', 'G1'], 'manual-g1')
626
+ await addReal(manual, 'P444_MANUAL_OFF', 'manual-off')
627
+ await until(() => events(manual).some(e => e.type === 'delay_enter'), 'manual-off real event paused')
628
+ assert.equal((await team(manual, ['standby', 'off'], 'manual-off-command')).status, 0)
629
+ writeFileSync(join(manual.dir, 'release-event'), 'release')
630
+ await until(() => lastBatch(manual)?.phase === 'observed', 'manual-off observation')
631
+ assert.equal(lastBatch(manual).outcome.standby, 'already-off')
632
+ assert.equal(snapshot(manual.state).standby.on, false)
633
+ writeFileSync(join(manual.dir, 'receipt.json'), JSON.stringify({ final: snapshot(manual.state) }, null, 2))
634
+ } finally { writeFileSync(join(manual.dir, 'release-event'), 'release'); await stop(manual) }
635
+ })
636
+
637
+ if (adversarialCase('death-event')) await test('death after a real event becomes unknown without resend; late replay cannot clear fresh G2', async () => {
638
+ const info = await start('adversarial-death-event', async ({ n, res }) => sse(res, { name: 'adversarial-death-event', ...final(`death event ${n}`) }),
639
+ { deferFirstResponse: true, earlierHandler: true, env: { P444_KILL_AT: 'event' } })
640
+ try {
641
+ await until(() => events(info).some(e => e.type === 'agent_settled'), 'death-event initial response')
642
+ await team(info, ['standby', 'on', '--reason', 'G1'], 'death-event-g1')
643
+ await addReal(info, 'P444_DEATH_AFTER_EVENT', 'death-event')
644
+ await until(() => existsSync(info.done) && events(info).some(e => e.type === 'delay_enter'), 'death inside earlier real event handler')
645
+ const original = replayPayload(info, 'late-original-event')
646
+ assert.equal(lastBatch(info).phase, 'intent'); assert.equal(snapshot(info.state).standby.on, true)
647
+ await restartDirect(info)
648
+ await delay(500)
649
+ const ledger = () => readFileSync(join(info.state, 'inbox-watch.log'), 'utf8')
650
+ assert.equal((ledger().match(/reminder intent-sent/g) ?? []).length, 1, 'restart did not resend the old intent')
651
+ await until(() => lastBatch(info)?.phase === 'unknown', 'actual sixty-second deadline marks the old intent unknown')
652
+ assert.equal(snapshot(info.state).standby.on, true)
653
+ await team(info, ['standby', 'off'], 'death-event-off1')
654
+ await team(info, ['standby', 'on', '--reason', 'fresh G2 after restart'], 'death-event-g2')
655
+ await replay(info, original, 'late original event')
656
+ await until(() => lastBatch(info)?.phase === 'observed', 'late real event observes unknown batch')
657
+ assert.equal(lastBatch(info).outcome.standby, 'generation-ambiguous')
658
+ assert.equal(snapshot(info.state).standby.on, true); assert.equal(snapshot(info.state).standby.generation, 2)
659
+ assert.equal(snapshot(info.state).audit.filter(a => a.op === 'remind-observed').length, 1)
660
+ assert.equal((ledger().match(/reminder intent-sent/g) ?? []).length, 1, 'late observation caused no automatic resend')
661
+ writeFileSync(join(info.dir, 'receipt.json'), JSON.stringify({ final: snapshot(info.state),
662
+ automaticSendCount: (ledger().match(/reminder intent-sent/g) ?? []).length,
663
+ replaySends: events(info).filter(e => e.type === 'fixture_send'), requestCount: requests(info).length,
664
+ timeline: events(info).filter(e => ['session_start', 'delay_enter', 'custom_start', 'fixture_send'].includes(e.type)) }, null, 2))
665
+ } finally { await stop(info) }
666
+ })
667
+ }
668
+
669
+ if (selection.includes('death')) {
670
+ for (const point of ['before-call', 'after-call']) await test(`process death ${point} preserves intent and never blind-resends`, async () => {
671
+ const name = `adversarial-death-${point}`
672
+ const info = await start(name, async ({ n, res }) => sse(res, { name, ...final(`${point} ${n}`) }), {
673
+ skillCopy: true, deferFirstResponse: true, env: { P444_KILL_AT: point },
674
+ mutate: copied => {
675
+ const path = join(copied, 'extension/team-inbox-watch.ts'), source = readFileSync(path, 'utf8')
676
+ const before = ' pi.sendMessage({\n'
677
+ const after = " }, { triggerTurn: true, deliverAs: 'followUp' })\n"
678
+ assert.equal(source.split(before).length, 2); assert.equal(source.split(after).length, 2)
679
+ writeFileSync(path, source.replace(before, ` appendFileSync(join(process.env.P442_EVIDENCE, 'pi-calls.log'), 'before-invoke\\n')\n if (process.env.P444_KILL_AT === 'before-call') process.kill(process.pid, 'SIGKILL')\n${before}`)
680
+ .replace(after, `${after} appendFileSync(join(process.env.P442_EVIDENCE, 'pi-calls.log'), 'after-invoke\\n')\n if (process.env.P444_KILL_AT === 'after-call') process.kill(process.pid, 'SIGKILL')\n`))
681
+ },
682
+ })
683
+ try {
684
+ await until(() => events(info).some(e => e.type === 'agent_settled'), `${point} initial response`)
685
+ const plan = plans.get(name)
686
+ if (point === 'after-call') {
687
+ plan.gateN = plan.requests
688
+ plan.gate = new Promise(resolve => { info.releaseBusy = resolve })
689
+ await control(info, 'busy')
690
+ await until(() => requests(info).length === plan.gateN + 1, 'after-call busy turn')
691
+ }
692
+ await team(info, ['standby', 'on', '--reason', point], `${point}-g1`)
693
+ await addReal(info, `P444_DEATH_${point}`, point)
694
+ await until(() => existsSync(info.done), `${point} process death`)
695
+ assert.equal(lastBatch(info).phase, 'intent'); assert.equal(snapshot(info.state).standby.on, true)
696
+ assert(!events(info).some(e => e.type === 'custom_start' && e.customType === 'team-reminder'), 'no observation was manufactured')
697
+ const ledgerBefore = readFileSync(join(info.state, 'inbox-watch.log'), 'utf8')
698
+ assert.equal((ledgerBefore.match(/reminder intent-sent/g) ?? []).length, 0, 'death precedes the post-call ledger append')
699
+ const callsBefore = readFileSync(join(info.dir, 'pi-calls.log'), 'utf8')
700
+ assert.equal((callsBefore.match(/before-invoke/g) ?? []).length, 1)
701
+ assert.equal((callsBefore.match(/after-invoke/g) ?? []).length, point === 'before-call' ? 0 : 1)
702
+ await restartDirect(info)
703
+ await delay(500)
704
+ const ledgerAfter = readFileSync(join(info.state, 'inbox-watch.log'), 'utf8')
705
+ assert.equal((ledgerAfter.match(/reminder intent-sent/g) ?? []).length, 0,
706
+ 'restart did not reach another post-call ledger append')
707
+ const callsAfter = readFileSync(join(info.dir, 'pi-calls.log'), 'utf8')
708
+ assert.equal((callsAfter.match(/before-invoke/g) ?? []).length, 1, 'restart did not issue another Pi call')
709
+ assert.equal((callsAfter.match(/after-invoke/g) ?? []).length, point === 'before-call' ? 0 : 1)
710
+ assert.equal(lastBatch(info).phase, 'intent'); assert.equal(snapshot(info.state).standby.on, true)
711
+ writeFileSync(join(info.dir, 'receipt.json'), JSON.stringify({ point, final: snapshot(info.state),
712
+ calls: callsAfter, automaticPostCallLedgerCount: (ledgerAfter.match(/reminder intent-sent/g) ?? []).length }, null, 2))
713
+ } finally { info.releaseBusy?.(); await stop(info) }
714
+ })
715
+ }
716
+
717
+ if (selection.includes('withdrawal')) {
718
+ for (const action of ['new', 'fork']) await test(`${action}: invalid replacement session immediately loses ready evidence`, async () => {
719
+ const name = `${action}-hide`
720
+ const info = await start(name, async ({ n, res }) => sse(res, { name, ...final(`${action} response ${n}`) }), { deferFirstResponse: true })
721
+ try {
722
+ await until(() => requests(info).length === 1 && events(info).some(e => e.type === 'agent_settled'), `${action} initial response`)
723
+ const added = await team(info, ['remind', 'add', '--after', '1h', '--message', `before ${action}`], `add-before-${action}`)
724
+ assert.equal(added.status, 0)
725
+ const before = readFileSync(join(info.state, 'reminders/state.json'), 'utf8')
726
+ await tmux('rename-window', '-t', info.pane, 'not-pm')
727
+ await tmux('send-keys', '-t', info.pane, '-l', `/p442-control ${action}`); await tmux('send-keys', '-t', info.pane, 'Enter')
728
+ await until(() => events(info).filter(e => e.type === 'session_start').length >= 2, `${action} replacement session`)
729
+ const current = events(info).filter(e => e.type === 'session_start').at(-1)
730
+ assert.equal(current.reminderTools[0]?.exposure, 'hidden')
731
+ assert.equal(current.activeTools.length, 0)
732
+ const evidencePath = join(info.state, 'remind-tool/current.json')
733
+ if (existsSync(evidencePath)) assert.equal(json(evidencePath).status, 'hidden')
734
+ assert(!/PM 提醒工具\s+.*ready/.test(await doctor(info)), 'doctor is not ready in the same replacement, without a 20s wait')
735
+ assert.equal(readFileSync(join(info.state, 'reminders/state.json'), 'utf8'), before)
736
+ } finally { await stop(info) }
737
+ })
738
+ }
739
+
740
+ if (selection.includes('doctor')) {
741
+ await test('running PM with no entry is unknown, not a load failure', async () => {
742
+ const info = await start('noentry', async ({ n, res }) => sse(res, { name: 'noentry', ...final('no entry') }), { invalid: 'no-entry', deferFirstResponse: true })
743
+ try {
744
+ await until(() => events(info).some(e => e.type === 'agent_settled'), 'no-entry response')
745
+ assert.match(await doctor(info), /PM 提醒工具\s+.*unknown evidence:ENOENT/)
746
+ assert(!existsSync(join(info.state, 'reminders/state.json')))
747
+ } finally { await stop(info) }
748
+ })
749
+ await test('generated config mismatch hides the tool and leaves a specific doctor error', async () => {
750
+ const info = await start('config-mismatch', async ({ n, res }) => sse(res, { name: 'config-mismatch', ...final('config mismatch') }), {
751
+ configure: mismatchGeneratedSession, deferFirstResponse: true,
752
+ })
753
+ try {
754
+ await until(() => existsSync(join(info.state, 'remind-tool/current.json')) && events(info).some(e => e.type === 'agent_settled'), 'config mismatch settles')
755
+ await assertConfigMismatch(info)
756
+ } finally { await stop(info) }
757
+ })
758
+ await test('flip: deleting config-error evidence turns the named visibility assertion red', async () => {
759
+ const info = await start('config-error-flip', async ({ n, res }) => sse(res, { name: 'config-error-flip', ...final('config error flip') }), {
760
+ skillCopy: true, configure: mismatchGeneratedSession, deferFirstResponse: true,
761
+ mutate: copied => {
762
+ const path = join(copied, 'extension/team-remind.ts'), source = readFileSync(path, 'utf8')
763
+ const anchor = " publish('error', 'hidden', e?.message ?? String(e))"
764
+ assert.equal(source.split(anchor).length, 2)
765
+ writeFileSync(path, source.replace(anchor, ' // P450 flip: config-error evidence write removed'))
766
+ },
767
+ })
768
+ try {
769
+ await until(() => events(info).some(e => e.type === 'agent_settled'), 'config error flip settles')
770
+ let failure
771
+ try { await assertConfigMismatch(info) } catch (e) { failure = e }
772
+ assert.match(failure?.message ?? '', /mismatched config leaves visible error evidence/,
773
+ 'removing the write must fail the named error-evidence assertion')
774
+ console.log(`EXPECTED RED config-error evidence: ${failure.message.split('\n')[0]}`)
775
+ } finally { await stop(info) }
776
+ })
777
+ await test('explicit bootstrap failure is error while fresh', async () => {
778
+ const info = await start('loaderror', async ({ n, res }) => sse(res, { name: 'loaderror', ...final('load error') }), {
779
+ skillCopy: true, deferFirstResponse: true,
780
+ mutate: copied => {
781
+ const path = join(copied, 'extension/team-remind.ts'), source = readFileSync(path, 'utf8')
782
+ const anchor = "pi.registerTool(definition('direct') as any)"
783
+ assert.equal(source.split(anchor).length, 2)
784
+ writeFileSync(path, source.replace(anchor, "throw new Error('controlled direct registration failure')"))
785
+ },
786
+ })
787
+ try {
788
+ await until(() => existsSync(join(info.state, 'remind-tool/current.json')), 'bootstrap error evidence')
789
+ const record = json(join(info.state, 'remind-tool/current.json'))
790
+ assert.equal(record.status, 'error'); assert.equal(record.exposure, 'hidden')
791
+ assert.match(await doctor(info), /PM 提醒工具\s+.*error controlled direct registration failure/)
792
+ assert(!existsSync(join(info.state, 'reminders/state.json')))
793
+ } finally { await stop(info) }
794
+ })
795
+ }
796
+ } finally {
797
+ server.closeAllConnections(); await new Promise(resolve => server.close(resolve))
798
+ }
799
+ await stopPoint()
800
+ console.log(`remind-tool-real: passed=${passed} failed=${failed} evidence=${evidence}`)
801
+ if (failed) process.exitCode = 1