@fish-under-sea/dsh-client-ui-task-board-fish 1.0.2 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (123) hide show
  1. package/NOTICE +1 -1
  2. package/README.en.md +4 -4
  3. package/README.md +4 -4
  4. package/README.zh.md +4 -4
  5. package/lib/client.js +4428 -1508
  6. package/lib/client.js.map +1 -1
  7. package/lib/index.js +2670 -496
  8. package/lib/types/client/CardDefaultPresetField.d.ts +35 -0
  9. package/lib/types/client/PluginSettingsCard.d.ts +130 -19
  10. package/lib/types/client/RangeBubble.d.ts +46 -0
  11. package/lib/types/client/SegmentGroup.d.ts +28 -0
  12. package/lib/types/client/TaskBoardSettingsCard.d.ts +63 -0
  13. package/lib/types/client/board/AttachmentField.d.ts +70 -0
  14. package/lib/types/client/board/ExecutionLog.d.ts +24 -0
  15. package/lib/types/client/board/ReasoningEffortField.d.ts +25 -0
  16. package/lib/types/client/board/TaskForm.d.ts +4 -0
  17. package/lib/types/client/board/VerificationReport.d.ts +2 -15
  18. package/lib/types/client/board/model-options.d.ts +87 -0
  19. package/lib/types/client/board/preset-label.d.ts +21 -0
  20. package/lib/types/client/board/preset-roster.d.ts +45 -0
  21. package/lib/types/client/board/source-group.d.ts +27 -0
  22. package/lib/types/client/body-mutations.d.ts +45 -0
  23. package/lib/types/client/host-api.d.ts +25 -0
  24. package/lib/types/client/locales.d.ts +87 -9
  25. package/lib/types/client/pending-verify.d.ts +47 -0
  26. package/lib/types/client/plugin-card-seat.d.ts +3 -1
  27. package/lib/types/client/service.d.ts +4 -1
  28. package/lib/types/client/settings-form.d.ts +73 -51
  29. package/lib/types/core/attachment.d.ts +132 -0
  30. package/lib/types/core/card-defaults.d.ts +78 -0
  31. package/lib/types/core/controller.d.ts +57 -8
  32. package/lib/types/core/execution-summary.d.ts +52 -0
  33. package/lib/types/core/extension.d.ts +116 -0
  34. package/lib/types/core/launch-width.d.ts +31 -0
  35. package/lib/types/core/reasoning-effort.d.ts +57 -0
  36. package/lib/types/core/session-reuse.d.ts +7 -1
  37. package/lib/types/core/spend-budget.d.ts +28 -0
  38. package/lib/types/core/subtask.d.ts +100 -37
  39. package/lib/types/core/tasks.d.ts +94 -10
  40. package/lib/types/core/use-cases/task-create.d.ts +10 -5
  41. package/lib/types/core/use-cases/task-tag.d.ts +36 -0
  42. package/lib/types/core/use-cases/task-update.d.ts +22 -1
  43. package/lib/types/core/wire-projection.d.ts +35 -0
  44. package/lib/types/core/workspace-target.d.ts +23 -3
  45. package/lib/types/host/attachments.d.ts +250 -0
  46. package/lib/types/host/extension-registry.d.ts +40 -0
  47. package/lib/types/host/launch-admission.d.ts +71 -0
  48. package/lib/types/host-ledger.d.ts +114 -47
  49. package/lib/types/host-routes.d.ts +63 -0
  50. package/lib/types/host-runner.d.ts +164 -18
  51. package/lib/types/host-service.d.ts +182 -46
  52. package/lib/types/host-spend.d.ts +52 -0
  53. package/lib/types/index.d.ts +173 -54
  54. package/lib/types/loopback.d.ts +41 -1
  55. package/lib/types/protocol.d.ts +52 -11
  56. package/lib/types/tool-surface.d.ts +1 -0
  57. package/locale/en.json +6 -0
  58. package/locale/zh.json +6 -0
  59. package/package.json +35 -28
  60. package/src/client/CardDefaultPresetField.tsx +101 -0
  61. package/src/client/PluginSettingsCard.tsx +385 -111
  62. package/src/client/RangeBubble.tsx +164 -0
  63. package/src/client/SegmentGroup.tsx +93 -0
  64. package/src/client/TaskBoardSettingsCard.tsx +332 -37
  65. package/src/client/board/AttachmentField.tsx +383 -0
  66. package/src/client/board/EditTaskModal.tsx +63 -0
  67. package/src/client/board/ExecutionLog.tsx +154 -0
  68. package/src/client/board/LinkSubtaskModal.tsx +1 -1
  69. package/src/client/board/NewTaskModal.tsx +154 -45
  70. package/src/client/board/ReasoningEffortField.tsx +50 -0
  71. package/src/client/board/TagManagerModal.tsx +151 -2
  72. package/src/client/board/TaskBoard.tsx +47 -10
  73. package/src/client/board/TaskCard.tsx +45 -23
  74. package/src/client/board/TaskDetail.tsx +468 -258
  75. package/src/client/board/TaskForm.tsx +19 -4
  76. package/src/client/board/VerificationReport.tsx +143 -104
  77. package/src/client/board/model-options.ts +208 -0
  78. package/src/client/board/preset-label.ts +32 -0
  79. package/src/client/board/preset-roster.ts +58 -0
  80. package/src/client/board/source-group.ts +94 -0
  81. package/src/client/board/task-markdown.module.css +11 -8
  82. package/src/client/board-settings.module.css +35 -7
  83. package/src/client/board.module.css +1044 -105
  84. package/src/client/body-mutations.ts +133 -0
  85. package/src/client/host-api.ts +70 -0
  86. package/src/client/index.ts +109 -95
  87. package/src/client/locales.ts +205 -48
  88. package/src/client/pending-verify.ts +90 -0
  89. package/src/client/plugin-card-seat.ts +8 -2
  90. package/src/client/service.ts +24 -0
  91. package/src/client/settings-card.module.css +466 -89
  92. package/src/client/settings-entry-form.ts +0 -1
  93. package/src/client/settings-form.ts +102 -60
  94. package/src/core/attachment.ts +287 -0
  95. package/src/core/card-defaults.ts +132 -0
  96. package/src/core/controller.ts +90 -11
  97. package/src/core/execution-summary.ts +96 -0
  98. package/src/core/extension.ts +120 -0
  99. package/src/core/launch-width.ts +38 -0
  100. package/src/core/reasoning-effort.ts +92 -0
  101. package/src/core/session-reuse.ts +7 -1
  102. package/src/core/spend-budget.ts +35 -0
  103. package/src/core/store.ts +19 -1
  104. package/src/core/subtask.ts +144 -68
  105. package/src/core/tasks.ts +117 -10
  106. package/src/core/use-cases/task-create.ts +27 -16
  107. package/src/core/use-cases/task-tag.ts +56 -0
  108. package/src/core/use-cases/task-update.ts +33 -5
  109. package/src/core/wire-projection.ts +81 -0
  110. package/src/core/workspace-target.ts +27 -3
  111. package/src/host/agent-tools.ts +33 -21
  112. package/src/host/attachments.ts +650 -0
  113. package/src/host/extension-registry.ts +150 -5
  114. package/src/host/launch-admission.ts +139 -0
  115. package/src/host-ledger.ts +248 -117
  116. package/src/host-routes.ts +233 -15
  117. package/src/host-runner.ts +395 -61
  118. package/src/host-service.ts +512 -139
  119. package/src/host-spend.ts +105 -0
  120. package/src/index.ts +312 -92
  121. package/src/loopback.ts +57 -1
  122. package/src/protocol.ts +83 -18
  123. package/src/tool-surface.ts +1 -0
