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,596 @@
1
+ /** Directed PM reply capture: lexical cleanup and source operations (not a reply store). */
2
+ import { TITLE_FORBIDDEN_RE, validateTitle, validateBody } from './replies.mjs'
3
+ import { closeSync, constants as C, fstatSync, fsyncSync, lstatSync, mkdirSync, openSync, readFileSync, realpathSync, renameSync, unlinkSync, writeFileSync } from 'node:fs'
4
+ import { spawn, spawnSync } from 'node:child_process'
5
+ import { createHash, randomUUID } from 'node:crypto'
6
+ import { basename, dirname, isAbsolute, join, resolve, sep } from 'node:path'
7
+ import { isDeepStrictEqual } from 'node:util'
8
+
9
+ function logicalLines(text) {
10
+ const lines = []
11
+ let start = 0
12
+ while (start < text.length) {
13
+ const lf = text.indexOf('\n', start)
14
+ const end = lf < 0 ? text.length : lf + 1
15
+ const textEnd = lf < 0 ? end : lf > start && text[lf - 1] === '\r' ? lf - 1 : lf
16
+ lines.push({ start, end, text: text.slice(start, textEnd) })
17
+ start = end
18
+ }
19
+ return lines
20
+ }
21
+
22
+ function fences(lines, length) {
23
+ const ranges = []
24
+ let open = null
25
+ for (const line of lines) {
26
+ if (open) {
27
+ const close = /^ {0,3}(`+|~+)([ \t]*)$/.exec(line.text)
28
+ if (close && close[1][0] === open.type && close[1].length >= open.length) {
29
+ ranges.push([open.start, line.end])
30
+ open = null
31
+ }
32
+ } else {
33
+ const match = /^ {0,3}(`{3,}|~{3,})(.*)$/.exec(line.text)
34
+ if (match && !(match[1][0] === '`' && match[2].includes('`'))) {
35
+ open = { start: line.start, type: match[1][0], length: match[1].length }
36
+ }
37
+ }
38
+ }
39
+ if (open) ranges.push([open.start, length])
40
+ return ranges
41
+ }
42
+
43
+ function inlineSpans(text, start, end) {
44
+ // Physical runs are the closer index: backslashes inside a span never escape a closer.
45
+ const runs = []
46
+ const byLength = new Map()
47
+ for (let pos = start; pos < end;) {
48
+ if (text[pos] !== '`') { pos++; continue }
49
+ const from = pos
50
+ while (pos < end && text[pos] === '`') pos++
51
+ let slashes = 0
52
+ for (let p = from - 1; p >= start && text[p] === '\\'; p--) slashes++
53
+ const index = runs.length
54
+ runs.push({ start: from, end: pos, escaped: slashes % 2 })
55
+ const length = pos - from
56
+ if (!byLength.has(length)) byLength.set(length, [])
57
+ byLength.get(length).push(index)
58
+ }
59
+ const ranges = []
60
+ for (let i = 0; i < runs.length; i++) {
61
+ const run = runs[i]
62
+ // An odd escape consumes ONLY the first tick, leaving its unescaped suffix.
63
+ const opener = run.start + run.escaped
64
+ const length = run.end - opener
65
+ if (!length) continue
66
+ const closers = byLength.get(length) ?? []
67
+ let lo = 0, hi = closers.length
68
+ while (lo < hi) {
69
+ const mid = (lo + hi) >>> 1
70
+ if (closers[mid] <= i) lo = mid + 1
71
+ else hi = mid
72
+ }
73
+ if (lo === closers.length) continue // Unmatched opener is literal, not protection to EOF.
74
+ const next = closers[lo]
75
+ ranges.push([opener, runs[next].end])
76
+ i = next
77
+ }
78
+ return ranges
79
+ }
80
+
81
+ function protectedRanges(text, lines) {
82
+ const fenced = fences(lines, text.length)
83
+ const ranges = []
84
+ let start = 0
85
+ for (const fence of fenced) {
86
+ ranges.push(...inlineSpans(text, start, fence[0]), fence)
87
+ start = fence[1]
88
+ }
89
+ ranges.push(...inlineSpans(text, start, text.length))
90
+ return ranges
91
+ }
92
+
93
+ function removeRanges(text, offset, ranges) {
94
+ const parts = []
95
+ let at = 0
96
+ for (const [start, end] of ranges) {
97
+ const lo = Math.max(0, start - offset), hi = Math.min(text.length, end - offset)
98
+ if (lo >= hi) continue
99
+ parts.push(text.slice(at, lo))
100
+ at = hi
101
+ }
102
+ parts.push(text.slice(at))
103
+ return parts.join('')
104
+ }
105
+
106
+ function derivedTitle(body) {
107
+ for (const line of logicalLines(body)) {
108
+ const view = line.text.trim().replace(/^§[0-9]+§[ \t]*/, '').trim()
109
+ if (!view) continue
110
+ const title = Array.from(view.replace(new RegExp(TITLE_FORBIDDEN_RE.source, 'g'), '')).slice(0, 160).join('')
111
+ if (title.trim()) return title
112
+ }
113
+ return '关键回复'
114
+ }
115
+
116
+ /** No mutation outside exact original control ranges; character offsets are NOT UTF-8 byte offsets. */
117
+ export function parseReply(message) {
118
+ const blocks = Array.isArray(message.content) ? message.content : []
119
+ const original = blocks.filter(b => b.type === 'text').map(b => b.text).join('')
120
+ const unchanged = { message, ranges: [], body: original, candidate: false, reason: 'unmarked' }
121
+ if (message.role !== 'assistant') return unchanged
122
+ const lines = logicalLines(original)
123
+ const protectedCode = protectedRanges(original, lines)
124
+ const controls = []
125
+ for (const line of lines) {
126
+ const match = /^\[\[team-reply(?::((?:(?!\]\]).)*))?\]\]$/.exec(line.text)
127
+ if (!match || protectedCode.some(([lo, hi]) => lo < line.end && hi > line.start)) continue
128
+ controls.push({ ...line, explicit: match[1] })
129
+ }
130
+ if (!controls.length) return unchanged
131
+ const ranges = controls.map(line => [line.start, line.end])
132
+ let offset = 0
133
+ const content = blocks.map(block => {
134
+ if (block.type !== 'text') return block
135
+ const text = removeRanges(block.text, offset, ranges)
136
+ offset += block.text.length
137
+ return text === block.text ? block : { ...block, text }
138
+ })
139
+ const body = content.filter(b => b.type === 'text').map(b => b.text).join('')
140
+ const result = { message: { ...message, content }, ranges, body, candidate: false, reason: '' }
141
+ if (controls.length !== 1) return { ...result, reason: 'ambiguous' }
142
+ const control = controls[0]
143
+ if (!/^(?:[ \t]*\r?\n)*[ \t]*$/.test(original.slice(control.end))) return { ...result, reason: 'misplaced' }
144
+ if (!/\S/.test(body)) return { ...result, reason: 'empty-body' }
145
+ const title = control.explicit === undefined ? derivedTitle(body) : control.explicit
146
+ try { validateTitle(title) } catch { return { ...result, title, reason: 'invalid-title' } }
147
+ try {
148
+ // Buffer.from replaces lone surrogates; reject rather than silently change those bytes.
149
+ const bytes = Buffer.from(body, 'utf8')
150
+ if (bytes.toString('utf8') !== body) throw new Error('invalid UTF-8 source')
151
+ validateBody(bytes)
152
+ } catch { return { ...result, title, reason: 'invalid-body' } }
153
+ return { ...result, title, candidate: true, reason: 'candidate' }
154
+ }
155
+
156
+ const digest = value => createHash('sha256').update(value).digest('hex')
157
+ const tupleOf = identity => [identity.root, identity.state, identity.sessionId, identity.sessionFile]
158
+ export const sessionKey = identity => digest(JSON.stringify(tupleOf(identity)))
159
+ export const sourceKey = (identity, entryId) => digest(JSON.stringify([...tupleOf(identity), entryId]))
160
+ const sameIdentity = (a, b) => isDeepStrictEqual(tupleOf(a), tupleOf(b))
161
+ const statuses = new Set(['pending', 'eligible', 'attempting', 'saved', 'unconfirmed', 'not-written', 'uncertain'])
162
+
163
+ export function processIdentity(pid) {
164
+ if (!Number.isSafeInteger(pid) || pid < 1) return {}
165
+ try {
166
+ const stat = readFileSync(`/proc/${pid}/stat`, 'utf8')
167
+ const fields = stat.slice(stat.lastIndexOf(')') + 2).trim().split(/\s+/)
168
+ return { pid, starttime: fields[19], ppid: Number(fields[1]), zombie: fields[0] === 'Z' }
169
+ } catch (e) {
170
+ if (e.code === 'ENOENT') return { dead: true }
171
+ return {} // /proc inaccessible is unknown, never proof that an attempt did not run.
172
+ }
173
+ }
174
+
175
+ /** Canonical, nonsymlink ancestry. Sticky system temp parents are allowed, writable private parents are not. */
176
+ export function safeDirectory(path, create = false) {
177
+ if (!isAbsolute(path) || resolve(path) !== path) throw new Error('noncanonical directory')
178
+ let at = sep
179
+ for (const part of path.split(sep).filter(Boolean)) {
180
+ at = join(at, part)
181
+ let st
182
+ try { st = lstatSync(at) } catch (e) {
183
+ if (e.code !== 'ENOENT' || !create) throw e
184
+ mkdirSync(at, { mode: 0o700 })
185
+ st = lstatSync(at)
186
+ }
187
+ if (!st.isDirectory() || st.isSymbolicLink() || ((st.mode & 0o022) && !(st.mode & 0o1000))) throw new Error('unsafe directory ancestry')
188
+ }
189
+ if (realpathSync(path) !== path) throw new Error('directory identity changed')
190
+ return path
191
+ }
192
+
193
+ function regular(path, flags, mode = 0o600) {
194
+ const fd = openSync(path, flags | C.O_NOFOLLOW | C.O_NONBLOCK, mode)
195
+ const st = fstatSync(fd)
196
+ if (!st.isFile() || st.nlink !== 1 || (st.mode & 0o022)) {
197
+ closeSync(fd)
198
+ throw new Error('unsafe regular file')
199
+ }
200
+ return fd
201
+ }
202
+
203
+ /** Fixed flock + anchored snapshot transaction; the lock is never unlinked. */
204
+ export class CaptureJournal {
205
+ constructor(identity) {
206
+ this.identity = { ...identity }
207
+ this.directory = join(identity.state, 'reply-capture')
208
+ this.name = `${sessionKey(identity)}.json`
209
+ this.path = join(this.directory, this.name)
210
+ this.failed = false
211
+ }
212
+
213
+ validate(snapshot) {
214
+ if (snapshot.version !== 1 || !isDeepStrictEqual(snapshot.tuple, tupleOf(this.identity)) ||
215
+ !snapshot.intents || !snapshot.sources || typeof snapshot.intents !== 'object' || typeof snapshot.sources !== 'object') throw new Error('invalid capture journal')
216
+ for (const [key, record] of Object.entries(snapshot.sources)) {
217
+ if (!record || !statuses.has(record.status) || typeof record.entryId !== 'string' || !record.entryId ||
218
+ key !== sourceKey(this.identity, record.entryId) || !isDeepStrictEqual(record.source, [...snapshot.tuple, record.entryId])) throw new Error('invalid source record')
219
+ if (!successful(record.message) || record.body !== record.message.content.filter(b => b.type === 'text').map(b => b.text).join('')) throw new Error('inconsistent source content')
220
+ validateTitle(record.title)
221
+ validateBody(Buffer.from(record.body, 'utf8'))
222
+ if (['eligible', 'attempting', 'saved', 'unconfirmed', 'not-written', 'uncertain'].includes(record.status) && !record.settledLeaf) throw new Error('missing settlement witness')
223
+ if (['attempting', 'saved', 'unconfirmed', 'not-written', 'uncertain'].includes(record.status) && !record.attempt?.token) throw new Error('missing attempt evidence')
224
+ }
225
+ return snapshot
226
+ }
227
+
228
+ transact(change, { create = false } = {}) {
229
+ if (this.failed) throw new Error('capture journal disabled after transaction failure')
230
+ safeDirectory(this.identity.root)
231
+ safeDirectory(this.identity.state, create)
232
+ safeDirectory(this.directory, create)
233
+ const directory = openSync(this.directory, C.O_RDONLY | C.O_DIRECTORY | C.O_NOFOLLOW)
234
+ const dirStat = fstatSync(directory)
235
+ const anchored = name => `/proc/self/fd/${directory}/${name}`
236
+ let lock, temp
237
+ try {
238
+ lock = regular(anchored(`${this.name}.lock`), C.O_RDWR | (create ? C.O_CREAT : 0))
239
+ const held = spawnSync('flock', ['-x', '3'], { stdio: ['ignore', 'ignore', 'ignore', lock] })
240
+ if (held.error || held.status !== 0) throw new Error('capture flock unavailable')
241
+ this.checkDirectory(dirStat)
242
+ let snapshot
243
+ try {
244
+ const fd = regular(anchored(this.name), C.O_RDONLY)
245
+ try { snapshot = this.validate(JSON.parse(readFileSync(fd, 'utf8'))) } finally { closeSync(fd) }
246
+ } catch (e) {
247
+ if (e.code !== 'ENOENT' || !create) throw e
248
+ snapshot = { version: 1, tuple: tupleOf(this.identity), intents: {}, sources: {} }
249
+ }
250
+ const before = JSON.stringify(snapshot)
251
+ const result = change(snapshot)
252
+ this.validate(snapshot)
253
+ if (JSON.stringify(snapshot) !== before) {
254
+ temp = `.capture-${randomUUID()}`
255
+ const fd = regular(anchored(temp), C.O_WRONLY | C.O_CREAT | C.O_EXCL)
256
+ try { writeFileSync(fd, JSON.stringify(snapshot) + '\n'); fsyncSync(fd) } finally { closeSync(fd) }
257
+ this.checkDirectory(dirStat)
258
+ // Refuse substitution of the target, even when rename itself would safely replace it.
259
+ try { const fd = regular(anchored(this.name), C.O_RDONLY); closeSync(fd) } catch (e) { if (e.code !== 'ENOENT') throw e }
260
+ renameSync(anchored(temp), anchored(this.name))
261
+ temp = null
262
+ fsyncSync(directory)
263
+ this.checkDirectory(dirStat)
264
+ }
265
+ return result
266
+ } catch (e) {
267
+ // A missing initial journal has no recovery work; other failures disable this runtime's journal.
268
+ if (e.code !== 'ENOENT') this.failed = true
269
+ throw e
270
+ } finally {
271
+ if (temp) unlinkSync(anchored(temp))
272
+ if (lock !== undefined) closeSync(lock)
273
+ closeSync(directory)
274
+ }
275
+ }
276
+
277
+ checkDirectory(expected) {
278
+ safeDirectory(this.identity.state)
279
+ const actual = lstatSync(this.directory)
280
+ if (!actual.isDirectory() || actual.dev !== expected.dev || actual.ino !== expected.ino) throw new Error('capture directory replaced')
281
+ }
282
+ }
283
+
284
+ function branchWitness(view, startLeaf, source, settledLeaf = view.leaf) {
285
+ const ids = view.branch.map(entry => entry.id)
286
+ const start = startLeaf === null ? -1 : ids.indexOf(startLeaf)
287
+ const at = ids.indexOf(source), end = ids.indexOf(settledLeaf)
288
+ return (startLeaf === null || start >= 0) && at > start && end >= at && view.leaf === ids.at(-1)
289
+ }
290
+ const successful = m => m?.role === 'assistant' && m.stopReason === 'stop' && !m.content.some(b => b.type === 'toolCall')
291
+
292
+ /** The real command, argv-only. No shell interpolation, fake receipt, or second writer. */
293
+ export function runReplyWriter({ team, identity, env }, record) {
294
+ return new Promise(resolveResult => {
295
+ let child
296
+ try {
297
+ child = spawn('bash', [team, '--root', identity.root, 'reply', 'post', '--from', 'pm', '--title', record.title, '--stdin'], {
298
+ cwd: identity.root,
299
+ env: { ...env, TEAM_ROOT: identity.root, TEAM_MAIN_ROOT: identity.root, TEAM_STATE_DIR: identity.state, TEAM_CONFIG_FILE: identity.config },
300
+ stdio: ['pipe', 'pipe', 'pipe'],
301
+ })
302
+ } catch (e) { resolveResult({ error: e.code, started: false }); return }
303
+ let stdout = '', pipeError = false, startError
304
+ child.stdout.setEncoding('utf8')
305
+ child.stdout.on('data', data => { stdout += data })
306
+ child.stderr.resume() // Writer diagnostics can include a title; capture reports only source/status/evidence.
307
+ child.stdin.on('error', () => { pipeError = true })
308
+ child.on('error', e => { startError = e.code })
309
+ child.on('close', (status, signal) => resolveResult({ status, signal, stdout, pipeError, error: startError, started: child.pid !== undefined }))
310
+ child.stdin.end(record.body, 'utf8')
311
+ })
312
+ }
313
+
314
+ function writerOutcome(result, record) {
315
+ const number = n => Number.isSafeInteger(n) && n > 0
316
+ if (result.error === 'ENOENT' && result.started === false) return { status: 'not-written', reason: 'not-started' }
317
+ if (result.signal || result.error || result.pipeError) return { status: 'uncertain', reason: 'process-outcome' }
318
+ if ([2, 5].includes(result.status)) return { status: 'not-written', reason: result.status === 5 ? 'busy' : 'input' }
319
+ let receipt
320
+ try { receipt = JSON.parse(result.stdout) } catch { return { status: 'uncertain', reason: 'missing-or-bad-receipt' } }
321
+ const bytes = Buffer.from(record.body)
322
+ if (receipt.from !== 'pm' || receipt.title !== record.title || receipt.bytes !== bytes.length || receipt.sha256 !== digest(bytes) ||
323
+ typeof receipt.at !== 'string' || !/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.\d+)?Z$/.test(receipt.at)) return { status: 'uncertain', reason: 'inconsistent-receipt' }
324
+ if (result.status === 0 && receipt.outcome === 'saved' && number(receipt.no) && receipt.candidate_no === undefined) return { status: 'saved', no: receipt.no }
325
+ if (result.status === 6 && receipt.outcome === 'unconfirmed' && number(receipt.candidate_no) && receipt.no === undefined) return { status: 'unconfirmed', candidate_no: receipt.candidate_no }
326
+ return { status: 'uncertain', reason: 'inconsistent-outcome' }
327
+ }
328
+
329
+ /** Pi event state, deliberately independent of the host. Only view.entry/branch of the actual current session bind a source. */
330
+ export class ReplyCapture {
331
+ constructor({ identity, journal = new CaptureJournal(identity), current, verify, writer, owner, diagnostic }) {
332
+ Object.assign(this, { identity, journal, current, verify, writer, owner, diagnostic })
333
+ this.activity = null
334
+ this.running = new Set()
335
+ }
336
+ memoryHost(view) { return this.current() && sameIdentity(this.identity, view.identity) }
337
+ eligibleHost(view) { return this.memoryHost(view) && this.verify() }
338
+ report(reason, entryId = '') {
339
+ try { this.diagnostic({ reason, entryId, path: this.journal.path }) }
340
+ catch { /* An unavailable diagnostic sink must not block final message cleanup. */ }
341
+ }
342
+ before(view) {
343
+ this.activity = this.memoryHost(view) ? { id: randomUUID(), startLeaf: view.leaf, ordinal: 0, latest: null } : null
344
+ }
345
+ start(message, view) {
346
+ if (message.role !== 'assistant' || !this.activity) return
347
+ if (!this.memoryHost(view)) { this.activity = null; return }
348
+ const a = this.activity
349
+ a.latest = { ordinal: ++a.ordinal, ended: false }
350
+ }
351
+ end(message, view) {
352
+ if (!this.current()) return message
353
+ // This transform must finish even when identity, staging, locking, or disk writes fail.
354
+ const parsed = parseReply(message)
355
+ if (message.role !== 'assistant') return message
356
+ const a = this.activity, latest = a?.latest
357
+ if (!latest || latest.ended) return parsed.message
358
+ latest.ended = true
359
+ latest.message = parsed.message
360
+ if (!parsed.candidate || !successful(parsed.message)) return parsed.message
361
+ try {
362
+ if (!this.eligibleHost(view)) return parsed.message
363
+ const intent = `${a.id}:${latest.ordinal}`
364
+ this.journal.transact(snapshot => {
365
+ snapshot.intents[intent] = { status: 'unbound', activity: a.id, ordinal: latest.ordinal, startLeaf: a.startLeaf, title: parsed.title, body: parsed.body, message: parsed.message }
366
+ }, { create: true })
367
+ latest.intent = intent
368
+ } catch (e) { this.report(`stage:${e.code ?? e.name}`) }
369
+ return parsed.message
370
+ }
371
+ turn(event, view) {
372
+ const a = this.activity, latest = a?.latest
373
+ if (!latest?.intent || latest.entryId || !this.eligibleHost(view)) return
374
+ const entry = view.entry(event.messageEntryId)
375
+ if (!event.messageEntryId || entry?.type !== 'message' || !isDeepStrictEqual(entry.message, latest.message) ||
376
+ !isDeepStrictEqual(event.message, latest.message) || !branchWitness(view, a.startLeaf, event.messageEntryId)) {
377
+ latest.intent = null // A bad binding cannot be repaired by another event or current-leaf inference.
378
+ this.report('binding-mismatch', event.messageEntryId)
379
+ return
380
+ }
381
+ try {
382
+ const key = sourceKey(this.identity, event.messageEntryId)
383
+ const bound = this.journal.transact(snapshot => {
384
+ const intent = snapshot.intents[latest.intent]
385
+ if (!intent || intent.status !== 'unbound' || snapshot.sources[key]) return false
386
+ snapshot.sources[key] = { ...intent, status: 'pending', entryId: event.messageEntryId, source: [...tupleOf(this.identity), event.messageEntryId] }
387
+ delete snapshot.intents[latest.intent]
388
+ return true
389
+ })
390
+ if (bound) latest.entryId = event.messageEntryId
391
+ } catch (e) { latest.intent = null; this.report(`binding:${e.code ?? e.name}`, event.messageEntryId) }
392
+ }
393
+ settled(event, view) {
394
+ const a = this.activity, latest = a?.latest
395
+ this.activity = null
396
+ if (a && !event.aborted && latest?.entryId && latest.ended && successful(latest.message) && this.eligibleHost(view) &&
397
+ branchWitness(view, a.startLeaf, latest.entryId)) {
398
+ try {
399
+ this.journal.transact(snapshot => {
400
+ const record = snapshot.sources[sourceKey(this.identity, latest.entryId)]
401
+ if (record?.status !== 'pending' || record.activity !== a.id || record.ordinal !== latest.ordinal) return
402
+ record.status = 'eligible'
403
+ record.settledLeaf = view.leaf
404
+ })
405
+ } catch (e) { this.report(`eligibility:${e.code ?? e.name}`, latest.entryId); return }
406
+ }
407
+ if (!event.aborted) this.recover(view)
408
+ }
409
+ reset() { this.activity = null }
410
+ recover(view) {
411
+ if (this.activity || !this.eligibleHost(view)) return
412
+ let records
413
+ try {
414
+ records = this.journal.transact(snapshot => {
415
+ for (const record of Object.values(snapshot.sources)) {
416
+ if (record.status !== 'attempting') continue
417
+ const life = processIdentity(record.attempt.pid)
418
+ if (life.dead || life.zombie || (life.starttime && life.starttime !== record.attempt.starttime)) {
419
+ record.status = 'uncertain'
420
+ record.reason = 'attempt-owner-exited'
421
+ }
422
+ }
423
+ return Object.values(snapshot.sources).filter(record => record.status === 'eligible' &&
424
+ branchWitness(view, record.startLeaf, record.entryId, record.settledLeaf) &&
425
+ isDeepStrictEqual(view.entry(record.entryId)?.message, record.message))
426
+ })
427
+ } catch (e) {
428
+ if (e.code !== 'ENOENT') this.report(`recovery:${e.code ?? e.name}`)
429
+ return // Missing journal is not a reason to reconstruct entries from history.
430
+ }
431
+ for (const record of records) this.attempt(record, view)
432
+ }
433
+ attempt(record, view) {
434
+ if (this.activity || !this.eligibleHost(view)) return
435
+ const token = randomUUID()
436
+ const key = sourceKey(this.identity, record.entryId)
437
+ try {
438
+ const acquired = this.journal.transact(snapshot => {
439
+ const stored = snapshot.sources[key]
440
+ if (stored?.status !== 'eligible') return false
441
+ stored.status = 'attempting'
442
+ stored.attempt = { token, ...this.owner, at: new Date().toISOString() }
443
+ return true
444
+ })
445
+ if (!acquired || !this.eligibleHost(view)) return
446
+ } catch (e) { this.report(`attempting:${e.code ?? e.name}`, record.entryId); return }
447
+ // Durable CAS above is the barrier, including a crash right before this invocation.
448
+ const work = Promise.resolve().then(() => {
449
+ if (this.activity || !this.eligibleHost(view)) return { started: false, error: 'STALE_OWNER' }
450
+ return this.writer(record)
451
+ }).then(result => {
452
+ if (!this.current()) return // A stale callback cannot replace a newer generation's evidence.
453
+ const outcome = writerOutcome(result, record)
454
+ try {
455
+ this.journal.transact(snapshot => {
456
+ const stored = snapshot.sources[key]
457
+ if (stored?.status !== 'attempting' || stored.attempt.token !== token) return
458
+ Object.assign(stored, outcome)
459
+ })
460
+ if (outcome.status !== 'saved') this.report(outcome.reason ?? outcome.status, record.entryId)
461
+ } catch (e) { this.report(`result:${e.code ?? e.name}`, record.entryId) }
462
+ }).catch(e => this.report(`writer:${e.code ?? e.name}`, record.entryId)).finally(() => this.running.delete(work))
463
+ this.running.add(work)
464
+ }
465
+ async drain() { await Promise.all([...this.running]) }
466
+ }
467
+
468
+ function command(bin, args, cwd) {
469
+ const result = spawnSync(bin, args, { cwd, encoding: 'utf8' })
470
+ if (result.error || result.status !== 0) throw new Error(`${basename(bin)} evidence unavailable`)
471
+ return result.stdout.trim()
472
+ }
473
+ function readRegular(path) {
474
+ safeDirectory(dirname(path))
475
+ const fd = regular(path, C.O_RDONLY)
476
+ try { return readFileSync(fd, 'utf8') } finally { closeSync(fd) }
477
+ }
478
+ function ancestor(older, younger) {
479
+ const seen = new Set()
480
+ while (younger > 0 && !seen.has(younger)) {
481
+ if (older === younger) return true
482
+ seen.add(younger)
483
+ younger = processIdentity(younger).ppid
484
+ }
485
+ return false
486
+ }
487
+ function proofPid(path, pid, root) {
488
+ try {
489
+ const raw = readRegular(path).trim()
490
+ if (!/^\d+$/.test(raw) || !ancestor(Number(raw), pid)) return false
491
+ const owner = processIdentity(Number(raw))
492
+ if (!owner.starttime || owner.zombie || realpathSync(`/proc/${raw}/cwd`) !== root) return false
493
+ const btime = /^btime (\d+)$/m.exec(readFileSync('/proc/stat', 'utf8'))?.[1]
494
+ const ticks = Number(command('getconf', ['CLK_TCK']))
495
+ const started = (Number(btime) + Number(owner.starttime) / ticks) * 1000
496
+ return lstatSync(path).mtimeMs >= Math.floor(started / 1000) * 1000
497
+ } catch (e) {
498
+ if (['ENOENT', 'ELOOP', 'ENOTDIR'].includes(e.code)) return false // A vanished/replaced proof is not evidence.
499
+ throw e
500
+ }
501
+ }
502
+ function tmuxEvidence(socket, pane) {
503
+ const fields = command('tmux', ['-S', socket, 'display-message', '-p', '-t', pane,
504
+ '#{socket_path}\t#{pid}\t#{pane_id}\t#{pane_pid}\t#{session_name}\t#{window_name}\t#{pane_current_path}']).split('\t')
505
+ if (fields.length !== 7) throw new Error('incomplete tmux evidence')
506
+ return { socket: realpathSync(fields[0]), serverPid: Number(fields[1]), pane: fields[2], panePid: Number(fields[3]), session: fields[4], window: fields[5], cwd: realpathSync(fields[6]) }
507
+ }
508
+
509
+ /** Only a directed builtin PM with current local process/pane/launch evidence can own capture. */
510
+ export function resolvePMIdentity(context, env = process.env) {
511
+ const cwd = realpathSync(context.cwd), actualCwd = realpathSync(process.cwd())
512
+ if (cwd !== actualCwd) throw new Error('context/process cwd mismatch')
513
+ const root = realpathSync(command('git', ['-C', cwd, 'rev-parse', '--show-toplevel']))
514
+ const common = realpathSync(command('git', ['-C', cwd, 'rev-parse', '--path-format=absolute', '--git-common-dir']))
515
+ if (cwd !== root || dirname(common) !== root) throw new Error('not the main checkout')
516
+ safeDirectory(root)
517
+ for (const key of ['TEAM_ROOT', 'TEAM_MAIN_ROOT']) if (env[key] && realpathSync(env[key]) !== root) throw new Error('inherited root mismatch')
518
+ if (!env.TEAM_STATE_DIR || !env.TEAM_CONFIG_FILE || !env.TEAM_PM_WINDOW || !env.TEAM_SESSION) throw new Error('missing directed PM launch environment')
519
+ const state = safeDirectory(env.TEAM_STATE_DIR), config = resolve(env.TEAM_CONFIG_FILE)
520
+ if (config !== env.TEAM_CONFIG_FILE || realpathSync(config) !== config) throw new Error('noncanonical PM config')
521
+ const configBytes = readRegular(config), configStat = lstatSync(config)
522
+ if (!context.sessionId || !context.sessionFile || !isAbsolute(context.sessionFile)) throw new Error('no persistent session identity')
523
+ const sessionFile = join(safeDirectory(dirname(context.sessionFile)), basename(context.sessionFile))
524
+ if (sessionFile !== context.sessionFile) throw new Error('noncanonical session path')
525
+ try { const fd = regular(sessionFile, C.O_RDONLY); closeSync(fd) } catch (e) {
526
+ if (e.code !== 'ENOENT') throw e // Pi may name its persistent file before the first append.
527
+ }
528
+ const [socketPath, serverPid] = (env.TMUX ?? '').split(',')
529
+ if (!socketPath || !env.TMUX_PANE) throw new Error('no actual tmux pane')
530
+ const tmux = tmuxEvidence(realpathSync(socketPath), env.TMUX_PANE)
531
+ const life = processIdentity(process.pid)
532
+ if (!life.starttime || life.zombie || tmux.serverPid !== Number(serverPid) || tmux.session !== env.TEAM_SESSION ||
533
+ tmux.window !== env.TEAM_PM_WINDOW || tmux.cwd !== root || !ancestor(tmux.panePid, process.pid)) throw new Error('foreign tmux/process identity')
534
+ let proof = proofPid(join(state, 'pm.pid.spawn'), process.pid, root) ? 'spawn' : ''
535
+ if (!proof && proofPid(join(state, 'pm.pid'), process.pid, root) && /^(argv|spawn)$/.test(readRegular(join(state, 'pm.pid.proof')).trim())) proof = 'final'
536
+ if (!proof) throw new Error('no current PM launch proof')
537
+ return { root, state, config, configHash: digest(configBytes), configDev: configStat.dev, configIno: configStat.ino,
538
+ sessionId: context.sessionId, sessionFile, pid: process.pid, starttime: life.starttime, cwd, tmux }
539
+ }
540
+
541
+ /** Registry is process evidence, not a second source index. Fixed lock and atomic replacement match journal discipline. */
542
+ export function updateRuntime(identity, change) {
543
+ const directory = join(safeDirectory(identity.state), 'reply-capture')
544
+ safeDirectory(directory, true)
545
+ const dir = openSync(directory, C.O_RDONLY | C.O_DIRECTORY | C.O_NOFOLLOW), expected = fstatSync(dir)
546
+ const at = name => `/proc/self/fd/${dir}/${name}`
547
+ let lock, temp
548
+ try {
549
+ lock = regular(at('runtime.lock'), C.O_RDWR | C.O_CREAT)
550
+ const held = spawnSync('flock', ['-x', '3'], { stdio: ['ignore', 'ignore', 'ignore', lock] })
551
+ if (held.error || held.status !== 0) throw new Error('runtime flock unavailable')
552
+ let current = null
553
+ try { const fd = regular(at('runtime.json'), C.O_RDONLY); try { current = JSON.parse(readFileSync(fd, 'utf8')) } finally { closeSync(fd) } }
554
+ catch (e) { if (e.code !== 'ENOENT') throw e }
555
+ const next = change(current)
556
+ if (next === undefined) return
557
+ temp = `.runtime-${randomUUID()}`
558
+ const fd = regular(at(temp), C.O_WRONLY | C.O_CREAT | C.O_EXCL)
559
+ try { writeFileSync(fd, JSON.stringify(next) + '\n'); fsyncSync(fd) } finally { closeSync(fd) }
560
+ safeDirectory(directory)
561
+ const actual = lstatSync(directory)
562
+ if (actual.dev !== expected.dev || actual.ino !== expected.ino) throw new Error('runtime directory replaced')
563
+ try { const fd = regular(at('runtime.json'), C.O_RDONLY); closeSync(fd) } catch (e) { if (e.code !== 'ENOENT') throw e }
564
+ renameSync(at(temp), at('runtime.json')); temp = null; fsyncSync(dir)
565
+ } finally {
566
+ if (temp) unlinkSync(at(temp))
567
+ if (lock !== undefined) closeSync(lock)
568
+ closeSync(dir)
569
+ }
570
+ }
571
+
572
+ export const captureSourceFiles = ['extension/team-reply.ts', 'scripts/reply-capture.mjs', 'scripts/replies.mjs']
573
+ export const captureFingerprint = hashes => digest(JSON.stringify(captureSourceFiles.map(file => [file, hashes[file]])))
574
+ export function captureDiskFingerprint(skill) {
575
+ const hashes = Object.fromEntries(captureSourceFiles.map(file => [file, digest(readFileSync(join(skill, file)))]))
576
+ return captureFingerprint(hashes)
577
+ }
578
+ export function inspectRuntime({ root, state, config, session, window, skill }) {
579
+ let disk
580
+ try { disk = captureDiskFingerprint(skill) } catch (e) { return { state: 'unknown', reason: `disk:${e.code ?? e.name}` } }
581
+ let runtime
582
+ try { runtime = JSON.parse(readRegular(join(state, 'reply-capture/runtime.json'))) }
583
+ catch (e) { return { disk, state: 'unknown', reason: `registration:${e.code ?? e.name}` } }
584
+ const base = { disk, loaded: runtime.fingerprint, generation: runtime.generation, extension: runtime.extension, sessionId: runtime.sessionId }
585
+ try {
586
+ if (runtime.root !== realpathSync(root) || runtime.state !== realpathSync(state) || runtime.config !== realpathSync(config) ||
587
+ runtime.configHash !== digest(readRegular(config))) throw new Error('identity/config changed')
588
+ const life = processIdentity(runtime.pid)
589
+ if (life.dead || life.zombie || !life.starttime || life.starttime !== runtime.starttime || realpathSync(`/proc/${runtime.pid}/cwd`) !== runtime.cwd) throw new Error('dead/reused/foreign process')
590
+ const actual = tmuxEvidence(runtime.tmux.socket, runtime.tmux.pane)
591
+ if (!isDeepStrictEqual(actual, runtime.tmux) || actual.session !== session || actual.window !== window || !ancestor(actual.panePid, runtime.pid)) throw new Error('pane/session changed')
592
+ if (runtime.status !== 'ready') return { ...base, state: 'degraded', reason: runtime.reason ?? runtime.status }
593
+ if (runtime.fingerprint !== disk) return { ...base, state: 'stale', reason: 'disk differs from loaded source' }
594
+ return { ...base, state: 'ready', reason: 'live PM registered actual loaded source' }
595
+ } catch (e) { return { ...base, state: 'stale', reason: e.message } }
596
+ }