@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/index.js CHANGED
@@ -1,12 +1,24 @@
1
1
  import { randomUUID } from 'node:crypto'
2
+ import { existsSync } from 'node:fs'
2
3
  import z from '@deepseek-ai/schemastery'
3
4
  import { defineTool } from '@deepseek-ai/dsh-tools'
4
- import { ORCHESTRATE_TOOL } from './api.js'
5
+ import { DELEGATE_STATUS_TOOL_NAME, ORCHESTRATE_TOOL } from './api.js'
5
6
  import { createCatalogPublisher } from './catalog.js'
6
- import { createDelegateTool } from './delegate.js'
7
- import { createSupervisionTurnState, effectiveAllowed, installGate, isDelegatedChild } from './gate.js'
7
+ import { createDelegateStatusTool } from './delegate-status.js'
8
+ import {
9
+ READ_ONLY_NOTICE, auditNotice, captureDispatchBaseline, createDelegateTool, settleDispatchWrite,
10
+ worktreeAuditSummary, worktreePromptNote,
11
+ } from './delegate.js'
12
+ import { createSupervisionTurnState, installGate, isDelegatedChild } from './gate.js'
13
+ import { auditGitBaseline, captureGitBaseline } from './git-audit.js'
8
14
  import { createOrchestrateTool } from './orchestrate.js'
9
15
  import { RETRY_SOURCE_KIND, createRetry } from './retry.js'
