@sshirkit/dsh-orchestrator 0.9.1 → 1.0.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.
@@ -0,0 +1,590 @@
1
+ import { randomUUID } from 'node:crypto'
2
+
3
+ const isId = (value) => typeof value === 'string' && value.length > 0
4
+ const isCount = (value) => Number.isSafeInteger(value) && value >= 0
5
+ const rowsOf = (value) => Array.isArray(value) ? value : []
6
+ const copy = (value) => value == null ? value : structuredClone(value)
7
+ const rootOf = ({ rootSessionId, parentId }) => rootSessionId || parentId || 'unknown'
8
+ const runOf = (runId, attemptSeq) => runId || `attempt-${attemptSeq ?? 0}`
9
+
10
+ export function makeSettleActionKey({ childId, runId, attemptSeq, ...owner } = {}) {
11
+ return `settle:${rootOf(owner)}:${childId}:${runOf(runId, attemptSeq)}`
12
+ }
13
+
14
+ export function makeResumeActionKey({ childId, interruptedRunId, attemptSeq, ...owner } = {}) {
15
+ return `resume:${rootOf(owner)}:${childId}:${runOf(interruptedRunId, attemptSeq)}`
16
+ }
17
+
18
+ export function makeRetryActionKey({ childId, failedRunId, attemptSeq, retryOrdinal, ...owner } = {}) {
19
+ return `retry:${rootOf(owner)}:${childId}:${runOf(failedRunId, attemptSeq)}:${retryOrdinal ?? 1}`
20
+ }
21
+
22
+ export function makeParentNoticeActionKey({ parentId, childId, kind, seqOrId } = {}) {
23
+ return `notice:${parentId || 'unknown'}:${childId || 'unknown'}:${kind || 'generic'}:${seqOrId ?? 0}`
24
+ }
25
+
26
+ const PHASE_REFUSALS = {
27
+ prepared: 'in-flight', accepted: 'already-accepted', unknown: 'delivery-unknown', done: 'already-done',
28
+ }
29
+
30
+ const ACTION_KEY_BUILDERS = new Map([
31
+ ['settle', makeSettleActionKey], ['resume', makeResumeActionKey], ['retry', makeRetryActionKey],
32
+ ])
33
+
34
+ // Strip only the final ordinal; a run identity can itself contain colons.
35
+ function resumeKeyForRetry(key) {
36
+ const ordinalAt = key.lastIndexOf(':')
37
+ return `resume:${key.slice('retry:'.length, ordinalAt)}`
38
+ }
39
+
40
+ /** Reserve before yielding, then persist before the caller may perform the side effect. */
41
+ export function createActionLedger({ store, initialActions = [], now = Date.now } = {}) {
42
+ const records = new Map()
43
+ const writes = new Map()
44
+
45
+ function hydrate(actions) {
46
+ for (const record of rowsOf(actions)) {
47
+ if (isId(record?.key) && !records.has(record.key)) records.set(record.key, copy(record))
48
+ }
49
+ }
50
+
51
+ function canInitiate(key, { allowRetryUnknown = false } = {}) {
52
+ const record = records.get(key)
53
+ if (!record) return { allowed: true, reason: 'new', record: null }
54
+ if (record.phase === 'unknown' && allowRetryUnknown === true) {
55
+ return { allowed: true, reason: 'unknown-retry-allowed', record: copy(record) }
56
+ }
57
+ const reason = Object.hasOwn(PHASE_REFUSALS, record.phase)
58
+ ? PHASE_REFUSALS[record.phase] : 'delivery-unknown'
59
+ return { allowed: false, reason, record: copy(record) }
60
+ }
61
+
62
+ function findWakeupConflict(key) {
63
+ if (key.startsWith('retry:')) {
64
+ const decision = canInitiate(resumeKeyForRetry(key))
65
+ return decision.allowed ? null : decision
66
+ }
67
+ if (key.startsWith('resume:')) {
68
+ for (const candidate of records.keys()) {
69
+ if (candidate.startsWith('retry:') && resumeKeyForRetry(candidate) === key) {
70
+ return canInitiate(candidate)
71
+ }
72
+ }
73
+ }
74
+ return null
75
+ }
76
+
77
+ function persist(record) {
78
+ if (typeof store?.putAction !== 'function') return Promise.resolve()
79
+ const write = (writes.get(record.key) ?? Promise.resolve()).then(async () => {
80
+ // A closed or stale store may explicitly reject a write without throwing.
81
+ if (await store.putAction(copy(record)) === false) {
82
+ throw new Error('action record was not persisted')
83
+ }
84
+ })
85
+ const tail = write.catch(() => {})
86
+ writes.set(record.key, tail)
87
+ void tail.then(() => {
88
+ if (writes.get(record.key) === tail) writes.delete(record.key)
89
+ })
90
+ return write
91
+ }
92
+
93
+ async function prepare(key, meta = {}) {
94
+ if (!isId(key)) throw new TypeError('action key must be a non-empty string')
95
+ const decision = canInitiate(key, meta)
96
+ const refusal = decision.allowed ? findWakeupConflict(key) : decision
97
+ if (refusal) return { ok: false, reason: refusal.reason, record: refusal.record }
98
+
99
+ const at = now()
100
+ const previous = decision.record
101
+ const record = {
102
+ key,
103
+ kind: previous?.kind ?? meta.kind ?? key.split(':', 1)[0],
104
+ phase: 'prepared',
105
+ rootSessionId: previous?.rootSessionId ?? meta.rootSessionId,
106
+ parentId: previous?.parentId ?? meta.parentId,
107
+ childId: previous?.childId ?? meta.childId,
108
+ runId: previous?.runId ?? meta.runId ?? meta.interruptedRunId ?? meta.failedRunId,
109
+ attemptSeq: previous?.attemptSeq ?? meta.attemptSeq,
110
+ requestId: previous?.requestId || meta.requestId || `req-${randomUUID()}`,
111
+ messageId: previous?.messageId ?? meta.messageId,
112
+ detail: copy(meta.detail ?? previous?.detail),
113
+ createdAt: previous?.createdAt ?? at,
114
+ updatedAt: at,
115
+ }
116
+ records.set(key, record)
117
+ // On an ambiguous storage failure, retain the reservation instead of reopening the gate.
118
+ await persist(record)
119
+ return { ok: true, record: copy(record) }
120
+ }
121
+
122
+ async function advance(key, phase, patch) {
123
+ const previous = records.get(key)
124
+ if (!previous) return null
125
+ if ((previous.phase === 'done' && phase !== 'done') ||
126
+ (previous.phase === 'accepted' && phase === 'unknown')) return copy(previous)
127
+
128
+ const { messageId = previous.messageId, detail = previous.detail } = patch
129
+ const record = { ...previous, phase, messageId, detail: copy(detail), updatedAt: now() }
130
+ records.set(key, record)
131
+ await persist(record)
132
+ return copy(record)
133
+ }
134
+
135
+ hydrate(initialActions)
136
+ return {
137
+ hydrate,
138
+ get: (key) => copy(records.get(key)) ?? null,
139
+ list: () => [...records.values()].map(copy),
140
+ canInitiate,
141
+ findWakeupConflict,
142
+ prepare,
143
+ async cancelPrepared(key) {
144
+ const record = records.get(key)
145
+ if (record?.phase !== 'prepared') return
146
+ await store?.deleteAction?.(key)
147
+ if (records.get(key) === record) records.delete(key)
148
+ },
149
+ markAccepted: (key, patch = {}) => advance(key, 'accepted', patch),
150
+ markUnknown: (key, patch = {}) => advance(key, 'unknown', patch),
151
+ markDone: (key, patch = {}) => advance(key, 'done', patch),
152
+ hasProcessedRun(kind, params = {}) {
153
+ const build = ACTION_KEY_BUILDERS.get(kind)
154
+ if (!build) return false
155
+ const { runId, interruptedRunId = runId, failedRunId = runId } = params
156
+ return records.has(build({ ...params, interruptedRunId, failedRunId }))
157
+ },
158
+ }
159
+ }
160
+
161
+ const NOT_FOUND_CODES = new Set(['SESSION_QUERY_SESSION_NOT_FOUND', 'SESSION_NOT_FOUND'])
162
+
163
+ async function readOnlySession(sessionQuery, sessionId, signal, consume) {
164
+ let observation
165
+ try {
166
+ signal?.throwIfAborted?.()
167
+ if (typeof sessionQuery?.observeSession === 'function') {
168
+ observation = await sessionQuery.observeSession(sessionId, { signal })
169
+ } else if (typeof sessionQuery?.readSession === 'function') {
170
+ observation = await sessionQuery.readSession(sessionId)
171
+ } else {
172
+ throw new Error('sessionQuery unavailable')
173
+ }
174
+ signal?.throwIfAborted?.()
175
+ if (observation == null || typeof observation !== 'object') {
176
+ throw new Error('sessionQuery returned no observation')
177
+ }
178
+ return consume(observation)
179
+ } finally {
180
+ observation?.[Symbol.dispose]?.()
181
+ }
182
+ }
183
+
184
+ function sessionEvidence(observation) {
185
+ return {
186
+ header: observation.header ?? observation.session ?? null,
187
+ inheritedEventCount: isCount(observation.inheritedEventCount) ? observation.inheritedEventCount : 0,
188
+ events: rowsOf(observation.events),
189
+ }
190
+ }
191
+
192
+ function extractHeadSeq(agent, sessions, childId) {
193
+ const explicit = agent?.headSeq
194
+ if (isCount(explicit)) return explicit
195
+ try {
196
+ const log = agent?.session?.log ?? sessions?.get?.(childId)?.log
197
+ if (Array.isArray(log)) {
198
+ const seq = log.at(-1)?.seq
199
+ return isCount(seq) ? seq : log.length
200
+ }
201
+ } catch {
202
+ // The head is advisory; a log read failure cannot change online presence.
203
+ }
204
+ return null
205
+ }
206
+
207
+ function unknownChild(childId, error) {
208
+ return {
209
+ childId, presence: 'unknown', alive: null, running: null, ownershipMismatch: false,
210
+ lastTurnEndKind: null, headSeq: null, error: String(error?.message || 'sessionQuery unavailable'),
211
+ evidenceSource: 'unknown',
212
+ }
213
+ }
214
+
215
+ /** Read only. In particular, neither session access path activates a cold session. */
216
+ export async function inspectHostChildState({
217
+ childId, expectedParentId, expectedRootSessionId, agents, sessions, sessionQuery, signal,
218
+ } = {}) {
219
+ if (!isId(childId)) return unknownChild(childId, new Error('invalid childId'))
220
+ let agent
221
+ try {
222
+ agent = await agents?.get?.(childId)
223
+ } catch (error) {
224
+ // Failed registry reads do not establish that a child is offline.
225
+ return unknownChild(childId, error)
226
+ }
227
+ const ownershipConflicts = (header) => Boolean(
228
+ (expectedParentId && header?.parentSession && header.parentSession !== expectedParentId) ||
229
+ (expectedRootSessionId && isId(header?.rootSessionId ?? header?.rootSession) &&
230
+ (header.rootSessionId ?? header.rootSession) !== expectedRootSessionId),
231
+ )
232
+ const onlineOwnershipMismatch = ownershipConflicts(agent?.session?.header)
233
+ const onlineIdle = agent != null && agent.status !== 'running'
234
+ if (agent?.status === 'running') {
235
+ return {
236
+ childId, presence: 'live-running', alive: true, running: true, ownershipMismatch: onlineOwnershipMismatch,
237
+ lastTurnEndKind: null, headSeq: extractHeadSeq(agent, sessions, childId), evidenceSource: 'agents',
238
+ }
239
+ }
240
+ try {
241
+ return await readOnlySession(sessionQuery, childId, signal, (observation) => {
242
+ const { header, inheritedEventCount, events } = sessionEvidence(observation)
243
+ const ownershipMismatch = onlineOwnershipMismatch || ownershipConflicts(header)
244
+ const lastEnd = events.slice(inheritedEventCount).findLast((event) =>
245
+ event?.type === 'turn/end' || event?.kind === 'turn/end')
246
+ return {
247
+ childId, presence: onlineIdle ? 'live-idle' : 'persisted-inactive', alive: onlineIdle,
248
+ running: false, ownershipMismatch, lastTurnEndKind: lastEnd?.data?.reason?.kind ?? lastEnd?.reason?.kind ?? null,
249
+ headSeq: events.length, inheritedEventCount, header,
250
+ evidenceSource: onlineIdle ? 'agents+sessionQuery' : 'sessionQuery',
251
+ }
252
+ })
253
+ } catch (error) {
254
+ if (onlineIdle) {
255
+ return {
256
+ childId, presence: 'live-idle', alive: true, running: false, ownershipMismatch: onlineOwnershipMismatch,
257
+ lastTurnEndKind: null, headSeq: extractHeadSeq(agent, sessions, childId), evidenceSource: 'agents',
258
+ }
259
+ }
260
+ if (NOT_FOUND_CODES.has(error?.code)) {
261
+ return {
262
+ childId, presence: 'not-found', alive: false, running: false, ownershipMismatch: false,
263
+ lastTurnEndKind: null, headSeq: 0, evidenceSource: 'sessionQuery',
264
+ }
265
+ }
266
+ return unknownChild(childId, error)
267
+ }
268
+ }
269
+
270
+ function noNotice(checked) {
271
+ return { checked, delivered: false, via: null, messageId: null, stopReason: null, seq: null }
272
+ }
273
+
274
+ /** A marker describes native delivery, not the identity or completion of a particular run. */
275
+ export async function inspectParentSettlementNotice({
276
+ parentId, childId, afterSeq = 0, sessionQuery, signal,
277
+ } = {}) {
278
+ if (!isId(parentId) || !isId(childId)) return noNotice(false)
279
+ const isMatch = (source) => source?.kind === 'subagent-settled' && source.senderSessionId === childId
280
+ try {
281
+ return await readOnlySession(sessionQuery, parentId, signal, (observation) => {
282
+ const { inheritedEventCount, events } = sessionEvidence(observation)
283
+ const start = Math.max(inheritedEventCount, isCount(afterSeq) ? afterSeq : 0)
284
+ for (let index = events.length - 1; index >= start; index -= 1) {
285
+ const event = events[index]
286
+ const data = event?.data
287
+ const type = event?.type ?? event?.kind
288
+ let message
289
+ let source
290
+ let via
291
+ if (type === 'agent/inbox/spliced') {
292
+ message = rowsOf(data?.inserted).findLast((row) => isMatch(row?.source))
293
+ source = message?.source
294
+ via = 'inbox'
295
+ } else if (type === 'user/message') {
296
+ message = data?.message ?? data
297
+ source = isMatch(data?.source) ? data.source : message?.source
298
+ via = 'user-message'
299
+ }
300
+ if (isMatch(source)) {
301
+ const messageId = message?.id ?? message?.messageId ?? data?.messageId
302
+ const stopReason = source.stopReason ?? message?.stopReason ?? data?.stopReason
303
+ return {
304
+ checked: true, delivered: true, via,
305
+ messageId: isId(messageId) ? messageId : null,
306
+ stopReason: isId(stopReason) ? stopReason : null,
307
+ seq: isCount(event.seq) ? event.seq : index + 1,
308
+ }
309
+ }
310
+ }
311
+ return noNotice(true)
312
+ })
313
+ } catch {
314
+ return noNotice(false)
315
+ }
316
+ }
317
+
318
+ export function evaluateWakeupGate({
319
+ actionLedger, worktrees, hostState, kind, rootSessionId, parentId, childId, runId, attemptSeq, retryOrdinal,
320
+ } = {}) {
321
+ const deny = (reason) => ({ allowed: false, reason })
322
+ const lock = worktrees?.isChildLocked?.(childId)
323
+ if (Boolean(lock && (lock === true || lock.locked))) return deny('worktree-child-locked')
324
+ if (hostState?.running === true) return deny('already-running')
325
+ if (!hostState || hostState.presence === 'unknown' || hostState.ownershipMismatch === true) {
326
+ return deny('host-state-unverified')
327
+ }
328
+ if (hostState.presence === 'not-found') return deny('child-not-found')
329
+ if (kind !== 'resume' && kind !== 'retry') return deny('invalid-kind')
330
+
331
+ const identity = { rootSessionId, parentId, childId, attemptSeq }
332
+ const resumeKey = makeResumeActionKey({ ...identity, interruptedRunId: runId })
333
+ const resume = actionLedger?.canInitiate?.(resumeKey)
334
+ if (resume?.allowed === false) return deny(resume.reason)
335
+
336
+ const retryKey = kind === 'retry' ? makeRetryActionKey({ ...identity, failedRunId: runId, retryOrdinal }) : null
337
+ if (retryKey) {
338
+ const retry = actionLedger?.canInitiate?.(retryKey)
339
+ if (retry?.allowed === false) return deny(retry.reason)
340
+ }
341
+ const conflict = actionLedger?.findWakeupConflict?.(resumeKey)
342
+ if (conflict) return deny(conflict.reason)
343
+ return { allowed: true, reason: 'ok', actionKey: retryKey ?? resumeKey, resumeKey, retryKey }
344
+ }
345
+
346
+ const TERMINAL_STATES = new Set(['ended', 'completed', 'aborted', 'interrupted', 'failed', 'lost'])
347
+ const FAILURE_REASONS = new Set(['error', 'blocked', 'max-tokens'])
348
+
349
+ function buildRetrySnapshotFromDelegates(delegates, actions) {
350
+ const records = []
351
+ const seenRuns = new Map()
352
+ function rememberRun(runId, childId) {
353
+ if (isId(runId) && !seenRuns.get(runId)) seenRuns.set(runId, isId(childId) ? childId : null)
354
+ }
355
+ for (const delegate of delegates) {
356
+ const retry = delegate?.retry
357
+ if (!retry || !isId(delegate.childId)) continue
358
+ for (const record of Array.isArray(retry.records) ? retry.records : [retry]) {
359
+ if (!record || (record.childId && record.childId !== delegate.childId)) continue
360
+ const parentId = record.parentId ?? delegate.parentId
361
+ if (isId(parentId)) {
362
+ records.push({ ...record, childId: delegate.childId, parentId, label: record.label ?? delegate.label })
363
+ }
364
+ }
365
+ for (const run of rowsOf(retry.seenRuns)) {
366
+ if (run?.childId && run.childId !== delegate.childId) continue
367
+ rememberRun(run?.runId ?? run, delegate.childId)
368
+ }
369
+ }
370
+ for (const action of actions) {
371
+ if (action?.kind === 'settle' && action.phase === 'done') rememberRun(action.runId, action.childId)
372
+ }
373
+ return {
374
+ records,
375
+ seenRuns: [...seenRuns].map(([runId, childId]) => childId ? { runId, childId } : runId),
376
+ }
377
+ }
378
+
379
+ function terminalState(reason) {
380
+ if (reason === 'completed' || reason === 'aborted') return { dispatchState: reason, stopReason: reason }
381
+ if (FAILURE_REASONS.has(reason)) return { dispatchState: 'failed', stopReason: reason }
382
+ return { dispatchState: 'interrupted', stopReason: 'interrupted' }
383
+ }
384
+
385
+ async function deleteLeases(store, ids) {
386
+ if (ids.length === 0) return
387
+ if (typeof store?.deleteLeases === 'function') await store.deleteLeases(ids)
388
+ else for (const id of ids) await store?.deleteLease?.(id)
389
+ }
390
+
391
+ function isDelegateLease(lease) {
392
+ return lease?.ownerKind === 'delegate' || lease?.ownerKind === 'child'
393
+ }
394
+
395
+ function leaseOwner(lease) {
396
+ if (lease?.ownerKind != null) return isDelegateLease(lease) ? lease.ownerId ?? lease.childId : null
397
+ return lease?.childId
398
+ }
399
+
400
+ async function updateTimeline(timeline, record) {
401
+ if (typeof timeline?.upsert === 'function') await timeline.upsert(record)
402
+ else if (typeof timeline?.update === 'function') await timeline.update(record)
403
+ else await timeline?.hydrateEntries?.([record])
404
+ }
405
+
406
+ /** Restore protections first; reconciliation only reads the host and never wakes a child. */
407
+ export async function reconcileOnStartup({
408
+ snapshot, store, worktrees, leases, timeline, retry, supervise, actionLedger,
409
+ agents, sessions, sessionQuery, now = Date.now, signal, logger,
410
+ onReattachRunning, onDelegateReconciled, onDelegateUpdated, hasPendingEnd, onProtectionUnverified,
411
+ readOnly = false, decorateTimeline = (record) => record,
412
+ } = {}) {
413
+ const at = now()
414
+ const delegates = rowsOf(snapshot?.delegates)
415
+ const leaseRows = rowsOf(snapshot?.leases)
416
+ const actions = rowsOf(snapshot?.actions)
417
+ const ledger = actionLedger ?? createActionLedger({ store, now })
418
+
419
+ const worktreeRows = rowsOf(snapshot?.worktrees)
420
+ const hydratedTrees = await worktrees?.hydrateRecords?.(worktreeRows)
421
+ const hydrated = await leases?.hydrateLeases?.(leaseRows, { now: at })
422
+ if (hydratedTrees?.skipped > 0 || hydrated?.skippedInvalid > 0) {
423
+ readOnly = true
424
+ onProtectionUnverified?.()
425
+ }
426
+ const expiredIds = Array.isArray(hydrated?.expiredLeaseIds)
427
+ ? hydrated.expiredLeaseIds
428
+ : leaseRows.filter((row) => Number.isFinite(row?.expiresAt) && row.expiresAt <= at).map((row) => row.leaseId)
429
+ const expired = new Set(expiredIds.filter(isId))
430
+ if (!readOnly) await deleteLeases(store, [...expired])
431
+ await timeline?.hydrateEntries?.(delegates.map(decorateTimeline))
432
+ await ledger.hydrate?.(actions)
433
+ await retry?.hydrateState?.(buildRetrySnapshotFromDelegates(delegates, actions), { now: at })
434
+
435
+ const summary = {
436
+ reattachedRunning: 0, settledDuringOffline: 0, interruptedChildren: 0, lostChildren: 0,
437
+ unknownChildren: 0, keptLeases: 0, releasedLeases: 0, expiredLeases: expired.size,
438
+ }
439
+ const leaseById = new Map(leaseRows.filter((row) => isId(row?.leaseId)).map((row) => [row.leaseId, row]))
440
+ const leasesByChild = new Map()
441
+ for (const lease of leaseById.values()) {
442
+ const owner = leaseOwner(lease)
443
+ if (expired.has(lease.leaseId) || !isId(owner)) continue
444
+ const owned = leasesByChild.get(owner) ?? []
445
+ owned.push(lease.leaseId)
446
+ leasesByChild.set(owner, owned)
447
+ }
448
+ const knownLeaseIds = new Set([...leaseById.keys(), ...rowsOf(await leases?.list?.()).map((row) => row?.leaseId)])
449
+ const accounted = new Set(expired)
450
+ const batchMatches = (lease, record) => isId(record.batchId) && lease?.ownerKind === 'batch' &&
451
+ (lease.ownerId === record.batchId || lease.ownerId === `${record.batchId}:item:${record.itemIndex}`) &&
452
+ lease.parentId === record.parentId
453
+ const pendingBatchStages = new Map()
454
+ for (const record of delegates) {
455
+ if (batchMatches(leaseById.get(record.leaseId), record)) {
456
+ const stages = pendingBatchStages.get(record.leaseId) ?? new Set()
457
+ stages.add(record.childId)
458
+ pendingBatchStages.set(record.leaseId, stages)
459
+ }
460
+ }
461
+ const inspect = (childId, expectedParentId, expectedRootSessionId) => inspectHostChildState({
462
+ childId, expectedParentId, expectedRootSessionId, agents, sessions, sessionQuery, signal,
463
+ })
464
+
465
+ function keep(id) {
466
+ if (!isId(id) || accounted.has(id)) return
467
+ accounted.add(id)
468
+ summary.keptLeases += 1
469
+ }
470
+
471
+ async function release(id) {
472
+ if (!isId(id) || accounted.has(id)) return
473
+ if (typeof store?.deleteLease === 'function') await store.deleteLease(id)
474
+ else await deleteLeases(store, [id])
475
+ await leases?.release?.(id)
476
+ accounted.add(id)
477
+ summary.releasedLeases += 1
478
+ }
479
+
480
+ for (const record of delegates) {
481
+ signal?.throwIfAborted?.()
482
+ if (!isId(record?.childId)) continue
483
+ const { childId, parentId, rootSessionId, runId, leaseId } = record
484
+ const childLeases = new Set(leasesByChild.get(childId))
485
+ if (isId(leaseId) && !expired.has(leaseId) && (knownLeaseIds.has(leaseId) || await leases?.get?.(leaseId))) {
486
+ childLeases.add(leaseId)
487
+ }
488
+ if (TERMINAL_STATES.has(record.dispatchState) && record.auditState !== 'pending' && childLeases.size === 0) continue
489
+
490
+ const host = await inspect(childId, parentId, rootSessionId)
491
+ signal?.throwIfAborted?.()
492
+ const leaseMismatch = [...childLeases].some((id) => {
493
+ const stored = leaseById.get(id)
494
+ const owner = leaseOwner(stored)
495
+ if (batchMatches(stored, record)) return false
496
+ return (stored?.ownerKind != null && !isDelegateLease(stored)) ||
497
+ (isId(owner) && owner !== childId) ||
498
+ (isId(parentId) && isId(stored?.parentId) && stored.parentId !== parentId)
499
+ })
500
+ const pendingEnd = () => hasPendingEnd?.(record) === true
501
+ if ((host.presence === 'unknown' && !pendingEnd()) || host.ownershipMismatch || leaseMismatch) {
502
+ for (const id of childLeases) keep(id)
503
+ summary.unknownChildren += 1
504
+ try {
505
+ logger?.warn?.(`orchestrator: startup reconciliation could not verify child ${childId}; retaining protections`)
506
+ } catch {
507
+ // A logger must not change the decision.
508
+ }
509
+ continue
510
+ }
511
+ if (host.presence === 'live-running' || pendingEnd()) {
512
+ for (const id of childLeases) keep(id)
513
+ if (record.watchCursor != null) {
514
+ await supervise?.hydrateCursor?.(childId, record.watchCursor, {
515
+ currentRunId: runId, currentHeadSeq: host.headSeq, now: at,
516
+ })
517
+ }
518
+ await onReattachRunning?.(record, host)
519
+ summary.reattachedRunning += 1
520
+ continue
521
+ }
522
+
523
+ if (readOnly) continue
524
+ if (record.wakeActionKey && ledger.get?.(record.wakeActionKey)?.phase !== 'done') {
525
+ // Offline state can describe the prior run, not a possibly dispatched new activation.
526
+ for (const id of childLeases) keep(id)
527
+ summary.unknownChildren += 1
528
+ continue
529
+ }
530
+ const lost = host.presence === 'not-found'
531
+ const terminal = lost ? { dispatchState: 'lost', stopReason: 'lost' } : terminalState(host.lastTurnEndKind)
532
+ const outcome = lost ? 'lost' : terminal.dispatchState === 'interrupted' ? 'interrupted' : 'settled-offline'
533
+ const updated = { ...record, ...terminal, endedAt: record.endedAt ?? at, updatedAt: at }
534
+ if (record.auditState === 'pending') updated.auditState = 'incomplete'
535
+ if (lost || record.auditState === 'pending') updated.incomplete = true
536
+ const batchStages = pendingBatchStages.get(leaseId)
537
+ if (!batchStages && (isId(leaseId) || childLeases.size > 0 || lost)) updated.leaseState = 'released'
538
+ if (!lost && sessionQuery && isId(parentId)) {
539
+ const notice = await inspectParentSettlementNotice({
540
+ parentId, childId, afterSeq: record.parentNoticeAfterSeq ?? record.parentHeadSeq, sessionQuery, signal,
541
+ })
542
+ if (notice.delivered) updated.nativeNoticeDetected = true
543
+ }
544
+ signal?.throwIfAborted?.()
545
+ if (pendingEnd()) {
546
+ for (const id of childLeases) keep(id)
547
+ await onReattachRunning?.(record, host)
548
+ summary.reattachedRunning += 1
549
+ continue
550
+ }
551
+ if (await store?.putDelegate?.(updated) === false) throw new Error('delegate record was not persisted')
552
+ batchStages?.delete(childId)
553
+ for (const id of childLeases) if (!pendingBatchStages.has(id)) await release(id)
554
+ await updateTimeline(timeline, decorateTimeline(updated))
555
+ await onDelegateReconciled?.(updated, host, outcome)
556
+ await onDelegateUpdated?.(updated, host, outcome)
557
+ if (lost) summary.lostChildren += 1
558
+ else if (outcome === 'interrupted') summary.interruptedChildren += 1
559
+ else summary.settledDuringOffline += 1
560
+ }
561
+
562
+ if (readOnly) return { actionLedger: ledger, summary }
563
+ for (const [id, lease] of leaseById) {
564
+ signal?.throwIfAborted?.()
565
+ if (accounted.has(id)) continue
566
+ const stages = pendingBatchStages.get(id)
567
+ if (stages) {
568
+ if (stages.size > 0) keep(id)
569
+ else {
570
+ await release(id)
571
+ for (const record of delegates.filter((row) => row.leaseId === id)) {
572
+ const updated = store?.getDelegate?.(record.childId) ?? record
573
+ await updateTimeline(timeline, decorateTimeline({ ...updated, leaseState: 'released' }))
574
+ }
575
+ }
576
+ continue
577
+ }
578
+ const childId = leaseOwner(lease)
579
+ if (!isId(childId)) {
580
+ keep(id)
581
+ continue
582
+ }
583
+ const host = await inspect(childId, lease.parentId, lease.rootSessionId)
584
+ signal?.throwIfAborted?.()
585
+ if ((host.presence === 'not-found' || host.presence === 'live-idle' || host.presence === 'persisted-inactive') &&
586
+ host.running === false && !host.ownershipMismatch) await release(id)
587
+ else keep(id)
588
+ }
589
+ return { actionLedger: ledger, summary }
590
+ }
package/lib/retry.js CHANGED
@@ -131,7 +131,9 @@ export function createRetry({
131
131
  maxRecords = MAX_RECORDS,
132
132
  } = {}) {
133
133
  const records = new Map()
134
- const seenRuns = new Set()
134
+ const seenRuns = new Map()
135
+ const isId = (value) => typeof value === 'string' && value !== ''
136
+ const isCount = (value) => Number.isSafeInteger(value) && value >= 0
135
137
 
136
138
  const warn = (message) => {
137
139
  try {
@@ -141,9 +143,9 @@ export function createRetry({
141
143
  }
142
144
  }
143
145
 
144
- const rememberRun = (runId) => {
145
- seenRuns.add(runId)
146
- while (seenRuns.size > MAX_RUNS) seenRuns.delete(seenRuns.values().next().value)
146
+ const rememberRun = (runId, childId) => {
147
+ if (!seenRuns.has(runId) || (!seenRuns.get(runId) && childId)) seenRuns.set(runId, childId)
148
+ while (seenRuns.size > MAX_RUNS) seenRuns.delete(seenRuns.keys().next().value)
147
149
  }
148
150
 
149
151
  const remember = (childId, record) => {
@@ -152,6 +154,64 @@ export function createRetry({
152
154
  while (records.size > maxRecords) records.delete(records.keys().next().value)
153
155
  }
154
156
 
157
+ function exportRecord(childId, record) {
158
+ const { parentId, label, attemptStartedAt, retries, fastFailures } = record
159
+ return { childId, parentId, label: typeof label === 'string' ? label : null,
160
+ attemptStartedAt, retries, fastFailures }
161
+ }
162
+
163
+ function exportState() {
164
+ return {
165
+ records: [...records].map(([childId, record]) => exportRecord(childId, record)),
166
+ seenRuns: [...seenRuns.keys()],
167
+ }
168
+ }
169
+
170
+ function exportChildRecord(childId) {
171
+ const record = records.get(childId)
172
+ return {
173
+ records: record ? [exportRecord(childId, record)] : [],
174
+ seenRuns: [...seenRuns].filter(([, owner]) => owner === childId).map(([runId]) => runId),
175
+ }
176
+ }
177
+
178
+ function hydrateState(state, options = {}) {
179
+ const result = { restored: 0, skipped: 0, restoredRuns: 0 }
180
+ const at = Number.isFinite(options.now) ? options.now : now()
181
+ for (const row of Array.isArray(state?.records) ? state.records : []) {
182
+ if (!isId(row?.childId) || !isId(row.parentId) || !Number.isFinite(row.attemptStartedAt) ||
183
+ !isCount(row.retries) || !isCount(row.fastFailures)) {
184
+ result.skipped += 1
185
+ continue
186
+ }
187
+ const { childId, parentId, retries, fastFailures } = row
188
+ const attemptStartedAt = Math.min(row.attemptStartedAt, at)
189
+ const previous = records.get(childId)
190
+ if (previous && (previous.parentId !== parentId || previous.attemptStartedAt > attemptStartedAt ||
191
+ (previous.attemptStartedAt === attemptStartedAt &&
192
+ (previous.retries > retries || previous.fastFailures > fastFailures)))) {
193
+ result.skipped += 1
194
+ continue
195
+ }
196
+ // Waiting to restore is not evidence of a successful long-running attempt. Keep
197
+ // the counters; settle applies the usual window to the actual attempt timestamp.
198
+ remember(childId, { parentId, label: typeof row.label === 'string' ? row.label : null,
199
+ attemptStartedAt, retries, fastFailures })
200
+ result.restored += 1
201
+ }
202
+ // A whole-table snapshot has global run IDs. Only a known per-child row can
203
+ // establish ownership (even a whole-table snapshot with one active child can
204
+ // contain runs from children whose retry records have already settled).
205
+ const childId = isId(options.childId) ? options.childId : undefined
206
+ for (const row of Array.isArray(state?.seenRuns) ? state.seenRuns : []) {
207
+ const runId = typeof row === 'string' ? row : row?.runId
208
+ if (!isId(runId)) continue
209
+ if (!seenRuns.has(runId)) result.restoredRuns += 1
210
+ rememberRun(runId, childId ?? (isId(row?.childId) ? row.childId : undefined))
211
+ }
212
+ return result
213
+ }
214
+
155
215
  /** One notice on the parent; a missing adapter or a failure is reported, never thrown. */
156
216
  const wake = async (parentId, text, childId) => {
157
217
  if (typeof wakeParent !== 'function') return 'unavailable'
@@ -164,6 +224,9 @@ export function createRetry({
164
224
  }
165
225
 
166
226
  return {
227
+ exportState,
228
+ exportChildRecord,
229
+ hydrateState,
167
230
  /**
168
231
  * Remember a freshly dispatched child. The record is what makes a later settlement
169
232
  * actionable: an unknown child is never retried, so a worker started by the host's
@@ -202,7 +265,7 @@ export function createRetry({
202
265
  if (record === undefined) return 'untracked'
203
266
  if (typeof runId === 'string' && runId !== '') {
204
267
  if (seenRuns.has(runId)) return 'duplicate'
205
- rememberRun(runId)
268
+ rememberRun(runId, childId)
206
269
  }
207
270
  // A completed child, or one that left a closing message, is done: its work reached
208
271
  // the parent, and a retry would duplicate it.