@loucompanion/forge-bridge 0.1.4-dev.ccffca94938b → 0.1.4-dev.deb7f72e7930

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 (141) hide show
  1. package/README.md +87 -1
  2. package/dist/bridge/bridge-chat-provider-command.d.ts +4 -1
  3. package/dist/bridge/bridge-chat-provider-command.js +14 -19
  4. package/dist/bridge/bridge-state-file.d.ts +161 -0
  5. package/dist/bridge/bridge-state-file.js +376 -0
  6. package/dist/bridge/bridge-state-io.d.ts +11 -0
  7. package/dist/bridge/bridge-state-io.js +50 -0
  8. package/dist/bridge/bridge-state-lock.d.ts +11 -0
  9. package/dist/bridge/bridge-state-lock.js +102 -0
  10. package/dist/bridge/bridge-state-unpublished.d.ts +17 -0
  11. package/dist/bridge/bridge-state-unpublished.js +111 -0
  12. package/dist/bridge/bridge.service.d.ts +16 -12
  13. package/dist/bridge/bridge.service.js +131 -243
  14. package/dist/bridge/bridge.types.d.ts +5 -0
  15. package/dist/bridge/in-flight-registry.d.ts +62 -0
  16. package/dist/bridge/in-flight-registry.js +207 -0
  17. package/dist/bridge/readiness-result-outbox.d.ts +5 -1
  18. package/dist/bridge/readiness-result-outbox.js +20 -0
  19. package/dist/bridge/sandbox-resource-accounting.d.ts +16 -0
  20. package/dist/bridge/sandbox-resource-accounting.js +150 -0
  21. package/dist/cleanup/cleanup-wip.d.ts +12 -0
  22. package/dist/cleanup/cleanup-wip.js +66 -0
  23. package/dist/cleanup/cleanup.service.d.ts +11 -1
  24. package/dist/cleanup/cleanup.service.js +80 -62
  25. package/dist/cleanup/cleanup.types.d.ts +2 -0
  26. package/dist/cleanup/host-runtime-ledger.d.ts +2 -0
  27. package/dist/cleanup/host-runtime-ledger.js +30 -9
  28. package/dist/cli/cli.help.js +56 -12
  29. package/dist/cli/cli.service.d.ts +3 -10
  30. package/dist/cli/cli.service.js +10 -171
  31. package/dist/cli/idle-status.d.ts +84 -0
  32. package/dist/cli/idle-status.js +181 -0
  33. package/dist/cli/local-config.d.ts +2 -0
  34. package/dist/cli/local-config.js +7 -1
  35. package/dist/cli/provider-cli-detection.d.ts +10 -0
  36. package/dist/cli/provider-cli-detection.js +160 -0
  37. package/dist/runtime/aspnet-runtime-prebuild.d.ts +5 -0
  38. package/dist/runtime/aspnet-runtime-prebuild.js +46 -1
  39. package/dist/runtime/attempt-database-broker.d.ts +1 -1
  40. package/dist/runtime/docker-engine-probe.d.ts +5 -0
  41. package/dist/runtime/docker-engine-probe.js +7 -0
  42. package/dist/runtime/ephemeral-test-postgres-grant.d.ts +37 -0
  43. package/dist/runtime/ephemeral-test-postgres-grant.js +85 -0
  44. package/dist/runtime/ephemeral-test-postgres.d.ts +57 -0
  45. package/dist/runtime/ephemeral-test-postgres.js +303 -0
  46. package/dist/runtime/host-load-governor.d.ts +2 -0
  47. package/dist/runtime/host-load-ledger-lock.js +6 -4
  48. package/dist/runtime/host-load-runtime-settings.js +4 -2
  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.js +10 -50
  52. package/dist/runtime/managed-command-teardown.js +5 -16
  53. package/dist/runtime/native-test-postgres-fallback.d.ts +51 -7
  54. package/dist/runtime/native-test-postgres-fallback.js +60 -8
  55. package/dist/runtime/runner-settings.d.ts +4 -0
  56. package/dist/runtime/runner-settings.js +22 -0
  57. package/dist/sandbox/host-capacity-broker.d.ts +3 -1
  58. package/dist/sandbox/host-capacity-broker.js +4 -2
  59. package/dist/sandbox/managed-branch.d.ts +13 -0
  60. package/dist/sandbox/managed-branch.js +36 -0
  61. package/dist/sandbox/provider-auth/codex.js +11 -11
  62. package/dist/sandbox/runtime.js +2 -6
  63. package/dist/session/managed-attempt-tools.d.ts +0 -7
  64. package/dist/session/managed-attempt-tools.js +45 -77
  65. package/dist/session/managed-build-receipt.d.ts +5 -0
  66. package/dist/session/managed-build-receipt.js +8 -3
  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 +43 -197
  74. package/dist/session/pre-publication-native-postgres.d.ts +30 -0
  75. package/dist/session/pre-publication-native-postgres.js +111 -0
  76. package/dist/session/pre-publication-process.js +10 -10
  77. package/dist/session/pre-publication-step-execution.d.ts +2 -1
  78. package/dist/session/pre-publication-step-execution.js +6 -5
  79. package/dist/session/pre-publication-validation.d.ts +7 -3
  80. package/dist/session/pre-publication-validation.js +32 -30
  81. package/dist/session/provider-cli/claude-background-work.d.ts +3 -2
  82. package/dist/session/provider-cli/claude-background-work.js +4 -3
  83. package/dist/session/provider-cli/host-build-lock.d.ts +18 -0
  84. package/dist/session/provider-cli/host-build-lock.js +30 -0
  85. package/dist/session/provider-cli/pre-publication-repair.d.ts +16 -0
  86. package/dist/session/provider-cli/pre-publication-repair.js +33 -0
  87. package/dist/session/provider-cli/provider-cli.child-environment.js +4 -2
  88. package/dist/session/provider-cli/provider-cli.process.d.ts +2 -14
  89. package/dist/session/provider-cli/provider-cli.process.js +4 -94
  90. package/dist/session/provider-cli/provider-cli.prompts.d.ts +3 -0
  91. package/dist/session/provider-cli/provider-cli.prompts.js +27 -27
  92. package/dist/session/provider-cli/provider-cli.runtime.d.ts +8 -0
  93. package/dist/session/provider-cli/provider-cli.runtime.js +23 -2
  94. package/dist/session/provider-cli/provider-cli.service.d.ts +4 -1
  95. package/dist/session/provider-cli/provider-cli.service.js +27 -43
  96. package/dist/session/provider-cli/provider-cli.windows-launch.d.ts +23 -0
  97. package/dist/session/provider-cli/provider-cli.windows-launch.js +131 -0
  98. package/dist/session/provider-cli/provider-user-config-isolation.d.ts +69 -0
  99. package/dist/session/provider-cli/provider-user-config-isolation.js +164 -0
  100. package/dist/session/qa-sidecar-validation.d.ts +6 -0
  101. package/dist/session/qa-sidecar-validation.js +28 -0
  102. package/dist/session/sandbox-host-capacity-gate.d.ts +22 -1
  103. package/dist/session/sandbox-host-capacity-gate.js +34 -15
  104. package/dist/session/session-redaction.js +31 -181
  105. package/dist/session/session.service.d.ts +2 -0
  106. package/dist/session/session.service.js +62 -56
  107. package/dist/session/session.types.js +1 -1
  108. package/dist/session/sidecar-json-shape.d.ts +31 -0
  109. package/dist/session/sidecar-json-shape.js +217 -0
  110. package/dist/shared/fs/file-identity.d.ts +10 -0
  111. package/dist/shared/fs/file-identity.js +15 -0
  112. package/dist/shared/fs/replace-file.d.ts +7 -0
  113. package/dist/shared/fs/replace-file.js +33 -0
  114. package/dist/shared/process/host-process-recovery.d.ts +14 -3
  115. package/dist/shared/process/host-process-recovery.js +23 -3
  116. package/dist/shared/process/host-process-supervisor.d.ts +13 -1
  117. package/dist/shared/process/host-process-supervisor.js +66 -14
  118. package/dist/shared/provider-capabilities.js +9 -1
  119. package/dist/version.d.ts +1 -1
  120. package/dist/version.js +1 -1
  121. package/dist/worktree/wip-git.d.ts +33 -0
  122. package/dist/worktree/wip-git.js +122 -0
  123. package/dist/worktree/wip-refs.d.ts +62 -0
  124. package/dist/worktree/wip-refs.js +119 -0
  125. package/dist/worktree/wip-restore.d.ts +38 -0
  126. package/dist/worktree/wip-restore.js +190 -0
  127. package/dist/worktree/wip-snapshot.d.ts +50 -0
  128. package/dist/worktree/wip-snapshot.js +268 -0
  129. package/dist/worktree/worktree-inputs.d.ts +8 -0
  130. package/dist/worktree/worktree-inputs.js +134 -0
  131. package/dist/worktree/worktree-origin-sync.d.ts +34 -0
  132. package/dist/worktree/worktree-origin-sync.js +127 -0
  133. package/dist/worktree/worktree-wip-events.d.ts +18 -0
  134. package/dist/worktree/worktree-wip-events.js +98 -0
  135. package/dist/worktree/worktree-wip.d.ts +49 -0
  136. package/dist/worktree/worktree-wip.js +182 -0
  137. package/dist/worktree/worktree.base.d.ts +7 -1
  138. package/dist/worktree/worktree.service.d.ts +27 -5
  139. package/dist/worktree/worktree.service.js +106 -181
  140. package/dist/worktree/worktree.types.d.ts +31 -0
  141. package/package.json +1 -1
