@loucompanion/forge-bridge 0.1.4-dev.63db04bcffca → 0.1.4-dev.83728c550770

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 (157) hide show
  1. package/README.md +25 -2
  2. package/dist/bridge/bridge.base.d.ts +9 -0
  3. package/dist/bridge/bridge.service.d.ts +84 -2
  4. package/dist/bridge/bridge.service.js +357 -12
  5. package/dist/bridge/bridge.types.d.ts +22 -0
  6. package/dist/bridge/dispatch-result-outbox.d.ts +11 -1
  7. package/dist/bridge/dispatch-result-outbox.js +31 -6
  8. package/dist/bridge/local-yield-flag.d.ts +6 -0
  9. package/dist/bridge/local-yield-flag.js +34 -0
  10. package/dist/bridge/runner-host-capabilities.d.ts +2 -0
  11. package/dist/bridge/runner-host-capabilities.js +4 -0
  12. package/dist/bridge/test-postgres-capability.d.ts +14 -0
  13. package/dist/bridge/test-postgres-capability.js +120 -0
  14. package/dist/cleanup/cleanup.service.d.ts +9 -0
  15. package/dist/cleanup/cleanup.service.js +72 -109
  16. package/dist/cleanup/cleanup.types.d.ts +4 -0
  17. package/dist/cleanup/forge-owned-paths.d.ts +9 -0
  18. package/dist/cleanup/forge-owned-paths.js +53 -0
  19. package/dist/cleanup/host-runtime-ledger.d.ts +5 -0
  20. package/dist/cleanup/host-runtime-ledger.js +109 -0
  21. package/dist/cleanup/managed-branch-sweep.d.ts +27 -0
  22. package/dist/cleanup/managed-branch-sweep.js +111 -0
  23. package/dist/cli/cli.help.js +18 -0
  24. package/dist/cli/cli.service.d.ts +5 -0
  25. package/dist/cli/cli.service.js +62 -4
  26. package/dist/cli/local-config.d.ts +2 -0
  27. package/dist/cli/local-config.js +7 -1
  28. package/dist/runtime/aspnet-runtime-prebuild.js +94 -6
  29. package/dist/runtime/attempt-process-supervisor.d.ts +19 -0
  30. package/dist/runtime/attempt-process-supervisor.js +50 -0
  31. package/dist/runtime/host-database-capability-boundary.d.ts +1 -1
  32. package/dist/runtime/host-database-capability-boundary.js +1 -0
  33. package/dist/runtime/host-facts.d.ts +35 -0
  34. package/dist/runtime/host-facts.js +95 -0
  35. package/dist/runtime/host-load-admission.d.ts +60 -0
  36. package/dist/runtime/host-load-admission.js +99 -0
  37. package/dist/runtime/host-load-child-environment.d.ts +22 -0
  38. package/dist/runtime/host-load-child-environment.js +67 -0
  39. package/dist/runtime/host-load-forge-cgroups.d.ts +49 -0
  40. package/dist/runtime/host-load-forge-cgroups.js +140 -0
  41. package/dist/runtime/host-load-governor-config.d.ts +43 -0
  42. package/dist/runtime/host-load-governor-config.js +76 -0
  43. package/dist/runtime/host-load-governor.d.ts +174 -0
  44. package/dist/runtime/host-load-governor.js +541 -0
  45. package/dist/runtime/host-load-ledger-lock.d.ts +69 -0
  46. package/dist/runtime/host-load-ledger-lock.js +185 -0
  47. package/dist/runtime/host-load-runtime-settings.d.ts +25 -0
  48. package/dist/runtime/host-load-runtime-settings.js +78 -0
  49. package/dist/runtime/host-load-sampler.d.ts +126 -0
  50. package/dist/runtime/host-load-sampler.js +232 -0
  51. package/dist/runtime/host-load-step-class.d.ts +68 -0
  52. package/dist/runtime/host-load-step-class.js +106 -0
  53. package/dist/runtime/host-load-step-reaper.d.ts +27 -0
  54. package/dist/runtime/host-load-step-reaper.js +95 -0
  55. package/dist/runtime/host-load-step-run.d.ts +73 -0
  56. package/dist/runtime/host-load-step-run.js +102 -0
  57. package/dist/runtime/host-load-token-ledger.d.ts +174 -0
  58. package/dist/runtime/host-load-token-ledger.js +421 -0
  59. package/dist/runtime/host-pressure-stall.d.ts +61 -0
  60. package/dist/runtime/host-pressure-stall.js +168 -0
  61. package/dist/runtime/host-runtime-contract.d.ts +4 -0
  62. package/dist/runtime/host-runtime-contract.js +6 -1
  63. package/dist/runtime/host-runtime-lease.d.ts +74 -4
  64. package/dist/runtime/host-runtime-lease.js +334 -19
  65. package/dist/runtime/host-runtime-promotion.js +12 -0
  66. package/dist/runtime/host-runtime-requirements-check.d.ts +17 -0
  67. package/dist/runtime/host-runtime-requirements-check.js +29 -0
  68. package/dist/runtime/host-runtime-requirements.d.ts +36 -0
  69. package/dist/runtime/host-runtime-requirements.js +117 -0
  70. package/dist/runtime/managed-command-teardown.d.ts +62 -0
  71. package/dist/runtime/managed-command-teardown.js +607 -0
  72. package/dist/runtime/playwright-browser-cache.d.ts +39 -0
  73. package/dist/runtime/playwright-browser-cache.js +227 -0
  74. package/dist/runtime/playwright-host-runtime-adapter.d.ts +18 -0
  75. package/dist/runtime/playwright-host-runtime-adapter.js +61 -55
  76. package/dist/runtime/runner-settings.d.ts +100 -0
  77. package/dist/runtime/runner-settings.js +214 -0
  78. package/dist/sandbox/host-capacity-broker.d.ts +107 -0
  79. package/dist/sandbox/host-capacity-broker.js +315 -0
  80. package/dist/sandbox/runtime.d.ts +10 -1
  81. package/dist/sandbox/runtime.js +45 -2
  82. package/dist/sandbox/sandbox-cgroups.d.ts +14 -0
  83. package/dist/sandbox/sandbox-cgroups.js +42 -0
  84. package/dist/session/managed-attempt-tools.d.ts +27 -0
  85. package/dist/session/managed-attempt-tools.js +356 -40
  86. package/dist/session/managed-build-coordinator.d.ts +1 -1
  87. package/dist/session/managed-build-coordinator.js +4 -1
  88. package/dist/session/managed-command-host-load.d.ts +45 -0
  89. package/dist/session/managed-command-host-load.js +82 -0
  90. package/dist/session/mcp-argument-coercion.d.ts +23 -0
  91. package/dist/session/mcp-argument-coercion.js +121 -0
  92. package/dist/session/phase-completion.artifacts.d.ts +7 -0
  93. package/dist/session/phase-completion.artifacts.js +98 -25
  94. package/dist/session/phase-completion.command-validation.d.ts +7 -0
  95. package/dist/session/phase-completion.command-validation.js +77 -0
  96. package/dist/session/phase-completion.d.ts +4 -0
  97. package/dist/session/phase-completion.helpers.js +13 -12
  98. package/dist/session/phase-completion.js +4 -0
  99. package/dist/session/phase-completion.prompts.js +6 -1
  100. package/dist/session/phase-completion.runtime.d.ts +5 -3
  101. package/dist/session/phase-completion.runtime.js +70 -35
  102. package/dist/session/phase-completion.schema-parts.d.ts +19 -0
  103. package/dist/session/phase-completion.schema-parts.js +188 -0
  104. package/dist/session/phase-completion.schemas.d.ts +3 -3
  105. package/dist/session/phase-completion.schemas.js +184 -209
  106. package/dist/session/phase-completion.validation.d.ts +2 -3
  107. package/dist/session/phase-completion.validation.js +46 -92
  108. package/dist/session/pre-publication-host-load.d.ts +27 -0
  109. package/dist/session/pre-publication-host-load.js +111 -0
  110. package/dist/session/pre-publication-process.d.ts +23 -0
  111. package/dist/session/pre-publication-process.js +109 -0
  112. package/dist/session/pre-publication-skipped-tests.d.ts +21 -0
  113. package/dist/session/pre-publication-skipped-tests.js +109 -0
  114. package/dist/session/pre-publication-step-execution.d.ts +11 -0
  115. package/dist/session/pre-publication-step-execution.js +49 -0
  116. package/dist/session/pre-publication-validation.d.ts +9 -9
  117. package/dist/session/pre-publication-validation.js +48 -112
  118. package/dist/session/provider-cli/provider-cli.artifacts.d.ts +2 -1
  119. package/dist/session/provider-cli/provider-cli.artifacts.js +21 -15
  120. package/dist/session/provider-cli/provider-cli.merge-integrity.d.ts +89 -0
  121. package/dist/session/provider-cli/provider-cli.merge-integrity.js +310 -0
  122. package/dist/session/provider-cli/provider-cli.process.d.ts +37 -1
  123. package/dist/session/provider-cli/provider-cli.process.js +299 -25
  124. package/dist/session/provider-cli/provider-cli.prompts.d.ts +5 -0
  125. package/dist/session/provider-cli/provider-cli.prompts.js +20 -2
  126. package/dist/session/provider-cli/provider-cli.service.d.ts +6 -0
  127. package/dist/session/provider-cli/provider-cli.service.js +244 -36
  128. package/dist/session/provider-cli/provider-cli.types.d.ts +30 -0
  129. package/dist/session/provider-cli/provider-in-flight-work.d.ts +6 -0
  130. package/dist/session/provider-cli/provider-in-flight-work.js +47 -0
  131. package/dist/session/provider-cli/provider-output-state.d.ts +6 -0
  132. package/dist/session/provider-cli/provider-output-state.js +9 -0
  133. package/dist/session/publishable-worktree-changes.d.ts +54 -0
  134. package/dist/session/publishable-worktree-changes.js +193 -0
  135. package/dist/session/sandbox-host-capacity-gate.d.ts +30 -0
  136. package/dist/session/sandbox-host-capacity-gate.js +229 -0
  137. package/dist/session/session.base.d.ts +9 -1
  138. package/dist/session/session.service.d.ts +9 -2
  139. package/dist/session/session.service.js +120 -5
  140. package/dist/session/session.types.d.ts +3 -0
  141. package/dist/session/session.types.js +15 -3
  142. package/dist/session/workspace-runtime-fingerprint.d.ts +32 -0
  143. package/dist/session/workspace-runtime-fingerprint.js +138 -0
  144. package/dist/shared/process/host-process-supervisor.d.ts +1 -0
  145. package/dist/shared/process/host-process-supervisor.js +1 -1
  146. package/dist/shared/process/process-tree.d.ts +52 -0
  147. package/dist/shared/process/process-tree.js +144 -0
  148. package/dist/shared/process/process.d.ts +67 -0
  149. package/dist/shared/process/process.js +213 -11
  150. package/dist/version.d.ts +1 -1
  151. package/dist/version.js +1 -1
  152. package/dist/worktree/dependency-warmer.d.ts +25 -0
  153. package/dist/worktree/dependency-warmer.js +46 -10
  154. package/dist/worktree/worktree.service.d.ts +10 -1
  155. package/dist/worktree/worktree.service.js +42 -2
  156. package/dist/worktree/worktree.types.d.ts +7 -0
  157. package/package.json +1 -1
