@loucompanion/forge-bridge 0.2.1-dev.4f11ffc822f9 → 0.2.1-dev.7171bf414613

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 (152) hide show
  1. package/README.md +41 -3
  2. package/dist/bridge/bridge-state-io.d.ts +6 -2
  3. package/dist/bridge/bridge-state-io.js +22 -4
  4. package/dist/bridge/bridge.service.d.ts +10 -0
  5. package/dist/bridge/bridge.service.js +63 -101
  6. package/dist/bridge/bridge.types.d.ts +16 -0
  7. package/dist/bridge/bridge.types.js +2 -1
  8. package/dist/bridge/default-session-service.d.ts +13 -0
  9. package/dist/bridge/default-session-service.js +22 -0
  10. package/dist/bridge/dispatch-offer-policy.d.ts +22 -0
  11. package/dist/bridge/dispatch-offer-policy.js +58 -0
  12. package/dist/bridge/runner-host-capabilities.js +14 -1
  13. package/dist/bridge/windows-bash-resolution.d.ts +31 -0
  14. package/dist/bridge/windows-bash-resolution.js +153 -0
  15. package/dist/cleanup/cleanup-wip.js +3 -3
  16. package/dist/cleanup/forge-owned-paths.d.ts +2 -0
  17. package/dist/cleanup/forge-owned-paths.js +9 -0
  18. package/dist/cli/cli.help.js +1 -1
  19. package/dist/cli/cli.service.js +11 -43
  20. package/dist/cli/local-config.d.ts +12 -1
  21. package/dist/cli/local-config.js +35 -1
  22. package/dist/cli/provider-cli-advertising.d.ts +24 -0
  23. package/dist/cli/provider-cli-advertising.js +88 -0
  24. package/dist/runtime/host-load-admission.d.ts +5 -0
  25. package/dist/runtime/host-load-capacity.d.ts +198 -0
  26. package/dist/runtime/host-load-capacity.js +353 -0
  27. package/dist/runtime/host-load-child-environment.d.ts +13 -0
  28. package/dist/runtime/host-load-child-environment.js +35 -1
  29. package/dist/runtime/host-load-governor-config.d.ts +33 -3
  30. package/dist/runtime/host-load-governor-config.js +24 -3
  31. package/dist/runtime/host-load-governor.d.ts +89 -2
  32. package/dist/runtime/host-load-governor.js +217 -18
  33. package/dist/runtime/host-load-live-test-slots.d.ts +61 -0
  34. package/dist/runtime/host-load-live-test-slots.js +193 -0
  35. package/dist/runtime/host-load-sampler.d.ts +17 -0
  36. package/dist/runtime/host-load-sampler.js +24 -0
  37. package/dist/runtime/host-load-step-run.d.ts +37 -3
  38. package/dist/runtime/host-load-step-run.js +63 -7
  39. package/dist/runtime/host-load-test-slot.d.ts +3 -0
  40. package/dist/runtime/host-load-test-slot.js +26 -7
  41. package/dist/runtime/host-runtime-contract.js +6 -4
  42. package/dist/runtime/prepared-runtime-readiness.d.ts +12 -2
  43. package/dist/runtime/prepared-runtime-readiness.js +35 -11
  44. package/dist/sandbox/runtime.d.ts +1 -2
  45. package/dist/sandbox/runtime.js +8 -14
  46. package/dist/sandbox/sandbox-input.d.ts +22 -0
  47. package/dist/sandbox/sandbox-input.js +49 -0
  48. package/dist/sandbox/workspace.service.js +15 -2
  49. package/dist/session/managed-attempt-tools.js +6 -29
  50. package/dist/session/managed-build-receipt.d.ts +3 -1
  51. package/dist/session/managed-build-receipt.js +5 -2
  52. package/dist/session/managed-command-environment.d.ts +8 -0
  53. package/dist/session/managed-command-environment.js +28 -0
  54. package/dist/session/managed-command-host-load.d.ts +10 -5
  55. package/dist/session/managed-command-host-load.js +18 -14
  56. package/dist/session/phase-completion.artifact-bundle.d.ts +20 -0
  57. package/dist/session/phase-completion.artifact-bundle.js +167 -0
  58. package/dist/session/phase-completion.artifacts.d.ts +2 -17
  59. package/dist/session/phase-completion.artifacts.js +63 -165
  60. package/dist/session/phase-completion.d.ts +25 -2
  61. package/dist/session/phase-completion.helpers.js +5 -53
  62. package/dist/session/phase-completion.js +15 -32
  63. package/dist/session/phase-completion.mcp-args.js +69 -2
  64. package/dist/session/phase-completion.phase-aliases.d.ts +5 -0
  65. package/dist/session/phase-completion.phase-aliases.js +43 -0
  66. package/dist/session/phase-completion.pr-review-schema.d.ts +1 -0
  67. package/dist/session/phase-completion.pr-review-schema.js +75 -0
  68. package/dist/session/phase-completion.pr-review-threads.d.ts +34 -0
  69. package/dist/session/phase-completion.pr-review-threads.js +90 -0
  70. package/dist/session/phase-completion.pr-review-validation.d.ts +11 -0
  71. package/dist/session/phase-completion.pr-review-validation.js +215 -0
  72. package/dist/session/phase-completion.pr-review.d.ts +36 -0
  73. package/dist/session/phase-completion.pr-review.js +294 -0
  74. package/dist/session/phase-completion.prompts.d.ts +1 -1
  75. package/dist/session/phase-completion.prompts.js +14 -0
  76. package/dist/session/phase-completion.runtime.js +9 -3
  77. package/dist/session/phase-completion.schemas.js +12 -2
  78. package/dist/session/phase-completion.validation.d.ts +1 -0
  79. package/dist/session/phase-completion.validation.js +9 -1
  80. package/dist/session/pr-review-diff-base.d.ts +18 -0
  81. package/dist/session/pr-review-diff-base.js +45 -0
  82. package/dist/session/pr-review-placement.d.ts +50 -0
  83. package/dist/session/pr-review-placement.js +91 -0
  84. package/dist/session/pre-publication-change-set.d.ts +62 -0
  85. package/dist/session/pre-publication-change-set.js +166 -0
  86. package/dist/session/pre-publication-host-load.js +6 -5
  87. package/dist/session/pre-publication-process.js +3 -2
  88. package/dist/session/pre-publication-validation.d.ts +2 -1
  89. package/dist/session/pre-publication-validation.js +31 -36
  90. package/dist/session/provider-cli/dispatch-target-branch.d.ts +7 -0
  91. package/dist/session/provider-cli/dispatch-target-branch.js +8 -0
  92. package/dist/session/provider-cli/pr-review-credential-isolation.d.ts +83 -0
  93. package/dist/session/provider-cli/pr-review-credential-isolation.js +144 -0
  94. package/dist/session/provider-cli/pr-review-guardrails.d.ts +70 -0
  95. package/dist/session/provider-cli/pr-review-guardrails.js +360 -0
  96. package/dist/session/provider-cli/pr-review-prompt.d.ts +11 -0
  97. package/dist/session/provider-cli/pr-review-prompt.js +132 -0
  98. package/dist/session/provider-cli/pre-publication-repair.js +8 -3
  99. package/dist/session/provider-cli/provider-cli.base.d.ts +1 -0
  100. package/dist/session/provider-cli/provider-cli.deterministic.d.ts +1 -0
  101. package/dist/session/provider-cli/provider-cli.deterministic.js +5 -0
  102. package/dist/session/provider-cli/provider-cli.merge-integrity.d.ts +6 -3
  103. package/dist/session/provider-cli/provider-cli.merge-integrity.js +29 -10
  104. package/dist/session/provider-cli/provider-cli.pr-review.d.ts +23 -0
  105. package/dist/session/provider-cli/provider-cli.pr-review.js +213 -0
  106. package/dist/session/provider-cli/provider-cli.prompts.d.ts +10 -3
  107. package/dist/session/provider-cli/provider-cli.prompts.js +123 -70
  108. package/dist/session/provider-cli/provider-cli.reapply-conflicts.d.ts +10 -0
  109. package/dist/session/provider-cli/provider-cli.reapply-conflicts.js +37 -0
  110. package/dist/session/provider-cli/provider-cli.runtime.d.ts +7 -0
  111. package/dist/session/provider-cli/provider-cli.runtime.js +14 -0
  112. package/dist/session/provider-cli/provider-cli.service-support.d.ts +37 -0
  113. package/dist/session/provider-cli/provider-cli.service-support.js +146 -0
  114. package/dist/session/provider-cli/provider-cli.service.d.ts +11 -17
  115. package/dist/session/provider-cli/provider-cli.service.js +33 -148
  116. package/dist/session/provider-cli/provider-cli.types.d.ts +7 -2
  117. package/dist/session/sandbox-host-capacity-gate.js +29 -7
  118. package/dist/session/session-host-project.d.ts +22 -0
  119. package/dist/session/session-host-project.js +98 -0
  120. package/dist/session/session.parse-helpers.d.ts +10 -0
  121. package/dist/session/session.parse-helpers.js +84 -0
  122. package/dist/session/session.runtime-refresh.d.ts +46 -0
  123. package/dist/session/session.runtime-refresh.js +116 -0
  124. package/dist/session/session.service.d.ts +2 -1
  125. package/dist/session/session.service.js +57 -158
  126. package/dist/session/session.types.d.ts +5 -0
  127. package/dist/session/session.types.js +8 -78
  128. package/dist/session/session.types.pr-review.d.ts +59 -0
  129. package/dist/session/session.types.pr-review.js +53 -0
  130. package/dist/shared/provider-capabilities.d.ts +2 -0
  131. package/dist/shared/provider-capabilities.js +9 -0
  132. package/dist/version.d.ts +1 -1
  133. package/dist/version.js +1 -1
  134. package/dist/worktree/artifact-injector.js +24 -0
  135. package/dist/worktree/wip-git.d.ts +25 -0
  136. package/dist/worktree/wip-git.js +64 -4
  137. package/dist/worktree/wip-refs.d.ts +23 -0
  138. package/dist/worktree/wip-refs.js +52 -2
  139. package/dist/worktree/wip-restore.d.ts +13 -0
  140. package/dist/worktree/wip-restore.js +159 -25
  141. package/dist/worktree/wip-snapshot.d.ts +5 -2
  142. package/dist/worktree/wip-snapshot.js +15 -13
  143. package/dist/worktree/worktree-origin-sync.d.ts +1 -0
  144. package/dist/worktree/worktree-origin-sync.js +1 -0
  145. package/dist/worktree/worktree-wip-events.d.ts +2 -0
  146. package/dist/worktree/worktree-wip-events.js +53 -3
  147. package/dist/worktree/worktree-wip.d.ts +7 -0
  148. package/dist/worktree/worktree-wip.js +17 -2
  149. package/dist/worktree/worktree.service.d.ts +23 -1
  150. package/dist/worktree/worktree.service.js +122 -15
  151. package/dist/worktree/worktree.types.d.ts +16 -0
  152. package/package.json +1 -1
