create-principles-disciple 1.155.3 → 1.156.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 (307) hide show
  1. package/_release/product-identity.json +2 -2
  2. package/codex-adapter/dist/ingestion/pain-receipt-fallback.d.ts +28 -1
  3. package/codex-adapter/dist/ingestion/pain-receipt-fallback.js +55 -18
  4. package/codex-adapter/dist/worker/workspace-worker.js +122 -67
  5. package/codex-adapter/package.json +1 -1
  6. package/console/dist/server/index.d.ts +11 -1
  7. package/console/dist/server/index.js +84 -19
  8. package/console/dist/server/release-handover.d.ts +256 -0
  9. package/console/dist/server/release-handover.js +402 -0
  10. package/console/dist/server/routes/onboarding.js +1 -0
  11. package/console/dist/server/routes/update-transaction.js +37 -3
  12. package/console/dist/server/routes/update.js +21 -1
  13. package/console/dist/server/successor.d.ts +46 -0
  14. package/console/dist/server/successor.js +128 -0
  15. package/console/dist/web/assets/app.css +18 -0
  16. package/console/dist/web/assets/app.js +32 -31
  17. package/console/package.json +1 -1
  18. package/core/dist/runtime/candidate-intake-service.d.ts +1 -1
  19. package/core/dist/runtime/candidate-intake-service.d.ts.map +1 -1
  20. package/core/dist/runtime/candidate-intake-service.js +89 -12
  21. package/core/dist/runtime/candidate-intake-service.js.map +1 -1
  22. package/core/dist/runtime/context-payload.d.ts +11 -0
  23. package/core/dist/runtime/context-payload.d.ts.map +1 -1
  24. package/core/dist/runtime/context-payload.js +27 -0
  25. package/core/dist/runtime/context-payload.js.map +1 -1
  26. package/core/dist/runtime/diagnostician-candidate.d.ts.map +1 -1
  27. package/core/dist/runtime/diagnostician-candidate.js +6 -4
  28. package/core/dist/runtime/diagnostician-candidate.js.map +1 -1
  29. package/core/dist/runtime/host-submission-context.d.ts +13 -6
  30. package/core/dist/runtime/host-submission-context.d.ts.map +1 -1
  31. package/core/dist/runtime/host-submission-context.js +77 -8
  32. package/core/dist/runtime/host-submission-context.js.map +1 -1
  33. package/core/dist/runtime/index.d.ts +4 -2
  34. package/core/dist/runtime/index.d.ts.map +1 -1
  35. package/core/dist/runtime/index.js +10 -1
  36. package/core/dist/runtime/index.js.map +1 -1
  37. package/core/dist/runtime/intent/intent-doc.d.ts +30 -0
  38. package/core/dist/runtime/intent/intent-doc.d.ts.map +1 -1
  39. package/core/dist/runtime/intent/intent-doc.js +47 -0
  40. package/core/dist/runtime/intent/intent-doc.js.map +1 -1
  41. package/core/dist/runtime/intent/intent-snapshot.d.ts +12 -0
  42. package/core/dist/runtime/intent/intent-snapshot.d.ts.map +1 -1
  43. package/core/dist/runtime/intent/intent-snapshot.js +20 -0
  44. package/core/dist/runtime/intent/intent-snapshot.js.map +1 -1
  45. package/core/dist/runtime/internalization/diag-rootcause-runner.d.ts +18 -0
  46. package/core/dist/runtime/internalization/diag-rootcause-runner.d.ts.map +1 -1
  47. package/core/dist/runtime/internalization/diag-rootcause-runner.js +53 -15
  48. package/core/dist/runtime/internalization/diag-rootcause-runner.js.map +1 -1
  49. package/core/dist/runtime/internalization/split-diagnostician-runner.d.ts.map +1 -1
  50. package/core/dist/runtime/internalization/split-diagnostician-runner.js +4 -0
  51. package/core/dist/runtime/internalization/split-diagnostician-runner.js.map +1 -1
  52. package/core/dist/runtime/pain-admission-disposition.d.ts +8 -4
  53. package/core/dist/runtime/pain-admission-disposition.d.ts.map +1 -1
  54. package/core/dist/runtime/pain-admission-disposition.js +8 -4
  55. package/core/dist/runtime/pain-admission-disposition.js.map +1 -1
  56. package/core/dist/runtime/pain-ingress.d.ts +8 -0
  57. package/core/dist/runtime/pain-ingress.d.ts.map +1 -1
  58. package/core/dist/runtime/pain-ingress.js +8 -1
  59. package/core/dist/runtime/pain-ingress.js.map +1 -1
  60. package/core/dist/runtime/pain-recall-read-model.d.ts +72 -0
  61. package/core/dist/runtime/pain-recall-read-model.d.ts.map +1 -1
  62. package/core/dist/runtime/pain-recall-read-model.js +46 -21
  63. package/core/dist/runtime/pain-recall-read-model.js.map +1 -1
  64. package/core/dist/runtime/pain-receipt-recovery.d.ts +39 -8
  65. package/core/dist/runtime/pain-receipt-recovery.d.ts.map +1 -1
  66. package/core/dist/runtime/pain-receipt-recovery.js +290 -36
  67. package/core/dist/runtime/pain-receipt-recovery.js.map +1 -1
  68. package/core/dist/runtime/pain-signal-bridge.d.ts +38 -23
  69. package/core/dist/runtime/pain-signal-bridge.d.ts.map +1 -1
  70. package/core/dist/runtime/pain-signal-bridge.js +533 -182
  71. package/core/dist/runtime/pain-signal-bridge.js.map +1 -1
  72. package/core/dist/runtime/pain-signal-runtime-factory.d.ts +68 -13
  73. package/core/dist/runtime/pain-signal-runtime-factory.d.ts.map +1 -1
  74. package/core/dist/runtime/pain-signal-runtime-factory.js +396 -167
  75. package/core/dist/runtime/pain-signal-runtime-factory.js.map +1 -1
  76. package/core/dist/runtime/pain-submit-capability.d.ts +14 -3
  77. package/core/dist/runtime/pain-submit-capability.d.ts.map +1 -1
  78. package/core/dist/runtime/pain-submit-capability.js +21 -9
  79. package/core/dist/runtime/pain-submit-capability.js.map +1 -1
  80. package/core/dist/runtime/pain-target-evidence-reconcile.d.ts +115 -6
  81. package/core/dist/runtime/pain-target-evidence-reconcile.d.ts.map +1 -1
  82. package/core/dist/runtime/pain-target-evidence-reconcile.js +446 -49
  83. package/core/dist/runtime/pain-target-evidence-reconcile.js.map +1 -1
  84. package/core/dist/runtime/pain-to-principle-service.d.ts +28 -10
  85. package/core/dist/runtime/pain-to-principle-service.d.ts.map +1 -1
  86. package/core/dist/runtime/pain-to-principle-service.js +63 -52
  87. package/core/dist/runtime/pain-to-principle-service.js.map +1 -1
  88. package/core/dist/runtime/store/candidate/admission-document.d.ts +43 -0
  89. package/core/dist/runtime/store/candidate/admission-document.d.ts.map +1 -1
  90. package/core/dist/runtime/store/candidate/admission-document.js +130 -0
  91. package/core/dist/runtime/store/candidate/admission-document.js.map +1 -1
  92. package/core/dist/runtime/store/candidate/candidate-store.d.ts +3 -1
  93. package/core/dist/runtime/store/candidate/candidate-store.d.ts.map +1 -1
  94. package/core/dist/runtime/store/candidate/memory-candidate-store.d.ts +2 -1
  95. package/core/dist/runtime/store/candidate/memory-candidate-store.d.ts.map +1 -1
  96. package/core/dist/runtime/store/candidate/memory-candidate-store.js +27 -1
  97. package/core/dist/runtime/store/candidate/memory-candidate-store.js.map +1 -1
  98. package/core/dist/runtime/store/candidate/sqlite-candidate-store.d.ts +2 -1
  99. package/core/dist/runtime/store/candidate/sqlite-candidate-store.d.ts.map +1 -1
  100. package/core/dist/runtime/store/candidate/sqlite-candidate-store.js +59 -2
  101. package/core/dist/runtime/store/candidate/sqlite-candidate-store.js.map +1 -1
  102. package/core/dist/runtime/store/context/sqlite-context-assembler.d.ts.map +1 -1
  103. package/core/dist/runtime/store/context/sqlite-context-assembler.js +18 -3
  104. package/core/dist/runtime/store/context/sqlite-context-assembler.js.map +1 -1
  105. package/core/dist/runtime/store/runtime-state-manager.d.ts +4 -1
  106. package/core/dist/runtime/store/runtime-state-manager.d.ts.map +1 -1
  107. package/core/dist/runtime/store/runtime-state-manager.js +22 -0
  108. package/core/dist/runtime/store/runtime-state-manager.js.map +1 -1
  109. package/core/dist/runtime/store/task/memory-task-store.d.ts.map +1 -1
  110. package/core/dist/runtime/store/task/memory-task-store.js +20 -0
  111. package/core/dist/runtime/store/task/memory-task-store.js.map +1 -1
  112. package/core/dist/runtime/store/task/sqlite-task-store.d.ts.map +1 -1
  113. package/core/dist/runtime/store/task/sqlite-task-store.js +9 -0
  114. package/core/dist/runtime/store/task/sqlite-task-store.js.map +1 -1
  115. package/core/dist/runtime/store/task/task-store.d.ts +10 -0
  116. package/core/dist/runtime/store/task/task-store.d.ts.map +1 -1
  117. package/core/dist/telemetry-event.d.ts +2 -2
  118. package/core/dist/telemetry-event.d.ts.map +1 -1
  119. package/core/dist/telemetry-event.js +5 -0
  120. package/core/dist/telemetry-event.js.map +1 -1
  121. package/core/package.json +1 -1
  122. package/dist/i18n.d.ts.map +1 -1
  123. package/dist/i18n.js +72 -0
  124. package/dist/i18n.js.map +1 -1
  125. package/dist/index.d.ts +15 -0
  126. package/dist/index.d.ts.map +1 -1
  127. package/dist/index.js +145 -35
  128. package/dist/index.js.map +1 -1
  129. package/dist/installer.d.ts +149 -9
  130. package/dist/installer.d.ts.map +1 -1
  131. package/dist/installer.js +542 -31
  132. package/dist/installer.js.map +1 -1
  133. package/dist/installers/codex-host-installer.js +1 -1
  134. package/dist/installers/codex-host-installer.js.map +1 -1
  135. package/dist/installers/index.d.ts +10 -0
  136. package/dist/installers/index.d.ts.map +1 -1
  137. package/dist/installers/index.js +4 -0
  138. package/dist/installers/index.js.map +1 -1
  139. package/dist/mvp-config.js +1 -1
  140. package/dist/mvp-config.js.map +1 -1
  141. package/dist/prompts.d.ts +36 -12
  142. package/dist/prompts.d.ts.map +1 -1
  143. package/dist/prompts.js +102 -30
  144. package/dist/prompts.js.map +1 -1
  145. package/dist/service-host-bridge.d.ts +71 -12
  146. package/dist/service-host-bridge.d.ts.map +1 -1
  147. package/dist/service-host-bridge.js +228 -48
  148. package/dist/service-host-bridge.js.map +1 -1
  149. package/dist/service-host-provisioning.d.ts +102 -0
  150. package/dist/service-host-provisioning.d.ts.map +1 -0
  151. package/dist/service-host-provisioning.js +595 -0
  152. package/dist/service-host-provisioning.js.map +1 -0
  153. package/dist/uninstaller.js +1 -1
  154. package/dist/uninstaller.js.map +1 -1
  155. package/dist/update/apply-payload.d.ts +9 -0
  156. package/dist/update/apply-payload.d.ts.map +1 -1
  157. package/dist/update/apply-payload.js +44 -2
  158. package/dist/update/apply-payload.js.map +1 -1
  159. package/dist/update/console-surface.d.ts +2 -1
  160. package/dist/update/console-surface.d.ts.map +1 -1
  161. package/dist/update/console-surface.js +6 -1
  162. package/dist/update/console-surface.js.map +1 -1
  163. package/dist/update/install-layout.d.ts +12 -0
  164. package/dist/update/install-layout.d.ts.map +1 -1
  165. package/dist/update/install-layout.js +49 -7
  166. package/dist/update/install-layout.js.map +1 -1
  167. package/dist/update/release-manager-authority.d.ts +16 -0
  168. package/dist/update/release-manager-authority.d.ts.map +1 -1
  169. package/dist/update/release-manager-authority.js +45 -3
  170. package/dist/update/release-manager-authority.js.map +1 -1
  171. package/dist/update/release-manager.d.ts +8 -3
  172. package/dist/update/release-manager.d.ts.map +1 -1
  173. package/dist/update/release-manager.js +29 -1
  174. package/dist/update/release-manager.js.map +1 -1
  175. package/dist/update/transaction-progress.d.ts +63 -0
  176. package/dist/update/transaction-progress.d.ts.map +1 -0
  177. package/dist/update/transaction-progress.js +207 -0
  178. package/dist/update/transaction-progress.js.map +1 -0
  179. package/dist/utils/env.d.ts +16 -1
  180. package/dist/utils/env.d.ts.map +1 -1
  181. package/dist/utils/env.js +55 -43
  182. package/dist/utils/env.js.map +1 -1
  183. package/host-runtime/dist/diagnostician-auto-run.js +46 -34
  184. package/host-runtime/dist/governance-observation-store.d.ts +38 -0
  185. package/host-runtime/dist/governance-observation-store.js +41 -0
  186. package/host-runtime/dist/governance-trajectory-turn-reader.js +26 -33
  187. package/host-runtime/dist/index.d.ts +1 -0
  188. package/host-runtime/dist/index.js +4 -0
  189. package/host-runtime/dist/intent-doc-reader.js +1 -1
  190. package/host-runtime/dist/workspace-pipeline-host-deps.d.ts +65 -0
  191. package/host-runtime/dist/workspace-pipeline-host-deps.js +94 -0
  192. package/host-runtime/dist/workspace-telemetry-emitter.js +14 -0
  193. package/host-runtime/package.json +1 -1
  194. package/install-layout/dist/background-execution-transition.d.ts +11 -1
  195. package/install-layout/dist/background-execution-transition.js +45 -1
  196. package/install-layout/dist/index.d.ts +4 -3
  197. package/install-layout/dist/index.js +11 -4
  198. package/install-layout/dist/openclaw-config-path.d.ts +9 -0
  199. package/install-layout/dist/openclaw-config-path.js +64 -0
  200. package/install-layout/dist/pd-home.d.ts +12 -0
  201. package/install-layout/dist/pd-home.js +6 -1
  202. package/install-layout/package.json +1 -1
  203. package/package.json +7 -7
  204. package/pd-cli/dist/commands/candidate.d.ts +15 -0
  205. package/pd-cli/dist/commands/candidate.d.ts.map +1 -1
  206. package/pd-cli/dist/commands/candidate.js +449 -93
  207. package/pd-cli/dist/commands/candidate.js.map +1 -1
  208. package/pd-cli/dist/commands/codex-worker.js +2 -2
  209. package/pd-cli/dist/commands/codex-worker.js.map +1 -1
  210. package/pd-cli/dist/commands/console.d.ts.map +1 -1
  211. package/pd-cli/dist/commands/console.js +10 -0
  212. package/pd-cli/dist/commands/console.js.map +1 -1
  213. package/pd-cli/dist/commands/diagnose.d.ts.map +1 -1
  214. package/pd-cli/dist/commands/diagnose.js +301 -233
  215. package/pd-cli/dist/commands/diagnose.js.map +1 -1
  216. package/pd-cli/dist/commands/intake-outcome-guidance.d.ts +57 -0
  217. package/pd-cli/dist/commands/intake-outcome-guidance.d.ts.map +1 -0
  218. package/pd-cli/dist/commands/intake-outcome-guidance.js +206 -0
  219. package/pd-cli/dist/commands/intake-outcome-guidance.js.map +1 -0
  220. package/pd-cli/dist/commands/mcp-probe.d.ts.map +1 -1
  221. package/pd-cli/dist/commands/mcp-probe.js +1 -0
  222. package/pd-cli/dist/commands/mcp-probe.js.map +1 -1
  223. package/pd-cli/dist/commands/pain-record.d.ts.map +1 -1
  224. package/pd-cli/dist/commands/pain-record.js +22 -16
  225. package/pd-cli/dist/commands/pain-record.js.map +1 -1
  226. package/pd-cli/dist/commands/pain-retry.d.ts.map +1 -1
  227. package/pd-cli/dist/commands/pain-retry.js +139 -85
  228. package/pd-cli/dist/commands/pain-retry.js.map +1 -1
  229. package/pd-cli/dist/commands/runtime-uat.d.ts.map +1 -1
  230. package/pd-cli/dist/commands/runtime-uat.js +1 -0
  231. package/pd-cli/dist/commands/runtime-uat.js.map +1 -1
  232. package/pd-cli/dist/commands/service-lifecycle.js +1 -1
  233. package/pd-cli/dist/commands/service-lifecycle.js.map +1 -1
  234. package/pd-cli/dist/commands/service-run-once.d.ts +1 -1
  235. package/pd-cli/dist/commands/service-run-once.d.ts.map +1 -1
  236. package/pd-cli/dist/commands/service-run-once.js +9 -5
  237. package/pd-cli/dist/commands/service-run-once.js.map +1 -1
  238. package/pd-cli/dist/commands/workbuddy-worker.js +2 -2
  239. package/pd-cli/dist/commands/workbuddy-worker.js.map +1 -1
  240. package/pd-cli/dist/program.d.ts.map +1 -1
  241. package/pd-cli/dist/program.js +14 -3
  242. package/pd-cli/dist/program.js.map +1 -1
  243. package/pd-cli/dist/services/admission-write-gate.d.ts +4 -0
  244. package/pd-cli/dist/services/admission-write-gate.d.ts.map +1 -1
  245. package/pd-cli/dist/services/admission-write-gate.js +50 -48
  246. package/pd-cli/dist/services/admission-write-gate.js.map +1 -1
  247. package/pd-cli/dist/services/config-doctor.d.ts.map +1 -1
  248. package/pd-cli/dist/services/config-doctor.js +7 -4
  249. package/pd-cli/dist/services/config-doctor.js.map +1 -1
  250. package/pd-cli/dist/services/console-launcher.js +3 -3
  251. package/pd-cli/dist/services/console-launcher.js.map +1 -1
  252. package/pd-cli/dist/services/service-host/managed-run.d.ts.map +1 -1
  253. package/pd-cli/dist/services/service-host/managed-run.js +25 -8
  254. package/pd-cli/dist/services/service-host/managed-run.js.map +1 -1
  255. package/pd-cli/dist/services/service-host/scheduler/service-status.d.ts +12 -0
  256. package/pd-cli/dist/services/service-host/scheduler/service-status.d.ts.map +1 -1
  257. package/pd-cli/dist/services/service-host/scheduler/service-status.js +16 -7
  258. package/pd-cli/dist/services/service-host/scheduler/service-status.js.map +1 -1
  259. package/pd-cli/dist/services/service-host/status/service-run-status.d.ts +7 -5
  260. package/pd-cli/dist/services/service-host/status/service-run-status.d.ts.map +1 -1
  261. package/pd-cli/dist/services/service-host/status/service-run-status.js +1 -1
  262. package/pd-cli/dist/services/service-host/status/service-run-status.js.map +1 -1
  263. package/pd-cli/package.json +1 -1
  264. package/pd-mcp-server/dist/server.d.ts +7 -0
  265. package/pd-mcp-server/dist/server.js +12 -1
  266. package/pd-mcp-server/dist/submit-assembly.js +63 -19
  267. package/pd-mcp-server/dist/version.d.ts +1 -1
  268. package/pd-mcp-server/dist/version.js +1 -1
  269. package/pd-mcp-server/package.json +1 -1
  270. package/plugin/dist/bundle.js +539 -503
  271. package/plugin/dist/core/config-health.d.ts +6 -0
  272. package/plugin/dist/core/openclaw-config-loader.d.ts +14 -0
  273. package/plugin/dist/core/pain-service.d.ts +26 -0
  274. package/plugin/dist/hooks/openclaw-run-turn-correlation.d.ts +30 -0
  275. package/plugin/dist/hooks/openclaw-target-turn-capture.d.ts +13 -0
  276. package/plugin/dist/hooks/pain-receipt-fallback.d.ts +107 -0
  277. package/plugin/dist/openclaw-sdk.d.ts +15 -0
  278. package/plugin/dist/openclaw-worker.d.ts +3 -0
  279. package/plugin/dist/openclaw-worker.js +288 -287
  280. package/plugin/dist/openclaw.plugin.json +1 -1
  281. package/plugin/openclaw.plugin.json +1 -1
  282. package/plugin/package.json +1 -1
  283. package/release-manager/dist/i18n.js +72 -0
  284. package/release-manager/dist/installer.js +542 -31
  285. package/release-manager/dist/installers/codex-host-installer.js +1 -1
  286. package/release-manager/dist/installers/index.js +4 -0
  287. package/release-manager/dist/mvp-config.js +1 -1
  288. package/release-manager/dist/service-host-bridge.js +228 -48
  289. package/release-manager/dist/service-host-provisioning.js +595 -0
  290. package/release-manager/dist/update/apply-payload.js +44 -2
  291. package/release-manager/dist/update/console-surface.js +6 -1
  292. package/release-manager/dist/update/install-layout.js +49 -7
  293. package/release-manager/dist/update/release-manager-authority.js +45 -3
  294. package/release-manager/dist/update/release-manager.js +29 -1
  295. package/release-manager/dist/update/transaction-progress.js +207 -0
  296. package/release-manager/dist/utils/env.js +55 -43
  297. package/release-manager/package.json +5 -5
  298. package/workbuddy-adapter/dist/codec/input-decoder.d.ts +21 -0
  299. package/workbuddy-adapter/dist/codec/input-decoder.js +50 -1
  300. package/workbuddy-adapter/dist/ingestion/pain-receipt-fallback.d.ts +68 -0
  301. package/workbuddy-adapter/dist/ingestion/pain-receipt-fallback.js +226 -0
  302. package/workbuddy-adapter/dist/pd-hook.js +60 -0
  303. package/workbuddy-adapter/dist/worker/workspace-worker.d.ts +3 -0
  304. package/workbuddy-adapter/dist/worker/workspace-worker.js +82 -47
  305. package/workbuddy-adapter/package.json +1 -1
  306. package/console/dist/server/utils/gateway.d.ts +0 -29
  307. package/console/dist/server/utils/gateway.js +0 -175
