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
@@ -1,5 +1,5 @@
1
1
  {
2
2
  "schemaVersion": 1,
3
- "productVersion": "2.8.11",
4
- "sourceCommit": "eb4674ed948673b9a0e5c22590f5dd9d8cfd7fed"
3
+ "productVersion": "2.8.12",
4
+ "sourceCommit": "16f7e15c5832284db3836b8babed2b7980bca8c9"
5
5
  }
@@ -1,3 +1,4 @@
1
+ import type { TargetTurnEvidenceRead } from '@principles/core/runtime';
1
2
  import { type PainReceiptRecoveryOutcome } from '@principles/core/runtime';
2
3
  /** The MCP tool id this fallback processes (the server gate lives in the
3
4
  * codec parser — exact match on both namespace segments, never a pattern). */
@@ -25,12 +26,38 @@ export interface PainReceiptFallbackInput {
25
26
  readonly minimalMetadataGranted: boolean;
26
27
  readonly now?: () => Date;
27
28
  }
29
+ /**
30
+ * PRI-1273 (A2): the structured target-turn evidence read the worker's
31
+ * waiting-task reconcile consumes. This is the EXACT-turn authority for the
32
+ * Codex host boundary:
33
+ *
34
+ * 1. the source-material consent ledger is consulted FIRST (PRI-1283 R2
35
+ * parity with the submit path): a missing / revoked / not-granted /
36
+ * unreadable decision returns `blocked_by_consent` BEFORE any store
37
+ * query — a denial is never mixed into the waiting set;
38
+ * 2. the governance store is queried for the EXACT (rollout identity, host
39
+ * turn id) — never a session scan, never the submission turn, never a
40
+ * recent-turn fallback;
41
+ * 3. rows keep the same retention/excerpt contract the submit path's
42
+ * enrichment uses (user/assistant turns, operational|promoted retention,
43
+ * `governance_observation:<logicalKey>` sourceRef, bounded note) so the
44
+ * backfilled entries are indistinguishable from submit-time evidence.
45
+ *
46
+ * Expired/purged rows (retention outside operational|promoted, empty text)
47
+ * simply do not qualify — an honest not_found until retention re-promotes
48
+ * or the turn is re-collected.
49
+ */
50
+ export declare function readCodexTargetTurnEvidence(workspaceDir: string, sessionId: string, turnId: string): TargetTurnEvidenceRead;
28
51
  /**
29
52
  * P1-3: does the authorized governance store already hold readable text for
30
53
  * the EXACT (session, turn)? Shared by the receipt fallback (disposition
31
54
  * choice) and the workspace worker's waiting-task reconcile (the flip) —
32
55
  * the diagnosis itself re-reads the turn through the same store.
33
- * Unreadable ⇒ missing.
56
+ * Unreadable ⇒ missing. Since PRI-1273 this boolean is the `available`
57
+ * projection of the consent-gated structured read above: a consent denial
58
+ * reads as "not available", so the receipt fallback's waiting disposition
59
+ * is reclassified to `blocked_by_source_material_consent` by the worker
60
+ * reconcile on its next bounded pass.
34
61
  */
35
62
  export declare function codexTargetTurnTextAvailable(workspaceDir: string, sessionId: string, turnId: string): boolean;
36
63
  /**
@@ -28,7 +28,7 @@
28
28
  * `tool_call` rows, or look-alike strings (SPEC TD §1.3).
29
29
  */
30
30
  import * as path from 'node:path';
31
- import { listGovernanceObservations } from '@principles/host-runtime';
31
+ import { createConsentLedgerSourceMaterialAuthorization, listGovernanceConversationTextsForHostTurn, readSourceMaterialAuthorization } from '@principles/host-runtime';
32
32
  import { isSentinelSessionId } from '@principles/core/runtime';
33
33
  import { recoverTaskIdentityFromReceipt, validatePainSubmitReceipt, } from '@principles/core/runtime';
34
34
  import { isPainSubmitPostToolUseToolName } from '../codec/input-decoder.js';
@@ -80,32 +80,68 @@ function normalizeEventId(value, opts) {
80
80
  return id.length > 0 && id.length <= 200 && !isSentinelSessionId(id) ? id : null;
81
81
  }
