@loucompanion/forge-bridge 0.1.4-dev.25308ca4a63d → 0.1.4-dev.297b5afcac9e

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 (126) hide show
  1. package/README.md +55 -0
  2. package/dist/bridge/bridge-chat-provider-command.d.ts +16 -0
  3. package/dist/bridge/bridge-chat-provider-command.js +137 -0
  4. package/dist/bridge/bridge-chat.types.d.ts +10 -0
  5. package/dist/bridge/bridge-chat.types.js +16 -1
  6. package/dist/bridge/bridge.base.d.ts +2 -0
  7. package/dist/bridge/bridge.service.d.ts +53 -1
  8. package/dist/bridge/bridge.service.js +234 -113
  9. package/dist/bridge/bridge.types.d.ts +11 -0
  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 +3 -0
  13. package/dist/bridge/runner-host-capabilities.js +13 -0
  14. package/dist/cli/cli.help.js +18 -0
  15. package/dist/cli/cli.service.d.ts +16 -0
  16. package/dist/cli/cli.service.js +122 -13
  17. package/dist/cli/local-config.d.ts +4 -0
  18. package/dist/cli/local-config.js +26 -4
  19. package/dist/runtime/aspnet-runtime-prebuild.d.ts +5 -0
  20. package/dist/runtime/aspnet-runtime-prebuild.js +44 -0
  21. package/dist/runtime/attempt-database-broker.d.ts +1 -1
  22. package/dist/runtime/docker-engine-probe.d.ts +5 -0
  23. package/dist/runtime/docker-engine-probe.js +7 -0
  24. package/dist/runtime/ephemeral-test-postgres-grant.d.ts +37 -0
  25. package/dist/runtime/ephemeral-test-postgres-grant.js +85 -0
  26. package/dist/runtime/ephemeral-test-postgres.d.ts +57 -0
  27. package/dist/runtime/ephemeral-test-postgres.js +303 -0
  28. package/dist/runtime/host-facts.d.ts +2 -1
  29. package/dist/runtime/host-load-admission.d.ts +18 -3
  30. package/dist/runtime/host-load-admission.js +19 -4
  31. package/dist/runtime/host-load-child-environment.d.ts +11 -6
  32. package/dist/runtime/host-load-child-environment.js +22 -11
  33. package/dist/runtime/host-load-governor-config.d.ts +19 -1
  34. package/dist/runtime/host-load-governor-config.js +37 -0
  35. package/dist/runtime/host-load-governor.d.ts +12 -0
  36. package/dist/runtime/host-load-governor.js +139 -26
  37. package/dist/runtime/host-load-runtime-settings.d.ts +25 -0
  38. package/dist/runtime/host-load-runtime-settings.js +78 -0
  39. package/dist/runtime/host-load-sampler.d.ts +34 -4
  40. package/dist/runtime/host-load-sampler.js +73 -7
  41. package/dist/runtime/host-load-step-class.d.ts +3 -1
  42. package/dist/runtime/host-load-step-class.js +60 -5
  43. package/dist/runtime/host-load-test-slot.d.ts +43 -0
  44. package/dist/runtime/host-load-test-slot.js +81 -0
  45. package/dist/runtime/host-load-token-ledger.d.ts +26 -0
  46. package/dist/runtime/host-load-token-ledger.js +93 -61
  47. package/dist/runtime/host-load-windows-cpu.d.ts +34 -0
  48. package/dist/runtime/host-load-windows-cpu.js +85 -0
  49. package/dist/runtime/host-runtime-contract.d.ts +12 -0
  50. package/dist/runtime/host-runtime-contract.js +29 -1
  51. package/dist/runtime/host-runtime-lease.d.ts +29 -3
  52. package/dist/runtime/host-runtime-lease.js +83 -63
  53. package/dist/runtime/host-runtime-promotion.d.ts +23 -0
  54. package/dist/runtime/host-runtime-promotion.js +36 -0
  55. package/dist/runtime/native-test-postgres-fallback.d.ts +51 -7
  56. package/dist/runtime/native-test-postgres-fallback.js +60 -8
  57. package/dist/runtime/runner-settings.d.ts +100 -0
  58. package/dist/runtime/runner-settings.js +214 -0
  59. package/dist/sandbox/host-capacity-broker.d.ts +7 -1
  60. package/dist/sandbox/host-capacity-broker.js +23 -4
  61. package/dist/session/architect-waits.d.ts +2 -0
  62. package/dist/session/architect-waits.js +138 -0
  63. package/dist/session/managed-attempt-tools.d.ts +0 -7
  64. package/dist/session/managed-attempt-tools.js +51 -62
  65. package/dist/session/managed-command-host-load.d.ts +2 -0
  66. package/dist/session/managed-command-host-load.js +2 -1
  67. package/dist/session/phase-completion.artifacts.js +2 -1
  68. package/dist/session/phase-completion.d.ts +8 -0
  69. package/dist/session/phase-completion.js +1 -0
  70. package/dist/session/phase-completion.mcp-args.d.ts +9 -0
  71. package/dist/session/phase-completion.mcp-args.js +156 -0
  72. package/dist/session/phase-completion.runtime.d.ts +0 -8
  73. package/dist/session/phase-completion.runtime.js +38 -168
  74. package/dist/session/phase-completion.schemas.js +25 -23
  75. package/dist/session/phase-completion.validation.js +3 -1
  76. package/dist/session/pre-publication-native-postgres.d.ts +30 -0
  77. package/dist/session/pre-publication-native-postgres.js +111 -0
  78. package/dist/session/pre-publication-pass.d.ts +61 -0
  79. package/dist/session/pre-publication-pass.js +148 -0
  80. package/dist/session/pre-publication-step-execution.d.ts +2 -1
  81. package/dist/session/pre-publication-step-execution.js +6 -5
  82. package/dist/session/pre-publication-validation.d.ts +30 -14
  83. package/dist/session/pre-publication-validation.js +207 -134
  84. package/dist/session/provider-cli/claude-background-work.d.ts +66 -0
  85. package/dist/session/provider-cli/claude-background-work.js +180 -0
  86. package/dist/session/provider-cli/pre-publication-repair.d.ts +56 -0
  87. package/dist/session/provider-cli/pre-publication-repair.js +276 -0
  88. package/dist/session/provider-cli/provider-cli.child-environment.d.ts +7 -0
  89. package/dist/session/provider-cli/provider-cli.child-environment.js +73 -0
  90. package/dist/session/provider-cli/provider-cli.codex-models-cache.d.ts +3 -0
  91. package/dist/session/provider-cli/provider-cli.codex-models-cache.js +37 -0
  92. package/dist/session/provider-cli/provider-cli.process.d.ts +15 -36
  93. package/dist/session/provider-cli/provider-cli.process.js +39 -430
  94. package/dist/session/provider-cli/provider-cli.prompts.d.ts +5 -0
  95. package/dist/session/provider-cli/provider-cli.prompts.js +58 -8
  96. package/dist/session/provider-cli/provider-cli.runtime.js +7 -0
  97. package/dist/session/provider-cli/provider-cli.service.d.ts +5 -5
  98. package/dist/session/provider-cli/provider-cli.service.js +65 -257
  99. package/dist/session/provider-cli/provider-cli.windows-environment.d.ts +10 -0
  100. package/dist/session/provider-cli/provider-cli.windows-environment.js +151 -0
  101. package/dist/session/provider-cli/provider-cli.windows-launch.d.ts +23 -0
  102. package/dist/session/provider-cli/provider-cli.windows-launch.js +131 -0
  103. package/dist/session/provider-cli/provider-in-flight-work.d.ts +4 -0
  104. package/dist/session/provider-cli/provider-in-flight-work.js +45 -0
  105. package/dist/session/provider-cli/provider-output-pipes.d.ts +30 -0
  106. package/dist/session/provider-cli/provider-output-pipes.js +67 -0
  107. package/dist/session/provider-cli/provider-output-state.d.ts +2 -0
  108. package/dist/session/provider-cli/provider-output-state.js +6 -0
  109. package/dist/session/qa-sidecar-validation.d.ts +6 -0
  110. package/dist/session/qa-sidecar-validation.js +28 -0
  111. package/dist/session/sandbox-host-capacity-gate.js +12 -3
  112. package/dist/session/session-redaction.js +31 -181
  113. package/dist/session/session.base.d.ts +6 -1
  114. package/dist/session/session.service.d.ts +4 -1
  115. package/dist/session/session.service.js +6 -0
  116. package/dist/session/session.types.js +3 -3
  117. package/dist/session/sidecar-json-shape.d.ts +31 -0
  118. package/dist/session/sidecar-json-shape.js +217 -0
  119. package/dist/shared/process/windows-app-execution-alias.d.ts +19 -0
  120. package/dist/shared/process/windows-app-execution-alias.js +45 -0
  121. package/dist/shared/process/windows-launch.d.ts +18 -0
  122. package/dist/shared/process/windows-launch.js +68 -0
  123. package/dist/shared/provider-capabilities.js +5 -6
  124. package/dist/version.d.ts +1 -1
  125. package/dist/version.js +1 -1
  126. package/package.json +2 -2
