pi-better-server 0.6.0 → 0.7.1

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 (142) hide show
  1. package/package.json +4 -3
  2. package/scripts/measure-full-runtime/frontend.ts +10 -2
  3. package/scripts/measure-full-runtime.mjs +2 -0
  4. package/src/codex/return.ts +3 -2
  5. package/src/detach/extension.ts +20 -3
  6. package/src/event-log.ts +40 -12
  7. package/src/hosted-session.ts +11 -5
  8. package/src/remote-client/packages.ts +1 -4
  9. package/src/runtime/background-tools.ts +54 -8
  10. package/src/runtime/background.ts +16 -4
  11. package/src/runtime/domain/background/process.mjs +49 -11
  12. package/src/runtime/domain/background/supervisor/store.mjs +3 -3
  13. package/src/runtime/domain/background/supervisor/supervisor.mjs +9 -3
  14. package/src/runtime/domain/background-service/index.domain.mjs +19 -0
  15. package/src/runtime/domain/background-service/index.ts +19 -0
  16. package/src/runtime/domain/background-service/managed-frontend.domain.mjs +87 -5
  17. package/src/runtime/domain/background-service/managed-frontend.ts +76 -5
  18. package/src/runtime/domain/background-service/navigator-provider.domain.mjs +5 -0
  19. package/src/runtime/domain/background-service/navigator-provider.ts +4 -0
  20. package/src/runtime/domain/background-service/observed-waits.domain.mjs +203 -31
  21. package/src/runtime/domain/background-service/observed-waits.ts +168 -24
  22. package/src/runtime/domain/background-service/process.domain.mjs +49 -11
  23. package/src/runtime/domain/background-service/process.ts +45 -11
  24. package/src/runtime/domain/background-service/review-settings.domain.mjs +16 -0
  25. package/src/runtime/domain/background-service/review-settings.ts +18 -0
  26. package/src/runtime/domain/background-service/runtime.domain.mjs +8 -70
  27. package/src/runtime/domain/background-service/runtime.ts +8 -73
  28. package/src/runtime/domain/background-service/shared-harness-settings.domain.mjs +2 -3
  29. package/src/runtime/domain/background-service/shared-harness-settings.ts +2 -5
  30. package/src/runtime/domain/background-service/shared-navigator.domain.mjs +55 -28
  31. package/src/runtime/domain/background-service/shared-navigator.ts +47 -26
  32. package/src/runtime/domain/background-service/shared-operation-coordinator/src/outbox.domain.mjs +7 -0
  33. package/src/runtime/domain/background-service/shared-operation-coordinator/src/outbox.ts +9 -0
  34. package/src/runtime/domain/background-service/shared-operation-coordinator/src/store.domain.mjs +5 -1
  35. package/src/runtime/domain/background-service/shared-operation-coordinator/src/store.ts +6 -0
  36. package/src/runtime/domain/background-service/shared-ssh-core/index.domain.mjs +1 -1
  37. package/src/runtime/domain/background-service/shared-ssh-core/index.ts +1 -1
  38. package/src/runtime/domain/background-service/stall.domain.mjs +5 -3
  39. package/src/runtime/domain/background-service/stall.ts +7 -4
  40. package/src/runtime/domain/background-service/supervised-progress.domain.mjs +42 -0
  41. package/src/runtime/domain/background-service/supervised-progress.ts +43 -0
  42. package/src/runtime/domain/background-service/supervisor/README.md +1 -4
  43. package/src/runtime/domain/background-service/supervisor/emit-runner.mjs +1 -0
  44. package/src/runtime/domain/background-service/supervisor/generated/process.mjs +49 -11
  45. package/src/runtime/domain/background-service/supervisor/generated/runner.mjs +47 -4
  46. package/src/runtime/domain/background-service/supervisor/generated/store.mjs +3 -3
  47. package/src/runtime/domain/background-service/supervisor/generated/watch-fingerprint.mjs +69 -0
  48. package/src/runtime/domain/background-service/supervisor/runner.domain.mjs +47 -4
  49. package/src/runtime/domain/background-service/supervisor/runner.ts +38 -3
  50. package/src/runtime/domain/background-service/supervisor/store.domain.mjs +3 -3
  51. package/src/runtime/domain/background-service/supervisor/store.ts +3 -3
  52. package/src/runtime/domain/background-service/supervisor/supervisor.domain.mjs +9 -3
  53. package/src/runtime/domain/background-service/supervisor/supervisor.ts +6 -3
  54. package/src/runtime/domain/background-service/tools.domain.mjs +22 -16
  55. package/src/runtime/domain/background-service/tools.ts +26 -16
  56. package/src/runtime/domain/background-service/types.ts +4 -2
  57. package/src/runtime/domain/background-service/watch-fingerprint.domain.mjs +67 -0
  58. package/src/runtime/domain/background-service/watch-fingerprint.ts +70 -0
  59. package/src/runtime/domain/catalog/catalog-preferences.mjs +1 -3
  60. package/src/runtime/domain/coordinator/src/outbox.mjs +7 -0
  61. package/src/runtime/domain/coordinator/src/store.mjs +5 -1
  62. package/src/runtime/domain/log-paths.mjs +8 -1
  63. package/src/runtime/domain/parse.mjs +9 -5
  64. package/src/runtime/domain/sandbox-policy/README.md +3 -3
  65. package/src/runtime/domain/sandbox-policy/package.json +1 -1
  66. package/src/runtime/domain/sandbox-policy/shared-harness-settings.domain.mjs +2 -3
  67. package/src/runtime/domain/sandbox-policy/shared-harness-settings.ts +2 -5
  68. package/src/runtime/domain/session-store.mjs +7 -0
  69. package/src/runtime/domain/shared-harness-settings.mjs +2 -3
  70. package/src/runtime/domain/subagents/README.md +12 -10
  71. package/src/runtime/domain/subagents/assignment-outcomes.domain.mjs +2 -5
  72. package/src/runtime/domain/subagents/assignment-outcomes.ts +2 -5
  73. package/src/runtime/domain/subagents/assignment-report.domain.mjs +22 -0
  74. package/src/runtime/domain/subagents/assignment-report.ts +20 -0
  75. package/src/runtime/domain/subagents/batch.mjs +13 -5
  76. package/src/runtime/domain/subagents/catalog-preferences.domain.mjs +1 -3
  77. package/src/runtime/domain/subagents/catalog-preferences.ts +1 -5
  78. package/src/runtime/domain/subagents/cleanup.domain.mjs +11 -2
  79. package/src/runtime/domain/subagents/cleanup.ts +10 -2
  80. package/src/runtime/domain/subagents/config.domain.mjs +5 -0
  81. package/src/runtime/domain/subagents/config.ts +8 -2
  82. package/src/runtime/domain/subagents/continuation.domain.mjs +4 -2
  83. package/src/runtime/domain/subagents/continuation.ts +4 -2
  84. package/src/runtime/domain/subagents/extensions.mjs +1 -0
  85. package/src/runtime/domain/subagents/failures.domain.mjs +11 -2
  86. package/src/runtime/domain/subagents/failures.ts +10 -2
  87. package/src/runtime/domain/subagents/finalization.domain.mjs +39 -32
  88. package/src/runtime/domain/subagents/finalization.ts +37 -30
  89. package/src/runtime/domain/subagents/git-workspace.domain.mjs +51 -6
  90. package/src/runtime/domain/subagents/git-workspace.ts +48 -6
  91. package/src/runtime/domain/subagents/index.domain.mjs +208 -75
  92. package/src/runtime/domain/subagents/index.ts +213 -75
  93. package/src/runtime/domain/subagents/isolated-workspace.domain.mjs +508 -0
  94. package/src/runtime/domain/subagents/isolated-workspace.ts +551 -0
  95. package/src/runtime/domain/subagents/list.mjs +2 -2
  96. package/src/runtime/domain/subagents/managed-launch-client.domain.mjs +22 -5
  97. package/src/runtime/domain/subagents/managed-launch-client.ts +23 -6
  98. package/src/runtime/domain/subagents/output-payload.domain.mjs +24 -9
  99. package/src/runtime/domain/subagents/output-payload.ts +26 -12
  100. package/src/runtime/domain/subagents/package.json +4 -2
  101. package/src/runtime/domain/subagents/parse.domain.mjs +9 -5
  102. package/src/runtime/domain/subagents/parse.ts +10 -5
  103. package/src/runtime/domain/subagents/registry.domain.mjs +31 -25
  104. package/src/runtime/domain/subagents/registry.ts +31 -13
  105. package/src/runtime/domain/subagents/retained-result.domain.mjs +56 -0
  106. package/src/runtime/domain/subagents/retained-result.ts +65 -0
  107. package/src/runtime/domain/subagents/session-selection.domain.mjs +3 -1
  108. package/src/runtime/domain/subagents/session-selection.ts +2 -1
  109. package/src/runtime/domain/subagents/session-store.domain.mjs +7 -0
  110. package/src/runtime/domain/subagents/session-store.ts +9 -0
  111. package/src/runtime/domain/subagents/settings-page.domain.mjs +151 -107
  112. package/src/runtime/domain/subagents/settings-page.ts +147 -108
  113. package/src/runtime/domain/subagents/shared-catalog.domain.mjs +23 -7
  114. package/src/runtime/domain/subagents/shared-catalog.ts +23 -7
  115. package/src/runtime/domain/subagents/shared-harness-settings.domain.mjs +2 -3
  116. package/src/runtime/domain/subagents/shared-harness-settings.ts +2 -5
  117. package/src/runtime/domain/subagents/shared-navigator.domain.mjs +55 -28
  118. package/src/runtime/domain/subagents/shared-navigator.ts +47 -26
  119. package/src/runtime/domain/subagents/shared-operation-coordinator/src/outbox.domain.mjs +7 -0
  120. package/src/runtime/domain/subagents/shared-operation-coordinator/src/outbox.ts +9 -0
  121. package/src/runtime/domain/subagents/shared-operation-coordinator/src/store.domain.mjs +5 -1
  122. package/src/runtime/domain/subagents/shared-operation-coordinator/src/store.ts +6 -0
  123. package/src/runtime/domain/subagents/task-guard.domain.mjs +14 -1
  124. package/src/runtime/domain/subagents/task-guard.ts +13 -1
  125. package/src/runtime/domain/subagents/task-policy.domain.mjs +2 -1
  126. package/src/runtime/domain/subagents/task-policy.ts +5 -1
  127. package/src/runtime/domain/subagents/tools.domain.mjs +4 -8
  128. package/src/runtime/domain/subagents/tools.ts +4 -7
  129. package/src/runtime/domain/subagents/work-observation.domain.mjs +25 -1
  130. package/src/runtime/domain/subagents/work-observation.ts +20 -1
  131. package/src/runtime/domain/subagents/workspace-files.domain.mjs +103 -0
  132. package/src/runtime/domain/subagents/workspace-files.ts +114 -0
  133. package/src/runtime/domain/subagents/workspace-prepare-worker.mjs +12 -0
  134. package/src/runtime/domain/subagents/workspace-scope.domain.d.mts +38 -0
  135. package/src/runtime/domain/subagents/workspace-scope.domain.mjs +5 -0
  136. package/src/runtime/domain/subagents/workspace-scope.ts +6 -0
  137. package/src/runtime/domain/subagents/worktree-feedback.domain.mjs +55 -0
  138. package/src/runtime/domain/subagents/worktree-feedback.ts +77 -0
  139. package/src/runtime/read-model.ts +4 -2
  140. package/src/runtime/root.ts +5 -2
  141. package/src/shared-ssh-core/index.ts +1 -1
  142. package/src/version.ts +1 -1