@@ -45,6 +45,8 @@ import { WorkBuddyDecoderError, WorkBuddyEncoderError, isWorkBuddyHookOutput, WO
45
45
  import { recordWorkbuddyOwnerStatement } from './explicit-owner-statement.js';
46
46
  import { recordWorkbuddyPromptDeliveryEvidence, recordWorkbuddyDenyEvidence } from './workbuddy-evidence-recorder.js';
47
47
  import { ingestWorkbuddyConversation } from './ingestion/ingestion.js';
48
+ import { attemptPainReceiptFallback, painReceiptFallbackDiagnostic } from './ingestion/pain-receipt-fallback.js';
49
+ import { isPainSubmitWorkbuddyToolName } from './codec/input-decoder.js';
48
50
  const MAX_DIAGNOSTIC = 500;
49
51
  function bound(text) {
50
52
  return text.replace(/\s+/g, ' ').trim().slice(0, MAX_DIAGNOSTIC);
@@ -563,12 +565,70 @@ export async function processWorkbuddyHookInvocation(rawStdin, channelEventName,
563
565
  evidenceDiagnostics.push(diagnostic('degraded', `workbuddy_evidence_deny_failed:${errorMessage(error)}`, 'The deny decision was already encoded; evidence replay from the durable source is safe.'));
564
566
  }
565
567
  }
568
+ // PRI-1275 (B2): PostToolUse structured-receipt fallback. When a
569
+ // pd_submit_pain MCP request carried no trusted host `_meta`, its
570
+ // original Pain/Task was legally persisted unbound; the host completion
571
+ // event's own structured receipt + host-authoritative identity now
572
+ // restores the SAME task via the Core CAS recovery. P1-1: the tool name
573
+ // arrives in WorkBuddy's MCP namespace (`mcp__pd-recall__pd_submit_pain`,
574
+ // hyphen preserved — the engine does NOT sanitize) and is gated by the
575
+ // exact codec parser — a bare or foreign-server name never enters.
576
+ // Independent of workbuddy_conversation_ingestion (no
577
+ // transcript read; ids only), gated by the Workspace-level
578
+ // host_identity_minimal_metadata authorization. Fail-open: a fallback
579
+ // failure never changes the host decision.
580
+ const receiptDiagnostics = [];
581
+ // Each hook invocation resolves the flags from the CURRENT config, so a
582
+ // revoked minimal identity authorization stops binding on the next event.
583
+ const minimalMetadataGranted = flags.host_identity_minimal_metadata?.enabled === true;
584
+ if (event.kind === 'after_tool_call'
585
+ && event.context.toolName !== undefined
586
+ && isPainSubmitWorkbuddyToolName(event.context.toolName)
587
+ && event.context.toolCallId !== undefined) {
588
+ try {
589
+ const fallback = await attemptPainReceiptFallback({
590
+ workspaceDir: resolution.workspaceDir,
591
+ toolName: event.context.toolName,
592
+ toolResponse: event.context.toolOutput,
593
+ // Identity comes from the EVENT's own session/call ids. The event's
594
+ // `generation_id` (decoder `context.turnId`) is deliberately NOT
595
+ // passed: its equivalence to a PD submission turn is unproven
596
+ // (SPEC TD §1.3 field rules; Devin/CodeRabbit round — mapping it
597
+ // would pin the recovery to a target the trajectory store cannot
598
+ // resolve, wedging the task in waiting_for_target_evidence).
599
+ identity: {
600
+ sessionId: event.context.sessionId,
601
+ toolCallId: event.context.toolCallId,
602
+ },
603
+ minimalMetadataGranted,
604
+ });
605
+ const line = painReceiptFallbackDiagnostic(fallback);
606
+ if (line !== null) {
607
+ const nextAction = fallback.status === 'not_applicable'
608
+ ? undefined
609
+ : fallback.outcome.status === 'recovered'
610
+ ? 'The submission identity was restored on the original task; no resubmission is needed.'
611
+ : fallback.outcome.status === 'already_bound'
612
+ ? 'The original task already carries this identity; nothing to do.'
613
+ : fallback.outcome.reasonCode === 'blocked_by_consent'
614
+ ? 'The Workspace has not granted minimal identity-metadata collection; enable host_identity_minimal_metadata in .pd/config.yaml if binding is wanted.'
615
+ : 'The recovery was refused and is not retried automatically; the submission stays legally unbound. Resubmit pd_submit_pain only if the binding is needed.';
616
+ receiptDiagnostics.push(nextAction === undefined
617
+ ? diagnostic('degraded', line, 'The receipt fallback outcome was recorded.')
618
+ : diagnostic('degraded', line, nextAction));
619
+ }
620
+ }
621
+ catch (error) {
622
+ receiptDiagnostics.push(diagnostic('degraded', `pain_receipt_fallback_failed:${errorMessage(error)}`, 'The hook decision is unaffected; identity recovery for this call did not complete and is not retried automatically — the submission stays legally unbound.'));
623
+ }
624
+ }
566
625
  const stderr = [
567
626
  ...annotateContextWarnings(result.warnings ?? []).slice(0, 16).map((warning) => diagnostic('degraded', warning, 'Inspect the PD governance workspace state and retry; the hook stayed permissive (allow+warnings is degraded health, not fail-closed).')),
568
627
  ...evaluationDiagnostics,
569
628
  ...evidenceDiagnostics,
570
629
  ...autoDiagnostics,
571
630
  ...toolSemanticsDiagnostics,
631
+ ...receiptDiagnostics,
572
632
  ];
573
633
  return { stdout: receiptOutput(encoded), exitCode: 0, stderr: [...stderr, ...(ownerReceipt === undefined ? [] : [ownerReceipt])] };
574
634
  }