package/README.md CHANGED
@@ -65,7 +65,7 @@ The bridge auto-detects these provider CLIs on `PATH` and advertises the ones it
65
65
 
66
66
  Claude Code notes:
67
67
 
68
- - Install with the native installer or `npm install -g @anthropic-ai/claude-code`. On Windows, Claude Code needs Git for Windows; set `CLAUDE_CODE_GIT_BASH_PATH` if `bash.exe` is not on `PATH`. `CLAUDE_CONFIG_DIR` is passed through if you keep config outside `~/.claude`.
68
+ - Install with the native installer or `npm install -g @anthropic-ai/claude-code`. On Windows, Claude Code needs Git for Windows; set `CLAUDE_CODE_GIT_BASH_PATH` if `bash.exe` is not on `PATH`. Forge doesn't pass `CLAUDE_CONFIG_DIR` to Claude Code, so it signs in from `~/.claude` (`%USERPROFILE%\.claude` on Windows) or with an Anthropic API key Forge grants; sign in there, not in a custom config directory.
69
69
  - Forge pipes the prompt on stdin, runs with `--permission-mode bypassPermissions` inside the managed worktree, and registers its completion MCP server through a temporary `--mcp-config` file outside the worktree with `--strict-mcp-config`, so user-level MCP servers are not loaded into unattended runs. Forge tools appear to the model as `mcp__forge__<tool>`.