@@ -12,7 +12,7 @@ import { redactText } from "../shared/redaction/redaction.js";
12
12
  import { BridgeRevokedError, bridgeRevokedExitCode, defaultBridgeServiceConfig, ForgeBridgeService, } from "../bridge/bridge.service.js";
13
13
  import { forgeBridgeVersion } from "../version.js";
14
14
  import { ManagedWorktreeCleanupService } from "../cleanup/cleanup.service.js";
15
- import { addRepoMapping, applyLocalConfigDefaults, providerStatusesFor, readLocalConfigSync, removeRepoMapping, resolveLocalConfigPath, setSandboxPolicy, setServerUrl, writeLocalConfig } from "./local-config.js";
15
+ import { addRepoMapping, applyLocalConfigDefaults, providerStatusesFor, readLocalConfigSync, removeRepoMapping, resolveLocalConfigPath, resolveLocalYieldFlagPath, setSandboxPolicy, setServerUrl, writeLocalConfig } from "./local-config.js";
16
16
  import { BridgeSessionService } from "../session/session.service.js";
17
17
  import { redactRunnerDispatchEvent, redactRunOnceResultPacket } from "../session/session-redaction.js";
18
18
  import { validateDockerfilePolicy, validateSandboxContract } from "../sandbox/contract.js";
@@ -22,6 +22,7 @@ import { DockerSandboxSmoke } from "../sandbox/smoke.js";
22
22
  import { parseCompletionMcpArgs, runCompletionMcpServer } from "../session/phase-completion.js";
23
23
  import { failureFactsFromError, failureResult, parseRunOnceDispatchPacket } from "../session/session.types.js";
24
24
  import { commandHelpText, helpText } from "./cli.help.js";
25
+ import { readLocalYieldFlag, writeLocalYieldFlag } from "../bridge/local-yield-flag.js";
25
26
  const apiKeySecretGrantEnv = "FORGE_API_KEY_SECRET_GRANT";
