@linxin666/dsh-client-ui-task-board 0.4.7 → 0.4.9

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.
Files changed (75) hide show
  1. package/README.i18n.yaml +2 -2
  2. package/README.md +29 -22
  3. package/README.zh.md +29 -22
  4. package/lib/client.js +1553 -670
  5. package/lib/client.js.map +1 -1
  6. package/lib/index.js +757 -419
  7. package/lib/types/client/PluginSettingsCard.d.ts +60 -0
  8. package/lib/types/client/TaskBoardSettingsCard.d.ts +14 -0
  9. package/lib/types/client/board/ExecutionLog.d.ts +16 -0
  10. package/lib/types/client/board/TaskForm.d.ts +4 -0
  11. package/lib/types/client/board/VerificationReport.d.ts +2 -15
  12. package/lib/types/client/body-mutations.d.ts +45 -0
  13. package/lib/types/client/locales.d.ts +44 -6
  14. package/lib/types/client/suppress-schedule-row.d.ts +86 -0
  15. package/lib/types/client/telemetry.d.ts +14 -2
  16. package/lib/types/core/controller.d.ts +1 -1
  17. package/lib/types/core/execution-summary.d.ts +52 -0
  18. package/lib/types/core/extension.d.ts +34 -0
  19. package/lib/types/core/spend-budget.d.ts +28 -0
  20. package/lib/types/core/subtask.d.ts +59 -49
  21. package/lib/types/core/tasks.d.ts +37 -9
  22. package/lib/types/core/use-cases/task-update.d.ts +1 -1
  23. package/lib/types/core/workspace-target.d.ts +23 -3
  24. package/lib/types/host/launch-admission.d.ts +8 -9
  25. package/lib/types/host-ledger.d.ts +96 -50
  26. package/lib/types/host-routes.d.ts +49 -0
  27. package/lib/types/host-runner.d.ts +24 -11
  28. package/lib/types/host-service.d.ts +38 -50
  29. package/lib/types/host-spend.d.ts +52 -0
  30. package/lib/types/index.d.ts +70 -61
  31. package/lib/types/loopback.d.ts +41 -1
  32. package/lib/types/protocol.d.ts +0 -5
  33. package/lib/types/tool-surface.d.ts +1 -0
  34. package/package.json +25 -25
  35. package/src/client/CardDefaultPresetField.tsx +1 -1
  36. package/src/client/PluginSettingsCard.tsx +140 -20
  37. package/src/client/TaskBoardSettingsCard.tsx +104 -24
  38. package/src/client/board/ExecutionLog.tsx +140 -0
  39. package/src/client/board/LinkSubtaskModal.tsx +1 -9
  40. package/src/client/board/NewTaskModal.tsx +2 -11
  41. package/src/client/board/TaskCard.tsx +45 -23
  42. package/src/client/board/TaskDetail.tsx +407 -261
  43. package/src/client/board/TaskForm.tsx +19 -4
  44. package/src/client/board/VerificationReport.tsx +143 -104
  45. package/src/client/board/task-markdown.module.css +11 -8
  46. package/src/client/board-settings.module.css +35 -7
  47. package/src/client/board.module.css +855 -115
  48. package/src/client/body-mutations.ts +133 -0
  49. package/src/client/index.ts +10 -0
  50. package/src/client/locales.ts +101 -24
  51. package/src/client/settings-card.module.css +141 -11
  52. package/src/client/suppress-schedule-row.ts +198 -0
  53. package/src/client/telemetry.ts +47 -2
  54. package/src/core/controller.ts +1 -3
  55. package/src/core/execution-summary.ts +96 -0
  56. package/src/core/extension.ts +34 -0
  57. package/src/core/spend-budget.ts +35 -0
  58. package/src/core/store.ts +4 -0
  59. package/src/core/subtask.ts +81 -76
  60. package/src/core/tasks.ts +48 -10
  61. package/src/core/use-cases/task-update.ts +1 -3
  62. package/src/core/workspace-target.ts +27 -3
  63. package/src/host/agent-tools.ts +14 -15
  64. package/src/host/launch-admission.ts +8 -9
  65. package/src/host-ledger.ts +218 -127
  66. package/src/host-routes.ts +65 -2
  67. package/src/host-runner.ts +68 -35
  68. package/src/host-service.ts +136 -132
  69. package/src/host-spend.ts +105 -0
  70. package/src/index.ts +115 -104
  71. package/src/loopback.ts +57 -1
  72. package/src/protocol.ts +2 -9
  73. package/src/tool-surface.ts +1 -0
  74. package/lib/types/client/board/team-run-promotion.d.ts +0 -26
  75. package/src/client/board/team-run-promotion.ts +0 -39
@@ -5,16 +5,22 @@ import { dirname, join } from 'node:path'
5
5
  import { dshHome } from './dsh-home.ts'
6
6
  import { isValidCron, isValidTimeZone, nextRunAtMs, resolveHostTimeZone } from './core/schedule.ts'
7
7
  import { isTaskRecord, parseLedger } from './core/store.ts'