70
70
  - Claude Code has no model-listing command, so the bridge advertises the `sonnet`, `opus`, and `haiku` aliases. Set `FORGE_CLAUDE_MODELS` to advertise specific model ids instead.
71
71
  - Claude runs in host mode only. Docker sandbox placement currently supports Codex only.
@@ -175,6 +175,92 @@ While yielding, the bridge takes no new attempts and heavy steps of running atte
175
175
  budget. Yield is on when this local flag or the runner's Yield toggle in Forge is on. The flag is stored
176
176
  in `bridge.yield.json` next to `bridge.json`, and a running bridge notices it within one heartbeat.
177
177
 
178
+ ## Restarting or updating the bridge safely
179
+
180
+ Restarting `forge-bridge connect` kills everything it is running, including work that has no agent
181
+ process yet: an accepted offer waiting for Start, host-runtime admission, worktree and dependency
182
+ preparation, prepared-runtime probes, pre-publication validation and teardown. Forge then records the
183
+ attempt's outcome as unknown. Checking for agent processes is not enough, so the running bridge
184
+ publishes its in-flight work to `bridge.state.json` next to `bridge.json` (pid, runner instance, a
185
+ heartbeat refreshed every 5 seconds, and each in-flight item with its ids, phase and start time), and
186
+ `forge-bridge status --idle` reads it. Each bridge reads and rewrites the file while it holds a lock
187
+ the operating system owns and frees when the bridge exits (an abstract socket on Linux, a named pipe
188
+ on Windows, a flock on `bridge.state.json.lock` on macOS), so a second bridge on the same config always
189
+ sees the first one's record and reports the conflict, and a stopping bridge never writes its "stopped"
190
+ record over a newer bridge's. A bridge that can't publish (a failed write, or the lock held by another
191
+ process for more than 5 seconds) leaves `bridge.state.json.unpublished.<id>.json` instead of touching
192
+ the shared record, and a record missing any field reads as unknown, so neither can read as idle:
193
+
194
+ | Exit code | Verdict | Meaning |
195
+ |---:|---|---|
196
+ | 0 | `idle` | A live bridge reported a fresh heartbeat with nothing in flight. |
197
+ | 1 | `busy` | Work is in flight; restarting now would kill it. |
198
+ | 2 | | Usage error. |
199
+ | 3 | `stale` / `unknown` | Old heartbeat (hung bridge or reused pid), missing or unreadable state file, two bridge processes publishing to one config, or the bridge is shutting down. Idle can't be confirmed. A bridge older than this check writes no state file, so it reads as `unknown`. |
200
+ | 4 | `not_running` | The recorded bridge process has exited. Nothing to interrupt, but it is not an idle report. |
201
+ | 5 | `not_yielding` | With `--require-yield`: nothing in flight, but Forge has not acknowledged yield from this bridge, so placement can still pick it. |
202
+
203
+ `--json` prints the verdict, the reason, the heartbeat age, the pid check, the yield state (`yielding`:
204
+ acknowledged by Forge; `yieldApplied`: applied by the bridge) and the in-flight list. `--wait <seconds>`
205
+ keeps checking until the bridge is idle, its process has exited, or the time is up, so a file briefly
206
+ held by antivirus or the indexer doesn't end the wait; `--wait 0` checks once, like no `--wait`.
207
+ Against a bridge older than this check (no state file) it waits out the full time; check once without
208
+ `--wait` first.
209
+
210
+ What yield does and doesn't stop:
211
+
212
+ - It stops new attempts: the bridge refuses Offers while yielding (Forge re-places them), and Forge
213
+ stops placing work on the runner once it has acknowledged the yield (the next heartbeat or settings
214
+ report, at most about 30 seconds). `--require-yield` waits for that acknowledgement.
215
+ - It defers background runtime-readiness probes; Forge retries them after yield is off.
216
+ - It doesn't stop a Bridge Chat turn whose chat lease is already bound to this runner: Forge has no
217
+ retry for a refused turn, so the bridge runs it, and `status --idle` reports it as busy until it ends.
218
+ - It doesn't stop a legacy `Dispatch`, which Forge sends only to protocol-1 bridges. This bridge
219
+ registers a newer protocol, so it receives Offer and Start instead. A legacy dispatch is still
220
+ counted as busy.
221
+ - Attempts already running finish normally.
222
+
223
+ Restart procedure: yield, wait for idle, restart, then turn yield off once the new bridge has connected
224
+ (the flag file survives the restart, so the new bridge starts yielded and takes no work until then).
225
+ If the wait fails, turn yield off again so the runner doesn't stay out of placement, or leave it on
226
+ deliberately and retry later.
227
+ Run the commands as the same user and with the same `FORGE_BRIDGE_CONFIG` as the bridge so they use its
228
+ `bridge.json`, `bridge.yield.json` and `bridge.state.json`. On Windows, a shell inside an MSIX-packaged
229
+ app can have `%APPDATA%` writes virtualized away from the bridge; `--require-yield` catches that, because
230
+ the yield has to be applied by the bridge and acknowledged by Forge.
231
+
232
+ Linux or macOS:
233
+
234
+ ```bash
235
+ forge-bridge yield on
236
+ if forge-bridge status --idle --require-yield --wait 3600; then
237
+ # Stop forge-bridge connect, update it (npm install -g @loucompanion/forge-bridge@next), start it again.
238
+ forge-bridge yield off # once the new bridge has connected
239
+ else
240
+ code=$?
241
+ forge-bridge yield off # don't leave the runner out of placement
242
+ echo "Bridge is not idle (exit $code); not restarting." >&2
243
+ fi
244
+ ```
245
+
246
+ Windows PowerShell:
247
+
248
+ ```powershell
249
+ forge-bridge yield on
250
+ forge-bridge status --idle --require-yield --wait 3600
251
+ $code = $LASTEXITCODE
252
+ if ($code -eq 0) {
253
+ # Stop forge-bridge connect, update it (npm install -g @loucompanion/forge-bridge@next), start it again.
254
+ forge-bridge yield off # once the new bridge has connected
255
+ } else {
256
+ forge-bridge yield off # don't leave the runner out of placement
257
+ Write-Error "Bridge is not idle (exit $code); not restarting."
258
+ }
259
+ ```
260
+
261
+ The bridge also logs each accepted offer, each accepted dispatch and the start and end of each run,
262
+ with the dispatch attempt, lease, session and cycle ids.
263
+
178
264
  ## Pre-publication repair
