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
@@ -12,7 +12,7 @@
12
12
  */
13
13
  import { createHash } from 'node:crypto';
14
14
  import { PainSignalBridge } from './pain-signal-bridge.js';
15
- import { RuntimeStateManager } from './store/runtime-state-manager.js';
15
+ import { RuntimeStateManager, workspaceIdentityForComparison } from './store/runtime-state-manager.js';
16
16
  import { SplitDiagnosticianRunner } from './internalization/split-diagnostician-runner.js';
17
17
  import { DiagRootCauseRunner } from './internalization/diag-rootcause-runner.js';
18
18
  import { DiagDistillerRunner } from './internalization/diag-distiller-runner.js';
@@ -29,7 +29,6 @@ import { ReuseEvaluationError, ReuseEvaluationRunner } from './principle-reuse/r
29
29
  import { SqliteDiagnosticianCommitter } from './store/commit/diagnostician-committer.js';
30
30
  import { SqliteContextAssembler } from './store/context/sqlite-context-assembler.js';
31
31
  import { SqliteHistoryQuery } from './store/history/sqlite-history-query.js';
32
- import { SqliteConnection } from './store/sqlite-connection.js';
33
32
  import { SqliteTrajectoryLocator } from './store/trajectory/sqlite-trajectory-locator.js';
34
33
  import { SqliteSourceTraceLocator } from './store/trajectory/sqlite-source-trace-locator.js';
35
34
  import { PiAiRuntimeAdapter } from './adapter/pi-ai-runtime-adapter.js';
