@loucompanion/forge-bridge 0.1.4-dev.81e48ecc185d → 0.1.4-dev.866b33be3065

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 (61) hide show
  1. package/README.md +3 -0
  2. package/dist/bridge/bridge-chat-provider-command.d.ts +1 -1
  3. package/dist/bridge/bridge-chat-provider-command.js +16 -4
  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/runner-host-capabilities.d.ts +3 -0
  7. package/dist/bridge/runner-host-capabilities.js +13 -0
  8. package/dist/runtime/attempt-database-broker.d.ts +1 -1
  9. package/dist/runtime/docker-engine-probe.d.ts +5 -0
  10. package/dist/runtime/docker-engine-probe.js +7 -0
  11. package/dist/runtime/ephemeral-test-postgres-grant.d.ts +37 -0
  12. package/dist/runtime/ephemeral-test-postgres-grant.js +85 -0
  13. package/dist/runtime/ephemeral-test-postgres.d.ts +57 -0
  14. package/dist/runtime/ephemeral-test-postgres.js +303 -0
  15. package/dist/runtime/host-facts.d.ts +2 -1
  16. package/dist/runtime/host-load-admission.d.ts +4 -1
  17. package/dist/runtime/host-load-sampler.d.ts +34 -4
  18. package/dist/runtime/host-load-sampler.js +73 -7
  19. package/dist/runtime/host-load-windows-cpu.d.ts +34 -0
  20. package/dist/runtime/host-load-windows-cpu.js +85 -0
  21. package/dist/runtime/native-test-postgres-fallback.d.ts +51 -7
  22. package/dist/runtime/native-test-postgres-fallback.js +60 -8
  23. package/dist/session/architect-waits.d.ts +2 -0
  24. package/dist/session/architect-waits.js +138 -0
  25. package/dist/session/managed-attempt-tools.d.ts +0 -7
  26. package/dist/session/managed-attempt-tools.js +44 -54
  27. package/dist/session/phase-completion.artifacts.js +2 -1
  28. package/dist/session/phase-completion.runtime.js +1 -1
  29. package/dist/session/phase-completion.schemas.js +3 -11
  30. package/dist/session/phase-completion.validation.js +3 -1
  31. package/dist/session/pre-publication-native-postgres.d.ts +30 -0
  32. package/dist/session/pre-publication-native-postgres.js +111 -0
  33. package/dist/session/pre-publication-step-execution.d.ts +2 -1
  34. package/dist/session/pre-publication-step-execution.js +6 -5
  35. package/dist/session/pre-publication-validation.d.ts +7 -3
  36. package/dist/session/pre-publication-validation.js +32 -30
  37. package/dist/session/provider-cli/provider-cli.child-environment.d.ts +7 -0
  38. package/dist/session/provider-cli/provider-cli.child-environment.js +73 -0
  39. package/dist/session/provider-cli/provider-cli.codex-models-cache.d.ts +3 -0
  40. package/dist/session/provider-cli/provider-cli.codex-models-cache.js +37 -0
  41. package/dist/session/provider-cli/provider-cli.process.d.ts +8 -30
  42. package/dist/session/provider-cli/provider-cli.process.js +25 -376
  43. package/dist/session/provider-cli/provider-cli.windows-environment.d.ts +10 -0
  44. package/dist/session/provider-cli/provider-cli.windows-environment.js +151 -0
  45. package/dist/session/provider-cli/provider-cli.windows-launch.d.ts +23 -0
  46. package/dist/session/provider-cli/provider-cli.windows-launch.js +131 -0
  47. package/dist/session/provider-cli/provider-output-pipes.d.ts +30 -0
  48. package/dist/session/provider-cli/provider-output-pipes.js +67 -0
  49. package/dist/session/qa-sidecar-validation.d.ts +6 -0
  50. package/dist/session/qa-sidecar-validation.js +28 -0
  51. package/dist/session/session-redaction.js +31 -181
  52. package/dist/session/session.types.js +1 -1
  53. package/dist/session/sidecar-json-shape.d.ts +31 -0
  54. package/dist/session/sidecar-json-shape.js +217 -0
  55. package/dist/shared/process/windows-app-execution-alias.d.ts +19 -0
  56. package/dist/shared/process/windows-app-execution-alias.js +45 -0
  57. package/dist/shared/process/windows-launch.d.ts +18 -0
  58. package/dist/shared/process/windows-launch.js +68 -0
  59. package/dist/version.d.ts +1 -1
  60. package/dist/version.js +1 -1
  61. package/package.json +1 -1