@@ -1,3 +1,4 @@
1
+ import { type TargetEvidenceReconcileReport } from '@principles/core/runtime';
1
2
  import { type InternalizationConsumerCycleOutcome, type ConsumerCycleLogger, type ReconcileGovernanceContinuationResult, type SignalLlmClassifier, type Stage2CorrectionCycleReport } from '@principles/host-runtime';
2
3
  import { type WorkbuddyCatchUpResult } from '../ingestion/catch-up.js';
3
4
  export type WorkbuddyWorkerMode = 'ready' | 'manual_action_required' | 'paused' | 'degraded';
@@ -14,6 +15,8 @@ export interface WorkbuddyWorkerCycleStepReport {
14
15
  readonly nextAction?: string;
15
16
  } | null;
16
17
  readonly downstream: InternalizationConsumerCycleOutcome | null;
18
+ /** PRI-1296: bounded exact-target evidence reconcile, before candidate picking. */
19
+ readonly targetEvidenceReconcile?: TargetEvidenceReconcileReport;
17
20
  /** Phase B Stage-2 review step (always last, ≤2 candidates / ≤60s aggregate). */
18
21
  readonly stage2?: Stage2CorrectionCycleReport;
19
22
  }
@@ -31,10 +31,11 @@
31
31
  */
32
32
  import fs from 'node:fs';
