@loucompanion/forge-bridge 0.1.4-dev.6b2148ecc60c → 0.1.4-dev.724427ea7be8

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 (163) hide show
  1. package/README.md +87 -1
  2. package/dist/bridge/bridge-chat-provider-command.d.ts +5 -2
  3. package/dist/bridge/bridge-chat-provider-command.js +29 -22
  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.service.d.ts +16 -12
  15. package/dist/bridge/bridge.service.js +131 -243
  16. package/dist/bridge/bridge.types.d.ts +5 -0
  17. package/dist/bridge/in-flight-registry.d.ts +62 -0
  18. package/dist/bridge/in-flight-registry.js +207 -0
  19. package/dist/bridge/readiness-result-outbox.d.ts +5 -1
  20. package/dist/bridge/readiness-result-outbox.js +20 -0
  21. package/dist/bridge/sandbox-resource-accounting.d.ts +16 -0
  22. package/dist/bridge/sandbox-resource-accounting.js +150 -0
  23. package/dist/cleanup/cleanup-wip.d.ts +12 -0
  24. package/dist/cleanup/cleanup-wip.js +66 -0
  25. package/dist/cleanup/cleanup.service.d.ts +11 -1
  26. package/dist/cleanup/cleanup.service.js +80 -62
  27. package/dist/cleanup/cleanup.types.d.ts +2 -0
  28. package/dist/cleanup/host-runtime-ledger.d.ts +2 -0
  29. package/dist/cleanup/host-runtime-ledger.js +30 -9
  30. package/dist/cli/cli.help.js +56 -12
  31. package/dist/cli/cli.service.d.ts +3 -10
  32. package/dist/cli/cli.service.js +10 -171
  33. package/dist/cli/idle-status.d.ts +84 -0
  34. package/dist/cli/idle-status.js +181 -0
  35. package/dist/cli/local-config.d.ts +2 -0
  36. package/dist/cli/local-config.js +7 -1
  37. package/dist/cli/provider-cli-detection.d.ts +10 -0
  38. package/dist/cli/provider-cli-detection.js +160 -0
  39. package/dist/runtime/aspnet-runtime-prebuild.d.ts +20 -0
  40. package/dist/runtime/aspnet-runtime-prebuild.js +104 -26
  41. package/dist/runtime/attempt-database-broker.d.ts +1 -1
  42. package/dist/runtime/attempt-node-runtime-launcher.js +9 -0
  43. package/dist/runtime/attempt-process-supervisor.d.ts +2 -0
  44. package/dist/runtime/attempt-process-supervisor.js +12 -6
  45. package/dist/runtime/docker-engine-probe.d.ts +5 -0
  46. package/dist/runtime/docker-engine-probe.js +7 -0
  47. package/dist/runtime/dotnet-build-outputs.d.ts +107 -0
  48. package/dist/runtime/dotnet-build-outputs.js +402 -0
  49. package/dist/runtime/ephemeral-test-postgres-grant.d.ts +37 -0
  50. package/dist/runtime/ephemeral-test-postgres-grant.js +85 -0
  51. package/dist/runtime/ephemeral-test-postgres.d.ts +57 -0
  52. package/dist/runtime/ephemeral-test-postgres.js +303 -0
  53. package/dist/runtime/host-load-governor.d.ts +2 -0
  54. package/dist/runtime/host-load-ledger-lock.js +6 -4
  55. package/dist/runtime/host-load-runtime-settings.js +4 -2
  56. package/dist/runtime/host-load-sampler.d.ts +8 -1
  57. package/dist/runtime/host-load-sampler.js +14 -7
  58. package/dist/runtime/host-runtime-contract.d.ts +12 -0
  59. package/dist/runtime/host-runtime-contract.js +29 -1
  60. package/dist/runtime/host-runtime-lease.d.ts +2 -1
  61. package/dist/runtime/host-runtime-lease.js +30 -153
  62. package/dist/runtime/host-runtime-ledger-recovery.d.ts +20 -0
  63. package/dist/runtime/host-runtime-ledger-recovery.js +134 -0
  64. package/dist/runtime/managed-command-teardown.js +5 -16
  65. package/dist/runtime/native-test-postgres-fallback.d.ts +51 -7
  66. package/dist/runtime/native-test-postgres-fallback.js +60 -8
  67. package/dist/runtime/runner-settings.d.ts +4 -0
  68. package/dist/runtime/runner-settings.js +22 -0
  69. package/dist/runtime/supervised-runtime-build-guard.d.ts +45 -0
  70. package/dist/runtime/supervised-runtime-build-guard.js +112 -0
  71. package/dist/sandbox/host-capacity-broker.d.ts +3 -1
  72. package/dist/sandbox/host-capacity-broker.js +4 -2
  73. package/dist/sandbox/managed-branch.d.ts +13 -0
  74. package/dist/sandbox/managed-branch.js +90 -0
  75. package/dist/sandbox/provider-auth/codex.js +11 -11
  76. package/dist/sandbox/runtime.js +2 -6
  77. package/dist/session/architect-waits.d.ts +2 -0
  78. package/dist/session/architect-waits.js +138 -0
  79. package/dist/session/managed-attempt-tools.d.ts +0 -7
  80. package/dist/session/managed-attempt-tools.js +50 -82
  81. package/dist/session/managed-build-coordinator.d.ts +16 -0
  82. package/dist/session/managed-build-coordinator.js +10 -0
  83. package/dist/session/managed-build-receipt.d.ts +5 -0
  84. package/dist/session/managed-build-receipt.js +8 -3
  85. package/dist/session/phase-completion.artifacts.js +2 -1
  86. package/dist/session/phase-completion.d.ts +8 -0
  87. package/dist/session/phase-completion.js +1 -0
  88. package/dist/session/phase-completion.mcp-args.d.ts +9 -0
  89. package/dist/session/phase-completion.mcp-args.js +156 -0
  90. package/dist/session/phase-completion.runtime.d.ts +0 -8
  91. package/dist/session/phase-completion.runtime.js +43 -197
  92. package/dist/session/phase-completion.schemas.js +3 -11
  93. package/dist/session/phase-completion.validation.js +3 -1
  94. package/dist/session/pre-publication-native-postgres.d.ts +30 -0
  95. package/dist/session/pre-publication-native-postgres.js +111 -0
  96. package/dist/session/pre-publication-process.js +10 -10
  97. package/dist/session/pre-publication-step-execution.d.ts +2 -1
  98. package/dist/session/pre-publication-step-execution.js +6 -5
  99. package/dist/session/pre-publication-validation.d.ts +7 -3
  100. package/dist/session/pre-publication-validation.js +32 -30
  101. package/dist/session/provider-cli/claude-background-work.d.ts +3 -2
  102. package/dist/session/provider-cli/claude-background-work.js +4 -3
  103. package/dist/session/provider-cli/host-build-lock.d.ts +18 -0
  104. package/dist/session/provider-cli/host-build-lock.js +30 -0
  105. package/dist/session/provider-cli/pre-publication-repair.d.ts +16 -0
  106. package/dist/session/provider-cli/pre-publication-repair.js +33 -0
  107. package/dist/session/provider-cli/provider-cli.child-environment.js +4 -2
  108. package/dist/session/provider-cli/provider-cli.process.d.ts +2 -14
  109. package/dist/session/provider-cli/provider-cli.process.js +4 -94
  110. package/dist/session/provider-cli/provider-cli.prompts.d.ts +3 -0
  111. package/dist/session/provider-cli/provider-cli.prompts.js +27 -27
  112. package/dist/session/provider-cli/provider-cli.runtime.d.ts +8 -0
  113. package/dist/session/provider-cli/provider-cli.runtime.js +23 -2
  114. package/dist/session/provider-cli/provider-cli.service.d.ts +4 -1
  115. package/dist/session/provider-cli/provider-cli.service.js +27 -43
  116. package/dist/session/provider-cli/provider-cli.windows-launch.d.ts +23 -0
  117. package/dist/session/provider-cli/provider-cli.windows-launch.js +131 -0
  118. package/dist/session/provider-cli/provider-user-config-isolation.d.ts +69 -0
  119. package/dist/session/provider-cli/provider-user-config-isolation.js +164 -0
  120. package/dist/session/qa-sidecar-validation.d.ts +6 -0
  121. package/dist/session/qa-sidecar-validation.js +28 -0
  122. package/dist/session/sandbox-host-capacity-gate.d.ts +22 -1
  123. package/dist/session/sandbox-host-capacity-gate.js +34 -15
  124. package/dist/session/session-redaction.js +31 -181
  125. package/dist/session/session.service.d.ts +2 -0
  126. package/dist/session/session.service.js +69 -64
  127. package/dist/session/session.types.js +1 -1
  128. package/dist/session/sidecar-json-shape.d.ts +31 -0
  129. package/dist/session/sidecar-json-shape.js +217 -0
  130. package/dist/shared/fs/file-identity.d.ts +10 -0
  131. package/dist/shared/fs/file-identity.js +15 -0
  132. package/dist/shared/fs/replace-file.d.ts +7 -0
  133. package/dist/shared/fs/replace-file.js +33 -0
  134. package/dist/shared/process/host-process-recovery.d.ts +14 -3
  135. package/dist/shared/process/host-process-recovery.js +23 -3
  136. package/dist/shared/process/host-process-supervisor.d.ts +13 -1
  137. package/dist/shared/process/host-process-supervisor.js +66 -14
  138. package/dist/shared/provider-capabilities.js +9 -1
  139. package/dist/version.d.ts +1 -1
  140. package/dist/version.js +1 -1
  141. package/dist/worktree/orphan-relink.d.ts +19 -0
  142. package/dist/worktree/orphan-relink.js +106 -0
  143. package/dist/worktree/wip-git.d.ts +33 -0
  144. package/dist/worktree/wip-git.js +122 -0
  145. package/dist/worktree/wip-refs.d.ts +62 -0
  146. package/dist/worktree/wip-refs.js +119 -0
  147. package/dist/worktree/wip-restore.d.ts +38 -0
  148. package/dist/worktree/wip-restore.js +190 -0
  149. package/dist/worktree/wip-snapshot.d.ts +50 -0
  150. package/dist/worktree/wip-snapshot.js +268 -0
  151. package/dist/worktree/worktree-inputs.d.ts +8 -0
  152. package/dist/worktree/worktree-inputs.js +134 -0
  153. package/dist/worktree/worktree-origin-sync.d.ts +34 -0
  154. package/dist/worktree/worktree-origin-sync.js +127 -0
  155. package/dist/worktree/worktree-wip-events.d.ts +18 -0
  156. package/dist/worktree/worktree-wip-events.js +98 -0
  157. package/dist/worktree/worktree-wip.d.ts +50 -0
  158. package/dist/worktree/worktree-wip.js +185 -0
  159. package/dist/worktree/worktree.base.d.ts +7 -1
  160. package/dist/worktree/worktree.service.d.ts +27 -5
  161. package/dist/worktree/worktree.service.js +110 -181
  162. package/dist/worktree/worktree.types.d.ts +31 -0
  163. package/package.json +1 -1
