@loucompanion/forge-bridge 0.1.4-dev.41da3780c451 → 0.1.4-dev.494233aa2e50

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 (49) hide show
  1. package/README.md +1 -1
  2. package/dist/bridge/bridge.service.d.ts +12 -1
  3. package/dist/bridge/bridge.service.js +51 -5
  4. package/dist/bridge/bridge.types.d.ts +6 -0
  5. package/dist/bridge/dispatch-result-outbox.d.ts +11 -1
  6. package/dist/bridge/dispatch-result-outbox.js +31 -6
  7. package/dist/cli/cli.help.js +2 -2
  8. package/dist/runtime/attempt-process-supervisor.d.ts +24 -0
  9. package/dist/runtime/attempt-process-supervisor.js +74 -1
  10. package/dist/runtime/host-database-capability-boundary.d.ts +1 -1
  11. package/dist/runtime/host-database-capability-boundary.js +1 -0
  12. package/dist/runtime/host-facts.d.ts +35 -0
  13. package/dist/runtime/host-facts.js +95 -0
  14. package/dist/runtime/host-load-sampler.d.ts +83 -0
  15. package/dist/runtime/host-load-sampler.js +164 -0
  16. package/dist/runtime/host-pressure-stall.d.ts +41 -0
  17. package/dist/runtime/host-pressure-stall.js +121 -0
  18. package/dist/runtime/host-runtime-contract.d.ts +1 -0
  19. package/dist/runtime/host-runtime-contract.js +2 -0
  20. package/dist/runtime/host-runtime-lease.js +55 -9
  21. package/dist/runtime/managed-command-teardown.d.ts +62 -0
  22. package/dist/runtime/managed-command-teardown.js +607 -0
  23. package/dist/runtime/playwright-browser-cache.d.ts +39 -0
  24. package/dist/runtime/playwright-browser-cache.js +227 -0
  25. package/dist/runtime/playwright-host-runtime-adapter.d.ts +11 -0
  26. package/dist/runtime/playwright-host-runtime-adapter.js +48 -54
  27. package/dist/session/managed-attempt-tools.d.ts +25 -0
  28. package/dist/session/managed-attempt-tools.js +212 -15
  29. package/dist/session/managed-build-coordinator.d.ts +1 -1
  30. package/dist/session/managed-build-coordinator.js +4 -1
  31. package/dist/session/phase-completion.artifacts.js +4 -0
  32. package/dist/session/phase-completion.runtime.js +22 -17
  33. package/dist/session/pre-publication-process.d.ts +20 -0
  34. package/dist/session/pre-publication-process.js +97 -0
  35. package/dist/session/pre-publication-skipped-tests.d.ts +21 -0
  36. package/dist/session/pre-publication-skipped-tests.js +109 -0
  37. package/dist/session/pre-publication-validation.js +27 -57
  38. package/dist/session/provider-cli/provider-cli.artifacts.js +2 -9
  39. package/dist/session/provider-cli/provider-cli.process.d.ts +6 -1
  40. package/dist/session/provider-cli/provider-cli.process.js +198 -16
  41. package/dist/session/provider-cli/provider-cli.service.js +61 -10
  42. package/dist/session/provider-cli/provider-usage.d.ts +2 -1
  43. package/dist/session/publishable-worktree-changes.d.ts +45 -0
  44. package/dist/session/publishable-worktree-changes.js +177 -0
  45. package/dist/session/session.types.js +3 -0
  46. package/dist/version.d.ts +1 -1
  47. package/dist/version.js +1 -1
  48. package/dist/worktree/dependency-warmer.js +74 -0
  49. package/package.json +1 -1
@@ -6,7 +6,8 @@ import { buildSpecBody, selectLaneCommand } from "../../worktree/artifact-inject
6
6
  import { defaultWorktreeCoordinatorStateRoot } from "../../worktree/worktree-paths.js";
7
7
  import { completionPhaseFromDispatch, prepareCompletionToolRuntime, readCompletionArtifact, usesDebugCycleCompletion, usesDevelopCycleCompletion } from "../phase-completion.js";
8
8
  import { ForgeFailureError } from "../session.types.js";