33
33
  import path from 'node:path';
34
- import { computeFeatureFlagsFromConfig, createRuntimeStateHandle, createPainSignalBridge, isRetryWaitBackoffElapsed, PrincipleTreeLedgerAdapter, resolveDiagnosticianCapability, } from '@principles/core/runtime';
35
- import { loadPdConfigForPlugin, loadFeatureFlagFromConfig, reconcileGovernanceContinuation, runInternalizationConsumerCycle, runStage2CorrectionCycle, createSignalClassifierForWorkspace, createGovernanceTrajectoryTurnReader, createConsentLedgerSourceMaterialAuthorization, createHostIntentDocReader, isAutomaticPainSubmissionAuthorized, saveHostToolDeclaration, HOST_TOOL_DECLARATION_VERSION, } from '@principles/host-runtime';
34
+ import { computeFeatureFlagsFromConfig, createRuntimeStateHandle, createPainSignalBridge, isRetryWaitBackoffElapsed, pickDiagnosticianCandidate, reconcileWaitingTargetEvidenceTasks, PrincipleTreeLedgerAdapter, resolveDiagnosticianCapability, } from '@principles/core/runtime';
35
+ import { loadPdConfigForPlugin, loadFeatureFlagFromConfig, reconcileGovernanceContinuation, runInternalizationConsumerCycle, runStage2CorrectionCycle, createSignalClassifierForWorkspace, resolveWorkspacePipelineHostDeps, saveHostToolDeclaration, HOST_TOOL_DECLARATION_VERSION, } from '@principles/host-runtime';
36
36
  import { WORKBUDDY_TOOL_SEMANTICS, WORKBUDDY_TOOL_SEMANTIC_MAPPINGS } from '../tool-semantics.js';
