@loucompanion/forge-bridge 0.2.1-dev.4f11ffc822f9 → 0.2.1-dev.573a8a5fa582

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 (57) hide show
  1. package/README.md +3 -1
  2. package/dist/bridge/bridge.service.js +1 -9
  3. package/dist/bridge/bridge.types.d.ts +10 -0
  4. package/dist/bridge/bridge.types.js +2 -1
  5. package/dist/bridge/runner-host-capabilities.js +14 -1
  6. package/dist/bridge/windows-bash-resolution.d.ts +31 -0
  7. package/dist/bridge/windows-bash-resolution.js +153 -0
  8. package/dist/cli/cli.service.js +8 -40
  9. package/dist/cli/local-config.d.ts +10 -1
  10. package/dist/cli/local-config.js +32 -1
  11. package/dist/cli/provider-cli-advertising.d.ts +24 -0
  12. package/dist/cli/provider-cli-advertising.js +88 -0
  13. package/dist/runtime/host-load-admission.d.ts +5 -0
  14. package/dist/runtime/host-load-governor-config.d.ts +10 -1
  15. package/dist/runtime/host-load-governor-config.js +4 -1
  16. package/dist/runtime/host-load-governor.d.ts +8 -1
  17. package/dist/runtime/host-load-governor.js +33 -3
  18. package/dist/runtime/host-load-test-slot.js +7 -0
  19. package/dist/runtime/host-runtime-contract.js +6 -4
  20. package/dist/runtime/prepared-runtime-readiness.d.ts +12 -2
  21. package/dist/runtime/prepared-runtime-readiness.js +35 -11
  22. package/dist/sandbox/runtime.js +1 -1
  23. package/dist/session/provider-cli/pre-publication-repair.js +1 -0
  24. package/dist/session/provider-cli/provider-cli.merge-integrity.d.ts +6 -3
  25. package/dist/session/provider-cli/provider-cli.merge-integrity.js +29 -10
  26. package/dist/session/provider-cli/provider-cli.prompts.d.ts +10 -0
  27. package/dist/session/provider-cli/provider-cli.prompts.js +37 -0
  28. package/dist/session/provider-cli/provider-cli.service.js +9 -9
  29. package/dist/session/provider-cli/provider-cli.types.d.ts +7 -2
  30. package/dist/session/sandbox-host-capacity-gate.js +1 -1
  31. package/dist/session/session-host-project.d.ts +22 -0
  32. package/dist/session/session-host-project.js +98 -0
  33. package/dist/session/session.service.js +24 -70
  34. package/dist/session/session.types.d.ts +1 -0
  35. package/dist/session/session.types.js +2 -2
  36. package/dist/shared/provider-capabilities.d.ts +2 -0
  37. package/dist/shared/provider-capabilities.js +9 -0
  38. package/dist/version.d.ts +1 -1
  39. package/dist/version.js +1 -1
  40. package/dist/worktree/wip-git.d.ts +25 -0
  41. package/dist/worktree/wip-git.js +64 -4
  42. package/dist/worktree/wip-refs.d.ts +23 -0
  43. package/dist/worktree/wip-refs.js +52 -2
  44. package/dist/worktree/wip-restore.d.ts +13 -0
  45. package/dist/worktree/wip-restore.js +159 -25
  46. package/dist/worktree/wip-snapshot.d.ts +5 -2
  47. package/dist/worktree/wip-snapshot.js +15 -13
  48. package/dist/worktree/worktree-origin-sync.d.ts +1 -0
  49. package/dist/worktree/worktree-origin-sync.js +1 -0
  50. package/dist/worktree/worktree-wip-events.d.ts +2 -0
  51. package/dist/worktree/worktree-wip-events.js +53 -3
  52. package/dist/worktree/worktree-wip.d.ts +7 -0
  53. package/dist/worktree/worktree-wip.js +17 -2
  54. package/dist/worktree/worktree.service.d.ts +1 -1
  55. package/dist/worktree/worktree.service.js +6 -3
  56. package/dist/worktree/worktree.types.d.ts +9 -0
  57. package/package.json +1 -1
