create-principles-disciple 1.154.4 → 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,1393 @@
1
+ /**
2
+ * Per-Workspace §8.4 atomic handover / rollback orchestration
3
+ * (SPEC-PD-SERVICE-HOST-001 §8.4, TD §9; PRI-1282 Phase 4).
4
+ *
5
+ * The state machine itself lives in `@principles/install-layout`
6
+ * (`transitionWorkspaceBackgroundExecution` — cross-process lock,
7
+ * generation fencing, operationId idempotency). This module is the SEQUENCE
8
+ * orchestrator the Operator drives:
9
+ *
10
+ * HANDOVER (irreversible-order steps, none may be skipped):
11
+ * 1. verify ownership readability + openclaw host binding (claims);
12
+ * 2. begin_handover (registers the workspace in the manifest in the SAME
13
+ * atomic write; effectiveOwner stays legacy — PREPARING grants no
14
+ * rights);
15
+ * 3. no-consume readiness via the ACTIVE-RELEASE worker
16
+ * (`openclaw worker --readiness`) — proves install wiring, declaration,
17
+ * evidence port and credentials WITHOUT consuming;
18
+ * 4. wait for the Gateway's persisted quiesce acknowledgment
19
+ * (`pd.gateway-quiesce.v1`, bound to this operationId + generation) —
20
+ * clearTimeout / PID absence / process exit are never substitutes;
21
+ * 5. ONE CAS transition to service_host_owned;
22
+ * 6. drive one real worker cycle through the same managed adapter the
23
+ * scheduler uses;
24
+ * 7. persist the completion evidence under <pdHome>/service/handover/.
25
+ *
26
+ * ROLLBACK mirrors it: stop new cycles (run-lock busy check) →
27
+ * begin_rollback → complete_rollback (CAS back to legacy) → observe the
28
+ * Gateway's resumption evidence (or record NOT_VERIFIED when the Gateway
29
+ * is not running) → evidence.
30
+ *
31
+ * Crash recovery is deterministic: every step re-derives from the persisted
32
+ * `state + operationId + generation` (design §7.3). Process liveness is
33
+ * never consulted.
34
+ */
35
+ import * as crypto from 'node:crypto';
36
+ import * as fs from 'node:fs';
37
+ import * as path from 'node:path';
38
+ import { readWorkspaceBackgroundOwnership, transitionWorkspaceBackgroundExecution, } from '@principles/install-layout';
39
+ import { resolveCoordinatorInstallIdentity } from './install-identity.js';
40
+ import { collectHostWorkspaceClaimsFor } from './handover-claims.js';
41
+ import { acquireServiceRunLock, probeServiceRunLockState, releaseServiceRunLock, workspaceServiceRunLockPath } from './locking/service-run-lock.js';
42
+ import { runSchedulerLifecycle } from './scheduler/index.js';
43
+ import { readActiveReleaseFacts } from './status/service-run-status.js';
44
+ import { buildWorkerEnvironment } from './worker-env.js';
45
+ import { readConfigCredentialEnvNames, resolveActiveReleaseCliEntry } from './worker-adapter.js';
46
+ import { createOpenClawWorkerAdapter } from './worker-adapter-openclaw.js';
47
+ import { runWorkerProcess } from './worker-process.js';
48
+ /* eslint-disable @typescript-eslint/no-use-before-define -- helpers declared after main, matching codebase convention */
49
+ export const DEFAULT_HANDOVER_ACK_WAIT_MS = 15 * 60_000;
50
+ export const DEFAULT_HANDOVER_STEP_TIMEOUT_MS = 2 * 60_000;
51
+ export const DEFAULT_ROLLBACK_RESUME_WAIT_MS = 90_000;
52
+ /**
53
+ * Bounded wait for the last in-flight worker cycle to release the workspace
54
+ * run mutex during rollback (PRI-1282 P1-1). Matches the consumer cycle's
55
+ * own bound; on expiry the workspace stays rollback_pending and resumable.
56
+ */
57
+ export const DEFAULT_ROLLBACK_DRAIN_WAIT_MS = 10 * 60_000;
58
+ const HANDOVER_EVIDENCE_SCHEMA = 'pd.service-handover-evidence.v1';
59
+ const HANDOVER_INTENT_SCHEMA = 'pd.service-handover-intent.v1';
60
+ export function establishHandoverContext(workspaceDir, input) {
61
+ const identity = resolveCoordinatorInstallIdentity(input.env ?? process.env, input.pdHomeOverride !== undefined ? { trustedHomeDir: input.pdHomeOverride } : {});
62
+ if (!identity.ok) {
63
+ return { ok: false, reason: `install_identity_unresolved:${identity.reason}`, nextAction: identity.nextAction };
64
+ }
65
+ const manifestPath = path.join(identity.identity.pdHome, 'install.json');
66
+ let workspace;
67
+ try {
68
+ workspace = path.resolve(workspaceDir);
69
+ }
70
+ catch {
71
+ return { ok: false, reason: 'workspace_path_invalid', nextAction: 'Pass an absolute canonical workspace directory.' };
72
+ }
73
+ // Pin the workspace to its REAL directory: intent files, evidence files,
74
+ // the worker launch and the workspace run mutex are all keyed off this
75
+ // spelling, so a symlinked and a real-path invocation meet the SAME
76
+ // operation and either spelling resumes it (PRI-1282 review).
77
+ try {
78
+ workspace = fs.realpathSync.native(workspace);
79
+ }
80
+ catch {
81
+ // Unresolvable target: keep the lexical spelling — the readiness probe
82
+ // reports the missing directory as the honest failure.
83
+ }
84
+ return { ok: true, pdHome: identity.identity.pdHome, homeDir: identity.identity.homeDir, manifestPath, workspaceDir: workspace };
85
+ }
86
+ function wait(ms) {
87
+ // REF'd on purpose: these are operator-command orchestration waits (ack
88
+ // polling, resumption observation) with hard deadlines. An unref'd timer
89
+ // here let Node exit mid-await with a pending promise — transitions
90
+ // applied, stdout empty, exit 0 (found in Stage 9 acceptance).
91
+ return new Promise((resolve) => {
92
+ setTimeout(resolve, ms);
93
+ });
94
+ }
95
+ function nowIso() {
96
+ return new Date().toISOString();
97
+ }
98
+ /**
99
+ * Sanitized single-line key for the evidence directory (no path
100
+ * separators). A readable stem ALONE is a real collision surface
101
+ * (`/tmp/a b` vs `/tmp/a_b` → same key → cross-workspace evidence mixing,
102
+ * PRI-1282 review P1-6), so the full path's SHA-256 suffix is the actual
103
+ * identity; the stem only keeps the directory browsable.
104
+ */
105
+ function workspaceEvidenceKey(canonicalDir) {
106
+ const stem = canonicalDir.replace(/[^A-Za-z0-9._-]+/g, '_').slice(-48);
107
+ const digest = crypto.createHash('sha256').update(canonicalDir, 'utf8').digest('hex').slice(0, 16);
108
+ return `${stem}-${digest}`;
109
+ }
110
+ /**
111
+ * operationId is the operation's idempotency key AND a filename component
112
+ * under <pdHome>/service/handover/ — an operator-supplied value that
113
+ * reached the filesystem unchecked allowed path traversal (PRI-1282 review
114
+ * P1-6). Whitelisted to characters that are safe on every filesystem.
115
+ */
116
+ const SAFE_OPERATION_ID = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;
117
+ function isSafeOperationId(operationId) {
118
+ return SAFE_OPERATION_ID.test(operationId);
119
+ }
120
+ /**
121
+ * Canonical-directory equality for the persisted quiesce ack (PRI-1282 r4
122
+ * §11): writer, reader and this context all key off REAL directory
123
+ * identity — an ack recorded under a symlinked alias spelling of the same
124
+ * directory binds it; a spelling that resolves elsewhere does not. An
125
+ * unresolvable spelling fails closed (no match).
126
+ */
127
+ function ackWorkspaceMatches(recorded, canonicalDir) {
128
+ let realRecorded;
129
+ try {
130
+ realRecorded = fs.realpathSync.native(recorded);
131
+ }
132
+ catch {
133
+ realRecorded = path.resolve(recorded);
134
+ }
135
+ let realCanonical;
136
+ try {
137
+ realCanonical = fs.realpathSync.native(canonicalDir);
138
+ }
139
+ catch {
140
+ realCanonical = path.resolve(canonicalDir);
141
+ }
142
+ return realRecorded === realCanonical;
143
+ }
144
+ function errnoOf(error) {
145
+ return typeof error === 'object' && error !== null && Object.hasOwn(error, 'code')
146
+ ? String(Reflect.get(error, 'code'))
147
+ : '';
148
+ }
149
+ export function handoverEvidencePath(pdHome, canonicalDir, operationId) {
150
+ return path.join(pdHome, 'service', 'handover', workspaceEvidenceKey(canonicalDir), `${operationId}.json`);
151
+ }
152
+ export function writeHandoverEvidence(evidence, pdHome) {
153
+ if (!isSafeOperationId(evidence.operationId)) {
154
+ return { ok: false, path: handoverEvidencePath(pdHome, evidence.workspaceDir, 'invalid'), reason: 'operation_id_invalid' };
155
+ }
156
+ const target = handoverEvidencePath(pdHome, evidence.workspaceDir, evidence.operationId);
157
+ try {
158
+ fs.mkdirSync(path.dirname(target), { recursive: true });
159
+ const tmp = `${target}.${process.pid}.${crypto.randomUUID().slice(0, 8)}.tmp`;
160
+ const fd = fs.openSync(tmp, fs.constants.O_WRONLY | fs.constants.O_CREAT | fs.constants.O_EXCL, 0o600);
161
+ try {
162
+ fs.writeFileSync(fd, JSON.stringify(evidence, null, 2) + '\n');
163
+ }
164
+ finally {
165
+ fs.closeSync(fd);
166
+ }
167
+ try {
168
+ // Write-once, ATOMICALLY: link() fails with EEXIST instead of
169
+ // replacing — rename() would silently overwrite a concurrently
170
+ // published document (PRI-1282 review P1-6).
171
+ fs.linkSync(tmp, target);
172
+ }
173
+ catch (linkError) {
174
+ try {
175
+ fs.unlinkSync(tmp);
176
+ }
177
+ catch { /* best effort */ }
178
+ if (errnoOf(linkError) === 'EEXIST') {
179
+ // An existing document is accepted ONLY when its FULL immutable
180
+ // identity is this operation's: schemaVersion + kind + operationId
181
+ // + workspaceDir are already proven by readHandoverEvidence's field
182
+ // check; outcome and the final ownership identity (status +
183
+ // generation) must also match — a same-named different-identity
184
+ // document is a conflict, never a no-op (PRI-1282 review r4 §6.1).
185
+ // startedAt/completedAt/steps are NOT part of the identity: a
186
+ // legitimate crash-retry of the SAME operation records its own
187
+ // timestamps.
188
+ const existing = readHandoverEvidence(pdHome, evidence.workspaceDir, evidence.operationId);
189
+ const generationOf = (doc) => doc.finalOwnership.status === 'manifest_unreadable' ? -1 : doc.finalOwnership.generation;
190
+ if (existing !== null
191
+ && existing.kind === evidence.kind
192
+ && existing.outcome === evidence.outcome
193
+ && existing.finalOwnership.status === evidence.finalOwnership.status
194
+ && generationOf(existing) === generationOf(evidence)) {
195
+ return { ok: true, path: target, reason: 'already_exists' };
196
+ }
197
+ return { ok: false, path: target, reason: 'evidence_identity_conflict' };
198
+ }
199
+ throw linkError;
200
+ }
201
+ fs.unlinkSync(tmp);
202
+ return { ok: true, path: target };
203
+ }
204
+ catch (error) {
205
+ return { ok: false, path: target, reason: error instanceof Error ? error.message : String(error) };
206
+ }
207
+ }
208
+ function isJsonObject(value) {
209
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
210
+ }
211
+ function isNonEmptyString(value) {
212
+ return typeof value === 'string' && value.length > 0;
213
+ }
214
+ /** Field-level validation of one persisted evidence step (rc-3/rc-4). */
215
+ function parseEvidenceStep(value) {
216
+ if (!isJsonObject(value))
217
+ return null;
218
+ if (!isNonEmptyString(value.step) || !isNonEmptyString(value.at) || !isNonEmptyString(value.outcome))
219
+ return null;
220
+ if (value.detail !== undefined && !isNonEmptyString(value.detail))
221
+ return null;
222
+ return { step: value.step, at: value.at, outcome: value.outcome, ...(value.detail !== undefined ? { detail: value.detail } : {}) };
223
+ }
224
+ /**
225
+ * Field-level validation of one embedded BackgroundExecutionRecord
226
+ * (rc-3: required fields validated explicitly, never cast into shape).
227
+ */
228
+ function parseEvidenceRecord(value, state) {
229
+ if (!isJsonObject(value))
230
+ return null;
231
+ if (value.state !== state)
232
+ return null;
233
+ if (value.effectiveOwner !== 'legacy' && value.effectiveOwner !== 'service_host')
234
+ return null;
235
+ if (typeof value.generation !== 'number' || !Number.isInteger(value.generation) || value.generation < 0)
236
+ return null;
237
+ if (value.operationId !== null && !isNonEmptyString(value.operationId))
238
+ return null;
239
+ if (value.previousOwner !== null && value.previousOwner !== 'legacy' && value.previousOwner !== 'service_host')
240
+ return null;
241
+ if (value.targetOwner !== null && value.targetOwner !== 'legacy' && value.targetOwner !== 'service_host')
242
+ return null;
243
+ if (!isNonEmptyString(value.updatedAt))
244
+ return null;
245
+ return {
246
+ state,
247
+ effectiveOwner: value.effectiveOwner,
248
+ generation: value.generation,
249
+ operationId: value.operationId ?? null,
250
+ previousOwner: value.previousOwner,
251
+ targetOwner: value.targetOwner,
252
+ updatedAt: value.updatedAt,
253
+ };
254
+ }
255
+ /**
256
+ * Field-level validation of the persisted ownership projection embedded in
257
+ * an evidence document (rc-2/rc-3: untrusted JSON until proven). Every
258
+ * branch constructs its exact variant from validated fields — no casts.
259
+ */
260
+ function parseEvidenceOwnership(value) {
261
+ if (!isJsonObject(value))
262
+ return null;
263
+ if (typeof value.generation !== 'number' || !Number.isInteger(value.generation) || value.generation < 0)
264
+ return null;
265
+ if (value.status === 'legacy_owned') {
266
+ if (value.source !== 'record' && value.source !== 'no_record')
267
+ return null;
268
+ if (value.record === undefined) {
269
+ return { status: 'legacy_owned', source: value.source, generation: value.generation };
270
+ }
271
+ const record = parseEvidenceRecord(value.record, 'legacy_owned');
272
+ if (record === null)
273
+ return null;
274
+ return { status: 'legacy_owned', source: value.source, generation: value.generation, record };
275
+ }
276
+ if (value.status === 'manifest_unreadable') {
277
+ if (!isNonEmptyString(value.reason) || !isNonEmptyString(value.nextAction))
278
+ return null;
279
+ return { status: 'manifest_unreadable', reason: value.reason, nextAction: value.nextAction };
280
+ }
281
+ if (value.status !== 'handover_preparing' && value.status !== 'service_host_owned' && value.status !== 'rollback_pending') {
282
+ return null;
283
+ }
284
+ const record = parseEvidenceRecord(value.record, value.status);
285
+ if (record === null)
286
+ return null;
287
+ return {
288
+ status: value.status,
289
+ generation: value.generation,
290
+ record,
291
+ };
292
+ }
293
+ /**
294
+ * Read + field-validate the write-once evidence document (rc-2/rc-3:
295
+ * untrusted JSON until proven — an unreadable or malformed document is
296
+ * null, i.e. "no evidence", and the caller fails closed).
297
+ */
298
+ export function readHandoverEvidence(pdHome, canonicalDir, operationId) {
299
+ try {
300
+ const parsed = JSON.parse(fs.readFileSync(handoverEvidencePath(pdHome, canonicalDir, operationId), 'utf8'));
301
+ if (!isJsonObject(parsed))
302
+ return null;
303
+ if (parsed.schemaVersion !== HANDOVER_EVIDENCE_SCHEMA)
304
+ return null;
305
+ if (parsed.kind !== 'handover' && parsed.kind !== 'rollback')
306
+ return null;
307
+ if (!isNonEmptyString(parsed.operationId) || !isNonEmptyString(parsed.workspaceDir))
308
+ return null;
309
+ // PRI-1282 review P1-6: the document must BE this operation's evidence
310
+ // for THIS workspace — a field check, not just path keying (path keying
311
+ // alone let a colliding wskey satisfy a foreign workspace's resume).
312
+ if (parsed.operationId !== operationId || parsed.workspaceDir !== canonicalDir)
313
+ return null;
314
+ if (!isNonEmptyString(parsed.startedAt) || !isNonEmptyString(parsed.completedAt))
315
+ return null;
316
+ if (parsed.outcome !== 'completed' && parsed.outcome !== 'aborted' && parsed.outcome !== 'failed')
317
+ return null;
318
+ if (!Array.isArray(parsed.steps))
319
+ return null;
320
+ const steps = [];
321
+ for (const rawStep of parsed.steps) {
322
+ const step = parseEvidenceStep(rawStep);
323
+ if (step === null)
324
+ return null;
325
+ steps.push(step);
326
+ }
327
+ const finalOwnership = parseEvidenceOwnership(parsed.finalOwnership);
328
+ if (finalOwnership === null)
329
+ return null;
330
+ return {
331
+ schemaVersion: HANDOVER_EVIDENCE_SCHEMA,
332
+ kind: parsed.kind,
333
+ operationId: parsed.operationId,
334
+ workspaceDir: parsed.workspaceDir,
335
+ startedAt: parsed.startedAt,
336
+ completedAt: parsed.completedAt,
337
+ outcome: parsed.outcome,
338
+ steps,
339
+ finalOwnership,
340
+ };
341
+ }
342
+ catch {
343
+ return null;
344
+ }
345
+ }
346
+ export function handoverIntentPath(pdHome, canonicalDir, operationId) {
347
+ return path.join(pdHome, 'service', 'handover', workspaceEvidenceKey(canonicalDir), `${operationId}.intent.json`);
348
+ }
349
+ export function writeHandoverIntent(intent, pdHome) {
350
+ if (!isSafeOperationId(intent.operationId)) {
351
+ return { ok: false, path: handoverIntentPath(pdHome, intent.workspaceDir, 'invalid'), reason: 'operation_id_invalid' };
352
+ }
353
+ const target = handoverIntentPath(pdHome, intent.workspaceDir, intent.operationId);
354
+ try {
355
+ fs.mkdirSync(path.dirname(target), { recursive: true });
356
+ const tmp = `${target}.${process.pid}.${crypto.randomUUID().slice(0, 8)}.tmp`;
357
+ const fd = fs.openSync(tmp, fs.constants.O_WRONLY | fs.constants.O_CREAT | fs.constants.O_EXCL, 0o600);
358
+ try {
359
+ fs.writeFileSync(fd, JSON.stringify(intent, null, 2) + '\n');
360
+ }
361
+ finally {
362
+ fs.closeSync(fd);
363
+ }
364
+ try {
365
+ // Atomic no-replace publish, same posture as the evidence document.
366
+ fs.linkSync(tmp, target);
367
+ }
368
+ catch (linkError) {
369
+ try {
370
+ fs.unlinkSync(tmp);
371
+ }
372
+ catch { /* best effort */ }
373
+ if (errnoOf(linkError) === 'EEXIST') {
374
+ // Full-identity compare (PRI-1282 r4 §6.2): kind/schemaVersion are
375
+ // proven by the reader's field check, but the operation AND the
376
+ // generation pair must also match — an operationId reused across
377
+ // generations is a conflict, never an idempotent replay.
378
+ const existing = readHandoverIntent(pdHome, intent.workspaceDir, intent.operationId);
379
+ if (existing !== null
380
+ && existing.workspaceDir === intent.workspaceDir
381
+ && existing.preparingGeneration === intent.preparingGeneration
382
+ && existing.committedGeneration === intent.committedGeneration) {
383
+ return { ok: true, path: target, reason: 'already_exists' };
384
+ }
385
+ return { ok: false, path: target, reason: 'intent_identity_conflict' };
386
+ }
387
+ throw linkError;
388
+ }
389
+ fs.unlinkSync(tmp);
390
+ return { ok: true, path: target };
391
+ }
392
+ catch (error) {
393
+ return { ok: false, path: target, reason: error instanceof Error ? error.message : String(error) };
394
+ }
395
+ }
396
+ /** Read + field-validate a persisted commit intent (null = absent/untrusted). */
397
+ export function readHandoverIntent(pdHome, canonicalDir, operationId) {
398
+ try {
399
+ const parsed = JSON.parse(fs.readFileSync(handoverIntentPath(pdHome, canonicalDir, operationId), 'utf8'));
400
+ if (!isJsonObject(parsed))
401
+ return null;
402
+ if (parsed.schemaVersion !== HANDOVER_INTENT_SCHEMA || parsed.kind !== 'handover')
403
+ return null;
404
+ if (!isNonEmptyString(parsed.operationId) || parsed.operationId !== operationId)
405
+ return null;
406
+ if (!isNonEmptyString(parsed.workspaceDir) || !isNonEmptyString(parsed.writtenAt))
407
+ return null;
408
+ if (typeof parsed.preparingGeneration !== 'number' || !Number.isInteger(parsed.preparingGeneration) || parsed.preparingGeneration < 0)
409
+ return null;
410
+ if (typeof parsed.committedGeneration !== 'number' || !Number.isInteger(parsed.committedGeneration) || parsed.committedGeneration < 1)
411
+ return null;
412
+ return {
413
+ schemaVersion: HANDOVER_INTENT_SCHEMA,
414
+ kind: 'handover',
415
+ operationId: parsed.operationId,
416
+ workspaceDir: parsed.workspaceDir,
417
+ preparingGeneration: parsed.preparingGeneration,
418
+ committedGeneration: parsed.committedGeneration,
419
+ writtenAt: parsed.writtenAt,
420
+ };
421
+ }
422
+ catch {
423
+ return null;
424
+ }
425
+ }
426
+ // ─── Rollback intent (crash recovery, PRI-1282 review r4 §8) ────────────────
427
+ //
428
+ // The rollback mirror of the handover commit intent: persisted AFTER
429
+ // begin_rollback and BEFORE the complete_rollback CAS, it binds
430
+ // operationId + workspace + pending/committed generations so a run killed
431
+ // between the CAS and the evidence write is resumable — `--resume` then
432
+ // only rewrites the missing evidence, never re-flips ownership.
433
+ const ROLLBACK_INTENT_SCHEMA = 'pd.service-rollback-intent.v1';
434
+ export function rollbackIntentPath(pdHome, canonicalDir, operationId) {
435
+ return path.join(pdHome, 'service', 'handover', workspaceEvidenceKey(canonicalDir), `${operationId}.rollback-intent.json`);
436
+ }
437
+ export function writeRollbackIntent(intent, pdHome) {
438
+ if (!isSafeOperationId(intent.operationId)) {
439
+ return { ok: false, path: rollbackIntentPath(pdHome, intent.workspaceDir, 'invalid'), reason: 'operation_id_invalid' };
440
+ }
441
+ const target = rollbackIntentPath(pdHome, intent.workspaceDir, intent.operationId);
442
+ try {
443
+ fs.mkdirSync(path.dirname(target), { recursive: true });
444
+ const tmp = `${target}.${process.pid}.${crypto.randomUUID().slice(0, 8)}.tmp`;
445
+ const fd = fs.openSync(tmp, fs.constants.O_WRONLY | fs.constants.O_CREAT | fs.constants.O_EXCL, 0o600);
446
+ try {
447
+ fs.writeFileSync(fd, JSON.stringify(intent, null, 2) + '\n');
448
+ }
449
+ finally {
450
+ fs.closeSync(fd);
451
+ }
452
+ try {
453
+ fs.linkSync(tmp, target); // atomic no-replace publish
454
+ }
455
+ catch (linkError) {
456
+ try {
457
+ fs.unlinkSync(tmp);
458
+ }
459
+ catch { /* best effort */ }
460
+ if (errnoOf(linkError) === 'EEXIST') {
461
+ const existing = readRollbackIntent(pdHome, intent.workspaceDir, intent.operationId);
462
+ if (existing !== null
463
+ && existing.workspaceDir === intent.workspaceDir
464
+ && existing.pendingGeneration === intent.pendingGeneration
465
+ && existing.committedGeneration === intent.committedGeneration) {
466
+ return { ok: true, path: target, reason: 'already_exists' };
467
+ }
468
+ return { ok: false, path: target, reason: 'intent_identity_conflict' };
469
+ }
470
+ throw linkError;
471
+ }
472
+ fs.unlinkSync(tmp);
473
+ return { ok: true, path: target };
474
+ }
475
+ catch (error) {
476
+ return { ok: false, path: target, reason: error instanceof Error ? error.message : String(error) };
477
+ }
478
+ }
479
+ /** Read + field-validate a persisted rollback intent (null = absent/untrusted). */
480
+ export function readRollbackIntent(pdHome, canonicalDir, operationId) {
481
+ try {
482
+ const parsed = JSON.parse(fs.readFileSync(rollbackIntentPath(pdHome, canonicalDir, operationId), 'utf8'));
483
+ if (!isJsonObject(parsed))
484
+ return null;
485
+ if (parsed.schemaVersion !== ROLLBACK_INTENT_SCHEMA || parsed.kind !== 'rollback')
486
+ return null;
487
+ if (!isNonEmptyString(parsed.operationId) || parsed.operationId !== operationId)
488
+ return null;
489
+ if (!isNonEmptyString(parsed.workspaceDir) || !isNonEmptyString(parsed.writtenAt))
490
+ return null;
491
+ if (typeof parsed.pendingGeneration !== 'number' || !Number.isInteger(parsed.pendingGeneration) || parsed.pendingGeneration < 0)
492
+ return null;
493
+ if (typeof parsed.committedGeneration !== 'number' || !Number.isInteger(parsed.committedGeneration) || parsed.committedGeneration < 1)
494
+ return null;
495
+ return {
496
+ schemaVersion: ROLLBACK_INTENT_SCHEMA,
497
+ kind: 'rollback',
498
+ operationId: parsed.operationId,
499
+ workspaceDir: parsed.workspaceDir,
500
+ pendingGeneration: parsed.pendingGeneration,
501
+ committedGeneration: parsed.committedGeneration,
502
+ writtenAt: parsed.writtenAt,
503
+ };
504
+ }
505
+ catch {
506
+ return null;
507
+ }
508
+ }
509
+ /** Default scheduler-enabled fact probe: `pd service status` on this install. */
510
+ async function probeSchedulerEnabled(context, env) {
511
+ const status = await runSchedulerLifecycle('status', { env: env ?? process.env, trustedHomeDir: context.homeDir });
512
+ if (!status.ok)
513
+ return { ok: false, reason: status.reason };
514
+ return { ok: true, registered: status.facts.registered, enabled: status.facts.enabled };
515
+ }
516
+ /** Spawn a bounded active-release CLI probe (readiness or one cycle). */
517
+ async function runActiveReleaseWorkerProbe(args) {
518
+ const identity = resolveCoordinatorInstallIdentity(process.env, { trustedHomeDir: args.homeDir });
519
+ if (!identity.ok)
520
+ return { ok: false, reason: `install_identity_unresolved:${identity.reason}`, nextAction: identity.nextAction };
521
+ const entry = resolveActiveReleaseCliEntry(identity.identity);
522
+ if (entry.kind === 'missing') {
523
+ return { ok: false, reason: `active_release_missing:${entry.reason}`, nextAction: entry.nextAction };
524
+ }
525
+ const { env } = buildWorkerEnvironment({
526
+ identity: identity.identity,
527
+ hostKind: 'openclaw',
528
+ inheritedEnv: process.env,
529
+ // Same allowlist the managed adapter uses: the workspace's own
530
+ // `apiKeyEnv` names must reach the probe child or a console-saved /
531
+ // custom-named credential is stripped (PRI-1282 review).
532
+ credentialEnvAllowlist: readConfigCredentialEnvNames(args.workspaceDir),
533
+ });
534
+ const result = await runWorkerProcess({
535
+ cliEntry: entry.entry,
536
+ args: ['openclaw', 'worker', args.mode === 'readiness' ? '--readiness' : '--once', '--json', '--workspace', args.workspaceDir],
537
+ env,
538
+ timeoutMs: args.timeoutMs,
539
+ ...(args.signal !== undefined ? { signal: args.signal } : {}),
540
+ });
541
+ return { ok: true, result };
542
+ }
543
+ /**
544
+ * One REAL worker cycle through the SAME managed adapter the scheduler's
545
+ * run-once uses (PRI-1282 review): entry resolution, allowlist env build
546
+ * (workspace credential names included), spawn, task-progress diffing,
547
+ * JSON/workspace/mode validation and liveness normalization are all the
548
+ * adapter's verified contract — the handover never trusts raw stdout.
549
+ */
550
+ async function runManagedOpenClawCycle(args) {
551
+ const identity = resolveCoordinatorInstallIdentity(process.env, { trustedHomeDir: args.homeDir });
552
+ if (!identity.ok)
553
+ return { ok: false, reason: `install_identity_unresolved:${identity.reason}`, nextAction: identity.nextAction };
554
+ const result = await createOpenClawWorkerAdapter().executeOnce({
555
+ workspaceDir: args.workspaceDir,
556
+ activeRelease: readActiveReleaseFacts(identity.identity.activeRecordPath),
557
+ invocationId: args.invocationId,
558
+ timeoutMs: args.timeoutMs,
559
+ ...(args.signal !== undefined ? { signal: args.signal } : {}),
560
+ identity: identity.identity,
561
+ inheritedEnv: process.env,
562
+ });
563
+ return { ok: true, result };
564
+ }
565
+ /** The cycle outcomes that prove a first managed cycle actually worked. */
566
+ function verifiedCycleOutcome(result) {
567
+ return result.cycleOutcome === 'cycle_completed' || result.cycleOutcome === 'cycle_completed_without_business_progress';
568
+ }
569
+ /**
570
+ * The consuming Worker child holds the per-workspace run mutex for its
571
+ * whole cycle — the lock survives the coordinator's own death because the
572
+ * CHILD is the recorded holder. Before launching (or rolling back around)
573
+ * a worker we probe that mutex: a live holder means the old cycle is still
574
+ * running and overlapping it would create two consumers on one workspace
575
+ * (PRI-1282 review). Returns the blocked/failed verdict or null to proceed.
576
+ */
577
+ function refuseWhileWorkerRunning(context, operationId) {
578
+ const probe = probeServiceRunLockState(workspaceServiceRunLockPath(context.pdHome, context.workspaceDir));
579
+ if (probe.state === 'free')
580
+ return null;
581
+ if (probe.state === 'held') {
582
+ return {
583
+ ok: false,
584
+ outcome: 'blocked',
585
+ reason: 'service_host_worker_still_running',
586
+ nextAction: 'A worker cycle is still consuming this workspace (its process holds the workspace run mutex); wait for it to finish — cycles are bounded — and rerun the operation.',
587
+ operationId,
588
+ };
589
+ }
590
+ return {
591
+ ok: false,
592
+ outcome: 'blocked',
593
+ reason: `service_host_worker_lock_unverifiable:${probe.detail ?? 'unknown'}`,
594
+ nextAction: 'The workspace run mutex could not be verified; refusing to risk overlapping a still-running worker. Repair or remove the stale lock under <pdHome>/service/workspace-runs/ and rerun.',
595
+ operationId,
596
+ };
597
+ }
598
+ function parseWorkerJson(stdout) {
599
+ try {
600
+ const parsed = JSON.parse(stdout);
601
+ return isJsonObject(parsed) ? parsed : null;
602
+ }
603
+ catch {
604
+ return null;
605
+ }
606
+ }
607
+ export async function runWorkspaceHandover(workspaceDir, options) {
608
+ const context = establishHandoverContext(workspaceDir, options);
609
+ if (!context.ok)
610
+ return { ok: false, outcome: 'blocked', reason: context.reason, nextAction: context.nextAction };
611
+ // operationId enters file paths and CAS records — a filesystem-safe
612
+ // whitelist at the command boundary, before anything keys off it
613
+ // (PRI-1282 review P1-6).
614
+ if (options.resumeOperationId !== undefined && !isSafeOperationId(options.resumeOperationId)) {
615
+ return { ok: false, outcome: 'blocked', reason: 'operation_id_invalid', nextAction: 'operationId may only contain letters, digits, dots, underscores and hyphens (1-128 chars).' };
616
+ }
617
+ const ackWaitMs = options.ackWaitMs ?? DEFAULT_HANDOVER_ACK_WAIT_MS;
618
+ const stepTimeoutMs = options.stepTimeoutMs ?? DEFAULT_HANDOVER_STEP_TIMEOUT_MS;
619
+ const startedAt = nowIso();
620
+ const steps = [];
621
+ const record = (step, outcome, detail) => {
622
+ steps.push({ step, at: nowIso(), outcome, ...(detail !== undefined ? { detail } : {}) });
623
+ };
624
+ const aborted = () => options.signal?.aborted === true;
625
+ // ── 1. Ownership readability + host binding verification. ──
626
+ const initial = readWorkspaceBackgroundOwnership({ manifestPath: context.manifestPath, workspaceDir: context.workspaceDir });
627
+ if (initial.status === 'manifest_unreadable') {
628
+ return { ok: false, outcome: 'blocked', reason: `ownership_unreadable:${initial.reason}`, nextAction: initial.nextAction };
629
+ }
630
+ // ── Crash-recovery continuation (design §7.3): a prior run already flipped
631
+ // the marker. Attribution comes from EITHER the completed evidence OR the
632
+ // commit intent the flip path persists first — a run killed between flip
633
+ // and evidence write is resumable because the intent carries
634
+ // workspace + operationId + committed generation (PRI-1282 review).
635
+ // ──
636
+ if (initial.status === 'service_host_owned') {
637
+ const priorOp = options.resumeOperationId ?? '';
638
+ const priorEvidence = priorOp !== '' ? readHandoverEvidence(context.pdHome, context.workspaceDir, priorOp) : null;
639
+ const priorIntent = priorOp !== '' ? readHandoverIntent(context.pdHome, context.workspaceDir, priorOp) : null;
640
+ // PRI-1282 review P1-6: 'completed' alone is not resumable — the
641
+ // evidence must be THIS workspace's handover whose committed ownership
642
+ // matches the CURRENT marker generation, else a stale/foreign document
643
+ // could impersonate the committed run.
644
+ const evidenceMatches = priorEvidence !== null
645
+ && priorEvidence.kind === 'handover'
646
+ && priorEvidence.outcome === 'completed'
647
+ && priorEvidence.finalOwnership.status === 'service_host_owned'
648
+ && priorEvidence.finalOwnership.generation === initial.generation;
649
+ const intentMatches = priorIntent !== null
650
+ && priorIntent.workspaceDir === context.workspaceDir
651
+ && priorIntent.committedGeneration === initial.generation;
652
+ if (priorOp !== '' && (evidenceMatches || intentMatches)) {
653
+ record('already_service_host_owned', intentMatches && priorEvidence?.outcome !== 'completed' ? 'verify_only_continuation_by_intent' : 'verify_only_continuation');
654
+ // A crashed run may have left its Worker child alive in its own
655
+ // process group — the child still holds the workspace run mutex, so
656
+ // resuming without this probe would overlap two consumers (PRI-1282).
657
+ const stillRunning = refuseWhileWorkerRunning(context, priorOp);
658
+ if (stillRunning !== null)
659
+ return stillRunning;
660
+ // The re-verification cycle joins the same install-level run mutex as
661
+ // the scheduler and rollback — a concurrent managed run must not
662
+ // overlap this verification (PRI-1282 review).
663
+ const contLock = acquireServiceRunLock(context.pdHome);
664
+ if (!contLock.ok) {
665
+ return { ok: false, outcome: 'blocked', reason: `service_run_in_progress:${contLock.kind}`, nextAction: 'A managed run-once is currently executing; wait for it to finish and rerun `pd service handover --resume` to re-verify.', operationId: priorOp };
666
+ }
667
+ try {
668
+ const cycleCont = await runManagedOpenClawCycle({ homeDir: context.homeDir, workspaceDir: context.workspaceDir, invocationId: priorOp, timeoutMs: Math.max(stepTimeoutMs, 10 * 60_000), ...(options.signal !== undefined ? { signal: options.signal } : {}) });
669
+ record('worker_cycle', cycleCont.ok ? `${cycleCont.result.cycleOutcome}${cycleCont.result.workerMode !== undefined ? `(${cycleCont.result.workerMode})` : ''}` : cycleCont.reason);
670
+ if (!cycleCont.ok || !verifiedCycleOutcome(cycleCont.result)) {
671
+ return {
672
+ ok: false,
673
+ outcome: 'failed',
674
+ reason: `first_cycle_unverified:${cycleCont.ok ? cycleCont.result.cycleOutcome : cycleCont.reason}`,
675
+ nextAction: 'The workspace is service_host_owned but the verification cycle did not complete; rerun `pd service handover --resume` to re-verify, or `pd service rollback` to return it to the Gateway.',
676
+ operationId: priorOp,
677
+ ...(cycleCont.ok && cycleCont.result.reason !== undefined ? { detail: cycleCont.result.reason } : {}),
678
+ };
679
+ }
680
+ const ownershipAfter = readWorkspaceBackgroundOwnership({ manifestPath: context.manifestPath, workspaceDir: context.workspaceDir });
681
+ const evidenceCont = {
682
+ schemaVersion: HANDOVER_EVIDENCE_SCHEMA,
683
+ kind: 'handover',
684
+ operationId: priorOp,
685
+ workspaceDir: context.workspaceDir,
686
+ startedAt,
687
+ completedAt: nowIso(),
688
+ outcome: 'completed',
689
+ steps,
690
+ finalOwnership: ownershipAfter,
691
+ };
692
+ const writtenCont = writeHandoverEvidence(evidenceCont, context.pdHome);
693
+ if (!writtenCont.ok) {
694
+ return { ok: false, outcome: 'failed', reason: `handover_evidence_write_failed:${writtenCont.reason ?? 'io'}`, nextAction: 'The verification cycle passed but the evidence could not be persisted; rerun `pd service handover --resume` after fixing the write failure.', operationId: priorOp };
695
+ }
696
+ return {
697
+ ok: true,
698
+ outcome: 'completed',
699
+ operationId: priorOp,
700
+ workspaceDir: context.workspaceDir,
701
+ generation: ownershipAfter.status === 'service_host_owned' ? ownershipAfter.generation : 0,
702
+ readiness: 'ready',
703
+ quiesceAck: { operationId: priorOp, generation: priorEvidence?.finalOwnership.status === 'service_host_owned' ? priorEvidence.finalOwnership.generation : (priorIntent?.committedGeneration ?? 0), outcome: 'verified_by_prior_evidence', startedVia: 'prior_run' },
704
+ workerCycle: { mode: cycleCont.result.workerMode ?? cycleCont.result.cycleOutcome, exitCode: cycleCont.result.worker.exitCode, evidencePath: writtenCont.path },
705
+ evidencePath: writtenCont.path,
706
+ };
707
+ }
708
+ finally {
709
+ releaseServiceRunLock(contLock.handle);
710
+ }
711
+ }
712
+ return {
713
+ ok: false,
714
+ outcome: 'blocked',
715
+ reason: 'already_service_host_owned',
716
+ nextAction: 'This workspace already belongs to the Service Host. Pass --resume <operationId> of the committed handover to re-verify, or use pd service rollback to return it to the legacy consumer.',
717
+ };
718
+ }
719
+ // ── Abort handling FIRST (PRI-1282 review P1-5): binding verification
720
+ // cannot gate an operator's abort — a workspace stuck in
721
+ // handover_preparing with a missing/broken OpenClaw binding would
722
+ // otherwise be unrecoverable by --abort. The abort must also name the
723
+ // EXACT in-flight operation: a marker's operationId no longer silently
724
+ // overrides an explicit --resume, and generation fencing keeps a stale
725
+ // caller from aborting a newer generation's work.
726
+ const markerOp = initial.status === 'handover_preparing' ? initial.record.operationId : undefined;
727
+ if (options.resumeOperationId !== undefined && markerOp !== undefined && options.resumeOperationId !== markerOp) {
728
+ return {
729
+ ok: false,
730
+ outcome: 'blocked',
731
+ reason: 'operation_id_mismatch',
732
+ nextAction: `The in-flight handover is ${markerOp}; --resume must name that exact operation (or omit --resume to adopt it).`,
733
+ operationId: markerOp ?? undefined,
734
+ };
735
+ }
736
+ if (options.abort === true) {
737
+ const target = markerOp;
738
+ if (target === undefined || target === null) {
739
+ return { ok: false, outcome: 'blocked', reason: 'abort_requires_operation', nextAction: 'No handover_preparing record exists for this workspace; nothing to abort.' };
740
+ }
741
+ const abortedTransition = transitionWorkspaceBackgroundExecution({
742
+ manifestPath: context.manifestPath, workspaceDir: context.workspaceDir, kind: 'abort_handover', operationId: target, expectedGeneration: initial.generation,
743
+ });
744
+ if (!abortedTransition.ok)
745
+ return { ok: false, outcome: 'failed', reason: `abort_failed:${abortedTransition.reason}`, nextAction: abortedTransition.nextAction ?? 'Inspect the manifest ownership record.', detail: abortedTransition.message };
746
+ record('aborted', 'legacy_owned');
747
+ return { ok: false, outcome: 'aborted', reason: 'handover_aborted_by_operator', nextAction: 'The workspace is back to legacy ownership; the Gateway consumer is the sole owner.', operationId: target };
748
+ }
749
+ // PRI-1282 review r4 §5: an explicit --resume may ONLY continue a real
750
+ // in-flight operation. With no handover_preparing marker there is nothing
751
+ // to resume — the command must NOT silently mint a new operationId out of
752
+ // the name the operator passed (and a completed operation can never
753
+ // re-enter the execution flow).
754
+ if (options.resumeOperationId !== undefined && markerOp === undefined) {
755
+ return {
756
+ ok: false,
757
+ outcome: 'blocked',
758
+ reason: 'no_resumable_operation',
759
+ nextAction: `No in-flight handover exists for this workspace to resume as '${options.resumeOperationId}'; omit --resume to start a new handover.`,
760
+ operationId: options.resumeOperationId,
761
+ };
762
+ }
763
+ const binding = collectHostWorkspaceClaimsFor(context.workspaceDir, context.homeDir, options.env);
764
+ if (binding.bindingUnverifiable !== null) {
765
+ return {
766
+ ok: false,
767
+ outcome: 'blocked',
768
+ reason: `foreign_owner_unverifiable:${binding.bindingUnverifiable}`,
769
+ nextAction: 'A host binding file could not be read or parsed, so cross-host ownership cannot be verified; repair the binding file(s) and retry (fail-closed per §9.1.8).',
770
+ };
771
+ }
772
+ if (!binding.openclawClaimed) {
773
+ return {
774
+ ok: false,
775
+ outcome: 'blocked',
776
+ reason: 'no_openclaw_host_binding',
777
+ nextAction: 'Bind the workspace to OpenClaw first (host declaration or validated mcp-binding claim); the handover never guesses host ownership.',
778
+ };
779
+ }
780
+ if (binding.foreignOwner !== null) {
781
+ return {
782
+ ok: false,
783
+ outcome: 'blocked',
784
+ reason: `foreign_workspace_owner:${binding.foreignOwner}`,
785
+ nextAction: 'Another host claims this workspace; resolve the cross-host ownership conflict before handing over to the Service Host.',
786
+ };
787
+ }
788
+ record('binding_verified', 'openclaw_claim_present');
789
+ // ── 2. begin_handover (idempotent; registers the workspace atomically). ──
790
+ const resumeOp = markerOp;
791
+ // ── 1.5. Scheduler gate (PRI-1282 review): handing ownership to the
792
+ // Service Host while no enabled OS trigger exists would leave the
793
+ // workspace consumed by NOBODY. Verified BEFORE the ownership-changing
794
+ // transition so a refusal keeps the workspace cleanly legacy-owned (and
795
+ // never blocks a recovery --abort); the command never enables the trigger
796
+ // on the operator's behalf. ──
797
+ const schedulerStatus = options.probes?.schedulerStatus !== undefined
798
+ ? await options.probes.schedulerStatus()
799
+ : await probeSchedulerEnabled(context, options.env);
800
+ if (!schedulerStatus.ok) {
801
+ return {
802
+ ok: false,
803
+ outcome: 'blocked',
804
+ reason: `service_host_scheduler_status_unavailable:${schedulerStatus.reason}`,
805
+ nextAction: 'The Service Host scheduler status could not be determined; resolve that first (the workspace stays legacy-owned and untouched).',
806
+ };
807
+ }
808
+ if (schedulerStatus.registered !== true || schedulerStatus.enabled !== true) {
809
+ return {
810
+ ok: false,
811
+ outcome: 'blocked',
812
+ reason: 'service_host_scheduler_not_enabled',
813
+ nextAction: 'Install and enable the Service Host scheduler for this install first (`pd service install`, `pd service enable`); without an enabled trigger a handed-over workspace is consumed by nobody, so the workspace stays legacy-owned.',
814
+ };
815
+ }
816
+ record('scheduler_trigger', 'registered_and_enabled');
817
+ // operationId comes from the in-flight marker alone now — an explicit
818
+ // --resume was already proven equal to it above, and a fresh operation
819
+ // mints a fresh id. A marker name is never silently replaced.
820
+ const operationId = resumeOp ?? options.probes?.mintOperationId?.('handover') ?? `handover-${crypto.randomUUID()}`;
821
+ if (!isSafeOperationId(operationId)) {
822
+ return { ok: false, outcome: 'blocked', reason: 'operation_id_invalid', nextAction: 'operationId may only contain letters, digits, dots, underscores and hyphens (1-128 chars).', operationId };
823
+ }
824
+ const begin = transitionWorkspaceBackgroundExecution({
825
+ manifestPath: context.manifestPath, workspaceDir: context.workspaceDir, kind: 'begin_handover', operationId, registerWorkspace: true,
826
+ });
827
+ if (!begin.ok) {
828
+ return { ok: false, outcome: 'blocked', reason: `begin_handover_failed:${begin.reason}`, nextAction: begin.nextAction ?? 'Re-read the ownership record and retry.', operationId, detail: begin.message };
829
+ }
830
+ record('begin_handover', begin.changed ? 'handover_preparing' : 'idempotent_replay', `generation=${begin.record.generation}`);
831
+ const preparingGeneration = begin.record.generation;
832
+ // ── 3. No-consume readiness through the ACTIVE-RELEASE worker. ──
833
+ const readiness = await runActiveReleaseWorkerProbe({ homeDir: context.homeDir, workspaceDir: context.workspaceDir, mode: 'readiness', timeoutMs: stepTimeoutMs, ...(options.signal !== undefined ? { signal: options.signal } : {}) });
834
+ if (!readiness.ok) {
835
+ const rollback = transitionWorkspaceBackgroundExecution({ manifestPath: context.manifestPath, workspaceDir: context.workspaceDir, kind: 'abort_handover', operationId, expectedGeneration: preparingGeneration });
836
+ record('readiness', 'unavailable', readiness.reason);
837
+ if (!rollback.ok) {
838
+ return { ok: false, outcome: 'failed', reason: `readiness_failed_and_abort_failed:${readiness.reason}|${rollback.reason}`, nextAction: 'The workspace is STUCK in handover_preparing — resolve manually (pd service handover --abort).', operationId, detail: readiness.nextAction };
839
+ }
840
+ return { ok: false, outcome: 'blocked', reason: `readiness_not_met:${readiness.reason}`, nextAction: `${readiness.nextAction} The workspace was restored to legacy ownership.`, operationId };
841
+ }
842
+ const readinessJson = parseWorkerJson(readiness.result.stdout);
843
+ const readinessMode = typeof readinessJson?.mode === 'string' ? readinessJson.mode : 'unknown';
844
+ // PRI-1282 review P2-1: 'ready' must be corroborated by a clean process
845
+ // outcome — a timed-out/cancelled/failed child that managed to print
846
+ // mode:'ready' before dying is not evidence of readiness.
847
+ const readinessProcessFailed = readiness.result.exitCode !== 0
848
+ || readiness.result.timedOut === true
849
+ || readiness.result.cancelled === true
850
+ || readiness.result.spawnError !== undefined
851
+ || readiness.result.stdoutTruncated === true
852
+ // close-observed is required: a worker whose stdout was captured but
853
+ // whose process never provably terminated cannot attest readiness
854
+ // (PRI-1282 r4 §10).
855
+ || readiness.result.terminationConfirmed !== true;
856
+ // The readiness document must attest THIS workspace — an out-of-band or
857
+ // stale 'ready' printed for another dir is not this workspace's proof.
858
+ const readinessWorkspaceMismatch = typeof readinessJson?.workspaceDir === 'string'
859
+ && path.resolve(readinessJson.workspaceDir) !== context.workspaceDir;
860
+ if (readinessMode !== 'ready' || readinessProcessFailed || readinessWorkspaceMismatch) {
861
+ const processDetail = readinessProcessFailed
862
+ ? `exitCode=${readiness.result.exitCode} timedOut=${readiness.result.timedOut} cancelled=${readiness.result.cancelled} stdoutTruncated=${readiness.result.stdoutTruncated} terminationConfirmed=${readiness.result.terminationConfirmed ?? false}${readiness.result.spawnError !== undefined ? ` spawnError=${readiness.result.spawnError}` : ''}`
863
+ : '';
864
+ const rollback = transitionWorkspaceBackgroundExecution({ manifestPath: context.manifestPath, workspaceDir: context.workspaceDir, kind: 'abort_handover', operationId, expectedGeneration: preparingGeneration });
865
+ record('readiness', readinessProcessFailed ? `process_failed(${processDetail})` : readinessMode, readiness.result.stdout.slice(0, 400));
866
+ if (!rollback.ok) {
867
+ return { ok: false, outcome: 'failed', reason: `readiness_not_ready_and_abort_failed:${readinessMode}|${rollback.reason}`, nextAction: 'The workspace is STUCK in handover_preparing — resolve manually (pd service handover --abort).', operationId };
868
+ }
869
+ return {
870
+ ok: false,
871
+ outcome: 'blocked',
872
+ reason: readinessWorkspaceMismatch
873
+ ? 'openclaw_worker_readiness_workspace_mismatch'
874
+ : readinessProcessFailed ? `openclaw_worker_readiness_process:${readinessMode}` : `openclaw_worker_readiness:${readinessMode}`,
875
+ nextAction: 'Fix the failing readiness checks (declaration / evidence port / credentials) and retry; the workspace was restored to legacy ownership.',
876
+ operationId,
877
+ detail: readinessJson ?? { exitCode: readiness.result.exitCode, timedOut: readiness.result.timedOut, cancelled: readiness.result.cancelled },
878
+ };
879
+ }
880
+ record('readiness', 'ready');
881
+ // ── 4. Wait for the Gateway quiesce ack (persisted, operation-bound). ──
882
+ const ackPlugin = await import('principles-disciple/openclaw-worker');
883
+ const ackDeadline = Date.now() + (options.ackWaitMs ?? ackWaitMs);
884
+ let ack = null;
885
+ while (Date.now() < ackDeadline) {
886
+ if (aborted())
887
+ break;
888
+ ack = ackPlugin.readGatewayQuiesceAck(context.workspaceDir);
889
+ // PRI-1282 review P2-2: the ack must bind THIS operation's state and
890
+ // THIS workspace too — an ack written for handover_preparing of another
891
+ // workspace (or a stale-marker state) is not this operation's evidence.
892
+ if (ack !== null
893
+ && ack.operationId === operationId
894
+ && ack.generation === preparingGeneration
895
+ && ack.state === 'handover_preparing'
896
+ // PRI-1282 r4 §11: compare REAL directory identity, not lexical
897
+ // spelling — an ack persisted under a symlinked alias spelling must
898
+ // still bind this workspace (and a foreign spelling must not).
899
+ && ackWorkspaceMatches(ack.workspaceDir, context.workspaceDir)
900
+ && ack.outcome === 'quiesced'
901
+ && ack.inFlightCycles === 0)
902
+ break;
903
+ await wait(2_000);
904
+ }
905
+ const ackDefect = ack === null
906
+ ? 'gateway_quiesce_ack_absent'
907
+ : ack.operationId !== operationId
908
+ ? 'gateway_quiesce_ack_operation_mismatch'
909
+ : ack.generation !== preparingGeneration
910
+ ? 'gateway_quiesce_ack_generation_mismatch'
911
+ : ack.state !== 'handover_preparing'
912
+ ? `gateway_quiesce_ack_state_mismatch:${ack.state}`
913
+ : !ackWorkspaceMatches(ack.workspaceDir, context.workspaceDir)
914
+ ? 'gateway_quiesce_ack_workspace_mismatch'
915
+ : ack.outcome !== 'quiesced'
916
+ ? `gateway_quiesce_ack_not_quiesced:${ack.outcome}`
917
+ : null;
918
+ if (ackDefect !== null) {
919
+ const rollback = transitionWorkspaceBackgroundExecution({ manifestPath: context.manifestPath, workspaceDir: context.workspaceDir, kind: 'abort_handover', operationId, expectedGeneration: preparingGeneration });
920
+ record('quiesce_ack', 'missing_or_mismatched', ack === null ? 'no_ack_file' : `${ack.state}/${ack.operationId}/${ack.outcome}`);
921
+ if (!rollback.ok) {
922
+ return { ok: false, outcome: 'failed', reason: `quiesce_unproven_and_abort_failed:${ackDefect}|${rollback.reason}`, nextAction: 'The workspace is STUCK in handover_preparing — resolve manually (pd service handover --abort).', operationId };
923
+ }
924
+ return {
925
+ ok: false,
926
+ outcome: 'blocked',
927
+ reason: ackDefect,
928
+ nextAction: ackDefect === 'gateway_quiesce_ack_not_quiesced:in_flight_timeout'
929
+ ? 'The Gateway reported an in-flight cycle it could not bound; retry the handover after the cycle settles.'
930
+ : ackDefect === 'gateway_quiesce_ack_operation_mismatch'
931
+ ? 'The persisted ack belongs to a DIFFERENT handover operation; let this operation reach the Gateway (it may still be mid-tick) and retry, or restart the Gateway so its gates re-acknowledge.'
932
+ : 'Start or restart the OpenClaw Gateway so it can acknowledge the handover (its start gate writes the ack), then retry.',
933
+ operationId,
934
+ detail: ack ?? undefined,
935
+ };
936
+ }
937
+ if (ack === null) {
938
+ // Unreachable (a null ack always yields a defect above) — kept total for
939
+ // the type system; fail loudly rather than trust a silent pass-through.
940
+ return { ok: false, outcome: 'failed', reason: 'internal_ack_unexpected_null', nextAction: 'Retry the handover.', operationId };
941
+ }
942
+ record('quiesce_ack', 'quiesced', `startedVia=${ack.writer.startedVia}`);
943
+ // ── 5-7. Commit section — under the SAME install-level run mutex the
944
+ // scheduler and rollback serialize on (PRI-1282 review): holding it from
945
+ // before the flip until the first worker child exits means a rollback can
946
+ // never flip ownership back while this cycle is still consuming, and a
947
+ // managed run-once sees `already_running` instead of overlapping us. A
948
+ // bare `pd openclaw worker --once` stays lock-free BY DESIGN — it is the
949
+ // leaf consumer the orchestrators drive; serializing it too would
950
+ // self-deadlock every launch below. ──
951
+ const runLock = acquireServiceRunLock(context.pdHome);
952
+ if (!runLock.ok) {
953
+ return {
954
+ ok: false,
955
+ outcome: 'blocked',
956
+ reason: `service_run_in_progress:${runLock.kind}`,
957
+ nextAction: 'A managed run-once or rollback is currently executing; wait for it to finish and rerun the handover — the workspace stays handover_preparing and this operationId resumes.',
958
+ operationId,
959
+ };
960
+ }
961
+ try {
962
+ // The workspace mutex still held means a Worker child outlived its
963
+ // coordinator — refuse before flipping rather than overlap it.
964
+ const stillRunning = refuseWhileWorkerRunning(context, operationId);
965
+ if (stillRunning !== null)
966
+ return stillRunning;
967
+ // Persist the commit intent BEFORE the flip: the steady-state marker
968
+ // clears operationId, so a crash between flip and evidence write would
969
+ // leave the commit unattributable without it (PRI-1282 review).
970
+ const intentWritten = writeHandoverIntent({
971
+ schemaVersion: HANDOVER_INTENT_SCHEMA,
972
+ kind: 'handover',
973
+ operationId,
974
+ workspaceDir: context.workspaceDir,
975
+ preparingGeneration,
976
+ committedGeneration: preparingGeneration + 1,
977
+ writtenAt: nowIso(),
978
+ }, context.pdHome);
979
+ if (!intentWritten.ok) {
980
+ return { ok: false, outcome: 'failed', reason: `handover_intent_write_failed:${intentWritten.reason ?? 'io'}`, nextAction: 'The commit intent could not be persisted; the workspace stays handover_preparing — fix the write failure and rerun (the operation resumes).', operationId };
981
+ }
982
+ // ── 4b. Scheduler re-check (PRI-1282 r4 §9): the §1.5 gate proved the
983
+ // trigger was enabled at command start, but `pd service disable` may
984
+ // have landed between then and now (it serializes on the SAME install
985
+ // lock, so an in-flight handover never overlaps a live disable — a
986
+ // disable that completed before our lock acquisition is what this
987
+ // catches). Re-verify immediately before the irreversible flip.
988
+ const schedulerRecheck = options.probes?.schedulerStatus !== undefined
989
+ ? await options.probes.schedulerStatus()
990
+ : await probeSchedulerEnabled(context, options.env);
991
+ if (!schedulerRecheck.ok || schedulerRecheck.registered !== true || schedulerRecheck.enabled !== true) {
992
+ const reason = !schedulerRecheck.ok
993
+ ? `service_host_scheduler_status_unavailable:${schedulerRecheck.reason}`
994
+ : 'service_host_scheduler_not_enabled';
995
+ const rollback = transitionWorkspaceBackgroundExecution({
996
+ manifestPath: context.manifestPath, workspaceDir: context.workspaceDir, kind: 'abort_handover', operationId, expectedGeneration: preparingGeneration,
997
+ });
998
+ record('cas_flip', 'aborted', `scheduler_recheck:${reason}${rollback.ok ? '' : ` (abort_handover failed: ${rollback.ok === false ? rollback.reason : '?'})`}`);
999
+ return {
1000
+ ok: false,
1001
+ outcome: 'blocked',
1002
+ reason,
1003
+ nextAction: 'The Service Host scheduler was disabled or became unreadable during the handover; the preparing state was rolled back — enable it (`pd service enable`) and rerun `pd service handover`.',
1004
+ operationId,
1005
+ };
1006
+ }
1007
+ // ── 5. The single CAS flip. ──
1008
+ const flip = transitionWorkspaceBackgroundExecution({
1009
+ manifestPath: context.manifestPath, workspaceDir: context.workspaceDir, kind: 'complete_handover', operationId, expectedGeneration: preparingGeneration,
1010
+ });
1011
+ if (!flip.ok) {
1012
+ // unexpected_state on service_host_owned can mean a prior crashed run
1013
+ // already flipped: distinguish via the marker, never by guessing.
1014
+ const after = readWorkspaceBackgroundOwnership({ manifestPath: context.manifestPath, workspaceDir: context.workspaceDir });
1015
+ if (after.status === 'service_host_owned') {
1016
+ record('cas_flip', 'already_service_host_owned', flip.reason);
1017
+ }
1018
+ else {
1019
+ return { ok: false, outcome: 'failed', reason: `complete_handover_failed:${flip.reason}`, nextAction: flip.nextAction ?? 'Re-read the ownership record and retry; the workspace is still handover_preparing.', operationId, detail: flip.message };
1020
+ }
1021
+ }
1022
+ else {
1023
+ record('cas_flip', 'service_host_owned', `generation=${flip.record.generation}`);
1024
+ }
1025
+ // ── 6. One real worker cycle through the SAME managed adapter the
1026
+ // scheduler drives — its contract already validates spawn, exit code,
1027
+ // workspace match and worker mode, so a failed/garbage first cycle is
1028
+ // never recorded as success (PRI-1282 review). ──
1029
+ const cycle = await runManagedOpenClawCycle({ homeDir: context.homeDir, workspaceDir: context.workspaceDir, invocationId: operationId, timeoutMs: Math.max(stepTimeoutMs, 10 * 60_000), ...(options.signal !== undefined ? { signal: options.signal } : {}) });
1030
+ record('worker_cycle', cycle.ok ? `${cycle.result.cycleOutcome}${cycle.result.workerMode !== undefined ? `(${cycle.result.workerMode})` : ''}` : cycle.reason);
1031
+ if (!cycle.ok || !verifiedCycleOutcome(cycle.result)) {
1032
+ // Ownership is committed but the FIRST cycle is not verified —
1033
+ // reported as a resumable failure, NEVER as a completed handover.
1034
+ return {
1035
+ ok: false,
1036
+ outcome: 'failed',
1037
+ reason: `first_cycle_unverified:${cycle.ok ? cycle.result.cycleOutcome : cycle.reason}`,
1038
+ nextAction: 'Ownership already flipped to the Service Host but the first managed cycle did not verify; fix the worker problem and rerun `pd service handover --resume <operationId>` to re-verify, or `pd service rollback` to return the workspace to the Gateway.',
1039
+ operationId,
1040
+ detail: cycle.ok ? (cycle.result.reason ?? cycle.result.worker.stderrTail ?? undefined) : cycle.nextAction,
1041
+ };
1042
+ }
1043
+ // ── 6b. Final ownership re-verification (PRI-1282 r4 §7): the worker
1044
+ // cycle verified, but 'completed' ALSO requires the authoritative
1045
+ // marker to still prove THIS operation's commit — status
1046
+ // service_host_owned at exactly the committed generation, backed by the
1047
+ // persisted commit intent bound to this operationId. A flipped-away or
1048
+ // re-generated marker means something else owns the workspace now —
1049
+ // report a resumable verification failure, never a completed handover.
1050
+ const finalOwnership = readWorkspaceBackgroundOwnership({ manifestPath: context.manifestPath, workspaceDir: context.workspaceDir });
1051
+ const persistedIntent = readHandoverIntent(context.pdHome, context.workspaceDir, operationId);
1052
+ const verificationDefect = finalOwnership.status !== 'service_host_owned'
1053
+ ? `final_ownership_status:${finalOwnership.status}`
1054
+ : finalOwnership.generation !== preparingGeneration + 1
1055
+ ? `final_ownership_generation:${finalOwnership.generation}!=${preparingGeneration + 1}`
1056
+ : persistedIntent === null
1057
+ ? 'commit_intent_absent'
1058
+ : persistedIntent.operationId !== operationId || persistedIntent.committedGeneration !== finalOwnership.generation
1059
+ ? 'commit_intent_mismatch'
1060
+ : null;
1061
+ if (verificationDefect !== null) {
1062
+ return {
1063
+ ok: false,
1064
+ outcome: 'failed',
1065
+ reason: `final_ownership_verification_failed:${verificationDefect}`,
1066
+ nextAction: 'The first managed cycle verified but the final ownership state cannot be proven to be THIS operation\'s commit; rerun `pd service handover --resume` with this operationId to re-verify, or `pd service rollback` to return the workspace to the Gateway.',
1067
+ operationId,
1068
+ };
1069
+ }
1070
+ record('final_ownership_verification', 'verified', `generation=${preparingGeneration + 1}`);
1071
+ // ── 7. Completion evidence (write-once, operationId keyed). The
1072
+ // handover only reports completion when BOTH the verified cycle and
1073
+ // this write landed. ──
1074
+ const evidence = {
1075
+ schemaVersion: HANDOVER_EVIDENCE_SCHEMA,
1076
+ kind: 'handover',
1077
+ operationId,
1078
+ workspaceDir: context.workspaceDir,
1079
+ startedAt,
1080
+ completedAt: nowIso(),
1081
+ outcome: 'completed',
1082
+ steps,
1083
+ finalOwnership,
1084
+ };
1085
+ const written = writeHandoverEvidence(evidence, context.pdHome);
1086
+ if (!written.ok) {
1087
+ return { ok: false, outcome: 'failed', reason: `handover_evidence_write_failed:${written.reason ?? 'io'}`, nextAction: 'The first managed cycle verified but the completion evidence could not be persisted; fix the write failure and rerun `pd service handover --resume <operationId>`.', operationId };
1088
+ }
1089
+ return {
1090
+ ok: true,
1091
+ outcome: 'completed',
1092
+ operationId,
1093
+ workspaceDir: context.workspaceDir,
1094
+ generation: finalOwnership.status === 'service_host_owned' ? finalOwnership.generation : (flip.ok ? flip.record.generation : preparingGeneration),
1095
+ readiness: 'ready',
1096
+ quiesceAck: { operationId: ack.operationId ?? operationId, generation: ack.generation, outcome: ack.outcome, startedVia: ack.writer.startedVia },
1097
+ workerCycle: { mode: cycle.result.workerMode ?? cycle.result.cycleOutcome, exitCode: cycle.result.worker.exitCode, evidencePath: written.path },
1098
+ evidencePath: written.path,
1099
+ };
1100
+ }
1101
+ finally {
1102
+ releaseServiceRunLock(runLock.handle);
1103
+ }
1104
+ }
1105
+ export async function runWorkspaceRollback(workspaceDir, options) {
1106
+ const context = establishHandoverContext(workspaceDir, options);
1107
+ if (!context.ok)
1108
+ return { ok: false, outcome: 'blocked', reason: context.reason, nextAction: context.nextAction };
1109
+ if (options.resumeOperationId !== undefined && !isSafeOperationId(options.resumeOperationId)) {
1110
+ return { ok: false, outcome: 'blocked', reason: 'operation_id_invalid', nextAction: 'operationId may only contain letters, digits, dots, underscores and hyphens (1-128 chars).' };
1111
+ }
1112
+ const startedAt = nowIso();
1113
+ const steps = [];
1114
+ const record = (step, outcome, detail) => {
1115
+ steps.push({ step, at: nowIso(), outcome, ...(detail !== undefined ? { detail } : {}) });
1116
+ };
1117
+ // ── 1-3. Stop Service Host cycles: a held run-once lock means a managed
1118
+ // run is ACTIVE — the rollback refuses rather than race it. ──
1119
+ const runLock = acquireServiceRunLock(context.pdHome);
1120
+ if (!runLock.ok) {
1121
+ return {
1122
+ ok: false,
1123
+ outcome: 'blocked',
1124
+ reason: `service_run_in_progress:${runLock.kind}`,
1125
+ nextAction: 'A managed run-once is currently executing; wait for it to finish (workers are bounded) and retry the rollback.',
1126
+ };
1127
+ }
1128
+ try {
1129
+ const initial = readWorkspaceBackgroundOwnership({ manifestPath: context.manifestPath, workspaceDir: context.workspaceDir });
1130
+ if (initial.status === 'manifest_unreadable') {
1131
+ return { ok: false, outcome: 'blocked', reason: `ownership_unreadable:${initial.reason}`, nextAction: initial.nextAction };
1132
+ }
1133
+ const resumeOp = initial.status === 'rollback_pending' ? initial.record.operationId : undefined;
1134
+ // ── --resume arbitration (PRI-1282 r4 §5/§8): an explicit resume may
1135
+ // only continue a REAL in-flight or already-committed operation.
1136
+ if (options.resumeOperationId !== undefined && resumeOp !== undefined && options.resumeOperationId !== resumeOp) {
1137
+ return {
1138
+ ok: false,
1139
+ outcome: 'blocked',
1140
+ reason: 'operation_id_mismatch',
1141
+ nextAction: `The in-flight rollback is ${resumeOp}; --resume must name that exact operation (or omit --resume to adopt it).`,
1142
+ operationId: resumeOp ?? undefined,
1143
+ };
1144
+ }
1145
+ if (options.resumeOperationId !== undefined && resumeOp === undefined) {
1146
+ const resumeIntent = readRollbackIntent(context.pdHome, context.workspaceDir, options.resumeOperationId);
1147
+ const canCompleteEvidence = initial.status === 'legacy_owned'
1148
+ && resumeIntent !== null
1149
+ && resumeIntent.workspaceDir === context.workspaceDir
1150
+ && resumeIntent.committedGeneration === initial.generation;
1151
+ if (!canCompleteEvidence) {
1152
+ return {
1153
+ ok: false,
1154
+ outcome: 'blocked',
1155
+ reason: 'no_resumable_operation',
1156
+ nextAction: `No in-flight or committed-but-unevidenced rollback exists for this workspace to resume as '${options.resumeOperationId}'.`,
1157
+ operationId: options.resumeOperationId,
1158
+ };
1159
+ }
1160
+ // PRI-1282 r5 F6 — resume of an ALREADY-EVIDENCED operation returns
1161
+ // the ORIGINAL recorded conclusion, never a fabricated re-verification:
1162
+ // if the first run persisted evidence (including its real
1163
+ // gateway_resumption observation) and then crashed, the stored
1164
+ // document is the answer.
1165
+ const existingEvidence = readHandoverEvidence(context.pdHome, context.workspaceDir, options.resumeOperationId);
1166
+ if (existingEvidence !== null && existingEvidence.kind === 'rollback') {
1167
+ if (existingEvidence.outcome !== 'completed') {
1168
+ return {
1169
+ ok: false,
1170
+ outcome: 'failed',
1171
+ reason: `prior_operation_outcome:${existingEvidence.outcome}`,
1172
+ nextAction: 'The persisted evidence records this operation did not complete; inspect the evidence document, then run a NEW rollback.',
1173
+ operationId: options.resumeOperationId,
1174
+ };
1175
+ }
1176
+ const observedStep = existingEvidence.steps.find((entry) => entry.step === 'gateway_resumption');
1177
+ return {
1178
+ ok: true,
1179
+ outcome: 'completed',
1180
+ operationId: options.resumeOperationId,
1181
+ workspaceDir: context.workspaceDir,
1182
+ generation: initial.generation,
1183
+ gatewayResumption: observedStep?.outcome === 'observed' ? 'observed' : 'not_verified_gateway_not_running',
1184
+ evidencePath: handoverEvidencePath(context.pdHome, context.workspaceDir, options.resumeOperationId),
1185
+ };
1186
+ }
1187
+ // Evidence-only continuation: ownership already returned to the
1188
+ // Gateway at exactly the intent's committed generation — rewrite ONLY
1189
+ // the missing evidence, never re-run the transition (§8.6).
1190
+ record('resume', 'evidence_only_continuation', `generation=${initial.generation}`);
1191
+ const evidence = {
1192
+ schemaVersion: HANDOVER_EVIDENCE_SCHEMA,
1193
+ kind: 'rollback',
1194
+ operationId: options.resumeOperationId,
1195
+ workspaceDir: context.workspaceDir,
1196
+ startedAt,
1197
+ completedAt: nowIso(),
1198
+ outcome: 'completed',
1199
+ steps,
1200
+ finalOwnership: initial,
1201
+ };
1202
+ const written = writeHandoverEvidence(evidence, context.pdHome);
1203
+ if (!written.ok) {
1204
+ return {
1205
+ ok: false,
1206
+ outcome: 'failed',
1207
+ reason: `rollback_evidence_write_failed:${written.reason ?? 'io'}`,
1208
+ nextAction: 'Ownership already returned to the Gateway but the rollback evidence still cannot be persisted; fix the write failure and rerun `pd service rollback --resume` with this operationId.',
1209
+ operationId: options.resumeOperationId,
1210
+ };
1211
+ }
1212
+ return {
1213
+ ok: true,
1214
+ outcome: 'completed',
1215
+ operationId: options.resumeOperationId,
1216
+ workspaceDir: context.workspaceDir,
1217
+ generation: initial.generation,
1218
+ gatewayResumption: 'not_verified_gateway_not_running',
1219
+ evidencePath: written.path,
1220
+ };
1221
+ }
1222
+ const operationId = resumeOp ?? options.probes?.mintOperationId?.('rollback') ?? `rollback-${crypto.randomUUID()}`;
1223
+ // ── 4-6. begin_rollback FIRST, then drain, then complete_rollback
1224
+ // (PRI-1282 review P1-1 — ordering, not a new lock): flipping the marker
1225
+ // to rollback_pending closes the worker gate (`service_host_owned` is
1226
+ // the only consumable state) BEFORE we wait, so a worker that starts
1227
+ // after this CAS can never begin consuming. Probing the workspace mutex
1228
+ // first left a TOCTOU window: a worker launched between the probe and
1229
+ // the CAS passed the gate and kept consuming past complete_rollback →
1230
+ // two consumers on one workspace.
1231
+ const begin = transitionWorkspaceBackgroundExecution({
1232
+ manifestPath: context.manifestPath, workspaceDir: context.workspaceDir, kind: 'begin_rollback', operationId,
1233
+ });
1234
+ if (!begin.ok) {
1235
+ return { ok: false, outcome: 'blocked', reason: `begin_rollback_failed:${begin.reason}`, nextAction: begin.nextAction ?? 'Only a service_host_owned workspace can roll back.', operationId };
1236
+ }
1237
+ record('begin_rollback', begin.changed ? 'rollback_pending' : 'idempotent_replay', `generation=${begin.record.generation}`);
1238
+ const rollbackGeneration = begin.record.generation;
1239
+ // Now that new cycles are gated out, wait for the LAST in-flight cycle
1240
+ // to finish — the workspace run mutex is held by the worker child for
1241
+ // its whole cycle, so 'free' is the honest drain proof (bounded; a
1242
+ // timeout keeps the workspace safely rollback_pending and resumable).
1243
+ const workspaceRunLockPath = workspaceServiceRunLockPath(context.pdHome, context.workspaceDir);
1244
+ const drainDeadline = Date.now() + (options.stepTimeoutMs ?? DEFAULT_ROLLBACK_DRAIN_WAIT_MS);
1245
+ for (;;) {
1246
+ const probe = probeServiceRunLockState(workspaceRunLockPath);
1247
+ if (probe.state === 'free')
1248
+ break;
1249
+ if (probe.state !== 'held') {
1250
+ return {
1251
+ ok: false,
1252
+ outcome: 'blocked',
1253
+ reason: `service_host_worker_lock_unverifiable:${probe.detail ?? 'unknown'}`,
1254
+ nextAction: 'The workspace run mutex could not be verified; the workspace stays rollback_pending (fail-closed) — repair the stale lock under <pdHome>/service/workspace-runs/ and rerun the rollback.',
1255
+ operationId,
1256
+ };
1257
+ }
1258
+ if (Date.now() >= drainDeadline || options.signal?.aborted === true) {
1259
+ return {
1260
+ ok: false,
1261
+ outcome: 'blocked',
1262
+ reason: 'service_host_worker_drain_timeout',
1263
+ nextAction: 'A worker cycle still holds the workspace run mutex past the drain deadline; the workspace stays rollback_pending — wait for the bounded cycle to finish and rerun the rollback.',
1264
+ operationId,
1265
+ };
1266
+ }
1267
+ await wait(2_000);
1268
+ }
1269
+ record('worker_drain', 'workspace_run_mutex_free');
1270
+ // Persist the rollback intent BEFORE the CAS (PRI-1282 r4 §8): a run
1271
+ // killed between complete_rollback and the evidence write would
1272
+ // otherwise leave the flip unattributable — --resume verifies against
1273
+ // this intent and only rewrites the missing evidence.
1274
+ const intentWritten = writeRollbackIntent({
1275
+ schemaVersion: ROLLBACK_INTENT_SCHEMA,
1276
+ kind: 'rollback',
1277
+ operationId,
1278
+ workspaceDir: context.workspaceDir,
1279
+ pendingGeneration: rollbackGeneration,
1280
+ committedGeneration: rollbackGeneration + 1,
1281
+ writtenAt: nowIso(),
1282
+ }, context.pdHome);
1283
+ if (!intentWritten.ok) {
1284
+ return { ok: false, outcome: 'failed', reason: `rollback_intent_write_failed:${intentWritten.reason ?? 'io'}`, nextAction: 'The rollback intent could not be persisted; the workspace stays rollback_pending — fix the write failure and rerun `pd service rollback --resume` with this operationId.', operationId };
1285
+ }
1286
+ const finish = transitionWorkspaceBackgroundExecution({
1287
+ manifestPath: context.manifestPath, workspaceDir: context.workspaceDir, kind: 'complete_rollback', operationId, expectedGeneration: rollbackGeneration,
1288
+ });
1289
+ if (!finish.ok) {
1290
+ return { ok: false, outcome: 'failed', reason: `complete_rollback_failed:${finish.reason}`, nextAction: 'The workspace is rollback_pending — rerun the rollback command to complete it (fail-closed, never auto-cleared).', operationId };
1291
+ }
1292
+ record('complete_rollback', 'legacy_owned', `generation=${finish.record.generation}`);
1293
+ // ── 6b. Final ownership re-verification (PRI-1282 r4 §7): 'completed'
1294
+ // requires the authoritative marker to prove THIS rollback's commit —
1295
+ // legacy_owned at exactly the intent's committed generation.
1296
+ const verifyOwnership = readWorkspaceBackgroundOwnership({ manifestPath: context.manifestPath, workspaceDir: context.workspaceDir });
1297
+ const verificationDefect = verifyOwnership.status !== 'legacy_owned'
1298
+ ? `final_ownership_status:${verifyOwnership.status}`
1299
+ : verifyOwnership.generation !== rollbackGeneration + 1
1300
+ ? `final_ownership_generation:${verifyOwnership.generation}!=${rollbackGeneration + 1}`
1301
+ : null;
1302
+ if (verificationDefect !== null) {
1303
+ return {
1304
+ ok: false,
1305
+ outcome: 'failed',
1306
+ reason: `final_ownership_verification_failed:${verificationDefect}`,
1307
+ nextAction: 'The rollback CAS committed but the final ownership state cannot be proven to be THIS operation\'s commit; rerun `pd service rollback --resume` with this operationId to re-verify.',
1308
+ operationId,
1309
+ };
1310
+ }
1311
+ record('final_ownership_verification', 'verified', `generation=${rollbackGeneration + 1}`);
1312
+ // ── 7-9. Observe the Gateway's resumption (bounded; honest NOT_VERIFIED
1313
+ // when the Gateway is not running — the start gate guarantees resumption
1314
+ // on its next launch, verified separately by the gate tests). ──
1315
+ let gatewayResumption = 'not_verified_gateway_not_running';
1316
+ const resumeDeadline = Date.now() + (options.ackWaitMs ?? DEFAULT_ROLLBACK_RESUME_WAIT_MS);
1317
+ const startedAtMs = Date.parse(startedAt);
1318
+ while (Date.now() < resumeDeadline) {
1319
+ if (options.signal?.aborted === true)
1320
+ break;
1321
+ const logsDir = path.join(context.workspaceDir, 'memory', 'logs');
1322
+ try {
1323
+ const logs = fs.readdirSync(logsDir).filter((name) => name.startsWith('SYSTEM_')).sort();
1324
+ for (const logName of logs.slice(-3)) {
1325
+ const text = fs.readFileSync(path.join(logsDir, logName), 'utf8');
1326
+ // PRI-1282 review P2-3: a resumption event only counts when its
1327
+ // SystemLogger timestamp is AT/AFTER this rollback started — a
1328
+ // substring hit on an older log line fabricated 'observed' from a
1329
+ // resumption that predates this rollback.
1330
+ for (const line of text.split('\n')) {
1331
+ const stamp = /^\[([^\]]+)\]\s*\[([A-Z_]+)\]/.exec(line);
1332
+ if (stamp === null || stamp[1] === undefined || stamp[2] === undefined)
1333
+ continue;
1334
+ const eventMs = Date.parse(stamp[1]);
1335
+ if (!Number.isFinite(eventMs) || eventMs < startedAtMs)
1336
+ continue;
1337
+ if (stamp[2] === 'INTERNALIZATION_CONSUMER_RESUMED' || stamp[2] === 'INTERNALIZATION_CONSUMER_STARTED') {
1338
+ gatewayResumption = 'observed';
1339
+ break;
1340
+ }
1341
+ }
1342
+ if (gatewayResumption === 'observed')
1343
+ break;
1344
+ }
1345
+ }
1346
+ catch {
1347
+ // No SystemLogger stream at all → Gateway has never run here in this
1348
+ // window; stays not_verified.
1349
+ }
1350
+ if (gatewayResumption === 'observed')
1351
+ break;
1352
+ await wait(3_000);
1353
+ }
1354
+ record('gateway_resumption', gatewayResumption);
1355
+ const evidence = {
1356
+ schemaVersion: HANDOVER_EVIDENCE_SCHEMA,
1357
+ kind: 'rollback',
1358
+ operationId,
1359
+ workspaceDir: context.workspaceDir,
1360
+ startedAt,
1361
+ completedAt: nowIso(),
1362
+ outcome: 'completed',
1363
+ steps,
1364
+ finalOwnership: verifyOwnership,
1365
+ };
1366
+ const written = writeHandoverEvidence(evidence, context.pdHome);
1367
+ // PRI-1282 review P2-3: the rollback did not complete if its audit
1368
+ // record could not be persisted — the ownership flip already happened,
1369
+ // so this reports a resumable failure, never silent success.
1370
+ if (!written.ok) {
1371
+ return {
1372
+ ok: false,
1373
+ outcome: 'failed',
1374
+ reason: `rollback_evidence_write_failed:${written.reason ?? 'io'}`,
1375
+ nextAction: 'Ownership already returned to the Gateway but the rollback evidence could not be persisted; fix the write failure and rerun `pd service rollback` to record it (the operation is idempotent).',
1376
+ operationId,
1377
+ };
1378
+ }
1379
+ return {
1380
+ ok: true,
1381
+ outcome: 'completed',
1382
+ operationId,
1383
+ workspaceDir: context.workspaceDir,
1384
+ generation: finish.record.generation,
1385
+ gatewayResumption,
1386
+ evidencePath: written.path,
1387
+ };
1388
+ }
1389
+ finally {
1390
+ releaseServiceRunLock(runLock.handle);
1391
+ }
1392
+ }
1393
+ //# sourceMappingURL=workspace-handover.js.map