@linxin666/dsh-client-ui-task-board 0.4.19 → 0.4.21

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 (45) hide show
  1. package/README.i18n.yaml +2 -2
  2. package/README.md +1 -1
  3. package/README.zh.md +1 -1
  4. package/lib/client.js +190 -63
  5. package/lib/client.js.map +1 -1
  6. package/lib/index.js +599 -95
  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 +160 -1
  14. package/lib/types/core/session-reuse.d.ts +46 -13
  15. package/lib/types/core/tasks.d.ts +16 -5
  16. package/lib/types/host/agent-tools.d.ts +12 -2
  17. package/lib/types/host/extension-registry.d.ts +38 -1
  18. package/lib/types/host-ledger.d.ts +86 -1
  19. package/lib/types/host-runner.d.ts +20 -1
  20. package/lib/types/host-service.d.ts +64 -15
  21. package/lib/types/protocol.d.ts +18 -1
  22. package/package.json +1 -1
  23. package/src/client/board/ExecutionLog.tsx +15 -2
  24. package/src/client/board/NewTaskModal.tsx +88 -3
  25. package/src/client/board/TaskDetail.tsx +18 -11
  26. package/src/client/board/TaskForm.tsx +13 -2
  27. package/src/client/board.module.css +67 -1
  28. package/src/client/index.ts +3 -0
  29. package/src/client/locales.ts +7 -6
  30. package/src/client/native-panel.tsx +2 -1
  31. package/src/client/seats.tsx +32 -4
  32. package/src/client/service.ts +3 -0
  33. package/src/client/settings-form.ts +21 -2
  34. package/src/core/controller.ts +9 -3
  35. package/src/core/execution-summary.ts +3 -2
  36. package/src/core/extension.ts +159 -1
  37. package/src/core/session-reuse.ts +58 -21
  38. package/src/core/store.ts +2 -0
  39. package/src/core/tasks.ts +16 -5
  40. package/src/host/agent-tools.ts +70 -17
  41. package/src/host/extension-registry.ts +157 -2
  42. package/src/host-ledger.ts +274 -23
  43. package/src/host-runner.ts +44 -5
  44. package/src/host-service.ts +190 -37
  45. package/src/protocol.ts +37 -3