@@ -0,0 +1,59 @@
1
+ export interface DispatchPrReviewContext {
2
+ /** The pull request head commit the worktree is checked out at, detached. */
3
+ readonly headSha: string;
4
+ /** The commit the review diffs against: the merge base of the base branch tip and the head, once the bridge resolved it. */
5
+ readonly baseSha: string;
6
+ /** The base branch tip the provider reported, when the bridge replaced it with the merge base. */
7
+ readonly baseTipSha?: string;
8
+ readonly reviewKind: string;
9
+ /** The approved Story spec text, written verbatim to the Story's spec.md. */
10
+ readonly storySpec: string;
11
+ readonly pullRequestNumber: number;
12
+ readonly title: string;
13
+ /** The pull request description. Author-controlled text: treat it as untrusted. */
14
+ readonly description: string;
15
+ readonly baseBranch: string;
16
+ readonly storyWorkItemId: string | null;
17
+ readonly storySpecPath: string | null;
18
+ readonly priorReviews: readonly DispatchPrReviewPriorReview[];
19
+ readonly priorThreads: readonly DispatchPrReviewThread[];
20
+ }
21
+ export interface DispatchPrReviewPriorReview {
22
+ readonly cycleRunId: string;
23
+ readonly sessionId: string;
24
+ readonly headSha: string;
25
+ readonly status: string;
26
+ readonly completedAt: string | null;
27
+ }
28
+ export interface DispatchPrReviewThread {
29
+ readonly threadId: string;
30
+ readonly path: string | null;
31
+ readonly line: number | null;
32
+ readonly startLine: number | null;
33
+ readonly side: string | null;
34
+ /** The head the thread was raised on. */
35
+ readonly reviewedHeadSha: string | null;
36
+ readonly isResolved: boolean;
37
+ readonly isOutdated: boolean;
38
+ /**
39
+ * The status the latest posted Forge review that reported the thread gave it (resolved_since_last_review,
40
+ * still_open or reintroduced); null when no posted Forge review reported it, such as one the last review raised.
41
+ */
42
+ readonly previousReviewStatus?: string | null;
43
+ /**
44
+ * Forge set this, not the reviewer: the thread's first comment is a finding an earlier Forge review posted from the
45
+ * account Forge posts with. Only such a thread holds a new finding at its lines back as a repeat; a thread a person,
46
+ * Copilot or another bot raised does not.
47
+ */
48
+ readonly raisedByForge?: boolean;
49
+ readonly comments: readonly DispatchPrReviewThreadComment[];
50
+ }
51
+ export interface DispatchPrReviewThreadComment {
52
+ readonly id: string;
53
+ readonly author: string | null;
54
+ /** Comment text. Author-controlled: treat it as untrusted. */
55
+ readonly body: string;
56
+ readonly url: string | null;
57
+ readonly createdAt: string | null;
58
+ }
59
+ export declare function parsePrReview(value: unknown): DispatchPrReviewContext | null;
@@ -0,0 +1,53 @@
1
+ import { asObject, optionalBoolean, optionalNonNegativeInteger, optionalObjectArray, optionalString, requiredString } from "./session.parse-helpers.js";
2
+ export function parsePrReview(value) {
3
+ if (value === undefined || value === null) {
4
+ return null;
5
+ }
6
+ const prReview = asObject(value, "prReview");
7
+ return {
8
+ headSha: requiredString(prReview, "headSha"),
9
+ baseSha: optionalString(prReview, "baseSha") ?? "",
10
+ ...(optionalString(prReview, "baseTipSha") ? { baseTipSha: optionalString(prReview, "baseTipSha") } : {}),
11
+ reviewKind: optionalString(prReview, "reviewKind") ?? "initial",
12
+ storySpec: optionalString(prReview, "storySpec") ?? "",
13
+ pullRequestNumber: optionalNonNegativeInteger(prReview, "pullRequestNumber") ?? 0,
14
+ title: optionalString(prReview, "title") ?? "",
15
+ description: optionalString(prReview, "description") ?? "",
16
+ baseBranch: optionalString(prReview, "baseBranch") ?? "",
17
+ storyWorkItemId: optionalString(prReview, "storyWorkItemId"),
18
+ storySpecPath: optionalString(prReview, "storySpecPath"),
19
+ priorReviews: optionalObjectArray(prReview, "priorReviews").map(parsePrReviewPriorReview),
20
+ priorThreads: optionalObjectArray(prReview, "priorThreads").map(parsePrReviewThread)
21
+ };
22
+ }
23
+ function parsePrReviewPriorReview(review) {
24
+ return {
25
+ cycleRunId: optionalString(review, "cycleRunId") ?? "",
26
+ sessionId: optionalString(review, "sessionId") ?? "",
27
+ headSha: requiredString(review, "headSha"),
28
+ status: optionalString(review, "status") ?? "",
29
+ completedAt: optionalString(review, "completedAt")
30
+ };
31
+ }
32
+ function parsePrReviewThread(thread) {
33
+ return {
34
+ // The server serializes the id as threadId; id is accepted for the review-finding shape.
35
+ threadId: optionalString(thread, "threadId") || requiredString(thread, "id"),
36
+ path: optionalString(thread, "path"),
37
+ line: optionalNonNegativeInteger(thread, "line"),
38
+ startLine: optionalNonNegativeInteger(thread, "startLine"),
39
+ side: optionalString(thread, "side"),
40
+ reviewedHeadSha: optionalString(thread, "reviewedHeadSha"),
41
+ isResolved: optionalBoolean(thread, "isResolved") ?? false,
42
+ isOutdated: optionalBoolean(thread, "isOutdated") ?? false,
43
+ previousReviewStatus: optionalString(thread, "previousReviewStatus"),
44
+ raisedByForge: optionalBoolean(thread, "raisedByForge") ?? false,
45
+ comments: optionalObjectArray(thread, "comments").map((comment) => ({
46
+ id: optionalString(comment, "id") ?? "",
47
+ author: optionalString(comment, "author"),
48
+ body: optionalString(comment, "body") ?? "",
49
+ url: optionalString(comment, "url"),
50
+ createdAt: optionalString(comment, "createdAt")
51
+ }))
52
+ };
53
+ }
@@ -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.7171bf414613";
package/dist/version.js CHANGED
@@ -1 +1 @@
1
- export const forgeBridgeVersion = "0.2.1-dev.4f11ffc822f9";
1
+ export const forgeBridgeVersion = "0.2.1-dev.7171bf414613";
@@ -32,6 +32,7 @@ const ARCHITECT_OPERATIONAL_HOOKS = new Set([
32
32
  "architect-complete",
33
33
  "architect-revise"
34
34
  ]);