8
- import { canMoveManually, hasOpenExecution, retainRecentExecutions, scheduleExhausted, scheduleRunBudget, settleExecution, settledStatus, startExecution, withSchedule, withStatus, type ExecutionOutcome, type ExecutionRecord, type ScheduleMode, type ScheduleStopReason, type TaskRecord } from './core/tasks.ts'
8
+ import { DEFAULT_SPEND_BUDGET_TOKENS, spendCapMessage, spendCapReached } from './core/spend-budget.ts'
9
+ import { usedTokensToday } from './host-spend.ts'
10
+ import { canMoveManually, hasOpenExecution, retainRecentExecutions, scheduleExhausted, scheduleRunBudget, settleExecution, settledStatus, startExecution, withSchedule, withStatus, type ExecutionOutcome, type ExecutionRecord, type ExecutionSummary, type ScheduleMode, type ScheduleStopReason, type TaskRecord } from './core/tasks.ts'
9
11
  import {
10
12
  DEFAULT_SUBTASK_DEPTH,
13
+ ancestorChain,
11
14
  cascadeTargets,
12
15
  combineCascadeOutcome,
13
- joinsCascadeRun,
16
+ hasOutstandingDescendants,
17
+ isOutstanding,
14
18
  normalizeSubtaskDepth,
15
19
  openGroupExecution,
20
+ outstandingDescendants as lineageOutstandingDescendants,
16
21
  pendingCascadeChildren,
17
22
  resolveExecutionTargets,
23
+ subtreeTasks,
18
24
  } from './core/subtask.ts'
19
25
  import { applyArchiveTask, applyRestoreTask } from './core/use-cases/task-archive.ts'
20
26
  import { applyCreateTask } from './core/use-cases/task-create.ts'
@@ -26,7 +32,7 @@ import { applyDeleteTag, applyRenameTag } from './core/use-cases/task-tag.ts'
26
32
  import { applyUpdateTask, canEditTaskContent, hasContentPatch } from './core/use-cases/task-update.ts'
27
33
  import { TASK_BOARD_MIGRATABLE_SCHEMA_VERSIONS, TASK_BOARD_SCHEMA_VERSION, TASK_BOARD_ZONE_STAMP_SCHEMA_VERSION, type TaskBoardAction, type TaskBoardSchedulerSnapshot } from './protocol.ts'
28
34
  import { withoutAcceptanceAnomalies, type ExecutionVerification } from './core/verification.ts'
29
- import { DEFAULT_SESSION_PERMISSION, effectivePermission, permissionCarriedBy, requiresPermissionConfirmation, type TaskPermission } from './core/handover.ts'
35
+ import { DEFAULT_SESSION_PERMISSION, requiresPermissionConfirmation, type TaskPermission } from './core/handover.ts'
30
36
 