@@ -26,14 +26,16 @@ import { createHash, randomUUID } from "node:crypto";
26
26
  import { closeSync, existsSync, fstatSync, mkdirSync, openSync, readdirSync, readFileSync, readSync, realpathSync, renameSync, rmSync, statSync, writeFileSync, watch } from "node:fs";
27
27
  import { homedir } from "node:os";
28
28
  import { dirname, isAbsolute, join, relative, resolve } from "node:path";
29
+ import { describeSupervisedProgress, supervisedProgress } from "./supervised-progress.domain.mjs";
30
+ import { formatProgressDuration } from "./stall.domain.mjs";
29
31
  import { validateCondition } from "./conditions.domain.mjs";
30
- import { STEP_GATE_COMMAND_ENV, commandExecution, parseStepGateFailure, processExists, stepGateScript, validateCommandSpec, } from "./process.domain.mjs";
32
+ import { STEP_GATE_COMMAND_ENV, commandExecution, parseStepGateFailure, processExists, resolveWindowsLaunchShell, stepGateScript, validateCommandSpec, } from "./process.domain.mjs";
31
33
  import { currentProcessStartToken, readProcessStartToken } from "./process-identity.domain.mjs";
32
34
  import { assertBackgroundExecutionAllowed, backgroundExecutionLimits, confineCommandSpec, resolveForegroundSandboxPlan, currentForegroundSandboxPolicy, resolveWorkerSandboxPlan, sandboxProvenance, } from "./sandbox.domain.mjs";