179
265
 
180
266
  Before Forge commits and pushes an agent's work, the bridge runs the CI parity checks in
@@ -10,7 +10,10 @@ export declare function assertChatTurnFinished(result: Pick<ProviderProcessRunRe
10
10
  export interface ChatProviderCommandPlan {
11
11
  readonly command: ProviderCliCommand;
12
12
  readonly stdin?: string;
13
- /** Provider environment, such as the headless background-work restrictions for Claude. */
13
+ /**
14
+ * Provider environment: the host's .NET build lock (host-build-lock.ts), Codex's own home, and
15
+ * the headless background-work restrictions for Claude.
16
+ */
14
17
  readonly env?: Readonly<Record<string, string>>;
15
18
  }
16
19
  export declare function buildChatProviderCommand(packet: ChatTurnDispatchPacket, cwd: string): ChatProviderCommandPlan;
@@ -3,7 +3,9 @@
3
3
  * and the prompt that carries the conversation, its context references and its bounded handoff
4
4
  * metadata.
5
5
  */
6
- import { claudeHeadlessEnvironment, claudeHeadlessToolArgs, providerTurnEndedWithBackgroundWorkFailure } from "../session/provider-cli/claude-background-work.js";
6
+ import { claudeHeadlessEnvironment, providerTurnEndedWithBackgroundWorkFailure } from "../session/provider-cli/claude-background-work.js";
7
+ import { hostDotnetBuildLockEnvironment, hostDotnetBuildLockInstruction } from "../session/provider-cli/host-build-lock.js";
8
+ import { claudeIsolatedLaunchArgs, providerUserConfigIsolationUnsupported, providerUserConfigIsolationEnv } from "../session/provider-cli/provider-user-config-isolation.js";
7
9
  import { codexSandboxModeForPlatform, providerEffort } from "../session/provider-cli/provider-cli.prompts.js";
8
10
  import { chatProviderKind } from "./bridge-chat.types.js";
9
11
  /** The turn-scoped handoff metadata file the bridge writes into the chat workspace. */
@@ -43,33 +45,23 @@ export function buildChatProviderCommand(packet, cwd) {
43
45
  args.push(resumeThreadId);
44
46
  }
45
47
  args.push("-");
46
- return { command: { command: "codex", args }, stdin: prompt };
47
- }
48
- if (provider === "cursor") {
49
- const args = ["--print", "--output-format", "stream-json", "--model", model, "--workspace", cwd];
50
- if (resumeThreadId) {
51
- args.push("--resume", resumeThreadId);
52
- }
53
- args.push("--yolo", "--approve-mcps", "--trust", prompt);
54
- return { command: { command: "cursor-agent", args } };
48
+ // Codex runs with Forge's own CODEX_HOME, not the user's ~/.codex (provider-user-config-isolation.ts).
49
+ return { command: { command: "codex", args }, stdin: prompt, env: { ...hostDotnetBuildLockEnvironment(), ...providerUserConfigIsolationEnv("codex") } };
55
50
  }
