@loucompanion/forge-bridge 0.1.4-dev.d2d83bc81b6a → 0.1.4-dev.deb7f72e7930

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 (253) hide show
  1. package/README.md +144 -3
  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-state-file.d.ts +161 -0
  7. package/dist/bridge/bridge-state-file.js +376 -0
  8. package/dist/bridge/bridge-state-io.d.ts +11 -0
  9. package/dist/bridge/bridge-state-io.js +50 -0
  10. package/dist/bridge/bridge-state-lock.d.ts +11 -0
  11. package/dist/bridge/bridge-state-lock.js +102 -0
  12. package/dist/bridge/bridge-state-unpublished.d.ts +17 -0
  13. package/dist/bridge/bridge-state-unpublished.js +111 -0
  14. package/dist/bridge/bridge.base.d.ts +9 -0
  15. package/dist/bridge/bridge.service.d.ts +92 -15
  16. package/dist/bridge/bridge.service.js +432 -342
  17. package/dist/bridge/bridge.types.d.ts +27 -0
  18. package/dist/bridge/in-flight-registry.d.ts +62 -0
  19. package/dist/bridge/in-flight-registry.js +207 -0
  20. package/dist/bridge/local-yield-flag.d.ts +6 -0
  21. package/dist/bridge/local-yield-flag.js +34 -0
  22. package/dist/bridge/readiness-result-outbox.d.ts +5 -1
  23. package/dist/bridge/readiness-result-outbox.js +20 -0
  24. package/dist/bridge/runner-host-capabilities.d.ts +5 -0
  25. package/dist/bridge/runner-host-capabilities.js +17 -0
  26. package/dist/bridge/sandbox-resource-accounting.d.ts +16 -0
  27. package/dist/bridge/sandbox-resource-accounting.js +150 -0
  28. package/dist/bridge/test-postgres-capability.d.ts +14 -0
  29. package/dist/bridge/test-postgres-capability.js +120 -0
  30. package/dist/cleanup/cleanup-wip.d.ts +12 -0
  31. package/dist/cleanup/cleanup-wip.js +66 -0
  32. package/dist/cleanup/cleanup.service.d.ts +20 -1
  33. package/dist/cleanup/cleanup.service.js +150 -169
  34. package/dist/cleanup/cleanup.types.d.ts +6 -0
  35. package/dist/cleanup/forge-owned-paths.d.ts +9 -0
  36. package/dist/cleanup/forge-owned-paths.js +53 -0
  37. package/dist/cleanup/host-runtime-ledger.d.ts +7 -0
  38. package/dist/cleanup/host-runtime-ledger.js +130 -0
  39. package/dist/cleanup/managed-branch-sweep.d.ts +27 -0
  40. package/dist/cleanup/managed-branch-sweep.js +111 -0
  41. package/dist/cli/cli.help.js +74 -12
  42. package/dist/cli/cli.service.d.ts +19 -10
  43. package/dist/cli/cli.service.js +152 -187
  44. package/dist/cli/idle-status.d.ts +84 -0
  45. package/dist/cli/idle-status.js +181 -0
  46. package/dist/cli/local-config.d.ts +6 -0
  47. package/dist/cli/local-config.js +32 -4
  48. package/dist/cli/provider-cli-detection.d.ts +10 -0
  49. package/dist/cli/provider-cli-detection.js +160 -0
  50. package/dist/runtime/aspnet-runtime-prebuild.d.ts +5 -0
  51. package/dist/runtime/aspnet-runtime-prebuild.js +140 -7
  52. package/dist/runtime/attempt-database-broker.d.ts +1 -1
  53. package/dist/runtime/docker-engine-probe.d.ts +5 -0
  54. package/dist/runtime/docker-engine-probe.js +7 -0
  55. package/dist/runtime/ephemeral-test-postgres-grant.d.ts +37 -0
  56. package/dist/runtime/ephemeral-test-postgres-grant.js +85 -0
  57. package/dist/runtime/ephemeral-test-postgres.d.ts +57 -0
  58. package/dist/runtime/ephemeral-test-postgres.js +303 -0
  59. package/dist/runtime/host-database-capability-boundary.d.ts +1 -1
  60. package/dist/runtime/host-database-capability-boundary.js +1 -0
  61. package/dist/runtime/host-facts.d.ts +36 -0
  62. package/dist/runtime/host-facts.js +95 -0
  63. package/dist/runtime/host-load-admission.d.ts +67 -0
  64. package/dist/runtime/host-load-admission.js +99 -0
  65. package/dist/runtime/host-load-child-environment.d.ts +27 -0
  66. package/dist/runtime/host-load-child-environment.js +76 -0
  67. package/dist/runtime/host-load-forge-cgroups.d.ts +49 -0
  68. package/dist/runtime/host-load-forge-cgroups.js +140 -0
  69. package/dist/runtime/host-load-governor-config.d.ts +52 -0
  70. package/dist/runtime/host-load-governor-config.js +83 -0
  71. package/dist/runtime/host-load-governor.d.ts +186 -0
  72. package/dist/runtime/host-load-governor.js +632 -0
  73. package/dist/runtime/host-load-ledger-lock.d.ts +69 -0
  74. package/dist/runtime/host-load-ledger-lock.js +187 -0
  75. package/dist/runtime/host-load-runtime-settings.d.ts +25 -0
  76. package/dist/runtime/host-load-runtime-settings.js +80 -0
  77. package/dist/runtime/host-load-sampler.d.ts +156 -0
  78. package/dist/runtime/host-load-sampler.js +298 -0
  79. package/dist/runtime/host-load-step-class.d.ts +70 -0
  80. package/dist/runtime/host-load-step-class.js +161 -0
  81. package/dist/runtime/host-load-step-reaper.d.ts +27 -0
  82. package/dist/runtime/host-load-step-reaper.js +95 -0
  83. package/dist/runtime/host-load-step-run.d.ts +73 -0
  84. package/dist/runtime/host-load-step-run.js +102 -0
  85. package/dist/runtime/host-load-test-slot.d.ts +43 -0
  86. package/dist/runtime/host-load-test-slot.js +81 -0
  87. package/dist/runtime/host-load-token-ledger.d.ts +200 -0
  88. package/dist/runtime/host-load-token-ledger.js +453 -0
  89. package/dist/runtime/host-load-windows-cpu.d.ts +34 -0
  90. package/dist/runtime/host-load-windows-cpu.js +85 -0
  91. package/dist/runtime/host-pressure-stall.d.ts +61 -0
  92. package/dist/runtime/host-pressure-stall.js +168 -0
  93. package/dist/runtime/host-runtime-contract.d.ts +16 -0
  94. package/dist/runtime/host-runtime-contract.js +35 -2
  95. package/dist/runtime/host-runtime-lease.d.ts +74 -4
  96. package/dist/runtime/host-runtime-lease.js +285 -55
  97. package/dist/runtime/host-runtime-promotion.d.ts +23 -0
  98. package/dist/runtime/host-runtime-promotion.js +48 -0
  99. package/dist/runtime/host-runtime-requirements-check.d.ts +17 -0
  100. package/dist/runtime/host-runtime-requirements-check.js +29 -0
  101. package/dist/runtime/host-runtime-requirements.d.ts +36 -0
  102. package/dist/runtime/host-runtime-requirements.js +117 -0
  103. package/dist/runtime/managed-command-teardown.js +5 -16
  104. package/dist/runtime/native-test-postgres-fallback.d.ts +51 -7
  105. package/dist/runtime/native-test-postgres-fallback.js +60 -8
  106. package/dist/runtime/playwright-host-runtime-adapter.d.ts +7 -0
  107. package/dist/runtime/playwright-host-runtime-adapter.js +13 -1
  108. package/dist/runtime/runner-settings.d.ts +104 -0
  109. package/dist/runtime/runner-settings.js +236 -0
  110. package/dist/sandbox/host-capacity-broker.d.ts +115 -0
  111. package/dist/sandbox/host-capacity-broker.js +336 -0
  112. package/dist/sandbox/managed-branch.d.ts +13 -0
  113. package/dist/sandbox/managed-branch.js +36 -0
  114. package/dist/sandbox/provider-auth/codex.js +11 -11
  115. package/dist/sandbox/runtime.d.ts +10 -1
  116. package/dist/sandbox/runtime.js +47 -8
  117. package/dist/sandbox/sandbox-cgroups.d.ts +14 -0
  118. package/dist/sandbox/sandbox-cgroups.js +42 -0
  119. package/dist/session/architect-waits.d.ts +2 -0
  120. package/dist/session/architect-waits.js +138 -0
  121. package/dist/session/managed-attempt-tools.d.ts +2 -7
  122. package/dist/session/managed-attempt-tools.js +202 -116
  123. package/dist/session/managed-build-receipt.d.ts +5 -0
  124. package/dist/session/managed-build-receipt.js +8 -3
  125. package/dist/session/managed-command-host-load.d.ts +47 -0
  126. package/dist/session/managed-command-host-load.js +83 -0
  127. package/dist/session/mcp-argument-coercion.d.ts +23 -0
  128. package/dist/session/mcp-argument-coercion.js +121 -0
  129. package/dist/session/phase-completion.artifacts.d.ts +7 -0
  130. package/dist/session/phase-completion.artifacts.js +100 -26
  131. package/dist/session/phase-completion.command-validation.d.ts +7 -0
  132. package/dist/session/phase-completion.command-validation.js +77 -0
  133. package/dist/session/phase-completion.d.ts +12 -0
  134. package/dist/session/phase-completion.helpers.js +13 -12
  135. package/dist/session/phase-completion.js +5 -0
  136. package/dist/session/phase-completion.mcp-args.d.ts +9 -0
  137. package/dist/session/phase-completion.mcp-args.js +156 -0
  138. package/dist/session/phase-completion.prompts.js +6 -1
  139. package/dist/session/phase-completion.runtime.d.ts +5 -11
  140. package/dist/session/phase-completion.runtime.js +91 -215
  141. package/dist/session/phase-completion.schema-parts.d.ts +19 -0
  142. package/dist/session/phase-completion.schema-parts.js +188 -0
  143. package/dist/session/phase-completion.schemas.d.ts +3 -3
  144. package/dist/session/phase-completion.schemas.js +208 -231
  145. package/dist/session/phase-completion.validation.d.ts +2 -3
  146. package/dist/session/phase-completion.validation.js +49 -93
  147. package/dist/session/pre-publication-host-load.d.ts +27 -0
  148. package/dist/session/pre-publication-host-load.js +111 -0
  149. package/dist/session/pre-publication-native-postgres.d.ts +30 -0
  150. package/dist/session/pre-publication-native-postgres.js +111 -0
  151. package/dist/session/pre-publication-pass.d.ts +61 -0
  152. package/dist/session/pre-publication-pass.js +148 -0
  153. package/dist/session/pre-publication-process.d.ts +3 -0
  154. package/dist/session/pre-publication-process.js +33 -20
  155. package/dist/session/pre-publication-skipped-tests.d.ts +21 -0
  156. package/dist/session/pre-publication-skipped-tests.js +109 -0
  157. package/dist/session/pre-publication-step-execution.d.ts +12 -0
  158. package/dist/session/pre-publication-step-execution.js +50 -0
  159. package/dist/session/pre-publication-validation.d.ts +37 -21
  160. package/dist/session/pre-publication-validation.js +224 -166
  161. package/dist/session/provider-cli/claude-background-work.d.ts +67 -0
  162. package/dist/session/provider-cli/claude-background-work.js +181 -0
  163. package/dist/session/provider-cli/host-build-lock.d.ts +18 -0
  164. package/dist/session/provider-cli/host-build-lock.js +30 -0
  165. package/dist/session/provider-cli/pre-publication-repair.d.ts +56 -0
  166. package/dist/session/provider-cli/pre-publication-repair.js +276 -0
  167. package/dist/session/provider-cli/provider-cli.artifacts.d.ts +2 -1
  168. package/dist/session/provider-cli/provider-cli.artifacts.js +21 -15
  169. package/dist/session/provider-cli/provider-cli.child-environment.d.ts +7 -0
  170. package/dist/session/provider-cli/provider-cli.child-environment.js +75 -0
  171. package/dist/session/provider-cli/provider-cli.codex-models-cache.d.ts +3 -0
  172. package/dist/session/provider-cli/provider-cli.codex-models-cache.js +37 -0
  173. package/dist/session/provider-cli/provider-cli.merge-integrity.d.ts +89 -0
  174. package/dist/session/provider-cli/provider-cli.merge-integrity.js +310 -0
  175. package/dist/session/provider-cli/provider-cli.process.d.ts +41 -31
  176. package/dist/session/provider-cli/provider-cli.process.js +139 -438
  177. package/dist/session/provider-cli/provider-cli.prompts.d.ts +10 -0
  178. package/dist/session/provider-cli/provider-cli.prompts.js +87 -32
  179. package/dist/session/provider-cli/provider-cli.runtime.d.ts +8 -0
  180. package/dist/session/provider-cli/provider-cli.runtime.js +29 -1
  181. package/dist/session/provider-cli/provider-cli.service.d.ts +7 -1
  182. package/dist/session/provider-cli/provider-cli.service.js +200 -189
  183. package/dist/session/provider-cli/provider-cli.types.d.ts +30 -0
  184. package/dist/session/provider-cli/provider-cli.windows-environment.d.ts +10 -0
  185. package/dist/session/provider-cli/provider-cli.windows-environment.js +151 -0
  186. package/dist/session/provider-cli/provider-cli.windows-launch.d.ts +23 -0
  187. package/dist/session/provider-cli/provider-cli.windows-launch.js +131 -0
  188. package/dist/session/provider-cli/provider-in-flight-work.d.ts +10 -0
  189. package/dist/session/provider-cli/provider-in-flight-work.js +92 -0
  190. package/dist/session/provider-cli/provider-output-pipes.d.ts +30 -0
  191. package/dist/session/provider-cli/provider-output-pipes.js +67 -0
  192. package/dist/session/provider-cli/provider-output-state.d.ts +8 -0
  193. package/dist/session/provider-cli/provider-output-state.js +15 -0
  194. package/dist/session/provider-cli/provider-user-config-isolation.d.ts +69 -0
  195. package/dist/session/provider-cli/provider-user-config-isolation.js +164 -0
  196. package/dist/session/publishable-worktree-changes.d.ts +54 -0
  197. package/dist/session/publishable-worktree-changes.js +193 -0
  198. package/dist/session/qa-sidecar-validation.d.ts +6 -0
  199. package/dist/session/qa-sidecar-validation.js +28 -0
  200. package/dist/session/sandbox-host-capacity-gate.d.ts +51 -0
  201. package/dist/session/sandbox-host-capacity-gate.js +257 -0
  202. package/dist/session/session-redaction.js +31 -181
  203. package/dist/session/session.base.d.ts +9 -1
  204. package/dist/session/session.service.d.ts +11 -2
  205. package/dist/session/session.service.js +182 -61
  206. package/dist/session/session.types.d.ts +3 -0
  207. package/dist/session/session.types.js +15 -3
  208. package/dist/session/sidecar-json-shape.d.ts +31 -0
  209. package/dist/session/sidecar-json-shape.js +217 -0
  210. package/dist/session/workspace-runtime-fingerprint.d.ts +32 -0
  211. package/dist/session/workspace-runtime-fingerprint.js +138 -0
  212. package/dist/shared/fs/file-identity.d.ts +10 -0
  213. package/dist/shared/fs/file-identity.js +15 -0
  214. package/dist/shared/fs/replace-file.d.ts +7 -0
  215. package/dist/shared/fs/replace-file.js +33 -0
  216. package/dist/shared/process/host-process-recovery.d.ts +14 -3
  217. package/dist/shared/process/host-process-recovery.js +23 -3
  218. package/dist/shared/process/host-process-supervisor.d.ts +14 -1
  219. package/dist/shared/process/host-process-supervisor.js +67 -15
  220. package/dist/shared/process/process-tree.d.ts +52 -0
  221. package/dist/shared/process/process-tree.js +144 -0
  222. package/dist/shared/process/process.d.ts +67 -0
  223. package/dist/shared/process/process.js +213 -11
  224. package/dist/shared/process/windows-app-execution-alias.d.ts +19 -0
  225. package/dist/shared/process/windows-app-execution-alias.js +45 -0
  226. package/dist/shared/process/windows-launch.d.ts +18 -0
  227. package/dist/shared/process/windows-launch.js +68 -0
  228. package/dist/shared/provider-capabilities.js +14 -7
  229. package/dist/version.d.ts +1 -1
  230. package/dist/version.js +1 -1
  231. package/dist/worktree/dependency-warmer.d.ts +25 -0
  232. package/dist/worktree/dependency-warmer.js +46 -10
  233. package/dist/worktree/wip-git.d.ts +33 -0
  234. package/dist/worktree/wip-git.js +122 -0
  235. package/dist/worktree/wip-refs.d.ts +62 -0
  236. package/dist/worktree/wip-refs.js +119 -0
  237. package/dist/worktree/wip-restore.d.ts +38 -0
  238. package/dist/worktree/wip-restore.js +190 -0
  239. package/dist/worktree/wip-snapshot.d.ts +50 -0
  240. package/dist/worktree/wip-snapshot.js +268 -0
  241. package/dist/worktree/worktree-inputs.d.ts +8 -0
  242. package/dist/worktree/worktree-inputs.js +134 -0
  243. package/dist/worktree/worktree-origin-sync.d.ts +34 -0
  244. package/dist/worktree/worktree-origin-sync.js +127 -0
  245. package/dist/worktree/worktree-wip-events.d.ts +18 -0
  246. package/dist/worktree/worktree-wip-events.js +98 -0
  247. package/dist/worktree/worktree-wip.d.ts +49 -0
  248. package/dist/worktree/worktree-wip.js +182 -0
  249. package/dist/worktree/worktree.base.d.ts +7 -1
  250. package/dist/worktree/worktree.service.d.ts +36 -5
  251. package/dist/worktree/worktree.service.js +120 -155
  252. package/dist/worktree/worktree.types.d.ts +38 -0
  253. package/package.json +2 -2