@@ -0,0 +1,85 @@
1
+ /**
2
+ * Host CPU use at which the estimate starts to report pressure. Waits for a CPU
3
+ * are rare below it on a many-core host. 0.6 puts the default backpressure
4
+ * threshold (50%) at 80% host CPU use, the default CPU budget.
5
+ */
6
+ export const windowsCpuPressureKnee = 0.6;
7
+ /** Busy is user + nice + sys + irq; idle is not busy. Null when any CPU lacks its times. */
8
+ export function cpuTimeTotals(cpus) {
9
+ if (cpus.length === 0)
10
+ return null;
11
+ let busyMs = 0;
12
+ let idleMs = 0;
13
+ for (const cpu of cpus) {
14
+ const times = cpu.times;
15
+ if (!times)
16
+ return null;
17
+ const values = [times.user, times.nice, times.sys, times.irq, times.idle];
18
+ if (!values.every(value => Number.isFinite(value) && value >= 0))
19
+ return null;
20
+ busyMs += times.user + times.nice + times.sys + times.irq;
21
+ idleMs += times.idle;
22
+ }
23
+ return { busyMs, totalMs: busyMs + idleMs, cpuCount: cpus.length };
24
+ }
25
+ /** Busy share of all logical CPUs (0-1) between two readings; null across a CPU count change or a counter reset. */
26
+ export function cpuUtilisation(previous, current) {
27
+ if (!previous || !current || previous.cpuCount !== current.cpuCount)
28
+ return null;
29
+ const totalDelta = current.totalMs - previous.totalMs;
30
+ const busyDelta = current.busyMs - previous.busyMs;
31
+ if (totalDelta <= 0 || busyDelta < 0)
32
+ return null;
33
+ return Math.min(1, busyDelta / totalDelta);
34
+ }
35
+ /** Estimated share of wall time (percent) some runnable thread waited for a CPU, for one window. */
36
+ export function estimatedCpuStallPercent(utilisation) {
37
+ const share = (utilisation - windowsCpuPressureKnee) / (1 - windowsCpuPressureKnee);
38
+ return Math.min(1, Math.max(0, share)) * 100;
39
+ }
40
+ const averageWindowsSeconds = { avg10: 10, avg60: 60, avg300: 300 };
41
+ /**
42
+ * Keeps 10/60/300-second exponentially decaying averages of the estimate, the
43
+ * way the kernel keeps PSI averages, so the governor's threshold and pressure
44
+ * streak read it exactly like PSI. The first window seeds every average, so a
45
+ * host already busy when the bridge starts reports pressure at once.
46
+ */
47
+ export class WindowsCpuPressureEstimator {
48
+ averages = null;
49
+ /** Folds in one window of host CPU use lasting `elapsedMs`. */
50
+ update(utilisation, elapsedMs) {
51
+ const stall = estimatedCpuStallPercent(utilisation);
52
+ const previous = this.averages;
53
+ this.averages = previous === null
54
+ ? { avg10: stall, avg60: stall, avg300: stall }
55
+ : {
56
+ avg10: decay(previous.avg10, stall, elapsedMs, averageWindowsSeconds.avg10),
57
+ avg60: decay(previous.avg60, stall, elapsedMs, averageWindowsSeconds.avg60),
58
+ avg300: decay(previous.avg300, stall, elapsedMs, averageWindowsSeconds.avg300),
59
+ };
60
+ return this.current();
61
+ }
62
+ current() {
63
+ if (!this.averages)
64
+ return null;
65
+ return {
66
+ some: {
67
+ avg10: roundPercent(this.averages.avg10),
68
+ avg60: roundPercent(this.averages.avg60),
69
+ avg300: roundPercent(this.averages.avg300),
70
+ },
71
+ // `full` (every runnable thread stalled) is not meaningful for CPU and is not estimated.
72
+ full: null,
73
+ };
74
+ }
75
+ reset() {
76
+ this.averages = null;
77
+ }
78
+ }
79
+ function decay(previous, sample, elapsedMs, windowSeconds) {
80
+ const weight = Math.exp(-Math.max(0, elapsedMs) / (windowSeconds * 1_000));
81
+ return sample + (previous - sample) * weight;
82
+ }
83
+ function roundPercent(value) {
84
+ return Math.round(value * 100) / 100;
85
+ }
@@ -2,15 +2,51 @@ export declare const nativeTestPostgresFallbackConfigEnvironment = "FORGE_NATIVE
2
2
  export declare const nativeTestPostgresFallbackFileName = "native-test-postgres.json";
