@xiangyixie/dsh-superagent 0.14.2 → 0.14.4

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.
@@ -49,6 +49,15 @@ const HEARTBEAT_MS = 30 * 1000
49
49
  const PLANNER_POLL_MS = 250
50
50
  /** A run with no heartbeat for this long is treated as orphaned. */
51
51
  const ORPHAN_MS = 3 * HEARTBEAT_MS
52
+ /**
53
+ * How long a declared deliverable is re-checked after a `ENOENT` before the
54
+ * check calls it missing. A worker's write can reach its own shell a moment
55
+ * before another process sees it on disk; this window covers that flush race.
56
+ * It is bounded on purpose — a file that never appears is still missing.
57
+ */
58
+ const DELIVERABLE_GRACE_MS = 150
59
+ /** Gap between re-checks inside the deliverable grace window. */
60
+ const DELIVERABLE_RECHECK_MS = 50
52
61
  /** A child that ignores abort must not hold a cancel call open forever. */
53
62
  const DISPOSE_MS = 1500
54
63
  /** Waking the owning session must not hold a finished run open forever. */
@@ -1216,7 +1225,8 @@ function cascadeSkips(run, byKey) {
1216
1225
  .map(key => byKey.get(key))
1217
1226
  .find(dependency => dependency
1218
1227
  && (dependency.status === 'failed' || dependency.status === 'skipped'
1219
- || dependency.status === 'blocked' || dependency.status === 'unverified'))
1228
+ || dependency.status === 'blocked' || dependency.status === 'unverified'
1229
+ || dependency.status === 'cancelled'))
1220
1230
  if (!blocker) continue
1221
1231
  subtask.status = 'skipped'
1222
1232
  subtask.skipKind = 'upstream'