@@ -12,7 +12,7 @@ export class ManagedBuildCoordinator {
12
12
  constructor(stateRoot = defaultWorktreeCoordinatorStateRoot()) {
13
13
  this.stateRoot = stateRoot;
14
14
  }
15
- async withBuildSlot(worktreePath, action, onWaiting) {
15
+ async withBuildSlot(worktreePath, action, onWaiting, signal) {
16
16
  const resolved = path.resolve(worktreePath);
17
17
  const key = createHash("sha256").update(resolved.toLowerCase()).digest("hex");
18
18
  const root = path.join(this.stateRoot, "managed-build-locks");
@@ -22,6 +22,9 @@ export class ManagedBuildCoordinator {
22
22
  let waitingReported = false;
23
23
  await fs.mkdir(root, { recursive: true, mode: 0o700 });
24
24
  while (true) {
25
+ if (signal?.aborted) {
26
+ throw signal.reason instanceof Error ? signal.reason : new Error("managed_build_slot_cancelled: the build-slot wait was cancelled.");
27
+ }
25
28
  try {
26
29
  const handle = await fs.open(target, "wx", 0o600);
27
30
  try {
@@ -0,0 +1,45 @@
1
+ import { type HostLoadStepGate } from "../runtime/host-load-governor.js";
2
+ import { type HostLoadStepClassification, type ManagedCommandStepInput } from "../runtime/host-load-step-class.js";
3
+ import { type HostLoadStepControl } from "../runtime/host-load-step-run.js";
4
+ /** Host-load facts a managed command receipt carries; absent while the governor is off. */
5
+ export interface ManagedCommandHostLoadFields {
6
+ readonly stepClass: string;
7
+ /** Queue time before admission; never part of elapsed_ms. */
8
+ readonly waitMs: number;
9
+ /** Set while the command is still queued: the receipt reports the wait so far. */
10
+ readonly waitStartedAt?: number;
11
+ /** When the command was admitted; elapsed_ms counts from here. */
12
+ readonly executionStartedAt?: number;
13
+ }
14
+ /** This MCP server's governor, built once from the environment the bridge handed it. */
15
+ export declare function managedCommandHostLoadGate(): HostLoadStepGate | undefined;
16
+ /** Test support: installs a gate (undefined disables it; null rebuilds from the environment). */
17
+ export declare function setManagedCommandHostLoadGateForTesting(value: HostLoadStepGate | undefined | null): void;
18
+ /**
19
+ * Admits one managed command. The waiting receipt is written while the command
20
+ * is queued and always lands before the launch receipts, so a stale "waiting"
21
+ * write can never replace a later status.
22
+ */
23
+ export declare class ManagedCommandHostCapacity {
24
+ private readonly persistWaiting;
25
+ private readonly gateFor;
26
+ readonly classification: HostLoadStepClassification;
27
+ private readonly label;
28
+ private requestedAtMs;
29
+ private waitingWrite;
30
+ constructor(input: ManagedCommandStepInput & {
31
+ readonly label: string;
32
+ }, persistWaiting: (fields: ManagedCommandHostLoadFields) => Promise<void>, gateFor?: () => HostLoadStepGate | undefined);
33
+ /** Runs `launch` once admitted; `fields` is undefined with the governor off. */
34
+ run<T>(signal: AbortSignal, launch: (fields: ManagedCommandHostLoadFields | undefined, control: HostLoadStepControl) => Promise<T>, onReleaseFailed?: (error: unknown) => Promise<void>): Promise<T>;
35
+ /**
36
+ * Host-load facts for a command that was never admitted (it timed out in
37
+ * the queue or was stopped while waiting), once its waiting receipt landed.
38
+ */
39
+ unadmittedFields(error: unknown): Promise<ManagedCommandHostLoadFields | undefined>;
40
+ }
41
+ /**
42
+ * The managed command's process tree as its supervisor recorded it, for its
43
+ * host load token: a reclaim then stops exactly this tree before reuse.
44
+ */
45
+ export declare function attachManagedCommandProcess(control: HostLoadStepControl, metadataPath: string): Promise<void>;
@@ -0,0 +1,82 @@
1
+ import { hostLoadGovernorFromChildEnvironment } from "../runtime/host-load-child-environment.js";
2
+ import { HostCapacityTimeoutError } from "../runtime/host-load-governor.js";
3
+ import { classifyManagedCommand } from "../runtime/host-load-step-class.js";
4
+ import { attachSupervisedStepProcess, runHostGovernedStep } from "../runtime/host-load-step-run.js";
5
+ let gate = null;
6
+ /** This MCP server's governor, built once from the environment the bridge handed it. */
7
+ export function managedCommandHostLoadGate() {
8
+ if (gate === null)
9
+ gate = hostLoadGovernorFromChildEnvironment();
10
+ return gate;
11
+ }
12
+ /** Test support: installs a gate (undefined disables it; null rebuilds from the environment). */
13
+ export function setManagedCommandHostLoadGateForTesting(value) {
14
+ gate = value;
15
+ }
16
+ /**
17
+ * Admits one managed command. The waiting receipt is written while the command
18
+ * is queued and always lands before the launch receipts, so a stale "waiting"
19
+ * write can never replace a later status.
20
+ */
21
+ export class ManagedCommandHostCapacity {
22
+ persistWaiting;
23
+ gateFor;
24
+ classification;
25
+ label;
26
+ requestedAtMs = null;
27
+ waitingWrite = Promise.resolve();
28
+ constructor(input, persistWaiting, gateFor = managedCommandHostLoadGate) {
29
+ this.persistWaiting = persistWaiting;
30
+ this.gateFor = gateFor;
31
+ this.classification = classifyManagedCommand(input);
32
+ this.label = input.label;
33
+ }
34
+ /** Runs `launch` once admitted; `fields` is undefined with the governor off. */
35
+ async run(signal, launch, onReleaseFailed) {
36
+ const current = this.gateFor();
37
+ if (current?.enabled)
38
+ this.requestedAtMs = Date.now();
39
+ return await runHostGovernedStep(current, {
40
+ classification: this.classification,
41
+ label: this.label,
42
+ dispatchAttemptId: process.env.FORGE_DISPATCH_ATTEMPT_ID?.trim() || null,
43
+ // An agent waits on its managed commands; readiness probes never start one.
44
+ priority: "foreground",
45
+ signal,
46
+ // The receipt says host_capacity_token_fenced itself (termination_reason).
47
+ reportsOwnFence: true,
48
+ onWaiting: () => {
49
+ this.waitingWrite = this.persistWaiting({
50
+ stepClass: this.classification.stepClass,
51
+ waitMs: 0,
52
+ waitStartedAt: this.requestedAtMs ?? Date.now(),
53
+ }).catch(() => undefined);
54
+ },
55
+ onReleaseFailed,
56
+ }, async (waitMs, control) => {
57
+ await this.waitingWrite;
58
+ // The launch timer and timeout_ms start inside `launch`, after admission.
59
+ return await launch(waitMs === null
60
+ ? undefined
61
+ : { stepClass: this.classification.stepClass, waitMs, executionStartedAt: Date.now() }, control);
62
+ });
63
+ }
64
+ /**
65
+ * Host-load facts for a command that was never admitted (it timed out in
66
+ * the queue or was stopped while waiting), once its waiting receipt landed.
67
+ */
68
+ async unadmittedFields(error) {
69
+ await this.waitingWrite;
70
+ if (this.requestedAtMs === null)
71
+ return undefined;
72
+ const waitMs = error instanceof HostCapacityTimeoutError ? error.waitMs : Date.now() - this.requestedAtMs;
73
+ return { stepClass: this.classification.stepClass, waitMs: Math.round(waitMs), executionStartedAt: Date.now() };
74
+ }
75
+ }
76
+ /**
77
+ * The managed command's process tree as its supervisor recorded it, for its
78
+ * host load token: a reclaim then stops exactly this tree before reuse.
79
+ */
80
+ export async function attachManagedCommandProcess(control, metadataPath) {
81
+ await attachSupervisedStepProcess(control, metadataPath);
82
+ }
@@ -0,0 +1,23 @@
1
+ /**
2
+ * MCP clients sometimes send a structured tool argument as its JSON text, for
3
+ * example `sidecars: "[{...}]"` instead of `sidecars: [{...}]`. At the tool-call
4
+ * boundary, before any validation, this replaces such a string with its parsed
5
+ * value, but only where the tool's declared input schema says the value is an
6
+ * array or an object and the string parses to exactly that kind of value.
7
+ *
8
+ * Nothing else is coerced: a string field that happens to contain JSON stays a
9
+ * string, an undeclared field is left alone, and a malformed string is passed
10
+ * through unchanged so the validator reports it.
11
+ */
12
+ export declare function coerceJsonStringArguments(value: unknown, schema: unknown): unknown;
13
+ type StructuredKind = "array" | "object";
14
+ /**
15
+ * Explains why a value is not the expected array or object, for validator
16
+ * messages. A string gets an explicit instruction because that is the usual
17
+ * client mistake; the hint never echoes the value itself.
18
+ */
19
+ export declare function structuredTypeHint(value: unknown, expected: StructuredKind): string;
20
+ /** True when a tool call arrived with no usable arguments at all. */
21
+ export declare function isEmptyToolInput(input: unknown): boolean;
22
+ export declare const emptyToolInputHint: string;
23
+ export {};
@@ -0,0 +1,121 @@
1
+ /**
2
+ * MCP clients sometimes send a structured tool argument as its JSON text, for
3
+ * example `sidecars: "[{...}]"` instead of `sidecars: [{...}]`. At the tool-call
4
+ * boundary, before any validation, this replaces such a string with its parsed
5
+ * value, but only where the tool's declared input schema says the value is an
6
+ * array or an object and the string parses to exactly that kind of value.
7
+ *
8
+ * Nothing else is coerced: a string field that happens to contain JSON stays a
9
+ * string, an undeclared field is left alone, and a malformed string is passed
10
+ * through unchanged so the validator reports it.
11
+ */
12
+ export function coerceJsonStringArguments(value, schema) {
13
+ const node = schemaNode(schema);
14
+ if (!node)
15
+ return value;
16
+ const expected = structuredKind(node);
17
+ let current = value;
18
+ if (typeof current === "string" && expected) {
19
+ const parsed = parseStructured(current, expected);
20
+ if (parsed !== undefined)
21
+ current = parsed;
22
+ }
23
+ if (Array.isArray(current)) {
24
+ const items = schemaNode(node.items);
25
+ if (!items || !acceptsKind(node, "array"))
26
+ return current;
27
+ let changed = current !== value;
28
+ const next = current.map((entry) => {
29
+ const coerced = coerceJsonStringArguments(entry, items);
30
+ if (coerced !== entry)
31
+ changed = true;
32
+ return coerced;
33
+ });
34
+ return changed ? next : current;
35
+ }
36
+ if (isPlainRecord(current)) {
37
+ const properties = schemaNode(node.properties);
38
+ if (!properties || !acceptsKind(node, "object"))
39
+ return current;
40
+ let next = current !== value ? { ...current } : null;
41
+ for (const [key, propertySchema] of Object.entries(properties)) {
42
+ if (!Object.prototype.hasOwnProperty.call(current, key))
43
+ continue;
44
+ const original = current[key];
45
+ const coerced = coerceJsonStringArguments(original, propertySchema);
46
+ if (coerced !== original) {
47
+ next ??= { ...current };
48
+ next[key] = coerced;
49
+ }
50
+ }
51
+ return next ?? current;
52
+ }
53
+ return current;
54
+ }
55
+ function structuredKind(node) {
56
+ const type = node.type;
57
+ if (type === "array" || type === "object")
58
+ return type;
59
+ if (Array.isArray(type)) {
60
+ // A schema that also admits a string must keep the string as sent.
61
+ if (type.includes("string"))
62
+ return null;
63
+ if (type.includes("array") && !type.includes("object"))
64
+ return "array";
65
+ if (type.includes("object") && !type.includes("array"))
66
+ return "object";
67
+ }
68
+ return null;
69
+ }
70
+ function acceptsKind(node, kind) {
71
+ const type = node.type;
72
+ if (type === undefined)
73
+ return true;
74
+ return type === kind || (Array.isArray(type) && type.includes(kind));
75
+ }
76
+ function parseStructured(text, expected) {
77
+ const trimmed = text.trim();
78
+ if (!trimmed.startsWith(expected === "array" ? "[" : "{"))
79
+ return undefined;
80
+ try {
81
+ const parsed = JSON.parse(trimmed);
82
+ if (expected === "array" ? Array.isArray(parsed) : isPlainRecord(parsed))
83
+ return parsed;
84
+ }
85
+ catch {
86
+ // Leave malformed JSON text in place; the validator reports it with a hint.
87
+ }
88
+ return undefined;
89
+ }
90
+ function schemaNode(value) {
91
+ return isPlainRecord(value) ? value : null;
92
+ }
93
+ function isPlainRecord(value) {
94
+ return Boolean(value) && typeof value === "object" && !Array.isArray(value);
95
+ }
96
+ /**
97
+ * Explains why a value is not the expected array or object, for validator
98
+ * messages. A string gets an explicit instruction because that is the usual
99
+ * client mistake; the hint never echoes the value itself.
100
+ */
101
+ export function structuredTypeHint(value, expected) {
102
+ if (value === undefined || value === null) {
103
+ return " (it was omitted)";
104
+ }
105
+ if (typeof value === "string") {
106
+ return expected === "array"
107
+ ? " (received a string; pass a JSON array value, not a quoted string)"
108
+ : " (received a string; pass a JSON object value, not a quoted string)";
109
+ }
110
+ if (Array.isArray(value))
111
+ return " (received an array)";
112
+ return typeof value === "object" ? " (received an object)" : ` (received a ${typeof value})`;
113
+ }
114
+ /** True when a tool call arrived with no usable arguments at all. */
115
+ export function isEmptyToolInput(input) {
116
+ return input === undefined
117
+ || input === null
118
+ || (isPlainRecord(input) && Object.keys(input).length === 0);
119
+ }
120
+ export const emptyToolInputHint = "No arguments were received: the call arrived as an empty object. "
121
+ + "If the call was large it was probably cut off before it was sent; resend it with every required field.";
@@ -2,6 +2,13 @@ import { type CompletionArtifactReference, type CompletionPhase, type Completion
2
2
  import type { RunnerDispatchArtifact } from "./session.types.js";
3
3
  export declare function writeDecomposeGateCompletionArtifact(config: CompletionToolServerConfig, gate: DecomposeCompletionGate, toolName: string, input: unknown): Promise<CompletionArtifactReference>;
4
4
  export declare function writeDraftGateCompletionArtifact(config: CompletionToolServerConfig, gate: DraftCompletionGate, toolName: string, input: unknown): Promise<CompletionArtifactReference>;
5
+ /**
6
+ * Judges a Decompose gate call before anything is written and returns its status. The gate's
7
+ * input schema advertises exactly these rules (see the completion tool schema contract test).
8
+ */
9
+ export declare function validateDecomposeGatePayload(gate: DecomposeCompletionGate, payload: Record<string, unknown>): string;
10
+ /** Judges a Draft gate call before anything is written and returns its status. */
11
+ export declare function validateDraftGatePayload(gate: DraftCompletionGate, payload: Record<string, unknown>): string;
5
12
  export declare function writeCompletionArtifact(config: CompletionToolServerConfig, toolName: string, input: unknown): Promise<CompletionArtifactReference>;
6
13
  export declare function writeArchitectCompletionArtifact(config: CompletionToolServerConfig, payload: Record<string, unknown>, status: string, producedBy: string): Promise<CompletionArtifactReference>;
7
14
  export declare function writeQaGateCompletionArtifact(config: CompletionToolServerConfig, gate: QaCompletionGate, input: unknown): Promise<CompletionArtifactReference>;
@@ -3,15 +3,14 @@ import fs from "node:fs/promises";
3
3
  import path from "node:path";
4
4
  import { redactSecrets } from "../shared/redaction/redaction.js";
5
5
  import { ensureNoSymbolicLinkPathSegments, isPathUnderRoot, sha256File } from "./qa-sidecar-validation.js";
6
- import { artifactRootFor, artifactRootForOwner, completionArtifactJsonPath, completionArtifactReportPath, decomposeGateFileNames, draftGateFileNames, phaseFiles, qaGateFileNames } from "./phase-completion.js";
7
- import { artifactOwnerFields, artifactReferenceOwnerFields, artifactOwnerRelativeRoot, defaultQaChecklist, fallbackReport, isNodeError, jsonText, normalizeArtifactPayload, normalizeCompletionStatus, normalizeQaGateArtifactPayload, normalizeQaGateStatus, normalizedString, optionalString, numberOrDefault, parseJsonObject, parseOptionalJsonObject, phaseFromToolName, qaArray, qaArtifactRelativePath, qaArtifactRelativePathForOwner, qaEvidenceSource, qaObjectArray, qaPolicyWarnings, qaStringArray, readOptionalFile, reportMarkdown, requiredRecord, requiredString, qaGateFromToolName, sha256, stableStringify, validateOptionalWorkItemId, validatePayloadShape, validateQaGatePayloadShape, validateQaScopeRecord, writeFileAtomic, asRecord } from "./phase-completion.validation.js";
6
+ import { assertClaimedChangedFilesMatchPublishableDiff } from "./publishable-worktree-changes.js";
7
+ import { coerceJsonStringArguments } from "./mcp-argument-coercion.js";
8
+ import { toolInputSchema } from "./phase-completion.schemas.js";
9
+ import { artifactRootFor, artifactRootForOwner, completionArtifactJsonPath, completionArtifactReportPath, decomposeGateFileNames, draftGateFileNames, phaseFiles, qaGateFileNames, decomposeStatuses, draftStatuses } from "./phase-completion.js";
10
+ import { artifactOwnerFields, artifactReferenceOwnerFields, artifactOwnerRelativeRoot, defaultQaChecklist, fallbackReport, isNodeError, jsonText, normalizeArtifactPayload, normalizeCompletionStatus, normalizeQaGateArtifactPayload, normalizeQaGateStatus, normalizedString, optionalString, numberOrDefault, parseJsonObject, parseOptionalJsonObject, phaseFromToolName, qaArray, qaArtifactRelativePath, qaArtifactRelativePathForOwner, qaEvidenceSource, qaObjectArray, qaPolicyWarnings, qaEvidenceGates, qaStringArray, readOptionalFile, reportMarkdown, requireField, requiredRecord, requiredString, qaGateFromToolName, sha256, stableStringify, validateOptionalWorkItemId, validatePayloadShape, validateQaGatePayloadShape, validateQaScopeRecord, writeFileAtomic, asRecord } from "./phase-completion.validation.js";
8
11
  export async function writeDecomposeGateCompletionArtifact(config, gate, toolName, input) {
9
12
  const payload = asRecord(input, "Decompose completion payload");
10
- const status = normalizeDraftStatus(optionalString(payload, "status") ?? "pass");
11
- if (gate === "decompose_proposal") {
12
- const proposalJson = asRecord(payload["proposal_json"] ?? payload["decomposition_json"], "proposal_json");
13
- validateDecomposeProposalJson(proposalJson);
14
- }
13
+ const status = validateDecomposeGatePayload(gate, payload);
15
14
  const redactedPayload = redactSecrets({ ...payload, status, phase: "decompose", gate, tool_name: toolName }, config.redactionSecrets ?? []);
16
15
  assertStructuralFieldsUnchanged(payload, redactedPayload);
17
16
  if (gate === "decompose_proposal") {
@@ -44,11 +43,7 @@ ${optionalString(redactedPayload, "summary") ?? "Decompose gate recorded."}
44
43
  }
45
44
  export async function writeDraftGateCompletionArtifact(config, gate, toolName, input) {
46
45
  const payload = asRecord(input, "Draft completion payload");
47
- const status = normalizeDraftStatus(optionalString(payload, "status") ?? "pass");
48
- if (gate === "draft_proposal") {
49
- const draftJson = asRecord(payload["draft_json"], "draft_json");
50
- validateDraftProposalJson(draftJson);
51
- }
46
+ const status = validateDraftGatePayload(gate, payload);
52
47
  const redactedPayload = redactSecrets({ ...payload, status, phase: "draft", gate, tool_name: toolName }, config.redactionSecrets ?? []);
53
48
  assertStructuralFieldsUnchanged(payload, redactedPayload);
54
49
  if (gate === "draft_proposal") {
@@ -76,9 +71,48 @@ export async function writeDraftGateCompletionArtifact(config, gate, toolName, i
76
71
  producedBy: config.producedBy ?? "forge-completion-tool"
77
72
  };
78
73
  }
79
- function normalizeDraftStatus(value) {
80
- const normalized = value.trim().toLowerCase();
81
- return normalized === "blocked" || normalized === "needs_revision" || normalized === "needs_rework" ? normalized : "pass";
74
+ /**
75
+ * Judges a Decompose gate call before anything is written and returns its status. The gate's
76
+ * input schema advertises exactly these rules (see the completion tool schema contract test).
77
+ */
78
+ export function validateDecomposeGatePayload(gate, payload) {
79
+ const status = gateStatus(payload, decomposeStatuses);
80
+ if (gate === "decompose_proposal") {
81
+ validateDecomposeProposalJson(asRecord(payload["proposal_json"] ?? payload["decomposition_json"], "proposal_json"));
82
+ }
83
+ else {
84
+ // An earlier Decompose gate's evidence is its summary, and a missing status means pass, so an
85
+ // empty call would otherwise record a pass and move to the next gate.
86
+ requireField(payload, "summary");
87
+ }
88
+ return status;
89
+ }
90
+ /** Judges a Draft gate call before anything is written and returns its status. */
91
+ export function validateDraftGatePayload(gate, payload) {
92
+ const status = gateStatus(payload, draftStatuses);
93
+ if (gate === "draft_proposal") {
94
+ validateDraftProposalJson(asRecord(payload["draft_json"], "draft_json"));
95
+ }
96
+ else {
97
+ // An earlier Draft gate's only evidence is its summary, and a missing status means pass, so an
98
+ // empty call would otherwise record a pass and move to the next gate.
99
+ requireField(payload, "summary");
100
+ }
101
+ return status;
102
+ }
103
+ // Only an omitted status defaults to pass. A status that is present must be one of the advertised
104
+ // values: a typo such as "pas", a blank string or a non-string is rejected rather than advancing
105
+ // the gate as a pass.
106
+ function gateStatus(payload, allowed) {
107
+ const value = payload["status"];
108
+ if (value === undefined || value === null) {
109
+ return "pass";
110
+ }
111
+ const normalized = typeof value === "string" ? value.trim().toLowerCase() : "";
112
+ if (!allowed.includes(normalized)) {
113
+ throw new Error(`status must be one of ${allowed.join(", ")}; received ${typeof value === "string" ? `'${value}'` : JSON.stringify(value)}.`);
114
+ }
115
+ return normalized;
82
116
  }
83
117
  function validateDraftProposalJson(draftJson) {
84
118
  if (draftJson.suggested_qa_scope !== undefined && draftJson.suggested_qa_scope !== null) {
@@ -158,6 +192,9 @@ export async function writeCompletionArtifact(config, toolName, input) {
158
192
  }
159
193
  validatePayloadShape(phase, validationPayload);
160
194
  validateOptionalWorkItemId(validationPayload, config.workItemId);
195
+ if (phase === "comment_repair" && status === "pass") {
196
+ await assertClaimedChangedFilesMatchPublishableDiff(config.worktreePath, validationPayload, toolName);
197
+ }
161
198
  const redactedPayload = redactSecrets(validationPayload, config.redactionSecrets ?? []);
162
199
  assertStructuralFieldsUnchanged(validationPayload, redactedPayload);
163
200
  validatePostRedaction(() => {
@@ -216,8 +253,10 @@ export async function writeArchitectCompletionArtifact(config, payload, status,
216
253
  const qaPlanPath = path.join(artifactRoot, "qa.plan.json");
217
254
  const verdictPath = path.join(artifactRoot, "architect.verdict.json");
218
255
  const reportPath = path.join(artifactRoot, "architect.report.md");
219
- const implementationPlan = requiredRecord(payload, "implementation_plan");
220
- const qaPlan = requiredRecord(payload, "qa_plan");
256
+ // A needs_revision or blocked verdict has no plan to approve; its schema lets
257
+ // the agent omit both plans, and the bundle still carries a file for each.
258
+ const implementationPlan = architectPlanRecord(payload, "implementation_plan", status);
259
+ const qaPlan = architectPlanRecord(payload, "qa_plan", status);
221
260
  const report = optionalString(payload, "report") ?? optionalString(payload, "report_markdown") ?? reportMarkdown(payload, "architect", status, producedBy, "pending");
222
261
  const artifactWithoutHash = normalizeArtifactPayload(payload, {
223
262
  phase: "architect",
@@ -250,13 +289,21 @@ export async function writeArchitectCompletionArtifact(config, payload, status,
250
289
  producedBy
251
290
  };
252
291
  }
292
+ function architectPlanRecord(payload, key, status) {
293
+ if (status !== "pass" && (payload[key] === undefined || payload[key] === null)) {
294
+ return {};
295
+ }
296
+ return requiredRecord(payload, key);
297
+ }
253
298
  export async function writeQaGateCompletionArtifact(config, gate, input) {
254
299
  const payload = asRecord(input, "QA gate completion payload");
255
300
  const status = normalizeQaGateStatus(requiredString(payload, "status"));
256
301
  validateQaGatePayloadShape(gate, payload, status);
257
302
  validateOptionalWorkItemId(payload, config.workItemId);
258
303
  const ownerFields = artifactOwnerFields(config);
259
- const validatedSidecars = gate === "qa_manual_web"
304
+ // Every evidence gate's sidecars are merged into the final verdict, which checks each file,
305
+ // so each gate checks its references (exists, under qa/, size and hash match) when it is called.
306
+ const validatedSidecars = qaEvidenceGates.has(gate)
260
307
  ? await validateQaSidecarReferences(config.worktreePath, config.workItemId, qaArray(payload, "sidecars", qaEvidenceSource(payload)), ownerFields.owner_type, ownerFields.owner_id)
261
308
  : null;
262
309
  const redactedPayload = redactSecrets({
@@ -269,7 +316,7 @@ export async function writeQaGateCompletionArtifact(config, gate, input) {
269
316
  validateQaGatePayloadShape(gate, redactedPayload, status);
270
317
  validateOptionalWorkItemId(redactedPayload, config.workItemId);
271
318
  });
272
- if (gate === "qa_manual_web") {
319
+ if (qaEvidenceGates.has(gate)) {
273
320
  await validateQaSidecarReferences(config.worktreePath, config.workItemId, qaArray(redactedPayload, "sidecars", qaEvidenceSource(redactedPayload)), ownerFields.owner_type, ownerFields.owner_id).catch((error) => {
274
321
  throw postRedactionValidationError(error);
275
322
  });
@@ -425,12 +472,12 @@ export async function writeQaCompletionArtifact(config, payload, status, produce
425
472
  };
426
473
  }
427
474
  async function synthesizeQaCycleVerdictPayload(config, payload, status) {
428
- const qaPlan = await readQaGateArtifact(config, "qa_plan");
429
- const qaRegression = await readQaGateArtifact(config, "qa_regression");
430
- const qaApi = await readQaGateArtifact(config, "qa_api");
431
- const qaManualWeb = await readQaGateArtifact(config, "qa_manual_web");
432
- const qaBugRepro = await readQaGateArtifact(config, "qa_bug_repro");
433
- const qaFindings = await readQaGateArtifact(config, "qa_findings");
475
+ const qaPlan = await readInheritedQaGateArtifact(config, "qa_plan");
476
+ const qaRegression = await readInheritedQaGateArtifact(config, "qa_regression");
477
+ const qaApi = await readInheritedQaGateArtifact(config, "qa_api");
478
+ const qaManualWeb = await readInheritedQaGateArtifact(config, "qa_manual_web");
479
+ const qaBugRepro = await readInheritedQaGateArtifact(config, "qa_bug_repro");
480
+ const qaFindings = await readInheritedQaGateArtifact(config, "qa_findings");
434
481
  const evidenceGates = [qaRegression, qaApi, qaManualWeb, qaBugRepro];
435
482
  const payloadEvidence = qaEvidenceSource(payload);
436
483
  const merged = { ...payload };
@@ -478,6 +525,32 @@ async function synthesizeQaCycleVerdictPayload(config, payload, status) {
478
525
  merged.candidate_bugs = mergeQaObjectArraysById(qaObjectArray(payload, "candidate_bugs"), qaObjectArray(qaFindings, "candidate_bugs"));
479
526
  return merged;
480
527
  }
528
+ /**
529
+ * Reads an earlier gate's artifact for the verdict merge. Gates recorded before
530
+ * argument coercion existed may hold a JSON-string array, so the same schema
531
+ * coercion is applied here, and any remaining shape error names the gate file
532
+ * instead of looking like a fault in the verdict payload.
533
+ */
534
+ async function readInheritedQaGateArtifact(config, gate) {
535
+ const artifact = coerceJsonStringArguments(await readQaGateArtifact(config, gate), toolInputSchema("qa", gate));
536
+ // Gates accept sidecars inside the evidence wrapper too; promote them so the verdict inherits
537
+ // them. A top-level value still takes precedence.
538
+ if (artifact.sidecars === undefined || artifact.sidecars === null) {
539
+ const nestedSidecars = qaEvidenceSource(artifact).sidecars;
540
+ if (nestedSidecars !== undefined && nestedSidecars !== null) {
541
+ artifact.sidecars = nestedSidecars;
542
+ }
543
+ }
544
+ for (const key of ["commands", "browser_checks", "sidecars", "checklist", "acceptance_criteria", "findings", "candidate_bugs"]) {
545
+ try {
546
+ qaArray(artifact, key);
547
+ }
548
+ catch (error) {
549
+ throw new Error(`${qaGateFileNames[gate]} recorded by ${gate} has an invalid ${key}: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
550
+ }
551
+ }
552
+ return artifact;
553
+ }
481
554
  export async function readQaGateArtifact(config, gate) {
482
555
  const ownerFields = artifactOwnerFields(config);
483
556
  const artifactRoot = ownerFields.owner_type && ownerFields.owner_id
@@ -0,0 +1,7 @@
1
+ export declare function validateQaGatePassingCommands(commands: readonly unknown[], options?: {
2
+ readonly allowClassifiedNonBlockingFailures?: boolean;
3
+ /** Payload field that holds these command records, for error messages. */
4
+ readonly label?: string;
5
+ /** Why a passing result is required, for error messages. */
6
+ readonly context?: string;
7
+ }): void;
@@ -0,0 +1,77 @@
1
+ /**
2
+ * Checks the command evidence records (commands, validation, narrow_validation,
3
+ * and similar fields) that a passing completion must report as passing, with
4
+ * the classified non-blocking failure exception for QA regression.
5
+ */
6
+ import { structuredTypeHint } from "./mcp-argument-coercion.js";
7
+ import { normalizedString, optionalString, requireNonEmptyStringRecord, throwCompletionPayloadIssues } from "./phase-completion.helpers.js";
8
+ export function validateQaGatePassingCommands(commands, options = {}) {
9
+ const label = options.label ?? "commands";
10
+ const context = options.context ?? "QA gate status is pass";
11
+ const issues = [];
12
+ for (const [index, command] of commands.entries()) {
13
+ if (!command || typeof command !== "object" || Array.isArray(command)) {
14
+ issues.push(`${label}[${index}] must be an object${structuredTypeHint(command, "object")}.`);
15
+ continue;
16
+ }
17
+ const record = command;
18
+ if (!optionalString(record, "command"))
19
+ issues.push(`${label}[${index}].command is required.`);
20
+ if (!optionalString(record, "status"))
21
+ issues.push(`${label}[${index}].status is required.`);
22
+ if (!optionalString(record, "summary"))
23
+ issues.push(`${label}[${index}].summary is required.`);
24
+ if (typeof record.exit_code !== "number" || !Number.isFinite(record.exit_code)) {
25
+ issues.push(`${label}[${index}].exit_code is required.`);
26
+ continue;
27
+ }
28
+ const passed = record.exit_code === 0 && normalizedString(record.status) === "pass";
29
+ if (!passed
30
+ && options.allowClassifiedNonBlockingFailures
31
+ && optionalString(record, "classification")) {
32
+ try {
33
+ validateClassifiedNonBlockingQaFailure(record, index, label);
34
+ }
35
+ catch (error) {
36
+ issues.push(error instanceof Error ? error.message : String(error));
37
+ }
38
+ continue;
39
+ }
40
+ if (record.exit_code !== 0) {
41
+ issues.push(`${label}[${index}].exit_code must be 0 when ${context}.`);
42
+ }
43
+ if (normalizedString(record.status) !== "pass") {
44
+ issues.push(`${label}[${index}].status must be pass when ${context}.`);
45
+ }
46
+ }
47
+ throwCompletionPayloadIssues(issues);
48
+ }
49
+ function validateClassifiedNonBlockingQaFailure(record, index, label) {
50
+ const prefix = `${label}[${index}]`;
51
+ const classification = normalizedString(optionalString(record, "classification"));
52
+ if (classification !== "out_of_scope_failure" && classification !== "baseline_failure") {
53
+ throw new Error(`${prefix}.classification must be out_of_scope_failure or baseline_failure: a non-passing command in a QA regression pass needs a classification with corroborating evidence.`);
54
+ }
55
+ const classified = `for a non-blocking ${classification} (also required: candidate_bug_id, scope_evidence, acceptance_criteria_independent: true, and ${classification === "out_of_scope_failure" ? "repro_command with a non-zero repro_exit_code" : "baseline_ref, a non-zero baseline_exit_code, and failure_signature_match: true"})`;
56
+ if (!optionalString(record, "candidate_bug_id"))
57
+ throw new Error(`${prefix}.candidate_bug_id is required ${classified}.`);
58
+ if (!optionalString(record, "scope_evidence"))
59
+ throw new Error(`${prefix}.scope_evidence is required ${classified}.`);
60
+ if (record.acceptance_criteria_independent !== true) {
61
+ throw new Error(`${prefix}.acceptance_criteria_independent must be true for a non-blocking QA regression failure.`);
62
+ }
63
+ if (classification === "out_of_scope_failure") {
64
+ requireNonEmptyStringRecord(record, "repro_command", `${prefix}.`);
65
+ if (typeof record.repro_exit_code !== "number" || !Number.isFinite(record.repro_exit_code) || record.repro_exit_code === 0) {
66
+ throw new Error(`${prefix}.repro_exit_code must be a non-zero number for an out-of-scope failure.`);
67
+ }
68
+ return;
69
+ }
70
+ requireNonEmptyStringRecord(record, "baseline_ref", `${prefix}.`);
71
+ if (typeof record.baseline_exit_code !== "number" || !Number.isFinite(record.baseline_exit_code) || record.baseline_exit_code === 0) {
72
+ throw new Error(`${prefix}.baseline_exit_code must be a non-zero number for a baseline failure.`);
73
+ }
74
+ if (record.failure_signature_match !== true) {
75
+ throw new Error(`${prefix}.failure_signature_match must be true for a baseline failure.`);
76
+ }
77
+ }
@@ -29,6 +29,8 @@ export interface CompletionToolRuntimeOptions {
29
29
  readonly worktree: WorktreeHandle;
30
30
  readonly phase?: CompletionPhase;
31
31
  readonly runtimeEnvironment?: Readonly<Record<string, string>>;
32
+ /** Host load governor variables; only the MCP server receives them. */
33
+ readonly hostLoadEnvironment?: Readonly<Record<string, string>>;
32
34
  }
33
35
  export interface CompletionToolServerConfig {
34
36
  readonly worktreePath: string;
@@ -94,6 +96,8 @@ export declare const debugCompletionPhaseOrder: readonly DebugCompletionPhase[];
94
96
  export declare const qaCompletionGateOrder: readonly QaCompletionGate[];
95
97
  export declare const draftCompletionGateOrder: readonly DraftCompletionGate[];
96
98
  export declare const decomposeCompletionGateOrder: readonly DecomposeCompletionGate[];
99
+ export declare const draftStatuses: readonly ["pass", "needs_revision", "needs_rework", "blocked"];
100
+ export declare const decomposeStatuses: readonly ["pass", "needs_rework", "fail", "failed", "needs_revision", "blocked"];
97
101
  export declare const decomposeGateFileNames: Record<DecomposeCompletionGate, string>;
98
102
  export declare const decomposeGateToolNames: Record<DecomposeCompletionGate, string>;
99
103
  export declare const draftGateFileNames: Record<DraftCompletionGate, string>;