@@ -0,0 +1,69 @@
1
+ import path from "node:path";
2
+ import { ForgeFailureError } from "../session.types.js";
3
+ /** Providers whose user configuration the helpers below shut out. Any other provider is refused. */
4
+ export declare const userConfigIsolatedProviders: readonly string[];
5
+ /**
6
+ * Variables that choose where a provider CLI finds the user's configuration: Claude Code's config
7
+ * directory, and the home directory under which Claude reads `.claude` and `.claude.json` (HOME;
8
+ * USERPROFILE on Windows, which HOMEDRIVE and HOMEPATH resolve to when it is unset). Only the
9
+ * bridge's own environment sets them (provider-cli.child-environment.ts); a project's runtime
10
+ * environment can't, or it could point the provider at another user's configuration.
11
+ */
12
+ export declare const providerConfigLocationVariables: readonly string[];
13
+ /** A strict MCP configuration with no servers, for Claude turns that get no Forge tools. */
14
+ export declare const emptyClaudeMcpConfig: string;
15
+ /**
16
+ * Claude Code launch arguments:
17
+ * - `--setting-sources project,local` drops the user settings source: `~/.claude/settings.json`
18
+ * (hooks, env, permissions, enabled and claude.ai-synced plugins), `~/.claude/CLAUDE.md`,
19
+ * user rules, skills, agents, commands and output styles.
20
+ * - `--mcp-config` plus `--strict-mcp-config` load only Forge's own MCP server (or none), never
21
+ * `~/.claude.json`, plugin or claude.ai connector servers.
22
+ */
23
+ export declare function claudeUserConfigIsolationArgs(forgeMcpConfigPath?: string | null): readonly string[];
24
+ /**
25
+ * Claude Code settings, passed with `--settings`:
26
+ * - `claudeMdExcludes` drops the instruction files Claude Code reads from every directory above
27
+ * the working directory (the user's home and folders such as `~/Repos`). They belong to the
28
+ * host, not to the repository, and the project settings source would otherwise load them.
29
+ * - `autoMemoryEnabled: false`: without the user settings source auto memory falls back to its
30
+ * default, and its memory files accumulate outside the repository between sessions.
31
+ */
32
+ export declare function claudeUserConfigIsolationSettings(workingDirectory: string, pathApi?: path.PlatformPath): Readonly<Record<string, unknown>>;
33
+ /**
34
+ * Every Claude Code agent launch: the isolation arguments, then one `--settings` value that carries
35
+ * the isolation settings and, for headless agent turns, the background-work restrictions with
36
+ * their tool deny list (`claude-background-work.ts`).
37
+ */
38
+ export declare function claudeIsolatedLaunchArgs(options: {
39
+ readonly workingDirectory: string;
40
+ readonly forgeMcpConfigPath?: string | null;
41
+ readonly headless: boolean;
42
+ }): readonly string[];
43
+ /**
44
+ * Instruction-file patterns for each directory strictly above the working directory. Windows
45
+ * paths are listed both as written and with forward slashes, the form glob matchers expect.
46
+ */
47
+ export declare function ancestorInstructionExcludes(workingDirectory: string, pathApi?: path.PlatformPath): readonly string[];
48
+ /**
49
+ * Codex reads `config.toml` (MCP servers, profiles, plugins), `AGENTS.md`, `AGENTS.override.md`,
50
+ * rules and skills from `CODEX_HOME`, so Forge runs it with a home of its own on each runner
51
+ * instead of the user's `~/.codex`. Codex's `--ignore-user-config` still loads the global
52
+ * `AGENTS.md`, so a separate home is the only full isolation. API-key turns authenticate through
53
+ * the environment; a local Codex CLI login is made once into this home
54
+ * (`CODEX_HOME=<path> codex login`).
55
+ *
56
+ * In a Forge sandbox container (`FORGE_RUNTIME_MODE=docker`) `~/.codex` is already Forge's own:
57
+ * an attempt-scoped volume that holds only the copied `auth.json` (sandbox/provider-auth/codex.ts).
58
+ */
59
+ export declare function forgeCodexHome(homeDirectory?: string, environment?: NodeJS.ProcessEnv): string;
60
+ export declare function codexUserConfigIsolationEnv(homeDirectory?: string, environment?: NodeJS.ProcessEnv): Readonly<Record<string, string>>;
61
+ /** The provider environment that shuts out the user's own configuration. */
62
+ export declare function providerUserConfigIsolationEnv(provider: string, homeDirectory?: string, environment?: NodeJS.ProcessEnv): Readonly<Record<string, string>>;
63
+ /**
64
+ * cursor-agent has no flag or environment variable that keeps it from reading `~/.cursor`
65
+ * (`mcp.json`, `cli-config.json`, rules), and `--approve-mcps` would approve every server there;
66
+ * other CLIs are unknown. Forge refuses to launch them.
67
+ */
68
+ export declare function providerUserConfigIsolationUnsupported(provider: string): ForgeFailureError;
69
+ export declare function isProviderUserConfigIsolated(provider: string): boolean;
@@ -0,0 +1,164 @@
1
+ /**
2
+ * Forge agents get only the context Forge gives them: Forge's prompts and `.forge/` artifacts,
3
+ * Forge's MCP tools, and the repository they work in. Nothing from the host user's own provider
4
+ * setup reaches an agent session on any runner: no user instruction files, settings, hooks,
5
+ * skills, plugins, rules, custom agents or commands, and no user, account or plugin MCP servers.
6
+ *
7
+ * Every agent launch path (session runs, repair and recovery turns, chat turns) builds its
8
+ * provider command from these helpers, and a provider whose user configuration Forge cannot
9
+ * shut out is refused rather than launched. `provider-user-config-isolation.test.ts` fails when a
10
+ * launch path stops applying them.
11
+ */
12
+ import fs from "node:fs";
13
+ import os from "node:os";
14
+ import path from "node:path";
15
+ import { ForgeFailureError } from "../session.types.js";
16
+ import { claudeHeadlessToolArgs } from "./claude-background-work.js";
17
+ /** Providers whose user configuration the helpers below shut out. Any other provider is refused. */
18
+ export const userConfigIsolatedProviders = Object.freeze(["claude", "codex"]);
19
+ /**
20
+ * Variables that choose where a provider CLI finds the user's configuration: Claude Code's config
21
+ * directory, and the home directory under which Claude reads `.claude` and `.claude.json` (HOME;
22
+ * USERPROFILE on Windows, which HOMEDRIVE and HOMEPATH resolve to when it is unset). Only the
23
+ * bridge's own environment sets them (provider-cli.child-environment.ts); a project's runtime
24
+ * environment can't, or it could point the provider at another user's configuration.
25
+ */
26
+ export const providerConfigLocationVariables = Object.freeze(["CLAUDE_CONFIG_DIR", "HOME", "USERPROFILE", "HOMEDRIVE", "HOMEPATH"]);
27
+ /** A strict MCP configuration with no servers, for Claude turns that get no Forge tools. */
28
+ export const emptyClaudeMcpConfig = JSON.stringify({ mcpServers: {} });
29
+ /**
30
+ * Claude Code launch arguments:
31
+ * - `--setting-sources project,local` drops the user settings source: `~/.claude/settings.json`
32
+ * (hooks, env, permissions, enabled and claude.ai-synced plugins), `~/.claude/CLAUDE.md`,
33
+ * user rules, skills, agents, commands and output styles.
34
+ * - `--mcp-config` plus `--strict-mcp-config` load only Forge's own MCP server (or none), never
35
+ * `~/.claude.json`, plugin or claude.ai connector servers.
36
+ */
37
+ export function claudeUserConfigIsolationArgs(forgeMcpConfigPath) {
38
+ return [
39
+ "--setting-sources", "project,local",
40
+ "--mcp-config", forgeMcpConfigPath?.trim() || emptyClaudeMcpConfig,
41
+ "--strict-mcp-config",
42
+ ];
43
+ }
44
+ /**
45
+ * Claude Code settings, passed with `--settings`:
46
+ * - `claudeMdExcludes` drops the instruction files Claude Code reads from every directory above
47
+ * the working directory (the user's home and folders such as `~/Repos`). They belong to the
48
+ * host, not to the repository, and the project settings source would otherwise load them.
49
+ * - `autoMemoryEnabled: false`: without the user settings source auto memory falls back to its
50
+ * default, and its memory files accumulate outside the repository between sessions.
51
+ */
52
+ export function claudeUserConfigIsolationSettings(workingDirectory, pathApi = path) {
53
+ return {
54
+ autoMemoryEnabled: false,
55
+ claudeMdExcludes: ancestorInstructionExcludes(workingDirectory, pathApi),
56
+ };
57
+ }
58
+ /**
59
+ * Every Claude Code agent launch: the isolation arguments, then one `--settings` value that carries
60
+ * the isolation settings and, for headless agent turns, the background-work restrictions with
61
+ * their tool deny list (`claude-background-work.ts`).
62
+ */
63
+ export function claudeIsolatedLaunchArgs(options) {
64
+ const settings = claudeUserConfigIsolationSettings(options.workingDirectory);
65
+ return [
66
+ ...claudeUserConfigIsolationArgs(options.forgeMcpConfigPath),
67
+ ...(options.headless ? claudeHeadlessToolArgs(settings) : ["--settings", JSON.stringify(settings)]),
68
+ ];
69
+ }
70
+ const ancestorInstructionEntries = ["CLAUDE.md", "CLAUDE.local.md", ".claude/CLAUDE.md", ".claude/rules/**"];
71
+ /**
72
+ * Instruction-file patterns for each directory strictly above the working directory. Windows
73
+ * paths are listed both as written and with forward slashes, the form glob matchers expect.
74
+ */
75
+ export function ancestorInstructionExcludes(workingDirectory, pathApi = path) {
76
+ const patterns = new Set();
77
+ let current = pathApi.resolve(workingDirectory);
78
+ for (let parent = pathApi.dirname(current); parent !== current; current = parent, parent = pathApi.dirname(current)) {
79
+ for (const entry of ancestorInstructionEntries) {
80
+ const pattern = pathApi.join(parent, entry);
81
+ patterns.add(pattern);
82
+ patterns.add(pattern.replaceAll("\\", "/"));
83
+ }
84
+ }
85
+ return [...patterns];
86
+ }
87
+ /**
88
+ * Codex reads `config.toml` (MCP servers, profiles, plugins), `AGENTS.md`, `AGENTS.override.md`,
89
+ * rules and skills from `CODEX_HOME`, so Forge runs it with a home of its own on each runner
90
+ * instead of the user's `~/.codex`. Codex's `--ignore-user-config` still loads the global
91
+ * `AGENTS.md`, so a separate home is the only full isolation. API-key turns authenticate through
92
+ * the environment; a local Codex CLI login is made once into this home
93
+ * (`CODEX_HOME=<path> codex login`).
94
+ *
95
+ * In a Forge sandbox container (`FORGE_RUNTIME_MODE=docker`) `~/.codex` is already Forge's own:
96
+ * an attempt-scoped volume that holds only the copied `auth.json` (sandbox/provider-auth/codex.ts).
97
+ */
98
+ export function forgeCodexHome(homeDirectory = os.homedir(), environment = process.env) {
99
+ return isForgeSandboxContainer(environment)
100
+ ? path.join(homeDirectory, ".codex")
101
+ : path.join(homeDirectory, ...forgeCodexHomeSegments);
102
+ }
103
+ const forgeCodexHomeSegments = [".forge", "provider-homes", "codex"];
104
+ export function codexUserConfigIsolationEnv(homeDirectory = os.homedir(), environment = process.env) {
105
+ const codexHome = forgeCodexHome(homeDirectory, environment);
106
+ if (!isForgeSandboxContainer(environment)) {
107
+ ensureForgeCodexHome(homeDirectory);
108
+ }
109
+ return { CODEX_HOME: codexHome };
110
+ }
111
+ /**
112
+ * Creates Forge's Codex home one directory at a time. Each directory Forge owns on the way
113
+ * (`.forge`, `provider-homes`, `codex`) must be a real directory: a symlink or Windows junction
114
+ * there, stale or user-made, would hand Codex another directory such as the user's `~/.codex`, so
115
+ * the launch is refused instead. The user's home directory itself may be reached through a link.
116
+ * The home is private whether Forge creates it now or it already exists, like Forge's other
117
+ * private directories; Windows keeps the profile's inherited ACL.
118
+ */
119
+ function ensureForgeCodexHome(homeDirectory) {
120
+ let current = homeDirectory;
121
+ for (const segment of forgeCodexHomeSegments) {
122
+ current = path.join(current, segment);
123
+ const stat = lstatIfPresent(current);
124
+ if (stat && (stat.isSymbolicLink() || !stat.isDirectory())) {
125
+ throw new ForgeFailureError("provider_home_redirected", `Forge can't run Codex with its own home: ${current} is a link or not a directory, so Codex could read another configuration, such as the user's own ~/.codex. Remove it; Forge recreates its own directory there on the next launch.`);
126
+ }
127
+ if (!stat)
128
+ fs.mkdirSync(current, { mode: 0o700 });
129
+ }
130
+ if (process.platform !== "win32")
131
+ fs.chmodSync(current, 0o700);
132
+ }
133
+ function lstatIfPresent(target) {
134
+ try {
135
+ return fs.lstatSync(target);
136
+ }
137
+ catch (error) {
138
+ if (error.code === "ENOENT")
139
+ return null;
140
+ throw error;
141
+ }
142
+ }
143
+ function isForgeSandboxContainer(environment) {
144
+ return environment.FORGE_RUNTIME_MODE?.trim().toLowerCase() === "docker";
145
+ }
146
+ /** The provider environment that shuts out the user's own configuration. */
147
+ export function providerUserConfigIsolationEnv(provider, homeDirectory = os.homedir(), environment = process.env) {
148
+ return normalizeProvider(provider) === "codex" ? codexUserConfigIsolationEnv(homeDirectory, environment) : {};
149
+ }
150
+ /**
151
+ * cursor-agent has no flag or environment variable that keeps it from reading `~/.cursor`
152
+ * (`mcp.json`, `cli-config.json`, rules), and `--approve-mcps` would approve every server there;
153
+ * other CLIs are unknown. Forge refuses to launch them.
154
+ */
155
+ export function providerUserConfigIsolationUnsupported(provider) {
156
+ const name = provider.trim() || "this provider";
157
+ return new ForgeFailureError("provider_user_config_isolation_unsupported", `Forge can't launch ${name}: it can't keep the host user's own ${name} configuration (instruction files, settings, rules, MCP servers, plugins) out of the agent session. Forge agents get only the context Forge gives them, so only ${userConfigIsolatedProviders.join(" and ")} sessions run on Forge runners.`);
158
+ }
159
+ export function isProviderUserConfigIsolated(provider) {
160
+ return userConfigIsolatedProviders.includes(normalizeProvider(provider));
161
+ }
162
+ function normalizeProvider(provider) {
163
+ return provider.trim().toLowerCase();
164
+ }
@@ -0,0 +1,54 @@
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
+ /** `.local/`, `.forge/work-items/` and `.forge/stories/`: never published, even during a merge. */
20
+ export declare function isRuntimeOnlyPath(relativePath: string): boolean;
21
+ /**
22
+ * Stages every publishable worktree change in the real index and returns both sets.
23
+ *
24
+ * During an in-progress merge it first refuses unresolved conflicts, and afterwards
25
+ * restores merge-owned paths that the exclusion unstaged back to HEAD (the story side),
26
+ * such as `.forge/` files the target branch added (#491). Runtime-only paths are never
27
+ * restored.
28
+ */
29
+ export declare function stagePublishableWorktreeChangeSet(git: Pick<GitClient, "run">, worktreePath: string): Promise<PublishableWorktreeChangeSet>;
30
+ /**
31
+ * Computes the same change set as {@link stagePublishableWorktreeChangeSet} without
32
+ * touching the worktree's index, using a throwaway copy of it. Returns null when
33
+ * `worktreePath` is not the root of a git worktree.
34
+ */
35
+ export declare function readPublishableWorktreeChangeSet(worktreePath: string, processRunner?: ProcessRunner): Promise<PublishableWorktreeChangeSet | null>;
36
+ /** Compares claimed `changed_files` paths with the publishable diff. */
37
+ export declare function diffClaimedChangedFiles(claimedPaths: readonly string[], publishablePaths: readonly string[]): {
38
+ readonly missing: readonly string[];
39
+ readonly unexpected: readonly string[];
40
+ };
41
+ export declare function normalizeChangedFilePath(value: string): string;
42
+ /**
43
+ * In-tool check for `forge.complete_comment_repair`: rejects a pass payload whose
44
+ * `changed_files` differs from what Forge would publish, so the agent can correct it
45
+ * in the same turn instead of failing at publication.
46
+ */
47
+ export declare function assertClaimedChangedFilesMatchPublishableDiff(worktreePath: string, payload: Record<string, unknown>, toolName: string, processRunner?: ProcessRunner): Promise<void>;
48
+ /**
49
+ * Returns the given paths whose worktree content differs from HEAD but is not in the
50
+ * publishable set: excluded runtime output, and untracked or git-ignored files that are
51
+ * never staged at all (for example an injected `.forge/` file in a repository that ignores
52
+ * `.forge/`). A review finding on such a path cannot be fixed by the published commit.
53
+ */
54
+ export declare function findUnpublishedWorktreePaths(git: Pick<GitClient, "run">, worktreePath: string, paths: readonly string[], publishablePaths: readonly string[]): Promise<readonly string[]>;
@@ -0,0 +1,193 @@
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
+ import { assertNoUnresolvedMergeConflicts, restoreMergeOwnedPaths } from "./provider-cli/provider-cli.merge-integrity.js";
7
+ /**
8
+ * Forge runtime output that is never published, whether or not the target repository
9
+ * tracks other `.forge/` content. Completion artifacts and evidence live here.
10
+ */
11
+ const runtimeOnlyPathPrefixes = [".local/", ".forge/work-items/", ".forge/stories/"];
12
+ const resetBatchSize = 200;
13
+ /**
14
+ * Decides whether a staged change is Forge runtime output rather than an author edit.
15
+ *
16
+ * `.local/`, `.forge/work-items/` and `.forge/stories/` are always runtime output. Any
17
+ * other `.forge/` path is runtime output only when HEAD does not track it (status `A`):
18
+ * that covers injected managed commands, hooks and skills. The injector never overwrites a
19
+ * tracked `.forge/` file and restores one that matches the managed body, so a tracked
20
+ * `.forge/` file that differs from HEAD is an author edit and must be published.
21
+ */
22
+ export function isNonPublishableWorktreeChange(relativePath, status) {
23
+ const normalized = relativePath.trim().replaceAll("\\", "/");
24
+ if (isRuntimeOnlyPath(normalized)) {
25
+ return true;
26
+ }
27
+ if (normalized === ".forge" || normalized.startsWith(".forge/")) {
28
+ return status.trim().toUpperCase().startsWith("A");
29
+ }
30
+ return false;
31
+ }
32
+ /** `.local/`, `.forge/work-items/` and `.forge/stories/`: never published, even during a merge. */
33
+ export function isRuntimeOnlyPath(relativePath) {
34
+ const normalizedPath = normalizeChangedFilePath(relativePath);
35
+ return normalizedPath === ".local" || runtimeOnlyPathPrefixes.some(prefix => normalizedPath.startsWith(prefix));
36
+ }
37
+ /**
38
+ * Stages every publishable worktree change in the real index and returns both sets.
39
+ *
40
+ * During an in-progress merge it first refuses unresolved conflicts, and afterwards
41
+ * restores merge-owned paths that the exclusion unstaged back to HEAD (the story side),
42
+ * such as `.forge/` files the target branch added (#491). Runtime-only paths are never
43
+ * restored.
44
+ */
45
+ export async function stagePublishableWorktreeChangeSet(git, worktreePath) {
46
+ await assertNoUnresolvedMergeConflicts(git, worktreePath);
47
+ await git.run(worktreePath, ["add", "-A"]);
48
+ const excludedChanges = (await readStagedChanges(git, worktreePath))
49
+ .filter(change => isNonPublishableWorktreeChange(change.path, change.status))
50
+ .map(change => change.path);
51
+ for (let index = 0; index < excludedChanges.length; index += resetBatchSize) {
52
+ const batch = excludedChanges.slice(index, index + resetBatchSize).map(filePath => `:(literal)${filePath}`);
53
+ await git.run(worktreePath, ["reset", "-q", "--", ...batch]);
54
+ }
55
+ const restored = new Set(await restoreMergeOwnedPaths(git, worktreePath, excludedChanges.filter(filePath => !isRuntimeOnlyPath(filePath))));
56
+ const excluded = excludedChanges.filter(filePath => !restored.has(filePath));
57
+ const publishable = (await git.run(worktreePath, ["diff", "--cached", "--name-only"]))
58
+ .split(/\r?\n/)
59
+ .map(line => line.trim())
60
+ .filter(Boolean);
61
+ return { publishable, excluded: [...new Set(excluded)].sort() };
62
+ }
63
+ /**
64
+ * Computes the same change set as {@link stagePublishableWorktreeChangeSet} without
65
+ * touching the worktree's index, using a throwaway copy of it. Returns null when
66
+ * `worktreePath` is not the root of a git worktree.
67
+ */
68
+ export async function readPublishableWorktreeChangeSet(worktreePath, processRunner = new NodeProcessRunner()) {
69
+ const resolvedWorktree = path.resolve(worktreePath);
70
+ const git = new GitClient(processRunner);
71
+ let topLevel;
72
+ try {
73
+ topLevel = (await git.run(resolvedWorktree, ["rev-parse", "--show-toplevel"])).trim();
74
+ }
75
+ catch {
76
+ return null;
77
+ }
78
+ if (!topLevel || !await samePath(topLevel, resolvedWorktree)) {
79
+ return null;
80
+ }
81
+ const realIndex = path.resolve(resolvedWorktree, (await git.run(resolvedWorktree, ["rev-parse", "--git-path", "index"])).trim());
82
+ const tempRoot = await fs.mkdtemp(path.join(os.tmpdir(), "forge-publishable-index-"));
83
+ try {
84
+ const tempIndex = path.join(tempRoot, "index");
85
+ await fs.copyFile(realIndex, tempIndex).catch((error) => {
86
+ if (error.code !== "ENOENT")
87
+ throw error;
88
+ });
89
+ const tempIndexGit = new GitClient({
90
+ run: request => processRunner.run({
91
+ ...request,
92
+ env: { ...(request.env ?? process.env), GIT_INDEX_FILE: tempIndex },
93
+ }),
94
+ });
95
+ return await stagePublishableWorktreeChangeSet(tempIndexGit, resolvedWorktree);
96
+ }
97
+ finally {
98
+ await fs.rm(tempRoot, { recursive: true, force: true });
99
+ }
100
+ }
101
+ /** Compares claimed `changed_files` paths with the publishable diff. */
102
+ export function diffClaimedChangedFiles(claimedPaths, publishablePaths) {
103
+ const claimed = new Set(claimedPaths.map(normalizeChangedFilePath).filter(Boolean));
104
+ const actual = new Set(publishablePaths.map(normalizeChangedFilePath).filter(Boolean));
105
+ return {
106
+ missing: [...actual].filter(filePath => !claimed.has(filePath)).sort(),
107
+ unexpected: [...claimed].filter(filePath => !actual.has(filePath)).sort(),
108
+ };
109
+ }
110
+ export function normalizeChangedFilePath(value) {
111
+ return value.trim().replaceAll("\\", "/");
112
+ }
113
+ async function readStagedChanges(git, worktreePath) {
114
+ const fields = (await git.run(worktreePath, ["diff", "--cached", "--name-status", "--no-renames", "-z"]))
115
+ .split("\0");
116
+ const changes = [];
117
+ for (let index = 0; index + 1 < fields.length; index += 2) {
118
+ const status = fields[index].trim();
119
+ const filePath = fields[index + 1];
120
+ if (status && filePath)
121
+ changes.push({ status, path: filePath });
122
+ }
123
+ return changes;
124
+ }
125
+ async function samePath(left, right) {
126
+ const [realLeft, realRight] = await Promise.all([
127
+ fs.realpath(left).catch(() => path.resolve(left)),
128
+ fs.realpath(right).catch(() => path.resolve(right)),
129
+ ]);
130
+ return process.platform === "win32"
131
+ ? realLeft.toLowerCase() === realRight.toLowerCase()
132
+ : realLeft === realRight;
133
+ }
134
+ /**
135
+ * In-tool check for `forge.complete_comment_repair`: rejects a pass payload whose
136
+ * `changed_files` differs from what Forge would publish, so the agent can correct it
137
+ * in the same turn instead of failing at publication.
138
+ */
139
+ export async function assertClaimedChangedFilesMatchPublishableDiff(worktreePath, payload, toolName, processRunner) {
140
+ const changeSet = await readPublishableWorktreeChangeSet(worktreePath, processRunner);
141
+ if (!changeSet)
142
+ return;
143
+ const claimed = Array.isArray(payload.changed_files)
144
+ ? payload.changed_files.map(value => String(value?.path ?? ""))
145
+ : [];
146
+ const { missing, unexpected } = diffClaimedChangedFiles(claimed, changeSet.publishable);
147
+ if (missing.length === 0 && unexpected.length === 0)
148
+ return;
149
+ const details = [
150
+ missing.length > 0 ? `Publishable changes missing from changed_files: ${missing.join(", ")}.` : "",
151
+ unexpected.length > 0 ? `changed_files entries that Forge will not publish: ${unexpected.join(", ")}.` : "",
152
+ ].filter(Boolean).join(" ");
153
+ throw new Error(`changed_files must list exactly the files Forge will publish. ${details} `
154
+ + "Forge publishes every source change, including edits to tracked .forge/ files; it never publishes "
155
+ + ".local/, .forge/work-items/, .forge/stories/, or new untracked .forge/ files. "
156
+ + `Correct changed_files (or the worktree) and call ${toolName} again.`);
157
+ }
158
+ /**
159
+ * Returns the given paths whose worktree content differs from HEAD but is not in the
160
+ * publishable set: excluded runtime output, and untracked or git-ignored files that are
161
+ * never staged at all (for example an injected `.forge/` file in a repository that ignores
162
+ * `.forge/`). A review finding on such a path cannot be fixed by the published commit.
163
+ */
164
+ export async function findUnpublishedWorktreePaths(git, worktreePath, paths, publishablePaths) {
165
+ const candidates = [...new Set(paths.map(normalizeChangedFilePath).filter(Boolean))];
166
+ if (candidates.length === 0)
167
+ return [];
168
+ const publishable = new Set(publishablePaths.map(normalizeChangedFilePath));
169
+ const unpublished = new Set();
170
+ for (let index = 0; index < candidates.length; index += resetBatchSize) {
171
+ const batch = candidates.slice(index, index + resetBatchSize).map(filePath => `:(literal)${filePath}`);
172
+ const output = await git.run(worktreePath, [
173
+ // `traditional` with `--untracked-files=all` lists each file inside an ignored directory.
174
+ "status", "--porcelain=v1", "-z", "--no-renames", "--ignored=traditional", "--untracked-files=all", "--", ...batch,
175
+ ]);
176
+ for (const entry of output.split("\0")) {
177
+ if (entry.length < 4)
178
+ continue;
179
+ const reported = normalizeChangedFilePath(entry.slice(3));
180
+ if (!reported)
181
+ continue;
182
+ // A collapsed directory entry ("dir/") covers every candidate beneath it.
183
+ const matches = reported.endsWith("/")
184
+ ? candidates.filter(candidate => candidate.startsWith(reported))
185
+ : [reported];
186
+ for (const filePath of matches) {
187
+ if (!publishable.has(filePath))
188
+ unpublished.add(filePath);
189
+ }
190
+ }
191
+ }
192
+ return [...unpublished].sort();
193
+ }
@@ -1,3 +1,9 @@
1
1
  export declare function isPathUnderRoot(root: string, target: string): boolean;