31
37
  interface PersistedScheduler extends TaskBoardSchedulerSnapshot {
32
38
  importedSources?: string[]
@@ -56,13 +62,10 @@ export interface LedgerState {
56
62
 
57
63
  /** Human-facing text for a refused binding, per surface. */
58
64
  function bindingRefusalMessage(
59
- refusal: { kind: 'root' | 'inherited' | 'subtask-pin'; title: string },
65
+ refusal: { kind: 'root' | 'inherited'; title: string },
60
66
  sessionDefault: TaskPermission,
61
67
  surface: 'run' | 'schedule',
62
68
  ): string {
63
- if (refusal.kind === 'subtask-pin') {
64
- return `team run cannot honor the permission binding of subtask "${refusal.title}": a teammate runs inside the Lead session and inherits its permission, which that pin exceeds; clear the card's permission or run the tree without Agent Team`
65
- }
66
69
  if (surface === 'schedule') return `task "${refusal.title}" has an unconfirmed above-default permission`
67
70
  if (refusal.kind === 'root') {
68
71
  return `confirmation-required: the effective permission is above the session default (${sessionDefault}); confirm the card's permission binding first`
@@ -73,15 +76,15 @@ function bindingRefusalMessage(
73
76
  export interface OpenedRun {
74
77
  task: TaskRecord
75
78
  execution: ExecutionRecord
76
- /**
77
- * How the Host obtains this run's session. Absent or `session` launches a
78
- * fresh (or reused) execution session; `teammate` means the run belongs to a
79
- * team-mode cascade, where the Host asks the root's Lead session to spawn a
80
- * teammate instead of launching a session of its own.
81
- */
82
- dispatch?: 'session' | 'teammate'
83
79
  }
84
80
 
81
+ /**
82
+ * Prefix of the `initiatedBy` an inherited descendant verdict carries. The Host
83
+ * recorded it on the run card's behalf (see `inheritVerdictForDescendants`), not
84
+ * an outside agent that reported its own work.
85
+ */
86
+ export const PARENT_RUN_INITIATOR_PREFIX = 'parent-run:'
87
+
85
88
  /** Minimal value copy used by the Host session monitor. */
86
89
  export interface OpenExecutionReference {
87
90
  readonly taskId: string
@@ -117,7 +120,7 @@ export interface LedgerRuntimeView {
117
120
  * Session ids of every open execution, including the ones
118
121
  * {@link openExecutions} skips because their own outcome is already
119
122
  * recorded. A caller that asks whether the board still observes any session
120
- * must use this list: a deferred cascade parent is settled by its members,
123
+ * must use this list: a stored run-group parent is settled by its members,
121
124
  * but it is still an open execution.
122
125
  */
123
126
  readonly openSessionIds: readonly string[]
@@ -398,7 +401,7 @@ function mergeTask(a: TaskRecord, b: TaskRecord): TaskRecord {
398
401
  * missing, cyclic, or names an archived parent while the child is on board is
399
402
  * dropped (the task becomes a root) instead of dropping the task. A chain
400
403
  * deeper than the current `maxSubtaskDepth` is deliberately KEPT: the limit
401
- * gates new links, it never deletes a stored one, and every cascade walk is
404
+ * gates new links, it never deletes a stored one, and every lineage walk is
402
405
  * bounded by the limit anyway. The Host is the only writer of these links, so
403
406
  * this is a last-resort guard against a hand-edited or imported document.
404
407
  */
@@ -411,7 +414,7 @@ export function repairParentLinks(tasks: readonly TaskRecord[]): TaskRecord[] {
411
414
  let depth = 0
412
415
  while (current !== undefined) {
413
416
  // The first hop is the parent itself: an archived parent holding an
414
- // on-board child is outside the archive cascade invariant, and only an
417
+ // on-board child is outside the archive subtree invariant, and only an
415
418
  // import can produce it.
416
419
  if (seen.has(current.id) || (depth === 0 && current.archivedAt !== undefined && task.archivedAt === undefined)) {
417
420
  return { ...task, parentId: undefined }
@@ -493,12 +496,24 @@ export class HostTaskLedger {
493
496
  /** Live reader of the deployment's new-card defaults (a volatile config read). */
494
497
  private readonly cardDefaults: () => CardDefaults
495
498
 
496
- constructor(dir: string = join(dshHome(), 'task-board'), private readonly now: () => number = Date.now, options: { sessionDefaultPermission?: TaskPermission | (() => TaskPermission); maxSubtaskDepth?: number; cardDefaults?: () => CardDefaults } = {}) {
499
+ /**
500
+ * Live reader of the daily token cap (0 = no gate). The scheduled path asks it
501
+ * per due occurrence, so a cap raised after a skipped occurrence admits the
502
+ * next one without a restart.
503
+ */
504
+ private readonly spendBudget: () => number
505
+
506
+ /** Today's measured spend in tokens, or undefined when nothing can be measured. */
507
+ private readonly spendUsed: (now: number) => number | undefined
508
+
509
+ constructor(dir: string = join(dshHome(), 'task-board'), private readonly now: () => number = Date.now, options: { sessionDefaultPermission?: TaskPermission | (() => TaskPermission); maxSubtaskDepth?: number; cardDefaults?: () => CardDefaults; spendBudgetTokens?: () => number; spendUsedToday?: (now: number) => number | undefined } = {}) {
497
510
  // Resolved before the load/repair passes below: they can evaluate the gate.
498
511
  const baseline = options.sessionDefaultPermission
499
512
  this.sessionDefault = typeof baseline === 'function' ? baseline : () => baseline ?? DEFAULT_SESSION_PERMISSION
500
513
  this.depthLimit = normalizeSubtaskDepth(options.maxSubtaskDepth ?? DEFAULT_SUBTASK_DEPTH)
501
514
  this.cardDefaults = options.cardDefaults ?? (() => ({}))
515
+ this.spendBudget = options.spendBudgetTokens ?? (() => DEFAULT_SPEND_BUDGET_TOKENS)
516
+ this.spendUsed = options.spendUsedToday ?? (now => usedTokensToday(now))
502
517
  mkdirSync(dir, { recursive: true })
503
518
  this.file = join(dir, 'ledger-v2.json')
504
519
  this.lockFile = join(dir, 'ledger-v2.lock')
@@ -579,8 +594,9 @@ export class HostTaskLedger {
579
594
  runtimeView(): LedgerRuntimeView {
580
595
  let armedSchedules = 0
581
596
  let runningCards = 0
582
- // Run groups opened by a team-mode card: every other member of those groups
583
- // runs as a teammate inside that card's Lead session.
597
+ // Stored run groups a team-mode card opened before team runs were retired:
598
+ // every other member of those groups ran as a teammate inside that card's
599
+ // Lead session, which is why its turn is read even while its session runs.
584
600
  const teamGroups = new Set<string>()
585
601
  for (const task of this.document.tasks) {
586
602
  if (task.teamRun !== true) continue
@@ -596,8 +612,8 @@ export class HostTaskLedger {
596
612
  for (const execution of task.executions) {
597
613
  if (execution.endedAt !== undefined) continue
598
614
  if (execution.sessionId !== undefined) openSessionIds.push(execution.sessionId)
599
- // A deferred cascade parent already knows its own outcome; the monitor
600
- // has nothing left to inspect, and its children's settles finalize it.
615
+ // A stored run-group parent already knows its own outcome; the monitor
616
+ // has nothing left to inspect, and its members' settles finalize it.
601
617
  if (execution.ownResult !== undefined) continue
602
618
  openExecutions.push({
603
619
  taskId: task.id,
@@ -710,10 +726,10 @@ export class HostTaskLedger {
710
726
  }
711
727
 
712
728
  /**
713
- * Open the cascade one due schedule triggers: an empty array means nothing
714
- * ran (already running, or a participant whose elevated permission is still
715
- * unconfirmed, a one-shot whose instant was missed, or an exhausted budget),
716
- * and the rule's own state says which.
729
+ * Open the one run a due schedule triggers: an empty array means nothing ran
730
+ * (already running, a card whose elevated permission is still unconfirmed, a
731
+ * one-shot whose instant was missed, or an exhausted budget), and the rule's
732
+ * own state says which.
717
733
  *
718
734
  * The run budget is enforced HERE, inside the single ledger writer: a rule
719
735
  * whose counter already reached its cap is stopped instead of opened, so no
@@ -753,10 +769,21 @@ export class HostTaskLedger {
753
769
  return []
754
770
  }
755
771
 
772
+ const spendRefusal = this.spendRefusal(triggeredAt)
773
+ if (spendRefusal !== undefined) {
774
+ // A scheduled occurrence has no client to throw at, so the refusal lands
775
+ // on the board's own scheduler error and the occurrence is skipped without
776
+ // consuming the rule's run budget: raising the cap, or the day rolling
777
+ // over, admits the next trigger instead of leaving a spent rule behind.
778
+ this.document.scheduler.error = `scheduled run refused for task ${taskId}: ${spendRefusal}`
779
+ this.skipOccurrence(taskId, 'limit', triggeredAt)
780
+ return []
781
+ }
782
+
756
783
  if (schedule.mode === 'once') {
757
784
  // The single planned instant is due: open its one run and stop the rule
758
785
  // in the same commit, so the budget can never produce a second one.
759
- return this.startCascade(task, triggeredAt, undefined, false, {
786
+ return this.startRun(task, triggeredAt, undefined, false, {
760
787
  consumed: 1,
761
788
  lastTriggeredAt: triggeredAt,
762
789
  endedReason: 'fired',
@@ -771,7 +798,7 @@ export class HostTaskLedger {
771
798
  const consumed = schedule.runCount + 1
772
799
  const budget = scheduleRunBudget(schedule)
773
800
  const spent = budget !== undefined && consumed >= budget
774
- return this.startCascade(task, triggeredAt, undefined, false, {
801
+ return this.startRun(task, triggeredAt, undefined, false, {
775
802
  consumed: 1,
776
803
  nextRunAt: spent ? undefined : next,
777
804
  lastTriggeredAt: triggeredAt,
@@ -779,6 +806,21 @@ export class HostTaskLedger {
779
806
  })
780
807
  }
781
808
 
809
+ /**
810
+ * Why a due occurrence may not open a run because the day already spent the
811
+ * cap, or undefined when it may. A cap of 0 — the default — answers before the
812
+ * measurement is read, so a board with no gate reads no ledger file.
813
+ * @param now - clock instant (ms epoch).
814
+ * @returns the refusal message, when the cap is reached.
815
+ */
816
+ private spendRefusal(now: number): string | undefined {
817
+ const cap = this.spendBudget()
818
+ if (!(cap > 0)) return undefined
819
+ const used = this.spendUsed(now)
820
+ if (used === undefined || !spendCapReached(used, cap)) return undefined
821
+ return spendCapMessage(used, cap)
822
+ }
823
+
782
824
  /**
783
825
  * Record a due occurrence that opened no execution: roll a recurring rule to
784
826
  * its next occurrence (budget untouched), or stop it when there is none. A
@@ -808,8 +850,8 @@ export class HostTaskLedger {
808
850
  * failed without creating a session (see
809
851
  * {@link applyScheduleRefund}). Called by the service on the failed-launch
810
852
  * path only; a manual run and a launch that did reach a session are never
811
- * refunded. A no-op for a task with no rule, so a failed cascade member does
812
- * not touch anything.
853
+ * refunded. A no-op for a task with no rule, so a failed run does not touch
854
+ * anything.
813
855
  * @param taskId - the task whose occurrence is being refunded.
814
856
  * @param now - clock instant (ms epoch).
815
857
  */
@@ -873,12 +915,18 @@ export class HostTaskLedger {
873
915
  }
874
916
 
875
917
  /**
876
- * Settle one execution. A cascade participant first records its OWN outcome
877
- * and only finalizes once every child execution in its run group has
878
- * settled, so a parent card leaves 'running' with the whole tree's verdict
879
- * rather than its own turn alone.
918
+ * Settle one execution. A NEW run is a single-member group, so it settles on
919
+ * its own turn. A run group the Host opened before it stopped spreading one
920
+ * run across a subtree is folded here instead: a stored participant records
921
+ * its OWN outcome and only finalizes once every child execution in its group
922
+ * has settled, so a parent card leaves 'running' with the whole group's
923
+ * verdict rather than its own turn alone.
924
+ *
925
+ * `summary` is what the run left behind (see `ExecutionSummary`), passed in
926
+ * by whichever reader observed the session. It is informational: a caller
927
+ * without one settles exactly as before, and a settlement never waits on it.
880
928
  */
881
- settle(taskId: string, executionId: string, outcome: ExecutionOutcome, error?: string): void {
929
+ settle(taskId: string, executionId: string, outcome: ExecutionOutcome, error?: string, summary?: ExecutionSummary): void {
882
930
  const now = this.now()
883
931
  const task = this.document.tasks.find(item => item.id === taskId)
884
932
  const execution = task?.executions.find(entry => entry.id === executionId)
@@ -886,17 +934,22 @@ export class HostTaskLedger {
886
934
  const groupId = execution.runGroupId
887
935
  if (groupId === undefined) {
888
936
  this.document.tasks = this.document.tasks.map(item => item.id === taskId
889
- ? settleExecution(item, executionId, outcome, now, error)
937
+ ? settleExecution(item, executionId, outcome, now, error, summary)
890
938
  : item)
891
939
  this.commit()
892
940
  return
893
941
  }
894
942
  let changed = false
895
943
  if (execution.ownResult === undefined) {
944
+ // A stored run-group parent records its own turn's closing text with its
945
+ // own outcome; the fold that finalizes the card carries no session of its
946
+ // own and leaves what is already here in place.
896
947
  this.document.tasks = this.document.tasks.map(item => item.id !== taskId ? item : {
897
948
  ...item,
898
949
  updatedAt: now,
899
- executions: item.executions.map(entry => entry.id === executionId ? { ...entry, ownResult: outcome, ownError: error } : entry),
950
+ executions: item.executions.map(entry => entry.id === executionId
951
+ ? { ...entry, ownResult: outcome, ownError: error, ...(summary === undefined ? {} : { summary }) }
952
+ : entry),
900
953
  })
901
954
  changed = true
902
955
  }
@@ -906,9 +959,82 @@ export class HostTaskLedger {
906
959
  if (task.teamRun === true
907
960
  && this.closeTeamMembers(taskId, groupId, execution.ownResult ?? outcome, execution.ownError ?? error, now)) changed = true
908
961
  if (this.settleCascade(taskId, groupId, now)) changed = true
962
+ // The run's own card may now be terminal: hand its verdict down to the
963
+ // subtasks it was expected to dispatch.
964
+ if (this.inheritVerdictForDescendants(taskId, executionId, groupId, now)) changed = true
909
965
  if (changed) this.commit()
910
966
  }
911
967
 
968
+ /**
969
+ * Record the run's verdict on the outstanding descendants its root was asked
970
+ * to dispatch.
971
+ *
972
+ * A card with unfinished subtasks runs as an autonomous dispatcher: its
973
+ * session reads the subtasks, dispatches them with subagents, and is asked to
974
+ * write their conclusions back with
975
+ * `task_board_manage({action:'record-external-outcome'})` before it finishes.
976
+ * A run that never wrote one back would leave those cards parked with no
977
+ * record of what the parent decided about them, so once the RUN CARD's
978
+ * execution reached a decisive terminal record, every outstanding descendant
979
+ * this run opened no execution for inherits that verdict as an external
980
+ * record.
981
+ *
982
+ * Idempotent by construction: a card that already carries an execution in
983
+ * this run group (the fold owns it), an open execution (it is running on its
984
+ * own), or a terminal record stamped after this run started (the dispatching
985
+ * agent's own backfill, or an earlier pass of this one) is left alone. Only a
986
+ * decisive verdict is inherited: a cancelled run judged nothing about the
987
+ * subtasks, and a subtask already in the done column has nothing left to
988
+ * inherit.
989
+ * @param taskId - the card whose execution just settled.
990
+ * @param executionId - that execution.
991
+ * @param groupId - its run group.
992
+ * @param now - clock instant (ms epoch).
993
+ * @returns whether the document changed.
994
+ */
995
+ private inheritVerdictForDescendants(taskId: string, executionId: string, groupId: string, now: number): boolean {
996
+ const root = this.document.tasks.find(item => item.id === taskId)
997
+ if (root === undefined) return false
998
+ const execution = root.executions.find(entry => entry.id === executionId)
999
+ if (execution?.endedAt === undefined || execution.result === undefined) return false
1000
+ if (execution.result !== 'succeeded' && execution.result !== 'failed') return false
1001
+ const verdict: ExecutionOutcome = execution.result
1002
+ // Only the card this run opened settles a tree it did not run itself: a
1003
+ // member of a historical multi-member group must not hand its own verdict
1004
+ // down to its siblings.
1005
+ if (ancestorChain(this.document.tasks, root).some(ancestor =>
1006
+ ancestor.executions.some(entry => entry.runGroupId === groupId))) return false
1007
+ const descendants = new Set(lineageOutstandingDescendants(this.document.tasks, root.id, this.maxSubtaskDepth).map(task => task.id))
1008
+ if (descendants.size === 0) return false
1009
+ const note = `本次执行由父卡「${root.title}」统一判定,本卡未单独开会话执行;结论继承自父卡运行`
1010
+ let changed = false
1011
+ this.document.tasks = this.document.tasks.map(task => {
1012
+ if (!descendants.has(task.id)) return task
1013
+ if (task.executions.some(entry => entry.runGroupId === groupId)) return task
1014
+ if (task.executions.some(entry => entry.endedAt === undefined)) return task
1015
+ if (task.executions.some(entry => entry.endedAt !== undefined && entry.startedAt >= execution.startedAt)) return task
1016
+ changed = true
1017
+ const inherited: ExecutionRecord = {
1018
+ id: crypto.randomUUID(),
1019
+ sessionId: undefined,
1020
+ startedAt: now,
1021
+ endedAt: now,
1022
+ result: verdict,
1023
+ error: note,
1024
+ initiatedBy: PARENT_RUN_INITIATOR_PREFIX + root.id,
1025
+ external: true,
1026
+ runGroupId: groupId,
1027
+ }
1028
+ return {
1029
+ ...task,
1030
+ status: settledStatus(task, verdict),
1031
+ updatedAt: now,
1032
+ executions: retainRecentExecutions([...task.executions, inherited]),
1033
+ }
1034
+ })
1035
+ return changed
1036
+ }
1037
+
912
1038
  attachSession(taskId: string, executionId: string, sessionId: string): void {
913
1039
  const now = this.now()
914
1040
  const task = this.document.tasks.find(item => item.id === taskId)
@@ -1088,7 +1214,7 @@ export class HostTaskLedger {
1088
1214
  const reason = 'execution closed manually by '
1089
1215
  + (initiator === undefined || initiator === '' ? 'the operator' : initiator)
1090
1216
  + ': no verdict was recorded'
1091
- for (const member of cascadeTargets(this.document.tasks, action.taskId, this.maxSubtaskDepth)) {
1217
+ for (const member of subtreeTasks(this.document.tasks, action.taskId, this.maxSubtaskDepth)) {
1092
1218
  for (const execution of member.executions) {
1093
1219
  if (execution.endedAt !== undefined) continue
1094
1220
  this.document.tasks = this.document.tasks.map(item => item.id !== member.id
@@ -1173,12 +1299,21 @@ export class HostTaskLedger {
1173
1299
  // unconfirmed as the parent would be without its own stamp.
1174
1300
  const refusal = this.bindingRefusal(task)
1175
1301
  if (refusal !== undefined) throw new Error(bindingRefusalMessage(refusal, this.sessionDefaultPermission, 'run'))
1176
- runs = this.startCascade(task, now, initiator, action.kind === 'rerun')
1302
+ runs = this.startRun(task, now, initiator, action.kind === 'rerun')
1177
1303
  break
1178
1304
  }
1305
+ default: {
1306
+ // Defence in depth. Every kind above is reachable only through
1307
+ // TaskBoardHostService.apply(), which validates the kind first; this
1308
+ // default exists so a future call path that reaches the ledger directly
1309
+ // fails loudly instead of falling through to the commit below — which is
1310
+ // exactly what an unknown kind did while the switch had no default:
1311
+ // unchanged document, new revision.
1312
+ throw new Error(`unknown task board action kind: ${String((action as { kind?: unknown }).kind)}`)
1313
+ }
1179
1314
  }
1180
- // startCascade committed the opened participants itself; committing again
1181
- // here would bump the revision twice for one action.
1315
+ // startRun committed the opened execution itself; committing again here
1316
+ // would bump the revision twice for one action.
1182
1317
  if (runs === undefined || runs.length === 0) this.commit()
1183
1318
  return { state: this.state(), ...(runs === undefined ? {} : { runs }) }
1184
1319
  }
@@ -1211,115 +1346,70 @@ export class HostTaskLedger {
1211
1346
  /**
1212
1347
  * The binding that makes a run illegal, if any.
1213
1348
  *
1214
- * A plain cascade launches one session per participant, so every participant
1215
- * carries its own resolved binding and each one gates the run. A team run
1216
- * launches only the Lead session: the Lead's binding gates it, and a
1217
- * teammate inherits that session's permission, so a subtask's OWN pin is
1218
- * refused exactly when the Lead session does not already carry it — the
1219
- * teammate could never be given that authority, and dropping the pin
1220
- * silently would misreport the work (an inherited binding is the Lead's own
1221
- * and stays allowed once the Lead is confirmed).
1349
+ * Only the card being run gets a session, so only ITS resolved binding gates
1350
+ * the run: a subtask's own elevated permission is that subtask's gate when the
1351
+ * subtask is run, and no longer blocks its parent from running.
1222
1352
  * @param root - the task being run.
1223
1353
  * @returns the first refusal, or undefined when the run may start.
1224
1354
  */
1225
- private bindingRefusal(root: TaskRecord): { kind: 'root' | 'inherited' | 'subtask-pin'; title: string } | undefined {
1226
- const participants = this.cascadeParticipants(root.id)
1227
- if (root.teamRun === true) {
1228
- const lead = participants.find(participant => participant.id === root.id)
1229
- if (lead !== undefined && requiresPermissionConfirmation(lead, this.sessionDefaultPermission)) {
1230
- return { kind: 'root', title: lead.title }
1231
- }
1232
- // The Lead session runs at the Lead's own binding, or at the deployment
1233
- // default when it pins none; a teammate inherits that permission and
1234
- // cannot be narrowed below it, so it carries a subtask pin when it is
1235
- // already at least as wide. The raw record carries the subtask's OWN
1236
- // binding: the resolved participant above already folded an inherited one
1237
- // into its permission.
1238
- const leadPermission = effectivePermission(lead ?? root) ?? this.sessionDefaultPermission
1239
- const pinned = participants.find(participant => {
1240
- if (participant.id === root.id) return false
1241
- const raw = this.document.tasks.find(task => task.id === participant.id)
1242
- return raw !== undefined && !permissionCarriedBy(leadPermission, effectivePermission(raw))
1243
- })
1244
- return pinned === undefined ? undefined : { kind: 'subtask-pin', title: pinned.title }
1245
- }
1246
- const unconfirmed = participants.find(participant => requiresPermissionConfirmation(participant, this.sessionDefaultPermission))
1247
- if (unconfirmed === undefined) return undefined
1248
- return { kind: unconfirmed.id === root.id ? 'root' : 'inherited', title: unconfirmed.title }
1249
- }
1250
-
1251
- /**
1252
- * The tasks a cascade from `rootId` would actually open executions for, with
1253
- * their effective execution targets resolved. Archived members never run, and
1254
- * a member that already has an open execution is skipped (a task cannot run
1255
- * twice), so the result is the participant set the launch will use.
1256
- */
1257
- private cascadeParticipants(rootId: string): TaskRecord[] {
1258
- return cascadeTargets(this.document.tasks, rootId, this.maxSubtaskDepth)
1259
- .map(participant => resolveExecutionTargets(participant, this.document.tasks, this.maxSubtaskDepth))
1260
- .filter(participant => participant.archivedAt === undefined
1261
- && !hasOpenExecution(participant))
1355
+ private bindingRefusal(root: TaskRecord): { kind: 'root' | 'inherited'; title: string } | undefined {
1356
+ const resolved = resolveExecutionTargets(root, this.document.tasks, this.maxSubtaskDepth)
1357
+ if (!requiresPermissionConfirmation(resolved, this.sessionDefaultPermission)) return undefined
1358
+ return { kind: root.parentId === undefined ? 'root' : 'inherited', title: root.title }
1262
1359
  }
1263
1360
 
1264
1361
  /** Whether a task or any of its subtasks still has an open execution. */
1265
1362
  private subtreeHasOpenExecution(id: string): boolean {
1266
- return cascadeTargets(this.document.tasks, id, this.maxSubtaskDepth)
1363
+ return subtreeTasks(this.document.tasks, id, this.maxSubtaskDepth)
1267
1364
  .some(task => hasOpenExecution(task))
1268
1365
  }
1269
1366
 
1367
+ /** The descendants of a card that still hold work, as the launch prompt names them. */
1368
+ outstandingDescendants(taskId: string): TaskRecord[] {
1369
+ return lineageOutstandingDescendants(this.document.tasks, taskId, this.maxSubtaskDepth)
1370
+ }
1371
+
1372
+ /** Whether a card still has a subtask outside the done column. */
1373
+ hasOutstandingDescendants(taskId: string): boolean {
1374
+ return hasOutstandingDescendants(this.document.tasks, taskId, this.maxSubtaskDepth)
1375
+ }
1376
+
1270
1377
  /**
1271
- * Open one execution per cascade participant that still has work (the
1272
- * requested task and its on-board descendants, within the depth limit) under
1273
- * a single run group, and commit the ledger once. A descendant in 'done' is
1274
- * not a participant ({@link joinsCascadeRun}). The returned runs are ordered
1275
- * root-first, so the Host launches the parent before its subtasks.
1378
+ * Open ONE execution for the requested card, under a fresh run group, and
1379
+ * commit the ledger once. The group stays single-member on purpose: a run
1380
+ * never opens a session for a subtask (that card's own agent dispatches
1381
+ * subagents inside this session), and the group id is what later lets the
1382
+ * settlement fold a HISTORICAL multi-member group it opened before this
1383
+ * behavior changed.
1276
1384
  * @param root - the task the user ran.
1277
1385
  * @param now - clock instant (ms epoch).
1278
1386
  * @param initiator - the DSH session that asked for the run (audit only).
1279
1387
  * @param rerun - true to reset the root to 'todo' before starting it.
1280
1388
  * @param progress - when set, this run was a due occurrence and the root's
1281
1389
  * rule is advanced (counter, next target, stop/skip record) in the same
1282
- * atomic commit that opened the executions.
1390
+ * atomic commit that opened the execution.
1283
1391
  */
1284
- private startCascade(root: TaskRecord, now: number, initiator?: string, rerun = false, progress?: ScheduleProgress): OpenedRun[] {
1392
+ private startRun(root: TaskRecord, now: number, initiator?: string, rerun = false, progress?: ScheduleProgress): OpenedRun[] {
1285
1393
  const before = this.document.tasks
1394
+ const [participant] = cascadeTargets(before, root.id)
1395
+ if (participant === undefined || participant.archivedAt !== undefined) return []
1396
+ if (hasOpenExecution(participant)) return []
1286
1397
  const groupId = crypto.randomUUID()
1287
- // A team-mode root runs as the Team Lead: every other member of the same
1288
- // cascade is handed to that Lead as a teammate (the tree is flattened into
1289
- // one Team, because only the Lead may spawn).
1290
- const team = root.teamRun === true
1291
- const started = new Map<string, TaskRecord>()
1292
- const runs: OpenedRun[] = []
1293
- for (const task of cascadeTargets(before, root.id, this.maxSubtaskDepth)) {
1294
- if (task.archivedAt !== undefined) continue
1295
- // A subtask that already sits in 'done' is left alone: running the parent
1296
- // repeats the parent, never the work a subtask has already finished. The
1297
- // rule is the card's column, so it holds for a manual run, a re-run and a
1298
- // due occurrence alike.
1299
- if (!joinsCascadeRun(task, root.id)) continue
1300
- if (hasOpenExecution(task)) continue
1301
- const base = rerun && task.id === root.id ? withStatus(task, 'todo', now) : task
1302
- const opened = startExecution(base, now, crypto.randomUUID(), initiator, groupId)
1303
- started.set(task.id, opened.task)
1304
- runs.push({
1305
- task: resolveExecutionTargets(opened.task, before, this.maxSubtaskDepth),
1306
- execution: opened.execution,
1307
- ...(team && task.id !== root.id ? { dispatch: 'teammate' as const } : {}),
1308
- })
1309
- }
1310
- if (runs.length === 0) return []
1311
- let tasks: readonly TaskRecord[] = before.map(task => started.get(task.id) ?? task)
1398
+ const base = rerun ? withStatus(participant, 'todo', now) : participant
1399
+ const opened = startExecution(base, now, crypto.randomUUID(), initiator, groupId)
1400
+ let tasks: readonly TaskRecord[] = before.map(task => task.id === participant.id ? opened.task : task)
1312
1401
  if (progress !== undefined) tasks = applyScheduleProgress(tasks, root.id, progress, now)
1313
1402
  this.document.tasks = [...tasks]
1314
1403
  this.commit()
1315
- return runs
1404
+ return [{ task: resolveExecutionTargets(opened.task, before, this.maxSubtaskDepth), execution: opened.execution }]
1316
1405
  }
1317
1406
 
1318
1407
  /**
1319
- * Finalize every cascade parent that is ready, walking from `taskId` up the
1320
- * lineage: a member settles once its own outcome is recorded and none of its
1321
- * group children is still open, and its verdict folds those children in
1322
- * (failure dominates, then cancellation).
1408
+ * Finalize every stored run-group parent that is ready, walking from `taskId`
1409
+ * up the lineage: a member settles once its own outcome is recorded and none
1410
+ * of its group children is still open, and its verdict folds those children in
1411
+ * (failure dominates, then cancellation). A single-member group — every run
1412
+ * this Host opens now — settles on its own turn exactly as any plain run does.
1323
1413
  */
1324
1414
  private settleCascade(taskId: string, groupId: string, now: number): boolean {
1325
1415
  let changed = false
@@ -1356,11 +1446,12 @@ export class HostTaskLedger {
1356
1446
  * members are all settled. The Host poll calls this on every tick, so a run
1357
1447
  * can no longer be left in the running column by a settle nobody observed:
1358
1448
  *
1359
- * - A team run is governed by its Lead. Once the Lead's own outcome is
1449
+ * - A stored team run is governed by its Lead. Once the Lead's own outcome is
1360
1450
  * recorded, its still-open members are settled with that verdict. A
1361
1451
  * teammate is a durable member of the Team and may never report a turn of
1362
- * its own, and without this the whole lineage waits on it forever.
1363
- * - A cascade parent whose members are all settled is finalized here even
1452
+ * its own, and without this the whole lineage waits on it forever. New runs
1453
+ * never start a team, so this only closes a group the ledger already holds.
1454
+ * - A stored group parent whose members are all settled is finalized here even
1364
1455
  * when the settle that completed the tree happened in another process, or
1365
1456
  * was interrupted between its child write and its parent write.
1366
1457
  *