35
+ const PR_REVIEW_OPERATIONAL_SKILLS = new Set(["pr-review"]);
35
36
  const DRAFT_OPERATIONAL_SKILLS = new Set([
36
37
  "draft-intent",
37
38
  "draft-repo-context",
@@ -74,6 +75,9 @@ export function filterArtifactsForLane(artifacts, lane, phase) {
74
75
  if (normalizedLane === "architect") {
75
76
  return artifacts.filter((artifact) => shouldInjectArchitectArtifact(artifact, commandSlug));
76
77
  }
78
+ if (normalizedLane === "pr_review" || normalizedLane === "pr-review") {
79
+ return artifacts.filter((artifact) => shouldInjectPrReviewArtifact(artifact, commandSlug));
80
+ }
77
81
  if (normalizedLane === "draft") {
78
82
  return artifacts.filter((artifact) => shouldInjectDraftArtifact(artifact, commandSlug, phase));
79
83
  }
@@ -112,6 +116,9 @@ export function resolveCommandSlug(lane, phase) {
112
116
  return "debug-prompt";
113
117
  }
114
118
  const normalizedPhase = phase.trim().toLowerCase().replace(/-/g, "_");
119
+ if (normalizedLane === "pr_review" || normalizedLane === "pr-review") {
120
+ return "pr-review-prompt";
121
+ }
115
122
  if (normalizedPhase === "rework") {
116
123
  return "rework-prompt";
117
124
  }
@@ -122,6 +129,9 @@ export function resolveCommandSlug(lane, phase) {
122
129
  return "architect-prompt";
123
130
  case "qa":
124
131
  return "qa-prompt";
132
+ case "pr_review":
133
+ case "pr-review":
134
+ return "pr-review-prompt";
125
135
  default:
126
136
  return "dev-prompt";
127
137
  }
@@ -191,6 +201,20 @@ function shouldInjectArchitectArtifact(artifact, commandSlug) {
191
201
  return false;
192
202
  }
193
203
  }
204
+ function shouldInjectPrReviewArtifact(artifact, commandSlug) {
205
+ if (artifact.scope.trim().toLowerCase() !== "operational") {
206
+ return false;
207
+ }
208
+ const slug = artifact.slug.trim().toLowerCase();
209
+ switch (normalizedArtifactKind(artifact.kind)) {
210
+ case "command":
211
+ return slug === commandSlug;
212
+ case "skill":
213
+ return PR_REVIEW_OPERATIONAL_SKILLS.has(slug);
214
+ default:
215
+ return false;
216
+ }
217
+ }
194
218
  function shouldInjectDraftArtifact(artifact, commandSlug, phase) {
195
219
  if (artifact.scope.trim().toLowerCase() !== "operational") {
196
220
  return false;
@@ -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>;