37
37
  import { catchUpWorkbuddyIngestion } from '../ingestion/catch-up.js';
38
+ import { readWorkbuddyTargetTurnEvidence } from '../ingestion/pain-receipt-fallback.js';
38
39
  const WORKER_OWNER = 'companion-worker';
39
40
  const DEFAULT_DIAG_CANDIDATE_LIMIT = 5;
40
41
  // ── Cycle liveness (Phase 2, SPEC §11 / TD §2.3: WorkBuddy had NO liveness
@@ -157,22 +158,18 @@ function finalizeLiveness(workspaceDir, cycleStartedAt, settlement) {
157
158
  });
158
159
  }
159
160
  /**
160
- * Oldest pending diagnostician first; retry_wait candidates are filtered to
161
- * those whose backoff window has ELAPSED (same discipline as the Codex
162
- * worker — an old-but-waiting task cannot starve a younger eligible one).
161
+ * PRI-1275 review round (CR-2): the candidate pick delegates to the SHARED
162
+ * Core `pickDiagnosticianCandidate` — the same authority the Codex worker
163
+ * uses. Its store queries exclude `waiting_for_target_evidence` /
164
+ * `blocked_by_source_material_consent` tasks INSIDE the SQL (before ORDER BY
165
+ * + LIMIT), so a task left waiting by the receipt recovery can never block
166
+ * the head of this host's diagnostician queue (SPEC §4 A3), and the
167
+ * pending/retry_wait fair-share cursor stays one implementation for both
168
+ * hosts. The local oldest-first variant this replaces had none of those
169
+ * exclusions.
163
170
  */