@@ -0,0 +1,138 @@
1
+ // Decision 0022: a blocked Architect verdict may say what it waits on (a sibling Story, a pull
2
+ // request, or something outside Forge) and which choice it needs from the owner. Forge records
3
+ // Story and pull request waits as dependency edges and re-plans the Story when they merge.
4
+ const architectWaitKinds = ["story", "pull_request", "external"];
5
+ const architectWaitUntil = ["merged"];
6
+ const storyIdPattern = /^(?:[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}|[0-9a-f]{8,32})$/i;
7
+ // Architect tool properties for non-pass verdicts: revision prose plus the structured waits.
8
+ export function architectNonPassProperties() {
9
+ return {
10
+ revision_questions: {
11
+ type: "array",
12
+ description: "Required for needs_revision when blockers are not used.",
13
+ items: { type: "string" }
14
+ },
15
+ revision_reasons: {
16
+ type: "array",
17
+ description: "Concrete reasons that prevent pass status.",
18
+ items: { type: "string" }
19
+ },
20
+ waits_on: {
21
+ type: "array",
22
+ description: "Only with status blocked. What must merge before this Story can be planned: a sibling Story (kind story, story_id as the full id or its first 8+ hex digits), a pull request (kind pull_request, pr_number), or something outside Forge (kind external). Forge records Story and sibling pull request waits and plans the Story again when they merge; external waits hold for the owner.",
23
+ items: {
24
+ type: "object",
25
+ additionalProperties: false,
26
+ required: ["kind", "until", "reason"],
27
+ properties: {
28
+ kind: { type: "string", enum: [...architectWaitKinds] },
29
+ story_id: { type: "string", description: "Required for kind story." },
30
+ pr_number: { type: "integer", minimum: 1, description: "Required for kind pull_request." },
31
+ until: { type: "string", enum: [...architectWaitUntil] },
32
+ reason: { type: "string", description: "What this Story needs from the blocker." }
33
+ }
34
+ }
35
+ },
36
+ owner_decision: {
37
+ type: "object",
38
+ description: "Only with status blocked. A choice only the owner can make before the Story can be planned. Forge holds the Story for the owner and never picks an option.",
39
+ additionalProperties: false,
40
+ required: ["question", "options"],
41
+ properties: {
42
+ question: { type: "string" },
43
+ options: {
44
+ type: "array",
45
+ minItems: 2,
46
+ items: {
47
+ type: "object",
48
+ additionalProperties: false,
49
+ required: ["label", "summary"],
50
+ properties: {
51
+ label: { type: "string" },
52
+ summary: { type: "string" }
53
+ }
54
+ }
55
+ },
56
+ recommended: { type: "string", description: "Label of the recommended option." }
57
+ }
58
+ }
59
+ };
60
+ }
61
+ // An explicit null is absent, as the API reads it.
62
+ function isPresent(value) {
63
+ return value !== undefined && value !== null;
64
+ }
65
+ function hasArchitectWaitDeclarations(payload) {
66
+ return isPresent(payload.waits_on) || isPresent(payload.owner_decision);
67
+ }
68
+ // Throws an actionable error for a malformed waits_on or owner_decision. Absent (or null) fields are valid.
69
+ export function validateArchitectWaits(payload, status) {
70
+ if (!hasArchitectWaitDeclarations(payload)) {
71
+ return;
72
+ }
73
+ if (status !== "blocked") {
74
+ throw new Error("waits_on/owner_decision: allowed only with status blocked; correction: remove them, or return status blocked when the plan cannot pass until they are resolved.");
75
+ }
76
+ if (isPresent(payload.waits_on)) {
77
+ validateWaitsOn(payload.waits_on);
78
+ }
79
+ if (isPresent(payload.owner_decision)) {
80
+ validateOwnerDecision(payload.owner_decision);
81
+ }
82
+ }
83
+ function validateWaitsOn(value) {
84
+ if (!Array.isArray(value) || value.length === 0) {
85
+ throw new Error("waits_on: expected a non-empty array; correction: list each Story, pull request or external dependency, or omit waits_on.");
86
+ }
87
+ value.forEach((entry, index) => validateWait(entry, `waits_on[${index}]`));
88
+ }
89
+ function validateWait(entry, label) {
90
+ const wait = requireRecord(entry, label);
91
+ const kind = wait.kind;
92
+ if (typeof kind !== "string" || !architectWaitKinds.includes(kind)) {
93
+ throw new Error(`${label}.kind: expected one of story, pull_request, external.`);
94
+ }
95
+ if (wait.until !== "merged") {
96
+ throw new Error(`${label}.until: expected "merged".`);
97
+ }
98
+ requireText(wait.reason, `${label}.reason`);
99
+ if (kind === "story") {
100
+ const storyId = requireText(wait.story_id, `${label}.story_id`);
101
+ if (!storyIdPattern.test(storyId)) {
102
+ throw new Error(`${label}.story_id: expected the Story's full id or its first 8+ hex digits; got '${storyId}'.`);
103
+ }
104
+ }
105
+ if (kind === "pull_request" && !(typeof wait.pr_number === "number" && Number.isInteger(wait.pr_number) && wait.pr_number > 0)) {
106
+ throw new Error(`${label}.pr_number: expected a positive integer pull request number.`);
107
+ }
108
+ }
109
+ function validateOwnerDecision(value) {
110
+ const decision = requireRecord(value, "owner_decision");
111
+ requireText(decision.question, "owner_decision.question");
112
+ if (!Array.isArray(decision.options) || decision.options.length < 2) {
113
+ throw new Error("owner_decision.options: expected at least two options, each with a distinct label and a summary.");
114
+ }
115
+ const labels = decision.options.map((option, index) => {
116
+ const record = requireRecord(option, `owner_decision.options[${index}]`);
117
+ requireText(record.summary, `owner_decision.options[${index}].summary`);
118
+ return requireText(record.label, `owner_decision.options[${index}].label`);
119
+ });
120
+ if (new Set(labels).size !== labels.length) {
121
+ throw new Error("owner_decision.options: expected at least two options, each with a distinct label and a summary.");
122
+ }
123
+ if (isPresent(decision.recommended) && !labels.includes(requireText(decision.recommended, "owner_decision.recommended"))) {
124
+ throw new Error("owner_decision.recommended: expected the label of one of the options.");
125
+ }
126
+ }
127
+ function requireRecord(value, label) {
128
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
129
+ throw new Error(`${label}: expected an object.`);
130
+ }
131
+ return value;
132
+ }
133
+ function requireText(value, label) {
134
+ if (typeof value !== "string" || value.trim().length === 0) {
135
+ throw new Error(`${label}: expected a non-empty string.`);
136
+ }
137
+ return value.trim();
138
+ }
@@ -1,4 +1,3 @@
1
- import { type NativeTestPostgresFallback } from "../runtime/native-test-postgres-fallback.js";
2
1
  export declare const managedAttemptToolNames: readonly ["forge.run_managed_command", "run_managed_command", "forge.start_managed_command", "start_managed_command", "forge.get_managed_command", "get_managed_command", "forge.wait_managed_command", "wait_managed_command", "forge.start_managed_verification", "start_managed_verification", "forge.reset_generated_outputs", "reset_generated_outputs"];