@@ -5,18 +5,26 @@ 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 ExecutionRework, 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,
16
+ hasOutstandingDescendants,
17
+ isOutstanding,
13
18
  normalizeSubtaskDepth,
14
19
  openGroupExecution,
20
+ outstandingDescendants as lineageOutstandingDescendants,
15
21
  pendingCascadeChildren,
16
22
  resolveExecutionTargets,
23
+ subtreeTasks,
17
24
  } from './core/subtask.ts'
18
25
  import { applyArchiveTask, applyRestoreTask } from './core/use-cases/task-archive.ts'
19
26
  import { applyCreateTask } from './core/use-cases/task-create.ts'
27
+ import type { CardDefaults } from './core/card-defaults.ts'
20
28
  import { applyDeleteTask } from './core/use-cases/task-delete.ts'
21
29
  import { applySetSchedule, applyScheduleProgress, applyScheduleRefund, type ScheduleProgress } from './core/use-cases/task-schedule.ts'
22
30
  import { applySetParent } from './core/use-cases/task-parent.ts'
@@ -24,7 +32,7 @@ import { applyDeleteTag, applyRenameTag } from './core/use-cases/task-tag.ts'
24
32
  import { applyUpdateTask, canEditTaskContent, hasContentPatch } from './core/use-cases/task-update.ts'
