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
@@ -5,17 +5,19 @@
5
5
  * pd diagnose status --task-id <taskId> --workspace <path>
6
6
  * pd diagnose run --task-id <taskId> --workspace <path>
7
7
  */
8
- import { RuntimeStateManager, SqliteHistoryQuery, SqliteContextAssembler, SqliteDiagnosticianCommitter, SqliteTrajectoryLocator, SqliteSourceTraceLocator, SplitDiagnosticianRunner, DiagRootCauseRunner, DiagDistillerRunner, DiagRouterRunner, DefaultDiagRootCauseValidator, DefaultDiagDistillerValidator, TestDoubleRuntimeAdapter, PDRuntimeError, isRuntimeConfigError, CandidateIntakeService, run as diagnoseRun, status as diagnoseStatus, PrincipleTreeLedgerAdapter, buildDreamerSeedFromCandidate, findExistingDreamerTask, CANDIDATE_KIND_TO_ROUTE, ROUTE_CHANNEL_MAP, MVP_ENABLED_CHANNELS, persistPainDiagnosis, createBridgeTelemetryEventEmitter, createReuseRecommendationHook, computeFeatureFlagsFromConfig, isFeatureEnabled, evaluateDreamerSeedSuppression, pendingOwnerDecision, } from '@principles/core/runtime';
9
- import { createGovernanceTrajectoryTurnReader, createConsentLedgerSourceMaterialAuthorization, createHostIntentDocReader } from '@principles/host-runtime';
8
+ import { RuntimeStateManager, TestDoubleRuntimeAdapter, PDRuntimeError, isRuntimeConfigError, CandidateIntakeService, run as diagnoseRun, status as diagnoseStatus, PrincipleTreeLedgerAdapter, buildDreamerSeedFromCandidate, findExistingDreamerTask, CANDIDATE_KIND_TO_ROUTE, ROUTE_CHANNEL_MAP, MVP_ENABLED_CHANNELS, persistPainDiagnosis, createBridgeTelemetryEventEmitter, createReuseRecommendationHook, computeFeatureFlagsFromConfig, isFeatureEnabled, evaluateDreamerSeedSuppression, pendingOwnerDecision, validateRecommendationKind,
9
+ // SPEC-PD-PIPELINE-SPINE-001 §4.3 (PRI-1292): the ONE cache-free diagnostician
10
+ // runner assembly shared with the cached-bridge factory and `pd pain retry`.
11
+ createDiagnosticianRunnerBundle, } from '@principles/core/runtime';
12
+ import { resolveWorkspacePipelineHostDeps } from '@principles/host-runtime';
10
13
  import { resolveWorkspaceDir } from '../resolve-workspace.js';
11
- import { createWorkspaceTelemetryEmitter } from '../services/workspace-telemetry.js';
12
- import { readOutputLanguageFromWorkspace } from '../config-reader.js';
13
14
  import { loadPdConfig, resolvePromptFullPipelineSeedMode } from '../services/pd-config-loader.js';
14
15
  import { SPLIT_PIPELINE_TOTAL_TIMEOUT_MS, resolveDiagnosticianCapability } from '@principles/core/runtime';
15
16
  import { resolveRuntimeAdapterFromConfig, ConfigResolutionError } from '../services/runtime-adapter-resolver.js';
16
17
  import { resolveRuntimeFromPdConfig } from '../services/resolve-runtime-from-pd-config.js';
17
18
  import { enforceFullAdmissionForWrite } from '../services/admission-write-gate.js';
18
19
  import { checkAdmissionGate } from './admission-gate.js';
20
+ import { buildIntakeOutcomeGuidance } from './intake-outcome-guidance.js';
19
21
  import { resolveSourcePainIdFromDiagnostician } from './candidate.js';
20
22
  import * as path from 'path';