3
2
  /**
4
3
  * Stops every managed command this MCP server started, proves each process tree stopped,
@@ -45,11 +44,5 @@ export declare function buildManagedVerificationCommand(profile: string, outputD
45
44
  export declare function preferredPowerShellExecutable(platform?: NodeJS.Platform, pathValue?: string): string;
46
45
  export declare function validatePlaywrightProjectName(project: string, availableProjects: readonly string[]): void;
47
46
  export declare function playwrightProjectNamesFromConfigSource(source: string): readonly string[];
48
- /**
49
- * Runner-authored verification normally uses its attempt-owned Testcontainers
50
- * database. Only when the Docker engine is unavailable does it switch to the
51
- * operator-provisioned native test cluster, which holds no real data.
52
- */
53
- export declare function managedVerificationDatabaseEnvironment(dockerAvailable?: () => Promise<boolean>, readFallback?: () => NativeTestPostgresFallback | null): Promise<Readonly<Record<string, string>>>;
54
47
  export declare function isBuildProducingManagedCommand(command: string, args: readonly string[]): boolean;
55
48
  export {};
@@ -3,19 +3,18 @@ import fs from "node:fs/promises";
3
3
  import os from "node:os";
4
4
  import path from "node:path";
5
5
  import { resetGeneratedOutputs } from "../runtime/generated-output-reset.js";