@@ -386,6 +385,110 @@ export function resolveRuntimeConfigFromPdConfig(effectiveConfig, getEnvVar) {
386
385
  // Key format: `${workspaceDir}:${runtimeKind}:...` (D-03). The openclawMode slot
387
386
  // left with ADR-0029: pi-ai has no mode, so a bridge is keyed by workspace+kind.
388
387
  const bridgeCache = new Map();
388
+ // Retired instances remain discoverable by workspace cleanup until their
389
+ // actual close completes, even after removal from the bounded cache.
390
+ const retiredBridges = new Map();
391
+ const pendingAcquisitions = new Map();
392
+ const closingWorkspaces = new Map();
393
+ function borrowBridge(bridge, registerBorrow) {
394
+ if (registerBorrow !== undefined) {
395
+ const release = bridge.retainFactoryBorrow();
396
+ try {
397
+ registerBorrow(release);
398
+ }
399
+ catch (error) {
400
+ void release();
401
+ throw error;
402
+ }
403
+ }
404
+ return bridge;
405
+ }
406
+ function retireBridge(workspaceDir, bridge) {
407
+ const pending = bridge.disposeWhenIdle();
408
+ const retired = retiredBridges.get(workspaceDir) ?? new Set();
409
+ retiredBridges.set(workspaceDir, retired);
410
+ retired.add(pending);
411
+ void pending.catch(() => undefined).finally(() => {
412
+ retired.delete(pending);
413
+ if (retired.size === 0 && retiredBridges.get(workspaceDir) === retired)
414
+ retiredBridges.delete(workspaceDir);
415
+ });
416
+ }
417
+ // SPEC-PD-PIPELINE-SPINE-001 review round 2 (P1-1): collaborator identity.
418
+ //
419
+ // Audit of what a bridge CAPTURES at construction, and what therefore belongs
420
+ // to its cache identity:
421
+ //
422
+ // collaborator | captured by | in the key
423
+ // -------------------------------------- | ---------------------- | -----------
424
+ // intentDocReader | Stage A runner | identity
425
+ // trajectoryTurnReader | context assembler | identity
426
+ // sourceMaterialAuthorization | assembler + stage runners | identity
427
+ // isAutoPainSubmissionAuthorized (probe) | bridge | identity
428
+ // telemetrySink | bridge / runners | identity
429
+ // autoIntakeEnabled | bridge + intake | value
430
+ // workspace, runtime kind, feature toggles, reuse-gate config | value
431
+ // ledgerAdapter | bridge + intake | NOT keyed:
432
+ // the ledger authority of the workspace — every call site constructs an
433
+ // equivalent instance per call and the existing cache contract reuses a
434
+ // bridge across those calls (pain-signal-factory-intent-reader-wiring).
435
+ //
436
+ // The key used to encode only whether an intent reader was PRESENT, so a
437
+ // second entry calling with its OWN reader / authorization for the same
438
+ // workspace got the first entry's bridge and silently ran with the first
439
+ // entry's collaborators (e.g. the OpenClaw command's session reader replaced
440
+ // by the background auto-run's governance reader, or a sync entry's
441
+ // authorization replaced by deny-all).
442
+ //
443
+ // Identity is OBJECT identity — never presence, which cannot tell two
444
+ // different readers apart. The key carries only a process-local counter per
445
+ // object: no authorization content, consent state or secret ever reaches it.
446
+ // Object identity keeps the Owner's revocation immediate: the consent-ledger
447
+ // authorization and the governance reader re-read consent on every call, so a
448
+ // cached bridge built with the SAME objects already reflects a revocation.
449
+ //
450
+ // Bounded: a workspace slot keeps at most COLLABORATOR_VARIANTS_PER_SLOT
451
+ // variants (least-recently-used first). A superseded bridge is retired
452
+ // idle-safely — it finishes an operation that is already running and then
453
+ // releases its SQLite handles — so alternating entries can neither grow the
454
+ // cache nor leak handles, and are never interrupted mid-diagnosis.
455
+ //
456
+ // Cost note: call sites that construct fresh collaborator objects per call
457
+ // (the workspace workers, the auto-run) no longer hit the cache across
458
+ // calls; a bridge is built per diagnosis — milliseconds against the model
459
+ // calls a diagnosis itself takes. Collapsing those per-call constructions
460
+ // into stable per-workspace collaborators is the Phase 2A assembly work
461
+ // (PRI-1292 `resolveWorkspacePipelineHostDeps`), which restores the hits.
462
+ const collaboratorIdentities = new WeakMap();
463
+ let nextCollaboratorIdentity = 1;
464
+ function collaboratorToken(value) {
465
+ if (value === undefined)
466
+ return 'none';
467
+ let identity = collaboratorIdentities.get(value);
468
+ if (identity === undefined) {
469
+ identity = nextCollaboratorIdentity;
470
+ nextCollaboratorIdentity += 1;
471
+ collaboratorIdentities.set(value, identity);
472
+ }
473
+ return `k${identity}`;
474
+ }
475
+ const COLLABORATOR_VARIANTS_PER_SLOT = 2;
476
+ /** Retire the least-recently-used collaborator variants of `slotKey` beyond
477
+ * the per-slot bound (the cache's iteration order is insertion/recency). */
478
+ function evictSupersededCollaboratorVariants(workspaceDir, slotKey, keepKey) {
479
+ const prefix = `${slotKey}:`;
480
+ const siblings = [...bridgeCache.keys()].filter((key) => key !== keepKey && key.startsWith(prefix));
481
+ while (siblings.length > COLLABORATOR_VARIANTS_PER_SLOT - 1) {
482
+ const evictedKey = siblings.shift();
483
+ if (evictedKey === undefined)
484
+ break;
485
+ const evicted = bridgeCache.get(evictedKey);
486
+ bridgeCache.delete(evictedKey);
487
+ if (evicted !== undefined) {
488
+ retireBridge(workspaceDir, evicted);
489
+ }
490
+ }
491
+ }
389
492
  export const DIAGNOSTICIAN_DISABLED_FAILURE_REASON = 'Diagnostician capability is disabled by Owner configuration (internalAgents.agents.diagnostician.enabled=false)';
390
493
  const DIAGNOSTICIAN_DISABLED_NEXT_ACTION = 'Enable internalAgents.agents.diagnostician.enabled in .pd/config.yaml (or Console → Control Center), then retry.';
391
494
  /**
@@ -461,6 +564,10 @@ const BRIDGE_PASSTHROUGH_EVENT_TYPES = new Set([
461
564
  // its persisted owning payload was unparseable or a retired non-V2 shape —
462
565
  // the skip must reach the durable workspace sink, never vanish in mapping.
463
566
  'replay_review_source_invalid',
567
+ // SPEC-PD-PIPELINE-SPINE-001 D4: the durable invalid-raw-kind refusal is
568
+ // operator-visible audit telemetry, not a degradation event and must not
569
+ // disappear at the bridge→workspace sink boundary.
570
+ 'candidate_seed_refused',
464
571
  ]);
465
572
  export function mapBridgeTelemetryToStoreEvent(event) {
466
573
  // PRI-917 v0.3.3: the Reuse Review Gate's park observation passes through
@@ -505,6 +612,124 @@ export function createBridgeTelemetryEventEmitter(sink) {
505
612
  },
506
613
  };
507
614
  }
615
+ export async function createDiagnosticianRunnerBundle(options) {
616
+ const ownsStateManager = options.stateManager === undefined;
617
+ const stateManager = options.stateManager ?? new RuntimeStateManager({ workspaceDir: options.workspaceDir });
618
+ if (workspaceIdentityForComparison(stateManager.workspaceDir) !== workspaceIdentityForComparison(options.workspaceDir)) {
619
+ throw new Error(`[PainSignalRuntimeFactory] workspace mismatch: bundle workspaceDir '${options.workspaceDir}' `
620
+ + `but stateManager workspaceDir '${stateManager.workspaceDir}'. Refusing to mix task state, consent, Intent and telemetry across workspaces.`);
621
+ }
622
+ let initializedHere = false;
623
+ try {
624
+ if (ownsStateManager) {
625
+ await stateManager.initialize();
626
+ initializedHere = true;
627
+ }
628
+ // Single-connection topology (the CLI-proven one): every collaborator
629
+ // below shares the state manager's connection. There is no second
630
+ // SqliteConnection to track or mis-close.
631
+ const { connection } = stateManager;
632
+ const historyQuery = new SqliteHistoryQuery(connection);
633
+ const committer = new SqliteDiagnosticianCommitter(connection);
634
+ const trajectoryLocator = new SqliteTrajectoryLocator(connection);
635
+ const sourceTraceLocator = new SqliteSourceTraceLocator(stateManager.taskStore, trajectoryLocator);
636
+ const contextAssembler = new SqliteContextAssembler(stateManager.taskStore, historyQuery, stateManager.runStore, {
637
+ sourceTraceLocator,
638
+ trajectoryTurnReader: options.trajectoryTurnReader,
639
+ sourceMaterialAuthorization: options.sourceMaterialAuthorization,
640
+ });
641
+ // PRI-336: resolve outputLanguage from the entry-provided effective config
642
+ // (same resolution authority as the cached-bridge path). Per ERR-002 the
643
+ // degradation is observable, not a silent fallback.
644
+ const resolvedLang = resolveOutputLanguage(options.effectiveConfig?.config.principles?.outputLanguage);
645
+ const outputLanguage = resolvedLang.outputLanguage;
646
+ if (resolvedLang.degradationWarning) {
647
+ (options.telemetrySink ?? storeEmitter).emitTelemetry({
648
+ eventType: 'degradation_triggered',
649
+ traceId: `output-language-config-${Date.now()}`,
650
+ timestamp: new Date().toISOString(),
651
+ sessionId: '',
652
+ payload: {
653
+ component: 'DiagnosticianRunnerBundle',
654
+ reason: 'invalid_output_language_config',
655
+ warning: resolvedLang.degradationWarning,
656
+ fallbackValue: resolvedLang.outputLanguage,
657
+ },
658
+ });
659
+ }
660
+ // SPEC-PD-PIPELINE-RELIABILITY-AND-EFFICIENCY-001 §5.1: resolve the timing
661
+ // contract ONCE and hand it to every stage. Parent budget = 3× stage —
662
+ // identical to the previous factory formula and to the SplitDiagnostician
663
+ // runner's own default derivation the CLIs relied on.
664
+ const executionTiming = resolveExecutionTiming({
665
+ stageTimeoutMs: options.stageTimeoutMs,
666
+ parentBudgetMs: options.stageTimeoutMs * 3,
667
+ });
668
+ const stageRunnerOptions = {
669
+ owner: options.owner,
670
+ runtimeKind: options.runtimeKind,
671
+ outputLanguage,
672
+ effectiveConfig: options.effectiveConfig,
673
+ timeoutMs: executionTiming.stageTimeoutMs,
674
+ leaseTtlMs: executionTiming.leaseTtlMs,
675
+ heartbeatIntervalMs: executionTiming.heartbeatIntervalMs,
676
+ };
677
+ const runnerEventEmitter = options.telemetrySink ?? storeEmitter;
678
+ const rootCauseRunner = new DiagRootCauseRunner({ stateManager, runtimeAdapter: options.runtimeAdapter, eventEmitter: runnerEventEmitter, artifactStore: stateManager.piArtifactStore, validator: new DefaultDiagRootCauseValidator(), contextAssembler, intentDocReader: options.intentDocReader, sourceMaterialAuthorization: options.sourceMaterialAuthorization }, stageRunnerOptions);
679
+ const distillerRunner = new DiagDistillerRunner({ stateManager, runtimeAdapter: options.runtimeAdapter, eventEmitter: runnerEventEmitter, artifactStore: stateManager.piArtifactStore, validator: new DefaultDiagDistillerValidator(), sourceMaterialAuthorization: options.sourceMaterialAuthorization }, stageRunnerOptions);
680
+ const routerRunner = new DiagRouterRunner({
681
+ stateManager, runtimeAdapter: options.runtimeAdapter, eventEmitter: runnerEventEmitter, artifactStore: stateManager.piArtifactStore, committer,
682
+ // Same structural detection as the cached-bridge path: a narrow
683
+ // LedgerAdapter double degrades to a typed `source_not_configured`
684
+ // receipt (observable, never a guessed allowlist).
685
+ trustedPrincipleSource: isRouterTrustedPrincipleSource(options.ledgerAdapter)
686
+ ? options.ledgerAdapter
687
+ : { readTrustedPrinciples: () => ({ status: 'unavailable', reason: 'source_not_configured' }) },
688
+ sourceMaterialAuthorization: options.sourceMaterialAuthorization,
689
+ }, stageRunnerOptions);
690
+ const runner = new SplitDiagnosticianRunner({
691
+ rootCauseRunner,
692
+ distillerRunner,
693
+ routerRunner,
694
+ stateManager,
695
+ committer,
696
+ runtimeKind: options.runtimeKind,
697
+ perStageTimeoutMs: executionTiming.stageTimeoutMs,
698
+ parentBudgetMs: executionTiming.parentBudgetMs,
699
+ leaseTtlMs: executionTiming.leaseTtlMs,
700
+ heartbeatIntervalMs: executionTiming.heartbeatIntervalMs,
701
+ });
702
+ let disposed = false;
703
+ const dispose = async () => {
704
+ if (disposed)
705
+ return;
706
+ disposed = true;
707
+ // Externally provided state manager: owned by the caller — never closed
708
+ // here (no double-close; the CLI finally keeps its original duty).
709
+ if (ownsStateManager) {
710
+ await stateManager.close();
711
+ }
712
+ };
713
+ return {
714
+ stateManager,
715
+ ownsStateManager,
716
+ contextAssembler,
717
+ committer,
718
+ runner,
719
+ executionTiming,
720
+ dispose,
721
+ };
722
+ }
723
+ catch (err) {
724
+ // Construction failure must not leak the manager the bundle created; an
725
+ // externally provided manager stays untouched (rc-9: the caller still
726
+ // owns its cleanup).
727
+ if (initializedHere) {
728
+ await stateManager.close().catch(() => undefined);
729
+ }
730
+ throw err;
731
+ }
732
+ }
508
733
  async function constructBridge(opts, runtimeConfig,
509
734
  // PRI-917 v0.3.3 review fix (P2-1): the reuse-gate hook is built ONCE by
510
735
  // createPainSignalBridge so the hook's captured reuseEvaluation config and
@@ -512,148 +737,89 @@ async function constructBridge(opts, runtimeConfig,
512
737
  construction) {
513
738
  const stateManager = new RuntimeStateManager({ workspaceDir: opts.workspaceDir });
514
739
  await stateManager.initialize();
515
- const connection = new SqliteConnection(opts.workspaceDir);
516
- const historyQuery = new SqliteHistoryQuery(connection);
517
- const committer = new SqliteDiagnosticianCommitter(connection);
518
- const trajectoryLocator = new SqliteTrajectoryLocator(connection);
519
- const sourceTraceLocator = new SqliteSourceTraceLocator(stateManager.taskStore, trajectoryLocator);
520
- const contextAssembler = new SqliteContextAssembler(stateManager.taskStore, historyQuery, stateManager.runStore, {
521
- sourceTraceLocator,
522
- trajectoryTurnReader: opts.trajectoryTurnReader,
523
- sourceMaterialAuthorization: opts.sourceMaterialAuthorization,
524
- });
525
- // ADR-0029: one adapter, one construction site. validateRuntimeConfig already
526
- // rejected every other kind before this point.
527
- const runtimeAdapter = new PiAiRuntimeAdapter({
528
- provider: String(runtimeConfig.provider),
529
- model: String(runtimeConfig.model),
530
- apiKeyEnv: String(runtimeConfig.apiKeyEnv),
531
- maxRetries: runtimeConfig.maxRetries,
532
- maxTokens: runtimeConfig.maxTokens,
533
- timeoutMs: runtimeConfig.timeoutMs,
534
- baseUrl: runtimeConfig.baseUrl,
535
- workspace: opts.workspaceDir,
536
- ...(runtimeConfig.reasoning !== undefined ? { reasoning: runtimeConfig.reasoning } : {}),
537
- ...(runtimeConfig.systemPrompt ? { systemPrompt: runtimeConfig.systemPrompt } : {}),
538
- });
539
- // PRI-336: Resolve outputLanguage from effective config
540
- // Per EP-07: use canonical resolved value, not raw input
541
- const resolvedLang = resolveOutputLanguage(opts.effectiveConfig?.config.principles?.outputLanguage);
542
- const outputLanguage = resolvedLang.outputLanguage;
543
- // Per ERR-002: degradation must be observable, not silent fallback
544
- if (resolvedLang.degradationWarning) {
545
- storeEmitter.emitTelemetry({
546
- eventType: 'degradation_triggered',
547
- traceId: `output-language-config-${Date.now()}`,
548
- timestamp: new Date().toISOString(),
549
- sessionId: '',
550
- payload: {
551
- component: 'PainSignalRuntimeFactory',
552
- reason: 'invalid_output_language_config',
553
- warning: resolvedLang.degradationWarning,
554
- fallbackValue: resolvedLang.outputLanguage,
555
- },
740
+ // Ownership rule: constructBridge owns this manager until PainSignalBridge
741
+ // construction succeeds. Any adapter/bundle/bridge constructor failure closes
742
+ // it exactly once here; after success the bridge's dispose() is the only owner.
743
+ let bridgeOwnsStateManager = false;
744
+ try {
745
+ // ADR-0029: one adapter, one construction site. validateRuntimeConfig already
746
+ // rejected every other kind before this point.
747
+ const runtimeAdapter = new PiAiRuntimeAdapter({
748
+ provider: String(runtimeConfig.provider),
749
+ model: String(runtimeConfig.model),
750
+ apiKeyEnv: String(runtimeConfig.apiKeyEnv),
751
+ maxRetries: runtimeConfig.maxRetries,
752
+ maxTokens: runtimeConfig.maxTokens,
753
+ timeoutMs: runtimeConfig.timeoutMs,
754
+ baseUrl: runtimeConfig.baseUrl,
755
+ workspace: opts.workspaceDir,
756
+ ...(runtimeConfig.reasoning !== undefined ? { reasoning: runtimeConfig.reasoning } : {}),
757
+ ...(runtimeConfig.systemPrompt ? { systemPrompt: runtimeConfig.systemPrompt } : {}),
758
+ });
759
+ // PRI-1292 Phase 2A: the diagnostician runner chain is assembled by the ONE
760
+ // cache-free bundle (same sequence `pd diagnose run` / `pd pain retry` use).
761
+ // This bridge path passes its own just-created stateManager, so the bundle
762
+ // owns nothing — the bridge's dispose() keeps closing it exactly as before.
763
+ // The bundle resolves outputLanguage (incl. the ERR-002 degradation event),
764
+ // execution timing and the single-connection collaborator topology.
765
+ const bundle = await createDiagnosticianRunnerBundle({
766
+ workspaceDir: opts.workspaceDir,
767
+ ledgerAdapter: opts.ledgerAdapter,
768
+ owner: opts.owner ?? 'pain-signal-bridge',
769
+ runtimeAdapter,
770
+ runtimeKind: runtimeConfig.runtimeKind,
771
+ stageTimeoutMs: runtimeConfig.timeoutMs ?? DEFAULT_TIMEOUT_MS,
772
+ effectiveConfig: opts.effectiveConfig,
773
+ stateManager,
774
+ intentDocReader: opts.intentDocReader,
775
+ trajectoryTurnReader: opts.trajectoryTurnReader,
776
+ sourceMaterialAuthorization: opts.sourceMaterialAuthorization,
777
+ telemetrySink: opts.telemetrySink,
778
+ });
779
+ // PRI-917 v0.3.3 — auto-path Reuse Review Gate: inject the semantic reuse
780
+ // recommendation hook handed down from createPainSignalBridge. `undefined`
781
+ // when reuseEvaluation is disabled or no effective config was supplied →
782
+ // the gate reports 'not_configured' and intake behaves EXACTLY as before
783
+ // v0.3.3 (SPEC T11 rollback switch).
784
+ const intakeService = new CandidateIntakeService({
785
+ stateManager,
786
+ ledgerAdapter: opts.ledgerAdapter,
787
+ ...(construction.reuseRecommendation
788
+ ? { reuseRecommendation: construction.reuseRecommendation, reuseStateDir: opts.stateDir }
789
+ : {}),
556
790
  });
791
+ const bridge = new PainSignalBridge({
792
+ stateManager: bundle.stateManager,
793
+ runner: bundle.runner,
794
+ intakeService,
795
+ ledgerAdapter: opts.ledgerAdapter,
796
+ autoIntakeEnabled: opts.autoIntakeEnabled ?? true,
797
+ workspaceDir: opts.workspaceDir,
798
+ diagnosisPersistenceEnabled: construction.diagnosisPersistenceEnabled,
799
+ // PRI-720: seed-time full-chain override for prompt/defer_archive chains
800
+ // (prompt_full_pipeline flag; Owner switch via Console / config file).
801
+ fullPipelinePromptSeeds: construction.fullPipelinePromptSeeds,
802
+ isAutoPainSubmissionAuthorized: opts.isAutoPainSubmissionAuthorized,
803
+ // rc-9: the persistence path must degrade observably in production. Only
804
+ // the persistence degradation events are forwarded (see
805
+ // createBridgeTelemetryEventEmitter); other bridge events stay dormant as on main.
806
+ // PRI-939 Option A: forward into the caller's workspace-scoped sink when
807
+ // provided (CLI short processes) so allowlisted events persist.
808
+ eventEmitter: createBridgeTelemetryEventEmitter(opts.telemetrySink),
809
+ // PRI-1292 Phase 2A: the bundle's single-connection topology removed the
810
+ // extra SqliteConnection — dispose() closes the state manager, whose own
811
+ // connection serves every collaborator.
812
+ ownedResources: [],
813
+ });
814
+ bridgeOwnsStateManager = true;
815
+ return bridge;
816
+ }
817
+ catch (err) {
818
+ if (!bridgeOwnsStateManager) {
819
+ await stateManager.close().catch(() => undefined);
820
+ }
821
+ throw err;
557
822
  }
558
- // PRI-638: implementation selection is no longer a decision this factory
559
- // makes. `diagnostician_split_pipeline` used to gate this on a second,
560
- // non-canonical kill switch; the split pipeline is the only implementation
561
- // left in the tree (no monolithic DiagnosticianRunner exists any more), so
562
- // the flag retains no implementation-selection or disable responsibility.
563
- //
564
- // P0-1 fix: onDiagnosisComplete is no longer wired into the router.
565
- // The bridge (PainSignalBridge.onPainDetected) is the sole invocation point.
566
- // PRI-1146 (round 2, P1-01): runner telemetry uses the SAME effective sink as
567
- // the bridge. When a workspace-scoped sink is injected (CLI short processes),
568
- // allowlisted runner events (e.g. diag_router_trusted_context_unavailable)
569
- // persist to critical-events.jsonl; the sink forwards every non-allowlisted
570
- // event to the storeEmitter singleton, so existing DB telemetry is preserved
571
- // without duplicating the event. Absent a sink, behavior is unchanged.
572
- const runnerEventEmitter = opts.telemetrySink ?? storeEmitter;
573
- // SPEC-PD-PIPELINE-RELIABILITY-AND-EFFICIENCY-001 §5.1: resolve the timing
574
- // contract ONCE and hand it to every stage. Previously `perStageTimeoutMs`
575
- // only reached sub-task metadata; the stage runners fell back to the
576
- // BasePeerRunner 300 s default.
577
- const executionTiming = resolveExecutionTiming({
578
- stageTimeoutMs: runtimeConfig.timeoutMs ?? DEFAULT_TIMEOUT_MS,
579
- parentBudgetMs: (runtimeConfig.timeoutMs ?? DEFAULT_TIMEOUT_MS) * 3,
580
- });
581
- const stageRunnerOptions = {
582
- owner: opts.owner ?? 'pain-signal-bridge',
583
- runtimeKind: runtimeConfig.runtimeKind,
584
- outputLanguage,
585
- effectiveConfig: opts.effectiveConfig,
586
- timeoutMs: executionTiming.stageTimeoutMs,
587
- leaseTtlMs: executionTiming.leaseTtlMs,
588
- heartbeatIntervalMs: executionTiming.heartbeatIntervalMs,
589
- };
590
- const rootCauseRunner = new DiagRootCauseRunner({ stateManager, runtimeAdapter, eventEmitter: runnerEventEmitter, artifactStore: stateManager.piArtifactStore, validator: new DefaultDiagRootCauseValidator(), contextAssembler, intentDocReader: opts.intentDocReader, sourceMaterialAuthorization: opts.sourceMaterialAuthorization }, stageRunnerOptions);
591
- const distillerRunner = new DiagDistillerRunner({ stateManager, runtimeAdapter, eventEmitter: runnerEventEmitter, artifactStore: stateManager.piArtifactStore, validator: new DefaultDiagDistillerValidator(), sourceMaterialAuthorization: opts.sourceMaterialAuthorization }, stageRunnerOptions);
592
- const routerRunner = new DiagRouterRunner({
593
- stateManager, runtimeAdapter, eventEmitter: runnerEventEmitter, artifactStore: stateManager.piArtifactStore, committer,
594
- // PRI-1146 / SPEC v0.6 §5: the trusted canonical principle exposure is
595
- // assembled BEFORE the model call. The concrete PrincipleTreeLedgerAdapter
596
- // implements the port; a narrow LedgerAdapter double without the port is
597
- // detected structurally and degrades to a typed `source_not_configured`
598
- // receipt (observable, never a guessed allowlist).
599
- trustedPrincipleSource: isRouterTrustedPrincipleSource(opts.ledgerAdapter)
600
- ? opts.ledgerAdapter
601
- : { readTrustedPrinciples: () => ({ status: 'unavailable', reason: 'source_not_configured' }) },
602
- sourceMaterialAuthorization: opts.sourceMaterialAuthorization,
603
- },
604
- // PRI-818 (R-08): effectiveConfig must reach Stage C like it does for
605
- // Stage A/B — without it, isDegradationEnabled() is always false and the
606
- // ADR-0019 rate-limit fast-fail degradation path can never fire here.
607
- stageRunnerOptions);
608
- const runner = new SplitDiagnosticianRunner({
609
- rootCauseRunner,
610
- distillerRunner,
611
- routerRunner,
612
- stateManager,
613
- committer,
614
- // PRI-1266: the parent run records the ACTUAL execution runtime — the same
615
- // resolved kind the stage runners carry (stageRunnerOptions.runtimeKind).
616
- runtimeKind: runtimeConfig.runtimeKind,
617
- perStageTimeoutMs: executionTiming.stageTimeoutMs,
618
- parentBudgetMs: executionTiming.parentBudgetMs,
619
- leaseTtlMs: executionTiming.leaseTtlMs,
620
- heartbeatIntervalMs: executionTiming.heartbeatIntervalMs,
621
- });
622
- // PRI-917 v0.3.3 — auto-path Reuse Review Gate: inject the semantic reuse
623
- // recommendation hook handed down from createPainSignalBridge. `undefined`
624
- // when reuseEvaluation is disabled or no effective config was supplied →
625
- // the gate reports 'not_configured' and intake behaves EXACTLY as before
626
- // v0.3.3 (SPEC T11 rollback switch).
627
- const intakeService = new CandidateIntakeService({
628
- stateManager,
629
- ledgerAdapter: opts.ledgerAdapter,
630
- ...(construction.reuseRecommendation
631
- ? { reuseRecommendation: construction.reuseRecommendation, reuseStateDir: opts.stateDir }
632
- : {}),
633
- });
634
- const bridge = new PainSignalBridge({
635
- stateManager,
636
- runner,
637
- intakeService,
638
- ledgerAdapter: opts.ledgerAdapter,
639
- autoIntakeEnabled: opts.autoIntakeEnabled ?? true,
640
- workspaceDir: opts.workspaceDir,
641
- diagnosisPersistenceEnabled: construction.diagnosisPersistenceEnabled,
642
- // PRI-720: seed-time full-chain override for prompt/defer_archive chains
643
- // (prompt_full_pipeline flag; Owner switch via Console / config file).
644
- fullPipelinePromptSeeds: construction.fullPipelinePromptSeeds,
645
- isAutoPainSubmissionAuthorized: opts.isAutoPainSubmissionAuthorized,
646
- // rc-9: the persistence path must degrade observably in production. Only
647
- // the persistence degradation events are forwarded (see
648
- // createBridgeTelemetryEventEmitter); other bridge events stay dormant as on main.
649
- // PRI-939 Option A: forward into the caller's workspace-scoped sink when
650
- // provided (CLI short processes) so allowlisted events persist.
651
- eventEmitter: createBridgeTelemetryEventEmitter(opts.telemetrySink),
652
- // PRI-624: the factory opens one extra connection (history/committer/
653
- // context assemblers) beyond the state manager — dispose() releases both.
654
- ownedResources: [connection],
655
- });
656
- return bridge;
657
823
  }
658
824
  /**
659
825
  * PRI-624: dispose + drop every cached bridge for a workspace, releasing
@@ -661,19 +827,27 @@ construction) {
661
827
  * this after execution; long-lived hosts that reuse the cached bridge do not.
662
828
  */
663
829
  export async function disposePainSignalBridgesForWorkspace(workspaceDir) {
664
- const prefix = `${workspaceDir}:`;
665
- const doomed = [];
666
- for (const [key, bridge] of bridgeCache) {
667
- if (key.startsWith(prefix)) {
668
- doomed.push(bridge);
669
- bridgeCache.delete(key);
830
+ const existing = closingWorkspaces.get(workspaceDir);
831
+ if (existing !== undefined)
832
+ return existing;
833
+ const cleanup = (async () => {
834
+ await Promise.allSettled([...(pendingAcquisitions.get(workspaceDir) ?? [])]);
835
+ const prefix = `${workspaceDir}:`;
836
+ for (const [key, bridge] of bridgeCache) {
837
+ if (key.startsWith(prefix)) {
838
+ bridgeCache.delete(key);
839
+ retireBridge(workspaceDir, bridge);
840
+ }
670
841
  }
842
+ await Promise.allSettled([...(retiredBridges.get(workspaceDir) ?? [])]);
843
+ })();
844
+ closingWorkspaces.set(workspaceDir, cleanup);
845
+ try {
846
+ await cleanup;
671
847
  }
672
- for (const bridge of doomed) {
673
- try {
674
- await bridge.dispose();
675
- }
676
- catch { /* best-effort cleanup */ }
848
+ finally {
849
+ if (closingWorkspaces.get(workspaceDir) === cleanup)
850
+ closingWorkspaces.delete(workspaceDir);
677
851
  }
678
852
  }
679
853
  /**
@@ -688,11 +862,12 @@ export async function disposePainSignalBridgesForWorkspace(workspaceDir) {
688
862
  *
689
863
  * Cache key is workspaceDir — one bridge per workspace per process.
690
864
  */
691
- async function createDisabledBridge(opts, capability) {
865
+ async function createDisabledBridge(opts, capability, registerBorrow) {
692
866
  const disabledCacheKey = `${opts.workspaceDir}:${DISABLED_BRIDGE_CACHE_SLOT}`;
693
867
  const cached = bridgeCache.get(disabledCacheKey);
694
- if (cached)
695
- return cached;
868
+ if (cached) {
869
+ return borrowBridge(cached, registerBorrow);
870
+ }
696
871
  const stateManager = new RuntimeStateManager({ workspaceDir: opts.workspaceDir });
697
872
  await stateManager.initialize();
698
873
  const intakeService = new CandidateIntakeService({
@@ -722,13 +897,15 @@ async function createDisabledBridge(opts, capability) {
722
897
  });
723
898
  const winner = bridgeCache.get(disabledCacheKey);
724
899
  if (winner !== undefined && winner !== bridge) {
900
+ // Borrow the winner before awaiting disposal of the losing constructor.
901
+ const borrowed = borrowBridge(winner, registerBorrow);
725
902
  await bridge.dispose().catch(() => undefined);
726
- return winner;
903
+ return borrowed;
727
904
  }
728
905
  bridgeCache.set(disabledCacheKey, bridge);
729
- return bridge;
906
+ return borrowBridge(bridge, registerBorrow);
730
907
  }
731
- export async function createPainSignalBridge(opts) {
908
+ async function createPainSignalBridgeInner(opts, registerBorrow) {
732
909
  // PRI-638: the capability decision comes FIRST and from ONE authority.
733
910
  //
734
911
  // Previously an Owner-disabled Diagnostician made this function throw, which
@@ -742,7 +919,7 @@ export async function createPainSignalBridge(opts) {
742
919
  // provider calls, so re-enabling the agent is enough to resume.
743
920
  const capability = resolveDiagnosticianCapability(opts.effectiveConfig);
744
921
  if (!capability.available) {
745
- return createDisabledBridge(opts, capability);
922
+ return createDisabledBridge(opts, capability, registerBorrow);
746
923
  }
747
924
  // PRI-306: Prefer config-driven binding when effectiveConfig is provided
748
925
  let runtimeConfig;
@@ -804,10 +981,26 @@ export async function createPainSignalBridge(opts) {
804
981
  Object.entries(profile ?? {}).sort(([a], [b]) => a.localeCompare(b)),
805
982
  ])).digest('hex');
806
983
  }
807
- const cacheKey = `${opts.workspaceDir}:${runtimeConfig.runtimeKind}:${diagnosisPersistenceEnabled ? 'pdp' : 'nopdp'}:${fullPipelinePromptSeeds ? 'pfp' : 'nopfp'}:${intentAnchoringEnabled ? 'ia' : 'noia'}:${opts.intentDocReader !== undefined ? 'r' : 'nor'}:${reuseCacheKey}`;
984
+ // `slotKey` = everything a bridge depends on apart from its per-entry
985
+ // collaborators (workspace, runtime kind, the toggles below, the reuse
986
+ // gate, automatic intake). The collaborator tokens extend it into the
987
+ // full cache key (see "collaborator identity" next to the cache).
988
+ const slotKey = `${opts.workspaceDir}:${runtimeConfig.runtimeKind}:${diagnosisPersistenceEnabled ? 'pdp' : 'nopdp'}:${fullPipelinePromptSeeds ? 'pfp' : 'nopfp'}:${intentAnchoringEnabled ? 'ia' : 'noia'}:${reuseCacheKey}:${opts.autoIntakeEnabled === false ? 'noai' : 'ai'}`;
989
+ const cacheKey = [
990
+ slotKey,
991
+ collaboratorToken(opts.intentDocReader),
992
+ collaboratorToken(opts.trajectoryTurnReader),
993
+ collaboratorToken(opts.sourceMaterialAuthorization),
994
+ collaboratorToken(opts.telemetrySink),
995
+ collaboratorToken(opts.isAutoPainSubmissionAuthorized),
996
+ ].join(':');
808
997
  const cached = bridgeCache.get(cacheKey);
809
- if (cached)
810
- return cached;
998
+ if (cached) {
999
+ // recency refresh for the per-slot bound
1000
+ bridgeCache.delete(cacheKey);
1001
+ bridgeCache.set(cacheKey, cached);
1002
+ return borrowBridge(cached, registerBorrow);
1003
+ }
811
1004
  const bridge = await constructBridge(opts, runtimeConfig, {
812
1005
  diagnosisPersistenceEnabled,
813
1006
  fullPipelinePromptSeeds,
@@ -817,11 +1010,15 @@ export async function createPainSignalBridge(opts) {
817
1010
  // were building — the loser self-disposes so its handles never leak.
818
1011
  const winner = bridgeCache.get(cacheKey);
819
1012
  if (winner !== undefined && winner !== bridge) {
1013
+ // Borrow the winner before awaiting disposal of the losing constructor.
1014
+ const borrowed = borrowBridge(winner, registerBorrow);
820
1015
  await bridge.dispose().catch(() => undefined);
821
- return winner;
1016
+ return borrowed;
822
1017
  }
823
1018
  bridgeCache.set(cacheKey, bridge);
824
- return bridge;
1019
+ const borrowed = borrowBridge(bridge, registerBorrow);
1020
+ evictSupersededCollaboratorVariants(opts.workspaceDir, slotKey, cacheKey);
1021
+ return borrowed;
825
1022
  }
826
1023
  /**
827
1024
  * PRI-638: bridge for the "Owner disabled the Diagnostician" state.
@@ -838,11 +1035,43 @@ export function invalidatePainSignalBridge(workspaceDir, runtimeKind) {
838
1035
  // disposePainSignalBridgesForWorkspace uses — instead of enumerating key
839
1036
  // components by hand.
840
1037
  const effectiveKind = runtimeKind ?? 'pi-ai';
841
- bridgeCache.delete(`${workspaceDir}:${DISABLED_BRIDGE_CACHE_SLOT}`);
1038
+ const retire = (key) => {
1039
+ const bridge = bridgeCache.get(key);
1040
+ if (bridge === undefined)
1041
+ return;
1042
+ bridgeCache.delete(key);
1043
+ // Invalidation removes discoverability immediately but preserves any
1044
+ // outstanding factory borrow or operation until it is safe to close.
1045
+ retireBridge(workspaceDir, bridge);
1046
+ };
1047
+ retire(`${workspaceDir}:${DISABLED_BRIDGE_CACHE_SLOT}`);
842
1048
  const kindPrefix = `${workspaceDir}:${effectiveKind}:`;
843
1049
  for (const key of [...bridgeCache.keys()]) {
844
1050
  if (key.startsWith(kindPrefix))
845
- bridgeCache.delete(key);
1051
+ retire(key);
1052
+ }
1053
+ }
1054
+ /**
1055
+ * Supply registerBorrow for use across await or concurrent cleanup/eviction.
1056
+ * Release the registered lease in finally, even if no operation is started.
1057
+ * The legacy one-argument form is an unleased lookup for callers which
1058
+ * externally coordinate the workspace lifetime (including inspection tests).
1059
+ */
1060
+ export async function createPainSignalBridge(opts, registerBorrow) {
1061
+ const { workspaceDir } = opts;
1062
+ if (closingWorkspaces.has(workspaceDir))
1063
+ throw new Error('PainSignalBridge workspace cleanup is in progress');
1064
+ const acquisition = createPainSignalBridgeInner(opts, registerBorrow);
1065
+ const pending = pendingAcquisitions.get(workspaceDir) ?? new Set();
1066
+ pendingAcquisitions.set(workspaceDir, pending);
1067
+ pending.add(acquisition);
1068
+ try {
1069
+ return await acquisition;
1070
+ }
1071
+ finally {
1072
+ pending.delete(acquisition);
1073
+ if (pending.size === 0 && pendingAcquisitions.get(workspaceDir) === pending)
1074
+ pendingAcquisitions.delete(workspaceDir);
846
1075
  }
847
1076
  }
848
1077
  //# sourceMappingURL=pain-signal-runtime-factory.js.map