21
23
  function validateStalledThreshold(val) {
@@ -285,30 +287,21 @@ export async function handleDiagnoseRun(opts) {
285
287
  let diagnosisObservedSucceeded = false;
286
288
  try {
287
289
  await stateManager.initialize();
288
- // Build context assembler from internal stores
289
- const sqliteConn = stateManager.connection;
290
- const { taskStore } = stateManager;
291
- const { runStore } = stateManager;
292
- const historyQuery = new SqliteHistoryQuery(sqliteConn);
293
- const trajectoryLocator = new SqliteTrajectoryLocator(sqliteConn);
294
- const sourceTraceLocator = new SqliteSourceTraceLocator(taskStore, trajectoryLocator);
295
- // PRI-1265: inject the authorized trajectory reader so a bound session
296
- // with stored turns gets its ORIGINAL text in the diagnosis context window
297
- // (same adapter the OpenClaw hook path uses, over the workspace's own
298
- // consent-tiered governance store).
299
- // PRI-1283 R2: one port per command invocation; every consumption
300
- // surface below (assembler + all three stage runners) shares it.
301
- const sourceMaterialAuthorization = createConsentLedgerSourceMaterialAuthorization(workspaceDir);
302
- const contextAssembler = new SqliteContextAssembler(taskStore, historyQuery, runStore, {
303
- sourceTraceLocator,
304
- trajectoryTurnReader: createGovernanceTrajectoryTurnReader({ workspaceDir, sourceMaterialAuthorization }),
305
- // PRI-1283 R2: latest-consent gate — governance-sourced evidence and
306
- // conversation material are filtered at assembly time.
307
- sourceMaterialAuthorization,
308
- });
309
- // PRI-939 Option A: workspace-scoped sink — allowlisted critical events
310
- // (persisted to critical-events.jsonl) must not emit into the bare singleton.
311
- const diagnoseTelemetry = createWorkspaceTelemetryEmitter(workspaceDir);
290
+ // SPEC-PD-PIPELINE-SPINE-001 §4.2/§4.3 (PRI-1292 Phase 2A): the runner
291
+ // chain and its collaborators are assembled below by the ONE cache-free
292
+ // bundle; the five host collaborators come from the ONE workspace deps
293
+ // resolver (the admission gate at :732 reuses the SAME authorization
294
+ // instance from those deps). The deps object is created once for this
295
+ // execution context, so runtime selection and the runner share ONE sink.
296
+ if (!configLoadResult.ok) {
297
+ const errSummary = configLoadResult.errors
298
+ .map((e) => `${e.path}: ${e.reason}`)
299
+ .join('; ');
300
+ console.warn(`[pd diagnose] .pd/config.yaml at ${configLoadResult.configPath} is malformed — falling back to default feature flags. Errors: ${errSummary}. Next action: ${configLoadResult.errors[0]?.nextAction ?? 'fix config errors and retry'}`);
301
+ }
302
+ const effectiveConfig = configLoadResult.ok ? configLoadResult.effective : configLoadResult.defaults;
303
+ const hostDeps = resolveWorkspacePipelineHostDeps({ workspaceDir, effectiveConfig });
304
+ const diagnoseTelemetry = hostDeps.telemetrySink;
312
305
  // Select runtime adapter based on --runtime flag (CLI-02)
313
306
  // PRI-431: migrated to shared resolveRuntimeAdapterFromConfig
314
307
  let runtimeAdapter;
@@ -414,64 +407,46 @@ export async function handleDiagnoseRun(opts) {
414
407
  }
415
408
  throw err;
416
409
  }
417
- // PRI-1146 P1-01: the split runners emit through the SAME workspace-scoped
418
- // sink as the bridge/persistence path — allowlisted critical events (e.g.
419
- // diag_router_trusted_context_unavailable) reach critical-events.jsonl
420
- // instead of the unsubscribed bare singleton; everything else forwards
421
- // upstream unchanged.
422
- const eventEmitter = diagnoseTelemetry;
423
- const committer = new SqliteDiagnosticianCommitter(sqliteConn);
424
- // PRI-336: Read outputLanguage from workspace config
425
- const outputLangResult = readOutputLanguageFromWorkspace(workspaceDir);
426
- const outputLanguage = outputLangResult.outputLanguage;
427
- // PRI-638: implementation selection is gone. The split pipeline is the only
428
- // Diagnostician implementation in the tree, so it always runs with its
429
- // documented 3-stage budget; `diagnostician_split_pipeline` no longer
430
- // selects a runner nor disables capability.
431
- const pipelineTimeoutMs = SPLIT_PIPELINE_TOTAL_TIMEOUT_MS;
432
- // BUG-1 (PRI-442): extract effectiveConfig so ADR-0019 LLM rate-limit
433
- // degradation (isDegradationEnabled in base-peer-runner) can read the
434
- // diagnostician_llm_degradation feature flag. Without this, the runners
435
- // receive no effectiveConfig and degradation silently never fires.
436
- // CR-1 (CodeRabbit P2, rc-9): warn when config load failed so the
437
- // fallback to defaults is observable — no silent degradation.
438
- if (!configLoadResult.ok) {
439
- const errSummary = configLoadResult.errors
440
- .map((e) => `${e.path}: ${e.reason}`)
441
- .join('; ');
442
- console.warn(`[pd diagnose] .pd/config.yaml at ${configLoadResult.configPath} is malformed — falling back to default feature flags. Errors: ${errSummary}. Next action: ${configLoadResult.errors[0]?.nextAction ?? 'fix config errors and retry'}`);
443
- }
444
- const effectiveConfig = configLoadResult.ok ? configLoadResult.effective : configLoadResult.defaults;
445
410
  // PRI-935: derive pain_diagnosis_persistence from the SAME canonical
446
411
  // authority the production factory uses (pain-signal-runtime-factory),
447
412
  // so a manual `pd diagnose run` ledger write is gated identically to the
448
413
  // automatic bridge path — no CLI-local flag.
449
414
  const diagnosisPersistenceEnabled = isFeatureEnabled(computeFeatureFlagsFromConfig(effectiveConfig), 'pain_diagnosis_persistence');
450
415
  const resolvedKind = typeof runtimeAdapter.kind === 'function' ? runtimeAdapter.kind() : runtimeKind;
451
- const perStageTimeoutMs = pipelineTimeoutMs / 3;
416
+ // PRI-638: implementation selection is gone. The split pipeline is the only
417
+ // Diagnostician implementation in the tree, so it always runs with its
418
+ // documented 3-stage budget; `diagnostician_split_pipeline` no longer
419
+ // selects a runner nor disables capability.
420
+ const perStageTimeoutMs = SPLIT_PIPELINE_TOTAL_TIMEOUT_MS / 3;
452
421
  // PRI-1146 / SPEC v0.6 §5: the router's trusted canonical principle source.
453
422
  // One adapter instance serves both the router exposure and the intake path
454
423
  // below (same ledger authority).
455
424
  const ledgerAdapter = new PrincipleTreeLedgerAdapter({ stateDir: path.join(workspaceDir, '.state') });
456
- const rootCauseRunner = new DiagRootCauseRunner(
457
- // PRI-1231 / SPEC §9.2: Stage A reads INTENT.md through the neutral
458
- // host reader (same Core semantics as every entry point). A task with
459
- // a persisted snapshot keeps using it — the runner never re-reads
460
- // INTENT.md for an already-captured task (SPEC §6.6).
461
- { stateManager, runtimeAdapter, eventEmitter, artifactStore: stateManager.piArtifactStore, validator: new DefaultDiagRootCauseValidator(), contextAssembler, intentDocReader: createHostIntentDocReader({ workspaceDir, effectiveConfig }), sourceMaterialAuthorization }, { owner: 'pd-cli-diagnose', runtimeKind: resolvedKind, outputLanguage, timeoutMs: perStageTimeoutMs, effectiveConfig });
462
- const distillerRunner = new DiagDistillerRunner({ stateManager, runtimeAdapter, eventEmitter, artifactStore: stateManager.piArtifactStore, validator: new DefaultDiagDistillerValidator(), sourceMaterialAuthorization }, { owner: 'pd-cli-diagnose', runtimeKind: resolvedKind, outputLanguage, timeoutMs: perStageTimeoutMs, effectiveConfig });
463
- const routerRunner = new DiagRouterRunner({ stateManager, runtimeAdapter, eventEmitter, artifactStore: stateManager.piArtifactStore, committer, trustedPrincipleSource: ledgerAdapter, sourceMaterialAuthorization }, { owner: 'pd-cli-diagnose', runtimeKind: resolvedKind, outputLanguage, timeoutMs: perStageTimeoutMs, effectiveConfig });
464
- const runner = new SplitDiagnosticianRunner({
465
- rootCauseRunner,
466
- distillerRunner,
467
- routerRunner,
468
- stateManager,
469
- committer,
470
- // PRI-1266: the parent run records the ACTUAL runtime — the same
471
- // resolved kind the stage runners carry.
425
+ // SPEC-PD-PIPELINE-SPINE-001 §4.2/§4.3 (PRI-1292 Phase 2A): the ~100-line
426
+ // hand-rolled Diag*Runner + SplitDiagnosticianRunner assembly is replaced
427
+ // by the ONE cache-free bundle the cached-bridge factory uses. The five
428
+ // host collaborators come from the ONE workspace deps resolver — the
429
+ // admission gate below reuses the SAME authorization instance.
430
+ // PRI-1146 P1-01: the split runners emit through the SAME workspace-scoped
431
+ // sink as the bridge/persistence path. This command owns stateManager
432
+ // (created + initialized above), so the bundle reuses its connection and
433
+ // dispose() never closes it — the outer finally keeps the original
434
+ // ownership.
435
+ const bundle = await createDiagnosticianRunnerBundle({
436
+ workspaceDir,
437
+ ledgerAdapter,
438
+ owner: 'pd-cli-diagnose',
439
+ runtimeAdapter,
472
440
  runtimeKind: resolvedKind,
473
- perStageTimeoutMs,
441
+ stageTimeoutMs: perStageTimeoutMs,
442
+ effectiveConfig,
443
+ stateManager,
444
+ intentDocReader: hostDeps.intentDocReader,
445
+ trajectoryTurnReader: hostDeps.trajectoryTurnReader,
446
+ sourceMaterialAuthorization: hostDeps.sourceMaterialAuthorization,
447
+ telemetrySink: hostDeps.telemetrySink,
474
448
  });
449
+ const { runner } = bundle;
475
450
  if (!opts.json) {
476
451
  console.log(`\nRunning diagnostician for task: ${opts.taskId}`);
477
452
  console.log(`Workspace: ${workspaceDir}\n`);
@@ -604,7 +579,7 @@ export async function handleDiagnoseRun(opts) {
604
579
  // cli-6-output-next-action: refusal result carries admissionBlock.nextAction.
605
580
  // SPEC review round-3 P1: the FULL write gate (persisted disposition /
606
581
  // re-evaluation), not the confidence/kind-only partial check.
607
- const admissionBlock = (await enforceFullAdmissionForWrite(stateManager, candidate.candidateId, { sourceMaterialAuthorization })) ?? checkAdmissionGate(candidate);
582
+ const admissionBlock = (await enforceFullAdmissionForWrite(stateManager, candidate.candidateId, { sourceMaterialAuthorization: hostDeps.sourceMaterialAuthorization, coordination: ledgerAdapter })) ?? checkAdmissionGate(candidate);
608
583
  if (admissionBlock) {
609
584
  intakeFailed = true;
610
585
  intakeResults.push({
@@ -622,13 +597,49 @@ export async function handleDiagnoseRun(opts) {
622
597
  }
623
598
  try {
624
599
  const intakeResult = await intakeService.intake(candidate.candidateId);
625
- // PRI-917 v0.3.3: a parked candidate stays PENDING — no consumed
626
- // marking, no dreamer seeding. The Owner resolves it via
627
- // `pd candidate review --decide`. Phase 7.2 B2: the intake service
628
- // itself persists the park on the candidate's admission processing
629
- // (the business truth source), so a later automatic re-intake
630
- // replays the park instead of re-rolling the evaluation; the
631
- // telemetry below stays observability-only.
600
+ // Invalid RAW kinds, their unreleased recovery parks, and pending
601
+ // Owner decisions are all non-terminal governance states. None may
602
+ // be consumed or seeded by this automatic path.
603
+ if (intakeResult.outcome === 'refused' && (intakeResult.reason === 'unknown_kind'
604
+ || intakeResult.reason === 'candidate_kind_recovery_required')) {
605
+ intakeFailed = true;
606
+ const invalidKind = intakeResult.reason === 'unknown_kind';
607
+ intakeResults.push({
608
+ candidateId: candidate.candidateId,
609
+ status: 'refused',
610
+ reason: invalidKind ? 'candidate_kind_invalid' : 'candidate_kind_recovery_required',
611
+ error: `${invalidKind ? 'candidate_kind_invalid' : 'candidate_kind_recovery_required'}: ${intakeResult.message}`,
612
+ nextAction: `After restoring the intended RAW kind, obtain explicit Owner authorization: pd candidate resume-post-processing --candidate-id ${candidate.candidateId} --workspace "${workspaceDir}" --reason "<why this repair is safe>" --confirm.`,
613
+ });
614
+ continue;
615
+ }
616
+ if (intakeResult.outcome === 'refused' && intakeResult.reason === 'admission_document_unreadable') {
617
+ intakeFailed = true;
618
+ intakeResults.push({
619
+ candidateId: candidate.candidateId,
620
+ status: 'intake_failed',
621
+ error: intakeResult.message,
622
+ nextAction: 'Inspect and repair the persisted admission_json; automatic intake failed closed and did not consume this candidate.',
623
+ });
624
+ continue;
625
+ }
626
+ if (intakeResult.outcome === 'refused' && intakeResult.reason === 'owner_decision_pending') {
627
+ const admission = await stateManager.getAdmissionDocument(candidate.candidateId);
628
+ const pending = pendingOwnerDecision(admission.ok ? admission.document ?? null : null);
629
+ const decision = pending?.decision ?? (intakeResult.message.includes('--decide reuse') ? 'reuse' : 'create');
630
+ const principleArg = decision === 'reuse' && pending?.selectedPrincipleId
631
+ ? ` --principle-id ${pending.selectedPrincipleId}`
632
+ : '';
633
+ intakeResults.push({
634
+ candidateId: candidate.candidateId,
635
+ status: 'review_required',
636
+ reason: 'owner_decision_pending',
637
+ nextAction: `Resume the SAME persisted Owner verdict: pd candidate review --candidate-id ${candidate.candidateId} --workspace "${workspaceDir}" --decide ${decision}${principleArg} --reason "...".`,
638
+ });
639
+ continue;
640
+ }
641
+ // A reuse-parked candidate also stays PENDING; the Owner resolves it
642
+ // through the existing review channel.
632
643
  if (intakeResult.outcome === 'refused' && intakeResult.reason === 'reuse_pending_owner') {
633
644
  const recommended = intakeResult.reuseRecommendation?.status === 'recommended' ? intakeResult.reuseRecommendation : undefined;
634
645
  // PRI-939 review fix (CodeRabbit): the park observation reaches the
@@ -653,11 +664,20 @@ export async function handleDiagnoseRun(opts) {
653
664
  });
654
665
  continue;
655
666
  }
656
- // Phase 1 / PR1: candidate status handling is deliberately UNCHANGED
657
- // (SPEC v2.1 Step 2 "保持现有 candidate persistence / routing / defer
658
- // 行为"). Only the Principle Ledger write is gated, so a refused
659
- // candidate is still consumed and remains eligible for the kind-aware
660
- // dreamer seed loop below.
667
+ if (intakeResult.outcome === 'refused' && intakeResult.reason === 'candidate_changed_during_intake') {
668
+ intakeFailed = true;
669
+ intakeResults.push({
670
+ candidateId: candidate.candidateId,
671
+ status: 'refused',
672
+ reason: intakeResult.reason,
673
+ error: intakeResult.message,
674
+ nextAction: 'Inspect the current candidate state; no task was created. Retry candidate processing against the current row.',
675
+ });
676
+ continue;
677
+ }
678
+ // Non-principle routing/defer refusals retain the historical
679
+ // consumed disposition. Invalid-kind, unreadable-admission and
680
+ // pending-Owner cases have already continued above without mutation.
661
681
  if (candidate.status !== 'consumed') {
662
682
  await stateManager.updateCandidateStatus(candidate.candidateId, { status: 'consumed' });
663
683
  }
@@ -734,140 +754,186 @@ export async function handleDiagnoseRun(opts) {
734
754
  // nextAction/exit-code signaling below (partial failure still exits non-zero).
735
755
  if (opts.intake !== false) {
736
756
  for (const candidate of candidates) {
737
- const kind = candidate.recommendationKind;
738
- if (kind === 'defer' || kind === 'implementation')
739
- continue;
740
- const intakeResult = intakeResults.find((r) => r.candidateId === candidate.candidateId);
757
+ const intakeResult = intakeResults.find((record) => record.candidateId === candidate.candidateId);
741
758
  if (!intakeResult || intakeResult.status !== 'consumed')
742
759
  continue;
743
- // Phase 7.2 B2.5 — Dreamer seed suppression. A candidate already
744
- // resolved onto an existing principle (reuse decision / INV-R07 replay
745
- // / B1 exact-duplicate guard — identity basis 'principle_reuse') or
746
- // still reuse-parked has no information gain from an independent
747
- // exploration chain. The verdict comes from PERSISTENT facts (ledger
748
- // identity + admission processing), so it holds for restarts, rescans
749
- // and candidates consumed in earlier runs — not just this run's
750
- // in-memory intake result. Fail-open on an unexpected read failure
751
- // (same posture as the bridge): the suppression is a chain-budget
752
- // guard, not a learning gate — an unreadable fact must not block the
753
- // seed, only make the check not run.
754
- let suppression = { suppress: false };
760
+ // Re-read and seed under the same candidate coordination lock used by
761
+ // Owner reuse and pd candidate internalize. The critical section is
762
+ // bounded SQLite/ledger I/O only; no LLM or network calls occur here.
755
763
  try {
756
- const admissionDoc = await stateManager.getAdmissionDocument(candidate.candidateId);
757
- const pending = pendingOwnerDecision(admissionDoc.ok ? admissionDoc.document ?? null : null);
758
- suppression = evaluateDreamerSeedSuppression({
759
- identity: ledgerAdapter.resolveCandidatePrincipleIdentity(candidate.candidateId, kind ?? 'principle'),
760
- processing: admissionDoc.ok ? admissionDoc.document?.processing : undefined,
761
- ...(pending !== null ? { pendingOwnerDecision: { decision: pending.decision } } : {}),
762
- });
763
- }
764
- catch {
765
- suppression = { suppress: false };
766
- }
767
- if (suppression.suppress) {
768
- intakeResults.push({
769
- candidateId: candidate.candidateId,
770
- status: 'dreamer_seed_suppressed',
771
- reusedPrincipleId: suppression.reason === 'reuse_resolved_to_existing_principle' ? suppression.principleId : intakeResult.reusedPrincipleId,
772
- nextAction: suppression.reason === 'reuse_resolved_to_existing_principle'
773
- ? 'No independent Dreamer chain: this candidate is durably resolved onto the existing principle (reuseEvidence).'
774
- : `pd candidate review --candidate-id ${candidate.candidateId} --decide reuse|create --reason "..."`,
764
+ await ledgerAdapter.withCandidateCoordination(candidate.candidateId, async () => {
765
+ const currentCandidate = await stateManager.getCandidate(candidate.candidateId);
766
+ if (currentCandidate === null) {
767
+ intakeFailed = true;
768
+ intakeResults.push({
769
+ candidateId: candidate.candidateId,
770
+ status: 'intake_failed',
771
+ error: 'candidate_disappeared_before_dreamer_seed',
772
+ nextAction: 'Re-run diagnosis after verifying the candidate row and its task lineage.',
773
+ });
774
+ return;
775
+ }
776
+ const rawKind = validateRecommendationKind(currentCandidate.rawRecommendationKind);
777
+ if (rawKind === null) {
778
+ const raw = typeof currentCandidate.rawRecommendationKind === 'string' ? currentCandidate.rawRecommendationKind : 'missing';
779
+ const shown = JSON.stringify(raw).slice(1, -1).slice(0, 40);
780
+ const nextAction = `Restore the intended RAW kind, then obtain explicit Owner authorization: pd candidate resume-post-processing --candidate-id ${candidate.candidateId} --workspace "${workspaceDir}" --reason "<why this repair is safe>" --confirm.`;
781
+ const admission = await stateManager.getAdmissionDocument(candidate.candidateId);
782
+ if (admission.ok) {
783
+ await stateManager.updateAdmissionProcessing(candidate.candidateId, {
784
+ state: 'awaiting_owner',
785
+ attempts: admission.document?.processing?.attempts ?? 0,
786
+ lastFailure: { reason: 'candidate_kind_invalid', nextAction, at: new Date().toISOString() },
787
+ blockedReason: `candidate_kind_invalid:${shown}`,
788
+ });
789
+ }
790
+ intakeFailed = true;
791
+ intakeResults.push({
792
+ candidateId: candidate.candidateId,
793
+ status: 'refused',
794
+ reason: 'candidate_kind_invalid',
795
+ error: `candidate_kind_invalid: ${raw === 'missing' ? 'missing' : raw}`,
796
+ nextAction,
797
+ });
798
+ return;
799
+ }
800
+ if (rawKind === 'defer' || rawKind === 'implementation')
801
+ return;
802
+ const admissionDoc = await stateManager.getAdmissionDocument(candidate.candidateId);
803
+ if (!admissionDoc.ok) {
804
+ intakeFailed = true;
805
+ intakeResults.push({
806
+ candidateId: candidate.candidateId,
807
+ status: 'intake_failed',
808
+ error: 'admission_document_unreadable_before_dreamer_seed',
809
+ nextAction: 'Inspect and repair admission_json. No Dreamer task was created.',
810
+ });
811
+ return;
812
+ }
813
+ const processing = admissionDoc.document?.processing;
814
+ if (processing?.state === 'awaiting_owner'
815
+ && typeof processing.blockedReason === 'string'
816
+ && processing.blockedReason.startsWith('candidate_kind_invalid')) {
817
+ intakeFailed = true;
818
+ intakeResults.push({
819
+ candidateId: candidate.candidateId,
820
+ status: 'refused',
821
+ reason: 'candidate_kind_recovery_required',
822
+ error: 'candidate_kind_recovery_required: persisted RAW kind is repaired but Owner authorization is still required',
823
+ nextAction: `After repairing the persisted RAW kind, run pd candidate resume-post-processing --candidate-id ${candidate.candidateId} --workspace "${workspaceDir}" --reason "<why this repair is safe>" --confirm.`,
824
+ });
825
+ return;
826
+ }
827
+ const pending = pendingOwnerDecision(admissionDoc.document ?? null);
828
+ if (pending !== null) {
829
+ const principleArg = pending.decision === 'reuse' && pending.selectedPrincipleId
830
+ ? ` --principle-id ${pending.selectedPrincipleId}`
831
+ : '';
832
+ intakeResults.push({
833
+ candidateId: candidate.candidateId,
834
+ status: 'review_required',
835
+ reason: 'owner_decision_pending',
836
+ nextAction: `Resume the SAME persisted Owner verdict with pd candidate review --candidate-id ${candidate.candidateId} --workspace "${workspaceDir}" --decide ${pending.decision}${principleArg} --reason "...".`,
837
+ });
838
+ return;
839
+ }
840
+ let suppression;
841
+ try {
842
+ suppression = evaluateDreamerSeedSuppression({
843
+ identity: ledgerAdapter.resolveCandidatePrincipleIdentity(candidate.candidateId, currentCandidate.rawRecommendationKind),
844
+ processing: admissionDoc.document?.processing,
845
+ });
846
+ }
847
+ catch {
848
+ intakeFailed = true;
849
+ intakeResults.push({
850
+ candidateId: candidate.candidateId,
851
+ status: 'intake_failed',
852
+ error: 'candidate_seed_authority_read_failed',
853
+ nextAction: 'Inspect the Principle Ledger identity and admission document; fail-closed prevented Dreamer creation.',
854
+ });
855
+ return;
856
+ }
857
+ if (suppression.suppress) {
858
+ intakeResults.push({
859
+ candidateId: candidate.candidateId,
860
+ status: 'dreamer_seed_suppressed',
861
+ reusedPrincipleId: suppression.reason === 'reuse_resolved_to_existing_principle'
862
+ ? suppression.principleId
863
+ : intakeResult.reusedPrincipleId,
864
+ nextAction: suppression.reason === 'reuse_resolved_to_existing_principle'
865
+ ? 'No independent Dreamer chain: this candidate is durably resolved onto the existing principle (reuseEvidence).'
866
+ : `pd candidate review --candidate-id ${candidate.candidateId} --decide reuse|create --reason "...".`,
867
+ });
868
+ return;
869
+ }
870
+ try {
871
+ const route = CANDIDATE_KIND_TO_ROUTE[rawKind];
872
+ if (!route)
873
+ return;
874
+ const channel = ROUTE_CHANNEL_MAP[route];
875
+ const ready = !!channel && MVP_ENABLED_CHANNELS.has(channel);
876
+ const sourcePainId = await resolveSourcePainIdFromDiagnostician(stateManager, currentCandidate);
877
+ const seed = buildDreamerSeedFromCandidate(currentCandidate, {
878
+ route,
879
+ ready,
880
+ sourcePainId: sourcePainId ?? undefined,
881
+ pipelineMode: seedPipelineMode,
882
+ });
883
+ // eslint-disable-next-line no-restricted-syntax -- 'in' required for discriminated union narrowing (BridgeTaskSeed | BridgeDecision)
884
+ if ('decision' in seed)
885
+ return;
886
+ const existingTask = await findExistingDreamerTask((id) => stateManager.getTask(id), candidate.candidateId);
887
+ if (!existingTask) {
888
+ await stateManager.createTask({
889
+ taskId: seed.taskId,
890
+ taskKind: seed.taskKind,
891
+ inputRef: '',
892
+ status: seed.status,
893
+ attemptCount: seed.attemptCount,
894
+ maxAttempts: seed.maxAttempts,
895
+ diagnosticJson: seed.diagnosticJson,
896
+ });
897
+ intakeResults.push({
898
+ candidateId: candidate.candidateId,
899
+ status: 'dreamer_seeded',
900
+ nextAction: `pd task show ${seed.taskId} | pd dreamer run --task-id ${seed.taskId}`,
901
+ });
902
+ }
903
+ }
904
+ catch (seedErr) {
905
+ intakeResults.push({
906
+ candidateId: candidate.candidateId,
907
+ status: 'dreamer_seed_failed',
908
+ error: seedErr instanceof Error ? seedErr.message : String(seedErr),
909
+ nextAction: `pd candidate internalize --candidate-id ${candidate.candidateId}`,
910
+ });
911
+ }
775
912
  });
776
- continue;
777
913
  }
778
- try {
779
- const route = CANDIDATE_KIND_TO_ROUTE[kind ?? ''];
780
- if (!route)
781
- continue;
782
- const channel = ROUTE_CHANNEL_MAP[route];
783
- const ready = !!channel && MVP_ENABLED_CHANNELS.has(channel);
784
- // BUG-2 (PRI-442): resolve sourcePainId from the diagnostician task
785
- // chain (rc-6 lineage consistency). The candidate itself doesn't carry
786
- // sourcePainId; it must be resolved from the diagnostician task's
787
- // diagnosticJson. ERR-004: never invent lineage.
788
- const sourcePainId = await resolveSourcePainIdFromDiagnostician(stateManager, candidate);
789
- const seed = buildDreamerSeedFromCandidate(candidate, { route, ready, sourcePainId: sourcePainId ?? undefined, pipelineMode: seedPipelineMode });
790
- // eslint-disable-next-line no-restricted-syntax -- 'in' required for discriminated union narrowing (BridgeTaskSeed | BridgeDecision)
791
- if ('decision' in seed)
792
- continue; // not_internalizable or invalid — skip
793
- // PRI-720 C6: candidate-level dedup (demotion may change the
794
- // derived channel suffix vs a pre-existing chain).
795
- const existingTask = await findExistingDreamerTask((id) => stateManager.getTask(id), candidate.candidateId);
796
- if (!existingTask) {
797
- await stateManager.createTask({
798
- taskId: seed.taskId,
799
- taskKind: seed.taskKind,
800
- inputRef: '',
801
- status: seed.status,
802
- attemptCount: seed.attemptCount,
803
- maxAttempts: seed.maxAttempts,
804
- diagnosticJson: seed.diagnosticJson,
805
- });
806
- intakeResults.push({
807
- candidateId: candidate.candidateId,
808
- status: 'dreamer_seeded',
809
- nextAction: `pd task show ${seed.taskId} | pd dreamer run --task-id ${seed.taskId}`,
810
- });
811
- }
812
- }
813
- catch (seedErr) {
914
+ catch (coordinationErr) {
915
+ intakeFailed = true;
814
916
  intakeResults.push({
815
917
  candidateId: candidate.candidateId,
816
- status: 'dreamer_seed_failed',
817
- error: seedErr instanceof Error ? seedErr.message : String(seedErr),
818
- nextAction: `pd candidate internalize --candidate-id ${candidate.candidateId}`,
918
+ status: 'intake_failed',
919
+ error: coordinationErr instanceof Error ? coordinationErr.message : String(coordinationErr),
920
+ nextAction: `Resolve the candidate coordination error, then retry internalization with pd candidate internalize --candidate-id ${candidate.candidateId} --workspace "${workspaceDir}"; the diagnosis itself already succeeded and will not be rerun.`,
819
921
  });
820
922
  }
821
923
  }
822
924
  }
925
+ // classification of every candidate into an outcome class drives both
926
+ // output paths — a mixed run (seed-refused + parked + admission-refused
927
+ // + internalizable) reports every class it contains with its own next
928
+ // step, and `--no-intake` computes the raw-kind eligibility from the
929
+ // candidate rows themselves (no seed result exists on that path).
930
+ const guidance = buildIntakeOutcomeGuidance({
931
+ candidates,
932
+ intakeResults,
933
+ intakeEnabled: opts.intake !== false,
934
+ workspaceDir,
935
+ });
823
936
  if (opts.json) {
824
- const candidateIds = candidates.map((c) => c.candidateId);
825
- // CodeRabbit review fix: reflect dreamer seed status in nextAction so
826
- // the owner knows whether internalization has already started or still
827
- // needs manual candidate internalize. Previously the message always
828
- // said "NOT started automatically" even when dreamer tasks were seeded.
829
- const dreamerSeededCount = intakeResults.filter((r) => r.status === 'dreamer_seeded').length;
830
- const dreamerSeedFailedCount = intakeResults.filter((r) => r.status === 'dreamer_seed_failed').length;
831
- // PRI-917 v0.3.3 review fix (P2-4): parked candidates must NOT be told to
832
- // internalize — the Owner decides via `pd candidate review` first.
833
- const reviewRequiredIds = intakeResults
834
- .filter((r) => r.status === 'review_required')
835
- .map((r) => r.candidateId);
836
- // Phase 7.2 B2.5 (CodeRabbit): seed-SUPPRESSED candidates are resolved
837
- // onto an existing principle (or still parked) — an independent chain is
838
- // suppressed by design, so they must not be offered `pd candidate
839
- // internalize` either.
840
- const seedSuppressedIds = intakeResults
841
- .filter((r) => r.status === 'dreamer_seed_suppressed')
842
- .map((r) => r.candidateId);
843
- // PRI-1263: admission-refused candidates must NOT be offered
844
- // `pd candidate internalize` — the write gate refuses them again. Point
845
- // the operator at the ACTUAL next action (evidence supplementation or
846
- // manual review) recorded on the intake result instead.
847
- const admissionRefusedResults = intakeResults.filter((r) => r.admissionRefused === true);
848
- const admissionRefusedIds = admissionRefusedResults.map((r) => r.candidateId);
849
- const reviewRequiredNote = reviewRequiredIds.length > 0
850
- ? ` ${reviewRequiredIds.length} candidate(s) parked for reuse review (suspected duplicates) — decide before internalizing: pd candidate review --candidate-id <id> --decide reuse|create`
851
- : '';
852
- const suppressedNote = seedSuppressedIds.length > 0
853
- ? ` ${seedSuppressedIds.length} candidate(s) had their Dreamer seed SUPPRESSED (durably resolved onto an existing principle or awaiting the Owner — no independent chain by design).`
854
- : '';
855
- const admissionRefusedNote = admissionRefusedResults.length > 0
856
- ? ` ${admissionRefusedResults.length} candidate(s) were REFUSED by the admission gate (e.g. confidence below threshold or insufficient evidence) — do NOT internalize them; supplement evidence or use manual review: ${[...new Set(admissionRefusedResults.map((r) => r.nextAction ?? 'provide additional evidence or request manual review'))].join(' / ')}`
857
- : '';
858
- const internalizableCandidateIds = candidateIds
859
- .filter((id) => !reviewRequiredIds.includes(id) && !seedSuppressedIds.includes(id) && !admissionRefusedIds.includes(id));
860
- const internalizeNextAction = dreamerSeededCount > 0
861
- ? `Dreamer tasks seeded automatically for ${dreamerSeededCount} candidate(s). To continue, run the dreamer tasks shown in intake.candidates[].${dreamerSeedFailedCount > 0 ? ` (${dreamerSeedFailedCount} candidate(s) failed seeding — see intake.candidates[] for retry guidance.)` : ''}${reviewRequiredNote}${suppressedNote}${admissionRefusedNote}`
862
- : internalizableCandidateIds.length > 0
863
- ? `Candidates generated but internalization has NOT started automatically. To begin internalization, run:\n ${internalizableCandidateIds.map((id) => `pd candidate internalize --candidate-id ${id} --workspace "${workspaceDir}"`).join('\n ')}${reviewRequiredNote}${suppressedNote}${admissionRefusedNote}`
864
- : reviewRequiredIds.length > 0
865
- ? `All candidates are parked for reuse review (suspected duplicates). To decide each, run:\n ${reviewRequiredIds.map((id) => `pd candidate review --candidate-id ${id} --decide reuse|create`).join('\n ')}`
866
- : admissionRefusedIds.length > 0 && admissionRefusedIds.length === candidateIds.length
867
- ? `All candidates were refused by the admission gate — internalization is correctly blocked. Per candidate: ${[...new Set(admissionRefusedResults.map((r) => r.nextAction ?? 'provide additional evidence or request manual review'))].join(' / ')}`
868
- : seedSuppressedIds.length > 0
869
- ? `All candidates are durably resolved (Dreamer seeds suppressed by design — no independent chain).${suppressedNote}`
870
- : 'No candidates were generated from this diagnosis.';
871
937
  const jsonOutput = {
872
938
  ...result,
873
939
  // PRI-1222: explicit diagnosis-chain outcome, decoupled from candidate
@@ -881,8 +947,11 @@ export async function handleDiagnoseRun(opts) {
881
947
  intake: {
882
948
  enabled: opts.intake !== false,
883
949
  candidates: intakeResults,
950
+ // every candidate in exactly one outcome class (machine-readable):
951
+ // no caller has to re-derive mixed outcomes from record statuses.
952
+ outcomeClasses: guidance.byClass,
884
953
  },
885
- nextAction: internalizeNextAction,
954
+ nextAction: guidance.nextAction,
886
955
  };
887
956
  console.log(JSON.stringify(jsonOutput, null, 2));
888
957
  // PRI-1222 exit-code contract (unchanged for backward compatibility):
@@ -966,6 +1035,14 @@ export async function handleDiagnoseRun(opts) {
966
1035
  console.log(` ${ir.candidateId}: REUSE REVIEW REQUIRED${ir.reusedPrincipleId ? ` — suspected duplicate of existing Principle ${ir.reusedPrincipleId}` : ' — suspected duplicate'}`);
967
1036
  console.log(` Next action: ${ir.nextAction}`);
968
1037
  }
1038
+ else if (ir.status === 'refused') {
1039
+ // SPEC-PD-PIPELINE-SPINE-001 D4 (v0.9): the seed refusal must be
1040
+ // visible in TTY output with its structured reason — never folded
1041
+ // into the consumed line above.
1042
+ console.log(` ${ir.candidateId}: DREAMER SEED REFUSED — ${ir.reason}`);
1043
+ if (ir.nextAction)
1044
+ console.log(` Next action: ${ir.nextAction}`);
1045
+ }
969
1046
  else if (ir.status === 'dreamer_seed_suppressed') {
970
1047
  // Phase 7.2 B2.5 (CodeRabbit): the suppression must be visible in
971
1048
  // TTY output too — with the reason and the resolved target.
@@ -974,31 +1051,22 @@ export async function handleDiagnoseRun(opts) {
974
1051
  }
975
1052
  }
976
1053
  }
977
- if (opts.intake === false && candidates.length > 0) {
978
- console.log(`\n Note: --no-intake was set. Candidates remain at 'pending'.`);
979
- console.log(` To intake manually:`);
980
- for (const c of candidates) {
981
- console.log(` pd candidate intake --candidate-id ${c.candidateId} --workspace "${workspaceDir}"`);
982
- }
983
- }
1054
+ // The TTY guidance comes from the SAME classification as the JSON
1055
+ // nextAction (review round 2, P2-2): only a class with a valid manual step
1056
+ // gets a command block, and every refusal that needs no command stays
1057
+ // visible as a note. `--no-intake` no longer offers `pd candidate intake`
1058
+ // to a candidate whose kind intake would refuse.
984
1059
  if (candidates.length > 0) {
985
- // PRI-917 v0.3.3 review fix (P2-4): parked candidates get review
986
- // guidance instead of an internalize command that would bypass the
987
- // Owner decision.
988
- const parkedResults = intakeResults.filter((ir) => ir.status === 'review_required');
989
- if (parkedResults.length > 0) {
990
- console.log(`\n Reuse Review Required (suspected duplicates parked for Owner decision):`);
991
- for (const ir of parkedResults) {
992
- console.log(` pd candidate review --candidate-id ${ir.candidateId} --decide reuse|create`);
993
- }
1060
+ if (opts.intake === false) {
1061
+ console.log(`\n Note: --no-intake was set. Candidates remain at 'pending'.`);
1062
+ }
1063
+ for (const note of guidance.notes) {
1064
+ console.log(`\n Note: ${note}`);
994
1065
  }
995
- const internalizable = candidates.filter((c) => !parkedResults.some((ir) => ir.candidateId === c.candidateId));
996
- if (internalizable.length > 0) {
997
- console.log(`\n Next Action:`);
998
- console.log(` Candidates generated but internalization has NOT started automatically.`);
999
- console.log(` To begin internalization:`);
1000
- for (const c of internalizable) {
1001
- console.log(` pd candidate internalize --candidate-id ${c.candidateId} --workspace "${workspaceDir}"`);
1066
+ for (const step of guidance.manualSteps) {
1067
+ console.log(`\n ${step.title}`);
1068
+ for (const command of step.commands) {
1069
+ console.log(` ${command}`);
1002
1070
  }
1003
1071
  }
1004
1072
  }