dsh-taskboard 0.5.0 → 0.5.2

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 (50) hide show
  1. package/README.md +25 -1
  2. package/lib/client.js +242 -174
  3. package/lib/host/execution.js +80 -33
  4. package/lib/host/execution.js.map +1 -1
  5. package/lib/host/git.js +49 -5
  6. package/lib/host/git.js.map +1 -1
  7. package/lib/host/routes.js +180 -109
  8. package/lib/host/routes.js.map +1 -1
  9. package/lib/host/scheduler.js +50 -28
  10. package/lib/host/scheduler.js.map +1 -1
  11. package/lib/host/sdk.js +7 -2
  12. package/lib/host/sdk.js.map +1 -1
  13. package/lib/host/store.js +41 -8
  14. package/lib/host/store.js.map +1 -1
  15. package/lib/host/templates.js +10 -3
  16. package/lib/host/templates.js.map +1 -1
  17. package/lib/host/tools.js +124 -93
  18. package/lib/host/tools.js.map +1 -1
  19. package/lib/index.js +3 -1
  20. package/lib/index.js.map +1 -1
  21. package/lib/shared/api.js.map +1 -1
  22. package/lib/shared/protocol.js +23 -2
  23. package/lib/shared/protocol.js.map +1 -1
  24. package/package.json +3 -2
  25. package/src/client/api.ts +19 -9
  26. package/src/client/board/ImportModal.tsx +1 -1
  27. package/src/client/board/TaskBoard.tsx +7 -38
  28. package/src/client/board/TaskCard.tsx +3 -5
  29. package/src/client/board/TaskDetail.tsx +30 -21
  30. package/src/client/board/TaskFormModal.tsx +30 -23
  31. package/src/client/board/format.ts +26 -0
  32. package/src/client/board/labels.ts +44 -0
  33. package/src/client/board-mount.tsx +9 -6
  34. package/src/client/controller.ts +60 -13
  35. package/src/client/index.ts +7 -5
  36. package/src/client/sidebar-entry.ts +16 -5
  37. package/src/client/styles.ts +5 -3
  38. package/src/host/execution.ts +90 -16
  39. package/src/host/git.ts +39 -10
  40. package/src/host/routes.ts +227 -126
  41. package/src/host/scheduler.ts +62 -36
  42. package/src/host/sdk.ts +12 -1
  43. package/src/host/store.ts +53 -7
  44. package/src/host/templates.ts +12 -3
  45. package/src/host/tools.ts +180 -123
  46. package/src/index.ts +10 -1
  47. package/src/shared/api.ts +1 -1
  48. package/src/shared/protocol.ts +35 -1
  49. package/src/shared/version.ts +1 -1
  50. package/src/client/board/NewTaskModal.tsx +0 -8
@@ -119,10 +119,8 @@ function isErrorTurnEnd(data: unknown): { message: string } | undefined {
119
119
  const kind = (reason as { kind?: unknown }).kind
120
120
  if (kind !== 'error') return undefined
121
121
  const error = (reason as { error?: { message?: unknown } }).error
122
- const detail = JSON.stringify(error) ?? ''
123
122
  const message = typeof error?.message === 'string' ? error.message : 'turn failed'
124
- console.error('[dsh-taskboard] turn error detail:', detail.slice(0, 2000))
125
- void detail
123
+ console.error('[dsh-taskboard] turn error detail:', JSON.stringify(error)?.slice(0, 2000) ?? '')
126
124
  return { message }
127
125
  }
128
126
 