@@ -0,0 +1,98 @@
1
+ import { hostRuntimeEventResources } from "../runtime/host-runtime-lease.js";
2
+ import { configuredLaunchPortNames } from "../runtime/host-runtime-promotion.js";
3
+ import { deferredProjectStartEvent } from "../worktree/worktree.service.js";
4
+ // The attempt's configured project on a managed host: its first start (or its deferral while a WIP
5
+ // re-apply left unresolved conflicts), the checkpoint text for a validation-time restart, and the
6
+ // Browser QA target it serves.
7
+ /**
8
+ * Builds and launches the attempt's configured project from the prepared worktree and reports the
9
+ * verified port; or, while a WIP re-apply left unresolved conflicts that would fail its build,
10
+ * defers the start to pre-publication validation (deferredProjectStartEvent) so the agent runs first.
11
+ */
12
+ export async function startOrDeferConfiguredProject(hostRuntime, hostLease, dispatch, reapplyConflicts, signal, emitLifecycle) {
13
+ // Only a managed runtime with a port to launch builds anything here (launchConfiguredProject returns
14
+ // at once for analysis_only or no launch config), so no other setup has a build to defer.
15
+ const deferred = (reapplyConflicts?.length ?? 0) > 0 && Boolean(hostRuntime.restartConfiguredProject)
16
+ && hostLease.executionClass === "managed_runtime"
17
+ && configuredLaunchPortNames(hostLease.runtimeContract).length > 0;
18
+ if (deferred) {
19
+ await emitLifecycle(deferredProjectStartEvent(reapplyConflicts));
20
+ return { hostLease, deferred };
21
+ }
22
+ const unconfiguredPortCount = hostLease.lease.resources.ports.length;
23
+ const started = await hostRuntime.startConfiguredProject(dispatch.sandbox.dispatchAttemptId, dispatch.lease.fencingToken, signal, async (checkpoint) => {
24
+ await emitLifecycle({
25
+ role: "runner",
26
+ kind: "checkpoint",
27
+ content: checkpoint.message,
28
+ eventType: checkpoint.code,
29
+ data: checkpoint.data ? JSON.stringify(checkpoint.data) : undefined,
30
+ });
31
+ });
32
+ if (started.lease.resources.ports.length > unconfiguredPortCount) {
33
+ const assigned = started.lease.resources.ports.at(-1);
34
+ await emitLifecycle({
35
+ role: "runner",
36
+ kind: "checkpoint",
37
+ content: `Verified supervised project runtime ${assigned.name} on ${assigned.hostIp}:${assigned.hostPort}.`,
38
+ eventType: "host_runtime_project_ready",
39
+ data: JSON.stringify(hostRuntimeEventResources(started.lease, started.runtimeContract, started.executionClass)),
40
+ });
41
+ }
42
+ return { hostLease: started, deferred };
43
+ }
44
+ export function managedQaLaunchTarget(runtimeContract) {
45
+ const playwright = runtimeContract.contract.runtime.playwright;
46
+ if (!playwright)
47
+ return null;
48
+ const port = runtimeContract.contract.runtime.ports.find(candidate => candidate.name === playwright.baseUrlPort);
49
+ return port?.launch && port.baseUrlEnv && port.format
50
+ ? { managedRuntimePort: port.name, routes: ["/"] }
51
+ : null;
52
+ }
53
+ /** The host_runtime_restart_started checkpoint text for the first cause of a validation-time restart. */
54
+ export function runtimeRestartStartedMessage(reason, changes) {
55
+ const current = "so validation runs against the current source.";
56
+ switch (reason) {
57
+ case "deferred_start":
58
+ return `Starting the attempt runtime stack, deferred until the restored work's re-apply conflicts were resolved, ${current}`;
59
+ case "workspace_changed":
60
+ return `The workspace changed since the attempt runtime stack was launched (${changes.join(", ")}); restarting it ${current}`;
61
+ case "previous_restart_incomplete":
62
+ return `The previous attempt runtime restart did not complete; restarting it again ${current}`
63
+ + (changes.length > 0 ? ` The workspace also changed since launch (${changes.join(", ")}).` : "");
64
+ default:
65
+ return `The workspace state could not be compared with the attempt runtime stack; restarting it ${current}`;
66
+ }
67
+ }
68
+ /**
69
+ * The dispatch with its managed Browser QA target's URL from the started stack. While the first start
70
+ * is deferred (startOrDeferConfiguredProject) the stack has no URL yet: the target keeps its port,
71
+ * and validation starts the stack once the agent has resolved the conflicts.
72
+ */
73
+ export function withMaterializedManagedQaTarget(dispatch, hostLease, projectStartDeferred = false) {
74
+ const target = dispatch.qaBrowser?.launchTarget;
75
+ const portName = target?.managed_runtime_port?.trim().toLowerCase();
76
+ if (!target || !portName)
77
+ return dispatch;
78
+ if (!hostLease) {
79
+ throw new Error("qa_managed_runtime_unavailable: Browser QA requires the verified managed host runtime selected during readiness.");
80
+ }
81
+ const normalizedName = portName.toUpperCase().replaceAll(/[^A-Z0-9]/gu, "_");
82
+ const url = hostLease.environment[`FORGE_${normalizedName}_URL`];
83
+ if (!url && projectStartDeferred)
84
+ return withQaTargetNote(dispatch, target, "Forge starts this port's stack at validation, after the conflicts from restored work are resolved; it has no URL before then.");
85
+ if (!url) {
86
+ throw new Error(`qa_managed_runtime_unavailable: verified runtime port '${portName}' was not launched for this attempt.`);
87
+ }
88
+ return withQaTargetNote(dispatch, { ...target, url: target.url ?? url, ready_url: target.ready_url ?? url }, "Forge launched and verified this URL inside the current fenced attempt.");
89
+ }
90
+ function withQaTargetNote(dispatch, target, note) {
91
+ return {
92
+ ...dispatch,
93
+ qaBrowser: dispatch.qaBrowser ? {
94
+ ...dispatch.qaBrowser,
95
+ launchTarget: { ...target, notes: [target.notes, note].filter(Boolean).join(" ") },
96
+ } : dispatch.qaBrowser,
97
+ };
98
+ }
@@ -2,10 +2,11 @@ import { redactRunnerDispatchEvent, redactRunOnceResultPacket } from "./session-
2
2
  import { randomUUID } from "node:crypto";
3
3
  import { RoutingProviderCliService } from "./provider-cli/provider-cli.service.js";
4
4
  import { ForgeFailureError, waitKindForEvent, waitWakeCondition } from "./session.types.js";
5
- import { emitWorktreePreparedEvents, GitWorktreeService, sessionWipOutcome, settleWorktree } from "../worktree/worktree.service.js";
5
+ import { emitWorktreePreparedEvents, GitWorktreeService, sessionWipOutcome, settleWorktree, } from "../worktree/worktree.service.js";
6
6
  import { SandboxWorkspaceService } from "../sandbox/workspace.service.js";
7
7
  import { HostRuntimeAdmissionExpiredError, hostRuntimeEventResources, hostRuntimeStackEnvironmentKeys, runtimeAdmissionPriority, } from "../runtime/host-runtime-lease.js";
8
8
  import { configuredLaunchPortNames, hostRuntimeContractFingerprint, hostRuntimeParallelEligible, } from "../runtime/host-runtime-promotion.js";
