teamsmith 0.3.3 → 0.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +8 -8
- package/package.json +2 -6
- package/skills/teamsmith/CHANGELOG.md +77 -0
- package/skills/teamsmith/SKILL.md +83 -163
- package/skills/teamsmith/extension/team-inbox-watch.ts +30 -1
- package/skills/teamsmith/extension/team-notify.ts +162 -21
- package/skills/teamsmith/extension/team-reply.ts +105 -0
- package/skills/teamsmith/references/agent-adapters.md +4 -2
- package/skills/teamsmith/references/config.md +21 -12
- package/skills/teamsmith/references/migration.md +47 -3
- package/skills/teamsmith/references/protocol.md +85 -31
- package/skills/teamsmith/references/reminders.md +131 -0
- package/skills/teamsmith/references/troubleshooting.md +26 -8
- package/skills/teamsmith/references/workflows.md +18 -16
- package/skills/teamsmith/scripts/lib/cmd-agents.sh +290 -68
- package/skills/teamsmith/scripts/lib/cmd-config.sh +1 -1
- package/skills/teamsmith/scripts/lib/cmd-project.sh +193 -21
- package/skills/teamsmith/scripts/lib/cmd-remind.sh +103 -0
- package/skills/teamsmith/scripts/lib/cmd-status.sh +177 -21
- package/skills/teamsmith/scripts/lib/cmd-update.sh +7 -4
- package/skills/teamsmith/scripts/lib/cmd-watch.sh +11 -1
- package/skills/teamsmith/scripts/lib/common.sh +50 -6
- package/skills/teamsmith/scripts/lib/outbox.sh +103 -21
- package/skills/teamsmith/scripts/panel/panel.js +1 -1
- package/skills/teamsmith/scripts/panel/src/strings/en.ts +1 -1
- package/skills/teamsmith/scripts/panel/src/strings/zh.ts +1 -1
- package/skills/teamsmith/scripts/remind-store.mjs +529 -0
- package/skills/teamsmith/scripts/replies.mjs +9 -3
- package/skills/teamsmith/scripts/reply-capture.mjs +596 -0
- package/skills/teamsmith/scripts/state-authority.mjs +500 -0
- package/skills/teamsmith/scripts/strings/commands.tsv +2 -1
- package/skills/teamsmith/scripts/strings/help.en.tsv +16 -2
- package/skills/teamsmith/scripts/strings/help.zh.tsv +16 -2
- package/skills/teamsmith/scripts/team +2 -0
- package/skills/teamsmith/templates/AGENTS.section.md.tmpl +68 -123
- package/skills/teamsmith/templates/PROTOCOL.md.tmpl +48 -55
- package/skills/teamsmith/templates/config.sh.tmpl +2 -1
- package/skills/teamsmith/templates/pm-prompt.md.tmpl +126 -119
- package/skills/teamsmith/tests/bg-ledger-harness.mjs +17 -6
- package/skills/teamsmith/tests/bg-ledger.sh +16 -5
- package/skills/teamsmith/tests/checkout-shape-probe.sh +6 -5
- package/skills/teamsmith/tests/delivery-truth.sh +82 -47
- package/skills/teamsmith/tests/fixtures/delivery-truth-real/README.md +71 -23
- package/skills/teamsmith/tests/fixtures/delivery-truth-real/__pycache__/judge-second.cpython-313.pyc +0 -0
- package/skills/teamsmith/tests/fixtures/delivery-truth-real/judge-dirty-ab.py +143 -0
- package/skills/teamsmith/tests/fixtures/delivery-truth-real/judge-second.py +26 -9
- package/skills/teamsmith/tests/fixtures/delivery-truth-real/run-case.sh +92 -20
- package/skills/teamsmith/tests/fixtures/delivery-truth-real/scenario.sh +47 -3
- package/skills/teamsmith/tests/fixtures/reply-capture-provider.ts +76 -0
- package/skills/teamsmith/tests/flip-p410-order2.sh +205 -0
- package/skills/teamsmith/tests/frames/README.md +3 -1
- package/skills/teamsmith/tests/gate-guard.sh +20 -4
- package/skills/teamsmith/tests/help-surface.sh +61 -3
- package/skills/teamsmith/tests/install-shape.sh +400 -38
- package/skills/teamsmith/tests/key-replies-pty.sh +197 -21
- package/skills/teamsmith/tests/key-replies.sh +187 -68
- package/skills/teamsmith/tests/ledger-claim.sh +8 -6
- package/skills/teamsmith/tests/lib/box-judge.sh +2 -1
- package/skills/teamsmith/tests/lib/main-team-fingerprint.sh +104 -0
- package/skills/teamsmith/tests/lib/pm-window.sh +127 -0
- package/skills/teamsmith/tests/lib/reply-fixture.sh +7 -19
- package/skills/teamsmith/tests/lib/reply-guard.sh +188 -0
- package/skills/teamsmith/tests/lib/section-calls.pl +171 -0
- package/skills/teamsmith/tests/loop-inventory.tsv +7 -5
- package/skills/teamsmith/tests/meta-suite.sh +215 -0
- package/skills/teamsmith/tests/panel-b3-pty-mouse.py +154 -17
- package/skills/teamsmith/tests/panel-b3.sh +33 -4
- package/skills/teamsmith/tests/panel-choices.sh +11 -7
- package/skills/teamsmith/tests/remind-cli.sh +574 -0
- package/skills/teamsmith/tests/reply-capture-real.mjs +360 -0
- package/skills/teamsmith/tests/reply-capture-real.sh +5 -0
- package/skills/teamsmith/tests/reply-capture.mjs +622 -0
- package/skills/teamsmith/tests/section-paths.tsv +41 -10
- package/skills/teamsmith/tests/section-select.sh +180 -26
- package/skills/teamsmith/tests/smoke.sh +1829 -249
- package/skills/teamsmith/tests/state-authority-node.mjs +42 -0
- package/skills/teamsmith/tests/state-authority.sh +629 -0
- package/skills/teamsmith/tests/task-model-routing.sh +10 -1
- package/skills/teamsmith/tests/team-inbox-watch-harness.mjs +33 -0
- package/skills/teamsmith/tests/team-notify-knock-marker.mjs +91 -0
- package/skills/teamsmith/tests/workflow-entry.sh +123 -3
- package/skills/teamsmith-init/SKILL.md +1 -1
|
@@ -0,0 +1,360 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import assert from 'node:assert/strict'
|
|
3
|
+
import { createServer } from 'node:http'
|
|
4
|
+
import { spawnSync } from 'node:child_process'
|
|
5
|
+
import { appendFileSync, cpSync, existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, symlinkSync, writeFileSync } from 'node:fs'
|
|
6
|
+
import { dirname, join, resolve } from 'node:path'
|
|
7
|
+
import { fileURLToPath } from 'node:url'
|
|
8
|
+
import { setTimeout as delay } from 'node:timers/promises'
|
|
9
|
+
import { CaptureJournal, captureDiskFingerprint, inspectRuntime } from '../scripts/reply-capture.mjs'
|
|
10
|
+
const tests = dirname(fileURLToPath(import.meta.url)), skill = dirname(tests)
|
|
11
|
+
const selection = (process.argv.find(a => a.startsWith('--select='))?.slice(9) ?? (process.argv.includes('--select') ? process.argv[process.argv.indexOf('--select') + 1] : undefined) ?? 'print,tui,terminal,identity,lifecycle,owner-mutations').split(',')
|
|
12
|
+
const evidence = resolve(process.env.P396_EVIDENCE ?? `${process.env.HOME}/.cache/P396/pi-${Date.now()}`)
|
|
13
|
+
mkdirSync(evidence, { recursive: true, mode: 0o700 })
|
|
14
|
+
const temporary = mkdtempSync('/var/tmp/p396-real-'), socket = join(temporary, 'socket')
|
|
15
|
+
const pi = process.env.P396_PI ?? `${process.env.HOME}/.bun/bin/pi`
|
|
16
|
+
const 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', TERM: 'xterm-256color', USER: process.env.USER ?? 'fixture', LOGNAME: process.env.LOGNAME ?? 'fixture', TMPDIR: temporary }
|
|
19
|
+
const sh = value => `'${value.replaceAll("'", "'\\''")}'`
|
|
20
|
+
function command(bin, args, options = {}) {
|
|
21
|
+
const r = spawnSync(bin, args, { encoding: 'utf8', env: base, ...options })
|
|
22
|
+
assert.equal(r.error, undefined, `${bin}: ${r.error}`)
|
|
23
|
+
assert.equal(r.status, 0, `${bin} ${args.join(' ')}: ${r.stderr}\n${r.stdout}`)
|
|
24
|
+
return r.stdout
|
|
25
|
+
}
|
|
26
|
+
const tmux = (...args) => command('tmux', ['-S', socket, '-f', '/dev/null', ...args])
|
|
27
|
+
const json = path => JSON.parse(readFileSync(path, 'utf8'))
|
|
28
|
+
const jsonl = path => existsSync(path) ? readFileSync(path, 'utf8').trim().split('\n').filter(Boolean).map(s => JSON.parse(s)) : []
|
|
29
|
+
const text = message => message.content.filter(b => b.type === 'text').map(b => b.text).join('')
|
|
30
|
+
let server, failed = 0, passed = 0
|
|
31
|
+
async function until(test, label) {
|
|
32
|
+
const end = Date.now() + 90000 // External fixture watchdog only, not a product latency assertion.
|
|
33
|
+
while (!test()) { if (Date.now() > end) throw new Error(`watchdog: ${label}`); await delay(40) }
|
|
34
|
+
}
|
|
35
|
+
const plans = new Map()
|
|
36
|
+
server = createServer(async (req, res) => {
|
|
37
|
+
let raw = ''; for await (const chunk of req) raw += chunk
|
|
38
|
+
const body = JSON.parse(raw), name = req.url.split('/')[1], plan = plans.get(name)
|
|
39
|
+
if (!plan) { res.writeHead(404); res.end(); return }
|
|
40
|
+
const n = plan.requests++
|
|
41
|
+
appendFileSync(join(plan.dir, 'requests.jsonl'), JSON.stringify(body) + '\n')
|
|
42
|
+
if (n === 0 && plan.gate) await plan.gate
|
|
43
|
+
if (plan.kind === 'retry' && n === 1) { res.writeHead(503, { 'Content-Type': 'application/json' }); res.end(JSON.stringify({ error: { message: 'controlled 503 overload', type: 'server_error' } })); return }
|
|
44
|
+
const followup = n > 0 && ['queued', 'continued', 'tool', 'retry'].includes(plan.kind)
|
|
45
|
+
let answer = followup ? `普通续答 ${name}` : `决定 ${name} 保留。\n[[team-reply:决定 ${name}]]`
|
|
46
|
+
let finish = plan.kind === 'length' ? 'length' : 'stop'
|
|
47
|
+
if (plan.kind === 'partial') answer = `未闭控制 ${name}\n[[team-reply:未闭`
|
|
48
|
+
res.writeHead(200, { 'Content-Type': 'text/event-stream', 'Cache-Control': 'no-cache', Connection: 'keep-alive' })
|
|
49
|
+
const emit = (delta, reason = null) => res.write(`data: ${JSON.stringify({ id: `fixture-${name}-${n}`, object: 'chat.completion.chunk', created: 1, model: 'controlled', choices: [{ index: 0, delta, finish_reason: reason }] })}\n\n`)
|
|
50
|
+
emit({ role: 'assistant', content: '' })
|
|
51
|
+
// Whole markers actually arrive in raw output; the interactive case leaves them visible until message_end.
|
|
52
|
+
for (const chunk of [answer.slice(0, answer.indexOf('\n') + 1), answer.slice(answer.indexOf('\n') + 1)]) {
|
|
53
|
+
if (chunk) { emit({ content: chunk }); await delay(100) }
|
|
54
|
+
}
|
|
55
|
+
if (plan.kind === 'aborted') await delay(250)
|
|
56
|
+
if (plan.kind === 'error') { res.destroy(new Error('controlled stream interruption')); return }
|
|
57
|
+
if (plan.kind === 'tool' && n === 0) {
|
|
58
|
+
emit({ tool_calls: [{ index: 0, id: 'fixture-call', type: 'function', function: { name: 'p396-tool', arguments: '{}' } }] })
|
|
59
|
+
finish = 'tool_calls'
|
|
60
|
+
}
|
|
61
|
+
emit({}, finish); res.end('data: [DONE]\n\n')
|
|
62
|
+
})
|
|
63
|
+
await new Promise(resolve => server.listen(0, '127.0.0.1', resolve))
|
|
64
|
+
const port = server.address().port
|
|
65
|
+
async function run(name, kind = 'print', opts = {}) {
|
|
66
|
+
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')
|
|
67
|
+
for (const path of [dir, home, state, join(root, 'docs/team/tasks'), join(root, 'docs/team/inbox'), join(root, 'docs/team/outbox'), join(home, '.pi/agent')]) mkdirSync(path, { recursive: true })
|
|
68
|
+
const runSkill = opts.skillCopy ? join(root, 'skill') : skill
|
|
69
|
+
if (opts.skillCopy) cpSync(skill, runSkill, { recursive: true })
|
|
70
|
+
if (opts.ownerFlip) {
|
|
71
|
+
const path = join(runSkill, 'extension/team-reply.ts'), bytes = readFileSync(path, 'utf8'), anchor = 'if (owners.has(key)) return'
|
|
72
|
+
assert.equal(bytes.split(anchor).length, 2); writeFileSync(path, bytes.replace(anchor, 'if (false) return'))
|
|
73
|
+
}
|
|
74
|
+
writeFileSync(join(home, '.pi/agent/settings.json'), JSON.stringify({ retry: { enabled: kind === 'retry', maxRetries: 1, baseDelayMs: 1 }, compaction: { enabled: false } }))
|
|
75
|
+
writeFileSync(join(root, 'docs/team/BOARD.md'), '# untouched\n')
|
|
76
|
+
command('git', ['init', '-q', '-b', 'main'], { cwd: root })
|
|
77
|
+
const session = `p396-${name}`, mode = kind === 'tui' || opts.interactive ? '' : '--print'
|
|
78
|
+
const fixture = join(tests, 'fixtures/reply-capture-provider.ts')
|
|
79
|
+
let extra = `--offline --no-extensions --no-skills --no-tools --no-context-files ${mode} -e ${sh(fixture)}`
|
|
80
|
+
let copy
|
|
81
|
+
if (opts.duplicate) {
|
|
82
|
+
copy = join(root, 'copy')
|
|
83
|
+
cpSync(runSkill, copy, { recursive: true })
|
|
84
|
+
extra += ` -e ${sh(join(copy, 'extension/team-reply.ts'))}`
|
|
85
|
+
}
|
|
86
|
+
writeFileSync(config, `TEAM_PROJECT='${session}'\nTEAM_SESSION='${session}'\nTEAM_PM_WINDOW='pm'\nTEAM_PM_MODEL='p396/controlled'\nTEAM_TASK_MODELS='routine=p396/controlled analysis=p396/controlled verify=p396/controlled'\nTEAM_VCS='local'\nTEAM_PI_THEME='dark'\nTEAM_PI_BIN=${sh(pi)}\nTEAM_PM_EXTRA_PI_ARGS=${sh(extra)}\n`)
|
|
87
|
+
const prompt = join(state, 'pm-prompt.md'); writeFileSync(prompt, `CASE ${name}\n`)
|
|
88
|
+
const env = { ...base, HOME: home, PI_CODING_AGENT_DIR: join(home, '.pi/agent'), P396_CASE: kind, P396_EVIDENCE: dir, P396_ENDPOINT: `http://127.0.0.1:${port}/${name}/v1`, P396_TUI: kind === 'tui' ? '1' : '0' }
|
|
89
|
+
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'))}`
|
|
90
|
+
let launch = command('bash', ['-c', sourceScript], { cwd: root, env })
|
|
91
|
+
if (opts.invalid === 'no-entry') launch = launch.replace(` -e ${join(runSkill, 'extension/team-reply.ts')}`, '')
|
|
92
|
+
if (opts.invalid === 'foreign' || opts.invalid === 'worker') {
|
|
93
|
+
const other = join(root, opts.invalid)
|
|
94
|
+
if (opts.invalid === 'foreign') { mkdirSync(other); command('git', ['init', '-q', '-b', 'main'], { cwd: other }) }
|
|
95
|
+
else {
|
|
96
|
+
writeFileSync(join(root, 'README'), 'fixture'); command('git', ['add', 'README'], { cwd: root })
|
|
97
|
+
command('git', ['-c', 'user.name=fixture', '-c', 'user.email=fixture@example.invalid', 'commit', '-qm', 'fixture'], { cwd: root })
|
|
98
|
+
command('git', ['worktree', 'add', '-q', '--detach', other, 'HEAD'], { cwd: root })
|
|
99
|
+
}
|
|
100
|
+
launch = launch.replace(`cd ${root} &&`, `cd ${other} &&`)
|
|
101
|
+
}
|
|
102
|
+
if (opts.invalid === 'inherited') launch = launch.replace(`export TEAM_ROOT=${sh(root)}`, `export TEAM_ROOT=${sh(join(root, 'elsewhere'))}`)
|
|
103
|
+
if (opts.invalid === 'config-link') {
|
|
104
|
+
const real = join(root, 'real-config.sh'); writeFileSync(real, readFileSync(config, 'utf8')); rmSync(config); symlinkSync(real, config)
|
|
105
|
+
}
|
|
106
|
+
if (opts.invalid === 'ordinary') launch = `cd ${sh(root)} && exec ${sh(pi)} --provider p396 --model controlled -e ${sh(join(skill, 'extension/team-reply.ts'))} ${extra} @${sh(prompt)}`
|
|
107
|
+
if (opts.invalid === 'custom') {
|
|
108
|
+
const custom = `${sh(pi)} --provider {provider} --model {model} ${extra} {prompt}`
|
|
109
|
+
const customScript = sourceScript.replace('; team_pm_launch_cmd ', `; TEAM_PM_FRESH_LAUNCH=1; TEAM_PM_CMD=${sh(custom)}; team_pm_launch_cmd `)
|
|
110
|
+
launch = command('bash', ['-c', customScript], { cwd: root, env })
|
|
111
|
+
assert(!launch.includes('extension/team-reply.ts'), 'custom template was not injected')
|
|
112
|
+
}
|
|
113
|
+
writeFileSync(join(dir, 'launch.txt'), launch + '\n')
|
|
114
|
+
if (!opts.invalid) assert.equal((launch.match(/extension\/team-reply\.ts/g) ?? []).length, opts.duplicate ? 2 : 1, 'one directed entry plus explicitly requested test copy')
|
|
115
|
+
assert(!launch.includes('extension/team-notify.ts'), 'recipient PM does not load worker notify')
|
|
116
|
+
let release
|
|
117
|
+
const gate = opts.onReady ? new Promise(resolve => { release = resolve }) : null
|
|
118
|
+
plans.set(name, { requests: 0, kind, dir, gate })
|
|
119
|
+
// Start a quiet private pane, install the raw PTY tap before the actual builtin launch.
|
|
120
|
+
tmux('new-session', '-d', '-s', session, '-n', 'pm', '-c', root, 'sleep 600')
|
|
121
|
+
const globalBefore = tmux('show-environment', '-g')
|
|
122
|
+
const pane = tmux('display-message', '-p', '-t', `${session}:pm`, '#{pane_id}').trim()
|
|
123
|
+
tmux('pipe-pane', '-O', '-t', pane, `cat >>${sh(join(dir, 'raw.pty'))}`)
|
|
124
|
+
const script = join(root, 'launch.sh'), done = join(dir, 'done')
|
|
125
|
+
// All environment is process-local. Never set-environment -g or mutate the caller's tmux server.
|
|
126
|
+
const assignments = Object.entries(env).map(([key, value]) => `export ${key}=${sh(value)};`).join('\n')
|
|
127
|
+
writeFileSync(script, `#!/usr/bin/env bash\n${assignments}\nunset TEAM_ROOT TEAM_MAIN_ROOT TEAM_CONFIG_FILE TEAM_STATE_DIR\nbash -c ${sh(launch)} ${sh(readFileSync(prompt, 'utf8'))} ${kind === 'tui' || opts.interactive ? '' : `>${sh(join(dir, 'stdout'))} 2>${sh(join(dir, 'stderr'))}`}\nrc=$?; printf '%s\\n' "$rc" >${sh(done)}\nsleep 600\n`)
|
|
128
|
+
tmux('respawn-pane', '-k', '-t', pane, `bash ${sh(script)}`)
|
|
129
|
+
if (opts.onReady) {
|
|
130
|
+
await until(() => existsSync(join(dir, 'session-start')) || existsSync(done), `${name} startup`)
|
|
131
|
+
try { await opts.onReady({ dir, root, state, config, session, env, pane, skill: runSkill }) } finally { release() }
|
|
132
|
+
}
|
|
133
|
+
if (opts.interactive) {
|
|
134
|
+
try { await opts.interactive({ dir, root, state, config, session, env, pane, skill: runSkill }) }
|
|
135
|
+
catch (e) {
|
|
136
|
+
cpSync(state, join(dir, 'state'), { recursive: true })
|
|
137
|
+
writeFileSync(join(dir, 'failure-screen.txt'), tmux('capture-pane', '-p', '-S', '-', '-t', pane))
|
|
138
|
+
throw e
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
const customExit = join(state, 'pm-launch.exit')
|
|
142
|
+
await until(() => existsSync(done) || (opts.invalid === 'custom' && existsSync(customExit)), `${name} launch`)
|
|
143
|
+
if (opts.interactive) {
|
|
144
|
+
cpSync(state, join(dir, 'state'), { recursive: true })
|
|
145
|
+
cpSync(join(home, '.pi/agent/sessions'), join(dir, 'sessions'), { recursive: true })
|
|
146
|
+
writeFileSync(join(dir, 'final-screen.txt'), tmux('capture-pane', '-p', '-S', '-', '-t', pane))
|
|
147
|
+
assert.equal(tmux('show-environment', '-g'), globalBefore, 'capture does not write tmux global identity')
|
|
148
|
+
tmux('kill-session', '-t', session)
|
|
149
|
+
return
|
|
150
|
+
}
|
|
151
|
+
const rc = existsSync(done) ? Number(readFileSync(done, 'utf8').trim()) : Number(readFileSync(customExit, 'utf8').trim().split(' ')[1])
|
|
152
|
+
const events = jsonl(join(dir, 'events.jsonl')), requests = jsonl(join(dir, 'requests.jsonl'))
|
|
153
|
+
const ends = events.filter(e => e.type === 'message_end'), turns = events.filter(e => e.type === 'turn_end')
|
|
154
|
+
assert(ends.length, `${name}: no finalized assistant; stderr=${existsSync(join(dir, 'stderr')) ? readFileSync(join(dir, 'stderr'), 'utf8') : tmux('capture-pane', '-p', '-t', pane)}`)
|
|
155
|
+
const start = events.find(e => e.type === 'session_start')
|
|
156
|
+
cpSync(state, join(dir, 'state'), { recursive: true })
|
|
157
|
+
if (start?.sessionFile && existsSync(start.sessionFile)) cpSync(start.sessionFile, join(dir, 'transcript.jsonl'))
|
|
158
|
+
assert(start && !start.finalPidPresent, 'initial startup precedes final pm.pid metadata')
|
|
159
|
+
if (!['ordinary', 'custom'].includes(opts.invalid)) assert(start.spawnPresent, 'initial capture observes the spawn proof')
|
|
160
|
+
for (const event of ends) {
|
|
161
|
+
if (opts.invalid) assert(text(event.message).includes('[[team-reply'), `${name}: unproven context must stay literal`)
|
|
162
|
+
else if (kind === 'partial') assert(text(event.message).includes('[[team-reply:未闭'))
|
|
163
|
+
else assert(!text(event.message).includes('[[team-reply'), `${name}: finalized marker leaked`)
|
|
164
|
+
const turn = turns.find(t => t.entry?.message?.timestamp === event.message.timestamp)
|
|
165
|
+
assert(turn?.id && turn.entry.id === turn.id, `${name}: real entry binding`)
|
|
166
|
+
assert.deepEqual(turn.entry.message, event.message)
|
|
167
|
+
assert.notEqual(event.leaf, turn.id, `${name}: message_end precedes Pi append`)
|
|
168
|
+
}
|
|
169
|
+
assert(events.find(e => e.type === 'agent_settled'), `${name}: missing real settled`)
|
|
170
|
+
const transcript = jsonl(start.sessionFile)
|
|
171
|
+
for (const entry of transcript.filter(e => e.type === 'message' && e.message.role === 'assistant')) {
|
|
172
|
+
if (kind !== 'partial' && !opts.invalid) assert(!text(entry.message).includes('[[team-reply'), 'transcript cleanup')
|
|
173
|
+
}
|
|
174
|
+
const index = join(state, 'key-replies/index.v1'), count = existsSync(index) ? readFileSync(index).length / 4096 : 0
|
|
175
|
+
const expected = !opts.invalid && !opts.noPublish && ['print', 'tui'].includes(kind) ? 1 : 0
|
|
176
|
+
assert.equal(count, expected, `${name}: store count`)
|
|
177
|
+
const journalDir = join(state, 'reply-capture'), sourceFiles = existsSync(journalDir) ? readdirSync(journalDir).filter(s => s.endsWith('.json') && s !== 'runtime.json') : []
|
|
178
|
+
const source = sourceFiles.length ? json(join(journalDir, sourceFiles[0])) : null
|
|
179
|
+
if (expected) {
|
|
180
|
+
const record = Object.values(source.sources)[0]
|
|
181
|
+
assert.equal(record.status, 'saved'); assert.equal(record.no, 1)
|
|
182
|
+
const body = readdirSync(join(state, 'key-replies/bodies')).map(file => readFileSync(join(state, 'key-replies/bodies', file), 'utf8'))
|
|
183
|
+
assert.deepEqual(body, [text(ends.at(-1).message)])
|
|
184
|
+
}
|
|
185
|
+
if (kind === 'overallabort') assert(events.find(e => e.type === 'agent_settled').aborted, 'real stop followed by overall abort')
|
|
186
|
+
if (['queued', 'continued', 'tool', 'retry'].includes(kind)) {
|
|
187
|
+
assert.equal(ends.length, kind === 'retry' ? 3 : 2); assert.equal(requests.length, kind === 'retry' ? 3 : 2)
|
|
188
|
+
if (kind === 'retry') assert(ends.some(e => e.message.stopReason === 'error') && ends.at(-1).message.stopReason === 'stop', 'real 503 error terminal then retry stop')
|
|
189
|
+
if (kind === 'tool') assert(ends.some(e => e.message.stopReason === 'toolUse' && e.message.content.some(b => b.type === 'toolCall')), 'actual tool-use terminal and tool metadata retained')
|
|
190
|
+
const history = requests[1].messages.filter(m => m.role === 'assistant')
|
|
191
|
+
assert.equal(history.length, 1); assert.equal(history[0].content, text(ends[0].message))
|
|
192
|
+
assert(!JSON.stringify(history).includes('[[team-reply'), 'next provider history is clean')
|
|
193
|
+
}
|
|
194
|
+
if (kind === 'print') assert.equal(readFileSync(join(dir, 'stdout'), 'utf8'), text(ends.at(-1).message) + '\n', 'exact final print stdout')
|
|
195
|
+
if (kind === 'tui') {
|
|
196
|
+
await delay(100)
|
|
197
|
+
const raw = readFileSync(join(dir, 'raw.pty'), 'utf8')
|
|
198
|
+
assert(raw.includes(`[[team-reply:决定 ${name}]]`), 'raw PTY actual matching marker positive')
|
|
199
|
+
const screen = tmux('capture-pane', '-p', '-S', '-', '-t', pane)
|
|
200
|
+
writeFileSync(join(dir, 'final-screen.txt'), screen)
|
|
201
|
+
assert(screen.includes(`决定 ${name} 保留。`), 'final frame matching body positive')
|
|
202
|
+
assert(!screen.includes('[[team-reply'), 'final frame has no complete control')
|
|
203
|
+
// Scrollback may retain transient frames: validate finalized authoritative message separately, never claim zero flash.
|
|
204
|
+
assert(raw.includes(`决定 ${name} 保留。`), 'raw PTY actual body positive')
|
|
205
|
+
}
|
|
206
|
+
assert.equal(tmux('show-environment', '-g'), globalBefore, 'capture does not write tmux global identity')
|
|
207
|
+
assert.equal(readFileSync(join(root, 'docs/team/BOARD.md'), 'utf8'), '# untouched\n')
|
|
208
|
+
assert.equal(readdirSync(join(root, 'docs/team/tasks')).length, 0)
|
|
209
|
+
assert.equal(readdirSync(join(root, 'docs/team/inbox')).length, 0)
|
|
210
|
+
assert.equal(readdirSync(join(root, 'docs/team/outbox')).length, 0)
|
|
211
|
+
for (const file of ['notify.events', 'pending', 'wake']) assert(!existsSync(join(state, file)), `no ${file} publication side effect`)
|
|
212
|
+
const runtime = events.find(e => e.type === 'runtime')?.value
|
|
213
|
+
if (opts.invalid) assert.equal(runtime, undefined, 'unproven context cannot register ready')
|
|
214
|
+
else {
|
|
215
|
+
assert.equal(runtime?.fingerprint?.length, 64, 'actual loaded source registered')
|
|
216
|
+
assert.equal(runtime.status, 'degraded', 'shutdown registration is not falsely ready')
|
|
217
|
+
assert.equal(runtime.reason, 'session shutdown')
|
|
218
|
+
assert.equal(runtime.extension, join(runSkill, 'extension/team-reply.ts'), 'first path keeps owner/runtime even with a second loaded copy')
|
|
219
|
+
}
|
|
220
|
+
writeFileSync(join(dir, 'receipt.json'), JSON.stringify({ rc, events: events.map(e => e.type), sources: source, requests: requests.length, storeCount: count, runtime }, null, 2))
|
|
221
|
+
tmux('kill-session', '-t', session)
|
|
222
|
+
return { dir, root, state, config, session, env, pane, events, requests, runtime, rc }
|
|
223
|
+
}
|
|
224
|
+
const storeCount = state => existsSync(join(state, 'key-replies/index.v1')) ? readFileSync(join(state, 'key-replies/index.v1')).length / 4096 : 0
|
|
225
|
+
const confirmedCount = state => existsSync(join(state, 'reply-capture')) ? readdirSync(join(state, 'reply-capture'))
|
|
226
|
+
.filter(f => f.endsWith('.json') && f !== 'runtime.json')
|
|
227
|
+
.flatMap(f => Object.values(json(join(state, 'reply-capture', f)).sources)).filter(s => s.status === 'saved').length : 0
|
|
228
|
+
async function control(info, action) {
|
|
229
|
+
const path = join(info.dir, 'events.jsonl'), previous = jsonl(path).filter(e => e.type === 'command_done' && e.action === action).length
|
|
230
|
+
tmux('send-keys', '-t', info.pane, '-l', `/p396-control ${action}`); tmux('send-keys', '-t', info.pane, 'Enter')
|
|
231
|
+
await until(() => jsonl(path).filter(e => e.type === 'command_done' && e.action === action).length > previous, `command ${action}`)
|
|
232
|
+
}
|
|
233
|
+
async function prompt(info, value) {
|
|
234
|
+
const path = join(info.dir, 'events.jsonl'), previous = jsonl(path).filter(e => e.type === 'agent_settled').length
|
|
235
|
+
tmux('send-keys', '-t', info.pane, '-l', value); tmux('send-keys', '-t', info.pane, 'Enter')
|
|
236
|
+
await until(() => jsonl(path).filter(e => e.type === 'agent_settled').length > previous, `prompt ${value}`)
|
|
237
|
+
}
|
|
238
|
+
async function test(name, body) {
|
|
239
|
+
try { await body(); console.log(`PASS real Pi ${name}`); passed++ }
|
|
240
|
+
catch (e) { failed++; console.error(`FAIL real Pi ${name}: ${e.stack}`) }
|
|
241
|
+
}
|
|
242
|
+
try {
|
|
243
|
+
if (selection.includes('print')) await test('builtin print/end/append/entry/settled/raw store/transcript', () => run('print'))
|
|
244
|
+
if (selection.includes('tui')) await test('interactive actual-marker raw PTY and authoritative final cleanup', () => run('tui', 'tui'))
|
|
245
|
+
if (selection.includes('terminal')) {
|
|
246
|
+
for (const kind of ['length', 'error', 'aborted', 'partial', 'queued', 'continued', 'tool', 'retry', 'overallabort']) await test(`${kind} cleanup and publication eligibility`, () => run(kind, kind))
|
|
247
|
+
await test('staging journal fault preserves real Pi stdout/transcript', () => run('stage-failure', 'print', {
|
|
248
|
+
noPublish: true,
|
|
249
|
+
onReady: async info => {
|
|
250
|
+
const start = jsonl(join(info.dir, 'events.jsonl')).find(e => e.type === 'session_start')
|
|
251
|
+
const journal = new CaptureJournal({ root: info.root, state: info.state, sessionId: start.sessionId, sessionFile: start.sessionFile })
|
|
252
|
+
const outside = join(info.root, 'not-a-lock'); writeFileSync(outside, 'unchanged'); symlinkSync(outside, `${journal.path}.lock`)
|
|
253
|
+
},
|
|
254
|
+
}))
|
|
255
|
+
}
|
|
256
|
+
if (selection.includes('owner-flip')) await test('first path keeps owner/runtime', () => run('owner-flip', 'print', { skillCopy: true, duplicate: true, ownerFlip: true }))
|
|
257
|
+
if (selection.includes('owner-control')) await test('first path keeps owner/runtime', () => run('owner-control', 'print', { skillCopy: true, duplicate: true }))
|
|
258
|
+
if (selection.includes('owner-mutations')) await test('owner mutation named red and restoration green in private Pi', async () => {
|
|
259
|
+
for (const [group, code] of [['owner-flip', 1], ['owner-control', 0]]) {
|
|
260
|
+
const result = spawnSync(process.execPath, [fileURLToPath(import.meta.url), `--select=${group}`], { env: { ...process.env, P396_EVIDENCE: join(evidence, group) }, encoding: 'utf8' })
|
|
261
|
+
const output = result.stdout + result.stderr
|
|
262
|
+
writeFileSync(join(evidence, `${group}.log`), output)
|
|
263
|
+
assert.equal(result.status, code, output)
|
|
264
|
+
assert(output.includes(code ? 'first path keeps owner/runtime' : 'passed=1 failed=0'), output)
|
|
265
|
+
}
|
|
266
|
+
})
|
|
267
|
+
if (selection.includes('lifecycle')) {
|
|
268
|
+
await test('loaded dependency reload evaluates new code; tree/fork/new/switch do not import', () => run('lifecycle', 'lifecycle', {
|
|
269
|
+
skillCopy: true,
|
|
270
|
+
interactive: async info => {
|
|
271
|
+
await until(() => storeCount(info.state) === 1 && confirmedCount(info.state) === 1, 'first lifecycle receipt journaled')
|
|
272
|
+
const path = join(info.state, 'reply-capture/runtime.json'), first = json(path)
|
|
273
|
+
await control(info, 'snapshot')
|
|
274
|
+
const launchHash = () => command('bash', ['-c', `TEAM_SKILL_DIR=${sh(info.skill)}; source ${sh(join(info.skill, 'scripts/lib/cmd-update.sh'))}; team_skill_hash`], { env: info.env, cwd: info.root }).trim()
|
|
275
|
+
const launchBefore = launchHash()
|
|
276
|
+
const parser = join(info.skill, 'scripts/reply-capture.mjs'), old = readFileSync(parser, 'utf8')
|
|
277
|
+
const anchor = "return { ...result, title, candidate: true, reason: 'candidate' }"
|
|
278
|
+
assert(old.includes(anchor)); writeFileSync(parser, old.replace(anchor, "return { ...result, title: 'dependency-loaded-v2', candidate: true, reason: 'candidate' }"))
|
|
279
|
+
const stale = inspectRuntime({ ...info, window: 'pm' }); assert.equal(stale.state, 'stale'); assert.equal(stale.loaded, first.fingerprint)
|
|
280
|
+
const launchAfter = launchHash(); assert.notEqual(launchAfter, launchBefore, 'launch/version hash includes dependency-only edits')
|
|
281
|
+
await control(info, 'reload')
|
|
282
|
+
await until(() => json(path).status === 'ready' && json(path).generation !== first.generation, 'new loaded generation')
|
|
283
|
+
const second = json(path)
|
|
284
|
+
writeFileSync(join(info.dir, 'fingerprints.json'), JSON.stringify({ before: first, stale, after: second, launchBefore, launchAfter }, null, 2))
|
|
285
|
+
assert.equal(second.fingerprint, captureDiskFingerprint(info.skill)); assert.notEqual(second.fingerprint, first.fingerprint)
|
|
286
|
+
assert.equal(storeCount(info.state), 1, 'reload cannot reattempt saved source')
|
|
287
|
+
await prompt(info, 'CASE lifecycle-after-reload')
|
|
288
|
+
await until(() => storeCount(info.state) === 2 && confirmedCount(info.state) === 2, 'new dependency receipt journaled')
|
|
289
|
+
const source = readdirSync(join(info.state, 'reply-capture')).find(f => f.endsWith('.json') && f !== 'runtime.json')
|
|
290
|
+
const saved = Object.values(json(join(info.state, 'reply-capture', source)).sources).filter(s => s.status === 'saved')
|
|
291
|
+
assert.equal(saved.find(s => s.no === 2)?.title, 'dependency-loaded-v2', 'evaluated replacement dependency, not reread hash over stale code')
|
|
292
|
+
await control(info, 'tree'); assert.equal(storeCount(info.state), 2)
|
|
293
|
+
await prompt(info, 'CASE lifecycle-after-tree'); await until(() => storeCount(info.state) === 3 && confirmedCount(info.state) === 3, 'post-tree new source journaled')
|
|
294
|
+
await control(info, 'fork')
|
|
295
|
+
assert.notEqual(json(path).sessionId, second.sessionId); assert.equal(storeCount(info.state), 3, 'copied fork entries never imported')
|
|
296
|
+
assert.equal(readdirSync(join(info.state, 'reply-capture')).filter(f => f.endsWith('.json') && f !== 'runtime.json').length, 1)
|
|
297
|
+
await prompt(info, 'CASE lifecycle-new-fork-entry'); await until(() => storeCount(info.state) === 4 && confirmedCount(info.state) === 4, 'new fork source journaled')
|
|
298
|
+
await control(info, 'new'); assert.equal(storeCount(info.state), 4)
|
|
299
|
+
await control(info, 'switch'); assert.equal(json(path).sessionId, second.sessionId); assert.equal(storeCount(info.state), 4)
|
|
300
|
+
const events = jsonl(join(info.dir, 'events.jsonl'))
|
|
301
|
+
assert(events.filter(e => e.type === 'session_start').length >= 5)
|
|
302
|
+
assert(events.filter(e => e.type === 'message_end').every(e => !text(e.message).includes('[[team-reply')))
|
|
303
|
+
await control(info, 'stop')
|
|
304
|
+
},
|
|
305
|
+
}))
|
|
306
|
+
await test('reload cannot invent a never-injected entry', () => run('noentry', 'lifecycle', {
|
|
307
|
+
skillCopy: true, invalid: 'no-entry',
|
|
308
|
+
interactive: async info => {
|
|
309
|
+
const events = join(info.dir, 'events.jsonl')
|
|
310
|
+
await until(() => jsonl(events).some(e => e.type === 'agent_settled'), 'no-entry first answer')
|
|
311
|
+
assert(!existsSync(join(info.state, 'reply-capture/runtime.json')))
|
|
312
|
+
await control(info, 'reload'); await prompt(info, 'CASE noentry-after-reload')
|
|
313
|
+
assert.equal(storeCount(info.state), 0); assert(!existsSync(join(info.state, 'reply-capture')))
|
|
314
|
+
assert(jsonl(events).filter(e => e.type === 'message_end').every(e => text(e.message).includes('[[team-reply')))
|
|
315
|
+
await control(info, 'stop')
|
|
316
|
+
},
|
|
317
|
+
}))
|
|
318
|
+
}
|
|
319
|
+
if (selection.includes('identity')) {
|
|
320
|
+
for (const invalid of ['foreign', 'worker', 'ordinary', 'custom', 'inherited', 'config-link']) await test(`${invalid} context cannot clean/publish/register`, () => run(invalid, 'print', { invalid }))
|
|
321
|
+
await test('two loaded paths share one owner and generation', () => run('duplicate', 'print', { duplicate: true }))
|
|
322
|
+
await test('live registration distinct from disk, dead/reused process and readonly doctor', () => run('runtime', 'print', {
|
|
323
|
+
onReady: async info => {
|
|
324
|
+
const args = { ...info, window: 'pm', skill }
|
|
325
|
+
const path = join(info.state, 'reply-capture/runtime.json'), original = readFileSync(path, 'utf8'), registration = JSON.parse(original)
|
|
326
|
+
const before = inspectRuntime(args); assert.equal(before.state, 'ready'); assert.equal(before.disk, before.loaded)
|
|
327
|
+
for (const patch of [{ pid: 2147483647 }, { starttime: String(Number(registration.starttime) + 1) }]) {
|
|
328
|
+
writeFileSync(path, JSON.stringify({ ...registration, ...patch }))
|
|
329
|
+
assert.equal(inspectRuntime(args).state, 'stale', 'dead or reused process not ready')
|
|
330
|
+
}
|
|
331
|
+
writeFileSync(path, original)
|
|
332
|
+
const isolated = join(info.root, 'fingerprint-copy')
|
|
333
|
+
for (const file of ['extension/team-reply.ts', 'scripts/reply-capture.mjs', 'scripts/replies.mjs']) {
|
|
334
|
+
mkdirSync(dirname(join(isolated, file)), { recursive: true }); cpSync(join(skill, file), join(isolated, file))
|
|
335
|
+
}
|
|
336
|
+
assert.equal(inspectRuntime({ ...args, skill: isolated }).state, 'ready')
|
|
337
|
+
appendFileSync(join(isolated, 'scripts/reply-capture.mjs'), '\n// dependency-only fixture edit\n')
|
|
338
|
+
const stale = inspectRuntime({ ...args, skill: isolated }); assert.equal(stale.state, 'stale'); assert.notEqual(stale.disk, stale.loaded)
|
|
339
|
+
const doctor = spawnSync('bash', [join(skill, 'scripts/team'), '--root', info.root, 'doctor'], { cwd: info.root, env: info.env, encoding: 'utf8' })
|
|
340
|
+
writeFileSync(join(info.dir, 'doctor.txt'), doctor.stdout + doctor.stderr)
|
|
341
|
+
assert.match(doctor.stdout, /关键回复运行/); assert.match(doctor.stdout, /ready disk=/)
|
|
342
|
+
assert.equal(readFileSync(path, 'utf8'), original, 'doctor cannot repair/update the live registration')
|
|
343
|
+
assert(!readdirSync(join(info.state, 'reply-capture')).some(f => f.endsWith('.json') && f !== 'runtime.json'), 'doctor cannot create source records')
|
|
344
|
+
writeFileSync(join(info.state, 'pm.pid'), `${registration.pid}\n`)
|
|
345
|
+
writeFileSync(join(info.state, 'pm.pid.proof'), 'spawn\n')
|
|
346
|
+
rmSync(join(info.state, 'pm.pid.spawn')) // Private launcher completes metadata after initial extension registration.
|
|
347
|
+
assert.equal(inspectRuntime(args).state, 'ready', 'late final metadata remains the same running PM')
|
|
348
|
+
},
|
|
349
|
+
}))
|
|
350
|
+
}
|
|
351
|
+
} finally {
|
|
352
|
+
server.closeAllConnections(); await new Promise(resolve => server.close(resolve))
|
|
353
|
+
// This socket was allocated by this invocation, never the live/default server.
|
|
354
|
+
const remaining = spawnSync('tmux', ['-S', socket, 'list-sessions'], { env: base, encoding: 'utf8' })
|
|
355
|
+
if (remaining.status === 0) tmux('kill-server')
|
|
356
|
+
else assert.match(remaining.stderr, /no server running|error connecting/, 'only an already-exited private server is expected')
|
|
357
|
+
rmSync(temporary, { recursive: true, force: true })
|
|
358
|
+
}
|
|
359
|
+
console.log(`reply-capture-real: passed=${passed} failed=${failed} evidence=${evidence}`)
|
|
360
|
+
if (failed) process.exitCode = 1
|