@loucompanion/forge-bridge 0.1.4-dev.63db04bcffca → 0.1.4-dev.6b2148ecc60c

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 (184) hide show
  1. package/README.md +57 -2
  2. package/dist/bridge/bridge-chat-provider-command.d.ts +16 -0
  3. package/dist/bridge/bridge-chat-provider-command.js +125 -0
  4. package/dist/bridge/bridge.base.d.ts +9 -0
  5. package/dist/bridge/bridge.service.d.ts +85 -3
  6. package/dist/bridge/bridge.service.js +361 -122
  7. package/dist/bridge/bridge.types.d.ts +22 -0
  8. package/dist/bridge/dispatch-result-outbox.d.ts +11 -1
  9. package/dist/bridge/dispatch-result-outbox.js +31 -6
  10. package/dist/bridge/local-yield-flag.d.ts +6 -0
  11. package/dist/bridge/local-yield-flag.js +34 -0
  12. package/dist/bridge/runner-host-capabilities.d.ts +5 -0
  13. package/dist/bridge/runner-host-capabilities.js +17 -0
  14. package/dist/bridge/test-postgres-capability.d.ts +14 -0
  15. package/dist/bridge/test-postgres-capability.js +120 -0
  16. package/dist/cleanup/cleanup.service.d.ts +9 -0
  17. package/dist/cleanup/cleanup.service.js +72 -109
  18. package/dist/cleanup/cleanup.types.d.ts +4 -0
  19. package/dist/cleanup/forge-owned-paths.d.ts +9 -0
  20. package/dist/cleanup/forge-owned-paths.js +53 -0
  21. package/dist/cleanup/host-runtime-ledger.d.ts +5 -0
  22. package/dist/cleanup/host-runtime-ledger.js +109 -0
  23. package/dist/cleanup/managed-branch-sweep.d.ts +27 -0
  24. package/dist/cleanup/managed-branch-sweep.js +111 -0
  25. package/dist/cli/cli.help.js +18 -0
  26. package/dist/cli/cli.service.d.ts +16 -0
  27. package/dist/cli/cli.service.js +142 -16
  28. package/dist/cli/local-config.d.ts +4 -0
  29. package/dist/cli/local-config.js +26 -4
  30. package/dist/runtime/aspnet-runtime-prebuild.js +94 -6
  31. package/dist/runtime/attempt-process-supervisor.d.ts +19 -0
  32. package/dist/runtime/attempt-process-supervisor.js +50 -0
  33. package/dist/runtime/host-database-capability-boundary.d.ts +1 -1
  34. package/dist/runtime/host-database-capability-boundary.js +1 -0
  35. package/dist/runtime/host-facts.d.ts +36 -0
  36. package/dist/runtime/host-facts.js +95 -0
  37. package/dist/runtime/host-load-admission.d.ts +67 -0
  38. package/dist/runtime/host-load-admission.js +99 -0
  39. package/dist/runtime/host-load-child-environment.d.ts +27 -0
  40. package/dist/runtime/host-load-child-environment.js +76 -0
  41. package/dist/runtime/host-load-forge-cgroups.d.ts +49 -0
  42. package/dist/runtime/host-load-forge-cgroups.js +140 -0
  43. package/dist/runtime/host-load-governor-config.d.ts +52 -0
  44. package/dist/runtime/host-load-governor-config.js +83 -0
  45. package/dist/runtime/host-load-governor.d.ts +184 -0
  46. package/dist/runtime/host-load-governor.js +632 -0
  47. package/dist/runtime/host-load-ledger-lock.d.ts +69 -0
  48. package/dist/runtime/host-load-ledger-lock.js +185 -0
  49. package/dist/runtime/host-load-runtime-settings.d.ts +25 -0
  50. package/dist/runtime/host-load-runtime-settings.js +78 -0
  51. package/dist/runtime/host-load-sampler.d.ts +149 -0
  52. package/dist/runtime/host-load-sampler.js +291 -0
  53. package/dist/runtime/host-load-step-class.d.ts +70 -0
  54. package/dist/runtime/host-load-step-class.js +161 -0
  55. package/dist/runtime/host-load-step-reaper.d.ts +27 -0
  56. package/dist/runtime/host-load-step-reaper.js +95 -0
  57. package/dist/runtime/host-load-step-run.d.ts +73 -0
  58. package/dist/runtime/host-load-step-run.js +102 -0
  59. package/dist/runtime/host-load-test-slot.d.ts +43 -0
  60. package/dist/runtime/host-load-test-slot.js +81 -0
  61. package/dist/runtime/host-load-token-ledger.d.ts +200 -0
  62. package/dist/runtime/host-load-token-ledger.js +453 -0
  63. package/dist/runtime/host-load-windows-cpu.d.ts +34 -0
  64. package/dist/runtime/host-load-windows-cpu.js +85 -0
  65. package/dist/runtime/host-pressure-stall.d.ts +61 -0
  66. package/dist/runtime/host-pressure-stall.js +168 -0
  67. package/dist/runtime/host-runtime-contract.d.ts +4 -0
  68. package/dist/runtime/host-runtime-contract.js +6 -1
  69. package/dist/runtime/host-runtime-lease.d.ts +74 -4
  70. package/dist/runtime/host-runtime-lease.js +336 -20
  71. package/dist/runtime/host-runtime-promotion.d.ts +23 -0
  72. package/dist/runtime/host-runtime-promotion.js +48 -0
  73. package/dist/runtime/host-runtime-requirements-check.d.ts +17 -0
  74. package/dist/runtime/host-runtime-requirements-check.js +29 -0
  75. package/dist/runtime/host-runtime-requirements.d.ts +36 -0
  76. package/dist/runtime/host-runtime-requirements.js +117 -0
  77. package/dist/runtime/managed-command-teardown.d.ts +62 -0
  78. package/dist/runtime/managed-command-teardown.js +607 -0
  79. package/dist/runtime/playwright-browser-cache.d.ts +39 -0
  80. package/dist/runtime/playwright-browser-cache.js +227 -0
  81. package/dist/runtime/playwright-host-runtime-adapter.d.ts +18 -0
  82. package/dist/runtime/playwright-host-runtime-adapter.js +61 -55
  83. package/dist/runtime/runner-settings.d.ts +100 -0
  84. package/dist/runtime/runner-settings.js +214 -0
  85. package/dist/sandbox/host-capacity-broker.d.ts +113 -0
  86. package/dist/sandbox/host-capacity-broker.js +334 -0
  87. package/dist/sandbox/runtime.d.ts +10 -1
  88. package/dist/sandbox/runtime.js +45 -2
  89. package/dist/sandbox/sandbox-cgroups.d.ts +14 -0
  90. package/dist/sandbox/sandbox-cgroups.js +42 -0
  91. package/dist/session/managed-attempt-tools.d.ts +27 -0
  92. package/dist/session/managed-attempt-tools.js +357 -42
  93. package/dist/session/managed-build-coordinator.d.ts +1 -1
  94. package/dist/session/managed-build-coordinator.js +4 -1
  95. package/dist/session/managed-command-host-load.d.ts +47 -0
  96. package/dist/session/managed-command-host-load.js +83 -0
  97. package/dist/session/mcp-argument-coercion.d.ts +23 -0
  98. package/dist/session/mcp-argument-coercion.js +121 -0
  99. package/dist/session/phase-completion.artifacts.d.ts +7 -0
  100. package/dist/session/phase-completion.artifacts.js +98 -25
  101. package/dist/session/phase-completion.command-validation.d.ts +7 -0
  102. package/dist/session/phase-completion.command-validation.js +77 -0
  103. package/dist/session/phase-completion.d.ts +4 -0
  104. package/dist/session/phase-completion.helpers.js +13 -12
  105. package/dist/session/phase-completion.js +4 -0
  106. package/dist/session/phase-completion.prompts.js +6 -1
  107. package/dist/session/phase-completion.runtime.d.ts +5 -3
  108. package/dist/session/phase-completion.runtime.js +70 -35
  109. package/dist/session/phase-completion.schema-parts.d.ts +19 -0
  110. package/dist/session/phase-completion.schema-parts.js +188 -0
  111. package/dist/session/phase-completion.schemas.d.ts +3 -3
  112. package/dist/session/phase-completion.schemas.js +206 -221
  113. package/dist/session/phase-completion.validation.d.ts +2 -3
  114. package/dist/session/phase-completion.validation.js +46 -92
  115. package/dist/session/pre-publication-host-load.d.ts +27 -0
  116. package/dist/session/pre-publication-host-load.js +111 -0
  117. package/dist/session/pre-publication-pass.d.ts +61 -0
  118. package/dist/session/pre-publication-pass.js +148 -0
  119. package/dist/session/pre-publication-process.d.ts +23 -0
  120. package/dist/session/pre-publication-process.js +109 -0
  121. package/dist/session/pre-publication-skipped-tests.d.ts +21 -0
  122. package/dist/session/pre-publication-skipped-tests.js +109 -0
  123. package/dist/session/pre-publication-step-execution.d.ts +11 -0
  124. package/dist/session/pre-publication-step-execution.js +49 -0
  125. package/dist/session/pre-publication-validation.d.ts +32 -20
  126. package/dist/session/pre-publication-validation.js +202 -195
  127. package/dist/session/provider-cli/claude-background-work.d.ts +66 -0
  128. package/dist/session/provider-cli/claude-background-work.js +180 -0
  129. package/dist/session/provider-cli/pre-publication-repair.d.ts +40 -0
  130. package/dist/session/provider-cli/pre-publication-repair.js +243 -0
  131. package/dist/session/provider-cli/provider-cli.artifacts.d.ts +2 -1
  132. package/dist/session/provider-cli/provider-cli.artifacts.js +21 -15
  133. package/dist/session/provider-cli/provider-cli.child-environment.d.ts +7 -0
  134. package/dist/session/provider-cli/provider-cli.child-environment.js +73 -0
  135. package/dist/session/provider-cli/provider-cli.codex-models-cache.d.ts +3 -0
  136. package/dist/session/provider-cli/provider-cli.codex-models-cache.js +37 -0
  137. package/dist/session/provider-cli/provider-cli.merge-integrity.d.ts +89 -0
  138. package/dist/session/provider-cli/provider-cli.merge-integrity.js +310 -0
  139. package/dist/session/provider-cli/provider-cli.process.d.ts +44 -17
  140. package/dist/session/provider-cli/provider-cli.process.js +283 -310
  141. package/dist/session/provider-cli/provider-cli.prompts.d.ts +7 -0
  142. package/dist/session/provider-cli/provider-cli.prompts.js +65 -10
  143. package/dist/session/provider-cli/provider-cli.runtime.js +7 -0
  144. package/dist/session/provider-cli/provider-cli.service.d.ts +4 -1
  145. package/dist/session/provider-cli/provider-cli.service.js +203 -172
  146. package/dist/session/provider-cli/provider-cli.types.d.ts +30 -0
  147. package/dist/session/provider-cli/provider-cli.windows-environment.d.ts +10 -0
  148. package/dist/session/provider-cli/provider-cli.windows-environment.js +151 -0
  149. package/dist/session/provider-cli/provider-in-flight-work.d.ts +10 -0
  150. package/dist/session/provider-cli/provider-in-flight-work.js +92 -0
  151. package/dist/session/provider-cli/provider-output-pipes.d.ts +30 -0
  152. package/dist/session/provider-cli/provider-output-pipes.js +67 -0
  153. package/dist/session/provider-cli/provider-output-state.d.ts +8 -0
  154. package/dist/session/provider-cli/provider-output-state.js +15 -0
  155. package/dist/session/publishable-worktree-changes.d.ts +54 -0
  156. package/dist/session/publishable-worktree-changes.js +193 -0
  157. package/dist/session/sandbox-host-capacity-gate.d.ts +30 -0
  158. package/dist/session/sandbox-host-capacity-gate.js +238 -0
  159. package/dist/session/session.base.d.ts +9 -1
  160. package/dist/session/session.service.d.ts +9 -2
  161. package/dist/session/session.service.js +120 -5
  162. package/dist/session/session.types.d.ts +3 -0
  163. package/dist/session/session.types.js +15 -3
  164. package/dist/session/workspace-runtime-fingerprint.d.ts +32 -0
  165. package/dist/session/workspace-runtime-fingerprint.js +138 -0
  166. package/dist/shared/process/host-process-supervisor.d.ts +1 -0
  167. package/dist/shared/process/host-process-supervisor.js +1 -1
  168. package/dist/shared/process/process-tree.d.ts +52 -0
  169. package/dist/shared/process/process-tree.js +144 -0
  170. package/dist/shared/process/process.d.ts +67 -0
  171. package/dist/shared/process/process.js +213 -11
  172. package/dist/shared/process/windows-app-execution-alias.d.ts +19 -0
  173. package/dist/shared/process/windows-app-execution-alias.js +45 -0
  174. package/dist/shared/process/windows-launch.d.ts +18 -0
  175. package/dist/shared/process/windows-launch.js +68 -0
  176. package/dist/shared/provider-capabilities.js +5 -6
  177. package/dist/version.d.ts +1 -1
  178. package/dist/version.js +1 -1
  179. package/dist/worktree/dependency-warmer.d.ts +25 -0
  180. package/dist/worktree/dependency-warmer.js +46 -10
  181. package/dist/worktree/worktree.service.d.ts +10 -1
  182. package/dist/worktree/worktree.service.js +42 -2
  183. package/dist/worktree/worktree.types.d.ts +7 -0
  184. package/package.json +2 -2