@@ -161,15 +159,32 @@ export class ExecutionService {
161
159
  /** Live executions by execution id (settles and cancels remove entries). */
162
160
  private readonly runs = new Map<string, RunEntry>()
163
161
 
162
+ /** Detaches the turn/end listener (plugin teardown — review P1). */
163
+ private readonly unsubscribeEvents: () => void
164
+
164
165
  /** @param deps - store + agents + workspaces + events + clock. */
165
166
  constructor(private readonly deps: ExecutionDeps) {
166
- deps.events.onSessionEvent((sessionId, event) => {
167
+ this.unsubscribeEvents = deps.events.onSessionEvent((sessionId, event) => {
167
168
  if (event.type !== 'turn/end') return
169
+ // S7 (open question): ANY turn/end with an error reason fails the whole
170
+ // execution and hands the task back. Whether the DSH session loop can
171
+ // produce recoverable per-turn errors (and keep the session alive) needs
172
+ // host-side confirmation; if it can, this should count consecutive
173
+ // errors or wait for an explicit termination signal instead.
168
174
  const failure = isErrorTurnEnd(event.data)
169
- if (failure !== undefined) this.noteFailure(sessionId, failure.message)
175
+ if (failure !== undefined) {
176
+ this.noteFailure(sessionId, failure.message).catch(error => {
177
+ console.error('[dsh-taskboard] failure settlement error:', error)
178
+ })
179
+ }
170
180
  })
171
181
  }
172
182
 
183
+ /** Detach the settlement listener; safe to call once at plugin teardown. */
184
+ dispose(): void {
185
+ this.unsubscribeEvents()
186
+ }
187
+
173
188
  /**
174
189
  * Best-effort evidence collection for a prepared run (fail-soft: undefined
175
190
  * on any git problem — settlement NEVER blocks on git).
@@ -195,13 +210,19 @@ export class ExecutionService {
195
210
  if (facts.diffStat !== undefined) execution.diffStat = facts.diffStat
196
211
  }
197
212
 
198
- /** Record a turn failure against the running execution of that session and give the task back. */
199
- private noteFailure(sessionId: string, message: string): void {
213
+ /**
214
+ * Record a turn failure against the running execution of that session and
215
+ * give the task back. Resolves once the failure settlement has COMMITTED —
216
+ * R2: the whenIdle rejection path awaits this (and only this) before
217
+ * releasing its run entry, so a success settlement can never race it into
218
+ * the ledger and record a failed run as succeeded.
219
+ */
220
+ private noteFailure(sessionId: string, message: string): Promise<void> {
200
221
  // The failed session may already have committed work — collect the
201
222
  // evidence (best effort) BEFORE marking the execution failed (0.3.1).
202
223
  const entry = [...this.runs.values()].find(e => e.sessionId === sessionId)
203
- void this.collectEvidence(entry?.prepared).then(facts => {
204
- void this.deps.store.mutate('execution-recorded', (ledger) => {
224
+ return this.collectEvidence(entry?.prepared).then(facts =>
225
+ this.deps.store.mutate('execution-recorded', (ledger) => {
205
226
  for (const task of ledger.tasks) {
206
227
  for (const execution of task.executions) {
207
228
  if (execution.sessionId === sessionId && execution.outcome === 'running') {
@@ -229,16 +250,22 @@ export class ExecutionService {
229
250
  }
230
251
  }
231
252
  return undefined
232
- })
233
- })
253
+ }),
254
+ ).then(() => { /* failure settlement committed */ })
234
255
  }
235
256
 
236
- /** Patch one task's execution record in the ledger. */
257
+ /**
258
+ * Patch one task's execution record in the ledger. R3 depth: a record that
259
+ * already settled (cancelled/failed/succeeded) is never resurrected — the
260
+ * startup path patches sessionId long after the gate opened, and a cancel
261
+ * may have committed in between.
262
+ */
237
263
  private async patchExecution(executionId: string, patch: Partial<ExecutionRecord>): Promise<void> {
238
264
  await this.deps.store.mutate('execution-recorded', (ledger) => {
239
265
  for (const task of ledger.tasks) {
240
266
  const execution = task.executions.find(e => e.id === executionId)
241
267
  if (execution !== undefined) {
268
+ if (execution.outcome !== 'running') return undefined
242
269
  Object.assign(execution, patch)
243
270
  return [task]
244
271
  }
@@ -296,6 +323,14 @@ export class ExecutionService {
296
323
  gate = 'task is already in progress'
297
324
  return undefined
298
325
  }
326
+ // S4: authoritative capacity check INSIDE the gate — counts ledger-wide
327
+ // running executions, immune to the startup window (`runs` registers
328
+ // only after agent creation, seconds later).
329
+ const running = ledger.tasks.reduce((n, t) => n + t.executions.filter(e => e.outcome === 'running').length, 0)
330
+ if (running >= max) {
331
+ gate = `execution concurrency limit reached (${running}/${max} running)`
332
+ return undefined
333
+ }
299
334
  target.executions.push({
300
335
  id: executionId,
301
336
  trigger,
@@ -305,7 +340,7 @@ export class ExecutionService {
305
340
  })
306
341
  target.status = 'in_progress'
307
342
  target.updatedAt = this.deps.now()
308
- target.updatedBy = { kind: 'user' }
343
+ target.updatedBy = { kind: 'system' }
309
344
  target.claimedBy = sessionId
310
345
  target.claimedAt = this.deps.now()
311
346
  return [target]
@@ -354,6 +389,10 @@ export class ExecutionService {
354
389
  const message = error instanceof Error ? error.message : String(error)
355
390
  await this.patchExecution(executionId, { outcome: 'failed', error: `preset 组合失败:${message.slice(0, 400)}`, endedAt: this.deps.now() })
356
391
  await this.revertProgress(taskId)
392
+ // S1: a run that never started must not leave its worktree behind.
393
+ if (prepared !== undefined && this.deps.git !== undefined) {
394
+ try { await this.deps.git.removeWorktree(workspace.path, prepared.worktreePath) } catch { /* best effort (dirty worktrees are kept) */ }
395
+ }
357
396
  return { ok: false, error: `preset composition failed: ${message}` }
358
397
  }
359
398
  let handle: Awaited<ReturnType<AgentsFace['create']>>
@@ -372,9 +411,31 @@ export class ExecutionService {
372
411
  const message = error instanceof Error ? error.message : String(error)
373
412
  await this.patchExecution(executionId, { outcome: 'failed', error: message.slice(0, 500), endedAt: this.deps.now() })
374
413
  await this.revertProgress(taskId)
414
+ // S1: a run that never started must not leave its worktree behind.
415
+ if (prepared !== undefined && this.deps.git !== undefined) {
416
+ try { await this.deps.git.removeWorktree(workspace.path, prepared.worktreePath) } catch { /* best effort (dirty worktrees are kept) */ }
417
+ }
375
418
  return { ok: false, error: message }
376
419
  }
377
420
 
421
+ // R3: the startup path above awaited seconds of git + agent work. A
422
+ // cancel() that landed inside that window already settled the execution
423
+ // (cancelled + task back to todo) — with nothing registered in `runs`,
424
+ // it could not dispose the agent this path was about to create. Re-verify
425
+ // INSIDE the queue (after any enqueued cancel committed) BEFORE injecting:
426
+ // a cancelled card must not gain a zombie session that burns tokens and
427
+ // edits files while the task sits in todo, re-runnable by anyone.
428
+ const stillRunning = await this.deps.store.read(ledger =>
429
+ ledger.tasks.some(t => t.executions.some(e => e.id === executionId && e.outcome === 'running')))
430
+ if (!stillRunning) {
431
+ await handle.dispose().catch(() => { /* best effort */ })
432
+ // S1: do not leave the startup artifacts behind a cancelled run either.
433
+ if (prepared !== undefined && this.deps.git !== undefined) {
434
+ try { await this.deps.git.removeWorktree(workspace.path, prepared.worktreePath) } catch { /* best effort */ }
435
+ }
436
+ return { ok: false, error: 'cancelled during startup' }
437
+ }
438
+
378
439
  // 3. Attach the session to the workspace (GUI project session list).
379
440
  await this.deps.workspaces.attach(task.workspaceId, sessionId).catch(() => { /* cosmetic */ })
380
441
 
@@ -418,9 +479,16 @@ export class ExecutionService {
418
479
  void this.settleExecution(executionId, sessionId, prepared)
419
480
  }
420
481
  this.runs.set(executionId, { sessionId, ...(prepared !== undefined ? { prepared } : {}), settle, dispose: () => handle.dispose() })
482
+ // R2: the rejection path owns its state transition EXCLUSIVELY — the old
483
+ // code also called settle() here, racing two evidence collections whose
484
+ // mutations both checked outcome === 'running': whoever committed first
485
+ // won, so a run that never reached quiescence could be recorded as
486
+ // succeeded (and auto-moved to in_review). Now only the failure
487
+ // settlement writes, and the run entry is released after it commits.
421
488
  void handle.agent.whenIdle().then(settle, () => {
422
489
  this.noteFailure(sessionId, 'agent did not reach quiescence')
423
- settle()
490
+ .then(() => { this.runs.delete(executionId) })
491
+ .catch(() => { this.runs.delete(executionId) })
424
492
  })
425
493
 
426
494
  return { ok: true, executionId, sessionId }
@@ -461,7 +529,7 @@ export class ExecutionService {
461
529
  })
462
530
  t.status = 'in_review'
463
531
  t.updatedAt = now
464
- t.updatedBy = { kind: 'user' }
532
+ t.updatedBy = { kind: 'system' }
465
533
  }
466
534
  return [t]
467
535
  }
@@ -554,11 +622,13 @@ export class ExecutionService {
554
622
  // The cancelled session may already have committed work — keep the
555
623
  // evidence (best effort) so the user can inspect or 续跑 (0.3.1).
556
624
  const facts = await this.collectEvidence(entry?.prepared)
625
+ let settled = false
557
626
  await this.deps.store.mutate('execution-recorded', (ledger) => {
558
627
  const target = ledger.tasks.find(t => t.id === taskId)
559
628
  if (target === undefined) return undefined
560
629
  const execution = target.executions.find(e => e.id === running.id)
561
630
  if (execution === undefined || execution.outcome !== 'running') return undefined
631
+ settled = true
562
632
  execution.outcome = 'cancelled'
563
633
  execution.endedAt = this.deps.now()
564
634
  this.applyFacts(execution, facts)
@@ -570,6 +640,10 @@ export class ExecutionService {
570
640
  }
571
641
  return [target]
572
642
  })
643
+ // The execution may have settled (succeeded/failed) between the stale
644
+ // read above and this mutation — a no-op cancel must NOT report success
645
+ // (the GUI used to show 取消成功 for an already-succeeded run, review P1).
646
+ if (!settled) return { ok: false, error: 'execution already settled' }
573
647
  return { ok: true, executionId: running.id }
574
648
  }
575
649
 
@@ -656,7 +730,7 @@ export class ExecutionService {
656
730
  const lastExec = [...task.executions].reverse().find(e => e.outcome !== 'running')
657
731
  const lastExecText = lastExec === undefined
658
732
  ? '(无)'
659
- : `${lastExec.trigger} · ${lastExec.outcome}${lastExec.error !== undefined ? ` · ${lastExec.error.slice(0, 200)}` : ''} · ${new Date(lastExec.startedAt ?? 0).toISOString()}`
733
+ : `${lastExec.trigger} · ${lastExec.outcome}${lastExec.error !== undefined ? ` · ${lastExec.error.slice(0, 200)}` : ''} · ${lastExec.startedAt !== undefined ? new Date(lastExec.startedAt).toISOString() : '?'}`
660
734
  const lastCommentsText = task.comments.slice(-3)
661
735
  .map(c => `[${c.threadId !== undefined ? 'agent' : 'user'}] ${c.body}`)
662
736
  .join('\n') || '(无)'
package/src/host/git.ts CHANGED
@@ -22,7 +22,8 @@
22
22
  *
23
23
  * @module dsh-taskboard/host/git
24
24
  */
25
- import type { CommitInfo } from '../shared/protocol.ts'
25
+ import { resolve } from 'node:path'
26
+ import { isValidTaskId, type CommitInfo } from '../shared/protocol.ts'
26
27
 
27
28
  /** Timeout for quick read-only queries (rev-parse / status / log / diff). */
28
29
  const QUICK_TIMEOUT_MS = 2_000
@@ -123,8 +124,12 @@ export interface GitFace {
123
124
  merge(root: string, branch: string): Promise<void>
124
125
  /** Whether `branch` is already an ancestor of HEAD (a merge would be a no-op). */
125
126
  isAncestor(root: string, branch: string): Promise<boolean>
126
- /** Remove a worktree; THROWS when it still has uncommitted changes. */
127
- removeWorktree(root: string, worktreePath: string): Promise<void>
127
+ /**
128
+ * Remove a worktree. Resolves 'removed' on success, 'unregistered' when git
129
+ * no longer knows the path (an orphaned directory). THROWS when it still
130
+ * has uncommitted changes, or on any other git failure (readable reason).
131
+ */
132
+ removeWorktree(root: string, worktreePath: string): Promise<'removed' | 'unregistered'>
128
133
  /** Delete a branch; THROWS (e.g. still checked out in a worktree). */
129
134
  deleteBranch(root: string, branch: string): Promise<void>
130
135
  /**
@@ -162,8 +167,16 @@ export function sanitizeBranchName(title: string, taskId: string): string {
162
167
  return head.length === 0 ? `task/${taskId}` : `task/${head}+${taskId}`
163
168
  }
164
169
 
165
- /** The canonical worktree path of a task inside its workspace (forward slashes). */
170
+ /**
171
+ * The canonical worktree path of a task inside its workspace (forward
172
+ * slashes). R4②: the id is validated HERE so every present and future call
173
+ * site is covered — a traversal-shaped id must never ride into a filesystem
174
+ * path (the cleanup/purge flows `rm -rf` what this returns).
175
+ */
166
176
  export function worktreePathOf(workspacePath: string, taskId: string): string {
177
+ if (!isValidTaskId(taskId)) {
178
+ throw new Error(`Error: invalid_input: illegal task id ${JSON.stringify(taskId.slice(0, 40))}`)
179
+ }
167
180
  const root = workspacePath.replace(/[\\/]+$/, '').replaceAll('\\', '/')
168
181
  return `${root}/${WORKTREE_DIR}/${taskId}`
169
182
  }
@@ -219,10 +232,15 @@ export function createGitFace(exec: ExecFn = realExec): GitFace {
219
232
  // worktree's own HEAD so evidence covers only the new run.
220
233
  if (mode === 'reuse') {
221
234
  const wtHead = await quick(['rev-parse', 'HEAD'], path)
222
- if (wtHead.ok && wtHead.stdout.trim().length > 0) {
235
+ // S14: a readable HEAD is not enough — the worktree must be on OUR
236
+ // branch, otherwise a user-created repo at the path would be silently
237
+ // taken over. Foreign or detached → fall through to fresh preparation.
238
+ const wtBranch = wtHead.ok ? await quick(['rev-parse', '--abbrev-ref', 'HEAD'], path) : undefined
239
+ if (wtHead.ok && wtHead.stdout.trim().length > 0
240
+ && wtBranch !== undefined && wtBranch.ok && wtBranch.stdout.trim() === branch) {
223
241
  return { path, branch, baseCommit: wtHead.stdout.trim(), reused: true }
224
242
  }
225
- // No live worktree → fall through to a fresh preparation.
243
+ // No live worktree on our branch → fall through to a fresh preparation.
226
244
  }
227
245
 
228
246
  // Baseline: the main worktree's current HEAD (also validates the repo).
@@ -302,7 +320,8 @@ export function createGitFace(exec: ExecFn = realExec): GitFace {
302
320
  return path !== WORKTREE_DIR && !path.startsWith(`${WORKTREE_DIR}/`)
303
321
  })
304
322
  if (dirtyLines.length > 0) {
305
- throw new Error(`主工作区有 ${dirtyLines.length} 处未提交修改,请先提交或暂存后再合并`)
323
+ // Machine-readable tag: callers classify without parsing zh-CN text.
324
+ throw Object.assign(new Error(`主工作区有 ${dirtyLines.length} 处未提交修改,请先提交或暂存后再合并`), { code: 'dirty-tree' })
306
325
  }
307
326
  }
308
327
  const merged = await heavy(['merge', '--no-ff', '--no-edit', branch], root)
@@ -320,14 +339,24 @@ export function createGitFace(exec: ExecFn = realExec): GitFace {
320
339
  return r.ok
321
340
  },
322
341
 
323
- removeWorktree: (root, worktreePath) => withRootLock(root, async () => {
342
+ removeWorktree: (root, worktreePath) => withRootLock(root, async (): Promise<'removed' | 'unregistered'> => {
324
343
  const status = await quick(['status', '--porcelain'], worktreePath)
325
344
  if (status.ok && status.stdout.trim().length > 0) {
326
345
  const lines = status.stdout.split('\n').map(l => l.trim()).filter(l => l.length > 0)
327
- throw new Error(`worktree ${lines.length} 处未提交修改,拒绝删除:\n${lines.slice(0, 10).join('\n')}`)
346
+ // Machine-readable tag: purge flows classify without parsing zh-CN text.
347
+ throw Object.assign(new Error(`worktree 有 ${lines.length} 处未提交修改,拒绝删除:\n${lines.slice(0, 10).join('\n')}`), { code: 'dirty-worktree' })
328
348
  }
329
349
  const removed = await heavy(['worktree', 'remove', worktreePath], root)
330
- if (!removed.ok) throw new Error(`删除 worktree 失败:${(removed.stderr.trim() || removed.stdout.trim()).slice(0, 300)}`)
350
+ if (removed.ok) return 'removed'
351
+ // S3: classify the failure WITHOUT parsing git's (localizable) stderr —
352
+ // a path absent from `worktree list` is an unregistered leftover, not
353
+ // an error the caller should relay verbatim.
354
+ const list = await quick(['worktree', 'list', '--porcelain'], root)
355
+ const registered = list.ok && list.stdout.split('\n')
356
+ .some(l => l.startsWith('worktree ')
357
+ && resolve(l.slice('worktree '.length).trim()).toLowerCase() === resolve(worktreePath).toLowerCase())
358
+ if (!registered) return 'unregistered'
359
+ throw new Error(`删除 worktree 失败:${(removed.stderr.trim() || removed.stdout.trim()).slice(0, 300)}`)
331
360
  }),
332
361
 
333
362
  deleteBranch: (root, branch) => withRootLock(root, async () => {