@@ -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 ?? [])
@@ -1165,15 +1306,26 @@ export class HostTaskLedger {
1165
1306
  // terminal verdict over it. This is also what keeps a stale report from
1166
1307
  // racing the session it claims to have replaced.
1167
1308
  if (hasOpenExecution(task)) throw new Error('running task cannot receive an external outcome')
1309
+ // A caller-chosen id must stay unique in the history: a duplicate would
1310
+ // make one handle name two attempts.
1311
+ if (action.executionId !== undefined && task.executions.some(entry => entry.id === action.executionId)) {
1312
+ throw new Error('execution id already recorded')
1313
+ }
1314
+ const succeeded = action.result === 'succeeded'
1168
1315
  const execution: ExecutionRecord = {
1169
- // A fresh id, exactly like a Host-launched run: the external work is a
1170
- // new attempt in the history, never an overwrite of an earlier record.
1171
- id: crypto.randomUUID(),
1316
+ // A fresh id unless the provider handed one out at launch: the external
1317
+ // work is a new attempt in the history, never an overwrite.
1318
+ id: action.executionId ?? crypto.randomUUID(),
1172
1319
  sessionId: undefined,
1173
- startedAt: now,
1320
+ startedAt: action.startedAt === undefined ? now : Math.min(action.startedAt, now),
1174
1321
  endedAt: now,
1175
1322
  result: action.result,
1176
- error: action.summary,
1323
+ // The two texts never share a field: a conclusion is a summary and only
1324
+ // a failure is an error.
1325
+ error: succeeded ? undefined : action.summary,
1326
+ ...(succeeded || action.errorCode === undefined ? {} : { errorCode: action.errorCode }),
1327
+ ...(succeeded || action.retryHint === undefined ? {} : { retryHint: action.retryHint }),
1328
+ ...(succeeded && action.summary !== undefined ? { summary: { text: action.summary } } : {}),
1177
1329
  initiatedBy: action.initiatedBy,
1178
1330
  external: true,
1179
1331
  }
@@ -1267,7 +1419,19 @@ export class HostTaskLedger {
1267
1419
  // unconfirmed as the parent would be without its own stamp.
1268
1420
  const refusal = this.bindingRefusal(task)
1269
1421
  if (refusal !== undefined) throw new Error(bindingRefusalMessage(refusal, this.sessionDefaultPermission, 'run'))
1270
- runs = this.startRun(task, now, initiator, action.kind !== 'run', undefined, rework)
1422
+ const started = this.startRun(
1423
+ task,
1424
+ now,
1425
+ initiator,
1426
+ action.kind !== 'run',
1427
+ undefined,
1428
+ rework,
1429
+ // A rework is the human entry point again, so only an explicit caller
1430
+ // hint (the run tool) and the rerun action name their own trigger.
1431
+ action.kind === 'run' ? trigger ?? 'manual' : action.kind === 'rerun' ? 'rerun' : 'manual',
1432
+ )
1433
+ runs = started.runs
1434
+ startCommitted = started.committed
1271
1435
  break
1272
1436
  }
1273
1437
  default: {
@@ -1280,9 +1444,10 @@ export class HostTaskLedger {
1280
1444
  throw new Error(`unknown task board action kind: ${String((action as { kind?: unknown }).kind)}`)
1281
1445
  }
1282
1446
  }
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()
1447
+ // The run path commits a write of its own — the opened execution, or the
1448
+ // running column an intercepted launch parked the card in; committing again
1449
+ // here would bump the revision twice for one action.
1450
+ if (runs === undefined || !startCommitted) this.commit()
1286
1451
  return { state: this.state(), ...(runs === undefined ? {} : { runs }) }
1287
1452
  }
1288
1453
 
@@ -1369,6 +1534,15 @@ export class HostTaskLedger {
1369
1534
  * subagents inside this session), and the group id is what later lets the
1370
1535
  * settlement fold a HISTORICAL multi-member group it opened before this
1371
1536
  * behavior changed.
1537
+ *
1538
+ * This is also the launch gate: every entry that opens a run — the run and
1539
+ * rerun actions, a due schedule, the run tool, a rework — arrives here, which
1540
+ * makes it the only point where a provider can take a run over before an
1541
+ * execution record exists and before any session can be created. A gate that
1542
+ * answers `external` writes the running column instead of an execution and
1543
+ * nothing else: no session, no run record, no settlement. A gate that answers
1544
+ * `local` runs the card exactly as it would have, carrying the preamble the
1545
+ * provider asked for to the prompt.
1372
1546
  * @param root - the task the user ran.
1373
1547
  * @param now - clock instant (ms epoch).
1374
1548
  * @param initiator - the DSH session that asked for the run (audit only).
