@sshirkit/dsh-orchestrator 0.9.2 → 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.
package/lib/supervise.js CHANGED
@@ -17,6 +17,9 @@
17
17
  * text extractors below, kept in one place because host fields may change.
18
18
  */
19
19
 
20
+ import { posix } from 'node:path'
21
+ import { SCOPE_KIND, coversPath, isNormalizedScope, normalizeScope } from './write-scope.js'
22
+
20
23
  /**
21
24
  * `source.kind` the wiring should put on the queued message, so a second notice
22
25
  * for the same parent can be recognized as already pending.
@@ -81,7 +84,12 @@ const NOTICE_HINT = [
81
84
  'A) 方向正确(无需干预):严禁调用任何工具,仅回复一行「巡检:正常」并立刻结束本回合;',
82
85
  'B) 跑偏或打转:禁止回复「巡检:正常」,请直接用调研工具或 send_message 纠偏;',
83
86
  'C) 需中止或换路:禁止回复「巡检:正常」,请先说明原因并用中断/控制或已有工具调整执行路线。',
84
- ].join('\n')
87
+ ]
88
+ const ATTENTION_WARNING = '待确认审计项不得验收为通过;「巡检:正常」仅表示运行方向无须干预,不代表审计通过。'
89
+ const ATTENTION_HINT = [
90
+ '请对仍在运行的子代理作出决定(本回合已硬禁止调用 todo_write):',
91
+ ...NOTICE_HINT.slice(1),
92
+ ]
85
93
 
86
94
  // ---------------------------------------------------------------------------
87
95
  // Event adapters: the one place that knows the host field names.
@@ -158,6 +166,10 @@ function normalizeArgs(value) {
158
166
  }
159
167
  }
160
168
 
169
+ function toolSignature(event, name = toolName(event)) {
170
+ return `${name}\u0000${stableKey(toolArgs(event) ?? null)}`
171
+ }
172
+
161
173
  /** Stable string for an arbitrary JSON-ish value: object key order does not matter. */
