@loucompanion/forge-bridge 0.1.4-dev.6b2148ecc60c → 0.1.4-dev.724427ea7be8

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 (163) hide show
  1. package/README.md +87 -1
  2. package/dist/bridge/bridge-chat-provider-command.d.ts +5 -2
  3. package/dist/bridge/bridge-chat-provider-command.js +29 -22
  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-state-file.d.ts +161 -0
  7. package/dist/bridge/bridge-state-file.js +376 -0
  8. package/dist/bridge/bridge-state-io.d.ts +11 -0
  9. package/dist/bridge/bridge-state-io.js +50 -0
  10. package/dist/bridge/bridge-state-lock.d.ts +11 -0
  11. package/dist/bridge/bridge-state-lock.js +102 -0
  12. package/dist/bridge/bridge-state-unpublished.d.ts +17 -0
  13. package/dist/bridge/bridge-state-unpublished.js +111 -0
  14. package/dist/bridge/bridge.service.d.ts +16 -12
  15. package/dist/bridge/bridge.service.js +131 -243
  16. package/dist/bridge/bridge.types.d.ts +5 -0
  17. package/dist/bridge/in-flight-registry.d.ts +62 -0
  18. package/dist/bridge/in-flight-registry.js +207 -0
  19. package/dist/bridge/readiness-result-outbox.d.ts +5 -1
  20. package/dist/bridge/readiness-result-outbox.js +20 -0
  21. package/dist/bridge/sandbox-resource-accounting.d.ts +16 -0
  22. package/dist/bridge/sandbox-resource-accounting.js +150 -0
  23. package/dist/cleanup/cleanup-wip.d.ts +12 -0
  24. package/dist/cleanup/cleanup-wip.js +66 -0
  25. package/dist/cleanup/cleanup.service.d.ts +11 -1
  26. package/dist/cleanup/cleanup.service.js +80 -62
  27. package/dist/cleanup/cleanup.types.d.ts +2 -0
  28. package/dist/cleanup/host-runtime-ledger.d.ts +2 -0
  29. package/dist/cleanup/host-runtime-ledger.js +30 -9
  30. package/dist/cli/cli.help.js +56 -12
  31. package/dist/cli/cli.service.d.ts +3 -10
  32. package/dist/cli/cli.service.js +10 -171
  33. package/dist/cli/idle-status.d.ts +84 -0
  34. package/dist/cli/idle-status.js +181 -0
  35. package/dist/cli/local-config.d.ts +2 -0
  36. package/dist/cli/local-config.js +7 -1
  37. package/dist/cli/provider-cli-detection.d.ts +10 -0
  38. package/dist/cli/provider-cli-detection.js +160 -0
  39. package/dist/runtime/aspnet-runtime-prebuild.d.ts +20 -0
  40. package/dist/runtime/aspnet-runtime-prebuild.js +104 -26
  41. package/dist/runtime/attempt-database-broker.d.ts +1 -1
  42. package/dist/runtime/attempt-node-runtime-launcher.js +9 -0
  43. package/dist/runtime/attempt-process-supervisor.d.ts +2 -0
  44. package/dist/runtime/attempt-process-supervisor.js +12 -6
  45. package/dist/runtime/docker-engine-probe.d.ts +5 -0
  46. package/dist/runtime/docker-engine-probe.js +7 -0
  47. package/dist/runtime/dotnet-build-outputs.d.ts +107 -0
  48. package/dist/runtime/dotnet-build-outputs.js +402 -0
  49. package/dist/runtime/ephemeral-test-postgres-grant.d.ts +37 -0
  50. package/dist/runtime/ephemeral-test-postgres-grant.js +85 -0
  51. package/dist/runtime/ephemeral-test-postgres.d.ts +57 -0
  52. package/dist/runtime/ephemeral-test-postgres.js +303 -0
  53. package/dist/runtime/host-load-governor.d.ts +2 -0
  54. package/dist/runtime/host-load-ledger-lock.js +6 -4
  55. package/dist/runtime/host-load-runtime-settings.js +4 -2
  56. package/dist/runtime/host-load-sampler.d.ts +8 -1
  57. package/dist/runtime/host-load-sampler.js +14 -7
  58. package/dist/runtime/host-runtime-contract.d.ts +12 -0
  59. package/dist/runtime/host-runtime-contract.js +29 -1
  60. package/dist/runtime/host-runtime-lease.d.ts +2 -1
  61. package/dist/runtime/host-runtime-lease.js +30 -153
  62. package/dist/runtime/host-runtime-ledger-recovery.d.ts +20 -0
  63. package/dist/runtime/host-runtime-ledger-recovery.js +134 -0
  64. package/dist/runtime/managed-command-teardown.js +5 -16
  65. package/dist/runtime/native-test-postgres-fallback.d.ts +51 -7
  66. package/dist/runtime/native-test-postgres-fallback.js +60 -8
  67. package/dist/runtime/runner-settings.d.ts +4 -0
  68. package/dist/runtime/runner-settings.js +22 -0
  69. package/dist/runtime/supervised-runtime-build-guard.d.ts +45 -0
  70. package/dist/runtime/supervised-runtime-build-guard.js +112 -0
  71. package/dist/sandbox/host-capacity-broker.d.ts +3 -1
  72. package/dist/sandbox/host-capacity-broker.js +4 -2
  73. package/dist/sandbox/managed-branch.d.ts +13 -0
  74. package/dist/sandbox/managed-branch.js +90 -0
  75. package/dist/sandbox/provider-auth/codex.js +11 -11
  76. package/dist/sandbox/runtime.js +2 -6
  77. package/dist/session/architect-waits.d.ts +2 -0
  78. package/dist/session/architect-waits.js +138 -0
  79. package/dist/session/managed-attempt-tools.d.ts +0 -7
  80. package/dist/session/managed-attempt-tools.js +50 -82
  81. package/dist/session/managed-build-coordinator.d.ts +16 -0
  82. package/dist/session/managed-build-coordinator.js +10 -0
  83. package/dist/session/managed-build-receipt.d.ts +5 -0
  84. package/dist/session/managed-build-receipt.js +8 -3
  85. package/dist/session/phase-completion.artifacts.js +2 -1
  86. package/dist/session/phase-completion.d.ts +8 -0
  87. package/dist/session/phase-completion.js +1 -0
  88. package/dist/session/phase-completion.mcp-args.d.ts +9 -0
  89. package/dist/session/phase-completion.mcp-args.js +156 -0
  90. package/dist/session/phase-completion.runtime.d.ts +0 -8
  91. package/dist/session/phase-completion.runtime.js +43 -197
  92. package/dist/session/phase-completion.schemas.js +3 -11
  93. package/dist/session/phase-completion.validation.js +3 -1
  94. package/dist/session/pre-publication-native-postgres.d.ts +30 -0
  95. package/dist/session/pre-publication-native-postgres.js +111 -0
  96. package/dist/session/pre-publication-process.js +10 -10
  97. package/dist/session/pre-publication-step-execution.d.ts +2 -1
  98. package/dist/session/pre-publication-step-execution.js +6 -5
  99. package/dist/session/pre-publication-validation.d.ts +7 -3
  100. package/dist/session/pre-publication-validation.js +32 -30
  101. package/dist/session/provider-cli/claude-background-work.d.ts +3 -2
  102. package/dist/session/provider-cli/claude-background-work.js +4 -3
  103. package/dist/session/provider-cli/host-build-lock.d.ts +18 -0
  104. package/dist/session/provider-cli/host-build-lock.js +30 -0
  105. package/dist/session/provider-cli/pre-publication-repair.d.ts +16 -0
  106. package/dist/session/provider-cli/pre-publication-repair.js +33 -0
  107. package/dist/session/provider-cli/provider-cli.child-environment.js +4 -2
  108. package/dist/session/provider-cli/provider-cli.process.d.ts +2 -14
  109. package/dist/session/provider-cli/provider-cli.process.js +4 -94
  110. package/dist/session/provider-cli/provider-cli.prompts.d.ts +3 -0
  111. package/dist/session/provider-cli/provider-cli.prompts.js +27 -27
  112. package/dist/session/provider-cli/provider-cli.runtime.d.ts +8 -0
  113. package/dist/session/provider-cli/provider-cli.runtime.js +23 -2
  114. package/dist/session/provider-cli/provider-cli.service.d.ts +4 -1
  115. package/dist/session/provider-cli/provider-cli.service.js +27 -43
  116. package/dist/session/provider-cli/provider-cli.windows-launch.d.ts +23 -0
  117. package/dist/session/provider-cli/provider-cli.windows-launch.js +131 -0
  118. package/dist/session/provider-cli/provider-user-config-isolation.d.ts +69 -0
  119. package/dist/session/provider-cli/provider-user-config-isolation.js +164 -0
  120. package/dist/session/qa-sidecar-validation.d.ts +6 -0
  121. package/dist/session/qa-sidecar-validation.js +28 -0
  122. package/dist/session/sandbox-host-capacity-gate.d.ts +22 -1
  123. package/dist/session/sandbox-host-capacity-gate.js +34 -15
  124. package/dist/session/session-redaction.js +31 -181
  125. package/dist/session/session.service.d.ts +2 -0
  126. package/dist/session/session.service.js +69 -64
  127. package/dist/session/session.types.js +1 -1
  128. package/dist/session/sidecar-json-shape.d.ts +31 -0
  129. package/dist/session/sidecar-json-shape.js +217 -0
  130. package/dist/shared/fs/file-identity.d.ts +10 -0
  131. package/dist/shared/fs/file-identity.js +15 -0
  132. package/dist/shared/fs/replace-file.d.ts +7 -0
  133. package/dist/shared/fs/replace-file.js +33 -0
  134. package/dist/shared/process/host-process-recovery.d.ts +14 -3
  135. package/dist/shared/process/host-process-recovery.js +23 -3
  136. package/dist/shared/process/host-process-supervisor.d.ts +13 -1
  137. package/dist/shared/process/host-process-supervisor.js +66 -14
  138. package/dist/shared/provider-capabilities.js +9 -1
  139. package/dist/version.d.ts +1 -1
  140. package/dist/version.js +1 -1
  141. package/dist/worktree/orphan-relink.d.ts +19 -0
  142. package/dist/worktree/orphan-relink.js +106 -0
  143. package/dist/worktree/wip-git.d.ts +33 -0
  144. package/dist/worktree/wip-git.js +122 -0
  145. package/dist/worktree/wip-refs.d.ts +62 -0
  146. package/dist/worktree/wip-refs.js +119 -0
  147. package/dist/worktree/wip-restore.d.ts +38 -0
  148. package/dist/worktree/wip-restore.js +190 -0
  149. package/dist/worktree/wip-snapshot.d.ts +50 -0
  150. package/dist/worktree/wip-snapshot.js +268 -0
  151. package/dist/worktree/worktree-inputs.d.ts +8 -0
  152. package/dist/worktree/worktree-inputs.js +134 -0
  153. package/dist/worktree/worktree-origin-sync.d.ts +34 -0
  154. package/dist/worktree/worktree-origin-sync.js +127 -0
  155. package/dist/worktree/worktree-wip-events.d.ts +18 -0
  156. package/dist/worktree/worktree-wip-events.js +98 -0
  157. package/dist/worktree/worktree-wip.d.ts +50 -0
  158. package/dist/worktree/worktree-wip.js +185 -0
  159. package/dist/worktree/worktree.base.d.ts +7 -1
  160. package/dist/worktree/worktree.service.d.ts +27 -5
  161. package/dist/worktree/worktree.service.js +110 -181
  162. package/dist/worktree/worktree.types.d.ts +31 -0
  163. package/package.json +1 -1