33
35
  import { openStore, cancellationCredential, } from "./shared-operation-coordinator/index.domain.mjs";
34
36
  import { createLocalSupervisor, defaultSupervisorDirectory, supervisorPaths, supervisorTaskIdForToken, } from "./supervisor/index.domain.mjs";
35
37
  import { processGroupAlive } from "./supervisor/identity.domain.mjs";
36
- import { readStopRequest } from "./supervisor/store.domain.mjs";
38
+ import { readStopRequest, writeTextAtomic } from "./supervisor/store.domain.mjs";
37
39
  export const OBSERVED_WAITS_SERVICE_VERSION = 2;
38
40
  export const OBSERVED_WAITS_SERVICE_CHANNEL = "pi-better-background-tasks:observed-waits-service";
39
41
  export const OBSERVED_WAITS_SERVICE_REQUEST_CHANNEL = "pi-better-background-tasks:observed-waits-service-request";
@@ -1308,6 +1310,124 @@ export class ObservedWaitHost {
1308
1310
  this.projectionMetrics.projectionsBuilt += 1;
1309
1311
  return this.projectDurable(operation, now);
1310
1312
  }
1313
+ /** Rebuild a live incident from the runner checkpoint. Only the native handoff writes its receipt. */
1314
+ pendingStallAlert(origin, taskId, waits) {
1315
+ const operation = this.operationForTask(taskId);
1316
+ if (!operation || operation.terminalRevision || !this.belongsToParentOrigin(operation, origin))
1317
+ return;
1318
+ const branchId = operation.owner.branchId;
1319
+ if (!this.isParentOriginActive(origin, branchId))
1320
+ return;
1321
+ const directory = this.observationDirectory(operation);
1322
+ if (!directory)
1323
+ return;
1324
+ const context = this.readLaunchContext(taskId, directory);
1325
+ if (!context?.callback)
1326
+ return;
1327
+ const inspection = this.passiveSnapshot(taskId, directory);
1328
+ if (!inspection || inspection.token !== operation.launchToken || inspection.stopRequestedAt !== undefined)
1329
+ return;
1330
+ const now = this.options.now?.() ?? Date.now();
1331
+ const progress = supervisedProgress(inspection, now);
1332
+ if (!progress?.alertDue)
1333
+ return;
1334
+ const receiptId = `background-stall:${operation.operationId}:${progress.observedAt}`;
1335
+ const receiptPath = join(inspection.taskDir, "stall-receipt");
1336
+ try {
1337
+ if (readFileSync(receiptPath, "utf8") === receiptId)
1338
+ return;
1339
+ }
1340
+ catch (error) {
1341
+ if (error.code !== "ENOENT")
1342
+ throw error;
1343
+ }
1344
+ const lines = [describeSupervisedProgress(progress, now),
1345
+ `Task has run for ${formatProgressDuration(now - inspection.launch.createdAt)}.`];
1346
+ for (const ref of waits) {
1347
+ const wait = this.requireStore().getWait(ref);
1348
+ if (!wait || wait.phase === "cancelled" || wait.phase === "consumed" || !sameOwner(wait.owner, operation.owner))
1349
+ continue;
1350
+ if (!wait.dependencies.some(dep => dep.operationId === operation.operationId))
1351
+ continue;
1352
+ const others = wait.dependencies.filter(dep => dep.operationId !== operation.operationId);
1353
+ const siblings = others.slice(0, 8).map(dep => {
1354
+ const sibling = this.requireStore().getOperation(dep.operationId);
1355
+ return `${sibling?.taskId ?? dep.operationId} ${sibling?.terminalOutcome ?? sibling?.phase ?? "unknown"}`;
1356
+ });
1357
+ if (others.length > siblings.length)
1358
+ siblings.push(`+${others.length - siblings.length} more`);
1359
+ lines.push(`Wait ${ref.waitId} ${wait.phase}${siblings.length ? ". Other tasks: " + siblings.join(", ") : ""}`);
1360
+ }
1361
+ const output = [inspection.logs.stdout, inspection.logs.stderr].map(path => lastLines(tail(path).text, 1).slice(-300)).filter(Boolean);
1362
+ lines.push(...output, `Evidence: bg_task_log id=${taskId}`);
1363
+ const notification = { taskId, operationId: operation.operationId, origin, branchId, urgent: true,
1364
+ event: { source: "background-task", id: receiptId, inspectId: taskId, label: context.name ?? taskId,
1365
+ status: "suspected stall", customType: "background-task-stall", content: lines.join("\n"), detailTool: "bg_task_status" } };
1366
+ return { notification, delivery: { receiptId, delivered: () => writeTextAtomic(receiptPath, receiptId), defer: () => { } } };
1367
+ }
1368
+ /** Review an ongoing parent wait using durable launch, progress and handoff evidence. */
1369
+ backgroundWaitReview(origin, taskId, waits, intervalMs) {
1370
+ const operation = this.operationForTask(taskId);
1371
+ if (!operation || operation.terminalRevision || !this.belongsToParentOrigin(operation, origin))
1372
+ return;
1373
+ const branchId = operation.owner.branchId;
1374
+ if (!this.isParentOriginActive(origin, branchId))
1375
+ return;
1376
+ const wait = waits.map(ref => this.requireStore().getWait(ref)).find(record => record?.phase === "waiting"
1377
+ && sameOwner(record.owner, operation.owner)
1378
+ && record.dependencies.some(dep => dep.operationId === operation.operationId));
1379
+ if (!wait)
1380
+ return;
1381
+ const directory = this.observationDirectory(operation);
1382
+ if (!directory)
1383
+ return;
1384
+ const context = this.readLaunchContext(taskId, directory);
1385
+ if (!context?.callback)
1386
+ return;
1387
+ const inspection = this.passiveSnapshot(taskId, directory);
1388
+ if (!inspection || inspection.token !== operation.launchToken || inspection.stopRequestedAt !== undefined)
1389
+ return;
1390
+ const clock = this.options.now ?? Date.now;
1391
+ const now = clock();
1392
+ const progress = supervisedProgress(inspection, now);
1393
+ if (!progress)
1394
+ return;
1395
+ const receiptPath = join(inspection.taskDir, "wait-review-receipt.json");
1396
+ const incident = [wait.waitId, wait.generation, progress.observedAt].join(":");
1397
+ const firstReviewAnchor = Math.max(wait.createdAt, progress.observedAt);
1398
+ let anchor = firstReviewAnchor;
1399
+ try {
1400
+ const receipt = JSON.parse(readFileSync(receiptPath, "utf8"));
1401
+ if (receipt?.incident === incident && Number.isFinite(receipt.deliveredAt)) {
1402
+ anchor = Math.max(anchor, receipt.deliveredAt);
1403
+ }
1404
+ }
1405
+ catch (error) {
1406
+ if (!(error instanceof SyntaxError) && error.code !== "ENOENT")
1407
+ throw error;
1408
+ }
1409
+ const dueAt = anchor + intervalMs;
1410
+ if (now < dueAt)
1411
+ return { dueAt };
1412
+ const receiptId = `background-wait-review:${operation.operationId}:${incident}:${anchor}`;
1413
+ const lines = [
1414
+ `Task has run for ${formatProgressDuration(now - inspection.launch.createdAt)}. No observed progress for ${formatProgressDuration(now - progress.observedAt)}.`,
1415
+ `Wait ${wait.waitId} is still waiting. Reassess the blocker and report the next step.`,
1416
+ `Continuation note: ${oneLine(wait.continuationNote, 250)}`,
1417
+ ];
1418
+ if (inspection.kind === "watch") {
1419
+ const lastCheck = lastLines(tail(inspection.logs.events).text, 12).split("\n").reverse().find(line => / check #\d+ exit=/.test(line));
1420
+ if (lastCheck)
1421
+ lines.push(`Latest check: ${oneLine(lastCheck, 200)}`);
1422
+ }
1423
+ const output = [inspection.logs.stdout, inspection.logs.stderr].map(path => lastLines(tail(path).text, 1).slice(-300)).filter(Boolean);
1424
+ lines.push(...output, `Evidence: bg_task_log id=${taskId}`);
1425
+ const notification = { taskId, operationId: operation.operationId, origin, branchId, urgent: true,
1426
+ event: { source: "background-task", id: receiptId, inspectId: taskId, label: context.name ?? taskId,
1427
+ status: "wait review due", customType: "background-wait-review", content: lines.join("\n"), detailTool: "bg_task_status" } };
1428
+ return { dueAt, alert: { notification, delivery: { receiptId,
1429
+ delivered: () => writeTextAtomic(receiptPath, JSON.stringify({ incident, deliveredAt: clock() })), defer: () => { } } } };
1430
+ }
1311
1431
  /** Accumulated projection work, for performance regression proof. */
1312
1432
  getDurableProjectionMetrics() {
1313
1433
  return { ...this.projectionMetrics };
@@ -1415,18 +1535,30 @@ export class ObservedWaitHost {
1415
1535
  return operation.owner.sessionId === origin.sessionId;
1416
1536
  return true;
1417
1537
  }
1538
+ observationDirectory(operation) {
1539
+ if (!operation.supervision?.hostId?.startsWith("server:"))
1540
+ return this.directory;
1541
+ const grant = this.store?.resultSupervision(operation.operationId);
1542
+ if (!grant || grant.launchToken !== operation.launchToken || !sameOwner(grant.owner, operation.owner))
1543
+ return;
1544
+ return grant.directory;
1545
+ }
1546
+ passiveSnapshot(taskId, directory) {
1547
+ if (!directory || !LOCAL_DURABLE_ID.test(taskId))
1548
+ return;
1549
+ const supervisor = directory === this.directory ? this.supervisor : createLocalSupervisor({ directory });
1550
+ try {
1551
+ return supervisor.snapshot(taskId);
1552
+ }
1553
+ catch {
1554
+ return;
1555
+ }
1556
+ }
1418
1557
  projectDurable(operation, now) {
1419
- const context = this.launchContext(operation.taskId);
1420
- // Projection is the rendering path: a snapshot reads the durable records
1421
- // without taking the cross-process fence or spawning `ps`.
1422
- const inspection = LOCAL_DURABLE_ID.test(operation.taskId)
1423
- ? (() => { try {
1424
- return this.supervisor.snapshot(operation.taskId);
1425
- }
1426
- catch {
1427
- return undefined;
1428
- } })()
1429
- : undefined;
1558
+ const directory = this.observationDirectory(operation);
1559
+ const context = directory === this.directory ? this.launchContext(operation.taskId)
1560
+ : directory ? this.readLaunchContext(operation.taskId, directory) : undefined;
1561
+ const inspection = this.passiveSnapshot(operation.taskId, directory);
1430
1562
  const storeStatus = operation.terminalRevision > 0 ? this.statusOf(operation.operationId) : undefined;
1431
1563
  const status = inspection?.terminal ? inspection.status : storeStatus ?? inspection?.status ?? "running";
1432
1564
  const terminal = inspection?.terminal === true || operation.terminalRevision > 0;
@@ -1450,6 +1582,7 @@ export class ObservedWaitHost {
1450
1582
  status,
1451
1583
  active,
1452
1584
  terminal,
1585
+ progress: active ? supervisedProgress(inspection, now) : undefined,
1453
1586
  attention: terminal && status !== "succeeded",
1454
1587
  ...(context?.name ?? inspection?.launch.name ? { name: context?.name ?? inspection?.launch.name } : {}),
1455
1588
  cwd: inspection?.launch.cwd ?? context?.cwd ?? operation.owner.workspace,
@@ -1481,7 +1614,8 @@ export class ObservedWaitHost {
1481
1614
  }
1482
1615
  statusForOperation(operation, owner) {
1483
1616
  const store = this.requireStore(), taskId = operation.taskId;
1484
- const inspection = this.inspect(taskId);
1617
+ const directory = this.observationDirectory(operation);
1618
+ const inspection = directory === this.directory ? this.inspect(taskId) : this.passiveSnapshot(taskId, directory);
1485
1619
  this.reconcileInspection(operation, inspection);
1486
1620
  const current = store.getOperation(operation.operationId) ?? operation;
1487
1621
  if (this.watchedRunningTasks.delete(taskId) && current.terminalRevision > 0) {
@@ -1493,14 +1627,14 @@ export class ObservedWaitHost {
1493
1627
  this.attemptTerminalCallback(current, this.statusOf(current.operationId), current.terminalOutcome ?? "failed", [], { pendingWithoutContext: true });
1494
1628
  }
1495
1629
  this.recordReadsForTask(owner, current);
1496
- const paths = supervisorPaths(this.directory, taskId);
1630
+ const paths = inspection?.logs ?? supervisorPaths(this.directory, taskId);
1497
1631
  const gateText = inspection ? `${tail(paths.stderr).text}` : "";
1498
1632
  const waits = store.listWaits({ pendingOnly: true })
1499
1633
  .filter((wait) => sameOwner(wait.owner, owner))
1500
1634
  .filter((wait) => wait.dependencies.some((dep) => dep.operationId === current.operationId))
1501
1635
  .map((wait) => this.waitView(wait));
1502
1636
  const result = inspection?.result;
1503
- const launched = this.launchContext(taskId);
1637
+ const launched = directory === this.directory ? this.launchContext(taskId) : directory ? this.readLaunchContext(taskId, directory) : undefined;
1504
1638
  const stepGate = result && launched?.gated ? parseStepGateFailure(gateText, taskId) : undefined;
1505
1639
  const kind = inspection?.kind ?? launched?.kind ?? "process";
1506
1640
  return {
@@ -1509,6 +1643,7 @@ export class ObservedWaitHost {
1509
1643
  kind: kind === "watch" ? "watch" : "process",
1510
1644
  status: inspection?.status ?? this.statusOf(current.operationId),
1511
1645
  phase: current.phase,
1646
+ progress: current.terminalRevision === 0 ? supervisedProgress(inspection, this.options.now?.() ?? Date.now()) : undefined,
1512
1647
  exitCode: result?.exitCode ?? null,
1513
1648
  signal: result?.signal ?? null,
1514
1649
  ...supervisionReasonFields(inspection),
@@ -1526,10 +1661,13 @@ export class ObservedWaitHost {
1526
1661
  log(taskId, owner, options = {}) {
1527
1662
  const store = this.requireStore();
1528
1663
  const operation = this.ownedOperation(taskId, owner);
1529
- const inspection = this.inspect(taskId);
1664
+ const directory = this.observationDirectory(operation);
1665
+ const inspection = directory === this.directory ? this.inspect(taskId) : this.passiveSnapshot(taskId, directory);
1530
1666
  this.reconcileInspection(operation, inspection);
1531
1667
  this.recordReadsForTask(owner, store.getOperation(operation.operationId) ?? operation);
1532
- const paths = supervisorPaths(this.directory, taskId);
1668
+ if (!directory)
1669
+ throw new Error("Captured Background log directory unavailable");
1670
+ const paths = inspection?.logs ?? supervisorPaths(directory, taskId);
1533
1671
  const lines = Math.max(1, Math.floor(options.lines ?? 40));
1534
1672
  const stdout = tail(paths.stdout);
1535
1673
  const stderr = tail(paths.stderr);
@@ -1569,6 +1707,9 @@ export class ObservedWaitHost {
1569
1707
  `${view.taskId} ${view.kind}: ${view.status} (${view.phase})`,
1570
1708
  `operation: ${view.operationId}; terminal revision: ${view.terminalRevision}${view.terminalOutcome ? ` (${view.terminalOutcome})` : ""}`,
1571
1709
  ];
1710
+ const progress = view.progress && describeSupervisedProgress(view.progress, this.options.now?.() ?? Date.now());
1711
+ if (progress)
1712
+ lines.push(progress);
1572
1713
  if (view.sandbox) {
1573
1714
  lines.push(`sandbox: ${view.sandbox.confinement}${view.sandbox.backend ? `; ${oneLine(view.sandbox.backend, 40)}` : ""}; source: ${oneLine(view.sandbox.policySource, 80)}; later changes do not affect this task.`);
1574
1715
  }
@@ -2631,6 +2772,8 @@ export class ObservedWaitHost {
2631
2772
  ? resolveWorkerSandboxPlan(this.pi, workerPolicy, params, tool)
2632
2773
  : resolveForegroundSandboxPlan(this.pi, false, params, tool);
2633
2774
  assertBackgroundExecutionAllowed(spec, plan, { remote: false, cwd });
2775
+ if (spec.shell !== false)
2776
+ spec.resolvedWindowsShell = resolveWindowsLaunchShell(this.pi);
2634
2777
  const limits = backgroundExecutionLimits(plan);
2635
2778
  const gated = kind === "process" && params.require_successful_steps === true;
2636
2779
  if (gated) {
@@ -2764,10 +2907,18 @@ export class ObservedWaitHost {
2764
2907
  throw error;
2765
2908
  }
2766
2909
  }
2767
- const inspection = this.inspect(operation.taskId);
2910
+ let inspection;
2911
+ let unavailable = false;
2912
+ try {
2913
+ if (LOCAL_DURABLE_ID.test(operation.taskId))
2914
+ inspection = this.supervisor.inspect(operation.taskId, { recordLost: true });
2915
+ }
2916
+ catch {
2917
+ unavailable = true;
2918
+ }
2768
2919
  if (!inspection) {
2769
2920
  const now = this.options.now?.() ?? Date.now();
2770
- if (now - operation.createdAt >= 30_000) {
2921
+ if (!unavailable && now - operation.createdAt >= 30_000) {
2771
2922
  // The supervisor writes its launch record before spawning. No record
2772
2923
  // after the claim grace means no execution can be witnessed; this is
2773
2924
  // `lost`, never a success and never a silent retry.
@@ -2791,14 +2942,15 @@ export class ObservedWaitHost {
2791
2942
  void this.dispatchOutbox();
2792
2943
  return;
2793
2944
  }
2945
+ const reason = unavailable ? "durable supervisor records could not be read" : "no durable supervisor record exists for this operation";
2794
2946
  try {
2795
- if (claimed || operation.health !== "unmonitored" || operation.healthReason !== "no durable supervisor record exists for this operation") {
2947
+ if (claimed || operation.health !== "unmonitored" || operation.healthReason !== reason) {
2796
2948
  this.store?.recordSupervision({
2797
2949
  operationId: operation.operationId,
2798
2950
  owner: operation.owner,
2799
2951
  expectedHostId: this.hostId,
2800
2952
  health: "unmonitored",
2801
- reason: "no durable supervisor record exists for this operation",
2953
+ reason,
2802
2954
  });
2803
2955
  }
2804
2956
  }
@@ -2965,7 +3117,7 @@ export class ObservedWaitHost {
2965
3117
  return;
2966
3118
  }
2967
3119
  this.options.logger?.(`observed waits: ${operation.taskId} ${status} (revision ${recorded.operation.terminalRevision})`);
2968
- this.attemptTerminalCallback(operation, status, outcome, refs, { pendingWithoutContext: true });
3120
+ this.attemptTerminalCallback(recorded.operation, status, outcome, refs, { pendingWithoutContext: true });
2969
3121
  this.emitDurableTaskChange(operation.owner);
2970
3122
  // The parent callback is independent from the worker's wait: a worker may be
2971
3123
  // parked, while the parent session still learns that the supervised task ended.
@@ -3012,6 +3164,11 @@ export class ObservedWaitHost {
3012
3164
  skip("already delivered");
3013
3165
  return;
3014
3166
  }
3167
+ if (this.waitDeliveredTerminalRevision(operation, context)) {
3168
+ this.pendingTerminalCallbacks.delete(operation.taskId);
3169
+ this.store?.setParentCallbackPending(operation.taskId, false);
3170
+ return;
3171
+ }
3015
3172
  const waitPending = this.store?.listWaits({ owner: operation.owner, pendingOnly: true })
3016
3173
  .some((wait) => wait.dependencies.some((dep) => dep.operationId === operation.operationId)) ?? false;
3017
3174
  if (waitPending) {
@@ -3200,6 +3357,12 @@ export class ObservedWaitHost {
3200
3357
  return !!proof && proof.waitId === event.waitId && proof.generation === event.generation
3201
3358
  && proof.terminalRevision === event.terminalRevision;
3202
3359
  }
3360
+ waitDeliveredTerminalRevision(operation, context) {
3361
+ if (operation.terminalRevision === 0)
3362
+ return false;
3363
+ return Object.values(context.outboxDelivered ?? {}).some(proof => proof.terminalRevision === operation.terminalRevision)
3364
+ || (this.store?.hasDeliveredWaitDependency(operation.operationId, operation.terminalRevision, operation.owner) ?? false);
3365
+ }
3203
3366
  recordOutboxHandoffProof(taskId, event) {
3204
3367
  const context = this.currentLaunchContext(taskId);
3205
3368
  if (!context)
@@ -3431,8 +3594,17 @@ export class ObservedWaitHost {
3431
3594
  catch { /* the store closed between handoff and receipt */ }
3432
3595
  // Key the recovered receipt to this exact event. Never use the
3433
3596
  // standalone task callback's receipt as proof for a wait.
3434
- if (!receipted && taskId)
3435
- this.recordOutboxHandoffProof(taskId, event);
3597
+ if (taskId) {
3598
+ this.pendingTerminalCallbacks.delete(taskId);
3599
+ if (!receipted)
3600
+ this.recordOutboxHandoffProof(taskId, event);
3601
+ else {
3602
+ try {
3603
+ store.setParentCallbackPending(taskId, false);
3604
+ }
3605
+ catch { /* the wait receipt survives for recovery */ }
3606
+ }
3607
+ }
3436
3608
  },
3437
3609
  defer: (reason) => {
3438
3610
  if (settled)
@@ -3852,15 +4024,15 @@ export class ObservedWaitHost {
3852
4024
  return undefined;
3853
4025
  }
3854
4026
  }
3855
- sidecarPath(taskId) {
3856
- return join(this.directory, "observed", `${taskId}.json`);
4027
+ sidecarPath(taskId, directory = this.directory) {
4028
+ return join(directory, "observed", `${taskId}.json`);
3857
4029
  }
3858
4030
  writeLaunchContext(taskId, context) {
3859
4031
  try {
3860
4032
  const operation = this.operationForTask(taskId);
3861
4033
  const parent = operation?.owner.kind === "parent-session";
3862
- const outboxDelivered = operation && Object.values(context.outboxDelivered ?? {}).some(proof => proof.terminalRevision === operation.terminalRevision);
3863
- const pending = context.callback !== false && context.callbackDeliveredAt === undefined && !outboxDelivered;
4034
+ const pending = context.callback !== false && context.callbackDeliveredAt === undefined
4035
+ && (!parent || !this.waitDeliveredTerminalRevision(operation, context));
3864
4036
  // Publish the obligation before the sidecar: a crash may leave a pending
3865
4037
  // candidate, but cannot hide an accepted callback. Retire only after the
3866
4038
  // delivered/disabled sidecar is durable, so replay can prove suppression.
@@ -3881,9 +4053,9 @@ export class ObservedWaitHost {
3881
4053
  }
3882
4054
  catch { /* retain an obligation if the exact sidecar cannot be persisted */ }
3883
4055
  }
3884
- readLaunchContext(taskId) {
4056
+ readLaunchContext(taskId, directory = this.directory) {
3885
4057
  try {
3886
- const value = JSON.parse(readFileSync(this.sidecarPath(taskId), "utf8"));
4058
+ const value = JSON.parse(readFileSync(this.sidecarPath(taskId, directory), "utf8"));
3887
4059
  if (value.kind !== "process" && value.kind !== "watch")
3888
4060
  return undefined;
3889
4061
  return {