@loucompanion/forge-bridge 0.1.4-dev.63db04bcffca → 0.1.4-dev.81e48ecc185d

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 (170) hide show
  1. package/README.md +54 -2
  2. package/dist/bridge/bridge-chat-provider-command.d.ts +16 -0
  3. package/dist/bridge/bridge-chat-provider-command.js +125 -0
  4. package/dist/bridge/bridge.base.d.ts +9 -0
  5. package/dist/bridge/bridge.service.d.ts +85 -3
  6. package/dist/bridge/bridge.service.js +361 -122
  7. package/dist/bridge/bridge.types.d.ts +22 -0
  8. package/dist/bridge/dispatch-result-outbox.d.ts +11 -1
  9. package/dist/bridge/dispatch-result-outbox.js +31 -6
  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 +2 -0
  13. package/dist/bridge/runner-host-capabilities.js +4 -0
  14. package/dist/bridge/test-postgres-capability.d.ts +14 -0
  15. package/dist/bridge/test-postgres-capability.js +120 -0
  16. package/dist/cleanup/cleanup.service.d.ts +9 -0
  17. package/dist/cleanup/cleanup.service.js +72 -109
  18. package/dist/cleanup/cleanup.types.d.ts +4 -0
  19. package/dist/cleanup/forge-owned-paths.d.ts +9 -0
  20. package/dist/cleanup/forge-owned-paths.js +53 -0
  21. package/dist/cleanup/host-runtime-ledger.d.ts +5 -0
  22. package/dist/cleanup/host-runtime-ledger.js +109 -0
  23. package/dist/cleanup/managed-branch-sweep.d.ts +27 -0
  24. package/dist/cleanup/managed-branch-sweep.js +111 -0
  25. package/dist/cli/cli.help.js +18 -0
  26. package/dist/cli/cli.service.d.ts +16 -0
  27. package/dist/cli/cli.service.js +142 -16
  28. package/dist/cli/local-config.d.ts +4 -0
  29. package/dist/cli/local-config.js +26 -4
  30. package/dist/runtime/aspnet-runtime-prebuild.js +94 -6
  31. package/dist/runtime/attempt-process-supervisor.d.ts +19 -0
  32. package/dist/runtime/attempt-process-supervisor.js +50 -0
  33. package/dist/runtime/host-database-capability-boundary.d.ts +1 -1
  34. package/dist/runtime/host-database-capability-boundary.js +1 -0
  35. package/dist/runtime/host-facts.d.ts +35 -0
  36. package/dist/runtime/host-facts.js +95 -0
  37. package/dist/runtime/host-load-admission.d.ts +64 -0
  38. package/dist/runtime/host-load-admission.js +99 -0
  39. package/dist/runtime/host-load-child-environment.d.ts +27 -0
  40. package/dist/runtime/host-load-child-environment.js +76 -0
  41. package/dist/runtime/host-load-forge-cgroups.d.ts +49 -0
  42. package/dist/runtime/host-load-forge-cgroups.js +140 -0
  43. package/dist/runtime/host-load-governor-config.d.ts +52 -0
  44. package/dist/runtime/host-load-governor-config.js +83 -0
  45. package/dist/runtime/host-load-governor.d.ts +184 -0
  46. package/dist/runtime/host-load-governor.js +632 -0
  47. package/dist/runtime/host-load-ledger-lock.d.ts +69 -0
  48. package/dist/runtime/host-load-ledger-lock.js +185 -0
  49. package/dist/runtime/host-load-runtime-settings.d.ts +25 -0
  50. package/dist/runtime/host-load-runtime-settings.js +78 -0
  51. package/dist/runtime/host-load-sampler.d.ts +126 -0
  52. package/dist/runtime/host-load-sampler.js +232 -0
  53. package/dist/runtime/host-load-step-class.d.ts +70 -0
  54. package/dist/runtime/host-load-step-class.js +161 -0
  55. package/dist/runtime/host-load-step-reaper.d.ts +27 -0
  56. package/dist/runtime/host-load-step-reaper.js +95 -0
  57. package/dist/runtime/host-load-step-run.d.ts +73 -0
  58. package/dist/runtime/host-load-step-run.js +102 -0
  59. package/dist/runtime/host-load-test-slot.d.ts +43 -0
  60. package/dist/runtime/host-load-test-slot.js +81 -0
  61. package/dist/runtime/host-load-token-ledger.d.ts +200 -0
  62. package/dist/runtime/host-load-token-ledger.js +453 -0
  63. package/dist/runtime/host-pressure-stall.d.ts +61 -0
  64. package/dist/runtime/host-pressure-stall.js +168 -0
  65. package/dist/runtime/host-runtime-contract.d.ts +4 -0
  66. package/dist/runtime/host-runtime-contract.js +6 -1
  67. package/dist/runtime/host-runtime-lease.d.ts +74 -4
  68. package/dist/runtime/host-runtime-lease.js +336 -20
  69. package/dist/runtime/host-runtime-promotion.d.ts +23 -0
  70. package/dist/runtime/host-runtime-promotion.js +48 -0
  71. package/dist/runtime/host-runtime-requirements-check.d.ts +17 -0
  72. package/dist/runtime/host-runtime-requirements-check.js +29 -0
  73. package/dist/runtime/host-runtime-requirements.d.ts +36 -0
  74. package/dist/runtime/host-runtime-requirements.js +117 -0
  75. package/dist/runtime/managed-command-teardown.d.ts +62 -0
  76. package/dist/runtime/managed-command-teardown.js +607 -0
  77. package/dist/runtime/playwright-browser-cache.d.ts +39 -0
  78. package/dist/runtime/playwright-browser-cache.js +227 -0
  79. package/dist/runtime/playwright-host-runtime-adapter.d.ts +18 -0
  80. package/dist/runtime/playwright-host-runtime-adapter.js +61 -55
  81. package/dist/runtime/runner-settings.d.ts +100 -0
  82. package/dist/runtime/runner-settings.js +214 -0
  83. package/dist/sandbox/host-capacity-broker.d.ts +113 -0
  84. package/dist/sandbox/host-capacity-broker.js +334 -0
  85. package/dist/sandbox/runtime.d.ts +10 -1
  86. package/dist/sandbox/runtime.js +45 -2
  87. package/dist/sandbox/sandbox-cgroups.d.ts +14 -0
  88. package/dist/sandbox/sandbox-cgroups.js +42 -0
  89. package/dist/session/managed-attempt-tools.d.ts +27 -0
  90. package/dist/session/managed-attempt-tools.js +356 -41
  91. package/dist/session/managed-build-coordinator.d.ts +1 -1
  92. package/dist/session/managed-build-coordinator.js +4 -1
  93. package/dist/session/managed-command-host-load.d.ts +47 -0
  94. package/dist/session/managed-command-host-load.js +83 -0
  95. package/dist/session/mcp-argument-coercion.d.ts +23 -0
  96. package/dist/session/mcp-argument-coercion.js +121 -0
  97. package/dist/session/phase-completion.artifacts.d.ts +7 -0
  98. package/dist/session/phase-completion.artifacts.js +98 -25
  99. package/dist/session/phase-completion.command-validation.d.ts +7 -0
  100. package/dist/session/phase-completion.command-validation.js +77 -0
  101. package/dist/session/phase-completion.d.ts +4 -0
  102. package/dist/session/phase-completion.helpers.js +13 -12
  103. package/dist/session/phase-completion.js +4 -0
  104. package/dist/session/phase-completion.prompts.js +6 -1
  105. package/dist/session/phase-completion.runtime.d.ts +5 -3
  106. package/dist/session/phase-completion.runtime.js +70 -35
  107. package/dist/session/phase-completion.schema-parts.d.ts +19 -0
  108. package/dist/session/phase-completion.schema-parts.js +188 -0
  109. package/dist/session/phase-completion.schemas.d.ts +3 -3
  110. package/dist/session/phase-completion.schemas.js +206 -221
  111. package/dist/session/phase-completion.validation.d.ts +2 -3
  112. package/dist/session/phase-completion.validation.js +46 -92
  113. package/dist/session/pre-publication-host-load.d.ts +27 -0
  114. package/dist/session/pre-publication-host-load.js +111 -0
  115. package/dist/session/pre-publication-pass.d.ts +61 -0
  116. package/dist/session/pre-publication-pass.js +148 -0
  117. package/dist/session/pre-publication-process.d.ts +23 -0
  118. package/dist/session/pre-publication-process.js +109 -0
  119. package/dist/session/pre-publication-skipped-tests.d.ts +21 -0
  120. package/dist/session/pre-publication-skipped-tests.js +109 -0
  121. package/dist/session/pre-publication-step-execution.d.ts +11 -0
  122. package/dist/session/pre-publication-step-execution.js +49 -0
  123. package/dist/session/pre-publication-validation.d.ts +32 -20
  124. package/dist/session/pre-publication-validation.js +202 -195
  125. package/dist/session/provider-cli/claude-background-work.d.ts +66 -0
  126. package/dist/session/provider-cli/claude-background-work.js +180 -0
  127. package/dist/session/provider-cli/pre-publication-repair.d.ts +40 -0
  128. package/dist/session/provider-cli/pre-publication-repair.js +243 -0
  129. package/dist/session/provider-cli/provider-cli.artifacts.d.ts +2 -1
  130. package/dist/session/provider-cli/provider-cli.artifacts.js +21 -15
  131. package/dist/session/provider-cli/provider-cli.merge-integrity.d.ts +89 -0
  132. package/dist/session/provider-cli/provider-cli.merge-integrity.js +310 -0
  133. package/dist/session/provider-cli/provider-cli.process.d.ts +39 -2
  134. package/dist/session/provider-cli/provider-cli.process.js +276 -42
  135. package/dist/session/provider-cli/provider-cli.prompts.d.ts +7 -0
  136. package/dist/session/provider-cli/provider-cli.prompts.js +65 -10
  137. package/dist/session/provider-cli/provider-cli.runtime.js +7 -0
  138. package/dist/session/provider-cli/provider-cli.service.d.ts +4 -1
  139. package/dist/session/provider-cli/provider-cli.service.js +203 -172
  140. package/dist/session/provider-cli/provider-cli.types.d.ts +30 -0
  141. package/dist/session/provider-cli/provider-in-flight-work.d.ts +10 -0
  142. package/dist/session/provider-cli/provider-in-flight-work.js +92 -0
  143. package/dist/session/provider-cli/provider-output-state.d.ts +8 -0
  144. package/dist/session/provider-cli/provider-output-state.js +15 -0
  145. package/dist/session/publishable-worktree-changes.d.ts +54 -0
  146. package/dist/session/publishable-worktree-changes.js +193 -0
  147. package/dist/session/sandbox-host-capacity-gate.d.ts +30 -0
  148. package/dist/session/sandbox-host-capacity-gate.js +238 -0
  149. package/dist/session/session.base.d.ts +9 -1
  150. package/dist/session/session.service.d.ts +9 -2
  151. package/dist/session/session.service.js +120 -5
  152. package/dist/session/session.types.d.ts +3 -0
  153. package/dist/session/session.types.js +15 -3
  154. package/dist/session/workspace-runtime-fingerprint.d.ts +32 -0
  155. package/dist/session/workspace-runtime-fingerprint.js +138 -0
  156. package/dist/shared/process/host-process-supervisor.d.ts +1 -0
  157. package/dist/shared/process/host-process-supervisor.js +1 -1
  158. package/dist/shared/process/process-tree.d.ts +52 -0
  159. package/dist/shared/process/process-tree.js +144 -0
  160. package/dist/shared/process/process.d.ts +67 -0
  161. package/dist/shared/process/process.js +213 -11
  162. package/dist/shared/provider-capabilities.js +5 -6
  163. package/dist/version.d.ts +1 -1
  164. package/dist/version.js +1 -1
  165. package/dist/worktree/dependency-warmer.d.ts +25 -0
  166. package/dist/worktree/dependency-warmer.js +46 -10
  167. package/dist/worktree/worktree.service.d.ts +10 -1
  168. package/dist/worktree/worktree.service.js +42 -2
  169. package/dist/worktree/worktree.types.d.ts +7 -0
  170. package/package.json +2 -2