@@ -4,19 +4,31 @@ import { RoutingProviderCliService } from "./provider-cli/provider-cli.service.j
4
4
  import { ForgeFailureError, waitKindForEvent, waitWakeCondition } from "./session.types.js";
5
5
  import { GitWorktreeService } from "../worktree/worktree.service.js";
6
6
  import { SandboxWorkspaceService } from "../sandbox/workspace.service.js";
7
- import { HostRuntimeAdmissionExpiredError, hostRuntimeEventResources, } from "../runtime/host-runtime-lease.js";
7
+ import { HostRuntimeAdmissionExpiredError, hostRuntimeEventResources, hostRuntimeStackEnvironmentKeys, runtimeAdmissionPriority, } from "../runtime/host-runtime-lease.js";
8
8
  import { configuredLaunchPortNames, hostRuntimeContractFingerprint, hostRuntimeParallelEligible, } from "../runtime/host-runtime-promotion.js";
9
+ import { readWorkspaceRuntimeFingerprint, sameWorkspaceRuntimeFingerprint, workspaceRuntimeFingerprintChanges, } from "./workspace-runtime-fingerprint.js";
9
10
  const minimumReadinessProbeStartupBudgetMs = 150_000;
10
11
  export class BridgeSessionService {
11
12
  worktrees;
12
13
  providerCli;
13
14
  hostRuntime;
15
+ workspaceFingerprint;
14
16
  constructor(worktrees = process.env.FORGE_SANDBOX_ID
15
17
  ? new SandboxWorkspaceService()
16
- : new GitWorktreeService(), providerCli = new RoutingProviderCliService(), hostRuntime) {
18
+ : new GitWorktreeService(), providerCli = new RoutingProviderCliService(), hostRuntime, workspaceFingerprint = readWorkspaceRuntimeFingerprint) {
17
19
  this.worktrees = worktrees;
18
20
  this.providerCli = providerCli;
19
21
  this.hostRuntime = hostRuntime;
22
+ this.workspaceFingerprint = workspaceFingerprint;
23
+ }
24
+ setHostRequirementsCheck(check) {
25
+ this.hostRuntime?.setRequirementsCheck?.(check);
26
+ }
27
+ runnerLimitDefaults() {
28
+ return this.hostRuntime?.capacityLimitDefaults?.() ?? null;
29
+ }
30
+ applyRunnerLimits(limits) {
31
+ this.hostRuntime?.applyCapacityLimits?.(limits);
20
32
  }
21
33
  async updateLease(dispatchAttemptId, fencingToken, expiresAt) {
22
34
  await this.hostRuntime?.updateLease(dispatchAttemptId, fencingToken, expiresAt);
@@ -61,6 +73,8 @@ export class BridgeSessionService {
61
73
  // failed agent worktrees for inspection.
62
74
  cleanupWorktrees: dispatch.serverLocal.cleanupWorktrees,
63
75
  artifacts: [],
76
+ hostLoadOwner: { dispatchAttemptId: dispatch.sandbox?.dispatchAttemptId ?? null, priority: "background" },
77
+ signal,
64
78
  });
65
79
  assertReadinessProbeStartupBudget(request.expiresAt);
66
80
  let started = await this.hostRuntime.start(dispatch, worktree.worktreePath, signal);
@@ -71,6 +85,7 @@ export class BridgeSessionService {
71
85
  status: "serialized",
72
86
  runtimeContractFingerprint: hostRuntimeContractFingerprint(started.runtimeContract),
73
87
  runtimeContractSource: started.runtimeContract.source,
88
+ runtimeRequirements: started.runtimeContract.contract.requires ?? null,
74
89
  reasonCode: discovery?.reasonCode ?? "host_runtime_contract_serialized",
75
90
  reasonMessage: discovery?.summary ?? "The detected runtime requires serialized host execution.",
76
91
  checkedAt: new Date().toISOString(),
@@ -87,6 +102,7 @@ export class BridgeSessionService {
87
102
  status: "parallel_ready",
88
103
  runtimeContractFingerprint: hostRuntimeContractFingerprint(started.runtimeContract),
89
104
  runtimeContractSource: started.runtimeContract.source,
105
+ runtimeRequirements: started.runtimeContract.contract.requires ?? null,
90
106
  reasonCode: null,
91
107
  reasonMessage: null,
92
108
  qaAppLaunchTarget: managedQaLaunchTarget(started.runtimeContract),
@@ -248,7 +264,12 @@ export class BridgeSessionService {
248
264
  qaRework: dispatch.qaRework,
249
265
  warmPathOverrides: dispatch.warmPathOverrides,
250
266
  applicationRuntimeRequired: dispatch.runtimeIntent.applicationRuntimeRequired,
251
- preserveExistingState: Boolean(dispatch.session.resumedFromSessionId)
267
+ preserveExistingState: Boolean(dispatch.session.resumedFromSessionId),
268
+ hostLoadOwner: {
269
+ dispatchAttemptId: dispatch.sandbox?.dispatchAttemptId ?? null,
270
+ priority: runtimeAdmissionPriority(dispatch),
271
+ },
272
+ signal,
252
273
  });
253
274
  }
254
275
  catch (error) {
@@ -326,7 +347,98 @@ export class BridgeSessionService {
326
347
  });
327
348
  }
