teamsmith 0.3.4 → 0.4.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +8 -8
- package/package.json +1 -1
- package/skills/teamsmith/CHANGELOG.md +40 -0
- package/skills/teamsmith/SKILL.md +83 -163
- package/skills/teamsmith/extension/team-notify.ts +1 -1
- package/skills/teamsmith/extension/team-reply.ts +105 -0
- package/skills/teamsmith/references/agent-adapters.md +1 -1
- package/skills/teamsmith/references/config.md +20 -11
- package/skills/teamsmith/references/migration.md +47 -3
- package/skills/teamsmith/references/protocol.md +64 -31
- package/skills/teamsmith/references/reminders.md +131 -0
- package/skills/teamsmith/references/troubleshooting.md +19 -5
- package/skills/teamsmith/references/workflows.md +18 -16
- package/skills/teamsmith/scripts/lib/cmd-agents.sh +77 -49
- package/skills/teamsmith/scripts/lib/cmd-project.sh +193 -21
- package/skills/teamsmith/scripts/lib/cmd-remind.sh +103 -0
- package/skills/teamsmith/scripts/lib/cmd-update.sh +7 -4
- package/skills/teamsmith/scripts/lib/common.sh +44 -4
- package/skills/teamsmith/scripts/lib/outbox.sh +72 -18
- package/skills/teamsmith/scripts/remind-store.mjs +529 -0
- package/skills/teamsmith/scripts/replies.mjs +9 -3
- package/skills/teamsmith/scripts/reply-capture.mjs +612 -0
- package/skills/teamsmith/scripts/state-authority.mjs +500 -0
- package/skills/teamsmith/scripts/strings/commands.tsv +2 -1
- package/skills/teamsmith/scripts/strings/help.en.tsv +16 -2
- package/skills/teamsmith/scripts/strings/help.zh.tsv +16 -2
- package/skills/teamsmith/scripts/team +1 -0
- package/skills/teamsmith/templates/AGENTS.section.md.tmpl +68 -123
- package/skills/teamsmith/templates/PROTOCOL.md.tmpl +48 -55
- package/skills/teamsmith/templates/pm-prompt.md.tmpl +126 -119
- package/skills/teamsmith/tests/checkout-shape-probe.sh +6 -5
- package/skills/teamsmith/tests/delivery-truth.sh +82 -47
- package/skills/teamsmith/tests/fixtures/delivery-truth-real/README.md +71 -23
- package/skills/teamsmith/tests/fixtures/delivery-truth-real/__pycache__/judge-second.cpython-313.pyc +0 -0
- package/skills/teamsmith/tests/fixtures/delivery-truth-real/judge-dirty-ab.py +143 -0
- package/skills/teamsmith/tests/fixtures/delivery-truth-real/judge-second.py +26 -9
- package/skills/teamsmith/tests/fixtures/delivery-truth-real/run-case.sh +92 -20
- package/skills/teamsmith/tests/fixtures/delivery-truth-real/scenario.sh +47 -3
- package/skills/teamsmith/tests/fixtures/reply-capture-provider.ts +76 -0
- package/skills/teamsmith/tests/flip-p410-order2.sh +205 -0
- package/skills/teamsmith/tests/frames/README.md +3 -1
- package/skills/teamsmith/tests/gate-guard.sh +20 -4
- package/skills/teamsmith/tests/help-surface.sh +60 -2
- package/skills/teamsmith/tests/install-shape.sh +312 -0
- package/skills/teamsmith/tests/key-replies-pty.sh +197 -21
- package/skills/teamsmith/tests/key-replies.sh +187 -68
- package/skills/teamsmith/tests/ledger-claim.sh +8 -6
- package/skills/teamsmith/tests/lib/box-judge.sh +2 -1
- package/skills/teamsmith/tests/lib/main-team-fingerprint.sh +104 -0
- package/skills/teamsmith/tests/lib/pm-window.sh +143 -0
- package/skills/teamsmith/tests/lib/reply-fixture.sh +7 -19
- package/skills/teamsmith/tests/lib/reply-guard.sh +188 -0
- package/skills/teamsmith/tests/lib/section-calls.pl +171 -0
- package/skills/teamsmith/tests/loop-inventory.tsv +7 -5
- package/skills/teamsmith/tests/meta-suite.sh +215 -0
- package/skills/teamsmith/tests/panel-b3-pty-mouse.py +154 -17
- package/skills/teamsmith/tests/panel-b3.sh +33 -4
- package/skills/teamsmith/tests/remind-cli.sh +574 -0
- package/skills/teamsmith/tests/reply-capture-real.mjs +360 -0
- package/skills/teamsmith/tests/reply-capture-real.sh +5 -0
- package/skills/teamsmith/tests/reply-capture.mjs +756 -0
- package/skills/teamsmith/tests/section-paths.tsv +40 -9
- package/skills/teamsmith/tests/section-select.sh +180 -26
- package/skills/teamsmith/tests/smoke.sh +1235 -238
- package/skills/teamsmith/tests/state-authority-node.mjs +42 -0
- package/skills/teamsmith/tests/state-authority.sh +629 -0
- package/skills/teamsmith/tests/workflow-entry.sh +123 -3
- package/skills/teamsmith-init/SKILL.md +1 -1
|
@@ -0,0 +1,612 @@
|
|
|
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
|
+
/** Groups this process can write as; a directory owned by one of them is not a foreign trust domain. */
|
|
176
|
+
const writableGroups = () => new Set([process.getgid(), process.getegid(), ...process.getgroups()])
|
|
177
|
+
/** Why a writable ancestor is unsafe: someone outside this process's groups can replace its entries. */
|
|
178
|
+
function foreignWriter(mode, gid, groups) {
|
|
179
|
+
if (mode & 0o1000) return '' // Sticky directories (system temp) protect entries the caller does not own.
|
|
180
|
+
if (mode & 0o002) return 'is other-writable'
|
|
181
|
+
if ((mode & 0o020) && !groups.has(gid)) return 'is group-writable outside the effective groups'
|
|
182
|
+
return ''
|
|
183
|
+
}
|
|
184
|
+
/** Canonical, nonsymlink ancestry. Sticky system temp parents are allowed; so are own-group 775 layouts. */
|
|
185
|
+
export function safeDirectory(path, create = false) {
|
|
186
|
+
if (!isAbsolute(path) || resolve(path) !== path) throw new Error('noncanonical directory')
|
|
187
|
+
const groups = writableGroups()
|
|
188
|
+
let at = sep
|
|
189
|
+
for (const part of path.split(sep).filter(Boolean)) {
|
|
190
|
+
at = join(at, part)
|
|
191
|
+
let st
|
|
192
|
+
try { st = lstatSync(at) } catch (e) {
|
|
193
|
+
if (e.code !== 'ENOENT' || !create) throw e
|
|
194
|
+
mkdirSync(at, { mode: 0o700 })
|
|
195
|
+
st = lstatSync(at)
|
|
196
|
+
}
|
|
197
|
+
if (!st.isDirectory() || st.isSymbolicLink()) throw new Error(`unsafe directory ancestry: ${at} is not a plain directory`)
|
|
198
|
+
const unsafe = foreignWriter(st.mode, st.gid, groups)
|
|
199
|
+
if (unsafe) throw new Error(`unsafe directory ancestry: ${at} ${unsafe}`)
|
|
200
|
+
}
|
|
201
|
+
if (realpathSync(path) !== path) throw new Error('directory identity changed')
|
|
202
|
+
return path
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
function regular(path, flags, mode = 0o600) {
|
|
206
|
+
const fd = openSync(path, flags | C.O_NOFOLLOW | C.O_NONBLOCK, mode)
|
|
207
|
+
const st = fstatSync(fd)
|
|
208
|
+
if (!st.isFile() || st.nlink !== 1 || (st.mode & 0o022)) {
|
|
209
|
+
closeSync(fd)
|
|
210
|
+
throw new Error('unsafe regular file')
|
|
211
|
+
}
|
|
212
|
+
return fd
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
/** Fixed flock + anchored snapshot transaction; the lock is never unlinked. */
|
|
216
|
+
export class CaptureJournal {
|
|
217
|
+
constructor(identity) {
|
|
218
|
+
this.identity = { ...identity }
|
|
219
|
+
this.directory = join(identity.state, 'reply-capture')
|
|
220
|
+
this.name = `${sessionKey(identity)}.json`
|
|
221
|
+
this.path = join(this.directory, this.name)
|
|
222
|
+
this.failed = false
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
validate(snapshot) {
|
|
226
|
+
if (snapshot.version !== 1 || !isDeepStrictEqual(snapshot.tuple, tupleOf(this.identity)) ||
|
|
227
|
+
!snapshot.intents || !snapshot.sources || typeof snapshot.intents !== 'object' || typeof snapshot.sources !== 'object') throw new Error('invalid capture journal')
|
|
228
|
+
for (const [key, record] of Object.entries(snapshot.sources)) {
|
|
229
|
+
if (!record || !statuses.has(record.status) || typeof record.entryId !== 'string' || !record.entryId ||
|
|
230
|
+
key !== sourceKey(this.identity, record.entryId) || !isDeepStrictEqual(record.source, [...snapshot.tuple, record.entryId])) throw new Error('invalid source record')
|
|
231
|
+
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')
|
|
232
|
+
validateTitle(record.title)
|
|
233
|
+
validateBody(Buffer.from(record.body, 'utf8'))
|
|
234
|
+
if (['eligible', 'attempting', 'saved', 'unconfirmed', 'not-written', 'uncertain'].includes(record.status) && !record.settledLeaf) throw new Error('missing settlement witness')
|
|
235
|
+
if (['attempting', 'saved', 'unconfirmed', 'not-written', 'uncertain'].includes(record.status) && !record.attempt?.token) throw new Error('missing attempt evidence')
|
|
236
|
+
}
|
|
237
|
+
return snapshot
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
transact(change, { create = false } = {}) {
|
|
241
|
+
if (this.failed) throw new Error('capture journal disabled after transaction failure')
|
|
242
|
+
safeDirectory(this.identity.root)
|
|
243
|
+
safeDirectory(this.identity.state, create)
|
|
244
|
+
safeDirectory(this.directory, create)
|
|
245
|
+
const directory = openSync(this.directory, C.O_RDONLY | C.O_DIRECTORY | C.O_NOFOLLOW)
|
|
246
|
+
const dirStat = fstatSync(directory)
|
|
247
|
+
const anchored = name => `/proc/self/fd/${directory}/${name}`
|
|
248
|
+
let lock, temp
|
|
249
|
+
try {
|
|
250
|
+
lock = regular(anchored(`${this.name}.lock`), C.O_RDWR | (create ? C.O_CREAT : 0))
|
|
251
|
+
const held = spawnSync('flock', ['-x', '3'], { stdio: ['ignore', 'ignore', 'ignore', lock] })
|
|
252
|
+
if (held.error || held.status !== 0) throw new Error('capture flock unavailable')
|
|
253
|
+
this.checkDirectory(dirStat)
|
|
254
|
+
let snapshot
|
|
255
|
+
try {
|
|
256
|
+
const fd = regular(anchored(this.name), C.O_RDONLY)
|
|
257
|
+
try { snapshot = this.validate(JSON.parse(readFileSync(fd, 'utf8'))) } finally { closeSync(fd) }
|
|
258
|
+
} catch (e) {
|
|
259
|
+
if (e.code !== 'ENOENT' || !create) throw e
|
|
260
|
+
snapshot = { version: 1, tuple: tupleOf(this.identity), intents: {}, sources: {} }
|
|
261
|
+
}
|
|
262
|
+
const before = JSON.stringify(snapshot)
|
|
263
|
+
const result = change(snapshot)
|
|
264
|
+
this.validate(snapshot)
|
|
265
|
+
if (JSON.stringify(snapshot) !== before) {
|
|
266
|
+
temp = `.capture-${randomUUID()}`
|
|
267
|
+
const fd = regular(anchored(temp), C.O_WRONLY | C.O_CREAT | C.O_EXCL)
|
|
268
|
+
try { writeFileSync(fd, JSON.stringify(snapshot) + '\n'); fsyncSync(fd) } finally { closeSync(fd) }
|
|
269
|
+
this.checkDirectory(dirStat)
|
|
270
|
+
// Refuse substitution of the target, even when rename itself would safely replace it.
|
|
271
|
+
try { const fd = regular(anchored(this.name), C.O_RDONLY); closeSync(fd) } catch (e) { if (e.code !== 'ENOENT') throw e }
|
|
272
|
+
renameSync(anchored(temp), anchored(this.name))
|
|
273
|
+
temp = null
|
|
274
|
+
fsyncSync(directory)
|
|
275
|
+
this.checkDirectory(dirStat)
|
|
276
|
+
}
|
|
277
|
+
return result
|
|
278
|
+
} catch (e) {
|
|
279
|
+
// A missing initial journal has no recovery work; other failures disable this runtime's journal.
|
|
280
|
+
if (e.code !== 'ENOENT') this.failed = true
|
|
281
|
+
throw e
|
|
282
|
+
} finally {
|
|
283
|
+
if (temp) unlinkSync(anchored(temp))
|
|
284
|
+
if (lock !== undefined) closeSync(lock)
|
|
285
|
+
closeSync(directory)
|
|
286
|
+
}
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
checkDirectory(expected) {
|
|
290
|
+
safeDirectory(this.identity.state)
|
|
291
|
+
const actual = lstatSync(this.directory)
|
|
292
|
+
if (!actual.isDirectory() || actual.dev !== expected.dev || actual.ino !== expected.ino) throw new Error('capture directory replaced')
|
|
293
|
+
}
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
function branchWitness(view, startLeaf, source, settledLeaf = view.leaf) {
|
|
297
|
+
const ids = view.branch.map(entry => entry.id)
|
|
298
|
+
const start = startLeaf === null ? -1 : ids.indexOf(startLeaf)
|
|
299
|
+
const at = ids.indexOf(source), end = ids.indexOf(settledLeaf)
|
|
300
|
+
return (startLeaf === null || start >= 0) && at > start && end >= at && view.leaf === ids.at(-1)
|
|
301
|
+
}
|
|
302
|
+
const successful = m => m?.role === 'assistant' && m.stopReason === 'stop' && !m.content.some(b => b.type === 'toolCall')
|
|
303
|
+
|
|
304
|
+
/** The real command, argv-only. No shell interpolation, fake receipt, or second writer. */
|
|
305
|
+
export function runReplyWriter({ team, identity, env }, record) {
|
|
306
|
+
return new Promise(resolveResult => {
|
|
307
|
+
let child
|
|
308
|
+
try {
|
|
309
|
+
child = spawn('bash', [team, '--root', identity.root, 'reply', 'post', '--from', 'pm', '--title', record.title, '--stdin'], {
|
|
310
|
+
cwd: identity.root,
|
|
311
|
+
env: { ...env, TEAM_ROOT: identity.root, TEAM_MAIN_ROOT: identity.root, TEAM_STATE_DIR: identity.state, TEAM_CONFIG_FILE: identity.config },
|
|
312
|
+
stdio: ['pipe', 'pipe', 'pipe'],
|
|
313
|
+
})
|
|
314
|
+
} catch (e) { resolveResult({ error: e.code, started: false }); return }
|
|
315
|
+
let stdout = '', pipeError = false, startError
|
|
316
|
+
child.stdout.setEncoding('utf8')
|
|
317
|
+
child.stdout.on('data', data => { stdout += data })
|
|
318
|
+
child.stderr.resume() // Writer diagnostics can include a title; capture reports only source/status/evidence.
|
|
319
|
+
child.stdin.on('error', () => { pipeError = true })
|
|
320
|
+
child.on('error', e => { startError = e.code })
|
|
321
|
+
child.on('close', (status, signal) => resolveResult({ status, signal, stdout, pipeError, error: startError, started: child.pid !== undefined }))
|
|
322
|
+
child.stdin.end(record.body, 'utf8')
|
|
323
|
+
})
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
function writerOutcome(result, record) {
|
|
327
|
+
const number = n => Number.isSafeInteger(n) && n > 0
|
|
328
|
+
if (result.error === 'ENOENT' && result.started === false) return { status: 'not-written', reason: 'not-started' }
|
|
329
|
+
if (result.signal || result.error || result.pipeError) return { status: 'uncertain', reason: 'process-outcome' }
|
|
330
|
+
if ([2, 5].includes(result.status)) return { status: 'not-written', reason: result.status === 5 ? 'busy' : 'input' }
|
|
331
|
+
let receipt
|
|
332
|
+
try { receipt = JSON.parse(result.stdout) } catch { return { status: 'uncertain', reason: 'missing-or-bad-receipt' } }
|
|
333
|
+
const bytes = Buffer.from(record.body)
|
|
334
|
+
if (receipt.from !== 'pm' || receipt.title !== record.title || receipt.bytes !== bytes.length || receipt.sha256 !== digest(bytes) ||
|
|
335
|
+
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' }
|
|
336
|
+
if (result.status === 0 && receipt.outcome === 'saved' && number(receipt.no) && receipt.candidate_no === undefined) return { status: 'saved', no: receipt.no }
|
|
337
|
+
if (result.status === 6 && receipt.outcome === 'unconfirmed' && number(receipt.candidate_no) && receipt.no === undefined) return { status: 'unconfirmed', candidate_no: receipt.candidate_no }
|
|
338
|
+
return { status: 'uncertain', reason: 'inconsistent-outcome' }
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
/** Pi event state, deliberately independent of the host. Only view.entry/branch of the actual current session bind a source. */
|
|
342
|
+
export class ReplyCapture {
|
|
343
|
+
constructor({ identity, journal = new CaptureJournal(identity), current, verify, writer, owner, diagnostic }) {
|
|
344
|
+
Object.assign(this, { identity, journal, current, verify, writer, owner, diagnostic })
|
|
345
|
+
this.activity = null
|
|
346
|
+
this.running = new Set()
|
|
347
|
+
}
|
|
348
|
+
memoryHost(view) { return this.current() && sameIdentity(this.identity, view.identity) }
|
|
349
|
+
eligibleHost(view) { return this.memoryHost(view) && this.verify() }
|
|
350
|
+
report(reason, entryId = '') {
|
|
351
|
+
try { this.diagnostic({ reason, entryId, path: this.journal.path }) }
|
|
352
|
+
catch { /* An unavailable diagnostic sink must not block final message cleanup. */ }
|
|
353
|
+
}
|
|
354
|
+
before(view) {
|
|
355
|
+
this.activity = this.memoryHost(view) ? { id: randomUUID(), startLeaf: view.leaf, ordinal: 0, latest: null } : null
|
|
356
|
+
}
|
|
357
|
+
start(message, view) {
|
|
358
|
+
if (message.role !== 'assistant' || !this.activity) return
|
|
359
|
+
if (!this.memoryHost(view)) { this.activity = null; return }
|
|
360
|
+
const a = this.activity
|
|
361
|
+
a.latest = { ordinal: ++a.ordinal, ended: false }
|
|
362
|
+
}
|
|
363
|
+
end(message, view) {
|
|
364
|
+
if (!this.current()) return message
|
|
365
|
+
// This transform must finish even when identity, staging, locking, or disk writes fail.
|
|
366
|
+
const parsed = parseReply(message)
|
|
367
|
+
if (message.role !== 'assistant') return message
|
|
368
|
+
const a = this.activity, latest = a?.latest
|
|
369
|
+
if (!latest || latest.ended) return parsed.message
|
|
370
|
+
latest.ended = true
|
|
371
|
+
latest.message = parsed.message
|
|
372
|
+
if (!parsed.candidate || !successful(parsed.message)) return parsed.message
|
|
373
|
+
try {
|
|
374
|
+
if (!this.eligibleHost(view)) return parsed.message
|
|
375
|
+
const intent = `${a.id}:${latest.ordinal}`
|
|
376
|
+
this.journal.transact(snapshot => {
|
|
377
|
+
snapshot.intents[intent] = { status: 'unbound', activity: a.id, ordinal: latest.ordinal, startLeaf: a.startLeaf, title: parsed.title, body: parsed.body, message: parsed.message }
|
|
378
|
+
}, { create: true })
|
|
379
|
+
latest.intent = intent
|
|
380
|
+
} catch (e) { this.report(`stage:${e.code ?? e.name}`) }
|
|
381
|
+
return parsed.message
|
|
382
|
+
}
|
|
383
|
+
turn(event, view) {
|
|
384
|
+
const a = this.activity, latest = a?.latest
|
|
385
|
+
if (!latest?.intent || latest.entryId || !this.eligibleHost(view)) return
|
|
386
|
+
const entry = view.entry(event.messageEntryId)
|
|
387
|
+
if (!event.messageEntryId || entry?.type !== 'message' || !isDeepStrictEqual(entry.message, latest.message) ||
|
|
388
|
+
!isDeepStrictEqual(event.message, latest.message) || !branchWitness(view, a.startLeaf, event.messageEntryId)) {
|
|
389
|
+
latest.intent = null // A bad binding cannot be repaired by another event or current-leaf inference.
|
|
390
|
+
this.report('binding-mismatch', event.messageEntryId)
|
|
391
|
+
return
|
|
392
|
+
}
|
|
393
|
+
try {
|
|
394
|
+
const key = sourceKey(this.identity, event.messageEntryId)
|
|
395
|
+
const bound = this.journal.transact(snapshot => {
|
|
396
|
+
const intent = snapshot.intents[latest.intent]
|
|
397
|
+
if (!intent || intent.status !== 'unbound' || snapshot.sources[key]) return false
|
|
398
|
+
snapshot.sources[key] = { ...intent, status: 'pending', entryId: event.messageEntryId, source: [...tupleOf(this.identity), event.messageEntryId] }
|
|
399
|
+
delete snapshot.intents[latest.intent]
|
|
400
|
+
return true
|
|
401
|
+
})
|
|
402
|
+
if (bound) latest.entryId = event.messageEntryId
|
|
403
|
+
} catch (e) { latest.intent = null; this.report(`binding:${e.code ?? e.name}`, event.messageEntryId) }
|
|
404
|
+
}
|
|
405
|
+
settled(event, view) {
|
|
406
|
+
const a = this.activity, latest = a?.latest
|
|
407
|
+
this.activity = null
|
|
408
|
+
if (a && !event.aborted && latest?.entryId && latest.ended && successful(latest.message) && this.eligibleHost(view) &&
|
|
409
|
+
branchWitness(view, a.startLeaf, latest.entryId)) {
|
|
410
|
+
try {
|
|
411
|
+
this.journal.transact(snapshot => {
|
|
412
|
+
const record = snapshot.sources[sourceKey(this.identity, latest.entryId)]
|
|
413
|
+
if (record?.status !== 'pending' || record.activity !== a.id || record.ordinal !== latest.ordinal) return
|
|
414
|
+
record.status = 'eligible'
|
|
415
|
+
record.settledLeaf = view.leaf
|
|
416
|
+
})
|
|
417
|
+
} catch (e) { this.report(`eligibility:${e.code ?? e.name}`, latest.entryId); return }
|
|
418
|
+
}
|
|
419
|
+
if (!event.aborted) this.recover(view)
|
|
420
|
+
}
|
|
421
|
+
reset() { this.activity = null }
|
|
422
|
+
recover(view) {
|
|
423
|
+
if (this.activity || !this.eligibleHost(view)) return
|
|
424
|
+
let records
|
|
425
|
+
try {
|
|
426
|
+
records = this.journal.transact(snapshot => {
|
|
427
|
+
for (const record of Object.values(snapshot.sources)) {
|
|
428
|
+
if (record.status !== 'attempting') continue
|
|
429
|
+
const life = processIdentity(record.attempt.pid)
|
|
430
|
+
if (life.dead || life.zombie || (life.starttime && life.starttime !== record.attempt.starttime)) {
|
|
431
|
+
record.status = 'uncertain'
|
|
432
|
+
record.reason = 'attempt-owner-exited'
|
|
433
|
+
}
|
|
434
|
+
}
|
|
435
|
+
return Object.values(snapshot.sources).filter(record => record.status === 'eligible' &&
|
|
436
|
+
branchWitness(view, record.startLeaf, record.entryId, record.settledLeaf) &&
|
|
437
|
+
isDeepStrictEqual(view.entry(record.entryId)?.message, record.message))
|
|
438
|
+
})
|
|
439
|
+
} catch (e) {
|
|
440
|
+
if (e.code !== 'ENOENT') this.report(`recovery:${e.code ?? e.name}`)
|
|
441
|
+
return // Missing journal is not a reason to reconstruct entries from history.
|
|
442
|
+
}
|
|
443
|
+
for (const record of records) this.attempt(record, view)
|
|
444
|
+
}
|
|
445
|
+
attempt(record, view) {
|
|
446
|
+
if (this.activity || !this.eligibleHost(view)) return
|
|
447
|
+
const token = randomUUID()
|
|
448
|
+
const key = sourceKey(this.identity, record.entryId)
|
|
449
|
+
try {
|
|
450
|
+
const acquired = this.journal.transact(snapshot => {
|
|
451
|
+
const stored = snapshot.sources[key]
|
|
452
|
+
if (stored?.status !== 'eligible') return false
|
|
453
|
+
stored.status = 'attempting'
|
|
454
|
+
stored.attempt = { token, ...this.owner, at: new Date().toISOString() }
|
|
455
|
+
return true
|
|
456
|
+
})
|
|
457
|
+
if (!acquired || !this.eligibleHost(view)) return
|
|
458
|
+
} catch (e) { this.report(`attempting:${e.code ?? e.name}`, record.entryId); return }
|
|
459
|
+
// Durable CAS above is the barrier, including a crash right before this invocation.
|
|
460
|
+
const work = Promise.resolve().then(() => {
|
|
461
|
+
if (this.activity || !this.eligibleHost(view)) return { started: false, error: 'STALE_OWNER' }
|
|
462
|
+
return this.writer(record)
|
|
463
|
+
}).then(result => {
|
|
464
|
+
if (!this.current()) return // A stale callback cannot replace a newer generation's evidence.
|
|
465
|
+
const outcome = writerOutcome(result, record)
|
|
466
|
+
try {
|
|
467
|
+
this.journal.transact(snapshot => {
|
|
468
|
+
const stored = snapshot.sources[key]
|
|
469
|
+
if (stored?.status !== 'attempting' || stored.attempt.token !== token) return
|
|
470
|
+
Object.assign(stored, outcome)
|
|
471
|
+
})
|
|
472
|
+
if (outcome.status !== 'saved') this.report(outcome.reason ?? outcome.status, record.entryId)
|
|
473
|
+
} catch (e) { this.report(`result:${e.code ?? e.name}`, record.entryId) }
|
|
474
|
+
}).catch(e => this.report(`writer:${e.code ?? e.name}`, record.entryId)).finally(() => this.running.delete(work))
|
|
475
|
+
this.running.add(work)
|
|
476
|
+
}
|
|
477
|
+
async drain() { await Promise.all([...this.running]) }
|
|
478
|
+
}
|
|
479
|
+
|
|
480
|
+
function command(bin, args, cwd) {
|
|
481
|
+
const result = spawnSync(bin, args, { cwd, encoding: 'utf8' })
|
|
482
|
+
if (result.error || result.status !== 0) throw new Error(`${basename(bin)} evidence unavailable`)
|
|
483
|
+
return result.stdout.trim()
|
|
484
|
+
}
|
|
485
|
+
function readRegular(path) {
|
|
486
|
+
safeDirectory(dirname(path))
|
|
487
|
+
const fd = regular(path, C.O_RDONLY)
|
|
488
|
+
try { return readFileSync(fd, 'utf8') } finally { closeSync(fd) }
|
|
489
|
+
}
|
|
490
|
+
function ancestor(older, younger) {
|
|
491
|
+
const seen = new Set()
|
|
492
|
+
while (younger > 0 && !seen.has(younger)) {
|
|
493
|
+
if (older === younger) return true
|
|
494
|
+
seen.add(younger)
|
|
495
|
+
younger = processIdentity(younger).ppid
|
|
496
|
+
}
|
|
497
|
+
return false
|
|
498
|
+
}
|
|
499
|
+
function proofPid(path, pid, root) {
|
|
500
|
+
try {
|
|
501
|
+
const raw = readRegular(path).trim()
|
|
502
|
+
if (!/^\d+$/.test(raw) || !ancestor(Number(raw), pid)) return false
|
|
503
|
+
const owner = processIdentity(Number(raw))
|
|
504
|
+
if (!owner.starttime || owner.zombie || realpathSync(`/proc/${raw}/cwd`) !== root) return false
|
|
505
|
+
const btime = /^btime (\d+)$/m.exec(readFileSync('/proc/stat', 'utf8'))?.[1]
|
|
506
|
+
const ticks = Number(command('getconf', ['CLK_TCK']))
|
|
507
|
+
const started = (Number(btime) + Number(owner.starttime) / ticks) * 1000
|
|
508
|
+
return lstatSync(path).mtimeMs >= Math.floor(started / 1000) * 1000
|
|
509
|
+
} catch (e) {
|
|
510
|
+
if (['ENOENT', 'ELOOP', 'ENOTDIR'].includes(e.code)) return false // A vanished/replaced proof is not evidence.
|
|
511
|
+
throw e
|
|
512
|
+
}
|
|
513
|
+
}
|
|
514
|
+
function tmuxEvidence(socket, pane) {
|
|
515
|
+
const fields = command('tmux', ['-S', socket, 'display-message', '-p', '-t', pane,
|
|
516
|
+
'#{socket_path}\t#{pid}\t#{pane_id}\t#{pane_pid}\t#{session_name}\t#{window_name}\t#{pane_current_path}']).split('\t')
|
|
517
|
+
if (fields.length !== 7) throw new Error('incomplete tmux evidence')
|
|
518
|
+
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]) }
|
|
519
|
+
}
|
|
520
|
+
|
|
521
|
+
/** Only a directed builtin PM with current local process/pane/launch evidence can own capture. */
|
|
522
|
+
export function resolvePMIdentity(context, env = process.env) {
|
|
523
|
+
const cwd = realpathSync(context.cwd), actualCwd = realpathSync(process.cwd())
|
|
524
|
+
if (cwd !== actualCwd) throw new Error('context/process cwd mismatch')
|
|
525
|
+
const root = realpathSync(command('git', ['-C', cwd, 'rev-parse', '--show-toplevel']))
|
|
526
|
+
const common = realpathSync(command('git', ['-C', cwd, 'rev-parse', '--path-format=absolute', '--git-common-dir']))
|
|
527
|
+
if (cwd !== root || dirname(common) !== root) throw new Error('not the main checkout')
|
|
528
|
+
safeDirectory(root)
|
|
529
|
+
for (const key of ['TEAM_ROOT', 'TEAM_MAIN_ROOT']) if (env[key] && realpathSync(env[key]) !== root) throw new Error('inherited root mismatch')
|
|
530
|
+
if (!env.TEAM_STATE_DIR || !env.TEAM_CONFIG_FILE || !env.TEAM_PM_WINDOW || !env.TEAM_SESSION) throw new Error('missing directed PM launch environment')
|
|
531
|
+
const state = safeDirectory(env.TEAM_STATE_DIR), config = resolve(env.TEAM_CONFIG_FILE)
|
|
532
|
+
if (config !== env.TEAM_CONFIG_FILE || realpathSync(config) !== config) throw new Error('noncanonical PM config')
|
|
533
|
+
const configBytes = readRegular(config), configStat = lstatSync(config)
|
|
534
|
+
if (!context.sessionId || !context.sessionFile || !isAbsolute(context.sessionFile)) throw new Error('no persistent session identity')
|
|
535
|
+
const sessionFile = join(safeDirectory(dirname(context.sessionFile)), basename(context.sessionFile))
|
|
536
|
+
if (sessionFile !== context.sessionFile) throw new Error('noncanonical session path')
|
|
537
|
+
try { const fd = regular(sessionFile, C.O_RDONLY); closeSync(fd) } catch (e) {
|
|
538
|
+
if (e.code !== 'ENOENT') throw e // Pi may name its persistent file before the first append.
|
|
539
|
+
}
|
|
540
|
+
const [socketPath, serverPid] = (env.TMUX ?? '').split(',')
|
|
541
|
+
if (!socketPath || !env.TMUX_PANE) throw new Error('no actual tmux pane')
|
|
542
|
+
const tmux = tmuxEvidence(realpathSync(socketPath), env.TMUX_PANE)
|
|
543
|
+
const life = processIdentity(process.pid)
|
|
544
|
+
if (!life.starttime || life.zombie || tmux.serverPid !== Number(serverPid) || tmux.session !== env.TEAM_SESSION ||
|
|
545
|
+
tmux.window !== env.TEAM_PM_WINDOW || tmux.cwd !== root || !ancestor(tmux.panePid, process.pid)) throw new Error('foreign tmux/process identity')
|
|
546
|
+
let proof = proofPid(join(state, 'pm.pid.spawn'), process.pid, root) ? 'spawn' : ''
|
|
547
|
+
if (!proof && proofPid(join(state, 'pm.pid'), process.pid, root) && /^(argv|spawn)$/.test(readRegular(join(state, 'pm.pid.proof')).trim())) proof = 'final'
|
|
548
|
+
if (!proof) throw new Error('no current PM launch proof')
|
|
549
|
+
return { root, state, config, configHash: digest(configBytes), configDev: configStat.dev, configIno: configStat.ino,
|
|
550
|
+
sessionId: context.sessionId, sessionFile, pid: process.pid, starttime: life.starttime, cwd, tmux }
|
|
551
|
+
}
|
|
552
|
+
|
|
553
|
+
/** Registry is process evidence, not a second source index. Fixed lock and atomic replacement match journal discipline. */
|
|
554
|
+
export function updateRuntime(identity, change) {
|
|
555
|
+
const directory = join(safeDirectory(identity.state), 'reply-capture')
|
|
556
|
+
safeDirectory(directory, true)
|
|
557
|
+
const dir = openSync(directory, C.O_RDONLY | C.O_DIRECTORY | C.O_NOFOLLOW), expected = fstatSync(dir)
|
|
558
|
+
const at = name => `/proc/self/fd/${dir}/${name}`
|
|
559
|
+
let lock, temp
|
|
560
|
+
try {
|
|
561
|
+
lock = regular(at('runtime.lock'), C.O_RDWR | C.O_CREAT)
|
|
562
|
+
const held = spawnSync('flock', ['-x', '3'], { stdio: ['ignore', 'ignore', 'ignore', lock] })
|
|
563
|
+
if (held.error || held.status !== 0) throw new Error('runtime flock unavailable')
|
|
564
|
+
let current = null
|
|
565
|
+
try { const fd = regular(at('runtime.json'), C.O_RDONLY); try { current = JSON.parse(readFileSync(fd, 'utf8')) } finally { closeSync(fd) } }
|
|
566
|
+
catch (e) { if (e.code !== 'ENOENT') throw e }
|
|
567
|
+
const next = change(current)
|
|
568
|
+
if (next === undefined) return
|
|
569
|
+
temp = `.runtime-${randomUUID()}`
|
|
570
|
+
const fd = regular(at(temp), C.O_WRONLY | C.O_CREAT | C.O_EXCL)
|
|
571
|
+
try { writeFileSync(fd, JSON.stringify(next) + '\n'); fsyncSync(fd) } finally { closeSync(fd) }
|
|
572
|
+
safeDirectory(directory)
|
|
573
|
+
const actual = lstatSync(directory)
|
|
574
|
+
if (actual.dev !== expected.dev || actual.ino !== expected.ino) throw new Error('runtime directory replaced')
|
|
575
|
+
try { const fd = regular(at('runtime.json'), C.O_RDONLY); closeSync(fd) } catch (e) { if (e.code !== 'ENOENT') throw e }
|
|
576
|
+
renameSync(at(temp), at('runtime.json')); temp = null; fsyncSync(dir)
|
|
577
|
+
} finally {
|
|
578
|
+
if (temp) unlinkSync(at(temp))
|
|
579
|
+
if (lock !== undefined) closeSync(lock)
|
|
580
|
+
closeSync(dir)
|
|
581
|
+
}
|
|
582
|
+
}
|
|
583
|
+
|
|
584
|
+
export const captureSourceFiles = ['extension/team-reply.ts', 'scripts/reply-capture.mjs', 'scripts/replies.mjs']
|
|
585
|
+
export const captureFingerprint = hashes => digest(JSON.stringify(captureSourceFiles.map(file => [file, hashes[file]])))
|
|
586
|
+
export function captureDiskFingerprint(skill) {
|
|
587
|
+
const hashes = Object.fromEntries(captureSourceFiles.map(file => [file, digest(readFileSync(join(skill, file)))]))
|
|
588
|
+
return captureFingerprint(hashes)
|
|
589
|
+
}
|
|
590
|
+
export function inspectRuntime({ root, state, config, session, window, skill }) {
|
|
591
|
+
let disk
|
|
592
|
+
try { disk = captureDiskFingerprint(skill) } catch (e) { return { state: 'unknown', reason: `disk:${e.code ?? e.name}` } }
|
|
593
|
+
// A refused ancestry is the reason registration never happened, so name the directory and the rule.
|
|
594
|
+
try { safeDirectory(root); safeDirectory(state) } catch (e) {
|
|
595
|
+
if (e.code !== 'ENOENT') return { disk, state: 'unknown', reason: `not registered: ${e.message}` }
|
|
596
|
+
}
|
|
597
|
+
let runtime
|
|
598
|
+
try { runtime = JSON.parse(readRegular(join(state, 'reply-capture/runtime.json'))) }
|
|
599
|
+
catch (e) { return { disk, state: 'unknown', reason: `registration:${e.code ?? e.name}` } }
|
|
600
|
+
const base = { disk, loaded: runtime.fingerprint, generation: runtime.generation, extension: runtime.extension, sessionId: runtime.sessionId }
|
|
601
|
+
try {
|
|
602
|
+
if (runtime.root !== realpathSync(root) || runtime.state !== realpathSync(state) || runtime.config !== realpathSync(config) ||
|
|
603
|
+
runtime.configHash !== digest(readRegular(config))) throw new Error('identity/config changed')
|
|
604
|
+
const life = processIdentity(runtime.pid)
|
|
605
|
+
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')
|
|
606
|
+
const actual = tmuxEvidence(runtime.tmux.socket, runtime.tmux.pane)
|
|
607
|
+
if (!isDeepStrictEqual(actual, runtime.tmux) || actual.session !== session || actual.window !== window || !ancestor(actual.panePid, runtime.pid)) throw new Error('pane/session changed')
|
|
608
|
+
if (runtime.status !== 'ready') return { ...base, state: 'degraded', reason: runtime.reason ?? runtime.status }
|
|
609
|
+
if (runtime.fingerprint !== disk) return { ...base, state: 'stale', reason: 'disk differs from loaded source' }
|
|
610
|
+
return { ...base, state: 'ready', reason: 'live PM registered actual loaded source' }
|
|
611
|
+
} catch (e) { return { ...base, state: 'stale', reason: e.message } }
|
|
612
|
+
}
|