@xiangyixie/dsh-superagent 0.14.2 → 0.14.3

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.
@@ -1216,7 +1216,8 @@ function cascadeSkips(run, byKey) {
1216
1216
  .map(key => byKey.get(key))
1217
1217
  .find(dependency => dependency
1218
1218
  && (dependency.status === 'failed' || dependency.status === 'skipped'
1219
- || dependency.status === 'blocked' || dependency.status === 'unverified'))
1219
+ || dependency.status === 'blocked' || dependency.status === 'unverified'
1220
+ || dependency.status === 'cancelled'))
1220
1221
  if (!blocker) continue
1221
1222
  subtask.status = 'skipped'
1222
1223
  subtask.skipKind = 'upstream'
@@ -1226,7 +1227,9 @@ function cascadeSkips(run, byKey) {
1226
1227
  ? `not started because ${blocker.key} was blocked by a missing capability`
1227
1228
  : blocker.status === 'unverified'
1228
1229
  ? `not started because ${blocker.key}'s deliverable could not be verified`
1229
- : `not started because ${blocker.key} was skipped`
1230
+ : blocker.status === 'cancelled'
1231
+ ? `not started because ${blocker.key} was cancelled`
1232
+ : `not started because ${blocker.key} was skipped`
1230
1233
  subtask.waitingOn = []
1231
1234
  round = true
1232
1235
  changed = true
@@ -1374,15 +1377,52 @@ export function createOrchestrator(deps) {
1374
1377
  /** Cached managers, keyed by boundary; a test may inject one instead of spawning real git. */
1375
1378
  let workspaceManagerRef = workspace
1376
1379
  const workspaceManagers = new Map()
1380
+
1381
+ /** Path comparison that ignores case and a trailing separator on Windows. */
1382
+ function sameDirectory(left, right) {
1383
+ const normalize = value => {
1384
+ const resolved = path.resolve(value)
1385
+ const trimmed = resolved.replace(/[\\/]+$/, '') || resolved
1386
+ return process.platform === 'win32' ? trimmed.toLowerCase() : trimmed
1387
+ }
1388
+ return normalize(left) === normalize(right)
1389
+ }
1390
+
1391
+ /**
1392
+ * Where isolation is based.
1393
+ *
1394
+ * The default follows the session. The sandbox boundary, the declared
1395
+ * deliverables and the merge target are all the directory the user is working
1396
+ * in, so basing worktrees anywhere else makes a merge land where nobody looks
1397
+ * — or fail outright on a checkout with unrelated local edits. A profile's
1398
+ * `workspaceRoot` is only honoured when it names that same directory;
1399
+ * `workspaceBase: 'config'` restores the old unconditional behaviour.
1400
+ *
1401
+ * @param {string} boundary - the session's cwd, absolute.
1402
+ * @returns {{ baseDir: string, note: string | null }} directory plus a visible mismatch note.
1403
+ */
1404
+ function workspaceBaseFor(boundary) {
1405
+ const configured = typeof config.workspaceRoot === 'string' ? config.workspaceRoot.trim() : ''
1406
+ if (!configured) return { baseDir: boundary, note: null }
1407
+ const resolved = path.resolve(configured)
1408
+ if (config.workspaceBase === 'config') return { baseDir: resolved, note: null }
1409
+ if (sameDirectory(resolved, boundary)) return { baseDir: resolved, note: null }
1410
+ return {
1411
+ baseDir: boundary,
1412
+ note: `workspaceRoot ${resolved} is not this session's directory (${boundary}), so isolation `
1413
+ + "used the session directory; set workspaceBase: 'config' to keep the configured one",
1414
+ }
1415
+ }
1416
+
1377
1417
  function workspaceManager(boundary) {
1378
1418
  if (workspaceManagerRef) return workspaceManagerRef
1379
1419
  const key = boundary ?? process.cwd()
1380
1420
  if (!workspaceManagers.has(key)) {
1381
- const configured = typeof config.workspaceRoot === 'string' ? config.workspaceRoot.trim() : ''
1421
+ const { baseDir } = workspaceBaseFor(key)
1382
1422
  // A checkout outside the boundary gets every write denied, so the pool
1383
- // is anchored there even when `workspaceRoot` points somewhere else.
1423
+ // is anchored there even when the base resolves somewhere else.
1384
1424
  workspaceManagers.set(key, createWorkspaceManager({
1385
- baseDir: configured ? path.resolve(configured) : key,
1425
+ baseDir,
1386
1426
  boundary: key,
1387
1427
  log,
1388
1428
  sleep,
@@ -1406,27 +1446,35 @@ export function createOrchestrator(deps) {
1406
1446
  if (config.workspaceIsolation !== true) return null
1407
1447
  if (run.workspace) return run.workspace.mode === 'git-worktree' ? run.workspace : null
1408
1448
  let verdict
1449
+ const boundary = sessionCwd(parent)
1409
1450
  try {
1410
- verdict = await workspaceManager(sessionCwd(parent)).probe()
1451
+ verdict = await workspaceManager(boundary).probe()
1411
1452
  } catch (error) {
1412
1453
  verdict = { ok: false, base: null, reason: error?.message ?? String(error) }
1413
1454
  }
1414
1455
  if (!verdict.ok) {
1415
1456
  // 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: [] }
1457
+ // in the shared directory, and both status and the report say so. `base`
1458
+ // is that shared directory — the session's own — so declared deliverables
1459
+ // are still checked where the workers actually write, instead of a stale
1460
+ // `workspaceRoot` from another project.
1461
+ run.workspace = { mode: 'unavailable', base: boundary, reason: verdict.reason, merges: [] }
1418
1462
  log(`run ${run.id}: workspace isolation unavailable — ${verdict.reason}`)
1419
1463
  await save(run)
1420
1464
  return null
1421
1465
  }
1466
+ const { note } = workspaceBaseFor(boundary)
1467
+ if (note) log(`run ${run.id}: ${note}`)
1422
1468
  run.workspace = {
1423
1469
  mode: 'git-worktree',
1424
1470
  base: verdict.base,
1425
1471
  root: verdict.root ?? null,
1426
- boundary: sessionCwd(parent),
1472
+ boundary,
1427
1473
  reason: null,
1428
1474
  merges: [],
1429
1475
  conflicts: 0,
1476
+ // Persisted so status can repeat the warning long after this log line.
1477
+ ...(note ? { baseNote: note } : {}),
1430
1478
  }
1431
1479
  await save(run)
1432
1480
  return run.workspace
@@ -1710,6 +1758,51 @@ export function createOrchestrator(deps) {
1710
1758
  await save(run)
1711
1759
  }
1712
1760
 
1761
+ /**
1762
+ * Merge outcomes whose files never reached the main checkout.
1763
+ *
1764
+ * A skipped merge (dirty checkout) and a conflict both leave the work only
1765
+ * inside the worker's branch. If such a run reported `completed`, the user
1766
+ * would open the target directory and find nothing — so status has to drop
1767
+ * and the branch has to be named somewhere they will read it.
1768
+ *
1769
+ * @param {object} run - live run record.
1770
+ * @returns {Array<object>} `run.workspace.merges` rows that did not land.
1771
+ */
1772
+ function unmergedOutcomes(run) {
1773
+ if (run.workspace?.mode !== 'git-worktree') return []
1774
+ return (run.workspace.merges ?? [])
1775
+ .filter(merge => merge.status !== 'merged' && merge.status !== 'no-changes')
1776
+ }
1777
+
1778
+ /**
1779
+ * The attention item that explains an unmerged run and how to finish it.
1780
+ *
1781
+ * @param {object} run - live run record.
1782
+ * @param {Array<object>} outcomes - rows from `unmergedOutcomes`.
1783
+ * @returns {{ question: string, options: string[], reason: string }} attention payload.
1784
+ */
1785
+ function mergeAttention(run, outcomes) {
1786
+ const base = run.workspace?.base ?? 'the main checkout'
1787
+ const branches = outcomes.map(outcome => outcome.branch).filter(Boolean)
1788
+ const detail = outcomes.map(outcome => {
1789
+ const kept = outcome.dir ? ` kept at ${outcome.dir}` : ''
1790
+ const why = outcome.detail ? ` — ${outcome.detail}` : ''
1791
+ return `[${outcome.index}] ${outcome.branch ?? 'unknown branch'} (${outcome.status})${kept}${why}`
1792
+ }).join('; ')
1793
+ const commands = branches.length > 0
1794
+ ? `git -C "${base}" stash push -u -m superagent-before-merge, then `
1795
+ + branches.map(branch => `git -C "${base}" merge --no-ff ${branch}`).join(', then ')
1796
+ : `commit or stash the changes in ${base} and resume the run`
1797
+ return {
1798
+ question: `${outcomes.length} worker branch(es) were never merged into ${base}, so their files are `
1799
+ + `not in the target directory. ${detail}. To finish by hand: ${commands}. `
1800
+ + 'The branches and worktrees are kept, so nothing is lost.',
1801
+ options: ['merge them now', 'keep the branches for review'],
1802
+ reason: 'the main checkout had uncommitted changes or the merge conflicted, so merging was refused',
1803
+ }
1804
+ }
1805
+
1713
1806
  function save(run) {
1714
1807
  run.updatedAt = new Date(now()).toISOString()
1715
1808
  // The guard is process-wide and owned by the caller; copy its counters onto
@@ -1900,6 +1993,8 @@ export function createOrchestrator(deps) {
1900
1993
  await settle(run, {
1901
1994
  controller: new AbortController(),
1902
1995
  activations: new Set(),
1996
+ subtaskAborts: new Map(),
1997
+ cancelledSubtasks: new Set(),
1903
1998
  waiters: 0,
1904
1999
  run,
1905
2000
  promise: null,
@@ -2928,7 +3023,14 @@ export function createOrchestrator(deps) {
2928
3023
  const blocked = budgetStop(run)
2929
3024
  if (blocked) {
2930
3025
  if (!rt.abortCause) rt.abortCause = 'budget'
2931
- if (!run.error) run.error = blocked
3026
+ // A budget stop is a notice, not a failure: the work that finished still
3027
+ // counts, so it is recorded beside the run instead of in `error`.
3028
+ run.budgetStop = {
3029
+ detail: blocked,
3030
+ at: new Date(now()).toISOString(),
3031
+ calls: spentCalls(run),
3032
+ tokens: spentTokens(run),
3033
+ }
2932
3034
  if (!rt.controller.signal.aborted) rt.controller.abort(new Error(blocked))
2933
3035
  throw new Error(`budget exceeded: ${blocked}; raise maxModelCallsPerRun or maxTokensPerRun if this was intended`)
2934
3036
  }
@@ -3327,7 +3429,9 @@ export function createOrchestrator(deps) {
3327
3429
  record.outcome = error?.code ?? 'error'
3328
3430
  record.error = lastReason
3329
3431
  }
3330
- log(`planner attempt ${round} failed: ${lastReason}`)
3432
+ // A host-side failure is otherwise only a message in the run file; the
3433
+ // stack keeps the failing host frame visible in the plugin log.
3434
+ log(`planner attempt ${round} failed: ${lastReason}${error?.stack ? `\n${error.stack}` : ''}`)
3331
3435
  if (error?.code === 'subagent-unavailable') {
3332
3436
  markHostGone(rt, error)
3333
3437
  break
@@ -3348,7 +3452,25 @@ export function createOrchestrator(deps) {
3348
3452
  }
3349
3453
 
3350
3454
  async function runSubtask(run, subtask, parent, rt, { model = null } = {}) {
3351
- const signal = rt.controller.signal
3455
+ const key = subtask.key ?? `w${subtask.index}`
3456
+ if (rt.cancelledSubtasks?.has(key)) {
3457
+ // A cancelled subtask stays cancelled: a retry pass, a self-heal round,
3458
+ // or the next graph tick must not quietly start it again.
3459
+ subtask.status = 'cancelled'
3460
+ subtask.finishedAt = subtask.finishedAt ?? new Date(now()).toISOString()
3461
+ subtask.cancelledAt = subtask.cancelledAt ?? subtask.finishedAt
3462
+ return
3463
+ }
3464
+ // The board can stop one subtask without stopping the run. Its own
3465
+ // controller is combined with the run's, so both reasons still abort this
3466
+ // child and only this child.
3467
+ const own = new AbortController()
3468
+ rt.subtaskAborts = rt.subtaskAborts ?? new Map()
3469
+ rt.subtaskAborts.set(key, own)
3470
+ const runSignal = rt.controller.signal
3471
+ const signal = typeof AbortSignal.any === 'function'
3472
+ ? AbortSignal.any([runSignal, own.signal])
3473
+ : runSignal
3352
3474
  for (let attempt = subtask.attempts + 1; attempt <= run.limits.attempts; attempt++) {
3353
3475
  if (signal.aborted) break
3354
3476
  subtask.status = 'running'
@@ -3385,6 +3507,7 @@ export function createOrchestrator(deps) {
3385
3507
  await save(run)
3386
3508
 
3387
3509
  const result = await abortable(handle.result, signal)
3510
+ if (rt.cancelledSubtasks?.has(key) || own.signal.aborted) break
3388
3511
  const raw = textOf(result.output)
3389
3512
  subtask.stopReason = result.stopReason
3390
3513
  if (result.stopReason === 'completed' && raw) {
@@ -3495,7 +3618,15 @@ export function createOrchestrator(deps) {
3495
3618
  }
3496
3619
 
3497
3620
  if (subtask.status !== 'completed') {
3498
- if (signal.aborted) {
3621
+ if (rt.cancelledSubtasks?.has(key) || own.signal.aborted) {
3622
+ // The person stopped this subtask on purpose. It is neither a failure
3623
+ // nor resumable work: `cancelled` says exactly what happened.
3624
+ subtask.status = 'cancelled'
3625
+ subtask.error = null
3626
+ subtask.stopReason = 'cancelled'
3627
+ subtask.cancelledAt = new Date(now()).toISOString()
3628
+ subtask.finishedAt = subtask.cancelledAt
3629
+ } else if (signal.aborted) {
3499
3630
  // Cancelled or out of time: the subtask did not fail on its own terms,
3500
3631
  // so leave it resumable instead of recording a failure.
3501
3632
  subtask.status = 'pending'
@@ -3527,6 +3658,13 @@ export function createOrchestrator(deps) {
3527
3658
  async function runGraph(run, parent, rt, { model = null } = {}) {
3528
3659
  const signal = rt.controller.signal
3529
3660
  const byKey = new Map(run.subtasks.map(subtask => [subtask.key, subtask]))
3661
+ // Two workers that declare the same output file would overwrite each other
3662
+ // in a shared checkout, so only one of them is ever in flight. Parallelism
3663
+ // is only worth what the plan keeps disjoint: a higher cap must not turn a
3664
+ // planner mistake into a lost file.
3665
+ const declaredWrites = subtask => new Set((subtask.deliverables ?? [])
3666
+ .map(entry => path.posix.normalize(String(entry?.path ?? '').replace(/\\/g, '/').trim()).toLowerCase())
3667
+ .filter(Boolean))
3530
3668
  let revived = false
3531
3669
  for (const subtask of run.subtasks) {
3532
3670
  if (subtask.status === 'skipped' && subtask.skipKind === 'upstream') {
@@ -3563,6 +3701,22 @@ export function createOrchestrator(deps) {
3563
3701
  subtask.waitingOn = []
3564
3702
  dirty = true
3565
3703
  }
3704
+ const own = declaredWrites(subtask)
3705
+ const clash = own.size === 0 ? null : [...inFlight.keys()].find(key => {
3706
+ const other = declaredWrites(byKey.get(key))
3707
+ return [...own].some(file => other.has(file))
3708
+ })
3709
+ if (clash) {
3710
+ // The file is already being written by that worker, so this one waits
3711
+ // for it instead of racing it. The plan's dependency edges stay as
3712
+ // written; the wait is repeated until the clash clears.
3713
+ if (subtask.status !== 'waiting' || subtask.waitingOn.join() !== clash) {
3714
+ subtask.status = 'waiting'
3715
+ subtask.waitingOn = [clash]
3716
+ dirty = true
3717
+ }
3718
+ continue
3719
+ }
3566
3720
  if (inFlight.size >= run.limits.maxParallel) break
3567
3721
  const task = runSubtask(run, subtask, parent, rt, { model })
3568
3722
  .catch(error => log(`subtask ${subtask.index} graph runner threw: ${error?.message ?? error}`))
@@ -3639,6 +3793,15 @@ export function createOrchestrator(deps) {
3639
3793
  // limit or stalling leaves the work partial even when every subtask of the
3640
3794
  // last round finished: the goal, not the round, is what was started.
3641
3795
  if (run.goalMode) return run.goalMode.achieved ? 'completed' : (completed > 0 ? 'partial' : 'failed')
3796
+ // Everything that did not finish was either stopped on purpose or waiting
3797
+ // on something that was. Calling that "failed" would blame the person who
3798
+ // pressed stop, so the run reports the same word the subtask does.
3799
+ const cancelled = subtasks.filter(subtask => subtask.status === 'cancelled').length
3800
+ if (completed === 0 && cancelled > 0) {
3801
+ return subtasks.every(subtask => subtask.status === 'cancelled' || subtask.status === 'skipped')
3802
+ ? 'cancelled'
3803
+ : 'failed'
3804
+ }
3642
3805
  if (completed === 0) return 'failed'
3643
3806
  if (rt.abortCause === 'deadline') {
3644
3807
  return completed === subtasks.length ? 'completed' : 'partial'
@@ -3805,6 +3968,19 @@ export function createOrchestrator(deps) {
3805
3968
  if (guardSection && typeof run.report === 'string' && run.report) {
3806
3969
  run.report = `${run.report.trimEnd()}\n\n${guardSection}`
3807
3970
  }
3971
+ // Work that never left its branch is not delivered. Reporting "completed"
3972
+ // while the target directory stays empty is the one outcome a user cannot
3973
+ // check their way out of, so the run drops to partial and the branch, the
3974
+ // reason and the manual merge land in the attention inbox.
3975
+ const unmerged = unmergedOutcomes(run)
3976
+ if (nextStatus === 'completed' && unmerged.length > 0) {
3977
+ nextStatus = 'partial'
3978
+ const note = `${unmerged.length} worker branch(es) were not merged into ${run.workspace?.base ?? 'the main checkout'}; `
3979
+ + 'the files exist only in the kept worktrees'
3980
+ run.error = run.error || note
3981
+ log(`run ${run.id}: ${note}; recorded as partial`)
3982
+ recordAttention(run, 'workspace-merge', mergeAttention(run, unmerged))
3983
+ }
3808
3984
  // Stripping an attention-only or notebook-only reply can leave nothing
3809
3985
  // behind. A run that "completed" with no artifact is not a completion:
3810
3986
  // keep the evidence and downgrade it so a schedule does not report success
@@ -3823,11 +3999,14 @@ export function createOrchestrator(deps) {
3823
3999
  error = 'cancelled by superagent_cancel'
3824
4000
  } else if (rt.abortCause === 'host-gone') {
3825
4001
  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) {
4002
+ } else if (nextStatus === 'failed' && !error && !run.budgetStop?.detail) {
3827
4003
  error = run.subtasks.map(subtask => subtask.error ?? subtask.skippedReason).filter(Boolean).slice(0, 3).join('; ')
3828
4004
  || 'no subtask completed'
3829
4005
  }
3830
4006
  if (rt.abortCause === 'deadline' && !error) error = 'deadline exceeded'
4007
+ // A budget stop only belongs in `error` when it is the reason the run did
4008
+ // not finish: a completed run reports it as a notice and keeps `error` null.
4009
+ if (nextStatus !== 'completed' && !error && run.budgetStop?.detail) error = run.budgetStop.detail
3831
4010
 
3832
4011
  let outcome = null
3833
4012
  if (TERMINAL_STATUSES.has(nextStatus)) {
@@ -4621,6 +4800,10 @@ export function createOrchestrator(deps) {
4621
4800
  const rt = {
4622
4801
  controller: new AbortController(),
4623
4802
  activations: new Set(),
4803
+ // Per-subtask stop buttons: a board cancel aborts only its own child,
4804
+ // while `cancelledSubtasks` stops a retry from starting it again.
4805
+ subtaskAborts: new Map(),
4806
+ cancelledSubtasks: new Set(),
4624
4807
  waiters: 0,
4625
4808
  run,
4626
4809
  promise: null,
@@ -4913,7 +5096,7 @@ export function createOrchestrator(deps) {
4913
5096
  * `reopen` lets `superagent_answer` continue a `completed` run: its subtasks
4914
5097
  * stay done and only the aggregation runs again, now with the answer.
4915
5098
  */
4916
- async function resumeLocked(runId, parent, clientTimeZone, { reopen = false, approvePolicy = false } = {}) {
5099
+ async function resumeLocked(runId, parent, clientTimeZone, { reopen = false, approvePolicy = false, only = null } = {}) {
4917
5100
  const id = String(runId ?? '').trim()
4918
5101
  if (!parent || typeof parent !== 'object') throw new Error('superagent requires a live parent agent')
4919
5102
  {
@@ -5012,8 +5195,13 @@ export function createOrchestrator(deps) {
5012
5195
  failed: failedBefore,
5013
5196
  }
5014
5197
 
5198
+ // `only` restricts a resume to named subtasks. The board uses it to
5199
+ // rerun one subtask without restarting unrelated failed work; an empty
5200
+ // list means "rerun none" and is how an accepted review re-aggregates.
5201
+ const onlyKeys = Array.isArray(only) ? new Set(only.map(String)) : null
5015
5202
  for (const subtask of run.subtasks ?? []) {
5016
5203
  if (subtask.status === 'completed') continue
5204
+ if (onlyKeys && !onlyKeys.has(String(subtask.key))) continue
5017
5205
  // A dependency on a subtask the plan never contained cannot be fixed
5018
5206
  // by resuming: nothing would ever clear it.
5019
5207
  if (subtask.skipKind === 'missing') continue
@@ -5292,6 +5480,225 @@ export function createOrchestrator(deps) {
5292
5480
  throw new Error(`no question ${wanted} on run ${run.id}; ${describeOpen()}.`)
5293
5481
  }
5294
5482
 
5483
+ /** Resolve one subtask by its plan key (`w2`) or by its 1-based index. */
5484
+ function findSubtask(run, target) {
5485
+ const wanted = String(target ?? '').trim()
5486
+ if (!wanted) throw new Error('subtask is required; pass its key (w2) or its 1-based index')
5487
+ const byKey = (run.subtasks ?? []).find(subtask => subtask.key === wanted)
5488
+ if (byKey) return byKey
5489
+ const asIndex = Number(wanted)
5490
+ if (Number.isInteger(asIndex) && asIndex > 0) {
5491
+ const byIndex = (run.subtasks ?? []).find(subtask => subtask.index === asIndex)
5492
+ if (byIndex) return byIndex
5493
+ }
5494
+ const known = (run.subtasks ?? []).map(subtask => subtask.key).join(', ')
5495
+ throw new Error(`no subtask ${wanted} on run ${run.id}; it has ${known || '(none)'}`)
5496
+ }
5497
+
5498
+ /**
5499
+ * Stop one subtask while the rest of the run keeps going.
5500
+ *
5501
+ * This is deliberately narrower than `cancel`: the run's own controller is
5502
+ * untouched, so other workers, the planner's remaining graph, and the final
5503
+ * report still run. Dependents of the stopped subtask are skipped by the
5504
+ * normal cascade, with the reason kept on each one.
5505
+ *
5506
+ * @param {string} runId - run identity.
5507
+ * @param {string} target - subtask key or 1-based index.
5508
+ * @returns {Promise<object>} the updated run.
5509
+ */
5510
+ async function cancelSubtask(runId, target) {
5511
+ const id = String(runId ?? '').trim()
5512
+ if (!id) throw new Error('run_id is required')
5513
+ const rt = runtime.get(id)
5514
+ if (!rt || !ACTIVE_STATUSES.has(rt.run.status)) {
5515
+ const run = await loadRun(id)
5516
+ throw new Error(
5517
+ `run ${id} is ${run.status}, so there is no running subtask to stop; `
5518
+ + 'use rerun on the board if that work should run again',
5519
+ )
5520
+ }
5521
+ const subtask = findSubtask(rt.run, target)
5522
+ if (subtask.status === 'completed') {
5523
+ throw new Error(`subtask ${subtask.key} already completed; rerun it on the board if it needs another pass`)
5524
+ }
5525
+ if (subtask.status === 'cancelled') return rt.run
5526
+ const at = new Date(now()).toISOString()
5527
+ rt.cancelledSubtasks.add(subtask.key)
5528
+ subtask.status = 'cancelled'
5529
+ subtask.error = null
5530
+ subtask.stopReason = 'cancelled'
5531
+ subtask.cancelledAt = at
5532
+ subtask.finishedAt = at
5533
+ subtask.cancelledBy = 'board'
5534
+ subtask.waitingOn = []
5535
+ const own = rt.subtaskAborts?.get(subtask.key)
5536
+ own?.abort(new Error('subtask cancelled from the board'))
5537
+ for (const handle of [...rt.activations]) {
5538
+ if (subtask.childId && handle.childId === subtask.childId) await disposeQuietly(handle)
5539
+ }
5540
+ await save(rt.run)
5541
+ await auditRecord({
5542
+ runId: id,
5543
+ subtaskId: `subtask-${subtask.index}`,
5544
+ actor: 'session',
5545
+ kind: 'subtask.cancel',
5546
+ action: 'board_cancel_subtask',
5547
+ target: subtask.title,
5548
+ result: 'cancelled',
5549
+ })
5550
+ return rt.run
5551
+ }
5552
+
5553
+ /**
5554
+ * Put one finished or skipped subtask back to `pending` and run only it.
5555
+ *
5556
+ * Completed siblings are not touched, so this is not a run restart. A
5557
+ * subtask that was skipped because this one failed is revived too, because
5558
+ * its dependency is about to run again; unrelated failures are left alone.
5559
+ *
5560
+ * @param {string} runId - run identity.
5561
+ * @param {string} target - subtask key or 1-based index.
5562
+ * @param {object} parent - live agent that owns the run.
5563
+ * @param {string} [clientTimeZone] - forwarded to the resume.
5564
+ * @returns {Promise<object>} the queued run.
5565
+ */
5566
+ async function rerunSubtask(runId, target, parent, clientTimeZone) {
5567
+ const id = String(runId ?? '').trim()
5568
+ if (!id) throw new Error('run_id is required')
5569
+ return serialize(async () => {
5570
+ if (runtime.has(id)) {
5571
+ throw new Error(`run ${id} is still active; wait for it to finish or stop the subtask first`)
5572
+ }
5573
+ const run = await loadRun(id)
5574
+ assertResumeOwner(run, parent)
5575
+ const subtask = findSubtask(run, target)
5576
+ if (subtask.status === 'running' || subtask.status === 'pending' || subtask.status === 'waiting') {
5577
+ throw new Error(`subtask ${subtask.key} is already waiting to run; resume the run instead`)
5578
+ }
5579
+ const keys = new Set([subtask.key])
5580
+ // A skip caused by this dependency is not a verdict on that subtask:
5581
+ // revive it so the rerun can actually unblock it.
5582
+ for (const candidate of run.subtasks ?? []) {
5583
+ if (candidate.status === 'skipped' && candidate.skipKind === 'upstream'
5584
+ && (candidate.dependsOn ?? []).some(dep => dep === subtask.key || keys.has(dep))) {
5585
+ keys.add(candidate.key)
5586
+ candidate.status = 'pending'
5587
+ candidate.skipKind = null
5588
+ candidate.skippedReason = null
5589
+ candidate.waitingOn = []
5590
+ }
5591
+ }
5592
+ subtask.status = 'pending'
5593
+ subtask.attempts = 0
5594
+ subtask.error = null
5595
+ subtask.stopReason = null
5596
+ subtask.result = null
5597
+ subtask.usage = null
5598
+ subtask.childId = null
5599
+ subtask.startedAt = null
5600
+ subtask.finishedAt = null
5601
+ subtask.cancelledAt = null
5602
+ subtask.cancelledBy = null
5603
+ subtask.waitingOn = []
5604
+ subtask.skipKind = null
5605
+ subtask.skippedReason = null
5606
+ subtask.blockKind = null
5607
+ subtask.blockedReason = null
5608
+ subtask.unverifiedReason = null
5609
+ subtask.deliverableCheck = null
5610
+ subtask.deliverables = []
5611
+ await save(run)
5612
+ const resumed = await resumeLocked(id, parent, clientTimeZone, {
5613
+ reopen: true,
5614
+ only: [...keys],
5615
+ })
5616
+ await auditRecord({
5617
+ runId: id,
5618
+ subtaskId: `subtask-${subtask.index}`,
5619
+ actor: `session:${parent?.id ?? 'unknown'}`,
5620
+ kind: 'subtask.rerun',
5621
+ action: 'board_rerun_subtask',
5622
+ target: subtask.title,
5623
+ result: 'queued',
5624
+ })
5625
+ return resumed
5626
+ })
5627
+ }
5628
+
5629
+ /**
5630
+ * Accept or reject an `unverified` deliverable from the board.
5631
+ *
5632
+ * An unverified subtask is one the session could not judge on its own; a
5633
+ * person saying "I checked it" is the missing capability. Accepting reopens
5634
+ * the run so the report includes it, and only the report runs again.
5635
+ *
5636
+ * @param {string} runId - run identity.
5637
+ * @param {string} target - subtask key or 1-based index.
5638
+ * @param {'accept' | 'reject'} verdict - the person's decision.
5639
+ * @param {object} parent - live agent that owns the run.
5640
+ * @param {string} [clientTimeZone] - forwarded to the resume.
5641
+ * @param {string} [note] - optional reason kept on the audit line.
5642
+ * @returns {Promise<object>} the run or a note when the review was only recorded.
5643
+ */
5644
+ async function reviewSubtask(runId, target, verdict, parent, clientTimeZone, note = null) {
5645
+ const id = String(runId ?? '').trim()
5646
+ if (!id) throw new Error('run_id is required')
5647
+ if (verdict !== 'accept' && verdict !== 'reject') {
5648
+ throw new Error('verdict must be accept or reject')
5649
+ }
5650
+ return serialize(async () => {
5651
+ if (runtime.has(id)) {
5652
+ throw new Error(`run ${id} is still active; wait for it to finish before reviewing its deliverables`)
5653
+ }
5654
+ const run = await loadRun(id)
5655
+ assertResumeOwner(run, parent)
5656
+ const subtask = findSubtask(run, target)
5657
+ if (subtask.status !== 'unverified') {
5658
+ throw new Error(`subtask ${subtask.key} is ${subtask.status}, not waiting for a review`)
5659
+ }
5660
+ const at = new Date(now()).toISOString()
5661
+ subtask.reviewedAt = at
5662
+ subtask.reviewedBy = `session:${parent?.id ?? 'unknown'}`
5663
+ subtask.reviewNote = typeof note === 'string' && note.trim() ? note.trim().slice(0, 500) : null
5664
+ if (verdict === 'accept') {
5665
+ subtask.status = 'completed'
5666
+ subtask.result = subtask.result ?? '(deliverable accepted by a person)'
5667
+ subtask.error = null
5668
+ subtask.unverifiedReason = null
5669
+ subtask.finishedAt = at
5670
+ await save(run)
5671
+ const resumed = await resumeLocked(id, parent, clientTimeZone, { reopen: true, only: [] })
5672
+ await auditRecord({
5673
+ runId: id,
5674
+ subtaskId: `subtask-${subtask.index}`,
5675
+ actor: `session:${parent?.id ?? 'unknown'}`,
5676
+ kind: 'subtask.review',
5677
+ action: 'board_accept_subtask',
5678
+ target: subtask.title,
5679
+ result: 'completed',
5680
+ meta: { note: subtask.reviewNote },
5681
+ })
5682
+ return resumed
5683
+ }
5684
+ subtask.status = 'failed'
5685
+ subtask.error = `验收未通过${subtask.reviewNote ? `:${subtask.reviewNote}` : ''}`
5686
+ subtask.finishedAt = at
5687
+ await save(run)
5688
+ await auditRecord({
5689
+ runId: id,
5690
+ subtaskId: `subtask-${subtask.index}`,
5691
+ actor: `session:${parent?.id ?? 'unknown'}`,
5692
+ kind: 'subtask.review',
5693
+ action: 'board_reject_subtask',
5694
+ target: subtask.title,
5695
+ result: 'failed',
5696
+ meta: { note: subtask.reviewNote },
5697
+ })
5698
+ return run
5699
+ })
5700
+ }
5701
+
5295
5702
  async function cancel(runId) {
5296
5703
  // A run that never got a slot has no owner process to ask: remove it from
5297
5704
  // the line here, so no timer can start it afterwards.
@@ -5466,6 +5873,9 @@ export function createOrchestrator(deps) {
5466
5873
  start,
5467
5874
  resume,
5468
5875
  cancel,
5876
+ cancelSubtask,
5877
+ rerunSubtask,
5878
+ reviewSubtask,
5469
5879
  followup,
5470
5880
  answer,
5471
5881
  inject,
package/lib/schedule.js CHANGED
@@ -494,6 +494,7 @@ export function createScheduler({
494
494
  }
495
495
  const open = (run.attention?.items ?? []).find(item => !item.answer) ?? null
496
496
  const budgetish = run.goalMode?.stop?.reason === 'budget'
497
+ || (Boolean(run.budgetStop?.detail) && run.status !== 'completed')
497
498
  || /budget/i.test(String(run.error ?? ''))
498
499
  || /budget/i.test(String(run.goalMode?.stop?.detail ?? ''))
499
500
  let outcome
@@ -513,7 +514,7 @@ export function createScheduler({
513
514
  }
514
515
  if (outcome === 'budget') {
515
516
  plan.enabled = false
516
- plan.pausedReason = `budget reached: ${oneLine(run.error ?? run.goalMode?.stop?.detail ?? 'the run hit its budget', 200)}`
517
+ plan.pausedReason = `budget reached: ${oneLine(run.budgetStop?.detail ?? run.error ?? run.goalMode?.stop?.detail ?? 'the run hit its budget', 200)}`
517
518
  plan.lastOutcome = 'budget'
518
519
  plan.lastReason = plan.pausedReason
519
520
  record(plan, 'budget', plan.pausedReason)