9
+ import { managedQaLaunchTarget, runtimeRestartStartedMessage, startOrDeferConfiguredProject, withMaterializedManagedQaTarget, } from "./session-host-project.js";
9
10
  import { readWorkspaceRuntimeFingerprint, sameWorkspaceRuntimeFingerprint, workspaceRuntimeFingerprintChanges, } from "./workspace-runtime-fingerprint.js";
10
11
  const minimumReadinessProbeStartupBudgetMs = 150_000;
11
12
  export class BridgeSessionService {
@@ -251,10 +252,7 @@ export class BridgeSessionService {
251
252
  applicationRuntimeRequired: dispatch.runtimeIntent.applicationRuntimeRequired,
252
253
  preserveExistingState: Boolean(dispatch.session.resumedFromSessionId),
253
254
  sessionId: dispatch.session.id,
254
- hostLoadOwner: {
255
- dispatchAttemptId: dispatch.sandbox?.dispatchAttemptId ?? null,
256
- priority: runtimeAdmissionPriority(dispatch),
257
- },
255
+ ...preparedAttemptOwner(dispatch),
258
256
  signal,
259
257
  });
260
258
  }
@@ -283,6 +281,10 @@ export class BridgeSessionService {
283
281
  if (worktree.dependencyWarm) {
284
282
  await emitDependencyWarmEvents(worktree.dependencyWarm, emit);
285
283
  }
284
+ // Conflicts a WIP re-apply left for the agent (deferredProjectStartEvent): the project stack
285
+ // is not started on them, and the prompt names them.
286
+ const reapplyConflicts = worktree.reapplyConflicts;
287
+ let projectStartDeferred = false;
286
288
  if (dispatch.sandbox?.executionMode === "host" && this.hostRuntime) {
287
289
  hostLease = await this.hostRuntime.start(dispatch, worktree.worktreePath, signal, async (checkpoint) => {
288
290
  const observation = waitObservation(checkpoint.code);
@@ -313,26 +315,7 @@ export class BridgeSessionService {
313
315
  remediation: "Enable Run in Docker in Project Settings.",
314
316
  }),
315
317
  });
316
- const unconfiguredPortCount = hostLease.lease.resources.ports.length;
317
- hostLease = await this.hostRuntime.startConfiguredProject(dispatch.sandbox.dispatchAttemptId, dispatch.lease.fencingToken, signal, async (checkpoint) => {
318
- await emitLifecycle({
319
- role: "runner",
320
- kind: "checkpoint",
321
- content: checkpoint.message,
322
- eventType: checkpoint.code,
323
- data: checkpoint.data ? JSON.stringify(checkpoint.data) : undefined,
324
- });
325
- });
326
- if (hostLease.lease.resources.ports.length > unconfiguredPortCount) {
327
- const assigned = hostLease.lease.resources.ports.at(-1);
328
- await emitLifecycle({
329
- role: "runner",
330
- kind: "checkpoint",
331
- content: `Verified supervised project runtime ${assigned.name} on ${assigned.hostIp}:${assigned.hostPort}.`,
332
- eventType: "host_runtime_project_ready",
333
- data: JSON.stringify(hostRuntimeEventResources(hostLease.lease, hostLease.runtimeContract, hostLease.executionClass)),
334
- });
335
- }
318
+ ({ hostLease, deferred: projectStartDeferred } = await startOrDeferConfiguredProject(this.hostRuntime, hostLease, dispatch, reapplyConflicts, signal, emitLifecycle));
336
319
  }
337
320
  // The stack was built and launched from this workspace state. Pre-publication
338
321
  // validation restarts it when the provider has changed the source since.