164
- async function pickDiagnosticianCandidate(stateManager, limit) {
165
- const pending = await stateManager.listTasks({ taskKind: 'diagnostician', status: 'pending', orderBy: 'updated_at_asc', limit });
166
- const [first] = pending;
167
- if (first !== undefined)
168
- return first;
169
- const retrying = await stateManager.listTasks({ taskKind: 'diagnostician', status: 'retry_wait', orderBy: 'updated_at_asc', limit });
170
- for (const candidate of retrying) {
171
- if (isRetryWaitBackoffElapsed(candidate.status, candidate.leaseExpiresAt)) {
172
- return candidate;
173
- }
174
- }
175
- return null;
171
+ async function pickNextDiagnosticianCandidate(stateManager, limit) {
172
+ return pickDiagnosticianCandidate(stateManager, limit, new Date().toISOString());
176
173
  }
177
174
  /**
178
175
  * Run ONE bounded worker cycle for a canonical governance workspace. Never
@@ -245,6 +242,8 @@ export async function runWorkbuddyWorkspaceWorkerCycle(options) {
245
242
  });
246
243
  // Steps 3–5 — execution authority: internalization_auto_consumer.
247
244
  let diagnostician = null;
245
+ // PRI-1296: filled by the exact-target evidence reconcile below.
246
+ let targetEvidenceReconcile = null;
248
247
  if (diagnosticianDisabled) {
249
248
  diagnostician = {
250
249
  taskId: '',
@@ -301,40 +300,76 @@ export async function runWorkbuddyWorkspaceWorkerCycle(options) {
301
300
  try {
302
301
  const handle = await createRuntimeStateHandle({ workspaceDir, readonly: false });
303
302
  try {
303
+ // SPEC-PD-PIPELINE-SPINE-001 §4.2 (PRI-1292 Phase 2A): ONE assembly
304
+ // point for the five host collaborators. The target-evidence reconcile
305
+ // and any diagnostician bridge in this cycle share the SAME consent
306
+ // authorization instance.
307
+ const hostDeps = resolveWorkspacePipelineHostDeps({
308
+ workspaceDir,
309
+ effectiveConfig: config.effective,
310
+ telemetryPersistenceFailureHandler: (detail) => {
311
+ try {
312
+ emitEvent('WORKBUDDY_WORKER_CRITICAL_TELEMETRY_PERSIST_FAILED', detail);
313
+ }
314
+ catch {
315
+ // Telemetry persistence warnings must never fail the worker cycle.
316
+ }
317
+ },
318
+ });
304
319
  const sweep = await handle.stateManager.runRecoverySweep();
305
320
  if (sweep.recovered > 0 || sweep.errors.length > 0) {
306
321
  emitEvent('WORKBUDDY_WORKER_RECOVERY_SWEEP', JSON.stringify({ recovered: sweep.recovered, failed: sweep.errors.length }));
307
322
  }
308
- const candidate = await pickDiagnosticianCandidate(handle.stateManager, options.diagnosticianCandidateLimit ?? DEFAULT_DIAG_CANDIDATE_LIMIT);
323
+ // PRI-1296: reconcile waiting target evidence BEFORE the candidate
324
+ // picker. Catch-up may have just delivered the exact target turn, and
325
+ // the picker SQL excludes waiting tasks; doing this after picking
326
+ // would let diagnosis consume a task before its evidence exists.
327
+ targetEvidenceReconcile = await reconcileWaitingTargetEvidenceTasks({
328
+ stateManager: handle.stateManager,
329
+ readTargetTurnEvidence: (sessionId, turnId) => readWorkbuddyTargetTurnEvidence(workspaceDir, sessionId, turnId),
330
+ sourceMaterialAuthorization: hostDeps.sourceMaterialAuthorization,
331
+ hostKind: 'workbuddy',
332
+ nowIso: new Date().toISOString(),
333
+ });
334
+ if (targetEvidenceReconcile.flipped > 0 || targetEvidenceReconcile.blocked > 0 || targetEvidenceReconcile.errors.length > 0) {
335
+ emitEvent('WORKBUDDY_WORKER_TARGET_EVIDENCE_RECONCILE', JSON.stringify(targetEvidenceReconcile));
336
+ }
337
+ const candidate = await pickNextDiagnosticianCandidate(handle.stateManager, options.diagnosticianCandidateLimit ?? DEFAULT_DIAG_CANDIDATE_LIMIT);
309
338
  if (candidate !== null) {
310
339
  const stateDir = path.join(workspaceDir, '.state');
311
- const bridge = await createPainSignalBridge({
312
- workspaceDir,
313
- stateDir,
314
- ledgerAdapter: new PrincipleTreeLedgerAdapter({ stateDir }),
315
- owner: WORKER_OWNER,
316
- effectiveConfig: config.effective,
317
- getEnvVar: (name) => process.env[name],
340
+ let releaseBridge;
341
+ try {
318
342
  // PRI-1233 / SPEC §9.2: this worker is where Stage A actually runs
319
- // for governance-admitted WorkBuddy pains — the neutral host reader
320
- // must ride along (flag-off = zero filesystem access inside it).
321
- intentDocReader: createHostIntentDocReader({ workspaceDir, effectiveConfig: config.effective }),
322
- // PRI-1265: the worker's Stage A gets the bound session's ORIGINAL
323
- // turns from the workspace's own consent-tiered governance store.
324
- trajectoryTurnReader: createGovernanceTrajectoryTurnReader({ workspaceDir, sourceMaterialAuthorization: createConsentLedgerSourceMaterialAuthorization(workspaceDir) }),
325
- // PRI-1283 R2: latest-consent gate consulted per assembly / model call.
326
- sourceMaterialAuthorization: createConsentLedgerSourceMaterialAuthorization(workspaceDir),
327
- // SPEC §9.6: lazy probe — a revoked flag stops persisted
328
- // automatic_hook tasks at the bridge's execution boundary.
329
- isAutoPainSubmissionAuthorized: () => isAutomaticPainSubmissionAuthorized(workspaceDir),
330
- });
331
- const executed = await bridge.executePendingDiagnosis({ taskId: candidate.taskId });
332
- diagnostician = {
333
- taskId: candidate.taskId,
334
- status: executed.status,
335
- ...(executed.message !== undefined ? { message: executed.message.slice(0, 200) } : {}),
336
- ...(executed.errorCategory !== undefined ? { errorCategory: executed.errorCategory } : {}),
337
- };
343
+ // for governance-admitted WorkBuddy pains; PRI-1265: the Stage A gets
344
+ // the bound session's ORIGINAL turns through the shared host deps.
345
+ const bridge = await createPainSignalBridge({
346
+ workspaceDir,
347
+ stateDir,
348
+ ledgerAdapter: new PrincipleTreeLedgerAdapter({ stateDir }),
349
+ owner: WORKER_OWNER,
350
+ effectiveConfig: config.effective,
351
+ getEnvVar: (name) => process.env[name],
352
+ intentDocReader: hostDeps.intentDocReader,
353
+ trajectoryTurnReader: hostDeps.trajectoryTurnReader,
354
+ sourceMaterialAuthorization: hostDeps.sourceMaterialAuthorization,
355
+ // PRI-939 Option A: allowlisted runner/bridge events persist to
356
+ // the workspace sink instead of the unsubscribed singleton.
357
+ telemetrySink: hostDeps.telemetrySink,
358
+ // SPEC §9.6: lazy probe — a revoked flag stops persisted
359
+ // automatic_hook tasks at the bridge's execution boundary.
360
+ isAutoPainSubmissionAuthorized: hostDeps.isAutoPainSubmissionAuthorized,
361
+ }, (release) => { releaseBridge = release; });
362
+ const executed = await bridge.executePendingDiagnosis({ taskId: candidate.taskId });
363
+ diagnostician = {
364
+ taskId: candidate.taskId,
365
+ status: executed.status,
366
+ ...(executed.message !== undefined ? { message: executed.message.slice(0, 200) } : {}),
367
+ ...(executed.errorCategory !== undefined ? { errorCategory: executed.errorCategory } : {}),
368
+ };
369
+ }
370
+ finally {
371
+ await releaseBridge?.();
372
+ }
338
373
  }
339
374
  else {
340
375
  const waiting = await handle.stateManager.listTasks({ taskKind: 'diagnostician', status: 'retry_wait', orderBy: 'updated_at_asc', limit: 1 });
@@ -358,7 +393,7 @@ export async function runWorkbuddyWorkspaceWorkerCycle(options) {
358
393
  mode: 'degraded',
359
394
  reason,
360
395
  nextAction: 'Inspect the governance workspace runtime profile and provider configuration; the task keeps its pending/retry state and no evidence was mutated.',
361
- report: { catchUp, reconcile, diagnostician: null, downstream: null },
396
+ report: { catchUp, reconcile, diagnostician: null, downstream: null, ...(targetEvidenceReconcile !== null ? { targetEvidenceReconcile } : {}) },
362
397
  };
363
398
  }
364
399
  }
@@ -381,7 +416,7 @@ export async function runWorkbuddyWorkspaceWorkerCycle(options) {
381
416
  mode: 'degraded',
382
417
  reason,
383
418
  nextAction: 'Repair WorkBuddy host declaration persistence (.pd/host-tool-semantics/workbuddy.json) before running the downstream internalization cycle; the worker retries automatically on the next cycle.',
384
- report: { catchUp, reconcile, diagnostician, downstream: null },
419
+ report: { catchUp, reconcile, diagnostician, downstream: null, ...(targetEvidenceReconcile !== null ? { targetEvidenceReconcile } : {}) },
385
420
  };
386
421
  }
387
422
  writeLiveness(workspaceDir, { runningStage: 'downstream_cycle', stageDeadline: new Date(Date.now() + LIVENESS_STAGE_DEADLINE_MS.downstream_cycle).toISOString() });
@@ -434,6 +469,6 @@ export async function runWorkbuddyWorkspaceWorkerCycle(options) {
434
469
  ...base,
435
470
  mode: degradedReason !== undefined ? 'degraded' : 'ready',
436
471
  ...(degradedReason !== undefined ? { reason: degradedReason, nextAction: 'Inspect the governance workspace .pd/config.yaml runtime profile and the per-step report above; the worker retries automatically on the next cycle.' } : {}),
437
- report: { catchUp, reconcile, diagnostician, downstream, stage2 },
472
+ report: { catchUp, reconcile, diagnostician, downstream, ...(targetEvidenceReconcile !== null ? { targetEvidenceReconcile } : {}), stage2 },
438
473
  };
439
474
  }
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@principles/workbuddy-adapter",
3
- "version": "0.8.0",
3
+ "version": "0.9.1",
4
4
  "description": "WorkBuddy host adapter for Principles Disciple — implements the HostAdapter interface for WorkBuddy's Git Bash command-hook model (ADR-0020 third host, SPEC workbuddy-host-adapter v0.3.0).",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -1,29 +0,0 @@
1
- export interface OpenClawGatewayStatus {
2
- isRunning: boolean;
3
- port?: number;
4
- pid?: number;
5
- }
6
- export interface GatewayControlResult {
7
- ok: boolean;
8
- error?: string;
9
- }
10
- /**
11
- * Check whether the OpenClaw gateway is currently running.
12
- * Reads the configured port from openclaw.json, probes 127.0.0.1:<port>,
13
- * and (best-effort) resolves the owning PID.
14
- */
15
- export declare function checkOpenClawGateway(): Promise<OpenClawGatewayStatus>;
16
- /**
17
- * Stop the OpenClaw gateway service. Call before mutating the plugin ext dir
18
- * to release file locks held on native modules (EPERM on backup copyfile).
19
- *
20
- * Tries a plain stop first, then `--force`: recent OpenClaw builds refuse an
21
- * operator-gateway stop without the flag, while older builds reject the
22
- * unknown option instead — only trying one shape breaks the other generation.
23
- */
24
- export declare function stopOpenClawGateway(): GatewayControlResult;
25
- /**
26
- * Start the OpenClaw gateway service (inverse of stopOpenClawGateway).
27
- * Called after update completes (success or failure) to leave the gateway running.
28
- */
29
- export declare function restartOpenClawGateway(): GatewayControlResult;
@@ -1,175 +0,0 @@
1
- /**
2
- * OpenClaw gateway control utilities for the update flow.
3
- *
4
- * Ported from create-principles-disciple/src/utils/env.ts (PRI-230 / commit 6efc0afa).
5
- * Lives in pd-console so the Web UI update handler can stop/restart the gateway
6
- * around file mutations without cross-package imports.
7
- *
8
- * rc-9: every function returns a structured result instead of throwing.
9
- */
10
- import { execFileSync } from 'child_process';
11
- import * as fs from 'fs';
12
- import * as path from 'path';
13
- import * as net from 'net';
14
- import { errorMessage } from './response.js';
15
- import { getPdHome, getPdHomeResolution } from './pd-home.js';
16
- // rc-2: type guard instead of `as` cast on parsed JSON.
17
- function isRecord(v) {
18
- return typeof v === 'object' && v !== null && !Array.isArray(v);
19
- }
20
- // ---------------------------------------------------------------------------
21
- // Gateway detection
22
- // ---------------------------------------------------------------------------
23
- /**
24
- * Resolve the OpenClaw config directory.
25
- *
26
- * PRI-872: derived from the process-wide PD home (production keeps
27
- * OPENCLAW_HOME > ~/.openclaw; an experiment instance reads its own root), so
28
- * the console never reports or probes the production gateway from a second
29
- * instance.
30
- */
31
- function resolveOpenClawConfigDir() {
32
- return getPdHome().openclawHome;
33
- }
34
- /**
35
- * Read the gateway port from ~/.openclaw/openclaw.json → { gateway: { port } }.
36
- * Returns null if the file or field is missing/malformed.
37
- */
38
- function readOpenClawPort() {
39
- const configPath = path.join(resolveOpenClawConfigDir(), 'openclaw.json');
40
- if (!fs.existsSync(configPath))
41
- return null;
42
- try {
43
- const raw = fs.readFileSync(configPath, 'utf-8');
44
- const config = JSON.parse(raw);
45
- if (!isRecord(config))
46
- return null;
47
- const gateway = config.gateway;
48
- if (!isRecord(gateway))
49
- return null;
50
- const port = gateway.port;
51
- if (typeof port === 'number' && port > 0 && port < 65536)
52
- return port;
53
- }
54
- catch { /* ignore */ }
55
- return null;
56
- }
57
- function checkPortListening(port) {
58
- return new Promise((resolve) => {
59
- const socket = new net.Socket();
60
- const timeout = 2000;
61
- socket.setTimeout(timeout);
62
- socket.on('connect', () => { socket.destroy(); resolve(true); });
63
- socket.on('error', () => { socket.destroy(); resolve(false); });
64
- socket.on('timeout', () => { socket.destroy(); resolve(false); });
65
- socket.connect(port, '127.0.0.1');
66
- });
67
- }
68
- /**
69
- * Check whether the OpenClaw gateway is currently running.
70
- * Reads the configured port from openclaw.json, probes 127.0.0.1:<port>,
71
- * and (best-effort) resolves the owning PID.
72
- */
73
- export async function checkOpenClawGateway() {
74
- const port = readOpenClawPort();
75
- if (!port)
76
- return { isRunning: false };
77
- const listening = await checkPortListening(port);
78
- if (!listening)
79
- return { isRunning: false };
80
- let pid = undefined;
81
- try {
82
- if (process.platform === 'win32') {
83
- // EP-08: spawn via argv array — no cmd.exe shell in the chain, so even a
84
- // hostile config value could never be re-interpreted as shell syntax.
85
- // port is already validated as an integer in readOpenClawPort().
86
- const output = execFileSync('powershell', ['-NoProfile', '-Command', `(Get-NetTCPConnection -LocalPort ${port} -State Listen -ErrorAction SilentlyContinue).OwningProcess`], { encoding: 'utf-8', timeout: 5000, stdio: ['ignore', 'pipe', 'ignore'] }).trim();
87
- if (output) {
88
- const [firstLine] = output.split('\n');
89
- if (firstLine)
90
- pid = parseInt(firstLine.trim(), 10);
91
- }
92
- }
93
- else {
94
- // EP-08: argv form replaces the old shell string (which needed
95
- // `2>/dev/null`); stderr is discarded via stdio instead.
96
- const output = execFileSync('lsof', ['-i', `:${port}`, '-t', '-sTCP:LISTEN'], { encoding: 'utf-8', timeout: 5000, stdio: ['ignore', 'pipe', 'ignore'] }).trim();
97
- if (output) {
98
- const [firstLine] = output.split('\n');
99
- if (firstLine)
100
- pid = parseInt(firstLine.trim(), 10);
101
- }
102
- }
103
- }
104
- catch { /* ignore */ }
105
- return { isRunning: true, port, pid };
106
- }
107
- // ---------------------------------------------------------------------------
108
- // Gateway stop / restart
109
- // ---------------------------------------------------------------------------
110
- /**
111
- * Run `openclaw gateway <subcommand>` (service-level: launchd/systemd/schtasks).
112
- * rc-9: never throws — returns {ok:false, error} so the caller can degrade
113
- * with a structured reason + nextAction instead of crashing mid-update.
114
- */
115
- function runGatewayServiceCommand(subcommand, extraArgs = []) {
116
- // PRI-872: `openclaw gateway stop|start` drives the MACHINE-LEVEL service
117
- // (launchd/systemd/schtasks), not a process this console owns. An experiment
118
- // instance must never stop the production gateway — its own gateway is a
119
- // foreground `openclaw gateway run` owned by the experiment launcher.
120
- // Resolution failure is reported, not thrown: this helper's contract is
121
- // "never throws" (rc-9), so callers degrade on a structured result.
122
- const pdHome = getPdHomeResolution();
123
- if (!pdHome.ok) {
124
- return { ok: false, error: `pd_home_invalid (${pdHome.reason}): ${pdHome.message}` };
125
- }
126
- if (pdHome.mode === 'experiment') {
127
- return {
128
- ok: false,
129
- error: 'experimental_instance: the machine-level OpenClaw service belongs to the production install; the experiment gateway runs in the foreground under the experiment launcher and must be restarted there.',
130
- };
131
- }
132
- try {
133
- // EP-08: argv array + typed subcommand union — every argv is a constant
134
- // literal, so no external input can reach the command line. shell:true is
135
- // required on Windows: the npm-global `openclaw` resolves to a .cmd shim,
136
- // and Node's CVE-2024-27980 hardening refuses to spawn .cmd targets
137
- // without a shell (observed 2026-09-10 as a silent ENOENT that skipped
138
- // every gateway stop/restart during console updates — PRI-723).
139
- execFileSync('openclaw', ['gateway', subcommand, ...extraArgs], {
140
- stdio: 'pipe',
141
- encoding: 'utf-8',
142
- timeout: 15000,
143
- shell: process.platform === 'win32',
144
- });
145
- return { ok: true };
146
- }
147
- catch (e) {
148
- const msg = errorMessage(e);
149
- return { ok: false, error: `\`openclaw gateway ${subcommand}\` failed: ${msg}` };
150
- }
151
- }
152
- /**
153
- * Stop the OpenClaw gateway service. Call before mutating the plugin ext dir
154
- * to release file locks held on native modules (EPERM on backup copyfile).
155
- *
156
- * Tries a plain stop first, then `--force`: recent OpenClaw builds refuse an
157
- * operator-gateway stop without the flag, while older builds reject the
158
- * unknown option instead — only trying one shape breaks the other generation.
159
- */
160
- export function stopOpenClawGateway() {
161
- const plain = runGatewayServiceCommand('stop');
162
- if (plain.ok)
163
- return plain;
164
- const forced = runGatewayServiceCommand('stop', ['--force']);
165
- if (forced.ok)
166
- return forced;
167
- return { ok: false, error: `${plain.error}; forced retry: ${forced.error}` };
168
- }
169
- /**
170
- * Start the OpenClaw gateway service (inverse of stopOpenClawGateway).
171
- * Called after update completes (success or failure) to leave the gateway running.
172
- */
173
- export function restartOpenClawGateway() {
174
- return runGatewayServiceCommand('start');
175
- }