@loucompanion/forge-bridge 0.2.1-dev.1a5cf93b48a1 → 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 (50) 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.js +2 -3
  25. package/dist/session/provider-cli/provider-cli.prompts.d.ts +10 -0
  26. package/dist/session/provider-cli/provider-cli.prompts.js +37 -0
  27. package/dist/session/provider-cli/provider-cli.service.js +9 -9
  28. package/dist/session/provider-cli/provider-cli.types.d.ts +7 -2
  29. package/dist/session/sandbox-host-capacity-gate.js +1 -1
  30. package/dist/session/session-host-project.d.ts +22 -0
  31. package/dist/session/session-host-project.js +98 -0
  32. package/dist/session/session.service.js +16 -66
  33. package/dist/shared/provider-capabilities.d.ts +2 -0
  34. package/dist/shared/provider-capabilities.js +9 -0
  35. package/dist/version.d.ts +1 -1
  36. package/dist/version.js +1 -1
  37. package/dist/worktree/wip-git.d.ts +16 -0
  38. package/dist/worktree/wip-git.js +44 -1
  39. package/dist/worktree/wip-refs.d.ts +8 -0
  40. package/dist/worktree/wip-refs.js +23 -0
  41. package/dist/worktree/wip-restore.d.ts +5 -0
  42. package/dist/worktree/wip-restore.js +47 -3
  43. package/dist/worktree/worktree-wip-events.d.ts +2 -0
  44. package/dist/worktree/worktree-wip-events.js +34 -1
  45. package/dist/worktree/worktree-wip.d.ts +6 -0
  46. package/dist/worktree/worktree-wip.js +11 -1
  47. package/dist/worktree/worktree.service.d.ts +1 -1
  48. package/dist/worktree/worktree.service.js +4 -3
  49. package/dist/worktree/worktree.types.d.ts +5 -0
  50. package/package.json +1 -1