@@ -349,31 +332,29 @@ export class BridgeSessionService {
349
332
  .catch(() => null);
350
333
  // Set while the stack may not match the workspace: a failed restart is retried on the next pass.
351
334
  let restartPending = false;
335
+ // Set until the deferred first start (re-apply conflicts) succeeds: the stack has never run.
336
+ let startDeferred = projectStartDeferred;
352
337
  refreshRuntimeEnvironment = async (refreshSignal) => {
353
338
  // A late violation stopped the stack: fail this validation pass rather than run it against closed ports.
354
339
  this.throwIfAbortedOrIsolationViolated(undefined, dispatch, hostLease);
355
340
  const current = await this.workspaceFingerprint(worktreePath).catch(() => null);
356
- if (!restartPending && sameWorkspaceRuntimeFingerprint(launchFingerprint, current))
341
+ if (!restartPending && !startDeferred && sameWorkspaceRuntimeFingerprint(launchFingerprint, current))
357
342
  return null;
358
343
  // Every cause that applies is reported; `reason` is the first of them. Changes are named
359
344
  // only when both states were read: an unreadable baseline is not a workspace change.
360
345
  const comparable = launchFingerprint !== null && current !== null;
361
346
  const changes = comparable ? workspaceRuntimeFingerprintChanges(launchFingerprint, current) : [];
362
347
  const causes = [
348
+ ...(startDeferred ? ["deferred_start"] : []),
363
349
  ...(restartPending ? ["previous_restart_incomplete"] : []),
364
350
  ...(comparable ? [] : ["fingerprint_unavailable"]),
365
351
  ...(changes.length > 0 ? ["workspace_changed"] : []),
366
352
  ];
367
353
  const reason = causes[0] ?? "workspace_changed";
368
- const changeText = changes.length > 0 ? ` The workspace also changed since launch (${changes.join(", ")}).` : "";
369
354
  await emitLifecycle({
370
355
  role: "runner",
371
356
  kind: "checkpoint",
372
- content: reason === "workspace_changed"
373
- ? `The workspace changed since the attempt runtime stack was launched (${changes.join(", ")}); restarting it so validation runs against the current source.`
374
- : reason === "previous_restart_incomplete"
375
- ? `The previous attempt runtime restart did not complete; restarting it again so validation runs against the current source.${changeText}`
376
- : `The workspace state could not be compared with the attempt runtime stack; restarting it so validation runs against the current source.`,
357
+ content: runtimeRestartStartedMessage(reason, changes),
377
358
  eventType: "host_runtime_restart_started",
378
359
  data: JSON.stringify({
379
360
  reason,
@@ -412,6 +393,7 @@ export class BridgeSessionService {
412
393
  // baseline never matches, so every later pass would restart and rotate ports again.
413
394
  launchFingerprint = await this.workspaceFingerprint(worktreePath).catch(() => current);
414
395
  restartPending = false;
396
+ startDeferred = false;
415
397
  await emitLifecycle({
416
398
  role: "runner",
417
399
  kind: "checkpoint",
@@ -422,7 +404,7 @@ export class BridgeSessionService {
422
404
  return { environment: restarted.environment, reason, changes };
423
405
  };
424
406
  }
425
- providerDispatch = withMaterializedManagedQaTarget(providerDispatch, hostLease);
407
+ providerDispatch = withMaterializedManagedQaTarget(providerDispatch, hostLease, projectStartDeferred);
426
408
  const providerEnvironment = {
427
409
  runtimeEnvironment: hostLease?.environment,
428
410
  // Only the completion MCP server gets these: its managed commands share the host ledger.
@@ -472,6 +454,8 @@ export class BridgeSessionService {
472
454
  ...(refreshRuntimeEnvironment && hostLease
473
455
  ? { refreshRuntimeEnvironment, runtimeStackEnvironmentKeys: hostRuntimeStackEnvironmentKeys(hostLease.runtimeContract) }
474
456
  : {}),
457
+ reapplyConflicts,
458
+ projectStartDeferred,
475
459
  emit,
476
460
  signal
477
461
  };
@@ -725,43 +709,6 @@ function assertReadinessProbeStartupBudget(expiresAt) {
725
709
  throw new Error("host_runtime_probe_deadline_insufficient: readiness admission completed too close to the probe deadline; Forge released the reservation before launching the application.");
726
710
  }
727
711
  }
728
- function managedQaLaunchTarget(runtimeContract) {
729
- const playwright = runtimeContract.contract.runtime.playwright;
730
- if (!playwright)
731
- return null;
732
- const port = runtimeContract.contract.runtime.ports.find(candidate => candidate.name === playwright.baseUrlPort);
733
- return port?.launch && port.baseUrlEnv && port.format
734
- ? { managedRuntimePort: port.name, routes: ["/"] }
735
- : null;
736
- }
737
- function withMaterializedManagedQaTarget(dispatch, hostLease) {
738
- const target = dispatch.qaBrowser?.launchTarget;
739
- const portName = target?.managed_runtime_port?.trim().toLowerCase();
740
- if (!target || !portName)
741
- return dispatch;
742
- if (!hostLease) {
743
- throw new Error("qa_managed_runtime_unavailable: Browser QA requires the verified managed host runtime selected during readiness.");
744
- }
745
- const normalizedName = portName.toUpperCase().replaceAll(/[^A-Z0-9]/gu, "_");
746
- const url = hostLease.environment[`FORGE_${normalizedName}_URL`];
747
- if (!url) {
748
- throw new Error(`qa_managed_runtime_unavailable: verified runtime port '${portName}' was not launched for this attempt.`);
749
- }
750
- return {
751
- ...dispatch,
752
- qaBrowser: dispatch.qaBrowser ? {
753
- ...dispatch.qaBrowser,
754
- launchTarget: {
755
- ...target,
756
- url: target.url ?? url,
757
- ready_url: target.ready_url ?? url,
758
- notes: [target.notes, "Forge launched and verified this URL inside the current fenced attempt."]
759
- .filter(Boolean)
760
- .join(" "),
761
- },
762
- } : dispatch.qaBrowser,
763
- };
764
- }
765
712
  function probeFailureCode(error) {
766
713
  const message = error instanceof Error ? error.message : String(error);
767
714
  const candidate = message.split(":", 1)[0]?.trim().toLowerCase() ?? "";
@@ -776,6 +723,13 @@ function throwIfAborted(signal) {
776
723
  throw new Error(String(signal.reason ?? "Dispatch cancelled."));
777
724
  }
778
725
  }
726
+ /** The dispatch attempt a worktree is prepared for: Forge's attempt for its WIP refs, and whose host load it reserves. */
727
+ function preparedAttemptOwner(dispatch) {
728
+ return {
729
+ wipAttempt: dispatch.wipAttempt ?? null,
730
+ hostLoadOwner: { dispatchAttemptId: dispatch.sandbox?.dispatchAttemptId ?? null, priority: runtimeAdmissionPriority(dispatch) },
731
+ };
732
+ }
779
733
  function validateApiKeySecretGrant(dispatch) {
780
734
  if (!dispatch.execution.requiresApiKeySecretGrant) {
781
735
  return;
@@ -11,6 +11,7 @@ export interface RunOnceDispatchPacket {
11
11
  readonly runtimeIntent: DispatchRuntimeIntent;
12
12
  readonly serverLocal: DispatchServerLocalConfig;
13
13
  readonly sandbox?: DispatchSandboxContext | null;
14
+ readonly wipAttempt?: number | null;
14
15
  readonly pullRequest?: DispatchPullRequestContext | null;
15
16
  readonly apiKeySecretGrant?: ApiKeySecretGrant | null;
16
17
  readonly apiKeySecretGrantHandle?: ApiKeySecretGrantHandle | null;
@@ -28,6 +28,7 @@ export function parseRunOnceDispatchPacket(value) {
28
28
  runtimeIntent: parseRuntimeIntent(packet.runtimeIntent),
29
29
  serverLocal: parseServerLocal(packet.serverLocal),
30
30
  sandbox: parseSandbox(packet.sandbox, schemaVersion),
31
+ wipAttempt: optionalNonNegativeInteger(packet, "wipAttempt"),
31
32
  pullRequest: parsePullRequest(packet.pullRequest),
32
33
  apiKeySecretGrant: parseApiKeySecretGrant(packet.apiKeySecretGrant),
33
34
  apiKeySecretGrantHandle: parseApiKeySecretGrantHandle(packet.apiKeySecretGrantHandle),
@@ -1373,9 +1374,8 @@ function optionalPositiveInteger(source, key) {
1373
1374
  }
1374
1375
  function optionalNonNegativeInteger(source, key) {
1375
1376
  const value = source[key];
1376
- if (value === undefined || value === null) {
1377
+ if (value === undefined || value === null)
1377
1378
  return null;
1378
- }
1379
1379
  if (typeof value !== "number" || !Number.isInteger(value) || value < 0) {
1380
1380
  throw new Error(`${key} must be a non-negative integer when provided.`);
1381
1381
  }
@@ -1,4 +1,6 @@
1
1
  import { type BridgeChatCapability } from "../bridge/bridge-chat.types.js";
2
2
  import type { BridgeProviderStatus } from "../bridge/bridge.types.js";
3
3
  export declare function supportsDraftImageAttachmentsFor(cliProviders: readonly string[]): boolean;
4
+ /** The sandbox profiles a bridge advertises when none are configured: Codex's sandbox, or none. */
5
+ export declare function defaultSandboxProfiles(providers: readonly string[], platform?: NodeJS.Platform): readonly string[];
4
6
  export declare function bridgeChatCapabilityFor(cliProviders: readonly string[], providerStatuses: Readonly<Record<string, BridgeProviderStatus>>, baseCapability?: BridgeChatCapability | null): BridgeChatCapability;
@@ -5,6 +5,15 @@ const defaultBridgeChatMaxContextRefs = 8;
5
5
  export function supportsDraftImageAttachmentsFor(cliProviders) {
6
6
  return cliProviders.some((provider) => provider.trim().toLowerCase() === "codex");
7
7
  }
8
+ /** The sandbox profiles a bridge advertises when none are configured: Codex's sandbox, or none. */
9
+ export function defaultSandboxProfiles(providers, platform = process.platform) {
10
+ if (!providers.some((provider) => provider.toLowerCase() === "codex")) {
11
+ return ["none"];
12
+ }
13
+ return platform === "win32"
14
+ ? ["danger-full-access"]
15
+ : ["provider-workspace-write"];
16
+ }
8
17
  export function bridgeChatCapabilityFor(cliProviders, providerStatuses, baseCapability) {
9
18
  const base = normalizeBridgeChatCapability(baseCapability ?? unavailableBridgeChatCapability());
10
19
  if (base.protocolVersion !== bridgeChatProtocolVersion) {
package/dist/version.d.ts CHANGED
@@ -1 +1 @@
1
- export declare const forgeBridgeVersion = "0.2.1-dev.4f11ffc822f9";
1
+ export declare const forgeBridgeVersion = "0.2.1-dev.573a8a5fa582";
package/dist/version.js CHANGED
@@ -1 +1 @@
1
- export const forgeBridgeVersion = "0.2.1-dev.4f11ffc822f9";
1
+ export const forgeBridgeVersion = "0.2.1-dev.573a8a5fa582";
@@ -6,6 +6,12 @@ export declare class WipGit {
6
6
  /** The same client with more environment, e.g. GIT_INDEX_FILE for a throwaway index. */
7
7
  with(env: NodeJS.ProcessEnv): WipGit;
8
8
  run(cwd: string, args: readonly string[]): Promise<string>;
9
+ /** Runs git and returns its exit code with its output, for commands whose non-zero exit is an answer. */
10
+ runWithStatus(cwd: string, args: readonly string[]): Promise<{
11
+ readonly exitCode: number;
12
+ readonly stdout: string;
13
+ readonly stderr: string;
14
+ }>;
9
15
  tryRun(cwd: string, args: readonly string[]): Promise<string | null>;
10
16
  /** Runs git with `input` on stdin (for `update-index --index-info`). */
11
17
  runWithInput(cwd: string, args: readonly string[], input: string): Promise<void>;
@@ -28,6 +34,25 @@ export declare function baseTrackedForgePaths(git: WipGit, cwd: string, base: st
28
34
  export declare function gitPath(git: WipGit, cwd: string, name: string): Promise<string>;
29
35
  export declare function partialRestoreMarkerPath(git: WipGit, cwd: string): Promise<string>;
30
36
  export declare function hasPartialRestoreMarker(git: WipGit, cwd: string): Promise<boolean>;
37
+ export declare function readReapplyConflictRecord(git: WipGit, cwd: string): Promise<string[]>;
38
+ /**
39
+ * The recorded re-apply conflicts (wip-refs.ts) the worktree has not resolved yet: paths that still
40
+ * have conflict stages in the index, or conflict markers in the file. A path the agent resolved
41
+ * (markers gone, or the file deleted) drops out; the record itself is left for publication to check.
42
+ * Throws when the record, the index or a recorded file cannot be read.
43
+ */
44
+ export declare function unresolvedReapplyConflicts(git: WipGit, cwd: string): Promise<string[]>;
45
+ /**
46
+ * The text to use for a file that must parse before the agent runs (the host runtime contract):
47
+ * while a WIP re-apply left it unresolved (unresolvedReapplyConflicts: index stages, which include
48
+ * marker-free modify/delete and binary conflicts, or markers), HEAD's version, or null when HEAD has
49
+ * none (the file counts as absent); otherwise `text` itself. The session defers the
50
+ * project start for those conflicts (deferredProjectStartEvent in worktree-wip-events.ts), and
51
+ * admission, readiness and the lease still need a valid contract to get the agent that far.
52
+ */
53
+ export declare function committedWhileReapplyConflicted(cwd: string, relativePath: string, text: string): Promise<string | null>;
54
+ /** Writes the re-apply conflict record (wip-refs.ts), or removes it when there are no paths. */
55
+ export declare function writeReapplyConflictRecord(git: WipGit, cwd: string, paths: readonly string[]): Promise<void>;
31
56
  /** A private directory for throwaway index files, removed by the caller. */
32
57
  export declare function makeWipTempDir(): Promise<string>;
33
58
  export declare function readOptionalFile(filePath: string): Promise<string | null>;
@@ -4,6 +4,7 @@ import os from "node:os";
4
4
  import path from "node:path";
5
5
  import { isRuntimeOnlyPath } from "../session/publishable-worktree-changes.js";
6
6
  import { NodeProcessRunner } from "../shared/process/process.js";
7
+ import { hasConflictMarkerLines, parseReapplyConflictRecord, wipReapplyConflictRecordName } from "./wip-refs.js";
7
8
  // Git plumbing shared by WIP snapshot and restore. Every command can carry extra environment
8
9
  // (a temporary index, or GIT_DIR/GIT_WORK_TREE for an orphaned checkout) without touching the
9
10
  // worktree's own index, HEAD or config.
@@ -26,6 +27,14 @@ export class WipGit {
26
27
  return new WipGit(this.runner, { ...this.env, ...env });
27
28
  }
28
29
  async run(cwd, args) {
30
+ const result = await this.runWithStatus(cwd, args);
31
+ if (result.exitCode !== 0) {
32
+ throw new Error(`git ${args.join(" ")} failed: ${result.stderr.trim() || result.stdout.trim()}`);
33
+ }
34
+ return result.stdout;
35
+ }
36
+ /** Runs git and returns its exit code with its output, for commands whose non-zero exit is an answer. */
37
+ async runWithStatus(cwd, args) {
29
38
  const result = await this.runner.run({
30
39
  command: "git",
31
40
  args,
@@ -33,10 +42,7 @@ export class WipGit {
33
42
  env: { ...process.env, ...wipIdentity, ...this.env },
34
43
  ...(args.includes("-z") ? { rawOutput: true } : {}),
35
44
  });
36
- if (result.exitCode !== 0) {
37
- throw new Error(`git ${args.join(" ")} failed: ${result.stderr.trim() || result.stdout.trim()}`);
38
- }
39
- return result.stdout;
45
+ return { exitCode: result.exitCode, stdout: result.stdout, stderr: result.stderr };
40
46
  }
41
47
  async tryRun(cwd, args) {
42
48
  return await this.run(cwd, args).catch(() => null);
@@ -109,6 +115,60 @@ export async function hasPartialRestoreMarker(git, cwd) {
109
115
  const marker = await partialRestoreMarkerPath(git, cwd).catch(() => null);
110
116
  return marker !== null && await fs.stat(marker).then(() => true, () => false);
111
117
  }
118
+ export async function readReapplyConflictRecord(git, cwd) {
119
+ return parseReapplyConflictRecord(await readOptionalFile(await gitPath(git, cwd, wipReapplyConflictRecordName)));
120
+ }
121
+ /**
122
+ * The recorded re-apply conflicts (wip-refs.ts) the worktree has not resolved yet: paths that still
123
+ * have conflict stages in the index, or conflict markers in the file. A path the agent resolved
124
+ * (markers gone, or the file deleted) drops out; the record itself is left for publication to check.
125
+ * Throws when the record, the index or a recorded file cannot be read.
126
+ */
127
+ export async function unresolvedReapplyConflicts(git, cwd) {
128
+ const recorded = await readReapplyConflictRecord(git, cwd);
129
+ if (recorded.length === 0)
130
+ return [];
131
+ const unmerged = new Set(splitNul(await git.run(cwd, ["ls-files", "-u", "-z"])).map(entry => entry.slice(entry.indexOf("\t") + 1)));
132
+ const unresolved = [];
133
+ for (const filePath of recorded) {
134
+ if (unmerged.has(filePath)) {
135
+ unresolved.push(filePath);
136
+ continue;
137
+ }
138
+ const content = await readOptionalFile(path.join(cwd, filePath));
139
+ if (content !== null && hasConflictMarkerLines(content))
140
+ unresolved.push(filePath);
141
+ }
142
+ return unresolved;
143
+ }
144
+ /**
145
+ * The text to use for a file that must parse before the agent runs (the host runtime contract):
146
+ * while a WIP re-apply left it unresolved (unresolvedReapplyConflicts: index stages, which include
147
+ * marker-free modify/delete and binary conflicts, or markers), HEAD's version, or null when HEAD has
148
+ * none (the file counts as absent); otherwise `text` itself. The session defers the
149
+ * project start for those conflicts (deferredProjectStartEvent in worktree-wip-events.ts), and
150
+ * admission, readiness and the lease still need a valid contract to get the agent that far.
151
+ */
152
+ export async function committedWhileReapplyConflicted(cwd, relativePath, text) {
153
+ const git = new WipGit();
154
+ // Outside a Git worktree there is no re-apply state. A prepared worktree whose record can't be
155
+ // read never gets this far: prepare fails on it (unresolvedWorktreeReapplyConflicts).
156
+ const conflicts = await unresolvedReapplyConflicts(git, cwd).catch(() => []);
157
+ if (!conflicts.includes(relativePath))
158
+ return text;
159
+ const tracked = await git.tryRun(cwd, ["ls-tree", "--name-only", "HEAD", "--", relativePath]);
160
+ if (tracked !== null && !tracked.trim())
161
+ return null;
162
+ return await git.tryRun(cwd, ["cat-file", "blob", `HEAD:${relativePath}`]) ?? text;
163
+ }
164
+ /** Writes the re-apply conflict record (wip-refs.ts), or removes it when there are no paths. */
165
+ export async function writeReapplyConflictRecord(git, cwd, paths) {
166
+ const record = await gitPath(git, cwd, wipReapplyConflictRecordName);
167
+ if (paths.length === 0)
168
+ await fs.rm(record, { force: true });
169
+ else
170
+ await fs.writeFile(record, [...new Set(paths)].sort().join("\0"), "utf8");
171
+ }
112
172
  /** A private directory for throwaway index files, removed by the caller. */
113
173
  export async function makeWipTempDir() {
114
174
  return await fs.mkdtemp(path.join(os.tmpdir(), "forge-wip-"));
@@ -1,5 +1,22 @@
1
1
  export declare const wipRefRoot = "refs/forge/wip";
2
2
  export declare const wipMetadataSchema = "forge.wip.v1";
3
+ /**
4
+ * Kept in a worktree's Git directory after a WIP re-apply across a branch move left conflicts
5
+ * (wip-restore.ts): the conflicted paths, NUL-separated. A re-apply writes no MERGE_HEAD, and staging
6
+ * a conflicted file clears its index stages but keeps its markers, so publication reads this to keep
7
+ * refusing those markers (provider-cli.merge-integrity.ts). Snapshots carry it (reapplyConflicts) and
8
+ * a restore writes it back; a restore that finds the worktree clean removes it.
9
+ */
10
+ export declare const wipReapplyConflictRecordName = "forge-wip-reapply-conflicts";
11
+ export declare function parseReapplyConflictRecord(content: string | null): string[];
12
+ /** True when the text has a Git conflict block: a `<<<<<<<` line followed later by a `>>>>>>>` line. */
13
+ export declare function hasConflictMarkerLines(text: string): boolean;
14
+ /**
15
+ * True when `text` has a conflict block (`<<<<<<<` through the next `>>>>>>>`) that `base` does not:
16
+ * blocks are compared by their exact text, as many times as each occurs, so a file whose base
17
+ * already holds a marker fixture still counts when another block is added to it.
18
+ */
19
+ export declare function hasNewConflictBlocks(text: string, base: string | null): boolean;
3
20
  /** The attempt of a snapshot taken without a Forge-issued attempt number. */
4
21
  export declare const unorderedWipAttempt = 0;
5
22
  /** Why a snapshot was taken. Session reasons name the session; the others are guards. */
@@ -27,6 +44,8 @@ export interface WipSnapshotMetadata {
27
44
  readonly mergeMessage: string | null;
28
45
  readonly mergeMode: string | null;
29
46
  readonly unmerged: readonly WipUnmergedEntry[];
47
+ /** The worktree's re-apply conflict record when it was taken (see wipReapplyConflictRecordName); [] before it existed. */
48
+ readonly reapplyConflicts: readonly string[];
30
49
  readonly changedPaths: number;
31
50
  readonly bytes: number;
32
51
  }
@@ -53,6 +72,10 @@ export declare function wipRefName(branchName: string, id: string): string;
53
72
  * for a guard snapshot.
54
73
  */
55
74
  export declare function wipRefId(reason: WipSnapshotReason, sessionId: string | null | undefined, now: Date, attempt?: number): string;
75
+ /** A Forge-issued attempt usable in a ref name; anything else (missing, out of range) is unorderedWipAttempt. */
76
+ export declare function issuedWipAttempt(value: number | null | undefined): number;
77
+ /** The attempt a WIP ref belongs to: its ten-digit id prefix, or unorderedWipAttempt without one. */
78
+ export declare function wipRefAttempt(ref: string): number;
56
79
  /** The cap on a snapshot's size, from FORGE_WIP_SNAPSHOT_MAX_BYTES when that is a positive integer. */
57
80
  export declare function wipSnapshotMaxBytes(env?: NodeJS.ProcessEnv): number;
58
81
  export declare function formatWipCommitMessage(metadata: WipSnapshotMetadata): string;
@@ -7,8 +7,11 @@
7
7
  //
8
8
  // refs/forge/wip/<owner key>/<attempt>-<session id | [session id-]reason-timestamp-nonce>
9
9
  //
10
- // <attempt> is ten zero-padded digits, so refs sort by it. It is reserved for Forge's per-story
11
- // attempt number (newest work wins); until the server sends one, snapshots carry attempt 0.
10
+ // <attempt> is ten zero-padded digits, so refs sort by it: the dispatch's wipAttempt, which Forge
11
+ // issues from a database sequence when it admits the dispatch attempt, so a later attempt on a story
12
+ // always has a larger one. Newest work wins: a restore takes the highest attempt first. Snapshots
13
+ // taken without an issued attempt (older servers, attempts admitted before it existed, cleanup and
14
+ // branch-reset guards) carry attempt 0.
12
15
  //
13
16
  // The owner key is the story's short id for a `story/<12 hex>` branch, and `b_` plus the branch
14
17
  // name with `_` → `_u` and `/` → `_s` for any other branch (`b_task_s0123456789ab`), so it is
@@ -26,6 +29,40 @@ const defaultWipSnapshotMaxBytes = 100 * 1024 * 1024;
26
29
  const wipSnapshotMaxBytesEnv = "FORGE_WIP_SNAPSHOT_MAX_BYTES";
27
30
  const storyBranchPattern = /^story\/([0-9a-f]{12})$/u;
28
31
  const refSegmentPattern = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/u;
32
+ /**
33
+ * Kept in a worktree's Git directory after a WIP re-apply across a branch move left conflicts
34
+ * (wip-restore.ts): the conflicted paths, NUL-separated. A re-apply writes no MERGE_HEAD, and staging
35
+ * a conflicted file clears its index stages but keeps its markers, so publication reads this to keep
36
+ * refusing those markers (provider-cli.merge-integrity.ts). Snapshots carry it (reapplyConflicts) and
37
+ * a restore writes it back; a restore that finds the worktree clean removes it.
38
+ */
39
+ export const wipReapplyConflictRecordName = "forge-wip-reapply-conflicts";
40
+ export function parseReapplyConflictRecord(content) {
41
+ return content ? [...new Set(content.split("\0").filter(Boolean))].sort() : [];
42
+ }
43
+ const conflictMarkerPattern = /^<{7}(?: |$)[\s\S]*^>{7}(?: |$)/mu;
44
+ /** True when the text has a Git conflict block: a `<<<<<<<` line followed later by a `>>>>>>>` line. */
45
+ export function hasConflictMarkerLines(text) {
46
+ return conflictMarkerPattern.test(text);
47
+ }
48
+ const conflictBlockPattern = /^<{7}(?: [^\n]*)?\r?\n[\s\S]*?^>{7}(?: [^\n]*)?$/gmu;
49
+ /**
50
+ * True when `text` has a conflict block (`<<<<<<<` through the next `>>>>>>>`) that `base` does not:
51
+ * blocks are compared by their exact text, as many times as each occurs, so a file whose base
52
+ * already holds a marker fixture still counts when another block is added to it.
53
+ */
54
+ export function hasNewConflictBlocks(text, base) {
55
+ const remaining = new Map();
56
+ for (const block of base?.match(conflictBlockPattern) ?? [])
57
+ remaining.set(block, (remaining.get(block) ?? 0) + 1);
58
+ for (const block of text.match(conflictBlockPattern) ?? []) {
59
+ const left = remaining.get(block) ?? 0;
60
+ if (left === 0)
61
+ return true;
62
+ remaining.set(block, left - 1);
63
+ }
64
+ return false;
65
+ }
29
66
  /** The attempt of a snapshot taken without a Forge-issued attempt number. */
30
67
  export const unorderedWipAttempt = 0;
31
68
  const maxWipAttempt = 9_999_999_999;
@@ -82,6 +119,16 @@ function isSessionReason(reason) {
82
119
  return reason === "session_failed" || reason === "repair_limit"
83
120
  || reason === "session_paused" || reason === "session_stopped";
84
121
  }
122
+ /** A Forge-issued attempt usable in a ref name; anything else (missing, out of range) is unorderedWipAttempt. */
123
+ export function issuedWipAttempt(value) {
124
+ return typeof value === "number" && Number.isSafeInteger(value) && value >= 0 && value <= maxWipAttempt ? value : unorderedWipAttempt;
125
+ }
126
+ /** The attempt a WIP ref belongs to: its ten-digit id prefix, or unorderedWipAttempt without one. */
127
+ export function wipRefAttempt(ref) {
128
+ const id = ref.slice(ref.lastIndexOf("/") + 1);
129
+ const match = /^(\d{10})-/u.exec(id);
130
+ return match ? Number(match[1]) : unorderedWipAttempt;
131
+ }
85
132
  /** The cap on a snapshot's size, from FORGE_WIP_SNAPSHOT_MAX_BYTES when that is a positive integer. */
86
133
  export function wipSnapshotMaxBytes(env = process.env) {
87
134
  const configured = Number.parseInt(env[wipSnapshotMaxBytesEnv] ?? "", 10);
@@ -106,6 +153,9 @@ export function parseWipCommitMessage(message) {
106
153
  ...parsed,
107
154
  unmerged: Array.isArray(parsed.unmerged) ? parsed.unmerged : [],
108
155
  autoRestore: parsed.autoRestore === true,
156
+ reapplyConflicts: Array.isArray(parsed.reapplyConflicts)
157
+ ? parsed.reapplyConflicts.filter(conflict => typeof conflict === "string")
158
+ : [],
109
159
  };
110
160
  }
111
161
  catch {
@@ -15,6 +15,13 @@ export type WipRestoreOutcome = {
15
15
  readonly sourceSessionId: string | null;
16
16
  readonly changedPaths: number;
17
17
  readonly mergeInProgress: boolean;
18
+ /** Set when the branch had moved and the snapshot was re-applied onto its new HEAD with a 3-way merge. */
19
+ readonly reapplied: WipReapply | null;
20
+ /**
21
+ * Every path left for the agent to resolve with no MERGE_HEAD to show it (the worktree's re-apply
22
+ * conflict record): this re-apply's conflicts and any an earlier re-apply left in the snapshot.
23
+ */
24
+ readonly reapplyConflicts: readonly string[];
18
25
  } | {
19
26
  readonly status: "not_restored";
20
27
  readonly ref: string;
@@ -31,6 +38,12 @@ export type WipRestoreOutcome = {
31
38
  readonly status: "unavailable";
32
39
  readonly detail: string;
33
40
  };
41
+ export interface WipReapply {
42
+ /** The HEAD the snapshot was taken on, used as the merge base. */
43
+ readonly snapshotBaseHead: string;
44
+ /** Paths the merge left unmerged, with conflict markers where Git writes them, for the agent to resolve. */
45
+ readonly conflictedPaths: readonly string[];
46
+ }
34
47
  export declare function restoreLatestWip(request: WipRestoreRequest): Promise<WipRestoreOutcome>;
35
48
  /** Deletes a WIP ref (on origin, or locally when there is no origin). Never throws. */
36
49
  export declare function deleteWipRef(repoPath: string, ref: string, processRunner?: ProcessRunner): Promise<boolean>;