teamsmith 0.3.4 → 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.
Files changed (68) hide show
  1. package/README.md +8 -8
  2. package/package.json +1 -1
  3. package/skills/teamsmith/CHANGELOG.md +30 -0
  4. package/skills/teamsmith/SKILL.md +83 -163
  5. package/skills/teamsmith/extension/team-notify.ts +1 -1
  6. package/skills/teamsmith/extension/team-reply.ts +105 -0
  7. package/skills/teamsmith/references/agent-adapters.md +1 -1
  8. package/skills/teamsmith/references/config.md +20 -11
  9. package/skills/teamsmith/references/migration.md +47 -3
  10. package/skills/teamsmith/references/protocol.md +64 -31
  11. package/skills/teamsmith/references/reminders.md +131 -0
  12. package/skills/teamsmith/references/troubleshooting.md +19 -5
  13. package/skills/teamsmith/references/workflows.md +18 -16
  14. package/skills/teamsmith/scripts/lib/cmd-agents.sh +77 -49
  15. package/skills/teamsmith/scripts/lib/cmd-project.sh +193 -21
  16. package/skills/teamsmith/scripts/lib/cmd-remind.sh +103 -0
  17. package/skills/teamsmith/scripts/lib/cmd-update.sh +7 -4
  18. package/skills/teamsmith/scripts/lib/common.sh +44 -4
  19. package/skills/teamsmith/scripts/lib/outbox.sh +72 -18
  20. package/skills/teamsmith/scripts/remind-store.mjs +529 -0
  21. package/skills/teamsmith/scripts/replies.mjs +9 -3
  22. package/skills/teamsmith/scripts/reply-capture.mjs +596 -0
  23. package/skills/teamsmith/scripts/state-authority.mjs +500 -0
  24. package/skills/teamsmith/scripts/strings/commands.tsv +2 -1
  25. package/skills/teamsmith/scripts/strings/help.en.tsv +16 -2
  26. package/skills/teamsmith/scripts/strings/help.zh.tsv +16 -2
  27. package/skills/teamsmith/scripts/team +1 -0
  28. package/skills/teamsmith/templates/AGENTS.section.md.tmpl +68 -123
  29. package/skills/teamsmith/templates/PROTOCOL.md.tmpl +48 -55
  30. package/skills/teamsmith/templates/pm-prompt.md.tmpl +126 -119
  31. package/skills/teamsmith/tests/checkout-shape-probe.sh +6 -5
  32. package/skills/teamsmith/tests/delivery-truth.sh +82 -47
  33. package/skills/teamsmith/tests/fixtures/delivery-truth-real/README.md +71 -23
  34. package/skills/teamsmith/tests/fixtures/delivery-truth-real/__pycache__/judge-second.cpython-313.pyc +0 -0
  35. package/skills/teamsmith/tests/fixtures/delivery-truth-real/judge-dirty-ab.py +143 -0
  36. package/skills/teamsmith/tests/fixtures/delivery-truth-real/judge-second.py +26 -9
  37. package/skills/teamsmith/tests/fixtures/delivery-truth-real/run-case.sh +92 -20
  38. package/skills/teamsmith/tests/fixtures/delivery-truth-real/scenario.sh +47 -3
  39. package/skills/teamsmith/tests/fixtures/reply-capture-provider.ts +76 -0
  40. package/skills/teamsmith/tests/flip-p410-order2.sh +205 -0
  41. package/skills/teamsmith/tests/frames/README.md +3 -1
  42. package/skills/teamsmith/tests/gate-guard.sh +20 -4
  43. package/skills/teamsmith/tests/help-surface.sh +60 -2
  44. package/skills/teamsmith/tests/install-shape.sh +312 -0
  45. package/skills/teamsmith/tests/key-replies-pty.sh +197 -21
  46. package/skills/teamsmith/tests/key-replies.sh +187 -68
  47. package/skills/teamsmith/tests/ledger-claim.sh +8 -6
  48. package/skills/teamsmith/tests/lib/box-judge.sh +2 -1
  49. package/skills/teamsmith/tests/lib/main-team-fingerprint.sh +104 -0
  50. package/skills/teamsmith/tests/lib/pm-window.sh +127 -0
  51. package/skills/teamsmith/tests/lib/reply-fixture.sh +7 -19
  52. package/skills/teamsmith/tests/lib/reply-guard.sh +188 -0
  53. package/skills/teamsmith/tests/lib/section-calls.pl +171 -0
  54. package/skills/teamsmith/tests/loop-inventory.tsv +7 -5
  55. package/skills/teamsmith/tests/meta-suite.sh +215 -0
  56. package/skills/teamsmith/tests/panel-b3-pty-mouse.py +154 -17
  57. package/skills/teamsmith/tests/panel-b3.sh +33 -4
  58. package/skills/teamsmith/tests/remind-cli.sh +574 -0
  59. package/skills/teamsmith/tests/reply-capture-real.mjs +360 -0
  60. package/skills/teamsmith/tests/reply-capture-real.sh +5 -0
  61. package/skills/teamsmith/tests/reply-capture.mjs +622 -0
  62. package/skills/teamsmith/tests/section-paths.tsv +40 -9
  63. package/skills/teamsmith/tests/section-select.sh +180 -26
  64. package/skills/teamsmith/tests/smoke.sh +1235 -238
  65. package/skills/teamsmith/tests/state-authority-node.mjs +42 -0
  66. package/skills/teamsmith/tests/state-authority.sh +629 -0
  67. package/skills/teamsmith/tests/workflow-entry.sh +123 -3
  68. package/skills/teamsmith-init/SKILL.md +1 -1
