@linxin666/dsh-client-ui-task-board 0.4.18 → 0.4.20

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 (46) hide show
  1. package/README.i18n.yaml +2 -2
  2. package/README.md +2 -2
  3. package/README.zh.md +2 -2
  4. package/lib/client.js +179 -60
  5. package/lib/client.js.map +1 -1
  6. package/lib/index.js +492 -74
  7. package/lib/types/client/board/TaskForm.d.ts +3 -1
  8. package/lib/types/client/index.d.ts +7 -1
  9. package/lib/types/client/native-panel.d.ts +1 -1
  10. package/lib/types/client/seats.d.ts +36 -2
  11. package/lib/types/client/settings-form.d.ts +2 -0
  12. package/lib/types/core/controller.d.ts +1 -1
  13. package/lib/types/core/extension.d.ts +135 -1
  14. package/lib/types/core/session-reuse.d.ts +46 -13
  15. package/lib/types/core/tasks.d.ts +2 -2
  16. package/lib/types/host/agent-tools.d.ts +7 -2
  17. package/lib/types/host/extension-registry.d.ts +30 -1
  18. package/lib/types/host-ledger.d.ts +86 -1
  19. package/lib/types/host-routes.d.ts +7 -1
  20. package/lib/types/host-runner.d.ts +20 -1
  21. package/lib/types/host-service.d.ts +59 -14
  22. package/lib/types/protocol.d.ts +9 -1
  23. package/package.json +26 -26
  24. package/src/client/board/ExecutionLog.tsx +9 -2
  25. package/src/client/board/NewTaskModal.tsx +88 -3
  26. package/src/client/board/TaskDetail.tsx +18 -11
  27. package/src/client/board/TaskForm.tsx +13 -2
  28. package/src/client/board.module.css +67 -1
  29. package/src/client/index.ts +3 -0
  30. package/src/client/locales.ts +7 -6
  31. package/src/client/native-panel.tsx +2 -1
  32. package/src/client/seats.tsx +32 -4
  33. package/src/client/service.ts +3 -0
  34. package/src/client/settings-form.ts +21 -2
  35. package/src/core/controller.ts +9 -3
  36. package/src/core/extension.ts +138 -1
  37. package/src/core/session-reuse.ts +58 -21
  38. package/src/core/tasks.ts +2 -2
  39. package/src/host/agent-tools.ts +8 -2
  40. package/src/host/extension-registry.ts +121 -2
  41. package/src/host-ledger.ts +252 -18
  42. package/src/host-routes.ts +30 -3
  43. package/src/host-runner.ts +44 -5
  44. package/src/host-service.ts +180 -37
  45. package/src/index.ts +28 -2
  46. package/src/protocol.ts +9 -1