2
2
  export declare function ensureNoSymbolicLinkPathSegments(root: string, targetDirectory: string, errorMessage: string): Promise<void>;
3
3
  export declare function sha256File(filePath: string): Promise<string>;
4
+ /**
5
+ * Applies the end-of-run sidecar shape check when a QA gate records the sidecar, so the agent
6
+ * learns about a malformed file (for example a JSON array followed by a summary line) while it
7
+ * can still rewrite it, instead of the whole attempt failing after the run.
8
+ */
9
+ export declare function assertQaSidecarJsonShape(fullPath: string, sidecarPath: string, label: string): Promise<void>;
@@ -2,6 +2,7 @@ import crypto from "node:crypto";
2
2
  import { createReadStream } from "node:fs";
3
3
  import fs from "node:fs/promises";
4
4
  import path from "node:path";
5
+ import { looksLikeJson, maximumIntegrityJsonBytes, oversizedJsonReason, sidecarJsonShapeProblem, sidecarJsonRepairInstruction, } from "./sidecar-json-shape.js";
5
6
  export function isPathUnderRoot(root, target) {
6
7
  const relative = path.relative(path.resolve(root), path.resolve(target));
7
8
  return Boolean(relative)
@@ -42,3 +43,30 @@ export async function sha256File(filePath) {
42
43
  }
43
44
  return hash.digest("hex");
44
45
  }
