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
@@ -6,12 +6,14 @@ import { denyAllSourceMaterialAuthorization, findUnauthorizedSourceRef, isOwnerM
6
6
  import { ADMISSION_POLICY_VERSION, fingerprintMaterial, fingerprintStatement, pendingOwnerDecision, } from './store/candidate/admission-document.js';
7
7
  import { parseRootCauseCategory } from './store/pain-diagnosis/pain-diagnosis-store.js';
8
8
  import { evaluateDreamerSeedSuppression } from './candidate-seed-suppression.js';
9
- import { buildDreamerSeedFromCandidate, findExistingDreamerTask, ROUTE_CHANNEL_MAP, CANDIDATE_KIND_TO_ROUTE } from './internalization/intake-to-internalization-bridge.js';
9
+ import { buildDreamerSeedFromCandidate, findExistingDreamerTask, ROUTE_CHANNEL_MAP, CANDIDATE_KIND_TO_ROUTE, MVP_ENABLED_CHANNELS } from './internalization/intake-to-internalization-bridge.js';
10
10
  import { isRetryWaitBackoffElapsed } from './internalization/internalization-task-guards.js';
11
11
  import { shapeBridgeResult } from './bridge-result-shaper.js';
12
12
  import { isPrincipleLedgerEligibleKind } from './store/candidate/recommendation-kind-resolver.js';
13
+ import { validateRecommendationKind } from './store/candidate/recommendation-kind-resolver.js';
13
14
  import { parsePainIngressV1Payload, checkIngressTopLevelConsistency, deriveProvenanceFromIngressFacts, isRecord, } from './pain-ingress-payload.js';
14
15
  import { sanitizeStringUnbounded } from './evidence-sanitizer.js';
16
+ import { deviationAnchorToPainAnchor } from './context-payload.js';
15
17
  /** PRI-359: Increased from 4 to 8 to accommodate failed tool_calls evidence */
16
18
  export const MAX_EVIDENCE_ENTRIES = 8;
17
19
  export const MAX_EVIDENCE_NOTE_CHARS = 200;
@@ -38,6 +40,24 @@ export function boundCorrectionEvidenceText(correctionEvidence, workspaceDir) {
38
40
  .slice(0, MAX_CORRECTION_EVIDENCE_TEXT_CHARS),
39
41
  };
40
42
  }
43
+ /**
44
+ * The refusal for one candidate. The persisted raw kind is untrusted data:
45
+ * only a bounded copy of it reaches the blocker, never free-form content.
46
+ */
47
+ function seedRefusalFor(candidate, workspaceDir) {
48
+ const raw = typeof candidate.rawRecommendationKind === 'string' ? candidate.rawRecommendationKind : '';
49
+ const shown = raw.trim().length === 0 ? 'missing' : raw.slice(0, 40);
50
+ const workspaceArg = workspaceDir === undefined ? '<workspace>' : `"${workspaceDir}"`;
51
+ return {
52
+ reason: 'candidate_kind_invalid',
53
+ blockedReason: `candidate_kind_invalid:${shown}`,
54
+ nextAction: `The persisted recommendation_kind of candidate ${candidate.candidateId} is invalid (${shown}); no Dreamer task was created. `
55
+ + 'Restore the intended RAW kind from the source recommendation; do not change it merely to bypass admission. '
56
+ + 'After verifying a seedable kind (principle | rule | prompt), a registered Owner must explicitly authorize recovery with '
57
+ + `pd candidate resume-post-processing --candidate-id ${candidate.candidateId} --workspace ${workspaceArg} --reason "<why this repair is safe>" --confirm. `
58
+ + 'This appends an audit record and returns the candidate to the existing worker backlog; it does not create a Dreamer task. A genuine reuse_pending_owner park is never resumed by this command.',
59
+ };
60
+ }
41
61
  export function createDiagnosticianTaskId(painId) {
42
62
  return `diagnosis_${painId}`;
43
63
  }