25
33
  import { TASK_BOARD_MIGRATABLE_SCHEMA_VERSIONS, TASK_BOARD_SCHEMA_VERSION, TASK_BOARD_ZONE_STAMP_SCHEMA_VERSION, type TaskBoardAction, type TaskBoardSchedulerSnapshot } from './protocol.ts'
26
34
  import { withoutAcceptanceAnomalies, type ExecutionVerification } from './core/verification.ts'
27
- 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'
28
36
 
29
37
  interface PersistedScheduler extends TaskBoardSchedulerSnapshot {
30
38
  importedSources?: string[]
@@ -54,13 +62,10 @@ export interface LedgerState {
54
62
 
55
63
  /** Human-facing text for a refused binding, per surface. */
56
64
  function bindingRefusalMessage(
57
- refusal: { kind: 'root' | 'inherited' | 'subtask-pin'; title: string },
65
+ refusal: { kind: 'root' | 'inherited'; title: string },
58
66
  sessionDefault: TaskPermission,
59
67
  surface: 'run' | 'schedule',
60
68
  ): string {
61
- if (refusal.kind === 'subtask-pin') {
62
- 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`
63
- }
64
69
  if (surface === 'schedule') return `task "${refusal.title}" has an unconfirmed above-default permission`
65
70
  if (refusal.kind === 'root') {
66
71
  return `confirmation-required: the effective permission is above the session default (${sessionDefault}); confirm the card's permission binding first`
@@ -71,15 +76,15 @@ function bindingRefusalMessage(
71
76
  export interface OpenedRun {
72
77
  task: TaskRecord
73
78
  execution: ExecutionRecord
74
- /**
75
- * How the Host obtains this run's session. Absent or `session` launches a
76
- * fresh (or reused) execution session; `teammate` means the run belongs to a
77
- * team-mode cascade, where the Host asks the root's Lead session to spawn a
78
- * teammate instead of launching a session of its own.
79
- */
80
- dispatch?: 'session' | 'teammate'
81
79
  }
82
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
+
83
88
  /** Minimal value copy used by the Host session monitor. */
84
89
  export interface OpenExecutionReference {
85
90
  readonly taskId: string
@@ -115,7 +120,7 @@ export interface LedgerRuntimeView {
115
120
  * Session ids of every open execution, including the ones
116
121
  * {@link openExecutions} skips because their own outcome is already
117
122
  * recorded. A caller that asks whether the board still observes any session
118
- * 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,
119
124
  * but it is still an open execution.
120
125
  */
121
126
  readonly openSessionIds: readonly string[]
@@ -396,7 +401,7 @@ function mergeTask(a: TaskRecord, b: TaskRecord): TaskRecord {
396
401
  * missing, cyclic, or names an archived parent while the child is on board is
397
402
  * dropped (the task becomes a root) instead of dropping the task. A chain
398
403
  * deeper than the current `maxSubtaskDepth` is deliberately KEPT: the limit
399
- * 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
400
405
  * bounded by the limit anyway. The Host is the only writer of these links, so
401
406
  * this is a last-resort guard against a hand-edited or imported document.
402
407
  */
@@ -409,7 +414,7 @@ export function repairParentLinks(tasks: readonly TaskRecord[]): TaskRecord[] {
409
414
  let depth = 0
410
415
  while (current !== undefined) {
411
416
  // The first hop is the parent itself: an archived parent holding an
412
- // 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
413
418
  // import can produce it.
414
419
  if (seen.has(current.id) || (depth === 0 && current.archivedAt !== undefined && task.archivedAt === undefined)) {
415
420
  return { ...task, parentId: undefined }
@@ -488,11 +493,27 @@ export class HostTaskLedger {
488
493
  */
489
494
  private depthLimit: number
490
495
 
491
- constructor(dir: string = join(dshHome(), 'task-board'), private readonly now: () => number = Date.now, options: { sessionDefaultPermission?: TaskPermission | (() => TaskPermission); maxSubtaskDepth?: number } = {}) {
496
+ /** Live reader of the deployment's new-card defaults (a volatile config read). */
497
+ private readonly cardDefaults: () => CardDefaults
498
+
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 } = {}) {
492
510
  // Resolved before the load/repair passes below: they can evaluate the gate.
493
511
  const baseline = options.sessionDefaultPermission
494
512
  this.sessionDefault = typeof baseline === 'function' ? baseline : () => baseline ?? DEFAULT_SESSION_PERMISSION
495
513
  this.depthLimit = normalizeSubtaskDepth(options.maxSubtaskDepth ?? DEFAULT_SUBTASK_DEPTH)
514
+ this.cardDefaults = options.cardDefaults ?? (() => ({}))
515
+ this.spendBudget = options.spendBudgetTokens ?? (() => DEFAULT_SPEND_BUDGET_TOKENS)
516
+ this.spendUsed = options.spendUsedToday ?? (now => usedTokensToday(now))
496
517
  mkdirSync(dir, { recursive: true })
497
518
  this.file = join(dir, 'ledger-v2.json')
498
519
  this.lockFile = join(dir, 'ledger-v2.lock')
@@ -573,8 +594,9 @@ export class HostTaskLedger {
573
594
  runtimeView(): LedgerRuntimeView {
574
595
  let armedSchedules = 0
575
596
  let runningCards = 0
576
- // Run groups opened by a team-mode card: every other member of those groups
577
- // 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.
578
600
  const teamGroups = new Set<string>()
579
601
  for (const task of this.document.tasks) {
580
602
  if (task.teamRun !== true) continue
@@ -590,8 +612,8 @@ export class HostTaskLedger {
590
612
  for (const execution of task.executions) {
591
613
  if (execution.endedAt !== undefined) continue
592
614
  if (execution.sessionId !== undefined) openSessionIds.push(execution.sessionId)
593
- // A deferred cascade parent already knows its own outcome; the monitor
594
- // 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.
595
617
  if (execution.ownResult !== undefined) continue
596
618
  openExecutions.push({
597
619
  taskId: task.id,
@@ -704,10 +726,10 @@ export class HostTaskLedger {
704
726
  }
705
727
 
706
728
  /**
707
- * Open the cascade one due schedule triggers: an empty array means nothing
708
- * ran (already running, or a participant whose elevated permission is still
709
- * unconfirmed, a one-shot whose instant was missed, or an exhausted budget),
710
- * 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.
711
733
  *
712
734
  * The run budget is enforced HERE, inside the single ledger writer: a rule
713
735
  * whose counter already reached its cap is stopped instead of opened, so no
@@ -747,10 +769,21 @@ export class HostTaskLedger {
747
769
  return []
748
770
  }
749
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
+
750
783
  if (schedule.mode === 'once') {
751
784
  // The single planned instant is due: open its one run and stop the rule
752
785
  // in the same commit, so the budget can never produce a second one.
753
- return this.startCascade(task, triggeredAt, undefined, false, {
786
+ return this.startRun(task, triggeredAt, undefined, false, {
754
787
  consumed: 1,
755
788
  lastTriggeredAt: triggeredAt,
756
789
  endedReason: 'fired',
@@ -765,7 +798,7 @@ export class HostTaskLedger {
765
798
  const consumed = schedule.runCount + 1
766
799
  const budget = scheduleRunBudget(schedule)
767
800
  const spent = budget !== undefined && consumed >= budget
768
- return this.startCascade(task, triggeredAt, undefined, false, {
801
+ return this.startRun(task, triggeredAt, undefined, false, {
769
802
  consumed: 1,
770
803
  nextRunAt: spent ? undefined : next,
771
804
  lastTriggeredAt: triggeredAt,
@@ -773,6 +806,21 @@ export class HostTaskLedger {
773
806
  })
774
807
  }
775
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
+
776
824
  /**
777
825
  * Record a due occurrence that opened no execution: roll a recurring rule to
778
826
  * its next occurrence (budget untouched), or stop it when there is none. A
@@ -802,8 +850,8 @@ export class HostTaskLedger {
802
850
  * failed without creating a session (see
803
851
  * {@link applyScheduleRefund}). Called by the service on the failed-launch
804
852
  * path only; a manual run and a launch that did reach a session are never
805
- * refunded. A no-op for a task with no rule, so a failed cascade member does
806
- * not touch anything.
853
+ * refunded. A no-op for a task with no rule, so a failed run does not touch
854
+ * anything.
807
855
  * @param taskId - the task whose occurrence is being refunded.
808
856
  * @param now - clock instant (ms epoch).
809
857
  */
@@ -867,12 +915,18 @@ export class HostTaskLedger {
867
915
  }
868
916
 
869
917
  /**
870
- * Settle one execution. A cascade participant first records its OWN outcome
871
- * and only finalizes once every child execution in its run group has
872
- * settled, so a parent card leaves 'running' with the whole tree's verdict
873
- * 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.
874
928
  */
875
- settle(taskId: string, executionId: string, outcome: ExecutionOutcome, error?: string): void {
929
+ settle(taskId: string, executionId: string, outcome: ExecutionOutcome, error?: string, summary?: ExecutionSummary): void {
876
930
  const now = this.now()
877
931
  const task = this.document.tasks.find(item => item.id === taskId)
878
932
  const execution = task?.executions.find(entry => entry.id === executionId)
@@ -880,17 +934,22 @@ export class HostTaskLedger {
880
934
  const groupId = execution.runGroupId
881
935
  if (groupId === undefined) {
882
936
  this.document.tasks = this.document.tasks.map(item => item.id === taskId
883
- ? settleExecution(item, executionId, outcome, now, error)
937
+ ? settleExecution(item, executionId, outcome, now, error, summary)
884
938
  : item)
885
939
  this.commit()
886
940
  return
887
941
  }
888
942
  let changed = false
889
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.
890
947
  this.document.tasks = this.document.tasks.map(item => item.id !== taskId ? item : {
891
948
  ...item,
892
949
  updatedAt: now,
893
- 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),
894
953
  })
895
954
  changed = true
896
955
  }
@@ -900,9 +959,82 @@ export class HostTaskLedger {
900
959
  if (task.teamRun === true
901
960
  && this.closeTeamMembers(taskId, groupId, execution.ownResult ?? outcome, execution.ownError ?? error, now)) changed = true
902
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
903
965
  if (changed) this.commit()
904
966
  }
905
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
+
906
1038
  attachSession(taskId: string, executionId: string, sessionId: string): void {
907
1039
  const now = this.now()
908
1040
  const task = this.document.tasks.find(item => item.id === taskId)
@@ -974,7 +1106,7 @@ export class HostTaskLedger {
974
1106
  const input = action.input.freeze === undefined || initiator === undefined || initiator === ''
975
1107
  ? action.input
976
1108
  : { ...action.input, freeze: { ...action.input.freeze, frozenBy: initiator } }
977
- const result = applyCreateTask(this.document.tasks, input, now, action.id, this.maxSubtaskDepth, timeZone())
1109
+ const result = applyCreateTask(this.document.tasks, input, now, action.id, this.maxSubtaskDepth, timeZone(), this.cardDefaults())
978
1110
  if (result.task === undefined) throw new Error(result.error ?? 'invalid task')
979
1111
  this.document.tasks = [...result.tasks]
980
1112
  break
@@ -1082,7 +1214,7 @@ export class HostTaskLedger {
1082
1214
  const reason = 'execution closed manually by '
1083
1215
  + (initiator === undefined || initiator === '' ? 'the operator' : initiator)
1084
1216
  + ': no verdict was recorded'
1085
- 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)) {
1086
1218
  for (const execution of member.executions) {
1087
1219
  if (execution.endedAt !== undefined) continue
1088
1220
  this.document.tasks = this.document.tasks.map(item => item.id !== member.id
@@ -1157,22 +1289,37 @@ export class HostTaskLedger {
1157
1289
  this.document.tasks = [...result.tasks]
1158
1290
  break
1159
1291
  }
1292
+ case 'rework':
1160
1293
  case 'rerun':
1161
1294
  case 'run': {
1162
1295
  const task = this.document.tasks.find(item => item.id === action.taskId)
1163
1296
  if (task?.archivedAt !== undefined) throw new Error('archived task is read-only')
1164
1297
  if (task === undefined || hasOpenExecution(task)) throw new Error('task is already running or missing')
1298
+ // A rework asks for a second attempt at work this card's own conversation
1299
+ // already holds; the ledger alone decides whether that conversation
1300
+ // exists, so the run can never be opened with instructions no session
1301
+ // ever saw.
1302
+ const rework = action.kind === 'rework' ? this.reworkInput(task, action.instructions) : undefined
1165
1303
  // The confirmation gate judges the RESOLVED binding: a subtask that
1166
1304
  // inherits an elevated permission from its parent is exactly as
1167
1305
  // unconfirmed as the parent would be without its own stamp.
1168
1306
  const refusal = this.bindingRefusal(task)
1169
1307
  if (refusal !== undefined) throw new Error(bindingRefusalMessage(refusal, this.sessionDefaultPermission, 'run'))
1170
- runs = this.startCascade(task, now, initiator, action.kind === 'rerun')
1308
+ runs = this.startRun(task, now, initiator, action.kind !== 'run', undefined, rework)
1171
1309
  break
1172
1310
  }
1311
+ default: {
1312
+ // Defence in depth. Every kind above is reachable only through
1313
+ // TaskBoardHostService.apply(), which validates the kind first; this
1314
+ // default exists so a future call path that reaches the ledger directly
1315
+ // fails loudly instead of falling through to the commit below — which is
1316
+ // exactly what an unknown kind did while the switch had no default:
1317
+ // unchanged document, new revision.
1318
+ throw new Error(`unknown task board action kind: ${String((action as { kind?: unknown }).kind)}`)
1319
+ }
1173
1320
  }
1174
- // startCascade committed the opened participants itself; committing again
1175
- // here would bump the revision twice for one action.
1321
+ // startRun committed the opened execution itself; committing again here
1322
+ // would bump the revision twice for one action.
1176
1323
  if (runs === undefined || runs.length === 0) this.commit()
1177
1324
  return { state: this.state(), ...(runs === undefined ? {} : { runs }) }
1178
1325
  }
@@ -1205,109 +1352,92 @@ export class HostTaskLedger {
1205
1352
  /**
1206
1353
  * The binding that makes a run illegal, if any.
1207
1354
  *
1208
- * A plain cascade launches one session per participant, so every participant
1209
- * carries its own resolved binding and each one gates the run. A team run
1210
- * launches only the Lead session: the Lead's binding gates it, and a
1211
- * teammate inherits that session's permission, so a subtask's OWN pin is
1212
- * refused exactly when the Lead session does not already carry it — the
1213
- * teammate could never be given that authority, and dropping the pin
1214
- * silently would misreport the work (an inherited binding is the Lead's own
1215
- * and stays allowed once the Lead is confirmed).
1355
+ * Only the card being run gets a session, so only ITS resolved binding gates
1356
+ * the run: a subtask's own elevated permission is that subtask's gate when the
1357
+ * subtask is run, and no longer blocks its parent from running.
1216
1358
  * @param root - the task being run.
1217
1359
  * @returns the first refusal, or undefined when the run may start.
1218
1360
  */
1219
- private bindingRefusal(root: TaskRecord): { kind: 'root' | 'inherited' | 'subtask-pin'; title: string } | undefined {
1220
- const participants = this.cascadeParticipants(root.id)
1221
- if (root.teamRun === true) {
1222
- const lead = participants.find(participant => participant.id === root.id)
1223
- if (lead !== undefined && requiresPermissionConfirmation(lead, this.sessionDefaultPermission)) {
1224
- return { kind: 'root', title: lead.title }
1225
- }
1226
- // The Lead session runs at the Lead's own binding, or at the deployment
1227
- // default when it pins none; a teammate inherits that permission and
1228
- // cannot be narrowed below it, so it carries a subtask pin when it is
1229
- // already at least as wide. The raw record carries the subtask's OWN
1230
- // binding: the resolved participant above already folded an inherited one
1231
- // into its permission.
1232
- const leadPermission = effectivePermission(lead ?? root) ?? this.sessionDefaultPermission
1233
- const pinned = participants.find(participant => {
1234
- if (participant.id === root.id) return false
1235
- const raw = this.document.tasks.find(task => task.id === participant.id)
1236
- return raw !== undefined && !permissionCarriedBy(leadPermission, effectivePermission(raw))
1237
- })
1238
- return pinned === undefined ? undefined : { kind: 'subtask-pin', title: pinned.title }
1239
- }
1240
- const unconfirmed = participants.find(participant => requiresPermissionConfirmation(participant, this.sessionDefaultPermission))
1241
- if (unconfirmed === undefined) return undefined
1242
- return { kind: unconfirmed.id === root.id ? 'root' : 'inherited', title: unconfirmed.title }
1361
+ private bindingRefusal(root: TaskRecord): { kind: 'root' | 'inherited'; title: string } | undefined {
1362
+ const resolved = resolveExecutionTargets(root, this.document.tasks, this.maxSubtaskDepth)
1363
+ if (!requiresPermissionConfirmation(resolved, this.sessionDefaultPermission)) return undefined
1364
+ return { kind: root.parentId === undefined ? 'root' : 'inherited', title: root.title }
1243
1365
  }
1244
1366
 
1245
1367
  /**
1246
- * The tasks a cascade from `rootId` would actually open executions for, with
1247
- * their effective execution targets resolved. Archived members never run, and
1248
- * a member that already has an open execution is skipped (a task cannot run
1249
- * twice), so the result is the participant set the launch will use.
1368
+ * The rework block a rework request opens its execution with, or the refusal
1369
+ * that names why there is nothing to rework.
1370
+ *
1371
+ * Read from the ledger alone: a card that never ran, and a card whose runs
1372
+ * recorded no session, have no conversation to send the reviewer's
1373
+ * instructions into. Minting one would hand those instructions to an agent
1374
+ * that never saw the work being sent back, which is the opposite of what a
1375
+ * rework asks for.
1376
+ * @param task - the card being reworked.
1377
+ * @param instructions - the reviewer's instructions, already validated.
1378
+ * @returns the block recorded on the opened execution.
1250
1379
  */
1251
- private cascadeParticipants(rootId: string): TaskRecord[] {
1252
- return cascadeTargets(this.document.tasks, rootId, this.maxSubtaskDepth)
1253
- .map(participant => resolveExecutionTargets(participant, this.document.tasks, this.maxSubtaskDepth))
1254
- .filter(participant => participant.archivedAt === undefined
1255
- && !hasOpenExecution(participant))
1380
+ private reworkInput(task: TaskRecord, instructions: string): ExecutionRework {
1381
+ if (task.executions.length === 0) throw new Error('task ' + task.id + ' has never executed; there is no run to rework')
1382
+ const settled = [...task.executions].reverse().find(entry => entry.endedAt !== undefined && entry.sessionId !== undefined)
1383
+ if (settled?.sessionId === undefined) throw new Error('task ' + task.id + ' records no execution session to continue')
1384
+ return { instructions }
1256
1385
  }
1257
1386
 
1258
1387
  /** Whether a task or any of its subtasks still has an open execution. */
1259
1388
  private subtreeHasOpenExecution(id: string): boolean {
1260
- return cascadeTargets(this.document.tasks, id, this.maxSubtaskDepth)
1389
+ return subtreeTasks(this.document.tasks, id, this.maxSubtaskDepth)
1261
1390
  .some(task => hasOpenExecution(task))
1262
1391
  }
1263
1392
 
1393
+ /** The descendants of a card that still hold work, as the launch prompt names them. */
1394
+ outstandingDescendants(taskId: string): TaskRecord[] {
1395
+ return lineageOutstandingDescendants(this.document.tasks, taskId, this.maxSubtaskDepth)
1396
+ }
1397
+
1398
+ /** Whether a card still has a subtask outside the done column. */
1399
+ hasOutstandingDescendants(taskId: string): boolean {
1400
+ return hasOutstandingDescendants(this.document.tasks, taskId, this.maxSubtaskDepth)
1401
+ }
1402
+
1264
1403
  /**
1265
- * Open one execution per cascade participant (the requested task and its
1266
- * on-board descendants, within the depth limit) under a single run group, and
1267
- * commit the ledger once. The returned runs are ordered root-first, so the
1268
- * Host launches the parent before its subtasks.
1404
+ * Open ONE execution for the requested card, under a fresh run group, and
1405
+ * commit the ledger once. The group stays single-member on purpose: a run
1406
+ * never opens a session for a subtask (that card's own agent dispatches
1407
+ * subagents inside this session), and the group id is what later lets the
1408
+ * settlement fold a HISTORICAL multi-member group it opened before this
1409
+ * behavior changed.
1269
1410
  * @param root - the task the user ran.
1270
1411
  * @param now - clock instant (ms epoch).
1271
1412
  * @param initiator - the DSH session that asked for the run (audit only).
1272
1413
  * @param rerun - true to reset the root to 'todo' before starting it.
1273
1414
  * @param progress - when set, this run was a due occurrence and the root's
1274
1415
  * rule is advanced (counter, next target, stop/skip record) in the same
1275
- * atomic commit that opened the executions.
1416
+ * atomic commit that opened the execution.
1417
+ * @param rework - the reviewer's instructions, when this run redoes previous
1418
+ * work; recorded on the execution it opens.
1276
1419
  */
1277
- private startCascade(root: TaskRecord, now: number, initiator?: string, rerun = false, progress?: ScheduleProgress): OpenedRun[] {
1420
+ private startRun(root: TaskRecord, now: number, initiator?: string, rerun = false, progress?: ScheduleProgress, rework?: ExecutionRework): OpenedRun[] {
1278
1421
  const before = this.document.tasks
1422
+ const [participant] = cascadeTargets(before, root.id)
1423
+ if (participant === undefined || participant.archivedAt !== undefined) return []
1424
+ if (hasOpenExecution(participant)) return []
1279
1425
  const groupId = crypto.randomUUID()
1280
- // A team-mode root runs as the Team Lead: every other member of the same
1281
- // cascade is handed to that Lead as a teammate (the tree is flattened into
1282
- // one Team, because only the Lead may spawn).
1283
- const team = root.teamRun === true
1284
- const started = new Map<string, TaskRecord>()
1285
- const runs: OpenedRun[] = []
1286
- for (const task of cascadeTargets(before, root.id, this.maxSubtaskDepth)) {
1287
- if (task.archivedAt !== undefined) continue
1288
- if (hasOpenExecution(task)) continue
1289
- const base = rerun && task.id === root.id ? withStatus(task, 'todo', now) : task
1290
- const opened = startExecution(base, now, crypto.randomUUID(), initiator, groupId)
1291
- started.set(task.id, opened.task)
1292
- runs.push({
1293
- task: resolveExecutionTargets(opened.task, before, this.maxSubtaskDepth),
1294
- execution: opened.execution,
1295
- ...(team && task.id !== root.id ? { dispatch: 'teammate' as const } : {}),
1296
- })
1297
- }
1298
- if (runs.length === 0) return []
1299
- let tasks: readonly TaskRecord[] = before.map(task => started.get(task.id) ?? task)
1426
+ const base = rerun ? withStatus(participant, 'todo', now) : participant
1427
+ const opened = startExecution(base, now, crypto.randomUUID(), initiator, groupId, rework)
1428
+ let tasks: readonly TaskRecord[] = before.map(task => task.id === participant.id ? opened.task : task)
1300
1429
  if (progress !== undefined) tasks = applyScheduleProgress(tasks, root.id, progress, now)
1301
1430
  this.document.tasks = [...tasks]
1302
1431
  this.commit()
1303
- return runs
1432
+ return [{ task: resolveExecutionTargets(opened.task, before, this.maxSubtaskDepth), execution: opened.execution }]
1304
1433
  }
1305
1434
 
1306
1435
  /**
1307
- * Finalize every cascade parent that is ready, walking from `taskId` up the
1308
- * lineage: a member settles once its own outcome is recorded and none of its
1309
- * group children is still open, and its verdict folds those children in
1310
- * (failure dominates, then cancellation).
1436
+ * Finalize every stored run-group parent that is ready, walking from `taskId`
1437
+ * up the lineage: a member settles once its own outcome is recorded and none
1438
+ * of its group children is still open, and its verdict folds those children in
1439
+ * (failure dominates, then cancellation). A single-member group — every run
1440
+ * this Host opens now — settles on its own turn exactly as any plain run does.
1311
1441
  */
1312
1442
  private settleCascade(taskId: string, groupId: string, now: number): boolean {
1313
1443
  let changed = false
@@ -1344,11 +1474,12 @@ export class HostTaskLedger {
1344
1474
  * members are all settled. The Host poll calls this on every tick, so a run
1345
1475
  * can no longer be left in the running column by a settle nobody observed:
1346
1476
  *
1347
- * - A team run is governed by its Lead. Once the Lead's own outcome is
1477
+ * - A stored team run is governed by its Lead. Once the Lead's own outcome is
1348
1478
  * recorded, its still-open members are settled with that verdict. A
1349
1479
  * teammate is a durable member of the Team and may never report a turn of
1350
- * its own, and without this the whole lineage waits on it forever.
1351
- * - A cascade parent whose members are all settled is finalized here even
1480
+ * its own, and without this the whole lineage waits on it forever. New runs
1481
+ * never start a team, so this only closes a group the ledger already holds.
1482
+ * - A stored group parent whose members are all settled is finalized here even
1352
1483
  * when the settle that completed the tree happened in another process, or
1353
1484
  * was interrupted between its child write and its parent write.
1354
1485
  *