@@ -0,0 +1,207 @@
1
+ // The connected bridge's in-flight work, so a host can tell whether restarting the
2
+ // bridge would kill something (owner, 2026-11-19: a restart killed a develop session
3
+ // that was still in host-runtime preparation, with no agent process yet).
4
+ //
5
+ // Two kinds of entries make up the snapshot:
6
+ // - tracked entries: every Offer, Start, Dispatch, chat turn and readiness probe
7
+ // handler from the moment Forge hands it over until the handler returns, with
8
+ // the phase updated from the runner events the dispatch emits;
9
+ // - source entries: work the bridge still holds after a handler returned or before
10
+ // one is tracked, read from the bridge's own ledgers (accepted offers waiting for
11
+ // Start, active sessions, readiness probes). A source entry that names the same
12
+ // work as a tracked one is dropped.
13
+ // Entries leave the snapshot when the handler settles (success, failure or cancel)
14
+ // or when the ledger releases the work, so nothing has to remember to remove them.
15
+ const idKeys = ["dispatchAttemptId", "leaseId", "sessionId", "cycleRunId", "workItemId", "turnId", "requestId"];
16
+ const identityKeys = ["dispatchAttemptId", "leaseId", "turnId", "requestId"];
17
+ // Ids are written to a local file and logs: keep only plain identifiers.
18
+ const safeId = /^[A-Za-z0-9._:-]{1,200}$/u;
19
+ const safePhase = /^[A-Za-z0-9._:-]{1,120}$/u;
20
+ export class BridgeInFlightRegistry {
21
+ now;
22
+ tracked = new Map();
23
+ sources = [];
24
+ listeners = new Set();
25
+ nextKey = 1;
26
+ constructor(now = () => new Date()) {
27
+ this.now = now;
28
+ }
29
+ /** Starts tracking one piece of work; returns the key that ends it. */
30
+ begin(kind, ids, phase = `${kind}_received`) {
31
+ const key = this.nextKey++;
32
+ const at = this.now().toISOString();
33
+ this.tracked.set(key, { kind, ids, phase: cleanPhase(phase), since: at, phaseSince: at });
34
+ this.changed();
35
+ return key;
36
+ }
37
+ end(key) {
38
+ if (this.tracked.delete(key))
39
+ this.changed();
40
+ }
41
+ /** Moves every tracked entry for this lease to a new phase. */
42
+ notePhase(leaseId, phase) {
43
+ if (!phase || !safePhase.test(phase))
44
+ return;
45
+ let changed = false;
46
+ for (const entry of this.tracked.values()) {
47
+ if (entry.ids.leaseId !== leaseId || entry.phase === phase)
48
+ continue;
49
+ entry.phase = phase;
50
+ entry.phaseSince = this.now().toISOString();
51
+ changed = true;
52
+ }
53
+ if (changed)
54
+ this.changed();
55
+ }
56
+ /** Tracks a hub handler for as long as it runs, whether it resolves or throws. */
57
+ async track(kind, raw, run) {
58
+ const key = this.begin(kind, inFlightIdsFrom(raw));
59
+ try {
60
+ return await run();
61
+ }
62
+ finally {
63
+ this.end(key);
64
+ }
65
+ }
66
+ addSource(source) {
67
+ this.sources.push(source);
68
+ }
69
+ onChange(listener) {
70
+ this.listeners.add(listener);
71
+ return () => this.listeners.delete(listener);
72
+ }
73
+ snapshot() {
74
+ const tracked = [...this.tracked.values()].map(entry => ({ ...entry, ids: { ...entry.ids } }));
75
+ const fromSources = [];
76
+ for (const source of this.sources) {
77
+ for (const entry of source()) {
78
+ if (![...tracked, ...fromSources].some(other => sameWork(entry.ids, other.ids)))
79
+ fromSources.push(entry);
80
+ }
81
+ }
82
+ return [...tracked, ...fromSources];
83
+ }
84
+ get idle() {
85
+ return this.snapshot().length === 0;
86
+ }
87
+ changed() {
88
+ for (const listener of this.listeners) {
89
+ try {
90
+ listener();
91
+ }
92
+ catch {
93
+ // A listener (the state file publisher) must never break the bridge.
94
+ }
95
+ }
96
+ }
97
+ }
98
+ /** Reads the ids of a hub payload: an Offer/Start envelope, a dispatch packet, a chat turn or a readiness probe. */
99
+ export function inFlightIdsFrom(raw) {
100
+ const root = asRecord(raw);
101
+ if (!root)
102
+ return {};
103
+ const packet = asRecord(field(root, "dispatch")) ?? root;
104
+ const values = {
105
+ dispatchAttemptId: firstId(root, asRecord(field(packet, "sandbox")), "dispatchAttemptId"),
106
+ leaseId: firstId(root, null, "leaseId") ?? firstId(asRecord(field(packet, "lease")), null, "id"),
107
+ sessionId: firstId(asRecord(field(packet, "session")), null, "id"),
108
+ cycleRunId: firstId(asRecord(field(packet, "cycleRun")), null, "id"),
109
+ workItemId: firstId(asRecord(field(packet, "workItem")), null, "id"),
110
+ turnId: firstId(root, null, "turnId"),
111
+ requestId: firstId(root, null, "requestId"),
112
+ };
113
+ return Object.fromEntries(idKeys.flatMap(key => values[key] ? [[key, values[key]]] : []));
114
+ }
115
+ /** Accepted offers whose Start has not arrived yet. A claimed one is the Start handler's. */
116
+ export function reservationInFlightEntries(reservations, now = Date.now()) {
117
+ return [...reservations].flatMap(([dispatchAttemptId, reservation]) => {
118
+ if (Date.parse(reservation.reservedUntil) <= now)
119
+ return [];
120
+ return [{
121
+ kind: "reservation",
122
+ ids: cleanIds({ dispatchAttemptId, leaseId: reservation.leaseId }),
123
+ phase: reservation.startClaim ? "start_claimed" : "awaiting_start",
124
+ since: null,
125
+ phaseSince: null,
126
+ }];
127
+ });
128
+ }
129
+ export function sessionInFlightEntries(sessions) {
130
+ return [...sessions].map(([leaseId, session]) => ({
131
+ kind: session.kind === "chat" ? "chat_turn" : "session",
132
+ ids: cleanIds({ leaseId, dispatchAttemptId: session.dispatchAttemptId ?? undefined, turnId: session.turnId }),
133
+ phase: "active",
134
+ since: null,
135
+ phaseSince: null,
136
+ }));
137
+ }
138
+ export function readinessInFlightEntries(probes) {
139
+ return [...probes.keys()].map(requestId => ({
140
+ kind: "readiness_probe",
141
+ ids: cleanIds({ requestId }),
142
+ phase: "probing",
143
+ since: null,
144
+ phaseSince: null,
145
+ }));
146
+ }
147
+ const inFlightKinds = new Set([
148
+ "offer", "start", "dispatch", "chat_turn", "readiness_probe", "reservation", "session", "unknown",
149
+ ]);
150
+ /** Whether a value read back from the state file is a complete in-flight entry. */
151
+ export function isInFlightEntry(value) {
152
+ const entry = asRecord(value);
153
+ const ids = entry ? asRecord(entry.ids) : null;
154
+ return entry !== null && ids !== null
155
+ && typeof entry.kind === "string" && inFlightKinds.has(entry.kind)
156
+ && Object.values(ids).every(id => typeof id === "string")
157
+ && typeof entry.phase === "string" && entry.phase.length > 0
158
+ && isNullableString(entry.since) && isNullableString(entry.phaseSince);
159
+ }
160
+ function isNullableString(value) {
161
+ return value === null || typeof value === "string";
162
+ }
163
+ /** A server-supplied label (role, phase) made safe for one log line: plain identifier or "unknown". */
164
+ export function safeLogLabel(value) {
165
+ return typeof value === "string" && safePhase.test(value) ? value : "unknown";
166
+ }
167
+ /** "attempt=…, lease=…, session=…, cycle=…" for log lines and status output. */
168
+ export function describeInFlightIds(ids) {
169
+ const labels = {
170
+ dispatchAttemptId: "attempt",
171
+ leaseId: "lease",
172
+ sessionId: "session",
173
+ cycleRunId: "cycle",
174
+ workItemId: "work item",
175
+ turnId: "turn",
176
+ requestId: "request",
177
+ };
178
+ const parts = idKeys.flatMap(key => ids[key] ? [`${labels[key]} ${ids[key]}`] : []);
179
+ return parts.length > 0 ? parts.join(", ") : "no ids";
180
+ }
181
+ function sameWork(left, right) {
182
+ return identityKeys.some(key => left[key] !== undefined && left[key] === right[key]);
183
+ }
184
+ function cleanIds(values) {
185
+ return Object.fromEntries(idKeys.flatMap(key => {
186
+ const value = values[key];
187
+ return typeof value === "string" && safeId.test(value) ? [[key, value]] : [];
188
+ }));
189
+ }
190
+ function cleanPhase(phase) {
191
+ return safePhase.test(phase) ? phase : "unknown";
192
+ }
193
+ function firstId(primary, fallback, key) {
194
+ for (const source of [primary, fallback]) {
195
+ const value = source ? field(source, key) : undefined;
196
+ if (typeof value === "string" && safeId.test(value))
197
+ return value;
198
+ }
199
+ return null;
200
+ }
201
+ // Hub payloads arrive camelCase; older servers sent PascalCase.
202
+ function field(source, camelKey) {
203
+ return source[camelKey] ?? source[camelKey.charAt(0).toUpperCase() + camelKey.slice(1)];
204
+ }
205
+ function asRecord(value) {
206
+ return value && typeof value === "object" && !Array.isArray(value) ? value : null;
207
+ }
@@ -1,4 +1,4 @@
1
- import type { BridgeRuntimeReadinessResult } from "./bridge.types.js";
1
+ import type { BridgeRuntimeReadinessRequest, BridgeRuntimeReadinessResult } from "./bridge.types.js";
2
2
  export interface DurableReadinessResult {
3
3
  readonly schemaVersion: 1;
4
4
  readonly expiresAt: string;
@@ -19,3 +19,7 @@ export declare class FileReadinessResultOutbox implements ReadinessResultOutbox
19
19
  acknowledge(requestId: string): Promise<void>;
20
20
  private operate;
21
21
  }