82
82
  /**
83
- * P1-3: does the authorized governance store already hold readable text for
84
- * the EXACT (session, turn)? Shared by the receipt fallback (disposition
85
- * choice) and the workspace worker's waiting-task reconcile (the flip) —
86
- * the diagnosis itself re-reads the turn through the same store.
87
- * Unreadable ⇒ missing.
83
+ * PRI-1273 (A2): the structured target-turn evidence read the worker's
84
+ * waiting-task reconcile consumes. This is the EXACT-turn authority for the
85
+ * Codex host boundary:
86
+ *
87
+ * 1. the source-material consent ledger is consulted FIRST (PRI-1283 R2
88
+ * parity with the submit path): a missing / revoked / not-granted /
89
+ * unreadable decision returns `blocked_by_consent` BEFORE any store
90
+ * query — a denial is never mixed into the waiting set;
91
+ * 2. the governance store is queried for the EXACT (rollout identity, host
92
+ * turn id) — never a session scan, never the submission turn, never a
93
+ * recent-turn fallback;
94
+ * 3. rows keep the same retention/excerpt contract the submit path's
95
+ * enrichment uses (user/assistant turns, operational|promoted retention,
96
+ * `governance_observation:<logicalKey>` sourceRef, bounded note) so the
97
+ * backfilled entries are indistinguishable from submit-time evidence.
98
+ *
99
+ * Expired/purged rows (retention outside operational|promoted, empty text)
100
+ * simply do not qualify — an honest not_found until retention re-promotes
101
+ * or the turn is re-collected.
88
102
  */