@@ -26,6 +26,10 @@ import {
26
26
  type TaskBoardExtensionHost,
27
27
  type TaskBoardExtensionPayload,
28
28
  type TaskBoardIntegrationFace,
29
+ type TaskBoardLaunchContext,
30
+ type TaskBoardLaunchDecision,
31
+ type TaskBoardLaunchFace,
32
+ type TaskBoardLaunchHandler,
29
33
  type TaskBoardLinkedTask,
30
34
  type TaskBoardSessionsFace,
31
35
  type TaskBoardStatusChangedEvent,
@@ -82,6 +86,8 @@ export interface TaskBoardExtensionRegistryOptions {
82
86
  rework?: TaskBoardReworkApplier
83
87
  /** Resolve the deployment's tool registry; absent loses the tool surface only. */
84
88
  toolRegistry?: () => TaskBoardExtensionToolRegistry | undefined
89
+ /** Notified whenever a provider publishes, changes, or withdraws its summary. */
90
+ onPublished?: () => void
85
91
  now?: () => number
86
92
  uuid?: () => string
87
93
  logger?: TaskBoardExtensionLogger
@@ -99,6 +105,8 @@ interface RegistryEntry {
99
105
  readonly subscriptions: Record<keyof TaskBoardEventFace, Set<RegistryEventCallback>>
100
106
  /** Tool definitions the provider registered, with their live disposers. */
101
107
  tools: Array<{ definition: ToolDefinition; dispose?: () => void }>
108
+ /** Launch handlers this provider holds, in registration order. */
109
+ readonly launchHandlers: Set<TaskBoardLaunchHandler>
102
110
  published?: TaskBoardExtensionPayload
103
111
  }
104
112
 
@@ -176,6 +184,43 @@ function extensionText(value: string, what: string): string {
176
184
  return text
177
185
  }
178
186
 
187
+ /**
188
+ * Read one handler answer as a launch decision.
189
+ *
190
+ * A handler is provider code reached synchronously from the launch path, so its
191
+ * return value is judged here instead of trusted: anything the board cannot act
192
+ * on is reported and treated as "not mine", exactly like a throw. A local
193
+ * decision with a blank preamble is normalized to no preamble, so a provider
194
+ * that answers local to take no visible part changes nothing at all.
195
+ * @param answer - what the handler returned.
196
+ * @param warn - sink for a refusal the provider can read.
197
+ * @returns the decision to act on, or undefined.
198
+ */
199
+ function launchDecision(
200
+ answer: unknown,
201
+ warn: (message: string) => void,
202
+ ): TaskBoardLaunchDecision | undefined {
203
+ if (answer === undefined) return undefined
204
+ if (typeof answer !== 'object' || answer === null) {
205
+ warn('returned a non-object decision')
206
+ return undefined
207
+ }
208
+ const kind = (answer as { kind?: unknown }).kind
209
+ if (kind === 'external') return { kind: 'external' }
210
+ if (kind !== 'local') {
211
+ warn('returned an unknown decision kind')
212
+ return undefined
213
+ }
214
+ const preamble = (answer as { promptPreamble?: unknown }).promptPreamble
215
+ if (preamble === undefined) return { kind: 'local' }
216
+ if (typeof preamble !== 'string') {
217
+ warn('returned a non-string promptPreamble')
218
+ return undefined
219
+ }
220
+ const trimmed = preamble.trim()
221
+ return trimmed === '' ? { kind: 'local' } : { kind: 'local', promptPreamble: trimmed }
222
+ }
223
+
179
224
  /**
180
225
  * The session a follow-up message goes to, or the refusal that says why there
181
226
  * is none. The open execution owns the answer while one is running: delivering
@@ -208,6 +253,8 @@ export class TaskBoardExtensionRegistry {
208
253
  private readonly uuid: () => string
209
254
  private readonly logger: TaskBoardExtensionLogger
210
255
  private toolResolver: (() => TaskBoardExtensionToolRegistry | undefined) | undefined
256
+ private readonly onPublished: (() => void) | undefined
257
+ private publishedVersionCounter = 0
211
258
  /** Board master switch (enabled config); providers start only while it is on. */
212
259
  private boardEnabled = true
213
260
  private disposed = false
@@ -221,6 +268,12 @@ export class TaskBoardExtensionRegistry {
221
268
  this.uuid = options.uuid ?? (() => crypto.randomUUID())
222
269
  this.logger = options.logger ?? DEFAULT_LOGGER
223
270
  this.toolResolver = options.toolRegistry
271
+ this.onPublished = options.onPublished
272
+ }
273
+
274
+ /** Monotonic revision of the published extension summaries map. */
275
+ get publishedRevision(): number {
276
+ return this.publishedVersionCounter
224
277
  }
225
278
 
226
279
  /**
@@ -272,7 +325,7 @@ export class TaskBoardExtensionRegistry {
272
325
  this.logger.error('[dsh-task-board] ' + message)
273
326
  throw new TaskBoardExtensionError('api-version-mismatch', message)
274
327
  }
275
- const entry: RegistryEntry = { extension, active: false, subscriptions: emptySubscriptions(), tools: [] }
328
+ const entry: RegistryEntry = { extension, active: false, subscriptions: emptySubscriptions(), tools: [], launchHandlers: new Set() }
276
329
  this.entries.set(extension.id, entry)
277
330
  this.reconcile(entry)
278
331
  return () => { this.unregister(extension.id) }
@@ -305,6 +358,42 @@ export class TaskBoardExtensionRegistry {
305
358
  return await handler.call(entry.extension, request)
306
359
  }
307
360
 
361
+ /**
362
+ * The board's single launch gate: ask every running provider whether this run
363
+ * is theirs.
364
+ *
365
+ * Consulted by the ledger at the one point every trigger passes — before a
366
+ * session exists and before an execution record is written — so the order
367
+ * here is the only ordering a provider can observe: registration order, first
368
+ * decision wins. A handler that throws is isolated and treated as "not mine",
369
+ * exactly as if it had answered undefined, because a provider's bug must cost
370
+ * its own interception and never the launch. Without a registered handler
371
+ * this answers nothing at all and the launch path is untouched.
372
+ * @param task - the card about to run.
373
+ * @param context - which entry asked for this run.
374
+ * @returns the first decision a running provider made, or undefined.
375
+ */
376
+ interceptLaunch(task: TaskRecord, context: TaskBoardLaunchContext): TaskBoardLaunchDecision | undefined {
377
+ if (this.disposed) return undefined
378
+ for (const entry of this.entries.values()) {
379
+ if (!entry.active) continue
380
+ for (const handler of [...entry.launchHandlers]) {
381
+ let answer: unknown
382
+ try {
383
+ answer = handler(task, context)
384
+ } catch (error) {
385
+ this.logger.error(`[dsh-task-board] extension "${entry.extension.id}" launch handler failed; the launch proceeds unhandled`, error)
386
+ continue
387
+ }
388
+ const decision = launchDecision(answer, (message) => {
389
+ this.logger.warn(`[dsh-task-board] extension "${entry.extension.id}" launch handler ${message}; the launch proceeds unhandled`)
390
+ })
391
+ if (decision !== undefined) return decision
392
+ }
393
+ }
394
+ return undefined
395
+ }
396
+
308
397
  /** Published summaries of currently running providers, keyed by extension id. */
309
398
  published(): Record<string, TaskBoardExtensionPayload> {
310
399
  const result: Record<string, TaskBoardExtensionPayload> = {}
@@ -376,6 +465,7 @@ export class TaskBoardExtensionRegistry {
376
465
  }
377
466
 
378
467
  private stopEntry(entry: RegistryEntry): void {
468
+ const hadPublished = entry.published !== undefined
379
469
  if (entry.active) {
380
470
  entry.active = false
381
471
  for (const kind of Object.keys(entry.subscriptions) as Array<keyof TaskBoardEventFace>) {
@@ -387,10 +477,17 @@ export class TaskBoardExtensionRegistry {
387
477
  this.logger.error(`[dsh-task-board] extension "${entry.extension.id}" stop() failed`, error)
388
478
  }
389
479
  }
480
+ entry.published = undefined
390
481
  this.disposeTools(entry)
391
482
  // A stopped provider re-registers its tools from start(); keeping the old
392
- // definitions would double-register them on the next enable.
483
+ // definitions would double-register them on the next enable. Launch
484
+ // handlers go with them: a switched-off provider is never consulted.
393
485
  entry.tools.length = 0
486
+ entry.launchHandlers.clear()
487
+ if (hadPublished) {
488
+ this.publishedVersionCounter += 1
489
+ if (!this.disposed) this.onPublished?.()
490
+ }
394
491
  }
395
492
 
396
493
  /** (Re)register every buffered tool against the current tool registry. */
@@ -463,9 +560,16 @@ export class TaskBoardExtensionRegistry {
463
560
  onExecutionSettled: (callback) => subscribe('onExecutionSettled', callback as RegistryEventCallback),
464
561
  onTaskDeleted: (callback) => subscribe('onTaskDeleted', callback as RegistryEventCallback),
465
562
  }
563
+ const launch: TaskBoardLaunchFace = {
564
+ intercept: (handler) => {
565
+ assertActive('intercept a launch')
566
+ return this.addLaunchHandler(entry, handler)
567
+ },
568
+ }
466
569
  return {
467
570
  tasks,
468
571
  sessions,
572
+ launch,
469
573
  integration,
470
574
  events,
471
575
  publish: (summary) => { this.publish(entry, summary) },
@@ -634,6 +738,21 @@ export class TaskBoardExtensionRegistry {
634
738
  throw new TaskBoardExtensionError('invalid-payload', 'published summary must be a pure JSON object within the size limit')
635
739
  }
636
740
  entry.published = summary
741
+ this.publishedVersionCounter += 1
742
+ this.onPublished?.()
743
+ }
744
+
745
+ /**
746
+ * Hold one launch handler for a running provider. The handler is dropped when
747
+ * the provider stops or is unregistered, so the disposer only has to cover the
748
+ * provider's own early withdrawal.
749
+ */
750
+ private addLaunchHandler(entry: RegistryEntry, handler: TaskBoardLaunchHandler): () => void {
751
+ if (typeof handler !== 'function') {
752
+ throw new TaskBoardExtensionError('invalid-handler', 'a launch handler must be a function')
753
+ }
754
+ entry.launchHandlers.add(handler)
755
+ return () => { entry.launchHandlers.delete(handler) }
637
756
  }
638
757
 
639
758
  private registerTool(entry: RegistryEntry, definition: ToolDefinition): () => void {
@@ -1,6 +1,6 @@
1
1
  import { spawnSync } from 'node:child_process'
2
2
  import { createHash } from 'node:crypto'
3
- import { chmodSync, closeSync, existsSync, fsyncSync, mkdirSync, openSync, readdirSync, readFileSync, renameSync, statSync, unlinkSync, writeFileSync } from 'node:fs'
3
+ import { chmodSync, closeSync, existsSync, fsyncSync, mkdirSync, openSync, readdirSync, readFileSync, renameSync, statSync, unlinkSync, utimesSync, writeFileSync } from 'node:fs'
4
4
  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'
@@ -31,6 +31,7 @@ import { applyDeleteTag, applyRenameTag } from './core/use-cases/task-tag.ts'
31
31
  import { applyUpdateTask, canEditTaskContent, hasContentPatch } from './core/use-cases/task-update.ts'
32
32
  import { TASK_BOARD_MIGRATABLE_SCHEMA_VERSIONS, TASK_BOARD_SCHEMA_VERSION, TASK_BOARD_ZONE_STAMP_SCHEMA_VERSION, type TaskBoardAction, type TaskBoardSchedulerSnapshot } from './protocol.ts'
33
33
  import { DEFAULT_SESSION_PERMISSION, requiresPermissionConfirmation, type TaskPermission } from './core/handover.ts'
34
+ import type { TaskBoardLaunchDecision, TaskBoardLaunchHandler, TaskBoardLaunchTrigger } from './core/extension.ts'
34
35
 
35
36
  interface PersistedScheduler extends TaskBoardSchedulerSnapshot {
36
37
  importedSources?: string[]
@@ -74,6 +75,26 @@ function bindingRefusalMessage(
74
75
  export interface OpenedRun {
75
76
  task: TaskRecord
76
77
  execution: ExecutionRecord
78
+ /**
79
+ * The prompt preamble the launch gate asked for, injected ahead of the card's
80
+ * own prompt text. Present only when a provider answered `local` with one.
81
+ */
82
+ promptPreamble?: string
83
+ }
84
+
85
+ /**
86
+ * What one run-opening call produced.
87
+ *
88
+ * A call that opened a run writes its own commit, and so does an intercepted
89
+ * launch that only parked the card in the running column; a call that found
90
+ * nothing to do leaves the document for its caller, which is why the caller has
91
+ * to know the difference instead of guessing from an empty run list.
92
+ */
93
+ interface StartRunOutcome {
94
+ /** Executions the call opened; empty when no session will be created. */
95
+ runs: OpenedRun[]
96
+ /** Whether this call already committed its own write. */
97
+ committed: boolean
77
98
  }
78
99
 
79
100
  /**
@@ -357,9 +378,35 @@ const LEGACY_START_TOLERANCE_MS = 2000
357
378
  * live owner; only one that has been unreadable for longer than any write can
358
379
  * take is treated as an unclean-shutdown leftover (issue #1528: a 0-byte lock
359
380
  * kept the Host half from mounting until it was deleted by hand).
381
+ *
382
+ * The same window bounds the identity-unprobeable takeover below: it is two
383
+ * heartbeat intervals, so an owner that keeps beating is never mistaken for a
384
+ * leftover (issue #2061).
360
385
  */
361
386
  const UNREADABLE_LOCK_GRACE_MS = 60_000
362
387
 
388
+ /**
389
+ * How often the lock owner refreshes its lock file's mtime (issue #2061). The
390
+ * record itself never changes, only the timestamp moves, so a later start can
391
+ * tell a live owner from a hard-kill leftover even when the platform identity
392
+ * probe reads nothing (a protected process, a WMI/CIM timeout). Two missed
393
+ * beats age the lock past UNREADABLE_LOCK_GRACE_MS and make it reclaimable; a
394
+ * beating owner stays protected.
395
+ */
396
+ const LOCK_HEARTBEAT_MS = 30_000
397
+
398
+ /**
399
+ * The process identity reads the lock decision depends on. Injectable so the
400
+ * unprobeable-identity branch is testable on every platform without a real
401
+ * PowerShell/CIM round trip.
402
+ */
403
+ export interface LockProcessProbe {
404
+ isAlive(pid: number): boolean
405
+ startTimeMs(pid: number): number | undefined
406
+ }
407
+
408
+ const defaultLockProcessProbe: LockProcessProbe = { isAlive: processIsAlive, startTimeMs: processStartTimeMs }
409
+
363
410
  /** Whether the recorded start time proves the recorded PID is another process. */
364
411
  function startTimeMismatch(recorded: number, actual: number, exact: boolean): boolean {
365
412
  return exact ? recorded !== actual : Math.abs(recorded - actual) > LEGACY_START_TOLERANCE_MS
@@ -457,6 +504,10 @@ export class HostTaskLedger {
457
504
  private readonly requestCache = new Map<string, CachedRequest>()
458
505
  private readonly lockToken = crypto.randomUUID()
459
506
  private lockFd: number | undefined
507
+ private lockHeartbeat: ReturnType<typeof setInterval> | undefined
508
+ private readonly processProbe: LockProcessProbe
509
+ /** Warning sink; defaults to console.warn, tests inject a collector. */
510
+ private readonly warn: (message: string) => void
460
511
  readonly file: string
461
512
  readonly lockFile: string
462
513
  /** Small sidecar for the 30 s scheduler heartbeat (lastTickAt only). */
@@ -494,7 +545,18 @@ export class HostTaskLedger {
494
545
  /** Today's measured spend in tokens, or undefined when nothing can be measured. */
495
546
  private readonly spendUsed: (now: number) => number | undefined
496
547
 
497
- 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 } = {}) {
548
+ /**
549
+ * The board's launch gate, or undefined when no consumer is attached.
550
+ *
551
+ * The ledger is where every run is opened — the run actions, a due schedule,
552
+ * the run tool, a rework all arrive here — so this is the one point a run can
553
+ * be handed to someone else before an execution record exists. Installed by
554
+ * the Host service after construction, because the gate belongs to the
555
+ * extension registry that is built around this ledger.
556
+ */
557
+ private launchGate: TaskBoardLaunchHandler | undefined
558
+
559
+ 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; processProbe?: LockProcessProbe; warn?: (message: string) => void; launchGate?: TaskBoardLaunchHandler } = {}) {
498
560
  // Resolved before the load/repair passes below: they can evaluate the gate.
499
561
  const baseline = options.sessionDefaultPermission
500
562
  this.sessionDefault = typeof baseline === 'function' ? baseline : () => baseline ?? DEFAULT_SESSION_PERMISSION
@@ -502,12 +564,16 @@ export class HostTaskLedger {
502
564
  this.cardDefaults = options.cardDefaults ?? (() => ({}))
503
565
  this.spendBudget = options.spendBudgetTokens ?? (() => DEFAULT_SPEND_BUDGET_TOKENS)
504
566
  this.spendUsed = options.spendUsedToday ?? (now => usedTokensToday(now))
567
+ this.launchGate = options.launchGate
568
+ this.processProbe = options.processProbe ?? defaultLockProcessProbe
569
+ this.warn = options.warn ?? ((message) => { console.warn(message) })
505
570
  mkdirSync(dir, { recursive: true })
506
571
  this.file = join(dir, 'ledger-v2.json')
507
572
  this.lockFile = join(dir, 'ledger-v2.lock')
508
573
  this.schedulerFile = join(dir, 'scheduler-v2.json')
509
574
  this.cleanStaleTemporaryFiles(dir)
510
575
  this.lockFd = this.acquireLock()
576
+ this.startLockHeartbeat()
511
577
  try {
512
578
  this.document = this.load(dir)
513
579
  for (const request of this.document.recentRequests) {
@@ -545,6 +611,19 @@ export class HostTaskLedger {
545
611
  this.notify()
546
612
  }
547
613
 
614
+ /**
615
+ * Install the launch gate, or remove it with undefined.
616
+ *
617
+ * The Host service owns it: the board's extension registry is built around
618
+ * this ledger, so the gate is attached once that registry exists. A ledger
619
+ * with no gate — every ledger a test drives on its own — opens every run
620
+ * itself, exactly as it did before the seam existed.
621
+ * @param gate - the gate to consult before a run opens, or undefined.
622
+ */
623
+ setLaunchGate(gate: TaskBoardLaunchHandler | undefined): void {
624
+ this.launchGate = gate
625
+ }
626
+
548
627
  /** Remove leftover *.tmp-* files from previous crashes or interrupted writes. */
549
628
  private cleanStaleTemporaryFiles(dir: string): void {
550
629
  try {
@@ -674,7 +753,46 @@ export class HostTaskLedger {
674
753
  return () => { this.listeners.delete(listener) }
675
754
  }
676
755
 
756
+ /**
757
+ * Refresh the lock's mtime so a later start can distinguish a live owner from
758
+ * a hard-kill leftover without reading the process identity (issue #2061).
759
+ * Best-effort: a failed beat only ages the lock, and a record that no longer
760
+ * carries this owner's token stops the heartbeat instead of beating for
761
+ * whoever holds the lock now.
762
+ */
763
+ renewLock(): void {
764
+ if (this.lockFd === undefined) return
765
+ try {
766
+ const owner = JSON.parse(readFileSync(this.lockFile, 'utf8')) as { token?: unknown }
767
+ if (owner.token !== this.lockToken) {
768
+ // Another start took the ledger over. Stop beating for a lock that is
769
+ // not ours and say so once: an operator needs to know two hosts met.
770
+ this.warn(`[task-board] lost the ledger lock to another owner; this instance stops renewing ${this.lockFile}`)
771
+ this.stopLockHeartbeat()
772
+ return
773
+ }
774
+ const seconds = this.now() / 1000
775
+ utimesSync(this.lockFile, seconds, seconds)
776
+ } catch {
777
+ // A missing or unreadable lock is not ours to refresh.
778
+ }
779
+ }
780
+
781
+ private startLockHeartbeat(): void {
782
+ const timer = setInterval(() => { this.renewLock() }, LOCK_HEARTBEAT_MS)
783
+ // The beat must never keep a stopping Host alive.
784
+ timer.unref?.()
785
+ this.lockHeartbeat = timer
786
+ }
787
+
788
+ private stopLockHeartbeat(): void {
789
+ if (this.lockHeartbeat === undefined) return
790
+ clearInterval(this.lockHeartbeat)
791
+ this.lockHeartbeat = undefined
792
+ }
793
+
677
794
  dispose(): void {
795
+ this.stopLockHeartbeat()
678
796
  const fd = this.lockFd
679
797
  if (fd === undefined) return
680
798
  this.lockFd = undefined
@@ -691,6 +809,7 @@ export class HostTaskLedger {
691
809
  requestId: string,
692
810
  action: TaskBoardAction,
693
811
  initiator?: string,
812
+ trigger?: TaskBoardLaunchTrigger,
694
813
  ): { state: LedgerState; runs?: OpenedRun[] } {
695
814
  const fingerprint = createHash('sha256').update(JSON.stringify(action)).digest('hex')
696
815
  const cached = this.requestCache.get(requestId)
@@ -705,7 +824,7 @@ export class HostTaskLedger {
705
824
  while (this.requestCache.size > MAX_REQUEST_CACHE) this.requestCache.delete(this.requestCache.keys().next().value as string)
706
825
  this.syncRecentRequests()
707
826
  try {
708
- return this.apply(action, initiator)
827
+ return this.apply(action, initiator, trigger)
709
828
  } catch (error) {
710
829
  this.requestCache.delete(requestId)
711
830
  this.syncRecentRequests()
@@ -713,6 +832,26 @@ export class HostTaskLedger {
713
832
  }
714
833
  }
715
834
 
835
+ /**
836
+ * Open the run one due occurrence produced, with the occurrence's own progress
837
+ * written in the same commit.
838
+ *
839
+ * The occurrence is spent either way: a launch gate that hands the run to a
840
+ * provider still consumed this trigger, so the rule's budget advances here
841
+ * exactly as it does for a run the Host opens itself. A call that opened
842
+ * nothing commits the progress it recorded on its own, because the fire path
843
+ * has no other commit behind it.
844
+ * @param task - the card whose rule fired.
845
+ * @param triggeredAt - the instant the occurrence came due.
846
+ * @param progress - the rule's advance, recorded atomically with the launch.
847
+ * @returns the executions the occurrence opened.
848
+ */
849
+ private scheduledRun(task: TaskRecord, triggeredAt: number, progress: ScheduleProgress): OpenedRun[] {
850
+ const started = this.startRun(task, triggeredAt, undefined, false, progress, undefined, 'schedule')
851
+ if (!started.committed) this.commit()
852
+ return started.runs
853
+ }
854
+
716
855
  /**
717
856
  * Open the one run a due schedule triggers: an empty array means nothing ran
718
857
  * (already running, a card whose elevated permission is still unconfirmed, a
@@ -752,7 +891,7 @@ export class HostTaskLedger {
752
891
  this.skipOccurrence(taskId, 'permission', triggeredAt)
753
892
  return []
754
893
  }
755
- if (hasOpenExecution(task)) {
894
+ if (hasOpenExecution(task) || task.status === 'running') {
756
895
  this.skipOccurrence(taskId, 'busy', triggeredAt)
757
896
  return []
758
897
  }
@@ -771,7 +910,7 @@ export class HostTaskLedger {
771
910
  if (schedule.mode === 'once') {
772
911
  // The single planned instant is due: open its one run and stop the rule
773
912
  // in the same commit, so the budget can never produce a second one.
774
- return this.startRun(task, triggeredAt, undefined, false, {
913
+ return this.scheduledRun(task, triggeredAt, {
775
914
  consumed: 1,
776
915
  lastTriggeredAt: triggeredAt,
777
916
  endedReason: 'fired',
@@ -786,7 +925,7 @@ export class HostTaskLedger {
786
925
  const consumed = schedule.runCount + 1
787
926
  const budget = scheduleRunBudget(schedule)
788
927
  const spent = budget !== undefined && consumed >= budget
789
- return this.startRun(task, triggeredAt, undefined, false, {
928
+ return this.scheduledRun(task, triggeredAt, {
790
929
  consumed: 1,
791
930
  nextRunAt: spent ? undefined : next,
792
931
  lastTriggeredAt: triggeredAt,
@@ -1056,9 +1195,11 @@ export class HostTaskLedger {
1056
1195
  this.commit()
1057
1196
  }
1058
1197
 
1059
- private apply(action: TaskBoardAction, initiator?: string): { state: LedgerState; runs?: OpenedRun[] } {
1198
+ private apply(action: TaskBoardAction, initiator?: string, trigger?: TaskBoardLaunchTrigger): { state: LedgerState; runs?: OpenedRun[] } {
1060
1199
  const now = this.now()
1061
1200
  let runs: OpenedRun[] | undefined
1201
+ /** Whether the run path already committed this action's write. */
1202
+ let startCommitted = false
1062
1203
  switch (action.kind) {
1063
1204
  case 'import': {
1064
1205
  const sources = new Set(this.document.scheduler.importedSources ?? [])
@@ -1267,7 +1408,19 @@ export class HostTaskLedger {
1267
1408
  // unconfirmed as the parent would be without its own stamp.
1268
1409
  const refusal = this.bindingRefusal(task)
1269
1410
  if (refusal !== undefined) throw new Error(bindingRefusalMessage(refusal, this.sessionDefaultPermission, 'run'))
1270
- runs = this.startRun(task, now, initiator, action.kind !== 'run', undefined, rework)
1411
+ const started = this.startRun(
1412
+ task,
1413
+ now,
1414
+ initiator,
1415
+ action.kind !== 'run',
1416
+ undefined,
1417
+ rework,
1418
+ // A rework is the human entry point again, so only an explicit caller
1419
+ // hint (the run tool) and the rerun action name their own trigger.
1420
+ action.kind === 'run' ? trigger ?? 'manual' : action.kind === 'rerun' ? 'rerun' : 'manual',
1421
+ )
1422
+ runs = started.runs
1423
+ startCommitted = started.committed
1271
1424
  break
1272
1425
  }
1273
1426
  default: {
@@ -1280,9 +1433,10 @@ export class HostTaskLedger {
1280
1433
  throw new Error(`unknown task board action kind: ${String((action as { kind?: unknown }).kind)}`)
1281
1434
  }
1282
1435
  }
1283
- // startRun committed the opened execution itself; committing again here
1284
- // would bump the revision twice for one action.
1285
- if (runs === undefined || runs.length === 0) this.commit()
1436
+ // The run path commits a write of its own — the opened execution, or the
1437
+ // running column an intercepted launch parked the card in; committing again
1438
+ // here would bump the revision twice for one action.
1439
+ if (runs === undefined || !startCommitted) this.commit()
1286
1440
  return { state: this.state(), ...(runs === undefined ? {} : { runs }) }
1287
1441
  }
1288
1442
 
@@ -1369,6 +1523,15 @@ export class HostTaskLedger {
1369
1523
  * subagents inside this session), and the group id is what later lets the
1370
1524
  * settlement fold a HISTORICAL multi-member group it opened before this
1371
1525
  * behavior changed.
1526
+ *
1527
+ * This is also the launch gate: every entry that opens a run — the run and
1528
+ * rerun actions, a due schedule, the run tool, a rework — arrives here, which
1529
+ * makes it the only point where a provider can take a run over before an
1530
+ * execution record exists and before any session can be created. A gate that
1531
+ * answers `external` writes the running column instead of an execution and
1532
+ * nothing else: no session, no run record, no settlement. A gate that answers
1533
+ * `local` runs the card exactly as it would have, carrying the preamble the
1534
+ * provider asked for to the prompt.
1372
1535
  * @param root - the task the user ran.
1373
1536
  * @param now - clock instant (ms epoch).
1374
1537
  * @param initiator - the DSH session that asked for the run (audit only).
@@ -1378,12 +1541,39 @@ export class HostTaskLedger {
1378
1541
  * atomic commit that opened the execution.
1379
1542
  * @param rework - the reviewer's instructions, when this run redoes previous
1380
1543
  * work; recorded on the execution it opens.
1544
+ * @param trigger - which entry asked for this run, handed to the gate.
1381
1545
  */
1382
- private startRun(root: TaskRecord, now: number, initiator?: string, rerun = false, progress?: ScheduleProgress, rework?: ExecutionRework): OpenedRun[] {
1546
+ private startRun(
1547
+ root: TaskRecord,
1548
+ now: number,
1549
+ initiator?: string,
1550
+ rerun = false,
1551
+ progress?: ScheduleProgress,
1552
+ rework?: ExecutionRework,
1553
+ trigger: TaskBoardLaunchTrigger = 'manual',
1554
+ ): StartRunOutcome {
1383
1555
  const before = this.document.tasks
1384
1556
  const [participant] = cascadeTargets(before, root.id)
1385
- if (participant === undefined || participant.archivedAt !== undefined) return []
1386
- if (hasOpenExecution(participant)) return []
1557
+ if (participant === undefined || participant.archivedAt !== undefined) return { runs: [], committed: false }
1558
+ if (hasOpenExecution(participant)) return { runs: [], committed: false }
1559
+ // The gate is consulted on the card that would actually run, before the
1560
+ // document is touched: a decision to hand the run over is not a mutation
1561
+ // the ledger has to roll back.
1562
+ const decision: TaskBoardLaunchDecision | undefined = this.launchGate?.(participant, { trigger })
1563
+ if (decision?.kind === 'external') {
1564
+ // The provider runs this card outside the board. The Host writes no
1565
+ // execution record, so nothing here can be inspected, settled or
1566
+ // recovered as a run — only the column moves, which is already how the
1567
+ // board says work is under way without a tracked session. The provider
1568
+ // closes the card through `record-external-outcome` when its own run ends.
1569
+ let handed: readonly TaskRecord[] = before.map(task => task.id === participant.id
1570
+ ? withStatus(participant, 'running', now)
1571
+ : task)
1572
+ if (progress !== undefined) handed = applyScheduleProgress(handed, root.id, progress, now)
1573
+ this.document.tasks = [...handed]
1574
+ this.commit()
1575
+ return { runs: [], committed: true }
1576
+ }
1387
1577
  const groupId = crypto.randomUUID()
1388
1578
  const base = rerun ? withStatus(participant, 'todo', now) : participant
1389
1579
  const opened = startExecution(base, now, crypto.randomUUID(), initiator, groupId, rework)
@@ -1391,7 +1581,15 @@ export class HostTaskLedger {
1391
1581
  if (progress !== undefined) tasks = applyScheduleProgress(tasks, root.id, progress, now)
1392
1582
  this.document.tasks = [...tasks]
1393
1583
  this.commit()
1394
- return [{ task: resolveExecutionTargets(opened.task, before, this.maxSubtaskDepth), execution: opened.execution }]
1584
+ const preamble = decision?.kind === 'local' ? decision.promptPreamble : undefined
1585
+ return {
1586
+ runs: [{
1587
+ task: resolveExecutionTargets(opened.task, before, this.maxSubtaskDepth),
1588
+ execution: opened.execution,
1589
+ ...(preamble === undefined ? {} : { promptPreamble: preamble }),
1590
+ }],
1591
+ committed: true,
1592
+ }
1395
1593
  }
1396
1594
 
1397
1595
  /**
@@ -1794,6 +1992,28 @@ export class HostTaskLedger {
1794
1992
  for (const listener of [...this.listeners]) listener()
1795
1993
  }
1796
1994
 
1995
+ /**
1996
+ * Move an unidentifiable, heartbeat-aged lock aside instead of deleting it:
1997
+ * the record is the only evidence of which process held the ledger, and the
1998
+ * takeover is a judgment call an operator may need to audit (issue #2061).
1999
+ * A refused rename falls back to removal, because the takeover itself must
2000
+ * not depend on the filesystem allowing the rename.
2001
+ */
2002
+ private quarantineOrphanLock(pid: number, age: number): void {
2003
+ const orphan = `${this.lockFile}.orphan-${this.now()}`
2004
+ let kept = true
2005
+ try {
2006
+ renameSync(this.lockFile, orphan)
2007
+ } catch {
2008
+ kept = false
2009
+ try { unlinkSync(this.lockFile) } catch (unlinkError) {
2010
+ if ((unlinkError as NodeJS.ErrnoException).code !== 'ENOENT') throw unlinkError
2011
+ }
2012
+ }
2013
+ const seconds = Number.isFinite(age) ? `${Math.round(age / 1000)}s` : 'an unreadable age'
2014
+ this.warn(`[task-board] reclaimed the ledger lock of process ${pid}: its identity could not be probed and its heartbeat is ${seconds} old${kept ? `; the record was kept as ${orphan}` : ''}`)
2015
+ }
2016
+
1797
2017
  private acquireLock(): number {
1798
2018
  for (let attempt = 0; attempt < 2; attempt += 1) {
1799
2019
  try {
@@ -1836,8 +2056,8 @@ export class HostTaskLedger {
1836
2056
  }
1837
2057
  continue
1838
2058
  }
1839
- if (pid !== undefined && processIsAlive(pid)) {
1840
- const actualStartedAt = pid === process.pid ? ownProcessStartTimeMs() : processStartTimeMs(pid)
2059
+ if (pid !== undefined && this.processProbe.isAlive(pid)) {
2060
+ const actualStartedAt = pid === process.pid ? ownProcessStartTimeMs() : this.processProbe.startTimeMs(pid)
1841
2061
  // A reused PID is exposed when the live process identity no longer
1842
2062
  // matches the recorded one: either the recorded start time differs
1843
2063
  // beyond the probe's resolution (strict for ms-precise 'exact'
@@ -1853,13 +2073,27 @@ export class HostTaskLedger {
1853
2073
  try { return statSync(this.lockFile).mtimeMs < actualStartedAt } catch { return true }
1854
2074
  })()
1855
2075
  )
1856
- if (!staleReuse) {
2076
+ // A live PID whose identity cannot be read at all (a protected
2077
+ // process, a WMI/CIM timeout) used to fail closed forever, so a
2078
+ // hard-kill leftover whose PID was reused kept the Host half, and
2079
+ // every cron card with it, unmounted until someone deleted the lock
2080
+ // by hand (issue #2061). The owner's heartbeat is the second identity
2081
+ // source: a lock untouched for longer than two beats cannot belong to
2082
+ // a running owner, so it is quarantined and taken over. A fresh lock
2083
+ // still fails closed, and a confirmed live owner is never stolen from
2084
+ // however old its lock looks.
2085
+ const lockAge = (() => {
2086
+ try { return this.now() - statSync(this.lockFile).mtimeMs } catch { return Number.POSITIVE_INFINITY }
2087
+ })()
2088
+ const staleHeartbeat = actualStartedAt === undefined && lockAge >= UNREADABLE_LOCK_GRACE_MS
2089
+ if (!staleReuse && !staleHeartbeat) {
1857
2090
  const confirmedOwner = ownerStartedAt !== undefined && actualStartedAt !== undefined && !startTimeMismatch(ownerStartedAt, actualStartedAt, ownerExact)
1858
2091
  const hint = confirmedOwner
1859
2092
  ? ''
1860
2093
  : `; if this PID was reused after a crash and no other DSH host is running, remove ${this.lockFile} manually and retry`
1861
2094
  throw new Error(`task-board ledger is already owned by process ${pid}${hint}`, { cause: error })
1862
2095
  }
2096
+ if (staleHeartbeat && !staleReuse) this.quarantineOrphanLock(pid, lockAge)
1863
2097
  }
1864
2098
  try { unlinkSync(this.lockFile) } catch (unlinkError) {
1865
2099
  if ((unlinkError as NodeJS.ErrnoException).code !== 'ENOENT') throw unlinkError