@@ -1226,7 +1236,9 @@ function cascadeSkips(run, byKey) {
1226
1236
  ? `not started because ${blocker.key} was blocked by a missing capability`
1227
1237
  : blocker.status === 'unverified'
1228
1238
  ? `not started because ${blocker.key}'s deliverable could not be verified`
1229
- : `not started because ${blocker.key} was skipped`
1239
+ : blocker.status === 'cancelled'
1240
+ ? `not started because ${blocker.key} was cancelled`
1241
+ : `not started because ${blocker.key} was skipped`
1230
1242
  subtask.waitingOn = []
1231
1243
  round = true
1232
1244
  changed = true
@@ -1374,15 +1386,68 @@ export function createOrchestrator(deps) {
1374
1386
  /** Cached managers, keyed by boundary; a test may inject one instead of spawning real git. */
1375
1387
  let workspaceManagerRef = workspace
1376
1388
  const workspaceManagers = new Map()
1389
+
1390
+ /** Resolved, without a trailing separator, and case-folded on Windows. */
1391
+ function comparablePath(value) {
1392
+ const resolved = path.resolve(value)
1393
+ const trimmed = resolved.replace(/[\\/]+$/, '') || resolved
1394
+ return process.platform === 'win32' ? trimmed.toLowerCase() : trimmed
1395
+ }
1396
+
1397
+ /** Path comparison that ignores case and a trailing separator on Windows. */
1398
+ function sameDirectory(left, right) {
1399
+ return comparablePath(left) === comparablePath(right)
1400
+ }
1401
+
1402
+ /**
1403
+ * Is `target` the directory `root`, or inside it?
1404
+ *
1405
+ * A declared path may arrive with either separator and, on Windows, in any
1406
+ * case. Comparing the resolved strings literally would reject a path that
1407
+ * names a file under the root, so both sides are compared the same way
1408
+ * `sameDirectory` compares directories.
1409
+ */
1410
+ function insideDirectory(root, target) {
1411
+ const base = comparablePath(root)
1412
+ const resolved = comparablePath(target)
1413
+ return resolved === base || resolved.startsWith(base + path.sep)
1414
+ }
1415
+
1416
+ /**
1417
+ * Where isolation is based.
1418
+ *
1419
+ * The default follows the session. The sandbox boundary, the declared
1420
+ * deliverables and the merge target are all the directory the user is working
1421
+ * in, so basing worktrees anywhere else makes a merge land where nobody looks
1422
+ * — or fail outright on a checkout with unrelated local edits. A profile's
1423
+ * `workspaceRoot` is only honoured when it names that same directory;
1424
+ * `workspaceBase: 'config'` restores the old unconditional behaviour.
1425
+ *
1426
+ * @param {string} boundary - the session's cwd, absolute.
1427
+ * @returns {{ baseDir: string, note: string | null }} directory plus a visible mismatch note.
1428
+ */
1429
+ function workspaceBaseFor(boundary) {
1430
+ const configured = typeof config.workspaceRoot === 'string' ? config.workspaceRoot.trim() : ''
1431
+ if (!configured) return { baseDir: boundary, note: null }
1432
+ const resolved = path.resolve(configured)
1433
+ if (config.workspaceBase === 'config') return { baseDir: resolved, note: null }
1434
+ if (sameDirectory(resolved, boundary)) return { baseDir: resolved, note: null }
1435
+ return {
1436
+ baseDir: boundary,
1437
+ note: `workspaceRoot ${resolved} is not this session's directory (${boundary}), so isolation `
1438
+ + "used the session directory; set workspaceBase: 'config' to keep the configured one",
1439
+ }
1440
+ }
1441
+
1377
1442
  function workspaceManager(boundary) {
1378
1443
  if (workspaceManagerRef) return workspaceManagerRef
1379
1444
  const key = boundary ?? process.cwd()
1380
1445
  if (!workspaceManagers.has(key)) {
1381
- const configured = typeof config.workspaceRoot === 'string' ? config.workspaceRoot.trim() : ''
1446
+ const { baseDir } = workspaceBaseFor(key)
1382
1447
  // A checkout outside the boundary gets every write denied, so the pool
1383
- // is anchored there even when `workspaceRoot` points somewhere else.
1448
+ // is anchored there even when the base resolves somewhere else.
1384
1449
  workspaceManagers.set(key, createWorkspaceManager({
1385
- baseDir: configured ? path.resolve(configured) : key,
1450
+ baseDir,
1386
1451
  boundary: key,
1387
1452
  log,
1388
1453
  sleep,
@@ -1406,27 +1471,35 @@ export function createOrchestrator(deps) {
1406
1471
  if (config.workspaceIsolation !== true) return null
1407
1472
  if (run.workspace) return run.workspace.mode === 'git-worktree' ? run.workspace : null
1408
1473
  let verdict
1474
+ const boundary = sessionCwd(parent)
1409
1475
  try {
1410
- verdict = await workspaceManager(sessionCwd(parent)).probe()
1476
+ verdict = await workspaceManager(boundary).probe()
1411
1477
  } catch (error) {
1412
1478
  verdict = { ok: false, base: null, reason: error?.message ?? String(error) }
1413
1479
  }
1414
1480
  if (!verdict.ok) {
1415
1481
  // Requested but impossible is not a failure of the work: the run goes on
1416
- // in the shared directory, and both status and the report say so.
1417
- run.workspace = { mode: 'unavailable', base: verdict.base ?? null, reason: verdict.reason, merges: [] }
1482
+ // in the shared directory, and both status and the report say so. `base`
1483
+ // is that shared directory — the session's own — so declared deliverables
1484
+ // are still checked where the workers actually write, instead of a stale
1485
+ // `workspaceRoot` from another project.
1486
+ run.workspace = { mode: 'unavailable', base: boundary, reason: verdict.reason, merges: [] }
1418
1487
  log(`run ${run.id}: workspace isolation unavailable — ${verdict.reason}`)
1419
1488
  await save(run)
1420
1489
  return null
1421
1490
  }
1491
+ const { note } = workspaceBaseFor(boundary)
1492
+ if (note) log(`run ${run.id}: ${note}`)
1422
1493
  run.workspace = {
1423
1494
  mode: 'git-worktree',
1424
1495
  base: verdict.base,
1425
1496
  root: verdict.root ?? null,
1426
- boundary: sessionCwd(parent),
1497
+ boundary,
1427
1498
  reason: null,
1428
1499
  merges: [],
1429
1500
  conflicts: 0,
1501
+ // Persisted so status can repeat the warning long after this log line.
1502
+ ...(note ? { baseNote: note } : {}),
1430
1503
  }
1431
1504
  await save(run)
1432
1505
  return run.workspace
@@ -1498,10 +1571,49 @@ export function createOrchestrator(deps) {
1498
1571
 
1499
1572
  /**
1500
1573
  * Directory against which a subtask's declared deliverables are resolved:
1501
- * its own checkout when isolated, the shared checkout otherwise.
1574
+ * its own checkout when isolated, otherwise the directory the workers were
1575
+ * actually told to work in.
1576
+ *
1577
+ * A goal-mode run carries that directory in `goalMode.cwd` — the same base
1578
+ * its machine checks and workspace fingerprints use — so the deliverable
1579
+ * check must honour it too. Falling straight through to this process's `cwd`
1580
+ * would read the host's launch directory instead, and a file the worker did
1581
+ * write would be reported as missing.
1502
1582
  */
1503
1583
  function deliverableRoot(run, subtask) {
1504
- return subtask.workspace?.dir ?? run.workspace?.base ?? config.workspaceRoot ?? cwd
1584
+ return subtask.workspace?.dir
1585
+ ?? run.workspace?.base
1586
+ ?? run.goalMode?.cwd
1587
+ ?? config.workspaceRoot
1588
+ ?? cwd
1589
+ }
1590
+
1591
+ /**
1592
+ * Stat a declared deliverable, re-reading it briefly before believing ENOENT.
1593
+ *
1594
+ * A file system can expose a write to the shell that made it slightly before
1595
+ * another process sees it, so a check that runs the instant a worker returns
1596
+ * can race the flush. The window is short and bounded: when the file never
1597
+ * appears the result is still ENOENT, which the caller reports as missing.
1598
+ *
1599
+ * @param {string} resolved - absolute path to check.
1600
+ * @returns {Promise<{ stats: object | null, error: NodeJS.ErrnoException | null }>}
1601
+ */
1602
+ async function statDeliverable(resolved) {
1603
+ const deadline = now() + DELIVERABLE_GRACE_MS
1604
+ let error = null
1605
+ for (let attempt = 0; attempt < 3; attempt++) {
1606
+ try {
1607
+ return { stats: await fsp.stat(resolved), error: null }
1608
+ } catch (caught) {
1609
+ error = caught
1610
+ const missing = caught?.code === 'ENOENT' || caught?.code === 'ENOTDIR'
1611
+ const remaining = deadline - now()
1612
+ if (!missing || remaining <= 0 || attempt === 2) break
1613
+ await sleep(Math.min(DELIVERABLE_RECHECK_MS, remaining))
1614
+ }
1615
+ }
1616
+ return { stats: null, error }
1505
1617
  }
1506
1618
 
1507
1619
  /**
@@ -1528,8 +1640,7 @@ export function createOrchestrator(deps) {
1528
1640
  for (const entry of declared) {
1529
1641
  const resolved = path.resolve(root, entry.path)
1530
1642
  // A plan cannot widen its own reach by naming ../../ or an absolute path.
1531
- const inside = resolved === root || resolved.startsWith(root + path.sep)
1532
- if (!inside) {
1643
+ if (!insideDirectory(root, resolved)) {
1533
1644
  items.push({
1534
1645
  ...entry,
1535
1646
  status: 'failed',
@@ -1537,10 +1648,10 @@ export function createOrchestrator(deps) {
1537
1648
  })
1538
1649
  continue
1539
1650
  }
1540
- let stats
1541
- try {
1542
- stats = await fsp.stat(resolved)
1543
- } catch (error) {
1651
+ const probed = await statDeliverable(resolved)
1652
+ const stats = probed.stats
1653
+ if (!stats) {
1654
+ const error = probed.error
1544
1655
  const missing = error?.code === 'ENOENT' || error?.code === 'ENOTDIR'
1545
1656
  if (!missing) {
1546
1657
  items.push({
@@ -1639,9 +1750,9 @@ export function createOrchestrator(deps) {
1639
1750
  if (run.workspace?.mode !== 'git-worktree') return null
1640
1751
  const base = run.workspace.base ? path.resolve(run.workspace.base) : null
1641
1752
  const here = path.resolve(deliverableRoot(run, subtask))
1642
- if (!base || base === here) return null
1753
+ if (!base || sameDirectory(base, here)) return null
1643
1754
  const candidate = path.resolve(base, entry.path)
1644
- if (candidate !== base && !candidate.startsWith(base + path.sep)) return null
1755
+ if (!insideDirectory(base, candidate)) return null
1645
1756
  try {
1646
1757
  const stats = await fsp.stat(candidate)
1647
1758
  return stats.isFile() ? candidate : null
@@ -1710,6 +1821,51 @@ export function createOrchestrator(deps) {
1710
1821
  await save(run)
1711
1822
  }
1712
1823
 
1824
+ /**
1825
+ * Merge outcomes whose files never reached the main checkout.
1826
+ *
1827
+ * A skipped merge (dirty checkout) and a conflict both leave the work only
1828
+ * inside the worker's branch. If such a run reported `completed`, the user
1829
+ * would open the target directory and find nothing — so status has to drop
1830
+ * and the branch has to be named somewhere they will read it.
1831
+ *
1832
+ * @param {object} run - live run record.
1833
+ * @returns {Array<object>} `run.workspace.merges` rows that did not land.
1834
+ */
1835
+ function unmergedOutcomes(run) {
1836
+ if (run.workspace?.mode !== 'git-worktree') return []
1837
+ return (run.workspace.merges ?? [])
1838
+ .filter(merge => merge.status !== 'merged' && merge.status !== 'no-changes')
1839
+ }
1840
+
1841
+ /**
1842
+ * The attention item that explains an unmerged run and how to finish it.
1843
+ *
1844
+ * @param {object} run - live run record.
1845
+ * @param {Array<object>} outcomes - rows from `unmergedOutcomes`.
1846
+ * @returns {{ question: string, options: string[], reason: string }} attention payload.
1847
+ */
1848
+ function mergeAttention(run, outcomes) {
1849
+ const base = run.workspace?.base ?? 'the main checkout'
1850
+ const branches = outcomes.map(outcome => outcome.branch).filter(Boolean)
1851
+ const detail = outcomes.map(outcome => {
1852
+ const kept = outcome.dir ? ` kept at ${outcome.dir}` : ''
1853
+ const why = outcome.detail ? ` — ${outcome.detail}` : ''
1854
+ return `[${outcome.index}] ${outcome.branch ?? 'unknown branch'} (${outcome.status})${kept}${why}`
1855
+ }).join('; ')
1856
+ const commands = branches.length > 0
1857
+ ? `git -C "${base}" stash push -u -m superagent-before-merge, then `
1858
+ + branches.map(branch => `git -C "${base}" merge --no-ff ${branch}`).join(', then ')
1859
+ : `commit or stash the changes in ${base} and resume the run`
1860
+ return {
1861
+ question: `${outcomes.length} worker branch(es) were never merged into ${base}, so their files are `
1862
+ + `not in the target directory. ${detail}. To finish by hand: ${commands}. `
1863
+ + 'The branches and worktrees are kept, so nothing is lost.',
1864
+ options: ['merge them now', 'keep the branches for review'],
1865
+ reason: 'the main checkout had uncommitted changes or the merge conflicted, so merging was refused',
1866
+ }
1867
+ }
1868
+
1713
1869
  function save(run) {
1714
1870
  run.updatedAt = new Date(now()).toISOString()
1715
1871
  // The guard is process-wide and owned by the caller; copy its counters onto
@@ -1900,6 +2056,8 @@ export function createOrchestrator(deps) {
1900
2056
  await settle(run, {
1901
2057
  controller: new AbortController(),
1902
2058
  activations: new Set(),
2059
+ subtaskAborts: new Map(),
2060
+ cancelledSubtasks: new Set(),
1903
2061
  waiters: 0,
1904
2062
  run,
1905
2063
  promise: null,
@@ -2928,7 +3086,14 @@ export function createOrchestrator(deps) {
2928
3086
  const blocked = budgetStop(run)
2929
3087
  if (blocked) {
2930
3088
  if (!rt.abortCause) rt.abortCause = 'budget'
2931
- if (!run.error) run.error = blocked
3089
+ // A budget stop is a notice, not a failure: the work that finished still
3090
+ // counts, so it is recorded beside the run instead of in `error`.
3091
+ run.budgetStop = {
3092
+ detail: blocked,
3093
+ at: new Date(now()).toISOString(),
3094
+ calls: spentCalls(run),
3095
+ tokens: spentTokens(run),
3096
+ }
2932
3097
  if (!rt.controller.signal.aborted) rt.controller.abort(new Error(blocked))
2933
3098
  throw new Error(`budget exceeded: ${blocked}; raise maxModelCallsPerRun or maxTokensPerRun if this was intended`)
2934
3099
  }
@@ -3327,7 +3492,9 @@ export function createOrchestrator(deps) {
3327
3492
  record.outcome = error?.code ?? 'error'
3328
3493
  record.error = lastReason
3329
3494
  }
3330
- log(`planner attempt ${round} failed: ${lastReason}`)
3495
+ // A host-side failure is otherwise only a message in the run file; the
3496
+ // stack keeps the failing host frame visible in the plugin log.
3497
+ log(`planner attempt ${round} failed: ${lastReason}${error?.stack ? `\n${error.stack}` : ''}`)
3331
3498
  if (error?.code === 'subagent-unavailable') {
3332
3499
  markHostGone(rt, error)
3333
3500
  break
@@ -3348,7 +3515,25 @@ export function createOrchestrator(deps) {
3348
3515
  }
3349
3516
 
3350
3517
  async function runSubtask(run, subtask, parent, rt, { model = null } = {}) {
3351
- const signal = rt.controller.signal
3518
+ const key = subtask.key ?? `w${subtask.index}`
3519
+ if (rt.cancelledSubtasks?.has(key)) {
3520
+ // A cancelled subtask stays cancelled: a retry pass, a self-heal round,
3521
+ // or the next graph tick must not quietly start it again.
3522
+ subtask.status = 'cancelled'
3523
+ subtask.finishedAt = subtask.finishedAt ?? new Date(now()).toISOString()
3524
+ subtask.cancelledAt = subtask.cancelledAt ?? subtask.finishedAt
3525
+ return
3526
+ }
3527
+ // The board can stop one subtask without stopping the run. Its own
3528
+ // controller is combined with the run's, so both reasons still abort this
3529
+ // child and only this child.
3530
+ const own = new AbortController()
3531
+ rt.subtaskAborts = rt.subtaskAborts ?? new Map()
3532
+ rt.subtaskAborts.set(key, own)
3533
+ const runSignal = rt.controller.signal
3534
+ const signal = typeof AbortSignal.any === 'function'
3535
+ ? AbortSignal.any([runSignal, own.signal])
3536
+ : runSignal
3352
3537
  for (let attempt = subtask.attempts + 1; attempt <= run.limits.attempts; attempt++) {
3353
3538
  if (signal.aborted) break
3354
3539
  subtask.status = 'running'
@@ -3385,6 +3570,7 @@ export function createOrchestrator(deps) {
3385
3570
  await save(run)
3386
3571
 
3387
3572
  const result = await abortable(handle.result, signal)
3573
+ if (rt.cancelledSubtasks?.has(key) || own.signal.aborted) break
3388
3574
  const raw = textOf(result.output)
3389
3575
  subtask.stopReason = result.stopReason
3390
3576
  if (result.stopReason === 'completed' && raw) {
@@ -3495,7 +3681,15 @@ export function createOrchestrator(deps) {
3495
3681
  }
3496
3682
 
3497
3683
  if (subtask.status !== 'completed') {
3498
- if (signal.aborted) {
3684
+ if (rt.cancelledSubtasks?.has(key) || own.signal.aborted) {
3685
+ // The person stopped this subtask on purpose. It is neither a failure
3686
+ // nor resumable work: `cancelled` says exactly what happened.
3687
+ subtask.status = 'cancelled'
3688
+ subtask.error = null
3689
+ subtask.stopReason = 'cancelled'
3690
+ subtask.cancelledAt = new Date(now()).toISOString()
3691
+ subtask.finishedAt = subtask.cancelledAt
3692
+ } else if (signal.aborted) {
3499
3693
  // Cancelled or out of time: the subtask did not fail on its own terms,
3500
3694
  // so leave it resumable instead of recording a failure.
3501
3695
  subtask.status = 'pending'
@@ -3527,6 +3721,13 @@ export function createOrchestrator(deps) {
3527
3721
  async function runGraph(run, parent, rt, { model = null } = {}) {
3528
3722
  const signal = rt.controller.signal
3529
3723
  const byKey = new Map(run.subtasks.map(subtask => [subtask.key, subtask]))
3724
+ // Two workers that declare the same output file would overwrite each other
3725
+ // in a shared checkout, so only one of them is ever in flight. Parallelism
3726
+ // is only worth what the plan keeps disjoint: a higher cap must not turn a
3727
+ // planner mistake into a lost file.
3728
+ const declaredWrites = subtask => new Set((subtask.deliverables ?? [])
3729
+ .map(entry => path.posix.normalize(String(entry?.path ?? '').replace(/\\/g, '/').trim()).toLowerCase())
3730
+ .filter(Boolean))
3530
3731
  let revived = false
3531
3732
  for (const subtask of run.subtasks) {
3532
3733
  if (subtask.status === 'skipped' && subtask.skipKind === 'upstream') {
@@ -3563,6 +3764,22 @@ export function createOrchestrator(deps) {
3563
3764
  subtask.waitingOn = []
3564
3765
  dirty = true
3565
3766
  }
3767
+ const own = declaredWrites(subtask)
3768
+ const clash = own.size === 0 ? null : [...inFlight.keys()].find(key => {
3769
+ const other = declaredWrites(byKey.get(key))
3770
+ return [...own].some(file => other.has(file))
3771
+ })
3772
+ if (clash) {
3773
+ // The file is already being written by that worker, so this one waits
3774
+ // for it instead of racing it. The plan's dependency edges stay as
3775
+ // written; the wait is repeated until the clash clears.
3776
+ if (subtask.status !== 'waiting' || subtask.waitingOn.join() !== clash) {
3777
+ subtask.status = 'waiting'
3778
+ subtask.waitingOn = [clash]
3779
+ dirty = true
3780
+ }
3781
+ continue
3782
+ }
3566
3783
  if (inFlight.size >= run.limits.maxParallel) break
3567
3784
  const task = runSubtask(run, subtask, parent, rt, { model })
3568
3785
  .catch(error => log(`subtask ${subtask.index} graph runner threw: ${error?.message ?? error}`))
@@ -3639,6 +3856,15 @@ export function createOrchestrator(deps) {
3639
3856
  // limit or stalling leaves the work partial even when every subtask of the
3640
3857
  // last round finished: the goal, not the round, is what was started.
3641
3858
  if (run.goalMode) return run.goalMode.achieved ? 'completed' : (completed > 0 ? 'partial' : 'failed')
3859
+ // Everything that did not finish was either stopped on purpose or waiting
3860
+ // on something that was. Calling that "failed" would blame the person who
3861
+ // pressed stop, so the run reports the same word the subtask does.
3862
+ const cancelled = subtasks.filter(subtask => subtask.status === 'cancelled').length
3863
+ if (completed === 0 && cancelled > 0) {
3864
+ return subtasks.every(subtask => subtask.status === 'cancelled' || subtask.status === 'skipped')
3865
+ ? 'cancelled'
3866
+ : 'failed'
3867
+ }
3642
3868
  if (completed === 0) return 'failed'
3643
3869
  if (rt.abortCause === 'deadline') {
3644
3870
  return completed === subtasks.length ? 'completed' : 'partial'
@@ -3805,6 +4031,19 @@ export function createOrchestrator(deps) {
3805
4031
  if (guardSection && typeof run.report === 'string' && run.report) {
3806
4032
  run.report = `${run.report.trimEnd()}\n\n${guardSection}`
3807
4033
  }
4034
+ // Work that never left its branch is not delivered. Reporting "completed"
4035
+ // while the target directory stays empty is the one outcome a user cannot
4036
+ // check their way out of, so the run drops to partial and the branch, the
4037
+ // reason and the manual merge land in the attention inbox.
4038
+ const unmerged = unmergedOutcomes(run)
4039
+ if (nextStatus === 'completed' && unmerged.length > 0) {
4040
+ nextStatus = 'partial'
4041
+ const note = `${unmerged.length} worker branch(es) were not merged into ${run.workspace?.base ?? 'the main checkout'}; `
4042
+ + 'the files exist only in the kept worktrees'
4043
+ run.error = run.error || note
4044
+ log(`run ${run.id}: ${note}; recorded as partial`)
4045
+ recordAttention(run, 'workspace-merge', mergeAttention(run, unmerged))
4046
+ }
3808
4047
  // Stripping an attention-only or notebook-only reply can leave nothing
3809
4048
  // behind. A run that "completed" with no artifact is not a completion:
3810
4049
  // keep the evidence and downgrade it so a schedule does not report success
@@ -3823,11 +4062,14 @@ export function createOrchestrator(deps) {
3823
4062
  error = 'cancelled by superagent_cancel'
3824
4063
  } else if (rt.abortCause === 'host-gone') {
3825
4064
  error = 'the host shut down while this run was active; run superagent_resume in a new host to finish it'
3826
- } else if (nextStatus === 'failed' && !error) {
4065
+ } else if (nextStatus === 'failed' && !error && !run.budgetStop?.detail) {
3827
4066
  error = run.subtasks.map(subtask => subtask.error ?? subtask.skippedReason).filter(Boolean).slice(0, 3).join('; ')
3828
4067
  || 'no subtask completed'
3829
4068
  }
3830
4069
  if (rt.abortCause === 'deadline' && !error) error = 'deadline exceeded'
4070
+ // A budget stop only belongs in `error` when it is the reason the run did
4071
+ // not finish: a completed run reports it as a notice and keeps `error` null.
4072
+ if (nextStatus !== 'completed' && !error && run.budgetStop?.detail) error = run.budgetStop.detail
3831
4073
 
3832
4074
  let outcome = null
3833
4075
  if (TERMINAL_STATUSES.has(nextStatus)) {
@@ -4621,6 +4863,10 @@ export function createOrchestrator(deps) {
4621
4863
  const rt = {
4622
4864
  controller: new AbortController(),
4623
4865
  activations: new Set(),
4866
+ // Per-subtask stop buttons: a board cancel aborts only its own child,
4867
+ // while `cancelledSubtasks` stops a retry from starting it again.
4868
+ subtaskAborts: new Map(),
4869
+ cancelledSubtasks: new Set(),
4624
4870
  waiters: 0,
4625
4871
  run,
4626
4872
  promise: null,
@@ -4913,7 +5159,7 @@ export function createOrchestrator(deps) {
4913
5159
  * `reopen` lets `superagent_answer` continue a `completed` run: its subtasks
4914
5160
  * stay done and only the aggregation runs again, now with the answer.
4915
5161
  */
4916
- async function resumeLocked(runId, parent, clientTimeZone, { reopen = false, approvePolicy = false } = {}) {
5162
+ async function resumeLocked(runId, parent, clientTimeZone, { reopen = false, approvePolicy = false, only = null } = {}) {
4917
5163
  const id = String(runId ?? '').trim()
4918
5164
  if (!parent || typeof parent !== 'object') throw new Error('superagent requires a live parent agent')
4919
5165
  {
@@ -5012,8 +5258,13 @@ export function createOrchestrator(deps) {
5012
5258
  failed: failedBefore,
5013
5259
  }
5014
5260
 
5261
+ // `only` restricts a resume to named subtasks. The board uses it to
5262
+ // rerun one subtask without restarting unrelated failed work; an empty
5263
+ // list means "rerun none" and is how an accepted review re-aggregates.
5264
+ const onlyKeys = Array.isArray(only) ? new Set(only.map(String)) : null
5015
5265
  for (const subtask of run.subtasks ?? []) {
5016
5266
  if (subtask.status === 'completed') continue
5267
+ if (onlyKeys && !onlyKeys.has(String(subtask.key))) continue
5017
5268
  // A dependency on a subtask the plan never contained cannot be fixed
5018
5269
  // by resuming: nothing would ever clear it.
5019
5270
  if (subtask.skipKind === 'missing') continue
@@ -5292,6 +5543,225 @@ export function createOrchestrator(deps) {
5292
5543
  throw new Error(`no question ${wanted} on run ${run.id}; ${describeOpen()}.`)
5293
5544
  }
5294
5545
 
5546
+ /** Resolve one subtask by its plan key (`w2`) or by its 1-based index. */
5547
+ function findSubtask(run, target) {
5548
+ const wanted = String(target ?? '').trim()
5549
+ if (!wanted) throw new Error('subtask is required; pass its key (w2) or its 1-based index')
5550
+ const byKey = (run.subtasks ?? []).find(subtask => subtask.key === wanted)
5551
+ if (byKey) return byKey
5552
+ const asIndex = Number(wanted)
5553
+ if (Number.isInteger(asIndex) && asIndex > 0) {
5554
+ const byIndex = (run.subtasks ?? []).find(subtask => subtask.index === asIndex)
5555
+ if (byIndex) return byIndex
5556
+ }
5557
+ const known = (run.subtasks ?? []).map(subtask => subtask.key).join(', ')
5558
+ throw new Error(`no subtask ${wanted} on run ${run.id}; it has ${known || '(none)'}`)
5559
+ }
5560
+
5561
+ /**
5562
+ * Stop one subtask while the rest of the run keeps going.
5563
+ *
5564
+ * This is deliberately narrower than `cancel`: the run's own controller is
5565
+ * untouched, so other workers, the planner's remaining graph, and the final
5566
+ * report still run. Dependents of the stopped subtask are skipped by the
5567
+ * normal cascade, with the reason kept on each one.
5568
+ *
5569
+ * @param {string} runId - run identity.
5570
+ * @param {string} target - subtask key or 1-based index.
5571
+ * @returns {Promise<object>} the updated run.
5572
+ */
5573
+ async function cancelSubtask(runId, target) {
5574
+ const id = String(runId ?? '').trim()
5575
+ if (!id) throw new Error('run_id is required')
5576
+ const rt = runtime.get(id)
5577
+ if (!rt || !ACTIVE_STATUSES.has(rt.run.status)) {
5578
+ const run = await loadRun(id)
5579
+ throw new Error(
5580
+ `run ${id} is ${run.status}, so there is no running subtask to stop; `
5581
+ + 'use rerun on the board if that work should run again',
5582
+ )
5583
+ }
5584
+ const subtask = findSubtask(rt.run, target)
5585
+ if (subtask.status === 'completed') {
5586
+ throw new Error(`subtask ${subtask.key} already completed; rerun it on the board if it needs another pass`)
5587
+ }
5588
+ if (subtask.status === 'cancelled') return rt.run
5589
+ const at = new Date(now()).toISOString()
5590
+ rt.cancelledSubtasks.add(subtask.key)
5591
+ subtask.status = 'cancelled'
5592
+ subtask.error = null
5593
+ subtask.stopReason = 'cancelled'
5594
+ subtask.cancelledAt = at
5595
+ subtask.finishedAt = at
5596
+ subtask.cancelledBy = 'board'
5597
+ subtask.waitingOn = []
5598
+ const own = rt.subtaskAborts?.get(subtask.key)
5599
+ own?.abort(new Error('subtask cancelled from the board'))
5600
+ for (const handle of [...rt.activations]) {
5601
+ if (subtask.childId && handle.childId === subtask.childId) await disposeQuietly(handle)
5602
+ }
5603
+ await save(rt.run)
5604
+ await auditRecord({
5605
+ runId: id,
5606
+ subtaskId: `subtask-${subtask.index}`,
5607
+ actor: 'session',
5608
+ kind: 'subtask.cancel',
5609
+ action: 'board_cancel_subtask',
5610
+ target: subtask.title,
5611
+ result: 'cancelled',
5612
+ })
5613
+ return rt.run
5614
+ }
5615
+
5616
+ /**
5617
+ * Put one finished or skipped subtask back to `pending` and run only it.
5618
+ *
5619
+ * Completed siblings are not touched, so this is not a run restart. A
5620
+ * subtask that was skipped because this one failed is revived too, because
5621
+ * its dependency is about to run again; unrelated failures are left alone.
5622
+ *
5623
+ * @param {string} runId - run identity.
5624
+ * @param {string} target - subtask key or 1-based index.
5625
+ * @param {object} parent - live agent that owns the run.
5626
+ * @param {string} [clientTimeZone] - forwarded to the resume.
5627
+ * @returns {Promise<object>} the queued run.
5628
+ */
5629
+ async function rerunSubtask(runId, target, parent, clientTimeZone) {
5630
+ const id = String(runId ?? '').trim()
5631
+ if (!id) throw new Error('run_id is required')
5632
+ return serialize(async () => {
5633
+ if (runtime.has(id)) {
5634
+ throw new Error(`run ${id} is still active; wait for it to finish or stop the subtask first`)
5635
+ }
5636
+ const run = await loadRun(id)
5637
+ assertResumeOwner(run, parent)
5638
+ const subtask = findSubtask(run, target)
5639
+ if (subtask.status === 'running' || subtask.status === 'pending' || subtask.status === 'waiting') {
5640
+ throw new Error(`subtask ${subtask.key} is already waiting to run; resume the run instead`)
5641
+ }
5642
+ const keys = new Set([subtask.key])
5643
+ // A skip caused by this dependency is not a verdict on that subtask:
5644
+ // revive it so the rerun can actually unblock it.
5645
+ for (const candidate of run.subtasks ?? []) {
5646
+ if (candidate.status === 'skipped' && candidate.skipKind === 'upstream'
5647
+ && (candidate.dependsOn ?? []).some(dep => dep === subtask.key || keys.has(dep))) {
5648
+ keys.add(candidate.key)
5649
+ candidate.status = 'pending'
5650
+ candidate.skipKind = null
5651
+ candidate.skippedReason = null
5652
+ candidate.waitingOn = []
5653
+ }
5654
+ }
5655
+ subtask.status = 'pending'
5656
+ subtask.attempts = 0
5657
+ subtask.error = null
5658
+ subtask.stopReason = null
5659
+ subtask.result = null
5660
+ subtask.usage = null
5661
+ subtask.childId = null
5662
+ subtask.startedAt = null
5663
+ subtask.finishedAt = null
5664
+ subtask.cancelledAt = null
5665
+ subtask.cancelledBy = null
5666
+ subtask.waitingOn = []
5667
+ subtask.skipKind = null
5668
+ subtask.skippedReason = null
5669
+ subtask.blockKind = null
5670
+ subtask.blockedReason = null
5671
+ subtask.unverifiedReason = null
5672
+ subtask.deliverableCheck = null
5673
+ subtask.deliverables = []
5674
+ await save(run)
5675
+ const resumed = await resumeLocked(id, parent, clientTimeZone, {
5676
+ reopen: true,
5677
+ only: [...keys],
5678
+ })
5679
+ await auditRecord({
5680
+ runId: id,
5681
+ subtaskId: `subtask-${subtask.index}`,
5682
+ actor: `session:${parent?.id ?? 'unknown'}`,
5683
+ kind: 'subtask.rerun',
5684
+ action: 'board_rerun_subtask',
5685
+ target: subtask.title,
5686
+ result: 'queued',
5687
+ })
5688
+ return resumed
5689
+ })
5690
+ }
5691
+
5692
+ /**
5693
+ * Accept or reject an `unverified` deliverable from the board.
5694
+ *
5695
+ * An unverified subtask is one the session could not judge on its own; a
5696
+ * person saying "I checked it" is the missing capability. Accepting reopens
5697
+ * the run so the report includes it, and only the report runs again.
5698
+ *
5699
+ * @param {string} runId - run identity.
5700
+ * @param {string} target - subtask key or 1-based index.
5701
+ * @param {'accept' | 'reject'} verdict - the person's decision.
5702
+ * @param {object} parent - live agent that owns the run.
5703
+ * @param {string} [clientTimeZone] - forwarded to the resume.
5704
+ * @param {string} [note] - optional reason kept on the audit line.
5705
+ * @returns {Promise<object>} the run or a note when the review was only recorded.
5706
+ */
5707
+ async function reviewSubtask(runId, target, verdict, parent, clientTimeZone, note = null) {
5708
+ const id = String(runId ?? '').trim()
5709
+ if (!id) throw new Error('run_id is required')
5710
+ if (verdict !== 'accept' && verdict !== 'reject') {
5711
+ throw new Error('verdict must be accept or reject')
5712
+ }
5713
+ return serialize(async () => {
5714
+ if (runtime.has(id)) {
5715
+ throw new Error(`run ${id} is still active; wait for it to finish before reviewing its deliverables`)
5716
+ }
5717
+ const run = await loadRun(id)
5718
+ assertResumeOwner(run, parent)
5719
+ const subtask = findSubtask(run, target)
5720
+ if (subtask.status !== 'unverified') {
5721
+ throw new Error(`subtask ${subtask.key} is ${subtask.status}, not waiting for a review`)
5722
+ }
5723
+ const at = new Date(now()).toISOString()
5724
+ subtask.reviewedAt = at
5725
+ subtask.reviewedBy = `session:${parent?.id ?? 'unknown'}`
5726
+ subtask.reviewNote = typeof note === 'string' && note.trim() ? note.trim().slice(0, 500) : null
5727
+ if (verdict === 'accept') {
5728
+ subtask.status = 'completed'
5729
+ subtask.result = subtask.result ?? '(deliverable accepted by a person)'
5730
+ subtask.error = null
5731
+ subtask.unverifiedReason = null
5732
+ subtask.finishedAt = at
5733
+ await save(run)
5734
+ const resumed = await resumeLocked(id, parent, clientTimeZone, { reopen: true, only: [] })
5735
+ await auditRecord({
5736
+ runId: id,
5737
+ subtaskId: `subtask-${subtask.index}`,
5738
+ actor: `session:${parent?.id ?? 'unknown'}`,
5739
+ kind: 'subtask.review',
5740
+ action: 'board_accept_subtask',
5741
+ target: subtask.title,
5742
+ result: 'completed',
5743
+ meta: { note: subtask.reviewNote },
5744
+ })
5745
+ return resumed
5746
+ }
5747
+ subtask.status = 'failed'
5748
+ subtask.error = `验收未通过${subtask.reviewNote ? `:${subtask.reviewNote}` : ''}`
5749
+ subtask.finishedAt = at
5750
+ await save(run)
5751
+ await auditRecord({
5752
+ runId: id,
5753
+ subtaskId: `subtask-${subtask.index}`,
5754
+ actor: `session:${parent?.id ?? 'unknown'}`,
5755
+ kind: 'subtask.review',
5756
+ action: 'board_reject_subtask',
5757
+ target: subtask.title,
5758
+ result: 'failed',
5759
+ meta: { note: subtask.reviewNote },
5760
+ })
5761
+ return run
5762
+ })
5763
+ }
5764
+
5295
5765
  async function cancel(runId) {
5296
5766
  // A run that never got a slot has no owner process to ask: remove it from
5297
5767
  // the line here, so no timer can start it afterwards.
@@ -5466,6 +5936,9 @@ export function createOrchestrator(deps) {
5466
5936
  start,
5467
5937
  resume,
5468
5938
  cancel,
5939
+ cancelSubtask,
5940
+ rerunSubtask,
5941
+ reviewSubtask,
5469
5942
  followup,
5470
5943
  answer,
5471
5944
  inject,