162
174
  function stableKey(value) {
163
175
  const seen = new WeakSet()
@@ -194,27 +206,28 @@ function stableKey(value) {
194
206
  * `{ type: 'text', text }` parts, and the `{ message: ... }` / `{ content: ... }`
195
207
  * wrappers the log may use. Non-text parts are ignored.
196
208
  */
197
- function extractText(value) {
209
+ function extractText(value, plainOnly = false) {
198
210
  if (typeof value === 'string') return value
199
211
  if (Array.isArray(value)) {
200
212
  let text = ''
201
- for (const part of value) text += extractText(part)
213
+ for (const part of value) text += extractText(part, plainOnly)
202
214
  return text
203
215
  }
204
216
  if (value !== null && typeof value === 'object') {
217
+ if (plainOnly && value.type !== undefined && value.type !== 'text') return ''
205
218
  if (typeof value.text === 'string') return value.text
206
219
  if (typeof value.content === 'string') return value.content
207
- if (Array.isArray(value.content)) return extractText(value.content)
208
- if (value.message !== undefined) return extractText(value.message)
220
+ if (Array.isArray(value.content)) return extractText(value.content, plainOnly)
221
+ if (value.message !== undefined) return extractText(value.message, plainOnly)
209
222
  if (typeof value.delta === 'string') return value.delta
210
223
  }
211
224
  return ''
212
225
  }
213
226
 
214
- function assistantText(event) {
227
+ function assistantText(event, plainOnly = false) {
215
228
  const data = eventData(event)
216
229
  for (const candidate of [data.message, data.text, data.content, data.delta]) {
217
- const text = extractText(candidate)
230
+ const text = extractText(candidate, plainOnly)
218
231
  if (text.trim() !== '') return text.trim()
219
232
  }
220
233
  return ''
@@ -246,6 +259,324 @@ function maxRepeatCount(signatures) {
246
259
  return best
247
260
  }
248
261
 
262
+ // ---------------------------------------------------------------------------
263
+ // Runtime semantics, not a protocol for the worker's final report.
264
+ // ---------------------------------------------------------------------------
265
+
266
+ const DIAGNOSES = Object.freeze({
267
+ scope_drift: ['high', '越界漂移'],
268
+ error_loop: ['medium-high', '连续碰壁'],
269
+ tool_loop: ['medium', '原地打转'],
270
+ stalled: ['medium', '停滞无进展'],
271
+ advancing: ['normal', '正常推进'],
272
+ })
273
+ const ERROR_WINDOW = 4
274
+ const ERROR_STREAK_WINDOW = 20
275
+ const ERROR_THRESHOLD = 3
276
+ const HOTSPOT_WINDOW = 6
277
+ const EVIDENCE_LIMIT = 4
278
+ const TARGET_KEYS = ['path', 'file_path', 'filePath', 'target', 'paths']
279
+ const EXPLICIT_OUTPUT_KEYS = ['output_path', 'outputPath', 'destination_path', 'destinationPath']
280
+ const OUTPUT_KEYS = [...EXPLICIT_OUTPUT_KEYS, 'destination', 'dest', 'to']
281
+ const WRITE_TOOL = /^(?:apply_patch|(?:write|edit|multi_edit|patch|delete|remove|create|append|replace|rename|move|copy)(?:_(?:file|files|directory|dir|text))?|mkdir|rmdir|file_(?:write|edit|patch|delete|move|copy))$/
282
+ const SHELL_TOOL = /^(?:bash|sh|shell|terminal|exec_command|run_command|powershell)$/
283
+ const LOOKUP_TOOL = /^(?:read(?:_file)?|read_image|glob|grep|list(?:_files|_directory)?|search(?:_files)?|web_fetch|web_search)$/
284
+
285
+ function toolLeaf(name) {
286
+ return typeof name === 'string' ? name.split('__').at(-1).toLowerCase().replace(/-/g, '_') : ''
287
+ }
288
+
289
+ function oneLine(text, size = 120) {
290
+ return typeof text === 'string' ? clip(text.replace(/[\u0000-\u001f\u007f\u2028\u2029]/g, ' ').trim(), size) : ''
291
+ }
292
+
293
+ function literalTarget(value) {
294
+ return typeof value === 'string' && value.trim() !== '' && !/[\u0000-\u001f]/.test(value)
295
+ }
296
+
297
+ function shellLiteral(token) {
298
+ if (/^[<>&;|]/.test(token)) return undefined
299
+ const target = token.replace(/^(['"])(.*)\1$/, '$2')
300
+ if (!literalTarget(target) || /[$`*?'"%(){}]/.test(target) || /^~(?:[\\/]|$)/.test(target)) return undefined
301
+ if (/^(?:\/dev\/|(?:nul|con|conout\$|conin\$)(?:[:.]|$))/i.test(target)) return undefined
302
+ return target
303
+ }
304
+
305
+ /** Recognize literal redirections and simple write commands without evaluating shell text. */
306
+ function shellTargets(args) {
307
+ const command = args?.command ?? args?.cmd
308
+ if (typeof command !== 'string' || /[\r\n]|<<|\\[<>]/.test(command)) return { paths: [], changesDirectory: false }
309
+ const tokens = command.match(/(?:'[^']*'|"(?:\\.|[^"\\])*"|[^\s'"<>;&|]+)+|>>?|[<;&|]+/g) ?? []
310
+ const changesDirectory = tokens.some((token) => /^(?:cd|pushd|popd|Set-Location)$/i.test(token))
311
+ const paths = []
312
+ for (let index = 0; index < tokens.length - 1; index += 1) {
313
+ if (tokens[index] !== '>' && tokens[index] !== '>>') continue
314
+ const target = shellLiteral(tokens[index + 1])
315
+ if (target !== undefined) paths.push(target)
316
+ }
317
+
318
+ const [program, ...operands] = tokens
319
+ // Do not guess option values, expansion, or destinations of compound commands.
320
+ if (/^(?:touch|mkdir|rmdir|rm|mv|cp)$/.test(program) && operands.length > 0 &&
321
+ operands.every((token) => !token.startsWith('-') && shellLiteral(token) !== undefined)) {
322
+ if (program === 'cp' && operands.length === 2) paths.push(shellLiteral(operands.at(-1)))
323
+ else if (program !== 'cp' && (program !== 'mv' || operands.length === 2)) {
324
+ paths.push(...operands.map(shellLiteral))
325
+ }
326
+ }
327
+ return { paths, changesDirectory }
328
+ }
329
+
330
+ function writeIntent(name, args) {
331
+ const leaf = toolLeaf(name)
332
+ const writes = WRITE_TOOL.test(leaf)
333
+ const keys = writes ? [...TARGET_KEYS, ...OUTPUT_KEYS] : EXPLICIT_OUTPUT_KEYS
334
+ const targets = keys.flatMap((key) => [args?.[key]].flat()).filter(literalTarget)
335
+ if (/^(?:move|rename)(?:_|$)|^file_move$/.test(leaf)) {
336
+ targets.push(...[args?.source, args?.src, args?.from].filter(literalTarget))
337
+ }
338
+ if (leaf === 'apply_patch' || leaf === 'patch') {
339
+ const patch = typeof args === 'string' ? args : args?.patch ?? args?.input
340
+ if (typeof patch === 'string') {
341
+ for (const match of patch.matchAll(/^\*\*\* (?:Add File|Update File|Delete File|Move to): (.+)$/gm)) {
342
+ if (literalTarget(match[1].trim())) targets.push(match[1].trim())
343
+ }
344
+ }
345
+ }
346
+ const shell = SHELL_TOOL.test(leaf) ? shellTargets(args) : undefined
347
+ if (shell) targets.push(...shell.paths)
348
+ return {
349
+ writes: writes || targets.length > 0,
350
+ targets: [...new Set(targets)],
351
+ changesDirectory: shell?.changesDirectory === true,
352
+ workdir: shell ? args?.workdir ?? args?.cwd : undefined,
353
+ }
354
+ }
355
+
356
+ function relativeKey(value, windows) {
357
+ const path = posix.normalize(windows ? value.replace(/\\/g, '/') : value).replace(/\/$/, '')
358
+ return windows ? path.toLowerCase() : path
359
+ }
360
+
361
+ const ROOTED_PATH = /^(?:[\\/]|[A-Za-z]:|~(?:[\\/]|$))/
362
+
363
+ function commandCwd(workdir, cwd) {
364
+ if (!literalTarget(workdir)) return cwd
365
+ const resolved = normalizeScope(workdir, cwd).entries?.[0]?.path
366
+ // The scope helper emits portable slash-separated UNC paths; restore the flavour for its cwd input.
367
+ return resolved?.startsWith('//') ? resolved.replace(/\//g, '\\') : resolved ?? workdir
368
+ }
369
+
370
+ /** Unknown cwd or an unresolvable target is not evidence of a boundary violation. */
371
+ function scopeCheck(writeScope, cwd) {
372
+ const normalized = isNormalizedScope(writeScope) ? writeScope : normalizeScope(writeScope, cwd).entries
373
+ if (normalized) {
374
+ if (normalized.some(({ kind }) => kind === SCOPE_KIND.root)) return () => false
375
+ return (target, targetCwd) => {
376
+ const options = { cwd: targetCwd }
377
+ return normalizeScope(target, options.cwd).ok && !coversPath(normalized, target, options)
378
+ }
379
+ }
380
+ const entries = typeof writeScope === 'string' ? [writeScope] : writeScope
381
+ if (cwd || !Array.isArray(entries) || entries.length === 0 || entries.some((entry) =>
382
+ !literalTarget(entry) || ROOTED_PATH.test(entry) || /[*?]/.test(entry.replace(/[\\/]\*\*[\\/]*$/, ''))
383
+ )) return () => false
384
+
385
+ // Without a cwd, two relative paths still share a lexical coordinate system.
386
+ return (target, targetCwd) => {
387
+ if (targetCwd || ROOTED_PATH.test(target) || /[*?]/.test(target)) return false
388
+ const windows = target.includes('\\') || entries.some((entry) => entry.includes('\\'))
389
+ const key = relativeKey(target, windows)
390
+ return !entries.some((entry) => {
391
+ const dir = /[\\/](?:\*\*[\\/]*)?$/.test(entry)
392
+ const base = relativeKey(entry.replace(/[\\/]\*\*[\\/]*$/, '') || '.', windows)
393
+ if (base === key) return dir || !/[\\/]$/.test(target)
394
+ if (!dir) return false
395
+ if (base === '.') return key !== '..' && !key.startsWith('../')
396
+ return key.startsWith(`${base}/`)
397
+ })
398
+ }
399
+ }
400
+
401
+ function resultMarker(event, tool) {
402
+ const data = eventData(event)
403
+ const blocks = [data, data.result, data.output, data.message, data.meta, data.result?.meta]
404
+ const forced = eventName(event) === 'tool/error' || blocks.some((block) =>
405
+ block?.isError === true || block?.is_error === true || block?.success === false || block?.ok === false ||
406
+ Boolean(block?.error)
407
+ )
408
+ const knownLookupSuccess = !forced && LOOKUP_TOOL.test(toolLeaf(tool)) && blocks.some((block) =>
409
+ block?.isError === false || block?.is_error === false || block?.success === true || block?.ok === true
410
+ )
411
+ for (const block of blocks) {
412
+ const code = asNumber(block?.exitCode ?? block?.exit_code)
413
+ if (code !== undefined && code !== 0) return `[exit code: ${code}]`
414
+ // A successful read/search can legitimately return source code containing error markers.
415
+ if (knownLookupSuccess) continue
416
+ const text = extractText(block, true) || extractText(block?.output, true) || extractText(block?.stderr, true)
417
+ for (const match of text.matchAll(/\[exit code:\s*(-?\d+)\s*\]/gi)) {
418
+ if (Number(match[1]) !== 0) return `[exit code: ${match[1]}]`
419
+ }
420
+ const marker = text.match(/\b(?:ENOENT|EACCES|FAILED)\b|\b(?:[A-Za-z]+)?Error:/)
421
+ if (marker) return marker[0]
422
+ }
423
+ if (forced) {
424
+ const code = data.error?.code ?? data.result?.error?.code
425
+ return typeof code === 'string' && /^[A-Z0-9_-]+$/.test(code) ? oneLine(code, 48) : '工具错误标记'
426
+ }
427
+ return undefined
428
+ }
429
+
430
+ function callIdentity(data) {
431
+ return data.callId ?? data.toolCallId ?? data.tool_call_id ?? data.message?.toolCallId ?? data.message?.source?.callId
432
+ }
433
+
434
+ function remember(list, item, max) {
435
+ if (list.length === max) list.shift()
436
+ list.push(item)
437
+ }
438
+
439
+ function trailingCount(items, matches) {
440
+ let count = 0
441
+ for (let index = items.length - 1; index >= 0 && matches(items[index]); index -= 1) count += 1
442
+ return count
443
+ }
444
+
445
+ /**
446
+ * Classify an ordered, parsed runtime log without I/O, clocks or report tags.
447
+ * `prevSummary` is the preceding scan's summary (or just its `lastSeq`); `elapsedMs`
448
+ * is the time since that scan, or since the worker began on its first inspection.
449
+ * Optional `now`/`startedAt` let the first scan use timestamps rather than guessing
450
+ * wall time. `runSinceSeq` excludes activity before a cold resume.
451
+ */
452
+ export function classifyProgress(events, context = {}) {
453
+ const {
454
+ writeScope, readOnly, cwd, prevSummary, elapsedMs, now, startedAt,
455
+ sinceSeq, runSinceSeq, repeatThreshold, stalledAfterMs,
456
+ } = context ?? {}
457
+ const runSince = asNumber(runSinceSeq)
458
+ const since = asNumber(prevSummary?.lastSeq ?? sinceSeq) ?? runSince
459
+ const watchFrom = since !== undefined && runSince !== undefined ? Math.max(since, runSince) : since
460
+ const checkScope = scopeCheck(writeScope, cwd)
461
+ const calls = []
462
+ const results = []
463
+ const violations = []
464
+ const inFlight = new Map()
465
+ let lastCall
466
+ let lastText = ''
467
+ let lastTextOrder = -1
468
+ let lastProgressAt = asNumber(startedAt)
469
+ let progressed = false
470
+ let scopeViolations = 0
471
+ let order = 0
472
+
473
+ for (const event of Array.isArray(events) ? events : []) {
474
+ if (event === null || typeof event !== 'object') continue
475
+ const seq = eventSeq(event)
476
+ if (runSince !== undefined && seq !== undefined && seq <= runSince) continue
477
+ const data = eventData(event)
478
+ const type = eventName(event)
479
+ const fresh = watchFrom === undefined || seq === undefined || seq > watchFrom
480
+ order += 1
481
+
482
+ if (type === 'tool/call') {
483
+ const tool = toolName(event)
484
+ if (!tool) continue
485
+ const call = { seq, tool, order, event }
486
+ remember(calls, call, REPEAT_WINDOW)
487
+ const id = callIdentity(data)
488
+ if (id !== undefined) inFlight.set(id, call)
489
+ lastCall = call
490
+ if (fresh && (readOnly === true || writeScope !== undefined)) {
491
+ const args = toolArgs(event)
492
+ const { writes, targets, changesDirectory, workdir } = writeIntent(tool, args)
493
+ const targetCwd = commandCwd(workdir, cwd)
494
+ const bad = readOnly === true && writes ? (targets.length ? targets : [undefined])
495
+ : changesDirectory ? [] : targets.filter((target) => checkScope(target, targetCwd))
496
+ for (const target of bad) {
497
+ scopeViolations += 1
498
+ remember(violations, { seq, tool, target: target === undefined ? undefined : oneLine(target) }, EVIDENCE_LIMIT)
499
+ }
500
+ }
501
+ } else if (type === 'tool/result' || type === 'tool/error') {
502
+ const id = callIdentity(data)
503
+ const call = id === undefined ? lastCall : inFlight.get(id)
504
+ const tool = toolName(event) ?? call?.tool
505
+ if (id !== undefined) inFlight.delete(id)
506
+ remember(results, { seq, tool, event }, ERROR_STREAK_WINDOW)
507
+ } else if (type === 'assistant/message' || type === 'assistant/delta') {
508
+ const text = assistantText(event, true).replace(/\s+/g, ' ')
509
+ if (text === '' || text === lastText) continue
510
+ lastText = text
511
+ lastTextOrder = order
512
+ } else if (type !== 'step/start' && type !== 'step/end' && type !== 'turn/start') {
513
+ continue
514
+ }
515
+ const time = eventTime(event)
516
+ if (time !== undefined) lastProgressAt = Math.max(lastProgressAt ?? time, time)
517
+ if (fresh) progressed = true
518
+ }
519
+
520
+ for (const call of calls) call.signature = toolSignature(call.event, call.tool)
521
+ const outcomes = results.map(({ seq, tool, event }) => ({ seq, tool, marker: resultMarker(event, tool) }))
522
+ const lastResult = outcomes.at(-1)
523
+ const lastSignature = calls.at(-1)?.signature
524
+ const errorStreak = trailingCount(outcomes, ({ marker }) => marker !== undefined)
525
+ const repeatStreak = trailingCount(calls, ({ signature }) => signature === lastSignature)
526
+ const metrics = { errorStreak, repeatStreak, scopeViolations, toolCallsInWindow: calls.length }
527
+ const diagnostic = (status, reason, evidence = []) => {
528
+ const [severity, label] = DIAGNOSES[status]
529
+ return { status, severity, label, reason, evidence, metrics }
530
+ }
531
+
532
+ if (scopeViolations > 0) {
533
+ const { tool, target } = violations.at(-1)
534
+ const detail = target ? `(目标:${target})` : ''
535
+ const reason = readOnly === true ? `只读子代理调用了 ${oneLine(tool, 48)}${detail}`
536
+ : `${oneLine(tool, 48)} 的写入目标不在声明作用域内${detail}`
537
+ return diagnostic('scope_drift', reason, violations)
538
+ }
539
+ const recentOutcomes = outcomes.slice(-ERROR_WINDOW)
540
+ const failures = recentOutcomes.filter(({ marker }) => marker !== undefined)
541
+ if (lastResult?.marker !== undefined && failures.length >= ERROR_THRESHOLD) {
542
+ const description = errorStreak >= ERROR_THRESHOLD ? `最近连续 ${errorStreak} 次工具结果失败`
543
+ : `最近 ${recentOutcomes.length} 次工具结果中 ${failures.length} 次失败,最新一次仍未恢复`
544
+ const tool = lastResult.tool ? `${oneLine(lastResult.tool, 48)}:` : ''
545
+ return diagnostic('error_loop', `${description}(${tool}${lastResult.marker})`, failures)
546
+ }
547
+ const threshold = positiveInteger(repeatThreshold, DEFAULTS.repeatThreshold)
548
+ const callEvidence = ({ seq, tool }) => ({ seq, tool })
549
+ if (repeatStreak >= threshold) {
550
+ const tool = oneLine(lastCall.tool, 48)
551
+ return diagnostic('tool_loop', `检测到同一工具调用连续重复 ${repeatStreak} 次,可能原地打转(${tool})`,
552
+ calls.slice(-Math.min(repeatStreak, EVIDENCE_LIMIT)).map(callEvidence))
553
+ }
554
+ const hotspot = calls.slice(-Math.max(HOTSPOT_WINDOW, 2 * threshold))
555
+ if (hotspot.length >= Math.max(HOTSPOT_WINDOW, 2 * threshold) && hotspot[0].order > lastTextOrder &&
556
+ hotspot.every(({ tool }) => LOOKUP_TOOL.test(toolLeaf(tool)))) {
557
+ const counts = new Map()
558
+ for (const { signature } of hotspot) counts.set(signature, (counts.get(signature) ?? 0) + 1)
559
+ if (counts.size <= 2 && [...counts.values()].every((count) => count >= threshold)) {
560
+ return diagnostic('tool_loop', `最近 ${hotspot.length} 次工具调用反复查询 ${counts.size} 组相同参数,期间无新文本推进`,
561
+ hotspot.slice(-EVIDENCE_LIMIT).map(callEvidence))
562
+ }
563
+ }
564
+
565
+ const elapsed = asNumber(elapsedMs)
566
+ const at = asNumber(now)
567
+ const idleFor = at !== undefined && lastProgressAt !== undefined ? Math.max(0, at - lastProgressAt) : undefined
568
+ // A still-running tool gets one additional window; a newly completed tool counts as progress.
569
+ const patience = positiveNumber(stalledAfterMs, DEFAULTS.intervalSeconds * 1000) * (inFlight.size > 0 ? 2 : 1)
570
+ const quietLongEnough = !progressed && (elapsed === undefined ? prevSummary !== undefined : elapsed >= patience)
571
+ if (quietLongEnough || (idleFor !== undefined && idleFor >= patience)) {
572
+ const duration = idleFor ?? elapsed
573
+ const span = duration === undefined ? '自上次巡检以来' : `近 ${formatDuration(duration)} 内`
574
+ return diagnostic('stalled', `${span}未观察到新增工具调用、有效步骤或文本推进`,
575
+ [{ lastProgressAt, idleMs: duration, inFlightTools: inFlight.size }])
576
+ }
577
+ return diagnostic('advancing', '未发现明显异常推进模式')
578
+ }
579
+
249
580
  // ---------------------------------------------------------------------------
250
581
  // summarize
251
582
  // ---------------------------------------------------------------------------
@@ -259,9 +590,10 @@ function maxRepeatCount(signatures) {
259
590
  * the distant past stops warning once the child moves on.
260
591
  *
261
592
  * Missing fields are tolerated: an absent `seq` simply cannot be "new", and an
262
- * absent `time` leaves the corresponding timestamp undefined.
593
+ * absent `time` leaves the corresponding timestamp undefined. `semantic` adds
594
+ * a runtime diagnosis and accepts the optional `classifyProgress` context.
263
595
  */
264
- export function summarize(events, { sinceSeq = 0, now, startedAt } = {}) {
596
+ export function summarize(events, { sinceSeq = 0, now, startedAt, ...context } = {}) {
265
597
  const list = Array.isArray(events) ? events : []
266
598
  const since = asNumber(sinceSeq) ?? 0
267
599
  const at = asNumber(now) ?? Date.now()
@@ -276,7 +608,7 @@ export function summarize(events, { sinceSeq = 0, now, startedAt } = {}) {
276
608
  let lastTool
277
609
  let lastToolAt
278
610
  let lastText = ''
279
- const signatures = []
611
+ const recentCalls = []
280
612
 
281
613
  for (const event of list) {
282
614
  if (event === null || typeof event !== 'object') continue
@@ -302,8 +634,7 @@ export function summarize(events, { sinceSeq = 0, now, startedAt } = {}) {
302
634
  if (tool !== undefined) {
303
635
  lastTool = tool
304
636
  lastToolAt = time
305
- const args = toolArgs(event)
306
- signatures.push(`${tool}\u0000${stableKey(args === undefined ? null : args)}`)
637
+ remember(recentCalls, { event, tool }, REPEAT_WINDOW)
307
638
  }
308
639
  } else if (name === 'assistant/message') {
309
640
  const text = assistantText(event)
@@ -318,11 +649,18 @@ export function summarize(events, { sinceSeq = 0, now, startedAt } = {}) {
318
649
  toolCalls,
319
650
  lastTool,
320
651
  lastToolAt,
321
- repeated: maxRepeatCount(signatures),
652
+ repeated: maxRepeatCount(recentCalls.map(({ event, tool }) => toolSignature(event, tool))),
322
653
  lastText,
323
654
  lastSeq,
324
655
  lastActivityAt,
325
656
  newEvents,
657
+ semantic: classifyProgress(list, {
658
+ ...context,
659
+ sinceSeq: since,
660
+ now,
661
+ startedAt: started,
662
+ elapsedMs: context.elapsedMs ?? (started === undefined ? undefined : Math.max(0, at - started)),
663
+ }),
326
664
  }
327
665
  }
328
666
 
@@ -356,11 +694,32 @@ function formatDuration(ms) {
356
694
  return `${seconds}s`
357
695
  }
358
696
 
697
+ function renderAttentionRow(row, number, childId, label, textLimit) {
698
+ const status = row.auditState === 'pending' ? '审计仍 pending' : '审计未通过(failed)'
699
+ const lines = [
700
+ `${number}) 子代理 ${childId}(已结束,${status};不得验收为通过)`,
701
+ ` 任务:${label}`,
702
+ ]
703
+ const summary = oneLine(row.summary, textLimit)
704
+ if (summary !== '') lines.push(` 审计摘要:${summary}`)
705
+ return lines.join('\n')
706
+ }
707
+
359
708
  function renderRow(row, number, textLimit, at, threshold) {
360
709
  const childId = typeof row.childId === 'string' && row.childId !== '' ? row.childId : '(未知)'
361
710
  const label = typeof row.label === 'string' && row.label !== '' ? row.label : '未命名'
711
+ if (row.kind === 'attention') return renderAttentionRow(row, number, childId, label, textLimit)
712
+
362
713
  const started = asNumber(row.startedAt)
363
714
  const runMs = started === undefined ? 0 : Math.max(0, at - started)
715
+ if (row.kind === 'sibling') {
716
+ const status = row.status ?? '同行在跑,本拍仅展示'
717
+ return [
718
+ `${number}) 子代理 ${childId}(${status})`,
719
+ ` 任务:${label} | 已运行 ${formatDuration(runMs)}`,
720
+ ].join('\n')
721
+ }
722
+
364
723
  const turns = nonNegativeInteger(row.turns, 0)
365
724
  const steps = nonNegativeInteger(row.steps, 0)
366
725
  const toolCalls = nonNegativeInteger(row.toolCalls, 0)
@@ -377,7 +736,11 @@ function renderRow(row, number, textLimit, at, threshold) {
377
736
  if (lastText !== '' && textLimit > 0) {
378
737
  lines.push(` 最后输出:${clip(lastText, textLimit)} [仅最新文本前${textLimit}字摘录,不代表最终成败]`)
379
738
  }
380
- if (repeated >= threshold) {
739
+ const semantic = row.semantic
740
+ if (semantic && semantic.status !== 'advancing') {
741
+ lines.push(` 语义诊断:[${oneLine(semantic.label, 24)}] ${oneLine(semantic.reason, 200)}`)
742
+ } else if (!semantic && repeated >= threshold) {
743
+ // Rows from older callers still get their original warning.
381
744
  lines.push(` ⚠ 检测到同一工具调用连续重复 ${repeated} 次,可能原地打转`)
382
745
  }
383
746
  if (row.newEvents === 0) {
@@ -387,13 +750,10 @@ function renderRow(row, number, textLimit, at, threshold) {
387
750
  }
388
751
 
389
752
  /**
390
- * Build the Chinese notice for one parent's due children.
391
- *
392
- * The result is strictly at most `maxChars` long. When it does not fit, each
393
- * child's `lastText` is shortened first; only if that is not enough are children
394
- * dropped from the end of the list, with a line saying how many were left out.
395
- * `index`/`max` are the notice number for that child and the per-child budget
396
- * (`max = 0` means unlimited, rendered as "第 N 次").
753
+ * Build one parent's panoramic notice. Legacy rows without `kind` are treated
754
+ * as triggers. Trim excerpts first, then omit siblings before triggers and
755
+ * audit warnings. The unabridged rows remain available to the delivery adapter.
756
+ * `index`/`max` describe the trigger budget (`max = 0` means unlimited).
397
757
  */
398
758
  export function composeNotice(rows, { now, index, max, maxChars = 2000, repeatThreshold = 3 } = {}) {
399
759
  const at = asNumber(now) ?? Date.now()
@@ -402,6 +762,12 @@ export function composeNotice(rows, { now, index, max, maxChars = 2000, repeatTh
402
762
  const limitChars = positiveInteger(maxChars, DEFAULTS.noticeMaxChars)
403
763
  const threshold = positiveInteger(repeatThreshold, DEFAULTS.repeatThreshold)
404
764
  const allRows = Array.isArray(rows) ? rows.filter((row) => row !== null && typeof row === 'object') : []
765
+ const triggers = allRows.filter((row) => row.kind !== 'attention' && row.kind !== 'sibling')
766
+ const attention = allRows.filter((row) => row.kind === 'attention')
767
+ const siblings = allRows.filter((row) => row.kind === 'sibling')
768
+ // Keep the first trigger and at least one audit warning ahead of extra rows.
769
+ const orderedRows = [...triggers.slice(0, 1), ...attention, ...triggers.slice(1), ...siblings]
770
+ const hint = attention.length > 0 ? ATTENTION_HINT : NOTICE_HINT
405
771
 
406
772
  const header =
407
773
  noticeMax > 0
@@ -410,16 +776,17 @@ export function composeNotice(rows, { now, index, max, maxChars = 2000, repeatTh
410
776
 
411
777
  const build = (keep, textLimit) => {
412
778
  const parts = [header]
779
+ if (attention.length > 0) parts.push(ATTENTION_WARNING)
413
780
  for (let i = 0; i < keep; i += 1) {
414
- parts.push(renderRow(allRows[i], i + 1, textLimit, at, threshold))
781
+ parts.push(renderRow(orderedRows[i], i + 1, textLimit, at, threshold))
415
782
  }
416
- const dropped = allRows.length - keep
783
+ const dropped = orderedRows.length - keep
417
784
  if (dropped > 0) parts.push(`另有 ${dropped} 个子代理未列出。`)
418
- parts.push(NOTICE_HINT)
785
+ parts.push(...hint)
419
786
  return parts.join('\n')
420
787
  }
421
788
 
422
- for (let keep = allRows.length; keep >= 1; keep -= 1) {
789
+ for (let keep = orderedRows.length; keep >= 1; keep -= 1) {
423
790
  for (const textLimit of TEXT_LIMITS) {
424
791
  const candidate = build(keep, textLimit)
425
792
  if (candidate.length <= limitChars) return candidate
@@ -467,11 +834,15 @@ function errorMessage(error) {
467
834
  *
468
835
  * - `config`: a plain object read on every `tick`, so an interval change applies
469
836
  * from the next tick; partially specified fields fall back to `DEFAULTS`.
470
- * `intervalSeconds` is the minimum age of a child before it is reported.
837
+ * `intervalSeconds` is the minimum age before a child can trigger a notice.
471
838
  * - `now()`, `isParentAlive(parentId)`, `isChildAlive(childId)`,
472
- * `readEvents(childId)`, `hasPendingNotice(parentId)`,
473
- * `deliver(parentId, text, childIds, { rows, composeMeta })`, `logger`. The async ones may return a
474
- * value or a Promise.
839
+ * `readEvents(childId)`, `hasPendingNotice(parentId)`, optional
840
+ * `hasActiveSupervisionTurn(parentId)` and `listAttentionItems(parentId)`,
841
+ * `deliver(parentId, text, childIds, { rows, composeMeta })`, `logger`.
842
+ * The adapters other than `now` may return a value or a Promise.
843
+ * - `deliver` receives active child ids only. Rows tagged `attention` are ended
844
+ * children with unconfirmed audits; `sibling` rows are display-only.
845
+ * - `track` accepts optional child metadata: `writeScope`, `readOnly`, `cwd`.
475
846
  *
476
847
  * `tick` never throws because of one child or parent: read, summarize, pending
477
848
  * check and delivery failures are logged and skipped (or retried next interval).
@@ -501,6 +872,13 @@ export function createSupervisor(options = {}) {
501
872
  }
502
873
  }
503
874
 
875
+ const idOrNull = (value) => typeof value === 'string' && value !== '' ? value : null
876
+ const countOr = (value, fallback) => Number.isSafeInteger(value) && value >= 0 ? value : fallback
877
+ const timeOr = (value, fallback) => Number.isFinite(value) ? value : fallback
878
+ const copyScope = (scope) => Array.isArray(scope)
879
+ ? scope.map((claim) => isNormalizedScope([claim]) ? { ...claim } : claim)
880
+ : scope
881
+
504
882
  const track = (entry) => {
505
883
  if (entry === null || typeof entry !== 'object') return
506
884
  const childId = entry.childId
@@ -508,33 +886,132 @@ export function createSupervisor(options = {}) {
508
886
  if (typeof childId !== 'string' || childId === '') return
509
887
  if (typeof parentId !== 'string' || parentId === '') return
510
888
 
889
+ const runId = idOrNull(entry.runId)
890
+ const previous = entries.get(childId)
891
+ if (runId !== null && previous?.runId === runId && previous.parentId === parentId) {
892
+ // A duplicate attach may enrich metadata, but cannot rewind the same run.
893
+ if (typeof entry.label === 'string') previous.label = entry.label
894
+ if (typeof entry.readOnly === 'boolean') previous.readOnly = entry.readOnly
895
+ if (entry.writeScope !== undefined) previous.writeScope = copyScope(entry.writeScope)
896
+ if (entry.cwd !== undefined) previous.cwd = entry.cwd
897
+ return
898
+ }
511
899
  const config = readConfig(opts.config)
512
900
  const intervalMs = intervalMsOf(config)
513
901
  const startedAt = asNumber(entry.startedAt) ?? currentTime()
514
- const previous = entries.get(childId)
515
902
  // A resumed worker is a new run of the same task: the interrupt that stopped it was
516
903
  // not the child's fault, so its notice budget starts over. Its log still holds the
517
904
  // pre-interrupt history, which must not be reported as fresh activity, so the
518
905
  // baseline is the caller's head-of-log mark when it has one.
519
- const resumed = entry.resumed === true
520
- const sinceSeq = asNumber(entry.sinceSeq)
906
+ const newRun = runId !== null && previous?.runId != null && runId !== previous.runId
907
+ const resumed = entry.resumed === true || newRun
908
+ const sinceSeq = resumed ? asNumber(entry.sinceSeq) ?? (newRun ? 0 : previous?.lastSeq ?? 0) : undefined
521
909
  entries.set(childId, {
522
910
  childId,
523
911
  parentId,
912
+ runId: runId ?? (resumed ? null : previous?.runId ?? null),
524
913
  label: typeof entry.label === 'string' && entry.label !== '' ? entry.label : '',
525
914
  startedAt,
526
915
  nextDueAt: startedAt + intervalMs,
527
916
  // A plain re-track refreshes the task and the deadline but keeps the budget used.
528
917
  noticesSent: resumed ? 0 : previous?.noticesSent ?? 0,
529
- lastSeq: resumed ? sinceSeq ?? previous?.lastSeq ?? 0 : 0,
918
+ lastSeq: sinceSeq ?? 0,
919
+ runSinceSeq: sinceSeq,
920
+ writeScope: copyScope(entry.writeScope),
921
+ readOnly: entry.readOnly === true,
922
+ cwd: entry.cwd,
530
923
  intervalMs,
531
924
  })
532
925
  }
533
926
 
927
+ function exportCursor(childId) {
928
+ const entry = entries.get(childId)
929
+ if (!entry) return null
930
+ const { parentId, runId, runSinceSeq, lastSeq, lastInspectionAt, nextDueAt,
931
+ intervalMs, noticesSent, startedAt } = entry
932
+ return { childId, parentId, runId, runSinceSeq: runSinceSeq ?? null, lastSeq,
933
+ lastInspectionAt: lastInspectionAt ?? null, nextDueAt, intervalMs, noticesSent, startedAt }
934
+ }
935
+
936
+ function exportCursors() {
937
+ return [...entries.keys()].map(exportCursor)
938
+ }
939
+
940
+ function hydrateCursor(childId, cursor, { currentRunId, currentHeadSeq, now } = {}) {
941
+ if (!idOrNull(childId) || !cursor || typeof cursor !== 'object' || Array.isArray(cursor) ||
942
+ (cursor.childId != null && cursor.childId !== childId)) return false
943
+ const previous = entries.get(childId)
944
+ const parentId = idOrNull(cursor.parentId) ?? previous?.parentId
945
+ if (!parentId || (previous && previous.parentId !== parentId)) return false
946
+ const savedRunId = idOrNull(cursor.runId)
947
+ const runId = idOrNull(currentRunId) ?? previous?.runId ?? savedRunId
948
+ const sameRun = runId === savedRunId
949
+ const at = timeOr(now, currentTime())
950
+ const configuredInterval = intervalMsOf(readConfig(opts.config))
951
+ const intervalMs = sameRun ? positiveNumber(cursor.intervalMs, configuredInterval) : configuredInterval
952
+ const head = countOr(currentHeadSeq, 0)
953
+ const startedAt = sameRun ? timeOr(cursor.startedAt, at) : at
954
+ const savedDeadline = timeOr(cursor.nextDueAt, startedAt + intervalMs)
955
+ const lastInspectionAt = sameRun ? timeOr(cursor.lastInspectionAt, undefined) : undefined
956
+ const runSinceSeq = sameRun ? countOr(cursor.runSinceSeq, undefined) : head
957
+ const lastSeq = sameRun ? Math.max(runSinceSeq ?? 0, countOr(cursor.lastSeq, 0)) : head
958
+ const noticesSent = sameRun ? countOr(cursor.noticesSent, 0) : 0
959
+ if (previous?.runId === runId && (previous.lastSeq > lastSeq || previous.noticesSent > noticesSent ||
960
+ (previous.lastInspectionAt ?? -Infinity) > (lastInspectionAt ?? -Infinity))) return false
961
+ entries.set(childId, {
962
+ childId, parentId, runId, startedAt, intervalMs, lastSeq, runSinceSeq, lastInspectionAt, noticesSent,
963
+ nextDueAt: sameRun ? Math.max(at, savedDeadline) : at + intervalMs,
964
+ label: typeof cursor.label === 'string' ? cursor.label : previous?.label ?? '',
965
+ readOnly: typeof cursor.readOnly === 'boolean' ? cursor.readOnly : previous?.readOnly ?? false,
966
+ writeScope: copyScope(cursor.writeScope ?? previous?.writeScope),
967
+ cwd: typeof cursor.cwd === 'string' ? cursor.cwd : previous?.cwd,
968
+ })
969
+ return true
970
+ }
971
+
972
+ function hydrateCursors(cursors, options) {
973
+ const result = { restored: 0, skipped: 0 }
974
+ if (!Array.isArray(cursors)) return result
975
+ for (const cursor of cursors) {
976
+ if (hydrateCursor(cursor?.childId, cursor, options)) result.restored += 1
977
+ else result.skipped += 1
978
+ }
979
+ return result
980
+ }
981
+
534
982
  const forget = (childId) => {
535
983
  entries.delete(childId)
536
984
  }
537
985
 
986
+ const isCurrent = ({ entry }) => entries.get(entry.childId) === entry
987
+
988
+ const isNoticeBlocked = async (parentId) => {
989
+ for (const name of ['hasPendingNotice', 'hasActiveSupervisionTurn']) {
990
+ try {
991
+ if (typeof opts[name] === 'function' && (await opts[name](parentId)) === true) return true
992
+ } catch (error) {
993
+ warn(`orchestrator: supervision: ${name}(${parentId}) failed: ${errorMessage(error)}`)
994
+ // A duplicate wake-up is worse than a delayed notice.
995
+ return true
996
+ }
997
+ }
998
+ return false
999
+ }
1000
+
1001
+ const getAttentionRows = async (parentId) => {
1002
+ try {
1003
+ const items = typeof opts.listAttentionItems === 'function' ? await opts.listAttentionItems(parentId) : []
1004
+ if (!Array.isArray(items)) return []
1005
+ return items
1006
+ .filter((item) => typeof item?.childId === 'string' && item.childId.trim() !== '' &&
1007
+ (item.auditState === 'pending' || item.auditState === 'failed'))
1008
+ .map((item) => ({ ...item, kind: 'attention' }))
1009
+ } catch (error) {
1010
+ warn(`orchestrator: supervision: listAttentionItems(${parentId}) failed: ${errorMessage(error)}`)
1011
+ return []
1012
+ }
1013
+ }
1014
+
538
1015
  const tick = async (nowOverride) => {
539
1016
  let config
540
1017
  try {
@@ -577,8 +1054,7 @@ export function createSupervisor(options = {}) {
577
1054
  }
578
1055
  if (entries.size === 0) return
579
1056
 
580
- /** parentId -> [{ entry, summary }] for this tick's due, notifying children. */
581
- const dueByParent = new Map()
1057
+ const activeByParent = new Map()
582
1058
 
583
1059
  for (const entry of [...entries.values()]) {
584
1060
  // A callback may have forgotten it while we awaited a previous entry.
@@ -593,11 +1069,20 @@ export function createSupervisor(options = {}) {
593
1069
  childAlive = true
594
1070
  }
595
1071
  }
1072
+ if (entries.get(entry.childId) !== entry) continue
596
1073
  if (!childAlive) {
597
1074
  entries.delete(entry.childId)
598
1075
  continue
599
1076
  }
600
1077
 
1078
+ const child = { entry }
1079
+ let batch = activeByParent.get(entry.parentId)
1080
+ if (batch === undefined) {
1081
+ batch = []
1082
+ activeByParent.set(entry.parentId, batch)
1083
+ }
1084
+ batch.push(child)
1085
+
601
1086
  // A changed interval takes effect at once. Shift the deadline by the same
602
1087
  // delta, so shrinking can make it due right now and growing delays it,
603
1088
  // without losing an advance already made for a skipped notice.
@@ -607,71 +1092,85 @@ export function createSupervisor(options = {}) {
607
1092
  entry.intervalMs = intervalMs
608
1093
  }
609
1094
 
610
- if (at < entry.nextDueAt) continue
1095
+ if (at < entry.nextDueAt) {
1096
+ child.status = '同行在跑,暂未到下一次巡检点'
1097
+ continue
1098
+ }
611
1099
 
612
- // The budget is spent, but the child is not forgotten: raising the budget or
613
- // switching to unlimited mid-run must resume supervision of this same child.
614
- // The deadline is left in the past, so the next scan after such a change
615
- // notifies at once instead of waiting out a whole interval.
616
- if (!config.unlimited && entry.noticesSent >= config.maxNoticesPerChild) continue
1100
+ // Retain capped children so a config change can resume supervision.
1101
+ if (!config.unlimited && entry.noticesSent >= config.maxNoticesPerChild) {
1102
+ child.status = '同行在跑,巡检预算已用完'
1103
+ continue
1104
+ }
617
1105
 
618
1106
  let events
619
1107
  try {
620
1108
  events = typeof opts.readEvents === 'function' ? await opts.readEvents(entry.childId) : []
621
1109
  } catch (error) {
622
1110
  warn(`orchestrator: supervision: readEvents(${entry.childId}) failed: ${errorMessage(error)}`)
623
- continue // Only this child skips; its deadline stays put and is retried.
1111
+ continue // A failed inspection stays due unless the parent batch is rescheduled.
624
1112
  }
625
1113
 
626
1114
  let summary
627
1115
  try {
628
- summary = summarize(events, { sinceSeq: entry.lastSeq, now: at, startedAt: entry.startedAt })
1116
+ summary = summarize(events, {
1117
+ sinceSeq: entry.lastSeq,
1118
+ runSinceSeq: entry.runSinceSeq,
1119
+ now: at,
1120
+ startedAt: entry.startedAt,
1121
+ prevSummary: entry.lastInspectionAt === undefined ? undefined : { lastSeq: entry.lastSeq },
1122
+ elapsedMs: Math.max(0, at - (entry.lastInspectionAt ?? entry.startedAt)),
1123
+ repeatThreshold: config.repeatThreshold,
1124
+ stalledAfterMs: intervalMs,
1125
+ writeScope: entry.writeScope,
1126
+ readOnly: entry.readOnly,
1127
+ cwd: entry.cwd,
1128
+ })
629
1129
  } catch (error) {
630
1130
  warn(`orchestrator: supervision: summarize(${entry.childId}) failed: ${errorMessage(error)}`)
631
1131
  continue
632
1132
  }
633
1133
 
634
- const looping = summary.repeated >= config.repeatThreshold
635
- // No new events and no loop is not worth a turn, unless asked to always report.
636
- // Unlimited supervision means "keep reporting until the child stops, delivers or
637
- // ends", so a quiet child is still reported every interval.
638
- if (summary.newEvents === 0 && !looping && !config.notifyOnNoProgress && !config.unlimited) {
1134
+ if (!isCurrent(child)) continue
1135
+ const { status } = summary.semantic
1136
+ const actionable = status === 'scope_drift' || status === 'error_loop' || status === 'tool_loop'
1137
+ // Keep the quiet-child policy: silence alone does not wake the parent
1138
+ // unless quiet or unlimited notices are enabled.
1139
+ if (summary.newEvents === 0 && !actionable && !config.notifyOnNoProgress && !config.unlimited) {
1140
+ child.status = '同行在跑,本周期暂无新增工具调用'
1141
+ entry.lastInspectionAt = at
639
1142
  entry.nextDueAt = at + intervalMs
640
1143
  continue
641
1144
  }
642
1145
 
643
- const batch = dueByParent.get(entry.parentId)
644
- if (batch === undefined) {
645
- dueByParent.set(entry.parentId, [{ entry, summary }])
646
- } else {
647
- batch.push({ entry, summary })
648
- }
1146
+ child.summary = summary
649
1147
  }
650
1148
 
651
- // One notice per parent, covering every due child of that parent.
652
- for (const [parentId, batch] of dueByParent) {
653
- const live = batch.filter(({ entry }) => entries.get(entry.childId) === entry)
654
- if (live.length === 0) continue
1149
+ const nextDueAt = at + intervalMs
1150
+ for (const [parentId, batch] of activeByParent) {
1151
+ if (!batch.some((child) => child.summary && isCurrent(child))) continue
655
1152
 
656
- let alreadyPending = false
657
- if (typeof opts.hasPendingNotice === 'function') {
658
- try {
659
- alreadyPending = (await opts.hasPendingNotice(parentId)) === true
660
- } catch (error) {
661
- warn(`orchestrator: supervision: hasPendingNotice(${parentId}) failed: ${errorMessage(error)}`)
662
- // Assume pending: a duplicate notice is worse than a delayed one.
663
- alreadyPending = true
1153
+ // Pending or claimed notices delay the whole batch, without spending budget
1154
+ // or letting a sibling with a slightly later deadline wake the parent again.
1155
+ const deferParent = () => {
1156
+ for (const child of batch.filter(isCurrent)) {
1157
+ child.entry.nextDueAt = Math.max(child.entry.nextDueAt, nextDueAt)
664
1158
  }
665
1159
  }
666
- if (alreadyPending) {
667
- // Skip the whole parent, spend no budget, but do not re-check every tick.
668
- for (const { entry } of live) entry.nextDueAt = at + intervalMs
1160
+ if (await isNoticeBlocked(parentId)) {
1161
+ deferParent()
669
1162
  continue
670
1163
  }
671
1164
 
672
- const index = live.reduce((highest, { entry }) => Math.max(highest, entry.noticesSent), 0) + 1
673
- const rows = live.map(({ entry, summary }) => ({
1165
+ const attentionRows = await getAttentionRows(parentId)
1166
+ const active = batch.filter(isCurrent)
1167
+ const triggers = active.filter(({ summary }) => summary !== undefined)
1168
+ if (triggers.length === 0) continue
1169
+
1170
+ const index = triggers.reduce((highest, { entry }) => Math.max(highest, entry.noticesSent), 0) + 1
1171
+ const rows = triggers.map(({ entry, summary }) => ({
674
1172
  childId: entry.childId,
1173
+ kind: 'running',
675
1174
  label: entry.label,
676
1175
  startedAt: entry.startedAt,
677
1176
  turns: summary.turns,
@@ -682,7 +1181,19 @@ export function createSupervisor(options = {}) {
682
1181
  repeated: summary.repeated,
683
1182
  lastText: summary.lastText,
684
1183
  newEvents: summary.newEvents,
1184
+ semantic: summary.semantic,
1185
+ }))
1186
+ const activeIds = new Set(active.map(({ entry }) => entry.childId))
1187
+ // A child whose log could not be inspected retains the existing skip behavior.
1188
+ const siblingRows = active.filter(({ status }) => status !== undefined).map(({ entry, status }) => ({
1189
+ childId: entry.childId,
1190
+ kind: 'sibling',
1191
+ label: entry.label,
1192
+ startedAt: entry.startedAt,
1193
+ status,
685
1194
  }))
1195
+ const childIds = [...rows, ...siblingRows].map(({ childId }) => childId)
1196
+ rows.push(...attentionRows.filter(({ childId }) => !activeIds.has(childId)), ...siblingRows)
686
1197
  const composeMeta = {
687
1198
  now: at,
688
1199
  index,
@@ -696,39 +1207,34 @@ export function createSupervisor(options = {}) {
696
1207
 
697
1208
  let result
698
1209
  try {
699
- result =
700
- typeof opts.deliver === 'function'
701
- ? await opts.deliver(
702
- parentId,
703
- text,
704
- live.map(({ entry }) => entry.childId),
705
- { rows, composeMeta },
706
- )
707
- : 'queued'
1210
+ result = typeof opts.deliver === 'function'
1211
+ ? await opts.deliver(parentId, text, childIds, { rows, composeMeta })
1212
+ : 'queued'
708
1213
  } catch (error) {
709
1214
  warn(`orchestrator: supervision: deliver(${parentId}) failed: ${errorMessage(error)}`)
710
- for (const { entry } of live) entry.nextDueAt = at + intervalMs
1215
+ for (const { entry } of triggers.filter(isCurrent)) entry.nextDueAt = nextDueAt
711
1216
  continue
712
1217
  }
713
1218
 
714
1219
  if (result === 'stale') continue
715
1220
  if (result === 'queued') {
716
- for (const { entry, summary } of live) {
717
- if (entries.get(entry.childId) !== entry) continue
1221
+ for (const { entry, summary } of active.filter(isCurrent)) {
1222
+ entry.nextDueAt = nextDueAt
1223
+ if (summary === undefined) continue
718
1224
  entry.noticesSent += 1
719
1225
  // A tail window can report a lower max than a previous read; never go backwards.
720
1226
  entry.lastSeq = Math.max(entry.lastSeq, summary.lastSeq)
721
- entry.nextDueAt = at + intervalMs
1227
+ entry.lastInspectionAt = at
722
1228
  }
723
1229
  } else if (result === 'parent-gone') {
724
1230
  for (const [childId, entry] of entries) {
725
1231
  if (entry.parentId === parentId) entries.delete(childId)
726
1232
  }
727
1233
  } else if (result === 'already-pending') {
728
- for (const { entry } of live) entry.nextDueAt = at + intervalMs
1234
+ deferParent()
729
1235
  } else {
730
1236
  warn(`orchestrator: supervision: deliver(${parentId}) returned ${String(result)}`)
731
- for (const { entry } of live) entry.nextDueAt = at + intervalMs
1237
+ for (const { entry } of triggers.filter(isCurrent)) entry.nextDueAt = nextDueAt
732
1238
  }
733
1239
  }
734
1240
  } catch (error) {
@@ -742,5 +1248,5 @@ export function createSupervisor(options = {}) {
742
1248
  const has = (childId) => entries.has(childId)
743
1249
  const size = () => entries.size
744
1250
 
745
- return { track, forget, has, tick, size }
1251
+ return { track, forget, has, tick, size, exportCursor, exportCursors, hydrateCursor, hydrateCursors }
746
1252
  }