teamsmith 0.1.1 → 0.2.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 +16 -8
- package/package.json +1 -1
- package/skills/teamsmith/CHANGELOG.md +55 -0
- package/skills/teamsmith/SKILL.md +18 -7
- package/skills/teamsmith/extension/team-bg.ts +47 -11
- package/skills/teamsmith/extension/team-notify.ts +143 -4
- package/skills/teamsmith/references/agent-adapters.md +7 -7
- package/skills/teamsmith/references/config.md +29 -15
- package/skills/teamsmith/references/migration.md +38 -2
- package/skills/teamsmith/references/openspec.md +23 -9
- package/skills/teamsmith/references/protocol.md +81 -13
- package/skills/teamsmith/references/workflows.md +31 -19
- package/skills/teamsmith/scripts/lib/cmd-agents.sh +210 -70
- package/skills/teamsmith/scripts/lib/cmd-bootstrap.sh +70 -9
- package/skills/teamsmith/scripts/lib/cmd-config.sh +222 -70
- package/skills/teamsmith/scripts/lib/cmd-death.sh +2 -15
- package/skills/teamsmith/scripts/lib/cmd-docs.sh +6 -3
- package/skills/teamsmith/scripts/lib/cmd-project.sh +134 -17
- package/skills/teamsmith/scripts/lib/cmd-reply.sh +96 -0
- package/skills/teamsmith/scripts/lib/cmd-review.sh +13 -10
- package/skills/teamsmith/scripts/lib/cmd-status.sh +42 -13
- package/skills/teamsmith/scripts/lib/cmd-watch.sh +75 -13
- package/skills/teamsmith/scripts/lib/common.sh +797 -71
- package/skills/teamsmith/scripts/monitor.mjs +34 -3
- package/skills/teamsmith/scripts/panel/README.md +22 -11
- package/skills/teamsmith/scripts/panel/panel.js +217 -215
- package/skills/teamsmith/scripts/panel/src/App.tsx +421 -164
- package/skills/teamsmith/scripts/panel/src/data.ts +84 -4
- package/skills/teamsmith/scripts/panel/src/layout.ts +502 -91
- package/skills/teamsmith/scripts/panel/src/main.tsx +97 -12
- package/skills/teamsmith/scripts/panel/src/settings.ts +1 -1
- package/skills/teamsmith/scripts/panel/src/strings/en.ts +56 -21
- package/skills/teamsmith/scripts/panel/src/strings/zh.ts +56 -21
- package/skills/teamsmith/scripts/panel/src/types.ts +178 -16
- package/skills/teamsmith/scripts/replies.mjs +893 -0
- package/skills/teamsmith/scripts/team +1 -0
- package/skills/teamsmith/templates/AGENTS.section.md.tmpl +15 -2
- package/skills/teamsmith/templates/BOARD.md.tmpl +2 -2
- package/skills/teamsmith/templates/OWNERSHIP.md.tmpl +7 -3
- package/skills/teamsmith/templates/PROTOCOL.md.tmpl +17 -0
- package/skills/teamsmith/templates/config.sh.tmpl +10 -5
- package/skills/teamsmith/templates/memory-seed.md.tmpl +3 -0
- package/skills/teamsmith/templates/pm-prompt.md.tmpl +20 -1
- package/skills/teamsmith/templates/report.md.tmpl +12 -0
- package/skills/teamsmith/templates/task.md.tmpl +4 -0
- package/skills/teamsmith/tests/bg-ledger-harness.mjs +682 -0
- package/skills/teamsmith/tests/bg-ledger.sh +307 -0
- package/skills/teamsmith/tests/checkout-shape-probe.sh +287 -58
- package/skills/teamsmith/tests/config-cli.sh +162 -288
- package/skills/teamsmith/tests/death-cause.sh +5 -2
- package/skills/teamsmith/tests/install-shape.sh +4 -2
- package/skills/teamsmith/tests/key-replies-pty.sh +375 -0
- package/skills/teamsmith/tests/key-replies-ui.sh +332 -0
- package/skills/teamsmith/tests/key-replies.sh +1075 -0
- package/skills/teamsmith/tests/ledger-ban.sh +5 -5
- package/skills/teamsmith/tests/ledger-claim.sh +247 -0
- package/skills/teamsmith/tests/lib/checkout-shape.sh +66 -14
- package/skills/teamsmith/tests/lib/model-policy.sh +26 -0
- package/skills/teamsmith/tests/lib/model-routing-boundary.sh +420 -0
- package/skills/teamsmith/tests/lib/model-routing-expansion.sh +155 -0
- package/skills/teamsmith/tests/lib/model-routing-flips.py +136 -0
- package/skills/teamsmith/tests/lib/model-routing-roles.sh +250 -0
- package/skills/teamsmith/tests/lib/proc-io.sh +103 -0
- package/skills/teamsmith/tests/lib/reply-fixture.sh +372 -0
- package/skills/teamsmith/tests/lib/tmux-iso.sh +8 -0
- package/skills/teamsmith/tests/panel-b2.sh +1 -1
- package/skills/teamsmith/tests/panel-b3-stub.sh +27 -0
- package/skills/teamsmith/tests/panel-b3.sh +14 -10
- package/skills/teamsmith/tests/panel-choices.sh +74 -61
- package/skills/teamsmith/tests/panel-cpu.sh +1 -1
- package/skills/teamsmith/tests/panel-p21.sh +311 -190
- package/skills/teamsmith/tests/perf.sh +1 -1
- package/skills/teamsmith/tests/pm-box-real.sh +1 -1
- package/skills/teamsmith/tests/pulse-nudge-key.sh +1 -1
- package/skills/teamsmith/tests/routes.sh +43 -22
- package/skills/teamsmith/tests/section-budgets.tsv +9 -5
- package/skills/teamsmith/tests/section-paths.tsv +26 -16
- package/skills/teamsmith/tests/section-select.sh +99 -16
- package/skills/teamsmith/tests/smoke.sh +930 -216
- package/skills/teamsmith/tests/snapshots/zh-dark-120-detail.txt +2 -2
- package/skills/teamsmith/tests/snapshots/zh-dark-120-p4.txt +2 -2
- package/skills/teamsmith/tests/snapshots/zh-dark-120.txt +9 -9
- package/skills/teamsmith/tests/snapshots/zh-dark-160-p4.txt +2 -2
- package/skills/teamsmith/tests/snapshots/zh-dark-160.txt +9 -9
- package/skills/teamsmith/tests/snapshots/zh-dark-59-detail.txt +1 -1
- package/skills/teamsmith/tests/snapshots/zh-dark-59-p4.txt +1 -1
- package/skills/teamsmith/tests/snapshots/zh-dark-59.txt +5 -5
- package/skills/teamsmith/tests/snapshots/zh-dark-99-p4.txt +2 -2
- package/skills/teamsmith/tests/snapshots/zh-dark-99.txt +5 -5
- package/skills/teamsmith/tests/snapshots/zh-light-120-detail.txt +2 -2
- package/skills/teamsmith/tests/snapshots/zh-light-120-p4.txt +2 -2
- package/skills/teamsmith/tests/snapshots/zh-light-120.txt +9 -9
- package/skills/teamsmith/tests/snapshots/zh-light-160-p4.txt +2 -2
- package/skills/teamsmith/tests/snapshots/zh-light-160.txt +9 -9
- package/skills/teamsmith/tests/snapshots/zh-light-59-detail.txt +1 -1
- package/skills/teamsmith/tests/snapshots/zh-light-59-p4.txt +1 -1
- package/skills/teamsmith/tests/snapshots/zh-light-59.txt +5 -5
- package/skills/teamsmith/tests/snapshots/zh-light-99-p4.txt +2 -2
- package/skills/teamsmith/tests/snapshots/zh-light-99.txt +5 -5
- package/skills/teamsmith/tests/task-header-model.sh +2 -1
- package/skills/teamsmith/tests/task-model-routing.sh +1014 -0
- package/skills/teamsmith-init/SKILL.md +38 -38
- package/skills/teamsmith-init/references/bootstrap.md +6 -4
- package/skills/teamsmith-init/templates/bootstrap-prompt.md.tmpl +9 -5
|
@@ -0,0 +1,682 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* P230 · long-job-suspend · A 刀夹具(`tests/bg-ledger.sh` 的确定性驱动)
|
|
4
|
+
*
|
|
5
|
+
* <node|bun> bg-ledger-harness.mjs --bg <extension/team-bg.ts> --root <fixture repo> \
|
|
6
|
+
* [--notify <extension/team-notify.ts>] [--groups wording,ledger,suspend-shape,owner-scope] [--marker <pre>]
|
|
7
|
+
*
|
|
8
|
+
* 为什么用「假 Pi 宿主」而不是真模型:本夹具要证的是**扩展自己的合同** —— 注册工具面的文本、
|
|
9
|
+
* 账本两类新行、挂起判定的目录解析与身份验证。这些都被接口(registerTool / agent_settled)完全决定,
|
|
10
|
+
* 用真模型只会把判据换成「模型有没有照着做」。
|
|
11
|
+
*
|
|
12
|
+
* 三条纪律(M7.2 / §13c):
|
|
13
|
+
* ① 身份隔离:启动时清掉继承来的 TEAM_ / SMOKE_ / TMUX 变量,绝不用调用者的项目身份;
|
|
14
|
+
* ② 每条用例的夹具仓库各带自己的 `.pi/team/config.sh`,只写 --root 与它旁边的 scratch 子树(/tmp 下);
|
|
15
|
+
* ③ 起的每个后台作业都登记 pid,退出时只对**登记过的 pid**发信号(不按名字/模式找进程)。
|
|
16
|
+
*
|
|
17
|
+
* 输出:每个用例一行 `BG-CASE PASS|FAIL <name> [:: detail]`;任一 FAIL → 退出码 1。
|
|
18
|
+
*/
|
|
19
|
+
import { execFileSync, spawn } from 'node:child_process'
|
|
20
|
+
import { existsSync, mkdirSync, readFileSync, rmSync, symlinkSync, writeFileSync } from 'node:fs'
|
|
21
|
+
import { dirname, join, resolve } from 'node:path'
|
|
22
|
+
|
|
23
|
+
// ── 参数与身份隔离 ─────────────────────────────────────────────────────────────
|
|
24
|
+
const argv = process.argv.slice(2)
|
|
25
|
+
const opt = (name, fallback = '') => {
|
|
26
|
+
const i = argv.indexOf(`--${name}`)
|
|
27
|
+
return i >= 0 && i + 1 < argv.length ? argv[i + 1] : fallback
|
|
28
|
+
}
|
|
29
|
+
const BG = opt('bg') ? resolve(opt('bg')) : ''
|
|
30
|
+
const NOTIFY = opt('notify', '-')
|
|
31
|
+
const ROOT = opt('root') ? resolve(opt('root')) : ''
|
|
32
|
+
const MARKER = opt('marker', 'bg-ledger')
|
|
33
|
+
const GROUPS = new Set(opt('groups', 'wording,ledger,suspend-shape,owner-scope').split(',').filter(Boolean))
|
|
34
|
+
if (!BG || !existsSync(BG)) {
|
|
35
|
+
console.error('bg-ledger-harness: --bg <extension/team-bg.ts> 是必需的')
|
|
36
|
+
process.exit(2)
|
|
37
|
+
}
|
|
38
|
+
if (!ROOT || !existsSync(join(ROOT, '.pi/team/config.sh'))) {
|
|
39
|
+
console.error('bg-ledger-harness: --root <夹具仓库> 是必需的(它必须带 .pi/team/config.sh)')
|
|
40
|
+
process.exit(2)
|
|
41
|
+
}
|
|
42
|
+
if ((GROUPS.has('suspend-shape') || GROUPS.has('owner-scope')) && NOTIFY === '-') {
|
|
43
|
+
console.error('bg-ledger-harness: suspend-shape / owner-scope 需要 --notify <extension/team-notify.ts>')
|
|
44
|
+
process.exit(2)
|
|
45
|
+
}
|
|
46
|
+
for (const key of Object.keys(process.env)) {
|
|
47
|
+
if (/^(TEAM_|SMOKE_)/.test(key) || key === 'TMUX' || key === 'TMUX_PANE') delete process.env[key]
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
// ── 基础工具 ──────────────────────────────────────────────────────────────────
|
|
51
|
+
const sleep = ms => new Promise(r => setTimeout(r, ms))
|
|
52
|
+
const waitFor = async (fn, ms = 4000) => { const t = Date.now(); for (;;) { if (fn()) return true; if (Date.now() - t > ms) return false; await sleep(25) } }
|
|
53
|
+
let failures = 0
|
|
54
|
+
const check = (name, ok, detail = '') => {
|
|
55
|
+
console.log(`BG-CASE ${ok ? 'PASS' : 'FAIL'} ${name}${detail ? ` :: ${detail}` : ''}`)
|
|
56
|
+
if (!ok) failures++
|
|
57
|
+
}
|
|
58
|
+
const trackedPids = new Set()
|
|
59
|
+
const trackPid = pid => { if (pid > 0) trackedPids.add(pid) }
|
|
60
|
+
process.on('exit', () => { for (const pid of trackedPids) { try { process.kill(pid, 'SIGKILL') } catch { /* ignore */ } } })
|
|
61
|
+
|
|
62
|
+
const git = (args, cwd) => execFileSync('git', args, { cwd, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim()
|
|
63
|
+
const escapeRe = s => String(s).replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
|
|
64
|
+
const jobName = suffix => `${MARKER}-${suffix}`
|
|
65
|
+
|
|
66
|
+
// ── 扩展加载(每个场景一个独立的假宿主实例;同一模块可以被 default() 多次实例化)─────
|
|
67
|
+
const modules = new Map()
|
|
68
|
+
const loadModule = async path => {
|
|
69
|
+
if (!modules.has(path)) modules.set(path, await import(path))
|
|
70
|
+
return modules.get(path)
|
|
71
|
+
}
|
|
72
|
+
const newBgHost = mod => {
|
|
73
|
+
const tools = {}
|
|
74
|
+
const handlers = {}
|
|
75
|
+
const sent = []
|
|
76
|
+
mod.default({
|
|
77
|
+
on: (name, fn) => { (handlers[name] ||= []).push(fn) },
|
|
78
|
+
registerTool: def => { tools[def.name] = def },
|
|
79
|
+
registerCommand: () => {},
|
|
80
|
+
sendMessage: (msg, opts) => { sent.push({ msg, opts }) },
|
|
81
|
+
getAllTools: () => Object.keys(tools),
|
|
82
|
+
})
|
|
83
|
+
return {
|
|
84
|
+
tools,
|
|
85
|
+
handlers,
|
|
86
|
+
sent,
|
|
87
|
+
emit: async (name, ...rest) => { for (const fn of handlers[name] ?? []) await fn(...rest) },
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
const makeRunner = (host, cwd) => {
|
|
91
|
+
const ctx = { cwd }
|
|
92
|
+
const run = async (command, name) => {
|
|
93
|
+
const res = await host.tools.team_bg_run.execute('call-run', { command, name }, null, null, ctx)
|
|
94
|
+
const id = String(res?.details?.id ?? '')
|
|
95
|
+
const pid = Number(res?.details?.pid ?? 0)
|
|
96
|
+
trackPid(pid)
|
|
97
|
+
return { id, pid, text: String(res?.content?.[0]?.text ?? ''), log: String(res?.details?.log ?? '') }
|
|
98
|
+
}
|
|
99
|
+
const wait = async (id, timeout_ms, signal) => {
|
|
100
|
+
const params = timeout_ms === undefined ? { id } : { id, timeout_ms }
|
|
101
|
+
const res = await host.tools.team_bg_wait.execute('call-wait', params, signal ?? null, null, ctx)
|
|
102
|
+
return String(res?.content?.[0]?.text ?? '')
|
|
103
|
+
}
|
|
104
|
+
const stop = async (job, ms = 4000) => {
|
|
105
|
+
try { process.kill(job.pid, 'SIGKILL') } catch { /* 已经不在了 */ }
|
|
106
|
+
try { await wait(job.id, ms) } catch { /* 作业表已经清掉等场合 */ }
|
|
107
|
+
}
|
|
108
|
+
return { ctx, run, wait, stop }
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
// ── 账本读取 ──────────────────────────────────────────────────────────────────
|
|
112
|
+
const ledgerLines = stateDir => existsSync(join(stateDir, 'bg.log'))
|
|
113
|
+
? readFileSync(join(stateDir, 'bg.log'), 'utf8').trim().split('\n').filter(Boolean)
|
|
114
|
+
: []
|
|
115
|
+
const ledgerFor = (stateDir, id, kind) => ledgerLines(stateDir)
|
|
116
|
+
.filter(l => new RegExp(` ${kind} id=${escapeRe(id)}( |$)`).test(l)).at(-1) ?? ''
|
|
117
|
+
const waitedOf = line => Number(/ waited_s=([0-9.]+)/.exec(line)?.[1] ?? NaN)
|
|
118
|
+
|
|
119
|
+
// ── 夹具仓库 ──────────────────────────────────────────────────────────────────
|
|
120
|
+
const SCRATCH = join(dirname(ROOT), 'p230-bg-ledger')
|
|
121
|
+
mkdirSync(SCRATCH, { recursive: true })
|
|
122
|
+
|
|
123
|
+
/** 一个独立夹具仓库:主工作树 + 每个席位一个链接工作树(默认只有 `dev`;不带 config —— 复现生产形状)。
|
|
124
|
+
* wip.txt 让树保持脏:挂起要证明「⚠ 前缀被省略」,非挂起形状要对出「前缀在」。
|
|
125
|
+
* seats 多于一个时(P236 owner-scope)名册与工作树同步扩展:两席位共享同一个车道 state 目录。 */
|
|
126
|
+
const makeBase = (name, { ownConfigInWorktree = false, seats = ['dev'] } = {}) => {
|
|
127
|
+
const base = join(SCRATCH, 'bases', name)
|
|
128
|
+
rmSync(base, { recursive: true, force: true })
|
|
129
|
+
mkdirSync(join(base, '.pi/team/state'), { recursive: true })
|
|
130
|
+
mkdirSync(join(base, 'docs/team/inbox'), { recursive: true })
|
|
131
|
+
writeFileSync(join(base, '.pi/team/config.sh'),
|
|
132
|
+
`TEAM_PROJECT="bg-ledger-${name}"\nTEAM_AGENTS="${seats.join(' ')}"\nTEAM_WORKTREES_DIR=".worktrees"\n` +
|
|
133
|
+
`TEAM_NOTIFY_LOG="${base}/.pi/team/state/notify.log"\n`)
|
|
134
|
+
writeFileSync(join(base, 'README.md'), `# bg-ledger fixture ${name}\n`)
|
|
135
|
+
git(['init', '-q', '-b', 'main'], base)
|
|
136
|
+
git(['add', 'README.md'], base)
|
|
137
|
+
git(['-c', 'user.email=fixture@teamsmith', '-c', 'user.name=fixture', 'commit', '-qm', 'init'], base)
|
|
138
|
+
const wts = {}
|
|
139
|
+
for (const [i, seat] of seats.entries()) {
|
|
140
|
+
const wt = join(base, '.worktrees', seat)
|
|
141
|
+
git(['worktree', 'add', '-q', '-b', i === 0 ? `task/P230-${name}` : `task/P230-${name}-${seat}`, wt], base)
|
|
142
|
+
writeFileSync(join(wt, 'wip.txt'), 'uncommitted fixture line\n')
|
|
143
|
+
if (ownConfigInWorktree) {
|
|
144
|
+
mkdirSync(join(wt, '.pi/team'), { recursive: true })
|
|
145
|
+
writeFileSync(join(wt, '.pi/team/config.sh'), readFileSync(join(base, '.pi/team/config.sh'), 'utf8'))
|
|
146
|
+
}
|
|
147
|
+
wts[seat] = wt
|
|
148
|
+
}
|
|
149
|
+
return { base, wt: wts[seats[0]], wts, state: join(base, '.pi/team/state') }
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
/** /proc/<pid>/stat 的启动时间指纹(第 22 字段),与扩展同一规则 —— 手写记录要用真指纹。 */
|
|
153
|
+
const procStartTime = pid => {
|
|
154
|
+
try {
|
|
155
|
+
const stat = readFileSync(`/proc/${pid}/stat`, 'utf8')
|
|
156
|
+
const rest = stat.slice(stat.lastIndexOf(')') + 1).trim().split(/\s+/)
|
|
157
|
+
return rest[19] ?? ''
|
|
158
|
+
} catch {
|
|
159
|
+
return ''
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
/** 写一条 `state/bg/<id>.job` 记录(与 team-bg 的记录同形状)。 */
|
|
164
|
+
const writeRecord = (bgDir, id, { pid, pgid = pid, start, cwd = '', log = '', cmd = 'fixture' }) => {
|
|
165
|
+
mkdirSync(bgDir, { recursive: true })
|
|
166
|
+
writeFileSync(join(bgDir, `${id}.job`),
|
|
167
|
+
`id=${id}\npid=${pid}\npgid=${pgid}\nstart=${start}\ncwd=${cwd}\nlog=${log}\ncmd=${cmd}\n`)
|
|
168
|
+
}
|
|
169
|
+
const spawnSleep = (seconds) => {
|
|
170
|
+
const child = spawn('sleep', [String(seconds)], { stdio: 'ignore' })
|
|
171
|
+
trackPid(child.pid)
|
|
172
|
+
return child
|
|
173
|
+
}
|
|
174
|
+
const reapedPid = async () => {
|
|
175
|
+
const child = spawnSleep(0.05)
|
|
176
|
+
const pid = child.pid
|
|
177
|
+
await new Promise(r => child.on('exit', r))
|
|
178
|
+
trackedPids.delete(pid)
|
|
179
|
+
return pid
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
// ── 通知侧驱动 ────────────────────────────────────────────────────────────────
|
|
183
|
+
const newNotify = async () => {
|
|
184
|
+
const mod = await loadModule(resolve(NOTIFY))
|
|
185
|
+
const handlers = {}
|
|
186
|
+
mod.default({
|
|
187
|
+
on: (name, fn) => { (handlers[name] ||= []).push(fn) },
|
|
188
|
+
registerCommand: () => {},
|
|
189
|
+
registerTool: () => {},
|
|
190
|
+
sendMessage: () => {},
|
|
191
|
+
})
|
|
192
|
+
const settled = handlers.agent_settled?.[0]
|
|
193
|
+
if (typeof settled !== 'function') throw new Error('notify 扩展没有注册 agent_settled')
|
|
194
|
+
return {
|
|
195
|
+
settle: (cwd, stopReason, text) => settled({}, {
|
|
196
|
+
cwd,
|
|
197
|
+
sessionManager: { getEntries: () => [{ message: { role: 'assistant', stopReason, content: [{ text }] } }] },
|
|
198
|
+
}),
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
const resetNotify = (base, agent = 'dev') => {
|
|
202
|
+
rmSync(join(base, '.pi/team/state/notify-dedup'), { force: true })
|
|
203
|
+
rmSync(join(base, 'docs/team/inbox', `${agent}.md`), { force: true })
|
|
204
|
+
}
|
|
205
|
+
const inboxLine = (base, agent = 'dev') => {
|
|
206
|
+
const file = join(base, 'docs/team/inbox', `${agent}.md`)
|
|
207
|
+
const lines = existsSync(file) ? readFileSync(file, 'utf8').trim().split('\n').filter(Boolean) : []
|
|
208
|
+
return lines.at(-1) ?? ''
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
// ── wording:注册工具面的挂起口径 ─────────────────────────────────────────────
|
|
212
|
+
const groupWording = async () => {
|
|
213
|
+
const mod = await loadModule(BG)
|
|
214
|
+
const host = newBgHost(mod)
|
|
215
|
+
const R = makeRunner(host, ROOT)
|
|
216
|
+
const receipt = await R.run('echo P230-wording', jobName('wording-receipt'))
|
|
217
|
+
const texts = {
|
|
218
|
+
'team_bg_run.description': String(host.tools.team_bg_run?.description ?? ''),
|
|
219
|
+
'team_bg_run.promptSnippet': String(host.tools.team_bg_run?.promptSnippet ?? ''),
|
|
220
|
+
'team_bg_run.promptGuidelines': (host.tools.team_bg_run?.promptGuidelines ?? []).join(' '),
|
|
221
|
+
'team_bg_run.start-result': receipt.text,
|
|
222
|
+
'team_bg_wait.description': String(host.tools.team_bg_wait?.description ?? ''),
|
|
223
|
+
}
|
|
224
|
+
const hasDefault = t => /end your turn/i.test(t) && /completion wake-up/i.test(t) && /normal harvest point/i.test(t)
|
|
225
|
+
const hasBudget = t => /inline-wait budget/i.test(t) && /2 minutes/.test(t)
|
|
226
|
+
const hasBlocked = t => /blocks your immediate next step/i.test(t)
|
|
227
|
+
const hasExclusive = t => /no other task work/i.test(t)
|
|
228
|
+
const hasException = t => /bounded exception/i.test(t) && hasBudget(t) && hasBlocked(t) && hasExclusive(t)
|
|
229
|
+
|
|
230
|
+
check('wording: team_bg_run description presents the suspend default',
|
|
231
|
+
hasDefault(texts['team_bg_run.description']), texts['team_bg_run.description'].slice(0, 90))
|
|
232
|
+
check('wording: team_bg_run prompt snippet presents the suspend default',
|
|
233
|
+
hasDefault(texts['team_bg_run.promptSnippet']), texts['team_bg_run.promptSnippet'].slice(0, 90))
|
|
234
|
+
check('wording: team_bg_run guidelines present the suspend default and the bounded exception',
|
|
235
|
+
hasDefault(texts['team_bg_run.promptGuidelines']) && hasException(texts['team_bg_run.promptGuidelines']),
|
|
236
|
+
texts['team_bg_run.promptGuidelines'].slice(0, 120))
|
|
237
|
+
check('wording: the start result presents the suspend default and the bounded exception',
|
|
238
|
+
hasDefault(texts['team_bg_run.start-result']) && hasException(texts['team_bg_run.start-result']),
|
|
239
|
+
texts['team_bg_run.start-result'].split('\n').at(-1)?.slice(0, 120) ?? '')
|
|
240
|
+
check('wording: team_bg_wait description names the three exception conditions and the budget',
|
|
241
|
+
hasDefault(texts['team_bg_wait.description']) && hasException(texts['team_bg_wait.description']),
|
|
242
|
+
texts['team_bg_wait.description'].slice(0, 120))
|
|
243
|
+
|
|
244
|
+
// 旧措辞零命中:两个被点名的退休句 + 更宽的「回合结束前必须收割」与「叫醒=损失」形状。
|
|
245
|
+
const retired = [
|
|
246
|
+
'Harvest it with team_bg_wait before you end your turn',
|
|
247
|
+
'harvest every job with team_bg_wait before ending your turn',
|
|
248
|
+
'before you end your turn',
|
|
249
|
+
'before ending your turn',
|
|
250
|
+
'must not end with unharvested',
|
|
251
|
+
'costs a turn',
|
|
252
|
+
]
|
|
253
|
+
const offenders = []
|
|
254
|
+
for (const [name, text] of Object.entries(texts)) {
|
|
255
|
+
for (const phrase of retired) if (text.includes(phrase)) offenders.push(`${name} :: ${phrase}`)
|
|
256
|
+
if (/\b(cost|penalt|loss|waste)/i.test(text)) offenders.push(`${name} :: loss framing`)
|
|
257
|
+
}
|
|
258
|
+
check('wording: the retired duty wording is gone from every registered text',
|
|
259
|
+
offenders.length === 0, offenders.join(' | ') || 'clean')
|
|
260
|
+
|
|
261
|
+
// 完成叫醒:多条合并成一条、点名每个 id、指 team_bg_wait(既有行为,钉住)。
|
|
262
|
+
// 先把回执作业收割掉(否则它会带着自己的叫醒混进下面那条合并消息的窗口)。
|
|
263
|
+
await R.wait(receipt.id, 5000)
|
|
264
|
+
const before = host.sent.length
|
|
265
|
+
const a = await R.run('sleep 0.25; echo WAKE-A', jobName('wording-wake-a'))
|
|
266
|
+
const b = await R.run('sleep 0.3; echo WAKE-B', jobName('wording-wake-b'))
|
|
267
|
+
const named = m => { const s = String(m?.msg?.content ?? ''); return s.includes(a.id) && s.includes(b.id) }
|
|
268
|
+
const woke = await waitFor(() => host.sent.slice(before).some(named), 5000)
|
|
269
|
+
const merged = host.sent.slice(before)
|
|
270
|
+
const body = String(merged[0]?.msg?.content ?? '')
|
|
271
|
+
check('wording: the merged completion wake-up still names both ids and team_bg_wait',
|
|
272
|
+
woke && merged.length === 1 && body.includes(a.id) && body.includes(b.id) && body.includes('team_bg_wait'),
|
|
273
|
+
`messages=${merged.length} ids=${a.id},${b.id} body=${body.split('\n')[0]}`)
|
|
274
|
+
await R.wait(a.id, 5000)
|
|
275
|
+
await R.wait(b.id, 5000)
|
|
276
|
+
await host.emit('session_shutdown', { reason: 'fixture' }, { cwd: ROOT })
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
// ── ledger:state/bg.log 的 start / wait 两类新行 ─────────────────────────────
|
|
280
|
+
const groupLedger = async () => {
|
|
281
|
+
const mod = await loadModule(BG)
|
|
282
|
+
const host = newBgHost(mod)
|
|
283
|
+
const R = makeRunner(host, ROOT)
|
|
284
|
+
const STATE = join(ROOT, '.pi/team/state')
|
|
285
|
+
|
|
286
|
+
// ① start 行与 .job 记录同点位、在返回 id 之前就落盘:作业还在跑(sleep 2)时读盘
|
|
287
|
+
const j1 = await R.run('sleep 2; echo LEDGER-1', jobName('lg-start'))
|
|
288
|
+
const startLine = ledgerFor(STATE, j1.id, 'start')
|
|
289
|
+
check('ledger: the start line lands on disk before the id is returned',
|
|
290
|
+
!!startLine && new RegExp(` start id=${escapeRe(j1.id)} pid=${j1.pid}$`).test(startLine) &&
|
|
291
|
+
existsSync(join(STATE, 'bg', `${j1.id}.job`)),
|
|
292
|
+
startLine || '(no start line)')
|
|
293
|
+
await R.wait(j1.id, 5000)
|
|
294
|
+
|
|
295
|
+
// ② 原地收割:wait 行量的是这次调用(≈ 作业运行时长)
|
|
296
|
+
const j2 = await R.run('sleep 1.1; echo LEDGER-2', jobName('lg-inline'))
|
|
297
|
+
await R.wait(j2.id, 5000)
|
|
298
|
+
const w2 = ledgerFor(STATE, j2.id, 'wait')
|
|
299
|
+
const s2 = waitedOf(w2)
|
|
300
|
+
check('ledger: an inline harvest records a wait line tracking the job runtime',
|
|
301
|
+
/ outcome=harvested /.test(w2) && s2 >= 0.7 && s2 <= 2.5, w2 || '(no wait line)')
|
|
302
|
+
const inlineSettled = ledgerLines(STATE).some(l => / settled-with-unharvested=\d/.test(l) && l.includes(j2.id))
|
|
303
|
+
check('ledger: the inline pattern has no suspension line naming it', !inlineSettled,
|
|
304
|
+
ledgerLines(STATE).filter(l => l.includes(j2.id)).join(' | '))
|
|
305
|
+
|
|
306
|
+
// ③ 超时:outcome=running,且作业没有因此被标成已收割(完成后照常叫醒)
|
|
307
|
+
const j3 = await R.run('sleep 1.0; echo LEDGER-3', jobName('lg-timeout'))
|
|
308
|
+
const timeoutText = await R.wait(j3.id, 250)
|
|
309
|
+
const w3 = ledgerFor(STATE, j3.id, 'wait')
|
|
310
|
+
const s3 = waitedOf(w3)
|
|
311
|
+
check('ledger: a timed-out wait records outcome=running with this call’s own wait',
|
|
312
|
+
/ outcome=running /.test(w3) && s3 >= 0.1 && s3 <= 0.8 && /still running/.test(timeoutText), w3 || '(no wait line)')
|
|
313
|
+
const beforeWake3 = host.sent.length
|
|
314
|
+
const woke3 = await waitFor(() => host.sent.slice(beforeWake3).some(m => String(m.msg?.content ?? '').includes(j3.id)), 5000)
|
|
315
|
+
check('ledger: a timed-out wait leaves the job unharvested (it still wakes)',
|
|
316
|
+
woke3, `wakes=${host.sent.length - beforeWake3}`)
|
|
317
|
+
await R.wait(j3.id, 5000)
|
|
318
|
+
|
|
319
|
+
// ④ 中止(AbortSignal):outcome=interrupted,同样不标收割
|
|
320
|
+
const j4 = await R.run('sleep 1.2; echo LEDGER-4', jobName('lg-abort'))
|
|
321
|
+
const ac = new AbortController()
|
|
322
|
+
setTimeout(() => ac.abort(), 200)
|
|
323
|
+
const abortText = await R.wait(j4.id, undefined, ac.signal)
|
|
324
|
+
const w4 = ledgerFor(STATE, j4.id, 'wait')
|
|
325
|
+
const s4 = waitedOf(w4)
|
|
326
|
+
check('ledger: an aborted wait records outcome=interrupted with this call’s own wait',
|
|
327
|
+
/ outcome=interrupted /.test(w4) && s4 >= 0.05 && s4 <= 1.0, w4 || '(no wait line)')
|
|
328
|
+
const beforeWake4 = host.sent.length
|
|
329
|
+
const woke4 = await waitFor(() => host.sent.slice(beforeWake4).some(m => String(m.msg?.content ?? '').includes(j4.id)), 5000)
|
|
330
|
+
check('ledger: an aborted wait leaves the job unharvested (it still wakes)',
|
|
331
|
+
woke4, `wakes=${host.sent.length - beforeWake4} abort="${abortText.split('\n')[0]}"`)
|
|
332
|
+
await R.wait(j4.id, 5000)
|
|
333
|
+
|
|
334
|
+
// ⑤ 挂起:start → settled-with-unharvested(点名该 id)→ wake(点名该 id)→ wait(waited_s≈0)
|
|
335
|
+
const beforeWake5 = host.sent.length
|
|
336
|
+
const j5 = await R.run('sleep 0.6; echo LEDGER-5', jobName('lg-suspend'))
|
|
337
|
+
await host.emit('agent_settled', {}, { cwd: ROOT })
|
|
338
|
+
const settled = ledgerLines(STATE)
|
|
339
|
+
.filter(l => / settled-with-unharvested=\d/.test(l) && l.includes(j5.id)).at(-1) ?? ''
|
|
340
|
+
const woke5 = await waitFor(() => host.sent.slice(beforeWake5).some(m => String(m.msg?.content ?? '').includes(j5.id)), 5000)
|
|
341
|
+
const wakeLine = ledgerLines(STATE).filter(l => / wake count=/.test(l)).at(-1) ?? ''
|
|
342
|
+
await R.wait(j5.id, 5000)
|
|
343
|
+
const w5 = ledgerFor(STATE, j5.id, 'wait')
|
|
344
|
+
const s5 = waitedOf(w5)
|
|
345
|
+
const lines = ledgerLines(STATE)
|
|
346
|
+
const iStart = lines.findIndex(l => new RegExp(` start id=${escapeRe(j5.id)}( |$)`).test(l))
|
|
347
|
+
const iSettled = lines.findIndex(l => new RegExp(` settled-with-unharvested=1 jobs=${escapeRe(j5.id)}:running`).test(l))
|
|
348
|
+
const iWait = lines.findIndex(l => new RegExp(` wait id=${escapeRe(j5.id)}( |$)`).test(l))
|
|
349
|
+
check('ledger: a suspension is distinguishable from an inline wait from the ledger alone',
|
|
350
|
+
woke5 && !!settled && wakeLine.includes(j5.id) && / outcome=harvested /.test(w5) &&
|
|
351
|
+
s5 >= 0 && s5 < 0.4 && iStart >= 0 && iStart < iSettled && iSettled < iWait && s2 >= 0.7,
|
|
352
|
+
`settled=[${settled}] wake=[${wakeLine}] wait=[${w5}] inline_wait=${s2}s suspend_wait=${s5}s`)
|
|
353
|
+
|
|
354
|
+
// ⑥ 既有行形状不变(wake / settled-with-unharvested);start / wait 是这里新增的两类
|
|
355
|
+
const iso = '\\d{4}-\\d{2}-\\d{2}T[\\d:.]+Z'
|
|
356
|
+
check('ledger: the wake line keeps its shape',
|
|
357
|
+
lines.some(l => new RegExp(`^${iso} wake count=\\d+ ids=[A-Za-z0-9._,-]+$`).test(l)),
|
|
358
|
+
lines.find(l => / wake /.test(l)) ?? '(none)')
|
|
359
|
+
check('ledger: the settled line keeps its shape',
|
|
360
|
+
lines.some(l => new RegExp(`^${iso} settled-with-unharvested=\\d+( jobs=[A-Za-z0-9._,-:]+)?$`).test(l)),
|
|
361
|
+
lines.find(l => / settled-with-unharvested=\d/.test(l)) ?? '(none)')
|
|
362
|
+
const newLines = lines.filter(l => / (start|wait) /.test(l))
|
|
363
|
+
check('ledger: the start and wait lines have the documented shape',
|
|
364
|
+
newLines.length >= 8 && newLines.every(l =>
|
|
365
|
+
new RegExp(`^${iso} start id=[A-Za-z0-9._-]+ pid=\\d+$`).test(l) ||
|
|
366
|
+
new RegExp(`^${iso} wait id=[A-Za-z0-9._-]+ outcome=(harvested|running|interrupted) waited_s=\\d+(\\.\\d+)?$`).test(l)),
|
|
367
|
+
newLines.slice(0, 3).join(' | '))
|
|
368
|
+
|
|
369
|
+
// ⑦ spawn-error 行形状不变(既有形状,逐字节):PATH 里只留 git(findRoot 还要用它),没有 bash
|
|
370
|
+
{
|
|
371
|
+
const fakeBin = join(SCRATCH, 'fake-bin')
|
|
372
|
+
rmSync(fakeBin, { recursive: true, force: true })
|
|
373
|
+
mkdirSync(fakeBin, { recursive: true })
|
|
374
|
+
symlinkSync(execFileSync('bash', ['-c', 'command -v git'], { encoding: 'utf8' }).trim(), join(fakeBin, 'git'))
|
|
375
|
+
const savedPath = process.env.PATH
|
|
376
|
+
process.env.PATH = fakeBin
|
|
377
|
+
let badJob
|
|
378
|
+
try {
|
|
379
|
+
badJob = await R.run('true', jobName('lg-spawn-error'))
|
|
380
|
+
} finally {
|
|
381
|
+
process.env.PATH = savedPath
|
|
382
|
+
}
|
|
383
|
+
const want = new RegExp(` spawn-error id=${escapeRe(badJob.id)} `)
|
|
384
|
+
await waitFor(() => ledgerLines(STATE).some(l => want.test(l)), 3000)
|
|
385
|
+
const spawnLine = ledgerLines(STATE).find(l => want.test(l)) ?? ''
|
|
386
|
+
check('ledger: the spawn-error line keeps its shape (and a failed spawn records no start)',
|
|
387
|
+
!!spawnLine && new RegExp(`^${iso} spawn-error id=${escapeRe(badJob.id)} \\S`).test(spawnLine) &&
|
|
388
|
+
!ledgerLines(STATE).some(l => new RegExp(` start id=${escapeRe(badJob.id)}( |$)`).test(l)),
|
|
389
|
+
spawnLine || '(no spawn-error line)')
|
|
390
|
+
}
|
|
391
|
+
|
|
392
|
+
// ⑧ 重启(会话级 job 表):新会话拒绝旧 id、不收养、不剪记录;作业本身不受影响
|
|
393
|
+
{
|
|
394
|
+
const j8 = await R.run('sleep 2.5; echo RESTART-EVIDENCE', jobName('lg-restart'))
|
|
395
|
+
const record = join(STATE, 'bg', `${j8.id}.job`)
|
|
396
|
+
const logFile = join(STATE, 'bg', `${j8.id}.log`)
|
|
397
|
+
const host2 = newBgHost(await loadModule(BG))
|
|
398
|
+
await host2.emit('session_start', { reason: 'restart' }, { cwd: ROOT })
|
|
399
|
+
const R2 = makeRunner(host2, ROOT)
|
|
400
|
+
let errText = ''
|
|
401
|
+
try { await R2.wait(j8.id, 0) } catch (error) { errText = String(error?.message ?? error) }
|
|
402
|
+
let alive = false
|
|
403
|
+
try { process.kill(j8.pid, 0); alive = true } catch { /* 作业已经不在 */ }
|
|
404
|
+
check('ledger: a restarted session refuses the old id and keeps the evidence',
|
|
405
|
+
/unknown job/.test(errText) && /started: \(none\)/.test(errText) &&
|
|
406
|
+
existsSync(record) && existsSync(logFile) && alive,
|
|
407
|
+
`err=${errText.slice(0, 80)} record=${existsSync(record)} log=${existsSync(logFile)} alive=${alive}`)
|
|
408
|
+
const own = await R2.run('echo NEW-SESSION', jobName('lg-restart-own'))
|
|
409
|
+
await R2.wait(own.id, 3000)
|
|
410
|
+
await host2.emit('agent_settled', {}, { cwd: ROOT })
|
|
411
|
+
const adopted = host2.sent.some(m => String(m.msg?.content ?? '').includes(j8.id))
|
|
412
|
+
check('ledger: a restarted session neither re-adopts nor prunes the old records',
|
|
413
|
+
!adopted && existsSync(record) && existsSync(logFile),
|
|
414
|
+
`adopted=${adopted} record=${existsSync(record)} log=${existsSync(logFile)}`)
|
|
415
|
+
await host2.emit('session_shutdown', { reason: 'fixture' }, { cwd: ROOT })
|
|
416
|
+
await R.wait(j8.id, 5000)
|
|
417
|
+
}
|
|
418
|
+
await host.emit('session_shutdown', { reason: 'fixture' }, { cwd: ROOT })
|
|
419
|
+
}
|
|
420
|
+
|
|
421
|
+
// ── suspend-shape:turn-end 通知的挂起判定 ────────────────────────────────────
|
|
422
|
+
const groupSuspendShape = async () => {
|
|
423
|
+
const bgMod = await loadModule(BG)
|
|
424
|
+
const bgHost = newBgHost(bgMod)
|
|
425
|
+
const notify = await newNotify()
|
|
426
|
+
const jobs = []
|
|
427
|
+
|
|
428
|
+
// ① 完成 + 活记录(真作业真记录)→ suspended + awaiting + 省略 ⚠ + 保留 uncommitted
|
|
429
|
+
{
|
|
430
|
+
const b = makeBase('suspend')
|
|
431
|
+
const R = makeRunner(bgHost, b.wt)
|
|
432
|
+
const job = await R.run('sleep 30', jobName('sus-live'))
|
|
433
|
+
jobs.push([R, job])
|
|
434
|
+
resetNotify(b.base)
|
|
435
|
+
await notify.settle(b.wt, 'stop', 'BG-LEDGER-SUSPEND completed turn parked on the job')
|
|
436
|
+
const line = inboxLine(b.base)
|
|
437
|
+
check('suspend: a completed turn with a live job record is tagged suspended',
|
|
438
|
+
line.includes('[auto·suspended]') && line.includes(`awaiting=${job.id}`) &&
|
|
439
|
+
/uncommitted=[1-9]/.test(line) && !line.includes('⚠ 未提交'),
|
|
440
|
+
line || '(no inbox line)')
|
|
441
|
+
}
|
|
442
|
+
|
|
443
|
+
// ② 完成 + 无记录 → 今天的形状逐字节不变([auto] + 脏树告警、无 awaiting)
|
|
444
|
+
{
|
|
445
|
+
const b = makeBase('clean')
|
|
446
|
+
resetNotify(b.base)
|
|
447
|
+
await notify.settle(b.wt, 'stop', 'BG-LEDGER-CLEAN completed turn with nothing running')
|
|
448
|
+
const line = inboxLine(b.base)
|
|
449
|
+
check('suspend: a completed turn with no running jobs stays in today’s shape',
|
|
450
|
+
line.includes('[auto] ') && !line.includes('awaiting=') && line.includes('⚠ 未提交'),
|
|
451
|
+
line || '(no inbox line)')
|
|
452
|
+
}
|
|
453
|
+
|
|
454
|
+
// ③ 死 pid → 不挂起
|
|
455
|
+
{
|
|
456
|
+
const b = makeBase('dead')
|
|
457
|
+
const pid = await reapedPid()
|
|
458
|
+
// cwd 指到本会话的工作树:本用例判的只是身份指纹(不让归属判据替它挡枪),
|
|
459
|
+
// 否则「去掉身份验证」的翻转会被归属判据掩盖而不再变红(P236 实测)。
|
|
460
|
+
writeRecord(join(b.state, 'bg'), 'bg-ledger-dead', { pid, pgid: pid, start: '1', cwd: b.wt })
|
|
461
|
+
resetNotify(b.base)
|
|
462
|
+
await notify.settle(b.wt, 'stop', 'BG-LEDGER-DEAD dead pid must not suspend')
|
|
463
|
+
const line = inboxLine(b.base)
|
|
464
|
+
check('suspend: a dead pid does not suspend',
|
|
465
|
+
line.includes('[auto] ') && !line.includes('awaiting=') && line.includes('⚠ 未提交'),
|
|
466
|
+
line || '(no inbox line)')
|
|
467
|
+
}
|
|
468
|
+
|
|
469
|
+
// ④ pid 复用(活着但启动指纹对不上)→ 不挂起
|
|
470
|
+
{
|
|
471
|
+
const b = makeBase('reused')
|
|
472
|
+
const sleeper = spawnSleep(30)
|
|
473
|
+
writeRecord(join(b.state, 'bg'), 'bg-ledger-reused', { pid: sleeper.pid, pgid: sleeper.pid, start: '1', cwd: b.wt })
|
|
474
|
+
resetNotify(b.base)
|
|
475
|
+
await notify.settle(b.wt, 'stop', 'BG-LEDGER-REUSED reused pid must not suspend')
|
|
476
|
+
const line = inboxLine(b.base)
|
|
477
|
+
check('suspend: a reused pid (fingerprint mismatch) does not suspend',
|
|
478
|
+
line.includes('[auto] ') && !line.includes('awaiting=') && line.includes('⚠ 未提交'),
|
|
479
|
+
line || '(no inbox line)')
|
|
480
|
+
try { process.kill(sleeper.pid, 'SIGKILL') } catch { /* ignore */ }
|
|
481
|
+
}
|
|
482
|
+
|
|
483
|
+
// ⑤ 畸形 / 不可读记录(非数字 pid、缺 start、目录、软链)→ 都不算在跑
|
|
484
|
+
{
|
|
485
|
+
const b = makeBase('malformed')
|
|
486
|
+
const sleeper = spawnSleep(30)
|
|
487
|
+
const bgDir = join(b.state, 'bg')
|
|
488
|
+
writeRecord(bgDir, 'bg-ledger-badpid', { pid: 'abc', pgid: '1', start: '1' })
|
|
489
|
+
writeFileSync(join(bgDir, 'bg-ledger-nostart.job'),
|
|
490
|
+
`id=bg-ledger-nostart\npid=${sleeper.pid}\npgid=${sleeper.pid}\ncwd=\nlog=\ncmd=fixture\n`)
|
|
491
|
+
mkdirSync(join(bgDir, 'bg-ledger-dir.job'), { recursive: true })
|
|
492
|
+
const target = join(bgDir, 'bg-ledger-link-target')
|
|
493
|
+
writeFileSync(target, `id=bg-ledger-link-target\npid=${sleeper.pid}\npgid=${sleeper.pid}\nstart=1\ncwd=\nlog=\ncmd=fixture\n`)
|
|
494
|
+
symlinkSync(target, join(bgDir, 'bg-ledger-link.job'))
|
|
495
|
+
resetNotify(b.base)
|
|
496
|
+
await notify.settle(b.wt, 'stop', 'BG-LEDGER-MALFORMED malformed records must not suspend')
|
|
497
|
+
const line = inboxLine(b.base)
|
|
498
|
+
check('suspend: an unreadable or malformed record does not suspend',
|
|
499
|
+
line.includes('[auto] ') && !line.includes('awaiting=') && line.includes('⚠ 未提交'),
|
|
500
|
+
line || '(no inbox line)')
|
|
501
|
+
try { process.kill(sleeper.pid, 'SIGKILL') } catch { /* ignore */ }
|
|
502
|
+
}
|
|
503
|
+
|
|
504
|
+
// ⑥ 中断 + 活记录 → 保持 [auto·interrupted] 且带 awaiting=
|
|
505
|
+
{
|
|
506
|
+
const b = makeBase('interrupted')
|
|
507
|
+
const R = makeRunner(bgHost, b.wt)
|
|
508
|
+
const job = await R.run('sleep 30', jobName('int-live'))
|
|
509
|
+
jobs.push([R, job])
|
|
510
|
+
resetNotify(b.base)
|
|
511
|
+
await notify.settle(b.wt, 'toolUse', 'BG-LEDGER-INTERRUPTED incomplete turn with a running job')
|
|
512
|
+
const line = inboxLine(b.base)
|
|
513
|
+
check('suspend: an interrupted turn with a running job keeps the interrupted tag and names it',
|
|
514
|
+
line.includes('[auto·interrupted]') && line.includes(`awaiting=${job.id}`),
|
|
515
|
+
line || '(no inbox line)')
|
|
516
|
+
}
|
|
517
|
+
|
|
518
|
+
// ⑦ worktree 自带 config → 用车道自己的目录;主工作树的活诱饵不算
|
|
519
|
+
{
|
|
520
|
+
const b = makeBase('wtown', { ownConfigInWorktree: true })
|
|
521
|
+
const own = await makeRunner(bgHost, b.wt).run('sleep 30', jobName('own-worktree'))
|
|
522
|
+
const decoy = await makeRunner(bgHost, b.base).run('sleep 30', jobName('decoy-main'))
|
|
523
|
+
jobs.push([makeRunner(bgHost, b.wt), own], [makeRunner(bgHost, b.base), decoy])
|
|
524
|
+
check('suspend: fixture — the linked worktree carries its own config',
|
|
525
|
+
existsSync(join(b.wt, '.pi/team/config.sh')) &&
|
|
526
|
+
existsSync(join(b.wt, '.pi/team/state/bg', `${own.id}.job`)) &&
|
|
527
|
+
existsSync(join(b.state, 'bg', `${decoy.id}.job`)),
|
|
528
|
+
`wt=${b.wt}`)
|
|
529
|
+
resetNotify(b.base)
|
|
530
|
+
await notify.settle(b.wt, 'stop', 'BG-LEDGER-WTOWN worktree-with-config lane records')
|
|
531
|
+
const line = inboxLine(b.base)
|
|
532
|
+
check('suspend: a worktree carrying its own config uses its own lane records',
|
|
533
|
+
line.includes('[auto·suspended]') && line.includes(`awaiting=${own.id}`) && !line.includes(decoy.id),
|
|
534
|
+
line || '(no inbox line)')
|
|
535
|
+
}
|
|
536
|
+
|
|
537
|
+
// ⑧ 显式 TEAM_STATE_DIR → 就是车道目录;notify 自己 root 下的活诱饵不算
|
|
538
|
+
{
|
|
539
|
+
const b = makeBase('statedir')
|
|
540
|
+
const lane = join(SCRATCH, 'statedir-lane')
|
|
541
|
+
rmSync(lane, { recursive: true, force: true })
|
|
542
|
+
process.env.TEAM_STATE_DIR = lane
|
|
543
|
+
let own
|
|
544
|
+
try { own = await makeRunner(bgHost, b.wt).run('sleep 30', jobName('own-statedir')) } finally { delete process.env.TEAM_STATE_DIR }
|
|
545
|
+
const decoy = await makeRunner(bgHost, b.base).run('sleep 30', jobName('decoy-statedir'))
|
|
546
|
+
jobs.push([makeRunner(bgHost, b.wt), own], [makeRunner(bgHost, b.base), decoy])
|
|
547
|
+
check('suspend: fixture — the explicit state directory holds the lane record',
|
|
548
|
+
existsSync(join(lane, 'bg', `${own.id}.job`)) && existsSync(join(b.state, 'bg', `${decoy.id}.job`)),
|
|
549
|
+
`lane=${lane}`)
|
|
550
|
+
resetNotify(b.base)
|
|
551
|
+
process.env.TEAM_STATE_DIR = lane
|
|
552
|
+
try { await notify.settle(b.wt, 'stop', 'BG-LEDGER-STATEDIR explicit state directory') } finally { delete process.env.TEAM_STATE_DIR }
|
|
553
|
+
const line = inboxLine(b.base)
|
|
554
|
+
check('suspend: an explicit TEAM_STATE_DIR is the lane’s directory',
|
|
555
|
+
line.includes('[auto·suspended]') && line.includes(`awaiting=${own.id}`) && !line.includes(decoy.id),
|
|
556
|
+
line || '(no inbox line)')
|
|
557
|
+
}
|
|
558
|
+
|
|
559
|
+
// 收尾:只按登记过的作业停(kill + 收割),然后清掉扩展的会话资源
|
|
560
|
+
for (const [R, job] of jobs) await R.stop(job)
|
|
561
|
+
await bgHost.emit('session_shutdown', { reason: 'fixture' }, { cwd: ROOT })
|
|
562
|
+
}
|
|
563
|
+
|
|
564
|
+
// ── owner-scope:挂起判定只认**本会话自己的**作业(P236)────────────────────────
|
|
565
|
+
// 缺陷现场(2026-10-12 真实运行):两个席位共享同一个车道 state 目录,dev 的作业躺在里面,
|
|
566
|
+
// dev2 结束回合时被打上 awaiting=<dev 的作业>。归属判据 = 记录里的 cwd(作业启动时的工作目录,
|
|
567
|
+
// 也就是拥有它的那个席位的工作树)与本会话自己的工作树/cwd 解析到同一个真实路径;别人的记录、
|
|
568
|
+
// 缺 cwd / 相对 cwd / 解析不出来的畸形记录一律不算(fail-closed)。
|
|
569
|
+
const groupOwnerScope = async () => {
|
|
570
|
+
const bgMod = await loadModule(BG)
|
|
571
|
+
const bgHost = newBgHost(bgMod)
|
|
572
|
+
const notify = await newNotify()
|
|
573
|
+
const jobs = []
|
|
574
|
+
|
|
575
|
+
// ① 三个席位各有自己的活作业:各自只认自己的 id(另外两个席位的作业既不入 awaiting 也不改标签)
|
|
576
|
+
{
|
|
577
|
+
const b = makeBase('owner-two', { seats: ['dev', 'dev2', 'dev3'] })
|
|
578
|
+
const seats = ['dev', 'dev2', 'dev3']
|
|
579
|
+
const tag = { dev: 'own-a', dev2: 'own-b', dev3: 'own-c' } // 后缀互不为前缀(否则子串断言会互相命中)
|
|
580
|
+
const own = {}
|
|
581
|
+
for (const seat of seats) {
|
|
582
|
+
const R = makeRunner(bgHost, b.wts[seat])
|
|
583
|
+
own[seat] = await R.run('sleep 30', jobName(tag[seat]))
|
|
584
|
+
jobs.push([R, own[seat]])
|
|
585
|
+
resetNotify(b.base, seat)
|
|
586
|
+
}
|
|
587
|
+
for (const seat of seats) {
|
|
588
|
+
await notify.settle(b.wts[seat], 'stop', `BG-LEDGER-OWNER-THREE ${seat} settles with its own job`)
|
|
589
|
+
const line = inboxLine(b.base, seat)
|
|
590
|
+
const others = seats.filter(s => s !== seat).map(s => own[s].id)
|
|
591
|
+
check(`owner-scope: each seat suspends on its own job only (${seat})`,
|
|
592
|
+
line.includes('[auto·suspended]') && line.includes(`awaiting=${own[seat].id}`) && others.every(id => !line.includes(id)),
|
|
593
|
+
line || '(no inbox line)')
|
|
594
|
+
}
|
|
595
|
+
}
|
|
596
|
+
|
|
597
|
+
// ② 只有一个席位有作业:**另外两个席位**(dev2、dev3)都不得出现 awaiting= / suspended
|
|
598
|
+
// (PM 在真实运行里两处都看到了:PM 2026-10-12 追加,dev3 的回合同样带着 dev 的 awaiting=)
|
|
599
|
+
{
|
|
600
|
+
const b = makeBase('owner-idle', { seats: ['dev', 'dev2', 'dev3'] })
|
|
601
|
+
const rDev = makeRunner(bgHost, b.wt)
|
|
602
|
+
const jDev = await rDev.run('sleep 30', jobName('own-busy'))
|
|
603
|
+
jobs.push([rDev, jDev])
|
|
604
|
+
for (const seat of ['dev2', 'dev3']) {
|
|
605
|
+
resetNotify(b.base, seat)
|
|
606
|
+
await notify.settle(b.wts[seat], 'stop', `BG-LEDGER-OWNER-IDLE ${seat} must not inherit the busy seat’s job`)
|
|
607
|
+
const line = inboxLine(b.base, seat)
|
|
608
|
+
check(`owner-scope: a seat with no job of its own is not suspended by another seat’s job (${seat})`,
|
|
609
|
+
line.includes('[auto] ') && !line.includes('awaiting=') && !line.includes('suspended') && line.includes('⚠ 未提交'),
|
|
610
|
+
line || '(no inbox line)')
|
|
611
|
+
}
|
|
612
|
+
}
|
|
613
|
+
|
|
614
|
+
// ③ 活 pid 的畸形记录:缺 cwd / 相对 cwd / 解析不出来的 cwd → 都不判挂起(fail-closed)
|
|
615
|
+
{
|
|
616
|
+
const b = makeBase('owner-nocwd')
|
|
617
|
+
const sleeper = spawnSleep(30)
|
|
618
|
+
const start = procStartTime(sleeper.pid)
|
|
619
|
+
const bgDir = join(b.state, 'bg')
|
|
620
|
+
mkdirSync(bgDir, { recursive: true })
|
|
621
|
+
writeFileSync(join(bgDir, 'bg-ledger-nocwd.job'),
|
|
622
|
+
`id=bg-ledger-nocwd\npid=${sleeper.pid}\npgid=${sleeper.pid}\nstart=${start}\nlog=\ncmd=fixture\n`)
|
|
623
|
+
writeRecord(bgDir, 'bg-ledger-relcwd', { pid: sleeper.pid, pgid: sleeper.pid, start, cwd: '.worktrees/dev' })
|
|
624
|
+
writeRecord(bgDir, 'bg-ledger-gonecwd', { pid: sleeper.pid, pgid: sleeper.pid, start, cwd: '/nonexistent/p236/worktree' })
|
|
625
|
+
resetNotify(b.base)
|
|
626
|
+
await notify.settle(b.wt, 'stop', 'BG-LEDGER-NOCWD records without an owning cwd must not suspend')
|
|
627
|
+
const line = inboxLine(b.base)
|
|
628
|
+
check('owner-scope: a live record with a missing, relative or unresolvable cwd does not suspend (fail-closed)',
|
|
629
|
+
line.includes('[auto] ') && !line.includes('awaiting=') && line.includes('⚠ 未提交'),
|
|
630
|
+
line || '(no inbox line)')
|
|
631
|
+
try { process.kill(sleeper.pid, 'SIGKILL') } catch { /* ignore */ }
|
|
632
|
+
}
|
|
633
|
+
|
|
634
|
+
// ④ 软链 + 尾斜杠:记录里的 cwd 文本不同、真实路径相同 → 仍然是本会话的作业(挂起)
|
|
635
|
+
{
|
|
636
|
+
const b = makeBase('owner-realpath')
|
|
637
|
+
const sleeper = spawnSleep(30)
|
|
638
|
+
const link = join(b.base, 'link-to-dev')
|
|
639
|
+
symlinkSync(b.wt, link)
|
|
640
|
+
writeRecord(join(b.state, 'bg'), 'bg-ledger-symlink', {
|
|
641
|
+
pid: sleeper.pid, pgid: sleeper.pid, start: procStartTime(sleeper.pid), cwd: `${link}/`,
|
|
642
|
+
})
|
|
643
|
+
resetNotify(b.base)
|
|
644
|
+
await notify.settle(b.wt, 'stop', 'BG-LEDGER-REALPATH symlink and trailing slash resolve to the seat worktree')
|
|
645
|
+
const line = inboxLine(b.base)
|
|
646
|
+
check('owner-scope: a job cwd reaching the session worktree through a symlink still belongs to it',
|
|
647
|
+
line.includes('[auto·suspended]') && line.includes('awaiting=bg-ledger-symlink'),
|
|
648
|
+
line || '(no inbox line)')
|
|
649
|
+
try { process.kill(sleeper.pid, 'SIGKILL') } catch { /* ignore */ }
|
|
650
|
+
}
|
|
651
|
+
|
|
652
|
+
// ⑤ 主工作树里起的作业(不属于任何席位工作树)→ 席位不判挂起
|
|
653
|
+
{
|
|
654
|
+
const b = makeBase('owner-main')
|
|
655
|
+
const rMain = makeRunner(bgHost, b.base)
|
|
656
|
+
const jMain = await rMain.run('sleep 30', jobName('own-main'))
|
|
657
|
+
jobs.push([rMain, jMain])
|
|
658
|
+
resetNotify(b.base)
|
|
659
|
+
await notify.settle(b.wt, 'stop', 'BG-LEDGER-MAINJOB a main-worktree job must not suspend a seat')
|
|
660
|
+
const line = inboxLine(b.base)
|
|
661
|
+
check('owner-scope: a job started from the main worktree does not suspend a seat',
|
|
662
|
+
line.includes('[auto] ') && !line.includes('awaiting=') && line.includes('⚠ 未提交'),
|
|
663
|
+
line || '(no inbox line)')
|
|
664
|
+
}
|
|
665
|
+
|
|
666
|
+
// 收尾:只按登记过的作业停(kill + 收割),然后清掉扩展的会话资源
|
|
667
|
+
for (const [R, job] of jobs) await R.stop(job)
|
|
668
|
+
await bgHost.emit('session_shutdown', { reason: 'fixture' }, { cwd: ROOT })
|
|
669
|
+
}
|
|
670
|
+
|
|
671
|
+
// ── 主流程 ────────────────────────────────────────────────────────────────────
|
|
672
|
+
console.log(`bg-ledger-harness · root=${ROOT} · groups=${[...GROUPS].join(',')} · bg=${BG} · notify=${NOTIFY}`)
|
|
673
|
+
try {
|
|
674
|
+
if (GROUPS.has('wording')) await groupWording()
|
|
675
|
+
if (GROUPS.has('ledger')) await groupLedger()
|
|
676
|
+
if (GROUPS.has('suspend-shape')) await groupSuspendShape()
|
|
677
|
+
if (GROUPS.has('owner-scope')) await groupOwnerScope()
|
|
678
|
+
} catch (error) {
|
|
679
|
+
check('harness: no unexpected exception', false, String(error?.stack ?? error).split('\n').slice(0, 3).join(' / '))
|
|
680
|
+
}
|
|
681
|
+
console.log(failures === 0 ? 'BG-LEDGER-HARNESS OK' : `BG-LEDGER-HARNESS FAIL (${failures})`)
|
|
682
|
+
process.exit(failures === 0 ? 0 : 1)
|