@@ -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 {
@@ -280,6 +281,10 @@ export class BridgeSessionService {
280
281
  if (worktree.dependencyWarm) {
281
282
  await emitDependencyWarmEvents(worktree.dependencyWarm, emit);
282
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;
283
288
  if (dispatch.sandbox?.executionMode === "host" && this.hostRuntime) {
284
289
  hostLease = await this.hostRuntime.start(dispatch, worktree.worktreePath, signal, async (checkpoint) => {
285
290
  const observation = waitObservation(checkpoint.code);
@@ -310,26 +315,7 @@ export class BridgeSessionService {
310
315
  remediation: "Enable Run in Docker in Project Settings.",
311
316
  }),
312
317
  });
313
- const unconfiguredPortCount = hostLease.lease.resources.ports.length;
314
- hostLease = await this.hostRuntime.startConfiguredProject(dispatch.sandbox.dispatchAttemptId, dispatch.lease.fencingToken, signal, async (checkpoint) => {
315
- await emitLifecycle({
316
- role: "runner",
317
- kind: "checkpoint",
318
- content: checkpoint.message,
319
- eventType: checkpoint.code,
320
- data: checkpoint.data ? JSON.stringify(checkpoint.data) : undefined,
321
- });
322
- });
323
- if (hostLease.lease.resources.ports.length > unconfiguredPortCount) {
324
- const assigned = hostLease.lease.resources.ports.at(-1);
325
- await emitLifecycle({
326
- role: "runner",
327
- kind: "checkpoint",
328
- content: `Verified supervised project runtime ${assigned.name} on ${assigned.hostIp}:${assigned.hostPort}.`,
329
- eventType: "host_runtime_project_ready",
330
- data: JSON.stringify(hostRuntimeEventResources(hostLease.lease, hostLease.runtimeContract, hostLease.executionClass)),
331
- });
332
- }
318
+ ({ hostLease, deferred: projectStartDeferred } = await startOrDeferConfiguredProject(this.hostRuntime, hostLease, dispatch, reapplyConflicts, signal, emitLifecycle));
333
319
  }
334
320
  // The stack was built and launched from this workspace state. Pre-publication
335
321
  // validation restarts it when the provider has changed the source since.
@@ -346,31 +332,29 @@ export class BridgeSessionService {
346
332
  .catch(() => null);
347
333
  // Set while the stack may not match the workspace: a failed restart is retried on the next pass.
348
334
  let restartPending = false;
335
+ // Set until the deferred first start (re-apply conflicts) succeeds: the stack has never run.
336
+ let startDeferred = projectStartDeferred;
349
337
  refreshRuntimeEnvironment = async (refreshSignal) => {
350
338
  // A late violation stopped the stack: fail this validation pass rather than run it against closed ports.
351
339
  this.throwIfAbortedOrIsolationViolated(undefined, dispatch, hostLease);
352
340
  const current = await this.workspaceFingerprint(worktreePath).catch(() => null);
353
- if (!restartPending && sameWorkspaceRuntimeFingerprint(launchFingerprint, current))
341
+ if (!restartPending && !startDeferred && sameWorkspaceRuntimeFingerprint(launchFingerprint, current))
354
342
  return null;
355
343
  // Every cause that applies is reported; `reason` is the first of them. Changes are named
356
344
  // only when both states were read: an unreadable baseline is not a workspace change.
357
345
  const comparable = launchFingerprint !== null && current !== null;
358
346
  const changes = comparable ? workspaceRuntimeFingerprintChanges(launchFingerprint, current) : [];
359
347
  const causes = [
348
+ ...(startDeferred ? ["deferred_start"] : []),
360
349
  ...(restartPending ? ["previous_restart_incomplete"] : []),
361
350
  ...(comparable ? [] : ["fingerprint_unavailable"]),
362
351
  ...(changes.length > 0 ? ["workspace_changed"] : []),
363
352
  ];
364
353
  const reason = causes[0] ?? "workspace_changed";
365
- const changeText = changes.length > 0 ? ` The workspace also changed since launch (${changes.join(", ")}).` : "";
366
354
  await emitLifecycle({
367
355
  role: "runner",
368
356
  kind: "checkpoint",
369
- content: reason === "workspace_changed"
370
- ? `The workspace changed since the attempt runtime stack was launched (${changes.join(", ")}); restarting it so validation runs against the current source.`
371
- : reason === "previous_restart_incomplete"
372
- ? `The previous attempt runtime restart did not complete; restarting it again so validation runs against the current source.${changeText}`
373
- : `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),
374
358
  eventType: "host_runtime_restart_started",
375
359
  data: JSON.stringify({
376
360
  reason,
@@ -409,6 +393,7 @@ export class BridgeSessionService {
409
393
  // baseline never matches, so every later pass would restart and rotate ports again.
410
394
  launchFingerprint = await this.workspaceFingerprint(worktreePath).catch(() => current);
411
395
  restartPending = false;
396
+ startDeferred = false;
412
397
  await emitLifecycle({
413
398
  role: "runner",
414
399
  kind: "checkpoint",
@@ -419,7 +404,7 @@ export class BridgeSessionService {
419
404
  return { environment: restarted.environment, reason, changes };
420
405
  };
421
406
  }
422
- providerDispatch = withMaterializedManagedQaTarget(providerDispatch, hostLease);
407
+ providerDispatch = withMaterializedManagedQaTarget(providerDispatch, hostLease, projectStartDeferred);
423
408
  const providerEnvironment = {
424
409
  runtimeEnvironment: hostLease?.environment,
425
410
  // Only the completion MCP server gets these: its managed commands share the host ledger.
@@ -469,6 +454,8 @@ export class BridgeSessionService {
469
454
  ...(refreshRuntimeEnvironment && hostLease
470
455
  ? { refreshRuntimeEnvironment, runtimeStackEnvironmentKeys: hostRuntimeStackEnvironmentKeys(hostLease.runtimeContract) }
471
456
  : {}),
457
+ reapplyConflicts,
458
+ projectStartDeferred,
472
459
  emit,
473
460
  signal
474
461
  };
@@ -722,43 +709,6 @@ function assertReadinessProbeStartupBudget(expiresAt) {
722
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.");
723
710
  }
724
711
  }
725
- function managedQaLaunchTarget(runtimeContract) {
726
- const playwright = runtimeContract.contract.runtime.playwright;
727
- if (!playwright)
728
- return null;
729
- const port = runtimeContract.contract.runtime.ports.find(candidate => candidate.name === playwright.baseUrlPort);
730
- return port?.launch && port.baseUrlEnv && port.format
731
- ? { managedRuntimePort: port.name, routes: ["/"] }
732
- : null;
733
- }
734
- function withMaterializedManagedQaTarget(dispatch, hostLease) {
735
- const target = dispatch.qaBrowser?.launchTarget;
736
- const portName = target?.managed_runtime_port?.trim().toLowerCase();
737
- if (!target || !portName)
738
- return dispatch;
739
- if (!hostLease) {
740
- throw new Error("qa_managed_runtime_unavailable: Browser QA requires the verified managed host runtime selected during readiness.");
741
- }
742
- const normalizedName = portName.toUpperCase().replaceAll(/[^A-Z0-9]/gu, "_");
743
- const url = hostLease.environment[`FORGE_${normalizedName}_URL`];
744
- if (!url) {
745
- throw new Error(`qa_managed_runtime_unavailable: verified runtime port '${portName}' was not launched for this attempt.`);
746
- }
747
- return {
748
- ...dispatch,
749
- qaBrowser: dispatch.qaBrowser ? {
750
- ...dispatch.qaBrowser,
751
- launchTarget: {
752
- ...target,
753
- url: target.url ?? url,
754
- ready_url: target.ready_url ?? url,
755
- notes: [target.notes, "Forge launched and verified this URL inside the current fenced attempt."]
756
- .filter(Boolean)
757
- .join(" "),
758
- },
759
- } : dispatch.qaBrowser,
760
- };
761
- }
762
712
  function probeFailureCode(error) {
763
713
  const message = error instanceof Error ? error.message : String(error);
764
714
  const candidate = message.split(":", 1)[0]?.trim().toLowerCase() ?? "";
@@ -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.1a5cf93b48a1";
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.1a5cf93b48a1";
1
+ export const forgeBridgeVersion = "0.2.1-dev.573a8a5fa582";
@@ -35,6 +35,22 @@ export declare function gitPath(git: WipGit, cwd: string, name: string): Promise
35
35
  export declare function partialRestoreMarkerPath(git: WipGit, cwd: string): Promise<string>;
36
36
  export declare function hasPartialRestoreMarker(git: WipGit, cwd: string): Promise<boolean>;
37
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>;
38
54
  /** Writes the re-apply conflict record (wip-refs.ts), or removes it when there are no paths. */
39
55
  export declare function writeReapplyConflictRecord(git: WipGit, cwd: string, paths: readonly string[]): Promise<void>;
40
56
  /** A private directory for throwaway index files, removed by the caller. */
@@ -4,7 +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 { parseReapplyConflictRecord, wipReapplyConflictRecordName } from "./wip-refs.js";
7
+ import { hasConflictMarkerLines, parseReapplyConflictRecord, wipReapplyConflictRecordName } from "./wip-refs.js";
8
8
  // Git plumbing shared by WIP snapshot and restore. Every command can carry extra environment
9
9
  // (a temporary index, or GIT_DIR/GIT_WORK_TREE for an orphaned checkout) without touching the
10
10
  // worktree's own index, HEAD or config.
@@ -118,6 +118,49 @@ export async function hasPartialRestoreMarker(git, cwd) {
118
118
  export async function readReapplyConflictRecord(git, cwd) {
119
119
  return parseReapplyConflictRecord(await readOptionalFile(await gitPath(git, cwd, wipReapplyConflictRecordName)));
120
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
+ }
121
164
  /** Writes the re-apply conflict record (wip-refs.ts), or removes it when there are no paths. */
122
165
  export async function writeReapplyConflictRecord(git, cwd, paths) {
123
166
  const record = await gitPath(git, cwd, wipReapplyConflictRecordName);
@@ -9,6 +9,14 @@ export declare const wipMetadataSchema = "forge.wip.v1";
9
9
  */
10
10
  export declare const wipReapplyConflictRecordName = "forge-wip-reapply-conflicts";
11
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;
12
20
  /** The attempt of a snapshot taken without a Forge-issued attempt number. */
13
21
  export declare const unorderedWipAttempt = 0;
14
22
  /** Why a snapshot was taken. Session reasons name the session; the others are guards. */
@@ -40,6 +40,29 @@ export const wipReapplyConflictRecordName = "forge-wip-reapply-conflicts";
40
40
  export function parseReapplyConflictRecord(content) {
41
41
  return content ? [...new Set(content.split("\0").filter(Boolean))].sort() : [];
42
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
+ }
43
66
  /** The attempt of a snapshot taken without a Forge-issued attempt number. */
44
67
  export const unorderedWipAttempt = 0;
45
68
  const maxWipAttempt = 9_999_999_999;
@@ -17,6 +17,11 @@ export type WipRestoreOutcome = {
17
17
  readonly mergeInProgress: boolean;
18
18
  /** Set when the branch had moved and the snapshot was re-applied onto its new HEAD with a 3-way merge. */
19
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[];
20
25
  } | {
21
26
  readonly status: "not_restored";
22
27
  readonly ref: string;
@@ -1,8 +1,8 @@
1
1
  import { randomUUID } from "node:crypto";
2
2
  import fs from "node:fs/promises";
3
3
  import path from "node:path";
4
- import { baseTrackedForgePaths, gitPath, isWipExcludedPath, makeWipTempDir, partialRestoreMarkerPath, splitNul, WipGit, writeReapplyConflictRecord, } from "./wip-git.js";
5
- import { commitMessageOf, issuedWipAttempt, parseWipCommitMessage, wipRefAttempt, wipRefPrefix, wipRefRoot, } from "./wip-refs.js";
4
+ import { baseTrackedForgePaths, gitPath, isWipExcludedPath, makeWipTempDir, partialRestoreMarkerPath, readOptionalFile, splitNul, WipGit, writeReapplyConflictRecord, } from "./wip-git.js";
5
+ import { commitMessageOf, hasConflictMarkerLines, hasNewConflictBlocks, issuedWipAttempt, parseWipCommitMessage, wipRefAttempt, wipRefPrefix, wipRefRoot, } from "./wip-refs.js";
6
6
  export async function restoreLatestWip(request) {
7
7
  const git = new WipGit(request.processRunner);
8
8
  let candidates;
@@ -45,7 +45,8 @@ export async function restoreLatestWip(request) {
45
45
  ? await applyReapply(git, request.worktreePath, currentHead, plan)
46
46
  : await applySnapshot(git, request.worktreePath, newest);
47
47
  // Conflicts with no MERGE_HEAD to show them: this re-apply's, and any the snapshot carried.
48
- await writeReapplyConflictRecord(git, request.worktreePath, [...newest.metadata.reapplyConflicts, ...(plan?.unmerged ?? []).map(entry => entry.path)]);
48
+ const reapplyConflicts = await restoredReapplyConflicts(git, request.worktreePath, newest, plan);
49
+ await writeReapplyConflictRecord(git, request.worktreePath, reapplyConflicts);
49
50
  return {
50
51
  status: "restored",
51
52
  ref: newest.ref,
@@ -57,6 +58,7 @@ export async function restoreLatestWip(request) {
57
58
  reapplied: plan
58
59
  ? { snapshotBaseHead: newest.metadata.baseHead, conflictedPaths: [...new Set(plan.unmerged.map(entry => entry.path))].sort() }
59
60
  : null,
61
+ reapplyConflicts,
60
62
  };
61
63
  }
62
64
  catch (error) {
@@ -148,6 +150,48 @@ async function isCleanWorktree(git, worktreePath) {
148
150
  const status = splitNul(await git.run(worktreePath, ["status", "--porcelain=v1", "-z", "--untracked-files=all", "--no-renames"]));
149
151
  return status.every(entry => isWipExcludedPath(entry.slice(3), forgePaths));
150
152
  }
153
+ /**
154
+ * The re-apply conflicts the restored worktree holds: the snapshot's record, and this re-apply's
155
+ * conflicts. A snapshot taken outside a merge can only hold conflict stages or markers that an
156
+ * earlier re-apply left (the agent never got to resolve them, as when a prepare step failed before
157
+ * it started), so its stages count too. One with no record and no stages (taken before snapshots
158
+ * carried the record), restored as it was or re-applied across a move, counts the paths whose
159
+ * snapshot version added conflict blocks its base did not have and whose restored file still has
160
+ * markers: Git merges marker text as ordinary content, so a re-apply can carry them over cleanly.
161
+ */
162
+ async function restoredReapplyConflicts(git, worktreePath, candidate, plan) {
163
+ const { metadata } = candidate;
164
+ const paths = new Set([...metadata.reapplyConflicts, ...(plan?.unmerged ?? []).map(entry => entry.path)]);
165
+ if (metadata.mergeHead)
166
+ return [...paths].sort();
167
+ if (!plan)
168
+ for (const entry of metadata.unmerged)
169
+ paths.add(entry.path);
170
+ if (metadata.reapplyConflicts.length === 0 && metadata.unmerged.length === 0) {
171
+ for (const filePath of await newConflictMarkerPaths(git, worktreePath, candidate))
172
+ paths.add(filePath);
173
+ }
174
+ return [...paths].sort();
175
+ }
176
+ /** Paths whose snapshot version added conflict blocks to its base version, still marked in the worktree. */
177
+ async function newConflictMarkerPaths(git, worktreePath, candidate) {
178
+ const { baseHead } = candidate.metadata;
179
+ const changes = await snapshotChanges(git, worktreePath, baseHead, candidate.commitSha);
180
+ const found = [];
181
+ for (const change of changes.filter(entry => entry.status !== "D")) {
182
+ const saved = await git.tryRun(worktreePath, ["cat-file", "blob", `${candidate.commitSha}:${change.path}`]);
183
+ if (saved === null || !hasConflictMarkerLines(saved))
184
+ continue;
185
+ const base = await git.tryRun(worktreePath, ["cat-file", "blob", `${baseHead}:${change.path}`]);
186
+ if (!hasNewConflictBlocks(saved, base))
187
+ continue;
188
+ // Only an absent file has no markers; any other read failure fails the restore (rolled back).
189
+ const restored = await readOptionalFile(path.join(worktreePath, change.path));
190
+ if (restored !== null && hasConflictMarkerLines(restored))
191
+ found.push(change.path);
192
+ }
193
+ return found;
194
+ }
151
195
  /** Writes the snapshot's files and index (and merge state) onto the clean worktree. */
152
196
  async function applySnapshot(git, worktreePath, candidate) {
153
197
  const { commitSha, metadata } = candidate;
@@ -15,4 +15,6 @@ export declare function sessionWipOutcome(signal: AbortSignal | undefined, event
15
15
  * reported as a cleanup failure.
16
16
  */
17
17
  export declare function settleWorktree(worktrees: WorktreeService, worktree: WorktreeHandle, outcome: WipSessionOutcome, signal: AbortSignal | undefined, emit: Emit): Promise<void>;
18
+ /** The checkpoint for a project start held back until the agent resolves the re-apply conflicts. */
19
+ export declare function deferredProjectStartEvent(paths: readonly string[]): RunnerDispatchEvent;
18
20
  export {};
@@ -8,7 +8,8 @@ export async function emitWipRestoreEvent(worktree, emit) {
8
8
  }
9
9
  else if (outcome.status === "restored") {
10
10
  await emit(checkpoint("worktree_wip_restored", `Restored uncommitted work saved in ${outcome.ref}${outcome.sourceSessionId ? ` by session ${outcome.sourceSessionId}` : ""} `
11
- + `(${outcome.changedPaths} path(s)${outcome.mergeInProgress ? ", with its merge still in progress" : ""}) onto ${worktree.branchName} before the provider started.`, outcome));
11
+ + `(${outcome.changedPaths} path(s)${outcome.mergeInProgress ? ", with its merge still in progress" : ""}) onto ${worktree.branchName} before the provider started.`
12
+ + carriedConflictsText(outcome.reapplyConflicts), outcome));
12
13
  }
13
14
  else if (outcome.status === "not_restored") {
14
15
  await emit(checkpoint("worktree_wip_not_restored", `Did not restore the uncommitted work saved in ${outcome.ref}: ${outcome.reason === "branch_moved" ? "the story branch has moved since it was saved" : "it could not be applied"}. `
@@ -35,6 +36,14 @@ function reappliedSummary(branchName, outcome, reapplied) {
35
36
  + `Forge will not publish them unresolved, and the ref is kept on origin.`;
36
37
  }
37
38
  const maxListedConflicts = 20;
39
+ /** For a snapshot restored as it was: the unresolved conflicts an earlier re-apply left in it. */
40
+ function carriedConflictsText(paths) {
41
+ if (paths.length === 0)
42
+ return "";
43
+ const more = paths.length > maxListedConflicts ? ` and ${paths.length - maxListedConflicts} more` : "";
44
+ return ` It still holds ${paths.length} conflict(s) from an earlier re-apply for the agent to resolve: `
45
+ + `${paths.slice(0, maxListedConflicts).join(", ")}${more}.`;
46
+ }
38
47
  /** How a session ended, for the snapshot it leaves behind. */
39
48
  export function sessionWipOutcome(signal, events, succeeded) {
40
49
  if (succeeded)
@@ -113,3 +122,27 @@ function checkpoint(eventType, content, data) {
113
122
  function messageOf(error) {
114
123
  return error instanceof Error ? error.message : String(error);
115
124
  }
125
+ // A WIP re-apply across a branch move can leave conflicts for the agent to resolve (wip-restore.ts):
126
+ // unmerged paths with conflict markers, kept in the worktree's re-apply conflict record. Those
127
+ // markers break any build of the worktree, so a host-runtime project start (the ASP.NET prebuild)
128
+ // would fail in prepare, before the agent could ever resolve them; the failure would be saved into
129
+ // the next snapshot, re-applied, and fail the same way on every retry. So while recorded conflicts
130
+ // are unresolved the session does not start the project stack: the agent runs first, is told which
131
+ // paths to resolve, and pre-publication validation then starts the stack from the resolved source
132
+ // (a failure there is a repair turn, not a prepare failure). The prepared-readiness probe skips such
133
+ // a worktree too (prepared-runtime-readiness.ts), and the prompt names the paths
134
+ // (withReapplyConflictInstruction in provider-cli.prompts.ts).
135
+ /** The checkpoint for a project start held back until the agent resolves the re-apply conflicts. */
136
+ export function deferredProjectStartEvent(paths) {
137
+ const listed = paths.slice(0, maxListedConflicts).join(", ");
138
+ const more = paths.length > maxListedConflicts ? ` and ${paths.length - maxListedConflicts} more` : "";
139
+ return {
140
+ role: "runner",
141
+ kind: "checkpoint",
142
+ content: `Deferred the attempt's application stack start: ${paths.length} path(s) restored from saved work still have unresolved `
143
+ + `re-apply conflicts (${listed}${more}), which would fail its build. The agent resolves them first; Forge starts the stack `
144
+ + "before pre-publication validation.",
145
+ eventType: "host_runtime_project_start_deferred",
146
+ data: JSON.stringify({ reason: "wip_reapply_conflicts", reapply_conflicts: paths }),
147
+ };
148
+ }
@@ -28,6 +28,12 @@ export declare function restoreWorktreeWip(input: {
28
28
  readonly sessionId?: string | null;
29
29
  readonly lane: string;
30
30
  }): Promise<WipRestoreOutcome | undefined>;
31
+ /**
32
+ * The worktree's recorded WIP re-apply conflicts that still have conflict stages or markers (see
33
+ * wipReapplyConflictRecordName); [] when there are none. Throws when the record or the index cannot
34
+ * be read: an unknown conflict state is never treated as conflict-free.
35
+ */
36
+ export declare function unresolvedWorktreeReapplyConflicts(worktreePath: string): Promise<readonly string[]>;
31
37
  /**
32
38
  * Saves a worktree that is about to be deleted. Its snapshot is never applied automatically (a
33
39
  * session that ended without succeeding has already saved its own work under its id; what is
@@ -1,6 +1,6 @@
1
1
  import { liveLeaseBranches, readHostRuntimeLeases } from "../cleanup/host-runtime-ledger.js";
2
2
  import { deleteBranchIfUnused, isRuntimeReadinessBranch, sweepManagedBranches } from "../cleanup/managed-branch-sweep.js";
3
- import { WipGit } from "./wip-git.js";
3
+ import { unresolvedReapplyConflicts, WipGit } from "./wip-git.js";
4
4
  import { formatWipCommitMessage, unorderedWipAttempt, wipMetadataSchema, WipPreservationError, wipRefId, wipRefName, } from "./wip-refs.js";
5
5
  import { deleteWipRef, hasNoUnsavedWork, restoreLatestWip } from "./wip-restore.js";
6
6
  import { forgetPreservedWip, forgetPreservedWipRef, preserveWorktreeWip } from "./wip-snapshot.js";
@@ -98,6 +98,16 @@ export async function restoreWorktreeWip(input) {
98
98
  return undefined;
99
99
  return await restoreLatestWip(input);
100
100
  }
101
+ /**
102
+ * The worktree's recorded WIP re-apply conflicts that still have conflict stages or markers (see
103
+ * wipReapplyConflictRecordName); [] when there are none. Throws when the record or the index cannot
104
+ * be read: an unknown conflict state is never treated as conflict-free.
105
+ */
106
+ export async function unresolvedWorktreeReapplyConflicts(worktreePath) {
107
+ return await unresolvedReapplyConflicts(new WipGit(), worktreePath).catch((error) => {
108
+ throw new Error(`the record of conflicts from re-applied saved work could not be read: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
109
+ });
110
+ }
101
111
  /**
102
112
  * Saves a worktree that is about to be deleted. Its snapshot is never applied automatically (a
103
113
  * session that ended without succeeding has already saved its own work under its id; what is
@@ -3,7 +3,7 @@ import type { HostLoadStepGate } from "../runtime/host-load-governor.js";
3
3
  import type { WorktreeLifecycleCoordinator, WorktreeService } from "./worktree.base.js";
4
4
  import type { WipSessionOutcome, WipSettlement, WorktreeHandle, WorktreePrepareRequest } from "./worktree.types.js";
5
5
  import { type BridgeLog } from "./worktree-origin-sync.js";
6
- export { emitWipRestoreEvent, sessionWipOutcome, settleWorktree } from "./worktree-wip-events.js";
6
+ export { deferredProjectStartEvent, emitWipRestoreEvent, sessionWipOutcome, settleWorktree } from "./worktree-wip-events.js";
7
7
  export { emitWorktreePreparedEvents } from "./worktree-origin-sync.js";
8
8
  export { clearRunArtifactRoots } from "./worktree-inputs.js";
9
9
  export declare class GitWorktreeService implements WorktreeService {
@@ -6,10 +6,10 @@ import { GitClient } from "../shared/git/git.js";
6
6
  import { ensureDirectory, isSubPath, resolveExistingDirectoryPath, safeSegment } from "../shared/path/path.js";
7
7
  import { warmWorktreeDependencies } from "./dependency-warmer.js";
8
8
  import { materializeWorktreeInputs } from "./worktree-inputs.js";
9
- import { guardBranchReset, guardWorktreeRelease, guardWorktreeReset, relinkOrphanedWorktree, restoreWorktreeWip, settleSessionWip, sweepBranchesAfterRelease, worktreeReleased, } from "./worktree-wip.js";
9
+ import { guardBranchReset, guardWorktreeRelease, guardWorktreeReset, relinkOrphanedWorktree, restoreWorktreeWip, unresolvedWorktreeReapplyConflicts, settleSessionWip, sweepBranchesAfterRelease, worktreeReleased, } from "./worktree-wip.js";
10
10
  import { defaultWorktreeCoordinatorStateRoot, managedRepoRoot, resolveManagedWorktreeRoot, } from "./worktree-paths.js";
11
11
  import { describeNewWorktreeStart, refuseStaleFallbackAfterFetchFailure, syncReusedWorktreeToOrigin, writeBridgeLog, } from "./worktree-origin-sync.js";
12
- export { emitWipRestoreEvent, sessionWipOutcome, settleWorktree } from "./worktree-wip-events.js";
12
+ export { deferredProjectStartEvent, emitWipRestoreEvent, sessionWipOutcome, settleWorktree } from "./worktree-wip-events.js";
13
13
  export { emitWorktreePreparedEvents } from "./worktree-origin-sync.js";
14
14
  export { clearRunArtifactRoots } from "./worktree-inputs.js";
15
15
  // Bounds the branch sweep that runs after each release, so one release never holds the repository lock long.
@@ -130,7 +130,8 @@ export class GitWorktreeService {
130
130
  /** Restores the story's saved WIP (still under the repository lock, before the provider starts). */
131
131
  async withRestoredWip(request, repoPath, branchName, worktreePath, originSync) {
132
132
  const wipRestore = await restoreWorktreeWip({ worktreePath, repoPath, branchName, sessionId: request.sessionId, lane: request.lane });
133
- return { worktreePath, ...(wipRestore ? { wipRestore } : {}), ...(originSync ? { originSync } : {}) };
133
+ const reapplyConflicts = await unresolvedWorktreeReapplyConflicts(worktreePath);
134
+ return { worktreePath, reapplyConflicts, ...(wipRestore ? { wipRestore } : {}), ...(originSync ? { originSync } : {}) };
134
135
  }
135
136
  /** Creates the lease's worktree; see describeNewWorktreeStart for what it reports. */
136
137
  async addWorktree(request, repoPath, branchName, worktreePath, baseStartPoint) {
@@ -51,6 +51,11 @@ export interface WorktreeHandle {
51
51
  readonly wipAttempt?: number | null;
52
52
  /** What happened to the story's saved WIP when this worktree was prepared. */
53
53
  readonly wipRestore?: WipRestoreOutcome;
54
+ /**
55
+ * Recorded WIP re-apply conflicts the worktree still has (unresolvedWorktreeReapplyConflicts); the
56
+ * session defers the project start on them. Prepare fails when they cannot be read.
57
+ */
58
+ readonly reapplyConflicts?: readonly string[];
54
59
  /** Set when prepare moved a stale local branch or reused worktree up to origin's head. */
55
60
  readonly originSync?: OriginSync;
56
61
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@loucompanion/forge-bridge",
3
- "version": "0.2.1-dev.1a5cf93b48a1",
3
+ "version": "0.2.1-dev.573a8a5fa582",
4
4
  "description": "Forge runner bridge CLI for connecting local developer machines to Forge dispatch.",
5
5
  "license": "UNLICENSED",
6
6
  "type": "module",