@loucompanion/forge-bridge 0.1.4-dev.ccffca94938b → 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.
- package/README.md +87 -1
- package/dist/bridge/bridge-chat-provider-command.d.ts +4 -1
- package/dist/bridge/bridge-chat-provider-command.js +14 -19
- package/dist/bridge/bridge-state-file.d.ts +161 -0
- package/dist/bridge/bridge-state-file.js +376 -0
- package/dist/bridge/bridge-state-io.d.ts +11 -0
- package/dist/bridge/bridge-state-io.js +50 -0
- package/dist/bridge/bridge-state-lock.d.ts +11 -0
- package/dist/bridge/bridge-state-lock.js +102 -0
- package/dist/bridge/bridge-state-unpublished.d.ts +17 -0
- package/dist/bridge/bridge-state-unpublished.js +111 -0
- package/dist/bridge/bridge.service.d.ts +16 -12
- package/dist/bridge/bridge.service.js +131 -243
- package/dist/bridge/bridge.types.d.ts +5 -0
- package/dist/bridge/in-flight-registry.d.ts +62 -0
- package/dist/bridge/in-flight-registry.js +207 -0
- package/dist/bridge/readiness-result-outbox.d.ts +5 -1
- package/dist/bridge/readiness-result-outbox.js +20 -0
- package/dist/bridge/sandbox-resource-accounting.d.ts +16 -0
- package/dist/bridge/sandbox-resource-accounting.js +150 -0
- package/dist/cleanup/cleanup-wip.d.ts +12 -0
- package/dist/cleanup/cleanup-wip.js +66 -0
- package/dist/cleanup/cleanup.service.d.ts +11 -1
- package/dist/cleanup/cleanup.service.js +80 -62
- package/dist/cleanup/cleanup.types.d.ts +2 -0
- package/dist/cleanup/host-runtime-ledger.d.ts +2 -0
- package/dist/cleanup/host-runtime-ledger.js +30 -9
- package/dist/cli/cli.help.js +56 -12
- package/dist/cli/cli.service.d.ts +3 -10
- package/dist/cli/cli.service.js +10 -171
- package/dist/cli/idle-status.d.ts +84 -0
- package/dist/cli/idle-status.js +181 -0
- package/dist/cli/local-config.d.ts +2 -0
- package/dist/cli/local-config.js +7 -1
- package/dist/cli/provider-cli-detection.d.ts +10 -0
- package/dist/cli/provider-cli-detection.js +160 -0
- package/dist/runtime/aspnet-runtime-prebuild.d.ts +5 -0
- package/dist/runtime/aspnet-runtime-prebuild.js +46 -1
- package/dist/runtime/attempt-database-broker.d.ts +1 -1
- package/dist/runtime/docker-engine-probe.d.ts +5 -0
- package/dist/runtime/docker-engine-probe.js +7 -0
- package/dist/runtime/ephemeral-test-postgres-grant.d.ts +37 -0
- package/dist/runtime/ephemeral-test-postgres-grant.js +85 -0
- package/dist/runtime/ephemeral-test-postgres.d.ts +57 -0
- package/dist/runtime/ephemeral-test-postgres.js +303 -0
- package/dist/runtime/host-load-governor.d.ts +2 -0
- package/dist/runtime/host-load-ledger-lock.js +6 -4
- package/dist/runtime/host-load-runtime-settings.js +4 -2
- package/dist/runtime/host-runtime-contract.d.ts +12 -0
- package/dist/runtime/host-runtime-contract.js +29 -1
- package/dist/runtime/host-runtime-lease.js +10 -50
- package/dist/runtime/managed-command-teardown.js +5 -16
- package/dist/runtime/native-test-postgres-fallback.d.ts +51 -7
- package/dist/runtime/native-test-postgres-fallback.js +60 -8
- package/dist/runtime/runner-settings.d.ts +4 -0
- package/dist/runtime/runner-settings.js +22 -0
- package/dist/sandbox/host-capacity-broker.d.ts +3 -1
- package/dist/sandbox/host-capacity-broker.js +4 -2
- package/dist/sandbox/managed-branch.d.ts +13 -0
- package/dist/sandbox/managed-branch.js +36 -0
- package/dist/sandbox/provider-auth/codex.js +11 -11
- package/dist/sandbox/runtime.js +2 -6
- package/dist/session/managed-attempt-tools.d.ts +0 -7
- package/dist/session/managed-attempt-tools.js +45 -77
- package/dist/session/managed-build-receipt.d.ts +5 -0
- package/dist/session/managed-build-receipt.js +8 -3
- package/dist/session/phase-completion.artifacts.js +2 -1
- package/dist/session/phase-completion.d.ts +8 -0
- package/dist/session/phase-completion.js +1 -0
- package/dist/session/phase-completion.mcp-args.d.ts +9 -0
- package/dist/session/phase-completion.mcp-args.js +156 -0
- package/dist/session/phase-completion.runtime.d.ts +0 -8
- package/dist/session/phase-completion.runtime.js +43 -197
- package/dist/session/pre-publication-native-postgres.d.ts +30 -0
- package/dist/session/pre-publication-native-postgres.js +111 -0
- package/dist/session/pre-publication-process.js +10 -10
- package/dist/session/pre-publication-step-execution.d.ts +2 -1
- package/dist/session/pre-publication-step-execution.js +6 -5
- package/dist/session/pre-publication-validation.d.ts +7 -3
- package/dist/session/pre-publication-validation.js +32 -30
- package/dist/session/provider-cli/claude-background-work.d.ts +3 -2
- package/dist/session/provider-cli/claude-background-work.js +4 -3
- package/dist/session/provider-cli/host-build-lock.d.ts +18 -0
- package/dist/session/provider-cli/host-build-lock.js +30 -0
- package/dist/session/provider-cli/pre-publication-repair.d.ts +16 -0
- package/dist/session/provider-cli/pre-publication-repair.js +33 -0
- package/dist/session/provider-cli/provider-cli.child-environment.js +4 -2
- package/dist/session/provider-cli/provider-cli.process.d.ts +2 -14
- package/dist/session/provider-cli/provider-cli.process.js +4 -94
- package/dist/session/provider-cli/provider-cli.prompts.d.ts +3 -0
- package/dist/session/provider-cli/provider-cli.prompts.js +27 -27
- package/dist/session/provider-cli/provider-cli.runtime.d.ts +8 -0
- package/dist/session/provider-cli/provider-cli.runtime.js +23 -2
- package/dist/session/provider-cli/provider-cli.service.d.ts +4 -1
- package/dist/session/provider-cli/provider-cli.service.js +27 -43
- package/dist/session/provider-cli/provider-cli.windows-launch.d.ts +23 -0
- package/dist/session/provider-cli/provider-cli.windows-launch.js +131 -0
- package/dist/session/provider-cli/provider-user-config-isolation.d.ts +69 -0
- package/dist/session/provider-cli/provider-user-config-isolation.js +164 -0
- package/dist/session/qa-sidecar-validation.d.ts +6 -0
- package/dist/session/qa-sidecar-validation.js +28 -0
- package/dist/session/sandbox-host-capacity-gate.d.ts +22 -1
- package/dist/session/sandbox-host-capacity-gate.js +34 -15
- package/dist/session/session-redaction.js +31 -181
- package/dist/session/session.service.d.ts +2 -0
- package/dist/session/session.service.js +62 -56
- package/dist/session/session.types.js +1 -1
- package/dist/session/sidecar-json-shape.d.ts +31 -0
- package/dist/session/sidecar-json-shape.js +217 -0
- package/dist/shared/fs/file-identity.d.ts +10 -0
- package/dist/shared/fs/file-identity.js +15 -0
- package/dist/shared/fs/replace-file.d.ts +7 -0
- package/dist/shared/fs/replace-file.js +33 -0
- package/dist/shared/process/host-process-recovery.d.ts +14 -3
- package/dist/shared/process/host-process-recovery.js +23 -3
- package/dist/shared/process/host-process-supervisor.d.ts +13 -1
- package/dist/shared/process/host-process-supervisor.js +66 -14
- package/dist/shared/provider-capabilities.js +9 -1
- package/dist/version.d.ts +1 -1
- package/dist/version.js +1 -1
- package/dist/worktree/wip-git.d.ts +33 -0
- package/dist/worktree/wip-git.js +122 -0
- package/dist/worktree/wip-refs.d.ts +62 -0
- package/dist/worktree/wip-refs.js +119 -0
- package/dist/worktree/wip-restore.d.ts +38 -0
- package/dist/worktree/wip-restore.js +190 -0
- package/dist/worktree/wip-snapshot.d.ts +50 -0
- package/dist/worktree/wip-snapshot.js +268 -0
- package/dist/worktree/worktree-inputs.d.ts +8 -0
- package/dist/worktree/worktree-inputs.js +134 -0
- package/dist/worktree/worktree-origin-sync.d.ts +34 -0
- package/dist/worktree/worktree-origin-sync.js +127 -0
- package/dist/worktree/worktree-wip-events.d.ts +18 -0
- package/dist/worktree/worktree-wip-events.js +98 -0
- package/dist/worktree/worktree-wip.d.ts +49 -0
- package/dist/worktree/worktree-wip.js +182 -0
- package/dist/worktree/worktree.base.d.ts +7 -1
- package/dist/worktree/worktree.service.d.ts +27 -5
- package/dist/worktree/worktree.service.js +106 -181
- package/dist/worktree/worktree.types.d.ts +31 -0
- package/package.json +1 -1
|
@@ -1,12 +1,37 @@
|
|
|
1
1
|
import fs from "node:fs";
|
|
2
2
|
import path from "node:path";
|
|
3
3
|
import { resolveLocalConfigPath } from "../cli/local-config.js";
|
|
4
|
+
import { DockerEngineProbe } from "./docker-engine-probe.js";
|
|
5
|
+
import { ephemeralTestPostgresClusterEnvironment } from "./ephemeral-test-postgres.js";
|
|
4
6
|
import { hostRuntimeLegacyTestPostgresEnvironment, hostRuntimeTestPostgresAdminEnvironment, } from "./host-runtime-contract.js";
|
|
5
7
|
export const nativeTestPostgresFallbackConfigEnvironment = "FORGE_NATIVE_TEST_POSTGRES_CONFIG";
|
|
6
8
|
export const nativeTestPostgresFallbackFileName = "native-test-postgres.json";
|
|
7
9
|
export const nativeTestPostgresFallbackDatabaseMode = "native_fallback";
|
|
10
|
+
/**
|
|
11
|
+
* The cluster serves the shared test server while Docker is up, so tests that need a
|
|
12
|
+
* pinned engine container still start one. Owner policy (2026-11-16): native PostgreSQL
|
|
13
|
+
* first, which keeps test databases out of the Docker VM and saves RAM.
|
|
14
|
+
*/
|
|
15
|
+
export const nativeTestPostgresPreferredDatabaseMode = "native_preferred";
|
|
16
|
+
const nativeTestPostgresUses = ["preferred", "docker_unavailable", "ephemeral"];
|
|
8
17
|
const defaultPostgresPort = 5432;
|
|
9
18
|
const loopbackHosts = new Set(["127.0.0.1", "localhost", "::1", "[::1]"]);
|
|
19
|
+
/**
|
|
20
|
+
* The provisioned cluster's grant for a check that can use it, or null to use Docker. A
|
|
21
|
+
* preferred cluster is granted whether or not Docker is up; the mode says which, because
|
|
22
|
+
* only the fallback mode excludes Docker for pinned-engine tests. An `ephemeral` host
|
|
23
|
+
* normally gets its own cluster instead (ephemeral-test-postgres-grant.ts); if that cannot
|
|
24
|
+
* start, the provisioned cluster serves only while Docker is down, as for `docker_unavailable`.
|
|
25
|
+
*/
|
|
26
|
+
export function nativeTestPostgresGrant(fallback, dockerAvailable) {
|
|
27
|
+
if (!fallback || (dockerAvailable && fallback.use !== "preferred"))
|
|
28
|
+
return null;
|
|
29
|
+
return {
|
|
30
|
+
connectionString: fallback.connectionString,
|
|
31
|
+
endpoint: fallback.endpoint,
|
|
32
|
+
mode: dockerAvailable ? nativeTestPostgresPreferredDatabaseMode : nativeTestPostgresFallbackDatabaseMode,
|
|
33
|
+
};
|
|
34
|
+
}
|
|
10
35
|
export class NativeTestPostgresFallbackError extends Error {
|
|
11
36
|
code = "native_test_postgres_fallback_invalid";
|
|
12
37
|
constructor(detail) {
|
|
@@ -46,9 +71,17 @@ export function readNativeTestPostgresFallback(configPath = resolveNativeTestPos
|
|
|
46
71
|
if (document.schemaVersion !== 1 || typeof document.connectionString !== "string") {
|
|
47
72
|
throw new NativeTestPostgresFallbackError(`${configPath} must contain schemaVersion 1 and a connectionString.`);
|
|
48
73
|
}
|
|
49
|
-
|
|
74
|
+
if (document.use !== undefined && !nativeTestPostgresUses.includes(document.use)) {
|
|
75
|
+
throw new NativeTestPostgresFallbackError(`${configPath} 'use' must be 'preferred', 'docker_unavailable' or 'ephemeral'.`);
|
|
76
|
+
}
|
|
77
|
+
if (document.postgresBin !== undefined
|
|
78
|
+
&& (typeof document.postgresBin !== "string" || !path.isAbsolute(document.postgresBin))) {
|
|
79
|
+
throw new NativeTestPostgresFallbackError(`${configPath} 'postgresBin' must be an absolute path.`);
|
|
80
|
+
}
|
|
81
|
+
const fallback = parseNativeTestPostgresFallback(document.connectionString, document.use ?? "preferred");
|
|
82
|
+
return typeof document.postgresBin === "string" ? { ...fallback, postgresBin: document.postgresBin } : fallback;
|
|
50
83
|
}
|
|
51
|
-
export function parseNativeTestPostgresFallback(connectionString) {
|
|
84
|
+
export function parseNativeTestPostgresFallback(connectionString, use = "preferred") {
|
|
52
85
|
const fields = new Map();
|
|
53
86
|
for (const segment of connectionString.split(";")) {
|
|
54
87
|
const separator = segment.indexOf("=");
|
|
@@ -79,13 +112,32 @@ export function parseNativeTestPostgresFallback(connectionString) {
|
|
|
79
112
|
if (!(fields.get("username") ?? fields.get("userid") ?? fields.get("user"))) {
|
|
80
113
|
throw new NativeTestPostgresFallbackError("the fallback must name a dedicated test role.");
|
|
81
114
|
}
|
|
82
|
-
return { connectionString: connectionString.trim(), endpoint: `${host}:${port}
|
|
115
|
+
return { connectionString: connectionString.trim(), endpoint: `${host}:${port}`, use };
|
|
83
116
|
}
|
|
84
|
-
/** Environment for one runner-authored .NET test process using the
|
|
85
|
-
export function nativeTestPostgresFallbackEnvironment(
|
|
117
|
+
/** Environment for one runner-authored .NET test process using the cluster. */
|
|
118
|
+
export function nativeTestPostgresFallbackEnvironment(grant) {
|
|
86
119
|
return {
|
|
87
|
-
[hostRuntimeTestPostgresAdminEnvironment]:
|
|
88
|
-
[hostRuntimeLegacyTestPostgresEnvironment]:
|
|
89
|
-
FORGE_MANAGED_VERIFICATION_DATABASE_MODE:
|
|
120
|
+
[hostRuntimeTestPostgresAdminEnvironment]: grant.connectionString,
|
|
121
|
+
[hostRuntimeLegacyTestPostgresEnvironment]: grant.connectionString,
|
|
122
|
+
FORGE_MANAGED_VERIFICATION_DATABASE_MODE: grant.mode,
|
|
123
|
+
// The fixtures accept a superuser login only on the cluster that reports this id.
|
|
124
|
+
...(grant.ephemeralClusterId ? { [ephemeralTestPostgresClusterEnvironment]: grant.ephemeralClusterId } : {}),
|
|
90
125
|
};
|
|
91
126
|
}
|
|
127
|
+
/**
|
|
128
|
+
* Runner-authored verification uses the operator-provisioned native test cluster,
|
|
129
|
+
* which holds no real data, whenever its file prefers it (the default); Docker then
|
|
130
|
+
* only starts pinned-engine containers. A `docker_unavailable` cluster is used only
|
|
131
|
+
* when the Docker engine is unavailable; otherwise the attempt-owned Testcontainers
|
|
132
|
+
* database serves.
|
|
133
|
+
*/
|
|
134
|
+
export async function managedVerificationDatabaseEnvironment(dockerAvailable = async () => (await new DockerEngineProbe().probeWithoutRecovery()).available, readFallback = () => {
|
|
135
|
+
const configPath = process.env[nativeTestPostgresFallbackConfigEnvironment]?.trim();
|
|
136
|
+
return configPath ? readNativeTestPostgresFallback(configPath) : null;
|
|
137
|
+
}) {
|
|
138
|
+
const fallback = readFallback();
|
|
139
|
+
if (!fallback)
|
|
140
|
+
return {};
|
|
141
|
+
const grant = nativeTestPostgresGrant(fallback, await dockerAvailable());
|
|
142
|
+
return grant ? nativeTestPostgresFallbackEnvironment(grant) : {};
|
|
143
|
+
}
|
|
@@ -98,3 +98,7 @@ export declare function parseRunnerSettingsDocument(raw: unknown): RunnerSetting
|
|
|
98
98
|
export declare function runnerSettingsInForce(report: RunnerSettingsReport, previous: RunnerSettingsReport, failures: readonly RunnerSettingRejection[]): RunnerSettingsReport;
|
|
99
99
|
/** True when two reports say the same thing (version included), so an unchanged recompute is not re-sent. */
|
|
100
100
|
export declare function sameRunnerSettingsReport(left: RunnerSettingsReport, right: RunnerSettingsReport): boolean;
|
|
101
|
+
/** The offer refusal message while the runner yields to foreground work. */
|
|
102
|
+
export declare function runnerYieldingMessage(report: RunnerSettingsReport): string;
|
|
103
|
+
/** One line describing the effective settings, for the bridge log. */
|
|
104
|
+
export declare function describeRunnerSettings(report: RunnerSettingsReport): string;
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { formatBytes } from "../shared/format/format-bytes.js";
|
|
1
2
|
import { parseHostLoadGovernorMode } from "./host-load-governor-config.js";
|
|
2
3
|
// Decision 0014 §3 "Precedence" and §6 "Bridge hub": the server pushes a runner
|
|
3
4
|
// settings document (`ApplySettings`) and is the source of truth. Host env vars
|
|
@@ -212,3 +213,24 @@ function numberEnv(environment, envVar, minimum, maximum) {
|
|
|
212
213
|
const parsed = Number(raw);
|
|
213
214
|
return Number.isFinite(parsed) ? { envVar, value: Math.min(maximum, Math.max(minimum, parsed)) } : null;
|
|
214
215
|
}
|
|
216
|
+
/** The offer refusal message while the runner yields to foreground work. */
|
|
217
|
+
export function runnerYieldingMessage(report) {
|
|
218
|
+
const where = report.sources.yieldToForeground === "host_local" ? "on this host (forge-bridge yield on)" : "in Forge";
|
|
219
|
+
return `runner_yielding: this runner is yielding to foreground work (turned on ${where}); it takes no new attempts until yield is off. Running attempts continue.`;
|
|
220
|
+
}
|
|
221
|
+
/** One line describing the effective settings, for the bridge log. */
|
|
222
|
+
export function describeRunnerSettings(report) {
|
|
223
|
+
const { values } = report;
|
|
224
|
+
const parts = [
|
|
225
|
+
`max attempts ${values.maxConcurrentAttempts}`,
|
|
226
|
+
`CPU budget ${values.cpuBudgetPercent}%`,
|
|
227
|
+
`yield budget ${values.yieldCpuBudgetPercent}%`,
|
|
228
|
+
`memory reserve ${formatBytes(values.memoryReserveBytes)}`,
|
|
229
|
+
`heavy steps ${values.maxHeavySteps ?? "budget only"}`,
|
|
230
|
+
`yield ${values.yieldToForeground ? "on" : "off"}`,
|
|
231
|
+
];
|
|
232
|
+
const capped = report.bounds
|
|
233
|
+
.filter(bound => report.sources[bound.key] === "host_env")
|
|
234
|
+
.map(bound => `${bound.envVar}=${bound.value}`);
|
|
235
|
+
return `${parts.join(", ")}${capped.length > 0 ? `; host bounds in force: ${[...new Set(capped)].join(", ")}` : ""}`;
|
|
236
|
+
}
|
|
@@ -108,6 +108,8 @@ export declare function sandboxHostCapacityDeliveryExecArgs(container: string):
|
|
|
108
108
|
* newer state. Replies are world-readable but owned by the writer (root, via
|
|
109
109
|
* `docker exec --user 0`). The directory must already be owned by that same uid
|
|
110
110
|
* and writable by no one else, i.e. the root-owned reply mount; it is never
|
|
111
|
-
* created here, where it could turn out to be the sandbox's own directory.
|
|
111
|
+
* created here, where it could turn out to be the sandbox's own directory. A
|
|
112
|
+
* runtime without POSIX user ids (Windows) cannot prove that, so the script
|
|
113
|
+
* writes nothing there (exit 3), as for any directory it cannot trust.
|
|
112
114
|
*/
|
|
113
115
|
export declare const sandboxHostCapacityResponseScript: string;
|
|
@@ -327,8 +327,10 @@ export function sandboxHostCapacityDeliveryExecArgs(container) {
|
|
|
327
327
|
* newer state. Replies are world-readable but owned by the writer (root, via
|
|
328
328
|
* `docker exec --user 0`). The directory must already be owned by that same uid
|
|
329
329
|
* and writable by no one else, i.e. the root-owned reply mount; it is never
|
|
330
|
-
* created here, where it could turn out to be the sandbox's own directory.
|
|
330
|
+
* created here, where it could turn out to be the sandbox's own directory. A
|
|
331
|
+
* runtime without POSIX user ids (Windows) cannot prove that, so the script
|
|
332
|
+
* writes nothing there (exit 3), as for any directory it cannot trust.
|
|
331
333
|
*/
|
|
332
334
|
export const sandboxHostCapacityResponseScript = "let s='';process.stdin.setEncoding('utf8');process.stdin.on('data',c=>s+=c);process.stdin.on('end',()=>{const f=require('fs'),r=JSON.parse(s),d='"
|
|
333
335
|
+ sandboxHostCapacityResponseRoot
|
|
334
|
-
+ "';if(!/^[0-9a-f-]{36}$/.test(r.requestId)||!Number.isSafeInteger(r.sequence))process.exit(2);const st=f.lstatSync(d);if(!st.isDirectory()||st.uid!==process.getuid()||(st.mode&0o022))process.exit(3);const p=d+'/'+r.requestId+'.json',t=p+'.'+process.pid+'.tmp';let o=-1;try{o=JSON.parse(f.readFileSync(p,'utf8')).sequence}catch{}if(Number.isSafeInteger(o)&&o>=r.sequence)return;f.writeFileSync(t,s,{mode:0o644,flag:'wx'});f.renameSync(t,p)})";
|
|
336
|
+
+ "';if(!/^[0-9a-f-]{36}$/.test(r.requestId)||!Number.isSafeInteger(r.sequence))process.exit(2);if(typeof process.getuid!=='function')process.exit(3);const st=f.lstatSync(d);if(!st.isDirectory()||st.uid!==process.getuid()||(st.mode&0o022))process.exit(3);const p=d+'/'+r.requestId+'.json',t=p+'.'+process.pid+'.tmp';let o=-1;try{o=JSON.parse(f.readFileSync(p,'utf8')).sequence}catch{}if(Number.isSafeInteger(o)&&o>=r.sequence)return;f.writeFileSync(t,s,{mode:0o644,flag:'wx'});f.renameSync(t,p)})";
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import { type SandboxProcessRequest, type SandboxProcessResult } from "./process.js";
|
|
2
|
+
export type ManagedBranchProcess = (request: SandboxProcessRequest) => Promise<SandboxProcessResult>;
|
|
3
|
+
export interface CheckedOutBranchUpdate {
|
|
4
|
+
readonly repoPath: string;
|
|
5
|
+
readonly worktreePath: string;
|
|
6
|
+
readonly branchRef: string;
|
|
7
|
+
/** The commit the sandbox started from; the branch and worktree must still be exactly there. */
|
|
8
|
+
readonly expected: string;
|
|
9
|
+
readonly imported: string;
|
|
10
|
+
/** Runs git; tests inject one. */
|
|
11
|
+
readonly run?: ManagedBranchProcess;
|
|
12
|
+
}
|
|
13
|
+
export declare function advanceCheckedOutBranch(update: CheckedOutBranchUpdate): Promise<void>;
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import { ForgeFailureError } from "../session/session.types.js";
|
|
2
|
+
import { requireSandboxProcess } from "./process.js";
|
|
3
|
+
export async function advanceCheckedOutBranch(update) {
|
|
4
|
+
const run = update.run ?? requireSandboxProcess;
|
|
5
|
+
const inWorktree = (args, timeoutMs) => run({ command: "git", args: ["-C", update.worktreePath, ...args], timeoutMs, maxOutputBytes: 4 * 1024 * 1024 });
|
|
6
|
+
const head = (await inWorktree(["rev-parse", "HEAD"], 30_000)).stdout.trim();
|
|
7
|
+
const status = (await inWorktree(["status", "--porcelain=v1", "--untracked-files=no"], 30_000)).stdout;
|
|
8
|
+
if (head !== update.expected || status.trim()) {
|
|
9
|
+
throw conflict("managed worktree changed after sandbox input was captured.");
|
|
10
|
+
}
|
|
11
|
+
await inWorktree(["read-tree", "-m", "-u", update.expected, update.imported], 2 * 60_000);
|
|
12
|
+
try {
|
|
13
|
+
await run({
|
|
14
|
+
command: "git",
|
|
15
|
+
args: ["-C", update.repoPath, "update-ref", update.branchRef, update.imported, update.expected],
|
|
16
|
+
timeoutMs: 30_000,
|
|
17
|
+
maxOutputBytes: 4 * 1024 * 1024,
|
|
18
|
+
});
|
|
19
|
+
}
|
|
20
|
+
catch (error) {
|
|
21
|
+
try {
|
|
22
|
+
await inWorktree(["read-tree", "-m", "-u", update.imported, update.expected], 2 * 60_000);
|
|
23
|
+
}
|
|
24
|
+
catch (rollbackError) {
|
|
25
|
+
throw conflict(`managed branch changed while the sandbox result was applied, and its worktree could not be put back to ${update.expected} `
|
|
26
|
+
+ `(${messageOf(rollbackError)}); it holds the imported files.`, { cause: rollbackError });
|
|
27
|
+
}
|
|
28
|
+
throw conflict(`managed branch changed while the sandbox result was applied (${messageOf(error)}); its worktree was put back.`, { cause: error });
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
function conflict(detail, options) {
|
|
32
|
+
return new ForgeFailureError("sandbox_output_conflict", `sandbox_output_conflict: ${detail}`, "sandbox", options);
|
|
33
|
+
}
|
|
34
|
+
function messageOf(error) {
|
|
35
|
+
return error instanceof Error ? error.message : String(error);
|
|
36
|
+
}
|
|
@@ -2,6 +2,7 @@ import fs from "node:fs";
|
|
|
2
2
|
import fsp from "node:fs/promises";
|
|
3
3
|
import os from "node:os";
|
|
4
4
|
import path from "node:path";
|
|
5
|
+
import { fileIdentityChanged } from "../../shared/fs/file-identity.js";
|
|
5
6
|
const maxCredentialFileBytes = 1024 * 1024;
|
|
6
7
|
// Capability and heartbeat paths call doctor() synchronously; keep validation
|
|
7
8
|
// fresh enough for auth changes without rereading auth.json for every offer.
|
|
@@ -87,7 +88,7 @@ function codexAuthDoctor(environment) {
|
|
|
87
88
|
async function readValidatedCodexAuthFile(authPath) {
|
|
88
89
|
let pathStat;
|
|
89
90
|
try {
|
|
90
|
-
pathStat = await fsp.lstat(authPath);
|
|
91
|
+
pathStat = await fsp.lstat(authPath, { bigint: true });
|
|
91
92
|
}
|
|
92
93
|
catch {
|
|
93
94
|
throw new Error("Codex Local CLI auth is not available on the bridge host.");
|
|
@@ -101,11 +102,11 @@ async function readValidatedCodexAuthFile(authPath) {
|
|
|
101
102
|
throw codexAuthOpenError(error);
|
|
102
103
|
}
|
|
103
104
|
try {
|
|
104
|
-
const openedStat = await handle.stat();
|
|
105
|
+
const openedStat = await handle.stat({ bigint: true });
|
|
105
106
|
validateSameCodexAuthFile(pathStat, openedStat);
|
|
106
107
|
validateCodexAuthStat(openedStat);
|
|
107
108
|
const content = await handle.readFile();
|
|
108
|
-
const afterStat = await handle.stat();
|
|
109
|
+
const afterStat = await handle.stat({ bigint: true });
|
|
109
110
|
validateSameCodexAuthFile(openedStat, afterStat);
|
|
110
111
|
validateCodexAuthStat(afterStat);
|
|
111
112
|
validateCodexAuthReadSize(content, openedStat, afterStat);
|
|
@@ -119,7 +120,7 @@ async function readValidatedCodexAuthFile(authPath) {
|
|
|
119
120
|
function readValidatedCodexAuthFileSync(authPath) {
|
|
120
121
|
let pathStat;
|
|
121
122
|
try {
|
|
122
|
-
pathStat = fs.lstatSync(authPath);
|
|
123
|
+
pathStat = fs.lstatSync(authPath, { bigint: true });
|
|
123
124
|
}
|
|
124
125
|
catch {
|
|
125
126
|
throw new Error("Codex Local CLI auth is not available on the bridge host.");
|
|
@@ -133,11 +134,11 @@ function readValidatedCodexAuthFileSync(authPath) {
|
|
|
133
134
|
throw codexAuthOpenError(error);
|
|
134
135
|
}
|
|
135
136
|
try {
|
|
136
|
-
const openedStat = fs.fstatSync(fd);
|
|
137
|
+
const openedStat = fs.fstatSync(fd, { bigint: true });
|
|
137
138
|
validateSameCodexAuthFile(pathStat, openedStat);
|
|
138
139
|
validateCodexAuthStat(openedStat);
|
|
139
140
|
const content = fs.readFileSync(fd);
|
|
140
|
-
const afterStat = fs.fstatSync(fd);
|
|
141
|
+
const afterStat = fs.fstatSync(fd, { bigint: true });
|
|
141
142
|
validateSameCodexAuthFile(openedStat, afterStat);
|
|
142
143
|
validateCodexAuthStat(afterStat);
|
|
143
144
|
validateCodexAuthReadSize(content, openedStat, afterStat);
|
|
@@ -158,21 +159,20 @@ function validateCodexAuthStat(stat) {
|
|
|
158
159
|
if (!stat.isFile()) {
|
|
159
160
|
throw new Error("Codex Local CLI auth.json is not a regular file.");
|
|
160
161
|
}
|
|
161
|
-
if (stat.size <=
|
|
162
|
+
if (stat.size <= 0n) {
|
|
162
163
|
throw new Error("Codex Local CLI auth.json is empty.");
|
|
163
164
|
}
|
|
164
|
-
if (stat.size > maxCredentialFileBytes) {
|
|
165
|
+
if (stat.size > BigInt(maxCredentialFileBytes)) {
|
|
165
166
|
throw new Error("Codex Local CLI auth.json exceeds the 1 MiB sandbox auth limit.");
|
|
166
167
|
}
|
|
167
168
|
}
|
|
168
169
|
function validateSameCodexAuthFile(before, after) {
|
|
169
|
-
if (before
|
|
170
|
-
&& (before.dev !== after.dev || before.ino !== after.ino)) {
|
|
170
|
+
if (fileIdentityChanged(before, after)) {
|
|
171
171
|
throw new Error("Codex Local CLI auth.json changed while being copied.");
|
|
172
172
|
}
|
|
173
173
|
}
|
|
174
174
|
function validateCodexAuthReadSize(content, openedStat, afterStat) {
|
|
175
|
-
if (openedStat.size !== afterStat.size || content.length !== afterStat.size) {
|
|
175
|
+
if (openedStat.size !== afterStat.size || BigInt(content.length) !== afterStat.size) {
|
|
176
176
|
throw new Error("Codex Local CLI auth.json changed while being copied.");
|
|
177
177
|
}
|
|
178
178
|
}
|
package/dist/sandbox/runtime.js
CHANGED
|
@@ -5,6 +5,7 @@ import { fileURLToPath } from "node:url";
|
|
|
5
5
|
import { createFailureEnvelope, ForgeFailureError, failureFactsForCode, failurePolicyForCode, failureResult, parseRunOnceResultPacket, } from "../session/session.types.js";
|
|
6
6
|
import { dockerfileUpstreamImages, validateDockerfilePolicy, validateSandboxContract } from "./contract.js";
|
|
7
7
|
import { requireSandboxProcess, runSandboxProcess } from "./process.js";
|
|
8
|
+
import { advanceCheckedOutBranch } from "./managed-branch.js";
|
|
8
9
|
import { createLeaseUpdate } from "./lease-watchdog.js";
|
|
9
10
|
import { evaluateSandboxImagePolicy, hasSandboxImagePolicyRecord, sandboxImagePolicyConfigurationDigest, verifySandboxImageSignature } from "./image-policy.js";
|
|
10
11
|
import { SandboxEventBudget } from "./event-budget.js";
|
|
@@ -1276,12 +1277,7 @@ class HostGit {
|
|
|
1276
1277
|
await this.git(["update-ref", branchRef, imported, managedBranchUpdateExpectedValue(current, expected, imported)], 30_000);
|
|
1277
1278
|
return;
|
|
1278
1279
|
}
|
|
1279
|
-
|
|
1280
|
-
const status = (await requireSandboxProcess({ command: "git", args: ["-C", checkedOut.path, "status", "--porcelain=v1", "--untracked-files=no"], timeoutMs: 30_000, maxOutputBytes: 4 * 1024 * 1024 })).stdout;
|
|
1281
|
-
if (head !== expected || status.trim())
|
|
1282
|
-
throw trustedSandboxFailure("sandbox_output_conflict", "managed worktree changed after sandbox input was captured.");
|
|
1283
|
-
await this.git(["update-ref", branchRef, imported, expected], 30_000);
|
|
1284
|
-
await requireSandboxProcess({ command: "git", args: ["-C", checkedOut.path, "reset", "--hard"], timeoutMs: 2 * 60_000, maxOutputBytes: 4 * 1024 * 1024 });
|
|
1280
|
+
await advanceCheckedOutBranch({ repoPath: this.repoPath, worktreePath: checkedOut.path, branchRef, expected, imported });
|
|
1285
1281
|
}
|
|
1286
1282
|
async resolveFirst(refs) {
|
|
1287
1283
|
for (const ref of refs) {
|
|
@@ -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,10 +3,9 @@ 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 {
|
|
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
11
|
import { ManagedBuildCoordinator } from "./managed-build-coordinator.js";
|
|
@@ -15,7 +14,7 @@ import { HostCapacityLedgerUnavailableError } from "../runtime/host-load-ledger-
|
|
|
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",
|
|
@@ -594,41 +591,48 @@ async function executeManagedCommand(invocation) {
|
|
|
594
591
|
return managedCommandPublicResult(receipt);
|
|
595
592
|
}
|
|
596
593
|
}
|
|
594
|
+
/** A command's environment and redaction list; a setup that throws releases the database it started. */
|
|
597
595
|
async function managedCommandProcessEnvironment(invocation) {
|
|
598
596
|
assertHostDatabaseCapabilityBoundary();
|
|
599
|
-
const
|
|
600
|
-
|
|
601
|
-
|
|
602
|
-
|
|
603
|
-
|
|
604
|
-
|
|
605
|
-
|
|
606
|
-
|
|
607
|
-
|
|
608
|
-
|
|
609
|
-
|
|
610
|
-
|
|
611
|
-
|
|
612
|
-
|
|
613
|
-
|
|
614
|
-
|
|
615
|
-
|
|
616
|
-
|
|
617
|
-
|
|
618
|
-
|
|
619
|
-
|
|
620
|
-
|
|
621
|
-
|
|
622
|
-
|
|
623
|
-
|
|
624
|
-
|
|
625
|
-
|
|
626
|
-
|
|
627
|
-
|
|
628
|
-
|
|
629
|
-
|
|
597
|
+
const database = invocation.verificationProfile ? await managedVerificationDatabase() : noManagedVerificationDatabase;
|
|
598
|
+
return await setUpWithManagedVerificationDatabase(database, () => {
|
|
599
|
+
const exactSecrets = [
|
|
600
|
+
...database.secrets,
|
|
601
|
+
// The attempt's brokered database login reaches managed commands; their output never shows it.
|
|
602
|
+
...attemptDatabaseCapabilitySecrets(process.env[attemptDatabaseCapabilityEnvironment]),
|
|
603
|
+
];
|
|
604
|
+
const environment = inheritedEnvironment({
|
|
605
|
+
FORGE_RUNTIME_MODE: "host",
|
|
606
|
+
FORGE_RESOURCE_LEASE_ID: requiredAttemptEnvironment("FORGE_RESOURCE_LEASE_ID"),
|
|
607
|
+
FORGE_DISPATCH_ATTEMPT_ID: requiredAttemptEnvironment("FORGE_DISPATCH_ATTEMPT_ID"),
|
|
608
|
+
// This nested command owns a distinct supervisor identity. A command-local
|
|
609
|
+
// fence avoids exposing the parent attempt's fencing capability to Codex's
|
|
610
|
+
// MCP subprocess configuration while preserving exact-tree cleanup proof.
|
|
611
|
+
FORGE_FENCING_TOKEN: randomUUID(),
|
|
612
|
+
FORGE_LOG_DIR: invocation.logDirectory,
|
|
613
|
+
FORGE_TEST_OUTPUT_DIR: requiredAttemptEnvironment("FORGE_TEST_OUTPUT_DIR"),
|
|
614
|
+
FORGE_PROCESS_SUPERVISOR_ID: `managed-${invocation.commandId.replaceAll("-", "")}`,
|
|
615
|
+
FORGE_PROCESS_SUPERVISOR_METADATA_PATH: invocation.metadataPath,
|
|
616
|
+
...(invocation.verificationProfile
|
|
617
|
+
? {
|
|
618
|
+
FORGE_MANAGED_VERIFICATION_PROFILE: invocation.verificationProfile,
|
|
619
|
+
// Managed verification executes mutable worktree scripts, SDK targets,
|
|
620
|
+
// and test assemblies. It uses an attempt-owned container, or the
|
|
621
|
+
// dedicated native test cluster while Docker is unavailable; it never
|
|
622
|
+
// receives a capability for a server that holds real data.
|
|
623
|
+
FORGE_MANAGED_VERIFICATION_DATABASE_MODE: "container_only",
|
|
624
|
+
...database.environment,
|
|
625
|
+
}
|
|
626
|
+
: {}),
|
|
627
|
+
});
|
|
628
|
+
return { environment, exactSecrets, release: database.release };
|
|
630
629
|
});
|
|
631
|
-
|
|
630
|
+
}
|
|
631
|
+
function clearManagedCommandTimers(...timers) {
|
|
632
|
+
// clearTimeout and clearInterval share one timer table.
|
|
633
|
+
for (const timer of timers)
|
|
634
|
+
if (timer)
|
|
635
|
+
clearTimeout(timer);
|
|
632
636
|
}
|
|
633
637
|
async function executeManagedCommandProcess(invocation) {
|
|
634
638
|
let prepared;
|
|
@@ -830,11 +834,9 @@ async function executeManagedCommandProcess(invocation) {
|
|
|
830
834
|
return managedCommandPublicResult(receipt);
|
|
831
835
|
}
|
|
832
836
|
finally {
|
|
833
|
-
|
|
834
|
-
|
|
835
|
-
|
|
836
|
-
if (progressHeartbeat)
|
|
837
|
-
clearInterval(progressHeartbeat);
|
|
837
|
+
clearManagedCommandTimers(launchTimer, timer, progressHeartbeat);
|
|
838
|
+
// An ephemeral verification cluster lives exactly as long as its command; one that would not stop is reaped later and named in the receipt.
|
|
839
|
+
await releaseManagedVerificationDatabase(prepared, async (message) => await annotateManagedCommandReceipt(invocation.receiptPath, { ephemeral_cluster_release_error: redactText(message, exactSecrets) }));
|
|
838
840
|
}
|
|
839
841
|
}
|
|
840
842
|
async function readManagedCommand(input) {
|
|
@@ -938,27 +940,7 @@ function managedCommandReceiptPath(logDirectory, commandId) {
|
|
|
938
940
|
return path.join(logDirectory, "managed-commands", `${commandId}.receipt.json`);
|
|
939
941
|
}
|
|
940
942
|
async function persistManagedCommandReceipt(receiptPath, receipt) {
|
|
941
|
-
|
|
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
|
-
}
|
|
943
|
+
await persistJsonAtomically(receiptPath, receipt);
|
|
962
944
|
}
|
|
963
945
|
function managedCommandResult(values) {
|
|
964
946
|
// Governed commands count elapsed time from admission: queue time is host_load_wait_ms.
|
|
@@ -1124,20 +1106,6 @@ function inheritedEnvironment(overrides) {
|
|
|
1124
1106
|
}
|
|
1125
1107
|
return { ...env, ...overrides };
|
|
1126
1108
|
}
|
|
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
1109
|
export function isBuildProducingManagedCommand(command, args) {
|
|
1142
1110
|
const executable = path.basename(command).toLowerCase();
|
|
1143
1111
|
if (executable === "dotnet" || executable === "dotnet.exe") {
|
|
@@ -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
|
|
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
|
-
|
|
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
|
|
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
|
+
};
|