89
- export function codexTargetTurnTextAvailable(workspaceDir, sessionId, turnId) {
103
+ export function readCodexTargetTurnEvidence(workspaceDir, sessionId, turnId) {
104
+ const authorization = readSourceMaterialAuthorization({ workspaceDir, hostKind: 'codex' });
105
+ if (authorization.status === 'blocked') {
106
+ return { status: 'blocked_by_consent', reason: authorization.reason };
107
+ }
90
108
  try {
91
- const result = listGovernanceObservations({
109
+ const result = listGovernanceConversationTextsForHostTurn({
92
110
  workspaceDir,
93
111
  hostKind: 'codex',
94
112
  rolloutIdentity: sessionId,
95
113
  hostTurnId: turnId,
96
- limit: 8,
114
+ limit: 12,
97
115
  });
98
- if (!result.ok)
99
- return false;
100
- return result.observations.some((row) => (row.kind === 'user_turn' || row.kind === 'assistant_turn')
101
- && (row.retentionClass === 'operational' || row.retentionClass === 'promoted')
102
- && typeof row.visibleText === 'string'
103
- && row.visibleText.trim() !== '');
116
+ if (!result.ok) {
117
+ return { status: 'read_failed', reason: result.reason };
118
+ }
119
+ const entries = result.rows.map((row) => ({
120
+ sourceRef: 'governance_observation:' + row.logicalKey,
121
+ note: row.visibleText.slice(0, 2000),
122
+ }));
123
+ return entries.length > 0
124
+ ? { status: 'available', entries }
125
+ : { status: 'not_found' };
104
126
  }
105
- catch {
106
- return false;
127
+ catch (error) {
128
+ return { status: 'read_failed', reason: error instanceof Error ? error.message.slice(0, 120) : 'store_exception' };
107
129
  }
108
130
  }
131
+ /**
132
+ * P1-3: does the authorized governance store already hold readable text for
133
+ * the EXACT (session, turn)? Shared by the receipt fallback (disposition
134
+ * choice) and the workspace worker's waiting-task reconcile (the flip) —
135
+ * the diagnosis itself re-reads the turn through the same store.
136
+ * Unreadable ⇒ missing. Since PRI-1273 this boolean is the `available`
137
+ * projection of the consent-gated structured read above: a consent denial
138
+ * reads as "not available", so the receipt fallback's waiting disposition
139
+ * is reclassified to `blocked_by_source_material_consent` by the worker
140
+ * reconcile on its next bounded pass.
141
+ */
142
+ export function codexTargetTurnTextAvailable(workspaceDir, sessionId, turnId) {
143
+ return readCodexTargetTurnEvidence(workspaceDir, sessionId, turnId).status === 'available';
144
+ }
109
145
  /**
110
146
  * Attempt the receipt fallback for one PostToolUse event. Never throws —
111
147
  * every failure is a structured result the hook surfaces as one bounded
@@ -169,7 +205,8 @@ export async function attemptPainReceiptFallback(input) {
169
205
  toolCallId,
170
206
  },
171
207
  authorization: { minimalMetadataGranted: input.minimalMetadataGranted },
172
- targetTurnTextAvailable: (hostSessionId, targetTurnId) => codexTargetTurnTextAvailable(normalizedWorkspace, hostSessionId, targetTurnId),
208
+ readTargetTurnEvidence: (hostSessionId, targetTurnId) => readCodexTargetTurnEvidence(normalizedWorkspace, hostSessionId, targetTurnId),
209
+ sourceMaterialAuthorization: createConsentLedgerSourceMaterialAuthorization(normalizedWorkspace),
173
210
  ...(input.now !== undefined ? { now: input.now } : {}),
174
211
  });
175
212
  return { status: 'attempted', outcome };
@@ -28,9 +28,9 @@
28
28
  import fs from 'node:fs';
29
29
  import path from 'node:path';
30
30
  import { computeFeatureFlagsFromConfig, createRuntimeStateHandle, createPainSignalBridge, isRetryWaitBackoffElapsed, pickDiagnosticianCandidate, reconcileWaitingTargetEvidenceTasks, PrincipleTreeLedgerAdapter, resolveDiagnosticianCapability, } from '@principles/core/runtime';
31
- import { createWorkspaceBehaviorEvidencePort, createCodexArtificerTrustedFactsPort, loadPdConfigForPlugin, loadFeatureFlagFromConfig, reconcileGovernanceContinuation, runInternalizationConsumerCycle, runStage2CorrectionCycle, createSignalClassifierForWorkspace, createGovernanceTrajectoryTurnReader, createConsentLedgerSourceMaterialAuthorization, createHostIntentDocReader, isAutomaticPainSubmissionAuthorized, saveHostToolDeclaration, HOST_TOOL_DECLARATION_VERSION, } from '@principles/host-runtime';
31
+ import { createWorkspaceBehaviorEvidencePort, createCodexArtificerTrustedFactsPort, loadPdConfigForPlugin, loadFeatureFlagFromConfig, reconcileGovernanceContinuation, runInternalizationConsumerCycle, runStage2CorrectionCycle, createSignalClassifierForWorkspace, createConsentLedgerSourceMaterialAuthorization, resolveWorkspacePipelineHostDeps, saveHostToolDeclaration, HOST_TOOL_DECLARATION_VERSION, } from '@principles/host-runtime';
32
32
  import { catchUpCodexIngestion } from '../ingestion/catch-up.js';
33
- import { codexTargetTurnTextAvailable } from '../ingestion/pain-receipt-fallback.js';
33
+ import { readCodexTargetTurnEvidence } from '../ingestion/pain-receipt-fallback.js';
34
34
  import { CODEX_TOOL_SEMANTIC_MAPPINGS, CODEX_TOOL_SEMANTICS } from '../tool-semantics.js';
35
35
  const WORKER_OWNER = 'companion-worker';
36
36
  const DEFAULT_DIAG_CANDIDATE_LIMIT = 5;
@@ -299,55 +299,87 @@ export async function runCodexWorkspaceWorkerCycle(options) {
299
299
  // and the picker's SQL excludes anything still waiting. Bounded work
300
300
  // over the existing task rows + the shared authorized-store probe;
301
301
  // no new queue, no scheduler, no scanning of general history.
302
+ // PRI-1273 (A2): the probe is the consent-gated EXACT-turn read —
303
+ // the flip CAS backfills the arrived evidence + evidenceClass onto
304
+ // the SAME task, and a source-material denial reclassifies the task
305
+ // to blocked_by_source_material_consent instead of waiting.
306
+ // SPEC TD §2.2 ruling 4: the SAME consent ledger is read once more
307
+ // right before the evidence write (the existing PRI-1283 R2 port), so
308
+ // a revocation landing between the read and the write persists nothing.
302
309
  targetEvidenceReconcile = await reconcileWaitingTargetEvidenceTasks({
303
310
  stateManager: handle.stateManager,
304
- targetTurnTextAvailable: (sessionId, turnId) => codexTargetTurnTextAvailable(path.resolve(workspaceDir), sessionId, turnId),
311
+ readTargetTurnEvidence: (sessionId, turnId) => readCodexTargetTurnEvidence(path.resolve(workspaceDir), sessionId, turnId),
312
+ sourceMaterialAuthorization: createConsentLedgerSourceMaterialAuthorization(path.resolve(workspaceDir)),
313
+ hostKind: 'codex',
305
314
  nowIso: new Date().toISOString(),
306
315
  });
307
- if (targetEvidenceReconcile.flipped > 0 || targetEvidenceReconcile.errors.length > 0) {
316
+ if (targetEvidenceReconcile.flipped > 0 || targetEvidenceReconcile.blocked > 0 || targetEvidenceReconcile.errors.length > 0) {
308
317
  emitEvent('CODEX_WORKER_TARGET_EVIDENCE_RECONCILE', JSON.stringify(targetEvidenceReconcile));
309
318
  }
310
319
  const candidate = await pickDiagnosticianCandidate(handle.stateManager, options.diagnosticianCandidateLimit ?? DEFAULT_DIAG_CANDIDATE_LIMIT, new Date().toISOString());
311
320
  if (candidate !== null) {
312
321
  const stateDir = path.join(workspaceDir, '.state');
313
- const bridge = await createPainSignalBridge({
314
- workspaceDir,
315
- stateDir,
316
- ledgerAdapter: new PrincipleTreeLedgerAdapter({ stateDir }),
317
- owner: WORKER_OWNER,
318
- effectiveConfig: config.effective,
319
- getEnvVar: (name) => process.env[name],
320
- // PRI-1233 / SPEC §9.2: this worker is where Stage A actually runs
321
- // for governance-admitted Codex pains — the neutral host reader
322
- // must ride along (flag-off = zero filesystem access inside it).
323
- intentDocReader: createHostIntentDocReader({ workspaceDir, effectiveConfig: config.effective }),
324
- // PRI-1265: the worker's Stage A gets the bound session's ORIGINAL
325
- // turns from the workspace's own consent-tiered governance store.
326
- trajectoryTurnReader: createGovernanceTrajectoryTurnReader({ workspaceDir, sourceMaterialAuthorization: createConsentLedgerSourceMaterialAuthorization(workspaceDir) }),
327
- // PRI-1283 R2: latest-consent gate consulted per assembly / model call.
328
- sourceMaterialAuthorization: createConsentLedgerSourceMaterialAuthorization(workspaceDir),
329
- // SPEC §9.6: lazy probe — a revoked flag stops persisted
330
- // automatic_hook tasks at the bridge's execution boundary.
331
- isAutoPainSubmissionAuthorized: () => isAutomaticPainSubmissionAuthorized(workspaceDir),
332
- });
333
- const executed = await bridge.executePendingDiagnosis({ taskId: candidate.taskId });
334
- // PRI-917 v0.3.3 review fix (P2-2): forward the parked-candidate
335
- // dispositions so the Owner sees the pending items instead of a bare
336
- // degraded status with no subject.
337
- const reuseReviewRequired = (executed.candidateOutcomes ?? [])
338
- .filter((outcome) => outcome.reason === 'reuse_review_required')
339
- .map((outcome) => outcome.candidateId);
340
- diagnostician = {
341
- taskId: candidate.taskId,
342
- status: executed.status,
343
- ...(executed.message !== undefined ? { message: executed.message.slice(0, 200) } : {}),
344
- ...(executed.errorCategory !== undefined ? { errorCategory: executed.errorCategory } : {}),
345
- ...(reuseReviewRequired.length > 0 ? { reuseReviewRequiredCandidateIds: reuseReviewRequired } : {}),
346
- };
347
- // The bridge stays cached per workspace (bounded: one per workspace
348
- // per worker process, exactly like the OpenClaw plugin host) — no
349
- // per-cycle dispose, so a concurrent cycle can never hit a disposed
350
- // bridge. The factory self-disposes losing concurrent constructions.
322
+ let releaseBridge;
323
+ try {
324
+ // SPEC-PD-PIPELINE-SPINE-001 §4.2 (PRI-1292 Phase 2A): ONE assembly
325
+ // point for the five host collaborators. The trajectory reader and
326
+ // the source-material gate share the SAME consent-ledger
327
+ // authorization instance (previously two separate instances per
328
+ // call). PRI-1233 / SPEC §9.2: this worker is where Stage A
329
+ // actually runs for governance-admitted Codex pains; PRI-1265: the
330
+ // Stage A gets the bound session's ORIGINAL turns from the
331
+ // workspace's consent-tiered governance store.
332
+ const hostDeps = resolveWorkspacePipelineHostDeps({
333
+ workspaceDir,
334
+ effectiveConfig: config.effective,
335
+ telemetryPersistenceFailureHandler: (detail) => {
336
+ try {
337
+ emitEvent('CODEX_WORKER_CRITICAL_TELEMETRY_PERSIST_FAILED', detail);
338
+ }
339
+ catch {
340
+ // Telemetry persistence warnings must never fail the worker cycle.
341
+ }
342
+ },
343
+ });
344
+ const bridge = await createPainSignalBridge({
345
+ workspaceDir,
346
+ stateDir,
347
+ ledgerAdapter: new PrincipleTreeLedgerAdapter({ stateDir }),
348
+ owner: WORKER_OWNER,
349
+ effectiveConfig: config.effective,
350
+ getEnvVar: (name) => process.env[name],
351
+ intentDocReader: hostDeps.intentDocReader,
352
+ trajectoryTurnReader: hostDeps.trajectoryTurnReader,
353
+ sourceMaterialAuthorization: hostDeps.sourceMaterialAuthorization,
354
+ // PRI-939 Option A: allowlisted runner/bridge events persist to
355
+ // the workspace sink instead of the unsubscribed singleton.
356
+ telemetrySink: hostDeps.telemetrySink,
357
+ // SPEC §9.6: lazy probe — a revoked flag stops persisted
358
+ // automatic_hook tasks at the bridge's execution boundary.
359
+ isAutoPainSubmissionAuthorized: hostDeps.isAutoPainSubmissionAuthorized,
360
+ }, (release) => { releaseBridge = release; });
361
+ const executed = await bridge.executePendingDiagnosis({ taskId: candidate.taskId });
362
+ // PRI-917 v0.3.3 review fix (P2-2): forward the parked-candidate
363
+ // dispositions so the Owner sees the pending items instead of a bare
364
+ // degraded status with no subject.
365
+ const reuseReviewRequired = (executed.candidateOutcomes ?? [])
366
+ .filter((outcome) => outcome.reason === 'reuse_review_required')
367
+ .map((outcome) => outcome.candidateId);
368
+ diagnostician = {
369
+ taskId: candidate.taskId,
370
+ status: executed.status,
371
+ ...(executed.message !== undefined ? { message: executed.message.slice(0, 200) } : {}),
372
+ ...(executed.errorCategory !== undefined ? { errorCategory: executed.errorCategory } : {}),
373
+ ...(reuseReviewRequired.length > 0 ? { reuseReviewRequiredCandidateIds: reuseReviewRequired } : {}),
374
+ };
375
+ // The bridge stays cached per workspace (bounded: one per workspace
376
+ // per worker process, exactly like the OpenClaw plugin host) — no
377
+ // per-cycle dispose, so a concurrent cycle can never hit a disposed
378
+ // bridge. The factory self-disposes losing concurrent constructions.
379
+ }
380
+ finally {
381
+ await releaseBridge?.();
382
+ }
351
383
  }
352
384
  else {
353
385
  // No eligible candidate, but a retry_wait task may still be inside
@@ -405,32 +437,55 @@ export async function runCodexWorkspaceWorkerCycle(options) {
405
437
  const resumedTaskIds = new Set();
406
438
  if (backlog.length > 0) {
407
439
  const stateDir = path.join(workspaceDir, '.state');
408
- const bridge = await createPainSignalBridge({
409
- workspaceDir,
410
- stateDir,
411
- ledgerAdapter: new PrincipleTreeLedgerAdapter({ stateDir }),
412
- owner: WORKER_OWNER,
413
- effectiveConfig: config.effective,
414
- getEnvVar: (name) => process.env[name],
415
- // PRI-1265: post-processing resumes see the same authorized
416
- // trajectory context as the initial diagnosis run.
417
- trajectoryTurnReader: createGovernanceTrajectoryTurnReader({ workspaceDir, sourceMaterialAuthorization: createConsentLedgerSourceMaterialAuthorization(workspaceDir) }),
418
- // PRI-1283 R2: latest-consent gate consulted per assembly / model call.
419
- sourceMaterialAuthorization: createConsentLedgerSourceMaterialAuthorization(workspaceDir),
420
- // SPEC §9.6: lazy probe — automatic_hook backlog resumes honor
421
- // the Workspace authorization too.
422
- isAutoPainSubmissionAuthorized: () => isAutomaticPainSubmissionAuthorized(workspaceDir),
423
- });
424
- for (const item of backlog) {
425
- const resumed = await bridge.resumeSucceededDiagnosisPostProcessing({ taskId: item.taskId });
426
- if (resumed.status === 'resumed') {
427
- resumedTaskIds.add(item.taskId);
440
+ let releaseBridge;
441
+ try {
442
+ // SPEC-PD-PIPELINE-SPINE-001 §4.2 (PRI-1292 Phase 2A): same single
443
+ // assembly point as the diagnosis site above — PRI-1265 authorized
444
+ // trajectory context, PRI-1283 R2 latest-consent gate, and the
445
+ // SAME consent-ledger authorization instance for both.
446
+ const hostDeps = resolveWorkspacePipelineHostDeps({
447
+ workspaceDir,
448
+ effectiveConfig: config.effective,
449
+ telemetryPersistenceFailureHandler: (detail) => {
450
+ try {
451
+ emitEvent('CODEX_WORKER_CRITICAL_TELEMETRY_PERSIST_FAILED', detail);
452
+ }
453
+ catch {
454
+ // Telemetry persistence warnings must never fail the worker cycle.
455
+ }
456
+ },
457
+ });
458
+ const bridge = await createPainSignalBridge({
459
+ workspaceDir,
460
+ stateDir,
461
+ ledgerAdapter: new PrincipleTreeLedgerAdapter({ stateDir }),
462
+ owner: WORKER_OWNER,
463
+ effectiveConfig: config.effective,
464
+ getEnvVar: (name) => process.env[name],
465
+ intentDocReader: hostDeps.intentDocReader,
466
+ trajectoryTurnReader: hostDeps.trajectoryTurnReader,
467
+ sourceMaterialAuthorization: hostDeps.sourceMaterialAuthorization,
468
+ // PRI-939 Option A: allowlisted runner/bridge events persist to
469
+ // the workspace sink instead of the unsubscribed singleton.
470
+ telemetrySink: hostDeps.telemetrySink,
471
+ // SPEC §9.6: lazy probe — automatic_hook backlog resumes honor
472
+ // the Workspace authorization too.
473
+ isAutoPainSubmissionAuthorized: hostDeps.isAutoPainSubmissionAuthorized,
474
+ }, (release) => { releaseBridge = release; });
475
+ for (const item of backlog) {
476
+ const resumed = await bridge.resumeSucceededDiagnosisPostProcessing({ taskId: item.taskId });
477
+ if (resumed.status === 'resumed') {
478
+ resumedTaskIds.add(item.taskId);
479
+ }
480
+ else if (resumed.status === 'blocked') {
481
+ blocked.push({ candidateId: item.candidateId, reason: resumed.reason ?? 'blocked' });
482
+ }
483
+ for (const skip of resumed.skipped ?? [])
484
+ blocked.push(skip);
428
485
  }
429
- else if (resumed.status === 'blocked') {
430
- blocked.push({ candidateId: item.candidateId, reason: resumed.reason ?? 'blocked' });
431
- }
432
- for (const skip of resumed.skipped ?? [])
433
- blocked.push(skip);
486
+ }
487
+ finally {
488
+ await releaseBridge?.();
434
489
  }
435
490
  }
436
491
  postProcessing = {
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@principles/codex-adapter",
3
- "version": "0.14.0",
3
+ "version": "0.15.1",
4
4
  "description": "Codex CLI host adapter for Principles Disciple — implements HostAdapter interface for OpenAI Codex CLI's stdin/stdout JSON hook model (ADR-0020).",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -23,5 +23,15 @@ interface AppServices {
23
23
  export declare function initServices(workspaceDir: string): Promise<AppServices>;
24
24
  export declare function closeServices(): Promise<void>;
25
25
  export declare function handleRequest(services: AppServices): (req: http.IncomingMessage, res: http.ServerResponse) => void;
26
- export declare function main(): Promise<void>;
26
+ /** How this process was asked to start; the defaults describe the packaged entry. */
27
+ export interface ConsoleLaunch {
28
+ /** The command line to serve with (`[node, entry, ...flags]`); defaults to this process's own. */
29
+ readonly argv?: readonly string[];
30
+ /**
31
+ * Successor mode (release handover): the predecessor is still releasing the
32
+ * port as this process boots, so "address in use" means "try again", not "stop".
33
+ */
34
+ readonly keepTryingToBind?: boolean;
35
+ }
36
+ export declare function main(launch?: ConsoleLaunch): Promise<void>;
27
37
  export {};
@@ -43,6 +43,8 @@ import { handleUpdateHistoryRoute, handleUpdateHistoryPruneRoute, reconcileUpdat
43
43
  import { handleUpdateTransactionRoute } from './routes/update-transaction.js';
44
44
  import { handleConfigRoute } from './routes/config.js';
45
45
  import { sendJson, sendNotFound, sendError } from './utils/response.js';
46
+ import { activeReleaseRecordPath, getInstallLayoutPathsFromPdHome } from '@principles/install-layout';
47
+ import { consoleIdentityUrl, decideReleaseHandoverWatch, HANDOVER_BIND_WAIT_MS, HANDOVER_HEALTHY_TIMEOUT_MS, HANDOVER_RELISTEN_RETRY_MS, isInstalledConsoleCode, listenWithHandoverRetry, performReleaseHandover, probeConsolePid, startConsoleSuccessor, startReleaseHandoverWatch, stopSuccessor, waitUntilAnswer, } from './release-handover.js';
46
48
  const __filename = fileURLToPath(import.meta.url);
47
49
  const __dirname = path.dirname(__filename);
48
50
  // WEB_ROOT calculation: server is at PKG_ROOT/dist/server/index.js
@@ -681,8 +683,7 @@ export function handleRequest(services) {
681
683
  sendNotFound(res, 'Not found');
682
684
  };
683
685
  }
684
- // ── Server startup ───────────────────────────────────────────────────────────
685
- export async function main() {
686
+ export async function main(launch = {}) {
686
687
  // PRI-872: resolve the PD home BEFORE anything else. Everything below
687
688
  // (registry, update history, backups, gateway probes) derives from it, and a
688
689
  // broken experiment configuration must stop the process here instead of
@@ -703,8 +704,9 @@ export async function main() {
703
704
  }
704
705
  throw error;
705
706
  }
706
- const { workspace, port, host } = parseArgs(process.argv, pdHome.mode);
707
- warnAboutLegacyAuthArgs(process.argv);
707
+ const argv = launch.argv === undefined ? process.argv : [...launch.argv];
708
+ const { workspace, port, host } = parseArgs(argv, pdHome.mode);
709
+ warnAboutLegacyAuthArgs(argv);
708
710
  if (pdHome.mode === 'experiment') {
709
711
  console.log(`[pd-console] Environment: experiment (PD_EXPERIMENT_ROOT=${pdHome.experimentRoot ?? ''})`);
710
712
  console.log(`[pd-console] PD home: ${pdHome.pdHome}`);
@@ -739,24 +741,87 @@ export async function main() {
739
741
  };
740
742
  process.on('SIGTERM', () => { void shutdown('SIGTERM'); });
741
743
  process.on('SIGINT', () => { void shutdown('SIGINT'); });
744
+ const stopAccepting = async () => {
745
+ await new Promise((resolve) => {
746
+ server.close(() => resolve());
747
+ // Keep-alive connections idle in a browser tab must not hold the port
748
+ // hostage; requests still in flight are left to finish, within a bound.
749
+ server.closeIdleConnections();
750
+ setTimeout(resolve, 2000).unref();
751
+ });
752
+ };
753
+ // Release handover: once this process is serving, it must not outlive the
754
+ // release it serves. The watch re-reads the active release record; when an
755
+ // update has replaced it, a successor on the installed code takes this port
756
+ // and this process exits (see release-handover.ts for the safety contract).
757
+ let watchingRelease = false;
758
+ // Only a console that IS the installed one may start "the successor beside
759
+ // this file" and call it the new release; decided once, at boot.
760
+ const handover = decideReleaseHandoverWatch(process.env, isInstalledConsoleCode(path.dirname(__filename), getInstallLayoutPathsFromPdHome(pdHome).consoleDir));
761
+ let handoverOffAnnounced = false;
762
+ /** The successor this process started, for as long as a called-off handover may have to stop it. */
763
+ let successor = null;
742
764
  // PRI-872: a second instance on an occupied port must fail with an
743
765
  // actionable message, not an unhandled 'error' stack. The usual cause is the
744
- // production console already listening on 3100.
745
- server.on('error', (error) => {
746
- if (error.code === 'EADDRINUSE') {
747
- console.error(`[pd-console] Port ${port} is already in use on ${host}.`);
748
- console.error(pdHome.mode === 'production'
749
- ? `[pd-console] Another console is probably serving this installation. Stop it, or pick another port with --port.`
750
- : `[pd-console] Stop the process holding the port, or pass a different --port (the experiment default is ${EXPERIMENT_CONSOLE_PORT}).`);
766
+ // production console already listening on 3100. A handover successor is the
767
+ // one legitimate second instance: it was started before its predecessor let
768
+ // go of the port, so for a bounded time it retries instead of giving up.
769
+ const listener = listenWithHandoverRetry({
770
+ server,
771
+ port,
772
+ host,
773
+ retryInUseForMs: launch.keepTryingToBind === true ? HANDOVER_BIND_WAIT_MS : 0,
774
+ onListening: () => {
775
+ console.log('[pd-console] Listening on http://' + host + ':' + port);
776
+ console.log('[pd-console] Workspace: ' + workspace);
777
+ console.log('[pd-console] Auth: none (local OS session)');
778
+ // rc-9: a console that will NOT hand itself over says so and why — the
779
+ // alternative is an update that quietly ends on "restart required".
780
+ if (!handover.watch) {
781
+ if (!handoverOffAnnounced) {
782
+ handoverOffAnnounced = true;
783
+ console.log(`[pd-console] Release handover off: ${handover.reason}.`);
784
+ }
785
+ return;
786
+ }
787
+ if (watchingRelease)
788
+ return;
789
+ watchingRelease = true;
790
+ startReleaseHandoverWatch({
791
+ recordPath: activeReleaseRecordPath(pdHome.pdHome),
792
+ onSuperseded: () => {
793
+ void performReleaseHandover({
794
+ log: (message) => console.log(message),
795
+ startSuccessor: () => {
796
+ successor = startConsoleSuccessor({ args: argv.slice(2) }, (message) => console.log(message));
797
+ return successor;
798
+ },
799
+ stopAccepting,
800
+ waitForSuccessor: () => waitUntilAnswer(() => probeConsolePid(consoleIdentityUrl(host, port), 1000), HANDOVER_HEALTHY_TIMEOUT_MS),
801
+ // Only the process this one started is ever stopped, and only when
802
+ // it failed to answer: it may be holding the port while it does.
803
+ abandonSuccessor: () => stopSuccessor(successor),
804
+ // A successor that was just stopped may still be letting go of the port.
805
+ resumeAccepting: () => listener.relisten(HANDOVER_RELISTEN_RETRY_MS),
806
+ exit: (code) => {
807
+ void closeServices().finally(() => process.exit(code));
808
+ },
809
+ });
810
+ },
811
+ });
812
+ },
813
+ giveUp: (error) => {
814
+ if (error.code === 'EADDRINUSE') {
815
+ console.error(`[pd-console] Port ${port} is already in use on ${host}.`);
816
+ console.error(pdHome.mode === 'production'
817
+ ? `[pd-console] Another console is probably serving this installation. Stop it, or pick another port with --port.`
818
+ : `[pd-console] Stop the process holding the port, or pass a different --port (the experiment default is ${EXPERIMENT_CONSOLE_PORT}).`);
819
+ }
820
+ else {
821
+ console.error('[pd-console] Server error:', error);
822
+ }
751
823
  process.exit(1);
752
- }
753
- console.error('[pd-console] Server error:', error);
754
- process.exit(1);
755
- });
756
- server.listen(port, host, () => {
757
- console.log('[pd-console] Listening on http://' + host + ':' + port);
758
- console.log('[pd-console] Workspace: ' + workspace);
759
- console.log('[pd-console] Auth: none (local OS session)');
824
+ },
760
825
  });
761
826
  }
762
827
  // cli-7 / PRI-892 precedent: importing this module (a test driving