@@ -1,18 +1,48 @@
1
1
  import type { RunOnceDispatchPacket, RunnerDispatchArtifact, RunnerDispatchEvent, RunnerDispatchSpec } from "../session.types.js";
2
2
  import type { WorktreeHandle } from "../../worktree/worktree.types.js";
3
3
  import type { ProviderProcessRunner } from "./provider-cli.process.js";
4
+ /**
5
+ * Why the attempt's runtime stack restarted before a validation pass. The first cause that applies:
6
+ * a previous restart did not complete; the workspace state could not be compared with the stack's
7
+ * (either reading was unavailable); or the workspace changed since the stack was launched.
8
+ */
9
+ export type RuntimeRestartReason = "previous_restart_incomplete" | "fingerprint_unavailable" | "workspace_changed";
10
+ export interface RuntimeEnvironmentRefresh {
11
+ /** The restarted stack's runtime environment. */
12
+ readonly environment: Readonly<Record<string, string>>;
13
+ readonly reason: RuntimeRestartReason;
14
+ /** What changed in the workspace since the stack was launched, when both states could be read. */
15
+ readonly changes: readonly string[];
16
+ }
4
17
  export interface ProviderCliRunContext {
5
18
  readonly dispatch: RunOnceDispatchPacket;
6
19
  readonly worktree: WorktreeHandle;
7
20
  readonly runtimeEnvironment?: Readonly<Record<string, string>>;
21
+ /** Host load governor variables for the completion MCP server only (decision 0013). */
22
+ readonly hostLoadEnvironment?: Readonly<Record<string, string>>;
8
23
  readonly processRunner?: ProviderProcessRunner;
9
24
  readonly signal?: AbortSignal;
25
+ /**
26
+ * Restarts the attempt's host runtime stack when the workspace changed since it was
27
+ * launched (an uncommitted edit, an in-progress merge), so validation and repair
28
+ * turns run against the current source. Resolves to the refreshed runtime
29
+ * environment and why the stack restarted, or null when the stack is current or
30
+ * there is no configured project.
31
+ */
32
+ refreshRuntimeEnvironment?(signal?: AbortSignal): Promise<RuntimeEnvironmentRefresh | null>;
33
+ /**
34
+ * The runtime environment keys that name the configured project's live stack (its URLs and
35
+ * ports). A failed restart withholds them from the repair turn, since the stack is down.
36
+ */
37
+ readonly runtimeStackEnvironmentKeys?: readonly string[];
10
38
  emit(event: RunnerDispatchEvent): Promise<void>;
11
39
  }