56
51
  if (provider === "claude") {
57
52
  const args = ["-p", "--output-format", "stream-json", "--verbose", "--model", model];
58
53
  if (effort) {
59
54
  args.push("--effort", effort);
60
55
  }
61
- args.push("--permission-mode", "bypassPermissions", ...claudeHeadlessToolArgs());
56
+ // Only Forge's context and no MCP servers (provider-user-config-isolation.ts).
57
+ args.push("--permission-mode", "bypassPermissions", ...claudeIsolatedLaunchArgs({ workingDirectory: cwd, forgeMcpConfigPath: null, headless: true }));
62
58
  if (resumeThreadId) {
63
59
  args.push("--resume", resumeThreadId);
64
60
  }
65
- return { command: { command: "claude", args }, stdin: prompt, env: claudeHeadlessEnvironment };
61
+ return { command: { command: "claude", args }, stdin: prompt, env: { ...hostDotnetBuildLockEnvironment(), ...claudeHeadlessEnvironment } };
66
62
  }
67
- return {
68
- command: {
69
- command: provider,
70
- args: ["--model", model, prompt],
71
- },
72
- };
63
+ // cursor-agent and other CLIs can't be kept from the host user's own configuration.
64
+ throw providerUserConfigIsolationUnsupported(packet.providerKind);
73
65
  }