@@ -0,0 +1,622 @@
1
+ #!/usr/bin/env node
2
+ /** Product parser/source evidence. All fixtures and mutations stay here, never in product code. */
3
+ import assert from 'node:assert/strict'
4
+ import { mkdtempSync, mkdirSync, readFileSync, writeFileSync, rmSync, copyFileSync, existsSync, symlinkSync, openSync, closeSync, appendFileSync, constants as C } from 'node:fs'
5
+ import { dirname, join, resolve } from 'node:path'
6
+ import { fileURLToPath, pathToFileURL } from 'node:url'
7
+ import { spawn, spawnSync } from 'node:child_process'
8
+
9
+ const here = dirname(fileURLToPath(import.meta.url))
10
+ const modulePath = process.env.TEST_CAPTURE_MODULE ?? resolve(here, '../scripts/reply-capture.mjs')
11
+ const product = await import(pathToFileURL(modulePath).href)
12
+ const { parseReply, CaptureJournal, ReplyCapture, runReplyWriter, processIdentity, sourceKey } = product
13
+ const tests = []
14
+ const test = (name, run) => tests.push({ name, run })
15
+ const message = (text, extra = {}) => ({ role: 'assistant', content: [{ type: 'text', text }], stopReason: 'stop', timestamp: 1, ...extra })
16
+ const textOf = m => m.content.filter(b => b.type === 'text').map(b => b.text).join('')
17
+ const marker = '[[team-reply]]'
18
+ function expect(input, body, candidate, reason) {
19
+ const m = typeof input === 'string' ? message(input) : input
20
+ const parsed = parseReply(m)
21
+ assert.equal(textOf(parsed.message), body)
22
+ assert.equal(parsed.body, body)
23
+ assert.equal(parsed.candidate, candidate)
24
+ if (reason) assert.equal(parsed.reason, reason)
25
+ const original = textOf(m)
26
+ let rebuilt = '', at = 0
27
+ for (const [lo, hi] of parsed.ranges) { rebuilt += original.slice(at, lo); at = hi }
28
+ rebuilt += original.slice(at)
29
+ assert.deepEqual(Buffer.from(parsed.body), Buffer.from(rebuilt), 'original ranges / UTF-8 bytes')
30
+ assert.equal(parsed.message.stopReason, m.stopReason)
31
+ assert.equal(parsed.message.timestamp, m.timestamp)
32
+ return parsed
33
+ }
34
+
35
+ for (const literal of [marker + ' ', ' ' + marker, '\t' + marker, '> ' + marker, '- ' + marker, '\\' + marker,
36
+ '[[Team-reply]]', '[[team-', '[[team-reply:abc]]def]]', '[[team-reply', '[[team-reply:a]]b]]']) {
37
+ test(`literal grammar ${JSON.stringify(literal)}`, () => {
38
+ const m = message(`正文\n${literal}`)
39
+ assert.deepEqual(parseReply(m).message, m)
40
+ assert.equal(parseReply(m).candidate, false)
41
+ })
42
+ }
43
+ test('exact final marker / own LF only / trailing blanks retained', () => {
44
+ const p = expect(`正文\n${marker}\n \t\n\t`, '正文\n \t\n\t', true)
45
+ assert.deepEqual(p.ranges, [[3, 18]])
46
+ assert.equal(p.title, '正文')
47
+ })
48
+ test('explicit raw title retained', () => assert.equal(expect('正文\n[[team-reply: 标题 ]]', '正文\n', true).title, ' 标题 '))
49
+ for (const title of ['', ' ', 'x'.repeat(161), '\u001b[31m标题', 'a\u202eb', 'a\u200bb', '\ud800']) {
50
+ test(`invalid explicit title ${JSON.stringify(title)}`, () => expect(`正文\n[[team-reply:${title}]]`, '正文\n', false, 'invalid-title'))
51
+ }
52
+ test('multiple complete lines cleaned / ambiguous', () => expect(`${marker}\n正文\n[[team-reply:标题]]\n`, '正文\n', false, 'ambiguous'))
53
+ test('single misplaced complete line cleaned', () => expect(`${marker}\n正文`, '正文', false, 'misplaced'))
54
+ test('empty body cleanup', () => expect(` \t\n${marker}`, ' \t\n', false, 'empty-body'))
55
+ test('bare CR after marker is not a blank logical line', () => expect(`正文\n${marker}\n\r`, '正文\n\r', false, 'misplaced'))
56
+ test('prose introduction does not protect bare reserved line', () => expect(`下面是标记\n${marker}`, '下面是标记\n', true))
57
+
58
+ const suffix = '示例:\\``\n[[team-reply]]\n`'
59
+ test('escaped-first-tick suffix inline-only exact content', () => {
60
+ const m = message(suffix)
61
+ assert.deepEqual(parseReply(m).message, m)
62
+ expect(m, suffix, false, 'unmarked')
63
+ })
64
+ test('escaped-first-tick suffix inline+real only deletes real final', () => {
65
+ const original = `${suffix}\n答复。\n${marker}`
66
+ const p = expect(original, `${suffix}\n答复。\n`, true)
67
+ assert.equal(p.ranges.length, 1)
68
+ })
69
+ for (const n of [1, 2, 3, 4]) {
70
+ const input = `${'\\'.repeat(n)}\`\`\n${marker}\n\`\n答复\n${marker}`
71
+ test(`backslash parity ${n} maximal suffix`, () => {
72
+ const odd = n % 2 === 1
73
+ expect(input, odd ? input.slice(0, -marker.length) : input.replace(`${marker}\n`, '').slice(0, -marker.length), odd, odd ? 'candidate' : 'ambiguous')
74
+ })
75
+ }
76
+ test('in-span backslash does not escape exact closer', () => {
77
+ const input = `\`\`\n${marker}\n\\\`\`\n答复\n${marker}`
78
+ expect(input, input.slice(0, -marker.length), true)
79
+ })
80
+ test('paired inline spans cross logical lines', () => {
81
+ const input = `\`\`\n${marker}\n\`\`\n正文\n${marker}`
82
+ expect(input, input.slice(0, -marker.length), true)
83
+ })
84
+ test('maximal runs close only equal lengths not 1 or 3', () => {
85
+ const input = `\`\`\n\`\n${marker}\nx\`\`\`\n${marker}\n\`\`\n正文\n${marker}`
86
+ expect(input, input.slice(0, -marker.length), true)
87
+ })
88
+ test('unmatched opener literal and later shorter pair still considered', () => {
89
+ const input = `\`\`\n${marker}\n\`\n${marker}\n\`\n正文\n${marker}`
90
+ expect(input, input.replace(`${marker}\n`, '').slice(0, -marker.length), false, 'ambiguous')
91
+ })
92
+ test('unmatched opener does not swallow real final marker to EOF', () => expect(`\`\` unmatched\n正文\n${marker}`, '`` unmatched\n正文\n', true))
93
+ for (const open of ['```js', '~~~text', ' ````']) {
94
+ test(`fence protection ${open}`, () => {
95
+ const close = open.includes('~') ? '~~~~' : '`````'
96
+ const input = `${open}\n${marker}\n${close}\n正文\n${marker}`
97
+ expect(input, input.slice(0, -marker.length), true)
98
+ })
99
+ }
100
+ test('unclosed fence protects to EOF', () => {
101
+ const input = `~~~\n${marker}\n
102
+ tail\n${marker}`
103
+ expect(input, input, false)
104
+ })
105
+ test('fence closer wrong kind/short/nonblank suffix stays protected', () => {
106
+ const input = `\`\`\`\`\n${marker}\n~~~\n\`\`\`\n\`\`\`\` bad\n${marker}\n\`\`\`\`\n正文\n${marker}`
107
+ expect(input, input.slice(0, -marker.length), true)
108
+ })
109
+ test('backtick info containing tick is not a fence', () => expect(`\`\`\` info\`\n正文\n${marker}`, '``` info`\n正文\n', true))
110
+ test('inline pairs never cross fence boundary', () => {
111
+ const input = `\`\`\n~~~\nexample\n~~~\n${marker}\n\`\`\n正文\n${marker}`
112
+ expect(input, input.replace(`${marker}\n`, '').slice(0, -marker.length), false, 'ambiguous')
113
+ })
114
+ test('CRLF/Unicode/cross-block offset projection preserves every field', () => {
115
+ const m = message('', { content: [
116
+ { type: 'thinking', thinking: 'hidden [[team-reply]]', signature: 'sig' },
117
+ { type: 'text', text: '😀甲\r\n[[team-', signature: 'a' },
118
+ { type: 'text', text: '', other: { keep: 1 } },
119
+ { type: 'image', data: 'abc', mimeType: 'image/png' },
120
+ { type: 'text', text: 'reply]]\r\n\r\n', signature: 'b' },
121
+ { type: 'toolCall', id: 't1', name: 'read', arguments: { path: 'literal' } },
122
+ ], usage: { output: 12 }, extra: { untouched: true } })
123
+ const p = expect(m, '😀甲\r\n\r\n', true)
124
+ assert.deepEqual(p.ranges, [[5, 21]])
125
+ assert.deepEqual(p.message, { ...m, content: m.content.map((b, i) => i === 1 ? { ...b, text: '😀甲\r\n' } : i === 4 ? { ...b, text: '\r\n' } : b) })
126
+ })
127
+ test('cross-block inline protection and raw bytes', () => {
128
+ const input = `${suffix}\n答复。\r\n${marker}\r\n\r\n`
129
+ for (let i = 0; i <= input.length; i++) {
130
+ const m = message('', { content: [{ type: 'text', text: input.slice(0, i), signature: '1' }, { type: 'text', text: '' }, { type: 'text', text: input.slice(i), signature: '2' }] })
131
+ expect(m, `${suffix}\n答复。\r\n\r\n`, true)
132
+ }
133
+ })
134
+ test('derived title ignores Magic Context in title view only', () => {
135
+ const body = '§123§ \n \t§456§ 答复😀\n'
136
+ const p = expect(body + marker, body, true)
137
+ assert.equal(p.title, '答复😀')
138
+ })
139
+ test('derived title removes controls and clips complete codepoints', () => {
140
+ const body = '§7§ \u001b😀'.repeat(200) + '\n'
141
+ const p = expect(body + marker, body, true)
142
+ assert.equal(Array.from(p.title).length, 160)
143
+ assert.ok(!p.title.includes('\u001b'))
144
+ })
145
+ test('derived title fallback', () => assert.equal(expect(`§7§\n${marker}`, '§7§\n', true).title, '关键回复'))
146
+ for (const [name, body, valid] of [['limit exact', 'x'.repeat(131071) + '\n', true], ['limit overflow', 'x'.repeat(131072) + '\n', false], ['NUL', 'x\0\n', false], ['lone surrogate', '\ud800\n', false]]) {
147
+ test(`body ${name}`, () => expect(body + '[[team-reply:标题]]', body, valid, valid ? 'candidate' : 'invalid-body'))
148
+ }
149
+ for (const stopReason of ['stop', 'toolUse', 'length', 'error', 'aborted']) {
150
+ test(`terminal ${stopReason} always cleans`, () => expect(message(`正文\n${marker}`, { stopReason }), '正文\n', true))
151
+ }
152
+ for (const role of ['user', 'custom', 'toolResult']) {
153
+ test(`not scanned ${role}`, () => {
154
+ const m = message(`正文\n${marker}`, { role })
155
+ assert.equal(parseReply(m).message, m)
156
+ assert.equal(parseReply(m).candidate, false)
157
+ })
158
+ }
159
+
160
+ async function mutations() {
161
+ const root = mkdtempSync('/var/tmp/p396-parser-flips.')
162
+ const source = readFileSync(modulePath, 'utf8')
163
+ const arms = [
164
+ ['inline-protection', 'ranges.push(...inlineSpans(text, start, text.length))', '// removed inline protection', 'paired inline spans'],
165
+ ['escaped-whole-run', 'const opener = run.start + run.escaped', 'if (run.escaped) continue; const opener = run.start', 'escaped-first-tick suffix inline-only'],
166
+ ['ignore-parity', 'const opener = run.start + run.escaped', 'const opener = run.start', 'backslash parity 1'],
167
+ ['arbitrary-run', 'const closers = byLength.get(length) ?? []', 'const closers = runs.map((_, i) => i)', 'maximal runs close only equal'],
168
+ ['unmatched-EOF', "if (lo === closers.length) continue // Unmatched opener is literal, not protection to EOF.", 'if (lo === closers.length) { ranges.push([opener, end]); break }', 'unmatched opener does not swallow'],
169
+ ['offset-bytes', 'offset += block.text.length', "offset += Buffer.byteLength(block.text, 'utf8')", 'CRLF/Unicode/cross-block offset'],
170
+ ['in-span-escape', 'byLength.get(length).push(index)', 'if (!slashes) byLength.get(length).push(index)', 'in-span backslash'],
171
+ ]
172
+ try {
173
+ const scripts = join(root, 'scripts'); mkdirSync(scripts)
174
+ copyFileSync(resolve(here, '../scripts/replies.mjs'), join(scripts, 'replies.mjs'))
175
+ for (const [name, old, replacement, named] of arms) {
176
+ assert.equal(source.split(old).length, 2, `${name}: unique mutation target`)
177
+ const target = join(scripts, 'reply-capture.mjs')
178
+ writeFileSync(target, source.replace(old, replacement))
179
+ const r = spawnSync(process.execPath, [fileURLToPath(import.meta.url), '--select', 'parser'], { env: { ...process.env, TEST_CAPTURE_MODULE: target }, encoding: 'utf8' })
180
+ const output = `${r.stdout}${r.stderr}`
181
+ if (process.env.TEAM_REPLY_EVIDENCE) {
182
+ mkdirSync(process.env.TEAM_REPLY_EVIDENCE, { recursive: true })
183
+ writeFileSync(join(process.env.TEAM_REPLY_EVIDENCE, `parser-flip-${name}.log`), output)
184
+ }
185
+ assert.equal(r.status, 1, `${name}: product mutation must fail`)
186
+ assert.ok(output.split('\n').some(line => line.startsWith('FAIL ') && line.includes(named)), `${name}: named assertion must fail: ${named}`)
187
+ console.log(`PASS mutation ${name}: named assertion red (${named})`)
188
+ }
189
+ writeFileSync(join(scripts, 'reply-capture.mjs'), source)
190
+ const restored = spawnSync(process.execPath, [fileURLToPath(import.meta.url), '--select', 'parser'], { env: { ...process.env, TEST_CAPTURE_MODULE: join(scripts, 'reply-capture.mjs') }, encoding: 'utf8' })
191
+ assert.equal(restored.status, 0, restored.stdout + restored.stderr)
192
+ console.log('PASS mutation restoration: parser green')
193
+ } finally { rmSync(root, { recursive: true, force: true }) }
194
+ }
195
+
196
+ const sourceTests = []
197
+ const state = (name, run) => sourceTests.push({ name, run })
198
+ const team = resolve(here, '../scripts/team')
199
+ const cleanEnv = Object.fromEntries(Object.entries(process.env).filter(([key]) => !key.startsWith('TEAM_')))
200
+ async function fixture(run) {
201
+ const root = mkdtempSync('/var/tmp/p396-source.')
202
+ try {
203
+ const init = spawnSync('git', ['init', '-q', '-b', 'main', root], { encoding: 'utf8' })
204
+ assert.equal(init.status, 0, init.stderr)
205
+ mkdirSync(join(root, '.pi/team/state'), { recursive: true })
206
+ writeFileSync(join(root, '.pi/team/config.sh'), '# private fixture\n')
207
+ writeFileSync(join(root, 'session.jsonl'), '')
208
+ const identity = { root, state: join(root, '.pi/team/state'), config: join(root, '.pi/team/config.sh'), sessionId: 'private-session', sessionFile: join(root, 'session.jsonl') }
209
+ const branch = [], diagnostics = []
210
+ let current = true, verified = true, calls = 0
211
+ const view = () => ({ identity: { ...identity }, leaf: branch.at(-1)?.id ?? null, branch: [...branch], entry: id => branch.find(entry => entry.id === id) })
212
+ const writer = async record => { calls++; return runReplyWriter({ team, identity, env: cleanEnv }, record) }
213
+ const journal = new CaptureJournal(identity)
214
+ const options = { identity, journal, current: () => current, verify: () => verified, writer, owner: { ...processIdentity(process.pid), generation: 'test-owner' }, diagnostic: d => diagnostics.push(d) }
215
+ const engine = new ReplyCapture(options)
216
+ const snapshot = () => JSON.parse(readFileSync(journal.path, 'utf8'))
217
+ const cli = (args, input, env = cleanEnv) => spawnSync('bash', [team, '--root', root, 'reply', ...args], { cwd: root, input, env, encoding: 'utf8' })
218
+ const list = () => { const r = cli(['list', '--json']); assert.equal(r.status, 0, r.stderr); return JSON.parse(r.stdout) }
219
+ const emit = (input, id = `entry-${branch.length + 1}`, { bind = true, settle = true, aborted = false, begin = true } = {}) => {
220
+ if (begin) engine.before(view())
221
+ engine.start(input, view())
222
+ const cleaned = engine.end(input, view())
223
+ branch.push({ type: 'message', id, parentId: branch.at(-1)?.id ?? null, message: cleaned })
224
+ if (bind) engine.turn({ messageEntryId: id, message: cleaned }, view())
225
+ if (settle) engine.settled({ aborted }, view())
226
+ return cleaned
227
+ }
228
+ await run({ root, identity, branch, view, engine, journal, options, emit, snapshot, cli, list, diagnostics,
229
+ calls: () => calls, revoke: () => { current = false }, degrade: () => { verified = false } })
230
+ } finally { rmSync(root, { recursive: true, force: true }) }
231
+ }
232
+ const records = f => Object.values(f.snapshot().sources)
233
+ state('null first leaf stages unbound then actual binding pending then settled saved/raw', () => fixture(async f => {
234
+ f.engine.before(f.view()); assert.equal(f.view().leaf, null)
235
+ const input = message('§123§ 完整😀正文\r\n[[team-reply:真实标题]]\r\n\r\n')
236
+ f.engine.start(input, f.view())
237
+ const cleaned = f.engine.end(input, f.view())
238
+ assert.equal(textOf(cleaned), '§123§ 完整😀正文\r\n\r\n')
239
+ assert.equal(Object.values(f.snapshot().intents)[0].status, 'unbound')
240
+ assert.equal(records(f).length, 0); assert.equal(f.calls(), 0)
241
+ f.branch.push({ type: 'message', id: 'actual-entry', message: cleaned })
242
+ f.engine.turn({ messageEntryId: 'actual-entry', message: cleaned }, f.view())
243
+ assert.equal(records(f)[0].status, 'pending'); assert.equal(f.calls(), 0)
244
+ f.engine.settled({ aborted: false }, f.view()); await f.engine.drain()
245
+ const record = records(f)[0]
246
+ assert.equal(record.status, 'saved'); assert.equal(record.no, 1); assert.equal(f.calls(), 1)
247
+ assert.deepEqual(record.source, [f.identity.root, f.identity.state, f.identity.sessionId, f.identity.sessionFile, 'actual-entry'])
248
+ const raw = f.cli(['show', '1', '--raw']); assert.equal(raw.status, 0, raw.stderr)
249
+ assert.deepEqual(Buffer.from(raw.stdout), Buffer.from(textOf(cleaned)))
250
+ }))
251
+ state('escaped suffix inline-only no journal and inline+real one real writer/raw', () => fixture(async f => {
252
+ f.emit(message(suffix)); await f.engine.drain()
253
+ assert.equal(f.calls(), 0); assert.ok(!existsSync(f.journal.path))
254
+ const body = `${suffix}\n答复。\n`
255
+ f.emit(message(body + marker)); await f.engine.drain()
256
+ assert.equal(f.calls(), 1); assert.equal(records(f)[0].status, 'saved')
257
+ assert.equal(f.cli(['show', '1', '--raw']).stdout, body)
258
+ }))
259
+ for (const [name, input] of [['queued ordinary', message('普通最终回答')], ['tool', message(`tool\n${marker}`, { stopReason: 'toolUse', content: [{ type: 'text', text: `tool\n${marker}` }, { type: 'toolCall', id: 'c1', name: 'read', arguments: {} }] })], ['error', message(`error\n${marker}`, { stopReason: 'error' })], ['length', message(`length\n${marker}`, { stopReason: 'length' })], ['aborted', message(`aborted\n${marker}`, { stopReason: 'aborted' })]]) {
260
+ state(`latest supersession ${name} no backward search`, () => fixture(async f => {
261
+ f.emit(message(`earlier\n${marker}`), 'early', { settle: false })
262
+ const cleaned = f.emit(input, 'latest', { begin: false })
263
+ await f.engine.drain()
264
+ assert.ok(!textOf(cleaned).includes(marker)); assert.equal(f.calls(), 0)
265
+ assert.equal(records(f).length, 1); assert.equal(records(f)[0].status, 'pending')
266
+ }))
267
+ }
268
+ state('retry/before-settle continuation replaces earlier marked stop', () => fixture(async f => {
269
+ f.emit(message(`earlier\n${marker}`), 'early', { settle: false })
270
+ f.emit(message(`final\n${marker}`), 'final', { begin: false })
271
+ await f.engine.drain()
272
+ assert.equal(f.calls(), 1)
273
+ assert.deepEqual(records(f).map(r => r.status), ['pending', 'saved'])
274
+ assert.equal(f.cli(['show', '1', '--raw']).stdout, 'final\n')
275
+ }))
276
+ state('overall abort after successful stop denies eligibility', () => fixture(async f => {
277
+ f.emit(message(`answer\n${marker}`), 'e1', { aborted: true })
278
+ await f.engine.drain(); assert.equal(f.calls(), 0); assert.equal(records(f)[0].status, 'pending')
279
+ new ReplyCapture(f.options).recover(f.view()); assert.equal(f.calls(), 0)
280
+ }))
281
+ state('no binding never substitutes current leaf or same body', () => fixture(async f => {
282
+ f.emit(message(`answer\n${marker}`), 'e1', { bind: false })
283
+ await f.engine.drain(); assert.equal(f.calls(), 0); assert.equal(records(f).length, 0)
284
+ new ReplyCapture(f.options).recover(f.view()); assert.equal(f.calls(), 0)
285
+ }))
286
+ state('mismatched entry binding is invalidated not repaired', () => fixture(async f => {
287
+ f.emit(message(`answer\n${marker}`), 'e1', { bind: false, settle: false })
288
+ const good = f.branch[0].message
289
+ f.engine.turn({ messageEntryId: 'wrong', message: good }, f.view())
290
+ f.engine.turn({ messageEntryId: 'e1', message: good }, f.view())
291
+ f.engine.settled({ aborted: false }, f.view()); await f.engine.drain()
292
+ assert.equal(f.calls(), 0); assert.equal(records(f).length, 0)
293
+ }))
294
+ state('same-body distinct entries each save while duplicate events do not', () => fixture(async f => {
295
+ const input = message(`identical\n${marker}`)
296
+ for (const id of ['e1', 'e2']) {
297
+ const cleaned = f.emit(input, id, { settle: false })
298
+ f.engine.end(input, f.view())
299
+ f.engine.turn({ messageEntryId: id, message: cleaned }, f.view())
300
+ f.engine.settled({ aborted: false }, f.view()); f.engine.settled({ aborted: false }, f.view())
301
+ await f.engine.drain()
302
+ new ReplyCapture(f.options).recover(f.view())
303
+ }
304
+ await f.engine.drain(); assert.equal(f.calls(), 2)
305
+ assert.deepEqual(records(f).map(r => r.no), [1, 2])
306
+ }))
307
+ state('source barrier survives saved beyond newest page', () => fixture(async f => {
308
+ f.emit(message(`old\n${marker}`), 'old'); await f.engine.drain()
309
+ for (let n = 0; n < 51; n++) {
310
+ const post = f.cli(['post', '--from', 'manual', '--title', 'newer', '--stdin'], `newer ${n}`)
311
+ assert.equal(post.status, 0, post.stderr)
312
+ }
313
+ const engine = new ReplyCapture(f.options); engine.recover(f.view()); await engine.drain()
314
+ assert.equal(f.calls(), 1); assert.equal(records(f)[0].no, 1)
315
+ const page = f.list(); assert.equal(page.entries.length, 50); assert.ok(page.entries.every(row => row.no > 1))
316
+ }))
317
+ state('new activity prevents recovery; session/branch witness cannot import', () => fixture(async f => {
318
+ const originalAttempt = f.engine.attempt
319
+ f.engine.attempt = () => {}
320
+ f.emit(message(`eligible\n${marker}`), 'e1')
321
+ assert.equal(records(f)[0].status, 'eligible')
322
+ f.engine.attempt = originalAttempt
323
+ f.engine.before(f.view()); f.engine.recover(f.view()); assert.equal(f.calls(), 0)
324
+ f.engine.reset()
325
+ const other = { ...f.view(), identity: { ...f.identity, sessionId: 'fork' } }
326
+ f.engine.recover(other); assert.equal(f.calls(), 0)
327
+ f.engine.recover({ ...f.view(), branch: [], leaf: null }); await f.engine.drain(); assert.equal(f.calls(), 0)
328
+ f.engine.recover(f.view()); await f.engine.drain(); assert.equal(f.calls(), 1)
329
+ }))
330
+ state('CAS two engines recover one eligible source once', () => fixture(async f => {
331
+ f.engine.attempt = () => {}
332
+ f.emit(message(`eligible\n${marker}`), 'e1')
333
+ const a = new ReplyCapture(f.options), b = new ReplyCapture(f.options)
334
+ a.recover(f.view()); b.recover(f.view()); await Promise.all([a.drain(), b.drain()])
335
+ assert.equal(f.calls(), 1); assert.equal(records(f)[0].status, 'saved')
336
+ }))
337
+ state('CAS stale discoveries cannot both attempt the same eligible source', () => fixture(async f => {
338
+ f.engine.attempt = () => {}; f.emit(message(`eligible\n${marker}`), 'e1')
339
+ const discovered = structuredClone(records(f)[0])
340
+ const a = new ReplyCapture(f.options), b = new ReplyCapture(f.options)
341
+ a.attempt(discovered, f.view()); b.attempt(discovered, f.view())
342
+ await Promise.all([a.drain(), b.drain()])
343
+ assert.equal(f.calls(), 1); assert.equal(records(f)[0].status, 'saved')
344
+ }))
345
+ state('two processes recover one eligible source with one real writer', () => fixture(async f => {
346
+ f.engine.attempt = () => {}; f.emit(message(`eligible\n${marker}`), 'e1')
347
+ writeFileSync(join(f.root, 'crash-identity.json'), JSON.stringify(f.identity))
348
+ writeFileSync(join(f.root, 'crash-branch.json'), JSON.stringify(f.branch))
349
+ const children = [1, 2].map(() => {
350
+ const child = spawn(process.execPath, [fileURLToPath(import.meta.url), '--recover-child', f.root], { env: cleanEnv, stdio: ['pipe', 'pipe', 'pipe'] })
351
+ let stdout = '', stderr = ''
352
+ const ready = new Promise((resolve, reject) => {
353
+ child.stdout.on('data', data => { stdout += data; if (stdout.includes('READY\n')) resolve() })
354
+ child.on('error', reject); child.on('exit', () => { if (!stdout.includes('READY\n')) reject(new Error(`child died before ready: ${stderr}`)) })
355
+ })
356
+ child.stderr.on('data', data => { stderr += data })
357
+ const closed = new Promise(resolve => child.on('close', code => resolve({ code, stderr })))
358
+ return { child, ready, closed }
359
+ })
360
+ try {
361
+ await Promise.all(children.map(c => c.ready))
362
+ for (const c of children) c.child.stdin.end('go')
363
+ for (const c of children) { const result = await c.closed; assert.equal(result.code, 0, result.stderr) }
364
+ assert.equal(readFileSync(join(f.root, 'attempt.log'), 'utf8').trim().split('\n').length, 1)
365
+ assert.equal(records(f)[0].status, 'saved'); assert.equal(f.list().entries.length, 1)
366
+ } finally { for (const c of children) if (c.child.exitCode === null) c.child.kill('SIGKILL') }
367
+ }))
368
+ state('degraded identity and staging exception still return cleaned message', () => fixture(async f => {
369
+ f.engine.before(f.view()); f.engine.start(message(''), f.view()); f.degrade()
370
+ const clean = f.engine.end(message(`answer\n${marker}`), f.view())
371
+ assert.equal(textOf(clean), 'answer\n'); assert.equal(f.calls(), 0); assert.ok(!existsSync(f.journal.path))
372
+ }))
373
+ state('staging disk failure never leaves marker or guesses binding', () => fixture(async f => {
374
+ f.journal.transact = () => { throw Object.assign(new Error('disk full'), { code: 'ENOSPC' }) }
375
+ const clean = f.emit(message(`answer\n${marker}`))
376
+ await f.engine.drain(); assert.equal(textOf(clean), 'answer\n'); assert.equal(f.calls(), 0)
377
+ assert.ok(f.diagnostics.some(d => d.reason === 'stage:ENOSPC'))
378
+ }))
379
+ state('symlink journal/lock/unsafe ancestor refused with normal cleanup', () => fixture(async f => {
380
+ mkdirSync(f.journal.directory)
381
+ writeFileSync(join(f.root, 'outside'), 'do not change')
382
+ symlinkSync(join(f.root, 'outside'), `${f.journal.path}.lock`)
383
+ const clean = f.emit(message(`answer\n${marker}`)); await f.engine.drain()
384
+ assert.equal(textOf(clean), 'answer\n'); assert.equal(f.calls(), 0)
385
+ assert.equal(readFileSync(join(f.root, 'outside'), 'utf8'), 'do not change')
386
+ }))
387
+ state('old owner callback cannot record result after generation replacement', () => fixture(async f => {
388
+ let release
389
+ const engine = new ReplyCapture({ ...f.options, writer: record => new Promise(resolve => { release = async () => resolve(await f.options.writer(record)) }) })
390
+ engine.before(f.view()); const input = message(`answer\n${marker}`)
391
+ engine.start(input, f.view()); const cleaned = engine.end(input, f.view())
392
+ f.branch.push({ type: 'message', id: 'e1', message: cleaned }); engine.turn({ messageEntryId: 'e1', message: cleaned }, f.view())
393
+ engine.settled({ aborted: false }, f.view()); await Promise.resolve()
394
+ assert.equal(records(f)[0].status, 'attempting'); f.revoke(); await release(); await engine.drain()
395
+ assert.equal(records(f)[0].status, 'attempting'); assert.equal(f.calls(), 1)
396
+ }))
397
+
398
+ state('real writer busy 5 never retries', () => fixture(async f => {
399
+ const directory = join(f.identity.state, 'key-replies'); mkdirSync(directory)
400
+ const lock = openSync(join(directory, 'writer.lock'), C.O_RDWR | C.O_CREAT, 0o600)
401
+ try {
402
+ const acquired = spawnSync('flock', ['-x', '3'], { stdio: ['ignore', 'ignore', 'ignore', lock] }); assert.equal(acquired.status, 0)
403
+ let actual
404
+ const engine = new ReplyCapture({ ...f.options, writer: async record => { actual = await f.options.writer(record); return actual } })
405
+ const input = message(`busy answer\n${marker}`)
406
+ engine.before(f.view()); engine.start(input, f.view()); const clean = engine.end(input, f.view())
407
+ f.branch.push({ type: 'message', id: 'e1', message: clean }); engine.turn({ messageEntryId: 'e1', message: clean }, f.view())
408
+ engine.settled({ aborted: false }, f.view()); await engine.drain()
409
+ assert.equal(actual.status, 5); assert.equal(textOf(clean), 'busy answer\n')
410
+ assert.equal(records(f)[0].status, 'not-written'); assert.equal(records(f)[0].reason, 'busy')
411
+ } finally { closeSync(lock) }
412
+ const resumed = new ReplyCapture(f.options); resumed.recover(f.view()); await resumed.drain()
413
+ assert.equal(f.calls(), 1); assert.equal(f.list().entries.length, 0)
414
+ }))
415
+ state('real fail:index-fsync unconfirmed 6 candidate never relabelled or retried', () => fixture(async f => {
416
+ let actual
417
+ const engine = new ReplyCapture({ ...f.options, writer: async record => {
418
+ actual = await runReplyWriter({ team, identity: f.identity, env: { ...cleanEnv, TEAM_REPLY_FAULT: 'fail:index-fsync' } }, record)
419
+ return actual
420
+ } })
421
+ const input = message(`unconfirmed answer\n${marker}`)
422
+ engine.before(f.view()); engine.start(input, f.view()); const clean = engine.end(input, f.view())
423
+ f.branch.push({ type: 'message', id: 'e1', message: clean }); engine.turn({ messageEntryId: 'e1', message: clean }, f.view())
424
+ engine.settled({ aborted: false }, f.view()); await engine.drain()
425
+ assert.equal(actual.status, 6); assert.equal(records(f)[0].status, 'unconfirmed')
426
+ assert.equal(records(f)[0].candidate_no, 1); assert.equal(records(f)[0].no, undefined)
427
+ const resumed = new ReplyCapture(f.options); resumed.recover(f.view()); await resumed.drain()
428
+ assert.equal(f.calls(), 0); assert.equal(f.list().entries.length, 1)
429
+ assert.equal(f.cli(['show', '1', '--raw']).stdout, textOf(clean))
430
+ }))
431
+ for (const fault of ['missing', 'malformed', 'inconsistent', 'result-journal']) {
432
+ state(`real committed writer ${fault} never retries`, () => fixture(async f => {
433
+ const transact = f.journal.transact.bind(f.journal)
434
+ if (fault === 'result-journal') f.journal.transact = (change, opts) => transact(snapshot => {
435
+ const result = change(snapshot)
436
+ if (Object.values(snapshot.sources).some(record => record.status === 'saved')) throw Object.assign(new Error('result disk failure'), { code: 'ENOSPC' })
437
+ return result
438
+ }, opts)
439
+ const engine = new ReplyCapture({ ...f.options, writer: async record => {
440
+ const result = await f.options.writer(record)
441
+ assert.equal(result.status, 0)
442
+ if (fault === 'missing') result.stdout = ''
443
+ if (fault === 'malformed') result.stdout = 'not json'
444
+ if (fault === 'inconsistent') { const receipt = JSON.parse(result.stdout); receipt.sha256 = '0'.repeat(64); result.stdout = JSON.stringify(receipt) }
445
+ return result
446
+ } })
447
+ const input = message(`complete answer ${fault}\n${marker}`)
448
+ engine.before(f.view()); engine.start(input, f.view()); const clean = engine.end(input, f.view())
449
+ f.branch.push({ type: 'message', id: 'e1', message: clean }); engine.turn({ messageEntryId: 'e1', message: clean }, f.view())
450
+ engine.settled({ aborted: false }, f.view()); await engine.drain()
451
+ assert.equal(records(f)[0].status, fault === 'result-journal' ? 'attempting' : 'uncertain')
452
+ const resumed = new ReplyCapture({ ...f.options, journal: new CaptureJournal(f.identity) }); resumed.recover(f.view()); await resumed.drain()
453
+ assert.equal(f.calls(), 1); assert.equal(f.list().entries.length, 1)
454
+ assert.equal(f.cli(['show', '1', '--raw']).stdout, textOf(clean))
455
+ }))
456
+ }
457
+ state('diagnostic sink failure still cleans terminal answer', () => fixture(async f => {
458
+ const engine = new ReplyCapture({ ...f.options, diagnostic: () => { throw new Error('closed diagnostic sink') }, journal: { path: f.journal.path, transact: () => { throw new Error('disk unavailable') } } })
459
+ engine.before(f.view()); engine.start(message(''), f.view())
460
+ const clean = engine.end(message(`answer\n${marker}`), f.view()); assert.equal(textOf(clean), 'answer\n')
461
+ }))
462
+
463
+ function crashChild(point, root) {
464
+ const identity = JSON.parse(readFileSync(join(root, 'crash-identity.json'), 'utf8'))
465
+ const journal = new CaptureJournal(identity)
466
+ const branch = []
467
+ const view = () => ({ identity, branch, leaf: branch.at(-1)?.id ?? null, entry: id => branch.find(entry => entry.id === id) })
468
+ const engine = new ReplyCapture({ identity, journal, current: () => true, verify: () => true,
469
+ writer: record => runReplyWriter({ team, identity, env: cleanEnv }, record),
470
+ owner: processIdentity(process.pid), diagnostic: d => console.error(d.reason) })
471
+ const exitAt = boundary => { if (point === boundary) process.exit(74) }
472
+ const transact = journal.transact.bind(journal)
473
+ journal.transact = (change, opts) => {
474
+ const result = transact(snapshot => {
475
+ const result = change(snapshot)
476
+ if (Object.values(snapshot.sources).some(r => r.status === 'eligible')) exitAt('during-eligible')
477
+ if (Object.values(snapshot.sources).some(r => r.status === 'attempting')) exitAt('during-attempting')
478
+ return result
479
+ }, opts)
480
+ const snapshot = JSON.parse(readFileSync(journal.path, 'utf8'))
481
+ if (Object.values(snapshot.sources).some(r => r.status === 'attempting')) exitAt('after-attempting')
482
+ return result
483
+ }
484
+ engine.before(view()); const input = message(`crash answer\n${marker}`); engine.start(input, view())
485
+ exitAt('before-stage')
486
+ const cleaned = engine.end(input, view()); exitAt('after-stage'); exitAt('before-append')
487
+ branch.push({ type: 'message', id: 'crash-entry', message: cleaned })
488
+ writeFileSync(join(root, 'crash-branch.json'), JSON.stringify(branch)); exitAt('after-append'); exitAt('before-binding')
489
+ engine.turn({ messageEntryId: 'crash-entry', message: cleaned }, view()); exitAt('after-binding')
490
+ if (point === 'after-eligible') engine.attempt = () => process.exit(74)
491
+ engine.settled({ aborted: false }, view())
492
+ throw new Error(`crash boundary not reached: ${point}`)
493
+ }
494
+ for (const point of ['before-stage', 'after-stage', 'before-append', 'after-append', 'before-binding', 'after-binding', 'during-eligible', 'after-eligible', 'during-attempting', 'after-attempting']) {
495
+ state(`external process death ${point}: only durable eligible can recover`, () => fixture(async f => {
496
+ writeFileSync(join(f.root, 'crash-identity.json'), JSON.stringify(f.identity))
497
+ const child = spawnSync(process.execPath, [fileURLToPath(import.meta.url), '--crash-child', point, f.root], { env: cleanEnv, encoding: 'utf8' })
498
+ assert.equal(child.status, 74, child.stderr)
499
+ if (existsSync(join(f.root, 'crash-branch.json'))) f.branch.push(...JSON.parse(readFileSync(join(f.root, 'crash-branch.json'), 'utf8')))
500
+ const resumed = new ReplyCapture({ ...f.options, journal: new CaptureJournal(f.identity) })
501
+ resumed.recover(f.view()); await resumed.drain()
502
+ const allowed = ['after-eligible', 'during-attempting'].includes(point)
503
+ assert.equal(f.calls(), allowed ? 1 : 0)
504
+ if (allowed) assert.equal(records(f)[0].status, 'saved')
505
+ if (point === 'after-attempting') assert.equal(records(f)[0].status, 'uncertain')
506
+ resumed.recover(f.view()); await resumed.drain(); assert.equal(f.calls(), allowed ? 1 : 0)
507
+ }))
508
+ }
509
+ for (const fault of ['kill:body-staged', 'kill:index-written', 'kill:index-durable', 'fail:index-write']) {
510
+ state(`real writer interruption ${fault} remains uncertain/no automatic retry`, () => fixture(async f => {
511
+ let calls = 0, actual
512
+ const engine = new ReplyCapture({ ...f.options, writer: async record => {
513
+ calls++; actual = await runReplyWriter({ team, identity: f.identity, env: { ...cleanEnv, TEAM_REPLY_FAULT: fault } }, record); return actual
514
+ } })
515
+ const input = message(`fault answer\n${marker}`)
516
+ engine.before(f.view()); engine.start(input, f.view()); const clean = engine.end(input, f.view())
517
+ f.branch.push({ type: 'message', id: 'e1', message: clean }); engine.turn({ messageEntryId: 'e1', message: clean }, f.view())
518
+ engine.settled({ aborted: false }, f.view()); await engine.drain()
519
+ assert.notEqual(actual.status, 0); assert.equal(records(f)[0].status, 'uncertain'); assert.equal(textOf(clean), 'fault answer\n')
520
+ const resumed = new ReplyCapture({ ...f.options, journal: new CaptureJournal(f.identity) }); resumed.recover(f.view()); await resumed.drain()
521
+ assert.equal(calls, 1); assert.equal(f.calls(), 0)
522
+ }))
523
+ }
524
+
525
+ // The shipped instruction surfaces print a concrete marker example. This group runs that printed text
526
+ // through the product parser and the real writer, so the promise "printed example works" is exercised
527
+ // rather than asserted about prose. A broken example must fail here (no vacuous pass).
528
+ async function shippedExample() {
529
+ const file = process.env.TEST_EXAMPLE_FILE
530
+ assert.ok(file, 'TEST_EXAMPLE_FILE must name the shipped marker example')
531
+ const text = readFileSync(file, 'utf8')
532
+ const parsed = parseReply(message(text))
533
+ assert.equal(parsed.reason, 'candidate', `shipped marker example is not a publishable candidate (${parsed.reason})`)
534
+ assert.equal(parsed.candidate, true)
535
+ const control = /^\[\[team-reply(?::[^\]]*)?\]\]$/m.exec(text)
536
+ assert.ok(control, 'shipped marker example must contain a final control line')
537
+ assert.equal(parsed.body, text.slice(0, control.index), 'published body is the example minus only the control line')
538
+ await fixture(async f => {
539
+ const cleaned = f.emit(message(text))
540
+ await f.engine.drain()
541
+ assert.equal(f.calls(), 1, 'one real writer attempt')
542
+ assert.deepEqual(records(f).map(r => r.status), ['saved'])
543
+ const page = f.list()
544
+ assert.equal(page.total_slots, 1, 'exactly one published reply')
545
+ const raw = f.cli(['show', '1', '--raw'])
546
+ assert.equal(raw.status, 0, raw.stderr)
547
+ assert.deepEqual(Buffer.from(raw.stdout), Buffer.from(textOf(cleaned)))
548
+ assert.deepEqual(Buffer.from(raw.stdout), Buffer.from(parsed.body))
549
+ assert.equal(records(f)[0].title, parsed.title)
550
+ })
551
+ console.log('PASS shipped marker example: product parser candidate, one real writer save, raw body equals the answer minus the control line')
552
+ }
553
+
554
+ async function stateMutations() {
555
+ const source = readFileSync(modulePath, 'utf8'), root = mkdtempSync('/var/tmp/p396-source-flips.')
556
+ try {
557
+ copyFileSync(resolve(here, '../scripts/replies.mjs'), join(root, 'replies.mjs'))
558
+ const arms = [
559
+ ['source-cas', "if (stored?.status !== 'eligible') return false", 'if (!stored) return false', 'CAS stale discoveries'],
560
+ ['durable-attempt', "stored.status = 'attempting'", "stored.status = 'eligible'", 'external process death after-attempting'],
561
+ ['current-branch', 'return (startLeaf === null || start >= 0) && at > start && end >= at && view.leaf === ids.at(-1)', 'return true', 'new activity prevents recovery'],
562
+ ]
563
+ for (const [name, old, replacement, named] of arms) {
564
+ assert.equal(source.split(old).length, 2, `${name}: unique mutation target`)
565
+ const target = join(root, 'reply-capture.mjs'); writeFileSync(target, source.replace(old, replacement))
566
+ const result = spawnSync(process.execPath, [fileURLToPath(import.meta.url), '--select', 'state'], { env: { ...cleanEnv, TEST_CAPTURE_MODULE: target }, encoding: 'utf8' })
567
+ const output = result.stdout + result.stderr
568
+ if (process.env.TEAM_REPLY_EVIDENCE) { mkdirSync(process.env.TEAM_REPLY_EVIDENCE, { recursive: true }); writeFileSync(join(process.env.TEAM_REPLY_EVIDENCE, `source-flip-${name}.log`), output) }
569
+ assert.equal(result.status, 1, `${name}: red`)
570
+ assert(output.split('\n').some(line => line.startsWith('FAIL ') && line.includes(named)), `${name}: named red ${named}`)
571
+ console.log(`PASS mutation ${name}: named assertion red (${named})`)
572
+ }
573
+ const target = join(root, 'reply-capture.mjs'); writeFileSync(target, source)
574
+ const restored = spawnSync(process.execPath, [fileURLToPath(import.meta.url), '--select', 'state'], { env: { ...cleanEnv, TEST_CAPTURE_MODULE: target }, encoding: 'utf8' })
575
+ assert.equal(restored.status, 0, restored.stdout + restored.stderr)
576
+ console.log('PASS mutation restoration: source green')
577
+ } finally { rmSync(root, { recursive: true, force: true }) }
578
+ }
579
+ async function recoverChild(root) {
580
+ const identity = JSON.parse(readFileSync(join(root, 'crash-identity.json'), 'utf8'))
581
+ const branch = JSON.parse(readFileSync(join(root, 'crash-branch.json'), 'utf8'))
582
+ const view = { identity, branch, leaf: branch.at(-1)?.id ?? null, entry: id => branch.find(e => e.id === id) }
583
+ console.log('READY')
584
+ await new Promise(resolve => process.stdin.once('data', resolve))
585
+ const engine = new ReplyCapture({ identity, current: () => true, verify: () => true, owner: processIdentity(process.pid), writer: record => {
586
+ appendFileSync(join(root, 'attempt.log'), `${process.pid}\n`)
587
+ return runReplyWriter({ team, identity, env: cleanEnv }, record)
588
+ } })
589
+ engine.recover(view); await engine.drain()
590
+ }
591
+ const args = process.argv.slice(2)
592
+ if (args[0] === '--recover-child') { await recoverChild(args[1]); process.exit(0) }
593
+ if (args[0] === '--crash-child') crashChild(args[1], args[2])
594
+ let groups = ['parser']
595
+ if (args.length && args[0] !== '--all') {
596
+ if (args[0] !== '--select' || args.length !== 2) throw new Error('usage: reply-capture.mjs --all | --select parser,state,mutations,state-mutations (or --select example with TEST_EXAMPLE_FILE)')
597
+ groups = args[1].split(',')
598
+ } else if (args[0] === '--all') groups = ['parser', 'state', 'mutations', 'state-mutations']
599
+ if (groups.some(g => !['parser', 'state', 'mutations', 'state-mutations', 'example'].includes(g))) throw new Error('unknown test group')
600
+ let passed = 0, failed = 0
601
+ if (groups.includes('parser')) for (const { name, run } of tests) {
602
+ try { await run(); passed++; console.log(`PASS ${name}`) }
603
+ catch (e) { failed++; console.log(`FAIL ${name}: ${e.message}`) }
604
+ }
605
+ if (groups.includes('state')) for (const { name, run } of sourceTests) {
606
+ try { await run(); passed++; console.log(`PASS ${name}`) }
607
+ catch (e) { failed++; console.log(`FAIL ${name}: ${e.stack}`) }
608
+ }
609
+ if (groups.includes('mutations')) {
610
+ try { await mutations(); passed += 8 }
611
+ catch (e) { failed++; console.log(`FAIL mutations: ${e.stack}`) }
612
+ }
613
+ if (groups.includes('state-mutations')) {
614
+ try { await stateMutations(); passed += 4 }
615
+ catch (e) { failed++; console.log(`FAIL state mutations: ${e.stack}`) }
616
+ }
617
+ if (groups.includes('example')) {
618
+ try { await shippedExample(); passed += 1 }
619
+ catch (e) { failed++; console.log(`FAIL example: ${e.stack}`) }
620
+ }
621
+ console.log(`reply-capture: passed=${passed} failed=${failed}`)
622
+ process.exitCode = failed ? 1 : 0