328
349
  }
350
+ // The stack was built and launched from this workspace state. Pre-publication
351
+ // validation restarts it when the provider has changed the source since.
352
+ let refreshRuntimeEnvironment;
353
+ const hostRuntime = this.hostRuntime;
354
+ if (hostLease && dispatch.sandbox && hostRuntime?.restartConfiguredProject
355
+ && hostLease.executionClass === "managed_runtime"
356
+ && configuredLaunchPortNames(hostLease.runtimeContract).length > 0) {
357
+ const worktreePath = worktree.worktreePath;
358
+ const dispatchAttemptId = dispatch.sandbox.dispatchAttemptId;
359
+ const fencingToken = dispatch.lease.fencingToken;
360
+ const restartConfiguredProject = hostRuntime.restartConfiguredProject.bind(hostRuntime);
361
+ let launchFingerprint = await this.workspaceFingerprint(worktreePath)
362
+ .catch(() => null);
363
+ // Set while the stack may not match the workspace: a failed restart is retried on the next pass.
364
+ let restartPending = false;
365
+ refreshRuntimeEnvironment = async (refreshSignal) => {
366
+ const current = await this.workspaceFingerprint(worktreePath).catch(() => null);
367
+ if (!restartPending && sameWorkspaceRuntimeFingerprint(launchFingerprint, current))
368
+ return null;
369
+ // Every cause that applies is reported; `reason` is the first of them. Changes are named
370
+ // only when both states were read: an unreadable baseline is not a workspace change.
371
+ const comparable = launchFingerprint !== null && current !== null;
372
+ const changes = comparable ? workspaceRuntimeFingerprintChanges(launchFingerprint, current) : [];
373
+ const causes = [
374
+ ...(restartPending ? ["previous_restart_incomplete"] : []),
375
+ ...(comparable ? [] : ["fingerprint_unavailable"]),
376
+ ...(changes.length > 0 ? ["workspace_changed"] : []),
377
+ ];
378
+ const reason = causes[0] ?? "workspace_changed";
379
+ const changeText = changes.length > 0 ? ` The workspace also changed since launch (${changes.join(", ")}).` : "";
380
+ await emitLifecycle({
381
+ role: "runner",
382
+ kind: "checkpoint",
383
+ content: reason === "workspace_changed"
384
+ ? `The workspace changed since the attempt runtime stack was launched (${changes.join(", ")}); restarting it so validation runs against the current source.`
385
+ : reason === "previous_restart_incomplete"
386
+ ? `The previous attempt runtime restart did not complete; restarting it again so validation runs against the current source.${changeText}`
387
+ : `The workspace state could not be compared with the attempt runtime stack; restarting it so validation runs against the current source.`,
388
+ eventType: "host_runtime_restart_started",
389
+ data: JSON.stringify({
390
+ reason,
391
+ causes,
392
+ changes,
393
+ head_sha: current?.headSha ?? null,
394
+ merge_in_progress: Boolean(current?.mergeHead),
395
+ }),
396
+ });
397
+ restartPending = true;
398
+ let restarted;
399
+ try {
400
+ restarted = await restartConfiguredProject(dispatchAttemptId, fencingToken, refreshSignal ?? signal, async (checkpoint) => {
401
+ await emitLifecycle({
402
+ role: "runner",
403
+ kind: "checkpoint",
404
+ content: checkpoint.message,
405
+ eventType: checkpoint.code,
406
+ data: checkpoint.data ? JSON.stringify(checkpoint.data) : undefined,
407
+ });
408
+ });
409
+ }
410
+ catch (error) {
411
+ await emitLifecycle({
412
+ role: "runner",
413
+ kind: "error",
414
+ content: `Restarting the attempt runtime stack failed: ${failureMessage(error)}`,
415
+ eventType: "host_runtime_restart_failed",
416
+ data: JSON.stringify({ reason, causes, changes }),
417
+ }).catch(() => undefined);
418
+ throw error;
419
+ }
420
+ hostLease = restarted;
421
+ // The restarted stack serves the workspace as it is now. Read that state again rather than
422
+ // keep the pre-restart reading, which is null when it could not be collected; a null
423
+ // baseline never matches, so every later pass would restart and rotate ports again.
424
+ launchFingerprint = await this.workspaceFingerprint(worktreePath).catch(() => current);
425
+ restartPending = false;
426
+ await emitLifecycle({
427
+ role: "runner",
428
+ kind: "checkpoint",
429
+ content: `Restarted the supervised project runtime on ${restarted.lease.resources.ports.map(port => `${port.name} ${port.hostIp}:${port.hostPort}`).join(", ") || "no ports"}.`,
430
+ eventType: "host_runtime_restarted",
431
+ data: JSON.stringify(hostRuntimeEventResources(restarted.lease, restarted.runtimeContract, restarted.executionClass)),
432
+ });
433
+ return { environment: restarted.environment, reason, changes };
434
+ };
435
+ }
329
436
  providerDispatch = withMaterializedManagedQaTarget(providerDispatch, hostLease);
