create-principles-disciple 1.154.5 → 1.155.1

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 (409) hide show
  1. package/_release/product-identity.json +2 -2
  2. package/codex-adapter/dist/codec/input-decoder.d.ts +17 -0
  3. package/codex-adapter/dist/codec/input-decoder.js +39 -0
  4. package/codex-adapter/dist/ingestion/explicit-owner-statement.js +125 -1
  5. package/codex-adapter/dist/ingestion/pain-receipt-fallback.d.ts +46 -0
  6. package/codex-adapter/dist/ingestion/pain-receipt-fallback.js +193 -0
  7. package/codex-adapter/dist/ingestion/turn-context.d.ts +10 -15
  8. package/codex-adapter/dist/ingestion/turn-context.js +35 -9
  9. package/codex-adapter/dist/pd-hook.js +57 -1
  10. package/codex-adapter/dist/worker/workspace-worker.d.ts +15 -0
  11. package/codex-adapter/dist/worker/workspace-worker.js +91 -12
  12. package/codex-adapter/package.json +1 -1
  13. package/console/dist/server/index.js +10 -0
  14. package/console/dist/server/models/EvidenceChainConsoleModel.js +31 -0
  15. package/console/dist/server/routes/service-host.d.ts +19 -0
  16. package/console/dist/server/routes/service-host.js +129 -0
  17. package/console/dist/web/assets/app.js +37 -37
  18. package/core/dist/runtime/context-payload.d.ts +48 -0
  19. package/core/dist/runtime/context-payload.d.ts.map +1 -1
  20. package/core/dist/runtime/context-payload.js +12 -0
  21. package/core/dist/runtime/context-payload.js.map +1 -1
  22. package/core/dist/runtime/diagnostician/rootcause-prompt-builder.d.ts.map +1 -1
  23. package/core/dist/runtime/diagnostician/rootcause-prompt-builder.js +18 -0
  24. package/core/dist/runtime/diagnostician/rootcause-prompt-builder.js.map +1 -1
  25. package/core/dist/runtime/diagnostician-candidate.d.ts.map +1 -1
  26. package/core/dist/runtime/diagnostician-candidate.js +18 -2
  27. package/core/dist/runtime/diagnostician-candidate.js.map +1 -1
  28. package/core/dist/runtime/evidence-guards.d.ts +7 -3
  29. package/core/dist/runtime/evidence-guards.d.ts.map +1 -1
  30. package/core/dist/runtime/evidence-guards.js +9 -7
  31. package/core/dist/runtime/evidence-guards.js.map +1 -1
  32. package/core/dist/runtime/feature-flags/feature-flag-contract.d.ts.map +1 -1
  33. package/core/dist/runtime/feature-flags/feature-flag-contract.js +14 -0
  34. package/core/dist/runtime/feature-flags/feature-flag-contract.js.map +1 -1
  35. package/core/dist/runtime/feature-flags/feature-flag-lifecycle.d.ts.map +1 -1
  36. package/core/dist/runtime/feature-flags/feature-flag-lifecycle.js +8 -0
  37. package/core/dist/runtime/feature-flags/feature-flag-lifecycle.js.map +1 -1
  38. package/core/dist/runtime/host-submission-context.d.ts +83 -0
  39. package/core/dist/runtime/host-submission-context.d.ts.map +1 -0
  40. package/core/dist/runtime/host-submission-context.js +183 -0
  41. package/core/dist/runtime/host-submission-context.js.map +1 -0
  42. package/core/dist/runtime/index.d.ts +9 -2
  43. package/core/dist/runtime/index.d.ts.map +1 -1
  44. package/core/dist/runtime/index.js +29 -2
  45. package/core/dist/runtime/index.js.map +1 -1
  46. package/core/dist/runtime/intent/intent-doc.d.ts.map +1 -1
  47. package/core/dist/runtime/intent/intent-doc.js +29 -5
  48. package/core/dist/runtime/intent/intent-doc.js.map +1 -1
  49. package/core/dist/runtime/internalization/diag-distiller-runner.d.ts +9 -0
  50. package/core/dist/runtime/internalization/diag-distiller-runner.d.ts.map +1 -1
  51. package/core/dist/runtime/internalization/diag-distiller-runner.js +13 -0
  52. package/core/dist/runtime/internalization/diag-distiller-runner.js.map +1 -1
  53. package/core/dist/runtime/internalization/diag-rootcause-runner.d.ts +11 -0
  54. package/core/dist/runtime/internalization/diag-rootcause-runner.d.ts.map +1 -1
  55. package/core/dist/runtime/internalization/diag-rootcause-runner.js +10 -0
  56. package/core/dist/runtime/internalization/diag-rootcause-runner.js.map +1 -1
  57. package/core/dist/runtime/internalization/diag-router-runner.d.ts +9 -0
  58. package/core/dist/runtime/internalization/diag-router-runner.d.ts.map +1 -1
  59. package/core/dist/runtime/internalization/diag-router-runner.js +13 -0
  60. package/core/dist/runtime/internalization/diag-router-runner.js.map +1 -1
  61. package/core/dist/runtime/internalization/index.d.ts +1 -1
  62. package/core/dist/runtime/internalization/index.d.ts.map +1 -1
  63. package/core/dist/runtime/internalization/index.js +1 -1
  64. package/core/dist/runtime/internalization/index.js.map +1 -1
  65. package/core/dist/runtime/internalization/intake-to-internalization-bridge.d.ts +19 -0
  66. package/core/dist/runtime/internalization/intake-to-internalization-bridge.d.ts.map +1 -1
  67. package/core/dist/runtime/internalization/intake-to-internalization-bridge.js +24 -0
  68. package/core/dist/runtime/internalization/intake-to-internalization-bridge.js.map +1 -1
  69. package/core/dist/runtime/internalization/internalization-orchestrator.d.ts +8 -0
  70. package/core/dist/runtime/internalization/internalization-orchestrator.d.ts.map +1 -1
  71. package/core/dist/runtime/internalization/internalization-orchestrator.js +36 -4
  72. package/core/dist/runtime/internalization/internalization-orchestrator.js.map +1 -1
  73. package/core/dist/runtime/internalization/source-authorization-boundary.d.ts +39 -0
  74. package/core/dist/runtime/internalization/source-authorization-boundary.d.ts.map +1 -0
  75. package/core/dist/runtime/internalization/source-authorization-boundary.js +57 -0
  76. package/core/dist/runtime/internalization/source-authorization-boundary.js.map +1 -0
  77. package/core/dist/runtime/internalization/split-diagnostician-runner.d.ts.map +1 -1
  78. package/core/dist/runtime/internalization/split-diagnostician-runner.js +72 -5
  79. package/core/dist/runtime/internalization/split-diagnostician-runner.js.map +1 -1
  80. package/core/dist/runtime/pain-admission-disposition.d.ts +60 -0
  81. package/core/dist/runtime/pain-admission-disposition.d.ts.map +1 -0
  82. package/core/dist/runtime/pain-admission-disposition.js +37 -0
  83. package/core/dist/runtime/pain-admission-disposition.js.map +1 -0
  84. package/core/dist/runtime/pain-ingress-payload.d.ts +36 -2
  85. package/core/dist/runtime/pain-ingress-payload.d.ts.map +1 -1
  86. package/core/dist/runtime/pain-ingress-payload.js +63 -6
  87. package/core/dist/runtime/pain-ingress-payload.js.map +1 -1
  88. package/core/dist/runtime/pain-ingress.d.ts.map +1 -1
  89. package/core/dist/runtime/pain-ingress.js +28 -0
  90. package/core/dist/runtime/pain-ingress.js.map +1 -1
  91. package/core/dist/runtime/pain-recall-read-model.d.ts +13 -1
  92. package/core/dist/runtime/pain-recall-read-model.d.ts.map +1 -1
  93. package/core/dist/runtime/pain-recall-read-model.js +50 -7
  94. package/core/dist/runtime/pain-recall-read-model.js.map +1 -1
  95. package/core/dist/runtime/pain-receipt-recovery.d.ts +147 -0
  96. package/core/dist/runtime/pain-receipt-recovery.d.ts.map +1 -0
  97. package/core/dist/runtime/pain-receipt-recovery.js +475 -0
  98. package/core/dist/runtime/pain-receipt-recovery.js.map +1 -0
  99. package/core/dist/runtime/pain-signal-bridge.d.ts +13 -1
  100. package/core/dist/runtime/pain-signal-bridge.d.ts.map +1 -1
  101. package/core/dist/runtime/pain-signal-bridge.js +174 -0
  102. package/core/dist/runtime/pain-signal-bridge.js.map +1 -1
  103. package/core/dist/runtime/pain-signal-runtime-factory.d.ts +9 -0
  104. package/core/dist/runtime/pain-signal-runtime-factory.d.ts.map +1 -1
  105. package/core/dist/runtime/pain-signal-runtime-factory.js +8 -3
  106. package/core/dist/runtime/pain-signal-runtime-factory.js.map +1 -1
  107. package/core/dist/runtime/pain-submit-capability.d.ts +11 -0
  108. package/core/dist/runtime/pain-submit-capability.d.ts.map +1 -1
  109. package/core/dist/runtime/pain-submit-capability.js +77 -3
  110. package/core/dist/runtime/pain-submit-capability.js.map +1 -1
  111. package/core/dist/runtime/pain-target-evidence-reconcile.d.ts +55 -0
  112. package/core/dist/runtime/pain-target-evidence-reconcile.d.ts.map +1 -0
  113. package/core/dist/runtime/pain-target-evidence-reconcile.js +164 -0
  114. package/core/dist/runtime/pain-target-evidence-reconcile.js.map +1 -0
  115. package/core/dist/runtime/pain-to-principle-service.d.ts +8 -0
  116. package/core/dist/runtime/pain-to-principle-service.d.ts.map +1 -1
  117. package/core/dist/runtime/pain-to-principle-service.js +1 -0
  118. package/core/dist/runtime/pain-to-principle-service.js.map +1 -1
  119. package/core/dist/runtime/source-material-authorization.d.ts +166 -0
  120. package/core/dist/runtime/source-material-authorization.d.ts.map +1 -0
  121. package/core/dist/runtime/source-material-authorization.js +250 -0
  122. package/core/dist/runtime/source-material-authorization.js.map +1 -0
  123. package/core/dist/runtime/store/context/index.d.ts +1 -0
  124. package/core/dist/runtime/store/context/index.d.ts.map +1 -1
  125. package/core/dist/runtime/store/context/index.js +1 -0
  126. package/core/dist/runtime/store/context/index.js.map +1 -1
  127. package/core/dist/runtime/store/context/promoted-evidence-reader.d.ts +8 -0
  128. package/core/dist/runtime/store/context/promoted-evidence-reader.d.ts.map +1 -1
  129. package/core/dist/runtime/store/context/promoted-evidence-reader.js +15 -1
  130. package/core/dist/runtime/store/context/promoted-evidence-reader.js.map +1 -1
  131. package/core/dist/runtime/store/context/sqlite-context-assembler.d.ts +22 -0
  132. package/core/dist/runtime/store/context/sqlite-context-assembler.d.ts.map +1 -1
  133. package/core/dist/runtime/store/context/sqlite-context-assembler.js +153 -3
  134. package/core/dist/runtime/store/context/sqlite-context-assembler.js.map +1 -1
  135. package/core/dist/runtime/store/context/trajectory-turn-reader.d.ts +13 -0
  136. package/core/dist/runtime/store/context/trajectory-turn-reader.d.ts.map +1 -1
  137. package/core/dist/runtime/store/lifecycle/lease-manager.d.ts +15 -0
  138. package/core/dist/runtime/store/lifecycle/lease-manager.d.ts.map +1 -1
  139. package/core/dist/runtime/store/lifecycle/lease-manager.js +16 -1
  140. package/core/dist/runtime/store/lifecycle/lease-manager.js.map +1 -1
  141. package/core/dist/runtime/store/runtime-state-manager.d.ts +2 -0
  142. package/core/dist/runtime/store/runtime-state-manager.d.ts.map +1 -1
  143. package/core/dist/runtime/store/runtime-state-manager.js.map +1 -1
  144. package/core/dist/runtime/store/task/memory-task-store.d.ts +1 -0
  145. package/core/dist/runtime/store/task/memory-task-store.d.ts.map +1 -1
  146. package/core/dist/runtime/store/task/memory-task-store.js +37 -0
  147. package/core/dist/runtime/store/task/memory-task-store.js.map +1 -1
  148. package/core/dist/runtime/store/task/sqlite-task-store.d.ts +10 -0
  149. package/core/dist/runtime/store/task/sqlite-task-store.d.ts.map +1 -1
  150. package/core/dist/runtime/store/task/sqlite-task-store.js +20 -0
  151. package/core/dist/runtime/store/task/sqlite-task-store.js.map +1 -1
  152. package/core/dist/runtime/store/task/task-store.d.ts +16 -0
  153. package/core/dist/runtime/store/task/task-store.d.ts.map +1 -1
  154. package/core/dist/runtime/task-status.d.ts +13 -0
  155. package/core/dist/runtime/task-status.d.ts.map +1 -1
  156. package/core/dist/runtime/task-status.js +9 -0
  157. package/core/dist/runtime/task-status.js.map +1 -1
  158. package/core/dist/runtime/types/evidence-chain-contract.d.ts +10 -0
  159. package/core/dist/runtime/types/evidence-chain-contract.d.ts.map +1 -1
  160. package/core/dist/runtime/types/evidence-chain-contract.js +7 -0
  161. package/core/dist/runtime/types/evidence-chain-contract.js.map +1 -1
  162. package/core/package.json +1 -1
  163. package/dist/index.d.ts.map +1 -1
  164. package/dist/index.js +11 -0
  165. package/dist/index.js.map +1 -1
  166. package/dist/installer.d.ts.map +1 -1
  167. package/dist/installer.js +77 -30
  168. package/dist/installer.js.map +1 -1
  169. package/dist/installers/mcp-registration-conflict.d.ts +8 -0
  170. package/dist/installers/mcp-registration-conflict.d.ts.map +1 -1
  171. package/dist/installers/mcp-registration-conflict.js +34 -1
  172. package/dist/installers/mcp-registration-conflict.js.map +1 -1
  173. package/dist/installers/workbuddy-host-installer.d.ts +45 -13
  174. package/dist/installers/workbuddy-host-installer.d.ts.map +1 -1
  175. package/dist/installers/workbuddy-host-installer.js +284 -21
  176. package/dist/installers/workbuddy-host-installer.js.map +1 -1
  177. package/dist/prompts.d.ts +11 -0
  178. package/dist/prompts.d.ts.map +1 -1
  179. package/dist/prompts.js +4 -0
  180. package/dist/prompts.js.map +1 -1
  181. package/dist/service-host-bridge.d.ts +67 -0
  182. package/dist/service-host-bridge.d.ts.map +1 -0
  183. package/dist/service-host-bridge.js +292 -0
  184. package/dist/service-host-bridge.js.map +1 -0
  185. package/dist/uninstaller.d.ts.map +1 -1
  186. package/dist/uninstaller.js +26 -0
  187. package/dist/uninstaller.js.map +1 -1
  188. package/dist/update/install-layout.d.ts +0 -12
  189. package/dist/update/install-layout.d.ts.map +1 -1
  190. package/dist/update/install-layout.js +42 -15
  191. package/dist/update/install-layout.js.map +1 -1
  192. package/host-runtime/dist/diagnostician-auto-run.js +4 -1
  193. package/host-runtime/dist/governance-observation-store.d.ts +7 -0
  194. package/host-runtime/dist/governance-observation-store.js +15 -4
  195. package/host-runtime/dist/governance-signal-admission.d.ts +49 -0
  196. package/host-runtime/dist/governance-signal-admission.js +355 -94
  197. package/host-runtime/dist/governance-trajectory-turn-reader.d.ts +20 -4
  198. package/host-runtime/dist/governance-trajectory-turn-reader.js +77 -5
  199. package/host-runtime/dist/index.d.ts +2 -0
  200. package/host-runtime/dist/index.js +5 -0
  201. package/host-runtime/dist/internalization-consumer-cycle.js +4 -1
  202. package/host-runtime/dist/pd-config.d.ts +10 -0
  203. package/host-runtime/dist/pd-config.js +37 -0
  204. package/host-runtime/dist/signal-stage2-cycle.js +28 -1
  205. package/host-runtime/dist/source-material-authorization.d.ts +53 -0
  206. package/host-runtime/dist/source-material-authorization.js +67 -0
  207. package/host-runtime/dist/source-revocation-sweep.d.ts +172 -0
  208. package/host-runtime/dist/source-revocation-sweep.js +928 -0
  209. package/host-runtime/package.json +5 -1
  210. package/install-layout/dist/background-execution-transition.d.ts +258 -0
  211. package/install-layout/dist/background-execution-transition.js +836 -0
  212. package/install-layout/dist/index.d.ts +8 -0
  213. package/install-layout/dist/index.js +8 -0
  214. package/install-layout/package.json +6 -2
  215. package/package.json +4 -4
  216. package/pd-cli/dist/commands/candidate.d.ts.map +1 -1
  217. package/pd-cli/dist/commands/candidate.js +16 -5
  218. package/pd-cli/dist/commands/candidate.js.map +1 -1
  219. package/pd-cli/dist/commands/codex-setup.d.ts.map +1 -1
  220. package/pd-cli/dist/commands/codex-setup.js +17 -1
  221. package/pd-cli/dist/commands/codex-setup.js.map +1 -1
  222. package/pd-cli/dist/commands/codex-worker.d.ts.map +1 -1
  223. package/pd-cli/dist/commands/codex-worker.js +8 -4
  224. package/pd-cli/dist/commands/codex-worker.js.map +1 -1
  225. package/pd-cli/dist/commands/consent-sweep-revoked.d.ts +20 -0
  226. package/pd-cli/dist/commands/consent-sweep-revoked.d.ts.map +1 -0
  227. package/pd-cli/dist/commands/consent-sweep-revoked.js +85 -0
  228. package/pd-cli/dist/commands/consent-sweep-revoked.js.map +1 -0
  229. package/pd-cli/dist/commands/context.d.ts.map +1 -1
  230. package/pd-cli/dist/commands/context.js +9 -1
  231. package/pd-cli/dist/commands/context.js.map +1 -1
  232. package/pd-cli/dist/commands/diagnose.d.ts.map +1 -1
  233. package/pd-cli/dist/commands/diagnose.js +12 -6
  234. package/pd-cli/dist/commands/diagnose.js.map +1 -1
  235. package/pd-cli/dist/commands/openclaw-worker.d.ts +11 -0
  236. package/pd-cli/dist/commands/openclaw-worker.d.ts.map +1 -0
  237. package/pd-cli/dist/commands/openclaw-worker.js +199 -0
  238. package/pd-cli/dist/commands/openclaw-worker.js.map +1 -0
  239. package/pd-cli/dist/commands/pain-explicit.d.ts.map +1 -1
  240. package/pd-cli/dist/commands/pain-explicit.js +1 -0
  241. package/pd-cli/dist/commands/pain-explicit.js.map +1 -1
  242. package/pd-cli/dist/commands/pain-recall.d.ts +2 -2
  243. package/pd-cli/dist/commands/pain-recall.d.ts.map +1 -1
  244. package/pd-cli/dist/commands/pain-recall.js +7 -1
  245. package/pd-cli/dist/commands/pain-recall.js.map +1 -1
  246. package/pd-cli/dist/commands/pain-retry.d.ts.map +1 -1
  247. package/pd-cli/dist/commands/pain-retry.js +12 -6
  248. package/pd-cli/dist/commands/pain-retry.js.map +1 -1
  249. package/pd-cli/dist/commands/runtime-internalization-enqueue-successors.d.ts.map +1 -1
  250. package/pd-cli/dist/commands/runtime-internalization-enqueue-successors.js +2 -1
  251. package/pd-cli/dist/commands/runtime-internalization-enqueue-successors.js.map +1 -1
  252. package/pd-cli/dist/commands/runtime-internalization-run-once.d.ts +1 -0
  253. package/pd-cli/dist/commands/runtime-internalization-run-once.d.ts.map +1 -1
  254. package/pd-cli/dist/commands/runtime-internalization-run-once.js +32 -8
  255. package/pd-cli/dist/commands/runtime-internalization-run-once.js.map +1 -1
  256. package/pd-cli/dist/commands/runtime-internalization-wake-once.d.ts.map +1 -1
  257. package/pd-cli/dist/commands/runtime-internalization-wake-once.js +2 -1
  258. package/pd-cli/dist/commands/runtime-internalization-wake-once.js.map +1 -1
  259. package/pd-cli/dist/commands/service-handover.d.ts +12 -0
  260. package/pd-cli/dist/commands/service-handover.d.ts.map +1 -0
  261. package/pd-cli/dist/commands/service-handover.js +117 -0
  262. package/pd-cli/dist/commands/service-handover.js.map +1 -0
  263. package/pd-cli/dist/commands/service-lifecycle.d.ts +31 -0
  264. package/pd-cli/dist/commands/service-lifecycle.d.ts.map +1 -0
  265. package/pd-cli/dist/commands/service-lifecycle.js +207 -0
  266. package/pd-cli/dist/commands/service-lifecycle.js.map +1 -0
  267. package/pd-cli/dist/commands/service-run-once.d.ts +96 -0
  268. package/pd-cli/dist/commands/service-run-once.d.ts.map +1 -1
  269. package/pd-cli/dist/commands/service-run-once.js +432 -13
  270. package/pd-cli/dist/commands/service-run-once.js.map +1 -1
  271. package/pd-cli/dist/commands/workbuddy-setup.d.ts.map +1 -1
  272. package/pd-cli/dist/commands/workbuddy-setup.js +22 -2
  273. package/pd-cli/dist/commands/workbuddy-setup.js.map +1 -1
  274. package/pd-cli/dist/program.d.ts.map +1 -1
  275. package/pd-cli/dist/program.js +167 -9
  276. package/pd-cli/dist/program.js.map +1 -1
  277. package/pd-cli/dist/services/admission-write-gate.d.ts +3 -1
  278. package/pd-cli/dist/services/admission-write-gate.d.ts.map +1 -1
  279. package/pd-cli/dist/services/admission-write-gate.js +1 -0
  280. package/pd-cli/dist/services/admission-write-gate.js.map +1 -1
  281. package/pd-cli/dist/services/service-host/coordinator-common.d.ts +49 -0
  282. package/pd-cli/dist/services/service-host/coordinator-common.d.ts.map +1 -0
  283. package/pd-cli/dist/services/service-host/coordinator-common.js +158 -0
  284. package/pd-cli/dist/services/service-host/coordinator-common.js.map +1 -0
  285. package/pd-cli/dist/services/service-host/handover-claims.d.ts +14 -0
  286. package/pd-cli/dist/services/service-host/handover-claims.d.ts.map +1 -0
  287. package/pd-cli/dist/services/service-host/handover-claims.js +50 -0
  288. package/pd-cli/dist/services/service-host/handover-claims.js.map +1 -0
  289. package/pd-cli/dist/services/service-host/index.d.ts +19 -3
  290. package/pd-cli/dist/services/service-host/index.d.ts.map +1 -1
  291. package/pd-cli/dist/services/service-host/index.js +21 -3
  292. package/pd-cli/dist/services/service-host/index.js.map +1 -1
  293. package/pd-cli/dist/services/service-host/install-identity.d.ts +23 -3
  294. package/pd-cli/dist/services/service-host/install-identity.d.ts.map +1 -1
  295. package/pd-cli/dist/services/service-host/install-identity.js +15 -5
  296. package/pd-cli/dist/services/service-host/install-identity.js.map +1 -1
  297. package/pd-cli/dist/services/service-host/locking/service-run-lock.d.ts +130 -9
  298. package/pd-cli/dist/services/service-host/locking/service-run-lock.d.ts.map +1 -1
  299. package/pd-cli/dist/services/service-host/locking/service-run-lock.js +99 -19
  300. package/pd-cli/dist/services/service-host/locking/service-run-lock.js.map +1 -1
  301. package/pd-cli/dist/services/service-host/managed-run.d.ts +75 -0
  302. package/pd-cli/dist/services/service-host/managed-run.d.ts.map +1 -0
  303. package/pd-cli/dist/services/service-host/managed-run.js +550 -0
  304. package/pd-cli/dist/services/service-host/managed-run.js.map +1 -0
  305. package/pd-cli/dist/services/service-host/progress-evidence.d.ts +38 -0
  306. package/pd-cli/dist/services/service-host/progress-evidence.d.ts.map +1 -0
  307. package/pd-cli/dist/services/service-host/progress-evidence.js +155 -0
  308. package/pd-cli/dist/services/service-host/progress-evidence.js.map +1 -0
  309. package/pd-cli/dist/services/service-host/run-once.d.ts.map +1 -1
  310. package/pd-cli/dist/services/service-host/run-once.js +4 -136
  311. package/pd-cli/dist/services/service-host/run-once.js.map +1 -1
  312. package/pd-cli/dist/services/service-host/scheduler/contract.d.ts +184 -0
  313. package/pd-cli/dist/services/service-host/scheduler/contract.d.ts.map +1 -0
  314. package/pd-cli/dist/services/service-host/scheduler/contract.js +86 -0
  315. package/pd-cli/dist/services/service-host/scheduler/contract.js.map +1 -0
  316. package/pd-cli/dist/services/service-host/scheduler/index.d.ts +76 -0
  317. package/pd-cli/dist/services/service-host/scheduler/index.d.ts.map +1 -0
  318. package/pd-cli/dist/services/service-host/scheduler/index.js +128 -0
  319. package/pd-cli/dist/services/service-host/scheduler/index.js.map +1 -0
  320. package/pd-cli/dist/services/service-host/scheduler/linux.d.ts +27 -0
  321. package/pd-cli/dist/services/service-host/scheduler/linux.d.ts.map +1 -0
  322. package/pd-cli/dist/services/service-host/scheduler/linux.js +1010 -0
  323. package/pd-cli/dist/services/service-host/scheduler/linux.js.map +1 -0
  324. package/pd-cli/dist/services/service-host/scheduler/macos.d.ts +13 -0
  325. package/pd-cli/dist/services/service-host/scheduler/macos.d.ts.map +1 -0
  326. package/pd-cli/dist/services/service-host/scheduler/macos.js +819 -0
  327. package/pd-cli/dist/services/service-host/scheduler/macos.js.map +1 -0
  328. package/pd-cli/dist/services/service-host/scheduler/runtime-io.d.ts +13 -0
  329. package/pd-cli/dist/services/service-host/scheduler/runtime-io.d.ts.map +1 -0
  330. package/pd-cli/dist/services/service-host/scheduler/runtime-io.js +141 -0
  331. package/pd-cli/dist/services/service-host/scheduler/runtime-io.js.map +1 -0
  332. package/pd-cli/dist/services/service-host/scheduler/service-status.d.ts +99 -0
  333. package/pd-cli/dist/services/service-host/scheduler/service-status.d.ts.map +1 -0
  334. package/pd-cli/dist/services/service-host/scheduler/service-status.js +202 -0
  335. package/pd-cli/dist/services/service-host/scheduler/service-status.js.map +1 -0
  336. package/pd-cli/dist/services/service-host/scheduler/windows.d.ts +40 -0
  337. package/pd-cli/dist/services/service-host/scheduler/windows.d.ts.map +1 -0
  338. package/pd-cli/dist/services/service-host/scheduler/windows.js +688 -0
  339. package/pd-cli/dist/services/service-host/scheduler/windows.js.map +1 -0
  340. package/pd-cli/dist/services/service-host/shadow-progress-store.d.ts +43 -0
  341. package/pd-cli/dist/services/service-host/shadow-progress-store.d.ts.map +1 -0
  342. package/pd-cli/dist/services/service-host/shadow-progress-store.js +156 -0
  343. package/pd-cli/dist/services/service-host/shadow-progress-store.js.map +1 -0
  344. package/pd-cli/dist/services/service-host/shadow-run.d.ts +87 -0
  345. package/pd-cli/dist/services/service-host/shadow-run.d.ts.map +1 -0
  346. package/pd-cli/dist/services/service-host/shadow-run.js +549 -0
  347. package/pd-cli/dist/services/service-host/shadow-run.js.map +1 -0
  348. package/pd-cli/dist/services/service-host/status/service-run-status.d.ts +114 -4
  349. package/pd-cli/dist/services/service-host/status/service-run-status.d.ts.map +1 -1
  350. package/pd-cli/dist/services/service-host/status/service-run-status.js +37 -0
  351. package/pd-cli/dist/services/service-host/status/service-run-status.js.map +1 -1
  352. package/pd-cli/dist/services/service-host/worker-adapter-codex.d.ts +2 -0
  353. package/pd-cli/dist/services/service-host/worker-adapter-codex.d.ts.map +1 -0
  354. package/pd-cli/dist/services/service-host/worker-adapter-codex.js +76 -0
  355. package/pd-cli/dist/services/service-host/worker-adapter-codex.js.map +1 -0
  356. package/pd-cli/dist/services/service-host/worker-adapter-openclaw.d.ts +2 -0
  357. package/pd-cli/dist/services/service-host/worker-adapter-openclaw.d.ts.map +1 -0
  358. package/pd-cli/dist/services/service-host/worker-adapter-openclaw.js +49 -0
  359. package/pd-cli/dist/services/service-host/worker-adapter-openclaw.js.map +1 -0
  360. package/pd-cli/dist/services/service-host/worker-adapter-workbuddy.d.ts +2 -0
  361. package/pd-cli/dist/services/service-host/worker-adapter-workbuddy.d.ts.map +1 -0
  362. package/pd-cli/dist/services/service-host/worker-adapter-workbuddy.js +36 -0
  363. package/pd-cli/dist/services/service-host/worker-adapter-workbuddy.js.map +1 -0
  364. package/pd-cli/dist/services/service-host/worker-adapter.d.ts +187 -0
  365. package/pd-cli/dist/services/service-host/worker-adapter.d.ts.map +1 -0
  366. package/pd-cli/dist/services/service-host/worker-adapter.js +609 -0
  367. package/pd-cli/dist/services/service-host/worker-adapter.js.map +1 -0
  368. package/pd-cli/dist/services/service-host/worker-env.d.ts +84 -0
  369. package/pd-cli/dist/services/service-host/worker-env.d.ts.map +1 -0
  370. package/pd-cli/dist/services/service-host/worker-env.js +195 -0
  371. package/pd-cli/dist/services/service-host/worker-env.js.map +1 -0
  372. package/pd-cli/dist/services/service-host/worker-process.d.ts +75 -0
  373. package/pd-cli/dist/services/service-host/worker-process.d.ts.map +1 -0
  374. package/pd-cli/dist/services/service-host/worker-process.js +225 -0
  375. package/pd-cli/dist/services/service-host/worker-process.js.map +1 -0
  376. package/pd-cli/dist/services/service-host/workspace-dispatch.d.ts +61 -0
  377. package/pd-cli/dist/services/service-host/workspace-dispatch.d.ts.map +1 -0
  378. package/pd-cli/dist/services/service-host/workspace-dispatch.js +105 -0
  379. package/pd-cli/dist/services/service-host/workspace-dispatch.js.map +1 -0
  380. package/pd-cli/dist/services/service-host/workspace-handover.d.ts +190 -0
  381. package/pd-cli/dist/services/service-host/workspace-handover.d.ts.map +1 -0
  382. package/pd-cli/dist/services/service-host/workspace-handover.js +1393 -0
  383. package/pd-cli/dist/services/service-host/workspace-handover.js.map +1 -0
  384. package/pd-cli/package.json +6 -5
  385. package/pd-mcp-server/dist/submit-assembly.js +159 -42
  386. package/pd-mcp-server/dist/version.d.ts +1 -1
  387. package/pd-mcp-server/dist/version.js +1 -1
  388. package/pd-mcp-server/package.json +1 -1
  389. package/plugin/dist/bundle.js +586 -568
  390. package/plugin/dist/openclaw-worker.d.ts +92 -0
  391. package/plugin/dist/openclaw-worker.js +2439 -0
  392. package/plugin/dist/openclaw.plugin.json +1 -1
  393. package/plugin/dist/service/gateway-consumer-lease.d.ts +142 -0
  394. package/plugin/dist/service/gateway-quiesce-ack.d.ts +40 -0
  395. package/plugin/dist/service/internalization-auto-consumer-service.d.ts +68 -1
  396. package/plugin/openclaw.plugin.json +1 -1
  397. package/plugin/package.json +5 -1
  398. package/release-manager/dist/installer.js +77 -30
  399. package/release-manager/dist/installers/mcp-registration-conflict.js +34 -1
  400. package/release-manager/dist/installers/workbuddy-host-installer.js +284 -21
  401. package/release-manager/dist/service-host-bridge.js +292 -0
  402. package/release-manager/dist/update/install-layout.js +42 -15
  403. package/release-manager/package.json +2 -2
  404. package/workbuddy-adapter/dist/index.d.ts +1 -1
  405. package/workbuddy-adapter/dist/index.js +1 -1
  406. package/workbuddy-adapter/dist/worker/workspace-worker.d.ts +7 -0
  407. package/workbuddy-adapter/dist/worker/workspace-worker.js +179 -10
  408. package/workbuddy-adapter/package.json +1 -1
  409. package/workbuddy-adapter/plugin/.codebuddy-plugin/plugin.json +2 -2