6
- import { DockerEngineProbe } from "../runtime/docker-engine-probe.js";
7
6
  import { attemptDatabaseCapabilityEnvironment, attemptDatabaseCapabilitySecrets, } from "../runtime/attempt-database-broker.js";
8
7
  import { assertHostDatabaseCapabilityBoundary } from "../runtime/host-database-capability-boundary.js";
9
- import { nativeTestPostgresFallbackConfigEnvironment, nativeTestPostgresFallbackDatabaseMode, nativeTestPostgresFallbackEnvironment, readNativeTestPostgresFallback, } from "../runtime/native-test-postgres-fallback.js";
8
+ import { managedVerificationDatabase, noManagedVerificationDatabase, releaseManagedVerificationDatabase, setUpWithManagedVerificationDatabase } from "../runtime/ephemeral-test-postgres-grant.js";
10
9
  import { redactText } from "../shared/redaction/redaction.js";
11
10
  import { emptyToolInputHint, isEmptyToolInput } from "./mcp-argument-coercion.js";
12
- import { ManagedBuildCoordinator } from "./managed-build-coordinator.js";
11
+ import { assertManagedBuildSparesSupervisedRuntimes, ManagedBuildCoordinator } from "./managed-build-coordinator.js";
13
12
  import { attachManagedCommandProcess, ManagedCommandHostCapacity, } from "./managed-command-host-load.js";
14
13
  import { HostCapacityLedgerUnavailableError } from "../runtime/host-load-ledger-lock.js";
15
14
  import { isProcessTreeTerminationUnproven } from "../shared/process/process.js";
16
15
  import { HostCapacityTokenFencedError } from "../runtime/host-load-token-ledger.js";
17
16
  import { withoutHostLoadGovernorVariables } from "../runtime/host-load-child-environment.js";