@@ -211,7 +231,17 @@ function buildDiagnosticJson(data, workspaceDir) {
211
231
  provenanceReason: provenanceReason(provenance),
212
232
  ...(data.hostKind ? { hostKind: data.hostKind } : {}),
213
233
  ...(data.deviationAnchor ? { deviationAnchor: data.deviationAnchor } : {}),
214
- ...(data.anchor ? { anchor: data.anchor } : {}),
234
+ // D2 single-track: the structured anchor wins; when it is absent but a
235
+ // verified deviation pair is present (historical/non-MCP entries), derive
236
+ // the canonical anchor from that pair instead of losing it downstream.
237
+ ...(data.anchor
238
+ ? { anchor: data.anchor }
239
+ : (data.deviationAnchor !== undefined
240
+ ? (() => {
241
+ const derived = deviationAnchorToPainAnchor(data.deviationAnchor);
242
+ return derived !== undefined ? { anchor: derived } : {};
243
+ })()
244
+ : {})),
215
245
  evidence: data.evidence ?? [],
216
246
  workspaceDir: workspaceDir ?? null,
217
247
  // PRI-844: the Owner's verbatim correction rides as its own top-level
@@ -636,6 +666,15 @@ export class PainSignalBridge {
636
666
  workspaceDir;
637
667
  eventEmitter;
638
668
  ownedResources;
669
+ /** Bridge-level operations in flight (see trackOperation / disposeWhenIdle). */
670
+ activeOperations = 0;
671
+ // Each scoped factory caller owns its own idempotent release closure.
672
+ outstandingFactoryBorrows = 0;
673
+ disposeRequested = false;
674
+ disposed = false;
675
+ closePromise;
676
+ retirementPromise;
677
+ notifyIdle;
639
678
  capabilityDisabled;
640
679
  isAutoPainSubmissionAuthorized;
641
680
  constructor(opts) {
@@ -648,7 +687,23 @@ export class PainSignalBridge {
648
687
  this.diagnosisPersistenceEnabled = opts.diagnosisPersistenceEnabled ?? false;
649
688
  this.fullPipelinePromptSeeds = opts.fullPipelinePromptSeeds ?? false;
650
689
  this.workspaceDir = opts.workspaceDir;
651
- this.eventEmitter = opts.eventEmitter;
690
+ // Telemetry is an observer (SPEC-PD-PIPELINE-SPINE-001 review round 2,
691
+ // P1-2): a throwing sink must never abort post-processing. Uncontained,
692
+ // the throw left a seeded task unconsumed and the rest of the batch
693
+ // unprocessed. Normal emissions are unchanged; only the throw is
694
+ // contained, at the single point where the emitter enters the bridge.
695
+ this.eventEmitter = opts.eventEmitter === undefined
696
+ ? undefined
697
+ : {
698
+ emitTelemetry: (event) => {
699
+ try {
700
+ opts.eventEmitter?.emitTelemetry(event);
701
+ }
702
+ catch {
703
+ // the sink is broken; the core state writes stay authoritative
704
+ }
705
+ },
706
+ };
652
707
  this.ownedResources = opts.ownedResources ?? [];
653
708
  this.capabilityDisabled = opts.capabilityDisabled;
654
709
  this.isAutoPainSubmissionAuthorized = opts.isAutoPainSubmissionAuthorized;
@@ -702,7 +757,7 @@ export class PainSignalBridge {
702
757
  * awaiting_owner / exhausted — are skipped and reported, not rescanned);
703
758
  * - read/CLI paths never call this; only the worker continuation does.
704
759
  */
705
- async resumeSucceededDiagnosisPostProcessing(input) {
760
+ async resumeSucceededDiagnosisPostProcessingInner(input) {
706
761
  const task = await this.stateManager.getTask(input.taskId);
707
762
  if (task === null)
708
763
  return { status: 'not_applicable', reason: 'task_missing' };
@@ -728,25 +783,31 @@ export class PainSignalBridge {
728
783
  const blockedAt = new Date().toISOString();
729
784
  for (const candidate of candidates) {
730
785
  try {
731
- await this.stateManager.appendAdmissionEvaluation(candidate.candidateId, {
732
- evaluationId: `ae_blocked_${fingerprintMaterial([candidate.candidateId, reentry.errorCode]).slice(0, 16)}`,
733
- decision: 'needs_evidence',
734
- reason: `diagnostic_material_unusable:${reentry.errorCode}`,
735
- nextAction: 'repair or re-run the diagnosis via the supported CLI command; the candidate resumes automatically afterwards',
736
- evaluatedAt: blockedAt,
737
- policyVersion: ADMISSION_POLICY_VERSION,
738
- provenance: 'automatic_hook',
739
- inputEvidenceCount: 0,
740
- ownerStatementPresent: false,
741
- recommendationKind: candidate.rawRecommendationKind,
742
- confidence: null,
743
- materialFingerprint: fingerprintMaterial(['unusable', reentry.errorCode]),
744
- materialSummary: { inputEvidenceCount: 0, outputEvidenceCount: 0, ownerStatementPresent: false },
745
- });
746
- await this.stateManager.updateAdmissionProcessing(candidate.candidateId, {
747
- state: 'exhausted',
748
- attempts: MAX_POST_PROCESSING_ATTEMPTS,
749
- blockedReason: `diagnostic_material_unusable:${reentry.errorCode}`,
786
+ await this.withCandidateCoordination(candidate.candidateId, async () => {
787
+ if (await this.automaticProcessingProtected(candidate.candidateId, true))
788
+ return;
789
+ const appended = await this.stateManager.appendAdmissionEvaluation(candidate.candidateId, {
790
+ evaluationId: `ae_blocked_${fingerprintMaterial([candidate.candidateId, reentry.errorCode]).slice(0, 16)}`,
791
+ decision: 'needs_evidence',
792
+ reason: `diagnostic_material_unusable:${reentry.errorCode}`,
793
+ nextAction: 'repair or re-run the diagnosis via the supported CLI command; the candidate resumes automatically afterwards',
794
+ evaluatedAt: blockedAt,
795
+ policyVersion: ADMISSION_POLICY_VERSION,
796
+ provenance: 'automatic_hook',
797
+ inputEvidenceCount: 0,
798
+ ownerStatementPresent: false,
799
+ recommendationKind: candidate.rawRecommendationKind,
800
+ confidence: null,
801
+ materialFingerprint: fingerprintMaterial(['unusable', reentry.errorCode]),
802
+ materialSummary: { inputEvidenceCount: 0, outputEvidenceCount: 0, ownerStatementPresent: false },
803
+ });
804
+ if (appended.status === 'refused')
805
+ return;
806
+ await this.stateManager.updateAdmissionProcessing(candidate.candidateId, {
807
+ state: 'exhausted',
808
+ attempts: MAX_POST_PROCESSING_ATTEMPTS,
809
+ blockedReason: `diagnostic_material_unusable:${reentry.errorCode}`,
810
+ });
750
811
  });
751
812
  }
752
813
  catch {
@@ -795,6 +856,9 @@ export class PainSignalBridge {
795
856
  }
796
857
  const processingState = admission.document?.processing?.state;
797
858
  if (processingState === 'complete' || processingState === 'awaiting_owner' || processingState === 'exhausted') {
859
+ // A raw-kind repair is not itself Owner authorization to resume. Only
860
+ // the explicit audited recovery transition may move this row from
861
+ // awaiting_owner to the existing in_progress worker backlog.
798
862
  skipped.push({ candidateId: candidate.candidateId, reason: `processing_${processingState}` });
799
863
  continue;
800
864
  }
@@ -809,24 +873,88 @@ export class PainSignalBridge {
809
873
  painId: typeof task.inputRef === 'string' && task.inputRef.length > 0 ? task.inputRef : `diagnosis-source:${input.taskId}`,
810
874
  provenance: reentry.provenance,
811
875
  inputEvidenceCount: reentry.evidenceCount,
876
+ candidateIds: eligible.map((candidate) => candidate.candidateId),
812
877
  ...(reentry.correctionEvidence !== undefined ? { correctionEvidence: reentry.correctionEvidence } : {}),
813
878
  });
814
879
  return {
815
880
  status: 'resumed',
816
881
  result,
817
- processedCandidateIds: eligible.map((c) => c.candidateId),
882
+ processedCandidateIds: result.candidateIds,
818
883
  skipped,
819
884
  remainingCount: 0,
820
885
  };
821
886
  }
822
887
  async dispose() {
823
- for (const resource of this.ownedResources) {
824
- try {
825
- await resource.close();
888
+ // Direct owners use dispose; the factory retires shared bridges via
889
+ // disposeWhenIdle. Concurrent close callers share the actual close.
890
+ this.closePromise ??= (async () => {
891
+ this.disposed = true;
892
+ for (const resource of this.ownedResources) {
893
+ try {
894
+ await resource.close();
895
+ }
896
+ catch { /* best-effort cleanup */ }
826
897
  }
827
- catch { /* best-effort cleanup */ }
898
+ await this.stateManager.close();
899
+ })();
900
+ return this.closePromise;
901
+ }
902
+ /** Acquire a distinct factory borrow; only its owner can release it. */
903
+ retainFactoryBorrow() {
904
+ if (this.disposed || this.disposeRequested)
905
+ throw new Error('Cannot borrow a retired PainSignalBridge');
906
+ this.outstandingFactoryBorrows += 1;
907
+ let released = false;
908
+ return async () => {
909
+ if (released)
910
+ return;
911
+ released = true;
912
+ this.outstandingFactoryBorrows -= 1;
913
+ await this.notifyRetirementIfIdle();
914
+ };
915
+ }
916
+ async notifyRetirementIfIdle() {
917
+ if (this.activeOperations === 0 && this.outstandingFactoryBorrows === 0 && this.disposeRequested) {
918
+ const notify = this.notifyIdle;
919
+ this.notifyIdle = undefined;
920
+ notify?.();
921
+ await this.retirementPromise?.catch(() => undefined);
828
922
  }
829
- await this.stateManager.close();
923
+ }
924
+ async trackOperation(operation) {
925
+ if (this.disposed)
926
+ throw new Error('PainSignalBridge has been disposed');
927
+ this.activeOperations += 1;
928
+ try {
929
+ return await operation();
930
+ }
931
+ finally {
932
+ this.activeOperations -= 1;
933
+ await this.notifyRetirementIfIdle();
934
+ }
935
+ }
936
+ /** Retire once; resolve only after every borrower and operation has drained. */
937
+ async disposeWhenIdle() {
938
+ if (this.retirementPromise === undefined) {
939
+ this.disposeRequested = true;
940
+ this.retirementPromise = (async () => {
941
+ if (this.activeOperations > 0 || this.outstandingFactoryBorrows > 0) {
942
+ await new Promise((resolve) => { this.notifyIdle = resolve; });
943
+ }
944
+ await this.dispose();
945
+ return true;
946
+ })();
947
+ }
948
+ return this.retirementPromise;
949
+ }
950
+ async resumeSucceededDiagnosisPostProcessing(input) {
951
+ return this.trackOperation(() => this.resumeSucceededDiagnosisPostProcessingInner(input));
952
+ }
953
+ async onPainDetected(data) {
954
+ return this.trackOperation(() => this.onPainDetectedInner(data));
955
+ }
956
+ async executePendingDiagnosis(input) {
957
+ return this.trackOperation(() => this.executePendingDiagnosisInner(input));
830
958
  }
831
959
  emitAdmissionEvent(candidateId, admission) {
832
960
  if (!this.eventEmitter)
@@ -845,9 +973,9 @@ export class PainSignalBridge {
845
973
  * PRI-369: async pain-record CLI — fire-and-forget submission.
846
974
  */
847
975
  async submitPainSignal(data) {
848
- return persistPendingPainSignal(this.stateManager, data, this.workspaceDir);
976
+ return this.trackOperation(() => persistPendingPainSignal(this.stateManager, data, this.workspaceDir));
849
977
  }
850
- async onPainDetected(data) {
978
+ async onPainDetectedInner(data) {
851
979
  const { painId } = data;
852
980
  const taskId = data.taskId ?? createDiagnosticianTaskId(painId);
853
981
  const provenance = data.provenance ?? inferProvenance(data);
@@ -986,7 +1114,7 @@ export class PainSignalBridge {
986
1114
  * 'needs_human_review' are skipped: terminal states need explicit
987
1115
  * Owner/manual action, never silent worker retries.
988
1116
  */
989
- async executePendingDiagnosis(input) {
1117
+ async executePendingDiagnosisInner(input) {
990
1118
  const { taskId } = input;
991
1119
  // PRI-638 P1-A: on a capability-disabled bridge execution is paused, never
992
1120
  // failed. The task keeps its exact durable state (including retry budget);
@@ -1092,15 +1220,53 @@ export class PainSignalBridge {
1092
1220
  });
1093
1221
  }
1094
1222
  /** Fire-and-forget processing-domain update that must never break the loop (sync-safe). */
1095
- safeUpdateAdmissionProcessing(candidateId, processing) {
1223
+ /**
1224
+ * Serialize admission writes with Owner decisions and candidate internalize.
1225
+ * Production LedgerAdapter supplies the cross-process candidate lock;
1226
+ * narrow test doubles may omit it and exercise the same state-store path.
1227
+ */
1228
+ async withCandidateCoordination(candidateId, operation) {
1229
+ if (typeof this.ledgerAdapter.withCandidateCoordination === 'function') {
1230
+ return this.ledgerAdapter.withCandidateCoordination(candidateId, operation);
1231
+ }
1232
+ return operation();
1233
+ }
1234
+ /** Check durable governance inside the same lock as any automatic write. */
1235
+ async automaticProcessingProtected(candidateId, protectAllOwnerParks = false) {
1236
+ if (typeof this.stateManager.getAdmissionDocument !== 'function') {
1237
+ // Only narrow legacy test doubles lack the production read seam.
1238
+ return typeof this.ledgerAdapter.withCandidateCoordination === 'function';
1239
+ }
1240
+ const read = await this.stateManager.getAdmissionDocument(candidateId);
1241
+ if (!read.ok)
1242
+ return true;
1243
+ const processing = read.document?.processing;
1244
+ const blocker = processing?.blockedReason ?? '';
1245
+ return pendingOwnerDecision(read.document ?? null) !== null
1246
+ || processing?.state === 'complete'
1247
+ || processing?.state === 'exhausted'
1248
+ || (processing?.state === 'awaiting_owner' && (protectAllOwnerParks || blocker === 'reuse_pending_owner'
1249
+ || blocker.startsWith('candidate_kind_invalid') || blocker.startsWith('candidate_identity_')));
1250
+ }
1251
+ async safeUpdateAdmissionProcessing(candidateId, processing) {
1096
1252
  try {
1097
- void this.stateManager.updateAdmissionProcessing(candidateId, processing).catch(() => undefined);
1253
+ await this.withCandidateCoordination(candidateId, async () => {
1254
+ if (await this.automaticProcessingProtected(candidateId))
1255
+ return;
1256
+ await this.stateManager.updateAdmissionProcessing(candidateId, processing);
1257
+ });
1098
1258
  }
1099
1259
  catch {
1100
- // partial state-manager seams (test doubles) may not implement the
1101
- // processing domain; the primary outcome path stays authoritative
1260
+ // Failed coordination or persistence never falls back to an unlocked write.
1102
1261
  }
1103
1262
  }
1263
+ async consumeCandidateIfUnblocked(candidateId) {
1264
+ await this.withCandidateCoordination(candidateId, async () => {
1265
+ if (await this.automaticProcessingProtected(candidateId))
1266
+ return;
1267
+ await this.stateManager.updateCandidateStatus(candidateId, { status: 'consumed' });
1268
+ });
1269
+ }
1104
1270
  /**
1105
1271
  * SPEC-CODEX-PAIN-CLOSURE-001 CR-05 (§9.2): bounded post-processing
1106
1272
  * failure bookkeeping in the independent processing domain. Default budget
@@ -1109,11 +1275,23 @@ export class PainSignalBridge {
1109
1275
  * diagnosis task's own attemptCount is never consumed by this.
1110
1276
  */
1111
1277
  async recordPostProcessingFailure(candidateId, rawReason) {
1278
+ try {
1279
+ await this.withCandidateCoordination(candidateId, () => this.recordPostProcessingFailureUnderLock(candidateId, rawReason));
1280
+ }
1281
+ catch {
1282
+ // A competing Owner operation or failed lock must not cause an unlocked write.
1283
+ }
1284
+ }
1285
+ /** Caller already owns the candidate coordination lock. Never re-enter it. */
1286
+ async recordPostProcessingFailureUnderLock(candidateId, rawReason) {
1112
1287
  try {
1113
1288
  const read = await this.stateManager.getAdmissionDocument(candidateId);
1114
1289
  if (!read.ok)
1115
1290
  return;
1116
1291
  const current = read.document?.processing;
1292
+ if (current?.state === 'awaiting_owner' || current?.state === 'complete' || current?.state === 'exhausted'
1293
+ || pendingOwnerDecision(read.document ?? null) !== null)
1294
+ return;
1117
1295
  const attempts = (current?.attempts ?? 0) + 1;
1118
1296
  const nowIso = new Date().toISOString();
1119
1297
  const reason = rawReason.slice(0, 300);
@@ -1146,10 +1324,21 @@ export class PainSignalBridge {
1146
1324
  * NOT call it (INF-9, PRI-857): the router only commits stage output.
1147
1325
  */
1148
1326
  async onDiagnosisComplete(opts) {
1327
+ return this.trackOperation(() => this.onDiagnosisCompleteInner(opts));
1328
+ }
1329
+ async onDiagnosisCompleteInner(opts) {
1149
1330
  const { taskId, diagnosticianOutput, painId, provenance, inputEvidenceCount = 0, correctionEvidence } = opts;
1150
1331
  const ownerStatementPresent = isOwnerStatementEvidence(correctionEvidence);
1151
1332
  const statementFingerprint = ownerStatementPresent && correctionEvidence ? fingerprintStatement(correctionEvidence.text) : undefined;
1152
- const candidates = await this.stateManager.getCandidatesByTaskId(taskId);
1333
+ const allCandidates = await this.stateManager.getCandidatesByTaskId(taskId);
1334
+ // The post-processing worker has already classified every row in the
1335
+ // batch. Re-read the task's candidates but only admit the exact eligible
1336
+ // ids; otherwise one authorized in_progress candidate could accidentally
1337
+ // pull an awaiting_owner sibling through this batch-wide entry point.
1338
+ const candidateFilter = opts.candidateIds === undefined ? null : new Set(opts.candidateIds);
1339
+ const candidates = candidateFilter === null
1340
+ ? allCandidates
1341
+ : allCandidates.filter((candidate) => candidateFilter.has(candidate.candidateId));
1153
1342
  const ledgerEntryIds = [];
1154
1343
  if (this.diagnosisPersistenceEnabled && diagnosticianOutput) {
1155
1344
  await persistPainDiagnosis({ stateManager: this.stateManager, eventEmitter: this.eventEmitter }, {
@@ -1241,7 +1430,7 @@ export class PainSignalBridge {
1241
1430
  if (typeof this.stateManager.appendAdmissionEvaluation !== 'function') {
1242
1431
  throw new Error('state_manager_admission_persistence_unavailable');
1243
1432
  }
1244
- const persisted = await this.stateManager.appendAdmissionEvaluation(candidate.candidateId, evaluation);
1433
+ const persisted = await this.withCandidateCoordination(candidate.candidateId, () => this.stateManager.appendAdmissionEvaluation(candidate.candidateId, evaluation));
1245
1434
  if (persisted.status === 'refused') {
1246
1435
  admissionPersistBlocked.add(candidate.candidateId);
1247
1436
  this.eventEmitter?.emitTelemetry({
@@ -1278,6 +1467,11 @@ export class PainSignalBridge {
1278
1467
  // decision — kept OUT of seeding/consumption/completion; the decision
1279
1468
  // lifecycle (Phase B/C re-run) owns their terminal state.
1280
1469
  const ownerDecisionPendingByCandidate = new Set();
1470
+ // SPEC-PD-PIPELINE-SPINE-001 D4 (review round 2, P1-2): candidates whose
1471
+ // RAW persisted kind is invalid or missing — refused at the seed gate
1472
+ // with a SAVED state (see seedRefusalFor); kept OUT of seeding, consumption
1473
+ // and completion.
1474
+ const seedRefusedByCandidate = new Map();
1281
1475
  // PRI-939 Option A: auto-path hook outcomes for CREATE dispositions —
1282
1476
  // `unavailable` must reach the Owner's output, not die at the gate.
1283
1477
  const reuseRecommendationByCandidate = new Map();
@@ -1291,7 +1485,7 @@ export class PainSignalBridge {
1291
1485
  this.emitAdmissionEvent(candidate.candidateId, admission.admission);
1292
1486
  // CR-03: a non-admitted disposition is a saved, explainable terminal
1293
1487
  // state for this material — the worker must not keep rescanning it.
1294
- this.safeUpdateAdmissionProcessing(candidate.candidateId, {
1488
+ await this.safeUpdateAdmissionProcessing(candidate.candidateId, {
1295
1489
  state: 'awaiting_owner',
1296
1490
  attempts: 0,
1297
1491
  blockedReason: `${admission.admission.decision}:${admission.admission.reason}`,
@@ -1338,7 +1532,8 @@ export class PainSignalBridge {
1338
1532
  // CR-05 (SPEC §9.1): the succeeded diagnosis with an unfinished
1339
1533
  // intake is an orphan the worker continuation must pick up — record
1340
1534
  // the attempt in the independent processing domain.
1341
- void this.recordPostProcessingFailure(candidate.candidateId, `intake_failed:${intakeErr instanceof Error ? intakeErr.message : String(intakeErr)}`).catch(() => undefined);
1535
+ await this.recordPostProcessingFailure(candidate.candidateId, `intake_failed:${intakeErr instanceof Error ? intakeErr.message : String(intakeErr)}`);
1536
+ admissionPersistBlocked.add(candidate.candidateId);
1342
1537
  continue;
1343
1538
  }
1344
1539
  // Phase 1 / PR1 (Principle Ledger write boundary): the intake service only
@@ -1384,7 +1579,7 @@ export class PainSignalBridge {
1384
1579
  });
1385
1580
  // CR-05: waiting for the Owner's reuse decision is a saved
1386
1581
  // awaiting-owner state, not a technical retry.
1387
- this.safeUpdateAdmissionProcessing(candidate.candidateId, {
1582
+ await this.safeUpdateAdmissionProcessing(candidate.candidateId, {
1388
1583
  state: 'awaiting_owner',
1389
1584
  attempts: 0,
1390
1585
  blockedReason: 'reuse_pending_owner',
@@ -1407,168 +1602,305 @@ export class PainSignalBridge {
1407
1602
  ownerDecisionPendingByCandidate.add(candidate.candidateId);
1408
1603
  continue;
1409
1604
  }
1410
- // Phase 7.2 B2.5 — Dreamer seed suppression. A candidate already
1411
- // resolved onto an existing principle (Owner reuse decision, INV-R07
1412
- // replay, or the B1 exact-duplicate guard — all durable via the
1413
- // ledger's reuseEvidence, i.e. identity basis 'principle_reuse') or
1414
- // still parked for the Owner (persisted admission processing) has no
1415
- // information gain from an independent exploration chain. The check
1416
- // reads PERSISTENT facts, so it holds across restarts, rescans and
1417
- // this very recovery loop (production anomaly 19aa989d: consumed AND
1418
- // parked AND seeded).
1419
- let seedSuppression = { suppress: false };
1420
- try {
1421
- const resolveIdentity = this.ledgerAdapter.resolveCandidatePrincipleIdentity;
1422
- if (typeof resolveIdentity === 'function') {
1423
- const admissionDoc = await this.stateManager.getAdmissionDocument(candidate.candidateId);
1424
- const pending = pendingOwnerDecision(admissionDoc.ok ? admissionDoc.document ?? null : null);
1425
- seedSuppression = evaluateDreamerSeedSuppression({
1426
- identity: resolveIdentity.call(this.ledgerAdapter, candidate.candidateId, candidate.recommendationKind ?? 'principle'),
1427
- processing: admissionDoc.ok ? admissionDoc.document?.processing : undefined,
1428
- ...(pending !== null ? { pendingOwnerDecision: { decision: pending.decision } } : {}),
1429
- });
1430
- }
1605
+ // An invalid-kind park remains authoritative after the raw row is
1606
+ // repaired. Intake returns this refusal before ledger replay; never
1607
+ // turn a valid-looking current kind into an implicit recovery.
1608
+ if (intakeResult.outcome === 'refused' && intakeResult.reason === 'candidate_kind_recovery_required') {
1609
+ const refusal = {
1610
+ reason: 'candidate_kind_recovery_required',
1611
+ nextAction: `After repairing the persisted RAW kind, run pd candidate resume-post-processing --candidate-id ${candidate.candidateId} --workspace "${this.workspaceDir}" --reason "<why this repair is safe>" --confirm.`,
1612
+ };
1613
+ seedRefusedByCandidate.set(candidate.candidateId, refusal);
1614
+ this.eventEmitter?.emitTelemetry({
1615
+ eventType: 'candidate_seed_refused',
1616
+ traceId: candidate.candidateId,
1617
+ timestamp: new Date().toISOString(),
1618
+ payload: { candidateId: candidate.candidateId, reason: refusal.reason, nextAction: refusal.nextAction },
1619
+ });
1620
+ continue;
1431
1621
  }
1432
- catch (identityErr) {
1433
- // Fail-open with visible telemetry: the suppression is a
1434
- // chain-budget correctness guard, not a safety gate — an unexpected
1435
- // identity/processing read failure must not block learning (Rule 4
1436
- // posture), but it must be observable (rc-9). Distinct event type
1437
- // so it never masks a real seed failure.
1622
+ if (intakeResult.outcome === 'refused' && intakeResult.reason === 'admission_document_unreadable') {
1623
+ const refusal = {
1624
+ reason: 'admission_document_unreadable',
1625
+ nextAction: 'Inspect and repair the persisted admission_json. Automatic Dreamer seeding failed closed; no candidate consumption or processing completion occurred.',
1626
+ };
1627
+ seedRefusedByCandidate.set(candidate.candidateId, refusal);
1438
1628
  this.eventEmitter?.emitTelemetry({
1439
- eventType: 'candidate_seed_suppression_check_failed',
1629
+ eventType: 'candidate_seed_refused',
1440
1630
  traceId: candidate.candidateId,
1441
1631
  timestamp: new Date().toISOString(),
1442
- payload: { error: `seed-suppression check failed: ${String(identityErr)}` },
1632
+ payload: { candidateId: candidate.candidateId, reason: refusal.reason, nextAction: refusal.nextAction },
1443
1633
  });
1634
+ continue;
1444
1635
  }
1445
- if (seedSuppression.suppress) {
1446
- seedSuppressedByCandidate.set(candidate.candidateId, seedSuppression);
1636
+ if (intakeResult.outcome === 'refused' && intakeResult.reason === 'candidate_changed_during_intake') {
1637
+ seedRefusedByCandidate.set(candidate.candidateId, {
1638
+ reason: 'candidate_seed_authority_unavailable',
1639
+ nextAction: 'Candidate changed during intake. No Dreamer task was created. Inspect the current persisted candidate and retry post-processing.',
1640
+ });
1641
+ await this.recordPostProcessingFailure(candidate.candidateId, 'candidate_changed_during_intake');
1642
+ continue;
1447
1643
  }
1448
- else {
1449
- // Hoisted so the catch can adopt the deterministic seed id when a
1450
- // concurrent writer won the insert (CodeRabbit PR #2684 #9 follow-up).
1451
- let seedTaskIdForAdoption = null;
1452
- try {
1453
- const route = CANDIDATE_KIND_TO_ROUTE[candidate.recommendationKind ?? ''];
1454
- if (route) {
1455
- // PRI-539: `ready` reflects only whether the route maps to a channel.
1456
- // Let computeBridgeDecision() itself decide MVP-disabled so the
1457
- // not_internalizable reason is accurate ("Channel ... MVP-disabled")
1458
- // instead of the misleading "not ready — missing required fields".
1459
- const channel = ROUTE_CHANNEL_MAP[route];
1460
- const ready = !!channel;
1461
- const seed = buildDreamerSeedFromCandidate(candidate, {
1462
- route,
1463
- ready,
1464
- sourcePainId: painId,
1465
- // PRI-720: explicit full-chain override when the Owner switched
1466
- // prompt_full_pipeline on. Seed-time application — in-flight
1467
- // chains keep their seeded topology.
1468
- pipelineMode: this.fullPipelinePromptSeeds ? 'full_chain' : undefined,
1644
+ // Final seed authorization, identity and task creation share the
1645
+ // candidate coordination lock used by Owner reuse and CLI
1646
+ // internalization. Only bounded SQLite/ledger work is performed here;
1647
+ // no LLM or network call is permitted inside this critical section.
1648
+ const seedUnderCandidateLock = async () => {
1649
+ const currentCandidate = await this.stateManager.getCandidate(candidate.candidateId);
1650
+ if (currentCandidate === null) {
1651
+ seedRefusedByCandidate.set(candidate.candidateId, {
1652
+ reason: 'candidate_seed_authority_unavailable',
1653
+ nextAction: 'Candidate disappeared before Dreamer seeding. Re-run diagnosis after verifying candidate lineage.',
1654
+ });
1655
+ return;
1656
+ }
1657
+ const admissionDoc = await this.stateManager.getAdmissionDocument(candidate.candidateId);
1658
+ if (!admissionDoc.ok) {
1659
+ seedRefusedByCandidate.set(candidate.candidateId, {
1660
+ reason: 'admission_document_unreadable',
1661
+ nextAction: 'Inspect and repair the persisted admission_json. No Dreamer task was created.',
1662
+ });
1663
+ return;
1664
+ }
1665
+ const processing = admissionDoc.document?.processing;
1666
+ if (processing?.state === 'awaiting_owner' && processing.blockedReason === 'reuse_pending_owner') {
1667
+ seedSuppressedByCandidate.set(candidate.candidateId, { suppress: true, reason: 'reuse_park_pending_owner' });
1668
+ return;
1669
+ }
1670
+ if (processing?.state === 'awaiting_owner'
1671
+ && typeof processing.blockedReason === 'string'
1672
+ && processing.blockedReason.startsWith('candidate_kind_invalid')
1673
+ && validateRecommendationKind(currentCandidate.rawRecommendationKind) !== null) {
1674
+ seedRefusedByCandidate.set(candidate.candidateId, {
1675
+ reason: 'candidate_kind_recovery_required',
1676
+ nextAction: `After repairing the persisted RAW kind, run pd candidate resume-post-processing --candidate-id ${candidate.candidateId} --workspace "${this.workspaceDir}" --reason "<why this repair is safe>" --confirm.`,
1677
+ });
1678
+ return;
1679
+ }
1680
+ const pending = pendingOwnerDecision(admissionDoc.document ?? null);
1681
+ if (pending !== null) {
1682
+ ownerDecisionPendingByCandidate.add(candidate.candidateId);
1683
+ return;
1684
+ }
1685
+ // Validate the latest persisted RAW kind, not the earlier task
1686
+ // snapshot. The normalized recommendationKind folds invalid values
1687
+ // to 'principle' and is never a write-boundary authority.
1688
+ const rawKind = validateRecommendationKind(currentCandidate.rawRecommendationKind);
1689
+ if (rawKind === null) {
1690
+ const refusal = seedRefusalFor(currentCandidate, this.workspaceDir);
1691
+ seedRefusedByCandidate.set(candidate.candidateId, refusal);
1692
+ // Intake may already have persisted the same invalid-kind park.
1693
+ // Do not replace the original blocker timestamp on replay.
1694
+ const alreadyParked = processing?.state === 'awaiting_owner'
1695
+ && typeof processing.blockedReason === 'string'
1696
+ && processing.blockedReason.startsWith('candidate_kind_invalid');
1697
+ const persisted = alreadyParked || await this.stateManager.updateAdmissionProcessing(candidate.candidateId, {
1698
+ state: 'awaiting_owner',
1699
+ attempts: processing?.attempts ?? 0,
1700
+ lastFailure: { reason: refusal.reason, nextAction: refusal.nextAction, at: new Date().toISOString() },
1701
+ blockedReason: refusal.blockedReason ?? 'candidate_kind_invalid',
1702
+ });
1703
+ if (!persisted) {
1704
+ seedRefusedByCandidate.set(candidate.candidateId, {
1705
+ reason: 'candidate_seed_authority_unavailable',
1706
+ nextAction: 'The invalid-kind refusal could not be persisted. Do not retry automatically; inspect admission_json and candidate storage.',
1469
1707
  });
1470
- if ('decision' in seed) {
1471
- // Not internalizable — nothing to adopt on a race below.
1472
- seedTaskIdForAdoption = null;
1473
- }
1474
- else {
1475
- seedTaskIdForAdoption = seed.taskId;
1708
+ }
1709
+ this.eventEmitter?.emitTelemetry({
1710
+ eventType: 'candidate_seed_refused',
1711
+ traceId: candidate.candidateId,
1712
+ timestamp: new Date().toISOString(),
1713
+ payload: {
1714
+ candidateId: candidate.candidateId,
1715
+ reason: refusal.reason,
1716
+ nextAction: refusal.nextAction,
1717
+ rawRecommendationKind: typeof currentCandidate.rawRecommendationKind === 'string'
1718
+ ? currentCandidate.rawRecommendationKind
1719
+ : null,
1720
+ },
1721
+ });
1722
+ return;
1723
+ }
1724
+ let seedSuppression;
1725
+ try {
1726
+ const resolveIdentity = this.ledgerAdapter.resolveCandidatePrincipleIdentity;
1727
+ if (typeof resolveIdentity === 'function') {
1728
+ const identity = resolveIdentity.call(this.ledgerAdapter, candidate.candidateId, currentCandidate.rawRecommendationKind);
1729
+ seedSuppression = evaluateDreamerSeedSuppression({ identity, processing });
1730
+ // A persisted Owner park takes precedence over identity availability.
1731
+ if (seedSuppression.suppress) {
1732
+ seedSuppressedByCandidate.set(candidate.candidateId, seedSuppression);
1733
+ return;
1476
1734
  }
1477
- // eslint-disable-next-line no-restricted-syntax -- 'in' required for discriminated union narrowing (BridgeTaskSeed | BridgeDecision)
1478
- if (!('decision' in seed)) {
1479
- // PRI-720 C6: dedup at candidate level — the demotion may have
1480
- // changed the derived channel suffix vs a pre-existing chain.
1481
- const existingTask = await findExistingDreamerTask((id) => this.stateManager.getTask(id), candidate.candidateId);
1482
- if (!existingTask) {
1483
- await this.stateManager.createTask({
1484
- taskId: seed.taskId,
1485
- taskKind: seed.taskKind,
1486
- inputRef: '',
1487
- status: seed.status,
1488
- attemptCount: seed.attemptCount,
1489
- maxAttempts: seed.maxAttempts,
1490
- diagnosticJson: seed.diagnosticJson,
1735
+ const identityOptional = identity.status !== 'resolved'
1736
+ && identity.reason === 'missing'
1737
+ && rawKind !== 'principle';
1738
+ if (identity.status !== 'resolved' && !identityOptional) {
1739
+ const nextAction = `Ledger identity is ${identity.reason}; inspect and repair the Principle Ledger or candidate binding before seeding. No Dreamer task was created.`;
1740
+ seedRefusedByCandidate.set(candidate.candidateId, {
1741
+ reason: 'candidate_seed_authority_unavailable',
1742
+ nextAction,
1743
+ });
1744
+ if (identity.reason === 'ledger_unavailable') {
1745
+ // A temporarily unavailable ledger is retryable: persist
1746
+ // bounded backoff so an old candidate cannot monopolize the
1747
+ // worker's oldest-first backlog page.
1748
+ await this.recordPostProcessingFailureUnderLock(candidate.candidateId, 'candidate_seed_authority_unavailable:ledger_unavailable');
1749
+ }
1750
+ else {
1751
+ // Ambiguous, revoked, corrupt, missing or ineligible
1752
+ // identities require a human repair. Persist an explicit
1753
+ // Owner blocker; an in-memory refusal alone would leave the
1754
+ // candidate eligible at the head of every worker scan.
1755
+ const persisted = await this.stateManager.updateAdmissionProcessing(candidate.candidateId, {
1756
+ state: 'awaiting_owner',
1757
+ attempts: processing?.attempts ?? 0,
1758
+ lastFailure: {
1759
+ reason: 'candidate_seed_authority_unavailable',
1760
+ nextAction,
1761
+ at: new Date().toISOString(),
1762
+ },
1763
+ blockedReason: `candidate_identity_${identity.reason}`,
1491
1764
  });
1492
- seededTaskByCandidate.set(candidate.candidateId, seed.taskId);
1765
+ if (!persisted) {
1766
+ await this.recordPostProcessingFailureUnderLock(candidate.candidateId, 'candidate_seed_authority_refusal_persistence_failed');
1767
+ }
1768
+ }
1769
+ this.eventEmitter?.emitTelemetry({
1770
+ eventType: 'candidate_seed_refused',
1771
+ traceId: candidate.candidateId,
1772
+ timestamp: new Date().toISOString(),
1773
+ payload: { candidateId: candidate.candidateId, reason: 'candidate_seed_authority_unavailable', identityReason: identity.reason, nextAction },
1774
+ });
1775
+ return;
1776
+ }
1777
+ }
1778
+ else {
1779
+ // Test doubles may omit the optional identity capability. The
1780
+ // production file-backed adapter implements it; pending Owner
1781
+ // and invalid-kind parks were checked above from durable state.
1782
+ seedSuppression = { suppress: false };
1783
+ }
1784
+ }
1785
+ catch {
1786
+ seedRefusedByCandidate.set(candidate.candidateId, {
1787
+ reason: 'candidate_seed_authority_unavailable',
1788
+ nextAction: 'The ledger identity or admission state could not be read. Seeding failed closed; inspect the workspace before retrying.',
1789
+ });
1790
+ return;
1791
+ }
1792
+ if (seedSuppression.suppress) {
1793
+ seedSuppressedByCandidate.set(candidate.candidateId, seedSuppression);
1794
+ }
1795
+ else {
1796
+ let seedTaskIdForAdoption = null;
1797
+ try {
1798
+ const route = CANDIDATE_KIND_TO_ROUTE[rawKind];
1799
+ if (route) {
1800
+ const channel = ROUTE_CHANNEL_MAP[route];
1801
+ const ready = !!channel && MVP_ENABLED_CHANNELS.has(channel);
1802
+ const seed = buildDreamerSeedFromCandidate(currentCandidate, {
1803
+ route,
1804
+ ready,
1805
+ sourcePainId: painId,
1806
+ pipelineMode: this.fullPipelinePromptSeeds ? 'full_chain' : undefined,
1807
+ });
1808
+ // eslint-disable-next-line no-restricted-syntax -- 'in' required for discriminated union narrowing (BridgeTaskSeed | BridgeDecision)
1809
+ if (!('decision' in seed)) {
1810
+ seedTaskIdForAdoption = seed.taskId;
1811
+ const existingTask = await findExistingDreamerTask((id) => this.stateManager.getTask(id), candidate.candidateId);
1812
+ if (!existingTask) {
1813
+ await this.stateManager.createTask({
1814
+ taskId: seed.taskId,
1815
+ taskKind: seed.taskKind,
1816
+ inputRef: '',
1817
+ status: seed.status,
1818
+ attemptCount: seed.attemptCount,
1819
+ maxAttempts: seed.maxAttempts,
1820
+ diagnosticJson: seed.diagnosticJson,
1821
+ });
1822
+ seededTaskByCandidate.set(candidate.candidateId, seed.taskId);
1823
+ this.eventEmitter?.emitTelemetry({
1824
+ eventType: 'candidate_dreamer_task_seeded',
1825
+ traceId: candidate.candidateId,
1826
+ timestamp: new Date().toISOString(),
1827
+ payload: {
1828
+ taskId: seed.taskId,
1829
+ channel: seed.channel,
1830
+ ...(seed.pipelineMode ? { pipelineMode: seed.pipelineMode } : {}),
1831
+ ...(seed.demotedFromChannel ? { demotedFromChannel: seed.demotedFromChannel } : {}),
1832
+ },
1833
+ });
1834
+ }
1835
+ }
1836
+ else if (seed.decision === 'not_internalizable') {
1837
+ notInternalizable.push({ candidateId: candidate.candidateId, reason: seed.reason });
1493
1838
  this.eventEmitter?.emitTelemetry({
1494
- eventType: 'candidate_dreamer_task_seeded',
1839
+ eventType: 'candidate_not_internalizable',
1495
1840
  traceId: candidate.candidateId,
1496
1841
  timestamp: new Date().toISOString(),
1497
- // rc-9: the full-chain override and the C6 channel demotion
1498
- // must both be observable at seed time.
1499
- payload: {
1500
- taskId: seed.taskId,
1501
- channel: seed.channel,
1502
- ...(seed.pipelineMode ? { pipelineMode: seed.pipelineMode } : {}),
1503
- ...(seed.demotedFromChannel ? { demotedFromChannel: seed.demotedFromChannel } : {}),
1504
- },
1842
+ payload: { reason: seed.reason, channel: channel ?? null, route },
1505
1843
  });
1506
1844
  }
1507
1845
  }
1508
- else if (seed.decision === 'not_internalizable') {
1509
- // PRI-539: surface MVP-disabled candidates instead of silently
1510
- // marking them consumed (rc-9-no-silent-fallback / ERR-002).
1511
- notInternalizable.push({ candidateId: candidate.candidateId, reason: seed.reason });
1846
+ }
1847
+ catch (seedErr) {
1848
+ const adoptedSeedTaskId = seedErr instanceof Error
1849
+ && seedTaskIdForAdoption !== null
1850
+ && seedErr.message.includes('UNIQUE constraint failed: tasks.task_id')
1851
+ && (await this.stateManager.getTask(seedTaskIdForAdoption)) !== null
1852
+ ? seedTaskIdForAdoption
1853
+ : null;
1854
+ if (adoptedSeedTaskId !== null) {
1855
+ seededTaskByCandidate.set(candidate.candidateId, adoptedSeedTaskId);
1512
1856
  this.eventEmitter?.emitTelemetry({
1513
- eventType: 'candidate_not_internalizable',
1857
+ eventType: 'candidate_dreamer_task_seed_failed',
1514
1858
  traceId: candidate.candidateId,
1515
1859
  timestamp: new Date().toISOString(),
1516
- payload: { reason: seed.reason, channel: channel ?? null, route },
1860
+ payload: {
1861
+ error: String(seedErr),
1862
+ adopted: true,
1863
+ adoptedTaskId: adoptedSeedTaskId,
1864
+ note: 'a concurrent writer created the deterministic seed first; adopted instead of degrading',
1865
+ },
1517
1866
  });
1518
1867
  }
1868
+ else {
1869
+ seedFailureCandidateIds.push(candidate.candidateId);
1870
+ this.eventEmitter?.emitTelemetry({
1871
+ eventType: 'candidate_dreamer_task_seed_failed',
1872
+ traceId: candidate.candidateId,
1873
+ timestamp: new Date().toISOString(),
1874
+ payload: { error: String(seedErr) },
1875
+ });
1876
+ await this.recordPostProcessingFailureUnderLock(candidate.candidateId, `seed_failed:${String(seedErr)}`);
1877
+ }
1519
1878
  }
1520
1879
  }
1521
- catch (seedErr) {
1522
- // PR #2684 CodeRabbit #9 follow-up: the dreamer seed id is
1523
- // DETERMINISTIC (`dreamer-<candidateId>-<channel>`), and the
1524
- // check-then-insert above is not atomic across connections — a
1525
- // concurrent writer (e.g. the worker's post-processing resume on a
1526
- // second bridge instance) can insert the same task between
1527
- // findExistingDreamerTask and createTask. A UNIQUE violation on
1528
- // tasks.task_id is therefore the idempotency contract WINNING, not
1529
- // a seed failure — the same convergence the diagnostician task
1530
- // creation already applies (Case-B repair). Adopt the existing
1531
- // seed and continue; only genuine errors degrade.
1532
- const adoptedSeedTaskId = seedErr instanceof Error
1533
- && seedTaskIdForAdoption !== null
1534
- && seedErr.message.includes('UNIQUE constraint failed: tasks.task_id')
1535
- && (await this.stateManager.getTask(seedTaskIdForAdoption)) !== null
1536
- ? seedTaskIdForAdoption
1537
- : null;
1538
- if (adoptedSeedTaskId !== null) {
1539
- seededTaskByCandidate.set(candidate.candidateId, adoptedSeedTaskId);
1540
- this.eventEmitter?.emitTelemetry({
1541
- eventType: 'candidate_dreamer_task_seed_failed',
1542
- traceId: candidate.candidateId,
1543
- timestamp: new Date().toISOString(),
1544
- payload: {
1545
- error: String(seedErr),
1546
- adopted: true,
1547
- adoptedTaskId: adoptedSeedTaskId,
1548
- note: 'a concurrent writer created the deterministic seed first; adopted instead of degrading (idempotency contract)',
1549
- },
1550
- });
1551
- // CodeRabbit PR #2684 r2: adopted seeds fall through to the SHARED
1552
- // consume logic below (seedFailure NOT recorded — the candidate is
1553
- // healthy, just raced). The previous `continue` skipped the
1554
- // consumed-status update, stranding the candidate as
1555
- // processing=complete but NOT consumed.
1556
- }
1557
- else {
1558
- seedFailureCandidateIds.push(candidate.candidateId);
1559
- this.eventEmitter?.emitTelemetry({
1560
- eventType: 'candidate_dreamer_task_seed_failed',
1561
- traceId: candidate.candidateId,
1562
- timestamp: new Date().toISOString(),
1563
- payload: { error: String(seedErr) },
1564
- });
1565
- // CR-05 (SPEC §9.1): seed failure is a post-processing orphan —
1566
- // consumed-but-unseeded must stay discoverable by the worker
1567
- // continuation (never hidden behind the consumed status).
1568
- void this.recordPostProcessingFailure(candidate.candidateId, `seed_failed:${String(seedErr)}`).catch(() => undefined);
1569
- }
1880
+ };
1881
+ try {
1882
+ const coordinate = this.ledgerAdapter.withCandidateCoordination;
1883
+ if (typeof coordinate === 'function') {
1884
+ await coordinate.call(this.ledgerAdapter, candidate.candidateId, seedUnderCandidateLock);
1885
+ }
1886
+ else {
1887
+ // The LedgerAdapter contract permits this only for test doubles;
1888
+ // production file-backed adapters implement the cross-process lock.
1889
+ await seedUnderCandidateLock();
1570
1890
  }
1571
- } // end of the !seedSuppression.suppress guard (Phase 7.2 B2.5)
1891
+ }
1892
+ catch {
1893
+ seedRefusedByCandidate.set(candidate.candidateId, {
1894
+ reason: 'candidate_seed_coordination_failed',
1895
+ nextAction: 'Candidate coordination lock failed. No unlocked seed fallback was attempted; retry after the competing operation finishes.',
1896
+ });
1897
+ }
1898
+ // Do not consume or complete any candidate whose durable seed
1899
+ // authorization failed or which still awaits an Owner decision.
1900
+ if (seedRefusedByCandidate.has(candidate.candidateId)
1901
+ || ownerDecisionPendingByCandidate.has(candidate.candidateId)) {
1902
+ continue;
1903
+ }
1572
1904
  // Phase 7.2 B2.5 (CodeRabbit): a candidate suppressed because a
1573
1905
  // persisted reuse PARK is still awaiting the Owner must NOT be
1574
1906
  // consumed — consuming it (or completing its processing below) would
@@ -1579,7 +1911,10 @@ export class PainSignalBridge {
1579
1911
  const suppression = seedSuppressedByCandidate.get(candidate.candidateId);
1580
1912
  const parkedSuppressed = suppression?.suppress === true && suppression.reason === 'reuse_park_pending_owner';
1581
1913
  if (!parkedSuppressed && candidate.status !== 'consumed') {
1582
- await this.stateManager.updateCandidateStatus(candidate.candidateId, { status: 'consumed' });
1914
+ // A failed Dreamer seed does not undo a successful Ledger write.
1915
+ // Preserve the established consumed contract, but still re-check
1916
+ // Owner governance under the candidate lock before changing status.
1917
+ await this.consumeCandidateIfUnblocked(candidate.candidateId);
1583
1918
  }
1584
1919
  }
1585
1920
  }
@@ -1606,7 +1941,13 @@ export class PainSignalBridge {
1606
1941
  // state — Phase C (not this loop) completes the candidate.
1607
1942
  if (ownerDecisionPendingByCandidate.has(candidate.candidateId))
1608
1943
  continue;
1609
- this.safeUpdateAdmissionProcessing(candidate.candidateId, {
1944
+ // D4 (review round 2, P1-2): a seed-refused candidate keeps its saved
1945
+ // `awaiting_owner` state. Marking it `complete` claimed a finished
1946
+ // post-processing that never happened, and the worker then skipped the
1947
+ // candidate forever while it still read as pending.
1948
+ if (seedRefusedByCandidate.has(candidate.candidateId))
1949
+ continue;
1950
+ await this.safeUpdateAdmissionProcessing(candidate.candidateId, {
1610
1951
  state: 'complete',
1611
1952
  attempts: 0,
1612
1953
  completedAt: new Date().toISOString(),
@@ -1649,6 +1990,16 @@ export class PainSignalBridge {
1649
1990
  outcome.nextAction = 'Inspect state.db and telemetry; re-run intake.';
1650
1991
  }
1651
1992
  }
1993
+ // D4 (review round 2, P1-2): the seed refusal is the candidate's outcome
1994
+ // — not the admission's. Without this override the caller saw the
1995
+ // admission's `admitted` + reason and could not tell that the candidate
1996
+ // was refused at the seed gate (rc-9 / EP-03: structured reason + next
1997
+ // action for every refusal).
1998
+ const seedRefused = seedRefusedByCandidate.get(candidate.candidateId);
1999
+ if (seedRefused !== undefined) {
2000
+ outcome.reason = seedRefused.reason;
2001
+ outcome.nextAction = seedRefused.nextAction;
2002
+ }
1652
2003
  // PRI-917 v0.3.3 — park override LAST: a Reuse-Review-Gate candidate is
1653
2004
  // neither seed-failed nor not-internalizable; it is deliberately awaiting
1654
2005
  // the Owner (rc-9: the waiting state must be visible, not silent).
@@ -1810,7 +2161,7 @@ export class PainSignalBridge {
1810
2161
  if (ledgerEntry)
1811
2162
  ledgerEntryIds.push(ledgerEntry.id);
1812
2163
  if (candidate.status !== 'consumed' && ledgerEntry) {
1813
- await this.stateManager.updateCandidateStatus(candidate.candidateId, { status: 'consumed' });
2164
+ await this.consumeCandidateIfUnblocked(candidate.candidateId);
1814
2165
  }
1815
2166
  if (candidate.status === 'pending' && !ledgerEntry && isPrincipleLedgerEligibleKind(candidate.rawRecommendationKind) && this.intakeService?.reuseReviewEnabled) {
1816
2167
  try {