@loucompanion/forge-bridge 0.1.4-dev.f22f5e3d01fe → 0.2.1-dev.0f07274d438b

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 (260) hide show
  1. package/README.md +128 -4
  2. package/dist/bridge/bridge-chat-giphy-look.d.ts +48 -0
  3. package/dist/bridge/bridge-chat-giphy-look.js +55 -0
  4. package/dist/bridge/bridge-chat-provider-command.d.ts +27 -3
  5. package/dist/bridge/bridge-chat-provider-command.js +131 -26
  6. package/dist/bridge/bridge-chat.types.d.ts +20 -0
  7. package/dist/bridge/bridge-chat.types.js +28 -1
  8. package/dist/bridge/bridge-state-file.d.ts +161 -0
  9. package/dist/bridge/bridge-state-file.js +376 -0
  10. package/dist/bridge/bridge-state-io.d.ts +15 -0
  11. package/dist/bridge/bridge-state-io.js +68 -0
  12. package/dist/bridge/bridge-state-lock.d.ts +11 -0
  13. package/dist/bridge/bridge-state-lock.js +102 -0
  14. package/dist/bridge/bridge-state-unpublished.d.ts +17 -0
  15. package/dist/bridge/bridge-state-unpublished.js +111 -0
  16. package/dist/bridge/bridge.service.d.ts +29 -12
  17. package/dist/bridge/bridge.service.js +215 -380
  18. package/dist/bridge/bridge.types.d.ts +21 -0
  19. package/dist/bridge/bridge.types.js +2 -1
  20. package/dist/bridge/default-session-service.d.ts +13 -0
  21. package/dist/bridge/default-session-service.js +22 -0
  22. package/dist/bridge/dispatch-offer-policy.d.ts +22 -0
  23. package/dist/bridge/dispatch-offer-policy.js +58 -0
  24. package/dist/bridge/in-flight-registry.d.ts +62 -0
  25. package/dist/bridge/in-flight-registry.js +207 -0
  26. package/dist/bridge/readiness-result-outbox.d.ts +5 -1
  27. package/dist/bridge/readiness-result-outbox.js +20 -0
  28. package/dist/bridge/runner-host-capabilities.js +14 -1
  29. package/dist/bridge/sandbox-resource-accounting.d.ts +16 -0
  30. package/dist/bridge/sandbox-resource-accounting.js +150 -0
  31. package/dist/bridge/windows-bash-resolution.d.ts +31 -0
  32. package/dist/bridge/windows-bash-resolution.js +153 -0
  33. package/dist/cleanup/cleanup-wip.d.ts +12 -0
  34. package/dist/cleanup/cleanup-wip.js +66 -0
  35. package/dist/cleanup/cleanup.service.d.ts +11 -1
  36. package/dist/cleanup/cleanup.service.js +80 -62
  37. package/dist/cleanup/cleanup.types.d.ts +2 -0
  38. package/dist/cleanup/forge-owned-paths.d.ts +2 -0
  39. package/dist/cleanup/forge-owned-paths.js +9 -0
  40. package/dist/cleanup/host-runtime-ledger.d.ts +2 -0
  41. package/dist/cleanup/host-runtime-ledger.js +30 -9
  42. package/dist/cli/cli.help.js +57 -13
  43. package/dist/cli/cli.service.d.ts +3 -10
  44. package/dist/cli/cli.service.js +20 -213
  45. package/dist/cli/idle-status.d.ts +84 -0
  46. package/dist/cli/idle-status.js +181 -0
  47. package/dist/cli/local-config.d.ts +14 -1
  48. package/dist/cli/local-config.js +42 -2
  49. package/dist/cli/provider-cli-advertising.d.ts +24 -0
  50. package/dist/cli/provider-cli-advertising.js +88 -0
  51. package/dist/cli/provider-cli-detection.d.ts +10 -0
  52. package/dist/cli/provider-cli-detection.js +160 -0
  53. package/dist/runtime/aspnet-runtime-prebuild.d.ts +20 -0
  54. package/dist/runtime/aspnet-runtime-prebuild.js +104 -26
  55. package/dist/runtime/attempt-database-broker.d.ts +1 -1
  56. package/dist/runtime/attempt-node-runtime-launcher.d.ts +36 -0
  57. package/dist/runtime/attempt-node-runtime-launcher.js +169 -0
  58. package/dist/runtime/attempt-process-supervisor.d.ts +2 -0
  59. package/dist/runtime/attempt-process-supervisor.js +12 -6
  60. package/dist/runtime/docker-engine-probe.d.ts +5 -0
  61. package/dist/runtime/docker-engine-probe.js +7 -0
  62. package/dist/runtime/dotnet-build-outputs.d.ts +107 -0
  63. package/dist/runtime/dotnet-build-outputs.js +402 -0
  64. package/dist/runtime/ephemeral-test-postgres-grant.d.ts +37 -0
  65. package/dist/runtime/ephemeral-test-postgres-grant.js +85 -0
  66. package/dist/runtime/ephemeral-test-postgres.d.ts +57 -0
  67. package/dist/runtime/ephemeral-test-postgres.js +303 -0
  68. package/dist/runtime/host-listener-inspector.d.ts +26 -0
  69. package/dist/runtime/host-listener-inspector.js +84 -3
  70. package/dist/runtime/host-load-admission.d.ts +5 -0
  71. package/dist/runtime/host-load-capacity.d.ts +198 -0
  72. package/dist/runtime/host-load-capacity.js +353 -0
  73. package/dist/runtime/host-load-child-environment.d.ts +13 -0
  74. package/dist/runtime/host-load-child-environment.js +35 -1
  75. package/dist/runtime/host-load-governor-config.d.ts +33 -3
  76. package/dist/runtime/host-load-governor-config.js +24 -3
  77. package/dist/runtime/host-load-governor.d.ts +91 -2
  78. package/dist/runtime/host-load-governor.js +217 -18
  79. package/dist/runtime/host-load-ledger-lock.js +6 -4
  80. package/dist/runtime/host-load-live-test-slots.d.ts +61 -0
  81. package/dist/runtime/host-load-live-test-slots.js +193 -0
  82. package/dist/runtime/host-load-runtime-settings.js +4 -2
  83. package/dist/runtime/host-load-sampler.d.ts +25 -1
  84. package/dist/runtime/host-load-sampler.js +38 -7
  85. package/dist/runtime/host-load-step-run.d.ts +37 -3
  86. package/dist/runtime/host-load-step-run.js +63 -7
  87. package/dist/runtime/host-load-test-slot.d.ts +3 -0
  88. package/dist/runtime/host-load-test-slot.js +26 -7
  89. package/dist/runtime/host-runtime-contract.d.ts +12 -0
  90. package/dist/runtime/host-runtime-contract.js +35 -5
  91. package/dist/runtime/host-runtime-lease.d.ts +28 -3
  92. package/dist/runtime/host-runtime-lease.js +140 -296
  93. package/dist/runtime/host-runtime-ledger-recovery.d.ts +20 -0
  94. package/dist/runtime/host-runtime-ledger-recovery.js +134 -0
  95. package/dist/runtime/host-runtime-promotion.d.ts +78 -2
  96. package/dist/runtime/host-runtime-promotion.js +307 -14
  97. package/dist/runtime/managed-command-teardown.js +5 -16
  98. package/dist/runtime/native-test-postgres-fallback.d.ts +51 -7
  99. package/dist/runtime/native-test-postgres-fallback.js +60 -8
  100. package/dist/runtime/prepared-runtime-identity.d.ts +4 -0
  101. package/dist/runtime/prepared-runtime-identity.js +130 -9
  102. package/dist/runtime/prepared-runtime-readiness.d.ts +23 -1
  103. package/dist/runtime/prepared-runtime-readiness.js +89 -18
  104. package/dist/runtime/runner-settings.d.ts +4 -0
  105. package/dist/runtime/runner-settings.js +22 -0
  106. package/dist/runtime/supervised-runtime-build-guard.d.ts +45 -0
  107. package/dist/runtime/supervised-runtime-build-guard.js +112 -0
  108. package/dist/sandbox/host-capacity-broker.d.ts +3 -1
  109. package/dist/sandbox/host-capacity-broker.js +4 -2
  110. package/dist/sandbox/managed-branch.d.ts +13 -0
  111. package/dist/sandbox/managed-branch.js +90 -0
  112. package/dist/sandbox/provider-auth/codex.js +11 -11
  113. package/dist/sandbox/runtime.d.ts +1 -2
  114. package/dist/sandbox/runtime.js +9 -19
  115. package/dist/sandbox/sandbox-input.d.ts +22 -0
  116. package/dist/sandbox/sandbox-input.js +49 -0
  117. package/dist/sandbox/workspace.service.js +15 -2
  118. package/dist/session/managed-attempt-tools.d.ts +0 -7
  119. package/dist/session/managed-attempt-tools.js +54 -109
  120. package/dist/session/managed-build-coordinator.d.ts +16 -0
  121. package/dist/session/managed-build-coordinator.js +10 -0
  122. package/dist/session/managed-build-receipt.d.ts +7 -0
  123. package/dist/session/managed-build-receipt.js +11 -3
  124. package/dist/session/managed-command-environment.d.ts +8 -0
  125. package/dist/session/managed-command-environment.js +28 -0
  126. package/dist/session/managed-command-host-load.d.ts +10 -5
  127. package/dist/session/managed-command-host-load.js +18 -14
  128. package/dist/session/phase-completion.artifact-bundle.d.ts +20 -0
  129. package/dist/session/phase-completion.artifact-bundle.js +167 -0
  130. package/dist/session/phase-completion.artifacts.d.ts +2 -17
  131. package/dist/session/phase-completion.artifacts.js +65 -166
  132. package/dist/session/phase-completion.d.ts +27 -2
  133. package/dist/session/phase-completion.helpers.js +5 -53
  134. package/dist/session/phase-completion.js +15 -32
  135. package/dist/session/phase-completion.mcp-args.d.ts +9 -0
  136. package/dist/session/phase-completion.mcp-args.js +195 -0
  137. package/dist/session/phase-completion.phase-aliases.d.ts +5 -0
  138. package/dist/session/phase-completion.phase-aliases.js +43 -0
  139. package/dist/session/phase-completion.pr-review-schema.d.ts +1 -0
  140. package/dist/session/phase-completion.pr-review-schema.js +75 -0
  141. package/dist/session/phase-completion.pr-review-validation.d.ts +11 -0
  142. package/dist/session/phase-completion.pr-review-validation.js +212 -0
  143. package/dist/session/phase-completion.pr-review.d.ts +36 -0
  144. package/dist/session/phase-completion.pr-review.js +294 -0
  145. package/dist/session/phase-completion.prompts.d.ts +1 -1
  146. package/dist/session/phase-completion.prompts.js +14 -0
  147. package/dist/session/phase-completion.runtime.d.ts +8 -9
  148. package/dist/session/phase-completion.runtime.js +65 -196
  149. package/dist/session/phase-completion.schemas.js +12 -2
  150. package/dist/session/phase-completion.validation.d.ts +1 -0
  151. package/dist/session/phase-completion.validation.js +9 -1
  152. package/dist/session/pr-review-diff-base.d.ts +18 -0
  153. package/dist/session/pr-review-diff-base.js +44 -0
  154. package/dist/session/pr-review-placement.d.ts +50 -0
  155. package/dist/session/pr-review-placement.js +91 -0
  156. package/dist/session/pre-publication-change-set.d.ts +62 -0
  157. package/dist/session/pre-publication-change-set.js +166 -0
  158. package/dist/session/pre-publication-host-load.js +6 -5
  159. package/dist/session/pre-publication-native-postgres.d.ts +30 -0
  160. package/dist/session/pre-publication-native-postgres.js +111 -0
  161. package/dist/session/pre-publication-process.js +13 -12
  162. package/dist/session/pre-publication-step-execution.d.ts +2 -1
  163. package/dist/session/pre-publication-step-execution.js +6 -5
  164. package/dist/session/pre-publication-validation.d.ts +9 -4
  165. package/dist/session/pre-publication-validation.js +62 -65
  166. package/dist/session/provider-cli/claude-background-work.d.ts +3 -2
  167. package/dist/session/provider-cli/claude-background-work.js +4 -3
  168. package/dist/session/provider-cli/dispatch-target-branch.d.ts +7 -0
  169. package/dist/session/provider-cli/dispatch-target-branch.js +8 -0
  170. package/dist/session/provider-cli/host-build-lock.d.ts +18 -0
  171. package/dist/session/provider-cli/host-build-lock.js +30 -0
  172. package/dist/session/provider-cli/pr-review-credential-isolation.d.ts +83 -0
  173. package/dist/session/provider-cli/pr-review-credential-isolation.js +144 -0
  174. package/dist/session/provider-cli/pr-review-guardrails.d.ts +70 -0
  175. package/dist/session/provider-cli/pr-review-guardrails.js +360 -0
  176. package/dist/session/provider-cli/pr-review-prompt.d.ts +2 -0
  177. package/dist/session/provider-cli/pr-review-prompt.js +119 -0
  178. package/dist/session/provider-cli/pre-publication-repair.d.ts +16 -0
  179. package/dist/session/provider-cli/pre-publication-repair.js +41 -3
  180. package/dist/session/provider-cli/provider-cli.base.d.ts +1 -0
  181. package/dist/session/provider-cli/provider-cli.child-environment.js +4 -2
  182. package/dist/session/provider-cli/provider-cli.deterministic.d.ts +1 -0
  183. package/dist/session/provider-cli/provider-cli.deterministic.js +5 -0
  184. package/dist/session/provider-cli/provider-cli.merge-integrity.d.ts +6 -3
  185. package/dist/session/provider-cli/provider-cli.merge-integrity.js +29 -10
  186. package/dist/session/provider-cli/provider-cli.pr-review.d.ts +23 -0
  187. package/dist/session/provider-cli/provider-cli.pr-review.js +213 -0
  188. package/dist/session/provider-cli/provider-cli.process.d.ts +2 -14
  189. package/dist/session/provider-cli/provider-cli.process.js +4 -94
  190. package/dist/session/provider-cli/provider-cli.prompts.d.ts +13 -3
  191. package/dist/session/provider-cli/provider-cli.prompts.js +137 -84
  192. package/dist/session/provider-cli/provider-cli.reapply-conflicts.d.ts +10 -0
  193. package/dist/session/provider-cli/provider-cli.reapply-conflicts.js +37 -0
  194. package/dist/session/provider-cli/provider-cli.runtime.d.ts +15 -0
  195. package/dist/session/provider-cli/provider-cli.runtime.js +37 -2
  196. package/dist/session/provider-cli/provider-cli.service-support.d.ts +37 -0
  197. package/dist/session/provider-cli/provider-cli.service-support.js +146 -0
  198. package/dist/session/provider-cli/provider-cli.service.d.ts +15 -18
  199. package/dist/session/provider-cli/provider-cli.service.js +59 -190
  200. package/dist/session/provider-cli/provider-cli.types.d.ts +7 -2
  201. package/dist/session/provider-cli/provider-cli.windows-launch.d.ts +23 -0
  202. package/dist/session/provider-cli/provider-cli.windows-launch.js +131 -0
  203. package/dist/session/provider-cli/provider-user-config-isolation.d.ts +69 -0
  204. package/dist/session/provider-cli/provider-user-config-isolation.js +164 -0
  205. package/dist/session/qa-sidecar-validation.d.ts +6 -0
  206. package/dist/session/qa-sidecar-validation.js +28 -0
  207. package/dist/session/sandbox-host-capacity-gate.d.ts +22 -1
  208. package/dist/session/sandbox-host-capacity-gate.js +63 -22
  209. package/dist/session/session-host-project.d.ts +22 -0
  210. package/dist/session/session-host-project.js +98 -0
  211. package/dist/session/session-redaction.js +31 -181
  212. package/dist/session/session.parse-helpers.d.ts +10 -0
  213. package/dist/session/session.parse-helpers.js +84 -0
  214. package/dist/session/session.runtime-refresh.d.ts +46 -0
  215. package/dist/session/session.runtime-refresh.js +116 -0
  216. package/dist/session/session.service.d.ts +8 -1
  217. package/dist/session/session.service.js +177 -239
  218. package/dist/session/session.types.d.ts +5 -0
  219. package/dist/session/session.types.js +9 -79
  220. package/dist/session/session.types.pr-review.d.ts +48 -0
  221. package/dist/session/session.types.pr-review.js +51 -0
  222. package/dist/session/sidecar-json-shape.d.ts +31 -0
  223. package/dist/session/sidecar-json-shape.js +217 -0
  224. package/dist/shared/fs/file-identity.d.ts +10 -0
  225. package/dist/shared/fs/file-identity.js +15 -0
  226. package/dist/shared/fs/replace-file.d.ts +7 -0
  227. package/dist/shared/fs/replace-file.js +33 -0
  228. package/dist/shared/process/host-process-recovery.d.ts +14 -3
  229. package/dist/shared/process/host-process-recovery.js +23 -3
  230. package/dist/shared/process/host-process-supervisor.d.ts +13 -1
  231. package/dist/shared/process/host-process-supervisor.js +66 -14
  232. package/dist/shared/provider-capabilities.d.ts +2 -0
  233. package/dist/shared/provider-capabilities.js +18 -1
  234. package/dist/version.d.ts +1 -1
  235. package/dist/version.js +1 -1
  236. package/dist/worktree/artifact-injector.js +24 -0
  237. package/dist/worktree/orphan-relink.d.ts +19 -0
  238. package/dist/worktree/orphan-relink.js +106 -0
  239. package/dist/worktree/wip-git.d.ts +58 -0
  240. package/dist/worktree/wip-git.js +182 -0
  241. package/dist/worktree/wip-refs.d.ts +85 -0
  242. package/dist/worktree/wip-refs.js +169 -0
  243. package/dist/worktree/wip-restore.d.ts +51 -0
  244. package/dist/worktree/wip-restore.js +324 -0
  245. package/dist/worktree/wip-snapshot.d.ts +53 -0
  246. package/dist/worktree/wip-snapshot.js +270 -0
  247. package/dist/worktree/worktree-inputs.d.ts +8 -0
  248. package/dist/worktree/worktree-inputs.js +134 -0
  249. package/dist/worktree/worktree-origin-sync.d.ts +35 -0
  250. package/dist/worktree/worktree-origin-sync.js +128 -0
  251. package/dist/worktree/worktree-wip-events.d.ts +20 -0
  252. package/dist/worktree/worktree-wip-events.js +148 -0
  253. package/dist/worktree/worktree-wip.d.ts +57 -0
  254. package/dist/worktree/worktree-wip.js +200 -0
  255. package/dist/worktree/worktree.base.d.ts +7 -1
  256. package/dist/worktree/worktree.service.d.ts +49 -5
  257. package/dist/worktree/worktree.service.js +223 -187
  258. package/dist/worktree/worktree.types.d.ts +47 -0
  259. package/package.json +1 -1
  260. package/runtime/windows-listener-owner.ps1 +12 -1
