@fish-under-sea/dsh-client-ui-task-board-fish 0.0.0-stage → 0.5.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 (165) hide show
  1. package/LICENSE +202 -0
  2. package/README.i18n.yaml +6 -0
  3. package/README.md +202 -2
  4. package/README.zh.md +203 -0
  5. package/cordis.patch.yml +12 -0
  6. package/icon.svg +3 -0
  7. package/lib/client.js +12941 -0
  8. package/lib/client.js.map +1 -0
  9. package/lib/index.js +10471 -0
  10. package/lib/types/client/PluginSettingsCard.d.ts +144 -0
  11. package/lib/types/client/TaskBoardSettingsCard.d.ts +92 -0
  12. package/lib/types/client/apply-guard.d.ts +25 -0
  13. package/lib/types/client/board/ClampedMarkdown.d.ts +3 -0
  14. package/lib/types/client/board/ConfirmDialog.d.ts +15 -0
  15. package/lib/types/client/board/EditTaskModal.d.ts +17 -0
  16. package/lib/types/client/board/LinkSubtaskModal.d.ts +14 -0
  17. package/lib/types/client/board/NewTaskModal.d.ts +26 -0
  18. package/lib/types/client/board/TagManagerModal.d.ts +26 -0
  19. package/lib/types/client/board/TaskBoard.d.ts +26 -0
  20. package/lib/types/client/board/TaskCard.d.ts +36 -0
  21. package/lib/types/client/board/TaskDetail.d.ts +9 -0
  22. package/lib/types/client/board/TaskForm.d.ts +72 -0
  23. package/lib/types/client/board/VerificationReport.d.ts +23 -0
  24. package/lib/types/client/board/card-view.d.ts +113 -0
  25. package/lib/types/client/board/icons.d.ts +32 -0
  26. package/lib/types/client/board/overlay.d.ts +69 -0
  27. package/lib/types/client/board/parse-model-pref.d.ts +4 -0
  28. package/lib/types/client/board/preset-label.d.ts +22 -0
  29. package/lib/types/client/board/status-key.d.ts +19 -0
  30. package/lib/types/client/board/task-markdown.d.ts +19 -0
  31. package/lib/types/client/host-api.d.ts +63 -0
  32. package/lib/types/client/index.d.ts +128 -0
  33. package/lib/types/client/locales.d.ts +443 -0
  34. package/lib/types/client/main-session.d.ts +32 -0
  35. package/lib/types/client/native-panel.d.ts +48 -0
  36. package/lib/types/client/plugin-card-seat.d.ts +108 -0
  37. package/lib/types/client/schedule-presets.d.ts +10 -0
  38. package/lib/types/client/schedule-zone.d.ts +97 -0
  39. package/lib/types/client/seats.d.ts +18 -0
  40. package/lib/types/client/service.d.ts +32 -0
  41. package/lib/types/client/settings-entry-form.d.ts +49 -0
  42. package/lib/types/client/settings-form.d.ts +213 -0
  43. package/lib/types/core/controller.d.ts +373 -0
  44. package/lib/types/core/degraded-reason.d.ts +46 -0
  45. package/lib/types/core/extension.d.ts +283 -0
  46. package/lib/types/core/freeze-snapshot.d.ts +71 -0
  47. package/lib/types/core/handover.d.ts +70 -0
  48. package/lib/types/core/issue-form.d.ts +16 -0
  49. package/lib/types/core/package-name.d.ts +9 -0
  50. package/lib/types/core/poll-cadence.d.ts +31 -0
  51. package/lib/types/core/schedule.d.ts +124 -0
  52. package/lib/types/core/session-reuse.d.ts +24 -0
  53. package/lib/types/core/store.d.ts +64 -0
  54. package/lib/types/core/subtask.d.ts +141 -0
  55. package/lib/types/core/tasks.d.ts +601 -0
  56. package/lib/types/core/use-cases/task-archive.d.ts +20 -0
  57. package/lib/types/core/use-cases/task-create.d.ts +27 -0
  58. package/lib/types/core/use-cases/task-delete.d.ts +27 -0
  59. package/lib/types/core/use-cases/task-parent.d.ts +21 -0
  60. package/lib/types/core/use-cases/task-schedule.d.ts +96 -0
  61. package/lib/types/core/use-cases/task-tag.d.ts +48 -0
  62. package/lib/types/core/use-cases/task-update.d.ts +56 -0
  63. package/lib/types/core/verification-budget.d.ts +52 -0
  64. package/lib/types/core/verification.d.ts +753 -0
  65. package/lib/types/core/workspace-target.d.ts +41 -0
  66. package/lib/types/dsh-home.d.ts +16 -0
  67. package/lib/types/host/agent-tools.d.ts +27 -0
  68. package/lib/types/host/extension-registry.d.ts +111 -0
  69. package/lib/types/host/llm-dispatch.d.ts +63 -0
  70. package/lib/types/host/verification-gate.d.ts +95 -0
  71. package/lib/types/host/verification-runner.d.ts +139 -0
  72. package/lib/types/host/workspace-evidence.d.ts +53 -0
  73. package/lib/types/host-ai.d.ts +51 -0
  74. package/lib/types/host-ledger.d.ts +385 -0
  75. package/lib/types/host-routes.d.ts +36 -0
  76. package/lib/types/host-runner.d.ts +252 -0
  77. package/lib/types/host-service.d.ts +379 -0
  78. package/lib/types/http.d.ts +59 -0
  79. package/lib/types/index.d.ts +322 -0
  80. package/lib/types/loopback.d.ts +24 -0
  81. package/lib/types/mount-once.d.ts +55 -0
  82. package/lib/types/power-inhibitor.d.ts +73 -0
  83. package/lib/types/protocol.d.ts +212 -0
  84. package/lib/types/tool-surface.d.ts +71 -0
  85. package/package.json +107 -4
  86. package/src/client/PluginSettingsCard.tsx +564 -0
  87. package/src/client/TaskBoardSettingsCard.tsx +539 -0
  88. package/src/client/apply-guard.ts +35 -0
  89. package/src/client/board/ClampedMarkdown.tsx +69 -0
  90. package/src/client/board/ConfirmDialog.tsx +44 -0
  91. package/src/client/board/EditTaskModal.tsx +110 -0
  92. package/src/client/board/LinkSubtaskModal.tsx +97 -0
  93. package/src/client/board/NewTaskModal.tsx +718 -0
  94. package/src/client/board/TagManagerModal.tsx +235 -0
  95. package/src/client/board/TaskBoard.tsx +558 -0
  96. package/src/client/board/TaskCard.tsx +315 -0
  97. package/src/client/board/TaskDetail.tsx +985 -0
  98. package/src/client/board/TaskForm.tsx +264 -0
  99. package/src/client/board/VerificationReport.tsx +322 -0
  100. package/src/client/board/card-view.ts +220 -0
  101. package/src/client/board/icons.tsx +89 -0
  102. package/src/client/board/overlay.tsx +189 -0
  103. package/src/client/board/parse-model-pref.ts +35 -0
  104. package/src/client/board/preset-label.ts +44 -0
  105. package/src/client/board/status-key.ts +41 -0
  106. package/src/client/board/task-markdown.module.css +137 -0
  107. package/src/client/board/task-markdown.tsx +106 -0
  108. package/src/client/board-settings.module.css +66 -0
  109. package/src/client/board.module.css +1837 -0
  110. package/src/client/css-modules.d.ts +5 -0
  111. package/src/client/host-api.ts +336 -0
  112. package/src/client/index.ts +501 -0
  113. package/src/client/locales.ts +905 -0
  114. package/src/client/main-session.ts +43 -0
  115. package/src/client/native-panel.tsx +140 -0
  116. package/src/client/plugin-card-seat.ts +199 -0
  117. package/src/client/schedule-presets.ts +13 -0
  118. package/src/client/schedule-zone.ts +233 -0
  119. package/src/client/seats.tsx +58 -0
  120. package/src/client/service.ts +94 -0
  121. package/src/client/settings-card.module.css +444 -0
  122. package/src/client/settings-entry-form.ts +142 -0
  123. package/src/client/settings-form.ts +468 -0
  124. package/src/core/controller.ts +871 -0
  125. package/src/core/degraded-reason.ts +81 -0
  126. package/src/core/extension.ts +376 -0
  127. package/src/core/freeze-snapshot.ts +213 -0
  128. package/src/core/handover.ts +132 -0
  129. package/src/core/issue-form.ts +19 -0
  130. package/src/core/package-name.ts +9 -0
  131. package/src/core/poll-cadence.ts +41 -0
  132. package/src/core/schedule.ts +363 -0
  133. package/src/core/session-reuse.ts +40 -0
  134. package/src/core/store.ts +371 -0
  135. package/src/core/subtask.ts +341 -0
  136. package/src/core/tasks.ts +843 -0
  137. package/src/core/use-cases/task-archive.ts +91 -0
  138. package/src/core/use-cases/task-create.ts +110 -0
  139. package/src/core/use-cases/task-delete.ts +43 -0
  140. package/src/core/use-cases/task-parent.ts +65 -0
  141. package/src/core/use-cases/task-schedule.ts +251 -0
  142. package/src/core/use-cases/task-tag.ts +110 -0
  143. package/src/core/use-cases/task-update.ts +126 -0
  144. package/src/core/verification-budget.ts +115 -0
  145. package/src/core/verification.ts +1594 -0
  146. package/src/core/workspace-target.ts +59 -0
  147. package/src/dsh-home.ts +42 -0
  148. package/src/host/agent-tools.ts +762 -0
  149. package/src/host/extension-registry.ts +509 -0
  150. package/src/host/llm-dispatch.ts +87 -0
  151. package/src/host/verification-gate.ts +487 -0
  152. package/src/host/verification-runner.ts +702 -0
  153. package/src/host/workspace-evidence.ts +176 -0
  154. package/src/host-ai.ts +158 -0
  155. package/src/host-ledger.ts +1826 -0
  156. package/src/host-routes.ts +306 -0
  157. package/src/host-runner.ts +755 -0
  158. package/src/host-service.ts +1112 -0
  159. package/src/http.ts +127 -0
  160. package/src/index.ts +722 -0
  161. package/src/loopback.ts +63 -0
  162. package/src/mount-once.ts +142 -0
  163. package/src/power-inhibitor.ts +321 -0
  164. package/src/protocol.ts +591 -0
  165. package/src/tool-surface.ts +95 -0
