@loucompanion/forge-bridge 0.1.4-dev.e83e5bc6ecce → 0.1.4-dev.efc418893964

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 (136) hide show
  1. package/README.md +56 -1
  2. package/dist/bridge/bridge-chat-provider-command.d.ts +19 -0
  3. package/dist/bridge/bridge-chat-provider-command.js +132 -0
  4. package/dist/bridge/bridge-chat.types.d.ts +10 -0
  5. package/dist/bridge/bridge-chat.types.js +16 -1
  6. package/dist/bridge/bridge.base.d.ts +9 -0
  7. package/dist/bridge/bridge.service.d.ts +71 -2
  8. package/dist/bridge/bridge.service.js +282 -114
  9. package/dist/bridge/bridge.types.d.ts +11 -0
  10. package/dist/bridge/local-yield-flag.d.ts +6 -0
  11. package/dist/bridge/local-yield-flag.js +34 -0
  12. package/dist/bridge/runner-host-capabilities.d.ts +3 -0
  13. package/dist/bridge/runner-host-capabilities.js +13 -0
  14. package/dist/cli/cli.help.js +18 -0
  15. package/dist/cli/cli.service.d.ts +16 -0
  16. package/dist/cli/cli.service.js +132 -14
  17. package/dist/cli/local-config.d.ts +4 -0
  18. package/dist/cli/local-config.js +26 -4
  19. package/dist/runtime/aspnet-runtime-prebuild.d.ts +5 -0
  20. package/dist/runtime/aspnet-runtime-prebuild.js +138 -6
  21. package/dist/runtime/attempt-database-broker.d.ts +1 -1
  22. package/dist/runtime/docker-engine-probe.d.ts +5 -0
  23. package/dist/runtime/docker-engine-probe.js +7 -0
  24. package/dist/runtime/ephemeral-test-postgres-grant.d.ts +37 -0
  25. package/dist/runtime/ephemeral-test-postgres-grant.js +85 -0
  26. package/dist/runtime/ephemeral-test-postgres.d.ts +57 -0
  27. package/dist/runtime/ephemeral-test-postgres.js +303 -0
  28. package/dist/runtime/host-facts.d.ts +2 -1
  29. package/dist/runtime/host-load-admission.d.ts +18 -3
  30. package/dist/runtime/host-load-admission.js +19 -4
  31. package/dist/runtime/host-load-child-environment.d.ts +11 -6
  32. package/dist/runtime/host-load-child-environment.js +22 -11
  33. package/dist/runtime/host-load-governor-config.d.ts +19 -1
  34. package/dist/runtime/host-load-governor-config.js +37 -0
  35. package/dist/runtime/host-load-governor.d.ts +12 -0
  36. package/dist/runtime/host-load-governor.js +139 -26
  37. package/dist/runtime/host-load-runtime-settings.d.ts +25 -0
  38. package/dist/runtime/host-load-runtime-settings.js +78 -0
  39. package/dist/runtime/host-load-sampler.d.ts +34 -4
  40. package/dist/runtime/host-load-sampler.js +73 -7
  41. package/dist/runtime/host-load-step-class.d.ts +3 -1
  42. package/dist/runtime/host-load-step-class.js +60 -5
  43. package/dist/runtime/host-load-test-slot.d.ts +43 -0
  44. package/dist/runtime/host-load-test-slot.js +81 -0
  45. package/dist/runtime/host-load-token-ledger.d.ts +26 -0
  46. package/dist/runtime/host-load-token-ledger.js +93 -61
  47. package/dist/runtime/host-load-windows-cpu.d.ts +34 -0
  48. package/dist/runtime/host-load-windows-cpu.js +85 -0
  49. package/dist/runtime/host-runtime-contract.d.ts +12 -0
  50. package/dist/runtime/host-runtime-contract.js +29 -1
  51. package/dist/runtime/host-runtime-lease.d.ts +59 -3
  52. package/dist/runtime/host-runtime-lease.js +209 -58
  53. package/dist/runtime/host-runtime-promotion.d.ts +23 -0
  54. package/dist/runtime/host-runtime-promotion.js +36 -0
  55. package/dist/runtime/native-test-postgres-fallback.d.ts +51 -7
  56. package/dist/runtime/native-test-postgres-fallback.js +60 -8
  57. package/dist/runtime/playwright-host-runtime-adapter.d.ts +7 -0
  58. package/dist/runtime/playwright-host-runtime-adapter.js +13 -1
  59. package/dist/runtime/runner-settings.d.ts +100 -0
  60. package/dist/runtime/runner-settings.js +214 -0
  61. package/dist/sandbox/host-capacity-broker.d.ts +7 -1
  62. package/dist/sandbox/host-capacity-broker.js +23 -4
  63. package/dist/session/architect-waits.d.ts +2 -0
  64. package/dist/session/architect-waits.js +138 -0
  65. package/dist/session/managed-attempt-tools.d.ts +0 -7
  66. package/dist/session/managed-attempt-tools.js +51 -62
  67. package/dist/session/managed-command-host-load.d.ts +2 -0
  68. package/dist/session/managed-command-host-load.js +2 -1
  69. package/dist/session/phase-completion.artifacts.js +2 -1
  70. package/dist/session/phase-completion.d.ts +8 -0
  71. package/dist/session/phase-completion.js +1 -0
  72. package/dist/session/phase-completion.mcp-args.d.ts +9 -0
  73. package/dist/session/phase-completion.mcp-args.js +156 -0
  74. package/dist/session/phase-completion.runtime.d.ts +0 -8
  75. package/dist/session/phase-completion.runtime.js +43 -197
  76. package/dist/session/phase-completion.schemas.js +25 -23
  77. package/dist/session/phase-completion.validation.js +3 -1
  78. package/dist/session/pre-publication-native-postgres.d.ts +30 -0
  79. package/dist/session/pre-publication-native-postgres.js +111 -0
  80. package/dist/session/pre-publication-pass.d.ts +61 -0
  81. package/dist/session/pre-publication-pass.js +148 -0
  82. package/dist/session/pre-publication-step-execution.d.ts +2 -1
  83. package/dist/session/pre-publication-step-execution.js +6 -5
  84. package/dist/session/pre-publication-validation.d.ts +30 -14
  85. package/dist/session/pre-publication-validation.js +207 -134
  86. package/dist/session/provider-cli/claude-background-work.d.ts +67 -0
  87. package/dist/session/provider-cli/claude-background-work.js +181 -0
  88. package/dist/session/provider-cli/host-build-lock.d.ts +18 -0
  89. package/dist/session/provider-cli/host-build-lock.js +30 -0
  90. package/dist/session/provider-cli/pre-publication-repair.d.ts +56 -0
  91. package/dist/session/provider-cli/pre-publication-repair.js +276 -0
  92. package/dist/session/provider-cli/provider-cli.child-environment.d.ts +7 -0
  93. package/dist/session/provider-cli/provider-cli.child-environment.js +75 -0
  94. package/dist/session/provider-cli/provider-cli.codex-models-cache.d.ts +3 -0
  95. package/dist/session/provider-cli/provider-cli.codex-models-cache.js +37 -0
  96. package/dist/session/provider-cli/provider-cli.process.d.ts +15 -36
  97. package/dist/session/provider-cli/provider-cli.process.js +39 -430
  98. package/dist/session/provider-cli/provider-cli.prompts.d.ts +5 -0
  99. package/dist/session/provider-cli/provider-cli.prompts.js +71 -31
  100. package/dist/session/provider-cli/provider-cli.runtime.d.ts +8 -0
  101. package/dist/session/provider-cli/provider-cli.runtime.js +29 -1
  102. package/dist/session/provider-cli/provider-cli.service.d.ts +7 -1
  103. package/dist/session/provider-cli/provider-cli.service.js +78 -171
  104. package/dist/session/provider-cli/provider-cli.types.d.ts +26 -0
  105. package/dist/session/provider-cli/provider-cli.windows-environment.d.ts +10 -0
  106. package/dist/session/provider-cli/provider-cli.windows-environment.js +151 -0
  107. package/dist/session/provider-cli/provider-cli.windows-launch.d.ts +23 -0
  108. package/dist/session/provider-cli/provider-cli.windows-launch.js +131 -0
  109. package/dist/session/provider-cli/provider-in-flight-work.d.ts +4 -0
  110. package/dist/session/provider-cli/provider-in-flight-work.js +45 -0
  111. package/dist/session/provider-cli/provider-output-pipes.d.ts +30 -0
  112. package/dist/session/provider-cli/provider-output-pipes.js +67 -0
  113. package/dist/session/provider-cli/provider-output-state.d.ts +2 -0
  114. package/dist/session/provider-cli/provider-output-state.js +6 -0
  115. package/dist/session/provider-cli/provider-user-config-isolation.d.ts +69 -0
  116. package/dist/session/provider-cli/provider-user-config-isolation.js +164 -0
  117. package/dist/session/qa-sidecar-validation.d.ts +6 -0
  118. package/dist/session/qa-sidecar-validation.js +28 -0
  119. package/dist/session/sandbox-host-capacity-gate.js +12 -3
  120. package/dist/session/session-redaction.js +31 -181
  121. package/dist/session/session.base.d.ts +6 -1
  122. package/dist/session/session.service.d.ts +7 -2
  123. package/dist/session/session.service.js +100 -2
  124. package/dist/session/session.types.js +4 -4
  125. package/dist/session/sidecar-json-shape.d.ts +31 -0
  126. package/dist/session/sidecar-json-shape.js +217 -0
  127. package/dist/session/workspace-runtime-fingerprint.d.ts +32 -0
  128. package/dist/session/workspace-runtime-fingerprint.js +138 -0
  129. package/dist/shared/process/windows-app-execution-alias.d.ts +19 -0
  130. package/dist/shared/process/windows-app-execution-alias.js +45 -0
  131. package/dist/shared/process/windows-launch.d.ts +18 -0
  132. package/dist/shared/process/windows-launch.js +68 -0
  133. package/dist/shared/provider-capabilities.js +14 -7
  134. package/dist/version.d.ts +1 -1
  135. package/dist/version.js +1 -1
  136. package/package.json +2 -2
