create-principles-disciple 1.155.2 → 1.156.0

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 (247) 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 +53 -17
  4. package/codex-adapter/dist/worker/workspace-worker.js +86 -66
  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 +2 -2
  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/host-submission-context.d.ts +13 -6
  27. package/core/dist/runtime/host-submission-context.d.ts.map +1 -1
  28. package/core/dist/runtime/host-submission-context.js +77 -8
  29. package/core/dist/runtime/host-submission-context.js.map +1 -1
  30. package/core/dist/runtime/index.d.ts +2 -1
  31. package/core/dist/runtime/index.d.ts.map +1 -1
  32. package/core/dist/runtime/index.js +8 -0
  33. package/core/dist/runtime/index.js.map +1 -1
  34. package/core/dist/runtime/pain-ingress.d.ts +8 -0
  35. package/core/dist/runtime/pain-ingress.d.ts.map +1 -1
  36. package/core/dist/runtime/pain-ingress.js +8 -1
  37. package/core/dist/runtime/pain-ingress.js.map +1 -1
  38. package/core/dist/runtime/pain-recall-read-model.d.ts +72 -0
  39. package/core/dist/runtime/pain-recall-read-model.d.ts.map +1 -1
  40. package/core/dist/runtime/pain-recall-read-model.js +46 -21
  41. package/core/dist/runtime/pain-recall-read-model.js.map +1 -1
  42. package/core/dist/runtime/pain-receipt-recovery.d.ts +4 -1
  43. package/core/dist/runtime/pain-receipt-recovery.d.ts.map +1 -1
  44. package/core/dist/runtime/pain-receipt-recovery.js +28 -10
  45. package/core/dist/runtime/pain-receipt-recovery.js.map +1 -1
  46. package/core/dist/runtime/pain-signal-bridge.d.ts +38 -23
  47. package/core/dist/runtime/pain-signal-bridge.d.ts.map +1 -1
  48. package/core/dist/runtime/pain-signal-bridge.js +533 -182
  49. package/core/dist/runtime/pain-signal-bridge.js.map +1 -1
  50. package/core/dist/runtime/pain-signal-runtime-factory.d.ts +8 -1
  51. package/core/dist/runtime/pain-signal-runtime-factory.d.ts.map +1 -1
  52. package/core/dist/runtime/pain-signal-runtime-factory.js +196 -25
  53. package/core/dist/runtime/pain-signal-runtime-factory.js.map +1 -1
  54. package/core/dist/runtime/pain-target-evidence-reconcile.d.ts +78 -4
  55. package/core/dist/runtime/pain-target-evidence-reconcile.d.ts.map +1 -1
  56. package/core/dist/runtime/pain-target-evidence-reconcile.js +229 -18
  57. package/core/dist/runtime/pain-target-evidence-reconcile.js.map +1 -1
  58. package/core/dist/runtime/pain-to-principle-service.d.ts +26 -5
  59. package/core/dist/runtime/pain-to-principle-service.d.ts.map +1 -1
  60. package/core/dist/runtime/pain-to-principle-service.js +63 -52
  61. package/core/dist/runtime/pain-to-principle-service.js.map +1 -1
  62. package/core/dist/runtime/store/candidate/admission-document.d.ts +43 -0
  63. package/core/dist/runtime/store/candidate/admission-document.d.ts.map +1 -1
  64. package/core/dist/runtime/store/candidate/admission-document.js +130 -0
  65. package/core/dist/runtime/store/candidate/admission-document.js.map +1 -1
  66. package/core/dist/runtime/store/candidate/candidate-store.d.ts +3 -1
  67. package/core/dist/runtime/store/candidate/candidate-store.d.ts.map +1 -1
  68. package/core/dist/runtime/store/candidate/memory-candidate-store.d.ts +2 -1
  69. package/core/dist/runtime/store/candidate/memory-candidate-store.d.ts.map +1 -1
  70. package/core/dist/runtime/store/candidate/memory-candidate-store.js +27 -1
  71. package/core/dist/runtime/store/candidate/memory-candidate-store.js.map +1 -1
  72. package/core/dist/runtime/store/candidate/sqlite-candidate-store.d.ts +2 -1
  73. package/core/dist/runtime/store/candidate/sqlite-candidate-store.d.ts.map +1 -1
  74. package/core/dist/runtime/store/candidate/sqlite-candidate-store.js +59 -2
  75. package/core/dist/runtime/store/candidate/sqlite-candidate-store.js.map +1 -1
  76. package/core/dist/runtime/store/context/sqlite-context-assembler.d.ts.map +1 -1
  77. package/core/dist/runtime/store/context/sqlite-context-assembler.js +18 -3
  78. package/core/dist/runtime/store/context/sqlite-context-assembler.js.map +1 -1
  79. package/core/dist/runtime/store/runtime-state-manager.d.ts +2 -1
  80. package/core/dist/runtime/store/runtime-state-manager.d.ts.map +1 -1
  81. package/core/dist/runtime/store/runtime-state-manager.js +4 -0
  82. package/core/dist/runtime/store/runtime-state-manager.js.map +1 -1
  83. package/core/dist/telemetry-event.d.ts +2 -2
  84. package/core/dist/telemetry-event.d.ts.map +1 -1
  85. package/core/dist/telemetry-event.js +5 -0
  86. package/core/dist/telemetry-event.js.map +1 -1
  87. package/core/package.json +1 -1
  88. package/dist/i18n.d.ts.map +1 -1
  89. package/dist/i18n.js +72 -0
  90. package/dist/i18n.js.map +1 -1
  91. package/dist/index.d.ts +15 -0
  92. package/dist/index.d.ts.map +1 -1
  93. package/dist/index.js +145 -35
  94. package/dist/index.js.map +1 -1
  95. package/dist/installer.d.ts +149 -9
  96. package/dist/installer.d.ts.map +1 -1
  97. package/dist/installer.js +562 -38
  98. package/dist/installer.js.map +1 -1
  99. package/dist/installers/codex-host-installer.js +1 -1
  100. package/dist/installers/codex-host-installer.js.map +1 -1
  101. package/dist/installers/index.d.ts +10 -0
  102. package/dist/installers/index.d.ts.map +1 -1
  103. package/dist/installers/index.js +4 -0
  104. package/dist/installers/index.js.map +1 -1
  105. package/dist/mvp-config.js +1 -1
  106. package/dist/mvp-config.js.map +1 -1
  107. package/dist/prompts.d.ts +36 -12
  108. package/dist/prompts.d.ts.map +1 -1
  109. package/dist/prompts.js +102 -30
  110. package/dist/prompts.js.map +1 -1
  111. package/dist/service-host-bridge.d.ts +71 -12
  112. package/dist/service-host-bridge.d.ts.map +1 -1
  113. package/dist/service-host-bridge.js +228 -48
  114. package/dist/service-host-bridge.js.map +1 -1
  115. package/dist/service-host-provisioning.d.ts +102 -0
  116. package/dist/service-host-provisioning.d.ts.map +1 -0
  117. package/dist/service-host-provisioning.js +595 -0
  118. package/dist/service-host-provisioning.js.map +1 -0
  119. package/dist/uninstaller.js +1 -1
  120. package/dist/uninstaller.js.map +1 -1
  121. package/dist/update/apply-payload.d.ts +9 -0
  122. package/dist/update/apply-payload.d.ts.map +1 -1
  123. package/dist/update/apply-payload.js +44 -2
  124. package/dist/update/apply-payload.js.map +1 -1
  125. package/dist/update/console-surface.d.ts +2 -1
  126. package/dist/update/console-surface.d.ts.map +1 -1
  127. package/dist/update/console-surface.js +6 -1
  128. package/dist/update/console-surface.js.map +1 -1
  129. package/dist/update/install-layout.d.ts +12 -0
  130. package/dist/update/install-layout.d.ts.map +1 -1
  131. package/dist/update/install-layout.js +49 -7
  132. package/dist/update/install-layout.js.map +1 -1
  133. package/dist/update/release-manager-authority.d.ts +16 -0
  134. package/dist/update/release-manager-authority.d.ts.map +1 -1
  135. package/dist/update/release-manager-authority.js +45 -3
  136. package/dist/update/release-manager-authority.js.map +1 -1
  137. package/dist/update/release-manager.d.ts +8 -3
  138. package/dist/update/release-manager.d.ts.map +1 -1
  139. package/dist/update/release-manager.js +29 -1
  140. package/dist/update/release-manager.js.map +1 -1
  141. package/dist/update/transaction-progress.d.ts +63 -0
  142. package/dist/update/transaction-progress.d.ts.map +1 -0
  143. package/dist/update/transaction-progress.js +207 -0
  144. package/dist/update/transaction-progress.js.map +1 -0
  145. package/dist/utils/env.d.ts +16 -1
  146. package/dist/utils/env.d.ts.map +1 -1
  147. package/dist/utils/env.js +55 -43
  148. package/dist/utils/env.js.map +1 -1
  149. package/host-runtime/dist/diagnostician-auto-run.js +37 -31
  150. package/host-runtime/dist/governance-observation-store.d.ts +38 -0
  151. package/host-runtime/dist/governance-observation-store.js +41 -0
  152. package/host-runtime/dist/governance-trajectory-turn-reader.js +26 -33
  153. package/host-runtime/package.json +1 -1
  154. package/install-layout/dist/background-execution-transition.d.ts +11 -1
  155. package/install-layout/dist/background-execution-transition.js +45 -1
  156. package/install-layout/dist/index.d.ts +3 -3
  157. package/install-layout/dist/index.js +10 -4
  158. package/install-layout/dist/pd-home.d.ts +12 -0
  159. package/install-layout/dist/pd-home.js +6 -1
  160. package/install-layout/package.json +1 -1
  161. package/package.json +10 -10
  162. package/pd-cli/dist/commands/candidate.d.ts +15 -0
  163. package/pd-cli/dist/commands/candidate.d.ts.map +1 -1
  164. package/pd-cli/dist/commands/candidate.js +449 -93
  165. package/pd-cli/dist/commands/candidate.js.map +1 -1
  166. package/pd-cli/dist/commands/console.d.ts.map +1 -1
  167. package/pd-cli/dist/commands/console.js +10 -0
  168. package/pd-cli/dist/commands/console.js.map +1 -1
  169. package/pd-cli/dist/commands/diagnose.d.ts.map +1 -1
  170. package/pd-cli/dist/commands/diagnose.js +254 -160
  171. package/pd-cli/dist/commands/diagnose.js.map +1 -1
  172. package/pd-cli/dist/commands/intake-outcome-guidance.d.ts +57 -0
  173. package/pd-cli/dist/commands/intake-outcome-guidance.d.ts.map +1 -0
  174. package/pd-cli/dist/commands/intake-outcome-guidance.js +206 -0
  175. package/pd-cli/dist/commands/intake-outcome-guidance.js.map +1 -0
  176. package/pd-cli/dist/commands/mcp-probe.d.ts.map +1 -1
  177. package/pd-cli/dist/commands/mcp-probe.js +1 -0
  178. package/pd-cli/dist/commands/mcp-probe.js.map +1 -1
  179. package/pd-cli/dist/commands/pain-record.d.ts.map +1 -1
  180. package/pd-cli/dist/commands/pain-record.js +18 -4
  181. package/pd-cli/dist/commands/pain-record.js.map +1 -1
  182. package/pd-cli/dist/commands/pain-retry.d.ts.map +1 -1
  183. package/pd-cli/dist/commands/pain-retry.js +91 -21
  184. package/pd-cli/dist/commands/pain-retry.js.map +1 -1
  185. package/pd-cli/dist/commands/runtime-uat.d.ts.map +1 -1
  186. package/pd-cli/dist/commands/runtime-uat.js +1 -0
  187. package/pd-cli/dist/commands/runtime-uat.js.map +1 -1
  188. package/pd-cli/dist/commands/service-lifecycle.js +1 -1
  189. package/pd-cli/dist/commands/service-lifecycle.js.map +1 -1
  190. package/pd-cli/dist/commands/service-run-once.d.ts +1 -1
  191. package/pd-cli/dist/commands/service-run-once.d.ts.map +1 -1
  192. package/pd-cli/dist/commands/service-run-once.js +9 -5
  193. package/pd-cli/dist/commands/service-run-once.js.map +1 -1
  194. package/pd-cli/dist/program.d.ts.map +1 -1
  195. package/pd-cli/dist/program.js +14 -3
  196. package/pd-cli/dist/program.js.map +1 -1
  197. package/pd-cli/dist/services/admission-write-gate.d.ts +4 -0
  198. package/pd-cli/dist/services/admission-write-gate.d.ts.map +1 -1
  199. package/pd-cli/dist/services/admission-write-gate.js +50 -48
  200. package/pd-cli/dist/services/admission-write-gate.js.map +1 -1
  201. package/pd-cli/dist/services/console-launcher.js +3 -3
  202. package/pd-cli/dist/services/console-launcher.js.map +1 -1
  203. package/pd-cli/dist/services/service-host/managed-run.d.ts.map +1 -1
  204. package/pd-cli/dist/services/service-host/managed-run.js +25 -8
  205. package/pd-cli/dist/services/service-host/managed-run.js.map +1 -1
  206. package/pd-cli/dist/services/service-host/scheduler/service-status.d.ts +12 -0
  207. package/pd-cli/dist/services/service-host/scheduler/service-status.d.ts.map +1 -1
  208. package/pd-cli/dist/services/service-host/scheduler/service-status.js +16 -7
  209. package/pd-cli/dist/services/service-host/scheduler/service-status.js.map +1 -1
  210. package/pd-cli/dist/services/service-host/status/service-run-status.d.ts +7 -5
  211. package/pd-cli/dist/services/service-host/status/service-run-status.d.ts.map +1 -1
  212. package/pd-cli/dist/services/service-host/status/service-run-status.js +1 -1
  213. package/pd-cli/dist/services/service-host/status/service-run-status.js.map +1 -1
  214. package/pd-cli/package.json +1 -1
  215. package/pd-mcp-server/dist/submit-assembly.js +61 -18
  216. package/pd-mcp-server/dist/version.d.ts +1 -1
  217. package/pd-mcp-server/dist/version.js +1 -1
  218. package/pd-mcp-server/package.json +1 -1
  219. package/plugin/dist/bundle.js +493 -493
  220. package/plugin/dist/openclaw-worker.js +263 -263
  221. package/plugin/dist/openclaw.plugin.json +1 -1
  222. package/plugin/openclaw.plugin.json +1 -1
  223. package/plugin/package.json +1 -1
  224. package/release-manager/dist/i18n.js +72 -0
  225. package/release-manager/dist/installer.js +562 -38
  226. package/release-manager/dist/installers/codex-host-installer.js +1 -1
  227. package/release-manager/dist/installers/index.js +4 -0
  228. package/release-manager/dist/mvp-config.js +1 -1
  229. package/release-manager/dist/service-host-bridge.js +228 -48
  230. package/release-manager/dist/service-host-provisioning.js +595 -0
  231. package/release-manager/dist/update/apply-payload.js +44 -2
  232. package/release-manager/dist/update/console-surface.js +6 -1
  233. package/release-manager/dist/update/install-layout.js +49 -7
  234. package/release-manager/dist/update/release-manager-authority.js +45 -3
  235. package/release-manager/dist/update/release-manager.js +29 -1
  236. package/release-manager/dist/update/transaction-progress.js +207 -0
  237. package/release-manager/dist/utils/env.js +55 -43
  238. package/release-manager/package.json +8 -8
  239. package/workbuddy-adapter/dist/codec/input-decoder.d.ts +21 -0
  240. package/workbuddy-adapter/dist/codec/input-decoder.js +50 -1
  241. package/workbuddy-adapter/dist/ingestion/pain-receipt-fallback.d.ts +68 -0
  242. package/workbuddy-adapter/dist/ingestion/pain-receipt-fallback.js +225 -0
  243. package/workbuddy-adapter/dist/pd-hook.js +60 -0
  244. package/workbuddy-adapter/dist/worker/workspace-worker.js +46 -44
  245. package/workbuddy-adapter/package.json +1 -1
  246. package/console/dist/server/utils/gateway.d.ts +0 -29
  247. 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
  }