@@ -1378,12 +1552,45 @@ export class HostTaskLedger {
1378
1552
  * atomic commit that opened the execution.
1379
1553
  * @param rework - the reviewer's instructions, when this run redoes previous
1380
1554
  * work; recorded on the execution it opens.
1555
+ * @param trigger - which entry asked for this run, handed to the gate.
1381
1556
  */
1382
- private startRun(root: TaskRecord, now: number, initiator?: string, rerun = false, progress?: ScheduleProgress, rework?: ExecutionRework): OpenedRun[] {
1557
+ private startRun(
1558
+ root: TaskRecord,
1559
+ now: number,
1560
+ initiator?: string,
1561
+ rerun = false,
1562
+ progress?: ScheduleProgress,
1563
+ rework?: ExecutionRework,
1564
+ trigger: TaskBoardLaunchTrigger = 'manual',
1565
+ ): StartRunOutcome {
1383
1566
  const before = this.document.tasks
1384
1567
  const [participant] = cascadeTargets(before, root.id)
1385
- if (participant === undefined || participant.archivedAt !== undefined) return []
1386
- if (hasOpenExecution(participant)) return []
1568
+ if (participant === undefined || participant.archivedAt !== undefined) return { runs: [], committed: false }
1569
+ if (hasOpenExecution(participant)) return { runs: [], committed: false }
1570
+ // The gate is consulted on the card that would actually run, before the
1571
+ // document is touched: a decision to hand the run over is not a mutation
1572
+ // the ledger has to roll back.
1573
+ const decision: TaskBoardLaunchDecision | undefined = this.launchGate?.(participant, { trigger })
1574
+ if (decision?.kind === 'refuse') {
1575
+ // A scheduled occurrence has no caller to answer, so it is skipped like an
1576
+ // open execution; every other entry hears the provider's own code.
1577
+ if (progress !== undefined) return { runs: [], committed: false }
1578
+ throw new Error(`${decision.code}: ${decision.reason}`)
1579
+ }
1580
+ if (decision?.kind === 'external') {
1581
+ // The provider runs this card outside the board. The Host writes no
1582
+ // execution record, so nothing here can be inspected, settled or
1583
+ // recovered as a run — only the column moves, which is already how the
1584
+ // board says work is under way without a tracked session. The provider
1585
+ // closes the card through `record-external-outcome` when its own run ends.
1586
+ let handed: readonly TaskRecord[] = before.map(task => task.id === participant.id
1587
+ ? withStatus(participant, 'running', now)
1588
+ : task)
1589
+ if (progress !== undefined) handed = applyScheduleProgress(handed, root.id, progress, now)
1590
+ this.document.tasks = [...handed]
1591
+ this.commit()
1592
+ return { runs: [], committed: true }
1593
+ }
1387
1594
  const groupId = crypto.randomUUID()
1388
1595
  const base = rerun ? withStatus(participant, 'todo', now) : participant
1389
1596
  const opened = startExecution(base, now, crypto.randomUUID(), initiator, groupId, rework)
@@ -1391,7 +1598,15 @@ export class HostTaskLedger {
1391
1598
  if (progress !== undefined) tasks = applyScheduleProgress(tasks, root.id, progress, now)
1392
1599
  this.document.tasks = [...tasks]
1393
1600
  this.commit()
1394
- return [{ task: resolveExecutionTargets(opened.task, before, this.maxSubtaskDepth), execution: opened.execution }]
1601
+ const preamble = decision?.kind === 'local' ? decision.promptPreamble : undefined
1602
+ return {
1603
+ runs: [{
1604
+ task: resolveExecutionTargets(opened.task, before, this.maxSubtaskDepth),
1605
+ execution: opened.execution,
1606
+ ...(preamble === undefined ? {} : { promptPreamble: preamble }),
1607
+ }],
1608
+ committed: true,
1609
+ }
1395
1610
  }
1396
1611
 
1397
1612
  /**
@@ -1794,6 +2009,28 @@ export class HostTaskLedger {
1794
2009
  for (const listener of [...this.listeners]) listener()
1795
2010
  }
1796
2011
 
2012
+ /**
2013
+ * Move an unidentifiable, heartbeat-aged lock aside instead of deleting it:
2014
+ * the record is the only evidence of which process held the ledger, and the
2015
+ * takeover is a judgment call an operator may need to audit (issue #2061).
2016
+ * A refused rename falls back to removal, because the takeover itself must
2017
+ * not depend on the filesystem allowing the rename.
2018
+ */
2019
+ private quarantineOrphanLock(pid: number, age: number): void {
2020
+ const orphan = `${this.lockFile}.orphan-${this.now()}`
2021
+ let kept = true
2022
+ try {
2023
+ renameSync(this.lockFile, orphan)
2024
+ } catch {
2025
+ kept = false
2026
+ try { unlinkSync(this.lockFile) } catch (unlinkError) {
2027
+ if ((unlinkError as NodeJS.ErrnoException).code !== 'ENOENT') throw unlinkError
2028
+ }
2029
+ }
2030
+ const seconds = Number.isFinite(age) ? `${Math.round(age / 1000)}s` : 'an unreadable age'
2031
+ 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}` : ''}`)
2032
+ }
2033
+
1797
2034
  private acquireLock(): number {
1798
2035
  for (let attempt = 0; attempt < 2; attempt += 1) {
1799
2036
  try {
@@ -1836,8 +2073,8 @@ export class HostTaskLedger {
1836
2073
  }
1837
2074
  continue
1838
2075
  }
1839
- if (pid !== undefined && processIsAlive(pid)) {
1840
- const actualStartedAt = pid === process.pid ? ownProcessStartTimeMs() : processStartTimeMs(pid)
2076
+ if (pid !== undefined && this.processProbe.isAlive(pid)) {
2077
+ const actualStartedAt = pid === process.pid ? ownProcessStartTimeMs() : this.processProbe.startTimeMs(pid)
1841
2078
  // A reused PID is exposed when the live process identity no longer
1842
2079
  // matches the recorded one: either the recorded start time differs
1843
2080
  // beyond the probe's resolution (strict for ms-precise 'exact'
@@ -1853,13 +2090,27 @@ export class HostTaskLedger {
1853
2090
  try { return statSync(this.lockFile).mtimeMs < actualStartedAt } catch { return true }
1854
2091
  })()
1855
2092
  )
1856
- if (!staleReuse) {
2093
+ // A live PID whose identity cannot be read at all (a protected
2094
+ // process, a WMI/CIM timeout) used to fail closed forever, so a
2095
+ // hard-kill leftover whose PID was reused kept the Host half, and
2096
+ // every cron card with it, unmounted until someone deleted the lock
2097
+ // by hand (issue #2061). The owner's heartbeat is the second identity
2098
+ // source: a lock untouched for longer than two beats cannot belong to
2099
+ // a running owner, so it is quarantined and taken over. A fresh lock
2100
+ // still fails closed, and a confirmed live owner is never stolen from
2101
+ // however old its lock looks.
2102
+ const lockAge = (() => {
2103
+ try { return this.now() - statSync(this.lockFile).mtimeMs } catch { return Number.POSITIVE_INFINITY }
2104
+ })()
2105
+ const staleHeartbeat = actualStartedAt === undefined && lockAge >= UNREADABLE_LOCK_GRACE_MS
2106
+ if (!staleReuse && !staleHeartbeat) {
1857
2107
  const confirmedOwner = ownerStartedAt !== undefined && actualStartedAt !== undefined && !startTimeMismatch(ownerStartedAt, actualStartedAt, ownerExact)
1858
2108
  const hint = confirmedOwner
1859
2109
  ? ''
1860
2110
  : `; if this PID was reused after a crash and no other DSH host is running, remove ${this.lockFile} manually and retry`
1861
2111
  throw new Error(`task-board ledger is already owned by process ${pid}${hint}`, { cause: error })
1862
2112
  }
2113
+ if (staleHeartbeat && !staleReuse) this.quarantineOrphanLock(pid, lockAge)
1863
2114
  }
1864
2115
  try { unlinkSync(this.lockFile) } catch (unlinkError) {
1865
2116
  if ((unlinkError as NodeJS.ErrnoException).code !== 'ENOENT') throw unlinkError
@@ -22,10 +22,21 @@ import { executionSummaryOf } from './core/execution-summary.ts'
22
22
 
23
23
  /**
24
24
  * Host services needed to validate a task's workspace before creating a
25
- * session, and to resolve the workspace an unpinned card runs in.
25
+ * session, resolve the workspace an unpinned card runs in, and tell a reusable
26
+ * conversation apart from an archived one.
26
27
  */
27
28
  export interface TaskBoardWorkspaceRegistry {
28
29
  list(): readonly Workspace[]
30
+ /**
31
+ * The registry-global archive set, in archive order (issue #2068). A Session
32
+ * in it cannot run a turn, so the reuse rule refuses it and the launch starts
33
+ * a fresh conversation instead of settling as `blocked`.
34
+ *
35
+ * Optional: a deployment whose registry face does not report an archive set
36
+ * offers no archive action to defend against, and reuse keeps its
37
+ * pre-archive-set behavior.
38
+ */
39
+ archivedSessionIds?: readonly string[]
29
40
  }
30
41
 
31
42
  /**
@@ -224,6 +235,14 @@ export interface PromptDescendant {
224
235
 
225
236
  /** Execution-shape context appended to the launched task's prompt. */
226
237
  export interface PromptContext {
238
+ /**
239
+ * The launch gate's section: what a provider that kept this run local needs
240
+ * the session to know before it reads the card. Injected on the same path as
241
+ * the tag prefixes and ahead of them, so it opens the prompt. Absent on every
242
+ * run nobody intercepted, which is what keeps the prompt byte-for-byte what
243
+ * it was before the seam existed.
244
+ */
245
+ launchPreamble?: string
227
246
  /**
228
247
  * The card's outstanding descendants. Present exactly when this run is an
229
248
  * autonomous dispatch: the Host opens no session for them, so this session
@@ -311,9 +330,13 @@ export function promptText(task: TaskRecord, context: PromptContext = {}): strin
311
330
  const handoverPreamble = handover === undefined || handover.references.length === 0
312
331
  ? undefined
313
332
  : `交接包引用(来自任务看板续接卡片,冻结于 ${new Date(handover.bundledAt).toISOString()}):\n${handover.references.map(reference => `- ${reference}`).join('\n')}`
314
- // Tag prompts come first: they are the run's standing context (business line,
315
- // output location), the handover preamble is a per-card note, the scheduled
316
- // section states why this run exists, and the task body is the instruction.
333
+ // The launch gate's section comes first (it states what this run is), then the
334
+ // tag prompts, which are the run's standing context (business line, output
335
+ // location); the handover preamble is a per-card note, the scheduled section
336
+ // states why this run exists, and the task body is the instruction.
337
+ // The launch gate's section opens the prompt: it states what this run IS
338
+ // before the board says anything about it.
339
+ const launchPreamble = launchPromptPreamble(context)
317
340
  const tagPreamble = tagPromptPreamble(task)
318
341
  // The attachment section names the readable paths of the card's files. It
319
342
  // is a section of its own, never folded into the handover preamble.
@@ -324,7 +347,7 @@ export function promptText(task: TaskRecord, context: PromptContext = {}): strin
324
347
  // The rework section sits last: it is the most specific instruction of this
325
348
  // run and therefore the one read immediately before the card body.
326
349
  const reworkSection = reworkPromptPreamble(context)
327
- const preambles = [tagPreamble, attachmentSection, handoverSection, schedulePreamble, runPreamble, reworkSection]
350
+ const preambles = [launchPreamble, tagPreamble, attachmentSection, handoverSection, schedulePreamble, runPreamble, reworkSection]
328
351
  .filter((part): part is string => part !== undefined)
329
352
  const preamble = preambles.length === 0 ? undefined : preambles.join('\n\n')
330
353
  const freeze = task.freeze
@@ -336,6 +359,22 @@ export function promptText(task: TaskRecord, context: PromptContext = {}): strin
336
359
  return preamble === undefined ? declaration : `${preamble}\n\n${declaration}`
337
360
  }
338
361
 
362
+ /**
363
+ * Build the launch-gate section of the execution prompt.
364
+ *
365
+ * A provider that answered `local` keeps the board's own execution and only
366
+ * adds context for it, so its text is a preamble like the tag prompts: same
367
+ * injection path, same placement rules, and the same delimiter neutralization —
368
+ * a preamble a provider composed from card text can therefore not counterfeit
369
+ * the freeze wrap either. A blank preamble yields undefined and the prompt is
370
+ * exactly what an unintercepted run produces.
371
+ */
372
+ function launchPromptPreamble(context: PromptContext): string | undefined {
373
+ const preamble = context.launchPreamble?.trim()
374
+ if (preamble === undefined || preamble === '') return undefined
375
+ return escapeProvenanceDelimiter(preamble)
376
+ }
377
+
339
378
  /**
340
379
  * Build the tag section of the execution prompt (issue #1521). Only tags with
341
380
  * a non-blank `promptPrefix` contribute; a task whose tags are all bare names