9
- import { cleanupCompletionTools, commitWorktreeChanges, completionPhaseFromArtifact, emitArchitectStructuredEvents, emitCompletionArtifactRecorded, emitDecomposeGateArtifacts, emitDraftGateArtifacts, emitPhaseCompletionEvent, emitPhaseGateEvents, emitQaArtifactRecorded, emitQaStructuredEvents, enforceQaBrowserLaunchTargetGate, LiveArchitectArtifactEmitter, LiveCompletionArtifactEmitter, LiveQaArtifactEmitter, readCompletionArtifactsForRun, readQaCompletionArtifactBundle, stagePublishableWorktreeChanges, waitForCompletionArtifact } from "./provider-cli.artifacts.js";
9
+ import { cleanupCompletionTools, commitWorktreeChanges, completionPhaseFromArtifact, emitArchitectStructuredEvents, emitCompletionArtifactRecorded, emitDecomposeGateArtifacts, emitDraftGateArtifacts, emitPhaseCompletionEvent, emitPhaseGateEvents, emitQaArtifactRecorded, emitQaStructuredEvents, enforceQaBrowserLaunchTargetGate, LiveArchitectArtifactEmitter, LiveCompletionArtifactEmitter, LiveQaArtifactEmitter, readCompletionArtifactsForRun, readQaCompletionArtifactBundle, waitForCompletionArtifact } from "./provider-cli.artifacts.js";
10
+ import { diffClaimedChangedFiles, findUnpublishedWorktreePaths, normalizeChangedFilePath, stagePublishableWorktreeChangeSet, } from "../publishable-worktree-changes.js";
10
11
  import { DeterministicProviderCliService } from "./provider-cli.deterministic.js";
11
12
  import { buildArchitectPrompt, buildConflictResolvePrompt, buildDebugCyclePrompt, buildDevelopCyclePrompt, buildDraftPrompt, buildDraftSpec, buildImplementationPrompt, buildProviderCliPrompt, buildProviderCliCommand, durableDraftInput, buildPullRequestCheckRepairPrompt, buildPullRequestCommentsPrompt, buildQaPrompt, formatProviderCliCommandForCheckpoint, isDecomposeDraftDispatch, isPullRequestCheckRepairDispatch, isPullRequestCommentsDispatch } from "./provider-cli.prompts.js";
12
13
  import { isTransientCodexProviderNotFoundFailure, recoveringProviderProcessRunner, StreamingProviderProcessRunner } from "./provider-cli.process.js";
@@ -68,12 +69,54 @@ function assertCommentRepairArtifactMatchesChanges(artifact, actualChangedFiles)
68
69
  const claimed = [...new Set(claimedChangedFiles)].sort();
69
70
  const actual = [...new Set(normalizedActual)].sort();
70
71
  if (hasFixedDisposition && actual.length === 0) {
71
- throw new Error("Comment repair fixed dispositions require an actual publishable source diff.");
72
+ throw commentRepairChangedFilesMismatch("Comment repair fixed dispositions require an actual publishable source diff.");
72
73
  }
73
74
  if (claimed.length !== actual.length || claimed.some((value, index) => value !== actual[index])) {
74
- throw new Error("Comment repair changed_files must exactly match the publishable staged source diff.");
75
+ const { missing, unexpected } = diffClaimedChangedFiles(claimed, actual);
76
+ throw commentRepairChangedFilesMismatch(`Comment repair changed_files must exactly match the publishable staged source diff${formatChangedFilesDelta(missing, unexpected)}.`);
75
77
  }
76
78
  }