@@ -0,0 +1,836 @@
1
+ /**
2
+ * Workspace background-execution ownership transitions — the CAS write path
3
+ * for SPEC-PD-SERVICE-HOST-001 §8.4 (PRI-1282 Phase 4).
4
+ *
5
+ * The manifest schema (`backgroundExecutions`, `BackgroundExecutionRecord`)
6
+ * lives in `index.ts`; this module owns the STATE MACHINE half that the
7
+ * schema doc string deferred: starting, completing, aborting and rolling back
8
+ * a per-Workspace ownership transition under a cross-process critical section
9
+ * with monotonic-generation fencing and operationId idempotency.
10
+ *
11
+ * Phase attribution (Owner execution directive 2026-11-22, closing the
12
+ * SPEC §8.4-10 / TD §9 conflict): Phase 4 implements this minimal, reusable
13
+ * primitive and uses it for the OpenClaw per-Workspace handover; Phase 5
14
+ * REUSES it for Codex / WorkBuddy — there is no second state machine.
15
+ *
16
+ * Concurrency model:
17
+ * - physical exclusion: one lock directory next to the manifest
18
+ * (`<manifest>.cas.lock/`, O_EXCL mkdir + owner metadata — the
19
+ * pd-worktree-mutation.lock pattern, at file scope), with every
20
+ * acquire / stale-reclaim / release DECISION serialized through a
21
+ * dedicated SQLite arbitration gate (`<manifest>.cas.gate.db`,
22
+ * `BEGIN IMMEDIATE` — the same proven mechanism as the service-run
23
+ * lock's `service-run-gate.db`, here on the dependency-free
24
+ * `better-sqlite3`, Node ≥22.0-compatible and warning-free). Under the
25
+ * gate, verify→remove→create is
26
+ * one serialized section: no contender can interleave between a
27
+ * reclaim's check and its recreate, and a release deletes only the
28
+ * lock whose owner token it verified inside the same transaction;
29
+ * - logical fencing: inside the critical section the writer re-reads the
30
+ * current record; a stale observed `generation` or an unexpected state
31
+ * loses and nothing is written;
32
+ * - durability: the manifest lands via temp file + atomic rename, so a crash
33
+ * mid-write leaves either the previous or the complete new document —
34
+ * never a partial one.
35
+ *
36
+ * Ownership of process liveness is NEVER consulted: PID, startup order and
37
+ * delays are not proof (SPEC §8.4). The persisted record is the only
38
+ * authority; `readWorkspaceBackgroundOwnership` is its read-side projection
39
+ * shared by the OpenClaw Gateway gate, the `pd openclaw worker` gate and the
40
+ * handover/rollback commands.
41
+ */
42
+ import * as crypto from 'node:crypto';
43
+ import * as fs from 'node:fs';
44
+ import * as os from 'node:os';
45
+ import * as path from 'node:path';
46
+ import Database from 'better-sqlite3';
47
+ import { installManifestHostsForPersist, mergeInstallManifestWorkspaces, parseInstallManifest, setInstallManifestBackgroundExecution, } from './index.js';
48
+ // ─── Lock ───────────────────────────────────────────────────────────────────
49
+ const CAS_LOCK_SCHEMA = 'pd.background-execution-cas-lock/1';
50
+ /** @deprecated Retired (PRI-1282 review round 4): file age never proves
51
+ * abandonment — reclaim authority is holder-PID liveness only. Kept exported
52
+ * for source compatibility; no code path consults it. */
53
+ export const DEFAULT_CAS_LOCK_STALE_MS = 30_000;
54
+ function defaultRealpath(target) {
55
+ try {
56
+ return fs.realpathSync.native(target);
57
+ }
58
+ catch {
59
+ return undefined;
60
+ }
61
+ }
62
+ /**
63
+ * Errno extraction without trusting the thrown shape (rc-1/rc-2/rc-5) — the
64
+ * same classification posture as `mcp-binding-contract.ts`.
65
+ */
66
+ function errnoOf(error) {
67
+ return typeof error === 'object' && error !== null && Object.hasOwn(error, 'code')
68
+ ? String(Reflect.get(error, 'code'))
69
+ : '';
70
+ }
71
+ function toError(error) {
72
+ return error instanceof Error ? error : new Error(String(error));
73
+ }
74
+ /** Type-guard narrowing for untrusted JSON values (rc-2: never an `as`). */
75
+ function isJsonObject(value) {
76
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
77
+ }
78
+ /**
79
+ * Default holder-liveness probe: signal-0 semantics, the same contract the
80
+ * service-run-lock uses — 'alive' includes EPERM-observable processes
81
+ * (exists, we just can't signal it); 'unknown' means the platform could not
82
+ * produce a reliable verdict and reclaim MUST fail closed on it.
83
+ */
84
+ function defaultProcessAlive(pid) {
85
+ try {
86
+ process.kill(pid, 0);
87
+ return 'alive';
88
+ }
89
+ catch (error) {
90
+ const code = errnoOf(error);
91
+ if (code === 'ESRCH')
92
+ return 'dead';
93
+ if (code === 'EPERM')
94
+ return 'alive';
95
+ return 'unknown';
96
+ }
97
+ }
98
+ function busyWaitMs(ms) {
99
+ // Sync context: a bounded spin over Date.now(). Callers only reach here on
100
+ // contention windows, which are millisecond-scale events.
101
+ const deadline = Date.now() + ms;
102
+ while (Date.now() < deadline) {
103
+ /* spin */
104
+ }
105
+ }
106
+ /** The one arbitration database per manifest — stable, never per-attempt. */
107
+ export function casGatePath(manifestPath) {
108
+ return `${manifestPath}.cas.gate.db`;
109
+ }
110
+ /** A lock decision is millisecond-scale file work; a contender waits only
111
+ * this long for the gate before reporting `lock_busy`. */
112
+ const CAS_GATE_BUSY_TIMEOUT_MS = 250;
113
+ /** Release gets a bounded wait of its own (same posture as the run lock). */
114
+ const CAS_GATE_RELEASE_BUSY_MS = 1500;
115
+ function defaultOpenGate(gatePath) {
116
+ const db = new Database(gatePath);
117
+ db.exec(`PRAGMA busy_timeout = ${CAS_GATE_BUSY_TIMEOUT_MS}`);
118
+ return db;
119
+ }
120
+ function isGateBusyError(error) {
121
+ // better-sqlite3 surfaces busy/locked as SqliteError.code strings.
122
+ const code = typeof error === 'object' && error !== null && Object.hasOwn(error, 'code')
123
+ ? String(Reflect.get(error, 'code'))
124
+ : '';
125
+ return code === 'SQLITE_BUSY' || code === 'SQLITE_LOCKED';
126
+ }
127
+ /**
128
+ * Run `body` while holding the CAS arbitration gate: open the per-manifest
129
+ * gate database, `BEGIN IMMEDIATE`, run the serialized decision, end the
130
+ * transaction. The gate stores no state — the transaction ends with
131
+ * `ROLLBACK`, so a failed COMMIT can never orphan filesystem work done in
132
+ * `body`. A process dying mid-transaction releases the gate through the OS
133
+ * (POSIX fcntl / Windows LockFileEx), so recovery is deterministic.
134
+ * SQLITE_BUSY maps to `lock_busy`; every other gate failure is
135
+ * `lock_io_error` — decisions NEVER run outside arbitration.
136
+ */
137
+ function withCasGate(manifestPath, opts, body) {
138
+ let db;
139
+ try {
140
+ db = (opts.openGate ?? defaultOpenGate)(casGatePath(manifestPath));
141
+ db.exec(`PRAGMA busy_timeout = ${opts.busyTimeoutMs}`);
142
+ }
143
+ catch (error) {
144
+ try {
145
+ db?.close();
146
+ }
147
+ catch {
148
+ // already closing
149
+ }
150
+ return { ok: false, reason: 'lock_io_error', message: `arbitration gate unavailable: ${toError(error).message}` };
151
+ }
152
+ const gateSync = opts.gateSync ?? (() => undefined);
153
+ try {
154
+ db.exec('BEGIN IMMEDIATE');
155
+ }
156
+ catch (error) {
157
+ try {
158
+ db.close();
159
+ }
160
+ catch {
161
+ // already closing
162
+ }
163
+ return {
164
+ ok: false,
165
+ reason: isGateBusyError(error) ? 'lock_busy' : 'lock_io_error',
166
+ message: `arbitration gate begin failed: ${toError(error).message}`,
167
+ };
168
+ }
169
+ try {
170
+ const value = body(gateSync);
171
+ // No persistent gate data: ROLLBACK ends the transaction.
172
+ db.exec('ROLLBACK');
173
+ return { ok: true, value };
174
+ }
175
+ catch (error) {
176
+ try {
177
+ db.exec('ROLLBACK');
178
+ }
179
+ catch {
180
+ // rollback best-effort; process death releases the gate anyway
181
+ }
182
+ return {
183
+ ok: false,
184
+ reason: isGateBusyError(error) ? 'lock_busy' : 'lock_io_error',
185
+ message: `arbitration gate transaction failed: ${toError(error).message}`,
186
+ };
187
+ }
188
+ finally {
189
+ try {
190
+ db.close();
191
+ }
192
+ catch {
193
+ // already closed
194
+ }
195
+ }
196
+ }
197
+ const realFsOps = {
198
+ mkdirExclusive(dir) {
199
+ try {
200
+ fs.mkdirSync(dir, { recursive: false });
201
+ return { ok: true };
202
+ }
203
+ catch (error) {
204
+ if (errnoOf(error) === 'EEXIST')
205
+ return { ok: false, code: 'exists' };
206
+ return { ok: false, code: 'io', error: toError(error) };
207
+ }
208
+ },
209
+ readJson(file) {
210
+ try {
211
+ return { ok: true, value: JSON.parse(fs.readFileSync(file, 'utf8')) };
212
+ }
213
+ catch (error) {
214
+ if (errnoOf(error) === 'ENOENT')
215
+ return { ok: false, code: 'missing' };
216
+ if (error instanceof SyntaxError)
217
+ return { ok: false, code: 'malformed', error: toError(error) };
218
+ return { ok: false, code: 'io', error: toError(error) };
219
+ }
220
+ },
221
+ writeJson(file, value) {
222
+ try {
223
+ fs.writeFileSync(file, JSON.stringify(value, null, 2) + '\n', 'utf8');
224
+ return { ok: true };
225
+ }
226
+ catch (error) {
227
+ return { ok: false, code: 'io', error: toError(error) };
228
+ }
229
+ },
230
+ removeDir(dir) {
231
+ try {
232
+ fs.rmSync(dir, { recursive: true, force: true });
233
+ return { ok: true };
234
+ }
235
+ catch (error) {
236
+ return { ok: false, code: 'io', error: toError(error) };
237
+ }
238
+ },
239
+ rename(from, to) {
240
+ try {
241
+ fs.renameSync(from, to);
242
+ return { ok: true };
243
+ }
244
+ catch (error) {
245
+ return { ok: false, code: 'io', error: toError(error) };
246
+ }
247
+ },
248
+ readFile(file) {
249
+ try {
250
+ return { ok: true, text: fs.readFileSync(file, 'utf8') };
251
+ }
252
+ catch (error) {
253
+ if (errnoOf(error) === 'ENOENT')
254
+ return { ok: false, code: 'missing' };
255
+ return { ok: false, code: 'io', error: toError(error) };
256
+ }
257
+ },
258
+ writeFile(file, text) {
259
+ try {
260
+ fs.writeFileSync(file, text, 'utf8');
261
+ return { ok: true };
262
+ }
263
+ catch (error) {
264
+ return { ok: false, code: 'io', error: toError(error) };
265
+ }
266
+ },
267
+ };
268
+ export function defaultCasFsOps() {
269
+ return realFsOps;
270
+ }
271
+ function parseLockOwner(value) {
272
+ if (typeof value !== 'object' || value === null || Array.isArray(value))
273
+ return null;
274
+ const record = value;
275
+ if (record.schema !== CAS_LOCK_SCHEMA)
276
+ return null;
277
+ const token = typeof record.token === 'string' ? record.token : '';
278
+ const operation = typeof record.operation === 'string' ? record.operation : '';
279
+ const workspaceDir = typeof record.workspaceDir === 'string' ? record.workspaceDir : '';
280
+ const createdAt = typeof record.createdAt === 'string' ? record.createdAt : '';
281
+ const pid = typeof record.pid === 'number' && Number.isInteger(record.pid) ? record.pid : -1;
282
+ const host = typeof record.host === 'string' ? record.host : '';
283
+ if (token.length === 0 || operation.length === 0 || workspaceDir.length === 0 || createdAt.length === 0)
284
+ return null;
285
+ return { schema: CAS_LOCK_SCHEMA, token, pid, host, operation, workspaceDir, createdAt };
286
+ }
287
+ function randomToken() {
288
+ // Identity token for lock attribution / temp-file uniqueness — not a secret,
289
+ // but randomUUID is free and collision-proof, so no weaker source is used.
290
+ return crypto.randomUUID().replace(/-/g, '').slice(0, 16);
291
+ }
292
+ function ownerFileName() {
293
+ // A fixed name keeps "is this lock well-formed" decidable without globbing.
294
+ return 'owner.json';
295
+ }
296
+ /**
297
+ * Remove a lock dir whose removal was already DECIDED inside the gate
298
+ * transaction: atomically move the whole directory out of the canonical
299
+ * lock path first, then delete the moved copy (PRI-1282 review round 5).
300
+ * Recursive deletion at the lock path removes owner.json before the dir,
301
+ * so a mid-delete kill stranded an unattributable orphan that blocked
302
+ * every later writer as `lock_invalid`. With move-out-first, a successor
303
+ * sees either the complete old lock or an absent path; a leftover
304
+ * `*.tombstone-*` sibling is inert garbage, not a lock.
305
+ */
306
+ function removeLockDirAtomically(fsOps, lockDir) {
307
+ const tombstone = `${lockDir}.tombstone-${randomToken()}`;
308
+ const moved = fsOps.rename(lockDir, tombstone);
309
+ if (!moved.ok)
310
+ return { ok: false, error: moved.error };
311
+ // Best-effort: the lock path is already free; a failed rm leaves an inert
312
+ // tombstone sibling, never a lock at the canonical path.
313
+ fsOps.removeDir(tombstone);
314
+ return { ok: true };
315
+ }
316
+ /**
317
+ * Acquire the per-manifest CAS critical section. Every decision — evaluate
318
+ * the existing lock, reclaim a provably-dead holder's lock, create ours —
319
+ * runs inside ONE `BEGIN IMMEDIATE` transaction on the per-manifest
320
+ * arbitration gate ({@link casGatePath}), so verify→remove→create is a
321
+ * serialized section by construction: no second contender can interleave
322
+ * between the check and the action (PRI-1282 review round 4 — the
323
+ * rename-quarantine/restore pattern it replaces could strand or overwrite
324
+ * a fresh lock in the check→act gap).
325
+ *
326
+ * Reclaim authority is the recorded holder's PID liveness, never file age:
327
+ * a lock is reclaimed ONLY when the recorded PID is provably dead on this
328
+ * host — a dead holder cannot be inside the critical section and cannot
329
+ * resume to delete the replacement lock. A live, foreign-host or
330
+ * unverifiable holder is `lock_busy`/`lock_invalid` — fail-closed.
331
+ */
332
+ export function acquireBackgroundExecutionCasLock(options) {
333
+ const fsOps = options.fsOps ?? realFsOps;
334
+ const now = options.now ?? (() => new Date());
335
+ const processAlive = options.probes?.processAlive ?? defaultProcessAlive;
336
+ const lockDir = `${options.manifestPath}.cas.lock`;
337
+ const ownerFile = path.join(lockDir, ownerFileName());
338
+ const buildOwner = () => ({
339
+ schema: CAS_LOCK_SCHEMA,
340
+ token: randomToken(),
341
+ pid: process.pid,
342
+ // Diagnostics-only field; never a control input.
343
+ host: typeof os.hostname === 'function' ? os.hostname() : 'unavailable',
344
+ operation: options.operation,
345
+ workspaceDir: options.workspaceDir,
346
+ createdAt: now().toISOString(),
347
+ });
348
+ const gated = withCasGate(options.manifestPath, { busyTimeoutMs: CAS_GATE_BUSY_TIMEOUT_MS, openGate: options.probes?.openGate, gateSync: options.probes?.gateSync }, (gateSync) => {
349
+ gateSync('gate-held');
350
+ const createOwned = () => {
351
+ const owner = buildOwner();
352
+ const created = fsOps.mkdirExclusive(lockDir);
353
+ if (!created.ok) {
354
+ return { ok: false, reason: 'lock_io_error', message: `failed to create CAS lock directory: ${created.error?.message ?? 'io error'}` };
355
+ }
356
+ const written = fsOps.writeJson(ownerFile, owner);
357
+ if (!written.ok) {
358
+ // We own the directory but cannot attribute it — remove it so the
359
+ // next acquirer is not stuck on an anonymous empty dir.
360
+ fsOps.removeDir(lockDir);
361
+ return { ok: false, reason: 'lock_io_error', message: `failed to write CAS lock owner metadata: ${written.error?.message ?? 'io error'}` };
362
+ }
363
+ gateSync('lock-created');
364
+ return { ok: true, owner };
365
+ };
366
+ // Lock exists (or absent): attribute it.
367
+ const ownerRead = fsOps.readJson(ownerFile);
368
+ if (!ownerRead.ok && ownerRead.code === 'missing') {
369
+ // No owner metadata: either the whole lock dir is absent (we create)
370
+ // or it exists as an unattributable orphan (a crashed mid-create —
371
+ // never a live cooperator, whose owner.json is written inside the
372
+ // same gate transaction). The exclusive mkdir decides which.
373
+ const probe = fsOps.mkdirExclusive(lockDir);
374
+ if (probe.ok) {
375
+ const owner = buildOwner();
376
+ const written = fsOps.writeJson(ownerFile, owner);
377
+ if (!written.ok) {
378
+ fsOps.removeDir(lockDir);
379
+ return { ok: false, reason: 'lock_io_error', message: `failed to write CAS lock owner metadata: ${written.error?.message ?? 'io error'}` };
380
+ }
381
+ gateSync('lock-created');
382
+ return { ok: true, owner };
383
+ }
384
+ if (probe.code === 'exists') {
385
+ // Orphaned dir without owner.json — a crashed mid-create (inside
386
+ // the gate a live cooperator cannot be mid-create). Reclaim it
387
+ // the same atomic way instead of failing closed forever: move it
388
+ // out of the canonical path, then recreate ours.
389
+ const cleared = removeLockDirAtomically(fsOps, lockDir);
390
+ if (!cleared.ok) {
391
+ return { ok: false, reason: 'lock_io_error', message: `failed to move the orphaned CAS lock aside: ${cleared.error?.message ?? 'io error'}` };
392
+ }
393
+ return createOwned();
394
+ }
395
+ return { ok: false, reason: 'lock_io_error', message: `failed to create CAS lock directory: ${probe.error?.message ?? 'io error'}` };
396
+ }
397
+ if (!ownerRead.ok) {
398
+ if (ownerRead.code === 'malformed') {
399
+ return { ok: false, reason: 'lock_invalid', message: `CAS lock ${lockDir} has malformed owner metadata; a human must inspect and remove it` };
400
+ }
401
+ return { ok: false, reason: 'lock_io_error', message: `failed to read CAS lock owner metadata: ${ownerRead.error?.message ?? 'io error'}` };
402
+ }
403
+ const holder = parseLockOwner(ownerRead.value);
404
+ if (holder === null) {
405
+ return { ok: false, reason: 'lock_invalid', message: `CAS lock ${lockDir} has missing or malformed owner metadata; a human must inspect and remove it` };
406
+ }
407
+ gateSync('lock-evaluated');
408
+ const ageMs = Date.parse(holder.createdAt);
409
+ const age = Number.isFinite(ageMs) ? now().getTime() - ageMs : Number.POSITIVE_INFINITY;
410
+ const liveness = holder.host === os.hostname() && holder.pid > 0
411
+ ? processAlive(holder.pid)
412
+ : 'unknown';
413
+ if (liveness !== 'dead') {
414
+ return {
415
+ ok: false,
416
+ reason: 'lock_busy',
417
+ message: `CAS lock held by operation=${holder.operation} pid=${holder.pid} host=${holder.host} ageMs=${Math.max(0, Math.round(age))} target=${holder.workspaceDir} liveness=${liveness} (a lock is only reclaimed when its holder PID is provably dead)`,
418
+ holder,
419
+ };
420
+ }
421
+ // Provably-dead holder → serialized reclaim: atomic move-out of the
422
+ // whole dir + recreate inside the SAME gate transaction, so no new
423
+ // lock can land in between and a mid-delete kill cannot strand an
424
+ // owner-less dir at the lock path.
425
+ const removed = removeLockDirAtomically(fsOps, lockDir);
426
+ if (!removed.ok) {
427
+ return { ok: false, reason: 'lock_io_error', message: `failed to move the dead holder's CAS lock aside: ${removed.error?.message ?? 'io error'}` };
428
+ }
429
+ gateSync('stale-removed');
430
+ return createOwned();
431
+ });
432
+ if (!gated.ok)
433
+ return { ok: false, reason: gated.reason, message: gated.message };
434
+ const acquired = gated.value;
435
+ if (!acquired.ok)
436
+ return acquired;
437
+ const { owner } = acquired;
438
+ return {
439
+ ok: true,
440
+ handle: {
441
+ lockDir,
442
+ owner,
443
+ release: () => {
444
+ // Compare-and-delete under the SAME arbitration gate: the owner
445
+ // metadata is re-read inside the transaction and the directory is
446
+ // removed only while it still carries OUR token — a foreign or
447
+ // replaced lock is never deleted, and no contender can interleave
448
+ // between the verify and the remove (PRI-1282 review round 4).
449
+ void withCasGate(options.manifestPath, { busyTimeoutMs: CAS_GATE_RELEASE_BUSY_MS, openGate: options.probes?.openGate }, () => {
450
+ const current = fsOps.readJson(ownerFile);
451
+ const parsed = current.ok ? parseLockOwner(current.value) : null;
452
+ if (parsed !== null && parsed.token === owner.token) {
453
+ removeLockDirAtomically(fsOps, lockDir);
454
+ }
455
+ // Absent or foreign: nothing provably ours to remove — leave it.
456
+ });
457
+ },
458
+ },
459
+ };
460
+ }
461
+ /**
462
+ * Run a manifest read-modify-write under the SAME physical lock the §8.4
463
+ * transition path takes (ERR-168: a whole-object load→modify→save writer that
464
+ * ignores the locked single-writer mutator can clobber its sub-section). The
465
+ * installer and update-side config writers wrap their writes with this; the
466
+ * transition primitive uses the lock directly. Lock failure is LOUD — a
467
+ * writer must never fall back to an unlocked write.
468
+ */
469
+ export function withInstallManifestWriteLock(options, fn) {
470
+ const retries = options.retries ?? 5;
471
+ const retryDelayMs = options.retryDelayMs ?? 50;
472
+ let lastFailure;
473
+ for (let attempt = 0; attempt <= retries; attempt += 1) {
474
+ const lock = acquireBackgroundExecutionCasLock({
475
+ manifestPath: options.manifestPath,
476
+ operation: options.operation,
477
+ workspaceDir: options.context,
478
+ now: options.now,
479
+ fsOps: options.fsOps,
480
+ });
481
+ if (lock.ok) {
482
+ try {
483
+ return { ok: true, value: fn() };
484
+ }
485
+ finally {
486
+ lock.handle.release();
487
+ }
488
+ }
489
+ lastFailure = { reason: lock.reason, message: lock.message };
490
+ if (lock.reason !== 'lock_busy')
491
+ break; // invalid/io failures never improve by retrying
492
+ if (attempt < retries)
493
+ busyWaitMs(retryDelayMs);
494
+ }
495
+ return { ok: false, reason: lastFailure?.reason ?? 'lock_busy', message: lastFailure?.message ?? 'lock acquisition failed' };
496
+ }
497
+ function sameOwnershipRecord(a, b) {
498
+ return a.state === b.state
499
+ && a.effectiveOwner === b.effectiveOwner
500
+ && a.generation === b.generation
501
+ && a.operationId === b.operationId
502
+ && a.previousOwner === b.previousOwner
503
+ && a.targetOwner === b.targetOwner;
504
+ }
505
+ function resolveOwnershipIdentity(args) {
506
+ const { manifest, workspaceDir, platform, realpath } = args;
507
+ const api = platform === 'win32' ? path.win32 : path.posix;
508
+ const identityOf = (candidate) => {
509
+ const lexical = api.resolve(candidate);
510
+ const resolved = realpath(lexical) ?? lexical;
511
+ return platform === 'win32' ? resolved.toLowerCase() : resolved;
512
+ };
513
+ const target = identityOf(workspaceDir);
514
+ const registeredAliases = (manifest.workspaces ?? []).filter((entry) => identityOf(entry) === target);
515
+ const records = [];
516
+ for (const key of registeredAliases) {
517
+ const record = manifest.backgroundExecutions?.[key];
518
+ if (record !== undefined && !records.some((entry) => sameOwnershipRecord(entry.record, record))) {
519
+ records.push({ key, record });
520
+ }
521
+ }
522
+ return { registeredAliases, records, conflicting: records.length > 1 };
523
+ }
524
+ const OWNER_ALIAS_CONFLICT_NEXT_ACTION = 'Two registered path spellings of the same directory carry DIFFERENT ownership records; a writer must reconcile ~/.pd/install.json (remove the duplicate workspace entry / record) before background execution decisions.';
525
+ /**
526
+ * The single read-side projection of §8.4 ownership for ONE workspace.
527
+ * Consumers: the OpenClaw Gateway start/tick gate, the `pd openclaw worker`
528
+ * gate, and the handover/rollback commands. Fail-closed: an unreadable or
529
+ * malformed manifest is `manifest_unreadable` — "cannot decide" is NEVER
530
+ * collapsed into "legacy by default" for a consumer that is about to act.
531
+ */
532
+ export function readWorkspaceBackgroundOwnership(options) {
533
+ const fsOps = options.fsOps ?? realFsOps;
534
+ const text = fsOps.readFile(options.manifestPath);
535
+ if (!text.ok) {
536
+ return {
537
+ status: 'manifest_unreadable',
538
+ reason: text.code === 'missing' ? 'install_manifest_missing' : 'install_manifest_io_error',
539
+ nextAction: text.code === 'missing'
540
+ ? 'The PD install manifest was not found; run the PD installer or restore ~/.pd/install.json before background execution decisions.'
541
+ : 'The PD install manifest could not be read; check permissions/disk and restore ~/.pd/install.json before background execution decisions.',
542
+ };
543
+ }
544
+ let raw;
545
+ try {
546
+ raw = JSON.parse(text.text);
547
+ }
548
+ catch {
549
+ return {
550
+ status: 'manifest_unreadable',
551
+ reason: 'install_manifest_malformed',
552
+ nextAction: 'The PD install manifest is not valid JSON; repair ~/.pd/install.json before background execution decisions.',
553
+ };
554
+ }
555
+ const parsed = parseInstallManifest(raw, options.platform);
556
+ if (!parsed.manifest) {
557
+ return {
558
+ status: 'manifest_unreadable',
559
+ reason: parsed.error ?? 'install_manifest_malformed',
560
+ nextAction: 'The PD install manifest failed validation; repair ~/.pd/install.json before background execution decisions.',
561
+ };
562
+ }
563
+ const platform = options.platform ?? process.platform;
564
+ const api = platform === 'win32' ? path.win32 : path.posix;
565
+ const canonical = api.resolve(options.workspaceDir);
566
+ const identity = resolveOwnershipIdentity({
567
+ manifest: parsed.manifest,
568
+ workspaceDir: canonical,
569
+ platform,
570
+ realpath: options.realpath ?? defaultRealpath,
571
+ });
572
+ if (identity.conflicting) {
573
+ return {
574
+ status: 'manifest_unreadable',
575
+ reason: `owner_alias_conflict:${identity.records.map((entry) => entry.key).join('|')}`,
576
+ nextAction: OWNER_ALIAS_CONFLICT_NEXT_ACTION,
577
+ };
578
+ }
579
+ const record = identity.records[0]?.record;
580
+ if (record === undefined) {
581
+ return { status: 'legacy_owned', source: 'no_record', generation: 0 };
582
+ }
583
+ if (record.state === 'legacy_owned') {
584
+ return { status: 'legacy_owned', source: 'record', generation: record.generation, record };
585
+ }
586
+ return { status: record.state, generation: record.generation, record };
587
+ }
588
+ // ─── Transitions ────────────────────────────────────────────────────────────
589
+ export const BACKGROUND_EXECUTION_TRANSITIONS = [
590
+ 'begin_handover',
591
+ 'abort_handover',
592
+ 'complete_handover',
593
+ 'begin_rollback',
594
+ 'complete_rollback',
595
+ 'abort_rollback',
596
+ ];
597
+ const TRANSITION_SPECS = {
598
+ // legacy_owned -> handover_preparing; effectiveOwner stays legacy (SPEC §8.4-3:
599
+ // PREPARING grants no new rights — the old consumer remains the only one).
600
+ begin_handover: { from: ['legacy_owned', 'handover_preparing'], to: 'handover_preparing', needsOperationId: true },
601
+ abort_handover: { from: ['handover_preparing'], to: 'legacy_owned', needsOperationId: false },
602
+ complete_handover: { from: ['handover_preparing'], to: 'service_host_owned', needsOperationId: false },
603
+ begin_rollback: { from: ['service_host_owned', 'rollback_pending'], to: 'rollback_pending', needsOperationId: true },
604
+ complete_rollback: { from: ['rollback_pending'], to: 'legacy_owned', needsOperationId: false },
605
+ abort_rollback: { from: ['rollback_pending'], to: 'service_host_owned', needsOperationId: false },
606
+ };
607
+ function buildTargetRecord(context) {
608
+ const generation = context.currentGeneration + 1;
609
+ const { operationId, nowIso } = context;
610
+ switch (context.kind) {
611
+ case 'begin_handover':
612
+ return { state: 'handover_preparing', effectiveOwner: 'legacy', generation, operationId, previousOwner: 'legacy', targetOwner: 'service_host', updatedAt: nowIso };
613
+ case 'abort_handover':
614
+ return { state: 'legacy_owned', effectiveOwner: 'legacy', generation, operationId: null, previousOwner: null, targetOwner: null, updatedAt: nowIso };
615
+ case 'complete_handover':
616
+ return { state: 'service_host_owned', effectiveOwner: 'service_host', generation, operationId: null, previousOwner: null, targetOwner: null, updatedAt: nowIso };
617
+ case 'begin_rollback':
618
+ return { state: 'rollback_pending', effectiveOwner: 'service_host', generation, operationId, previousOwner: 'service_host', targetOwner: 'legacy', updatedAt: nowIso };
619
+ case 'complete_rollback':
620
+ return { state: 'legacy_owned', effectiveOwner: 'legacy', generation, operationId: null, previousOwner: null, targetOwner: null, updatedAt: nowIso };
621
+ case 'abort_rollback':
622
+ return { state: 'service_host_owned', effectiveOwner: 'service_host', generation, operationId: null, previousOwner: null, targetOwner: null, updatedAt: nowIso };
623
+ }
624
+ }
625
+ function projectOwnership(state, generation, record) {
626
+ if (state === 'legacy_owned') {
627
+ return { status: 'legacy_owned', source: record !== undefined ? 'record' : 'no_record', generation, record };
628
+ }
629
+ if (record === undefined) {
630
+ // Unreachable for transition states (a record must exist), kept total.
631
+ return { status: 'legacy_owned', source: 'no_record', generation };
632
+ }
633
+ return { status: state, generation, record };
634
+ }
635
+ /**
636
+ * Execute one §8.4 state-machine transition for one Workspace under the CAS
637
+ * critical section. The manifest is read, validated, mutated as a RAW object
638
+ * (unknown top-level fields survive — the update side owns `channel` /
639
+ * `autoCheck` / `releaseMetadataUrl`), re-validated, and landed with an
640
+ * atomic rename. A legacy single-key `backgroundExecution` spelling is
641
+ * migrated to the per-Workspace map in the same write (both spellings after
642
+ * the write would be a parse conflict).
643
+ */
644
+ export function transitionWorkspaceBackgroundExecution(input) {
645
+ if (input.operationId.length === 0) {
646
+ return { ok: false, reason: 'invalid_input', message: 'operationId must be a non-empty idempotency key' };
647
+ }
648
+ const fsOps = input.fsOps ?? realFsOps;
649
+ const now = input.now ?? (() => new Date());
650
+ const lock = acquireBackgroundExecutionCasLock({
651
+ manifestPath: input.manifestPath,
652
+ operation: input.kind,
653
+ workspaceDir: input.workspaceDir,
654
+ staleMs: input.staleMs,
655
+ now,
656
+ fsOps,
657
+ probes: input.probes,
658
+ });
659
+ if (!lock.ok) {
660
+ return { ok: false, reason: lock.reason === 'lock_busy' ? 'lock_busy' : lock.reason === 'lock_invalid' ? 'lock_invalid' : 'lock_io_error', message: lock.message };
661
+ }
662
+ try {
663
+ const text = fsOps.readFile(input.manifestPath);
664
+ if (!text.ok) {
665
+ return {
666
+ ok: false,
667
+ reason: 'manifest_unreadable',
668
+ message: text.code === 'missing' ? 'install manifest not found' : 'install manifest not readable',
669
+ nextAction: 'Restore ~/.pd/install.json; a transition never fabricates a fresh manifest over a missing one.',
670
+ };
671
+ }
672
+ let raw;
673
+ try {
674
+ const parsedJson = JSON.parse(text.text);
675
+ if (!isJsonObject(parsedJson)) {
676
+ return { ok: false, reason: 'manifest_unreadable', message: 'install manifest is not a JSON object', nextAction: 'Repair ~/.pd/install.json.' };
677
+ }
678
+ raw = parsedJson;
679
+ }
680
+ catch {
681
+ return { ok: false, reason: 'manifest_unreadable', message: 'install manifest is not valid JSON', nextAction: 'Repair ~/.pd/install.json.' };
682
+ }
683
+ const parsed = parseInstallManifest(raw, input.platform);
684
+ if (!parsed.manifest) {
685
+ return { ok: false, reason: 'manifest_unreadable', message: parsed.error ?? 'install manifest malformed', nextAction: 'Repair ~/.pd/install.json.' };
686
+ }
687
+ const manifest = parsed.manifest;
688
+ const platform = input.platform ?? process.platform;
689
+ const pathApi = platform === 'win32' ? path.win32 : path.posix;
690
+ const canonical = pathApi.resolve(input.workspaceDir);
691
+ const realpath = input.realpath ?? defaultRealpath;
692
+ // The real directory the caller's path resolves to — records are pinned
693
+ // to THIS, never to a registered alias spelling that could repoint.
694
+ const realDir = pathApi.resolve(realpath(canonical) ?? canonical);
695
+ // Identity is the REAL directory: the record may live under any
696
+ // workspaces[] spelling of it (PRI-1282 review). Conflicting records
697
+ // under one real directory refuse — never guess which alias wins.
698
+ const identity = resolveOwnershipIdentity({ manifest, workspaceDir: canonical, platform, realpath });
699
+ if (identity.conflicting) {
700
+ return {
701
+ ok: false,
702
+ reason: 'manifest_unreadable',
703
+ message: `conflicting ownership records across path aliases: ${identity.records.map((entry) => entry.key).join(' vs ')}`,
704
+ nextAction: OWNER_ALIAS_CONFLICT_NEXT_ACTION,
705
+ };
706
+ }
707
+ // Workspace registration: begin_handover may register (single atomic write
708
+ // together with the record); every other kind requires existing membership
709
+ // because a marker key outside `workspaces[]` cannot parse back. An alias
710
+ // registration for the same real directory counts as registered.
711
+ const registered = identity.registeredAliases.length > 0;
712
+ if (!registered && !(input.kind === 'begin_handover' && input.registerWorkspace === true)) {
713
+ return {
714
+ ok: false,
715
+ reason: 'workspace_not_registered',
716
+ message: `workspace ${canonical} is not in the manifest workspaces list`,
717
+ nextAction: 'Register the workspace through a begin_handover with registration, or the installer bind path.',
718
+ };
719
+ }
720
+ const spec = TRANSITION_SPECS[input.kind];
721
+ const recordKey = realDir;
722
+ const priorKey = identity.records[0]?.key;
723
+ const currentRecord = identity.records[0]?.record;
724
+ const currentState = currentRecord?.state ?? 'legacy_owned';
725
+ const currentGeneration = currentRecord?.generation ?? 0;
726
+ if (input.expectedGeneration !== undefined && input.expectedGeneration !== currentGeneration) {
727
+ return {
728
+ ok: false,
729
+ reason: 'stale_generation',
730
+ message: `observed generation ${input.expectedGeneration} but the manifest holds ${currentGeneration}`,
731
+ nextAction: 'Re-read the ownership record and retry with the current generation; a stale observer never writes.',
732
+ current: projectOwnership(currentState, currentGeneration, currentRecord),
733
+ };
734
+ }
735
+ if (currentRecord !== undefined && currentState === spec.to && spec.needsOperationId) {
736
+ // Idempotent begin replay: same operationId onto the same transition
737
+ // state is a no-op; a different id means another operation owns it.
738
+ const holderOp = currentRecord.operationId ?? '';
739
+ if (holderOp === input.operationId) {
740
+ return { ok: true, changed: false, record: currentRecord, previous: currentRecord };
741
+ }
742
+ return {
743
+ ok: false,
744
+ reason: 'operation_in_progress',
745
+ message: `workspace is ${currentState} under operationId ${holderOp || '(none)'}; refusing to start ${input.operationId}`,
746
+ nextAction: 'Wait for the in-flight operation to finish or abort it explicitly; one transition operation per workspace.',
747
+ current: projectOwnership(currentState, currentGeneration, currentRecord),
748
+ };
749
+ }
750
+ if (!spec.from.includes(currentState)) {
751
+ return {
752
+ ok: false,
753
+ reason: 'unexpected_state',
754
+ message: `${input.kind} requires state ${spec.from.join('|')} but the workspace is ${currentState}`,
755
+ nextAction: 'Re-read the ownership record; recovery continues from the persisted state, never from process liveness.',
756
+ current: projectOwnership(currentState, currentGeneration, currentRecord),
757
+ };
758
+ }
759
+ // complete/abort must address the operation that opened the transition.
760
+ if (currentState === 'handover_preparing' || currentState === 'rollback_pending') {
761
+ const holderOp = currentRecord?.operationId ?? '';
762
+ if (holderOp !== input.operationId) {
763
+ return {
764
+ ok: false,
765
+ reason: 'operation_mismatch',
766
+ message: `${input.kind} addresses operationId ${input.operationId} but the transition record holds ${holderOp || '(none)'}`,
767
+ nextAction: 'Use the persisted operationId, or abort the in-flight operation first.',
768
+ current: projectOwnership(currentState, currentGeneration, currentRecord),
769
+ };
770
+ }
771
+ }
772
+ const target = buildTargetRecord({
773
+ kind: input.kind,
774
+ currentGeneration,
775
+ operationId: input.operationId,
776
+ nowIso: now().toISOString(),
777
+ });
778
+ // Mutate the RAW object (unknown top-level fields survive) using the same
779
+ // single-key authority helper the schema exposes. The record key is the
780
+ // REAL directory; a record persisting under an alias spelling migrates
781
+ // onto it in the same write so a repointed symlink cannot carry this
782
+ // workspace's ownership to another directory (PRI-1282 review).
783
+ const nextRecords = setInstallManifestBackgroundExecution(manifest, { workspaceDir: recordKey, platform }, target);
784
+ if (priorKey !== undefined && priorKey !== recordKey) {
785
+ delete nextRecords[priorKey];
786
+ }
787
+ if (Object.keys(nextRecords).length > 0) {
788
+ raw.backgroundExecutions = nextRecords;
789
+ }
790
+ else {
791
+ delete raw.backgroundExecutions;
792
+ }
793
+ // Migrate the legacy single-key spelling away in the same write.
794
+ delete raw.backgroundExecution;
795
+ // The record key MUST be a workspaces[] member or it cannot parse back:
796
+ // the real directory registers in the same CAS — on begin_handover for
797
+ // a new workspace, on any later transition that migrated an alias-keyed
798
+ // record (PRI-1282 review).
799
+ const registeredKeys = manifest.workspaces ?? [];
800
+ const recordKeyRegistered = registeredKeys.some((entry) => pathApi.resolve(entry) === recordKey);
801
+ if (!recordKeyRegistered) {
802
+ raw.workspaces = mergeInstallManifestWorkspaces(manifest, recordKey, platform);
803
+ raw.hosts = installManifestHostsForPersist(manifest);
804
+ }
805
+ else if (input.kind === 'begin_handover' && input.registerWorkspace === true && !registered) {
806
+ raw.workspaces = mergeInstallManifestWorkspaces(manifest, recordKey, platform);
807
+ raw.hosts = installManifestHostsForPersist(manifest);
808
+ }
809
+ // Re-validate the exact bytes we are about to land.
810
+ const revalidated = parseInstallManifest(raw, input.platform);
811
+ if (!revalidated.manifest || revalidated.manifest.backgroundExecutions?.[recordKey] === undefined) {
812
+ return {
813
+ ok: false,
814
+ reason: 'io_error',
815
+ message: `post-mutation validation failed: ${revalidated.error ?? 'target record missing after mutation'}`,
816
+ nextAction: 'The manifest was NOT written; report this with the manifest backup.',
817
+ };
818
+ }
819
+ const serialized = JSON.stringify(raw, null, 2) + '\n';
820
+ const tempPath = `${input.manifestPath}.cas-tmp-${process.pid}-${randomToken()}`;
821
+ const written = fsOps.writeFile(tempPath, serialized);
822
+ if (!written.ok) {
823
+ fsOps.removeDir(tempPath);
824
+ return { ok: false, reason: 'io_error', message: `failed to write transition temp file: ${written.error?.message ?? 'io error'}` };
825
+ }
826
+ const renamed = fsOps.rename(tempPath, input.manifestPath);
827
+ if (!renamed.ok) {
828
+ fsOps.removeDir(tempPath);
829
+ return { ok: false, reason: 'io_error', message: `failed to land the transition atomically: ${renamed.error?.message ?? 'io error'}` };
830
+ }
831
+ return { ok: true, changed: true, record: target, previous: currentRecord };
832
+ }
833
+ finally {
834
+ lock.handle.release();
835
+ }
836
+ }