22
+ /** A failed result Forge retries later (`host_runtime_probe_deferred`), for a probe the bridge will not run now. */
23
+ export declare function deferredReadinessResult(request: BridgeRuntimeReadinessRequest, runnerInstanceId: string, reasonMessage?: string): BridgeRuntimeReadinessResult;
24
+ /** The deferral reason a probe was aborted with, or null when it was aborted for another reason. */
25
+ export declare function readinessDeferralReason(signal: AbortSignal): string | null;
@@ -52,3 +52,23 @@ function recordName(requestId) {
52
52
  throw new Error("runtime_readiness_result_invalid: request id must be a UUID.");
53
53
  return `${value}.json`;
54
54
  }
55
+ /** A failed result Forge retries later (`host_runtime_probe_deferred`), for a probe the bridge will not run now. */
56
+ export function deferredReadinessResult(request, runnerInstanceId, reasonMessage = "Foreground agent work is active; Forge deferred background runtime readiness so it cannot consume the agent's host capacity.") {
57
+ return {
58
+ schemaVersion: 1,
59
+ requestId: request.requestId,
60
+ fencingToken: request.fencingToken,
61
+ runnerInstanceId,
62
+ status: "failed",
63
+ reasonCode: "host_runtime_probe_deferred",
64
+ reasonMessage,
65
+ checkedAt: new Date().toISOString(),
66
+ };
67
+ }
68
+ /** The deferral reason a probe was aborted with, or null when it was aborted for another reason. */
69
+ export function readinessDeferralReason(signal) {
70
+ if (!signal.aborted)
71
+ return null;
72
+ const reason = signal.reason instanceof Error ? signal.reason.message : String(signal.reason);
73
+ return reason.startsWith("host_runtime_probe_deferred:") ? reason : null;
74
+ }
@@ -0,0 +1,16 @@
1
+ import type { SandboxPreflightResult } from "../sandbox/sandbox.types.js";
2
+ import type { DispatchSandboxResourceRequest, RunOnceDispatchPacket } from "../session/session.types.js";
3
+ import type { BridgeServiceConfig } from "./bridge.types.js";
4
+ export interface ResolvedSandboxResourceProfile {
5
+ readonly resources: DispatchSandboxResourceRequest;
6
+ readonly sandboxConfigCommitSha: string;
7
+ }
8
+ export type SandboxResourceVector = DispatchSandboxResourceRequest;
9
+ export declare function canReserveSandboxResources(used: SandboxResourceVector, requested: SandboxResourceVector, capacity: SandboxResourceVector): boolean;
10
+ export declare function sandboxMemoryCommitmentCapacity(preflight: Pick<SandboxPreflightResult, "totalMemoryBytes" | "availableMemoryBytes" | "hostReserveBytes">, activeMemoryBytes: number): number;
11
+ export declare function sandboxCapacityFailureMessage(used: SandboxResourceVector, requested: SandboxResourceVector, capacity: SandboxResourceVector, preflight: SandboxPreflightResult | null, config: BridgeServiceConfig): string;
12
+ export declare function sumSandboxResources(resources: readonly SandboxResourceVector[]): SandboxResourceVector;
13
+ export declare function zeroSandboxResources(): SandboxResourceVector;
14
+ export declare function defaultSandboxResources(): SandboxResourceVector;
15
+ export declare function resolveDynamicSandboxResources(requested: DispatchSandboxResourceRequest, serviceCount: number, networkMode: "offline" | "public_allowlist" | "open_public", baseRuntimeOverheadBytes?: number): DispatchSandboxResourceRequest;
16
+ export declare function resolveSandboxResourcesFromRepo(dispatch: RunOnceDispatchPacket, baseRuntimeOverheadBytes?: number): Promise<ResolvedSandboxResourceProfile>;
@@ -0,0 +1,150 @@
1
+ import { formatBytes } from "../shared/format/format-bytes.js";
2
+ import { validateSandboxContract } from "../sandbox/contract.js";
3
+ import { runSandboxProcess } from "../sandbox/process.js";
4
+ import { selectSandboxConfigRefs } from "../sandbox/runtime.js";
5
+ import { estimateWorkspaceBytesFromRepo } from "../runtime/workspace-resource-estimator.js";
6
+ export function canReserveSandboxResources(used, requested, capacity) {
7
+ return used.sandboxSlots + requested.sandboxSlots <= capacity.sandboxSlots
8
+ && used.cpuMillis + requested.cpuMillis <= capacity.cpuMillis
9
+ && used.memoryBytes + requested.memoryBytes <= capacity.memoryBytes
10
+ && used.workspaceBytes + requested.workspaceBytes <= capacity.workspaceBytes
11
+ && used.pids + requested.pids <= capacity.pids
12
+ && used.buildSlots + requested.buildSlots <= capacity.buildSlots;
13
+ }
14
+ export function sandboxMemoryCommitmentCapacity(preflight, activeMemoryBytes) {
15
+ const ambientCapacity = preflight.availableMemoryBytes
16
+ - preflight.hostReserveBytes
17
+ + activeMemoryBytes;
18
+ const commitmentCapacity = preflight.totalMemoryBytes
19
+ - preflight.hostReserveBytes;
20
+ return Math.max(0, Math.min(ambientCapacity, commitmentCapacity));
21
+ }
22
+ export function sandboxCapacityFailureMessage(used, requested, capacity, preflight, config) {
23
+ const availableSlots = Math.max(0, capacity.sandboxSlots - used.sandboxSlots);
24
+ if (requested.sandboxSlots > availableSlots) {
25
+ return `Sandbox slot capacity is insufficient: requested ${requested.sandboxSlots}, available ${availableSlots}, ${used.sandboxSlots} already reserved.`;
26
+ }
27
+ const availableMemoryBytes = Math.max(0, capacity.memoryBytes - used.memoryBytes);
28
+ if (requested.memoryBytes > availableMemoryBytes) {
29
+ return [
30
+ `Sandbox memory capacity is insufficient: requested ${formatBytes(requested.memoryBytes)} total`,
31
+ `(worker ${formatBytes(requested.workerMemoryLimitBytes)}, services ${formatBytes(requested.serviceMemoryLimitBytes)}, runtime overhead ${formatBytes(requested.runtimeOverheadBytes)}),`,
32
+ `but ${formatBytes(availableMemoryBytes)} is available for admission.`,
33
+ `Docker reports ${formatBytes(preflight?.availableMemoryBytes ?? 0)} available of ${formatBytes(preflight?.totalMemoryBytes ?? 0)};`,
34
+ `Forge reserves ${formatBytes(preflight?.hostReserveBytes ?? config.sandboxHostMemoryReserveBytes ?? 0)} for the host and tracks ${formatBytes(used.memoryBytes)} in active or reserved attempts.`,
35
+ ].join(" ");
36
+ }
37
+ const availableCpuMillis = Math.max(0, capacity.cpuMillis - used.cpuMillis);
38
+ if (requested.cpuMillis > availableCpuMillis) {
39
+ return `Sandbox CPU capacity is insufficient: requested ${requested.cpuMillis} millis, available ${availableCpuMillis} millis, ${used.cpuMillis} millis already reserved.`;
40
+ }
41
+ const availableWorkspaceBytes = Math.max(0, capacity.workspaceBytes - used.workspaceBytes);
42
+ if (requested.workspaceBytes > availableWorkspaceBytes) {
43
+ return `Sandbox workspace capacity is insufficient: requested ${formatBytes(requested.workspaceBytes)}, available ${formatBytes(availableWorkspaceBytes)}, ${formatBytes(used.workspaceBytes)} already reserved.`;
44
+ }
45
+ const availablePids = Math.max(0, capacity.pids - used.pids);
46
+ if (requested.pids > availablePids) {
47
+ return `Sandbox PID capacity is insufficient: requested ${requested.pids}, available ${availablePids}, ${used.pids} already reserved.`;
48
+ }
49
+ const availableBuildSlots = Math.max(0, capacity.buildSlots - used.buildSlots);
50
+ return `Sandbox build capacity is insufficient: requested ${requested.buildSlots}, available ${availableBuildSlots}, ${used.buildSlots} already reserved.`;
51
+ }
52
+ export function sumSandboxResources(resources) {
53
+ return resources.reduce((total, resource) => ({
54
+ sandboxSlots: total.sandboxSlots + resource.sandboxSlots,
55
+ cpuMillis: total.cpuMillis + resource.cpuMillis,
56
+ workerMemoryLimitBytes: total.workerMemoryLimitBytes + resource.workerMemoryLimitBytes,
57
+ serviceMemoryLimitBytes: total.serviceMemoryLimitBytes + resource.serviceMemoryLimitBytes,
58
+ runtimeOverheadBytes: total.runtimeOverheadBytes + resource.runtimeOverheadBytes,
59
+ memoryBytes: total.memoryBytes + resource.memoryBytes,
60
+ workspaceBytes: total.workspaceBytes + resource.workspaceBytes,
61
+ pids: total.pids + resource.pids,
62
+ buildSlots: total.buildSlots + resource.buildSlots
63
+ }), zeroSandboxResources());
64
+ }
65
+ export function zeroSandboxResources() {
66
+ return {
67
+ sandboxSlots: 0,
68
+ cpuMillis: 0,
69
+ workerMemoryLimitBytes: 0,
70
+ serviceMemoryLimitBytes: 0,
71
+ runtimeOverheadBytes: 0,
72
+ memoryBytes: 0,
73
+ workspaceBytes: 0,
74
+ pids: 0,
75
+ buildSlots: 0,
76
+ };
77
+ }
78
+ export function defaultSandboxResources() {
79
+ return {
80
+ sandboxSlots: 1,
81
+ cpuMillis: 2000,
82
+ workerMemoryLimitBytes: 2 * 1024 ** 3,
83
+ serviceMemoryLimitBytes: 0,
84
+ runtimeOverheadBytes: 128 * 1024 ** 2,
85
+ memoryBytes: 2 * 1024 ** 3 + 128 * 1024 ** 2,
86
+ workspaceBytes: 10 * 1024 ** 3,
87
+ pids: 512,
88
+ buildSlots: 0
89
+ };
90
+ }
91
+ export function resolveDynamicSandboxResources(requested, serviceCount, networkMode, baseRuntimeOverheadBytes = 128 * 1024 ** 2) {
92
+ const serviceMemoryLimitBytes = Math.max(0, serviceCount) * 1024 ** 3;
93
+ const runtimeOverheadBytes = Math.max(128 * 1024 ** 2, baseRuntimeOverheadBytes)
94
+ + (networkMode === "public_allowlist" ? 256 * 1024 ** 2 : 0);
95
+ return {
96
+ ...requested,
97
+ serviceMemoryLimitBytes,
98
+ runtimeOverheadBytes,
99
+ memoryBytes: requested.workerMemoryLimitBytes + serviceMemoryLimitBytes + runtimeOverheadBytes,
100
+ };
101
+ }
102
+ export async function resolveSandboxResourcesFromRepo(dispatch, baseRuntimeOverheadBytes = 128 * 1024 ** 2) {
103
+ const repoPath = dispatch.repo.serverLocalPath;
104
+ const sandbox = dispatch.sandbox;
105
+ if (!repoPath || !sandbox) {
106
+ throw new Error("Sandbox admission needs a mapped repository.");
107
+ }
108
+ const selection = selectSandboxConfigRefs(sandbox.executionPolicy, sandbox.sandboxConfigCommitSha, dispatch.repo.defaultBranch);
109
+ const configCommitSha = await resolveFirstGitCommit(repoPath, selection.refs);
110
+ if (!configCommitSha) {
111
+ throw new Error("Sandbox admission could not resolve the immutable sandbox config commit.");
112
+ }
113
+ const contractResult = await runSandboxProcess({
114
+ command: "git",
115
+ args: ["-C", repoPath, "show", `${configCommitSha}:.forge/forge.sandbox.yml`],
116
+ timeoutMs: 30_000,
117
+ maxOutputBytes: 1024 * 1024,
118
+ });
119
+ if (contractResult.exitCode !== 0) {
120
+ throw new Error("The approved immutable sandbox contract is unavailable in the mapped repository.");
121
+ }
122
+ const contract = validateSandboxContract(contractResult.stdout);
123
+ const workspaceBytes = await estimateWorkspaceBytesFromRepo(repoPath, {
124
+ role: dispatch.execution.role,
125
+ serviceCount: contract.contract.services.length,
126
+ browser: contract.contract.browser,
127
+ });
128
+ return {
129
+ resources: resolveDynamicSandboxResources({
130
+ ...sandbox.requestedResources,
131
+ workspaceBytes: Math.max(sandbox.requestedResources.workspaceBytes, workspaceBytes),
132
+ }, contract.contract.services.length, sandbox.networkPolicy.mode, baseRuntimeOverheadBytes),
133
+ sandboxConfigCommitSha: configCommitSha,
134
+ };
135
+ }
136
+ async function resolveFirstGitCommit(repoPath, refs) {
137
+ for (const ref of refs) {
138
+ const result = await runSandboxProcess({
139
+ command: "git",
140
+ args: ["-C", repoPath, "rev-parse", "--verify", `${ref}^{commit}`],
141
+ timeoutMs: 30_000,
142
+ maxOutputBytes: 1024 * 1024,
143
+ });
144
+ const commitSha = result.stdout.trim().toLowerCase();
145
+ if (result.exitCode === 0 && /^(?:[0-9a-f]{40}|[0-9a-f]{64})$/u.test(commitSha)) {
146
+ return commitSha;
147
+ }
148
+ }
149
+ return null;
150
+ }
@@ -0,0 +1,12 @@
1
+ import { GitClient } from "../shared/git/git.js";
2
+ export type CandidateWipOutcome = {
3
+ readonly status: "exempt" | "clean";
4
+ } | {
5
+ readonly status: "saved";
6
+ readonly ref: string;
7
+ } | {
8
+ readonly status: "failed";
9
+ readonly reason: string;
10
+ };
11
+ /** Saves a stale candidate's uncommitted work. Never throws: a failure means "keep the folder". */
12
+ export declare function saveStaleWorktreeWork(git: GitClient, repoPath: string, worktreeRoot: string, candidate: string): Promise<CandidateWipOutcome>;
@@ -0,0 +1,66 @@
1
+ import path from "node:path";
2
+ import { preserveWorktreeWip } from "../worktree/wip-snapshot.js";
3
+ import { isRuntimeReadinessName } from "./forge-owned-paths.js";
4
+ import { isForgeManagedWorkBranch } from "./managed-branch-sweep.js";
5
+ // Cleanup removes stale Forge worktrees: folders whose Git registration is gone (or prunable) and
6
+ // that no lease owns. Such a folder can still hold a session's uncommitted work (the #558 loss:
7
+ // six staged review fixes in a story worktree that cleanup deleted). Before one is removed, its
8
+ // work is saved to the branch's WIP ref; when that fails, the folder is kept and the reason given.
9
+ const releaseSuffix = /\.forge-release-[0-9a-f-]{36}$/u;
10
+ /** Saves a stale candidate's uncommitted work. Never throws: a failure means "keep the folder". */
11
+ export async function saveStaleWorktreeWork(git, repoPath, worktreeRoot, candidate) {
12
+ const branchName = candidateBranch(worktreeRoot, candidate);
13
+ // A readiness probe never runs an agent: there is no work of anyone's in it.
14
+ if (isRuntimeReadinessName(branchName))
15
+ return { status: "exempt" };
16
+ try {
17
+ const result = await snapshotCandidate(git, repoPath, candidate, branchName);
18
+ return result.status === "clean" ? { status: "clean" } : { status: "saved", ref: result.ref };
19
+ }
20
+ catch (error) {
21
+ return { status: "failed", reason: error instanceof Error ? error.message : String(error) };
22
+ }
23
+ }
24
+ async function snapshotCandidate(git, repoPath, candidate, branchName) {
25
+ const restorable = isForgeManagedWorkBranch(branchName) && /^(?:story|task|bug)\//u.test(branchName);
26
+ // A checkout Git still recognizes (a prunable registration) keeps its own HEAD, index and merge state.
27
+ if (await isOwnGitCheckout(git, candidate)) {
28
+ return await preserveWorktreeWip({
29
+ worktreePath: candidate, branchName, reason: "pre_cleanup", autoRestore: restorable,
30
+ });
31
+ }
32
+ // Otherwise only the files are left; compare them with the branch the folder was created for:
33
+ // its local branch, else its branch on origin. Either way the snapshot is based on the branch's
34
+ // own commit, so a later pass can apply it (restore still requires that exact HEAD). Compared
35
+ // with the repository's HEAD instead, it is saved for inspection only.
36
+ const branchRef = await existingRef(git, repoPath, `refs/heads/${branchName}`)
37
+ ?? await existingRef(git, repoPath, `refs/remotes/origin/${branchName}`);
38
+ const baseRef = branchRef ?? await existingRef(git, repoPath, "HEAD");
39
+ if (!baseRef)
40
+ throw new Error(`no base commit to compare ${candidate} with.`);
41
+ return await preserveWorktreeWip({
42
+ worktreePath: candidate,
43
+ branchName,
44
+ reason: "pre_cleanup",
45
+ autoRestore: restorable && branchRef !== null,
46
+ orphan: { repoPath, baseRef },
47
+ });
48
+ }
49
+ /** The branch Forge created the folder for: its path under the managed root, without a release suffix. */
50
+ function candidateBranch(worktreeRoot, candidate) {
51
+ return path.relative(worktreeRoot, candidate).split(/[\\/]+/u).filter(Boolean).join("/").replace(releaseSuffix, "");
52
+ }
53
+ async function isOwnGitCheckout(git, candidate) {
54
+ const topLevel = await git.run(candidate, ["rev-parse", "--show-toplevel"]).catch(() => "");
55
+ if (!topLevel.trim())
56
+ return false;
57
+ const normalize = (value) => {
58
+ const resolved = path.resolve(value.trim());
59
+ return process.platform === "win32" ? resolved.toLowerCase() : resolved;
60
+ };
61
+ return normalize(topLevel) === normalize(candidate);
62
+ }
63
+ async function existingRef(git, repoPath, ref) {
64
+ const resolved = await git.run(repoPath, ["rev-parse", "-q", "--verify", `${ref}^{commit}`]).catch(() => "");
65
+ return resolved.trim() ? ref : null;
66
+ }
@@ -6,9 +6,19 @@ export declare class ManagedWorktreeCleanupService implements CleanupService {
6
6
  private readonly stateRoot;
7
7
  private readonly git;
8
8
  private readonly coordinator;
9
- constructor(stateRoot?: string, git?: GitClient, coordinator?: WorktreeLifecycleCoordinator);
9
+ /** Where cleanup explains each worktree it kept because its work could not be saved. */
10
+ private readonly warn;
11
+ constructor(stateRoot?: string, git?: GitClient, coordinator?: WorktreeLifecycleCoordinator,
12
+ /** Where cleanup explains each worktree it kept because its work could not be saved. */
13
+ warn?: (message: string) => void);
10
14
  run(request: CleanupRequest): Promise<CleanupResult>;
11
15
  private runLocked;
16
+ /** All mode: removes the managed root itself once nothing in it is active, unowned or unsaved. */
17
+ private removeWholeRoot;
18
+ /** Re-reads registrations and leases: a candidate may have become active since the scan. */
19
+ private isProtectedNow;
20
+ /** Saves each candidate's uncommitted work to a WIP ref; returns how many could not be saved. */
21
+ private saveCandidatesWork;
12
22
  private sweepReadinessBranches;
13
23
  /**
14
24
  * The branch merged work lands on: origin/HEAD when it points at a remote-tracking ref that