437
+ const providerEnvironment = {
438
+ runtimeEnvironment: hostLease?.environment,
439
+ // Only the completion MCP server gets these: its managed commands share the host ledger.
440
+ hostLoadEnvironment: hostLease ? this.hostRuntime?.hostLoadChildEnvironment?.() : undefined,
441
+ };
330
442
  if (dispatch.draft) {
331
443
  throwIfAborted(signal);
332
444
  const processRunner = hostLease && dispatch.sandbox
@@ -335,7 +447,7 @@ export class BridgeSessionService {
335
447
  const run = await this.providerCli.runDraft({
336
448
  dispatch: providerDispatch,
337
449
  worktree,
338
- runtimeEnvironment: hostLease?.environment,
450
+ ...providerEnvironment,
339
451
  processRunner,
340
452
  emit,
341
453
  signal
@@ -363,10 +475,13 @@ export class BridgeSessionService {
363
475
  const context = {
364
476
  dispatch: providerDispatch,
365
477
  worktree,
366
- runtimeEnvironment: hostLease?.environment,
478
+ ...providerEnvironment,
367
479
  processRunner: hostLease && dispatch.sandbox
368
480
  ? this.hostRuntime?.providerProcessRunner?.(dispatch.sandbox.dispatchAttemptId, dispatch.lease.fencingToken) ?? undefined
369
481
  : undefined,
482
+ ...(refreshRuntimeEnvironment && hostLease
483
+ ? { refreshRuntimeEnvironment, runtimeStackEnvironmentKeys: hostRuntimeStackEnvironmentKeys(hostLease.runtimeContract) }
484
+ : {}),
370
485
  emit,
371
486
  signal
372
487
  };
@@ -1,3 +1,4 @@
1
+ import type { HostRuntimeRequirements } from "../runtime/host-runtime-requirements.js";
1
2
  export interface RunOnceDispatchPacket {
2
3
  readonly schemaVersion: 1 | 2;
3
4
  readonly userId: string;
@@ -546,6 +547,8 @@ export interface HostRuntimeReadinessProbeResult {
546
547
  readonly status: "parallel_ready" | "serialized" | "failed";
547
548
  readonly runtimeContractFingerprint?: string | null;
548
549
  readonly runtimeContractSource?: string | null;
550
+ /** Requirements declared by the probed contract (decision 0013); null when none. */
551
+ readonly runtimeRequirements?: HostRuntimeRequirements | null;
549
552
  readonly reasonCode?: string | null;
550
553
  readonly reasonMessage?: string | null;
551
554
  readonly qaAppLaunchTarget?: HostRuntimeReadinessQaLaunchTarget | null;
@@ -469,18 +469,21 @@ function unvalidatedFailureFactsForCode(code, source) {
469
469
  if (code === "bridge.unavailable") {
470
470
  return facts(code, "transport", "offer", source, "retryable", "retry_dispatch");
471
471
  }
472
- if (["capacity_unavailable", "bridge.runner_draining", "docker_engine_unavailable", "docker_memory_low", "docker_memory_sample_unavailable", "docker_cpu_low", "docker_disk_low", "server_local.resource_pressure", "server_local.capacity_unavailable", "dispatch.preparation_resource_pressure", "sandbox_capacity_profile_unavailable", "host_runtime_admission_expired"].includes(code)) {
472
+ if (["capacity_unavailable", "bridge.runner_draining", "docker_engine_unavailable", "docker_memory_low", "docker_memory_sample_unavailable", "docker_cpu_low", "docker_disk_low", "server_local.resource_pressure", "server_local.capacity_unavailable", "dispatch.preparation_resource_pressure", "sandbox_capacity_profile_unavailable", "host_runtime_admission_expired", "placement_requirements_unmet", "runner_yielding", "runner_settings_pending", "runner_settings_apply_failed", "runner_tier_light", "runner_project_not_allowed"].includes(code)) {
473
473
  return facts(code, "resource", "offer", source, "retryable", "retry_dispatch");
474
474
  }
475
475
  if (["bridge.lease_retry_exhausted", "bridge.capacity_wait_exhausted"].includes(code)) {
476
476
  return facts(code, "resource", "offer", source, "non_retryable", "inspect_failure");
477
477
  }
478
- if (["prepublication_infrastructure_failed", "prepublication_capability_unavailable"].includes(code)) {
478
+ if (["prepublication_infrastructure_failed", "prepublication_capability_unavailable", "host_capacity_timeout", "host_capacity_token_fenced", "host_capacity_ledger_unavailable"].includes(code)) {
479
479
  return facts(code, "resource", "validation", source, "retryable", "retry_with_policy");
480
480
  }
481
481
  if (["prepublication_validation_failed", "prepublication_contract_invalid", "prepublication_execution_scope_invalid"].includes(code)) {
482
482
  return facts(code, "domain", "validation", source, "non_retryable", "fix_input");
483
483
  }
484
+ if (code === "comment_repair_changed_files_mismatch") {
485
+ return facts(code, "domain", "validation", source, "non_retryable", "inspect_failure");
486
+ }
484
487
  if (["generated_output_reset_failed", "generated_output_reset_unverified", "worktree_prepare_failed", "host_runtime_ledger_write_failed", "host_diagnostics_temporary_unavailable", "attempt_process_supervisor_start_failed", "attempt_process_supervisor_start_timeout"].includes(code)) {
485
488
  return facts(code, "transport", "prepare", source, "retryable", "retry_dispatch");
486
489
  }
@@ -493,7 +496,7 @@ function unvalidatedFailureFactsForCode(code, source) {
493
496
  if (code === "provider_configuration_invalid") {
494
497
  return facts(code, "provider", "prepare", source, "non_retryable", "fix_environment");
495
498
  }
496
- if (["host_port_collision", "host_runtime_process_exited", "host_runtime_listener_timeout", "host_runtime_http_readiness_timeout", "host_runtime_prepared_source_changed", "host_runtime_prepared_probe_incomplete", "host_runtime_prepared_probe_cleanup_unconfirmed"].includes(code)) {
499
+ if (["host_port_collision", "host_runtime_process_exited", "host_runtime_listener_timeout", "host_runtime_http_readiness_timeout", "host_runtime_prepared_source_changed", "host_runtime_contract_changed", "host_runtime_prepared_probe_incomplete", "host_runtime_prepared_probe_cleanup_unconfirmed"].includes(code)) {
497
500
  return facts(code, "resource", "prepare", source, "retryable", "retry_dispatch");
498
501
  }
499
502
  if (code === "host_runtime_project_start_failed") {
@@ -519,6 +522,12 @@ function unvalidatedFailureFactsForCode(code, source) {
519
522
  if (code === "provider_capacity_unavailable") {
520
523
  return facts(code, "resource", "offer", source, "retryable", "retry_dispatch");
521
524
  }
525
+ if (code === "provider_completion_tool_missing") {
526
+ return facts(code, "provider", "agent", source, "non_retryable", "inspect_failure");
527
+ }
528
+ if (["provider_terminated_at_turn_ceiling", "provider_turn_ended_with_background_work"].includes(code)) {
529
+ return facts(code, "provider", "agent", source, "retryable", "retry_with_policy");
530
+ }
522
531
  if (code === "provider_context_window_exhausted") {
523
532
  return facts(code, "provider", "agent", source, "retryable", "retry_dispatch");
524
533
  }
@@ -563,6 +572,9 @@ function unvalidatedFailureFactsForCode(code, source) {
563
572
  if (code === "worktree_branch_integration_conflict") {
564
573
  return facts(code, "domain", "agent", source, "non_retryable", "fix_input");
565
574
  }
575
+ if (["merge_resolution_reverts_upstream_changes", "merge_resolution_unresolved_conflict"].includes(code)) {
576
+ return facts(code, "domain", "validation", source, "non_retryable", "inspect_failure");
577
+ }
566
578
  if (stableFailureFamilyCodes.has(code) && code.startsWith("sandbox_")) {
567
579
  return facts(code, "provider", "agent", source, "non_retryable", "inspect_failure");
568
580
  }
@@ -0,0 +1,32 @@
1
+ import { GitClient } from "../shared/git/git.js";
2
+ /**
3
+ * What the attempt's host runtime stack was built and launched from. When the
4
+ * workspace no longer matches, the running API binary and dev server are stale:
5
+ * an uncommitted edit or an in-progress `merge --no-commit` changes the source
6
+ * without moving HEAD.
7
+ */
8
+ export interface WorkspaceRuntimeFingerprint {
9
+ readonly headSha: string;
10
+ /** Contents of MERGE_HEAD while a merge is in progress, else null. */
11
+ readonly mergeHead: string | null;
12
+ /** sha256 of `git diff HEAD --binary` (staged and unstaged changes to tracked files, mode changes included). */
13
+ readonly diffDigest: string;
14
+ /**
15
+ * sha256 over untracked, non-ignored file names, their executable bit, and their contents (or
16
+ * size and mtime for large files).
17
+ */
18
+ readonly untrackedDigest: string;
19
+ /**
20
+ * sha256 over the runtime contract as loaded now and the files its launch commands name. Git's
21
+ * views above skip ignored files, and a project may ignore its contract or a launch script; a
22
+ * change there alters what the stack runs without changing anything git reports.
23
+ */
24
+ readonly runtimeInputsDigest: string;
25
+ /** One digest over every field above. */
26
+ readonly digest: string;
27
+ }
28
+ export type WorkspaceRuntimeFingerprintReader = (worktreePath: string) => Promise<WorkspaceRuntimeFingerprint>;
29
+ export declare function readWorkspaceRuntimeFingerprint(worktreePath: string, git?: Pick<GitClient, "run">): Promise<WorkspaceRuntimeFingerprint>;
30
+ export declare function sameWorkspaceRuntimeFingerprint(left: WorkspaceRuntimeFingerprint | null, right: WorkspaceRuntimeFingerprint | null): boolean;
31
+ /** Names what changed between two fingerprints, for the restart checkpoint. */
32
+ export declare function workspaceRuntimeFingerprintChanges(previous: WorkspaceRuntimeFingerprint | null, current: WorkspaceRuntimeFingerprint): readonly string[];
@@ -0,0 +1,138 @@
1
+ import { createHash } from "node:crypto";
2
+ import fs from "node:fs/promises";
3
+ import path from "node:path";
4
+ import { GitClient } from "../shared/git/git.js";
5
+ import { loadHostRuntimeContract } from "../runtime/host-runtime-contract.js";
6
+ import { hostRuntimeContractFingerprint } from "../runtime/host-runtime-promotion.js";
7
+ import { isRuntimeOnlyPath } from "./publishable-worktree-changes.js";
8
+ /** Untracked files up to this size are hashed by content; larger ones by size and mtime. */
9
+ const untrackedContentHashLimitBytes = 1024 * 1024;
10
+ /**
11
+ * Forge's own runtime output never changes what the application runs, and Forge
12
+ * rewrites some of it (readiness manifests, completion artifacts) between passes.
13
+ */
14
+ const runtimeOnlyPathspecs = [
15
+ ":(exclude).local",
16
+ ":(exclude).forge/work-items",
17
+ ":(exclude).forge/stories",
18
+ ];
19
+ export async function readWorkspaceRuntimeFingerprint(worktreePath, git = new GitClient()) {
20
+ const headSha = (await git.run(worktreePath, ["rev-parse", "--verify", "HEAD^{commit}"])).trim().toLowerCase();
21
+ const mergeHead = await readMergeHead(git, worktreePath);
22
+ // A mode change (chmod +x on a launch script) changes what runs. The repository may set
23
+ // core.fileMode=false, which would drop it from the diff, so this read always records modes.
24
+ const diff = await git.run(worktreePath, ["-c", "core.fileMode=true", "diff", "HEAD", "--binary", "--no-ext-diff", "--no-textconv", "--", ".", ...runtimeOnlyPathspecs]);
25
+ const diffDigest = sha256(diff);
26
+ const untracked = (await git.run(worktreePath, [
27
+ "ls-files", "--others", "--exclude-standard", "-z", "--", ".", ...runtimeOnlyPathspecs,
28
+ ]))
29
+ .split("\0")
30
+ .filter(entry => entry.length > 0 && !isRuntimeOnlyPath(entry))
31
+ .sort((left, right) => left.localeCompare(right));
32
+ const untrackedHash = createHash("sha256");
33
+ for (const relative of untracked) {
34
+ untrackedHash.update(relative).update("\0");
35
+ const absolute = path.join(worktreePath, relative);
36
+ const stat = await fs.lstat(absolute).catch(() => null);
37
+ if (!stat) {
38
+ untrackedHash.update("missing\0");
39
+ continue;
40
+ }
41
+ // Like git, record the executable bit: chmod changes what runs without touching content or mtime.
42
+ untrackedHash.update(stat.isFile() && (stat.mode & 0o111) !== 0 ? "exec\0" : "plain\0");
43
+ if (stat.isFile() && stat.size <= untrackedContentHashLimitBytes) {
44
+ const content = await fs.readFile(absolute).catch(() => null);
45
+ untrackedHash.update(content ? `content:${sha256(content)}\0` : `unreadable:${stat.size}:${stat.mtimeMs}\0`);
46
+ }
47
+ else {
48
+ untrackedHash.update(`stat:${stat.size}:${stat.mtimeMs}\0`);
49
+ }
50
+ }
51
+ const untrackedDigest = `sha256:${untrackedHash.digest("hex")}`;
52
+ const runtimeInputsDigest = await readRuntimeInputsDigest(worktreePath);
53
+ const digest = sha256(JSON.stringify({ headSha, mergeHead, diffDigest, untrackedDigest, runtimeInputsDigest }));
54
+ return { headSha, mergeHead, diffDigest, untrackedDigest, runtimeInputsDigest, digest };
55
+ }
56
+ export function sameWorkspaceRuntimeFingerprint(left, right) {
57
+ return left !== null && right !== null && left.digest === right.digest;
58
+ }
59
+ /** Names what changed between two fingerprints, for the restart checkpoint. */
60
+ export function workspaceRuntimeFingerprintChanges(previous, current) {
61
+ if (!previous)
62
+ return ["unrecorded"];
63
+ const changes = [];
64
+ if (previous.headSha !== current.headSha)
65
+ changes.push("head");
66
+ if (previous.mergeHead !== current.mergeHead)
67
+ changes.push("merge_head");
68
+ if (previous.diffDigest !== current.diffDigest)
69
+ changes.push("tracked_changes");
70
+ if (previous.untrackedDigest !== current.untrackedDigest)
71
+ changes.push("untracked_files");
72
+ if (previous.runtimeInputsDigest !== current.runtimeInputsDigest)
73
+ changes.push("runtime_inputs");
74
+ return changes;
75
+ }
76
+ /**
77
+ * The loaded runtime contract (project file or derived) and each regular file inside the worktree
78
+ * that a configured launch names as its command or an argument, by executable bit and content.
79
+ * Ignored or not: these are exactly what the stack was launched from. Nothing else ignored is read.
80
+ */
81
+ async function readRuntimeInputsDigest(worktreePath) {
82
+ const hash = createHash("sha256");
83
+ let contract;
84
+ try {
85
+ contract = await loadHostRuntimeContract(worktreePath);
86
+ }
87
+ catch (error) {
88
+ // An unloadable contract is a state of its own; the restart reports why it cannot load.
89
+ const message = error instanceof Error ? error.message : String(error);
90
+ return sha256(`unloadable:${message.split(":", 1)[0]}`);
91
+ }
92
+ hash.update(`contract:${hostRuntimeContractFingerprint(contract)}\0`);
93
+ const root = await fs.realpath(worktreePath);
94
+ const named = new Set();
95
+ for (const port of contract.contract.runtime.ports) {
96
+ if (!port.launch)
97
+ continue;
98
+ const workingDirectory = path.resolve(root, port.launch.workingDirectory);
99
+ for (const candidate of [port.launch.command, ...port.launch.args]) {
100
+ if (!candidate || candidate.startsWith("-"))
101
+ continue;
102
+ const absolute = path.resolve(workingDirectory, candidate);
103
+ const relative = path.relative(root, absolute);
104
+ if (relative === "" || relative.startsWith("..") || path.isAbsolute(relative))
105
+ continue;
106
+ named.add(relative);
107
+ }
108
+ }
109
+ for (const relative of [...named].sort((left, right) => left.localeCompare(right))) {
110
+ const stat = await fs.stat(path.join(root, relative)).catch(() => null);
111
+ if (!stat?.isFile())
112
+ continue;
113
+ hash.update(relative).update("\0").update((stat.mode & 0o111) !== 0 ? "exec\0" : "plain\0");
114
+ if (stat.size <= untrackedContentHashLimitBytes) {
115
+ const content = await fs.readFile(path.join(root, relative)).catch(() => null);
116
+ hash.update(content ? `content:${sha256(content)}\0` : `unreadable:${stat.size}:${stat.mtimeMs}\0`);
117
+ }
118
+ else {
119
+ hash.update(`stat:${stat.size}:${stat.mtimeMs}\0`);
120
+ }
121
+ }
122
+ return `sha256:${hash.digest("hex")}`;
123
+ }
124
+ async function readMergeHead(git, worktreePath) {
125
+ const relative = (await git.run(worktreePath, ["rev-parse", "--git-path", "MERGE_HEAD"])).trim();
126
+ if (!relative)
127
+ return null;
128
+ const mergeHeadPath = path.resolve(worktreePath, relative);
129
+ const content = await fs.readFile(mergeHeadPath, "utf8").catch((error) => {
130
+ if (error.code === "ENOENT")
131
+ return null;
132
+ throw error;
133
+ });
134
+ return content === null ? null : content.trim().toLowerCase();
135
+ }
136
+ function sha256(value) {
137
+ return `sha256:${createHash("sha256").update(value).digest("hex")}`;
138
+ }
@@ -57,3 +57,4 @@ export declare function persistHostProcessSupervisorMetadata(launch: HostProcess
57
57
  */
58
58
  export declare function captureHostProcessIdentity(pid: number, platform?: NodeJS.Platform): string | null;
59
59
  export declare function terminateHostProcessTree(child: ChildProcess, launch: HostProcessSupervisedLaunch | null, graceMs?: number): Promise<void>;
60
+ export declare function windowsPowerShellPath(): string;
@@ -250,7 +250,7 @@ function assertMetadataPath(logDirectory, metadataPath) {
250
250
  throw new Error("host_process_supervisor_invalid: metadata path must be inside FORGE_LOG_DIR.");
251
251
  }
252
252
  }
253
- function windowsPowerShellPath() {
253
+ export function windowsPowerShellPath() {
254
254
  const systemRoot = process.env.SystemRoot?.trim() || "C:\\Windows";
255
255
  const candidate = path.win32.join(systemRoot, "System32", "WindowsPowerShell", "v1.0", "powershell.exe");
256
256
  return fs.existsSync(candidate) ? candidate : "powershell.exe";
@@ -0,0 +1,52 @@
1
+ export interface WindowsProcessEntry {
2
+ readonly pid: number;
3
+ readonly parentPid: number;
4
+ /** Creation time; a pid with a different one is a different process. */
5
+ readonly createdAt: string;
6
+ }
7
+ /** The process table and termination primitive, injectable for tests. */
8
+ export interface WindowsProcessTable {
9
+ list(): Promise<readonly WindowsProcessEntry[]>;
10
+ /** `taskkill /PID <pid> /T /F`: the process and the descendants Windows still links to it. */
11
+ killTree(pid: number): Promise<void>;
12
+ }
13
+ export declare const systemWindowsProcessTable: WindowsProcessTable;
14
+ /** What is known about the root's creation before it has been seen in the table. */
15
+ export type WindowsRootMarker =
16
+ /** Its recorded birth marker (Get-Process ticks): matched within a millisecond. */
17
+ {
18
+ readonly exactCreatedAt: string;
19
+ }
20
+ /** It was spawned no earlier than this (ticks): set synchronously at spawn. */
21
+ | {
22
+ readonly notBefore: string;
23
+ };
24
+ /** .NET ticks (100 ns since 0001-01-01 UTC), the unit Win32_Process creation times are read in. */
25
+ export declare function windowsTicksFromEpochMs(epochMs: number): string;
26
+ /** A Windows command's tracked tree; see the module comment. */
27
+ export declare class WindowsProcessTree {
28
+ private readonly rootPid;
29
+ private readonly table;
30
+ private readonly marker;
31
+ private readonly known;
32
+ /** The root's creation time as the process table reports it, once seen. */
33
+ private observedRoot;
34
+ private rootExited;
35
+ /**
36
+ * The root marker anchors the tree even if the root exits before the first
37
+ * snapshot (or, for a reaped token, before the reaper runs): descendants
38
+ * created after it whose parent was the root are still found. A tree with
39
+ * no marker that never saw its root cannot be proven gone.
40
+ */
41
+ constructor(rootPid: number, table: WindowsProcessTable, marker?: WindowsRootMarker | null);
42
+ /** The root has exited: from now on its pid only names it if its exact creation was seen. */
43
+ markRootExited(): void;
44
+ /** Records the root's current descendants; call while the command runs. */
45
+ track(): Promise<void>;
46
+ /** Stops every tracked member and proves none is left; false when one survives or nothing anchors the tree. */
47
+ stop(deadlineMs: number): Promise<boolean>;
48
+ private rootAnchor;
49
+ private isRoot;
50
+ private absorb;
51
+ private alive;
52
+ }
@@ -0,0 +1,144 @@
1
+ import { execFile } from "node:child_process";
2
+ import { promisify } from "node:util";
3
+ import { windowsPowerShellPath } from "./host-process-supervisor.js";
4
+ const execFileAsync = promisify(execFile);
5
+ export const systemWindowsProcessTable = {
6
+ async list() {
7
+ const { stdout } = await execFileAsync(windowsPowerShellPath(), [
8
+ "-NoLogo", "-NoProfile", "-NonInteractive", "-Command",
9
+ "Get-CimInstance Win32_Process | ForEach-Object { \"$($_.ProcessId) $($_.ParentProcessId) $($_.CreationDate.ToUniversalTime().Ticks)\" }",
10
+ ], { encoding: "utf8", windowsHide: true, maxBuffer: 8 * 1024 * 1024, timeout: 30_000 });
11
+ return stdout.split(/\r?\n/u).flatMap(line => {
12
+ const [pid, parentPid, createdAt] = line.trim().split(" ");
13
+ return pid && parentPid && createdAt ? [{ pid: Number(pid), parentPid: Number(parentPid), createdAt }] : [];
14
+ });
15
+ },
16
+ async killTree(pid) {
17
+ await execFileAsync("taskkill", ["/PID", String(pid), "/T", "/F"], { windowsHide: true, timeout: 30_000 })
18
+ .catch(() => undefined);
19
+ },
20
+ };
21
+ /** .NET ticks (100 ns since 0001-01-01 UTC), the unit Win32_Process creation times are read in. */
22
+ export function windowsTicksFromEpochMs(epochMs) {
23
+ return ((BigInt(Math.floor(epochMs)) + 62135596800000n) * 10000n).toString();
24
+ }
25
+ /** A Windows command's tracked tree; see the module comment. */
26
+ export class WindowsProcessTree {
27
+ rootPid;
28
+ table;
29
+ marker;
30
+ known = new Map();
31
+ /** The root's creation time as the process table reports it, once seen. */
32
+ observedRoot = null;
33
+ rootExited = false;
34
+ /**
35
+ * The root marker anchors the tree even if the root exits before the first
36
+ * snapshot (or, for a reaped token, before the reaper runs): descendants
37
+ * created after it whose parent was the root are still found. A tree with
38
+ * no marker that never saw its root cannot be proven gone.
39
+ */
40
+ constructor(rootPid, table, marker = null) {
41
+ this.rootPid = rootPid;
42
+ this.table = table;
43
+ this.marker = marker;
44
+ const anchor = this.rootAnchor();
45
+ if (anchor !== null)
46
+ this.known.set(rootPid, anchor);
47
+ }
48
+ /** The root has exited: from now on its pid only names it if its exact creation was seen. */
49
+ markRootExited() {
50
+ this.rootExited = true;
51
+ }
52
+ /** Records the root's current descendants; call while the command runs. */
53
+ async track() {
54
+ const entries = await this.table.list().catch(() => null);
55
+ if (entries)
56
+ this.absorb(entries);
57
+ }
58
+ /** Stops every tracked member and proves none is left; false when one survives or nothing anchors the tree. */
59
+ async stop(deadlineMs) {
60
+ for (;;) {
61
+ const entries = await this.table.list().catch(() => null);
62
+ if (!entries) {
63
+ if (Date.now() >= deadlineMs)
64
+ return false;
65
+ await delay(200);
66
+ continue;
67
+ }
68
+ this.absorb(entries);
69
+ // Without any anchor nothing proves which processes were the root's: fail closed.
70
+ if (!this.known.has(this.rootPid))
71
+ return false;
72
+ const alive = this.alive(entries);
73
+ if (alive.length === 0)
74
+ return true;
75
+ if (Date.now() >= deadlineMs)
76
+ return false;
77
+ for (const pid of alive)
78
+ await this.table.killTree(pid);
79
+ await delay(100);
80
+ }
81
+ }
82
+ rootAnchor() {
83
+ if (this.observedRoot !== null)
84
+ return this.observedRoot;
85
+ if (this.marker === null)
86
+ return null;
87
+ return "exactCreatedAt" in this.marker ? this.marker.exactCreatedAt : this.marker.notBefore;
88
+ }
89
+ isRoot(entry) {
90
+ if (entry.pid !== this.rootPid)
91
+ return false;
92
+ if (this.observedRoot !== null)
93
+ return entry.createdAt === this.observedRoot;
94
+ if (this.marker !== null && "exactCreatedAt" in this.marker)
95
+ return ticksClose(entry.createdAt, this.marker.exactCreatedAt);
96
+ // Before it exits, the root's pid cannot name anyone else.
97
+ if (this.rootExited)
98
+ return false;
99
+ return this.marker === null || compareTicks(entry.createdAt, this.marker.notBefore) >= 0;
100
+ }
101
+ absorb(entries) {
102
+ const root = entries.find(entry => this.isRoot(entry));
103
+ if (root && this.observedRoot === null)
104
+ this.observedRoot = root.createdAt;
105
+ const anchor = this.rootAnchor();
106
+ if (anchor !== null)
107
+ this.known.set(this.rootPid, anchor);
108
+ // Parents first: repeat until no new descendant of a known member appears.
109
+ let added = true;
110
+ while (added) {
111
+ added = false;
112
+ for (const entry of entries) {
113
+ if (this.known.has(entry.pid) || entry.pid === entry.parentPid)
114
+ continue;
115
+ const parentCreatedAt = this.known.get(entry.parentPid);
116
+ // A child is never older than its parent; an older one only reuses the parent's pid as its parent id.
117
+ if (parentCreatedAt === undefined || compareTicks(entry.createdAt, parentCreatedAt) < 0)
118
+ continue;
119
+ this.known.set(entry.pid, entry.createdAt);
120
+ added = true;
121
+ }
122
+ }
123
+ }
124
+ alive(entries) {
125
+ return entries
126
+ .filter(entry => entry.pid === this.rootPid ? this.isRoot(entry) : this.known.get(entry.pid) === entry.createdAt)
127
+ .map(entry => entry.pid);
128
+ }
129
+ }
130
+ function ticksClose(left, right) {
131
+ if (!/^\d+$/u.test(left) || !/^\d+$/u.test(right))
132
+ return left === right;
133
+ const difference = BigInt(left) - BigInt(right);
134
+ return (difference < 0n ? -difference : difference) <= 10000n;
135
+ }
136
+ function compareTicks(left, right) {
137
+ if (/^\d+$/u.test(left) && /^\d+$/u.test(right)) {
138
+ return left.length === right.length ? left.localeCompare(right) : left.length - right.length;
139
+ }
140
+ return left.localeCompare(right);
141
+ }
142
+ async function delay(ms) {
143
+ await new Promise(resolve => setTimeout(resolve, ms));
144
+ }