@loucompanion/forge-bridge 0.2.1-dev.4f11ffc822f9 → 0.2.1-dev.7171bf414613

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 (152) hide show
  1. package/README.md +41 -3
  2. package/dist/bridge/bridge-state-io.d.ts +6 -2
  3. package/dist/bridge/bridge-state-io.js +22 -4
  4. package/dist/bridge/bridge.service.d.ts +10 -0
  5. package/dist/bridge/bridge.service.js +63 -101
  6. package/dist/bridge/bridge.types.d.ts +16 -0
  7. package/dist/bridge/bridge.types.js +2 -1
  8. package/dist/bridge/default-session-service.d.ts +13 -0
  9. package/dist/bridge/default-session-service.js +22 -0
  10. package/dist/bridge/dispatch-offer-policy.d.ts +22 -0
  11. package/dist/bridge/dispatch-offer-policy.js +58 -0
  12. package/dist/bridge/runner-host-capabilities.js +14 -1
  13. package/dist/bridge/windows-bash-resolution.d.ts +31 -0
  14. package/dist/bridge/windows-bash-resolution.js +153 -0
  15. package/dist/cleanup/cleanup-wip.js +3 -3
  16. package/dist/cleanup/forge-owned-paths.d.ts +2 -0
  17. package/dist/cleanup/forge-owned-paths.js +9 -0
  18. package/dist/cli/cli.help.js +1 -1
  19. package/dist/cli/cli.service.js +11 -43
  20. package/dist/cli/local-config.d.ts +12 -1
  21. package/dist/cli/local-config.js +35 -1
  22. package/dist/cli/provider-cli-advertising.d.ts +24 -0
  23. package/dist/cli/provider-cli-advertising.js +88 -0
  24. package/dist/runtime/host-load-admission.d.ts +5 -0
  25. package/dist/runtime/host-load-capacity.d.ts +198 -0
  26. package/dist/runtime/host-load-capacity.js +353 -0
  27. package/dist/runtime/host-load-child-environment.d.ts +13 -0
  28. package/dist/runtime/host-load-child-environment.js +35 -1
  29. package/dist/runtime/host-load-governor-config.d.ts +33 -3
  30. package/dist/runtime/host-load-governor-config.js +24 -3
  31. package/dist/runtime/host-load-governor.d.ts +89 -2
  32. package/dist/runtime/host-load-governor.js +217 -18
  33. package/dist/runtime/host-load-live-test-slots.d.ts +61 -0
  34. package/dist/runtime/host-load-live-test-slots.js +193 -0
  35. package/dist/runtime/host-load-sampler.d.ts +17 -0
  36. package/dist/runtime/host-load-sampler.js +24 -0
  37. package/dist/runtime/host-load-step-run.d.ts +37 -3
  38. package/dist/runtime/host-load-step-run.js +63 -7
  39. package/dist/runtime/host-load-test-slot.d.ts +3 -0
  40. package/dist/runtime/host-load-test-slot.js +26 -7
  41. package/dist/runtime/host-runtime-contract.js +6 -4
  42. package/dist/runtime/prepared-runtime-readiness.d.ts +12 -2
  43. package/dist/runtime/prepared-runtime-readiness.js +35 -11
  44. package/dist/sandbox/runtime.d.ts +1 -2
  45. package/dist/sandbox/runtime.js +8 -14
  46. package/dist/sandbox/sandbox-input.d.ts +22 -0
  47. package/dist/sandbox/sandbox-input.js +49 -0
  48. package/dist/sandbox/workspace.service.js +15 -2
  49. package/dist/session/managed-attempt-tools.js +6 -29
  50. package/dist/session/managed-build-receipt.d.ts +3 -1
  51. package/dist/session/managed-build-receipt.js +5 -2
  52. package/dist/session/managed-command-environment.d.ts +8 -0
  53. package/dist/session/managed-command-environment.js +28 -0
  54. package/dist/session/managed-command-host-load.d.ts +10 -5
  55. package/dist/session/managed-command-host-load.js +18 -14
  56. package/dist/session/phase-completion.artifact-bundle.d.ts +20 -0
  57. package/dist/session/phase-completion.artifact-bundle.js +167 -0
  58. package/dist/session/phase-completion.artifacts.d.ts +2 -17
  59. package/dist/session/phase-completion.artifacts.js +63 -165
  60. package/dist/session/phase-completion.d.ts +25 -2
  61. package/dist/session/phase-completion.helpers.js +5 -53
  62. package/dist/session/phase-completion.js +15 -32
  63. package/dist/session/phase-completion.mcp-args.js +69 -2
  64. package/dist/session/phase-completion.phase-aliases.d.ts +5 -0
  65. package/dist/session/phase-completion.phase-aliases.js +43 -0
  66. package/dist/session/phase-completion.pr-review-schema.d.ts +1 -0
  67. package/dist/session/phase-completion.pr-review-schema.js +75 -0
  68. package/dist/session/phase-completion.pr-review-threads.d.ts +34 -0
  69. package/dist/session/phase-completion.pr-review-threads.js +90 -0
  70. package/dist/session/phase-completion.pr-review-validation.d.ts +11 -0
  71. package/dist/session/phase-completion.pr-review-validation.js +215 -0
  72. package/dist/session/phase-completion.pr-review.d.ts +36 -0
  73. package/dist/session/phase-completion.pr-review.js +294 -0
  74. package/dist/session/phase-completion.prompts.d.ts +1 -1
  75. package/dist/session/phase-completion.prompts.js +14 -0
  76. package/dist/session/phase-completion.runtime.js +9 -3
  77. package/dist/session/phase-completion.schemas.js +12 -2
  78. package/dist/session/phase-completion.validation.d.ts +1 -0
  79. package/dist/session/phase-completion.validation.js +9 -1
  80. package/dist/session/pr-review-diff-base.d.ts +18 -0
  81. package/dist/session/pr-review-diff-base.js +45 -0
  82. package/dist/session/pr-review-placement.d.ts +50 -0
  83. package/dist/session/pr-review-placement.js +91 -0
  84. package/dist/session/pre-publication-change-set.d.ts +62 -0
  85. package/dist/session/pre-publication-change-set.js +166 -0
  86. package/dist/session/pre-publication-host-load.js +6 -5
  87. package/dist/session/pre-publication-process.js +3 -2
  88. package/dist/session/pre-publication-validation.d.ts +2 -1
  89. package/dist/session/pre-publication-validation.js +31 -36
  90. package/dist/session/provider-cli/dispatch-target-branch.d.ts +7 -0
  91. package/dist/session/provider-cli/dispatch-target-branch.js +8 -0
  92. package/dist/session/provider-cli/pr-review-credential-isolation.d.ts +83 -0
  93. package/dist/session/provider-cli/pr-review-credential-isolation.js +144 -0
  94. package/dist/session/provider-cli/pr-review-guardrails.d.ts +70 -0
  95. package/dist/session/provider-cli/pr-review-guardrails.js +360 -0
  96. package/dist/session/provider-cli/pr-review-prompt.d.ts +11 -0
  97. package/dist/session/provider-cli/pr-review-prompt.js +132 -0
  98. package/dist/session/provider-cli/pre-publication-repair.js +8 -3
  99. package/dist/session/provider-cli/provider-cli.base.d.ts +1 -0
  100. package/dist/session/provider-cli/provider-cli.deterministic.d.ts +1 -0
  101. package/dist/session/provider-cli/provider-cli.deterministic.js +5 -0
  102. package/dist/session/provider-cli/provider-cli.merge-integrity.d.ts +6 -3
  103. package/dist/session/provider-cli/provider-cli.merge-integrity.js +29 -10
  104. package/dist/session/provider-cli/provider-cli.pr-review.d.ts +23 -0
  105. package/dist/session/provider-cli/provider-cli.pr-review.js +213 -0
  106. package/dist/session/provider-cli/provider-cli.prompts.d.ts +10 -3
  107. package/dist/session/provider-cli/provider-cli.prompts.js +123 -70
  108. package/dist/session/provider-cli/provider-cli.reapply-conflicts.d.ts +10 -0
  109. package/dist/session/provider-cli/provider-cli.reapply-conflicts.js +37 -0
  110. package/dist/session/provider-cli/provider-cli.runtime.d.ts +7 -0
  111. package/dist/session/provider-cli/provider-cli.runtime.js +14 -0
  112. package/dist/session/provider-cli/provider-cli.service-support.d.ts +37 -0
  113. package/dist/session/provider-cli/provider-cli.service-support.js +146 -0
  114. package/dist/session/provider-cli/provider-cli.service.d.ts +11 -17
  115. package/dist/session/provider-cli/provider-cli.service.js +33 -148
  116. package/dist/session/provider-cli/provider-cli.types.d.ts +7 -2
  117. package/dist/session/sandbox-host-capacity-gate.js +29 -7
  118. package/dist/session/session-host-project.d.ts +22 -0
  119. package/dist/session/session-host-project.js +98 -0
  120. package/dist/session/session.parse-helpers.d.ts +10 -0
  121. package/dist/session/session.parse-helpers.js +84 -0
  122. package/dist/session/session.runtime-refresh.d.ts +46 -0
  123. package/dist/session/session.runtime-refresh.js +116 -0
  124. package/dist/session/session.service.d.ts +2 -1
  125. package/dist/session/session.service.js +57 -158
  126. package/dist/session/session.types.d.ts +5 -0
  127. package/dist/session/session.types.js +8 -78
  128. package/dist/session/session.types.pr-review.d.ts +59 -0
  129. package/dist/session/session.types.pr-review.js +53 -0
  130. package/dist/shared/provider-capabilities.d.ts +2 -0
  131. package/dist/shared/provider-capabilities.js +9 -0
  132. package/dist/version.d.ts +1 -1
  133. package/dist/version.js +1 -1
  134. package/dist/worktree/artifact-injector.js +24 -0
  135. package/dist/worktree/wip-git.d.ts +25 -0
  136. package/dist/worktree/wip-git.js +64 -4
  137. package/dist/worktree/wip-refs.d.ts +23 -0
  138. package/dist/worktree/wip-refs.js +52 -2
  139. package/dist/worktree/wip-restore.d.ts +13 -0
  140. package/dist/worktree/wip-restore.js +159 -25
  141. package/dist/worktree/wip-snapshot.d.ts +5 -2
  142. package/dist/worktree/wip-snapshot.js +15 -13
  143. package/dist/worktree/worktree-origin-sync.d.ts +1 -0
  144. package/dist/worktree/worktree-origin-sync.js +1 -0
  145. package/dist/worktree/worktree-wip-events.d.ts +2 -0
  146. package/dist/worktree/worktree-wip-events.js +53 -3
  147. package/dist/worktree/worktree-wip.d.ts +7 -0
  148. package/dist/worktree/worktree-wip.js +17 -2
  149. package/dist/worktree/worktree.service.d.ts +23 -1
  150. package/dist/worktree/worktree.service.js +122 -15
  151. package/dist/worktree/worktree.types.d.ts +16 -0
  152. package/package.json +1 -1
