@loucompanion/forge-bridge 0.1.3-dev.d46a8e73d03d → 0.1.3-dev.eeefdb0d19c1

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 (118) hide show
  1. package/README.md +34 -0
  2. package/dist/bridge/bridge.base.d.ts +2 -1
  3. package/dist/bridge/bridge.service.d.ts +22 -3
  4. package/dist/bridge/bridge.service.js +416 -40
  5. package/dist/bridge/bridge.types.d.ts +59 -1
  6. package/dist/cleanup/cleanup.service.d.ts +13 -2
  7. package/dist/cleanup/cleanup.service.js +435 -3
  8. package/dist/cleanup/cleanup.types.d.ts +10 -0
  9. package/dist/cleanup/index.d.ts +1 -1
  10. package/dist/cleanup/index.js +1 -1
  11. package/dist/cleanup/internals.d.ts +2 -2
  12. package/dist/cleanup/internals.js +1 -1
  13. package/dist/cli/cli.help.js +37 -3
  14. package/dist/cli/cli.service.d.ts +30 -2
  15. package/dist/cli/cli.service.js +182 -23
  16. package/dist/cli/local-config.d.ts +4 -0
  17. package/dist/cli/local-config.js +41 -1
  18. package/dist/runtime/attempt-node-runtime-launcher.d.ts +17 -0
  19. package/dist/runtime/attempt-node-runtime-launcher.js +101 -0
  20. package/dist/runtime/attempt-process-supervisor-registry.d.ts +20 -0
  21. package/dist/runtime/attempt-process-supervisor-registry.js +64 -0
  22. package/dist/runtime/attempt-process-supervisor.d.ts +86 -0
  23. package/dist/runtime/attempt-process-supervisor.js +343 -0
  24. package/dist/runtime/generated-output-reset.d.ts +10 -0
  25. package/dist/runtime/generated-output-reset.js +103 -0
  26. package/dist/runtime/host-listener-inspector.d.ts +44 -0
  27. package/dist/runtime/host-listener-inspector.js +324 -0
  28. package/dist/runtime/host-port-broker.d.ts +76 -0
  29. package/dist/runtime/host-port-broker.js +333 -0
  30. package/dist/runtime/host-runtime-contract.d.ts +47 -0
  31. package/dist/runtime/host-runtime-contract.js +700 -0
  32. package/dist/runtime/host-runtime-lease.d.ts +133 -0
  33. package/dist/runtime/host-runtime-lease.js +1460 -0
  34. package/dist/runtime/host-runtime-promotion.d.ts +23 -0
  35. package/dist/runtime/host-runtime-promotion.js +159 -0
  36. package/dist/runtime/node-host-runtime-adapter.d.ts +51 -0
  37. package/dist/runtime/node-host-runtime-adapter.js +268 -0
  38. package/dist/runtime/playwright-host-runtime-adapter.d.ts +20 -0
  39. package/dist/runtime/playwright-host-runtime-adapter.js +220 -0
  40. package/dist/runtime/runtime-isolation-lease.d.ts +67 -0
  41. package/dist/runtime/runtime-isolation-lease.js +158 -0
  42. package/dist/sandbox/preflight.d.ts +14 -0
  43. package/dist/sandbox/preflight.js +91 -12
  44. package/dist/sandbox/process.js +125 -40
  45. package/dist/sandbox/repository-lock.js +37 -1
  46. package/dist/sandbox/runtime.d.ts +66 -3
  47. package/dist/sandbox/runtime.js +670 -105
  48. package/dist/sandbox/sandbox.types.d.ts +3 -0
  49. package/dist/sandbox/smoke.d.ts +76 -0
  50. package/dist/sandbox/smoke.js +380 -0
  51. package/dist/sandbox/worker-supervisor.js +1 -1
  52. package/dist/sandbox/worker.js +2 -5
  53. package/dist/sandbox/workspace.service.d.ts +1 -0
  54. package/dist/sandbox/workspace.service.js +28 -5
  55. package/dist/session/managed-attempt-tools.d.ts +12 -0
  56. package/dist/session/managed-attempt-tools.js +350 -0
  57. package/dist/session/phase-completion.artifacts.js +9 -2
  58. package/dist/session/phase-completion.d.ts +4 -2
  59. package/dist/session/phase-completion.helpers.js +27 -3
  60. package/dist/session/phase-completion.js +12 -3
  61. package/dist/session/phase-completion.prompts.d.ts +3 -3
  62. package/dist/session/phase-completion.prompts.js +19 -5
  63. package/dist/session/phase-completion.runtime.d.ts +12 -1
  64. package/dist/session/phase-completion.runtime.js +127 -7
  65. package/dist/session/phase-completion.schemas.js +108 -3
  66. package/dist/session/phase-completion.validation.d.ts +4 -1
  67. package/dist/session/phase-completion.validation.js +106 -2
  68. package/dist/session/provider-cli/ci-repair-readiness.d.ts +8 -0
  69. package/dist/session/provider-cli/ci-repair-readiness.js +90 -0
  70. package/dist/session/provider-cli/provider-cli.artifacts.d.ts +1 -1
  71. package/dist/session/provider-cli/provider-cli.artifacts.js +28 -4
  72. package/dist/session/provider-cli/provider-cli.deterministic.js +47 -1
  73. package/dist/session/provider-cli/provider-cli.process.d.ts +16 -0
  74. package/dist/session/provider-cli/provider-cli.process.js +212 -25
  75. package/dist/session/provider-cli/provider-cli.prompts.d.ts +4 -1
  76. package/dist/session/provider-cli/provider-cli.prompts.js +84 -17
  77. package/dist/session/provider-cli/provider-cli.qa-sidecars.js +1 -0
  78. package/dist/session/provider-cli/provider-cli.runtime.d.ts +1 -1
  79. package/dist/session/provider-cli/provider-cli.runtime.js +3 -2
  80. package/dist/session/provider-cli/provider-cli.service.d.ts +3 -2
  81. package/dist/session/provider-cli/provider-cli.service.js +254 -71
  82. package/dist/session/provider-cli/provider-cli.types.d.ts +5 -0
  83. package/dist/session/provider-cli/provider-output-state.d.ts +2 -0
  84. package/dist/session/provider-cli/provider-output-state.js +30 -2
  85. package/dist/session/session-redaction.d.ts +3 -0
  86. package/dist/session/session-redaction.js +23 -0
  87. package/dist/session/session.base.d.ts +6 -1
  88. package/dist/session/session.service.d.ts +8 -2
  89. package/dist/session/session.service.js +436 -41
  90. package/dist/session/session.types.d.ts +55 -0
  91. package/dist/session/session.types.js +69 -2
  92. package/dist/shared/path/path.js +3 -1
  93. package/dist/shared/process/host-process-recovery.d.ts +12 -0
  94. package/dist/shared/process/host-process-recovery.js +78 -0
  95. package/dist/shared/process/host-process-supervisor.d.ts +57 -0
  96. package/dist/shared/process/host-process-supervisor.js +282 -0
  97. package/dist/shared/process/process.d.ts +1 -0
  98. package/dist/shared/process/process.js +1 -0
  99. package/dist/shared/redaction/redaction.js +6 -1
  100. package/dist/version.d.ts +1 -1
  101. package/dist/version.js +1 -1
  102. package/dist/worktree/artifact-injector.d.ts +3 -2
  103. package/dist/worktree/artifact-injector.js +43 -4
  104. package/dist/worktree/dependency-warmer.d.ts +10 -1
  105. package/dist/worktree/dependency-warmer.js +94 -5
  106. package/dist/worktree/index.d.ts +1 -0
  107. package/dist/worktree/index.js +1 -0
  108. package/dist/worktree/prior-phase-artifact-hydrator.d.ts +2 -0
  109. package/dist/worktree/prior-phase-artifact-hydrator.js +136 -0
  110. package/dist/worktree/worktree-paths.d.ts +4 -0
  111. package/dist/worktree/worktree-paths.js +30 -0
  112. package/dist/worktree/worktree.base.d.ts +3 -0
  113. package/dist/worktree/worktree.service.d.ts +7 -2
  114. package/dist/worktree/worktree.service.js +72 -44
  115. package/dist/worktree/worktree.types.d.ts +3 -1
  116. package/package.json +3 -2
  117. package/runtime/windows-job-supervisor.ps1 +356 -0
  118. package/runtime/windows-listener-owner.ps1 +33 -0
