teamsmith 0.4.6 → 0.4.7

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