@@ -31,7 +31,7 @@
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';
34
+ import { computeFeatureFlagsFromConfig, createRuntimeStateHandle, createPainSignalBridge, isRetryWaitBackoffElapsed, pickDiagnosticianCandidate, PrincipleTreeLedgerAdapter, resolveDiagnosticianCapability, } from '@principles/core/runtime';
35
35
  import { loadPdConfigForPlugin, loadFeatureFlagFromConfig, reconcileGovernanceContinuation, runInternalizationConsumerCycle, runStage2CorrectionCycle, createSignalClassifierForWorkspace, createGovernanceTrajectoryTurnReader, createConsentLedgerSourceMaterialAuthorization, createHostIntentDocReader, isAutomaticPainSubmissionAuthorized, 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';
@@ -157,22 +157,18 @@ function finalizeLiveness(workspaceDir, cycleStartedAt, settlement) {
157
157
  });
158
158
  }
159
159
  /**
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).
160
+ * PRI-1275 review round (CR-2): the candidate pick delegates to the SHARED
161
+ * Core `pickDiagnosticianCandidate` — the same authority the Codex worker
162
+ * uses. Its store queries exclude `waiting_for_target_evidence` /
163
+ * `blocked_by_source_material_consent` tasks INSIDE the SQL (before ORDER BY
164
+ * + LIMIT), so a task left waiting by the receipt recovery can never block
165
+ * the head of this host's diagnostician queue (SPEC §4 A3), and the
166
+ * pending/retry_wait fair-share cursor stays one implementation for both
167
+ * hosts. The local oldest-first variant this replaces had none of those
168
+ * exclusions.
163
169
  */
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;
170
+ async function pickNextDiagnosticianCandidate(stateManager, limit) {
171
+ return pickDiagnosticianCandidate(stateManager, limit, new Date().toISOString());
176
172
  }