16
+ import {
17
+ createActionLedger, evaluateWakeupGate, inspectHostChildState, makeResumeActionKey,
18
+ makeSettleActionKey, reconcileOnStartup,
19
+ } from './reconcile.js'
20
+ import { createStateStore } from './state-store.js'
21
+ import { normalizeScope } from './write-scope.js'
10
22
  import {
11
23
  SUPERVISE_SOURCE_KIND,
12
24
  composeNotice,
@@ -18,11 +30,15 @@ import {
18
30
  summarize,
19
31
  } from './supervise.js'
20
32
  import { SWITCH_SOURCE_KIND, createSwitchNotices } from './switch-notice.js'
21
- import { installToolSurface } from './tool-surface.js'
33
+ import { INLINE_AUDIT_SOURCE_KIND, createDispatchTimeline, formatInlineAuditNotice } from './timeline.js'
34
+ import { DEFAULT_ALLOWED_TOOLS, NATIVE_TEAM_TOOLS, installToolSurface, resolveEffectiveAllowedTools } from './tool-surface.js'
22
35
  import { isDispatchEnabled } from './worker.js'
23
36
  import { createWriteLeases } from './write-lease.js'
37
+ import { formatWorktreeError, releaseWriteScope } from './write-scope-tool.js'
38
+ import { createWorktreeManager, probeGitRepo } from './worktree.js'
39
+ import { createPersistentWorktreeTool } from './worktree-tool.js'
24
40
 
25
- export { SUPERVISE_SOURCE_KIND, SWITCH_SOURCE_KIND }
41
+ export { DEFAULT_ALLOWED_TOOLS, INLINE_AUDIT_SOURCE_KIND, SUPERVISE_SOURCE_KIND, SWITCH_SOURCE_KIND }
26
42
 
27
43
  export const name = '@sshirkit/dsh-orchestrator'
28
44
 
@@ -32,37 +48,6 @@ export const name = '@sshirkit/dsh-orchestrator'
32
48
  */
33
49
  export const inject = ['sessionProjections', 'tools', 'subagents', 'agents', 'sessions']
34
50
 
35
- /**
36
- * The tools a main agent keeps while orchestration mode is on — the shipped whitelist.
37
- *
38
- * The gate is whitelist-driven: this list is the whole surface a main agent has, and
39
- * every other tool the host offers (files, search, shells, fetch, the native
40
- * `subagent`/`workflow`, and any plugin or MCP tool) is hidden and refused. The order is
41
- * fixed because the panel and the client fallback mirror it literally.
42
- *
43
- * `wait_agent` (added in DSH 0.2.2-rc.2) is deliberately left out of the default
44
- * whitelist: a main agent that blocks on a wait can stall the whole tree and misread a
45
- * timeout as a worker failure. Delegation stays event-driven — the main agent dispatches
46
- * and is woken by the completion notice instead of polling.
47
- */
48
- export const DEFAULT_ALLOWED_TOOLS = [
49
- // Delegation & worker control — the main agent's core orchestration surface
50
- 'delegate',
51
- 'orchestrate',
52
- 'send_message',
53
- 'interrupt_agent',
54
- // Planning, user clarification & context compression
55
- 'todo_write',
56
- 'ask_user_question',
57
- 'compress',
58
- // Read-only session history inspection
59
- 'session_search',
60
- 'session_trace',
61
- 'session_event_search',
62
- 'session_event_read',
63
- 'session_event_trace',
64
- ]
65
-
66
51
  /**
67
52
  * Every field is volatile so a switch or settings card can rewrite it without
68
53
  * editing the profile file. `enabled` and `allowedTools` are read live by the guard,
@@ -72,10 +57,13 @@ export const DEFAULT_ALLOWED_TOOLS = [
72
57
  export const Config = z.object({
73
58
  /** Hide the creation tools from top-level agents. Delegated children keep them. */
74
59
  enabled: z.boolean().default(true).volatile(),
60
+ worktreeIsolationEnabled: z.boolean().default(true)
61
+ .description('Git 仓库下对写任务默认启用独立 Worktree 隔离与 git diff/log 审计(delegate 与 orchestrate 按 item 隔离),非 Git 目录自动降级逻辑快照')
62
+ .volatile(),
75
63
  /**
76
64
  * The only tool whitelist there is. Whitelist-driven: only the names listed here stay
77
65
  * available to the main agent, and every other host, MCP or plugin tool is automatically
78
- * hidden and blocked. Workers always keep the full tool set.
66
+ * hidden and blocked. The unconfigured list also includes registered native Team tools.
79
67
  *
80
68
  * That is only the default: the panel may check any tool the host offers.
81
69
  * `tools.restrict` hides the global ones; a guard additionally refuses every name that is
@@ -85,14 +73,14 @@ export const Config = z.object({
85
73
  */
86
74
  allowedTools: z
87
75
  .array(z.string())
88
- .default(DEFAULT_ALLOWED_TOOLS)
76
+ // Schemastery arrays default to []; retain the distinction between missing and explicitly empty.
77
+ .default(undefined)
89
78
  .description(
90
- 'Tools allowed for the main agent while orchestration mode is enabled. ' +
91
- 'Whitelist-driven: only tools in this list are available to the main agent; ' +
92
- 'every other host, MCP, or plugin tool is automatically hidden and blocked. ' +
93
- 'Workers always keep the full tool set.'
79
+ 'Explicit main-agent whitelist. Omit to use the shipped list plus available Team tools. ' +
80
+ 'An empty list disables all whitelist entries; subagent_fork and workflow are not allowed by default.'
94
81
  )
95
82
  .volatile(),
83
+ allowAgentTeam: z.boolean().default(true).description('Allow native Team tools on the gated main agent.').volatile(),
96
84
  /**
97
85
  * Read-only mirror of every tool the running host has registered, published by the plugin
98
86
  * for the Allowed Tools panel: a web client cannot enumerate tools itself, so the catalog
@@ -160,13 +148,13 @@ function messageOf(error) {
160
148
  * no longer be attached to the prompt. A retry therefore reads as a user turn in the
161
149
  * session log; only `source.rpcId` (the `requestId` below) traces it back.
162
150
  */
163
- export async function deliverRetryPrompt(ctx, parentId, childId, text) {
151
+ export async function deliverRetryPrompt(ctx, parentId, childId, text, requestId = randomUUID()) {
164
152
  if (typeof ctx?.subagents?.prompt !== 'function') {
165
153
  throw new Error('the host does not expose subagents.prompt')
166
154
  }
167
155
  const receipt = await ctx.subagents.prompt(
168
156
  {
169
- requestId: randomUUID(),
157
+ requestId,
170
158
  childSessionId: childId,
171
159
  delivery: 'queue',
172
160
  content: [{ type: 'text', text }],
@@ -366,12 +354,13 @@ function isRuntimeContext(message) {
366
354
  }
367
355
 
368
356
  /** Reconcile claimed notices synchronously on both sides of downstream awaits. */
369
- function filterSupervisionMessages(messages, { isLive, rebuildNotice, agent, staleIds }) {
357
+ function filterSupervisionMessages(messages, { liveNoticeIds, rebuildNotice, agent, staleIds }) {
358
+ if (staleIds.size === 0 && !messages.some(isSupervisionMessage)) return messages
370
359
  return messages.flatMap((message) => {
371
360
  if (staleIds.has(message?.id)) return []
372
361
  if (!isSupervisionMessage(message)) return [message]
373
362
  const originalIds = getSupervisionChildIds(message)
374
- const liveIds = originalIds.filter(isLive)
363
+ const liveIds = liveNoticeIds(message, originalIds, agent.id)
375
364
  if (liveIds.length === 0) {
376
365
  staleIds.add(message.id)
377
366
  return []
@@ -388,11 +377,55 @@ function filterSupervisionMessages(messages, { isLive, rebuildNotice, agent, sta
388
377
  })
389
378
  }
390
379
 
380
+ function settledAuditEntries(timeline, parentId, messages) {
381
+ const matches = new Map()
382
+ for (const message of messages) {
383
+ const source = message?.source
384
+ if (source?.kind !== 'subagent-settled') continue
385
+ const childId = source.senderSessionId
386
+ if (typeof childId !== 'string' || matches.has(childId)) continue
387
+ const entry = timeline.get(parentId, childId)
388
+ if (entry !== null) matches.set(childId, { childId, entry })
389
+ }
390
+ return [...matches.values()]
391
+ }
392
+
393
+ /** Commit delivery only for the exact messages entering the model step. */
394
+ function attachAuditMessages({ timeline, agent, messages, createMessage, scheduleReconcileInbox, logger }) {
395
+ if (createMessage === undefined) return messages
396
+ const parentId = agent.id
397
+ const attached = settledAuditEntries(timeline, parentId, messages)
398
+ if (attached.length === 0) return messages
399
+ let notice
400
+ try {
401
+ notice = createMessage({
402
+ content: [{ type: 'text', text: formatInlineAuditNotice(attached) }],
403
+ source: { kind: INLINE_AUDIT_SOURCE_KIND, form: 'notice' },
404
+ })
405
+ } catch (error) {
406
+ try {
407
+ logger?.warn?.(`orchestrator: cannot build the inline audit notice: ${messageOf(error)}`)
408
+ } catch {
409
+ // Neither a message constructor nor a logger may break the parent model step.
410
+ }
411
+ return messages
412
+ }
413
+
414
+ let changed = false
415
+ for (const { childId, entry } of attached) {
416
+ if (entry.auditState !== 'passed' && entry.auditState !== 'failed') continue
417
+ changed = timeline.markAuditDelivered({ parentId, childId, via: 'inline-pre-step' }) || changed
418
+ }
419
+ if (changed) scheduleReconcileInbox?.(parentId)
420
+ return [...messages, notice]
421
+ }
422
+
391
423
  /** Filter claimed inbox messages before any downstream handler can add model context. */
392
424
  export function createSupervisionPreStep({
393
425
  ctx, config, supervisor, supervisionTurnState, todoTracker, nextStep, rebuildNotice, retainNotices,
426
+ auditTimeline, loadAuditCreator, scheduleReconcileInbox,
427
+ liveNoticeIds = (_message, ids) => ids.filter((id) => supervisor.has(id) && ctx?.agents?.get?.(id) !== undefined),
394
428
  }) {
395
- const isLive = (id) => supervisor.has(id) && ctx?.agents?.get?.(id) !== undefined
396
429
  const run = async (payload, next) => {
397
430
  const agent = payload?.agent
398
431
  if (agent === undefined || agent === null || isDelegatedChild(agent)) return nextStep(payload, next)
@@ -404,7 +437,7 @@ export function createSupervisionPreStep({
404
437
  let restored = false
405
438
  const reconcile = (batch) => {
406
439
  wasSupervision ||= batch.some(isSupervisionMessage)
407
- const remaining = filterSupervisionMessages(batch, { isLive, rebuildNotice, agent, staleIds })
440
+ const remaining = filterSupervisionMessages(batch, { liveNoticeIds, rebuildNotice, agent, staleIds })
408
441
  const substantive = remaining.filter((message) => !isRuntimeContext(message))
409
442
  const hasSubstantive = substantive.length > 0
410
443
  const hasOrdinary = substantive.some((message) => !isSupervisionMessage(message))
@@ -448,7 +481,25 @@ export function createSupervisionPreStep({
448
481
  current = reconcile(decision.messages)
449
482
  }
450
483
  if (wasSupervision && !current.hasSubstantive) return { kind: 'reject' }
451
- return { ...decision, messages: current.remaining }
484
+ let createMessage
485
+ if (auditTimeline !== undefined && current.remaining.some((message) =>
486
+ message?.source?.kind === 'subagent-settled' && auditTimeline.get(agent.id, message.source.senderSessionId) !== null)) {
487
+ createMessage = await loadAuditCreator?.()
488
+ current = reconcile(decision.messages)
489
+ if ((wasSupervision && !current.hasSubstantive) || (pure && !current.hasOrdinary)) {
490
+ await restoreOnce()
491
+ current = reconcile(decision.messages)
492
+ }
493
+ }
494
+ if (payload?.signal?.aborted) {
495
+ supervisionTurnState.clearTurn(agent.id, payload.turn)
496
+ return decision
497
+ }
498
+ if (wasSupervision && !current.hasSubstantive) return { kind: 'reject' }
499
+ const enteringMessages = auditTimeline === undefined ? current.remaining : attachAuditMessages({
500
+ timeline: auditTimeline, agent, messages: current.remaining, createMessage, scheduleReconcileInbox, logger: ctx?.logger,
501
+ })
502
+ return enteringMessages === decision.messages ? decision : { ...decision, messages: enteringMessages }
452
503
  }
453
504
  return async (payload, next) => {
454
505
  const release = retainNotices?.(payload)
@@ -470,7 +521,10 @@ export function createSupervisionPreStep({
470
521
  * import, which is never a top-level import (the plugin must load even when the
471
522
  * package is not resolvable in a unit test).
472
523
  */
473
- export function createSupervision({ ctx, config, logger = ctx?.logger, loadLlm = () => import('@deepseek-ai/dsh-llm') }) {
524
+ export function createSupervision({
525
+ ctx, config, logger = ctx?.logger, loadLlm = () => import('@deepseek-ai/dsh-llm'),
526
+ supervisionTurnState, listAttentionItems = () => [], isActive = () => true,
527
+ }) {
474
528
  let pendingWarned = false
475
529
  const warn = (message) => {
476
530
  try {
@@ -551,9 +605,26 @@ export function createSupervision({ ctx, config, logger = ctx?.logger, loadLlm =
551
605
  const pendingNoticeMeta = new Map()
552
606
  const noticeOwners = new Map()
553
607
  const claimedNotices = new Map()
608
+ const retainedNoticeAgents = new WeakMap()
554
609
  const reconcileScheduled = new Set()
555
610
  let noticeCreator
556
- const liveChildIds = (ids) => ids.filter((id) => supervisor.has(id) && isChildAlive(id))
611
+ const hasActiveSupervisionTurn = (parentId) => {
612
+ const parent = ctx?.agents?.get?.(parentId)
613
+ return supervisionTurnState?.hasActiveParent(parentId) === true ||
614
+ claimedNotices.has(parent) || retainedNoticeAgents.has(parent)
615
+ }
616
+ const liveRowIds = (ids, parentId, rowsByChildId) => {
617
+ let attentionById
618
+ return ids.filter((id) => {
619
+ const row = rowsByChildId?.get(id)
620
+ if (row?.kind !== 'attention') return supervisor.has(id) && isChildAlive(id)
621
+ attentionById ??= new Map(listAttentionItems(parentId).map((entry) => [entry.childId, entry]))
622
+ const current = attentionById.get(id)
623
+ return current !== undefined && current.auditState === row.auditState && current.attemptSeq === row.attemptSeq
624
+ })
625
+ }
626
+ const liveNoticeIds = (message, ids, parentId) =>
627
+ liveRowIds(ids, parentId, pendingNoticeMeta.get(message.id)?.rowsByChildId)
557
628
  const inboxMessages = (parent) => [parent?.inbox?.nextTurn, parent?.inbox?.nextStep]
558
629
  .flatMap((bucket) => Array.isArray(bucket) ? bucket : [])
559
630
 
@@ -610,6 +681,7 @@ export function createSupervision({ ctx, config, logger = ctx?.logger, loadLlm =
610
681
  const ids = new Set((Array.isArray(payload.messages) ? payload.messages : [])
611
682
  .filter(isSupervisionMessage).map((message) => message.id).filter((id) => pendingNoticeMeta.has(id)))
612
683
  for (const id of ids) ownNotice(id)
684
+ if (ids.size > 0) retainedNoticeAgents.set(agent, (retainedNoticeAgents.get(agent) ?? 0) + 1)
613
685
  // Transfer only this batch; another concurrent pre-step may own other claims in the same turn.
614
686
  releaseClaimedNotices(agent, payload.turn, ids)
615
687
  let released = false
@@ -617,6 +689,11 @@ export function createSupervision({ ctx, config, logger = ctx?.logger, loadLlm =
617
689
  if (released) return
618
690
  released = true
619
691
  for (const id of ids) releaseNotice(id)
692
+ if (ids.size > 0) {
693
+ const remaining = (retainedNoticeAgents.get(agent) ?? 0) - 1
694
+ if (remaining > 0) retainedNoticeAgents.set(agent, remaining)
695
+ else retainedNoticeAgents.delete(agent)
696
+ }
620
697
  pruneNoticeMeta()
621
698
  }
622
699
  }
@@ -664,7 +741,7 @@ export function createSupervision({ ctx, config, logger = ctx?.logger, loadLlm =
664
741
  let retry = false
665
742
  for (const message of inboxMessages(parent).filter(isSupervisionMessage)) {
666
743
  const originalIds = getSupervisionChildIds(message)
667
- const ids = liveChildIds(originalIds)
744
+ const ids = liveNoticeIds(message, originalIds, parentId)
668
745
  if (ids.length === originalIds.length && ids.length > 0) continue
669
746
  if (ids.length > 0 && typeof parent.inbox.replace !== 'function') continue
670
747
  const updated = ids.length > 0 ? rebuildNotice(message, ids, parentId) : undefined
@@ -683,10 +760,11 @@ export function createSupervision({ ctx, config, logger = ctx?.logger, loadLlm =
683
760
 
684
761
  /** Inbox mutation must run outside the synchronous session/event publish stack. */
685
762
  const scheduleReconcileInbox = (parentId, attempt = 0) => {
686
- if (typeof parentId !== 'string' || reconcileScheduled.has(parentId)) return
763
+ if (!isActive() || typeof parentId !== 'string' || reconcileScheduled.has(parentId)) return
687
764
  reconcileScheduled.add(parentId)
688
765
  queueMicrotask(() => {
689
766
  reconcileScheduled.delete(parentId)
767
+ if (!isActive()) return
690
768
  try {
691
769
  if (reconcileInbox(parentId) && attempt < 2) scheduleReconcileInbox(parentId, attempt + 1)
692
770
  } catch (error) {
@@ -695,23 +773,29 @@ export function createSupervision({ ctx, config, logger = ctx?.logger, loadLlm =
695
773
  })
696
774
  }
697
775
 
698
- const deliverAs = async (kind, parentId, text, childIds, meta) => {
776
+ const deliverAs = async (kind, parentId, text, childIds, meta, checkQueue) => {
777
+ if (!isActive()) return 'unavailable'
699
778
  const parent = ctx?.agents?.get?.(parentId)
700
779
  if (parent === undefined || parent === null) return 'parent-gone'
701
780
  // The dynamic import is not retried once it failed: the supervisor reschedules
702
781
  // without spending the child's budget, and one warning is enough.
703
782
  const createMessage = await loadCreator()
704
- if (createMessage === undefined) return 'unavailable'
783
+ if (createMessage === undefined || !isActive()) return 'unavailable'
705
784
  noticeCreator = createMessage
706
785
 
707
786
  if (ctx?.agents?.get?.(parentId) !== parent) return 'parent-gone'
708
787
  let message
709
788
  let noticeMeta
710
789
  if (kind === SUPERVISE_SOURCE_KIND) {
711
- const originalIds = getSupervisionChildIds({ source: { childIds } })
712
- const ids = liveChildIds(originalIds)
790
+ const rowsByChildId = new Map((meta?.rows ?? []).map((row) => [row.childId, { ...row }]))
791
+ const allIds = [...(childIds ?? []), ...[...rowsByChildId.values()]
792
+ .filter((row) => row.kind === 'attention').map((row) => row.childId)]
793
+ const originalIds = getSupervisionChildIds({ source: { childIds: allIds } })
794
+ const ids = liveRowIds(originalIds, parentId, rowsByChildId)
713
795
  if (ids.length === 0) return 'stale'
714
- const notice = buildNotice(createMessage, parentId, ids, ids.length === originalIds.length ? text : undefined, meta)
796
+ const notice = buildNotice(createMessage, parentId, ids, ids.length === originalIds.length ? text : undefined, {
797
+ rowsByChildId, composeMeta: meta?.composeMeta,
798
+ })
715
799
  message = notice.message
716
800
  noticeMeta = notice.meta
717
801
  } else {
@@ -719,8 +803,16 @@ export function createSupervision({ ctx, config, logger = ctx?.logger, loadLlm =
719
803
  if (Array.isArray(childIds) && typeof childIds[0] === 'string') source.senderSessionId = childIds[0]
720
804
  message = createMessage({ content: [{ type: 'text', text }], source })
721
805
  }
722
- parent.followup(message)
806
+ const skip = checkQueue?.()
807
+ if (skip !== undefined) return skip
808
+ // Register identity before followup can synchronously publish a claim.
723
809
  if (noticeMeta !== undefined && message.id !== undefined) pendingNoticeMeta.set(message.id, noticeMeta)
810
+ try {
811
+ parent.followup(message)
812
+ } catch (error) {
813
+ pendingNoticeMeta.delete(message.id)
814
+ throw error
815
+ }
724
816
  pruneNoticeMeta()
725
817
  try {
726
818
  const flushed = await ctx?.sessions?.flush?.(parent.session)
@@ -762,7 +854,10 @@ export function createSupervision({ ctx, config, logger = ctx?.logger, loadLlm =
762
854
  isChildAlive,
763
855
  readEvents,
764
856
  hasPendingNotice,
765
- deliver,
857
+ hasActiveSupervisionTurn,
858
+ listAttentionItems,
859
+ deliver: (parentId, text, childIds, meta) => deliverAs(SUPERVISE_SOURCE_KIND, parentId, text, childIds, meta, () =>
860
+ hasPendingNotice(parentId) || hasActiveSupervisionTurn(parentId) ? 'already-pending' : undefined),
766
861
  logger,
767
862
  })
768
863
 
@@ -786,8 +881,8 @@ export function createSupervision({ ctx, config, logger = ctx?.logger, loadLlm =
786
881
 
787
882
  return {
788
883
  supervisor, isParentAlive, isChildAlive, readEvents, headSeq, hasPendingNotice,
789
- deliver, deliverRetry, rebuildNotice, scheduleReconcileInbox, pendingNoticeMeta,
790
- claimNotice, releaseClaimedNotices, retainNotices,
884
+ deliver, deliverRetry, rebuildNotice, liveNoticeIds, scheduleReconcileInbox, pendingNoticeMeta,
885
+ claimNotice, releaseClaimedNotices, retainNotices, loadAuditCreator: loadCreator,
791
886
  }
792
887
  }
793
888
 
@@ -837,11 +932,12 @@ export function createSupervisionHooks(supervisor, { headSeq, retry, scheduleRec
837
932
  }
838
933
 
839
934
  return {
840
- onStarted(parent, started, args) {
935
+ onStarted(parent, started, args, write) {
841
936
  const childId = started?.childId
842
937
  const parentId = parent?.id
843
938
  if (typeof childId !== 'string' || typeof parentId !== 'string') return
844
- remember(childId, { parentId, label: args?.description })
939
+ const scope = write === undefined ? {} : { writeScope: write.entries, readOnly: write.readOnly, cwd: write.cwd }
940
+ remember(childId, { parentId, label: args?.description, scope })
845
941
  activeParents.set(childId, parentId)
846
942
  // The retry policy keys on the same record: a child this plugin did not dispatch is
847
943
  // never retried, so the host's own `subagent` children stay untouched.
@@ -851,7 +947,8 @@ export function createSupervisionHooks(supervisor, { headSeq, retry, scheduleRec
851
947
  // A retry bookkeeping failure cannot affect the dispatch.
852
948
  }
853
949
  try {
854
- supervisor.track({ childId, parentId, label: args?.description, startedAt: Date.now() })
950
+ supervisor.track({ childId, parentId, label: args?.description, startedAt: Date.now(),
951
+ ...(started.runId && { runId: started.runId }), ...scope })
855
952
  } catch {
856
953
  // Still subscribe to the receipt below: an untracked child is harmless.
857
954
  }
@@ -891,6 +988,7 @@ export function createSupervisionHooks(supervisor, { headSeq, retry, scheduleRec
891
988
  startedAt: Date.now(),
892
989
  resumed: true,
893
990
  sinceSeq: baselineOf(childId),
991
+ ...record.scope,
894
992
  })
895
993
  } catch {
896
994
  // Supervision is best-effort; the resumed worker still runs without it.
@@ -901,15 +999,360 @@ export function createSupervisionHooks(supervisor, { headSeq, retry, scheduleRec
901
999
  }
902
1000
  }
903
1001
 
1002
+ // Cordis may start the next generation without awaiting an async effect disposer.
1003
+ // Keep the reservation across module reloads, but never serialize unrelated facilities.
1004
+ const domainOwnersKey = Symbol.for('@sshirkit/dsh-orchestrator/storage-domain-owners')
1005
+ const domainOwners = globalThis[domainOwnersKey] ??= new WeakMap()
1006
+
1007
+ function reserveDomain(facility) {
1008
+ const previous = domainOwners.get(facility)
1009
+ let release
1010
+ const current = new Promise((resolve) => { release = resolve })
1011
+ const tail = Promise.resolve(previous).then(() => current)
1012
+ domainOwners.set(facility, tail)
1013
+ void tail.then(() => {
1014
+ if (domainOwners.get(facility) === tail) domainOwners.delete(facility)
1015
+ })
1016
+ return { previous, release }
1017
+ }
1018
+
1019
+ const MAX_GIT_BASELINE_BYTES = 32 * 1024
1020
+ function smallGitBaseline(baseline) {
1021
+ if (baseline?.kind !== 'git-worktree') return undefined
1022
+ return Buffer.byteLength(JSON.stringify(baseline)) <= MAX_GIT_BASELINE_BYTES ? baseline : undefined
1023
+ }
1024
+
1025
+ function restoredGitBaseline(row, worktree) {
1026
+ const baseline = row.gitBaseline
1027
+ if (!worktree || baseline?.kind !== 'git-worktree' || baseline.baselineId !== row.baselineId ||
1028
+ baseline.worktreeId !== worktree.id || baseline.worktreePath !== worktree.worktreePath ||
1029
+ baseline.execCwd !== worktree.execCwd || baseline.repoRoot !== worktree.repoRoot ||
1030
+ baseline.baseCommit !== worktree.baseCommit || baseline.branch !== worktree.branch) return undefined
1031
+ return baseline
1032
+ }
1033
+
1034
+ function missingBaselineAudit(record) {
1035
+ return {
1036
+ baselineId: record.baselineId, passed: false, readOnly: record.readOnly,
1037
+ isolationLevel: record.worktree ? 'git-worktree' : 'logical-post-audit',
1038
+ isolationNote: '历史派发基线无法恢复;不能据此确认写入合规。',
1039
+ changedFiles: [],
1040
+ violations: [{ code: 'audit-incomplete', path: '.', reason: '缺少可核验的历史派发基线' }],
1041
+ summary: { added: 0, modified: 0, deleted: 0, violations: 1, truncated: false },
1042
+ }
1043
+ }
1044
+
904
1045
  export function apply(ctx, config) {
905
- const supervision = createSupervision({ ctx, config })
1046
+ let facility
1047
+ let startupError
1048
+ try {
1049
+ facility = ctx.get?.('storageDomain')
1050
+ } catch (error) {
1051
+ startupError = error
1052
+ }
1053
+ const hasStorage = typeof facility?.open === 'function'
1054
+ const stateStore = createStateStore({ facility, logger: ctx.logger })
1055
+ const actionLedger = createActionLedger({ store: stateStore })
1056
+ const domainReservation = hasStorage ? reserveDomain(facility) : undefined
1057
+ const startupAbort = new AbortController()
1058
+ const lifecycleQueue = []
1059
+ const pendingEnds = new Set()
1060
+ const endIdentity = (childId, parentId, runId) => JSON.stringify([childId, parentId, runId])
1061
+ const producerDisposers = []
1062
+ const listenerDisposers = []
1063
+ let disposing = false
1064
+ let restoring = hasStorage
1065
+ let bufferingLifecycle = hasStorage
1066
+ let readyPromise
1067
+ let disposePromise
1068
+ const timeline = createDispatchTimeline()
1069
+ const supervisionTurnState = createSupervisionTurnState()
1070
+ const supervision = createSupervision({
1071
+ ctx, config, supervisionTurnState, listAttentionItems: timeline.listAttentionItems,
1072
+ isActive: () => !disposing,
1073
+ })
1074
+ const writeLeases = createWriteLeases()
1075
+ const worktrees = createWorktreeManager()
1076
+ const worktreeOf = (childId) => worktrees.getByWorktreeOrChild(childId)
1077
+ const writes = new Map()
1078
+ const batchStages = new Map()
1079
+ const detachedBatchLeases = new Set()
1080
+ const wakeups = new Map()
1081
+ // Keep recent shared/readonly delegates resumable in memory as well as in persistent hosts.
1082
+ const keepWorktreeWrite = (record) => {
1083
+ const worktree = record.worktree && worktrees.get(record.worktree.id)
1084
+ return Boolean(worktree && worktree.mergeCommit === null && worktree.state !== 'discarded')
1085
+ }
1086
+ const hostRuns = new Map()
1087
+ const earlyEnds = new Map()
1088
+ const earlyDisposals = new Map()
1089
+ const endedRuns = new Set()
906
1090
 
907
- // A child that dies without a closing message is woken again on the same durable session,
908
- // so the work already in the workspace is not thrown away; the policy (lib/retry.js) owns
909
- // the budget, and waking the main agent reuses the supervision delivery.
1091
+ const warn = (text) => {
1092
+ try {
1093
+ ctx.logger?.warn?.(`orchestrator: ${text}`)
1094
+ } catch {
1095
+ // A logger must not break settlement or release.
1096
+ }
1097
+ }
1098
+
1099
+ const assertActive = () => {
1100
+ if (disposing) throw new Error('orchestrator: 插件正在卸载')
1101
+ if (startupError) throw new Error(`orchestrator: 持久状态未验证;已拒绝操作(${messageOf(startupError)})`)
1102
+ }
1103
+ const persist = async (operation) => {
1104
+ try {
1105
+ if (await operation === false && !disposing) throw new Error('状态写入未确认')
1106
+ } catch (error) {
1107
+ startupError ??= error
1108
+ warn(`持久化失败:${messageOf(error)}`)
1109
+ throw error
1110
+ }
1111
+ }
1112
+ const background = (operation) => { void operation.catch(() => {}) }
1113
+ const optionalSessionQuery = () => {
1114
+ try { return ctx.get?.('sessionQuery') } catch { return undefined }
1115
+ }
1116
+ const exportTree = (id) => worktrees.exportRecords().find((row) => row.id === id)
1117
+ const putTree = (id) => {
1118
+ const row = !disposing && id && exportTree(id)
1119
+ return row ? persist(stateStore.putWorktree(row)) : Promise.resolve()
1120
+ }
1121
+ const putLease = (lease, baselineId) => {
1122
+ const row = !disposing && lease && writeLeases.exportLeases().find((entry) => entry.leaseId === lease.leaseId)
1123
+ return row ? persist(stateStore.putLease({ ...row, baselineId: baselineId ?? row.baselineId })) : Promise.resolve()
1124
+ }
1125
+ const deleteLease = (lease) => lease && !disposing
1126
+ ? persist(stateStore.deleteLease(lease.leaseId).then(() => true)) : Promise.resolve()
1127
+ const persistDelegate = (childId, record, patch = {}) => {
1128
+ if (disposing || startupError) return Promise.resolve()
1129
+ const entry = timeline.get(record.parentId, childId)
1130
+ if (!entry) return Promise.resolve()
1131
+ const baseline = record.attempt?.baseline
1132
+ return persist(stateStore.putDelegate({
1133
+ ...stateStore.getDelegate(childId), ...entry, ...patch,
1134
+ childId, parentId: record.parentId, rootSessionId: record.rootSessionId ?? record.parentId,
1135
+ expectedTargets: record.expectedTargets, worktreeId: record.worktree?.id ?? entry.worktree?.id ?? null,
1136
+ wakeActionKey: record.wakeActionKey ?? null,
1137
+ retry: retry.exportChildRecord(childId),
1138
+ watchCursor: supervision.supervisor.exportCursor(childId),
1139
+ gitBaseline: smallGitBaseline(baseline) ?? null,
1140
+ }))
1141
+ }
1142
+ const queueLifecycle = (handler) => (payload) => {
1143
+ if (disposing) return
1144
+ if (bufferingLifecycle) {
1145
+ lifecycleQueue.push(() => handler(payload))
1146
+ return readyPromise
1147
+ }
1148
+ return handler(payload)
1149
+ }
1150
+ const defineReadyTool = (definition) => defineTool({
1151
+ ...definition,
1152
+ async execute(args, exec) {
1153
+ if (restoring) await readyPromise
1154
+ if (disposing || definition.name === 'delegate' || definition.name === ORCHESTRATE_TOOL) assertActive()
1155
+ return definition.execute(args, exec)
1156
+ },
1157
+ })
1158
+ const worktreeResumeRefusal = (childId) => {
1159
+ const worktree = worktreeOf(childId)
1160
+ const lock = worktrees.isChildLocked(childId)
1161
+ const missing = worktree && (!existsSync(worktree.worktreePath) || !existsSync(worktree.execCwd))
1162
+ if (!lock.locked && !missing) return undefined
1163
+ const detail = missing && !['merged', 'discarded'].includes(worktree.state)
1164
+ ? '工作树或执行目录已缺失,已拒绝投递以防写入主工作区。'
1165
+ : lock.reason
1166
+ return `[worktree-child-locked] ${formatWorktreeError('worktree-child-locked', detail)}`
1167
+ }
1168
+
1169
+ const observeAudit = ({ childId, parentId, audit, itemIndex, worktree }) => {
1170
+ try {
1171
+ ctx.emit?.('orchestrator/write-audit', { childId, parentId, audit, ...(worktree && { itemIndex, worktreeId: worktree.id }) })
1172
+ } catch (error) {
1173
+ warn(`无法发布子代理 ${childId} 的审计证据:${messageOf(error)}`)
1174
+ }
1175
+ // Failed evidence is attached to native settlement or queried, never a new wake-up turn.
1176
+ if (!audit.passed) warn(`【${childId}】不得验收为通过。\n${auditNotice(audit)}`)
1177
+ }
1178
+
1179
+ const closeWrite = (childId, record) => {
1180
+ const parentId = record.parentId
1181
+ const attempt = record.attempt
1182
+ if (attempt === undefined) {
1183
+ if (record.ended && record.disposalAudit !== undefined) {
1184
+ timeline.recordAudit(record.disposalAudit)
1185
+ record.disposalAudit = undefined
1186
+ }
1187
+ return
1188
+ }
1189
+ record.attempt = undefined
1190
+ record.releasedLease = attempt.lease
1191
+ try {
1192
+ const audit = settleDispatchWrite(attempt.baseline, auditGitBaseline) ??
1193
+ (record.baselineId ? missingBaselineAudit(record) : undefined)
1194
+ if (audit !== undefined) {
1195
+ const { summary, violations } = audit
1196
+ const evidence = {
1197
+ childId, parentId, runId: record.runId, baselineId: audit.baselineId,
1198
+ passed: audit.passed, incomplete: summary.truncated || violations.some(({ code }) => code === 'audit-incomplete'),
1199
+ violations, summary: `新增 ${summary.added};修改 ${summary.modified};删除 ${summary.deleted};违规 ${summary.violations}`,
1200
+ isolation: audit.isolationLevel, at: Date.now(),
1201
+ }
1202
+ if (record.worktree && audit.isolationLevel === 'git-worktree') {
1203
+ const stats = worktreeAuditSummary(audit)
1204
+ const review = worktrees.markReadyForReview(record.worktree.id, stats)
1205
+ background(putTree(record.worktree.id))
1206
+ timeline.recordWorktreeState(childId, { parentId, id: record.worktree.id, state: review?.state, ...stats })
1207
+ // Keep the full Git audit for the same-frame notice, including when disposal precedes end.
1208
+ evidence.audit = audit
1209
+ }
1210
+ // A disposal can provide negative evidence and release the lease, but only end certifies a pass.
1211
+ if (!record.ended && evidence.passed && !evidence.incomplete) record.disposalAudit = evidence
1212
+ else timeline.recordAudit(evidence)
1213
+ observeAudit({ childId, parentId, audit })
1214
+ }
1215
+ } finally {
1216
+ if (!record.batchId) {
1217
+ releaseWriteScope(writeLeases, attempt.lease)
1218
+ if (attempt.lease) timeline.recordLeaseReleased({ childId, parentId, leaseId: attempt.lease.leaseId, at: Date.now() })
1219
+ }
1220
+ supervision.scheduleReconcileInbox(parentId)
1221
+ }
1222
+ }
1223
+
1224
+ const disposeWrite = (childId, record, at = Date.now()) => {
1225
+ timeline.recordDisposed({ childId, parentId: record.parentId, at })
1226
+ closeWrite(childId, record)
1227
+ if (!record.batchId) background(persistDelegate(childId, record).then(() => deleteLease(record.releasedLease)))
1228
+ }
1229
+
1230
+ const prepareWriteRetry = (childId, record, operation = '自动续跑') => {
1231
+ const refusal = worktreeResumeRefusal(childId)
1232
+ if (refusal) throw new Error(refusal)
1233
+ const { parentId } = record
1234
+ let lease = null
1235
+ if (!record.readOnly) {
1236
+ const acquired = writeLeases.acquire({ childId, parentId, entries: record.entries })
1237
+ if (!acquired.ok) throw new Error(`已拒绝${operation}(${acquired.code}):${acquired.message}`)
1238
+ lease = acquired.lease
1239
+ }
1240
+ let baseline
1241
+ try {
1242
+ // Old fingerprints described the original dispatch, not the bytes already written by it.
1243
+ const baselineOptions = {
1244
+ cwd: record.cwd, writeScope: record.writeScope, readOnly: record.readOnly, expectedTargets: record.expectedTargets,
1245
+ }
1246
+ baseline = record.worktree
1247
+ ? captureGitBaseline({ ...baselineOptions, worktree: record.worktree, repoRoot: record.worktree.repoRoot })
1248
+ : captureDispatchBaseline(baselineOptions)
1249
+ } catch (error) {
1250
+ releaseWriteScope(writeLeases, lease)
1251
+ throw error
1252
+ }
1253
+ record.attempt = { lease, baseline }
1254
+ record.baselineId = baseline?.baselineId
1255
+ record.ended = false
1256
+ record.runId = undefined
1257
+ record.agent = null // Await the new residency; an old disposal cannot close this lease.
1258
+ timeline.recordRetry({
1259
+ parentId, childId, baselineId: baseline?.baselineId, leaseId: lease?.leaseId,
1260
+ readOnly: record.readOnly, startedAt: Date.now(),
1261
+ })
1262
+ return record.attempt
1263
+ }
1264
+
1265
+ const wakeIdentity = (childId, record) => ({
1266
+ childId, parentId: record.parentId, rootSessionId: record.rootSessionId ?? record.parentId,
1267
+ runId: record.runId, attemptSeq: timeline.get(record.parentId, childId)?.attemptSeq ?? 1,
1268
+ })
1269
+ const inspectChild = (identity) => inspectHostChildState({
1270
+ childId: identity.childId, expectedParentId: identity.parentId, expectedRootSessionId: identity.rootSessionId,
1271
+ agents: ctx.agents, sessions: ctx.sessions, sessionQuery: optionalSessionQuery(), signal: startupAbort.signal,
1272
+ })
1273
+ const saveAttempt = (childId, record) => Promise.all([
1274
+ putLease(record.attempt?.lease, record.baselineId), persistDelegate(childId, record),
1275
+ ])
1276
+
1277
+ // The policy still owns classification and budget; the adapter owns the durable wakeup and lease.
910
1278
  const retry = createRetry({
911
- deliverPrompt: (parentId, childId, text) => deliverRetryPrompt(ctx, parentId, childId, text),
912
- wakeParent: supervision.deliverRetry,
1279
+ async deliverPrompt(parentId, childId, text) {
1280
+ assertActive()
1281
+ const record = writes.get(childId)
1282
+ if (record === undefined || record.parentId !== parentId || record.attempt !== undefined) {
1283
+ throw new Error('没有可安全恢复的原写作用域记录;已拒绝自动续跑')
1284
+ }
1285
+ const refusal = worktreeResumeRefusal(childId)
1286
+ if (refusal) throw new Error(refusal)
1287
+ let reservation
1288
+ let sent = false
1289
+ if (hasStorage) {
1290
+ const identity = wakeIdentity(childId, record)
1291
+ const hostState = await inspectChild(identity)
1292
+ assertActive()
1293
+ const retryOrdinal = retry.exportChildRecord(childId).records[0]?.retries ?? 1
1294
+ const gate = evaluateWakeupGate({ ...identity, kind: 'retry', retryOrdinal, worktrees, hostState, actionLedger })
1295
+ if (!gate.allowed || wakeups.has(childId) || record.runId !== identity.runId || record.attempt) {
1296
+ throw new Error(`唤醒门禁拒绝自动续跑:${gate.allowed ? 'in-flight' : gate.reason}`)
1297
+ }
1298
+ reservation = { key: gate.actionKey, kind: 'retry', identity }
1299
+ wakeups.set(childId, reservation)
1300
+ }
1301
+ let attempt
1302
+ try {
1303
+ attempt = prepareWriteRetry(childId, record)
1304
+ if (reservation) {
1305
+ const prepared = await actionLedger.prepare(reservation.key, { ...reservation.identity, kind: 'retry' })
1306
+ if (!prepared.ok) throw new Error(`唤醒预留失败:${prepared.reason}`)
1307
+ reservation.requestId = prepared.record.requestId
1308
+ record.wakeActionKey = reservation.key
1309
+ await saveAttempt(childId, record)
1310
+ assertActive()
1311
+ }
1312
+ } catch (error) {
1313
+ if (reservation && wakeups.get(childId) === reservation) wakeups.delete(childId)
1314
+ if (attempt && record.attempt === attempt) {
1315
+ record.attempt = undefined
1316
+ record.ended = true
1317
+ releaseWriteScope(writeLeases, attempt.lease)
1318
+ await deleteLease(attempt.lease)
1319
+ }
1320
+ throw error
1321
+ }
1322
+ const { lease, baseline } = attempt
1323
+ try {
1324
+ const baselineNote = baseline === undefined ? '' : `\n本轮写后审计基线:${baseline.baselineId}。`
1325
+ const modeNote = record.readOnly ? `\n${READ_ONLY_NOTICE}` : ''
1326
+ const worktreeNote = record.worktree ? `\n${worktreePromptNote(record.worktree)}` : ''
1327
+ if (reservation?.observed) return undefined
1328
+ sent = true
1329
+ if (reservation) reservation.submitted = true
1330
+ const messageId = await deliverRetryPrompt(ctx, parentId, childId,
1331
+ text + modeNote + baselineNote + worktreeNote, reservation?.requestId)
1332
+ if (reservation && !disposing) {
1333
+ if (!messageId && !record.runId) throw new Error('宿主未确认投递')
1334
+ await actionLedger.markAccepted(reservation.key, { messageId })
1335
+ if (record.runId) await actionLedger.markDone(reservation.key, { messageId })
1336
+ }
1337
+ return messageId
1338
+ } catch (error) {
1339
+ if (reservation && sent) {
1340
+ // A transport error is not evidence that no activation happened.
1341
+ if (!disposing && !record.runId) await actionLedger.markUnknown(reservation.key, { detail: messageOf(error) })
1342
+ throw error
1343
+ }
1344
+ if (record.attempt === attempt) {
1345
+ record.attempt = undefined
1346
+ record.ended = true
1347
+ timeline.recordDisposed({ childId, parentId, at: Date.now() })
1348
+ releaseWriteScope(writeLeases, lease)
1349
+ if (lease) timeline.recordLeaseReleased({ childId, parentId, leaseId: lease.leaseId, at: Date.now() })
1350
+ }
1351
+ supervision.scheduleReconcileInbox(parentId)
1352
+ throw error
1353
+ }
1354
+ },
1355
+ wakeParent: (...args) => disposing ? undefined : supervision.deliverRetry(...args),
913
1356
  logger: ctx.logger,
914
1357
  })
915
1358
  const hooks = createSupervisionHooks(supervision.supervisor, {
@@ -917,7 +1360,6 @@ export function apply(ctx, config) {
917
1360
  retry,
918
1361
  scheduleReconcileInbox: supervision.scheduleReconcileInbox,
919
1362
  })
920
- const supervisionTurnState = createSupervisionTurnState()
921
1363
  const rootAgents = new Map()
922
1364
  const sessionToRootAgent = new Map()
923
1365
  const todoTracker = createTodoSnapshotTracker(ctx, {
@@ -933,53 +1375,252 @@ export function apply(ctx, config) {
933
1375
  logger: ctx.logger,
934
1376
  })
935
1377
 
936
- // One lease table for the plugin's lifetime. `delegate` claims one lease per child and
937
- // `orchestrate` one per batch, so keeping the single instance here is what makes two
938
- // dispatches of either tool see each other. The lifecycle hooks below release by child
939
- // id, and a plugin reload drops the whole table.
940
- const writeLeases = createWriteLeases()
1378
+ // Only bounded recent host identities are needed to bridge receipt and event ordering.
1379
+ const rememberRecent = (map, key, value) => {
1380
+ map.delete(key)
1381
+ map.set(key, value)
1382
+ if (map.size > 256) map.delete(map.keys().next().value)
1383
+ }
941
1384
 
942
- const releaseWriteLease = (childId) => {
943
- try {
944
- writeLeases.releaseByChild(childId)
945
- } catch (error) {
1385
+ const finishDetachedBatch = async (childId, record) => {
1386
+ const lease = record.releasedLease
1387
+ if (!lease || !detachedBatchLeases.has(lease.leaseId)) return
1388
+ const stageRows = stateStore.listDelegates().filter((row) => row.leaseId === lease.leaseId)
1389
+ if (stageRows.some((row) => row.childId !== childId && row.dispatchState === 'running')) return
1390
+ await deleteLease(lease)
1391
+ releaseWriteScope(writeLeases, lease)
1392
+ detachedBatchLeases.delete(lease.leaseId)
1393
+ for (const row of stageRows) timeline.recordLeaseReleased({ childId: row.childId,
1394
+ parentId: row.parentId, leaseId: lease.leaseId, at: Date.now() })
1395
+ }
1396
+
1397
+ const settleChild = (info) => {
1398
+ const childId = info?.id
1399
+ if (typeof childId !== 'string' || childId === '') return
1400
+ const runId = info.runId
1401
+ if (runId && endedRuns.has(runId)) return
1402
+ const record = writes.get(childId)
1403
+ if (record === undefined) {
1404
+ // A worker can finish before startActivation's receipt is handed back to delegate.
1405
+ if (hostRuns.get(childId)?.runId === runId && runId) rememberRecent(earlyEnds, childId, info)
1406
+ return
1407
+ }
1408
+ if (typeof info.parentSessionId === 'string' && record.parentId !== info.parentSessionId) return
1409
+ if (record.runId && runId && record.runId !== runId) return
1410
+ if (runId) {
1411
+ endedRuns.add(runId)
1412
+ if (endedRuns.size > 256) endedRuns.delete(endedRuns.values().next().value)
1413
+ } else if (record.ended) {
1414
+ return
1415
+ }
1416
+ const settle = async () => {
1417
+ if (hasStorage) {
1418
+ assertActive()
1419
+ const identity = { ...wakeIdentity(childId, record), runId: runId ?? record.runId }
1420
+ const key = makeSettleActionKey(identity)
1421
+ const prepared = await actionLedger.prepare(key, { ...identity, kind: 'settle' })
1422
+ if (!prepared.ok || disposing) return
1423
+ return completeSettlement(key)
1424
+ }
1425
+ return completeSettlement()
1426
+ }
1427
+ const completeSettlement = async (key) => {
1428
+ record.ended = true
1429
+ record.agent = null
1430
+ record.runId ??= runId
1431
+ const parentId = record.parentId
1432
+ timeline.recordEnded({ childId, parentId, runId, stopReason: info.stopReason, at: Date.now() })
1433
+ closeWrite(childId, record)
1434
+ hooks.forget(childId)
1435
+ supervision.scheduleReconcileInbox(parentId)
1436
+ const lease = record.releasedLease
1437
+ const durable = persistDelegate(childId, record).then(() =>
1438
+ record.batchId ? finishDetachedBatch(childId, record) : deleteLease(lease))
1439
+ if (key) {
1440
+ await durable
1441
+ if (disposing) return
1442
+ await actionLedger.markDone(key)
1443
+ } else background(durable)
1444
+ if (record.batchId || disposing) return
946
1445
  try {
947
- ctx.logger?.warn?.(`orchestrator: cannot release the write lease of ${childId}: ${messageOf(error)}`)
948
- } catch {
949
- // A logging failure must not escape a lifecycle listener.
1446
+ await retry.settle(childId, info, runId ?? record.runId)
1447
+ } finally {
1448
+ await persistDelegate(childId, record)
950
1449
  }
951
1450
  }
1451
+ const pending = settle().catch((error) => warn(`无法结算子代理 ${childId}:${messageOf(error)}`))
1452
+ return pending
952
1453
  }
953
1454
 
954
- ctx.effect(
955
- () => () => {
956
- const cleared = writeLeases.clear()
957
- if (cleared > 0) {
958
- try {
959
- ctx.logger?.info?.(`orchestrator: cleared ${cleared} write lease(s) on dispose`)
960
- } catch {
961
- // Disposal must not fail on a logger.
1455
+ const onDelegateStarted = (parent, started, args, write, agentName) => {
1456
+ const childId = started.childId
1457
+ const parentId = parent.id
1458
+ const cachedRun = hostRuns.get(childId)
1459
+ const hostRun = cachedRun?.parentId === undefined || cachedRun.parentId === parentId ? cachedRun : undefined
1460
+ const { baseline, lease, ...metadata } = write
1461
+ const runId = hostRun?.runId ?? started.runId
1462
+ if (disposing) return
1463
+ timeline.recordDispatched({
1464
+ parentId, childId, agentName, label: args.description, readOnly: write.readOnly, writeScope: write.writeScope,
1465
+ cwd: write.cwd, baselineId: baseline?.baselineId, leaseId: lease?.leaseId, startedAt: Date.now(), worktree: write.worktree,
1466
+ })
1467
+ timeline.recordRunStarted({ childId, parentId, runId })
1468
+ const record = {
1469
+ ...metadata,
1470
+ parentId,
1471
+ rootSessionId: parent.session?.header?.rootSessionId ?? parentId,
1472
+ label: args.description,
1473
+ baselineId: baseline?.baselineId,
1474
+ expectedTargets: baseline?.expectedTargets ?? args.expectedTargets,
1475
+ runId,
1476
+ agent: hostRun?.agent ?? ctx.agents?.get?.(childId),
1477
+ attempt: { lease, baseline },
1478
+ }
1479
+ writes.set(childId, record)
1480
+ // Keep resumable worktree metadata through review, but bound other detached records.
1481
+ for (const [id, record] of writes) {
1482
+ if (writes.size <= 256) break
1483
+ if (record.attempt === undefined && !retry.has(id) && !wakeups.has(id) && !keepWorktreeWrite(record)) writes.delete(id)
1484
+ }
1485
+ hooks.onStarted(parent, { ...started, runId }, args, write)
1486
+ const durable = Promise.all([putTree(write.worktree?.id), saveAttempt(childId, record)])
1487
+ const earlyDisposal = earlyDisposals.get(childId)
1488
+ if (earlyDisposal !== undefined && earlyDisposal.agent === record.agent && earlyDisposal.runId === runId) {
1489
+ earlyDisposals.delete(childId)
1490
+ disposeWrite(childId, record, earlyDisposal.at)
1491
+ hooks.forget(childId)
1492
+ }
1493
+ const earlyEnd = earlyEnds.get(childId)
1494
+ if (earlyEnd?.parentSessionId === parent.id) {
1495
+ earlyEnds.delete(childId)
1496
+ background(Promise.resolve(settleChild(earlyEnd)))
1497
+ }
1498
+ return durable
1499
+ }
1500
+
1501
+ // Legacy synchronous embedders may dispose individual registration effects.
1502
+ // The Cordis path instead has a single owner for the runtime and its handles.
1503
+ const legacyEffects = typeof ctx.get !== 'function'
1504
+ const rememberCleanup = (list, handle) => {
1505
+ if (typeof handle === 'function') list.push(handle)
1506
+ else if (typeof handle?.[Symbol.dispose] === 'function') list.push(() => handle[Symbol.dispose]())
1507
+ }
1508
+ const own = (setup, label) => {
1509
+ if (legacyEffects) return ctx.effect(setup, label)
1510
+ rememberCleanup(producerDisposers, setup())
1511
+ }
1512
+ const listen = (...args) => rememberCleanup(listenerDisposers, ctx.on(...args))
1513
+ const clean = (disposers) => {
1514
+ while (disposers.length > 0) {
1515
+ try { disposers.pop()() } catch (error) { warn(`卸载清理失败:${messageOf(error)}`) }
1516
+ }
1517
+ }
1518
+ if (legacyEffects) ctx.effect(() => () => writeLeases.clear(), 'orchestrator: write leases')
1519
+
1520
+ const dispatchPersistence = {
1521
+ assertActive,
1522
+ isDisposing: () => disposing,
1523
+ async beforeLaunch(write) {
1524
+ assertActive()
1525
+ await Promise.all([putTree(write.worktree?.id), putLease(write.lease, write.baseline?.baselineId)])
1526
+ },
1527
+ async afterFailedLaunch(write) {
1528
+ await putTree(write.worktree?.id)
1529
+ await deleteLease(write.lease)
1530
+ },
1531
+ }
1532
+
1533
+ const stageTracking = {
1534
+ ...dispatchPersistence,
1535
+ async stageStarted(batch, handle, stage) {
1536
+ if (disposing) return
1537
+ const { parent, write, batchId } = batch
1538
+ const childId = handle.childId
1539
+ const cached = hostRuns.get(childId)
1540
+ const runId = cached?.parentId === parent.id ? cached.runId ?? handle.runId : handle.runId
1541
+ if (write.worktree) {
1542
+ worktrees.rebindChild(write.worktree.id, childId)
1543
+ worktrees.bindChild(write.worktree.id, childId)
1544
+ }
1545
+ const record = {
1546
+ ...stage, batchId, childId, parentId: parent.id, rootSessionId: parent.session?.header?.rootSessionId ?? parent.id,
1547
+ worktree: write.worktree, expectedTargets: write.baseline?.expectedTargets, runId,
1548
+ }
1549
+ batch.children.set(childId, { record, ended: false })
1550
+ batchStages.set(childId, batch)
1551
+ timeline.recordDispatched({ ...record, ...write, baselineId: write.baseline?.baselineId, leaseId: write.lease?.leaseId })
1552
+ timeline.recordRunStarted({ childId, parentId: parent.id, runId })
1553
+ await Promise.all([putTree(write.worktree?.id), putLease(write.lease, write.baseline?.baselineId),
1554
+ persistDelegate(childId, record, { ...stage, batchId })])
1555
+ },
1556
+ async stageEnded(batch, handle, result) {
1557
+ if (disposing) return
1558
+ const stage = batch.children.get(handle.childId)
1559
+ if (!stage || stage.ended) return
1560
+ stage.ended = true
1561
+ const { record } = stage
1562
+ timeline.recordEnded({ ...record, stopReason: result.stopReason })
1563
+ await persistDelegate(record.childId, record, { batchId: record.batchId, itemIndex: record.itemIndex, stageIndex: record.stageIndex })
1564
+ },
1565
+ canFinishBatch(batch) {
1566
+ return batch.inFlightStarts === 0 && [...batch.children.values()].every((stage) => stage.ended)
1567
+ },
1568
+ async finishBatch(batch, audit) {
1569
+ const { write } = batch
1570
+ await putTree(write.worktree?.id)
1571
+ for (const [childId, { record }] of batch.children) {
1572
+ if (disposing) return
1573
+ const { parentId } = record
1574
+ if (audit) {
1575
+ const incomplete = audit.summary.truncated || audit.violations.some(({ code }) => code === 'audit-incomplete')
1576
+ timeline.recordAudit({ childId, parentId, baselineId: audit.baselineId, passed: audit.passed,
1577
+ incomplete, violations: audit.violations, isolation: audit.isolationLevel, audit })
962
1578
  }
1579
+ const tree = write.worktree && worktrees.get(write.worktree.id)
1580
+ if (tree) timeline.recordWorktreeState(childId, { parentId, id: tree.id, state: tree.state, ...tree.auditSummary })
1581
+ if (write.lease) timeline.recordLeaseReleased({ childId, parentId, leaseId: write.lease.leaseId })
1582
+ await persistDelegate(childId, record, { batchId: record.batchId, itemIndex: record.itemIndex, stageIndex: record.stageIndex })
1583
+ batchStages.delete(childId)
963
1584
  }
1585
+ await deleteLease(write.lease)
1586
+ releaseWriteScope(writeLeases, write.lease)
964
1587
  },
965
- 'orchestrator: write leases',
966
- )
1588
+ }
967
1589
 
968
- // The rule text the delegation tools show names exactly the tools the gate allows,
969
- // read from the same effective whitelist, so the prompt cannot drift from the
970
- // enforcement even when a profile checks a different set. The list is a function
971
- // because `allowedTools` is volatile: the tools re-read it when their description is
972
- // rendered, and the guard re-reads it on every call.
973
- const allowedTools = () =>
974
- effectiveAllowed(configValue(config, 'allowedTools', undefined), DEFAULT_ALLOWED_TOOLS)
1590
+ // The same live whitelist feeds the prompt, execution guard and tool definitions.
1591
+ const catalog = createCatalogPublisher({ ctx, config })
1592
+ const allowAgentTeam = () => configValue(config, 'allowAgentTeam', true) !== false
1593
+ const allowedTools = () => resolveEffectiveAllowedTools(configValue(config, 'allowedTools', undefined), {
1594
+ defaults: DEFAULT_ALLOWED_TOOLS,
1595
+ allowAgentTeam: allowAgentTeam(),
1596
+ availableTools: catalog.published(),
1597
+ })
1598
+ const nativeToolNote = () => {
1599
+ const allowed = allowedTools()
1600
+ const team = NATIVE_TEAM_TOOLS.some((name) => allowed.includes(name))
1601
+ ? '原生 team_task_* 仅用于共享任务板,不替代派发或写租约。'
1602
+ : ''
1603
+ return `${team}subagent_fork / workflow 默认屏蔽。`
1604
+ }
1605
+
1606
+ const worktreeDispatch = {
1607
+ worktrees,
1608
+ isWorktreeEnabled: () => configValue(config, 'worktreeIsolationEnabled', true) !== false,
1609
+ captureGitBaseline,
1610
+ auditGitBaseline,
1611
+ probeGitRepo,
1612
+ onCleanupFailed: (error) => warn(`无法清理未启动的工作树:${messageOf(error)}`),
1613
+ }
975
1614
 
976
- // One registration for every agent; children get it too and are bounded by maxDepth.
977
- // A child has both names masked away below, so one definition per tool is enough.
1615
+ // One registry entry per tool. The root whitelist and child mask own visibility.
978
1616
  const delegateTool = createDelegateTool({
979
- defineTool,
1617
+ ...worktreeDispatch,
1618
+ defineTool: defineReadyTool,
1619
+ persistence: hasStorage ? dispatchPersistence : undefined,
980
1620
  subagents: ctx.subagents,
981
1621
  config,
982
- onStarted: hooks.onStarted,
1622
+ onStarted: onDelegateStarted,
1623
+ nativeToolNote,
983
1624
  allowedTools,
984
1625
  leases: writeLeases,
985
1626
  })
@@ -987,13 +1628,144 @@ export function apply(ctx, config) {
987
1628
  // claim the same path at the same time; a second table would make them blind to each
988
1629
  // other and defeat the exclusion entirely.
989
1630
  const orchestrateTool = createOrchestrateTool({
990
- defineTool,
1631
+ ...worktreeDispatch,
1632
+ defineTool: defineReadyTool,
1633
+ stageTracking: hasStorage ? stageTracking : undefined,
991
1634
  subagents: ctx.subagents,
992
1635
  config,
993
1636
  leases: writeLeases,
1637
+ onAudited: observeAudit,
994
1638
  })
995
- ctx.effect(() => ctx.tools.register(delegateTool), 'orchestrator: delegate tool')
996
- ctx.effect(() => ctx.tools.register(orchestrateTool), `orchestrator: ${ORCHESTRATE_TOOL} tool`)
1639
+ own(() => ctx.tools.register(delegateTool), 'orchestrator: delegate tool')
1640
+ own(() => ctx.tools.register(orchestrateTool), `orchestrator: ${ORCHESTRATE_TOOL} tool`)
1641
+ const delegateStatusTool = createDelegateStatusTool({
1642
+ defineTool: defineReadyTool,
1643
+ timeline,
1644
+ toolName: DELEGATE_STATUS_TOOL_NAME,
1645
+ isRootAgent: (agent) => !isDelegatedChild(agent),
1646
+ })
1647
+ own(() => ctx.tools.register(delegateStatusTool), `orchestrator: ${DELEGATE_STATUS_TOOL_NAME} tool`)
1648
+ const worktreeManageTool = createPersistentWorktreeTool({
1649
+ worktrees, stateStore, timeline, assertActive, persist, isWakePending: (id) => wakeups.has(id),
1650
+ onClosed(record) {
1651
+ const write = writes.get(record.childId)
1652
+ if (write?.worktree?.id === record.id && write.attempt === undefined) writes.delete(record.childId)
1653
+ },
1654
+ isRootAgent: (exec) => Boolean(exec?.agent) && !isDelegatedChild(exec.agent),
1655
+ defineTool: defineReadyTool,
1656
+ })
1657
+ own(() => ctx.tools.register(worktreeManageTool), `orchestrator: ${worktreeManageTool.name} tool`)
1658
+
1659
+ // Resolve exactly as the native tool does without changing its argument contract.
1660
+ const resolveMessageTarget = async (exec) => {
1661
+ const target = exec.arguments?.agent
1662
+ if (typeof target !== 'string' || target === '') return {}
1663
+ assertActive()
1664
+ let childId = target
1665
+ let refusal = worktreeResumeRefusal(childId)
1666
+ if (!refusal && (writes.size > 0 || worktrees.getChildWorktreeMap().size > 0 ||
1667
+ (hasStorage && stateStore.listDelegates().length > 0)) && typeof ctx.subagents.resolveName === 'function') {
1668
+ childId = (await ctx.subagents.resolveName(exec.agent, target, exec.signal)) ?? target
1669
+ assertActive()
1670
+ refusal = worktreeResumeRefusal(childId)
1671
+ }
1672
+ if (refusal) throw new Error(refusal)
1673
+ const row = hasStorage ? stateStore.getDelegate(childId) : undefined
1674
+ const record = writes.get(childId) ?? row
1675
+ if (!record) return { childId }
1676
+ const identity = wakeIdentity(childId, record)
1677
+ if (wakeups.has(childId)) throw new Error('唤醒门禁拒绝 send_message:in-flight')
1678
+ if (hasStorage) {
1679
+ const hostState = await inspectChild(identity)
1680
+ assertActive()
1681
+ if (hostState.running && !hostState.ownershipMismatch) return { childId }
1682
+ if (row?.wakeActionKey) {
1683
+ const pending = actionLedger.canInitiate(row.wakeActionKey)
1684
+ if (!pending.allowed && pending.record?.phase !== 'done') throw new Error(`唤醒门禁拒绝 send_message:${pending.reason}`)
1685
+ }
1686
+ if (record.batchId) throw new Error('编排阶段不能单独恢复;请新建任务。')
1687
+ const gate = evaluateWakeupGate({ ...identity, kind: 'resume', worktrees, hostState, actionLedger })
1688
+ if (!gate.allowed) throw new Error(`唤醒门禁拒绝 send_message:${gate.reason}`)
1689
+ if (wakeups.has(childId) || identity.runId !== record.runId) throw new Error('唤醒门禁拒绝 send_message:in-flight')
1690
+ if (record.attempt) throw new Error('原运行仍在结算,请稍后向同一代理重试。')
1691
+ return { childId, row, identity, key: gate.actionKey }
1692
+ }
1693
+ return { childId, identity }
1694
+ }
1695
+
1696
+ // Early preflight keeps lock refusals visible to direct and Code Mode callers. Reserve
1697
+ // only in tools/execute, after the host's approval and remaining pre-execute guards.
1698
+ listen('tools/pre-execute', async (exec, next) => {
1699
+ const decision = await next()
1700
+ if (decision?.kind === 'deny' || exec.name !== 'send_message') return decision
1701
+ if (restoring) await readyPromise
1702
+ try {
1703
+ await resolveMessageTarget(exec)
1704
+ return decision
1705
+ } catch (error) {
1706
+ return { kind: 'deny', reason: `无法核验 send_message 目标「${exec.arguments?.agent}」:${messageOf(error)}` }
1707
+ }
1708
+ }, { global: true })
1709
+
1710
+ listen('tools/execute', async (exec, next) => {
1711
+ if (exec.name !== 'send_message') return next()
1712
+ if (restoring) await readyPromise
1713
+ const { childId, row, identity, key } = await resolveMessageTarget(exec)
1714
+ if (!identity) return next()
1715
+ const refusal = worktreeResumeRefusal(childId)
1716
+ if (refusal) throw new Error(refusal)
1717
+ const current = writes.get(childId) ?? hydrateWrite(row)
1718
+ if (wakeups.has(childId) || identity.runId !== current.runId) throw new Error('唤醒门禁拒绝 send_message:in-flight')
1719
+ if (current.attempt) return next() // A live residency still owns its original lease and baseline.
1720
+ if (!current.readOnly && !current.entries?.length) throw new Error('无法核验原写作用域')
1721
+
1722
+ const previous = { ...current }
1723
+ const entry = timeline.get(current.parentId, childId)
1724
+ const reservation = { kind: 'resume', key, identity }
1725
+ wakeups.set(childId, reservation)
1726
+ let attempt
1727
+ let prepared = false
1728
+ let delivering = false
1729
+ let result
1730
+ try {
1731
+ attempt = prepareWriteRetry(childId, current, 'send_message 续跑')
1732
+ if (key) {
1733
+ const claim = await actionLedger.prepare(key, { ...identity, kind: 'resume' })
1734
+ if (!claim.ok) throw new Error(`唤醒门禁拒绝 send_message:${claim.reason}`)
1735
+ prepared = true
1736
+ current.wakeActionKey = key
1737
+ await saveAttempt(childId, current)
1738
+ }
1739
+ assertActive()
1740
+ const refusal = worktreeResumeRefusal(childId)
1741
+ if (refusal) throw new Error(refusal)
1742
+ exec.signal?.throwIfAborted?.()
1743
+ delivering = true
1744
+ result = await next()
1745
+ if (key && !result?.isError) await actionLedger.markAccepted(key, { messageId: result?.value?.messageId })
1746
+ return result
1747
+ } finally {
1748
+ // A published start takes ownership, even if a later hook cannot confirm delivery.
1749
+ if (!reservation.observed && (!delivering || result?.isError === true)) {
1750
+ if (attempt && current.attempt === attempt) {
1751
+ Object.assign(current, previous, { wakeActionKey: previous.wakeActionKey })
1752
+ releaseWriteScope(writeLeases, attempt.lease)
1753
+ if (entry) timeline.hydrateEntries([{ ...entry, updatedAt: Date.now() }])
1754
+ }
1755
+ try {
1756
+ if (prepared) await actionLedger.cancelPrepared(key)
1757
+ if (attempt && key) {
1758
+ await deleteLease(attempt.lease)
1759
+ await persistDelegate(childId, current)
1760
+ }
1761
+ } finally {
1762
+ if (wakeups.get(childId) === reservation) wakeups.delete(childId)
1763
+ }
1764
+ } else if (key && delivering && !result && !reservation.observed) {
1765
+ await actionLedger.markUnknown(key)
1766
+ }
1767
+ }
1768
+ }, { global: true })
997
1769
 
998
1770
  /**
999
1771
  * The live guard of every gated main agent, keyed by agent id. One predicate covers every
@@ -1007,6 +1779,7 @@ export function apply(ctx, config) {
1007
1779
  const installFor = (agent) => installGate({
1008
1780
  agent,
1009
1781
  allowed: allowedTools,
1782
+ allowAgentTeam,
1010
1783
  enabled: dispatchEnabled,
1011
1784
  checkSupervision: (current, tool, options) => supervisionTurnState.checkTool(current.id, currentTurnOf(current), tool, options),
1012
1785
  })
@@ -1020,9 +1793,8 @@ export function apply(ctx, config) {
1020
1793
  * nothing at all. The first read runs here: later registrations announce themselves on
1021
1794
  * `tools/change`.
1022
1795
  */
1023
- const catalog = createCatalogPublisher({ ctx, config })
1024
- ctx.effect(() => () => catalog.dispose(), 'orchestrator: tool catalog')
1025
- ctx.on('tools/change', () => {
1796
+ own(() => () => catalog.dispose(), 'orchestrator: tool catalog')
1797
+ listen('tools/change', () => {
1026
1798
  // Publishing keeps the panel's checklist complete. Nothing else has to happen: the
1027
1799
  // model-facing table is filtered per request by the surface wrapper below.
1028
1800
  catalog.schedule()
@@ -1038,63 +1810,191 @@ export function apply(ctx, config) {
1038
1810
  * (a request built inside that window saw them appear, the next saw them vanish, and the
1039
1811
  * cached prompt prefix was lost each time).
1040
1812
  */
1041
- ctx.effect(
1813
+ own(
1042
1814
  () =>
1043
1815
  installToolSurface({
1044
1816
  tools: ctx.tools,
1045
1817
  allowed: allowedTools,
1818
+ allowAgentTeam,
1046
1819
  enabled: dispatchEnabled,
1047
1820
  }),
1048
1821
  'orchestrator: tool surface',
1049
1822
  )
1050
1823
 
1824
+ const hydrateWrite = (row, { active = false, agent } = {}) => {
1825
+ const worktree = row.worktreeId ? worktrees.get(row.worktreeId) : undefined
1826
+ const lease = row.leaseId && writeLeases.get(row.leaseId)
1827
+ const scope = row.readOnly ? null : normalizeScope(row.writeScope ?? [], row.cwd)
1828
+ const record = {
1829
+ ...row, worktree, agent, ended: !active, entries: lease?.entries ?? scope?.entries,
1830
+ attempt: active ? { lease, baseline: restoredGitBaseline(row, worktree) } : undefined,
1831
+ }
1832
+ writes.set(row.childId, record)
1833
+ if (active && row.batchId && lease) detachedBatchLeases.add(lease.leaseId)
1834
+ return record
1835
+ }
1836
+ const armRun = (childId, record, { resumed = false, startedAt = Date.now() } = {}) => {
1837
+ if (record.batchId) return
1838
+ supervision.supervisor.track({
1839
+ childId, parentId: record.parentId, runId: record.runId, label: record.label,
1840
+ startedAt, resumed, readOnly: record.readOnly, cwd: record.cwd, writeScope: record.entries,
1841
+ ...(resumed && { sinceSeq: supervision.headSeq(childId) }),
1842
+ })
1843
+ }
1844
+ const runStarted = (childId, record, agent, runId) => {
1845
+ if (record.worktree) {
1846
+ const review = worktrees.reopenForRetry(record.worktree.id)
1847
+ timeline.recordWorktreeState(childId, {
1848
+ parentId: record.parentId, id: record.worktree.id, state: review?.state, conflictFiles: review?.conflictFiles,
1849
+ })
1850
+ background(putTree(record.worktree.id))
1851
+ }
1852
+ const changedRun = runId && record.runId !== runId
1853
+ record.runId = runId ?? record.runId
1854
+ record.agent = agent
1855
+ timeline.recordRunStarted({ childId, parentId: record.parentId, runId })
1856
+ const reservation = wakeups.get(childId)
1857
+ if (reservation) {
1858
+ reservation.observed = true
1859
+ if (!retry.has(childId)) retry.track(childId, { parentId: record.parentId, label: record.label })
1860
+ }
1861
+ if (changedRun && (hasStorage || reservation)) armRun(childId, record, { resumed: true })
1862
+ const actionKey = reservation?.key ?? record.wakeActionKey
1863
+ const previousRun = reservation?.identity.runId ?? actionLedger.get(actionKey)?.runId
1864
+ if (reservation && runId !== previousRun) wakeups.delete(childId)
1865
+ if (actionKey && runId && runId !== previousRun) {
1866
+ record.wakeActionKey = null
1867
+ return persistDelegate(childId, record).then(() => actionLedger.markDone(actionKey))
1868
+ }
1869
+ return persistDelegate(childId, record)
1870
+ }
1871
+ const resumeFromHost = async (agent, childId, runId, parentId) => {
1872
+ if (disposing || startupError) return
1873
+ const refusal = worktreeResumeRefusal(childId)
1874
+ if (refusal) { warn(refusal); return }
1875
+ const row = stateStore.getDelegate(childId)
1876
+ const record = writes.get(childId) ?? (row && !row.batchId && hydrateWrite(row))
1877
+ if (!record || record.batchId || (parentId && record.parentId !== parentId)) return
1878
+ if (record.runId === runId && runId && !record.ended) return
1879
+ let reservation = wakeups.get(childId)
1880
+ if (!reservation) {
1881
+ const identity = wakeIdentity(childId, record)
1882
+ const key = makeResumeActionKey({ ...identity, interruptedRunId: identity.runId })
1883
+ reservation = { kind: 'resume', key, identity }
1884
+ wakeups.set(childId, reservation)
1885
+ const prepared = await actionLedger.prepare(key, { ...identity, kind: 'resume', interruptedRunId: identity.runId })
1886
+ if (!prepared.ok) {
1887
+ wakeups.delete(childId)
1888
+ warn(`未重复挂接 ${childId} 的恢复动作:${prepared.reason}`)
1889
+ return
1890
+ }
1891
+ }
1892
+ if (disposing) return
1893
+ reservation.observed = true
1894
+ if (reservation.kind === 'retry' && !reservation.submitted) {
1895
+ // A host-side resume won before the plugin called prompt().
1896
+ await actionLedger.markAccepted(reservation.key)
1897
+ }
1898
+ if (!record.attempt) {
1899
+ if (!record.readOnly && !record.entries?.length) {
1900
+ warn(`子代理 ${childId} 缺少可验证的写作用域;未重建活跃追踪`)
1901
+ return
1902
+ }
1903
+ prepareWriteRetry(childId, record)
1904
+ record.wakeActionKey = reservation.key
1905
+ if (!retry.has(childId)) retry.track(childId, { parentId: record.parentId, label: record.label })
1906
+ armRun(childId, record, { resumed: true })
1907
+ await saveAttempt(childId, record)
1908
+ } else if (record.runId && runId && record.runId !== runId) {
1909
+ // A new native run cannot inherit a still-open, different attempt.
1910
+ warn(`子代理 ${childId} 的活动代次不匹配;保留原租约`)
1911
+ return
1912
+ }
1913
+ if (!disposing) {
1914
+ if (!retry.has(childId)) retry.track(childId, { parentId: record.parentId, label: record.label })
1915
+ await actionLedger.markAccepted(reservation.key)
1916
+ const activeRun = runId ?? hostRuns.get(childId)?.runId
1917
+ if (activeRun && activeRun !== reservation.identity.runId) await runStarted(childId, record, agent, activeRun)
1918
+ }
1919
+ }
1920
+
1051
1921
  // The host may not mount cordis-plugin-timer, so use the platform timer through
1052
1922
  // the existing effect lifecycle. The period is fixed at 5 s because a tick only
1053
1923
  // compares clocks; a child's log is read only once it is due, so this keeps the
1054
1924
  // 10-second minimum interval prompt without a configurable scan. `unref` keeps a
1055
1925
  // short-lived CLI test process from hanging on an interval the host would own.
1056
1926
  const scanMs = 5000
1057
- ctx.effect(
1058
- () => {
1059
- const timer = setInterval(() => {
1060
- void Promise.resolve(supervision.supervisor.tick()).catch((error) => {
1061
- ctx.logger?.warn?.(`orchestrator: supervision timer: ${messageOf(error)}`)
1062
- })
1063
- }, scanMs)
1064
- if (typeof timer?.unref === 'function') timer.unref()
1065
- return () => clearInterval(timer)
1066
- },
1067
- 'orchestrator: supervision timer',
1068
- )
1069
-
1070
- /**
1071
- * The settlement edge of every delegated child. A child that stops with `error` and left
1072
- * no text behind is the case lib/retry.js retries; anything else releases its record.
1073
- *
1074
- * The host dispatches this edge with the child's parent as its carrier, so the listener
1075
- * must be global: a context-scoped listener is filtered out for a child-scoped emission.
1076
- * The policy is async (it queues one prompt), and the emitter contains rejections, but the
1077
- * failure is still reported here so a broken retry is visible rather than silent.
1078
- */
1079
- ctx.on(
1080
- 'subagent/end',
1081
- (info) => {
1082
- const childId = info?.id
1083
- if (typeof childId !== 'string' || childId === '') return
1084
- // Settlement is one of the two edges a live child stops at; a lease held past this
1085
- // point would refuse every later writer until its TTL.
1086
- releaseWriteLease(childId)
1087
- hooks.forget(childId)
1088
- void Promise.resolve(retry.settle(childId, info, info?.runId)).catch((error) => {
1089
- try {
1090
- ctx.logger?.warn?.(`orchestrator: retry: cannot apply the settlement of ${childId}: ${messageOf(error)}`)
1091
- } catch {
1092
- // A logging failure must not escape the listener either.
1927
+ let scanning = false
1928
+ const timer = setInterval(() => {
1929
+ if (restoring || disposing || scanning || startupError) return
1930
+ scanning = true
1931
+ const before = new Map(supervision.supervisor.exportCursors().map((row) => [row.childId, JSON.stringify(row)]))
1932
+ const scan = async () => {
1933
+ try {
1934
+ await supervision.supervisor.tick()
1935
+ if (!disposing && hasStorage) {
1936
+ for (const cursor of supervision.supervisor.exportCursors()) {
1937
+ if (before.get(cursor.childId) !== JSON.stringify(cursor)) {
1938
+ const record = writes.get(cursor.childId)
1939
+ if (record?.attempt) await persistDelegate(cursor.childId, record)
1940
+ }
1941
+ }
1093
1942
  }
1094
- })
1095
- },
1096
- { global: true },
1097
- )
1943
+ } catch (error) {
1944
+ warn(`巡检失败:${messageOf(error)}`)
1945
+ } finally {
1946
+ scanning = false
1947
+ }
1948
+ }
1949
+ return scan()
1950
+ }, scanMs)
1951
+ timer?.unref?.()
1952
+ const stopTimer = () => clearInterval(timer)
1953
+ if (legacyEffects) ctx.effect(() => stopTimer, 'orchestrator: supervision timer')
1954
+
1955
+ // Host lifecycle events use the parent as carrier, so both listeners are global.
1956
+ listen('subagent/start', queueLifecycle((info) => {
1957
+ const childId = info?.id
1958
+ if (typeof childId !== 'string' || childId === '') return
1959
+ const agent = ctx.agents?.get?.(childId)
1960
+ const { parentSessionId: parentId, runId } = info
1961
+ if (runId && endedRuns.has(runId)) return
1962
+ const record = writes.get(childId)
1963
+ if (typeof parentId === 'string' && record !== undefined && parentId !== record.parentId) return
1964
+ rememberRecent(hostRuns, childId, { parentId, runId, agent })
1965
+ earlyEnds.delete(childId)
1966
+ earlyDisposals.delete(childId)
1967
+ if (hasStorage) {
1968
+ if (batchStages.has(childId)) return
1969
+ if (record?.attempt && (!record.runId || !runId || record.runId === runId)) {
1970
+ return runStarted(childId, record, agent, runId)
1971
+ }
1972
+ const row = stateStore.getDelegate(childId)
1973
+ if (row && !row.batchId && row.runId !== runId) {
1974
+ return resumeFromHost(agent, childId, runId, parentId).catch((error) => warn(messageOf(error)))
1975
+ }
1976
+ return
1977
+ }
1978
+ // Keep the legacy Worktree lifecycle fallback for starts outside the tool path.
1979
+ if (record?.ended && record.attempt === undefined && runId && keepWorktreeWrite(record)) {
1980
+ try {
1981
+ prepareWriteRetry(childId, record)
1982
+ if (!retry.has(childId)) retry.track(childId, { parentId: record.parentId })
1983
+ } catch (error) {
1984
+ warn(`无法为子代理 ${childId} 的返工准备审计:${messageOf(error)}`)
1985
+ }
1986
+ }
1987
+ if (record?.attempt !== undefined && (!record.runId || !runId || record.runId === runId)) {
1988
+ return runStarted(childId, record, agent, runId)
1989
+ }
1990
+ }), { global: true })
1991
+ const receiveEnd = queueLifecycle(settleChild)
1992
+ listen('subagent/end', (info) => {
1993
+ if (bufferingLifecycle && info?.id && info.runId) {
1994
+ pendingEnds.add(endIdentity(info.id, info.parentSessionId, info.runId))
1995
+ }
1996
+ return receiveEnd(info)
1997
+ }, { global: true })
1098
1998
 
1099
1999
  /** Registration also covers roots that were already alive when the plugin mounted. */
1100
2000
  const registerRootAgent = (agent) => {
@@ -1134,12 +2034,18 @@ export function apply(ctx, config) {
1134
2034
  }
1135
2035
  }
1136
2036
 
1137
- ctx.effect(() => () => {
2037
+ own(() => () => {
1138
2038
  for (const agent of rootAgents.values()) unregisterRootAgent(agent)
1139
2039
  sessionToRootAgent.clear()
1140
2040
  }, 'orchestrator: root agents')
1141
2041
 
1142
- ctx.on('agent/created', (payload) => {
2042
+ const receiveResume = queueLifecycle(({ agent, runId }) => {
2043
+ if (!hasStorage) return hooks.onResumed(agent)
2044
+ return resumeFromHost(agent, agent.id, runId, agent.session?.header?.parentSession)
2045
+ .catch((error) => warn(`恢复子代理 ${agent.id} 失败:${messageOf(error)}`))
2046
+ })
2047
+ listen('agent/created', (payload) => {
2048
+ if (disposing) return
1143
2049
  const agent = payload?.agent
1144
2050
  // A new root agent is the only place a preset or scope-local tool becomes visible,
1145
2051
  // so the catalog may have grown even though the registry itself did not change.
@@ -1151,7 +2057,7 @@ export function apply(ctx, config) {
1151
2057
  // no `tools/change` is announced. A `send_message` cold resume recreates an
1152
2058
  // interrupted worker, and its receipt was already settled, so supervision has
1153
2059
  // forgotten it; only a child this plugin dispatched is re-armed.
1154
- if (payload?.source === 'resume') hooks.onResumed(agent)
2060
+ if (payload?.source === 'resume') return receiveResume({ agent, runId: payload.runId })
1155
2061
  return
1156
2062
  }
1157
2063
 
@@ -1174,21 +2080,29 @@ export function apply(ctx, config) {
1174
2080
 
1175
2081
  // A gated agent that goes away takes its guard with it: the entry is the only owner of
1176
2082
  // the disposer, so dropping it here must not leave a predicate behind.
1177
- ctx.on('agent/disposed', (payload) => {
2083
+ listen('agent/disposed', queueLifecycle((payload) => {
1178
2084
  const agent = payload?.agent
1179
2085
  const id = agent?.id
1180
2086
  // A root agent going away can drop its scope-local names from the catalog.
1181
2087
  catalog.schedule()
1182
2088
  if (typeof id !== 'string') return
1183
- // A worker may be disposed without a settlement edge (host shutdown, killed process),
1184
- // so this is the second, independent release path for its write lease.
1185
- releaseWriteLease(id)
2089
+ const record = writes.get(id)
2090
+ // On this host disposal can precede subagent/end or even the activation receipt.
2091
+ // Only this residency can release its lease; a stale disposal must not release a retry lease.
2092
+ if (record !== undefined && !record.ended && !record.batchId && (record.agent === undefined || record.agent === agent)) {
2093
+ disposeWrite(id, record)
2094
+ } else if (record === undefined && !earlyEnds.has(id) && isDelegatedChild(agent)) {
2095
+ const hostRun = hostRuns.get(id)
2096
+ if (hostRun?.agent === agent && !endedRuns.has(hostRun.runId)) {
2097
+ rememberRecent(earlyDisposals, id, { ...hostRun, at: Date.now() })
2098
+ }
2099
+ }
1186
2100
  unregisterRootAgent(agent)
1187
2101
  supervision.scheduleReconcileInbox(id)
1188
- // A disposed worker must not keep a supervision slot: until it is resumed its session
1189
- // is gone, and the tick would only read a dead log. A resume re-arms it above.
1190
- if (isDelegatedChild(agent)) hooks.forget(id)
1191
- })
2102
+ if (isDelegatedChild(agent) && (record === undefined || record.agent === undefined || record.agent === agent)) {
2103
+ hooks.forget(id)
2104
+ }
2105
+ }))
1192
2106
 
1193
2107
  /**
1194
2108
  * The panel writes `enabled` and `allowedTools` as volatile config: the loader commits
@@ -1201,7 +2115,7 @@ export function apply(ctx, config) {
1201
2115
  * the model what changed. Nothing is delivered now: a notice at this moment would splice
1202
2116
  * into a turn the user is still reading.
1203
2117
  */
1204
- ctx.on('loader/volatile-update', () => {
2118
+ listen('loader/volatile-update', () => {
1205
2119
  // Restore it before the write's own settings read answers, so the panel never falls
1206
2120
  // back to its built-in copy after a checkbox click.
1207
2121
  catalog.publish()
@@ -1216,9 +2130,10 @@ export function apply(ctx, config) {
1216
2130
  * reentrancy, rides inside the user's own turn with zero extra bubbles or turns, and leaves
1217
2131
  * the pending flag untouched if an outer hook rejects or aborts the step.
1218
2132
  */
1219
- ctx.on('agent/inbox/claimed', supervision.claimNotice, { global: true })
2133
+ listen('agent/inbox/claimed', (...args) => { if (!disposing) supervision.claimNotice(...args) }, { global: true })
1220
2134
 
1221
- ctx.on('session/event', (session, event) => {
2135
+ listen('session/event', (session, event) => {
2136
+ if (disposing) return
1222
2137
  const agent = sessionToRootAgent.get(session)
1223
2138
  if (agent === undefined || isDelegatedChild(agent)) return
1224
2139
  if (event?.type === 'todo/write') {
@@ -1234,18 +2149,115 @@ export function apply(ctx, config) {
1234
2149
  }
1235
2150
  }, { global: true })
1236
2151
 
1237
- ctx.on(
1238
- 'agent/pre-step',
1239
- createSupervisionPreStep({
2152
+ const preStep = createSupervisionPreStep({
1240
2153
  ctx,
1241
2154
  config,
1242
2155
  supervisor: supervision.supervisor,
1243
2156
  rebuildNotice: supervision.rebuildNotice,
2157
+ liveNoticeIds: supervision.liveNoticeIds,
2158
+ auditTimeline: timeline,
2159
+ loadAuditCreator: supervision.loadAuditCreator,
2160
+ scheduleReconcileInbox: supervision.scheduleReconcileInbox,
1244
2161
  retainNotices: supervision.retainNotices,
1245
2162
  supervisionTurnState,
1246
2163
  todoTracker,
1247
- nextStep: createSwitchPreStep({ switchNotices, logger: ctx.logger, supervisionTurnState }),
1248
- }),
1249
- { global: true },
1250
- )
2164
+ nextStep: createSwitchPreStep({ switchNotices, logger: ctx.logger, supervisionTurnState }),
2165
+ })
2166
+ listen('agent/pre-step', async (payload, next) => {
2167
+ if (restoring) await readyPromise
2168
+ if (disposing) return next()
2169
+ const decision = await preStep(payload, next)
2170
+ if (hasStorage && !disposing && Array.isArray(decision?.messages)) {
2171
+ for (const { childId, entry } of settledAuditEntries(timeline, payload?.agent?.id, decision.messages)) {
2172
+ if (entry.auditDeliveredVia && entry.auditDeliveredVia !== stateStore.getDelegate(childId)?.auditDeliveredVia) {
2173
+ await persistDelegate(childId, writes.get(childId) ?? stateStore.getDelegate(childId) ?? entry)
2174
+ }
2175
+ }
2176
+ }
2177
+ return decision
2178
+ }, { global: true })
2179
+
2180
+ // Register the lifecycle edges above before opening storage; events captured during I/O
2181
+ // are replayed before tools are let through the readiness gate.
2182
+ const startRecovery = async () => {
2183
+ await domainReservation.previous
2184
+ if (disposing) return
2185
+ await stateStore.open()
2186
+ if (disposing) return
2187
+ if (stateStore.hasUnsafeState()) startupError ??= new Error('存储域无法完整读取;原始数据已保留')
2188
+ const snapshot = stateStore.getSnapshot()
2189
+ const decorateTimeline = (row) => {
2190
+ const tree = row.worktreeId && worktrees.get(row.worktreeId)
2191
+ const leaseState = row.leaseState ?? (!row.leaseId ? 'none'
2192
+ : writeLeases.get(row.leaseId) ? 'held' : startupError ? 'unknown' : 'released')
2193
+ return { ...row, leaseState, ...(tree && { worktree: { ...tree, ...tree.auditSummary, locked: tree.locked } }) }
2194
+ }
2195
+ await reconcileOnStartup({
2196
+ snapshot, store: stateStore, worktrees, leases: writeLeases, timeline, retry, actionLedger,
2197
+ supervise: supervision.supervisor, agents: ctx.agents, sessions: ctx.sessions,
2198
+ sessionQuery: optionalSessionQuery(), signal: startupAbort.signal, logger: ctx.logger,
2199
+ decorateTimeline, readOnly: Boolean(startupError),
2200
+ onProtectionUnverified() { startupError ??= new Error('部分工作树或写租约没有通过水合校验') },
2201
+ hasPendingEnd(row) {
2202
+ return Boolean(row.runId && pendingEnds.has(endIdentity(row.childId, row.parentId, row.runId)))
2203
+ },
2204
+ onReattachRunning(row) {
2205
+ const refusal = worktreeResumeRefusal(row.childId)
2206
+ if (refusal) { warn(refusal); return }
2207
+ const record = hydrateWrite(row, { active: true, agent: ctx.agents?.get?.(row.childId) })
2208
+ armRun(row.childId, record, { startedAt: row.startedAt })
2209
+ },
2210
+ async onDelegateReconciled(row) {
2211
+ const tree = row.worktreeId && worktrees.get(row.worktreeId)
2212
+ if (tree?.state !== 'active' || stateStore.listDelegates().some((other) =>
2213
+ other.worktreeId === tree.id && other.childId !== row.childId && other.dispatchState === 'running')) return
2214
+ const review = worktrees.markReadyForReview(tree.id, { incomplete: row.incomplete === true })
2215
+ await putTree(tree.id)
2216
+ for (const childId of tree.childIds) timeline.recordWorktreeState(childId, {
2217
+ id: tree.id, parentId: tree.parentId, state: review?.state,
2218
+ })
2219
+ },
2220
+ })
2221
+ bufferingLifecycle = false
2222
+ for (const dispatch of lifecycleQueue.splice(0)) {
2223
+ if (disposing) return
2224
+ await dispatch()
2225
+ }
2226
+ pendingEnds.clear()
2227
+ if (!disposing && !startupError) await stateStore.pruneHistory()
2228
+ }
2229
+ readyPromise = hasStorage ? startRecovery().catch((error) => {
2230
+ if (!disposing) startupError ??= error
2231
+ }).finally(() => {
2232
+ restoring = false
2233
+ bufferingLifecycle = false
2234
+ lifecycleQueue.length = 0
2235
+ pendingEnds.clear()
2236
+ if (startupError && !disposing) warn(`恢复保护状态失败:${messageOf(startupError)}`)
2237
+ }) : stateStore.open()
2238
+
2239
+ ctx.effect(() => () => {
2240
+ if (disposePromise) return disposePromise
2241
+ disposing = true
2242
+ if (!legacyEffects) stopTimer()
2243
+ startupAbort.abort()
2244
+ const closing = stateStore.close()
2245
+ disposePromise = closing.catch((error) => warn(`关闭存储域失败:${messageOf(error)}`)).finally(() => {
2246
+ try {
2247
+ clean(listenerDisposers)
2248
+ for (const cursor of supervision.supervisor.exportCursors()) supervision.supervisor.forget(cursor.childId)
2249
+ writeLeases.clear()
2250
+ worktrees.clear()
2251
+ writes.clear()
2252
+ batchStages.clear()
2253
+ wakeups.clear()
2254
+ } finally {
2255
+ domainReservation?.release()
2256
+ }
2257
+ })
2258
+ // Unpublish dispatch producers before a younger fiber registers the same tool names.
2259
+ // Already queued storage writes and the actual domain close still share one ordered chain.
2260
+ clean(producerDisposers)
2261
+ return disposePromise
2262
+ }, 'orchestrator: lifecycle')
1251
2263
  }