@loucompanion/forge-bridge 0.1.4-dev.9445952e33ba → 0.1.4-dev.9e8a5b93cbcb

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.
package/README.md CHANGED
@@ -65,7 +65,7 @@ Show or change the saved server without editing `bridge.json`:
65
65
  ```bash
66
66
  forge-bridge server show
67
67
  forge-bridge server set http://localhost:5208
68
- forge-bridge server set https://srv1493013.tail66073d.ts.net:8443
68
+ forge-bridge server set https://forge.example.ts.net:8443
69
69
  ```
70
70
 
71
71
  `FORGE_URL` overrides the saved server. Changing the saved URL retains runner credentials so aliases for the same deployment keep working; pair again with `--server` when switching to a different Forge deployment.
@@ -28,7 +28,7 @@ export function helpText() {
28
28
  "",
29
29
  "Examples:",
30
30
  " npm install -g @loucompanion/forge-bridge@next",
31
- " forge-bridge pair 1234-5678 --server https://srv1493013.tail66073d.ts.net:8443 --repo-root \"%USERPROFILE%\\ForgeRepos\"",
31
+ " forge-bridge pair 1234-5678 --server https://forge.example.ts.net:8443 --repo-root \"%USERPROFILE%\\ForgeRepos\"",
32
32
  " forge-bridge connect",
33
33
  " forge-bridge status --check-updates",
34
34
  " forge-bridge server set http://localhost:5208",
@@ -116,7 +116,7 @@ export function commandHelpText(command) {
116
116
  "",
117
117
  "Examples:",
118
118
  " forge-bridge server set http://localhost:5208",
119
- " forge-bridge server set https://srv1493013.tail66073d.ts.net:8443",
119
+ " forge-bridge server set https://forge.example.ts.net:8443",
120
120
  "",
121
121
  ].join("\n");
122
122
  case "add-repo":
@@ -46,6 +46,8 @@ export interface AttemptProcessChildHandle {
46
46
  export interface AttemptProcessSupervisorOptions {
47
47
  readonly metadataReadyTimeoutMs?: number;
48
48
  readonly signal?: AbortSignal;
49
+ readonly replaceLedgerFile?: (temporaryPath: string, ledgerPath: string) => Promise<void>;
50
+ readonly ledgerReplaceRetryMs?: number;
49
51
  }
50
52
  export interface AttemptProcessChildReadyOptions {
51
53
  readonly maxStartAttempts?: number;
@@ -62,6 +64,8 @@ export declare class AttemptProcessSupervisor {
62
64
  readonly ledgerPath: string;
63
65
  private readonly identity;
64
66
  private readonly metadataReadyTimeoutMs;
67
+ private readonly replaceLedgerFile;
68
+ private readonly ledgerReplaceRetryMs;
65
69
  private readonly records;
66
70
  private readonly currentByName;
67
71
  private readonly attemptController;
@@ -86,6 +90,7 @@ export declare class AttemptProcessSupervisor {
86
90
  providerMemoryTelemetry(): AttemptProcessTreeMemoryTelemetry | null;
87
91
  private observeChildReady;
88
92
  private settleChild;
93
+ private replaceLedger;
89
94
  private assertFence;
90
95
  private persist;
91
96
  }
@@ -2,8 +2,14 @@ import { createHash } from "node:crypto";
2
2
  import fs from "node:fs/promises";
3
3
  import path from "node:path";
4
4
  import { ForgeFailureError, sanitizeFailureError } from "../session/session.types.js";
5
+ import { monotonicNowMs } from "../shared/time/monotonic.js";
5
6
  const terminalChildStatuses = new Set(["exited", "failed"]);
6
7
  const defaultMetadataReadyTimeoutMs = process.platform === "win32" ? 60_000 : 10_000;
8
+ // Windows refuses to replace a file another process (a scanner or indexer) briefly holds
9
+ // open. One such refusal must not degrade the attempt, so the ledger replace is retried.
10
+ const ledgerReplaceAttempts = 40;
11
+ const defaultLedgerReplaceRetryMs = 25;
12
+ const transientLedgerReplaceCodes = new Set(["EPERM", "EACCES", "EBUSY"]);
7
13
  /**
8
14
  * Owns the independently supervised process trees that belong to one host
9
15
  * dispatch attempt. Each named child gets a distinct Windows Job Object or
@@ -15,6 +21,8 @@ export class AttemptProcessSupervisor {
15
21
  ledgerPath;
16
22
  identity;
17
23
  metadataReadyTimeoutMs;
24
+ replaceLedgerFile;
25
+ ledgerReplaceRetryMs;
18
26
  records = [];
19
27
  currentByName = new Map();
20
28
  attemptController = new AbortController();
@@ -26,6 +34,8 @@ export class AttemptProcessSupervisor {
26
34
  this.runner = runner;
27
35
  this.identity = validateIdentity(identity);
28
36
  this.metadataReadyTimeoutMs = boundedInteger(options.metadataReadyTimeoutMs ?? defaultMetadataReadyTimeoutMs, 100, 120_000, "metadataReadyTimeoutMs");
37
+ this.replaceLedgerFile = options.replaceLedgerFile ?? ((temporaryPath, ledgerPath) => fs.rename(temporaryPath, ledgerPath));
38
+ this.ledgerReplaceRetryMs = options.ledgerReplaceRetryMs ?? defaultLedgerReplaceRetryMs;
29
39
  this.ledgerPath = path.join(this.identity.logDirectory, "attempt-process-supervisor.json");
30
40
  if (options.signal?.aborted) {
31
41
  this.status = "stopping";
@@ -248,8 +258,8 @@ export class AttemptProcessSupervisor {
248
258
  };
249
259
  }
250
260
  async observeChildReady(record) {
251
- const deadline = Date.now() + this.metadataReadyTimeoutMs;
252
- while (Date.now() <= deadline) {
261
+ const deadline = monotonicNowMs() + this.metadataReadyTimeoutMs;
262
+ while (monotonicNowMs() <= deadline) {
253
263
  if (await fileExists(record.metadataPath)) {
254
264
  if (record.status === "starting") {
255
265
  record.status = "running";
@@ -290,6 +300,20 @@ export class AttemptProcessSupervisor {
290
300
  this.status = "degraded";
291
301
  });
292
302
  }
303
+ async replaceLedger(temporary) {
304
+ for (let attempt = 1;; attempt += 1) {
305
+ try {
306
+ await this.replaceLedgerFile(temporary, this.ledgerPath);
307
+ return;
308
+ }
309
+ catch (error) {
310
+ const code = error.code;
311
+ if (attempt >= ledgerReplaceAttempts || !code || !transientLedgerReplaceCodes.has(code))
312
+ throw error;
313
+ await wait(this.ledgerReplaceRetryMs);
314
+ }
315
+ }
316
+ }
293
317
  assertFence(fencingToken) {
294
318
  if (fencingToken !== this.identity.fencingToken) {
295
319
  throw new Error("attempt_process_supervisor_fenced: fencing token does not own this attempt.");
@@ -308,7 +332,7 @@ export class AttemptProcessSupervisor {
308
332
  finally {
309
333
  await handle.close();
310
334
  }
311
- await fs.rename(temporary, this.ledgerPath);
335
+ await this.replaceLedger(temporary);
312
336
  }
313
337
  catch (error) {
314
338
  await fs.rm(temporary, { force: true }).catch(() => undefined);
@@ -6,6 +6,7 @@ import { assertCanonicalDirectory } from "./attempt-private-directory.js";
6
6
  import { runAttemptArchiveOperation, runAttemptPathOperation } from "./attempt-path-operation.js";
7
7
  import { readPinnedSourceDirectory } from "./pinned-source-directory.js";
8
8
  import { compactHostAttemptId } from "./host-execution-root.js";
9
+ import { monotonicNowMs } from "../shared/time/monotonic.js";
9
10
  const maximumEvidenceBytes = 200 * 1024 * 1024;
10
11
  const diagnosticsRetentionDeadlineMs = 30_000;
11
12
  const diagnosticsHelperTerminationConfirmationMs = 2_000;
@@ -21,7 +22,7 @@ export async function retainHostDiagnostics(stateRoot, attemptRoot, attemptId, e
21
22
  const configuredDeadlineMs = Math.max(1, Math.min(diagnosticsRetentionDeadlineMs, Number.isFinite(requestedDeadlineMs) && (requestedDeadlineMs ?? 0) > 0
22
23
  ? Math.floor(requestedDeadlineMs)
23
24
  : diagnosticsRetentionDeadlineMs));
24
- const retentionDeadline = Date.now() + configuredDeadlineMs;
25
+ const retentionDeadline = monotonicNowMs() + configuredDeadlineMs;
25
26
  const identity = attemptId.replaceAll("-", "").toLowerCase();
26
27
  const compactAttemptRoot = path.resolve(attemptOwnerRoot, "a", compactHostAttemptId(attemptId));
27
28
  const legacyAttemptRoot = path.resolve(stateRoot, "host-attempts", identity);
@@ -155,7 +156,7 @@ function remainingHelperTiming(retentionDeadline, configuredDeadlineMs) {
155
156
  return { operationTimeoutMs, terminationConfirmationMs };
156
157
  }
157
158
  function remainingRetentionMs(retentionDeadline, configuredDeadlineMs) {
158
- const remainingMs = retentionDeadline - Date.now();
159
+ const remainingMs = retentionDeadline - monotonicNowMs();
159
160
  if (remainingMs <= 0)
160
161
  throw diagnosticsDeadlineError(configuredDeadlineMs);
161
162
  return remainingMs;
@@ -181,7 +182,7 @@ async function runWithinRetentionHelperDeadline(operation, retentionDeadline, co
181
182
  return await operation();
182
183
  }
183
184
  catch (error) {
184
- if (Date.now() >= retentionDeadline)
185
+ if (monotonicNowMs() >= retentionDeadline)
185
186
  throw diagnosticsDeadlineError(configuredDeadlineMs);
186
187
  throw error;
187
188
  }
@@ -2,6 +2,7 @@ import path from "node:path";
2
2
  import { ForgeFailureError } from "../session/session.types.js";
3
3
  import { withAspNetPrebuiltRunArguments } from "./aspnet-runtime-prebuild.js";
4
4
  import { hostPortEnvironment, } from "./host-runtime-contract.js";
5
+ import { monotonicNowMs } from "../shared/time/monotonic.js";
5
6
  /**
6
7
  * Launches an explicitly configured HTTP project command beneath the caller's
7
8
  * attempt supervisor. It never shells a command and never promotes a project
@@ -53,12 +54,12 @@ export class NodeHostRuntimeAdapter {
53
54
  return { ...launched, request: activeRequest };
54
55
  }
55
56
  async waitUntilReady(value, request, launcher, signal) {
56
- const startedAt = Date.now();
57
+ const startedAt = monotonicNowMs();
57
58
  const hardDeadline = startedAt + this.hardReadinessTimeoutMs;
58
59
  let idleDeadline = startedAt + this.readinessTimeoutMs;
59
60
  let outputRevision = -1;
60
61
  let observedOwnership = "unbound";
61
- while (Date.now() <= idleDeadline && Date.now() <= hardDeadline) {
62
+ while (monotonicNowMs() <= idleDeadline && monotonicNowMs() <= hardDeadline) {
62
63
  if (signal?.aborted)
63
64
  throw cancellationError(signal);
64
65
  const diagnostics = await launcher.readinessDiagnostics?.(value);
@@ -67,7 +68,7 @@ export class NodeHostRuntimeAdapter {
67
68
  }
68
69
  if (diagnostics?.outputRevision !== undefined && diagnostics.outputRevision > outputRevision) {
69
70
  outputRevision = diagnostics.outputRevision;
70
- idleDeadline = Math.min(hardDeadline, Date.now() + this.readinessTimeoutMs);
71
+ idleDeadline = Math.min(hardDeadline, monotonicNowMs() + this.readinessTimeoutMs);
71
72
  }
72
73
  const ownership = await launcher.inspectListener(value, request, signal);
73
74
  observedOwnership = ownership;
@@ -85,7 +86,7 @@ export class NodeHostRuntimeAdapter {
85
86
  const code = observedOwnership === "owned"
86
87
  ? "host_runtime_http_readiness_timeout"
87
88
  : "host_runtime_listener_timeout";
88
- const reachedHardDeadline = Date.now() >= hardDeadline;
89
+ const reachedHardDeadline = monotonicNowMs() >= hardDeadline;
89
90
  const detail = observedOwnership === "owned"
90
91
  ? reachedHardDeadline
91
92
  ? `the supervised process owned its assigned loopback port but HTTP readiness did not succeed within the ${this.hardReadinessTimeoutMs}ms hard limit`
@@ -4,6 +4,7 @@ import fs from "node:fs/promises";
4
4
  import path from "node:path";
5
5
  import { resolvePathIdentity } from "../shared/path/path.js";
6
6
  import { ForgeFailureError } from "../session/session.types.js";
7
+ import { monotonicNowMs } from "../shared/time/monotonic.js";
7
8
  const LOCK_HEARTBEAT_INTERVAL_MS = 30_000;
8
9
  const LOCK_STALE_AFTER_MS = 2 * 60_000;
9
10
  export class RepositoryCoordinatorLock {
@@ -21,7 +22,7 @@ export class RepositoryCoordinatorLock {
21
22
  const target = path.join(root, `${key}.lock`);
22
23
  const token = randomUUID();
23
24
  await fs.mkdir(root, { recursive: true, mode: 0o700 });
24
- const started = Date.now();
25
+ const started = monotonicNowMs();
25
26
  while (true) {
26
27
  if (signal?.aborted) {
27
28
  throw new ForgeFailureError("sandbox_import_cancelled", "sandbox_import_cancelled: repository coordination was cancelled.", "sandbox");
@@ -44,7 +45,7 @@ export class RepositoryCoordinatorLock {
44
45
  await fs.rm(target, { force: true });
45
46
  continue;
46
47
  }
47
- if (Date.now() - started >= this.lockTimeoutMs) {
48
+ if (monotonicNowMs() - started >= this.lockTimeoutMs) {
48
49
  throw new ForgeFailureError("sandbox_import_unavailable", "sandbox_import_unavailable: repository coordinator lock timed out.", "sandbox", { cause: error });
49
50
  }
50
51
  await abortableDelay(50, signal);
@@ -12,6 +12,7 @@ import { RepositoryCoordinatorLock } from "./repository-lock.js";
12
12
  import { redactText } from "../shared/redaction/redaction.js";
13
13
  import { createRuntimeIsolationLease, renewRuntimeIsolationLease, transitionRuntimeIsolationLease, validRuntimeIsolationLease, withRuntimeIsolationResources, } from "../runtime/runtime-isolation-lease.js";
14
14
  import { sandboxProviderAuthAdapterFor, sandboxProviderAuthUnavailableMessage } from "./provider-auth/codex.js";
15
+ import { monotonicNowMs } from "../shared/time/monotonic.js";
15
16
  const managedLabel = "dev.forge.managed=true";
16
17
  const bridgeRuntimeDigestLabel = "dev.forge.bridge-runtime-digest";
17
18
  export class DockerSandboxRuntime {
@@ -554,10 +555,10 @@ export class DockerSandboxRuntime {
554
555
  const existing = this.builds.get(key);
555
556
  if (existing) {
556
557
  await sink.emit(event("sandbox_image_cache_miss", `Sandbox image ${key.slice(0, 12)} is being built by another dispatch.`, { cacheKey: key, singleflight: true }));
557
- const waitStartedAt = Date.now();
558
+ const waitStartedAt = monotonicNowMs();
558
559
  const built = await existing;
559
560
  await sink.emit(event("sandbox_build_singleflight_wait", `Waited for the existing sandbox image build ${key.slice(0, 12)}.`, {
560
- durationMs: Date.now() - waitStartedAt,
561
+ durationMs: Math.round(monotonicNowMs() - waitStartedAt),
561
562
  imageDigest: built.imageDigest
562
563
  }));
563
564
  return built;
@@ -889,8 +890,8 @@ export class DockerSandboxRuntime {
889
890
  await sink.emit(event("sandbox_image_signature_warning", `Image signature enforcement is not configured for adoption-mode image ${image}.`));
890
891
  }
891
892
  async waitForServiceHealthy(name, signal) {
892
- const deadline = Date.now() + 60_000;
893
- while (Date.now() < deadline) {
893
+ const deadline = monotonicNowMs() + 60_000;
894
+ while (monotonicNowMs() < deadline) {
894
895
  if (signal?.aborted)
895
896
  throw new Error(String(signal.reason ?? "sandbox service startup cancelled"));
896
897
  const status = (await this.docker(["container", "inspect", name, "--format", "{{.State.Health.Status}}"], 10_000, signal)).stdout.trim();
@@ -11,6 +11,7 @@ import { ManagedBuildCoordinator } from "./managed-build-coordinator.js";
11
11
  import { managedBuildConfiguration, publishManagedBuildReceipt, verifyManagedBuildReceipt, } from "./managed-build-receipt.js";
12
12
  import { managedLongTierTimeoutMs, managedMaximumCommandTimeoutMs, managedVerificationTierTimeoutMs, } from "./managed-verification-timeouts.js";
13
13
  import { resolveWindowsCommandFromPath, StreamingProviderProcessRunner } from "./provider-cli/provider-cli.process.js";
14
+ import { monotonicNowMs } from "../shared/time/monotonic.js";
14
15
  const managedCommandNames = new Set(["forge.run_managed_command", "run_managed_command"]);
15
16
  const startManagedCommandNames = new Set(["forge.start_managed_command", "start_managed_command"]);
16
17
  const getManagedCommandNames = new Set(["forge.get_managed_command", "get_managed_command"]);
@@ -612,7 +613,7 @@ async function waitManagedCommand(input) {
612
613
  const commandId = validatedCommandId(record);
613
614
  const requestedWaitTimeoutMs = optionalWaitTimeout(record.wait_timeout_ms);
614
615
  const waitTimeoutMs = Math.min(requestedWaitTimeoutMs, maximumSynchronousWaitMs);
615
- const deadline = Date.now() + waitTimeoutMs;
616
+ const deadline = monotonicNowMs() + waitTimeoutMs;
616
617
  const receiptPath = managedCommandReceiptPath(requiredAttemptEnvironment("FORGE_LOG_DIR"), commandId);
617
618
  const task = managedCommandTasks.get(commandId);
618
619
  if (task) {
@@ -623,12 +624,12 @@ async function waitManagedCommand(input) {
623
624
  if (result)
624
625
  return result;
625
626
  }
626
- while (Date.now() < deadline) {
627
+ while (monotonicNowMs() < deadline) {
627
628
  const result = await readManagedCommand({ command_id: commandId });
628
629
  if (terminalManagedCommandStatuses.has(String(result.structuredContent.status))) {
629
630
  return result;
630
631
  }
631
- await delay(Math.min(managedCommandReceiptPollIntervalMs, Math.max(1, deadline - Date.now())));
632
+ await delay(Math.min(managedCommandReceiptPollIntervalMs, Math.max(1, deadline - monotonicNowMs())));
632
633
  }
633
634
  const receipt = await readManagedCommand({ command_id: commandId });
634
635
  // Only a running receipt is refreshed on a heartbeat; queued or starting receipts are
@@ -2,6 +2,7 @@ import { createHash, randomUUID } from "node:crypto";
2
2
  import fs from "node:fs/promises";
3
3
  import path from "node:path";
4
4
  import { defaultWorktreeCoordinatorStateRoot } from "../worktree/worktree-paths.js";
5
+ import { monotonicNowMs } from "../shared/time/monotonic.js";
5
6
  const heartbeatIntervalMs = 30_000;
6
7
  const staleAfterMs = 2 * 60_000;
7
8
  const acquisitionTimeoutMs = 2 * 60 * 60_000;
@@ -17,7 +18,7 @@ export class ManagedBuildCoordinator {
17
18
  const root = path.join(this.stateRoot, "managed-build-locks");
18
19
  const target = path.join(root, `${key}.lock`);
19
20
  const token = randomUUID();
20
- const startedAt = Date.now();
21
+ const startedAt = monotonicNowMs();
21
22
  let waitingReported = false;
22
23
  await fs.mkdir(root, { recursive: true, mode: 0o700 });
23
24
  while (true) {
@@ -49,7 +50,7 @@ export class ManagedBuildCoordinator {
49
50
  waitingReported = true;
50
51
  await onWaiting?.();
51
52
  }
52
- if (Date.now() - startedAt >= acquisitionTimeoutMs) {
53
+ if (monotonicNowMs() - startedAt >= acquisitionTimeoutMs) {
53
54
  throw new Error("managed_build_slot_timeout: another build held this worktree for more than two hours.", { cause: error });
54
55
  }
55
56
  await delay(pollIntervalMs);
@@ -58,7 +59,7 @@ export class ManagedBuildCoordinator {
58
59
  const heartbeat = setInterval(() => void refreshHeartbeat(target, token), heartbeatIntervalMs);
59
60
  heartbeat.unref?.();
60
61
  try {
61
- return await action(Date.now() - startedAt);
62
+ return await action(Math.round(monotonicNowMs() - startedAt));
62
63
  }
63
64
  finally {
64
65
  clearInterval(heartbeat);
@@ -75,6 +75,8 @@ export declare class StreamingProviderProcessRunner implements ProviderProcessRu
75
75
  }
76
76
  /** Returns aggregate resident bytes for the exact supervised Unix process group. */
77
77
  export declare function processGroupResidentMemoryBytes(processGroupId: number, platform?: NodeJS.Platform, procRoot?: string): number | null;
78
+ export declare const UNIX_PROVIDER_START_GRANT_LINE = "forge-provider-start-granted\n";
79
+ export declare function buildUnixProviderStartGateLaunch(command: string, args: readonly string[]): LaunchCommand;
78
80
  export declare function resolveCodexNpmDirectLaunch(commandPath: string, args: readonly string[]): LaunchCommand | null;
79
81
  /**
80
82
  * npm installs of Claude Code (`npm i -g @anthropic-ai/claude-code`) put a `claude.cmd` shim on
@@ -323,12 +323,29 @@ export class StreamingProviderProcessRunner {
323
323
  // An unsupervised Unix provider still gets a dedicated process group so a
324
324
  // cancellation can stop descendants instead of only the CLI root.
325
325
  const launch = supervisedLaunch ?? { ...providerLaunch, detached: process.platform !== "win32" };
326
+ const childEnvironment = buildProviderChildEnvironment(request.env);
327
+ // A piped prompt must reach the provider promptly (Claude Code abandons a
328
+ // silent stdin after ~3s), but the provider must not run before Forge has
329
+ // recorded its start. Off Windows, hold the launch behind a start gate in
330
+ // the same process: the prompt is written immediately and buffers in the
331
+ // pipe, and the gate execs the provider only once onStarted succeeds.
332
+ const startGated = process.platform !== "win32"
333
+ && supervisedLaunch?.strategy !== "windows_job_object"
334
+ && request.stdin !== undefined
335
+ && fs.existsSync(UNIX_PROVIDER_START_GATE_SHELL)
336
+ && isUnixExecutableAvailable(launch.command, childEnvironment.PATH, request.cwd);
337
+ const spawnLaunch = startGated
338
+ ? buildUnixProviderStartGateLaunch(launch.command, launch.args)
339
+ : launch;
326
340
  return await new Promise((resolve, reject) => {
327
341
  const rootCreatedAt = new Date().toISOString();
328
- const child = spawn(launch.command, launch.args, {
342
+ const stdinMode = request.stdin === undefined ? "ignore" : "pipe";
343
+ const child = spawn(spawnLaunch.command, spawnLaunch.args, {
329
344
  cwd: request.cwd,
330
- env: buildProviderChildEnvironment(request.env),
331
- stdio: [request.stdin === undefined ? "ignore" : "pipe", "pipe", "pipe"],
345
+ env: childEnvironment,
346
+ stdio: startGated
347
+ ? [stdinMode, "pipe", "pipe", "pipe"]
348
+ : [stdinMode, "pipe", "pipe"],
332
349
  windowsHide: true,
333
350
  detached: launch.detached,
334
351
  });
@@ -386,6 +403,27 @@ export class StreamingProviderProcessRunner {
386
403
  signal?.addEventListener("abort", abort, { once: true });
387
404
  }
388
405
  child.on("error", fail);
406
+ const startGrant = startGated ? child.stdio[3] : null;
407
+ if (startGated && !startGrant) {
408
+ fail(new Error("Provider start-grant stream was not piped."));
409
+ return;
410
+ }
411
+ startGrant?.on("error", error => {
412
+ // A broken grant pipe means the gate already exited (terminated before
413
+ // its grant, or it died on its own). Its close event carries the real
414
+ // exit status, so an EPIPE here must not replace that result.
415
+ if (isBrokenPipeError(error))
416
+ return;
417
+ fail(error);
418
+ });
419
+ const grantUnixProviderStart = () => {
420
+ if (!startGrant)
421
+ return;
422
+ // Never release a provider whose launch was cancelled or already failed.
423
+ if (closed || settled || cancellationRequested || signal?.aborted)
424
+ return;
425
+ startGrant.end(UNIX_PROVIDER_START_GRANT_LINE, "utf8");
426
+ };
389
427
  child.once("spawn", () => {
390
428
  readiness = (async () => {
391
429
  const providerReady = supervisedLaunch?.strategy === "windows_job_object"
@@ -398,6 +436,9 @@ export class StreamingProviderProcessRunner {
398
436
  if (supervisedLaunch?.strategy === "windows_job_object") {
399
437
  grantWindowsProviderStart(supervisedLaunch);
400
438
  }
439
+ else if (startGated) {
440
+ grantUnixProviderStart();
441
+ }
401
442
  })();
402
443
  void readiness.catch(error => {
403
444
  if (!closed && !signal?.aborted)
@@ -413,15 +454,20 @@ export class StreamingProviderProcessRunner {
413
454
  return;
414
455
  }
415
456
  child.stdin.on("error", (error) => {
457
+ // A prompt still buffered when Forge stops the process (cancellation,
458
+ // or a refused start grant) cannot be delivered; that broken pipe is
459
+ // not a failure. Any other stdin error still is.
460
+ if ((cancellationRequested || termination) && isBrokenPipeError(error))
461
+ return;
416
462
  void terminate();
417
463
  fail(error);
418
464
  });
419
465
  child.stdin.end(request.stdin, "utf8");
420
466
  };
421
467
  if (request.stdin !== undefined) {
422
- if (supervisedLaunch?.strategy === "windows_job_object") {
423
- // The outer supervisor must receive stdin before it can launch the
424
- // inner provider. Its start-grant file prevents prompt delivery.
468
+ if (supervisedLaunch?.strategy === "windows_job_object" || startGated) {
469
+ // The outer supervisor / Unix start gate must receive stdin before it
470
+ // can launch the provider. Its start grant fences prompt processing.
425
471
  writeProviderInput();
426
472
  }
427
473
  else {
@@ -682,6 +728,64 @@ async function resolveProviderProcessLaunch(command, args) {
682
728
  ?? resolvePackageManagerDirectLaunch(resolved, args)
683
729
  ?? buildWindowsLaunchCommand(resolved, args);
684
730
  }
731
+ const UNIX_PROVIDER_START_GATE_SHELL = "/bin/sh";
732
+ const UNIX_PROVIDER_START_GATE_NAME = "forge-provider-start-gate";
733
+ export const UNIX_PROVIDER_START_GRANT_LINE = "forge-provider-start-granted\n";
734
+ /**
735
+ * Blocks on fd 3 until the bridge writes the exact grant line, then replaces
736
+ * itself with the provider (`exec`), so the supervised root PID, process group
737
+ * and birth identity stay the provider's. The provider command and arguments
738
+ * are passed positionally and expanded only as "$@"; nothing is interpolated
739
+ * into the script. EOF, a read error, or any other content on fd 3 exits
740
+ * without running the provider. fd 3 is closed before exec so the provider and
741
+ * its descendants never inherit the grant channel. stdin is not touched, so
742
+ * the prompt stays buffered in its pipe for the provider.
743
+ */
744
+ const UNIX_PROVIDER_START_GATE_SCRIPT = [
745
+ "IFS= read -r forge_start_grant <&3 || { echo \"$0: provider start was not granted\" >&2; exit 125; }",
746
+ `[ "$forge_start_grant" = "${UNIX_PROVIDER_START_GRANT_LINE.trim()}" ] || { echo "$0: provider start grant was invalid" >&2; exit 125; }`,
747
+ "exec \"$@\" 3<&-",
748
+ ].join("\n");
749
+ export function buildUnixProviderStartGateLaunch(command, args) {
750
+ return {
751
+ command: UNIX_PROVIDER_START_GATE_SHELL,
752
+ args: ["-c", UNIX_PROVIDER_START_GATE_SCRIPT, UNIX_PROVIDER_START_GATE_NAME, command, ...args],
753
+ };
754
+ }
755
+ /**
756
+ * Mirrors the executable lookup the gate's `exec` will perform. A command that
757
+ * cannot be found is spawned directly instead so it keeps failing as a spawn
758
+ * ENOENT before any start is recorded; nothing can run in that case. The check
759
+ * is advisory: if the executable disappears between this lookup and the gated
760
+ * `exec`, the gate exits 127 with the shell's "not found" message after the
761
+ * start was recorded, which surfaces as an ordinary provider failure.
762
+ */
763
+ function isUnixExecutableAvailable(command, pathValue, cwd) {
764
+ if (!command || command.startsWith("-"))
765
+ return false;
766
+ const candidates = command.includes("/")
767
+ ? [path.resolve(cwd, command)]
768
+ : pathValue === undefined
769
+ ? null
770
+ : pathValue.split(path.delimiter).map(directory => path.resolve(cwd, directory || ".", command));
771
+ if (candidates === null)
772
+ return true;
773
+ return candidates.some(candidate => {
774
+ try {
775
+ if (!fs.statSync(candidate).isFile())
776
+ return false;
777
+ fs.accessSync(candidate, fs.constants.X_OK);
778
+ return true;
779
+ }
780
+ catch {
781
+ return false;
782
+ }
783
+ });
784
+ }
785
+ function isBrokenPipeError(error) {
786
+ const code = error?.code;
787
+ return code === "EPIPE" || code === "ERR_STREAM_DESTROYED" || code === "ECONNRESET";
788
+ }
685
789
  function grantWindowsProviderStart(launch) {
686
790
  if (!launch.startGrantPath) {
687
791
  throw new Error("host_process_supervisor_invalid: Windows provider start-grant path was not assigned.");
@@ -4,7 +4,8 @@ export type InputTokenSemantics = "includes_cached_input" | "excludes_cache_toke
4
4
  export declare const PROVIDER_USAGE_SCHEMA_VERSION = 1;
5
5
  /**
6
6
  * Normalized, provider-agnostic token usage accumulated for a dispatch. Cost is never computed
7
- * here; the API recomputes cost from these tokens x model rates (ADR-0006).
7
+ * here; the API recomputes cost from these tokens x model rates (legacy
8
+ * ADR-0006, .forge-designer/decisions/legacy/0006-cost-capture.md).
8
9
  */
9
10
  export interface ProviderUsage {
10
11
  /** Normalized total input. Cached input is a subset, never an additive peer. */
@@ -1,4 +1,5 @@
1
1
  import { captureHostProcessIdentity } from "./host-process-supervisor.js";
2
+ import { monotonicNowMs } from "../time/monotonic.js";
2
3
  /** Exact, birth-marker-fenced recovery for a process tree left by an old bridge. */
3
4
  export class ExactHostProcessRecovery {
4
5
  platform;
@@ -71,8 +72,8 @@ function signalExactProcessGroup(pid, signal) {
71
72
  }
72
73
  }
73
74
  async function waitForExit(pid, timeoutMs) {
74
- const deadline = Date.now() + timeoutMs;
75
- while (Date.now() < deadline && processExists(pid)) {
75
+ const deadline = monotonicNowMs() + timeoutMs;
76
+ while (monotonicNowMs() < deadline && processExists(pid)) {
76
77
  await new Promise(resolve => setTimeout(resolve, 25));
77
78
  }
78
79
  }
@@ -3,6 +3,7 @@ import { execFileSync } from "node:child_process";
3
3
  import fs from "node:fs";
4
4
  import path from "node:path";
5
5
  import { fileURLToPath } from "node:url";
6
+ import { monotonicNowMs } from "../time/monotonic.js";
6
7
  const windowsJobSupervisorPath = fileURLToPath(new URL("../../../runtime/windows-job-supervisor.ps1", import.meta.url));
7
8
  export function resolveHostProcessSupervisedLaunch(request, resolvedCommand, resolvedArgs, platform = process.platform) {
8
9
  const env = request.env;
@@ -277,8 +278,8 @@ function unixProcessGroupExists(processGroupId) {
277
278
  }
278
279
  }
279
280
  async function waitForUnixProcessGroupExit(processGroupId, timeoutMs) {
280
- const deadline = Date.now() + timeoutMs;
281
- while (Date.now() < deadline && unixProcessGroupExists(processGroupId)) {
281
+ const deadline = monotonicNowMs() + timeoutMs;
282
+ while (monotonicNowMs() < deadline && unixProcessGroupExists(processGroupId)) {
282
283
  await new Promise(resolve => setTimeout(resolve, 25));
283
284
  }
284
285
  }
@@ -307,8 +308,8 @@ function processExists(pid) {
307
308
  }
308
309
  }
309
310
  async function waitForExactProcessExit(pid, identity, timeoutMs, platform) {
310
- const deadline = Date.now() + timeoutMs;
311
- while (Date.now() < deadline && exactProcessExists(pid, identity, platform)) {
311
+ const deadline = monotonicNowMs() + timeoutMs;
312
+ while (monotonicNowMs() < deadline && exactProcessExists(pid, identity, platform)) {
312
313
  await new Promise(resolve => setTimeout(resolve, 25));
313
314
  }
314
315
  }
@@ -0,0 +1 @@
1
+ export declare function monotonicNowMs(): number;
@@ -0,0 +1,8 @@
1
+ // Elapsed time and local deadlines use the monotonic clock. The wall clock can step:
2
+ // a WSL VM's clock is corrected in multi-second jumps, which would end a local wait
3
+ // early or count time that never passed. Timestamps that are persisted or compared
4
+ // across processes (lease expiry, receipts, file mtimes) stay on the wall clock.
5
+ // Read through the global so test fake timers that replace `performance` apply.
6
+ export function monotonicNowMs() {
7
+ return performance.now();
8
+ }
package/dist/version.d.ts CHANGED
@@ -1 +1 @@
1
- export declare const forgeBridgeVersion = "0.1.4-dev.9445952e33ba";
1
+ export declare const forgeBridgeVersion = "0.1.4-dev.9e8a5b93cbcb";
package/dist/version.js CHANGED
@@ -1 +1 @@
1
- export const forgeBridgeVersion = "0.1.4-dev.9445952e33ba";
1
+ export const forgeBridgeVersion = "0.1.4-dev.9e8a5b93cbcb";
@@ -36,6 +36,7 @@ const dependencyPreparationCoordinator = new RepositoryCoordinatorLock(defaultWo
36
36
  export async function detectWarmPaths(repoRoot, warmPathOverrides = []) {
37
37
  const entries = new Map();
38
38
  await collectDetectedPaths(repoRoot, repoRoot, entries, 0);
39
+ await collectSolutionProjectRestores(repoRoot, entries);
39
40
  for (const override of warmPathOverrides) {
40
41
  const normalized = normalizeRelativePath(override);
41
42
  if (!normalized) {
@@ -539,6 +540,79 @@ async function hasPythonMarker(dir) {
539
540
  return (await pathExists(path.join(dir, "pyproject.toml")))
540
541
  || (await pathExists(path.join(dir, "requirements.txt")));
541
542
  }
543
+ const solutionProjectPattern = /^Project\("\{[0-9A-Fa-f-]+\}"\)\s*=\s*"[^"]*"\s*,\s*"([^"]+\.(?:cs|fs|vb)proj)"/gimu;
544
+ const slnxProjectPattern = /<Project\b[^>]*\bPath\s*=\s*"([^"]+\.(?:cs|fs|vb)proj)"/giu;
545
+ const projectFilePattern = /\.(?:cs|fs|vb)proj$/iu;
546
+ const solutionFilePattern = /\.(?:sln|slnx|slnf)$/iu;
547
+ /**
548
+ * A worktree built from a never-built base checkout (a fresh runner clone has no bin/ or obj/)
549
+ * still needs its .NET projects restored, or the --no-restore runtime build fails with NETSDK1004.
550
+ * Restore exactly the projects the root solution(s) (.sln, .slnx, .slnf) list, or a lone root
551
+ * project when there is no solution. Other projects (fixtures, samples) keep the base-checkout
552
+ * output heuristic above.
553
+ */
554
+ async function collectSolutionProjectRestores(repoRoot, entries) {
555
+ const rootNames = await fs.readdir(repoRoot).catch(() => []);
556
+ const solutions = rootNames.filter((name) => solutionFilePattern.test(name));
557
+ if (solutions.length === 0) {
558
+ const rootProjects = rootNames.filter((name) => name.toLowerCase().endsWith(".csproj"));
559
+ if (rootProjects.length === 1) {
560
+ addEntry(entries, repoRoot, "", "obj", "dotnet", "obj");
561
+ }
562
+ return;
563
+ }
564
+ for (const solution of solutions) {
565
+ for (const listed of await readSolutionProjectPaths(repoRoot, solution)) {
566
+ const projectPath = path.posix.normalize(normalizeRelativePath(listed));
567
+ if (!projectPath || projectPath === ".." || projectPath.startsWith("../") || path.posix.isAbsolute(projectPath)) {
568
+ continue;
569
+ }
570
+ const absoluteProject = path.resolve(repoRoot, ...projectPath.split("/"));
571
+ if (!isSubPath(repoRoot, absoluteProject) || !(await pathExists(absoluteProject))) {
572
+ continue;
573
+ }
574
+ const projectDir = path.posix.dirname(projectPath);
575
+ // The fallback runs a bare `dotnet restore` in the project's directory. Beside the solution,
576
+ // or next to another project file, that restore is ambiguous (MSB1011); leave those layouts
577
+ // to the base-checkout output heuristic.
578
+ if (projectDir === "." || (await countProjectFiles(path.dirname(absoluteProject))) !== 1) {
579
+ continue;
580
+ }
581
+ addEntry(entries, repoRoot, projectDir, "obj", "dotnet", joinRelative(projectDir, "obj"));
582
+ }
583
+ }
584
+ }
585
+ /** Project paths a root solution lists, relative to the repo root (forward slashes). */
586
+ async function readSolutionProjectPaths(repoRoot, solution) {
587
+ const text = await fs.readFile(path.join(repoRoot, solution), "utf8").catch(() => "");
588
+ const lower = solution.toLowerCase();
589
+ if (lower.endsWith(".sln")) {
590
+ return [...text.matchAll(solutionProjectPattern)].map((match) => match[1].replace(/\\/g, "/"));
591
+ }
592
+ if (lower.endsWith(".slnx")) {
593
+ return [...text.matchAll(slnxProjectPattern)].map((match) => match[1].replace(/\\/g, "/"));
594
+ }
595
+ // .slnf: {"solution": {"path": "<solution>", "projects": [...]}}, projects relative to that solution.
596
+ let filter;
597
+ try {
598
+ filter = JSON.parse(text.replace(/^\uFEFF/u, ""));
599
+ }
600
+ catch {
601
+ return [];
602
+ }
603
+ const body = filter?.solution;
604
+ if (!body || typeof body.path !== "string" || !Array.isArray(body.projects)) {
605
+ return [];
606
+ }
607
+ const solutionDir = path.posix.dirname(body.path.replace(/\\/g, "/"));
608
+ return body.projects
609
+ .filter((project) => typeof project === "string" && projectFilePattern.test(project))
610
+ .map((project) => path.posix.join(solutionDir, project.replace(/\\/g, "/")));
611
+ }
612
+ async function countProjectFiles(dir) {
613
+ const names = await fs.readdir(dir).catch(() => []);
614
+ return names.filter((name) => projectFilePattern.test(name)).length;
615
+ }
542
616
  async function hasDotNetMarker(dir) {
543
617
  const entries = await fs.readdir(dir).catch(() => []);
544
618
  return entries.some((name) => name.endsWith(".csproj") || name.endsWith(".sln"));
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@loucompanion/forge-bridge",
3
- "version": "0.1.4-dev.9445952e33ba",
3
+ "version": "0.1.4-dev.9e8a5b93cbcb",
4
4
  "description": "Forge runner bridge CLI for connecting local developer machines to Forge dispatch.",
5
5
  "license": "UNLICENSED",
6
6
  "type": "module",