@loucompanion/forge-bridge 0.1.3-dev.fbe15023cdfe → 0.1.4-dev.03584818ede5

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 (275) hide show
  1. package/README.md +146 -5
  2. package/dist/bridge/bridge-chat-provider-command.d.ts +16 -0
  3. package/dist/bridge/bridge-chat-provider-command.js +137 -0
  4. package/dist/bridge/bridge-chat.types.d.ts +121 -0
  5. package/dist/bridge/bridge-chat.types.js +416 -0
  6. package/dist/bridge/bridge.base.d.ts +13 -1
  7. package/dist/bridge/bridge.service.d.ts +155 -4
  8. package/dist/bridge/bridge.service.js +1805 -155
  9. package/dist/bridge/bridge.types.d.ts +68 -1
  10. package/dist/bridge/dispatch-result-outbox.d.ts +35 -0
  11. package/dist/bridge/dispatch-result-outbox.js +87 -0
  12. package/dist/bridge/dispatch-result-worker.d.ts +2 -0
  13. package/dist/bridge/dispatch-result-worker.js +122 -0
  14. package/dist/bridge/internals.d.ts +2 -0
  15. package/dist/bridge/internals.js +1 -0
  16. package/dist/bridge/local-yield-flag.d.ts +6 -0
  17. package/dist/bridge/local-yield-flag.js +34 -0
  18. package/dist/bridge/readiness-result-outbox.d.ts +21 -0
  19. package/dist/bridge/readiness-result-outbox.js +54 -0
  20. package/dist/bridge/readiness-result-worker.d.ts +2 -0
  21. package/dist/bridge/readiness-result-worker.js +121 -0
  22. package/dist/bridge/runner-host-capabilities.d.ts +20 -0
  23. package/dist/bridge/runner-host-capabilities.js +110 -0
  24. package/dist/bridge/test-postgres-capability.d.ts +14 -0
  25. package/dist/bridge/test-postgres-capability.js +120 -0
  26. package/dist/cleanup/cleanup.service.d.ts +10 -0
  27. package/dist/cleanup/cleanup.service.js +128 -104
  28. package/dist/cleanup/cleanup.types.d.ts +4 -0
  29. package/dist/cleanup/forge-owned-paths.d.ts +9 -0
  30. package/dist/cleanup/forge-owned-paths.js +53 -0
  31. package/dist/cleanup/host-runtime-ledger.d.ts +5 -0
  32. package/dist/cleanup/host-runtime-ledger.js +109 -0
  33. package/dist/cleanup/managed-branch-sweep.d.ts +27 -0
  34. package/dist/cleanup/managed-branch-sweep.js +111 -0
  35. package/dist/cli/cli.help.js +22 -4
  36. package/dist/cli/cli.service.d.ts +30 -6
  37. package/dist/cli/cli.service.js +216 -31
  38. package/dist/cli/local-config.d.ts +5 -0
  39. package/dist/cli/local-config.js +30 -4
  40. package/dist/runtime/aspnet-runtime-prebuild.d.ts +36 -0
  41. package/dist/runtime/aspnet-runtime-prebuild.js +429 -0
  42. package/dist/runtime/attempt-database-broker.d.ts +89 -0
  43. package/dist/runtime/attempt-database-broker.js +390 -0
  44. package/dist/runtime/attempt-node-runtime-launcher.d.ts +2 -1
  45. package/dist/runtime/attempt-node-runtime-launcher.js +57 -18
  46. package/dist/runtime/attempt-path-operation.d.ts +21 -0
  47. package/dist/runtime/attempt-path-operation.js +94 -0
  48. package/dist/runtime/attempt-private-directory.d.ts +6 -0
  49. package/dist/runtime/attempt-private-directory.js +54 -0
  50. package/dist/runtime/attempt-process-supervisor.d.ts +35 -0
  51. package/dist/runtime/attempt-process-supervisor.js +144 -23
  52. package/dist/runtime/canonical-source-file.d.ts +3 -0
  53. package/dist/runtime/canonical-source-file.js +54 -0
  54. package/dist/runtime/docker-engine-probe.d.ts +90 -0
  55. package/dist/runtime/docker-engine-probe.js +333 -0
  56. package/dist/runtime/generated-output-reset.d.ts +10 -0
  57. package/dist/runtime/generated-output-reset.js +62 -8
  58. package/dist/runtime/host-database-capability-boundary.d.ts +16 -0
  59. package/dist/runtime/host-database-capability-boundary.js +63 -0
  60. package/dist/runtime/host-diagnostics.d.ts +11 -0
  61. package/dist/runtime/host-diagnostics.js +192 -0
  62. package/dist/runtime/host-execution-root.d.ts +4 -0
  63. package/dist/runtime/host-execution-root.js +39 -0
  64. package/dist/runtime/host-facts.d.ts +36 -0
  65. package/dist/runtime/host-facts.js +95 -0
  66. package/dist/runtime/host-listener-inspector.d.ts +8 -1
  67. package/dist/runtime/host-listener-inspector.js +121 -60
  68. package/dist/runtime/host-load-admission.d.ts +67 -0
  69. package/dist/runtime/host-load-admission.js +99 -0
  70. package/dist/runtime/host-load-child-environment.d.ts +27 -0
  71. package/dist/runtime/host-load-child-environment.js +76 -0
  72. package/dist/runtime/host-load-forge-cgroups.d.ts +49 -0
  73. package/dist/runtime/host-load-forge-cgroups.js +140 -0
  74. package/dist/runtime/host-load-governor-config.d.ts +52 -0
  75. package/dist/runtime/host-load-governor-config.js +83 -0
  76. package/dist/runtime/host-load-governor.d.ts +184 -0
  77. package/dist/runtime/host-load-governor.js +632 -0
  78. package/dist/runtime/host-load-ledger-lock.d.ts +69 -0
  79. package/dist/runtime/host-load-ledger-lock.js +185 -0
  80. package/dist/runtime/host-load-runtime-settings.d.ts +25 -0
  81. package/dist/runtime/host-load-runtime-settings.js +78 -0
  82. package/dist/runtime/host-load-sampler.d.ts +149 -0
  83. package/dist/runtime/host-load-sampler.js +291 -0
  84. package/dist/runtime/host-load-step-class.d.ts +70 -0
  85. package/dist/runtime/host-load-step-class.js +161 -0
  86. package/dist/runtime/host-load-step-reaper.d.ts +27 -0
  87. package/dist/runtime/host-load-step-reaper.js +95 -0
  88. package/dist/runtime/host-load-step-run.d.ts +73 -0
  89. package/dist/runtime/host-load-step-run.js +102 -0
  90. package/dist/runtime/host-load-test-slot.d.ts +43 -0
  91. package/dist/runtime/host-load-test-slot.js +81 -0
  92. package/dist/runtime/host-load-token-ledger.d.ts +200 -0
  93. package/dist/runtime/host-load-token-ledger.js +453 -0
  94. package/dist/runtime/host-load-windows-cpu.d.ts +34 -0
  95. package/dist/runtime/host-load-windows-cpu.js +85 -0
  96. package/dist/runtime/host-pressure-stall.d.ts +61 -0
  97. package/dist/runtime/host-pressure-stall.js +168 -0
  98. package/dist/runtime/host-runtime-contract.d.ts +16 -1
  99. package/dist/runtime/host-runtime-contract.js +174 -56
  100. package/dist/runtime/host-runtime-lease.d.ts +163 -9
  101. package/dist/runtime/host-runtime-lease.js +1464 -121
  102. package/dist/runtime/host-runtime-promotion.d.ts +35 -3
  103. package/dist/runtime/host-runtime-promotion.js +107 -12
  104. package/dist/runtime/host-runtime-requirements-check.d.ts +17 -0
  105. package/dist/runtime/host-runtime-requirements-check.js +29 -0
  106. package/dist/runtime/host-runtime-requirements.d.ts +36 -0
  107. package/dist/runtime/host-runtime-requirements.js +117 -0
  108. package/dist/runtime/managed-command-teardown.d.ts +62 -0
  109. package/dist/runtime/managed-command-teardown.js +607 -0
  110. package/dist/runtime/memory-capacity.d.ts +70 -0
  111. package/dist/runtime/memory-capacity.js +123 -0
  112. package/dist/runtime/native-test-postgres-fallback.d.ts +25 -0
  113. package/dist/runtime/native-test-postgres-fallback.js +91 -0
  114. package/dist/runtime/node-host-runtime-adapter.d.ts +3 -0
  115. package/dist/runtime/node-host-runtime-adapter.js +29 -11
  116. package/dist/runtime/pinned-directory-process.d.ts +9 -0
  117. package/dist/runtime/pinned-directory-process.js +61 -0
  118. package/dist/runtime/pinned-source-directory.d.ts +17 -0
  119. package/dist/runtime/pinned-source-directory.js +94 -0
  120. package/dist/runtime/playwright-browser-cache.d.ts +39 -0
  121. package/dist/runtime/playwright-browser-cache.js +227 -0
  122. package/dist/runtime/playwright-host-runtime-adapter.d.ts +19 -0
  123. package/dist/runtime/playwright-host-runtime-adapter.js +113 -59
  124. package/dist/runtime/prepared-runtime-identity.d.ts +6 -0
  125. package/dist/runtime/prepared-runtime-identity.js +218 -0
  126. package/dist/runtime/prepared-runtime-readiness.d.ts +30 -0
  127. package/dist/runtime/prepared-runtime-readiness.js +285 -0
  128. package/dist/runtime/runner-settings.d.ts +100 -0
  129. package/dist/runtime/runner-settings.js +214 -0
  130. package/dist/runtime/runtime-isolation-lease.js +4 -1
  131. package/dist/runtime/workspace-resource-estimator.d.ts +17 -0
  132. package/dist/runtime/workspace-resource-estimator.js +174 -0
  133. package/dist/sandbox/host-capacity-broker.d.ts +113 -0
  134. package/dist/sandbox/host-capacity-broker.js +334 -0
  135. package/dist/sandbox/preflight.d.ts +31 -1
  136. package/dist/sandbox/preflight.js +237 -51
  137. package/dist/sandbox/repository-lock.d.ts +2 -1
  138. package/dist/sandbox/repository-lock.js +19 -9
  139. package/dist/sandbox/runtime.d.ts +16 -2
  140. package/dist/sandbox/runtime.js +182 -109
  141. package/dist/sandbox/sandbox-cgroups.d.ts +14 -0
  142. package/dist/sandbox/sandbox-cgroups.js +42 -0
  143. package/dist/sandbox/sandbox.types.d.ts +7 -0
  144. package/dist/sandbox/workspace.service.js +2 -0
  145. package/dist/session/architect-waits.d.ts +2 -0
  146. package/dist/session/architect-waits.js +138 -0
  147. package/dist/session/managed-attempt-tools.d.ts +44 -1
  148. package/dist/session/managed-attempt-tools.js +816 -46
  149. package/dist/session/managed-build-coordinator.d.ts +5 -0
  150. package/dist/session/managed-build-coordinator.js +109 -0
  151. package/dist/session/managed-build-receipt.d.ts +21 -0
  152. package/dist/session/managed-build-receipt.js +337 -0
  153. package/dist/session/managed-command-host-load.d.ts +47 -0
  154. package/dist/session/managed-command-host-load.js +83 -0
  155. package/dist/session/managed-verification-timeouts.d.ts +8 -0
  156. package/dist/session/managed-verification-timeouts.js +17 -0
  157. package/dist/session/mcp-argument-coercion.d.ts +23 -0
  158. package/dist/session/mcp-argument-coercion.js +121 -0
  159. package/dist/session/phase-completion.artifacts.d.ts +24 -0
  160. package/dist/session/phase-completion.artifacts.js +319 -44
  161. package/dist/session/phase-completion.command-validation.d.ts +7 -0
  162. package/dist/session/phase-completion.command-validation.js +77 -0
  163. package/dist/session/phase-completion.d.ts +15 -1
  164. package/dist/session/phase-completion.helpers.d.ts +5 -0
  165. package/dist/session/phase-completion.helpers.js +43 -19
  166. package/dist/session/phase-completion.js +18 -3
  167. package/dist/session/phase-completion.prompts.js +22 -18
  168. package/dist/session/phase-completion.runtime.d.ts +6 -2
  169. package/dist/session/phase-completion.runtime.js +191 -47
  170. package/dist/session/phase-completion.schema-parts.d.ts +19 -0
  171. package/dist/session/phase-completion.schema-parts.js +188 -0
  172. package/dist/session/phase-completion.schemas.d.ts +3 -3
  173. package/dist/session/phase-completion.schemas.js +250 -226
  174. package/dist/session/phase-completion.validation.d.ts +3 -3
  175. package/dist/session/phase-completion.validation.js +135 -89
  176. package/dist/session/pre-publication-host-load.d.ts +27 -0
  177. package/dist/session/pre-publication-host-load.js +111 -0
  178. package/dist/session/pre-publication-pass.d.ts +61 -0
  179. package/dist/session/pre-publication-pass.js +148 -0
  180. package/dist/session/pre-publication-process.d.ts +23 -0
  181. package/dist/session/pre-publication-process.js +109 -0
  182. package/dist/session/pre-publication-skipped-tests.d.ts +21 -0
  183. package/dist/session/pre-publication-skipped-tests.js +109 -0
  184. package/dist/session/pre-publication-step-execution.d.ts +11 -0
  185. package/dist/session/pre-publication-step-execution.js +49 -0
  186. package/dist/session/pre-publication-validation.d.ts +87 -0
  187. package/dist/session/pre-publication-validation.js +668 -0
  188. package/dist/session/provider-cli/bridge-cli.conformance-fixtures.d.ts +72 -0
  189. package/dist/session/provider-cli/bridge-cli.conformance-fixtures.js +462 -0
  190. package/dist/session/provider-cli/ci-repair-readiness.d.ts +8 -0
  191. package/dist/session/provider-cli/ci-repair-readiness.js +23 -3
  192. package/dist/session/provider-cli/claude-background-work.d.ts +66 -0
  193. package/dist/session/provider-cli/claude-background-work.js +180 -0
  194. package/dist/session/provider-cli/pre-publication-repair.d.ts +40 -0
  195. package/dist/session/provider-cli/pre-publication-repair.js +243 -0
  196. package/dist/session/provider-cli/provider-cli.artifacts.d.ts +6 -3
  197. package/dist/session/provider-cli/provider-cli.artifacts.js +62 -22
  198. package/dist/session/provider-cli/provider-cli.child-environment.d.ts +7 -0
  199. package/dist/session/provider-cli/provider-cli.child-environment.js +73 -0
  200. package/dist/session/provider-cli/provider-cli.codex-models-cache.d.ts +3 -0
  201. package/dist/session/provider-cli/provider-cli.codex-models-cache.js +37 -0
  202. package/dist/session/provider-cli/provider-cli.deterministic.js +34 -2
  203. package/dist/session/provider-cli/provider-cli.merge-integrity.d.ts +89 -0
  204. package/dist/session/provider-cli/provider-cli.merge-integrity.js +310 -0
  205. package/dist/session/provider-cli/provider-cli.process.d.ts +92 -14
  206. package/dist/session/provider-cli/provider-cli.process.js +583 -210
  207. package/dist/session/provider-cli/provider-cli.prompts.d.ts +12 -0
  208. package/dist/session/provider-cli/provider-cli.prompts.js +200 -25
  209. package/dist/session/provider-cli/provider-cli.repair-epoch.d.ts +6 -0
  210. package/dist/session/provider-cli/provider-cli.repair-epoch.js +11 -0
  211. package/dist/session/provider-cli/provider-cli.runtime.d.ts +14 -1
  212. package/dist/session/provider-cli/provider-cli.runtime.js +61 -3
  213. package/dist/session/provider-cli/provider-cli.service.d.ts +33 -5
  214. package/dist/session/provider-cli/provider-cli.service.js +819 -84
  215. package/dist/session/provider-cli/provider-cli.types.d.ts +32 -0
  216. package/dist/session/provider-cli/provider-cli.windows-environment.d.ts +10 -0
  217. package/dist/session/provider-cli/provider-cli.windows-environment.js +151 -0
  218. package/dist/session/provider-cli/provider-in-flight-work.d.ts +10 -0
  219. package/dist/session/provider-cli/provider-in-flight-work.js +92 -0
  220. package/dist/session/provider-cli/provider-output-pipes.d.ts +30 -0
  221. package/dist/session/provider-cli/provider-output-pipes.js +67 -0
  222. package/dist/session/provider-cli/provider-output-state.d.ts +18 -0
  223. package/dist/session/provider-cli/provider-output-state.js +376 -17
  224. package/dist/session/provider-cli/provider-usage.d.ts +9 -1
  225. package/dist/session/provider-cli/provider-usage.js +28 -5
  226. package/dist/session/publishable-worktree-changes.d.ts +54 -0
  227. package/dist/session/publishable-worktree-changes.js +193 -0
  228. package/dist/session/sandbox-host-capacity-gate.d.ts +30 -0
  229. package/dist/session/sandbox-host-capacity-gate.js +238 -0
  230. package/dist/session/session-redaction.js +434 -9
  231. package/dist/session/session.base.d.ts +9 -1
  232. package/dist/session/session.service.d.ts +9 -2
  233. package/dist/session/session.service.js +264 -27
  234. package/dist/session/session.types.d.ts +150 -2
  235. package/dist/session/session.types.js +599 -7
  236. package/dist/session/unreferenced-exports.d.ts +12 -0
  237. package/dist/session/unreferenced-exports.js +59 -0
  238. package/dist/session/workspace-runtime-fingerprint.d.ts +32 -0
  239. package/dist/session/workspace-runtime-fingerprint.js +138 -0
  240. package/dist/shared/format/format-bytes.d.ts +1 -0
  241. package/dist/shared/format/format-bytes.js +9 -0
  242. package/dist/shared/git/git.js +2 -1
  243. package/dist/shared/path/path.d.ts +1 -0
  244. package/dist/shared/path/path.js +18 -0
  245. package/dist/shared/process/dotnet-toolchain.d.ts +17 -0
  246. package/dist/shared/process/dotnet-toolchain.js +307 -0
  247. package/dist/shared/process/host-process-recovery.js +3 -2
  248. package/dist/shared/process/host-process-supervisor.d.ts +3 -0
  249. package/dist/shared/process/host-process-supervisor.js +61 -12
  250. package/dist/shared/process/process-tree.d.ts +52 -0
  251. package/dist/shared/process/process-tree.js +144 -0
  252. package/dist/shared/process/process.d.ts +69 -0
  253. package/dist/shared/process/process.js +223 -16
  254. package/dist/shared/process/windows-app-execution-alias.d.ts +19 -0
  255. package/dist/shared/process/windows-app-execution-alias.js +45 -0
  256. package/dist/shared/process/windows-launch.d.ts +18 -0
  257. package/dist/shared/process/windows-launch.js +68 -0
  258. package/dist/shared/provider-capabilities.d.ts +3 -0
  259. package/dist/shared/provider-capabilities.js +84 -0
  260. package/dist/shared/redaction/redaction.d.ts +1 -0
  261. package/dist/shared/redaction/redaction.js +39 -3
  262. package/dist/shared/time/monotonic.d.ts +1 -0
  263. package/dist/shared/time/monotonic.js +8 -0
  264. package/dist/version.d.ts +1 -1
  265. package/dist/version.js +1 -1
  266. package/dist/worktree/dependency-warmer.d.ts +66 -9
  267. package/dist/worktree/dependency-warmer.js +609 -24
  268. package/dist/worktree/index.d.ts +1 -1
  269. package/dist/worktree/story-qa-reference-hydrator.d.ts +4 -0
  270. package/dist/worktree/story-qa-reference-hydrator.js +253 -0
  271. package/dist/worktree/worktree.service.d.ts +17 -1
  272. package/dist/worktree/worktree.service.js +293 -21
  273. package/dist/worktree/worktree.types.d.ts +14 -1
  274. package/package.json +8 -6
  275. package/runtime/windows-job-supervisor.ps1 +380 -14