177
173
  /**
178
174
  * Run ONE bounded worker cycle for a canonical governance workspace. Never
@@ -305,36 +301,42 @@ export async function runWorkbuddyWorkspaceWorkerCycle(options) {
305
301
  if (sweep.recovered > 0 || sweep.errors.length > 0) {
306
302
  emitEvent('WORKBUDDY_WORKER_RECOVERY_SWEEP', JSON.stringify({ recovered: sweep.recovered, failed: sweep.errors.length }));
307
303
  }
308
- const candidate = await pickDiagnosticianCandidate(handle.stateManager, options.diagnosticianCandidateLimit ?? DEFAULT_DIAG_CANDIDATE_LIMIT);
304
+ const candidate = await pickNextDiagnosticianCandidate(handle.stateManager, options.diagnosticianCandidateLimit ?? DEFAULT_DIAG_CANDIDATE_LIMIT);
309
305
  if (candidate !== null) {
310
306
  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],
318
- // 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
- };
307
+ let releaseBridge;
308
+ try {
309
+ const bridge = await createPainSignalBridge({
310
+ workspaceDir,
311
+ stateDir,
312
+ ledgerAdapter: new PrincipleTreeLedgerAdapter({ stateDir }),
313
+ owner: WORKER_OWNER,
314
+ effectiveConfig: config.effective,
315
+ getEnvVar: (name) => process.env[name],
316
+ // PRI-1233 / SPEC §9.2: this worker is where Stage A actually runs
317
+ // for governance-admitted WorkBuddy pains — the neutral host reader
318
+ // must ride along (flag-off = zero filesystem access inside it).
319
+ intentDocReader: createHostIntentDocReader({ workspaceDir, effectiveConfig: config.effective }),
320
+ // PRI-1265: the worker's Stage A gets the bound session's ORIGINAL
321
+ // turns from the workspace's own consent-tiered governance store.
322
+ trajectoryTurnReader: createGovernanceTrajectoryTurnReader({ workspaceDir, sourceMaterialAuthorization: createConsentLedgerSourceMaterialAuthorization(workspaceDir) }),
323
+ // PRI-1283 R2: latest-consent gate consulted per assembly / model call.
324
+ sourceMaterialAuthorization: createConsentLedgerSourceMaterialAuthorization(workspaceDir),
325
+ // SPEC §9.6: lazy probe — a revoked flag stops persisted
326
+ // automatic_hook tasks at the bridge's execution boundary.
327
+ isAutoPainSubmissionAuthorized: () => isAutomaticPainSubmissionAuthorized(workspaceDir),
328
+ }, (release) => { releaseBridge = release; });
329
+ const executed = await bridge.executePendingDiagnosis({ taskId: candidate.taskId });
330
+ diagnostician = {
331
+ taskId: candidate.taskId,
332
+ status: executed.status,
333
+ ...(executed.message !== undefined ? { message: executed.message.slice(0, 200) } : {}),
334
+ ...(executed.errorCategory !== undefined ? { errorCategory: executed.errorCategory } : {}),
335
+ };
336
+ }
337
+ finally {
338
+ await releaseBridge?.();
339
+ }
338
340
  }
339
341
  else {
340
342
  const waiting = await handle.stateManager.listTasks({ taskKind: 'diagnostician', status: 'retry_wait', orderBy: 'updated_at_asc', limit: 1 });
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@principles/workbuddy-adapter",
3
- "version": "0.8.0",
3
+ "version": "0.9.0",
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
- }