3
3
  export declare const nativeTestPostgresFallbackDatabaseMode = "native_fallback";
4
4
  /**
5
- * A dedicated, operator-provisioned PostgreSQL cluster that runner-authored .NET
6
- * test tiers may use only while the Docker engine is unavailable. The cluster
7
- * must hold nothing but disposable test databases, so its capability carries no
8
- * more authority than the attempt-private container it replaces.
5
+ * The cluster serves the shared test server while Docker is up, so tests that need a
6
+ * pinned engine container still start one. Owner policy (2026-11-16): native PostgreSQL
7
+ * first, which keeps test databases out of the Docker VM and saves RAM.
8
+ */
9
+ export declare const nativeTestPostgresPreferredDatabaseMode = "native_preferred";
10
+ export type NativeTestPostgresDatabaseMode = typeof nativeTestPostgresFallbackDatabaseMode | typeof nativeTestPostgresPreferredDatabaseMode;
11
+ /**
12
+ * What runner-authored .NET test tiers get: `preferred` (the default) the provisioned
13
+ * cluster whenever it is configured; `docker_unavailable` that cluster only after a
14
+ * Docker probe fails; `ephemeral` a throwaway cluster of their own for each check, whose
15
+ * bootstrap superuser they hold (owner policy 2026-11-17). The provisioned cluster still
16
+ * hosts the attempt database broker in every mode.
17
+ */
18
+ export type NativeTestPostgresUse = "preferred" | "docker_unavailable" | "ephemeral";
19
+ /**
20
+ * A dedicated, operator-provisioned PostgreSQL cluster for runner-authored .NET
21
+ * test tiers, preferred over Docker unless its file says `docker_unavailable`.
22
+ * The cluster must hold nothing but disposable test databases, so its capability
23
+ * carries no more authority than the attempt-private container it replaces.
9
24
  */
10
25
  export interface NativeTestPostgresFallback {
11
26
  readonly connectionString: string;
12
27
  readonly endpoint: string;
28
+ readonly use: NativeTestPostgresUse;
29
+ /** The PostgreSQL bin directory an ephemeral cluster runs from; defaults to the one beside psql. */
30
+ readonly postgresBin?: string;
13
31
  }