26
27
  const execFileAsync = promisify(execFile);
27
28
  export class ForgeBridgeCliService {
@@ -130,13 +131,22 @@ export class ForgeBridgeCliService {
130
131
  const current = readLocalConfigSync();
131
132
  io.stdout.write(`Pairing with server: ${args.serverUrl}\n`);
132
133
  const code = await resolvePairingCode(args.code);
133
- const repoRoot = await resolvePairRepoRoot(args.repoRoot, current.defaultRepoRoot);
134
- await fs.mkdir(repoRoot, { recursive: true });
135
- const pairArgs = await withDetectedPairCliProviders({ ...args, code, repoRoot });
134
+ const provisionalRoot = path.resolve(args.repoRoot ?? current.defaultRepoRoot ?? path.join(os.homedir(), "ForgeRepos"));
135
+ const pairArgs = await withDetectedPairCliProviders({ ...args, code, repoRoot: provisionalRoot });
136
136
  const claim = await this.pairRunner(pairArgs);
137
- const next = pairedConfig(current, pairArgs, claim);
138
- await writeLocalConfig(next);
139
- io.stdout.write(`Paired runner ${claim.runnerId}.\n`);
137
+ // The code is spent now: save the credentials before anything else can fail or prompt.
138
+ const applied = applyPairHost(pairArgs, claim.host, args.repoRoot !== undefined, io);
139
+ await writeLocalConfig(pairedConfig(current, applied.args, claim));
140
+ let repoRoot = applied.args.repoRoot;
141
+ if (!args.repoRoot && !applied.repoRootFromHost) {
142
+ const answered = await promptPairRepoRoot(repoRoot);
143
+ if (answered !== repoRoot) {
144
+ repoRoot = answered;
145
+ await writeLocalConfig(pairedConfig(current, { ...applied.args, repoRoot }, claim));
146
+ }
147
+ }
148
+ await fs.mkdir(repoRoot, { recursive: true });
149
+ io.stdout.write(`Paired runner ${claim.runnerId}${applied.args.name ? ` (${applied.args.name})` : ""}.\n`);
140
150
  io.stdout.write(`Repo folder: ${repoRoot}\n`);
141
151
  io.stdout.write(`Config: ${resolveLocalConfigPath()}\n`);
142
152
  io.stdout.write("Start the bridge with: forge-bridge connect\n");
@@ -219,6 +229,9 @@ export class ForgeBridgeCliService {
219
229
  writeSandboxPolicyStatus(readLocalConfigSync(), io);
220
230
  return 0;
221
231
  }
232
+ if (args.command === "yield") {
233
+ return await runYieldCommand(args.action, io);
234
+ }
222
235
  if (args.command === "mcp") {
223
236
  const parsed = parseCompletionMcpArgs(args.argv);
224
237
  if (!parsed.ok) {
@@ -256,6 +269,36 @@ export class ForgeBridgeCliService {
256
269
  }
257
270
  }
258
271
  }
272
+ /**
273
+ * Decision 0014 `forge-bridge yield`: the host's own yield switch. It writes a
274
+ * flag file next to the bridge config (never bridge.json); a running bridge
275
+ * polls it and stops taking new attempts without a restart.
276
+ */
277
+ async function runYieldCommand(action, io) {
278
+ const flagPath = resolveLocalYieldFlagPath();
279
+ try {
280
+ if (action !== "status") {
281
+ await writeLocalYieldFlag(flagPath, action === "on");
282
+ }
283
+ const on = await readLocalYieldFlag(flagPath);
284
+ if (action === "on") {
285
+ io.stdout.write("Local yield to foreground is on. A running bridge takes no new attempts within one heartbeat; running attempts finish.\n");
286
+ }
287
+ else if (action === "off") {
288
+ io.stdout.write("Local yield to foreground is off. The bridge takes new attempts again unless yield is on in Forge.\n");
289
+ }
290
+ else {
291
+ io.stdout.write(`Local yield to foreground: ${on ? "on" : "off"}\n`);
292
+ }
293
+ io.stdout.write(`Flag file: ${flagPath}\n`);
294
+ io.stdout.write("The effective state also depends on Forge: the runner yields when this flag or its Yield toggle in Forge is on.\n");
295
+ return 0;
296
+ }
297
+ catch (error) {
298
+ io.stderr.write(`${error instanceof Error ? error.message : String(error)}\n`);
299
+ return 1;
300
+ }
301
+ }
259
302
  function attachEnvSecretGrant(dispatch) {
260
303
  if (!dispatch.execution.requiresApiKeySecretGrant) {
261
304
  delete process.env[apiKeySecretGrantEnv];
@@ -359,6 +402,13 @@ export function parseArgs(argv) {
359
402
  if (argv[0] === "sandbox") {
360
403
  return parseSandboxArgs(argv);
361
404
  }
405
+ if (argv[0] === "yield") {
406
+ const action = argv[1] ?? "status";
407
+ if (argv.length > 2 || (action !== "on" && action !== "off" && action !== "status")) {
408
+ return { ok: false, error: "Usage: forge-bridge yield [on|off|status]" };
409
+ }
410
+ return { ok: true, command: "yield", action };
411
+ }
362
412
  if (argv[0] !== "run-once") {
363
413
  return {
364
414
  ok: false,
@@ -772,6 +822,7 @@ function parsePairArgs(argv) {
772
822
  repoRoot: repoRoot?.trim() ? path.resolve(repoRoot) : undefined,
773
823
  cleanupWorktrees: cleanupWorktrees ?? defaultConfig.cleanupWorktrees,
774
824
  cliProviders: cliProviders.length > 0 ? cliProviders : localConfig.cliProviders && localConfig.cliProviders.length > 0 ? [...localConfig.cliProviders] : ["codex"],
825
+ cliProvidersFromFlag: cliProviders.length > 0,
775
826
  projectLabels: projectLabels.length > 0 ? projectLabels : localConfig.projectLabels ? [...localConfig.projectLabels] : []
776
827
  };
777
828
  }
@@ -834,9 +885,71 @@ async function claimBridgeRunner(args) {
834
885
  }
835
886
  return {
836
887
  runnerId: value.runnerId,
837
- deviceToken: value.deviceToken
888
+ deviceToken: value.deviceToken,
889
+ host: parsePairRunnerHost(value.host)
838
890
  };
839
891
  }
892
+ function parsePairRunnerHost(value) {
893
+ if (!value || typeof value !== "object") {
894
+ return undefined;
895
+ }
896
+ const host = value;
897
+ const name = typeof host.name === "string" && host.name.trim() ? host.name.trim() : undefined;
898
+ const repoRoot = typeof host.repoRoot === "string" && host.repoRoot.trim() ? host.repoRoot.trim() : undefined;
899
+ const cliProviders = Array.isArray(host.cliProviders)
900
+ ? host.cliProviders.filter((provider) => typeof provider === "string" && provider.trim().length > 0)
901
+ : [];
902
+ return { name, repoRoot, cliProviders: cliProviders.length > 0 ? cliProviders : undefined };
903
+ }
904
+ /**
905
+ * Decision 0014 §5: the claim's host block carries what the Connect dialog chose. The runner name
906
+ * is the server's; providers and the repo folder apply unless a flag named them on this command line.
907
+ */
908
+ function applyPairHost(args, host, repoRootFromFlag, io) {
909
+ if (!host) {
910
+ return { args, repoRootFromHost: false };
911
+ }
912
+ let repoRoot = args.repoRoot;
913
+ let repoRootFromHost = false;
914
+ if (host.repoRoot && !repoRootFromFlag) {
915
+ const resolved = resolveHostRepoRoot(host.repoRoot);
916
+ if (!resolved) {
917
+ io.stderr.write(`Ignoring the repo folder chosen in Forge (${host.repoRoot}): it is not a path on this machine.\n`);
918
+ }
919
+ else {
920
+ repoRootFromHost = true;
921
+ repoRoot = resolved;
922
+ }
923
+ }
924
+ return {
925
+ args: {
926
+ ...args,
927
+ name: host.name ?? args.name,
928
+ cliProviders: host.cliProviders && !args.cliProvidersFromFlag ? [...host.cliProviders] : args.cliProviders,
929
+ repoRoot
930
+ },
931
+ repoRootFromHost
932
+ };
933
+ }
934
+ /** Expands `~` in a repo folder chosen in Forge and rejects one shaped for another OS. */
935
+ export function resolveHostRepoRoot(value, platform = process.platform, home = os.homedir()) {
936
+ const trimmed = value.trim();
937
+ if (!trimmed) {
938
+ return undefined;
939
+ }
940
+ const pathApi = platform === "win32" ? path.win32 : path.posix;
941
+ if (trimmed === "~") {
942
+ return home;
943
+ }
944
+ if (/^~[\\/]/.test(trimmed)) {
945
+ return pathApi.resolve(home, trimmed.slice(2));
946
+ }
947
+ const windowsShaped = /^[A-Za-z]:[\\/]/.test(trimmed) || trimmed.startsWith("\\\\");
948
+ if (platform === "win32") {
949
+ return windowsShaped || trimmed.startsWith("/") ? pathApi.resolve(trimmed) : undefined;
950
+ }
951
+ return !windowsShaped && trimmed.startsWith("/") ? pathApi.resolve(trimmed) : undefined;
952
+ }
840
953
  function pairedConfig(current, args, claim) {
841
954
  return {
842
955
  ...current,
@@ -881,11 +994,7 @@ async function resolvePairingCode(code) {
881
994
  prompt.close();
882
995
  }
883
996
  }
884
- async function resolvePairRepoRoot(repoRoot, configuredRoot) {
885
- const fallback = path.resolve(repoRoot ?? configuredRoot ?? path.join(os.homedir(), "ForgeRepos"));
886
- if (repoRoot?.trim()) {
887
- return fallback;
888
- }
997
+ async function promptPairRepoRoot(fallback) {
889
998
  if (!process.stdin.isTTY || !process.stdout.isTTY) {
890
999
  return fallback;
891
1000
  }
@@ -30,8 +30,12 @@ export interface LocalRepoMapping extends BridgeRepoMapping {
30
30
  export declare function resolveLocalConfigPath(): string;
31
31
  export declare function readLocalConfig(): Promise<BridgeLocalConfig>;
32
32
  export declare function readLocalConfigSync(): BridgeLocalConfig;
33
+ /** Decision 0014 §5: `bridge.json` holds the device token, so only its owner may read it. */
34
+ export declare const localConfigFileMode = 384;
33
35
  export declare function writeLocalConfig(config: BridgeLocalConfig): Promise<void>;
34
36
  export declare function applyLocalConfigDefaults(config: BridgeServiceConfig, local: BridgeLocalConfig): BridgeServiceConfig;
37
+ /** Decision 0014: the `forge-bridge yield` flag, beside the bridge config and never inside it. */
38
+ export declare function resolveLocalYieldFlagPath(): string;
35
39
  export declare function addRepoMapping(label: string, repoPath: string): Promise<BridgeLocalConfig>;
36
40
  export declare function removeRepoMapping(label: string): Promise<{
37
41
  readonly config: BridgeLocalConfig;
@@ -2,6 +2,7 @@ import fs from "node:fs/promises";
2
2
  import fsSync from "node:fs";
3
3
  import os from "node:os";
4
4
  import path from "node:path";
5
+ import { localYieldFlagPathFor } from "../bridge/local-yield-flag.js";
5
6
  export function resolveLocalConfigPath() {
6
7
  if (process.env.FORGE_BRIDGE_CONFIG?.trim()) {
7
8
  return path.resolve(process.env.FORGE_BRIDGE_CONFIG);
@@ -28,12 +29,28 @@ export function readLocalConfigSync() {
28
29
  }
29
30
  return parseLocalConfig(fsSync.readFileSync(configPath, "utf8"));
30
31
  }
32
+ /** Decision 0014 §5: `bridge.json` holds the device token, so only its owner may read it. */
33
+ export const localConfigFileMode = 0o600;
34
+ const localConfigDirectoryMode = 0o700;
31
35
  export async function writeLocalConfig(config) {
32
36
  const configPath = resolveLocalConfigPath();
33
- await fs.mkdir(path.dirname(configPath), { recursive: true });
37
+ await fs.mkdir(path.dirname(configPath), { recursive: true, mode: localConfigDirectoryMode });
34
38
  const tempPath = `${configPath}.${process.pid}.${Date.now()}.tmp`;
35
- await fs.writeFile(tempPath, `${JSON.stringify(normalizeLocalConfig(config), null, 2)}\n`, "utf8");
36
- await fs.rename(tempPath, configPath);
39
+ try {
40
+ await fs.writeFile(tempPath, `${JSON.stringify(normalizeLocalConfig(config), null, 2)}\n`, {
41
+ encoding: "utf8",
42
+ mode: localConfigFileMode
43
+ });
44
+ if (process.platform !== "win32") {
45
+ // The create mode is masked by the umask; set it exactly before the file becomes visible.
46
+ await fs.chmod(tempPath, localConfigFileMode);
47
+ }
48
+ await fs.rename(tempPath, configPath);
49
+ }
50
+ catch (error) {
51
+ await fs.rm(tempPath, { force: true }).catch(() => undefined);
52
+ throw error;
53
+ }
37
54
  }
38
55
  export function applyLocalConfigDefaults(config, local) {
39
56
  const cliProviders = local.cliProviders && local.cliProviders.length > 0 ? [...local.cliProviders] : config.cliProviders;
@@ -65,9 +82,14 @@ export function applyLocalConfigDefaults(config, local) {
65
82
  supportsRunnerAuthoredPhaseArtifacts: local.supportsRunnerAuthoredPhaseArtifacts ?? config.supportsRunnerAuthoredPhaseArtifacts,
66
83
  supportsDraftRunOnce: local.supportsDraftRunOnce ?? config.supportsDraftRunOnce,
67
84
  supportsDraftAttachments: local.supportsDraftAttachments ?? config.supportsDraftAttachments,
68
- supportsDraftImageAttachments: local.supportsDraftImageAttachments ?? config.supportsDraftImageAttachments
85
+ supportsDraftImageAttachments: local.supportsDraftImageAttachments ?? config.supportsDraftImageAttachments,
86
+ localYieldFlagPath: resolveLocalYieldFlagPath()
69
87
  };
70
88
  }
89
+ /** Decision 0014: the `forge-bridge yield` flag, beside the bridge config and never inside it. */
90
+ export function resolveLocalYieldFlagPath() {
91
+ return localYieldFlagPathFor(resolveLocalConfigPath());
92
+ }
71
93
  export async function addRepoMapping(label, repoPath) {
72
94
  const normalizedLabel = normalizeLabel(label);
73
95
  const localPath = path.resolve(repoPath);
@@ -1,3 +1,4 @@
1
+ import type { AttemptProcessSupervisor } from "./attempt-process-supervisor.js";
1
2
  export interface AspNetRuntimePrebuildPlan {
2
3
  readonly fingerprint: string;
3
4
  readonly receiptPath: string;
@@ -22,6 +23,10 @@ export interface AspNetRuntimeBuildExecutionResult {
22
23
  readonly stderrLogPath: string;
23
24
  }
24
25
  export type AspNetRuntimeBuildExecutor = (plan: AspNetRuntimePrebuildPlan, signal?: AbortSignal) => Promise<AspNetRuntimeBuildExecutionResult>;
26
+ /** Runs one ASP.NET runtime build under the attempt's supervisor, logging only redacted output. */
27
+ export declare function executeAspNetRuntimeBuild(supervisor: AttemptProcessSupervisor, logDirectory: string, plan: AspNetRuntimePrebuildPlan, signal?: AbortSignal, exactSecrets?: readonly string[],
28
+ /** Once the build's supervised tree is up: records it on the build's host load token. */
29
+ onStarted?: (metadataPath: string) => Promise<void>): Promise<AspNetRuntimeBuildExecutionResult>;
25
30
  export declare function createAspNetRuntimePrebuildPlan(options: {
26
31
  readonly command: string;
27
32
  readonly args: readonly string[];
@@ -3,7 +3,51 @@ import { spawn } from "node:child_process";
3
3
  import fs from "node:fs/promises";
4
4
  import path from "node:path";
5
5
  import { ForgeFailureError } from "../session/session.types.js";
6
+ import { redactText } from "../shared/redaction/redaction.js";
6
7
  const inFlightPrebuilds = new Map();
8
+ /** Runs one ASP.NET runtime build under the attempt's supervisor, logging only redacted output. */
9
+ export async function executeAspNetRuntimeBuild(supervisor, logDirectory, plan, signal, exactSecrets = [],
10
+ /** Once the build's supervised tree is up: records it on the build's host load token. */
11
+ onStarted) {
12
+ const childName = `runtime-build-${plan.fingerprint.slice(-12)}`;
13
+ const stdoutLogPath = path.join(logDirectory, `${childName}.stdout.log`);
14
+ const stderrLogPath = path.join(logDirectory, `${childName}.stderr.log`);
15
+ let stdoutTail = "";
16
+ let stderrTail = "";
17
+ const append = async (target, line) => {
18
+ await fs.appendFile(target, `${redactText(line, exactSecrets)}\n`, { encoding: "utf8", mode: 0o600 });
19
+ };
20
+ const child = await supervisor.startChildReady(childName, {
21
+ command: plan.command,
22
+ args: plan.args,
23
+ cwd: plan.cwd,
24
+ env: plan.environment,
25
+ captureOutput: false,
26
+ }, {
27
+ onStdoutLine: async (line) => {
28
+ stdoutTail = appendRuntimeBuildTail(stdoutTail, redactText(line, exactSecrets));
29
+ await append(stdoutLogPath, line);
30
+ },
31
+ onStderrLine: async (line) => {
32
+ stderrTail = appendRuntimeBuildTail(stderrTail, redactText(line, exactSecrets));
33
+ await append(stderrLogPath, line);
34
+ },
35
+ }, signal, { maxStartAttempts: 2, retryDelayMs: 250 });
36
+ await onStarted?.(child.metadataPath);
37
+ const result = await child.result;
38
+ return {
39
+ exitCode: result.exitCode,
40
+ stdoutTail: appendRuntimeBuildTail(stdoutTail, redactText(result.stdout, exactSecrets)),
41
+ stderrTail: appendRuntimeBuildTail(stderrTail, redactText(result.stderr, exactSecrets)),
42
+ stdoutLogPath,
43
+ stderrLogPath,
44
+ };
45
+ }
46
+ function appendRuntimeBuildTail(current, value) {
47
+ if (!value)
48
+ return current;
49
+ return `${current}${current ? "\n" : ""}${value}`.slice(-4_000);
50
+ }
7
51
  export function createAspNetRuntimePrebuildPlan(options) {
8
52
  if (!isDotnetRun(options.command, options.args))
9
53
  return null;
@@ -75,7 +75,7 @@ export interface NativeTestClusterAdmin {
75
75
  readonly username: string;
76
76
  readonly password: string;
77
77
  }
78
- export declare function nativeTestClusterAdmin(fallback: NativeTestPostgresFallback): NativeTestClusterAdmin;
78
+ export declare function nativeTestClusterAdmin(fallback: Pick<NativeTestPostgresFallback, "connectionString" | "endpoint">): NativeTestClusterAdmin;
79
79
  /** Runs SQL through the psql that ships with the PostgreSQL install hosting the native test cluster. */
80
80
  export declare function psqlSqlRunner(admin: NativeTestClusterAdmin, psqlPath: string, timeoutMs?: number): AttemptDatabaseSqlRunner;
81
81
  /** psql beside the cluster's pg_ctl: FORGE_NATIVE_TEST_POSTGRES_PSQL, a Windows install, or PATH. */
@@ -62,6 +62,11 @@ export declare class DockerEngineProbe {
62
62
  constructor(options?: DockerEngineProbeOptions, commands?: CommandRunner, cacheMs?: number);
63
63
  current(): DockerEngineCapabilitySnapshot | null;
64
64
  refresh(force?: boolean): Promise<DockerEngineCapabilitySnapshot>;
65
+ /**
66
+ * One fresh daemon reading that never starts recovery and leaves the cache and the
67
+ * failure streak alone, for callers that only need to know whether Docker is up.
68
+ */
69
+ probeWithoutRecovery(): Promise<DockerEngineCapabilitySnapshot>;
65
70
  /**
66
71
  * Establishes a fresh daemon fence for work that declares Docker as a hard
67
72
  * prerequisite. This remains bounded, cooldown protected and single-flight;
@@ -69,6 +69,13 @@ export class DockerEngineProbe {
69
69
  this.inFlight = operation;
70
70
  return await operation;
71
71
  }
72
+ /**
73
+ * One fresh daemon reading that never starts recovery and leaves the cache and the
74
+ * failure streak alone, for callers that only need to know whether Docker is up.
75
+ */
76
+ async probeWithoutRecovery() {
77
+ return await this.inspectSafely();
78
+ }
72
79
  /**
73
80
  * Establishes a fresh daemon fence for work that declares Docker as a hard
74
81
  * prerequisite. This remains bounded, cooldown protected and single-flight;
@@ -0,0 +1,37 @@
1
+ import { type EphemeralTestPostgresCluster, type EphemeralTestPostgresOptions } from "./ephemeral-test-postgres.js";
2
+ import { type NativeTestPostgresFallback, type NativeTestPostgresGrant } from "./native-test-postgres-fallback.js";
3
+ export type StartEphemeralTestPostgres = (options: EphemeralTestPostgresOptions) => Promise<EphemeralTestPostgresCluster>;
4
+ /** The bin directory an ephemeral cluster runs from: the file's `postgresBin`, else the one holding psql. */
5
+ export declare function ephemeralTestPostgresBinDirectory(fallback: Pick<NativeTestPostgresFallback, "postgresBin">, psqlPath?: () => string | null): string;
6
+ /**
7
+ * Starts a throwaway cluster for one check and returns its grant. The grant's mode keeps the
8
+ * Docker semantics of the shared cluster: with Docker up, pinned-engine tests still start their
9
+ * own containers; with Docker down, they are skipped. The caller must call `release`.
10
+ */
11
+ export declare function startEphemeralTestPostgresGrant(fallback: Pick<NativeTestPostgresFallback, "postgresBin">, dockerAvailable: boolean, start?: StartEphemeralTestPostgres): Promise<NativeTestPostgresGrant>;
12
+ /** A managed verification command's database environment, and what to release when the command ends. */
13
+ export interface ManagedVerificationDatabase {
14
+ readonly environment: Readonly<Record<string, string>>;
15
+ /** The connection strings and their passwords, for redaction; never the mode or the cluster id. */
16
+ readonly secrets: readonly string[];
17
+ readonly release: () => Promise<void>;
18
+ }
19
+ /** A command that runs no verification profile gets no database. */
20
+ export declare const noManagedVerificationDatabase: ManagedVerificationDatabase;
21
+ /**
22
+ * Builds a command's setup from its database. If the setup throws, the command never starts and
23
+ * no caller holds the database, so it is released here before the error is rethrown.
24
+ */
25
+ export declare function setUpWithManagedVerificationDatabase<T>(database: Pick<ManagedVerificationDatabase, "release">, setUp: () => T): Promise<T>;
26
+ /**
27
+ * Releases a command's database once the command has ended. A cluster that would not stop is left
28
+ * disowned for the next start's reap; the failure goes to `report` instead of being dropped.
29
+ */
30
+ export declare function releaseManagedVerificationDatabase(database: Pick<ManagedVerificationDatabase, "release">, report: (message: string) => Promise<void>): Promise<void>;
31
+ /**
32
+ * Managed verification on an `ephemeral` host gets a throwaway cluster for the command's
33
+ * lifetime; every other host keeps managedVerificationDatabaseEnvironment's rules. A cluster
34
+ * that cannot start fails the command rather than silently handing it Docker or the shared
35
+ * cluster's narrower login.
36
+ */
37
+ export declare function managedVerificationDatabase(dockerAvailable?: () => Promise<boolean>, readFallback?: () => NativeTestPostgresFallback | null, start?: StartEphemeralTestPostgres): Promise<ManagedVerificationDatabase>;
@@ -0,0 +1,85 @@
1
+ import path from "node:path";
2
+ import { attemptDatabaseCapabilitySecrets, resolvePsqlPath } from "./attempt-database-broker.js";
3
+ import { EphemeralTestPostgresError, ephemeralTestPostgresClusterEnvironment, startEphemeralTestPostgres, } from "./ephemeral-test-postgres.js";
4
+ import { DockerEngineProbe } from "./docker-engine-probe.js";
5
+ import { managedVerificationDatabaseEnvironment, nativeTestPostgresFallbackConfigEnvironment, nativeTestPostgresFallbackDatabaseMode, nativeTestPostgresFallbackEnvironment, nativeTestPostgresPreferredDatabaseMode, readNativeTestPostgresFallback, } from "./native-test-postgres-fallback.js";
6
+ /** The bin directory an ephemeral cluster runs from: the file's `postgresBin`, else the one holding psql. */
7
+ export function ephemeralTestPostgresBinDirectory(fallback, psqlPath = resolvePsqlPath) {
8
+ if (fallback.postgresBin)
9
+ return fallback.postgresBin;
10
+ const psql = psqlPath();
11
+ if (!psql) {
12
+ throw new EphemeralTestPostgresError("no PostgreSQL install was found; set 'postgresBin' in native-test-postgres.json or FORGE_NATIVE_TEST_POSTGRES_PSQL.");
13
+ }
14
+ return path.dirname(psql);
15
+ }
16
+ /**
17
+ * Starts a throwaway cluster for one check and returns its grant. The grant's mode keeps the
18
+ * Docker semantics of the shared cluster: with Docker up, pinned-engine tests still start their
19
+ * own containers; with Docker down, they are skipped. The caller must call `release`.
20
+ */
21
+ export async function startEphemeralTestPostgresGrant(fallback, dockerAvailable, start = startEphemeralTestPostgres) {
22
+ const cluster = await start({ binDirectory: ephemeralTestPostgresBinDirectory(fallback) });
23
+ return {
24
+ connectionString: cluster.connectionString,
25
+ endpoint: cluster.endpoint,
26
+ mode: dockerAvailable ? nativeTestPostgresPreferredDatabaseMode : nativeTestPostgresFallbackDatabaseMode,
27
+ ephemeralClusterId: cluster.id,
28
+ release: cluster.release,
29
+ };
30
+ }
31
+ /** A command that runs no verification profile gets no database. */
32
+ export const noManagedVerificationDatabase = {
33
+ environment: {},
34
+ secrets: [],
35
+ release: async () => undefined,
36
+ };
37
+ /**
38
+ * Builds a command's setup from its database. If the setup throws, the command never starts and
39
+ * no caller holds the database, so it is released here before the error is rethrown.
40
+ */
41
+ export async function setUpWithManagedVerificationDatabase(database, setUp) {
42
+ try {
43
+ return setUp();
44
+ }
45
+ catch (error) {
46
+ await database.release().catch(() => undefined);
47
+ throw error;
48
+ }
49
+ }
50
+ /**
51
+ * Releases a command's database once the command has ended. A cluster that would not stop is left
52
+ * disowned for the next start's reap; the failure goes to `report` instead of being dropped.
53
+ */
54
+ export async function releaseManagedVerificationDatabase(database, report) {
55
+ try {
56
+ await database.release();
57
+ }
58
+ catch (error) {
59
+ await report(error instanceof Error ? error.message : String(error)).catch(() => undefined);
60
+ }
61
+ }
62
+ function databaseSecrets(environment) {
63
+ return Object.entries(environment)
64
+ .filter(([name]) => name !== "FORGE_MANAGED_VERIFICATION_DATABASE_MODE" && name !== ephemeralTestPostgresClusterEnvironment)
65
+ .flatMap(([, value]) => attemptDatabaseCapabilitySecrets(value));
66
+ }
67
+ /**
68
+ * Managed verification on an `ephemeral` host gets a throwaway cluster for the command's
69
+ * lifetime; every other host keeps managedVerificationDatabaseEnvironment's rules. A cluster
70
+ * that cannot start fails the command rather than silently handing it Docker or the shared
71
+ * cluster's narrower login.
72
+ */
73
+ export async function managedVerificationDatabase(dockerAvailable = async () => (await new DockerEngineProbe().probeWithoutRecovery()).available, readFallback = () => {
74
+ const configPath = process.env[nativeTestPostgresFallbackConfigEnvironment]?.trim();
75
+ return configPath ? readNativeTestPostgresFallback(configPath) : null;
76
+ }, start = startEphemeralTestPostgres) {
77
+ const fallback = readFallback();
78
+ if (fallback?.use !== "ephemeral") {
79
+ const environment = await managedVerificationDatabaseEnvironment(dockerAvailable, () => fallback);
80
+ return { environment, secrets: databaseSecrets(environment), release: async () => undefined };
81
+ }
82
+ const grant = await startEphemeralTestPostgresGrant(fallback, await dockerAvailable(), start);
83
+ const environment = nativeTestPostgresFallbackEnvironment(grant);
84
+ return { environment, secrets: databaseSecrets(environment), release: grant.release ?? (async () => undefined) };
85
+ }
@@ -0,0 +1,57 @@
1
+ /** Set for a test run on an ephemeral cluster: its id, which the server reports as `forge.ephemeral_cluster`. */
2
+ export declare const ephemeralTestPostgresClusterEnvironment = "FORGE_TEST_POSTGRES_EPHEMERAL_CLUSTER";
3
+ export declare const ephemeralTestPostgresMarkerSetting = "forge.ephemeral_cluster";
4
+ export declare class EphemeralTestPostgresError extends Error {
5
+ readonly code = "ephemeral_test_postgres_unavailable";
6
+ constructor(detail: string);
7
+ }
8
+ export interface EphemeralTestPostgresCluster {
9
+ readonly id: string;
10
+ readonly connectionString: string;
11
+ readonly endpoint: string;
12
+ readonly password: string;
13
+ /**
14
+ * Stops the server and deletes its directory. Safe to call more than once. Rejects, keeping the
15
+ * directory, when the server is still running after the stop.
16
+ */
17
+ release(): Promise<void>;
18
+ }
19
+ export interface ToolResult {
20
+ readonly code: number | null;
21
+ readonly output: string;
22
+ }
23
+ /** Runs one PostgreSQL program. `detached` programs (pg_ctl start) leave a server running, so their output goes to its log. */
24
+ export type EphemeralToolRunner = (file: string, args: readonly string[], options: {
25
+ readonly env: Readonly<Record<string, string>>;
26
+ readonly timeoutMs: number;
27
+ readonly detached?: boolean;
28
+ }) => Promise<ToolResult>;
29
+ export interface EphemeralTestPostgresOptions {
30
+ /** The directory holding initdb, pg_ctl and psql of the PostgreSQL install to run. */
31
+ readonly binDirectory: string;
32
+ readonly root?: string;
33
+ readonly ownerPid?: number;
34
+ readonly runTool?: EphemeralToolRunner;
35
+ readonly isProcessAlive?: (pid: number) => boolean;
36
+ readonly freePort?: () => Promise<number>;
37
+ readonly now?: () => number;
38
+ }
39
+ export declare function defaultEphemeralTestPostgresRoot(): string;
40
+ /**
41
+ * A superuser of a cluster run by the `postgres` OS user can read every cluster that user runs,
42
+ * including live ones (Debian and Ubuntu packages run them all as `postgres`). An ephemeral
43
+ * cluster therefore runs only as an ordinary user, the same one that already runs the attempt.
44
+ */
45
+ export declare function assertEphemeralClusterOsUser(userName?: string, uid?: number | undefined): void;
46
+ /** Creates, starts and prepares one cluster. On any failure nothing of it is left behind. */
47
+ export declare function startEphemeralTestPostgres(options: EphemeralTestPostgresOptions): Promise<EphemeralTestPostgresCluster>;
48
+ /**
49
+ * Removes clusters whose owning Bridge process is gone. Only directories named like a cluster
50
+ * id inside the root are considered, and a live owner's clusters are never touched.
51
+ */
52
+ export declare function reapEphemeralTestPostgres(options: EphemeralTestPostgresOptions): Promise<readonly string[]>;
53
+ /**
54
+ * On Windows a started postgres inherits pg_ctl's standard handles, so a pipe would stay open for
55
+ * the server's lifetime; a detached program gets no pipes and settles when it exits.
56
+ */
57
+ export declare const runPostgresTool: EphemeralToolRunner;