@@ -0,0 +1,91 @@
1
+ /**
2
+ * Archive/restore task use case: move a task off the main board and back,
3
+ * whatever its status but running. The task keeps its status, execution
4
+ * history, and transcript references, while archiving disarms any schedule so
5
+ * it cannot create more execution records until the user restores and
6
+ * re-enables it.
7
+ *
8
+ * Subtask trees move as a unit: archiving takes the whole subtree (an on-board
9
+ * subtask under an archived parent would be unreachable from its parent) and
10
+ * refuses the whole group while any member is running. Restoring brings the
11
+ * task, its ancestors and its subtree back together.
12
+ */
13
+ import { DEFAULT_SUBTASK_DEPTH, ancestorChain, descendantTasks, normalizeSubtaskDepth } from '../subtask.ts'
14
+ import type { TaskRecord } from '../tasks.ts'
15
+ import { ARCHIVABLE_STATUSES } from '../tasks.ts'
16
+
17
+ /** Result of an archive transition. */
18
+ export interface ArchiveTaskResult {
19
+ /** The next ledger. */
20
+ tasks: readonly TaskRecord[]
21
+ /** Whether the archive was applied (false = unknown task / not archivable). */
22
+ archived: boolean
23
+ }
24
+
25
+ /** The archive/restore id set: the task, its subtree, and (for restore) its ancestors. */
26
+ function groupIds(tasks: readonly TaskRecord[], id: string, maxSubtaskDepth: number, withAncestors: boolean): Set<string> {
27
+ const target = tasks.find(task => task.id === id)
28
+ const ids = new Set<string>([id])
29
+ for (const task of descendantTasks(tasks, id, normalizeSubtaskDepth(maxSubtaskDepth))) ids.add(task.id)
30
+ if (withAncestors && target !== undefined) {
31
+ for (const ancestor of ancestorChain(tasks, target)) ids.add(ancestor.id)
32
+ }
33
+ return ids
34
+ }
35
+
36
+ /**
37
+ * Archive one task and its subtasks: only a running member keeps the group on
38
+ * the board (its runner still owns its lifecycle until the execution settles);
39
+ * any other status can be archived. Archiving disarms schedules; an
40
+ * already-archived task is a no-op.
41
+ */
42
+ export function applyArchiveTask(
43
+ tasks: readonly TaskRecord[],
44
+ id: string,
45
+ now: number,
46
+ maxSubtaskDepth: number = DEFAULT_SUBTASK_DEPTH,
47
+ ): ArchiveTaskResult {
48
+ const target = tasks.find(task => task.id === id)
49
+ if (target === undefined || target.archivedAt !== undefined) return { tasks, archived: false }
50
+ const ids = groupIds(tasks, id, maxSubtaskDepth, false)
51
+ const declining = tasks.some(task => ids.has(task.id) && !(ARCHIVABLE_STATUSES as readonly string[]).includes(task.status))
52
+ if (declining) return { tasks, archived: false }
53
+ let applied = false
54
+ const next = tasks.map(task => {
55
+ if (!ids.has(task.id) || task.archivedAt !== undefined) return task
56
+ applied = true
57
+ const schedule = task.schedule === undefined
58
+ ? undefined
59
+ : { ...task.schedule, enabled: false, nextRunAt: undefined }
60
+ return {
61
+ ...task,
62
+ ...(schedule === undefined ? {} : { schedule }),
63
+ archivedAt: now,
64
+ updatedAt: now,
65
+ }
66
+ })
67
+ return { tasks: next, archived: applied }
68
+ }
69
+
70
+ /**
71
+ * Restore one task back onto the main board, together with its ancestors (an
72
+ * on-board subtask must not point at an archived parent) and its subtasks.
73
+ */
74
+ export function applyRestoreTask(
75
+ tasks: readonly TaskRecord[],
76
+ id: string,
77
+ now: number,
78
+ maxSubtaskDepth: number = DEFAULT_SUBTASK_DEPTH,
79
+ ): ArchiveTaskResult {
80
+ const target = tasks.find(task => task.id === id)
81
+ if (target === undefined || target.archivedAt === undefined) return { tasks, archived: false }
82
+ const ids = groupIds(tasks, id, maxSubtaskDepth, true)
83
+ let applied = false
84
+ const next = tasks.map(task => {
85
+ if (!ids.has(task.id) || task.archivedAt === undefined) return task
86
+ applied = true
87
+ const { archivedAt: _archived, ...rest } = task
88
+ return { ...rest, updatedAt: now }
89
+ })
90
+ return { tasks: next, archived: applied }
91
+ }
@@ -0,0 +1,110 @@
1
+ /**
2
+ * Create-task use case: mint a new task from user input, rejecting a blank
3
+ * title and any parent link the lineage gate refuses. Pure ledger transition
4
+ * (no persistence or notify - the controller orchestrates those), so it is
5
+ * unit-testable without any runtime face.
6
+ */
7
+ import { isValidCron, isValidTimeZone, nextRunAtMs, resolveHostTimeZone } from '../schedule.ts'
8
+ import { DEFAULT_SUBTASK_DEPTH, normalizeSubtaskDepth, taskDepth } from '../subtask.ts'
9
+ import { createTask, withSchedule, type NewTaskInput, type TaskRecord } from '../tasks.ts'
10
+
11
+ /** Result of a create transition: the new task (when accepted) + the next ledger. */
12
+ export interface CreateTaskResult {
13
+ /** The minted task, or undefined when the input was rejected. */
14
+ task: TaskRecord | undefined
15
+ /** The next ledger; identical reference when rejected. */
16
+ tasks: readonly TaskRecord[]
17
+ /** Why the input was rejected; absent when a task was minted. */
18
+ error?: string
19
+ }
20
+
21
+ /**
22
+ * Apply a create against the current ledger. Returns the new task and the
23
+ * appended ledger, or the unchanged ledger when the title is blank or the
24
+ * requested parent link is refused.
25
+ *
26
+ * A subtask inherits the execution targets its parent already pins (workspace,
27
+ * agent preset, permission, model) unless the form supplied its own; the
28
+ * parent human permission confirmation travels with an inherited permission,
29
+ * so a subtask of an already-confirmed elevated card is runnable at once.
30
+ * @param tasks - current ledger.
31
+ * @param input - raw user input (title/description/prompt + optional schedule/parent).
32
+ * @param now - clock instant (ms epoch).
33
+ * @param id - minted task id.
34
+ * @param maxSubtaskDepth - deployment subtask depth limit.
35
+ * @param hostTimeZone - zone a rule that stores no zone of its own follows.
36
+ */
37
+ export function applyCreateTask(
38
+ tasks: readonly TaskRecord[],
39
+ input: NewTaskInput,
40
+ now: number,
41
+ id: string,
42
+ maxSubtaskDepth: number = DEFAULT_SUBTASK_DEPTH,
43
+ hostTimeZone: string = resolveHostTimeZone(),
44
+ ): CreateTaskResult {
45
+ if (input.title.trim() === '') return { task: undefined, tasks, error: 'title is required' }
46
+ const limit = normalizeSubtaskDepth(maxSubtaskDepth)
47
+ let parent: TaskRecord | undefined
48
+ if (input.parentId !== undefined) {
49
+ parent = tasks.find(task => task.id === input.parentId)
50
+ if (parent === undefined) return { task: undefined, tasks, error: 'parent task not found' }
51
+ if (parent.archivedAt !== undefined) return { task: undefined, tasks, error: 'parent task is archived' }
52
+ if (taskDepth(tasks, parent.id) + 1 > limit) {
53
+ return { task: undefined, tasks, error: `subtask depth limit (${limit}) exceeded` }
54
+ }
55
+ }
56
+ // A subtask copies the execution targets its parent pins so the card shows
57
+ // what it will run with — EXCEPT the permission. A copied permission would
58
+ // also have to copy the parent's human confirmation to stay runnable, and the
59
+ // child would keep both after being detached: one confirmed parent would mint
60
+ // unbounded confirmed elevated roots. The permission is resolved live from the
61
+ // attached ancestors at launch instead (see core/subtask.ts), so detaching
62
+ // removes the inheritance by construction.
63
+ const effective: NewTaskInput = parent === undefined ? input : {
64
+ ...input,
65
+ workspaceId: input.workspaceId ?? parent.workspaceId,
66
+ mode: input.mode ?? parent.mode,
67
+ model: input.model ?? parent.model,
68
+ }
69
+ let task = createTask(effective, now, id)
70
+ // Arm the requested schedule (new-task dialog). The Host wire gate already
71
+ // rejects a malformed enabled plan; this arm re-checks it so a direct caller
72
+ // (a test or an embedder) cannot persist an unusable rule either.
73
+ const requested = input.schedule
74
+ if (requested?.enabled === true) {
75
+ const requestedZone = requested.timeZone
76
+ // An unusable zone is refused rather than silently reinterpreted as the
77
+ // Host zone: the caller asked for a specific wall clock.
78
+ if (requestedZone !== undefined && !isValidTimeZone(requestedZone)) {
79
+ return { task: undefined, tasks, error: 'invalid schedule time zone' }
80
+ }
81
+ if (requested.mode === 'once') {
82
+ const at = requested.at
83
+ if (at === undefined || !Number.isInteger(at) || at <= now) {
84
+ return { task: undefined, tasks, error: 'invalid schedule instant' }
85
+ }
86
+ task = withSchedule(task, {
87
+ enabled: true,
88
+ mode: 'once',
89
+ at,
90
+ timeZone: requestedZone,
91
+ nextRunAt: at,
92
+ runCount: 0,
93
+ }, now)
94
+ } else {
95
+ const cron = (requested.cron ?? '').trim()
96
+ if (cron !== '' && isValidCron(cron)) {
97
+ const maxRuns = requested.maxRuns
98
+ if (maxRuns !== undefined && (!Number.isInteger(maxRuns) || maxRuns < 1)) {
99
+ return { task: undefined, tasks, error: 'invalid schedule run cap' }
100
+ }
101
+ const zone = requestedZone ?? hostTimeZone
102
+ const nextRunAt = nextRunAtMs(cron, now, zone)
103
+ if (nextRunAt !== undefined) {
104
+ task = withSchedule(task, { enabled: true, mode: 'cron', cron, maxRuns, timeZone: requestedZone, nextRunAt, runCount: 0 }, now)
105
+ }
106
+ }
107
+ }
108
+ }
109
+ return { task, tasks: [...tasks, task] }
110
+ }
@@ -0,0 +1,43 @@
1
+ /**
2
+ * Delete-task use case: drop a task from the ledger and clear the selection
3
+ * when it pointed at the removed task. Pure ledger transition (no persistence
4
+ * or notify - the controller orchestrates those).
5
+ *
6
+ * A task that still has subtasks is refused: deleting the parent would leave
7
+ * dangling child links, and silently detaching (or cascading) the children is
8
+ * a data-loss decision the user must make explicitly.
9
+ */
10
+ import type { TaskRecord } from '../tasks.ts'
11
+
12
+ /** Result of a delete transition. */
13
+ export interface DeleteTaskResult {
14
+ /** The next ledger (the removed task absent). */
15
+ tasks: readonly TaskRecord[]
16
+ /** Whether the previous selection referenced the removed task. */
17
+ selectionCleared: boolean
18
+ /** True when the task still carries subtasks, so nothing was removed. */
19
+ blocked: boolean
20
+ }
21
+
22
+ /**
23
+ * Apply a delete across the ledger. The selection (a task id) is cleared when
24
+ * it matches the removed task, so the UI never lingers on a vanished detail.
25
+ * @param tasks - current ledger.
26
+ * @param selectedTaskId - the currently selected task id (may be undefined).
27
+ * @param id - the task to remove.
28
+ */
29
+ export function applyDeleteTask(
30
+ tasks: readonly TaskRecord[],
31
+ selectedTaskId: string | undefined,
32
+ id: string,
33
+ ): DeleteTaskResult {
34
+ if (tasks.some(task => task.parentId === id)) {
35
+ return { tasks, selectionCleared: false, blocked: true }
36
+ }
37
+ const next = tasks.filter(task => task.id !== id)
38
+ return {
39
+ tasks: next,
40
+ selectionCleared: selectedTaskId === id,
41
+ blocked: false,
42
+ }
43
+ }
@@ -0,0 +1,65 @@
1
+ /**
2
+ * Parent-link use case: attach an existing on-board task under another as a
3
+ * subtask, or detach it back to the root. The lineage gate is the same one
4
+ * creation uses (unknown or archived parent, self, cycle, depth), so the two
5
+ * ways into the tree cannot disagree. Pure ledger transition.
6
+ */
7
+ import { DEFAULT_SUBTASK_DEPTH, checkParentLink, normalizeSubtaskDepth, type ParentLinkRejection } from '../subtask.ts'
8
+ import type { TaskRecord } from '../tasks.ts'
9
+
10
+ /** Result of a parent-link transition. */
11
+ export interface SetParentResult {
12
+ /** The next ledger; the input reference when refused. */
13
+ tasks: readonly TaskRecord[]
14
+ /** Whether the link (or the detachment) was stored. */
15
+ applied: boolean
16
+ /** User-facing refusal reason; absent when applied. */
17
+ error?: string
18
+ }
19
+
20
+ /** Host error text per refusal reason (the wire carries the same strings). */
21
+ const REJECTION_TEXT: Record<ParentLinkRejection, string> = {
22
+ 'unknown-task': 'task not found',
23
+ 'unknown-parent': 'parent task not found',
24
+ 'archived-parent': 'parent task is archived',
25
+ 'self-parent': 'a task cannot be its own parent',
26
+ 'cycle': 'a task cannot be attached under its own subtask',
27
+ 'depth-exceeded': 'subtask depth limit exceeded',
28
+ }
29
+
30
+ /**
31
+ * Attach or detach one task. A null (or blank) parent detaches, which is always
32
+ * allowed for a known on-board task; attaching validates the whole chain so a
33
+ * cyclic or too-deep ledger can never be stored.
34
+ * @param tasks - current ledger.
35
+ * @param id - the task being moved.
36
+ * @param parentId - the new parent, or null to detach.
37
+ * @param now - clock instant (ms epoch).
38
+ * @param maxSubtaskDepth - deployment subtask depth limit.
39
+ */
40
+ export function applySetParent(
41
+ tasks: readonly TaskRecord[],
42
+ id: string,
43
+ parentId: string | null,
44
+ now: number,
45
+ maxSubtaskDepth: number = DEFAULT_SUBTASK_DEPTH,
46
+ ): SetParentResult {
47
+ const task = tasks.find(candidate => candidate.id === id)
48
+ if (task === undefined) return { tasks, applied: false, error: REJECTION_TEXT['unknown-task'] }
49
+ if (task.archivedAt !== undefined) return { tasks, applied: false, error: 'archived task is read-only' }
50
+ // A task with an open execution may be a participant of a running cascade.
51
+ // Moving it would break that group's parent walk and leave the parent card
52
+ // in the running column forever, so the link is frozen until it settles. The
53
+ // lock is the open execution: a card parked in 'running' by hand links freely.
54
+ if (task.executions.some(execution => execution.endedAt === undefined)) {
55
+ return { tasks, applied: false, error: 'running task cannot be re-parented' }
56
+ }
57
+ const check = checkParentLink(tasks, id, parentId, normalizeSubtaskDepth(maxSubtaskDepth))
58
+ if (!check.ok) return { tasks, applied: false, error: REJECTION_TEXT[check.reason ?? 'unknown-task'] }
59
+ const nextParentId = parentId === null || parentId === '' ? undefined : parentId
60
+ if (nextParentId === task.parentId) return { tasks: [...tasks], applied: true }
61
+ return {
62
+ tasks: tasks.map(candidate => candidate.id === id ? { ...candidate, parentId: nextParentId, updatedAt: now } : candidate),
63
+ applied: true,
64
+ }
65
+ }
@@ -0,0 +1,251 @@
1
+ /**
2
+ * Schedule use cases: arm/disarm a task's scheduling rule, and record what a
3
+ * due occurrence did to it. Pure ledger transitions (no persistence or notify
4
+ * — the controller orchestrates those). Validation and next-run computation
5
+ * live here, sharing the core cron parser (schedule.ts) and the withSchedule
6
+ * transition.
7
+ *
8
+ * A rule is either a recurring cron rule or a single planned instant, and
9
+ * either kind may be capped by a run budget. The counter (`runCount`) moves
10
+ * only when the Host actually opened an execution; a skipped occurrence
11
+ * (busy, unconfirmed permission, missed instant, unreachable plan) moves the
12
+ * rule without consuming its budget.
13
+ */
14
+ import { isValidCron, isValidTimeZone, nextRunAtMs } from '../schedule.ts'
15
+ import { withSchedule, type ScheduleMode, type ScheduleRule, type ScheduleStopReason, type TaskRecord } from '../tasks.ts'
16
+
17
+ /** Fields the schedule use case may change on a rule. */
18
+ export interface SetSchedulePatch {
19
+ enabled?: boolean
20
+ /** Which kind of plan to write; an absent key keeps the current mode. */
21
+ mode?: ScheduleMode
22
+ /** 5-field cron expression of a recurring rule. */
23
+ cron?: string
24
+ /** Planned instant of a one-shot rule (ms epoch). */
25
+ at?: number
26
+ /** IANA zone for the wall clock; `null` clears it back to the Host zone. */
27
+ timeZone?: string | null
28
+ /** Run cap of a recurring rule; `null` clears it back to unlimited. */
29
+ maxRuns?: number | null
30
+ }
31
+
32
+ /** Result of arming/disarming a rule. */
33
+ export interface SetScheduleResult {
34
+ /** The next ledger; unchanged reference when rejected. */
35
+ tasks: readonly TaskRecord[]
36
+ /** Whether the rule was applied (false on unknown task / invalid plan). */
37
+ applied: boolean
38
+ }
39
+
40
+ /**
41
+ * Set an on-board task's scheduling rule. An unknown or archived task, an
42
+ * unusable zone, a blank or invalid cron, a one-shot with no usable instant,
43
+ * a one-shot armed in the past, and a run cap that is not a positive integer
44
+ * are all rejected (state untouched). An enabled rule computes its next run
45
+ * instant immediately — a one-shot's next instant IS its planned instant — and
46
+ * a disabled rule carries none.
47
+ *
48
+ * Arming a rule that was not enabled, or switching its kind, starts a fresh
49
+ * budget: the run counter and any previous stop/skip record are cleared. Edits
50
+ * to a live rule (expression, zone, cap) keep the consumed count, so an
51
+ * already-spent budget can never silently reset and overrun.
52
+ * @param tasks - current ledger.
53
+ * @param id - the task to schedule.
54
+ * @param patch - rule fields to change (absent fields keep their current value).
55
+ * @param now - clock instant (ms epoch).
56
+ * @param hostTimeZone - zone a rule with no stored zone follows.
57
+ */
58
+ export function applySetSchedule(
59
+ tasks: readonly TaskRecord[],
60
+ id: string,
61
+ patch: SetSchedulePatch,
62
+ now: number,
63
+ hostTimeZone: string,
64
+ ): SetScheduleResult {
65
+ const task = tasks.find(candidate => candidate.id === id)
66
+ if (task === undefined || task.archivedAt !== undefined) return { tasks, applied: false }
67
+ const current = task.schedule
68
+ const mode: ScheduleMode = patch.mode ?? current?.mode ?? 'cron'
69
+ // An explicit null clears the stored zone; an absent key keeps it.
70
+ const timeZone = patch.timeZone === undefined ? current?.timeZone : patch.timeZone ?? undefined
71
+ if (timeZone !== undefined && !isValidTimeZone(timeZone)) return { tasks, applied: false }
72
+ const enabled = patch.enabled ?? current?.enabled ?? false
73
+ const restart = (enabled && current?.enabled !== true) || (current?.mode ?? 'cron') !== mode
74
+ const runCount = restart ? 0 : current?.runCount ?? 0
75
+ const effectiveZone = timeZone ?? hostTimeZone
76
+ const cleared = restart
77
+ ? { endedAt: undefined, endedReason: undefined, skippedAt: undefined, skippedReason: undefined }
78
+ : { endedAt: current?.endedAt, endedReason: current?.endedReason, skippedAt: current?.skippedAt, skippedReason: current?.skippedReason }
79
+
80
+ if (mode === 'once') {
81
+ const at = patch.at ?? current?.at
82
+ if (at === undefined || !Number.isInteger(at)) return { tasks, applied: false }
83
+ // A one-shot is armed for a FUTURE instant: re-arming one at or before
84
+ // "now" would fire on the next tick, which is not what the user chose. A
85
+ // disabled rule may keep a stored past instant as the record of its plan.
86
+ if (enabled && at <= now) return { tasks, applied: false }
87
+ return {
88
+ tasks: tasks.map(candidate => candidate.id !== id ? candidate : withSchedule(candidate, {
89
+ enabled,
90
+ mode: 'once',
91
+ at,
92
+ cron: undefined,
93
+ maxRuns: undefined,
94
+ timeZone: timeZone ?? undefined,
95
+ nextRunAt: enabled ? at : undefined,
96
+ runCount,
97
+ ...cleared,
98
+ }, now)),
99
+ applied: true,
100
+ }
101
+ }
102
+
103
+ const cron = (patch.cron ?? current?.cron ?? '').trim()
104
+ if (cron === '' || !isValidCron(cron)) return { tasks, applied: false }
105
+ // An absent key keeps the stored cap; an explicit null clears it (unlimited).
106
+ const maxRuns = ('maxRuns' in patch ? patch.maxRuns : current?.maxRuns) ?? undefined
107
+ if (maxRuns !== undefined && (!Number.isInteger(maxRuns) || maxRuns < 1)) return { tasks, applied: false }
108
+ const spent = maxRuns !== undefined && runCount >= maxRuns
109
+ const armed = enabled && !spent
110
+ const nextRunAt = armed ? nextRunAtMs(cron, now, effectiveZone) : undefined
111
+ if (armed && nextRunAt === undefined) return { tasks, applied: false }
112
+ // Lowering the cap below what the rule already ran ends it immediately
113
+ // instead of leaving an exhausted rule that would wait for a fire to die.
114
+ const exhausted = enabled && spent
115
+ return {
116
+ tasks: tasks.map(candidate => candidate.id !== id ? candidate : withSchedule(candidate, {
117
+ enabled: armed,
118
+ mode: 'cron',
119
+ cron,
120
+ at: undefined,
121
+ maxRuns,
122
+ timeZone: timeZone ?? undefined,
123
+ nextRunAt,
124
+ runCount,
125
+ ...(exhausted ? { endedAt: now, endedReason: 'limit' as const } : cleared),
126
+ }, now)),
127
+ applied: true,
128
+ }
129
+ }
130
+
131
+ /**
132
+ * Roll a task's schedule rule forward (legacy pure-controller seam): persist
133
+ * the next due instant and the trigger instant. No-op for tasks without a rule.
134
+ * @param tasks - current ledger.
135
+ * @param id - the task to roll forward.
136
+ * @param nextRunAt - next due instant (may be undefined to clear).
137
+ * @param lastTriggeredAt - the trigger instant of this run.
138
+ * @param now - clock instant (ms epoch).
139
+ */
140
+ export function applyScheduleNextRun(
141
+ tasks: readonly TaskRecord[],
142
+ id: string,
143
+ nextRunAt: number | undefined,
144
+ lastTriggeredAt: number | undefined,
145
+ now: number,
146
+ ): readonly TaskRecord[] {
147
+ return tasks.map(task =>
148
+ task.id === id && task.archivedAt === undefined && task.schedule !== undefined
149
+ ? withSchedule(task, { nextRunAt, lastTriggeredAt }, now)
150
+ : task)
151
+ }
152
+
153
+ /**
154
+ * The effect one due occurrence has on its rule, applied by the Host ledger.
155
+ */
156
+ export interface ScheduleProgress {
157
+ /** Executions this occurrence actually opened (0 or 1), added to the counter. */
158
+ consumed: number
159
+ /** Next due instant; absent stops the rule. */
160
+ nextRunAt?: number
161
+ /** Trigger instant recorded as `lastTriggeredAt` (a consumed run only). */
162
+ lastTriggeredAt?: number
163
+ /** Terminal reason when the rule stops itself (disarms it). */
164
+ endedReason?: ScheduleStopReason
165
+ /** Why this occurrence produced no run, when it did not. */
166
+ skippedReason?: ScheduleStopReason
167
+ }
168
+
169
+ /**
170
+ * Refund the one scheduled run an occurrence consumed before its launch failed
171
+ * without ever creating a session. Nothing ran, so the run budget is restored
172
+ * and the rule is left able to serve its next occurrence — a launch failure
173
+ * must never silently spend the user's limited budget.
174
+ *
175
+ * A recurring rule keeps its already-rolled-forward target; a fire that ended
176
+ * the rule at its cap (no target left) is restored and re-armed at the next
177
+ * occurrence, so a failed launch consumes nothing. A one-shot has no later
178
+ * occurrence, so it is left stopped with `launch-failed` and its run returned.
179
+ * A rule the user disabled in the meantime is not resurrected.
180
+ * @param tasks - current ledger.
181
+ * @param id - the task whose occurrence is being refunded.
182
+ * @param now - clock instant (ms epoch).
183
+ * @param hostTimeZone - zone a rule with no stored zone follows.
184
+ * @returns the next ledger.
185
+ */
186
+ export function applyScheduleRefund(
187
+ tasks: readonly TaskRecord[],
188
+ id: string,
189
+ now: number,
190
+ hostTimeZone: string,
191
+ ): readonly TaskRecord[] {
192
+ return tasks.map(task => {
193
+ if (task.id !== id || task.archivedAt !== undefined || task.schedule === undefined) return task
194
+ const rule = task.schedule
195
+ const runCount = Math.max(rule.runCount - 1, 0)
196
+ if (rule.mode === 'once') {
197
+ return withSchedule(task, {
198
+ enabled: false,
199
+ runCount,
200
+ nextRunAt: undefined,
201
+ endedAt: now,
202
+ endedReason: 'launch-failed',
203
+ skippedAt: undefined,
204
+ skippedReason: undefined,
205
+ }, now)
206
+ }
207
+ const refunded = withSchedule(task, {
208
+ runCount,
209
+ skippedAt: now,
210
+ skippedReason: 'launch-failed',
211
+ }, now)
212
+ // The fire already rolled the target forward; only a fire that spent its
213
+ // last run (target cleared, ended at the cap) needs to be restored.
214
+ if (rule.nextRunAt !== undefined || rule.endedReason !== 'limit') return refunded
215
+ const cron = rule.cron ?? ''
216
+ const next = cron === '' ? undefined : nextRunAtMs(cron, now, rule.timeZone ?? hostTimeZone)
217
+ return withSchedule(refunded, next === undefined
218
+ ? { enabled: false, endedAt: now, endedReason: 'no-target' }
219
+ : { enabled: true, nextRunAt: next, endedAt: undefined, endedReason: undefined }, now)
220
+ })
221
+ }
222
+
223
+ /**
224
+ * Record what a due occurrence did to a task's rule: advance the run counter
225
+ * by the executions it opened, set the next target (or stop the rule), and
226
+ * note a terminal reason or a skipped occurrence. Nothing is written for a
227
+ * task that has no rule or has been archived mid-tick.
228
+ * @param tasks - current ledger.
229
+ * @param id - the task whose rule fired.
230
+ * @param progress - the occurrence's effect.
231
+ * @param now - clock instant (ms epoch).
232
+ * @returns the next ledger.
233
+ */
234
+ export function applyScheduleProgress(
235
+ tasks: readonly TaskRecord[],
236
+ id: string,
237
+ progress: ScheduleProgress,
238
+ now: number,
239
+ ): readonly TaskRecord[] {
240
+ return tasks.map(task => {
241
+ if (task.id !== id || task.archivedAt !== undefined || task.schedule === undefined) return task
242
+ const patch: Partial<ScheduleRule> = {
243
+ runCount: task.schedule.runCount + progress.consumed,
244
+ nextRunAt: progress.nextRunAt,
245
+ ...(progress.lastTriggeredAt === undefined ? {} : { lastTriggeredAt: progress.lastTriggeredAt }),
246
+ ...(progress.endedReason === undefined ? {} : { enabled: false, endedAt: now, endedReason: progress.endedReason }),
247
+ ...(progress.skippedReason === undefined ? {} : { skippedAt: now, skippedReason: progress.skippedReason }),
248
+ }
249
+ return withSchedule(task, patch, now)
250
+ })
251
+ }
@@ -0,0 +1,110 @@
1
+ /**
2
+ * Label-management use cases (issue: labels could not be cleaned up).
3
+ *
4
+ * A label lives on every task that carries it, so renaming or removing one is a
5
+ * ledger-wide edit, not a task edit: the board's label row is the union of the
6
+ * labels in use, and without these two transitions a label created by an
7
+ * afternoon experiment stayed on the board forever.
8
+ *
9
+ * Both transitions are pure ledger rewrites (no persistence, no notify — the
10
+ * controller and the Host ledger orchestrate those), and both are idempotent:
11
+ * a label that no task carries changes nothing and reports no error for the
12
+ * delete path (the desired end state already holds), while a rename from an
13
+ * unknown label is refused so a stale tab cannot silently do nothing.
14
+ *
15
+ * Renaming onto a name that is already in use MERGES the two: a task carrying
16
+ * both keeps the row it already had (with its execution hint) and loses the
17
+ * duplicate, which is the only reading that cannot lose a hint the user typed.
18
+ */
19
+
20
+ import { TAG_NAME_MAX_LENGTH, collectKnownTags, normalizeTags, type TaskRecord, type TaskTag } from '../tasks.ts'
21
+
22
+ /** Outcome of one ledger-wide label edit. */
23
+ export interface TagEditResult {
24
+ /** The ledger after the edit, or the input unchanged when nothing applied. */
25
+ tasks: readonly TaskRecord[]
26
+ /** Whether any task actually changed (drives whether the caller persists). */
27
+ changed: boolean
28
+ /** Refusal reason; the ledger is unchanged when set. */
29
+ error?: string
30
+ }
31
+
32
+ /** Trim a label name the way creation does. */
33
+ function normalizeName(value: string): string {
34
+ return value.trim()
35
+ }
36
+
37
+ /** Whether any task in the ledger carries this label. */
38
+ function carries(tasks: readonly TaskRecord[], name: string): boolean {
39
+ return collectKnownTags(tasks).some(tag => tag.name === name)
40
+ }
41
+
42
+ /**
43
+ * Rename one label everywhere, merging into an existing label of the target
44
+ * name. Every touched task gets a fresh updatedAt; untouched tasks keep theirs.
45
+ * @param tasks - current ledger.
46
+ * @param from - the label to rename.
47
+ * @param to - the new name (an existing name merges the two labels).
48
+ * @param now - clock instant (ms epoch).
49
+ * @returns the rewritten ledger, or a refusal.
50
+ */
51
+ export function applyRenameTag(
52
+ tasks: readonly TaskRecord[],
53
+ from: string,
54
+ to: string,
55
+ now: number,
56
+ ): TagEditResult {
57
+ const source = normalizeName(from)
58
+ const target = normalizeName(to)
59
+ if (source === '') return { tasks, changed: false, error: 'a label name is required' }
60
+ if (target === '') return { tasks, changed: false, error: 'a label name is required' }
61
+ if (target.length > TAG_NAME_MAX_LENGTH) return { tasks, changed: false, error: 'label name is too long' }
62
+ if (source === target) return { tasks, changed: false }
63
+ if (!carries(tasks, source)) return { tasks, changed: false, error: 'label not found' }
64
+ let changed = false
65
+ const next = tasks.map(task => {
66
+ const tags = task.tags
67
+ if (tags === undefined || !tags.some(tag => tag.name === source)) return task
68
+ changed = true
69
+ // A task that already carried BOTH names keeps the target's own row — the
70
+ // target is the label that survives, so its execution hint stays the one
71
+ // that applies. A task carrying only the source keeps that row's hint under
72
+ // the new name.
73
+ const hasTarget = tags.some(tag => tag.name === target)
74
+ const merged: TaskTag[] = []
75
+ for (const tag of tags) {
76
+ if (hasTarget && tag.name === source) continue
77
+ const name = tag.name === source ? target : tag.name
78
+ if (merged.some(entry => entry.name === name)) continue
79
+ merged.push(name === tag.name ? tag : { ...tag, name })
80
+ }
81
+ return { ...task, tags: normalizeTags(merged), updatedAt: now }
82
+ })
83
+ return { tasks: changed ? next : tasks, changed }
84
+ }
85
+
86
+ /**
87
+ * Remove one label from every task that carries it. Archived cards are included:
88
+ * the board's label row draws from the whole ledger, so a label left on an
89
+ * archived card would come straight back into the filter.
90
+ * @param tasks - current ledger.
91
+ * @param name - the label to remove.
92
+ * @param now - clock instant (ms epoch).
93
+ * @returns the rewritten ledger.
94
+ */
95
+ export function applyDeleteTag(
96
+ tasks: readonly TaskRecord[],
97
+ name: string,
98
+ now: number,
99
+ ): TagEditResult {
100
+ const target = normalizeName(name)
101
+ if (target === '') return { tasks, changed: false, error: 'a label name is required' }
102
+ let changed = false
103
+ const next = tasks.map(task => {
104
+ const tags = task.tags
105
+ if (tags === undefined || !tags.some(tag => tag.name === target)) return task
106
+ changed = true
107
+ return { ...task, tags: normalizeTags(tags.filter(tag => tag.name !== target)), updatedAt: now }
108
+ })
109
+ return { tasks: changed ? next : tasks, changed }
110
+ }