@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/README.md +142 -93
- package/README.zh.md +144 -95
- package/docs/images/dispatch-panel.png +0 -0
- package/docs/images/hero-banner.png +0 -0
- package/lib/api.js +1 -0
- package/lib/catalog.js +2 -1
- package/lib/client.js +131 -44
- package/lib/delegate-status.js +125 -0
- package/lib/delegate.js +299 -59
- package/lib/gate.js +57 -15
- package/lib/git-audit.js +383 -0
- package/lib/index.js +1185 -173
- package/lib/orchestrate.js +313 -89
- package/lib/reconcile.js +590 -0
- package/lib/retry.js +68 -5
- package/lib/rules.js +15 -2
- package/lib/state-store.js +455 -0
- package/lib/supervise.js +593 -87
- package/lib/timeline.js +464 -0
- package/lib/tool-surface.js +69 -21
- package/lib/worktree-manage.js +244 -0
- package/lib/worktree-tool.js +38 -0
- package/lib/worktree.js +687 -0
- package/lib/write-audit.js +333 -0
- package/lib/write-lease.js +161 -7
- package/lib/write-scope-tool.js +29 -0
- package/lib/write-scope.js +14 -18
- package/package.json +3 -3
package/lib/orchestrate.js
CHANGED
|
@@ -9,16 +9,22 @@
|
|
|
9
9
|
* provider/model override the user asked for — `delivery: 'caller'` and, when the
|
|
10
10
|
* stage declares one, `outputSchema`.
|
|
11
11
|
*
|
|
12
|
-
* A batch
|
|
13
|
-
*
|
|
14
|
-
*
|
|
15
|
-
* trimming items — see `docs/zh/03-issue-0001-write-scope.md` §6.7.2.
|
|
12
|
+
* A writable batch declares one top-level `writeScope`. In Git isolation each item
|
|
13
|
+
* owns a checkout, lease and audit across all its stages. Shared mode preserves the
|
|
14
|
+
* atomic batch lease and workspace snapshot; a conflict starts no workers.
|
|
16
15
|
*/
|
|
17
16
|
|
|
17
|
+
import { randomUUID } from 'node:crypto'
|
|
18
18
|
import { DELIVERY, LIMITS, ORCHESTRATE_TOOL, ORCHESTRATION_KIND, disabledToolMessage } from './api.js'
|
|
19
|
+
import {
|
|
20
|
+
READ_ONLY_NOTICE, auditNotice, discardEmptyWorktree, dispatchWorkspaceRoot, dispatchWriteParameters,
|
|
21
|
+
prepareDispatchWrite, settleDispatchWrite, validateDispatchIsolation, validateDispatchWrite,
|
|
22
|
+
worktreeAuditSummary, worktreeDetails, worktreeFailure, worktreePromptNote,
|
|
23
|
+
} from './delegate.js'
|
|
19
24
|
import { assertObjectSchema, isJsonValue, validateJsonSchemaValue } from './schema.js'
|
|
20
25
|
import { buildSpawnActivation, isDispatchEnabled, readRoute, readRouteOverride } from './worker.js'
|
|
21
|
-
import {
|
|
26
|
+
import { probeGitRepo } from './worktree.js'
|
|
27
|
+
import { dispatchCwd, formatWorktreeError, releaseWriteScope, writeScopeNotice } from './write-scope-tool.js'
|
|
22
28
|
|
|
23
29
|
function isPlainObject(value) {
|
|
24
30
|
if (typeof value !== 'object' || value === null || Array.isArray(value)) return false
|
|
@@ -43,6 +49,10 @@ const ARGUMENT_KEYS = Object.freeze([
|
|
|
43
49
|
'model',
|
|
44
50
|
'reasoning_effort',
|
|
45
51
|
'writeScope',
|
|
52
|
+
'readOnly',
|
|
53
|
+
'isolation',
|
|
54
|
+
'expectedFingerprints',
|
|
55
|
+
'expectedTargets',
|
|
46
56
|
])
|
|
47
57
|
const STAGE_KEYS = Object.freeze(['name', 'prompt', 'schema'])
|
|
48
58
|
|
|
@@ -113,10 +123,8 @@ export function parseOrchestrateArgs(args) {
|
|
|
113
123
|
if (cwd === '') fail('"cwd" must be a non-empty string when provided')
|
|
114
124
|
}
|
|
115
125
|
|
|
116
|
-
//
|
|
117
|
-
|
|
118
|
-
// schema and checked by `execute` before this parser runs, so the plan always carries it.
|
|
119
|
-
const { writeScope } = args
|
|
126
|
+
// The dispatch layer validates write arguments before this parser runs.
|
|
127
|
+
const { writeScope, readOnly } = args
|
|
120
128
|
|
|
121
129
|
return {
|
|
122
130
|
cwd,
|
|
@@ -124,14 +132,14 @@ export function parseOrchestrateArgs(args) {
|
|
|
124
132
|
stages,
|
|
125
133
|
maxConcurrency: args.maxConcurrency ?? LIMITS.maxConcurrency.default,
|
|
126
134
|
writeScope,
|
|
135
|
+
readOnly: readOnly === true,
|
|
127
136
|
}
|
|
128
137
|
}
|
|
129
138
|
|
|
130
139
|
/**
|
|
131
140
|
* A worker-visible prompt: stage instruction, original item and previous output.
|
|
132
141
|
*
|
|
133
|
-
*
|
|
134
|
-
* paragraph: every batch declares one, so there is no undeclared variant to preserve.
|
|
142
|
+
* Every stage receives the batch's normalized scope or the explicit read-only constraint.
|
|
135
143
|
*/
|
|
136
144
|
export function buildStagePrompt({
|
|
137
145
|
stage,
|
|
@@ -142,6 +150,9 @@ export function buildStagePrompt({
|
|
|
142
150
|
itemCount,
|
|
143
151
|
previous,
|
|
144
152
|
writeScope,
|
|
153
|
+
readOnly,
|
|
154
|
+
baselineId,
|
|
155
|
+
worktree,
|
|
145
156
|
}) {
|
|
146
157
|
const lines = [
|
|
147
158
|
stage.prompt.trim(),
|
|
@@ -174,7 +185,9 @@ export function buildStagePrompt({
|
|
|
174
185
|
// Unlike a single delegation, a batch has no per-worker description carrying the
|
|
175
186
|
// declaration, so the constraint always travels with the prompt.
|
|
176
187
|
lines.push('')
|
|
177
|
-
lines.push(writeScopeNotice(writeScope))
|
|
188
|
+
lines.push(readOnly ? READ_ONLY_NOTICE : writeScopeNotice(writeScope))
|
|
189
|
+
if (baselineId !== undefined) lines.push(`写后审计基线:${baselineId}。`)
|
|
190
|
+
if (worktree) lines.push('', worktreePromptNote(worktree))
|
|
178
191
|
return lines.join('\n')
|
|
179
192
|
}
|
|
180
193
|
|
|
@@ -297,9 +310,8 @@ function createLimiter(limit) {
|
|
|
297
310
|
* Run the plan. Returns the unified result, or throws for a global failure
|
|
298
311
|
* (abort, oversized result, an internal error outside per-item isolation).
|
|
299
312
|
*
|
|
300
|
-
*
|
|
301
|
-
* reaches the worker prompts,
|
|
302
|
-
* declares one.
|
|
313
|
+
* A writable batch's normalized `writeScope` is already leased by the caller and
|
|
314
|
+
* reaches the worker prompts, not the result payload.
|
|
303
315
|
*/
|
|
304
316
|
export async function runOrchestration({
|
|
305
317
|
plan,
|
|
@@ -309,8 +321,12 @@ export async function runOrchestration({
|
|
|
309
321
|
subagents,
|
|
310
322
|
signal,
|
|
311
323
|
writeScope,
|
|
324
|
+
baselineId,
|
|
325
|
+
itemIsolation,
|
|
326
|
+
stageTracking,
|
|
327
|
+
sharedBatch,
|
|
312
328
|
}) {
|
|
313
|
-
const { cwd, items, stages, maxConcurrency } = plan
|
|
329
|
+
const { cwd, items, stages, maxConcurrency, readOnly } = plan
|
|
314
330
|
const limiter = createLimiter(maxConcurrency)
|
|
315
331
|
const results = new Array(items.length).fill(null)
|
|
316
332
|
const errors = []
|
|
@@ -351,15 +367,19 @@ export async function runOrchestration({
|
|
|
351
367
|
if (signal.aborted) throw abortReason(signal)
|
|
352
368
|
signal.addEventListener('abort', onAbort, { once: true })
|
|
353
369
|
|
|
354
|
-
const runStage = async ({ stage, stageIndex, prompt, itemIndex }) => {
|
|
370
|
+
const runStage = async ({ stage, stageIndex, prompt, itemIndex, workspace }) => {
|
|
355
371
|
let acquired = false
|
|
356
372
|
let started
|
|
373
|
+
const batch = workspace?.batch ?? sharedBatch
|
|
374
|
+
let result
|
|
357
375
|
try {
|
|
358
|
-
|
|
359
|
-
|
|
376
|
+
if (!itemIsolation) {
|
|
377
|
+
await limiter.acquire(signal)
|
|
378
|
+
acquired = true
|
|
379
|
+
}
|
|
360
380
|
if (signal.aborted) throw abortReason(signal)
|
|
361
381
|
const spec = buildSpawnActivation({
|
|
362
|
-
cwd,
|
|
382
|
+
cwd: workspace?.worktree.execCwd ?? cwd,
|
|
363
383
|
prompt,
|
|
364
384
|
label: `orchestrate ${stage.name} (item ${itemIndex + 1}/${items.length}, stage ${stageIndex + 1}/${stages.length})`,
|
|
365
385
|
parent,
|
|
@@ -372,11 +392,45 @@ export async function runOrchestration({
|
|
|
372
392
|
// Race the start itself against abort: a hanging startActivation must not
|
|
373
393
|
// delay cancellation. A handle that only resolves after the abort is
|
|
374
394
|
// disposed on arrival and is never dispatched.
|
|
375
|
-
const startPromise = Promise.resolve().then(() =>
|
|
395
|
+
const startPromise = Promise.resolve().then(async () => {
|
|
396
|
+
if (signal.aborted) throw abortReason(signal)
|
|
397
|
+
stageTracking?.assertActive()
|
|
398
|
+
if (batch) batch.inFlightStarts += 1
|
|
399
|
+
try {
|
|
400
|
+
const handle = await subagents.startActivation(spec)
|
|
401
|
+
if (batch && handle?.childId) {
|
|
402
|
+
try {
|
|
403
|
+
await stageTracking.stageStarted(batch, handle, { itemIndex, stageIndex, label: spec.label })
|
|
404
|
+
} catch (error) {
|
|
405
|
+
await dispose(handle)
|
|
406
|
+
throw error
|
|
407
|
+
}
|
|
408
|
+
}
|
|
409
|
+
return handle
|
|
410
|
+
} finally {
|
|
411
|
+
if (batch) batch.inFlightStarts -= 1
|
|
412
|
+
}
|
|
413
|
+
})
|
|
376
414
|
const settledStart = startPromise.then(
|
|
377
415
|
(handle) => ({ handle }),
|
|
378
416
|
(error) => ({ error }),
|
|
379
417
|
)
|
|
418
|
+
// A start still in flight can launch a writer even after cancellation. Do not remove
|
|
419
|
+
// or audit the checkout until a late receipt has been observed and disposed.
|
|
420
|
+
if (workspace) {
|
|
421
|
+
const pending = settledStart.then(async ({ handle }) => {
|
|
422
|
+
if (!handle || typeof handle !== 'object') return
|
|
423
|
+
// A receipt without a child or result is not evidence that a stage ran.
|
|
424
|
+
workspace.started ||= (typeof handle.childId === 'string' && handle.childId.length > 0) ||
|
|
425
|
+
typeof handle.result?.then === 'function'
|
|
426
|
+
if (workspace.started) itemIsolation.bind(workspace, handle)
|
|
427
|
+
if (signal.aborted) await dispose(handle)
|
|
428
|
+
})
|
|
429
|
+
workspace.pending = pending
|
|
430
|
+
void pending.finally(() => {
|
|
431
|
+
if (workspace.pending === pending) workspace.pending = undefined
|
|
432
|
+
}).catch(() => {})
|
|
433
|
+
}
|
|
380
434
|
started = await new Promise((resolve, reject) => {
|
|
381
435
|
const onAbort = () => reject(abortReason(signal))
|
|
382
436
|
if (signal.aborted) onAbort()
|
|
@@ -408,7 +462,7 @@ export async function runOrchestration({
|
|
|
408
462
|
active.add(started)
|
|
409
463
|
// Race the worker against the abort signal: cancellation must not wait for a
|
|
410
464
|
// worker that ignores its own signal, and the handle is disposed in `finally`.
|
|
411
|
-
|
|
465
|
+
result = await new Promise((resolve, reject) => {
|
|
412
466
|
const onAbort = () => reject(abortReason(signal))
|
|
413
467
|
signal.addEventListener('abort', onAbort, { once: true })
|
|
414
468
|
started.result.then(
|
|
@@ -425,43 +479,70 @@ export async function runOrchestration({
|
|
|
425
479
|
if (signal.aborted) throw abortReason(signal)
|
|
426
480
|
return readStageOutput(stage, result)
|
|
427
481
|
} finally {
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
482
|
+
try {
|
|
483
|
+
if (started !== undefined) {
|
|
484
|
+
active.delete(started)
|
|
485
|
+
await dispose(started)
|
|
486
|
+
if (batch && result) await stageTracking.stageEnded(batch, started, result)
|
|
487
|
+
}
|
|
488
|
+
} finally {
|
|
489
|
+
if (acquired) limiter.release()
|
|
431
490
|
}
|
|
432
|
-
if (acquired) limiter.release()
|
|
433
491
|
}
|
|
434
492
|
}
|
|
435
493
|
|
|
436
494
|
const runItem = async (item, index) => {
|
|
495
|
+
let acquired = false
|
|
496
|
+
let workspace
|
|
437
497
|
let previous
|
|
438
498
|
let output
|
|
439
|
-
let
|
|
440
|
-
|
|
499
|
+
let stageIndex = 0
|
|
500
|
+
try {
|
|
501
|
+
if (itemIsolation) {
|
|
502
|
+
await limiter.acquire(signal)
|
|
503
|
+
acquired = true
|
|
504
|
+
signal.throwIfAborted()
|
|
505
|
+
workspace = itemIsolation.prepare(index)
|
|
506
|
+
if (workspace.batch) await stageTracking.beforeLaunch(workspace.write)
|
|
507
|
+
}
|
|
508
|
+
for (; stageIndex < stages.length; stageIndex += 1) {
|
|
509
|
+
if (signal.aborted) throw abortReason(signal)
|
|
510
|
+
const stage = stages[stageIndex]
|
|
511
|
+
const prompt = buildStagePrompt({
|
|
512
|
+
stage,
|
|
513
|
+
stageIndex,
|
|
514
|
+
stageCount: stages.length,
|
|
515
|
+
item,
|
|
516
|
+
itemIndex: index,
|
|
517
|
+
itemCount: items.length,
|
|
518
|
+
previous,
|
|
519
|
+
writeScope: workspace?.write.writeScope ?? writeScope,
|
|
520
|
+
readOnly,
|
|
521
|
+
baselineId: workspace?.write.baseline?.baselineId ?? baselineId,
|
|
522
|
+
worktree: workspace?.worktree,
|
|
523
|
+
})
|
|
524
|
+
output = await runStage({ stage, stageIndex, prompt, itemIndex: index, workspace })
|
|
525
|
+
previous = { stageName: stage.name, output }
|
|
526
|
+
}
|
|
527
|
+
return { index, output, stopReason: 'completed' }
|
|
528
|
+
} catch (error) {
|
|
441
529
|
if (signal.aborted) throw abortReason(signal)
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
stageIndex,
|
|
446
|
-
stageCount: stages.length,
|
|
447
|
-
item,
|
|
448
|
-
itemIndex: index,
|
|
449
|
-
itemCount: items.length,
|
|
450
|
-
previous,
|
|
451
|
-
writeScope,
|
|
452
|
-
})
|
|
530
|
+
errors.push({ index, stage: stages[stageIndex].name, stageIndex, message: messageOf(error) })
|
|
531
|
+
return null
|
|
532
|
+
} finally {
|
|
453
533
|
try {
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
534
|
+
if (workspace) {
|
|
535
|
+
const finish = () => itemIsolation.finish(workspace, index)
|
|
536
|
+
if (workspace.pending && signal.aborted) itemIsolation.defer(workspace.pending, finish)
|
|
537
|
+
else {
|
|
538
|
+
await workspace.pending
|
|
539
|
+
await finish()
|
|
540
|
+
}
|
|
541
|
+
}
|
|
542
|
+
} finally {
|
|
543
|
+
if (acquired) limiter.release()
|
|
462
544
|
}
|
|
463
545
|
}
|
|
464
|
-
return { index, output, stopReason }
|
|
465
546
|
}
|
|
466
547
|
|
|
467
548
|
try {
|
|
@@ -499,18 +580,124 @@ export async function runOrchestration({
|
|
|
499
580
|
* records it like a child: `batch-<parent>-<n>` is what `details[].owner` names and what
|
|
500
581
|
* `release` frees at the end.
|
|
501
582
|
*
|
|
502
|
-
* The
|
|
503
|
-
* tool instances in the same process must not mint the same identity — doing so would make
|
|
504
|
-
* the table merge their leases (`childId` is the one-lease-per-child key) instead of
|
|
505
|
-
* refusing the second batch.
|
|
583
|
+
* The identity must also be unique against leases restored from an earlier process.
|
|
506
584
|
*/
|
|
507
|
-
let batchSequence = 0
|
|
508
585
|
function nextBatchId(parent) {
|
|
509
|
-
|
|
510
|
-
|
|
586
|
+
return `batch-${String(parent?.id ?? 'parent')}-${randomUUID()}`
|
|
587
|
+
}
|
|
588
|
+
|
|
589
|
+
const newBatch = (batchId, parent, write) => ({
|
|
590
|
+
batchId, parent, write, children: new Map(), inFlightStarts: 0,
|
|
591
|
+
})
|
|
592
|
+
|
|
593
|
+
function prepareItemIsolation({
|
|
594
|
+
isolation, worktrees, args, exec, parent, checked, leases, batchId, probeRepo, getWorkspaceRoot,
|
|
595
|
+
captureGit, auditGit, onAudited, onWorktreeChild, onCleanupFailed, stageTracking,
|
|
596
|
+
}) {
|
|
597
|
+
const sourceCwd = dispatchCwd(args, exec)
|
|
598
|
+
const workspaceRoot = dispatchWorkspaceRoot(exec, getWorkspaceRoot)
|
|
599
|
+
const forced = isolation.mode === 'worktree'
|
|
600
|
+
const fallback = (result, quiet = false) => {
|
|
601
|
+
if (forced) throw worktreeFailure(result)
|
|
602
|
+
return quiet ? {} : { isolationFallback: { code: result.code, message: formatWorktreeError(result.code, result) } }
|
|
603
|
+
}
|
|
604
|
+
if (!worktrees) return fallback({ code: 'worktree-create-failed', message: '工作树管理器不可用。' })
|
|
605
|
+
let probe
|
|
606
|
+
try {
|
|
607
|
+
probe = probeRepo(sourceCwd)
|
|
608
|
+
} catch (error) {
|
|
609
|
+
return fallback({ code: 'worktree-create-failed', message: messageOf(error) })
|
|
610
|
+
}
|
|
611
|
+
if (!probe.isGit || !probe.headCommit) return fallback({ code: probe.reason ?? 'not-git-repo' }, true)
|
|
612
|
+
|
|
613
|
+
const create = (index) => worktrees.create({
|
|
614
|
+
sourceCwd, workspaceRoot, label: `orchestrate item ${index + 1}`,
|
|
615
|
+
parentId: parent.id ?? null, batchId, itemIndex: index,
|
|
616
|
+
})
|
|
617
|
+
// The first checkout doubles as the containment check. Once any worker can run,
|
|
618
|
+
// no item may fall back to the main checkout.
|
|
619
|
+
const first = create(0)
|
|
620
|
+
if (!first.ok) return fallback(first)
|
|
621
|
+
let seed = first.worktree
|
|
622
|
+
const rows = []
|
|
623
|
+
return {
|
|
624
|
+
rows,
|
|
625
|
+
disposeUnused() {
|
|
626
|
+
if (seed && !stageTracking?.isDisposing()) discardEmptyWorktree(worktrees, seed, onCleanupFailed)
|
|
627
|
+
},
|
|
628
|
+
itemIsolation: {
|
|
629
|
+
prepare(index) {
|
|
630
|
+
const created = index === 0 ? { ok: true, worktree: seed } : create(index)
|
|
631
|
+
if (index === 0) seed = undefined
|
|
632
|
+
if (!created.ok) throw worktreeFailure(created)
|
|
633
|
+
const worktree = created.worktree
|
|
634
|
+
try {
|
|
635
|
+
const write = prepareDispatchWrite({
|
|
636
|
+
args, exec, parent, leases, childId: `${batchId}:item:${index}`, tool: ORCHESTRATE_TOOL,
|
|
637
|
+
checked, worktree, captureGit,
|
|
638
|
+
})
|
|
639
|
+
const batch = stageTracking ? newBatch(batchId, parent, write) : undefined
|
|
640
|
+
return { worktree, write, batch, started: false }
|
|
641
|
+
} catch (error) {
|
|
642
|
+
discardEmptyWorktree(worktrees, worktree, onCleanupFailed)
|
|
643
|
+
throw error
|
|
644
|
+
}
|
|
645
|
+
},
|
|
646
|
+
bind({ worktree }, handle) {
|
|
647
|
+
const childId = handle.childId
|
|
648
|
+
if (typeof childId !== 'string' || childId === '') return
|
|
649
|
+
if (worktrees.get(worktree.id)?.childId !== childId) worktrees.rebindChild(worktree.id, childId)
|
|
650
|
+
worktrees.bindChild?.(worktree.id, childId)
|
|
651
|
+
onWorktreeChild?.(worktree, handle, parent)
|
|
652
|
+
},
|
|
653
|
+
async finish({ worktree, write, started, batch }, itemIndex) {
|
|
654
|
+
if (stageTracking?.isDisposing() || (batch && !stageTracking.canFinishBatch(batch))) return
|
|
655
|
+
let audit
|
|
656
|
+
try {
|
|
657
|
+
if (!started) {
|
|
658
|
+
discardEmptyWorktree(worktrees, worktree, onCleanupFailed)
|
|
659
|
+
return
|
|
660
|
+
}
|
|
661
|
+
audit = settleDispatchWrite(write.baseline, auditGit)
|
|
662
|
+
worktrees.markReadyForReview(worktree.id, worktreeAuditSummary(audit))
|
|
663
|
+
const { id: worktreeId, branch, path } = worktreeDetails(worktree)
|
|
664
|
+
rows.push({ itemIndex, worktreeId, branch, path, audit })
|
|
665
|
+
onAudited?.({ childId: `${batchId}:item:${itemIndex}`, parentId: parent.id, audit, itemIndex, worktree })
|
|
666
|
+
} finally {
|
|
667
|
+
if (batch) await stageTracking.finishBatch(batch, audit)
|
|
668
|
+
else releaseWriteScope(leases, write.lease)
|
|
669
|
+
}
|
|
670
|
+
},
|
|
671
|
+
defer(pending, finish) {
|
|
672
|
+
void pending.finally(finish).catch((error) => onCleanupFailed?.(error))
|
|
673
|
+
},
|
|
674
|
+
},
|
|
675
|
+
}
|
|
511
676
|
}
|
|
512
677
|
|
|
513
|
-
|
|
678
|
+
function aggregateItemAudits(rows) {
|
|
679
|
+
const summary = { added: 0, modified: 0, deleted: 0, violations: 0, truncated: false }
|
|
680
|
+
const changedFiles = []
|
|
681
|
+
const violations = []
|
|
682
|
+
for (const { itemIndex, audit } of rows) {
|
|
683
|
+
for (const key of ['added', 'modified', 'deleted', 'violations']) summary[key] += audit.summary[key]
|
|
684
|
+
summary.truncated ||= audit.summary.truncated === true
|
|
685
|
+
changedFiles.push(...audit.changedFiles.map((entry) => ({ ...entry, itemIndex })))
|
|
686
|
+
violations.push(...audit.violations.map((entry) => ({ ...entry, path: `item ${itemIndex + 1}: ${entry.path}`, itemIndex })))
|
|
687
|
+
}
|
|
688
|
+
return {
|
|
689
|
+
passed: rows.every(({ audit }) => audit.passed), readOnly: false, isolationLevel: 'git-worktree',
|
|
690
|
+
isolationNote: '每个条目独立完成 Git 审计;具体证据见 details.itemAudits。',
|
|
691
|
+
changedFiles, violations, summary,
|
|
692
|
+
}
|
|
693
|
+
}
|
|
694
|
+
|
|
695
|
+
export function createOrchestrateTool({
|
|
696
|
+
defineTool, subagents, config, leases, onAudited, worktrees, onWorktreeChild, onCleanupFailed,
|
|
697
|
+
isWorktreeEnabled = () => true, getWorkspaceRoot,
|
|
698
|
+
captureGitBaseline: captureGit, auditGitBaseline: auditGit, probeGitRepo: probeRepo = probeGitRepo,
|
|
699
|
+
stageTracking,
|
|
700
|
+
}) {
|
|
514
701
|
// This description does not repeat `mainAgentRule`: only `delegate` opens with it.
|
|
515
702
|
// The plumbing still accepts the whitelist fields a shared factory passes down so a
|
|
516
703
|
// caller does not have to branch, but they are unused here.
|
|
@@ -519,7 +706,8 @@ export function createOrchestrateTool({ defineTool, subagents, config, leases })
|
|
|
519
706
|
const body =
|
|
520
707
|
'按 item 派发子代理:单 stage 即批量扇出;多 stage 时各 item 独立走完阶段,无全局屏障,每阶段自动附带指令、原始 item 与上阶段输出。' +
|
|
521
708
|
'声明 schema 的阶段输出校验过的 JSON,否则为文本;单 item 失败置为 null 并记入 errors。' +
|
|
522
|
-
'maxConcurrency
|
|
709
|
+
'maxConcurrency 限制并发数;非只读调用必填 writeScope。Git 写任务默认按 item 分配独立 Worktree,同 item 多 stage 复用一树,结算后保留,由 worktree_manage 评审、合回或丢弃。' +
|
|
710
|
+
'非 Git 自动降级:共享模式整批共享一个写租约,冲突时整批失败不排队;readOnly: true 不占租约,仅做逻辑写后审计,不是物理隔离。' +
|
|
523
711
|
'无关批次可并发调用;单任务请用 delegate。'
|
|
524
712
|
const descriptionOf = () => (enabled() ? ruleLead + body : body)
|
|
525
713
|
|
|
@@ -531,17 +719,7 @@ export function createOrchestrateTool({ defineTool, subagents, config, leases })
|
|
|
531
719
|
type: 'string',
|
|
532
720
|
description: '初始工作目录(相对路径基于当前目录);省略则继承。',
|
|
533
721
|
},
|
|
534
|
-
|
|
535
|
-
type: 'array',
|
|
536
|
-
required: true,
|
|
537
|
-
items: { type: 'string' },
|
|
538
|
-
// Required, with no default and no minItems — the same conventions as `delegate`:
|
|
539
|
-
// omitting the field is `write-scope-missing`, an empty array is invalid.
|
|
540
|
-
description:
|
|
541
|
-
'必填:允许写入的文件/目录清单(至少一项),整批共享一个写租约。' +
|
|
542
|
-
'派发前与在租作用域求交,冲突则整批失败并报 write-scope-conflict。' +
|
|
543
|
-
'相对路径基于 cwd;目录用 "/" 或 "/**";不推荐 "*"。仅声明,不扩大权限也不阻止越界写入。',
|
|
544
|
-
},
|
|
722
|
+
...dispatchWriteParameters({ batch: true }),
|
|
545
723
|
items: {
|
|
546
724
|
type: 'array',
|
|
547
725
|
required: true,
|
|
@@ -601,6 +779,8 @@ export function createOrchestrateTool({ defineTool, subagents, config, leases })
|
|
|
601
779
|
properties: {
|
|
602
780
|
kind: { type: 'string', const: ORCHESTRATION_KIND },
|
|
603
781
|
agentsStarted: { type: 'integer' },
|
|
782
|
+
audit: { type: 'object', additionalProperties: true },
|
|
783
|
+
details: { type: 'object', additionalProperties: true },
|
|
604
784
|
results: {
|
|
605
785
|
type: 'array',
|
|
606
786
|
items: {
|
|
@@ -637,7 +817,13 @@ export function createOrchestrateTool({ defineTool, subagents, config, leases })
|
|
|
637
817
|
type: 'text',
|
|
638
818
|
text:
|
|
639
819
|
`orchestration finished: ${value.results.filter((entry) => entry !== null).length}/${value.results.length} items, ` +
|
|
640
|
-
`${value.errors.length} errors, ${value.agentsStarted} workers started
|
|
820
|
+
`${value.errors.length} errors, ${value.agentsStarted} workers started` +
|
|
821
|
+
(value.audit?.passed === false ? `\n不得验收为通过。\n${auditNotice(value.audit)}` : '') +
|
|
822
|
+
(value.details?.worktrees?.length
|
|
823
|
+
? '\n请用 worktree_manage 逐项 inspect / merge / discard:\n' + value.details.worktrees.map((worktree) =>
|
|
824
|
+
`item ${worktree.itemIndex + 1}:${worktree.worktreeId}(${worktree.branch})${worktree.audit.passed ? '审计通过' : '审计失败'}`).join('\n')
|
|
825
|
+
: '') +
|
|
826
|
+
(value.details?.isolationFallback ? `\n已降级为共享工作区:${value.details.isolationFallback.message}` : ''),
|
|
641
827
|
},
|
|
642
828
|
],
|
|
643
829
|
},
|
|
@@ -646,9 +832,8 @@ export function createOrchestrateTool({ defineTool, subagents, config, leases })
|
|
|
646
832
|
if (!enabled()) throw new Error(disabledToolMessage(ORCHESTRATE_TOOL))
|
|
647
833
|
const parent = exec?.agent
|
|
648
834
|
if (!parent) throw new Error('orchestrate requires a calling agent (exec.agent was undefined)')
|
|
649
|
-
|
|
650
|
-
|
|
651
|
-
requireWriteScope(args, ORCHESTRATE_TOOL)
|
|
835
|
+
const isolation = validateDispatchIsolation(args)
|
|
836
|
+
const checked = validateDispatchWrite(args, ORCHESTRATE_TOOL)
|
|
652
837
|
// Parse first: bad input or schema must fail before any worker starts.
|
|
653
838
|
const plan = parseOrchestrateArgs(args)
|
|
654
839
|
const signal = exec.signal
|
|
@@ -661,32 +846,71 @@ export function createOrchestrateTool({ defineTool, subagents, config, leases })
|
|
|
661
846
|
const route = readRouteOverride(args, ORCHESTRATE_TOOL) ?? readRoute(config)
|
|
662
847
|
const maxDepth = subagents.resolveMaxDepth(undefined)
|
|
663
848
|
signal.throwIfAborted()
|
|
664
|
-
|
|
665
|
-
|
|
666
|
-
|
|
667
|
-
|
|
668
|
-
|
|
669
|
-
|
|
670
|
-
|
|
671
|
-
|
|
672
|
-
|
|
673
|
-
|
|
674
|
-
|
|
675
|
-
|
|
849
|
+
const childId = nextBatchId(parent)
|
|
850
|
+
let isolationFallback
|
|
851
|
+
if (!checked.readOnly && (isolation.mode === 'worktree' ||
|
|
852
|
+
(isolation.mode === 'auto' && worktrees && isWorktreeEnabled()))) {
|
|
853
|
+
const isolated = prepareItemIsolation({
|
|
854
|
+
isolation, worktrees, args, exec, parent, checked, leases, batchId: childId, probeRepo, getWorkspaceRoot,
|
|
855
|
+
captureGit, auditGit, onAudited, onWorktreeChild, onCleanupFailed, stageTracking,
|
|
856
|
+
})
|
|
857
|
+
if (isolated.itemIsolation) {
|
|
858
|
+
try {
|
|
859
|
+
const result = await runOrchestration({
|
|
860
|
+
plan, parent, route, maxDepth, subagents, signal, itemIsolation: isolated.itemIsolation, stageTracking,
|
|
861
|
+
})
|
|
862
|
+
const rows = isolated.rows.sort((left, right) => left.itemIndex - right.itemIndex)
|
|
863
|
+
const audit = rows.length === 0 ? undefined : aggregateItemAudits(rows)
|
|
864
|
+
return {
|
|
865
|
+
...result,
|
|
866
|
+
...(audit && { audit }),
|
|
867
|
+
details: {
|
|
868
|
+
worktrees: rows,
|
|
869
|
+
itemAudits: rows.map(({ itemIndex, worktreeId, audit }) => ({ itemIndex, worktreeId, audit })),
|
|
870
|
+
...(audit && { writeAudit: audit }),
|
|
871
|
+
},
|
|
872
|
+
}
|
|
873
|
+
} finally {
|
|
874
|
+
isolated.disposeUnused()
|
|
875
|
+
}
|
|
876
|
+
}
|
|
877
|
+
isolationFallback = isolated.isolationFallback
|
|
878
|
+
}
|
|
879
|
+
// Shared mode keeps the atomic batch lease and one snapshot audit.
|
|
880
|
+
const write = prepareDispatchWrite({ args, exec, parent, leases, childId, tool: ORCHESTRATE_TOOL, checked })
|
|
881
|
+
const sharedBatch = stageTracking ? newBatch(childId, parent, write) : undefined
|
|
882
|
+
let result
|
|
883
|
+
let audit
|
|
676
884
|
try {
|
|
677
|
-
|
|
885
|
+
if (sharedBatch) await stageTracking.beforeLaunch(write)
|
|
886
|
+
result = await runOrchestration({
|
|
678
887
|
plan,
|
|
679
888
|
parent,
|
|
680
889
|
route,
|
|
681
890
|
maxDepth,
|
|
682
891
|
subagents,
|
|
683
892
|
signal,
|
|
684
|
-
writeScope:
|
|
893
|
+
writeScope: write.lease?.scope,
|
|
894
|
+
baselineId: write.baseline?.baselineId,
|
|
895
|
+
stageTracking,
|
|
896
|
+
sharedBatch,
|
|
685
897
|
})
|
|
686
898
|
} finally {
|
|
687
|
-
|
|
688
|
-
|
|
689
|
-
|
|
899
|
+
if (!stageTracking?.isDisposing() && (!sharedBatch || stageTracking.canFinishBatch(sharedBatch))) {
|
|
900
|
+
try {
|
|
901
|
+
audit = settleDispatchWrite(write.baseline)
|
|
902
|
+
// On abort or another thrown error there is no result to attach evidence to.
|
|
903
|
+
if (audit !== undefined) onAudited?.({ childId, parentId: parent.id, audit, hasResult: result !== undefined })
|
|
904
|
+
} finally {
|
|
905
|
+
if (sharedBatch) await stageTracking.finishBatch(sharedBatch, audit)
|
|
906
|
+
else releaseWriteScope(leases, write.lease)
|
|
907
|
+
}
|
|
908
|
+
}
|
|
909
|
+
}
|
|
910
|
+
return {
|
|
911
|
+
...result,
|
|
912
|
+
...(audit && { audit }),
|
|
913
|
+
...(isolationFallback && { details: { isolationFallback } }),
|
|
690
914
|
}
|
|
691
915
|
},
|
|
692
916
|
})
|