12
40
  export interface ProviderCliDraftContext {
13
41
  readonly dispatch: RunOnceDispatchPacket;
14
42
  readonly worktree: WorktreeHandle;
15
43
  readonly runtimeEnvironment?: Readonly<Record<string, string>>;
44
+ /** Host load governor variables for the completion MCP server only (decision 0013). */
45
+ readonly hostLoadEnvironment?: Readonly<Record<string, string>>;
16
46
  readonly processRunner?: ProviderProcessRunner;
17
47
  readonly signal?: AbortSignal;
18
48
  emit(event: RunnerDispatchEvent): Promise<void>;
@@ -0,0 +1,10 @@
1
+ /**
2
+ * True while an attempt-owned managed command (a receipt under
3
+ * `<FORGE_LOG_DIR>/managed-commands/`) is still starting, queued or running.
4
+ * Unreadable or stale receipts do not count.
5
+ */
6
+ export declare function hasNonterminalManagedCommand(logDirectory: string | undefined, nowMs?: number): Promise<boolean>;
7
+ /** A stream event that shows the provider is working on a turn: model output or a tool result. */
8
+ export declare function isProviderTurnActivity(line: string): boolean;
9
+ export declare function isProviderTerminalFailure(line: string): boolean;
10
+ export declare function isProviderTerminalSuccess(line: string): boolean;
@@ -0,0 +1,92 @@
1
+ import fs from "node:fs/promises";
2
+ import path from "node:path";
3
+ const nonterminalManagedCommandStatuses = new Set(["starting", "running", "waiting_for_build_slot"]);
4
+ // A running receipt is rewritten every 5 s. One that has not changed for a minute
5
+ // belongs to a command whose supervisor is gone, so it no longer holds the provider open.
6
+ const runningReceiptStaleMs = 60_000;
7
+ // Starting and queued receipts are written once. They hold the provider open for at most
8
+ // the command's own timeout (the managed-command maximum when absent) plus a margin.
9
+ const maximumManagedCommandTimeoutMs = 2 * 60 * 60_000;
10
+ const queuedReceiptMarginMs = 60_000;
11
+ /**
12
+ * True while an attempt-owned managed command (a receipt under
13
+ * `<FORGE_LOG_DIR>/managed-commands/`) is still starting, queued or running.
14
+ * Unreadable or stale receipts do not count.
15
+ */
16
+ export async function hasNonterminalManagedCommand(logDirectory, nowMs = Date.now()) {
17
+ if (!logDirectory?.trim())
18
+ return false;
19
+ const directory = path.join(logDirectory, "managed-commands");
20
+ const names = await fs.readdir(directory).catch(() => []);
21
+ for (const name of names) {
22
+ if (!name.endsWith(".receipt.json"))
23
+ continue;
24
+ if (await receiptHoldsProvider(path.join(directory, name), nowMs))
25
+ return true;
26
+ }
27
+ return false;
28
+ }
29
+ async function receiptHoldsProvider(receiptPath, nowMs) {
30
+ try {
31
+ const [stat, content] = await Promise.all([fs.stat(receiptPath), fs.readFile(receiptPath, "utf8")]);
32
+ const receipt = JSON.parse(content);
33
+ const status = typeof receipt.status === "string" ? receipt.status : "";
34
+ if (!nonterminalManagedCommandStatuses.has(status))
35
+ return false;
36
+ const ageMs = nowMs - stat.mtimeMs;
37
+ if (status === "running")
38
+ return ageMs <= runningReceiptStaleMs;
39
+ const timeoutMs = typeof receipt.timeout_ms === "number" && Number.isFinite(receipt.timeout_ms)
40
+ ? receipt.timeout_ms
41
+ : maximumManagedCommandTimeoutMs;
42
+ return ageMs <= timeoutMs + queuedReceiptMarginMs;
43
+ }
44
+ catch {
45
+ return false;
46
+ }
47
+ }
48
+ /** A stream event that shows the provider is working on a turn: model output or a tool result. */
49
+ export function isProviderTurnActivity(line) {
50
+ const trimmed = line.trim();
51
+ if (!trimmed.startsWith("{"))
52
+ return false;
53
+ try {
54
+ const event = JSON.parse(trimmed);
55
+ return event.type === "assistant"
56
+ || event.type === "user"
57
+ || (event.type === "system" && event.subtype === "init")
58
+ || event.type === "turn.started"
59
+ || event.type === "item.started";
60
+ }
61
+ catch {
62
+ return false;
63
+ }
64
+ }
65
+ export function isProviderTerminalFailure(line) {
66
+ const trimmed = line.trim();
67
+ if (!trimmed.startsWith("{"))
68
+ return false;
69
+ try {
70
+ const event = JSON.parse(trimmed);
71
+ // The same events the output parsers report as provider errors.
72
+ return event.type === "turn.failed"
73
+ || event.type === "error"
74
+ || (event.type === "result" && (event.subtype !== "success" || event.is_error === true));
75
+ }
76
+ catch {
77
+ return false;
78
+ }
79
+ }
80
+ export function isProviderTerminalSuccess(line) {
81
+ const trimmed = line.trim();
82
+ if (!trimmed.startsWith("{"))
83
+ return false;
84
+ try {
85
+ const event = JSON.parse(trimmed);
86
+ return event.type === "turn.completed"
87
+ || (event.type === "result" && event.subtype === "success" && event.is_error !== true);
88
+ }
89
+ catch {
90
+ return false;
91
+ }
92
+ }
@@ -1,6 +1,8 @@
1
1
  import type { RunnerDispatchEvent } from "../session.types.js";
2
2
  import { type ProviderUsage } from "./provider-usage.js";
3
3
  export declare function messageFromError(error: unknown): string;
4
+ /** Keeps the end of `value`, where a process's failure detail is, within `maximumLength`. */
5
+ export declare function clipTail(value: string, maximumLength: number): string;
4
6
  export declare function clip(value: string, maxLength: number): string;
5
7
  export interface ProviderOutputState {
6
8
  readonly sessionLabel: string | null;
@@ -9,6 +11,12 @@ export interface ProviderOutputState {
9
11
  finalMessage: string | null;
10
12
  /** True only while the provider has reported a tool/command start without a matching completion. */
11
13
  readonly hasActiveToolCall: boolean;
14
+ /**
15
+ * Forgets tool calls a previous provider generation started but never completed. A
16
+ * generation that exits mid-call reports no completion, and the next generation must not
17
+ * inherit that call as still in flight.
18
+ */
19
+ resetActiveToolCalls(): void;
12
20
  /** Accumulated provider-reported token usage for this run, or null when none was reported. */
13
21
  readonly usage: ProviderUsage | null;
14
22
  consume(line: string): readonly RunnerDispatchEvent[];
@@ -2,6 +2,12 @@ import { addUsage, emptyUsage, readUsageNumber } from "./provider-usage.js";
2
2
  export function messageFromError(error) {
3
3
  return error instanceof Error ? error.message : String(error);
4
4
  }
5
+ /** Keeps the end of `value`, where a process's failure detail is, within `maximumLength`. */
6
+ export function clipTail(value, maximumLength) {
7
+ if (value.length <= maximumLength)
8
+ return value;
9
+ return `...${value.slice(-(maximumLength - 3))}`;
10
+ }
5
11
  export function clip(value, maxLength) {
6
12
  if (maxLength <= 0) {
7
13
  return "";
@@ -43,6 +49,9 @@ class CursorStreamJsonState {
43
49
  get hasActiveToolCall() {
44
50
  return this.activeToolCallCount > 0;
45
51
  }
52
+ resetActiveToolCalls() {
53
+ this.activeToolCallCount = 0;
54
+ }
46
55
  consume(line) {
47
56
  const event = parseJsonLine(line);
48
57
  if (!event) {
@@ -264,6 +273,9 @@ class ClaudeStreamJsonState {
264
273
  get hasActiveToolCall() {
265
274
  return this.activeToolUses.size > 0;
266
275
  }
276
+ resetActiveToolCalls() {
277
+ this.activeToolUses.clear();
278
+ }
267
279
  consume(line) {
268
280
  const event = parseJsonLine(line);
269
281
  if (!event) {
@@ -544,6 +556,9 @@ class CodexJsonState {
544
556
  get hasActiveToolCall() {
545
557
  return this.activeToolCallCount > 0;
546
558
  }
559
+ resetActiveToolCalls() {
560
+ this.activeToolCallCount = 0;
561
+ }
547
562
  consume(line) {
548
563
  const event = parseJsonLine(line);
549
564
  if (!event) {
@@ -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
+ }
@@ -0,0 +1,30 @@
1
+ import { type HostLoadAcquireOptions, type HostLoadAdmission, type HostLoadStepGate, type HostLoadStepRequest } from "../runtime/host-load-governor.js";
2
+ export interface SandboxHostCapacityGateOptions {
3
+ readonly write?: (line: string) => void;
4
+ readonly responseRoot?: string;
5
+ readonly pollMs?: number;
6
+ /** Fails closed if the bridge never answers (the host enforces its own maximum wait first). */
7
+ readonly maxWaitMs?: number;
8
+ /** Owner of authentic replies (root in the container; tests use their own uid). */
9
+ readonly trustedOwnerUid?: number;
10
+ }
11
+ export declare class SandboxBrokeredHostLoadGate implements HostLoadStepGate {
12
+ readonly enabled = true;
13
+ private readonly write;
14
+ private readonly responseRoot;
15
+ private readonly pollMs;
16
+ private readonly trustedOwnerUid;
17
+ readonly maxWaitMs: number;
18
+ constructor(options?: SandboxHostCapacityGateOptions);
19
+ acquire(request: HostLoadStepRequest, options?: HostLoadAcquireOptions): Promise<HostLoadAdmission>;
20
+ private admission;
21
+ private send;
22
+ }
23
+ /**
24
+ * The brokered gate when the host bridge enabled it for this sandbox. The
25
+ * variable is removed once read, so commands the sandbox runs never inherit it
26
+ * (a nested Forge process must not queue behind its parent's token).
27
+ */
28
+ export declare function sandboxHostLoadGateFromEnvironment(environment?: NodeJS.ProcessEnv): HostLoadStepGate | undefined;
29
+ /** Test support: forgets the cached gate. */
30
+ export declare function resetSandboxHostLoadGateForTesting(): void;