18
- import { managedBuildConfiguration, publishManagedBuildReceipt, verifyManagedBuildReceipt, } from "./managed-build-receipt.js";
17
+ import { managedBuildConfiguration, persistJsonAtomically, publishManagedBuildReceipt, verifyManagedBuildReceipt, } from "./managed-build-receipt.js";
19
18
  import { managedLongTierTimeoutMs, managedMaximumCommandTimeoutMs, managedVerificationTierTimeoutMs, } from "./managed-verification-timeouts.js";
20
19
  import { resolveWindowsCommandFromPath, StreamingProviderProcessRunner } from "./provider-cli/provider-cli.process.js";
21
20
  import { monotonicNowMs } from "../shared/time/monotonic.js";
@@ -38,8 +37,6 @@ const managedCommandRetryAfterMs = 60_000;
38
37
  const managedCommandLaunchTimeoutMs = 60_000;
39
38
  const managedCommandProgressPersistIntervalMs = 5_000;
40
39
  const managedCommandReceiptPollIntervalMs = 1_000;
41
- const managedCommandReceiptReplaceAttempts = 40;
42
- const managedCommandReceiptReplaceRetryMs = 25;
43
40
  const terminalManagedCommandStatuses = new Set([
44
41
  "pass",
45
42
  "fail",
@@ -295,6 +292,9 @@ async function launchManagedCommand(record, worktreePath, forceAsync, verificati
295
292
  buildReceiptReuse,
296
293
  controller: new AbortController(),
297
294
  };
295
+ // A build aimed at the output a running supervised runtime executes from fails here, naming
296
+ // that runtime, instead of failing on its locked files after the build-slot and capacity waits.
297
+ await assertManagedBuildSparesSupervisedRuntimes(invocation);
298
298
  if (forceAsync || timeoutMs > maximumSynchronousWaitMs) {
299
299
  const started = managedCommandResult({
300
300
  ...invocation,
@@ -594,41 +594,48 @@ async function executeManagedCommand(invocation) {
594
594
  return managedCommandPublicResult(receipt);
595
595
  }
596
596
  }
597
+ /** A command's environment and redaction list; a setup that throws releases the database it started. */
597
598
  async function managedCommandProcessEnvironment(invocation) {
598
599
  assertHostDatabaseCapabilityBoundary();
599
- const databaseEnvironment = invocation.verificationProfile
600
- ? await managedVerificationDatabaseEnvironment()
601
- : {};
602
- const exactSecrets = [
603
- ...Object.values(databaseEnvironment).filter(value => value !== nativeTestPostgresFallbackDatabaseMode),
604
- // The attempt's brokered database login reaches managed commands; their output never shows it.
605
- ...attemptDatabaseCapabilitySecrets(process.env[attemptDatabaseCapabilityEnvironment]),
606
- ];
607
- const environment = inheritedEnvironment({
608
- FORGE_RUNTIME_MODE: "host",
609
- FORGE_RESOURCE_LEASE_ID: requiredAttemptEnvironment("FORGE_RESOURCE_LEASE_ID"),
610
- FORGE_DISPATCH_ATTEMPT_ID: requiredAttemptEnvironment("FORGE_DISPATCH_ATTEMPT_ID"),
611
- // This nested command owns a distinct supervisor identity. A command-local
612
- // fence avoids exposing the parent attempt's fencing capability to Codex's
613
- // MCP subprocess configuration while preserving exact-tree cleanup proof.
614
- FORGE_FENCING_TOKEN: randomUUID(),
615
- FORGE_LOG_DIR: invocation.logDirectory,
616
- FORGE_TEST_OUTPUT_DIR: requiredAttemptEnvironment("FORGE_TEST_OUTPUT_DIR"),
617
- FORGE_PROCESS_SUPERVISOR_ID: `managed-${invocation.commandId.replaceAll("-", "")}`,
618
- FORGE_PROCESS_SUPERVISOR_METADATA_PATH: invocation.metadataPath,
619
- ...(invocation.verificationProfile
620
- ? {
621
- FORGE_MANAGED_VERIFICATION_PROFILE: invocation.verificationProfile,
622
- // Managed verification executes mutable worktree scripts, SDK targets,
623
- // and test assemblies. It uses an attempt-owned container, or the
624
- // dedicated native test cluster while Docker is unavailable; it never
625
- // receives a capability for a server that holds real data.
626
- FORGE_MANAGED_VERIFICATION_DATABASE_MODE: "container_only",
627
- ...databaseEnvironment,
628
- }
629
- : {}),
600
+ const database = invocation.verificationProfile ? await managedVerificationDatabase() : noManagedVerificationDatabase;
601
+ return await setUpWithManagedVerificationDatabase(database, () => {
602
+ const exactSecrets = [
603
+ ...database.secrets,
604
+ // The attempt's brokered database login reaches managed commands; their output never shows it.
605
+ ...attemptDatabaseCapabilitySecrets(process.env[attemptDatabaseCapabilityEnvironment]),
606
+ ];
607
+ const environment = inheritedEnvironment({
608
+ FORGE_RUNTIME_MODE: "host",
609
+ FORGE_RESOURCE_LEASE_ID: requiredAttemptEnvironment("FORGE_RESOURCE_LEASE_ID"),
610
+ FORGE_DISPATCH_ATTEMPT_ID: requiredAttemptEnvironment("FORGE_DISPATCH_ATTEMPT_ID"),
611
+ // This nested command owns a distinct supervisor identity. A command-local
612
+ // fence avoids exposing the parent attempt's fencing capability to Codex's
613
+ // MCP subprocess configuration while preserving exact-tree cleanup proof.
614
+ FORGE_FENCING_TOKEN: randomUUID(),
615
+ FORGE_LOG_DIR: invocation.logDirectory,
616
+ FORGE_TEST_OUTPUT_DIR: requiredAttemptEnvironment("FORGE_TEST_OUTPUT_DIR"),
617
+ FORGE_PROCESS_SUPERVISOR_ID: `managed-${invocation.commandId.replaceAll("-", "")}`,
618
+ FORGE_PROCESS_SUPERVISOR_METADATA_PATH: invocation.metadataPath,
619
+ ...(invocation.verificationProfile
620
+ ? {
621
+ FORGE_MANAGED_VERIFICATION_PROFILE: invocation.verificationProfile,
622
+ // Managed verification executes mutable worktree scripts, SDK targets,
623
+ // and test assemblies. It uses an attempt-owned container, or the
624
+ // dedicated native test cluster while Docker is unavailable; it never
625
+ // receives a capability for a server that holds real data.
626
+ FORGE_MANAGED_VERIFICATION_DATABASE_MODE: "container_only",
627
+ ...database.environment,
628
+ }
629
+ : {}),
630
+ });
631
+ return { environment, exactSecrets, release: database.release };
630
632
  });
631
- return { environment, exactSecrets };
633
+ }
634
+ function clearManagedCommandTimers(...timers) {
635
+ // clearTimeout and clearInterval share one timer table.
636
+ for (const timer of timers)
637
+ if (timer)
638
+ clearTimeout(timer);
632
639
  }
633
640
  async function executeManagedCommandProcess(invocation) {
634
641
  let prepared;
@@ -830,11 +837,9 @@ async function executeManagedCommandProcess(invocation) {
830
837
  return managedCommandPublicResult(receipt);
831
838
  }
832
839
  finally {
833
- clearTimeout(launchTimer);
834
- if (timer)
835
- clearTimeout(timer);
836
- if (progressHeartbeat)
837
- clearInterval(progressHeartbeat);
840
+ clearManagedCommandTimers(launchTimer, timer, progressHeartbeat);
841
+ // An ephemeral verification cluster lives exactly as long as its command; one that would not stop is reaped later and named in the receipt.
842
+ await releaseManagedVerificationDatabase(prepared, async (message) => await annotateManagedCommandReceipt(invocation.receiptPath, { ephemeral_cluster_release_error: redactText(message, exactSecrets) }));
838
843
  }
839
844
  }
840
845
  async function readManagedCommand(input) {
@@ -938,27 +943,7 @@ function managedCommandReceiptPath(logDirectory, commandId) {
938
943
  return path.join(logDirectory, "managed-commands", `${commandId}.receipt.json`);
939
944
  }
940
945
  async function persistManagedCommandReceipt(receiptPath, receipt) {
941
- const temporaryPath = `${receiptPath}.${randomUUID()}.tmp`;
942
- await fs.writeFile(temporaryPath, `${JSON.stringify(receipt, null, 2)}\n`, { encoding: "utf8", mode: 0o600 });
943
- try {
944
- for (let attempt = 1;; attempt += 1) {
945
- try {
946
- await fs.rename(temporaryPath, receiptPath);
947
- break;
948
- }
949
- catch (error) {
950
- const code = error.code;
951
- if (attempt >= managedCommandReceiptReplaceAttempts
952
- || (code !== "EPERM" && code !== "EBUSY" && code !== "EACCES")) {
953
- throw error;
954
- }
955
- await delay(managedCommandReceiptReplaceRetryMs);
956
- }
957
- }
958
- }
959
- finally {
960
- await fs.rm(temporaryPath, { force: true }).catch(() => undefined);
961
- }
946
+ await persistJsonAtomically(receiptPath, receipt);
962
947
  }
963
948
  function managedCommandResult(values) {
964
949
  // Governed commands count elapsed time from admission: queue time is host_load_wait_ms.
@@ -1124,20 +1109,6 @@ function inheritedEnvironment(overrides) {
1124
1109
  }
1125
1110
  return { ...env, ...overrides };
1126
1111
  }
1127
- /**
1128
- * Runner-authored verification normally uses its attempt-owned Testcontainers
1129
- * database. Only when the Docker engine is unavailable does it switch to the
1130
- * operator-provisioned native test cluster, which holds no real data.
1131
- */
1132
- export async function managedVerificationDatabaseEnvironment(dockerAvailable = async () => (await new DockerEngineProbe().refresh(true)).available, readFallback = () => {
1133
- const configPath = process.env[nativeTestPostgresFallbackConfigEnvironment]?.trim();
1134
- return configPath ? readNativeTestPostgresFallback(configPath) : null;
1135
- }) {
1136
- const fallback = readFallback();
1137
- if (!fallback || await dockerAvailable())
1138
- return {};
1139
- return nativeTestPostgresFallbackEnvironment(fallback);
1140
- }
1141
1112
  export function isBuildProducingManagedCommand(command, args) {
1142
1113
  const executable = path.basename(command).toLowerCase();
1143
1114
  if (executable === "dotnet" || executable === "dotnet.exe") {
@@ -1149,10 +1120,7 @@ export function isBuildProducingManagedCommand(command, args) {
1149
1120
  if (["powershell", "powershell.exe", "pwsh", "pwsh.exe"].includes(executable)) {
1150
1121
  const fileIndex = args.findIndex(argument => argument.toLowerCase() === "-file");
1151
1122
  const script = fileIndex >= 0 ? path.basename(args[fileIndex + 1] ?? "").toLowerCase() : "";
1152
- if (script === "run-dotnet-test-tier-set.ps1" || script === "run-dotnet-test-suite.ps1") {
1153
- return !args.some(argument => argument.toLowerCase() === "-nobuild");
1154
- }
1155
- if (script === "run-dotnet-test-tier.ps1") {
1123
+ if (["run-dotnet-test-tier.ps1", "run-dotnet-test-tier-set.ps1", "run-dotnet-test-suite.ps1"].includes(script)) {
1156
1124
  return !args.some(argument => argument.toLowerCase() === "-nobuild");
1157
1125
  }
1158
1126
  }
@@ -1,3 +1,19 @@
1
+ /** The managed command a build check needs: what it runs, where, and for which attempt. */
2
+ export interface ManagedBuildCandidate {
3
+ readonly command: string;
4
+ readonly args: readonly string[];
5
+ readonly cwd: string;
6
+ readonly worktreePath: string;
7
+ readonly logDirectory: string;
8
+ readonly buildProducing: boolean;
9
+ }
10
+ /**
11
+ * Refuses, before launch, a managed command that would build into the output one of the
12
+ * attempt's running supervised runtimes executes from. The build slot below orders builds
13
+ * against each other; a running runtime cannot wait its turn, so the collision fails fast
14
+ * with an error naming the runtime instead of a build stuck on its locked files.
15
+ */
16
+ export declare function assertManagedBuildSparesSupervisedRuntimes(candidate: ManagedBuildCandidate): Promise<void>;
1
17
  export declare class ManagedBuildCoordinator {
2
18
  private readonly stateRoot;
3
19
  constructor(stateRoot?: string);
@@ -3,10 +3,20 @@ import fs from "node:fs/promises";
3
3
  import path from "node:path";
4
4
  import { defaultWorktreeCoordinatorStateRoot } from "../worktree/worktree-paths.js";
5
5
  import { monotonicNowMs } from "../shared/time/monotonic.js";
6
+ import { assertBuildSparesSupervisedRuntimes } from "../runtime/supervised-runtime-build-guard.js";
6
7
  const heartbeatIntervalMs = 30_000;
7
8
  const staleAfterMs = 2 * 60_000;
8
9
  const acquisitionTimeoutMs = 2 * 60 * 60_000;
9
10
  const pollIntervalMs = 100;
11
+ /**
12
+ * Refuses, before launch, a managed command that would build into the output one of the
13
+ * attempt's running supervised runtimes executes from. The build slot below orders builds
14
+ * against each other; a running runtime cannot wait its turn, so the collision fails fast
15
+ * with an error naming the runtime instead of a build stuck on its locked files.
16
+ */
17
+ export async function assertManagedBuildSparesSupervisedRuntimes(candidate) {
18
+ await assertBuildSparesSupervisedRuntimes({ ...candidate, buildsWorktreeSolution: candidate.buildProducing });
19
+ }
10
20
  export class ManagedBuildCoordinator {
11
21
  stateRoot;
12
22
  constructor(stateRoot = defaultWorktreeCoordinatorStateRoot()) {
@@ -19,3 +19,8 @@ export declare function verifyManagedBuildReceipt(options: {
19
19
  readonly requiredCoverage: string;
20
20
  }): Promise<ManagedBuildReceiptEvidence>;
21
21
  export declare function managedBuildConfiguration(command: string, args: readonly string[]): string;
22
+ /**
23
+ * Writes a JSON receipt by replacing the whole file. Agents and Forge poll receipts, and on
24
+ * Windows a poll that has one open refuses the replace: that delays a write, never fails it.
25
+ */
26
+ export declare function persistJsonAtomically(receiptPath: string, value: unknown): Promise<void>;
@@ -3,6 +3,7 @@ import { spawn } from "node:child_process";
3
3
  import fs from "node:fs/promises";
4
4
  import path from "node:path";
5
5
  import { defaultWorktreeCoordinatorStateRoot } from "../worktree/worktree-paths.js";
6
+ import { replaceFile } from "../shared/fs/replace-file.js";
6
7
  const schemaVersion = 1;
7
8
  const maximumRetainedReceipts = 8;
8
9
  const maximumOutputManifestEntries = 20_000;
@@ -262,7 +263,7 @@ async function persistImmutableReceipt(receiptPath, receipt) {
262
263
  const temporaryPath = `${receiptPath}.${randomUUID()}.tmp`;
263
264
  await fs.writeFile(temporaryPath, `${JSON.stringify(receipt, null, 2)}\n`, { encoding: "utf8", mode: 0o600 });
264
265
  try {
265
- await fs.rename(temporaryPath, receiptPath).catch(async (error) => {
266
+ await replaceFile(temporaryPath, receiptPath).catch(async (error) => {
266
267
  if (error.code !== "EEXIST")
267
268
  throw error;
268
269
  });
@@ -271,11 +272,15 @@ async function persistImmutableReceipt(receiptPath, receipt) {
271
272
  await fs.rm(temporaryPath, { force: true }).catch(() => undefined);
272
273
  }
273
274
  }
274
- async function persistJsonAtomically(receiptPath, value) {
275
+ /**
276
+ * Writes a JSON receipt by replacing the whole file. Agents and Forge poll receipts, and on
277
+ * Windows a poll that has one open refuses the replace: that delays a write, never fails it.
278
+ */
279
+ export async function persistJsonAtomically(receiptPath, value) {
275
280
  const temporaryPath = `${receiptPath}.${randomUUID()}.tmp`;
276
281
  await fs.writeFile(temporaryPath, `${JSON.stringify(value, null, 2)}\n`, { encoding: "utf8", mode: 0o600 });
277
282
  try {
278
- await fs.rename(temporaryPath, receiptPath);
283
+ await replaceFile(temporaryPath, receiptPath);
279
284
  }
280
285
  finally {
281
286
  await fs.rm(temporaryPath, { force: true }).catch(() => undefined);
@@ -2,7 +2,7 @@ import crypto from "node:crypto";
2
2
  import fs from "node:fs/promises";
3
3
  import path from "node:path";
4
4
  import { redactSecrets } from "../shared/redaction/redaction.js";
5
- import { ensureNoSymbolicLinkPathSegments, isPathUnderRoot, sha256File } from "./qa-sidecar-validation.js";
5
+ import { assertQaSidecarJsonShape, ensureNoSymbolicLinkPathSegments, isPathUnderRoot, sha256File } from "./qa-sidecar-validation.js";
6
6
  import { assertClaimedChangedFilesMatchPublishableDiff } from "./publishable-worktree-changes.js";
7
7
  import { coerceJsonStringArguments } from "./mcp-argument-coercion.js";
8
8
  import { toolInputSchema } from "./phase-completion.schemas.js";
@@ -690,6 +690,7 @@ async function validateQaSidecarReferences(worktreePath, workItemId, sidecars, o
690
690
  if (actualHash !== normalizeSha256ContentHash(contentHash)) {
691
691
  throw new Error(`sidecars[${index}].content_hash does not match the referenced file.`);
692
692
  }
693
+ await assertQaSidecarJsonShape(fullPath, sidecarPath, `sidecars[${index}]`);
693
694
  const canonicalPath = path.relative(worktreePath, fullPath).split(path.sep).join("/");
694
695
  const duplicateKey = canonicalPath.toLowerCase();
695
696
  const existing = validatedByPath.get(duplicateKey);
@@ -4,6 +4,7 @@ export { isDebugCompletionPhase } from "./phase-completion.validation.js";
4
4
  export { readCompletionArtifact, writeCompletionArtifact } from "./phase-completion.artifacts.js";
5
5
  export * from "./phase-completion.prompts.js";
6
6
  export * from "./phase-completion.runtime.js";
7
+ export * from "./phase-completion.mcp-args.js";
7
8
  export type DevelopCompletionPhase = "implementation" | "self_review" | "validation";
8
9
  export type DebugCompletionPhase = "debug_repro" | "debug_root_cause" | "debug_fix" | "debug_regression";
9
10
  export type ArchitectCompletionPhase = "architect";
@@ -31,6 +32,12 @@ export interface CompletionToolRuntimeOptions {
31
32
  readonly runtimeEnvironment?: Readonly<Record<string, string>>;
32
33
  /** Host load governor variables; only the MCP server receives them. */
33
34
  readonly hostLoadEnvironment?: Readonly<Record<string, string>>;
35
+ /**
36
+ * Serve only the managed-attempt tools (managed commands, verification, waits), never a
37
+ * completion tool. A pre-publication repair turn uses this: its phase's completion artifacts are
38
+ * already recorded and validated, and the repair prompt forbids rewriting them.
39
+ */
40
+ readonly managedToolsOnly?: boolean;
34
41
  }
35
42
  export interface CompletionToolServerConfig {
36
43
  readonly worktreePath: string;
@@ -46,6 +53,7 @@ export interface CompletionToolServerConfig {
46
53
  readonly architectCycle?: boolean;
47
54
  readonly draftCycle?: boolean;
48
55
  readonly decomposeCycle?: boolean;
56
+ readonly managedToolsOnly?: boolean;
49
57
  }
50
58
  export interface CompletionToolCallResult {
51
59
  readonly content: readonly {
@@ -4,6 +4,7 @@ export { isDebugCompletionPhase } from "./phase-completion.validation.js";
4
4
  export { readCompletionArtifact, writeCompletionArtifact } from "./phase-completion.artifacts.js";
5
5
  export * from "./phase-completion.prompts.js";
6
6
  export * from "./phase-completion.runtime.js";
7
+ export * from "./phase-completion.mcp-args.js";
7
8
  export const toolServerName = "forge";
8
9
  export const completionRedactionSecretsEnv = "FORGE_COMPLETION_REDACTION_SECRETS";
9
10
  export const completionPhaseOrder = ["implementation", "self_review", "validation"];
@@ -0,0 +1,9 @@
1
+ import { type CompletionToolServerConfig } from "./phase-completion.js";
2
+ export declare function buildCompletionToolServerArgs(config: CompletionToolServerConfig): readonly string[];
3
+ export declare function parseCompletionMcpArgs(argv: readonly string[]): {
4
+ readonly ok: true;
5
+ readonly config: CompletionToolServerConfig;
6
+ } | {
7
+ readonly ok: false;
8
+ readonly error: string;
9
+ };