@@ -0,0 +1,217 @@
1
+ import { TextDecoder } from "node:util";
2
+ // One set of JSON shape rules for result sidecars. The end-of-run secret check and the QA gate
3
+ // tools that record sidecars during the run both use it, so the agent is told about a malformed
4
+ // sidecar while it can still rewrite the file, and the end-of-run check never disagrees with it.
5
+ //
6
+ // Content sniffing is deliberate: any sidecar whose text starts like JSON ("{", "[" or '"') is
7
+ // held to strict JSON, whatever its file name, so JSON escapes cannot hide secret material from
8
+ // the byte scan. Only a parseable document can be checked token by token.
9
+ export const maximumIntegrityJsonBytes = 8 * 1024 * 1024;
10
+ const maximumIntegrityJsonDepth = 128;
11
+ const maximumIntegrityJsonTokens = 262_144;
12
+ const jsonEscapePattern = /\\(?:u([0-9a-fA-F]{4})|(["\\/bfnrt]))/gu;
13
+ const simpleJsonEscapes = {
14
+ "\"": "\"", "\\": "\\", "/": "/", b: "\b", f: "\f", n: "\n", r: "\r", t: "\t",
15
+ };
16
+ /** A JSON text that breaks a shape rule. `reason` names the rule and never quotes file content. */
17
+ export class JsonShapeError extends Error {
18
+ reason;
19
+ constructor(reason) {
20
+ super(reason);
21
+ this.reason = reason;
22
+ this.name = "JsonShapeError";
23
+ }
24
+ }
25
+ export const oversizedJsonReason = "it is larger than the 8 MiB JSON inspection limit";
26
+ /**
27
+ * Checks a bounded JSON text and calls `onString` with every decoded string token (property names
28
+ * and values). Throws JsonShapeError for a shape problem; errors thrown by `onString` propagate.
29
+ */
30
+ export function inspectJsonText(value, onString) {
31
+ if (Buffer.byteLength(value, "utf8") > maximumIntegrityJsonBytes)
32
+ throw new JsonShapeError(oversizedJsonReason);
33
+ if (value.trim().length === 0)
34
+ throw new JsonShapeError("the file is empty");
35
+ const containers = [];
36
+ let tokenCount = 0;
37
+ let index = 0;
38
+ while (index < value.length) {
39
+ const code = value.charCodeAt(index);
40
+ if (isJsonWhitespace(code) || code === 0x2c || code === 0x3a) {
41
+ index += 1;
42
+ continue;
43
+ }
44
+ tokenCount += 1;
45
+ if (tokenCount > maximumIntegrityJsonTokens) {
46
+ throw new JsonShapeError(`it has more than ${maximumIntegrityJsonTokens} JSON tokens`);
47
+ }
48
+ index = inspectJsonToken(value, index, containers, onString);
49
+ }
50
+ if (containers.length !== 0)
51
+ throw new JsonShapeError("a bracket or brace is never closed");
52
+ assertJsonParses(value);
53
+ }
54
+ function inspectJsonToken(value, index, containers, onString) {
55
+ const code = value.charCodeAt(index);
56
+ if (code === 0x22) {
57
+ const token = decodeJsonStringToken(value, index);
58
+ onString?.(token.decoded);
59
+ return token.nextIndex;
60
+ }
61
+ if (code === 0x7b || code === 0x5b) {
62
+ containers.push(code);
63
+ if (containers.length > maximumIntegrityJsonDepth) {
64
+ throw new JsonShapeError(`it nests deeper than ${maximumIntegrityJsonDepth} levels`);
65
+ }
66
+ return index + 1;
67
+ }
68
+ if (code === 0x7d || code === 0x5d) {
69
+ if (containers.pop() !== (code === 0x7d ? 0x7b : 0x5b)) {
70
+ throw new JsonShapeError(`an unmatched closing bracket or brace ${locationOf(value, index)}`);
71
+ }
72
+ return index + 1;
73
+ }
74
+ let end = index + 1;
75
+ while (end < value.length && !isJsonWhitespace(value.charCodeAt(end)) && !isJsonPunctuation(value.charCodeAt(end))) {
76
+ end += 1;
77
+ }
78
+ return end;
79
+ }
80
+ function assertJsonParses(value) {
81
+ try {
82
+ JSON.parse(value);
83
+ }
84
+ catch (error) {
85
+ // The parser's message can quote the offending text; keep only its position.
86
+ const message = error instanceof Error ? error.message : "";
87
+ const position = /\bposition (\d+)/u.exec(message);
88
+ const location = position ? ` ${locationOf(value, Number(position[1]))}` : "";
89
+ throw new JsonShapeError(message.includes("after JSON")
90
+ ? `unexpected text after the JSON value${location}`
91
+ : `invalid JSON syntax${location}`);
92
+ }
93
+ }
94
+ export function decodeJsonStringToken(value, openingQuoteIndex) {
95
+ const chunks = [];
96
+ let segmentStart = openingQuoteIndex + 1;
97
+ let index = segmentStart;
98
+ while (index < value.length) {
99
+ const code = value.charCodeAt(index);
100
+ if (code === 0x22) {
101
+ chunks.push(value.slice(segmentStart, index));
102
+ const decoded = chunks.join("");
103
+ if (!isWellFormedUnicode(decoded)) {
104
+ throw new JsonShapeError(`a string has an unpaired Unicode surrogate ${locationOf(value, openingQuoteIndex)}`);
105
+ }
106
+ return { decoded, nextIndex: index + 1 };
107
+ }
108
+ if (code < 0x20) {
109
+ throw new JsonShapeError(`a string contains a raw control character ${locationOf(value, index)}`);
110
+ }
111
+ if (code !== 0x5c) {
112
+ index += 1;
113
+ continue;
114
+ }
115
+ chunks.push(value.slice(segmentStart, index));
116
+ const escape = decodeJsonEscape(value, index);
117
+ chunks.push(escape.decoded);
118
+ index = escape.nextIndex;
119
+ segmentStart = index;
120
+ }
121
+ throw new JsonShapeError(`a string is never closed ${locationOf(value, openingQuoteIndex)}`);
122
+ }
123
+ function decodeJsonEscape(value, backslashIndex) {
124
+ const escaped = value[backslashIndex + 1];
125
+ const simple = escaped === undefined ? undefined : simpleJsonEscapes[escaped];
126
+ if (simple !== undefined)
127
+ return { decoded: simple, nextIndex: backslashIndex + 2 };
128
+ const hex = value.slice(backslashIndex + 2, backslashIndex + 6);
129
+ if (escaped !== "u" || !/^[0-9a-fA-F]{4}$/u.test(hex)) {
130
+ throw new JsonShapeError(`a string has an invalid escape sequence ${locationOf(value, backslashIndex)}`);
131
+ }
132
+ return { decoded: String.fromCharCode(Number.parseInt(hex, 16)), nextIndex: backslashIndex + 6 };
133
+ }
134
+ /**
135
+ * Why a sidecar that looks like JSON is not acceptable JSON, or null when it is fine: valid JSON,
136
+ * plain text that does not start like JSON, or binary content that is not named *.json.
137
+ */
138
+ export function sidecarJsonShapeProblem(content, path, onString) {
139
+ let decoded;
140
+ try {
141
+ decoded = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(content);
142
+ }
143
+ catch {
144
+ // Sniff the bytes anyway (invalid sequences decode to U+FFFD, which is not whitespace), so a
145
+ // file that starts like JSON cannot dodge the strict check with a stray invalid byte.
146
+ return looksLikeJson(Buffer.from(content).toString("utf8"), path) ? "the file is not valid UTF-8" : null;
147
+ }
148
+ if (!looksLikeJson(decoded, path))
149
+ return null;
150
+ if (content.length >= 3 && content[0] === 0xef && content[1] === 0xbb && content[2] === 0xbf) {
151
+ return "the file starts with a UTF-8 byte-order mark";
152
+ }
153
+ try {
154
+ inspectJsonText(decoded, onString);
155
+ return null;
156
+ }
157
+ catch (error) {
158
+ if (error instanceof JsonShapeError)
159
+ return error.reason;
160
+ throw error;
161
+ }
162
+ }
163
+ /** The instruction an agent gets when it records a sidecar that fails the shape check. */
164
+ export function sidecarJsonRepairInstruction(path, reason) {
165
+ const fix = isJsonFileName(path)
166
+ ? "Rewrite it as valid JSON (UTF-8, no byte-order mark), or save plain-text output under a name that does not end in .json"
167
+ : "Rewrite it as valid JSON, or as plain text that does not start with \"[\", \"{\" or a double quote (for example, put a title line first)";
168
+ return `${path} looks like JSON but is not valid JSON (${reason}). Forge rejects sidecars it cannot fully inspect. `
169
+ + `${fix}, then resubmit with the file's new bytes and content_hash.`;
170
+ }
171
+ /**
172
+ * Best-effort decoding of every JSON escape in a text that failed the shape check, so a secret
173
+ * hidden behind escapes still gets the secret error rather than the malformed-sidecar error.
174
+ */
175
+ export function decodeJsonEscapesLeniently(value) {
176
+ return value.replace(jsonEscapePattern, (_match, hex, simple) => hex !== undefined ? String.fromCharCode(Number.parseInt(hex, 16)) : simpleJsonEscapes[simple ?? ""] ?? "");
177
+ }
178
+ export function looksLikeJson(value, path) {
179
+ if (isJsonFileName(path))
180
+ return true;
181
+ const candidate = value.trimStart().replace(/^\uFEFF/u, "").trimStart();
182
+ return candidate.startsWith("{") || candidate.startsWith("[") || candidate.startsWith("\"");
183
+ }
184
+ function isJsonFileName(path) {
185
+ return path.toLowerCase().endsWith(".json");
186
+ }
187
+ function locationOf(value, index) {
188
+ let line = 1;
189
+ let lineStart = 0;
190
+ for (let cursor = value.indexOf("\n"); cursor >= 0 && cursor < index; cursor = value.indexOf("\n", cursor + 1)) {
191
+ line += 1;
192
+ lineStart = cursor + 1;
193
+ }
194
+ return `at line ${line}, column ${index - lineStart + 1}`;
195
+ }
196
+ function isWellFormedUnicode(value) {
197
+ for (let index = 0; index < value.length; index += 1) {
198
+ const code = value.charCodeAt(index);
199
+ if (code >= 0xd800 && code <= 0xdbff) {
200
+ const next = value.charCodeAt(index + 1);
201
+ if (!(next >= 0xdc00 && next <= 0xdfff))
202
+ return false;
203
+ index += 1;
204
+ }
205
+ else if (code >= 0xdc00 && code <= 0xdfff) {
206
+ return false;
207
+ }
208
+ }
209
+ return true;
210
+ }
211
+ export function isJsonWhitespace(code) {
212
+ return code === 0x20 || code === 0x09 || code === 0x0a || code === 0x0d;
213
+ }
214
+ export function isJsonPunctuation(code) {
215
+ return code === 0x7b || code === 0x7d || code === 0x5b || code === 0x5d
216
+ || code === 0x2c || code === 0x3a || code === 0x22;
217
+ }
@@ -0,0 +1,32 @@
1
+ import { GitClient } from "../shared/git/git.js";
2
+ /**
3
+ * What the attempt's host runtime stack was built and launched from. When the
4
+ * workspace no longer matches, the running API binary and dev server are stale:
5
+ * an uncommitted edit or an in-progress `merge --no-commit` changes the source
6
+ * without moving HEAD.
7
+ */
8
+ export interface WorkspaceRuntimeFingerprint {
9
+ readonly headSha: string;
10
+ /** Contents of MERGE_HEAD while a merge is in progress, else null. */
11
+ readonly mergeHead: string | null;
12
+ /** sha256 of `git diff HEAD --binary` (staged and unstaged changes to tracked files, mode changes included). */
13
+ readonly diffDigest: string;
14
+ /**
15
+ * sha256 over untracked, non-ignored file names, their executable bit, and their contents (or
16
+ * size and mtime for large files).
17
+ */
18
+ readonly untrackedDigest: string;
19
+ /**
20
+ * sha256 over the runtime contract as loaded now and the files its launch commands name. Git's
21
+ * views above skip ignored files, and a project may ignore its contract or a launch script; a
22
+ * change there alters what the stack runs without changing anything git reports.
23
+ */
24
+ readonly runtimeInputsDigest: string;
25
+ /** One digest over every field above. */
26
+ readonly digest: string;
27
+ }
28
+ export type WorkspaceRuntimeFingerprintReader = (worktreePath: string) => Promise<WorkspaceRuntimeFingerprint>;
29
+ export declare function readWorkspaceRuntimeFingerprint(worktreePath: string, git?: Pick<GitClient, "run">): Promise<WorkspaceRuntimeFingerprint>;
30
+ export declare function sameWorkspaceRuntimeFingerprint(left: WorkspaceRuntimeFingerprint | null, right: WorkspaceRuntimeFingerprint | null): boolean;
31
+ /** Names what changed between two fingerprints, for the restart checkpoint. */
32
+ export declare function workspaceRuntimeFingerprintChanges(previous: WorkspaceRuntimeFingerprint | null, current: WorkspaceRuntimeFingerprint): readonly string[];
@@ -0,0 +1,138 @@
1
+ import { createHash } from "node:crypto";
2
+ import fs from "node:fs/promises";
3
+ import path from "node:path";
4
+ import { GitClient } from "../shared/git/git.js";
5
+ import { loadHostRuntimeContract } from "../runtime/host-runtime-contract.js";
6
+ import { hostRuntimeContractFingerprint } from "../runtime/host-runtime-promotion.js";
7
+ import { isRuntimeOnlyPath } from "./publishable-worktree-changes.js";
8
+ /** Untracked files up to this size are hashed by content; larger ones by size and mtime. */
9
+ const untrackedContentHashLimitBytes = 1024 * 1024;
10
+ /**
11
+ * Forge's own runtime output never changes what the application runs, and Forge
12
+ * rewrites some of it (readiness manifests, completion artifacts) between passes.
13
+ */
14
+ const runtimeOnlyPathspecs = [
15
+ ":(exclude).local",
16
+ ":(exclude).forge/work-items",
17
+ ":(exclude).forge/stories",
18
+ ];
19
+ export async function readWorkspaceRuntimeFingerprint(worktreePath, git = new GitClient()) {
20
+ const headSha = (await git.run(worktreePath, ["rev-parse", "--verify", "HEAD^{commit}"])).trim().toLowerCase();
21
+ const mergeHead = await readMergeHead(git, worktreePath);
22
+ // A mode change (chmod +x on a launch script) changes what runs. The repository may set
23
+ // core.fileMode=false, which would drop it from the diff, so this read always records modes.
24
+ const diff = await git.run(worktreePath, ["-c", "core.fileMode=true", "diff", "HEAD", "--binary", "--no-ext-diff", "--no-textconv", "--", ".", ...runtimeOnlyPathspecs]);
25
+ const diffDigest = sha256(diff);
26
+ const untracked = (await git.run(worktreePath, [
27
+ "ls-files", "--others", "--exclude-standard", "-z", "--", ".", ...runtimeOnlyPathspecs,
28
+ ]))
29
+ .split("\0")
30
+ .filter(entry => entry.length > 0 && !isRuntimeOnlyPath(entry))
31
+ .sort((left, right) => left.localeCompare(right));
32
+ const untrackedHash = createHash("sha256");
33
+ for (const relative of untracked) {
34
+ untrackedHash.update(relative).update("\0");
35
+ const absolute = path.join(worktreePath, relative);
36
+ const stat = await fs.lstat(absolute).catch(() => null);
37
+ if (!stat) {
38
+ untrackedHash.update("missing\0");
39
+ continue;
40
+ }
41
+ // Like git, record the executable bit: chmod changes what runs without touching content or mtime.
42
+ untrackedHash.update(stat.isFile() && (stat.mode & 0o111) !== 0 ? "exec\0" : "plain\0");
43
+ if (stat.isFile() && stat.size <= untrackedContentHashLimitBytes) {
44
+ const content = await fs.readFile(absolute).catch(() => null);
45
+ untrackedHash.update(content ? `content:${sha256(content)}\0` : `unreadable:${stat.size}:${stat.mtimeMs}\0`);
46
+ }
47
+ else {
48
+ untrackedHash.update(`stat:${stat.size}:${stat.mtimeMs}\0`);
49
+ }
50
+ }
51
+ const untrackedDigest = `sha256:${untrackedHash.digest("hex")}`;
52
+ const runtimeInputsDigest = await readRuntimeInputsDigest(worktreePath);
53
+ const digest = sha256(JSON.stringify({ headSha, mergeHead, diffDigest, untrackedDigest, runtimeInputsDigest }));
54
+ return { headSha, mergeHead, diffDigest, untrackedDigest, runtimeInputsDigest, digest };
55
+ }
56
+ export function sameWorkspaceRuntimeFingerprint(left, right) {
57
+ return left !== null && right !== null && left.digest === right.digest;
58
+ }
59
+ /** Names what changed between two fingerprints, for the restart checkpoint. */
60
+ export function workspaceRuntimeFingerprintChanges(previous, current) {
61
+ if (!previous)
62
+ return ["unrecorded"];
63
+ const changes = [];
64
+ if (previous.headSha !== current.headSha)
65
+ changes.push("head");
66
+ if (previous.mergeHead !== current.mergeHead)
67
+ changes.push("merge_head");
68
+ if (previous.diffDigest !== current.diffDigest)
69
+ changes.push("tracked_changes");
70
+ if (previous.untrackedDigest !== current.untrackedDigest)
71
+ changes.push("untracked_files");
72
+ if (previous.runtimeInputsDigest !== current.runtimeInputsDigest)
73
+ changes.push("runtime_inputs");
74
+ return changes;
75
+ }
76
+ /**
77
+ * The loaded runtime contract (project file or derived) and each regular file inside the worktree
78
+ * that a configured launch names as its command or an argument, by executable bit and content.
79
+ * Ignored or not: these are exactly what the stack was launched from. Nothing else ignored is read.
80
+ */
81
+ async function readRuntimeInputsDigest(worktreePath) {
82
+ const hash = createHash("sha256");
83
+ let contract;
84
+ try {
85
+ contract = await loadHostRuntimeContract(worktreePath);
86
+ }
87
+ catch (error) {
88
+ // An unloadable contract is a state of its own; the restart reports why it cannot load.
89
+ const message = error instanceof Error ? error.message : String(error);
90
+ return sha256(`unloadable:${message.split(":", 1)[0]}`);
91
+ }
92
+ hash.update(`contract:${hostRuntimeContractFingerprint(contract)}\0`);
93
+ const root = await fs.realpath(worktreePath);
94
+ const named = new Set();
95
+ for (const port of contract.contract.runtime.ports) {
96
+ if (!port.launch)
97
+ continue;
98
+ const workingDirectory = path.resolve(root, port.launch.workingDirectory);
99
+ for (const candidate of [port.launch.command, ...port.launch.args]) {
100
+ if (!candidate || candidate.startsWith("-"))
101
+ continue;
102
+ const absolute = path.resolve(workingDirectory, candidate);
103
+ const relative = path.relative(root, absolute);
104
+ if (relative === "" || relative.startsWith("..") || path.isAbsolute(relative))
105
+ continue;
106
+ named.add(relative);
107
+ }
108
+ }
109
+ for (const relative of [...named].sort((left, right) => left.localeCompare(right))) {
110
+ const stat = await fs.stat(path.join(root, relative)).catch(() => null);
111
+ if (!stat?.isFile())
112
+ continue;
113
+ hash.update(relative).update("\0").update((stat.mode & 0o111) !== 0 ? "exec\0" : "plain\0");
114
+ if (stat.size <= untrackedContentHashLimitBytes) {
115
+ const content = await fs.readFile(path.join(root, relative)).catch(() => null);
116
+ hash.update(content ? `content:${sha256(content)}\0` : `unreadable:${stat.size}:${stat.mtimeMs}\0`);
117
+ }
118
+ else {
119
+ hash.update(`stat:${stat.size}:${stat.mtimeMs}\0`);
120
+ }
121
+ }
122
+ return `sha256:${hash.digest("hex")}`;
123
+ }
124
+ async function readMergeHead(git, worktreePath) {
125
+ const relative = (await git.run(worktreePath, ["rev-parse", "--git-path", "MERGE_HEAD"])).trim();
126
+ if (!relative)
127
+ return null;
128
+ const mergeHeadPath = path.resolve(worktreePath, relative);
129
+ const content = await fs.readFile(mergeHeadPath, "utf8").catch((error) => {
130
+ if (error.code === "ENOENT")
131
+ return null;
132
+ throw error;
133
+ });
134
+ return content === null ? null : content.trim().toLowerCase();
135
+ }
136
+ function sha256(value) {
137
+ return `sha256:${createHash("sha256").update(value).digest("hex")}`;
138
+ }
@@ -0,0 +1,19 @@
1
+ /**
2
+ * Tools an agent commonly starts by bare name. When one of them resolves to a Microsoft Store
3
+ * app-execution alias (`%LOCALAPPDATA%\Microsoft\WindowsApps\pwsh.exe` and the like), Windows
4
+ * creates the process it starts outside the provider's Job Object: it survives the job, keeps the
5
+ * pipe handles it inherited, and holds the attempt's output open until it exits on its own.
6
+ */
7
+ export declare const APP_EXECUTION_ALIAS_SENSITIVE_TOOLS: readonly ["pwsh", "node", "dotnet"];
8
+ export interface AppExecutionAliasFinding {
9
+ readonly tool: string;
10
+ /** The alias the tool's bare name resolves to. */
11
+ readonly aliasPath: string;
12
+ /** The first regular install later on PATH, or null when the alias is the only one. */
13
+ readonly nextInstallPath: string | null;
14
+ }
15
+ /** The sensitive tools whose bare name resolves, on this PATH, to an app-execution alias. */
16
+ export declare function findAppExecutionAliasTools(pathValue: string, pathExtValue?: string, tools?: readonly string[]): AppExecutionAliasFinding[];
17
+ export declare function describeAppExecutionAliasFindings(findings: readonly AppExecutionAliasFinding[]): string | null;
18
+ /** Reads PATH and PATHEXT from an environment whose key case is not normalized (Windows: "Path"). */
19
+ export declare function appExecutionAliasWarning(env: Readonly<Record<string, string | undefined>>, platform?: NodeJS.Platform): string | null;
@@ -0,0 +1,45 @@
1
+ import { isWindowsAppExecutionAliasPath, resolveWindowsCommandFromPath } from "./windows-launch.js";
2
+ /**
3
+ * Tools an agent commonly starts by bare name. When one of them resolves to a Microsoft Store
4
+ * app-execution alias (`%LOCALAPPDATA%\Microsoft\WindowsApps\pwsh.exe` and the like), Windows
5
+ * creates the process it starts outside the provider's Job Object: it survives the job, keeps the
6
+ * pipe handles it inherited, and holds the attempt's output open until it exits on its own.
7
+ */
8
+ export const APP_EXECUTION_ALIAS_SENSITIVE_TOOLS = ["pwsh", "node", "dotnet"];
9
+ /** The sensitive tools whose bare name resolves, on this PATH, to an app-execution alias. */
10
+ export function findAppExecutionAliasTools(pathValue, pathExtValue, tools = APP_EXECUTION_ALIAS_SENSITIVE_TOOLS) {
11
+ const findings = [];
12
+ for (const tool of tools) {
13
+ const aliasPath = resolveWindowsCommandFromPath(tool, pathValue, pathExtValue);
14
+ if (!aliasPath || !isWindowsAppExecutionAliasPath(aliasPath))
15
+ continue;
16
+ const nextInstallPath = resolveWindowsCommandFromPath(tool, pathValue, pathExtValue, { skipAppExecutionAliases: true });
17
+ findings.push({ tool, aliasPath, nextInstallPath });
18
+ }
19
+ return findings;
20
+ }
21
+ export function describeAppExecutionAliasFindings(findings) {
22
+ if (findings.length === 0)
23
+ return null;
24
+ const tools = findings.map(finding => `${finding.tool} -> ${finding.aliasPath}${finding.nextInstallPath
25
+ ? ` (a regular install later on PATH: ${finding.nextInstallPath})`
26
+ : " (no regular install on PATH)"}`);
27
+ return "Host readiness warning: on the provider PATH, "
28
+ + `${tools.join("; ")} resolve${findings.length === 1 ? "s" : ""} to a Microsoft Store app-execution alias under WindowsApps. `
29
+ + "A process started through an alias is created outside the provider's Windows Job Object, survives it, "
30
+ + "and can hold the attempt's output pipes open until it exits. Install the tool normally "
31
+ + "(for PowerShell, the MSI under C:\\Program Files\\PowerShell\\7) and put it ahead of WindowsApps on PATH.";
32
+ }
33
+ /** Reads PATH and PATHEXT from an environment whose key case is not normalized (Windows: "Path"). */
34
+ export function appExecutionAliasWarning(env, platform = process.platform) {
35
+ if (platform !== "win32")
36
+ return null;
37
+ const pathValue = environmentValue(env, "PATH");
38
+ if (!pathValue)
39
+ return null;
40
+ return describeAppExecutionAliasFindings(findAppExecutionAliasTools(pathValue, environmentValue(env, "PATHEXT")));
41
+ }
42
+ function environmentValue(env, name) {
43
+ const key = Object.keys(env).find(candidate => candidate.toUpperCase() === name);
44
+ return key === undefined ? undefined : env[key];
45
+ }
@@ -6,3 +6,21 @@ export declare function buildWindowsCmdLaunch(command: string, args: readonly st
6
6
  export declare function buildWindowsLaunchCommand(commandPath: string, args: readonly string[]): LaunchCommand;
7
7
  export declare function windowsCommandLine(command: string, args: readonly string[]): string;
8
8
  export declare function quoteWindowsCommandLineArg(value: string): string;
9
+ export interface WindowsCommandPathOptions {
10
+ /**
11
+ * Skip candidates under a `WindowsApps` directory. Those are Microsoft Store app-execution
12
+ * aliases: the process they start is created outside the caller's Job Object, so it survives the
13
+ * job and keeps any inherited pipe open. Resolve the next real install on PATH instead.
14
+ */
15
+ readonly skipAppExecutionAliases?: boolean;
16
+ }
17
+ /**
18
+ * Resolves Windows commands without spawning where.exe. Runtime launches can
19
+ * happen while the machine is under enough process pressure for where.exe to
20
+ * miss its timeout; returning the unresolved package-manager name in that case
21
+ * makes Node fall back to a shell shim that cannot survive Job Object wrapping.
22
+ */
23
+ export declare function resolveWindowsCommandFromPath(command: string, pathValue?: string, pathExtValue?: string, options?: WindowsCommandPathOptions): string | null;
24
+ export declare function chooseWindowsCommandCandidate(candidates: readonly string[]): string | null;
25
+ /** True for a path inside a `WindowsApps` directory, where Store app-execution aliases live. */
26
+ export declare function isWindowsAppExecutionAliasPath(candidate: string): boolean;
@@ -1,3 +1,4 @@
1
+ import fs from "node:fs";
1
2
  import path from "node:path";
2
3
  export function buildWindowsCmdLaunch(command, args, comSpec = process.env.ComSpec) {
3
4
  const resolvedComSpec = comSpec?.trim();
@@ -39,3 +40,70 @@ function powershellExecutable() {
39
40
  ? path.join(systemRoot, "System32", "WindowsPowerShell", "v1.0", "powershell.exe")
40
41
  : "powershell.exe";
41
42
  }
43
+ /**
44
+ * Resolves Windows commands without spawning where.exe. Runtime launches can
45
+ * happen while the machine is under enough process pressure for where.exe to
46
+ * miss its timeout; returning the unresolved package-manager name in that case
47
+ * makes Node fall back to a shell shim that cannot survive Job Object wrapping.
48
+ */
49
+ export function resolveWindowsCommandFromPath(command, pathValue = process.env.PATH ?? "", pathExtValue = process.env.PATHEXT ?? ".COM;.EXE;.BAT;.CMD", options = {}) {
50
+ if (!command || path.isAbsolute(command) || command.includes("/") || command.includes("\\")) {
51
+ return null;
52
+ }
53
+ const hasExtension = path.extname(command).length > 0;
54
+ const extensions = hasExtension
55
+ ? [""]
56
+ : [...new Set([
57
+ "",
58
+ ".exe",
59
+ ".ps1",
60
+ ".cmd",
61
+ ".bat",
62
+ ...pathExtValue.split(";").map(value => value.trim().toLowerCase()).filter(Boolean),
63
+ ])];
64
+ for (const rawDirectory of pathValue.split(path.delimiter)) {
65
+ const directory = rawDirectory.trim().replace(/^"|"$/gu, "");
66
+ if (!directory)
67
+ continue;
68
+ const candidates = [];
69
+ for (const extension of extensions) {
70
+ const candidate = path.join(directory, `${command}${extension}`);
71
+ if (options.skipAppExecutionAliases && isWindowsAppExecutionAliasPath(candidate))
72
+ continue;
73
+ if (pathEntryExists(candidate))
74
+ candidates.push(candidate);
75
+ }
76
+ const resolved = chooseWindowsCommandCandidate(candidates);
77
+ if (resolved)
78
+ return resolved;
79
+ }
80
+ return null;
81
+ }
82
+ export function chooseWindowsCommandCandidate(candidates) {
83
+ const normalized = candidates
84
+ .map((candidate) => candidate.trim())
85
+ .filter((candidate) => candidate.length > 0);
86
+ if (normalized.length === 0) {
87
+ return null;
88
+ }
89
+ const preferredExtensions = [".exe", ".ps1", ".cmd", ".bat", ""];
90
+ for (const extension of preferredExtensions) {
91
+ const candidate = normalized.find((entry) => path.extname(entry).toLowerCase() === extension);
92
+ if (candidate) {
93
+ return candidate;
94
+ }
95
+ }
96
+ return normalized[0];
97
+ }
98
+ /** True for a path inside a `WindowsApps` directory, where Store app-execution aliases live. */
99
+ export function isWindowsAppExecutionAliasPath(candidate) {
100
+ return candidate.split(/[\\/]+/u).some(segment => segment.toLowerCase() === "windowsapps");
101
+ }
102
+ // An app-execution alias is a reparse point that stat() may not open, so an
103
+ // alias is also accepted when only lstat() can see it.
104
+ function pathEntryExists(candidate) {
105
+ if (fs.existsSync(candidate))
106
+ return true;
107
+ return isWindowsAppExecutionAliasPath(candidate)
108
+ && fs.lstatSync(candidate, { throwIfNoEntry: false }) !== undefined;
109
+ }
@@ -1,4 +1,5 @@
1
1
  import { bridgeChatProtocolVersion, normalizeBridgeChatCapability, unavailableBridgeChatCapability, } from "../bridge/bridge-chat.types.js";
2
+ import { isProviderUserConfigIsolated, userConfigIsolatedProviders } from "../session/provider-cli/provider-user-config-isolation.js";
2
3
  const defaultBridgeChatMaxMessageBytes = 128 * 1024;
3
4
  const defaultBridgeChatMaxContextRefs = 8;
4
5
  export function supportsDraftImageAttachmentsFor(cliProviders) {
@@ -9,7 +10,14 @@ export function bridgeChatCapabilityFor(cliProviders, providerStatuses, baseCapa
9
10
  if (base.protocolVersion !== bridgeChatProtocolVersion) {
10
11
  return base;
11
12
  }
12
- const providers = chatProviderEntries(cliProviders, providerStatuses);
13
+ const configuredProviders = chatProviderEntries(cliProviders, providerStatuses);
14
+ // Bridge Chat refuses a provider whose user configuration Forge can't keep out of the turn
15
+ // (cursor-agent, unknown CLIs), so it is never offered. The remaining providers decide
16
+ // availability: the server dispatches a turn only to a capability that is fully available.
17
+ const providers = configuredProviders.filter((provider) => isProviderUserConfigIsolated(provider.providerKind));
18
+ if (configuredProviders.length > 0 && providers.length === 0) {
19
+ return unavailableBridgeChatCapability(bridgeChatProtocolVersion, "no_isolated_cli_providers", `Bridge Chat runs only ${userConfigIsolatedProviders.join(" and ")}; Forge can't keep the host user's own configuration out of ${configuredProviders.map((provider) => provider.providerKind).join(", ")}.`);
20
+ }
13
21
  const usableProviders = providers.filter((provider) => provider.status?.signedIn !== false);
14
22
  if (usableProviders.length === 0) {
15
23
  return unavailableBridgeChatCapability(bridgeChatProtocolVersion, providers.length === 0 ? "no_cli_providers" : "no_signed_in_cli_providers", providers.length === 0
@@ -40,8 +48,12 @@ function chatProviderEntries(cliProviders, providerStatuses) {
40
48
  const providerKind = provider.trim().toLowerCase();
41
49
  if (providerKind.length === 0)
42
50
  continue;
43
- statuses.set(providerKind, { providerKind, status });
51
+ statuses.set(providerKind, { status });
44
52
  }
53
+ // Only configured CLI providers can run a Bridge Chat turn. A status entry for a
54
+ // provider that is not in cliProviders (for example a leftover entry in
55
+ // bridge.json for a CLI that is no longer installed) annotates nothing and must
56
+ // not be advertised as a chat provider.
45
57
  const providers = new Map();
46
58
  for (const provider of cliProviders) {
47
59
  const providerKind = provider.trim().toLowerCase();
@@ -52,11 +64,6 @@ function chatProviderEntries(cliProviders, providerStatuses) {
52
64
  status: statuses.get(providerKind)?.status,
53
65
  });
54
66
  }
55
- for (const [providerKind, entry] of statuses) {
56
- if (!providers.has(providerKind)) {
57
- providers.set(providerKind, entry);
58
- }
59
- }
60
67
  return [...providers.values()].sort((left, right) => compareStable(left.providerKind, right.providerKind));
61
68
  }
62
69
  function sortedUniqueStrings(values, lower) {
package/dist/version.d.ts CHANGED
@@ -1 +1 @@
1
- export declare const forgeBridgeVersion = "0.1.4-dev.e83e5bc6ecce";
1
+ export declare const forgeBridgeVersion = "0.1.4-dev.efc418893964";
package/dist/version.js CHANGED
@@ -1 +1 @@
1
- export const forgeBridgeVersion = "0.1.4-dev.e83e5bc6ecce";
1
+ export const forgeBridgeVersion = "0.1.4-dev.efc418893964";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@loucompanion/forge-bridge",
3
- "version": "0.1.4-dev.e83e5bc6ecce",
3
+ "version": "0.1.4-dev.efc418893964",
4
4
  "description": "Forge runner bridge CLI for connecting local developer machines to Forge dispatch.",
5
5
  "license": "UNLICENSED",
6
6
  "type": "module",
@@ -43,7 +43,7 @@
43
43
  "test:residue": "node scripts/run-owned-residue-gate.mjs",
44
44
  "test:watch": "vitest",
45
45
  "smoke:package": "tsc -p tsconfig.json && node scripts/smoke-package.mjs",
46
- "lint": "eslint \"src/**/*.ts\" \"scripts/**/*.mjs\" \"vitest.config.ts\" \"vitest.setup.ts\""
46
+ "lint": "eslint \"src/**/*.ts\" \"scripts/**/*.mjs\" \"vitest.config.ts\" \"vitest.setup.ts\" && node ../../scripts/class-design/check-eslint-ratchet.mjs bridge"
47
47
  },
48
48
  "dependencies": {
49
49
  "@microsoft/signalr": "^8.0.17",