79
+ /**
80
+ * A finding resolved as fixed must not point at a file whose edit Forge leaves out of the
81
+ * published commit; otherwise the thread would be resolved without its fix. That covers
82
+ * runtime output Forge unstaged and untracked or git-ignored files it never stages.
83
+ */
84
+ async function assertFixedFindingsArePublished(git, worktreePath, dispatch, artifact, changeSet) {
85
+ const findingPaths = new Map((dispatch.pullRequest?.reviewFindings ?? []).map(finding => [
86
+ `${finding.kind.trim().toLowerCase()}:${finding.claimId}:${finding.bodySha256.trim().toLowerCase()}`,
87
+ finding.path ? normalizeChangedFilePath(finding.path) : "",
88
+ ]));
89
+ const payload = JSON.parse(artifact.verdictJson);
90
+ const dispositions = Array.isArray(payload.dispositions) ? payload.dispositions : [];
91
+ const fixed = dispositions.flatMap(value => {
92
+ const record = value;
93
+ if (record.disposition !== "fixed")
94
+ return [];
95
+ const identity = `${String(record.kind ?? "").trim().toLowerCase()}:${String(record.claim_id ?? "")}:${String(record.body_sha256 ?? "").trim().toLowerCase()}`;
96
+ const findingPath = findingPaths.get(identity);
97
+ return findingPath ? [{ claimId: String(record.claim_id ?? ""), path: findingPath }] : [];
98
+ });
99
+ if (fixed.length === 0)
100
+ return;
101
+ const unpublished = new Set([
102
+ ...changeSet.excluded.map(normalizeChangedFilePath),
103
+ ...await findUnpublishedWorktreePaths(git, worktreePath, fixed.map(entry => entry.path), changeSet.publishable),
104
+ ]);
105
+ const dropped = fixed.filter(entry => unpublished.has(entry.path)).map(entry => `${entry.claimId} (${entry.path})`);
106
+ if (dropped.length > 0) {
107
+ throw commentRepairChangedFilesMismatch(`Comment repair marked ${dropped.join(", ")} fixed, but Forge does not publish that file (runtime output, untracked, or git-ignored); Forge did not publish or resolve review findings.`);
108
+ }
109
+ }
110
+ function commentRepairChangedFilesMismatch(message) {
111
+ return new ForgeFailureError("comment_repair_changed_files_mismatch", message);
112
+ }
113
+ function formatChangedFilesDelta(missing, unexpected) {
114
+ const parts = [
115
+ missing.length > 0 ? `missing from changed_files: ${missing.join(", ")}` : "",
116
+ unexpected.length > 0 ? `not in the publishable diff: ${unexpected.join(", ")}` : "",
117
+ ].filter(Boolean);
118
+ return parts.length > 0 ? ` (${parts.join("; ")})` : "";
119
+ }
77
120
  async function finalizeCommentRepairChangedFiles(artifact, baselineChangedFiles, actualChangedFiles) {
78
121
  const payload = JSON.parse(artifact.verdictJson);
79
122
  const claimedRecords = Array.isArray(payload.changed_files)
@@ -90,11 +133,11 @@ async function finalizeCommentRepairChangedFiles(artifact, baselineChangedFiles,
90
133
  const dispositions = Array.isArray(payload.dispositions) ? payload.dispositions : [];
91
134
  const hasFixedDisposition = dispositions.some(value => value.disposition === "fixed");
92
135
  if (hasFixedDisposition && authoritativePaths.length === 0) {
93
- throw new Error("Comment repair fixed dispositions require an actual publishable source diff.");
136
+ throw commentRepairChangedFilesMismatch("Comment repair fixed dispositions require an actual publishable source diff.");
94
137
  }
95
138
  for (const baselinePath of baselineChangedFiles.map(value => value.trim().replaceAll("\\", "/"))) {
96
139
  if (baselinePath && !authoritative.has(baselinePath)) {
97
- throw new Error(`Comment repair pre-publication repair removed '${baselinePath}' from the publishable staged source diff.`);
140
+ throw commentRepairChangedFilesMismatch(`Comment repair pre-publication repair removed '${baselinePath}' from the publishable staged source diff.`);
98
141
  }
99
142
  }
100
143
  payload.changed_files = authoritativePaths.map(filePath => {
@@ -1220,7 +1263,9 @@ export class ProcessBackedProviderCliService {
1220
1263
  }
1221
1264
  let commentRepairBaselineChangedFiles = null;
1222
1265
  if (addressComments && repairArtifact) {
1223
- commentRepairBaselineChangedFiles = await stagePublishableWorktreeChanges(this.git, worktree.worktreePath);
1266
+ const baseline = await stagePublishableWorktreeChangeSet(this.git, worktree.worktreePath);
1267
+ commentRepairBaselineChangedFiles = baseline.publishable;
1268
+ await assertFixedFindingsArePublished(this.git, worktree.worktreePath, dispatch, repairArtifact, baseline);
1224
1269
  assertCommentRepairArtifactMatchesChanges(repairArtifact, commentRepairBaselineChangedFiles);
1225
1270
  }
1226
1271
  const validationProfile = repairChecks
@@ -1236,8 +1281,10 @@ export class ProcessBackedProviderCliService {
1236
1281
  preparedHeadSha,
1237
1282
  repairScope: "pull_request",
1238
1283
  });
1239
- const stagedChangedFiles = await stagePublishableWorktreeChanges(this.git, worktree.worktreePath);
1284
+ const stagedChangeSet = await stagePublishableWorktreeChangeSet(this.git, worktree.worktreePath);
1285
+ const stagedChangedFiles = stagedChangeSet.publishable;
1240
1286
  if (addressComments && repairArtifact && commentRepairBaselineChangedFiles) {
1287
+ await assertFixedFindingsArePublished(this.git, worktree.worktreePath, dispatch, repairArtifact, stagedChangeSet);
1241
1288
  repairArtifact = await finalizeCommentRepairChangedFiles(repairArtifact, commentRepairBaselineChangedFiles, stagedChangedFiles);
1242
1289
  }
1243
1290
  const committed = await commitWorktreeChanges(this.git, worktree.worktreePath, dispatch.workItem.id, stagedChangedFiles);
@@ -1397,10 +1444,14 @@ export class ProcessBackedProviderCliService {
1397
1444
  session: { ...dispatch.session, resumeProviderThreadId: providerThreadId },
1398
1445
  };
1399
1446
  const recoveryPrompt = [
1400
- "Forge did not receive the required forge.complete_comment_repair call from your previous turn.",
1447
+ "Forge did not receive the required forge.complete_comment_repair call from your previous turn, so the provider process exited.",
1448
+ "Background watchers, monitors and notifications from that turn did not survive and will never report back,",
1449
+ "and Forge stopped any managed command that process was still running; its receipt reports that.",
1401
1450
  "Resume the existing work exactly where it is. Do not reimplement or discard the prepared changes.",
1402
- "Review the current diff and the durable review snapshot, preserve the validation evidence already gathered,",
1403
- "then call forge.complete_comment_repair with an evidence-backed disposition for every actionable finding.",
1451
+ "Review the current diff and the durable review snapshot and preserve the validation evidence already gathered.",
1452
+ "Check each managed command with forge.get_managed_command, restart any that were interrupted,",
1453
+ "and block on long commands with forge.wait_managed_command, calling it again while command_continues is true.",
1454
+ "Do not end your turn until you have called forge.complete_comment_repair with an evidence-backed disposition for every actionable finding.",
1404
1455
  "Do not commit or push; Forge owns publication after the completion gate succeeds.",
1405
1456
  ].join(" ");
1406
1457
  const providerPrompt = buildProviderCliPrompt(recoveryDispatch, recoveryPrompt, repairEnvironment);
@@ -4,7 +4,8 @@ export type InputTokenSemantics = "includes_cached_input" | "excludes_cache_toke
4
4
  export declare const PROVIDER_USAGE_SCHEMA_VERSION = 1;
5
5
  /**
6
6
  * Normalized, provider-agnostic token usage accumulated for a dispatch. Cost is never computed
7
- * here; the API recomputes cost from these tokens x model rates (ADR-0006).
7
+ * here; the API recomputes cost from these tokens x model rates (legacy
8
+ * ADR-0006, .forge-designer/decisions/legacy/0006-cost-capture.md).
8
9
  */
9
10
  export interface ProviderUsage {
10
11
  /** Normalized total input. Cached input is a subset, never an additive peer. */
@@ -0,0 +1,45 @@
1
+ import { GitClient } from "../shared/git/git.js";
2
+ import { type ProcessRunner } from "../shared/process/process.js";
3
+ export interface PublishableWorktreeChangeSet {
4
+ /** Paths staged for publication, as `git diff --cached --name-only` reports them. */
5
+ readonly publishable: readonly string[];
6
+ /** Worktree changes Forge treats as runtime output and leaves unstaged. */
7
+ readonly excluded: readonly string[];
8
+ }
9
+ /**
10
+ * Decides whether a staged change is Forge runtime output rather than an author edit.
11
+ *
12
+ * `.local/`, `.forge/work-items/` and `.forge/stories/` are always runtime output. Any
13
+ * other `.forge/` path is runtime output only when HEAD does not track it (status `A`):
14
+ * that covers injected managed commands, hooks and skills. The injector never overwrites a
15
+ * tracked `.forge/` file and restores one that matches the managed body, so a tracked
16
+ * `.forge/` file that differs from HEAD is an author edit and must be published.
17
+ */
18
+ export declare function isNonPublishableWorktreeChange(relativePath: string, status: string): boolean;
19
+ /** Stages every publishable worktree change in the real index and returns both sets. */
20
+ export declare function stagePublishableWorktreeChangeSet(git: Pick<GitClient, "run">, worktreePath: string): Promise<PublishableWorktreeChangeSet>;
21
+ /**
22
+ * Computes the same change set as {@link stagePublishableWorktreeChangeSet} without
23
+ * touching the worktree's index, using a throwaway copy of it. Returns null when
24
+ * `worktreePath` is not the root of a git worktree.
25
+ */
26
+ export declare function readPublishableWorktreeChangeSet(worktreePath: string, processRunner?: ProcessRunner): Promise<PublishableWorktreeChangeSet | null>;
27
+ /** Compares claimed `changed_files` paths with the publishable diff. */
28
+ export declare function diffClaimedChangedFiles(claimedPaths: readonly string[], publishablePaths: readonly string[]): {
29
+ readonly missing: readonly string[];
30
+ readonly unexpected: readonly string[];
31
+ };
32
+ export declare function normalizeChangedFilePath(value: string): string;
33
+ /**
34
+ * In-tool check for `forge.complete_comment_repair`: rejects a pass payload whose
35
+ * `changed_files` differs from what Forge would publish, so the agent can correct it
36
+ * in the same turn instead of failing at publication.
37
+ */
38
+ export declare function assertClaimedChangedFilesMatchPublishableDiff(worktreePath: string, payload: Record<string, unknown>, toolName: string, processRunner?: ProcessRunner): Promise<void>;
39
+ /**
40
+ * Returns the given paths whose worktree content differs from HEAD but is not in the
41
+ * publishable set: excluded runtime output, and untracked or git-ignored files that are
42
+ * never staged at all (for example an injected `.forge/` file in a repository that ignores
43
+ * `.forge/`). A review finding on such a path cannot be fixed by the published commit.
44
+ */
45
+ export declare function findUnpublishedWorktreePaths(git: Pick<GitClient, "run">, worktreePath: string, paths: readonly string[], publishablePaths: readonly string[]): Promise<readonly string[]>;
@@ -0,0 +1,177 @@
1
+ import fs from "node:fs/promises";
2
+ import os from "node:os";
3
+ import path from "node:path";
4
+ import { GitClient } from "../shared/git/git.js";
5
+ import { NodeProcessRunner } from "../shared/process/process.js";
6
+ /**
7
+ * Forge runtime output that is never published, whether or not the target repository
8
+ * tracks other `.forge/` content. Completion artifacts and evidence live here.
9
+ */
10
+ const runtimeOnlyPathPrefixes = [".local/", ".forge/work-items/", ".forge/stories/"];
11
+ const resetBatchSize = 200;
12
+ /**
13
+ * Decides whether a staged change is Forge runtime output rather than an author edit.
14
+ *
15
+ * `.local/`, `.forge/work-items/` and `.forge/stories/` are always runtime output. Any
16
+ * other `.forge/` path is runtime output only when HEAD does not track it (status `A`):
17
+ * that covers injected managed commands, hooks and skills. The injector never overwrites a
18
+ * tracked `.forge/` file and restores one that matches the managed body, so a tracked
19
+ * `.forge/` file that differs from HEAD is an author edit and must be published.
20
+ */
21
+ export function isNonPublishableWorktreeChange(relativePath, status) {
22
+ const normalized = relativePath.trim().replaceAll("\\", "/");
23
+ if (normalized === ".local" || runtimeOnlyPathPrefixes.some(prefix => normalized.startsWith(prefix))) {
24
+ return true;
25
+ }
26
+ if (normalized === ".forge" || normalized.startsWith(".forge/")) {
27
+ return status.trim().toUpperCase().startsWith("A");
28
+ }
29
+ return false;
30
+ }
31
+ /** Stages every publishable worktree change in the real index and returns both sets. */
32
+ export async function stagePublishableWorktreeChangeSet(git, worktreePath) {
33
+ await git.run(worktreePath, ["add", "-A"]);
34
+ const excluded = (await readStagedChanges(git, worktreePath))
35
+ .filter(change => isNonPublishableWorktreeChange(change.path, change.status))
36
+ .map(change => change.path);
37
+ for (let index = 0; index < excluded.length; index += resetBatchSize) {
38
+ const batch = excluded.slice(index, index + resetBatchSize).map(filePath => `:(literal)${filePath}`);
39
+ await git.run(worktreePath, ["reset", "-q", "--", ...batch]);
40
+ }
41
+ const publishable = (await git.run(worktreePath, ["diff", "--cached", "--name-only"]))
42
+ .split(/\r?\n/)
43
+ .map(line => line.trim())
44
+ .filter(Boolean);
45
+ return { publishable, excluded: [...new Set(excluded)].sort() };
46
+ }
47
+ /**
48
+ * Computes the same change set as {@link stagePublishableWorktreeChangeSet} without
49
+ * touching the worktree's index, using a throwaway copy of it. Returns null when
50
+ * `worktreePath` is not the root of a git worktree.
51
+ */
52
+ export async function readPublishableWorktreeChangeSet(worktreePath, processRunner = new NodeProcessRunner()) {
53
+ const resolvedWorktree = path.resolve(worktreePath);
54
+ const git = new GitClient(processRunner);
55
+ let topLevel;
56
+ try {
57
+ topLevel = (await git.run(resolvedWorktree, ["rev-parse", "--show-toplevel"])).trim();
58
+ }
59
+ catch {
60
+ return null;
61
+ }
62
+ if (!topLevel || !await samePath(topLevel, resolvedWorktree)) {
63
+ return null;
64
+ }
65
+ const realIndex = path.resolve(resolvedWorktree, (await git.run(resolvedWorktree, ["rev-parse", "--git-path", "index"])).trim());
66
+ const tempRoot = await fs.mkdtemp(path.join(os.tmpdir(), "forge-publishable-index-"));
67
+ try {
68
+ const tempIndex = path.join(tempRoot, "index");
69
+ await fs.copyFile(realIndex, tempIndex).catch((error) => {
70
+ if (error.code !== "ENOENT")
71
+ throw error;
72
+ });
73
+ const tempIndexGit = new GitClient({
74
+ run: request => processRunner.run({
75
+ ...request,
76
+ env: { ...(request.env ?? process.env), GIT_INDEX_FILE: tempIndex },
77
+ }),
78
+ });
79
+ return await stagePublishableWorktreeChangeSet(tempIndexGit, resolvedWorktree);
80
+ }
81
+ finally {
82
+ await fs.rm(tempRoot, { recursive: true, force: true });
83
+ }
84
+ }
85
+ /** Compares claimed `changed_files` paths with the publishable diff. */
86
+ export function diffClaimedChangedFiles(claimedPaths, publishablePaths) {
87
+ const claimed = new Set(claimedPaths.map(normalizeChangedFilePath).filter(Boolean));
88
+ const actual = new Set(publishablePaths.map(normalizeChangedFilePath).filter(Boolean));
89
+ return {
90
+ missing: [...actual].filter(filePath => !claimed.has(filePath)).sort(),
91
+ unexpected: [...claimed].filter(filePath => !actual.has(filePath)).sort(),
92
+ };
93
+ }
94
+ export function normalizeChangedFilePath(value) {
95
+ return value.trim().replaceAll("\\", "/");
96
+ }
97
+ async function readStagedChanges(git, worktreePath) {
98
+ const fields = (await git.run(worktreePath, ["diff", "--cached", "--name-status", "--no-renames", "-z"]))
99
+ .split("\0");
100
+ const changes = [];
101
+ for (let index = 0; index + 1 < fields.length; index += 2) {
102
+ const status = fields[index].trim();
103
+ const filePath = fields[index + 1];
104
+ if (status && filePath)
105
+ changes.push({ status, path: filePath });
106
+ }
107
+ return changes;
108
+ }
109
+ async function samePath(left, right) {
110
+ const [realLeft, realRight] = await Promise.all([
111
+ fs.realpath(left).catch(() => path.resolve(left)),
112
+ fs.realpath(right).catch(() => path.resolve(right)),
113
+ ]);
114
+ return process.platform === "win32"
115
+ ? realLeft.toLowerCase() === realRight.toLowerCase()
116
+ : realLeft === realRight;
117
+ }
118
+ /**
119
+ * In-tool check for `forge.complete_comment_repair`: rejects a pass payload whose
120
+ * `changed_files` differs from what Forge would publish, so the agent can correct it
121
+ * in the same turn instead of failing at publication.
122
+ */
123
+ export async function assertClaimedChangedFilesMatchPublishableDiff(worktreePath, payload, toolName, processRunner) {
124
+ const changeSet = await readPublishableWorktreeChangeSet(worktreePath, processRunner);
125
+ if (!changeSet)
126
+ return;
127
+ const claimed = Array.isArray(payload.changed_files)
128
+ ? payload.changed_files.map(value => String(value?.path ?? ""))
129
+ : [];
130
+ const { missing, unexpected } = diffClaimedChangedFiles(claimed, changeSet.publishable);
131
+ if (missing.length === 0 && unexpected.length === 0)
132
+ return;
133
+ const details = [
134
+ missing.length > 0 ? `Publishable changes missing from changed_files: ${missing.join(", ")}.` : "",
135
+ unexpected.length > 0 ? `changed_files entries that Forge will not publish: ${unexpected.join(", ")}.` : "",
136
+ ].filter(Boolean).join(" ");
137
+ throw new Error(`changed_files must list exactly the files Forge will publish. ${details} `
138
+ + "Forge publishes every source change, including edits to tracked .forge/ files; it never publishes "
139
+ + ".local/, .forge/work-items/, .forge/stories/, or new untracked .forge/ files. "
140
+ + `Correct changed_files (or the worktree) and call ${toolName} again.`);
141
+ }
142
+ /**
143
+ * Returns the given paths whose worktree content differs from HEAD but is not in the
144
+ * publishable set: excluded runtime output, and untracked or git-ignored files that are
145
+ * never staged at all (for example an injected `.forge/` file in a repository that ignores
146
+ * `.forge/`). A review finding on such a path cannot be fixed by the published commit.
147
+ */
148
+ export async function findUnpublishedWorktreePaths(git, worktreePath, paths, publishablePaths) {
149
+ const candidates = [...new Set(paths.map(normalizeChangedFilePath).filter(Boolean))];
150
+ if (candidates.length === 0)
151
+ return [];
152
+ const publishable = new Set(publishablePaths.map(normalizeChangedFilePath));
153
+ const unpublished = new Set();
154
+ for (let index = 0; index < candidates.length; index += resetBatchSize) {
155
+ const batch = candidates.slice(index, index + resetBatchSize).map(filePath => `:(literal)${filePath}`);
156
+ const output = await git.run(worktreePath, [
157
+ // `traditional` with `--untracked-files=all` lists each file inside an ignored directory.
158
+ "status", "--porcelain=v1", "-z", "--no-renames", "--ignored=traditional", "--untracked-files=all", "--", ...batch,
159
+ ]);
160
+ for (const entry of output.split("\0")) {
161
+ if (entry.length < 4)
162
+ continue;
163
+ const reported = normalizeChangedFilePath(entry.slice(3));
164
+ if (!reported)
165
+ continue;
166
+ // A collapsed directory entry ("dir/") covers every candidate beneath it.
167
+ const matches = reported.endsWith("/")
168
+ ? candidates.filter(candidate => candidate.startsWith(reported))
169
+ : [reported];
170
+ for (const filePath of matches) {
171
+ if (!publishable.has(filePath))
172
+ unpublished.add(filePath);
173
+ }
174
+ }
175
+ }
176
+ return [...unpublished].sort();
177
+ }
@@ -481,6 +481,9 @@ function unvalidatedFailureFactsForCode(code, source) {
481
481
  if (["prepublication_validation_failed", "prepublication_contract_invalid", "prepublication_execution_scope_invalid"].includes(code)) {
482
482
  return facts(code, "domain", "validation", source, "non_retryable", "fix_input");
483
483
  }
484
+ if (code === "comment_repair_changed_files_mismatch") {
485
+ return facts(code, "domain", "validation", source, "non_retryable", "inspect_failure");
486
+ }
484
487
  if (["generated_output_reset_failed", "generated_output_reset_unverified", "worktree_prepare_failed", "host_runtime_ledger_write_failed", "host_diagnostics_temporary_unavailable", "attempt_process_supervisor_start_failed", "attempt_process_supervisor_start_timeout"].includes(code)) {
485
488
  return facts(code, "transport", "prepare", source, "retryable", "retry_dispatch");
486
489
  }
package/dist/version.d.ts CHANGED
@@ -1 +1 @@
1
- export declare const forgeBridgeVersion = "0.1.4-dev.41da3780c451";
1
+ export declare const forgeBridgeVersion = "0.1.4-dev.494233aa2e50";
package/dist/version.js CHANGED
@@ -1 +1 @@
1
- export const forgeBridgeVersion = "0.1.4-dev.41da3780c451";
1
+ export const forgeBridgeVersion = "0.1.4-dev.494233aa2e50";
@@ -36,6 +36,7 @@ const dependencyPreparationCoordinator = new RepositoryCoordinatorLock(defaultWo
36
36
  export async function detectWarmPaths(repoRoot, warmPathOverrides = []) {
37
37
  const entries = new Map();
38
38
  await collectDetectedPaths(repoRoot, repoRoot, entries, 0);
39
+ await collectSolutionProjectRestores(repoRoot, entries);
39
40
  for (const override of warmPathOverrides) {
40
41
  const normalized = normalizeRelativePath(override);
41
42
  if (!normalized) {
@@ -539,6 +540,79 @@ async function hasPythonMarker(dir) {
539
540
  return (await pathExists(path.join(dir, "pyproject.toml")))
540
541
  || (await pathExists(path.join(dir, "requirements.txt")));
541
542
  }
543
+ const solutionProjectPattern = /^Project\("\{[0-9A-Fa-f-]+\}"\)\s*=\s*"[^"]*"\s*,\s*"([^"]+\.(?:cs|fs|vb)proj)"/gimu;
544
+ const slnxProjectPattern = /<Project\b[^>]*\bPath\s*=\s*"([^"]+\.(?:cs|fs|vb)proj)"/giu;
545
+ const projectFilePattern = /\.(?:cs|fs|vb)proj$/iu;
546
+ const solutionFilePattern = /\.(?:sln|slnx|slnf)$/iu;
547
+ /**
548
+ * A worktree built from a never-built base checkout (a fresh runner clone has no bin/ or obj/)
549
+ * still needs its .NET projects restored, or the --no-restore runtime build fails with NETSDK1004.
550
+ * Restore exactly the projects the root solution(s) (.sln, .slnx, .slnf) list, or a lone root
551
+ * project when there is no solution. Other projects (fixtures, samples) keep the base-checkout
552
+ * output heuristic above.
553
+ */
554
+ async function collectSolutionProjectRestores(repoRoot, entries) {
555
+ const rootNames = await fs.readdir(repoRoot).catch(() => []);
556
+ const solutions = rootNames.filter((name) => solutionFilePattern.test(name));
557
+ if (solutions.length === 0) {
558
+ const rootProjects = rootNames.filter((name) => name.toLowerCase().endsWith(".csproj"));
559
+ if (rootProjects.length === 1) {
560
+ addEntry(entries, repoRoot, "", "obj", "dotnet", "obj");
561
+ }
562
+ return;
563
+ }
564
+ for (const solution of solutions) {
565
+ for (const listed of await readSolutionProjectPaths(repoRoot, solution)) {
566
+ const projectPath = path.posix.normalize(normalizeRelativePath(listed));
567
+ if (!projectPath || projectPath === ".." || projectPath.startsWith("../") || path.posix.isAbsolute(projectPath)) {
568
+ continue;
569
+ }
570
+ const absoluteProject = path.resolve(repoRoot, ...projectPath.split("/"));
571
+ if (!isSubPath(repoRoot, absoluteProject) || !(await pathExists(absoluteProject))) {
572
+ continue;
573
+ }
574
+ const projectDir = path.posix.dirname(projectPath);
575
+ // The fallback runs a bare `dotnet restore` in the project's directory. Beside the solution,
576
+ // or next to another project file, that restore is ambiguous (MSB1011); leave those layouts
577
+ // to the base-checkout output heuristic.
578
+ if (projectDir === "." || (await countProjectFiles(path.dirname(absoluteProject))) !== 1) {
579
+ continue;
580
+ }
581
+ addEntry(entries, repoRoot, projectDir, "obj", "dotnet", joinRelative(projectDir, "obj"));
582
+ }
583
+ }
584
+ }
585
+ /** Project paths a root solution lists, relative to the repo root (forward slashes). */
586
+ async function readSolutionProjectPaths(repoRoot, solution) {
587
+ const text = await fs.readFile(path.join(repoRoot, solution), "utf8").catch(() => "");
588
+ const lower = solution.toLowerCase();
589
+ if (lower.endsWith(".sln")) {
590
+ return [...text.matchAll(solutionProjectPattern)].map((match) => match[1].replace(/\\/g, "/"));
591
+ }
592
+ if (lower.endsWith(".slnx")) {
593
+ return [...text.matchAll(slnxProjectPattern)].map((match) => match[1].replace(/\\/g, "/"));
594
+ }
595
+ // .slnf: {"solution": {"path": "<solution>", "projects": [...]}}, projects relative to that solution.
596
+ let filter;
597
+ try {
598
+ filter = JSON.parse(text.replace(/^\uFEFF/u, ""));
599
+ }
600
+ catch {
601
+ return [];
602
+ }
603
+ const body = filter?.solution;
604
+ if (!body || typeof body.path !== "string" || !Array.isArray(body.projects)) {
605
+ return [];
606
+ }
607
+ const solutionDir = path.posix.dirname(body.path.replace(/\\/g, "/"));
608
+ return body.projects
609
+ .filter((project) => typeof project === "string" && projectFilePattern.test(project))
610
+ .map((project) => path.posix.join(solutionDir, project.replace(/\\/g, "/")));
611
+ }
612
+ async function countProjectFiles(dir) {
613
+ const names = await fs.readdir(dir).catch(() => []);
614
+ return names.filter((name) => projectFilePattern.test(name)).length;
615
+ }
542
616
  async function hasDotNetMarker(dir) {
543
617
  const entries = await fs.readdir(dir).catch(() => []);
544
618
  return entries.some((name) => name.endsWith(".csproj") || name.endsWith(".sln"));
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@loucompanion/forge-bridge",
3
- "version": "0.1.4-dev.41da3780c451",
3
+ "version": "0.1.4-dev.494233aa2e50",
4
4
  "description": "Forge runner bridge CLI for connecting local developer machines to Forge dispatch.",
5
5
  "license": "UNLICENSED",
6
6
  "type": "module",