46
+ /**
47
+ * Applies the end-of-run sidecar shape check when a QA gate records the sidecar, so the agent
48
+ * learns about a malformed file (for example a JSON array followed by a summary line) while it
49
+ * can still rewrite it, instead of the whole attempt failing after the run.
50
+ */
51
+ export async function assertQaSidecarJsonShape(fullPath, sidecarPath, label) {
52
+ const problem = await qaSidecarJsonShapeProblem(fullPath, sidecarPath);
53
+ if (problem !== null) {
54
+ throw new Error(`${label}: ${sidecarJsonRepairInstruction(sidecarPath, problem)}`);
55
+ }
56
+ }
57
+ async function qaSidecarJsonShapeProblem(fullPath, sidecarPath) {
58
+ const handle = await fs.open(fullPath, "r");
59
+ try {
60
+ const { size } = await handle.stat();
61
+ if (size <= maximumIntegrityJsonBytes) {
62
+ return sidecarJsonShapeProblem(await handle.readFile(), sidecarPath);
63
+ }
64
+ // Too large to inspect as JSON: only a file that starts like JSON is a problem.
65
+ const prefix = Buffer.alloc(4096);
66
+ const { bytesRead } = await handle.read(prefix, 0, prefix.length, 0);
67
+ return looksLikeJson(prefix.subarray(0, bytesRead).toString("utf8"), sidecarPath) ? oversizedJsonReason : null;
68
+ }
69
+ finally {
70
+ await handle.close();
71
+ }
72
+ }
@@ -0,0 +1,51 @@
1
+ import { type BigIntStats } from "node:fs";
2
+ import { type HostLoadAcquireOptions, type HostLoadAdmission, type HostLoadStepGate, type HostLoadStepRequest } from "../runtime/host-load-governor.js";
3
+ export interface SandboxHostCapacityGateOptions {
4
+ readonly write?: (line: string) => void;
5
+ readonly responseRoot?: string;
6
+ readonly pollMs?: number;
7
+ /** Fails closed if the bridge never answers (the host enforces its own maximum wait first). */
8
+ readonly maxWaitMs?: number;
9
+ /** Owner of authentic replies (root in the container; tests use their own uid). */
10
+ readonly trustedOwnerUid?: number;
11
+ /**
12
+ * How a reply is proven the bridge's; by default POSIX ownership by trustedOwnerUid,
13
+ * which is what the Linux sandbox has. A test standing in for the container on a
14
+ * host without POSIX ownership supplies the provenance it can prove instead.
15
+ */
16
+ readonly replyOwnership?: SandboxReplyOwnership;
17
+ }
18
+ /**
19
+ * Whether the bridge owns a reply, judged from the stat of the open handle of a
20
+ * regular file with a single link: null when it does, otherwise why it does not.
21
+ * The stat is exact (bigint): no owner id or file identity is rounded to a double.
22
+ */
23
+ export type SandboxReplyOwnership = (stat: BigIntStats) => string | null;
24
+ /**
25
+ * Inside the Linux sandbox a reply is the bridge's when the trusted uid (root)
26
+ * owns it and no one else can write it: the sandbox user can create neither.
27
+ * Windows has no such proof in a file's stat (Node reports uid 0 for every file
28
+ * and derives the mode from the read-only attribute alone), so there no reply
29
+ * is ever trusted: the gate fails closed rather than read a read-only file as root's.
30
+ */
31
+ export declare function posixReplyOwnership(trustedOwnerUid: number, platform?: NodeJS.Platform): SandboxReplyOwnership;
32
+ export declare class SandboxBrokeredHostLoadGate implements HostLoadStepGate {
33
+ readonly enabled = true;
34
+ private readonly write;
35
+ private readonly responseRoot;
36
+ private readonly pollMs;
37
+ private readonly replyOwnership;
38
+ readonly maxWaitMs: number;
39
+ constructor(options?: SandboxHostCapacityGateOptions);
40
+ acquire(request: HostLoadStepRequest, options?: HostLoadAcquireOptions): Promise<HostLoadAdmission>;
41
+ private admission;
42
+ private send;
43
+ }
44
+ /**
45
+ * The brokered gate when the host bridge enabled it for this sandbox. The
46
+ * variable is removed once read, so commands the sandbox runs never inherit it
47
+ * (a nested Forge process must not queue behind its parent's token).
48
+ */
49
+ export declare function sandboxHostLoadGateFromEnvironment(environment?: NodeJS.ProcessEnv): HostLoadStepGate | undefined;
50
+ /** Test support: forgets the cached gate. */
51
+ export declare function resetSandboxHostLoadGateForTesting(): void;