@@ -0,0 +1,36 @@
1
+ import { type ProcessRunner } from "../shared/process/process.js";
2
+ import type { PrReviewCompletionContext } from "./phase-completion.js";
3
+ /** Inclusive new-side line range that sits inside one hunk of the pull request diff. */
4
+ export interface DiffLineRange {
5
+ readonly start: number;
6
+ readonly end: number;
7
+ }
8
+ /** New-side (RIGHT) lines GitHub accepts inline comments on, per changed path. */
9
+ export type NewSideDiffLines = ReadonlyMap<string, readonly DiffLineRange[]>;
10
+ /**
11
+ * Parses `git diff --unified=3` output into the new-side line ranges of every hunk.
12
+ * Added and context lines both count: GitHub lets a review comment land on either.
13
+ * Hunk header counts drive the walk, so a content line that starts with `+++` is not mistaken for a file header.
14
+ */
15
+ export declare function parseNewSideDiffLines(diff: string): NewSideDiffLines;
16
+ export declare function isLineInRanges(ranges: readonly DiffLineRange[] | undefined, line: number): boolean;
17
+ /** Messages for every finding whose anchor GitHub would reject, each with how to re-anchor. */
18
+ export declare function offDiffAnchorProblems(findings: readonly Record<string, unknown>[], diffLines: NewSideDiffLines, range: string): string[];
19
+ export declare function normalizeFindingPath(value: string): string;
20
+ /**
21
+ * Checks what a `reviewed` payload claims against the worktree: the review must be bound to the
22
+ * commit that is checked out (and to the dispatched head when Forge supplied one), `base_sha`
23
+ * must be a real commit, and every inline comment must land on a line of the PR diff.
24
+ * Throws an error that tells the agent how to repair the payload.
25
+ */
26
+ export declare function assertPrReviewMatchesRepository(worktreePath: string, payload: Record<string, unknown>, context: PrReviewCompletionContext | undefined, processRunner?: ProcessRunner): Promise<void>;
27
+ /**
28
+ * Re-checks the recorded pr-review.result.json as if it had just been submitted. The completion tool
29
+ * validates what it writes, but the session can also write that file itself (the post-run worktree
30
+ * check skips Forge's artifact directory), so the file Forge hands on must pass the same shape,
31
+ * head, base and diff-anchor rules, name this work item and phase, and carry the content hash the tool
32
+ * computes. Returns the reason it is rejected, or null.
33
+ */
34
+ export declare function recordedPrReviewArtifactProblem(worktreePath: string, workItemId: string, verdictJson: string, context: PrReviewCompletionContext | undefined, processRunner?: ProcessRunner): Promise<string | null>;
35
+ /** Renders the pr-review.report.md that sits next to pr-review.result.json. */
36
+ export declare function prReviewReportMarkdown(artifact: Record<string, unknown>, contentHash: string): string;
@@ -0,0 +1,294 @@
1
+ import path from "node:path";
2
+ import { NodeProcessRunner } from "../shared/process/process.js";
3
+ import { normalizedString, optionalString, sha256, stableStringify } from "./phase-completion.helpers.js";
4
+ import { validatePrReviewPayloadShape } from "./phase-completion.pr-review-validation.js";
5
+ const maxListedRanges = 8;
6
+ const maxListedFiles = 20;
7
+ /**
8
+ * Parses `git diff --unified=3` output into the new-side line ranges of every hunk.
9
+ * Added and context lines both count: GitHub lets a review comment land on either.
10
+ * Hunk header counts drive the walk, so a content line that starts with `+++` is not mistaken for a file header.
11
+ */
12
+ export function parseNewSideDiffLines(diff) {
13
+ const files = new Map();
14
+ const lines = diff.split("\n");
15
+ let currentFile = null;
16
+ let index = 0;
17
+ while (index < lines.length) {
18
+ const line = lines[index];
19
+ if (line.startsWith("diff --git ")) {
20
+ currentFile = null;
21
+ index += 1;
22
+ continue;
23
+ }
24
+ if (line.startsWith("+++ ")) {
25
+ const target = line.slice(4).replace(/\t.*$/u, "").replace(/\r$/u, "");
26
+ currentFile = target === "/dev/null" ? null : target.replace(/^b\//u, "");
27
+ index += 1;
28
+ continue;
29
+ }
30
+ const header = /^@@ -\d+(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/u.exec(line);
31
+ if (!header || currentFile === null) {
32
+ index += 1;
33
+ continue;
34
+ }
35
+ let oldRemaining = header[1] === undefined ? 1 : Number(header[1]);
36
+ let newRemaining = header[3] === undefined ? 1 : Number(header[3]);
37
+ let newLine = Number(header[2]);
38
+ const hunkStart = newLine;
39
+ index += 1;
40
+ while (index < lines.length && (oldRemaining > 0 || newRemaining > 0)) {
41
+ const body = lines[index];
42
+ const marker = body[0];
43
+ if (marker === "\\") {
44
+ index += 1;
45
+ continue;
46
+ }
47
+ if (marker === "+") {
48
+ newRemaining -= 1;
49
+ newLine += 1;
50
+ }
51
+ else if (marker === "-") {
52
+ oldRemaining -= 1;
53
+ }
54
+ else {
55
+ // A context line, or a blank one whose leading space was stripped.
56
+ oldRemaining -= 1;
57
+ newRemaining -= 1;
58
+ newLine += 1;
59
+ }
60
+ index += 1;
61
+ }
62
+ if (newLine > hunkStart) {
63
+ const ranges = files.get(currentFile) ?? [];
64
+ ranges.push({ start: hunkStart, end: newLine - 1 });
65
+ files.set(currentFile, ranges);
66
+ }
67
+ }
68
+ return files;
69
+ }
70
+ export function isLineInRanges(ranges, line) {
71
+ return Boolean(ranges?.some((range) => line >= range.start && line <= range.end));
72
+ }
73
+ /** Messages for every finding whose anchor GitHub would reject, each with how to re-anchor. */
74
+ export function offDiffAnchorProblems(findings, diffLines, range) {
75
+ const problems = [];
76
+ for (const [index, finding] of findings.entries()) {
77
+ const findingPath = normalizeFindingPath(optionalString(finding, "path") ?? "");
78
+ const line = finding.line;
79
+ const startLine = typeof finding.start_line === "number" ? finding.start_line : null;
80
+ const ranges = diffLines.get(findingPath);
81
+ const label = `findings[${index}] (${findingPath}:${line})`;
82
+ if (!ranges || ranges.length === 0) {
83
+ const changed = [...diffLines.keys()];
84
+ const listed = changed.slice(0, maxListedFiles).join(", ");
85
+ problems.push(`${label}: ${findingPath} has no changed lines in ${range}. Re-anchor at the changed line that introduces the problem, and name the unchanged location in the body as path:line. Files in the diff: ${listed || "none"}${changed.length > maxListedFiles ? `, and ${changed.length - maxListedFiles} more` : ""}.`);
86
+ continue;
87
+ }
88
+ const containing = ranges.find((candidate) => line >= candidate.start && line <= candidate.end);
89
+ if (!containing) {
90
+ problems.push(`${label}: line ${line} is not on the new side of the diff. Re-anchor at a changed line (side RIGHT); ${describeRanges(findingPath, ranges)}`);
91
+ continue;
92
+ }
93
+ if (startLine !== null && (startLine < containing.start || startLine > containing.end)) {
94
+ problems.push(`${label}: start_line ${startLine} is outside the hunk that contains line ${line} (${containing.start}-${containing.end}). A multi-line comment must stay inside one hunk; move start_line into ${containing.start}-${containing.end} or set it to null.`);
95
+ }
96
+ }
97
+ return problems;
98
+ }
99
+ function describeRanges(filePath, ranges) {
100
+ const listed = ranges.slice(0, maxListedRanges).map((range) => range.start === range.end ? `${range.start}` : `${range.start}-${range.end}`);
101
+ return `lines you can anchor to in ${filePath}: ${listed.join(", ")}${ranges.length > maxListedRanges ? `, and ${ranges.length - maxListedRanges} more ranges` : ""}.`;
102
+ }
103
+ export function normalizeFindingPath(value) {
104
+ return value.trim().replaceAll("\\", "/").replace(/^\.\//u, "");
105
+ }
106
+ /**
107
+ * Checks what a `reviewed` payload claims against the worktree: the review must be bound to the
108
+ * commit that is checked out (and to the dispatched head when Forge supplied one), `base_sha`
109
+ * must be a real commit, and every inline comment must land on a line of the PR diff.
110
+ * Throws an error that tells the agent how to repair the payload.
111
+ */
112
+ export async function assertPrReviewMatchesRepository(worktreePath, payload, context, processRunner = new NodeProcessRunner()) {
113
+ const git = gitRunner(worktreePath, processRunner);
114
+ const headSha = (optionalString(payload, "head_sha") ?? "").trim().toLowerCase();
115
+ const baseSha = (optionalString(payload, "base_sha") ?? "").trim().toLowerCase();
116
+ const worktreeHead = await git(["rev-parse", "--verify", "--quiet", "HEAD^{commit}"]);
117
+ const checkedOut = worktreeHead.ok ? worktreeHead.out.trim().toLowerCase() : null;
118
+ assertHeadBinding(headSha, checkedOut, context);
119
+ if (checkedOut === null) {
120
+ // Nothing to diff against without a checkout; the dispatched-head comparison above is all that can be proven.
121
+ return;
122
+ }
123
+ const resolvedBase = await resolveReviewBase(git, baseSha, context);
124
+ const findings = (payload.findings ?? []);
125
+ if (findings.length === 0)
126
+ return;
127
+ await assertFindingsOnDiff(git, findings, resolvedBase, checkedOut);
128
+ }
129
+ function gitRunner(worktreePath, processRunner) {
130
+ return async (args) => {
131
+ try {
132
+ const result = await processRunner.run({ command: "git", args: ["-c", "core.quotepath=off", ...args], cwd: path.resolve(worktreePath), rawOutput: true });
133
+ return { ok: result.exitCode === 0, out: result.stdout, error: result.stderr.trim() };
134
+ }
135
+ catch (error) {
136
+ return { ok: false, out: "", error: error instanceof Error ? error.message : String(error) };
137
+ }
138
+ };
139
+ }
140
+ function assertHeadBinding(headSha, checkedOut, context) {
141
+ if (checkedOut === null && !context?.headSha) {
142
+ throw new Error("Forge could not read HEAD in the review worktree, so it cannot confirm which commit you reviewed. Complete with status \"blocked\" and a reason if the repository is unreadable.");
143
+ }
144
+ if (checkedOut === null) {
145
+ return;
146
+ }
147
+ if (!sameCommit(headSha, checkedOut)) {
148
+ throw new Error(`head_sha ${headSha} is not the commit checked out in the review worktree (${checkedOut}). A review is bound to the head you read: set head_sha to the output of \`git rev-parse HEAD\` after reviewing that commit. If the worktree is not at the dispatched head, complete with status "stale_head" and head_sha set to ${checkedOut} instead of reviewing it.`);
149
+ }
150
+ if (context?.headSha && !sameCommit(context.headSha.trim().toLowerCase(), checkedOut)) {
151
+ throw new Error(`The review worktree is at ${checkedOut}, not the dispatched head ${context.headSha}. Complete with status "stale_head" and head_sha ${checkedOut}; a review of the wrong commit is worse than none.`);
152
+ }
153
+ }
154
+ async function resolveReviewBase(git, baseSha, context) {
155
+ const base = await git(["rev-parse", "--verify", "--quiet", `${baseSha}^{commit}`]);
156
+ if (!base.ok) {
157
+ throw new Error(`base_sha ${baseSha} is not a commit in the review worktree${base.error ? ` (${base.error})` : ""}. Use the dispatch's base_sha exactly, or complete with status "blocked" and a reason if the base commit is missing from the worktree.`);
158
+ }
159
+ const resolvedBase = base.out.trim().toLowerCase();
160
+ if (context?.baseSha && !sameCommit(context.baseSha.trim().toLowerCase(), resolvedBase)) {
161
+ throw new Error(`base_sha ${baseSha} is not the dispatched base ${context.baseSha}. Diff and review against the dispatched base.`);
162
+ }
163
+ return resolvedBase;
164
+ }
165
+ async function assertFindingsOnDiff(git, findings, resolvedBase, checkedOut) {
166
+ const diff = await git(["diff", "--no-color", "--no-ext-diff", "--no-renames", "--unified=3", "--src-prefix=a/", "--dst-prefix=b/", `${resolvedBase}...${checkedOut}`]);
167
+ if (!diff.ok) {
168
+ throw new Error(`Forge could not read the diff ${resolvedBase}...${checkedOut} to check your inline comments${diff.error ? ` (${diff.error})` : ""}. Complete with status "blocked" and a reason if the diff cannot be read.`);
169
+ }
170
+ const problems = offDiffAnchorProblems(findings, parseNewSideDiffLines(diff.out), `${resolvedBase.slice(0, 12)}...${checkedOut.slice(0, 12)}`);
171
+ if (problems.length > 0) {
172
+ throw new Error(`Inline comments must land on a line of the pull request diff, on the new side (side RIGHT), or GitHub rejects them. Re-anchor these and call forge.complete_pr_review again:\n- ${problems.join("\n- ")}`);
173
+ }
174
+ }
175
+ function sameCommit(claimed, actual) {
176
+ return claimed === actual;
177
+ }
178
+ const recordedPrReviewStatuses = new Set(["reviewed", "stale_head", "blocked"]);
179
+ /**
180
+ * Re-checks the recorded pr-review.result.json as if it had just been submitted. The completion tool
181
+ * validates what it writes, but the session can also write that file itself (the post-run worktree
182
+ * check skips Forge's artifact directory), so the file Forge hands on must pass the same shape,
183
+ * head, base and diff-anchor rules, name this work item and phase, and carry the content hash the tool
184
+ * computes. Returns the reason it is rejected, or null.
185
+ */
186
+ export async function recordedPrReviewArtifactProblem(worktreePath, workItemId, verdictJson, context, processRunner = new NodeProcessRunner()) {
187
+ let payload;
188
+ try {
189
+ const parsed = JSON.parse(verdictJson);
190
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed))
191
+ return "the recorded review is not a JSON object";
192
+ payload = parsed;
193
+ }
194
+ catch {
195
+ return "the recorded review is not valid JSON";
196
+ }
197
+ const status = optionalString(payload, "status")?.trim() ?? "";
198
+ if (!recordedPrReviewStatuses.has(status))
199
+ return `the recorded review has status '${status}', not reviewed, stale_head or blocked`;
200
+ if (optionalString(payload, "phase") !== "pr_review")
201
+ return "the recorded review is not a pr_review artifact";
202
+ if (optionalString(payload, "work_item_id") !== workItemId)
203
+ return `the recorded review names work item '${optionalString(payload, "work_item_id") ?? ""}', not ${workItemId}`;
204
+ const { content_hash: contentHash, ...withoutHash } = payload;
205
+ if (typeof contentHash !== "string" || contentHash !== sha256(stableStringify(withoutHash))) {
206
+ return "the recorded review's content_hash does not match its content, so forge.complete_pr_review did not write it";
207
+ }
208
+ try {
209
+ validatePrReviewPayloadShape(payload, status, context);
210
+ if (status === "reviewed") {
211
+ await assertPrReviewMatchesRepository(worktreePath, payload, context, processRunner);
212
+ }
213
+ }
214
+ catch (error) {
215
+ return error instanceof Error ? error.message : String(error);
216
+ }
217
+ return null;
218
+ }
219
+ /** Renders the pr-review.report.md that sits next to pr-review.result.json. */
220
+ export function prReviewReportMarkdown(artifact, contentHash) {
221
+ const status = normalizedString(optionalString(artifact, "status"));
222
+ const lines = ["# Forge PR review", ""];
223
+ lines.push(`Status: ${status}`);
224
+ const head = optionalString(artifact, "head_sha");
225
+ if (head)
226
+ lines.push(`Head: ${head}`);
227
+ const base = optionalString(artifact, "base_sha");
228
+ if (base)
229
+ lines.push(`Base: ${base}`);
230
+ lines.push(`Produced by: ${optionalString(artifact, "produced_by") ?? "forge-completion-tool"}`);
231
+ lines.push(`Content hash: ${contentHash}`, "");
232
+ if (status !== "reviewed") {
233
+ const reason = optionalString(artifact, "reason") ?? optionalString(artifact, "summary") ?? optionalString(artifact, "verdict_reason");
234
+ lines.push(status === "stale_head" ? "## Stale head" : "## Blocked", "", reason ?? "No reason recorded.", "");
235
+ return `${lines.join("\n")}\n`;
236
+ }
237
+ appendReviewedOverview(lines, artifact);
238
+ appendFindingsSection(lines, recordList(artifact.findings));
239
+ appendPriorThreadsSection(lines, recordList(artifact.prior_threads));
240
+ appendSecuritySection(lines, (artifact.security_review ?? {}));
241
+ const skipped = recordList(artifact.skipped_files);
242
+ if (skipped.length > 0) {
243
+ lines.push("## Skipped files", "");
244
+ lines.push(...skipped.map((file) => `- ${optionalString(file, "path")}: ${optionalString(file, "reason")}`), "");
245
+ }
246
+ return `${lines.join("\n").replace(/\n{3,}/gu, "\n\n")}\n`;
247
+ }
248
+ function appendReviewedOverview(lines, artifact) {
249
+ lines.push(`Verdict: ${optionalString(artifact, "verdict") ?? "unknown"}${optionalString(artifact, "review_effort") ? ` (${optionalString(artifact, "review_effort")} review)` : ""}`, "");
250
+ lines.push(optionalString(artifact, "verdict_reason") ?? "", "");
251
+ lines.push("## Overview", "", optionalString(artifact, "summary") ?? "", "");
252
+ const changes = stringList(artifact.changes);
253
+ if (changes.length > 0)
254
+ lines.push(...changes.map((change) => `- ${change}`), "");
255
+ const files = recordList(artifact.files);
256
+ if (files.length > 0) {
257
+ lines.push("| File | Description |", "| --- | --- |");
258
+ lines.push(...files.map((file) => `| ${tableCell(optionalString(file, "path"))} | ${tableCell(optionalString(file, "description"))} |`), "");
259
+ }
260
+ }
261
+ function appendFindingsSection(lines, findings) {
262
+ lines.push(`## Findings (${findings.length})`, "");
263
+ if (findings.length === 0)
264
+ lines.push("No new findings.", "");
265
+ for (const finding of findings) {
266
+ lines.push(`### ${optionalString(finding, "title") ?? "Finding"}`, "");
267
+ lines.push(`${String(finding.severity)} ${String(finding.category)} at \`${optionalString(finding, "path")}:${String(finding.line)}\``, "");
268
+ lines.push(optionalString(finding, "body") ?? "", "");
269
+ }
270
+ }
271
+ function appendPriorThreadsSection(lines, threads) {
272
+ if (threads.length === 0)
273
+ return;
274
+ lines.push("## Prior threads", "");
275
+ lines.push(...threads.map((thread) => `- ${optionalString(thread, "thread_id")}: ${optionalString(thread, "status")}`), "");
276
+ }
277
+ function appendSecuritySection(lines, security) {
278
+ lines.push("## Security review", "", `Status: ${optionalString(security, "status") ?? "unknown"}`, "");
279
+ const checked = stringList(security.checked);
280
+ if (checked.length > 0)
281
+ lines.push(`Checked: ${checked.join(", ")}`, "");
282
+ lines.push(optionalString(security, "notes") ?? "", "");
283
+ }
284
+ function stringList(value) {
285
+ return Array.isArray(value) ? value.filter((entry) => typeof entry === "string" && entry.trim().length > 0) : [];
286
+ }
287
+ function recordList(value) {
288
+ return Array.isArray(value)
289
+ ? value.filter((entry) => Boolean(entry) && typeof entry === "object" && !Array.isArray(entry))
290
+ : [];
291
+ }
292
+ function tableCell(value) {
293
+ return (value ?? "").replace(/\|/gu, "\\|").replace(/\r?\n/gu, " ");
294
+ }
@@ -7,7 +7,7 @@ export declare function completionPromptForDecomposeCycle(currentGate?: Decompos
7
7
  export declare function completionPromptForDebugCycle(currentGate?: DebugCompletionPhase): string;
8
8
  export declare function nextPhaseAfter(phase: CompletionPhase): DevelopCompletionPhase | null;
9
9
  export declare function nextDebugPhaseAfter(phase: DebugCompletionPhase): DebugCompletionPhase | null;
10
- export declare function completionToolNextInstruction(completedPhase: CompletionPhase, status: string, nextPhase: CompletionPhase | "dev_test_ready" | "qa_ready" | "sign_off_ready" | "provider_checks_ready"): string;
10
+ export declare function completionToolNextInstruction(completedPhase: CompletionPhase, status: string, nextPhase: CompletionPhase | "dev_test_ready" | "qa_ready" | "sign_off_ready" | "provider_checks_ready" | "pr_review_complete"): string;
11
11
  export declare function completionToolNextInstructionForDraftGate(completedGate: DraftCompletionGate, status: string, nextGate: DraftCompletionGate | null): string;
12
12
  export declare function completionToolNextInstructionForQaGate(completedGate: QaCompletionGate, status: string, nextGate: QaCompletionGate | null): string;
13
13
  export declare function completionToolNextInstructionForDecomposeGate(completedGate: DecomposeCompletionGate, status: string, nextGate: DecomposeCompletionGate | null): string;
@@ -23,6 +23,13 @@ When a task's implementation or validation starts containers or otherwise needs
23
23
  Dependency entries use canonical \`before\` and \`after\` task ids, for example \`{ "before": "task-1", "after": "task-2" }\`. Forge accepts \`from\`/\`to\` only as aliases and normalizes them before writing artifacts.
24
24
  Use \`status: "pass"\` for a valid pending-approval plan, \`needs_revision\` when story/design input must change, or \`blocked\` with a concrete blocker.
25
25
  Forge will mirror only the tool-written Architect artifacts; reporting the plan in prose is not enough.`;
26
+ }
27
+ if (phase === "pr_review") {
28
+ return `Forge completion tools are available through the MCP server named \`${toolServerName}\`.
29
+ Review only: do not edit, commit, push, or post to GitHub, and do not write the review artifact by hand. When the review is complete, call \`${toolName}(...)\`${alias ? ` (or \`${alias}\` if your client shows unqualified MCP tool names)` : ""} with the review payload from the pr-review skill, bound to the head you reviewed.
30
+ That tool writes \`${artifactRoot}/${artifactName}\` and \`${phaseFiles[phase].reportFileName}\`. Forge posts the review afterwards; the tool itself publishes nothing.
31
+ Use \`status: "reviewed"\` for a completed review, \`status: "stale_head"\` (with head_sha set to the commit you found) when HEAD differs from the dispatched head, and \`status: "blocked"\` with a reason when the diff cannot be read.
32
+ If the tool rejects the payload, it names the fields to correct: a head_sha that is not the checked-out head, a side other than RIGHT, a line that is not in the diff (re-anchor at a changed line), a verdict that contradicts the open issues, or an unknown prior thread id. Fix them and call again. Ending your turn without an accepted call records no review.`;
26
33
  }
27
34
  if (phase === "ci_repair") {
28
35
  return `Forge completion tools are available through the MCP server named \`${toolServerName}\`.
@@ -127,6 +134,13 @@ export function completionToolNextInstruction(completedPhase, status, nextPhase)
127
134
  ? "CI repair handoff accepted. Forge Bridge may now commit, push, and return the PR to provider checks."
128
135
  : "Stay in CI repair, address the exact missing evidence returned by this gate, then call forge.complete_ci_repair again.";
129
136
  }
137
+ if (completedPhase === "pr_review") {
138
+ return status === "stale_head"
139
+ ? "Stale head recorded. Forge will re-dispatch the review at the current head. Do not post anything to GitHub; end your turn with a one-line summary."
140
+ : status === "blocked"
141
+ ? "Blocked review recorded. Do not post anything to GitHub; end your turn with a one-line summary naming the blocker."
142
+ : "Review recorded. Forge will post it as one comment-only review on the reviewed head; do not post anything to GitHub yourself. End your turn with a concise summary of the verdict, the number of findings, and the completion status.";
143
+ }
130
144
  if (status !== "pass") {
131
145
  return `Stay in ${completedPhase}, address the recorded blockers, then call ${expectedCompletionToolName(completedPhase)} again.`;
132
146
  }
@@ -1,7 +1,13 @@
1
- import { type CompletionToolCallResult, type CompletionToolRuntime, type CompletionToolRuntimeOptions, type CompletionToolServerConfig } from "./phase-completion.js";
1
+ import type { RunOnceDispatchPacket } from "./session.types.js";
2
+ import { type CompletionToolCallResult, type CompletionToolRuntime, type CompletionToolRuntimeOptions, type CompletionToolServerConfig, type PrReviewCompletionContext } from "./phase-completion.js";
2
3
  import { type ManagedAttemptToolResult } from "./managed-attempt-tools.js";
3
4
  export declare function prepareCompletionToolRuntime(options: CompletionToolRuntimeOptions): Promise<CompletionToolRuntime>;
4
- export declare function buildCompletionToolServerArgs(config: CompletionToolServerConfig): readonly string[];
5
+ /**
6
+ * The pull-request facts the pr_review completion tool holds a review to: the admitted head
7
+ * (prReview.headSha, never the live pull request head) and the prior review threads the
8
+ * dispatch lists, and the dispatched base commit the payload's base_sha must resolve to.
9
+ */
10
+ export declare function prReviewContextFromDispatch(dispatch: RunOnceDispatchPacket): PrReviewCompletionContext | undefined;
5
11
  export declare function codexMcpConfigArgs(runtime: CompletionToolRuntime): readonly string[];
6
12
  export declare function cursorMcpServerConfig(runtime: CompletionToolRuntime): unknown;
7
13
  export declare function claudeMcpServerConfig(runtime: CompletionToolRuntime): unknown;
@@ -38,13 +44,6 @@ export declare function completionToolRuntimeEnvironment(runtimeEnvironment?: Re
38
44
  */
39
45
  export declare function assertManagedQaRegressionEvidence(input: unknown, receipts: readonly Readonly<Record<string, unknown>>[]): void;
40
46
  export declare function runCompletionMcpServer(config: CompletionToolServerConfig): Promise<void>;
41
- export declare function parseCompletionMcpArgs(argv: readonly string[]): {
42
- readonly ok: true;
43
- readonly config: CompletionToolServerConfig;
44
- } | {
45
- readonly ok: false;
46
- readonly error: string;
47
- };
48
47
  export declare function completionRedactionEnv(secrets: readonly string[]): Readonly<Record<string, string>>;
49
48
  export declare function completionToolRejectedResult(toolName: string, error: unknown, input?: unknown): Readonly<Record<string, unknown>>;
50
49
  /** The input schema a completion tool advertises; also the shape its arguments are coerced to. */