@@ -13,7 +13,7 @@ import { attachManagedCommandProcess, ManagedCommandHostCapacity, } from "./mana
13
13
  import { HostCapacityLedgerUnavailableError } from "../runtime/host-load-ledger-lock.js";
14
14
  import { isProcessTreeTerminationUnproven } from "../shared/process/process.js";
15
15
  import { HostCapacityTokenFencedError } from "../runtime/host-load-token-ledger.js";
16
- import { withoutHostLoadGovernorVariables } from "../runtime/host-load-child-environment.js";
16
+ import { inheritedManagedCommandEnvironment } from "./managed-command-environment.js";
17
17
  import { managedBuildConfiguration, persistJsonAtomically, publishManagedBuildReceipt, verifyManagedBuildReceipt, } from "./managed-build-receipt.js";
18
18
  import { managedLongTierTimeoutMs, managedMaximumCommandTimeoutMs, managedVerificationTierTimeoutMs, } from "./managed-verification-timeouts.js";
19
19
  import { resolveWindowsCommandFromPath, StreamingProviderProcessRunner } from "./provider-cli/provider-cli.process.js";
@@ -512,7 +512,7 @@ async function executeManagedCommand(invocation) {
512
512
  let processStarted = false;
513
513
  // The per-worktree build slot is taken first: holding a host token while
514
514
  // queued behind this worktree's own build would waste host capacity.
515
- const hostCapacity = new ManagedCommandHostCapacity({ ...invocation, label: invocation.verificationProfile ?? invocation.commandId }, async (hostLoad) => await persistManagedCommandReceipt(invocation.receiptPath, managedCommandResult({
515
+ const hostCapacity = new ManagedCommandHostCapacity({ ...invocation, label: invocation.verificationProfile ?? invocation.commandId }, async (hostLoad, fence) => await persistManagedCommandReceipt(invocation.receiptPath, managedCommandResult({
516
516
  ...invocation,
517
517
  hostLoad,
518
518
  timedOut: false,
@@ -521,7 +521,7 @@ async function executeManagedCommand(invocation) {
521
521
  stdout: "",
522
522
  stderr: "",
523
523
  launchRequested: false,
524
- }).structuredContent));
524
+ }).structuredContent, async (replace) => await fence.commit(replace)));
525
525
  const launch = async (buildQueueWaitMs) => await hostCapacity.run(invocation.controller.signal, async (hostLoad, control) => {
526
526
  processStarted = true;
527
527
  // A reclaimed token means this command's capacity is gone: it stops. A fence that
@@ -604,7 +604,7 @@ async function managedCommandProcessEnvironment(invocation) {
604
604
  // The attempt's brokered database login reaches managed commands; their output never shows it.
605
605
  ...attemptDatabaseCapabilitySecrets(process.env[attemptDatabaseCapabilityEnvironment]),
606
606
  ];
607
- const environment = inheritedEnvironment({
607
+ const environment = inheritedManagedCommandEnvironment({
608
608
  FORGE_RUNTIME_MODE: "host",
609
609
  FORGE_RESOURCE_LEASE_ID: requiredAttemptEnvironment("FORGE_RESOURCE_LEASE_ID"),
610
610
  FORGE_DISPATCH_ATTEMPT_ID: requiredAttemptEnvironment("FORGE_DISPATCH_ATTEMPT_ID"),
@@ -942,8 +942,8 @@ async function waitManagedCommand(input) {
942
942
  function managedCommandReceiptPath(logDirectory, commandId) {
943
943
  return path.join(logDirectory, "managed-commands", `${commandId}.receipt.json`);
944
944
  }
945
- async function persistManagedCommandReceipt(receiptPath, receipt) {
946
- await persistJsonAtomically(receiptPath, receipt);
945
+ async function persistManagedCommandReceipt(receiptPath, receipt, commit) {
946
+ await persistJsonAtomically(receiptPath, receipt, commit);
947
947
  }
948
948
  function managedCommandResult(values) {
949
949
  // Governed commands count elapsed time from admission: queue time is host_load_wait_ms.
@@ -1098,17 +1098,6 @@ async function containedWorkingDirectory(worktreePath, input) {
1098
1098
  }
1099
1099
  return target;
1100
1100
  }
1101
- function inheritedEnvironment(overrides) {
1102
- const env = {};
1103
- // A nested Forge process must not join the host ledger: it would queue behind the
1104
- // token this command already holds. Every FORGE_HOST_LOAD_* variable is dropped,
1105
- // the test slot count too (decision 0018).
1106
- for (const [key, value] of Object.entries(withoutHostLoadGovernorVariables(process.env))) {
1107
- if (typeof value === "string" && !looksSensitiveEnvironmentName(key))
1108
- env[key] = value;
1109
- }
1110
- return { ...env, ...overrides };
1111
- }
1112
1101
  export function isBuildProducingManagedCommand(command, args) {
1113
1102
  const executable = path.basename(command).toLowerCase();
1114
1103
  if (executable === "dotnet" || executable === "dotnet.exe") {
@@ -1152,18 +1141,6 @@ function managedBuildReceiptCoverage(invocation) {
1152
1141
  }
1153
1142
  return null;
1154
1143
  }
1155
- function looksSensitiveEnvironmentName(name) {
1156
- const normalized = name.trim().toUpperCase();
1157
- return normalized.includes("SECRET")
1158
- || normalized.includes("TOKEN")
1159
- || normalized.includes("PASSWORD")
1160
- || normalized.includes("CREDENTIAL")
1161
- || normalized.includes("CONNECTION_STRING")
1162
- || normalized.startsWith("CONNECTIONSTRINGS__")
1163
- || normalized.startsWith("CONNECTIONSTRINGS:")
1164
- || normalized.endsWith("_API_KEY")
1165
- || normalized === "OPENAI_API_KEY";
1166
- }
1167
1144
  function requiredAttemptEnvironment(name) {
1168
1145
  const value = process.env[name]?.trim();
1169
1146
  if (!value)
@@ -22,5 +22,7 @@ export declare function managedBuildConfiguration(command: string, args: readonl
22
22
  /**
23
23
  * Writes a JSON receipt by replacing the whole file. Agents and Forge poll receipts, and on
24
24
  * Windows a poll that has one open refuses the replace: that delays a write, never fails it.
25
+ * `commit`, when given, runs the final replace and may skip it (a write that went stale while
26
+ * it was being prepared); the receipt is then left as it was.
25
27
  */
26
- export declare function persistJsonAtomically(receiptPath: string, value: unknown): Promise<void>;
28
+ export declare function persistJsonAtomically(receiptPath: string, value: unknown, commit?: (replace: () => Promise<void>) => Promise<unknown>): Promise<void>;
@@ -275,12 +275,15 @@ async function persistImmutableReceipt(receiptPath, receipt) {
275
275
  /**
276
276
  * Writes a JSON receipt by replacing the whole file. Agents and Forge poll receipts, and on
277
277
  * Windows a poll that has one open refuses the replace: that delays a write, never fails it.
278
+ * `commit`, when given, runs the final replace and may skip it (a write that went stale while
279
+ * it was being prepared); the receipt is then left as it was.
278
280
  */
279
- export async function persistJsonAtomically(receiptPath, value) {
281
+ export async function persistJsonAtomically(receiptPath, value, commit) {
280
282
  const temporaryPath = `${receiptPath}.${randomUUID()}.tmp`;
281
283
  await fs.writeFile(temporaryPath, `${JSON.stringify(value, null, 2)}\n`, { encoding: "utf8", mode: 0o600 });
282
284
  try {
283
- await replaceFile(temporaryPath, receiptPath);
285
+ const replace = async () => await replaceFile(temporaryPath, receiptPath);
286
+ await (commit ? commit(replace) : replace());
284
287
  }
285
288
  finally {
286
289
  await fs.rm(temporaryPath, { force: true }).catch(() => undefined);
@@ -0,0 +1,8 @@
1
+ /**
2
+ * The environment a managed command runs with: the bridge's own, without secrets and without
3
+ * the host load governor, plus the command's overrides. A nested Forge process must not join
4
+ * the host ledger: it would queue behind the token this command already holds, so every
5
+ * FORGE_HOST_LOAD_* variable is dropped, the test slot count too (decision 0018). A heavy
6
+ * command that shares the host with other heavy steps sizes its test parallelism for its share.
7
+ */
8
+ export declare function inheritedManagedCommandEnvironment(overrides: Readonly<Record<string, string>>, source?: Readonly<Record<string, string | undefined>>): Readonly<Record<string, string>>;
@@ -0,0 +1,28 @@
1
+ import { withHostTestParallelism, withoutHostLoadGovernorVariables } from "../runtime/host-load-child-environment.js";
2
+ /**
3
+ * The environment a managed command runs with: the bridge's own, without secrets and without
4
+ * the host load governor, plus the command's overrides. A nested Forge process must not join
5
+ * the host ledger: it would queue behind the token this command already holds, so every
6
+ * FORGE_HOST_LOAD_* variable is dropped, the test slot count too (decision 0018). A heavy
7
+ * command that shares the host with other heavy steps sizes its test parallelism for its share.
8
+ */
9
+ export function inheritedManagedCommandEnvironment(overrides, source = process.env) {
10
+ const env = {};
11
+ for (const [key, value] of Object.entries(withoutHostLoadGovernorVariables(source))) {
12
+ if (typeof value === "string" && !looksSensitiveEnvironmentName(key))
13
+ env[key] = value;
14
+ }
15
+ return withHostTestParallelism({ ...env, ...overrides });
16
+ }
17
+ function looksSensitiveEnvironmentName(name) {
18
+ const normalized = name.trim().toUpperCase();
19
+ return normalized.includes("SECRET")
20
+ || normalized.includes("TOKEN")
21
+ || normalized.includes("PASSWORD")
22
+ || normalized.includes("CREDENTIAL")
23
+ || normalized.includes("CONNECTION_STRING")
24
+ || normalized.startsWith("CONNECTIONSTRINGS__")
25
+ || normalized.startsWith("CONNECTIONSTRINGS:")
26
+ || normalized.endsWith("_API_KEY")
27
+ || normalized === "OPENAI_API_KEY";
28
+ }
@@ -1,6 +1,6 @@
1
1
  import { type HostLoadStepGate } from "../runtime/host-load-governor.js";
2
2
  import { type HostLoadStepClassification, type ManagedCommandStepInput } from "../runtime/host-load-step-class.js";
3
- import { type HostLoadStepControl } from "../runtime/host-load-step-run.js";
3
+ import { type HostLoadStepControl, type WaitReportFence } from "../runtime/host-load-step-run.js";
4
4
  /** Host-load facts a managed command receipt carries; absent while the governor is off. */
5
5
  export interface ManagedCommandHostLoadFields {
6
6
  readonly stepClass: string;
@@ -19,8 +19,13 @@ export declare function managedCommandHostLoadGate(): HostLoadStepGate | undefin
19
19
  export declare function setManagedCommandHostLoadGateForTesting(value: HostLoadStepGate | undefined | null): void;
20
20
  /**
21
21
  * Admits one managed command. The waiting receipt is written while the command
22
- * is queued and always lands before the launch receipts, so a stale "waiting"
23
- * write can never replace a later status.
22
+ * is queued, and rewritten whenever the wait changes (a new slot holder, say).
23
+ * The writes run in order and land before the launch receipts, so a stale
24
+ * "waiting" write can never replace a later status or a newer wait. A write
25
+ * that never settles holds the launch (with its token) or the terminal receipt
26
+ * back only for the governor's drain bound; writes still queued after it are
27
+ * dropped as stale, and one still running can no longer replace the receipt
28
+ * (orderedWaitReports, WaitReportFence).
24
29
  */
25
30
  export declare class ManagedCommandHostCapacity {
26
31
  private readonly persistWaiting;
@@ -28,10 +33,10 @@ export declare class ManagedCommandHostCapacity {
28
33
  readonly classification: HostLoadStepClassification;
29
34
  private readonly label;
30
35
  private requestedAtMs;
31
- private waitingWrite;
36
+ private readonly waitingWrites;
32
37
  constructor(input: ManagedCommandStepInput & {
33
38
  readonly label: string;
34
- }, persistWaiting: (fields: ManagedCommandHostLoadFields) => Promise<void>, gateFor?: () => HostLoadStepGate | undefined);
39
+ }, persistWaiting: (fields: ManagedCommandHostLoadFields, fence: WaitReportFence) => Promise<void>, gateFor?: () => HostLoadStepGate | undefined);
35
40
  /** Runs `launch` once admitted; `fields` is undefined with the governor off. */
36
41
  run<T>(signal: AbortSignal, launch: (fields: ManagedCommandHostLoadFields | undefined, control: HostLoadStepControl) => Promise<T>, onReleaseFailed?: (error: unknown) => Promise<void>): Promise<T>;
37
42
  /**
@@ -1,7 +1,7 @@
1
1
  import { hostLoadGovernorFromChildEnvironment } from "../runtime/host-load-child-environment.js";
2
2
  import { HostCapacityTimeoutError } from "../runtime/host-load-governor.js";
3
3
  import { classifyManagedCommand } from "../runtime/host-load-step-class.js";
4
- import { attachSupervisedStepProcess, runHostGovernedStep } from "../runtime/host-load-step-run.js";
4
+ import { attachSupervisedStepProcess, orderedWaitReports, runHostGovernedStep, } from "../runtime/host-load-step-run.js";
5
5
  let gate = null;
6
6
  /** This MCP server's governor, built once from the environment the bridge handed it. */
7
7
  export function managedCommandHostLoadGate() {
@@ -15,8 +15,13 @@ export function setManagedCommandHostLoadGateForTesting(value) {
15
15
  }
16
16
  /**
17
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.
18
+ * is queued, and rewritten whenever the wait changes (a new slot holder, say).
19
+ * The writes run in order and land before the launch receipts, so a stale
20
+ * "waiting" write can never replace a later status or a newer wait. A write
21
+ * that never settles holds the launch (with its token) or the terminal receipt
22
+ * back only for the governor's drain bound; writes still queued after it are
23
+ * dropped as stale, and one still running can no longer replace the receipt
24
+ * (orderedWaitReports, WaitReportFence).
20
25
  */
21
26
  export class ManagedCommandHostCapacity {
22
27
  persistWaiting;
@@ -24,12 +29,18 @@ export class ManagedCommandHostCapacity {
24
29
  classification;
25
30
  label;
26
31
  requestedAtMs = null;
27
- waitingWrite = Promise.resolve();
32
+ waitingWrites;
28
33
  constructor(input, persistWaiting, gateFor = managedCommandHostLoadGate) {
29
34
  this.persistWaiting = persistWaiting;
30
35
  this.gateFor = gateFor;
31
36
  this.classification = classifyManagedCommand(input);
32
37
  this.label = input.label;
38
+ this.waitingWrites = orderedWaitReports(async (decision, fence) => await this.persistWaiting({
39
+ stepClass: this.classification.stepClass,
40
+ waitMs: 0,
41
+ waitStartedAt: this.requestedAtMs ?? Date.now(),
42
+ waitDetail: decision.detail,
43
+ }, fence));
33
44
  }
34
45
  /** Runs `launch` once admitted; `fields` is undefined with the governor off. */
35
46
  async run(signal, launch, onReleaseFailed) {
@@ -45,17 +56,10 @@ export class ManagedCommandHostCapacity {
45
56
  signal,
46
57
  // The receipt says host_capacity_token_fenced itself (termination_reason).
47
58
  reportsOwnFence: true,
48
- onWaiting: decision => {
49
- this.waitingWrite = this.persistWaiting({
50
- stepClass: this.classification.stepClass,
51
- waitMs: 0,
52
- waitStartedAt: this.requestedAtMs ?? Date.now(),
53
- waitDetail: decision.detail,
54
- }).catch(() => undefined);
55
- },
59
+ onWaiting: this.waitingWrites.onWaiting,
56
60
  onReleaseFailed,
57
61
  }, async (waitMs, control) => {
58
- await this.waitingWrite;
62
+ await this.waitingWrites.drained();
59
63
  // The launch timer and timeout_ms start inside `launch`, after admission.
60
64
  return await launch(waitMs === null
61
65
  ? undefined
@@ -67,7 +71,7 @@ export class ManagedCommandHostCapacity {
67
71
  * the queue or was stopped while waiting), once its waiting receipt landed.
68
72
  */
69
73
  async unadmittedFields(error) {
70
- await this.waitingWrite;
74
+ await this.waitingWrites.drained();
71
75
  if (this.requestedAtMs === null)
72
76
  return undefined;
73
77
  const waitMs = error instanceof HostCapacityTimeoutError ? error.waitMs : Date.now() - this.requestedAtMs;
@@ -0,0 +1,20 @@
1
+ export interface ArtifactBundleFile {
2
+ readonly fileName: string;
3
+ readonly content: string;
4
+ }
5
+ export interface ArtifactBundlePublicationOptions {
6
+ readonly signal?: AbortSignal;
7
+ /** Fault-injection hook used by publication tests. */
8
+ readonly beforePublishFile?: (fileName: string, index: number) => void | Promise<void>;
9
+ }
10
+ /**
11
+ * Stages a complete phase bundle outside the live artifact directory, then
12
+ * publishes its canonical verdict/marker last. Consumers treat the marker as
13
+ * the bundle's commit point, so they can observe either the old complete bundle
14
+ * or the new complete bundle, never a partially written set. A failed or
15
+ * cancelled publication rolls every touched file back before rejecting.
16
+ */
17
+ export declare function publishArtifactBundleAtomic(artifactRoot: string, files: readonly ArtifactBundleFile[], commitFileName: string, options?: ArtifactBundlePublicationOptions): Promise<void>;
18
+ export declare function validatePostRedaction(validate: () => void): void;
19
+ export declare function postRedactionValidationError(error: unknown): Error;
20
+ export declare function assertStructuralFieldsUnchanged(original: Record<string, unknown>, redacted: Record<string, unknown>): void;
@@ -0,0 +1,167 @@
1
+ import crypto from "node:crypto";
2
+ import fs from "node:fs/promises";
3
+ import path from "node:path";
4
+ import { isNodeError, stableStringify } from "./phase-completion.validation.js";
5
+ /**
6
+ * Stages a complete phase bundle outside the live artifact directory, then
7
+ * publishes its canonical verdict/marker last. Consumers treat the marker as
8
+ * the bundle's commit point, so they can observe either the old complete bundle
9
+ * or the new complete bundle, never a partially written set. A failed or
10
+ * cancelled publication rolls every touched file back before rejecting.
11
+ */
12
+ export async function publishArtifactBundleAtomic(artifactRoot, files, commitFileName, options = {}) {
13
+ validateArtifactBundleFiles(files, commitFileName);
14
+ throwIfPublicationCancelled(options.signal);
15
+ const parent = path.dirname(artifactRoot);
16
+ const transactionId = `${process.pid}.${crypto.randomUUID()}`;
17
+ const stagingRoot = path.join(parent, `.${path.basename(artifactRoot)}.${transactionId}.publish`);
18
+ const backupRoot = path.join(stagingRoot, ".previous");
19
+ const orderedFiles = [
20
+ ...files.filter((file) => file.fileName !== commitFileName),
21
+ files.find((file) => file.fileName === commitFileName)
22
+ ];
23
+ const backedUp = new Set();
24
+ const published = new Set();
25
+ try {
26
+ await fs.mkdir(parent, { recursive: true });
27
+ await fs.mkdir(stagingRoot, { recursive: false });
28
+ for (const file of orderedFiles) {
29
+ throwIfPublicationCancelled(options.signal);
30
+ const handle = await fs.open(path.join(stagingRoot, file.fileName), "wx");
31
+ try {
32
+ await handle.writeFile(file.content, { encoding: "utf8", signal: options.signal });
33
+ await handle.sync();
34
+ }
35
+ finally {
36
+ await handle.close();
37
+ }
38
+ }
39
+ throwIfPublicationCancelled(options.signal);
40
+ await fs.mkdir(artifactRoot, { recursive: true });
41
+ await fs.mkdir(backupRoot, { recursive: true });
42
+ // Hide the previous commit marker before changing any supporting file.
43
+ for (const fileName of [commitFileName, ...orderedFiles.map((file) => file.fileName).filter((name) => name !== commitFileName)]) {
44
+ const livePath = path.join(artifactRoot, fileName);
45
+ try {
46
+ await fs.rename(livePath, path.join(backupRoot, fileName));
47
+ backedUp.add(fileName);
48
+ }
49
+ catch (error) {
50
+ if (!isNodeError(error) || error.code !== "ENOENT") {
51
+ throw error;
52
+ }
53
+ }
54
+ }
55
+ for (const [index, file] of orderedFiles.entries()) {
56
+ throwIfPublicationCancelled(options.signal);
57
+ await options.beforePublishFile?.(file.fileName, index);
58
+ await fs.rename(path.join(stagingRoot, file.fileName), path.join(artifactRoot, file.fileName));
59
+ published.add(file.fileName);
60
+ }
61
+ }
62
+ catch (error) {
63
+ const rollbackErrors = [];
64
+ for (const file of [...orderedFiles].reverse()) {
65
+ if (!published.has(file.fileName))
66
+ continue;
67
+ await fs.rm(path.join(artifactRoot, file.fileName), { force: true }).catch(() => {
68
+ rollbackErrors.push(file.fileName);
69
+ });
70
+ }
71
+ // Restore the previous marker last for the same observable commit boundary.
72
+ const restoreOrder = [
73
+ ...orderedFiles.filter((file) => file.fileName !== commitFileName),
74
+ orderedFiles.find((file) => file.fileName === commitFileName)
75
+ ];
76
+ for (const file of restoreOrder) {
77
+ if (!backedUp.has(file.fileName))
78
+ continue;
79
+ await fs.rename(path.join(backupRoot, file.fileName), path.join(artifactRoot, file.fileName)).catch(() => {
80
+ rollbackErrors.push(file.fileName);
81
+ });
82
+ }
83
+ if (rollbackErrors.length === 0
84
+ && error instanceof Error
85
+ && error.message.startsWith("artifact_atomic_publish_cancelled:")) {
86
+ throw error;
87
+ }
88
+ const suffix = rollbackErrors.length > 0 ? " Rollback did not restore every bundle file." : "";
89
+ throw new Error(`artifact_atomic_publish_failure: completion artifact bundle was not published.${suffix}`, { cause: error });
90
+ }
91
+ finally {
92
+ await fs.rm(stagingRoot, { recursive: true, force: true }).catch(() => undefined);
93
+ }
94
+ }
95
+ function validateArtifactBundleFiles(files, commitFileName) {
96
+ if (files.length === 0 || !files.some((file) => file.fileName === commitFileName)) {
97
+ throw new Error("artifact_atomic_publish_failure: bundle commit file is missing.");
98
+ }
99
+ const names = new Set();
100
+ for (const file of files) {
101
+ if (!file.fileName || path.basename(file.fileName) !== file.fileName || names.has(file.fileName)) {
102
+ throw new Error("artifact_atomic_publish_failure: bundle file names must be unique safe base names.");
103
+ }
104
+ names.add(file.fileName);
105
+ }
106
+ }
107
+ function throwIfPublicationCancelled(signal) {
108
+ if (signal?.aborted) {
109
+ throw new Error("artifact_atomic_publish_cancelled: completion artifact bundle publication was cancelled.");
110
+ }
111
+ }
112
+ export function validatePostRedaction(validate) {
113
+ try {
114
+ validate();
115
+ }
116
+ catch (error) {
117
+ throw postRedactionValidationError(error);
118
+ }
119
+ }
120
+ export function postRedactionValidationError(error) {
121
+ const message = error instanceof Error ? error.message : String(error);
122
+ return new Error(`artifact_post_redaction_validation_failed: ${message}`, { cause: error });
123
+ }
124
+ export function assertStructuralFieldsUnchanged(original, redacted) {
125
+ if (structuralFieldFingerprint(original) !== structuralFieldFingerprint(redacted)) {
126
+ // This stable code is intentionally safe for telemetry: it does not include
127
+ // the structural value or any candidate secret.
128
+ throw new Error("artifact_redaction_changed_structural_field: redaction changed a structural identifier; the bundle was not published.");
129
+ }
130
+ }
131
+ function structuralFieldFingerprint(value, key = "", result = []) {
132
+ if (Array.isArray(value)) {
133
+ if (isStructuralFieldKey(key) && value.every((item) => item === null || typeof item !== "object")) {
134
+ result.push(stableStringify(value));
135
+ }
136
+ else {
137
+ for (const item of value)
138
+ structuralFieldFingerprint(item, key, result);
139
+ }
140
+ return result.join("\n");
141
+ }
142
+ if (!value || typeof value !== "object") {
143
+ if (isStructuralFieldKey(key))
144
+ result.push(stableStringify(value));
145
+ return result.join("\n");
146
+ }
147
+ for (const [childKey, child] of Object.entries(value)) {
148
+ if (isStructuralFieldKey(childKey)) {
149
+ result.push(`${childKey}:${stableStringify(child)}`);
150
+ }
151
+ else {
152
+ structuralFieldFingerprint(child, childKey, result);
153
+ }
154
+ }
155
+ return result.join("\n");
156
+ }
157
+ function isStructuralFieldKey(key) {
158
+ return key === "id"
159
+ || key === "before"
160
+ || key === "after"
161
+ || key === "from"
162
+ || key === "to"
163
+ || key === "tasks"
164
+ || key === "phases"
165
+ || /(?:^|_)(?:id|ids)$/i.test(key)
166
+ || /(?:Id|Ids)$/.test(key);
167
+ }
@@ -15,20 +15,5 @@ export declare function writeQaGateCompletionArtifact(config: CompletionToolServ
15
15
  export declare function writeQaCompletionArtifact(config: CompletionToolServerConfig, payload: Record<string, unknown>, status: string, producedBy: string): Promise<CompletionArtifactReference>;
16
16
  export declare function readQaGateArtifact(config: CompletionToolServerConfig, gate: QaCompletionGate): Promise<Record<string, unknown>>;
17
17
  export declare function readCompletionArtifact(worktreePath: string, workItemId: string, phase: CompletionPhase, ownerType?: string | null, ownerId?: string | null): Promise<RunnerDispatchArtifact | null>;
18
- export interface ArtifactBundleFile {
19
- readonly fileName: string;
20
- readonly content: string;
21
- }
22
- export interface ArtifactBundlePublicationOptions {
23
- readonly signal?: AbortSignal;
24
- /** Fault-injection hook used by publication tests. */
25
- readonly beforePublishFile?: (fileName: string, index: number) => void | Promise<void>;
26
- }
27
- /**
28
- * Stages a complete phase bundle outside the live artifact directory, then
29
- * publishes its canonical verdict/marker last. Consumers treat the marker as
30
- * the bundle's commit point, so they can observe either the old complete bundle
31
- * or the new complete bundle, never a partially written set. A failed or
32
- * cancelled publication rolls every touched file back before rejecting.
33
- */
34
- export declare function publishArtifactBundleAtomic(artifactRoot: string, files: readonly ArtifactBundleFile[], commitFileName: string, options?: ArtifactBundlePublicationOptions): Promise<void>;
18
+ export { publishArtifactBundleAtomic } from "./phase-completion.artifact-bundle.js";
19
+ export type { ArtifactBundleFile, ArtifactBundlePublicationOptions } from "./phase-completion.artifact-bundle.js";