32
+ /** The cluster as handed to one test process, with the mode its fixtures run in. */
33
+ export interface NativeTestPostgresGrant {
34
+ readonly connectionString: string;
35
+ readonly endpoint: string;
36
+ readonly mode: NativeTestPostgresDatabaseMode;
37
+ /** Set when the grant is a throwaway cluster of its own; the server reports it as `forge.ephemeral_cluster`. */
38
+ readonly ephemeralClusterId?: string;
39
+ /** Stops and deletes an ephemeral cluster once its check has finished. */
40
+ readonly release?: () => Promise<void>;
41
+ }
42
+ /**
43
+ * The provisioned cluster's grant for a check that can use it, or null to use Docker. A
44
+ * preferred cluster is granted whether or not Docker is up; the mode says which, because
45
+ * only the fallback mode excludes Docker for pinned-engine tests. An `ephemeral` host
46
+ * normally gets its own cluster instead (ephemeral-test-postgres-grant.ts); if that cannot
47
+ * start, the provisioned cluster serves only while Docker is down, as for `docker_unavailable`.
48
+ */
49
+ export declare function nativeTestPostgresGrant(fallback: NativeTestPostgresFallback | null, dockerAvailable: boolean): NativeTestPostgresGrant | null;
14
50
  export declare class NativeTestPostgresFallbackError extends Error {
15
51
  readonly code = "native_test_postgres_fallback_invalid";
16
52
  constructor(detail: string);
@@ -20,6 +56,14 @@ export declare function resolveNativeTestPostgresFallbackPath(): string;
20
56
  export declare function configuredNativeTestPostgresFallbackPath(): string | null;
21
57
  /** Returns null when no fallback is configured; throws when one is configured unsafely. */
22
58
  export declare function readNativeTestPostgresFallback(configPath?: string): NativeTestPostgresFallback | null;
23
- export declare function parseNativeTestPostgresFallback(connectionString: string): NativeTestPostgresFallback;
24
- /** Environment for one runner-authored .NET test process using the fallback. */
25
- export declare function nativeTestPostgresFallbackEnvironment(fallback: NativeTestPostgresFallback): Readonly<Record<string, string>>;
59
+ export declare function parseNativeTestPostgresFallback(connectionString: string, use?: NativeTestPostgresUse): NativeTestPostgresFallback;
60
+ /** Environment for one runner-authored .NET test process using the cluster. */
61
+ export declare function nativeTestPostgresFallbackEnvironment(grant: Pick<NativeTestPostgresGrant, "connectionString" | "mode" | "ephemeralClusterId">): Readonly<Record<string, string>>;
62
+ /**
63
+ * Runner-authored verification uses the operator-provisioned native test cluster,
64
+ * which holds no real data, whenever its file prefers it (the default); Docker then
65
+ * only starts pinned-engine containers. A `docker_unavailable` cluster is used only
66
+ * when the Docker engine is unavailable; otherwise the attempt-owned Testcontainers
67
+ * database serves.
68
+ */
69
+ export declare function managedVerificationDatabaseEnvironment(dockerAvailable?: () => Promise<boolean>, readFallback?: () => NativeTestPostgresFallback | null): Promise<Readonly<Record<string, string>>>;
@@ -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
- return parseNativeTestPostgresFallback(document.connectionString);
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 fallback. */
85
- export function nativeTestPostgresFallbackEnvironment(fallback) {
117
+ /** Environment for one runner-authored .NET test process using the cluster. */
118
+ export function nativeTestPostgresFallbackEnvironment(grant) {
86
119
  return {
87
- [hostRuntimeTestPostgresAdminEnvironment]: fallback.connectionString,
88
- [hostRuntimeLegacyTestPostgresEnvironment]: fallback.connectionString,
89
- FORGE_MANAGED_VERIFICATION_DATABASE_MODE: nativeTestPostgresFallbackDatabaseMode,
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
+ }
@@ -0,0 +1,2 @@
1
+ export declare function architectNonPassProperties(): Record<string, unknown>;
2
+ export declare function validateArchitectWaits(payload: Record<string, unknown>, status: string): void;
@@ -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,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 { 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
11
  import { ManagedBuildCoordinator } from "./managed-build-coordinator.js";
@@ -447,7 +446,7 @@ export function buildManagedVerificationCommand(profile, outputDirectory, shardC
447
446
  export function preferredPowerShellExecutable(platform = process.platform, pathValue = process.env.PATH ?? "") {
448
447
  if (platform !== "win32")
449
448
  return "pwsh";
450
- return resolveWindowsCommandFromPath("pwsh.exe", pathValue) ?? "powershell.exe";
449
+ return resolveWindowsCommandFromPath("pwsh.exe", pathValue, undefined, { skipAppExecutionAliases: true }) ?? "powershell.exe";
451
450
  }
452
451
  export function validatePlaywrightProjectName(project, availableProjects) {
453
452
  if (!availableProjects.includes(project)) {
@@ -594,41 +593,48 @@ async function executeManagedCommand(invocation) {
594
593
  return managedCommandPublicResult(receipt);
595
594
  }
596
595
  }
596
+ /** A command's environment and redaction list; a setup that throws releases the database it started. */
597
597
  async function managedCommandProcessEnvironment(invocation) {
598
598
  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
- : {}),
599
+ const database = invocation.verificationProfile ? await managedVerificationDatabase() : noManagedVerificationDatabase;
600
+ return await setUpWithManagedVerificationDatabase(database, () => {
601
+ const exactSecrets = [
602
+ ...database.secrets,
603
+ // The attempt's brokered database login reaches managed commands; their output never shows it.
604
+ ...attemptDatabaseCapabilitySecrets(process.env[attemptDatabaseCapabilityEnvironment]),
605
+ ];
606
+ const environment = inheritedEnvironment({
607
+ FORGE_RUNTIME_MODE: "host",
608
+ FORGE_RESOURCE_LEASE_ID: requiredAttemptEnvironment("FORGE_RESOURCE_LEASE_ID"),
609
+ FORGE_DISPATCH_ATTEMPT_ID: requiredAttemptEnvironment("FORGE_DISPATCH_ATTEMPT_ID"),
610
+ // This nested command owns a distinct supervisor identity. A command-local
611
+ // fence avoids exposing the parent attempt's fencing capability to Codex's
612
+ // MCP subprocess configuration while preserving exact-tree cleanup proof.
613
+ FORGE_FENCING_TOKEN: randomUUID(),
614
+ FORGE_LOG_DIR: invocation.logDirectory,
615
+ FORGE_TEST_OUTPUT_DIR: requiredAttemptEnvironment("FORGE_TEST_OUTPUT_DIR"),
616
+ FORGE_PROCESS_SUPERVISOR_ID: `managed-${invocation.commandId.replaceAll("-", "")}`,
617
+ FORGE_PROCESS_SUPERVISOR_METADATA_PATH: invocation.metadataPath,
618
+ ...(invocation.verificationProfile
619
+ ? {
620
+ FORGE_MANAGED_VERIFICATION_PROFILE: invocation.verificationProfile,
621
+ // Managed verification executes mutable worktree scripts, SDK targets,
622
+ // and test assemblies. It uses an attempt-owned container, or the
623
+ // dedicated native test cluster while Docker is unavailable; it never
624
+ // receives a capability for a server that holds real data.
625
+ FORGE_MANAGED_VERIFICATION_DATABASE_MODE: "container_only",
626
+ ...database.environment,
627
+ }
628
+ : {}),
629
+ });
630
+ return { environment, exactSecrets, release: database.release };
630
631
  });
631
- return { environment, exactSecrets };
632
+ }
633
+ function clearManagedCommandTimers(...timers) {
634
+ // clearTimeout and clearInterval share one timer table.
635
+ for (const timer of timers)
636
+ if (timer)
637
+ clearTimeout(timer);
632
638
  }
633
639
  async function executeManagedCommandProcess(invocation) {
634
640
  let prepared;
@@ -830,11 +836,9 @@ async function executeManagedCommandProcess(invocation) {
830
836
  return managedCommandPublicResult(receipt);
831
837
  }
832
838
  finally {
833
- clearTimeout(launchTimer);
834
- if (timer)
835
- clearTimeout(timer);
836
- if (progressHeartbeat)
837
- clearInterval(progressHeartbeat);
839
+ clearManagedCommandTimers(launchTimer, timer, progressHeartbeat);
840
+ // An ephemeral verification cluster lives exactly as long as its command; one that would not stop is reaped later and named in the receipt.
841
+ await releaseManagedVerificationDatabase(prepared, async (message) => await annotateManagedCommandReceipt(invocation.receiptPath, { ephemeral_cluster_release_error: redactText(message, exactSecrets) }));
838
842
  }
839
843
  }
840
844
  async function readManagedCommand(input) {
@@ -1124,20 +1128,6 @@ function inheritedEnvironment(overrides) {
1124
1128
  }
1125
1129
  return { ...env, ...overrides };
1126
1130
  }
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
1131
  export function isBuildProducingManagedCommand(command, args) {
1142
1132
  const executable = path.basename(command).toLowerCase();
1143
1133
  if (executable === "dotnet" || executable === "dotnet.exe") {
@@ -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);
@@ -491,7 +491,7 @@ export function completionToolRuntimeEnvironment(runtimeEnvironment, nativeTestP
491
491
  env[name] = value.trim();
492
492
  }
493
493
  // Managed verification reads the operator's native test cluster only through
494
- // this explicit path, and only while Docker is unavailable.
494
+ // this explicit path; the file's `use` decides whether Docker comes first.
495
495
  if (runtimeEnvironment && nativeTestPostgresFallbackPath) {
496
496
  env[nativeTestPostgresFallbackConfigEnvironment] = nativeTestPostgresFallbackPath;
497
497
  }
@@ -1,5 +1,6 @@
1
1
  import { decomposeGateFileNames, decomposeStatuses, draftStatuses, isDebugCompletionPhase, phaseFiles, qaBlockerReasons, qaGateFileNames } from "./phase-completion.js";
2
2
  import { browserCheckSchema, qaSidecarsSchema, qaEvidenceWrapperSchema, qaGateEvidenceWrapperSchema, findingEvidenceSchema, objectToolSchema, evidenceObjectSchema, qaScopeSchema, commandEvidenceSchema, resolvedFindingSchema, acceptanceCriteriaSchema, reviewSectionSchema, reviewSectionProperties } from "./phase-completion.schema-parts.js";
3
+ import { architectNonPassProperties } from "./architect-waits.js";
3
4
  export function toolDescription(phase, qaGate = null, decomposeGate = null, draftGate = null) {
4
5
  if (qaGate) {
5
6
  return qaGate === "qa_verdict"
@@ -499,17 +500,8 @@ export function toolInputSchema(phase, qaGate = null, decomposeGate = null, draf
499
500
  report_markdown: { type: "string", description: "Human-readable Architect report. Use report as an alias only when the client cannot send report_markdown." },
500
501
  report: { type: "string", description: "Alias for report_markdown." },
501
502
  blockers: baseProperties.blockers,
502
- revision_questions: {
503
- type: "array",
504
- description: "Required for needs_revision when blockers are not used.",
505
- items: { type: "string" }
506
- },
507
- revision_reasons: {
508
- type: "array",
509
- description: "Concrete reasons that prevent pass status.",
510
- items: { type: "string" }
511
- }
512
- }, ["status", "summary"], "For status pass, include implementation_plan and qa_plan at the top level of the MCP tool arguments, as JSON objects rather than quoted strings. implementation_plan.phases must be a top-level array inside implementation_plan, not nested under another object. For needs_revision or blocked, implementation_plan and qa_plan may be omitted; include blockers, revision_questions, or revision_reasons instead.");
503
+ ...architectNonPassProperties()
504
+ }, ["status", "summary"], "For status pass, include implementation_plan and qa_plan at the top level of the MCP tool arguments, as JSON objects rather than quoted strings. implementation_plan.phases must be a top-level array inside implementation_plan, not nested under another object. For needs_revision or blocked, implementation_plan and qa_plan may be omitted; include blockers, revision_questions, or revision_reasons instead. When blocked because another Story or pull request must merge first, also list it in waits_on; when the owner must choose, also set owner_decision.");
513
505
  }
514
506
  return objectToolSchema({
515
507
  ...baseProperties,
@@ -1,5 +1,6 @@
1
1
  import { qaBlockerReasons, qaCandidateBugActions, qaFindingScopes, qaFindingSeverities, qaGateToolNames, qaScopeAuthorities, qaScopeCapabilities, qaScopeConfidence, qaScopeEvidence, qaScopeFields, qaScopeSources, qaScopeSurfaces } from "./phase-completion.js";
2
2
  import { structuredTypeHint } from "./mcp-argument-coercion.js";
3
+ import { validateArchitectWaits } from "./architect-waits.js";
3
4
  import { validateQaGatePassingCommands } from "./phase-completion.command-validation.js";
4
5
  export { validateQaGatePassingCommands } from "./phase-completion.command-validation.js";
5
6
  export const qaEvidenceGates = new Set(["qa_regression", "qa_api", "qa_manual_web", "qa_bug_repro"]);
@@ -353,6 +354,7 @@ export function validateQaGatePayloadShape(gate, payload, status) {
353
354
  }
354
355
  }
355
356
  export function validateArchitectPayloadShape(payload, status) {
357
+ validateArchitectWaits(payload, status);
356
358
  if (status !== "pass") {
357
359
  requireArchitectNonPassEvidence(payload);
358
360
  return;
@@ -706,7 +708,7 @@ export function hasArchitectDependencyCycle(edges) {
706
708
  return false;
707
709
  }
708
710
  export function requireArchitectNonPassEvidence(payload) {
709
- const evidenceKeys = ["blockers", "revision_questions", "revision_reasons", "known_gaps", "findings", "remaining_risks", "failures"];
711
+ const evidenceKeys = ["blockers", "revision_questions", "revision_reasons", "waits_on", "owner_decision", "known_gaps", "findings", "remaining_risks", "failures"];
710
712
  const hasEvidence = evidenceKeys.some((key) => {
711
713
  const value = payload[key];
712
714
  if (typeof value === "string") {