74
66
  function buildChatPrompt(packet) {
75
67
  const messages = packet.messages
@@ -89,12 +81,15 @@ function buildChatPrompt(packet) {
89
81
  ? "\n\nContinue the existing provider thread identified by the bridge; do not restart the conversation context."
90
82
  : "";
91
83
  const boundedMetadata = buildChatBoundedMetadataPrompt(packet);
84
+ // Chat turns run on the bridge's host, so they follow its .NET build lock like session turns.
85
+ const buildLock = hostDotnetBuildLockInstruction(process.env, "chat");
86
+ const hostRules = buildLock ? `\n\n# Host rules\n${buildLock}` : "";
92
87
  return `You are handling a Forge Bridge Chat turn.
93
88
 
94
89
  Conversation ID: ${packet.conversationId}
95
90
  Turn ID: ${packet.turnId}
96
91
  Provider: ${packet.providerKind}
97
- Model: ${packet.model}${continuation}${boundedMetadata}
92
+ Model: ${packet.model}${continuation}${boundedMetadata}${hostRules}
98
93
 
99
94
  # Conversation
100
95
 
@@ -0,0 +1,161 @@
1
+ import { type InFlightEntry } from "./in-flight-registry.js";
2
+ import { type BridgeStateLockOptions } from "./bridge-state-lock.js";
3
+ import { type UnpublishedMarker } from "./bridge-state-unpublished.js";
4
+ export { isProcessAlive } from "./bridge-state-io.js";
5
+ export declare const bridgeStateSchemaVersion = 1;
6
+ export declare const defaultStatePublishIntervalMs = 5000;
7
+ export interface BridgeStateFile {
8
+ readonly schemaVersion: typeof bridgeStateSchemaVersion;
9
+ readonly pid: number;
10
+ readonly runnerId: string;
11
+ readonly runnerInstanceId: string;
12
+ readonly version: string;
13
+ /** "running" while connect runs; "stopped" once it has shut down cleanly. */
14
+ readonly state: "running" | "stopped";
15
+ readonly startedAt: string;
16
+ readonly updatedAt: string;
17
+ readonly publishIntervalMs: number;
18
+ readonly connected: boolean;
19
+ /** Yield (local flag or Forge's toggle) that Forge has acknowledged: placement no longer picks this runner. */
20
+ readonly yielding: boolean;
21
+ /** Yield the bridge applies, acknowledged by Forge or not yet. */
22
+ readonly yieldApplied?: boolean;
23
+ /** Another live bridge process publishing to the same file, as last seen by this one. */
24
+ readonly conflict?: BridgeStateConflict | null;
25
+ /** Random per publisher: whose record this is, so a stopping bridge never finalizes another's. */
26
+ readonly publisherId?: string;
27
+ readonly inFlight: readonly InFlightEntry[];
28
+ }
29
+ export interface BridgeStateConflict {
30
+ readonly pid: number;
31
+ readonly runnerInstanceId: string;
32
+ readonly seenAt: string;
33
+ }
34
+ export type BridgeStateRead = {
35
+ readonly kind: "ok";
36
+ readonly state: BridgeStateFile;
37
+ /** Publishers that could not publish their latest state; present only when there are any. */
38
+ readonly unpublished?: readonly UnpublishedMarker[];
39
+ } | {
40
+ readonly kind: "missing";
41
+ } | {
42
+ readonly kind: "invalid";
43
+ readonly error: string;
44
+ };
45
+ export type BridgeIdleVerdict = "idle" | "busy" | "not_yielding" | "stale" | "unknown" | "not_running";
46
+ export declare const bridgeIdleExitCodes: Readonly<Record<BridgeIdleVerdict, number>>;
47
+ export interface BridgeIdleEvaluation {
48
+ readonly verdict: BridgeIdleVerdict;
49
+ readonly exitCode: number;
50
+ readonly reason: string;
51
+ readonly heartbeatAgeMs: number | null;
52
+ readonly staleAfterMs: number;
53
+ readonly pidAlive: boolean | null;
54
+ readonly state: BridgeStateFile | null;
55
+ }
56
+ /** `<config dir>/<config name>.state.json`, e.g. `~/.config/forge/bridge.state.json` beside `bridge.json`. */
57
+ export declare function bridgeStatePathFor(configPath: string): string;
58
+ /**
59
+ * Writes the state atomically: a temp file in the same folder, then a rename over the
60
+ * old one. On Windows the rename fails with EPERM/EBUSY/EACCES while a reader or an
61
+ * antivirus scanner has the target open, so it retries briefly.
62
+ */
63
+ export declare function writeBridgeStateFile(statePath: string, state: BridgeStateFile): Promise<void>;
64
+ /** The record and any live publisher's unpublished marker: what `status --idle` evaluates. */
65
+ export declare function readBridgeStateFile(statePath: string): Promise<BridgeStateRead>;
66
+ /** The record alone, as a publisher reads it before writing the next one. */
67
+ export declare function readBridgeStateRecord(statePath: string): Promise<BridgeStateRead>;
68
+ /** Removes the record so readers report unknown. Only a publisher holding the lock, over its own record. */
69
+ export declare function removeBridgeStateFile(statePath: string): Promise<void>;
70
+ export declare function staleAfterMsFor(state: Pick<BridgeStateFile, "publishIntervalMs"> | null): number;
71
+ /**
72
+ * Idle only when a live bridge process published a fresh heartbeat with nothing in
73
+ * flight. A dead pid, a stale heartbeat, a clean stop or an unreadable file is never
74
+ * reported as idle: each has its own verdict and a non-zero exit code.
75
+ */
76
+ export declare function evaluateBridgeIdle(read: BridgeStateRead, options: {
77
+ readonly now: number;
78
+ readonly pidAlive: (pid: number) => boolean;
79
+ readonly requireYield?: boolean;
80
+ }): BridgeIdleEvaluation;
81
+ export interface BridgeStateIdentity {
82
+ readonly runnerId: string;
83
+ readonly runnerInstanceId: string;
84
+ readonly version: string;
85
+ }
86
+ export interface BridgeStateSource {
87
+ inFlight(): readonly InFlightEntry[];
88
+ yielding(): boolean;
89
+ yieldApplied?(): boolean;
90
+ connected(): boolean;
91
+ }
92
+ export interface BridgeStatePublisherOptions {
93
+ readonly intervalMs?: number;
94
+ readonly now?: () => Date;
95
+ readonly pid?: number;
96
+ readonly write?: (statePath: string, state: BridgeStateFile) => Promise<void>;
97
+ readonly read?: (statePath: string) => Promise<BridgeStateRead>;
98
+ readonly pidAlive?: (pid: number) => boolean;
99
+ readonly log?: (message: string) => void;
100
+ /** Removes this publisher's own record after a write under the lock failed (fail closed). */
101
+ readonly invalidate?: (statePath: string) => Promise<void>;
102
+ /** Records that this publisher could not publish (fail closed without touching the shared record). */
103
+ readonly markUnpublished?: (statePath: string, marker: UnpublishedMarker) => Promise<void>;
104
+ readonly lock?: BridgeStateLockOptions;
105
+ }
106
+ /**
107
+ * Keeps the state file current while connect runs: on every in-flight change
108
+ * (coalesced) and on a heartbeat timer. Each publish reads the current record and
109
+ * writes the next one under the state file's lock. A failed publish removes the
110
+ * record, so readers report unknown instead of trusting the last one; failures are
111
+ * logged once per streak and never reach the bridge.
112
+ */
113
+ export declare class BridgeStatePublisher {
114
+ private readonly statePath;
115
+ private readonly identity;
116
+ private readonly source;
117
+ private readonly options;
118
+ private readonly intervalMs;
119
+ private readonly now;
120
+ private readonly startedAt;
121
+ private readonly publisherId;
122
+ private timer;
123
+ private writing;
124
+ private dirty;
125
+ private stopped;
126
+ private failing;
127
+ private conflict;
128
+ private unpublishedSince;
129
+ private sweptExitedMarkers;
130
+ constructor(statePath: string, identity: BridgeStateIdentity, source: BridgeStateSource, options?: BridgeStatePublisherOptions);
131
+ start(): Promise<void>;
132
+ /** Publishes now, or right after the write in progress. */
133
+ publish(): Promise<void>;
134
+ /** Stops the heartbeat and records a clean stop, only over this publisher's own record. */
135
+ stop(): Promise<void>;
136
+ snapshot(state?: BridgeStateFile["state"]): BridgeStateFile;
137
+ private get pid();
138
+ private read;
139
+ private writeLoop;
140
+ /**
141
+ * Reads the record and writes the next one while holding the lock, so no other publisher
142
+ * writes in between: a second bridge always sees the first one's record (and publishes the
143
+ * conflict), and a stopping bridge's "stopped" record never lands over a newer bridge's.
144
+ */
145
+ private publishRecord;
146
+ /**
147
+ * The last record may say idle while new work starts. This publisher's marker makes readers
148
+ * report unknown; while it holds the lock it also removes its own record, never another's.
149
+ */
150
+ private failClosed;
151
+ private clearUnpublished;
152
+ private noteFailure;
153
+ private ownsRecord;
154
+ /**
155
+ * Two `connect` processes on one config would overwrite each other's record, and the
156
+ * last writer could be the idle one. Each remembers the other live, fresh writer it saw
157
+ * until that writer is gone or would read as stale, and publishes it as a conflict.
158
+ */
159
+ private noteConflict;
160
+ }
161
+ export declare function formatAge(ms: number): string;