@@ -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,9 +2,33 @@ 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>;
8
15
  export declare function writeQaCompletionArtifact(config: CompletionToolServerConfig, payload: Record<string, unknown>, status: string, producedBy: string): Promise<CompletionArtifactReference>;
9
16
  export declare function readQaGateArtifact(config: CompletionToolServerConfig, gate: QaCompletionGate): Promise<Record<string, unknown>>;
10
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>;
@@ -1,19 +1,22 @@
1
+ import crypto from "node:crypto";
1
2
  import fs from "node:fs/promises";
2
3
  import path from "node:path";
3
4
  import { redactSecrets } from "../shared/redaction/redaction.js";
4
5
  import { ensureNoSymbolicLinkPathSegments, isPathUnderRoot, sha256File } from "./qa-sidecar-validation.js";
5
- import { artifactRootFor, artifactRootForOwner, completionArtifactJsonPath, completionArtifactReportPath, decomposeGateFileNames, draftGateFileNames, phaseFiles, qaGateFileNames } from "./phase-completion.js";
6
- 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";
7
11
  export async function writeDecomposeGateCompletionArtifact(config, gate, toolName, input) {
8
12
  const payload = asRecord(input, "Decompose completion payload");
9
- const status = normalizeDraftStatus(optionalString(payload, "status") ?? "pass");
13
+ const status = validateDecomposeGatePayload(gate, payload);
14
+ const redactedPayload = redactSecrets({ ...payload, status, phase: "decompose", gate, tool_name: toolName }, config.redactionSecrets ?? []);
15
+ assertStructuralFieldsUnchanged(payload, redactedPayload);
10
16
  if (gate === "decompose_proposal") {
11
- const proposalJson = asRecord(payload["proposal_json"] ?? payload["decomposition_json"], "proposal_json");
12
- validateDecomposeProposalJson(proposalJson);
17
+ validatePostRedaction(() => validateDecomposeProposalJson(asRecord(redactedPayload["proposal_json"] ?? redactedPayload["decomposition_json"], "proposal_json")));
13
18
  }
14
- const redactedPayload = redactSecrets({ ...payload, status, phase: "decompose", gate, tool_name: toolName }, config.redactionSecrets ?? []);
15
19
  const root = artifactRootFor(config.worktreePath, config.workItemId);
16
- await fs.mkdir(root, { recursive: true });
17
20
  const artifactPath = path.join(root, decomposeGateFileNames[gate]);
18
21
  const reportPath = gate === "decompose_proposal" ? path.join(root, phaseFiles.decompose.reportFileName) : path.join(root, `${gate}.md`);
19
22
  const verdictJson = jsonText(redactedPayload);
@@ -21,8 +24,10 @@ export async function writeDecomposeGateCompletionArtifact(config, gate, toolNam
21
24
 
22
25
  ${optionalString(redactedPayload, "summary") ?? "Decompose gate recorded."}
23
26
  `;
24
- await writeFileAtomic(artifactPath, verdictJson);
25
- await writeFileAtomic(reportPath, report);
27
+ await publishArtifactBundleAtomic(root, [
28
+ { fileName: path.basename(reportPath), content: report },
29
+ { fileName: path.basename(artifactPath), content: verdictJson }
30
+ ], path.basename(artifactPath));
26
31
  return {
27
32
  phase: "decompose",
28
33
  workItemId: config.workItemId,
@@ -38,20 +43,21 @@ ${optionalString(redactedPayload, "summary") ?? "Decompose gate recorded."}
38
43
  }
39
44
  export async function writeDraftGateCompletionArtifact(config, gate, toolName, input) {
40
45
  const payload = asRecord(input, "Draft completion payload");
41
- const status = normalizeDraftStatus(optionalString(payload, "status") ?? "pass");
46
+ const status = validateDraftGatePayload(gate, payload);
47
+ const redactedPayload = redactSecrets({ ...payload, status, phase: "draft", gate, tool_name: toolName }, config.redactionSecrets ?? []);
48
+ assertStructuralFieldsUnchanged(payload, redactedPayload);
42
49
  if (gate === "draft_proposal") {
43
- const draftJson = asRecord(payload["draft_json"], "draft_json");
44
- validateDraftProposalJson(draftJson);
50
+ validatePostRedaction(() => validateDraftProposalJson(asRecord(redactedPayload["draft_json"], "draft_json")));
45
51
  }
46
- const redactedPayload = redactSecrets({ ...payload, status, phase: "draft", gate, tool_name: toolName }, config.redactionSecrets ?? []);
47
52
  const root = artifactRootFor(config.worktreePath, config.workItemId);
48
- await fs.mkdir(root, { recursive: true });
49
53
  const artifactPath = path.join(root, draftGateFileNames[gate]);
50
54
  const reportPath = gate === "draft_proposal" ? path.join(root, phaseFiles.draft.reportFileName) : path.join(root, `${gate}.md`);
51
55
  const verdictJson = jsonText(redactedPayload);
52
56
  const report = optionalString(redactedPayload, "report_markdown") ?? `# ${gate.replace(/_/g, " ")}\n\n${optionalString(redactedPayload, "summary") ?? "Draft gate recorded."}\n`;
53
- await writeFileAtomic(artifactPath, verdictJson);
54
- await writeFileAtomic(reportPath, report);
57
+ await publishArtifactBundleAtomic(root, [
58
+ { fileName: path.basename(reportPath), content: report },
59
+ { fileName: path.basename(artifactPath), content: verdictJson }
60
+ ], path.basename(artifactPath));
55
61
  return {
56
62
  phase: "draft",
57
63
  workItemId: config.workItemId,
@@ -65,9 +71,48 @@ export async function writeDraftGateCompletionArtifact(config, gate, toolName, i
65
71
  producedBy: config.producedBy ?? "forge-completion-tool"
66
72
  };
67
73
  }
68
- function normalizeDraftStatus(value) {
69
- const normalized = value.trim().toLowerCase();
70
- 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;
71
116
  }
72
117
  function validateDraftProposalJson(draftJson) {
73
118
  if (draftJson.suggested_qa_scope !== undefined && draftJson.suggested_qa_scope !== null) {
@@ -147,7 +192,15 @@ export async function writeCompletionArtifact(config, toolName, input) {
147
192
  }
148
193
  validatePayloadShape(phase, validationPayload);
149
194
  validateOptionalWorkItemId(validationPayload, config.workItemId);
195
+ if (phase === "comment_repair" && status === "pass") {
196
+ await assertClaimedChangedFilesMatchPublishableDiff(config.worktreePath, validationPayload, toolName);
197
+ }
150
198
  const redactedPayload = redactSecrets(validationPayload, config.redactionSecrets ?? []);
199
+ assertStructuralFieldsUnchanged(validationPayload, redactedPayload);
200
+ validatePostRedaction(() => {
201
+ validatePayloadShape(phase, redactedPayload);
202
+ validateOptionalWorkItemId(redactedPayload, config.workItemId);
203
+ });
151
204
  const producedBy = optionalString(redactedPayload, "produced_by")
152
205
  ?? optionalString(redactedPayload, "producedBy")
153
206
  ?? config.producedBy
@@ -175,9 +228,10 @@ export async function writeCompletionArtifact(config, toolName, input) {
175
228
  const report = reportMarkdown(redactedPayload, phase, status, producedBy, contentHash);
176
229
  const artifactPath = completionArtifactJsonPath(config.worktreePath, config.workItemId, phase);
177
230
  const reportPath = completionArtifactReportPath(config.worktreePath, config.workItemId, phase);
178
- await fs.mkdir(path.dirname(artifactPath), { recursive: true });
179
- await writeFileAtomic(artifactPath, artifactJson);
180
- await writeFileAtomic(reportPath, report);
231
+ await publishArtifactBundleAtomic(path.dirname(artifactPath), [
232
+ { fileName: path.basename(reportPath), content: report },
233
+ { fileName: path.basename(artifactPath), content: artifactJson }
234
+ ], path.basename(artifactPath));
181
235
  return {
182
236
  phase,
183
237
  workItemId: config.workItemId,
@@ -199,8 +253,10 @@ export async function writeArchitectCompletionArtifact(config, payload, status,
199
253
  const qaPlanPath = path.join(artifactRoot, "qa.plan.json");
200
254
  const verdictPath = path.join(artifactRoot, "architect.verdict.json");
201
255
  const reportPath = path.join(artifactRoot, "architect.report.md");
202
- const implementationPlan = requiredRecord(payload, "implementation_plan");
203
- 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);
204
260
  const report = optionalString(payload, "report") ?? optionalString(payload, "report_markdown") ?? reportMarkdown(payload, "architect", status, producedBy, "pending");
205
261
  const artifactWithoutHash = normalizeArtifactPayload(payload, {
206
262
  phase: "architect",
@@ -215,11 +271,12 @@ export async function writeArchitectCompletionArtifact(config, payload, status,
215
271
  ...artifactWithoutHash,
216
272
  content_hash: contentHash
217
273
  };
218
- await fs.mkdir(artifactRoot, { recursive: true });
219
- await writeFileAtomic(implementationPlanPath, jsonText(implementationPlan));
220
- await writeFileAtomic(qaPlanPath, jsonText(qaPlan));
221
- await writeFileAtomic(verdictPath, jsonText(verdict));
222
- await writeFileAtomic(reportPath, `${report.trim()}\n`);
274
+ await publishArtifactBundleAtomic(artifactRoot, [
275
+ { fileName: path.basename(implementationPlanPath), content: jsonText(implementationPlan) },
276
+ { fileName: path.basename(qaPlanPath), content: jsonText(qaPlan) },
277
+ { fileName: path.basename(reportPath), content: `${report.trim()}\n` },
278
+ { fileName: path.basename(verdictPath), content: jsonText(verdict) }
279
+ ], path.basename(verdictPath));
223
280
  return {
224
281
  phase: "architect",
225
282
  workItemId: config.workItemId,
@@ -232,13 +289,21 @@ export async function writeArchitectCompletionArtifact(config, payload, status,
232
289
  producedBy
233
290
  };
234
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
+ }
235
298
  export async function writeQaGateCompletionArtifact(config, gate, input) {
236
299
  const payload = asRecord(input, "QA gate completion payload");
237
300
  const status = normalizeQaGateStatus(requiredString(payload, "status"));
238
301
  validateQaGatePayloadShape(gate, payload, status);
239
302
  validateOptionalWorkItemId(payload, config.workItemId);
240
303
  const ownerFields = artifactOwnerFields(config);
241
- 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)
242
307
  ? await validateQaSidecarReferences(config.worktreePath, config.workItemId, qaArray(payload, "sidecars", qaEvidenceSource(payload)), ownerFields.owner_type, ownerFields.owner_id)
243
308
  : null;
244
309
  const redactedPayload = redactSecrets({
@@ -246,6 +311,16 @@ export async function writeQaGateCompletionArtifact(config, gate, input) {
246
311
  status,
247
312
  ...(validatedSidecars ? { sidecars: validatedSidecars } : {})
248
313
  }, config.redactionSecrets ?? []);
314
+ assertStructuralFieldsUnchanged(payload, redactedPayload);
315
+ validatePostRedaction(() => {
316
+ validateQaGatePayloadShape(gate, redactedPayload, status);
317
+ validateOptionalWorkItemId(redactedPayload, config.workItemId);
318
+ });
319
+ if (qaEvidenceGates.has(gate)) {
320
+ await validateQaSidecarReferences(config.worktreePath, config.workItemId, qaArray(redactedPayload, "sidecars", qaEvidenceSource(redactedPayload)), ownerFields.owner_type, ownerFields.owner_id).catch((error) => {
321
+ throw postRedactionValidationError(error);
322
+ });
323
+ }
249
324
  const producedBy = optionalString(redactedPayload, "produced_by")
250
325
  ?? optionalString(redactedPayload, "producedBy")
251
326
  ?? config.producedBy
@@ -269,7 +344,6 @@ export async function writeQaGateCompletionArtifact(config, gate, input) {
269
344
  ...artifactWithoutHash,
270
345
  content_hash: contentHash
271
346
  };
272
- await fs.mkdir(artifactRoot, { recursive: true });
273
347
  await writeFileAtomic(artifactPath, jsonText(artifact));
274
348
  return {
275
349
  phase: "qa",
@@ -378,12 +452,13 @@ export async function writeQaCompletionArtifact(config, payload, status, produce
378
452
  content_hash: contentHash
379
453
  });
380
454
  const finalReport = reportMarkdown(payload, "qa", status, producedBy, contentHash);
381
- await fs.mkdir(artifactRoot, { recursive: true });
382
- await writeFileAtomic(planPath, planJson);
383
- await writeFileAtomic(evidencePath, evidenceJson);
384
- await writeFileAtomic(findingsPath, findingsJson);
385
- await writeFileAtomic(verdictPath, verdictJson);
386
- await writeFileAtomic(reportPath, finalReport);
455
+ await publishArtifactBundleAtomic(artifactRoot, [
456
+ { fileName: path.basename(planPath), content: planJson },
457
+ { fileName: path.basename(evidencePath), content: evidenceJson },
458
+ { fileName: path.basename(findingsPath), content: findingsJson },
459
+ { fileName: path.basename(reportPath), content: finalReport },
460
+ { fileName: path.basename(verdictPath), content: verdictJson }
461
+ ], path.basename(verdictPath));
387
462
  return {
388
463
  phase: "qa",
389
464
  workItemId: config.workItemId,
@@ -397,12 +472,12 @@ export async function writeQaCompletionArtifact(config, payload, status, produce
397
472
  };
398
473
  }
399
474
  async function synthesizeQaCycleVerdictPayload(config, payload, status) {
400
- const qaPlan = await readQaGateArtifact(config, "qa_plan");
401
- const qaRegression = await readQaGateArtifact(config, "qa_regression");
402
- const qaApi = await readQaGateArtifact(config, "qa_api");
403
- const qaManualWeb = await readQaGateArtifact(config, "qa_manual_web");
404
- const qaBugRepro = await readQaGateArtifact(config, "qa_bug_repro");
405
- 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");
406
481
  const evidenceGates = [qaRegression, qaApi, qaManualWeb, qaBugRepro];
407
482
  const payloadEvidence = qaEvidenceSource(payload);
408
483
  const merged = { ...payload };
@@ -450,6 +525,32 @@ async function synthesizeQaCycleVerdictPayload(config, payload, status) {
450
525
  merged.candidate_bugs = mergeQaObjectArraysById(qaObjectArray(payload, "candidate_bugs"), qaObjectArray(qaFindings, "candidate_bugs"));
451
526
  return merged;
452
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
+ }
453
554
  export async function readQaGateArtifact(config, gate) {
454
555
  const ownerFields = artifactOwnerFields(config);
455
556
  const artifactRoot = ownerFields.owner_type && ownerFields.owner_id
@@ -553,6 +654,7 @@ async function validateQaSidecarReferences(worktreePath, workItemId, sidecars, o
553
654
  : artifactRootFor(worktreePath, workItemId);
554
655
  const qaSidecarRoot = path.resolve(artifactRoot, "qa");
555
656
  const validated = [];
657
+ const validatedByPath = new Map();
556
658
  for (const [index, sidecar] of sidecars.entries()) {
557
659
  if (!sidecar || typeof sidecar !== "object" || Array.isArray(sidecar)) {
558
660
  throw new Error(`sidecars[${index}] must be an object.`);
@@ -588,9 +690,19 @@ async function validateQaSidecarReferences(worktreePath, workItemId, sidecars, o
588
690
  if (actualHash !== normalizeSha256ContentHash(contentHash)) {
589
691
  throw new Error(`sidecars[${index}].content_hash does not match the referenced file.`);
590
692
  }
693
+ const canonicalPath = path.relative(worktreePath, fullPath).split(path.sep).join("/");
694
+ const duplicateKey = canonicalPath.toLowerCase();
695
+ const existing = validatedByPath.get(duplicateKey);
696
+ if (existing) {
697
+ if (existing.contentHash !== actualHash || existing.bytes !== stat.size) {
698
+ throw new Error(`sidecars[${index}] conflicts with another payload for ${canonicalPath}.`);
699
+ }
700
+ continue;
701
+ }
702
+ validatedByPath.set(duplicateKey, { contentHash: actualHash, bytes: stat.size });
591
703
  validated.push({
592
704
  ...record,
593
- path: path.relative(worktreePath, fullPath).split(path.sep).join("/"),
705
+ path: canonicalPath,
594
706
  content_hash: actualHash,
595
707
  bytes: stat.size
596
708
  });
@@ -625,3 +737,166 @@ export async function readCompletionArtifact(worktreePath, workItemId, phase, ow
625
737
  phase
626
738
  };
627
739
  }
740
+ /**
741
+ * Stages a complete phase bundle outside the live artifact directory, then
742
+ * publishes its canonical verdict/marker last. Consumers treat the marker as
743
+ * the bundle's commit point, so they can observe either the old complete bundle
744
+ * or the new complete bundle, never a partially written set. A failed or
745
+ * cancelled publication rolls every touched file back before rejecting.
746
+ */
747
+ export async function publishArtifactBundleAtomic(artifactRoot, files, commitFileName, options = {}) {
748
+ validateArtifactBundleFiles(files, commitFileName);
749
+ throwIfPublicationCancelled(options.signal);
750
+ const parent = path.dirname(artifactRoot);
751
+ const transactionId = `${process.pid}.${crypto.randomUUID()}`;
752
+ const stagingRoot = path.join(parent, `.${path.basename(artifactRoot)}.${transactionId}.publish`);
753
+ const backupRoot = path.join(stagingRoot, ".previous");
754
+ const orderedFiles = [
755
+ ...files.filter((file) => file.fileName !== commitFileName),
756
+ files.find((file) => file.fileName === commitFileName)
757
+ ];
758
+ const backedUp = new Set();
759
+ const published = new Set();
760
+ try {
761
+ await fs.mkdir(parent, { recursive: true });
762
+ await fs.mkdir(stagingRoot, { recursive: false });
763
+ for (const file of orderedFiles) {
764
+ throwIfPublicationCancelled(options.signal);
765
+ const handle = await fs.open(path.join(stagingRoot, file.fileName), "wx");
766
+ try {
767
+ await handle.writeFile(file.content, { encoding: "utf8", signal: options.signal });
768
+ await handle.sync();
769
+ }
770
+ finally {
771
+ await handle.close();
772
+ }
773
+ }
774
+ throwIfPublicationCancelled(options.signal);
775
+ await fs.mkdir(artifactRoot, { recursive: true });
776
+ await fs.mkdir(backupRoot, { recursive: true });
777
+ // Hide the previous commit marker before changing any supporting file.
778
+ for (const fileName of [commitFileName, ...orderedFiles.map((file) => file.fileName).filter((name) => name !== commitFileName)]) {
779
+ const livePath = path.join(artifactRoot, fileName);
780
+ try {
781
+ await fs.rename(livePath, path.join(backupRoot, fileName));
782
+ backedUp.add(fileName);
783
+ }
784
+ catch (error) {
785
+ if (!isNodeError(error) || error.code !== "ENOENT") {
786
+ throw error;
787
+ }
788
+ }
789
+ }
790
+ for (const [index, file] of orderedFiles.entries()) {
791
+ throwIfPublicationCancelled(options.signal);
792
+ await options.beforePublishFile?.(file.fileName, index);
793
+ await fs.rename(path.join(stagingRoot, file.fileName), path.join(artifactRoot, file.fileName));
794
+ published.add(file.fileName);
795
+ }
796
+ }
797
+ catch (error) {
798
+ const rollbackErrors = [];
799
+ for (const file of [...orderedFiles].reverse()) {
800
+ if (!published.has(file.fileName))
801
+ continue;
802
+ await fs.rm(path.join(artifactRoot, file.fileName), { force: true }).catch(() => {
803
+ rollbackErrors.push(file.fileName);
804
+ });
805
+ }
806
+ // Restore the previous marker last for the same observable commit boundary.
807
+ const restoreOrder = [
808
+ ...orderedFiles.filter((file) => file.fileName !== commitFileName),
809
+ orderedFiles.find((file) => file.fileName === commitFileName)
810
+ ];
811
+ for (const file of restoreOrder) {
812
+ if (!backedUp.has(file.fileName))
813
+ continue;
814
+ await fs.rename(path.join(backupRoot, file.fileName), path.join(artifactRoot, file.fileName)).catch(() => {
815
+ rollbackErrors.push(file.fileName);
816
+ });
817
+ }
818
+ if (rollbackErrors.length === 0
819
+ && error instanceof Error
820
+ && error.message.startsWith("artifact_atomic_publish_cancelled:")) {
821
+ throw error;
822
+ }
823
+ const suffix = rollbackErrors.length > 0 ? " Rollback did not restore every bundle file." : "";
824
+ throw new Error(`artifact_atomic_publish_failure: completion artifact bundle was not published.${suffix}`, { cause: error });
825
+ }
826
+ finally {
827
+ await fs.rm(stagingRoot, { recursive: true, force: true }).catch(() => undefined);
828
+ }
829
+ }
830
+ function validateArtifactBundleFiles(files, commitFileName) {
831
+ if (files.length === 0 || !files.some((file) => file.fileName === commitFileName)) {
832
+ throw new Error("artifact_atomic_publish_failure: bundle commit file is missing.");
833
+ }
834
+ const names = new Set();
835
+ for (const file of files) {
836
+ if (!file.fileName || path.basename(file.fileName) !== file.fileName || names.has(file.fileName)) {
837
+ throw new Error("artifact_atomic_publish_failure: bundle file names must be unique safe base names.");
838
+ }
839
+ names.add(file.fileName);
840
+ }
841
+ }
842
+ function throwIfPublicationCancelled(signal) {
843
+ if (signal?.aborted) {
844
+ throw new Error("artifact_atomic_publish_cancelled: completion artifact bundle publication was cancelled.");
845
+ }
846
+ }
847
+ function validatePostRedaction(validate) {
848
+ try {
849
+ validate();
850
+ }
851
+ catch (error) {
852
+ throw postRedactionValidationError(error);
853
+ }
854
+ }
855
+ function postRedactionValidationError(error) {
856
+ const message = error instanceof Error ? error.message : String(error);
857
+ return new Error(`artifact_post_redaction_validation_failed: ${message}`, { cause: error });
858
+ }
859
+ function assertStructuralFieldsUnchanged(original, redacted) {
860
+ if (structuralFieldFingerprint(original) !== structuralFieldFingerprint(redacted)) {
861
+ // This stable code is intentionally safe for telemetry: it does not include
862
+ // the structural value or any candidate secret.
863
+ throw new Error("artifact_redaction_changed_structural_field: redaction changed a structural identifier; the bundle was not published.");
864
+ }
865
+ }
866
+ function structuralFieldFingerprint(value, key = "", result = []) {
867
+ if (Array.isArray(value)) {
868
+ if (isStructuralFieldKey(key) && value.every((item) => item === null || typeof item !== "object")) {
869
+ result.push(stableStringify(value));
870
+ }
871
+ else {
872
+ for (const item of value)
873
+ structuralFieldFingerprint(item, key, result);
874
+ }
875
+ return result.join("\n");
876
+ }
877
+ if (!value || typeof value !== "object") {
878
+ if (isStructuralFieldKey(key))
879
+ result.push(stableStringify(value));
880
+ return result.join("\n");
881
+ }
882
+ for (const [childKey, child] of Object.entries(value)) {
883
+ if (isStructuralFieldKey(childKey)) {
884
+ result.push(`${childKey}:${stableStringify(child)}`);
885
+ }
886
+ else {
887
+ structuralFieldFingerprint(child, childKey, result);
888
+ }
889
+ }
890
+ return result.join("\n");
891
+ }
892
+ function isStructuralFieldKey(key) {
893
+ return key === "id"
894
+ || key === "before"
895
+ || key === "after"
896
+ || key === "from"
897
+ || key === "to"
898
+ || key === "tasks"
899
+ || key === "phases"
900
+ || /(?:^|_)(?:id|ids)$/i.test(key)
901
+ || /(?:Id|Ids)$/.test(key);
902
+ }