@@ -0,0 +1,101 @@
1
+ import { createHash } from "node:crypto";
2
+ import fs from "node:fs/promises";
3
+ import path from "node:path";
4
+ import { HostListenerInspector } from "./host-listener-inspector.js";
5
+ const diagnosticTailLength = 4_000;
6
+ /** Launches one explicitly configured HTTP project beneath the attempt coordinator. */
7
+ export class AttemptNodeRuntimeLauncher {
8
+ supervisor;
9
+ owner;
10
+ logDirectory;
11
+ listenerInspector;
12
+ diagnosticsByChild = new WeakMap();
13
+ constructor(supervisor, owner, logDirectory, listenerInspector = new HostListenerInspector()) {
14
+ this.supervisor = supervisor;
15
+ this.owner = owner;
16
+ this.logDirectory = logDirectory;
17
+ this.listenerInspector = listenerInspector;
18
+ }
19
+ async launch(request, signal) {
20
+ const childName = projectChildName(request.port.name);
21
+ const stdoutPath = path.join(this.logDirectory, `${childName}.stdout.log`);
22
+ const stderrPath = path.join(this.logDirectory, `${childName}.stderr.log`);
23
+ const diagnostics = { exited: false, stdoutTail: "", stderrTail: "" };
24
+ let child;
25
+ try {
26
+ child = await this.supervisor.startChildReady(childName, {
27
+ command: request.command,
28
+ args: request.args,
29
+ cwd: request.cwd,
30
+ env: request.environment,
31
+ captureOutput: false,
32
+ }, {
33
+ onStdoutLine: async (line) => {
34
+ diagnostics.stdoutTail = appendTail(diagnostics.stdoutTail, line);
35
+ await appendLine(stdoutPath, line);
36
+ },
37
+ onStderrLine: async (line) => {
38
+ diagnostics.stderrTail = appendTail(diagnostics.stderrTail, line);
39
+ await appendLine(stderrPath, line);
40
+ },
41
+ }, signal, { maxStartAttempts: 3, retryDelayMs: 250 });
42
+ }
43
+ catch (error) {
44
+ throw enrichLaunchFailure(error, diagnostics);
45
+ }
46
+ this.diagnosticsByChild.set(child, diagnostics);
47
+ void child.result.then(result => {
48
+ diagnostics.exited = true;
49
+ diagnostics.exitCode = result.exitCode;
50
+ diagnostics.stdoutTail = appendTail(diagnostics.stdoutTail, result.stdout);
51
+ diagnostics.stderrTail = appendTail(diagnostics.stderrTail, result.stderr);
52
+ }, error => {
53
+ diagnostics.exited = true;
54
+ diagnostics.stderrTail = appendTail(diagnostics.stderrTail, error instanceof Error ? error.message : String(error));
55
+ });
56
+ return child;
57
+ }
58
+ async inspectListener(child, request) {
59
+ return await this.listenerInspector.inspect(child, request.port, this.owner);
60
+ }
61
+ async stop(child) {
62
+ await child.stop(this.owner.fencingToken);
63
+ }
64
+ async readinessDiagnostics(child) {
65
+ // Yield once so an already-settled result can update the diagnostic record.
66
+ await Promise.resolve();
67
+ const diagnostics = this.diagnosticsByChild.get(child);
68
+ return diagnostics ?? { exited: false };
69
+ }
70
+ }
71
+ function projectChildName(portName) {
72
+ const candidate = `project-${portName}`;
73
+ if (/^[a-z][a-z0-9_-]{0,31}$/u.test(candidate))
74
+ return candidate;
75
+ const digest = createHash("sha256").update(portName).digest("hex").slice(0, 16);
76
+ return `project-${digest}`;
77
+ }
78
+ async function appendLine(target, line) {
79
+ await fs.appendFile(target, `${line}\n`, { encoding: "utf8", mode: 0o600 });
80
+ }
81
+ function appendTail(current, value) {
82
+ if (!value)
83
+ return current;
84
+ const combined = current ? `${current}\n${value}` : value;
85
+ return combined.slice(-diagnosticTailLength);
86
+ }
87
+ function enrichLaunchFailure(error, diagnostics) {
88
+ const message = error instanceof Error ? error.message : String(error);
89
+ const evidence = [
90
+ diagnostics.stderrTail ? `stderr tail: ${boundedDiagnostic(diagnostics.stderrTail)}` : "",
91
+ diagnostics.stdoutTail ? `stdout tail: ${boundedDiagnostic(diagnostics.stdoutTail)}` : "",
92
+ ].filter(Boolean);
93
+ return evidence.length > 0
94
+ ? new Error(`${message} ${evidence.join("; ")}`, { cause: error })
95
+ : error instanceof Error
96
+ ? error
97
+ : new Error(message);
98
+ }
99
+ function boundedDiagnostic(value) {
100
+ return value.replaceAll(/[\r\n\t]+/gu, " ").trim().slice(-1_000);
101
+ }
@@ -0,0 +1,20 @@
1
+ import type { ProviderProcessHandlers, ProviderProcessRunRequest, ProviderProcessRunner, ProviderProcessRunResult } from "../session/provider-cli/provider-cli.process.js";
2
+ import { AttemptProcessSupervisor, type AttemptProcessSupervisorIdentity, type AttemptProcessSupervisorOptions } from "./attempt-process-supervisor.js";
3
+ /** Runner-local authority for active host attempt process coordinators. */
4
+ export declare class AttemptProcessSupervisorRegistry {
5
+ private readonly active;
6
+ register(identity: AttemptProcessSupervisorIdentity, runner: ProviderProcessRunner, options?: AttemptProcessSupervisorOptions): AttemptProcessSupervisor;
7
+ require(dispatchAttemptId: string, fencingToken: string): AttemptProcessSupervisor;
8
+ unregister(dispatchAttemptId: string, fencingToken: string): boolean;
9
+ has(dispatchAttemptId: string): boolean;
10
+ }
11
+ /**
12
+ * Routes managed-host provider commands through the attempt's named provider
13
+ * child while retaining the raw runner for Docker and unmanaged execution.
14
+ */
15
+ export declare class AttemptCoordinatedProviderProcessRunner implements ProviderProcessRunner {
16
+ private readonly registry;
17
+ private readonly rawRunner;
18
+ constructor(registry: AttemptProcessSupervisorRegistry, rawRunner: ProviderProcessRunner);
19
+ run(request: ProviderProcessRunRequest, handlers?: ProviderProcessHandlers, signal?: AbortSignal): Promise<ProviderProcessRunResult>;
20
+ }
@@ -0,0 +1,64 @@
1
+ import { AttemptProcessSupervisor, } from "./attempt-process-supervisor.js";
2
+ /** Runner-local authority for active host attempt process coordinators. */
3
+ export class AttemptProcessSupervisorRegistry {
4
+ active = new Map();
5
+ register(identity, runner, options = {}) {
6
+ const existing = this.active.get(identity.dispatchAttemptId);
7
+ if (existing) {
8
+ if (existing.fencingToken !== identity.fencingToken) {
9
+ throw new Error("attempt_process_registry_conflict: dispatch attempt is registered under a different fence.");
10
+ }
11
+ return existing.supervisor;
12
+ }
13
+ const supervisor = new AttemptProcessSupervisor(identity, runner, options);
14
+ this.active.set(identity.dispatchAttemptId, { fencingToken: identity.fencingToken, supervisor });
15
+ return supervisor;
16
+ }
17
+ require(dispatchAttemptId, fencingToken) {
18
+ const registered = this.active.get(dispatchAttemptId);
19
+ if (!registered) {
20
+ throw new Error("attempt_process_registry_missing: no process coordinator owns this dispatch attempt.");
21
+ }
22
+ if (registered.fencingToken !== fencingToken) {
23
+ throw new Error("attempt_process_registry_fenced: process coordinator fence does not match the dispatch.");
24
+ }
25
+ return registered.supervisor;
26
+ }
27
+ unregister(dispatchAttemptId, fencingToken) {
28
+ const registered = this.active.get(dispatchAttemptId);
29
+ if (!registered || registered.fencingToken !== fencingToken)
30
+ return false;
31
+ return this.active.delete(dispatchAttemptId);
32
+ }
33
+ has(dispatchAttemptId) {
34
+ return this.active.has(dispatchAttemptId);
35
+ }
36
+ }
37
+ /**
38
+ * Routes managed-host provider commands through the attempt's named provider
39
+ * child while retaining the raw runner for Docker and unmanaged execution.
40
+ */
41
+ export class AttemptCoordinatedProviderProcessRunner {
42
+ registry;
43
+ rawRunner;
44
+ constructor(registry, rawRunner) {
45
+ this.registry = registry;
46
+ this.rawRunner = rawRunner;
47
+ }
48
+ async run(request, handlers, signal) {
49
+ if (request.env?.FORGE_RUNTIME_MODE !== "host") {
50
+ return await this.rawRunner.run(request, handlers, signal);
51
+ }
52
+ const dispatchAttemptId = requiredEnvironment(request, "FORGE_DISPATCH_ATTEMPT_ID");
53
+ const fencingToken = requiredEnvironment(request, "FORGE_FENCING_TOKEN");
54
+ const supervisor = this.registry.require(dispatchAttemptId, fencingToken);
55
+ const child = await supervisor.startChildReady("provider", request, handlers, signal, { maxStartAttempts: request.stdin === undefined ? 1 : 3, retryDelayMs: 100 });
56
+ return await child.result;
57
+ }
58
+ }
59
+ function requiredEnvironment(request, name) {
60
+ const value = request.env?.[name]?.trim();
61
+ if (!value)
62
+ throw new Error(`attempt_process_registry_invalid: ${name} is required for managed-host execution.`);
63
+ return value;
64
+ }
@@ -0,0 +1,86 @@
1
+ import type { ProviderProcessHandlers, ProviderProcessRunRequest, ProviderProcessRunner, ProviderProcessRunResult } from "../session/provider-cli/provider-cli.process.js";
2
+ export type AttemptProcessChildStatus = "starting" | "running" | "stopping" | "exited" | "failed";
3
+ export type AttemptProcessSupervisorStatus = "active" | "stopping" | "stopped" | "degraded";
4
+ export interface AttemptProcessSupervisorIdentity {
5
+ readonly processSupervisorId: string;
6
+ readonly dispatchAttemptId: string;
7
+ readonly executionLeaseId: string;
8
+ readonly fencingToken: string;
9
+ readonly logDirectory: string;
10
+ }
11
+ export interface AttemptProcessChildLedgerEntry {
12
+ readonly name: string;
13
+ readonly generation: number;
14
+ readonly childId: string;
15
+ readonly processSupervisorId: string;
16
+ readonly metadataPath: string;
17
+ readonly status: AttemptProcessChildStatus;
18
+ readonly startedAt: string;
19
+ readonly settledAt?: string;
20
+ readonly exitCode?: number;
21
+ readonly failure?: string;
22
+ }
23
+ export interface AttemptProcessSupervisorLedger {
24
+ readonly schemaVersion: 1;
25
+ readonly attemptSupervisorId: string;
26
+ readonly dispatchAttemptId: string;
27
+ readonly executionLeaseId: string;
28
+ readonly status: AttemptProcessSupervisorStatus;
29
+ readonly updatedAt: string;
30
+ readonly children: readonly AttemptProcessChildLedgerEntry[];
31
+ }
32
+ export interface AttemptProcessChildHandle {
33
+ readonly name: string;
34
+ readonly generation: number;
35
+ readonly childId: string;
36
+ readonly processSupervisorId: string;
37
+ readonly metadataPath: string;
38
+ readonly ready: Promise<void>;
39
+ readonly result: Promise<ProviderProcessRunResult>;
40
+ stop(fencingToken: string): Promise<ProviderProcessRunResult>;
41
+ }
42
+ export interface AttemptProcessSupervisorOptions {
43
+ readonly metadataReadyTimeoutMs?: number;
44
+ readonly signal?: AbortSignal;
45
+ }
46
+ export interface AttemptProcessChildReadyOptions {
47
+ readonly maxStartAttempts?: number;
48
+ readonly retryDelayMs?: number;
49
+ }
50
+ /**
51
+ * Owns the independently supervised process trees that belong to one host
52
+ * dispatch attempt. Each named child gets a distinct Windows Job Object or
53
+ * Unix process group through the existing process runner, while this
54
+ * coordinator supplies shared fencing, cancellation, and a durable ledger.
55
+ */
56
+ export declare class AttemptProcessSupervisor {
57
+ private readonly runner;
58
+ readonly ledgerPath: string;
59
+ private readonly identity;
60
+ private readonly metadataReadyTimeoutMs;
61
+ private readonly records;
62
+ private readonly currentByName;
63
+ private readonly attemptController;
64
+ private status;
65
+ private persistTail;
66
+ private persistenceFailure;
67
+ private stopOperation;
68
+ constructor(identity: AttemptProcessSupervisorIdentity, runner: ProviderProcessRunner, options?: AttemptProcessSupervisorOptions);
69
+ startChild(name: string, request: ProviderProcessRunRequest, handlers?: ProviderProcessHandlers, signal?: AbortSignal): Promise<AttemptProcessChildHandle>;
70
+ /**
71
+ * Starts a child and proves that the OS process tree is supervised before
72
+ * returning it to the caller. A launch that settles before producing its
73
+ * provider-ready supervision record is safe to retry: the raw runner only
74
+ * persists that record after the actual provider child has started, before
75
+ * Forge announces the provider as active.
76
+ */
77
+ startChildReady(name: string, request: ProviderProcessRunRequest, handlers?: ProviderProcessHandlers, signal?: AbortSignal, options?: AttemptProcessChildReadyOptions): Promise<AttemptProcessChildHandle>;
78
+ stopChild(name: string, generation: number, fencingToken: string, reason?: unknown): Promise<ProviderProcessRunResult>;
79
+ stopAll(fencingToken: string, reason?: unknown): Promise<void>;
80
+ private performStopAll;
81
+ snapshot(): AttemptProcessSupervisorLedger;
82
+ private observeChildReady;
83
+ private settleChild;
84
+ private assertFence;
85
+ private persist;
86
+ }
@@ -0,0 +1,343 @@
1
+ import { createHash } from "node:crypto";
2
+ import fs from "node:fs/promises";
3
+ import path from "node:path";
4
+ const terminalChildStatuses = new Set(["exited", "failed"]);
5
+ const defaultMetadataReadyTimeoutMs = process.platform === "win32" ? 60_000 : 10_000;
6
+ /**
7
+ * Owns the independently supervised process trees that belong to one host
8
+ * dispatch attempt. Each named child gets a distinct Windows Job Object or
9
+ * Unix process group through the existing process runner, while this
10
+ * coordinator supplies shared fencing, cancellation, and a durable ledger.
11
+ */
12
+ export class AttemptProcessSupervisor {
13
+ runner;
14
+ ledgerPath;
15
+ identity;
16
+ metadataReadyTimeoutMs;
17
+ records = [];
18
+ currentByName = new Map();
19
+ attemptController = new AbortController();
20
+ status = "active";
21
+ persistTail = Promise.resolve();
22
+ persistenceFailure;
23
+ stopOperation = null;
24
+ constructor(identity, runner, options = {}) {
25
+ this.runner = runner;
26
+ this.identity = validateIdentity(identity);
27
+ this.metadataReadyTimeoutMs = boundedInteger(options.metadataReadyTimeoutMs ?? defaultMetadataReadyTimeoutMs, 100, 120_000, "metadataReadyTimeoutMs");
28
+ this.ledgerPath = path.join(this.identity.logDirectory, "attempt-process-supervisor.json");
29
+ if (options.signal?.aborted) {
30
+ this.status = "stopping";
31
+ this.attemptController.abort(options.signal.reason);
32
+ }
33
+ else {
34
+ options.signal?.addEventListener("abort", () => {
35
+ void this.stopAll(this.identity.fencingToken, options.signal?.reason).catch(error => {
36
+ this.persistenceFailure ??= error;
37
+ });
38
+ }, { once: true });
39
+ }
40
+ }
41
+ async startChild(name, request, handlers = {}, signal) {
42
+ assertChildName(name);
43
+ if (this.status !== "active" || this.attemptController.signal.aborted) {
44
+ throw new Error("attempt_process_supervisor_closed: the attempt no longer accepts child processes.");
45
+ }
46
+ if (signal?.aborted)
47
+ throw cancellationError(signal);
48
+ const existing = this.currentByName.get(name);
49
+ if (existing && !terminalChildStatuses.has(existing.status)) {
50
+ throw new Error(`attempt_process_supervisor_conflict: child '${name}' is already active.`);
51
+ }
52
+ const generation = (existing?.generation ?? 0) + 1;
53
+ const childId = `${name}:${generation}`;
54
+ const processSupervisorId = childProcessSupervisorId(this.identity.processSupervisorId, childId);
55
+ const metadataPath = path.join(this.identity.logDirectory, `process-supervisor.${name}.${generation}.json`);
56
+ const controller = new AbortController();
57
+ const combinedSignal = signal
58
+ ? AbortSignal.any([this.attemptController.signal, controller.signal, signal])
59
+ : AbortSignal.any([this.attemptController.signal, controller.signal]);
60
+ const childRequest = {
61
+ ...request,
62
+ env: {
63
+ ...request.env,
64
+ FORGE_RUNTIME_MODE: "host",
65
+ FORGE_RESOURCE_LEASE_ID: this.identity.executionLeaseId,
66
+ FORGE_EXECUTION_LEASE_ID: this.identity.executionLeaseId,
67
+ FORGE_DISPATCH_ATTEMPT_ID: this.identity.dispatchAttemptId,
68
+ FORGE_FENCING_TOKEN: this.identity.fencingToken,
69
+ FORGE_LOG_DIR: this.identity.logDirectory,
70
+ FORGE_PROCESS_SUPERVISOR_ID: processSupervisorId,
71
+ FORGE_PROCESS_SUPERVISOR_METADATA_PATH: metadataPath,
72
+ FORGE_PROCESS_CHILD_ID: childId,
73
+ FORGE_PROCESS_CHILD_NAME: name,
74
+ FORGE_PROCESS_CHILD_GENERATION: String(generation),
75
+ },
76
+ };
77
+ const startedAt = new Date().toISOString();
78
+ const record = {
79
+ name,
80
+ generation,
81
+ childId,
82
+ processSupervisorId,
83
+ metadataPath,
84
+ controller,
85
+ startedAt,
86
+ status: "starting",
87
+ result: Promise.resolve({ exitCode: 1, stdout: "", stderr: "not started" }),
88
+ };
89
+ this.records.push(record);
90
+ this.currentByName.set(name, record);
91
+ const result = this.runner.run(childRequest, handlers, combinedSignal);
92
+ record.result = result;
93
+ void result.then(value => this.settleChild(record, "exited", value.exitCode), error => this.settleChild(record, "failed", undefined, error));
94
+ try {
95
+ await this.persist();
96
+ }
97
+ catch (error) {
98
+ controller.abort("Attempt process ledger could not be persisted.");
99
+ await result.catch(() => undefined);
100
+ throw error;
101
+ }
102
+ const ready = this.observeChildReady(record);
103
+ void ready.catch(() => undefined);
104
+ return {
105
+ name,
106
+ generation,
107
+ childId,
108
+ processSupervisorId,
109
+ metadataPath,
110
+ ready,
111
+ result,
112
+ stop: async (fencingToken) => await this.stopChild(name, generation, fencingToken),
113
+ };
114
+ }
115
+ /**
116
+ * Starts a child and proves that the OS process tree is supervised before
117
+ * returning it to the caller. A launch that settles before producing its
118
+ * provider-ready supervision record is safe to retry: the raw runner only
119
+ * persists that record after the actual provider child has started, before
120
+ * Forge announces the provider as active.
121
+ */
122
+ async startChildReady(name, request, handlers = {}, signal, options = {}) {
123
+ const maxStartAttempts = boundedInteger(options.maxStartAttempts ?? 1, 1, 5, "maxStartAttempts");
124
+ const retryDelayMs = boundedInteger(options.retryDelayMs ?? 100, 0, 5_000, "retryDelayMs");
125
+ let lastError;
126
+ for (let attempt = 1; attempt <= maxStartAttempts; attempt += 1) {
127
+ const child = await this.startChild(name, request, handlers, signal);
128
+ try {
129
+ await child.ready;
130
+ return child;
131
+ }
132
+ catch (error) {
133
+ lastError = error;
134
+ await child.result.catch(() => undefined);
135
+ if (!isRetryableStartFailure(error) || attempt === maxStartAttempts)
136
+ throw error;
137
+ if (signal?.aborted)
138
+ throw cancellationError(signal);
139
+ if (retryDelayMs > 0)
140
+ await wait(retryDelayMs * attempt);
141
+ }
142
+ }
143
+ throw lastError;
144
+ }
145
+ async stopChild(name, generation, fencingToken, reason = "Forge stopped the supervised child.") {
146
+ this.assertFence(fencingToken);
147
+ const record = this.currentByName.get(name);
148
+ if (!record || record.generation !== generation) {
149
+ throw new Error(`attempt_process_supervisor_stale: child '${name}' generation ${generation} is no longer current.`);
150
+ }
151
+ if (!terminalChildStatuses.has(record.status)) {
152
+ record.status = "stopping";
153
+ record.controller.abort(reason);
154
+ await this.persist();
155
+ }
156
+ return await record.result;
157
+ }
158
+ async stopAll(fencingToken, reason = "Forge stopped the supervised attempt.") {
159
+ this.assertFence(fencingToken);
160
+ if (this.status === "stopped")
161
+ return;
162
+ if (!this.stopOperation) {
163
+ const operation = this.performStopAll(reason);
164
+ this.stopOperation = operation;
165
+ void operation.catch(() => undefined).finally(() => {
166
+ if (this.stopOperation === operation && this.status !== "stopped")
167
+ this.stopOperation = null;
168
+ });
169
+ }
170
+ return await this.stopOperation;
171
+ }
172
+ async performStopAll(reason) {
173
+ this.status = "stopping";
174
+ this.attemptController.abort(reason);
175
+ const active = [...this.currentByName.values()].filter(record => !terminalChildStatuses.has(record.status));
176
+ for (const record of active)
177
+ record.status = "stopping";
178
+ await this.persist();
179
+ const results = await Promise.allSettled(active.map(record => record.result));
180
+ const rejected = results.filter((result) => result.status === "rejected");
181
+ this.status = rejected.length > 0 || this.persistenceFailure !== undefined ? "degraded" : "stopped";
182
+ await this.persist();
183
+ if (rejected.length > 0) {
184
+ throw new AggregateError(rejected.map(result => result.reason), "attempt_process_supervisor_cleanup_degraded");
185
+ }
186
+ if (this.persistenceFailure !== undefined)
187
+ throw this.persistenceFailure;
188
+ }
189
+ snapshot() {
190
+ return {
191
+ schemaVersion: 1,
192
+ attemptSupervisorId: this.identity.processSupervisorId,
193
+ dispatchAttemptId: this.identity.dispatchAttemptId,
194
+ executionLeaseId: this.identity.executionLeaseId,
195
+ status: this.status,
196
+ updatedAt: new Date().toISOString(),
197
+ children: this.records.map(record => ({
198
+ name: record.name,
199
+ generation: record.generation,
200
+ childId: record.childId,
201
+ processSupervisorId: record.processSupervisorId,
202
+ metadataPath: record.metadataPath,
203
+ status: record.status,
204
+ startedAt: record.startedAt,
205
+ ...(record.settledAt ? { settledAt: record.settledAt } : {}),
206
+ ...(record.exitCode === undefined ? {} : { exitCode: record.exitCode }),
207
+ ...(record.failure ? { failure: record.failure } : {}),
208
+ })),
209
+ };
210
+ }
211
+ async observeChildReady(record) {
212
+ const deadline = Date.now() + this.metadataReadyTimeoutMs;
213
+ while (Date.now() <= deadline) {
214
+ if (await fileExists(record.metadataPath)) {
215
+ if (record.status === "starting") {
216
+ record.status = "running";
217
+ await this.persist();
218
+ }
219
+ return;
220
+ }
221
+ if (terminalChildStatuses.has(record.status)) {
222
+ const detail = await childStartFailureDetail(record);
223
+ throw new Error(`attempt_process_supervisor_start_failed: child '${record.childId}' exited before supervision metadata was produced${detail ? `: ${detail}` : "."}`);
224
+ }
225
+ await wait(25);
226
+ }
227
+ record.controller.abort("Supervised child metadata was not produced before the readiness deadline.");
228
+ const detail = await childStartFailureDetail(record);
229
+ throw new Error(`attempt_process_supervisor_start_timeout: child '${record.childId}' did not become supervised${detail ? `: ${detail}` : "."}`);
230
+ }
231
+ async settleChild(record, status, exitCode, failure) {
232
+ record.status = status;
233
+ record.settledAt = new Date().toISOString();
234
+ record.exitCode = exitCode;
235
+ record.failure = failure === undefined ? undefined : boundedFailure(failure);
236
+ await this.persist().catch(error => {
237
+ this.persistenceFailure ??= error;
238
+ this.status = "degraded";
239
+ });
240
+ }
241
+ assertFence(fencingToken) {
242
+ if (fencingToken !== this.identity.fencingToken) {
243
+ throw new Error("attempt_process_supervisor_fenced: fencing token does not own this attempt.");
244
+ }
245
+ }
246
+ persist() {
247
+ const snapshot = this.snapshot();
248
+ const operation = this.persistTail.then(async () => {
249
+ await ensurePrivateDirectory(this.identity.logDirectory);
250
+ const temporary = `${this.ledgerPath}.${process.pid}.${Date.now()}.${Math.random().toString(16).slice(2)}.tmp`;
251
+ try {
252
+ const handle = await fs.open(temporary, "wx", 0o600);
253
+ try {
254
+ await handle.writeFile(`${JSON.stringify(snapshot)}\n`);
255
+ await handle.sync();
256
+ }
257
+ finally {
258
+ await handle.close();
259
+ }
260
+ await fs.rename(temporary, this.ledgerPath);
261
+ }
262
+ catch (error) {
263
+ await fs.rm(temporary, { force: true }).catch(() => undefined);
264
+ throw error;
265
+ }
266
+ });
267
+ this.persistTail = operation.catch(() => undefined);
268
+ return operation;
269
+ }
270
+ }
271
+ function validateIdentity(identity) {
272
+ if (!/^[A-Za-z0-9][A-Za-z0-9_.-]{0,127}$/u.test(identity.processSupervisorId)) {
273
+ throw new Error("attempt_process_supervisor_invalid: process supervisor id is invalid.");
274
+ }
275
+ assertUuid(identity.dispatchAttemptId, "dispatch attempt");
276
+ assertUuid(identity.executionLeaseId, "execution lease");
277
+ assertUuid(identity.fencingToken, "fencing token");
278
+ if (!path.isAbsolute(identity.logDirectory)) {
279
+ throw new Error("attempt_process_supervisor_invalid: log directory must be absolute.");
280
+ }
281
+ return { ...identity, logDirectory: path.resolve(identity.logDirectory) };
282
+ }
283
+ function assertChildName(name) {
284
+ if (!/^[a-z][a-z0-9_-]{0,31}$/u.test(name)) {
285
+ throw new Error("attempt_process_supervisor_invalid: child name must be a safe lowercase identifier.");
286
+ }
287
+ }
288
+ function childProcessSupervisorId(attemptSupervisorId, childId) {
289
+ const digest = createHash("sha256")
290
+ .update(JSON.stringify([attemptSupervisorId, childId]))
291
+ .digest("hex")
292
+ .slice(0, 32);
293
+ return `host-${digest}`;
294
+ }
295
+ function assertUuid(value, label) {
296
+ if (!/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu.test(value)) {
297
+ throw new Error(`attempt_process_supervisor_invalid: ${label} id must be a UUID.`);
298
+ }
299
+ }
300
+ function boundedInteger(value, minimum, maximum, name) {
301
+ if (!Number.isSafeInteger(value) || value < minimum || value > maximum) {
302
+ throw new Error(`attempt_process_supervisor_invalid: ${name} must be between ${minimum} and ${maximum}.`);
303
+ }
304
+ return value;
305
+ }
306
+ function boundedFailure(error) {
307
+ const message = error instanceof Error ? error.message : String(error);
308
+ return message.replaceAll(/[\r\n\t]+/gu, " ").slice(0, 512);
309
+ }
310
+ async function childStartFailureDetail(record) {
311
+ try {
312
+ const result = await record.result;
313
+ const stderr = boundedDiagnostic(result.stderr);
314
+ return stderr
315
+ ? `exit ${result.exitCode}; stderr: ${stderr}`
316
+ : `exit ${result.exitCode}`;
317
+ }
318
+ catch (error) {
319
+ return boundedFailure(error);
320
+ }
321
+ }
322
+ function boundedDiagnostic(value) {
323
+ return value.replaceAll(/[\r\n\t]+/gu, " ").trim().slice(0, 512);
324
+ }
325
+ function isRetryableStartFailure(error) {
326
+ return error instanceof Error
327
+ && (error.message.startsWith("attempt_process_supervisor_start_failed:")
328
+ || error.message.startsWith("attempt_process_supervisor_start_timeout:"));
329
+ }
330
+ function cancellationError(signal) {
331
+ return new Error(String(signal.reason ?? "Supervised child launch was cancelled."));
332
+ }
333
+ async function ensurePrivateDirectory(directory) {
334
+ await fs.mkdir(directory, { recursive: true, mode: 0o700 });
335
+ if (process.platform !== "win32")
336
+ await fs.chmod(directory, 0o700);
337
+ }
338
+ async function fileExists(target) {
339
+ return await fs.stat(target).then(() => true, () => false);
340
+ }
341
+ function wait(milliseconds) {
342
+ return new Promise(resolve => setTimeout(resolve, milliseconds));
343
+ }
@@ -0,0 +1,10 @@
1
+ export interface GeneratedOutputResetResult {
2
+ readonly quarantineDirectory: string;
3
+ readonly quarantinedPaths: readonly string[];
4
+ }
5
+ /**
6
+ * Moves only known, untracked test-output directories out of a worktree before
7
+ * a managed attempt starts. The quarantine lives in the attempt-owned output
8
+ * directory, so cleanup is recoverable and cannot cross the attempt boundary.
9
+ */
10
+ export declare function resetGeneratedOutputs(worktreePath: string, testOutputDirectory: string): Promise<GeneratedOutputResetResult>;