create-principles-disciple 1.150.2 → 1.150.4

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 (267) hide show
  1. package/_release/product-identity.json +1 -1
  2. package/codex-adapter/dist/ingestion/admission.js +2 -0
  3. package/codex-adapter/dist/pd-hook.d.ts +7 -5
  4. package/codex-adapter/dist/pd-hook.js +18 -7
  5. package/codex-adapter/dist/tool-semantics.js +5 -1
  6. package/codex-adapter/dist/worker/workspace-worker.js +4 -2
  7. package/codex-adapter/package.json +1 -1
  8. package/console/dist/lib/utils.js +16 -1
  9. package/console/dist/web/assets/app.css +147 -46
  10. package/console/dist/web/assets/app.js +35 -32
  11. package/console/package.json +2 -0
  12. package/core/dist/runtime/activation/adaptive-selection-output.d.ts +35 -0
  13. package/core/dist/runtime/activation/adaptive-selection-output.d.ts.map +1 -0
  14. package/core/dist/runtime/activation/adaptive-selection-output.js +38 -0
  15. package/core/dist/runtime/activation/adaptive-selection-output.js.map +1 -0
  16. package/core/dist/runtime/activation-compatibility-read-model.d.ts.map +1 -1
  17. package/core/dist/runtime/activation-compatibility-read-model.js +2 -1
  18. package/core/dist/runtime/activation-compatibility-read-model.js.map +1 -1
  19. package/core/dist/runtime/adapter/artificer-l2-adapter.d.ts.map +1 -1
  20. package/core/dist/runtime/adapter/artificer-l2-adapter.js +89 -27
  21. package/core/dist/runtime/adapter/artificer-l2-adapter.js.map +1 -1
  22. package/core/dist/runtime/adapter/context-budget.d.ts +49 -0
  23. package/core/dist/runtime/adapter/context-budget.d.ts.map +1 -0
  24. package/core/dist/runtime/adapter/context-budget.js +127 -0
  25. package/core/dist/runtime/adapter/context-budget.js.map +1 -0
  26. package/core/dist/runtime/adapter/output-schema-registry.d.ts.map +1 -1
  27. package/core/dist/runtime/adapter/output-schema-registry.js +7 -0
  28. package/core/dist/runtime/adapter/output-schema-registry.js.map +1 -1
  29. package/core/dist/runtime/adapter/pi-ai-runtime-adapter.d.ts +30 -7
  30. package/core/dist/runtime/adapter/pi-ai-runtime-adapter.d.ts.map +1 -1
  31. package/core/dist/runtime/adapter/pi-ai-runtime-adapter.js +559 -211
  32. package/core/dist/runtime/adapter/pi-ai-runtime-adapter.js.map +1 -1
  33. package/core/dist/runtime/candidate-audit.d.ts.map +1 -1
  34. package/core/dist/runtime/candidate-audit.js +2 -1
  35. package/core/dist/runtime/candidate-audit.js.map +1 -1
  36. package/core/dist/runtime/config/pd-config-effective.d.ts.map +1 -1
  37. package/core/dist/runtime/config/pd-config-effective.js +2 -0
  38. package/core/dist/runtime/config/pd-config-effective.js.map +1 -1
  39. package/core/dist/runtime/config/pd-config-types.d.ts +52 -0
  40. package/core/dist/runtime/config/pd-config-types.d.ts.map +1 -1
  41. package/core/dist/runtime/config/pd-config-types.js.map +1 -1
  42. package/core/dist/runtime/config/pd-config-validate.d.ts.map +1 -1
  43. package/core/dist/runtime/config/pd-config-validate.js +134 -0
  44. package/core/dist/runtime/config/pd-config-validate.js.map +1 -1
  45. package/core/dist/runtime/feature-flags/feature-flag-contract.d.ts.map +1 -1
  46. package/core/dist/runtime/feature-flags/feature-flag-contract.js +8 -0
  47. package/core/dist/runtime/feature-flags/feature-flag-contract.js.map +1 -1
  48. package/core/dist/runtime/feature-flags/feature-flag-lifecycle.d.ts.map +1 -1
  49. package/core/dist/runtime/feature-flags/feature-flag-lifecycle.js +24 -0
  50. package/core/dist/runtime/feature-flags/feature-flag-lifecycle.js.map +1 -1
  51. package/core/dist/runtime/index.d.ts +2 -0
  52. package/core/dist/runtime/index.d.ts.map +1 -1
  53. package/core/dist/runtime/index.js +2 -0
  54. package/core/dist/runtime/index.js.map +1 -1
  55. package/core/dist/runtime/internalization/rule-host-input-builder.d.ts +16 -0
  56. package/core/dist/runtime/internalization/rule-host-input-builder.d.ts.map +1 -1
  57. package/core/dist/runtime/internalization/rule-host-input-builder.js +18 -0
  58. package/core/dist/runtime/internalization/rule-host-input-builder.js.map +1 -1
  59. package/core/dist/runtime/internalization/split-diagnostician-runner.d.ts +8 -0
  60. package/core/dist/runtime/internalization/split-diagnostician-runner.d.ts.map +1 -1
  61. package/core/dist/runtime/internalization/split-diagnostician-runner.js +24 -2
  62. package/core/dist/runtime/internalization/split-diagnostician-runner.js.map +1 -1
  63. package/core/dist/runtime/internalization/tool-semantic-registry.d.ts +26 -0
  64. package/core/dist/runtime/internalization/tool-semantic-registry.d.ts.map +1 -1
  65. package/core/dist/runtime/internalization/tool-semantic-registry.js +55 -5
  66. package/core/dist/runtime/internalization/tool-semantic-registry.js.map +1 -1
  67. package/core/dist/runtime/internalization-chain-integrity-read-model.d.ts.map +1 -1
  68. package/core/dist/runtime/internalization-chain-integrity-read-model.js +2 -2
  69. package/core/dist/runtime/internalization-chain-integrity-read-model.js.map +1 -1
  70. package/core/dist/runtime/internalization-integrity-remediation.d.ts.map +1 -1
  71. package/core/dist/runtime/internalization-integrity-remediation.js +2 -2
  72. package/core/dist/runtime/internalization-integrity-remediation.js.map +1 -1
  73. package/core/dist/runtime/operator-health-read-model.d.ts.map +1 -1
  74. package/core/dist/runtime/operator-health-read-model.js +2 -2
  75. package/core/dist/runtime/operator-health-read-model.js.map +1 -1
  76. package/core/dist/runtime/pain-recall-read-model.d.ts.map +1 -1
  77. package/core/dist/runtime/pain-recall-read-model.js +4 -3
  78. package/core/dist/runtime/pain-recall-read-model.js.map +1 -1
  79. package/core/dist/runtime/pruning-read-model.d.ts.map +1 -1
  80. package/core/dist/runtime/pruning-read-model.js +3 -2
  81. package/core/dist/runtime/pruning-read-model.js.map +1 -1
  82. package/core/dist/runtime/risk/risk-calculator-policy.d.ts +12 -2
  83. package/core/dist/runtime/risk/risk-calculator-policy.d.ts.map +1 -1
  84. package/core/dist/runtime/risk/risk-calculator-policy.js +33 -22
  85. package/core/dist/runtime/risk/risk-calculator-policy.js.map +1 -1
  86. package/core/dist/runtime/schema-conformance-read-model.js +2 -2
  87. package/core/dist/runtime/schema-conformance-read-model.js.map +1 -1
  88. package/core/dist/runtime/store/sqlite-connection.d.ts +0 -5
  89. package/core/dist/runtime/store/sqlite-connection.d.ts.map +1 -1
  90. package/core/dist/runtime/store/sqlite-connection.js +4 -12
  91. package/core/dist/runtime/store/sqlite-connection.js.map +1 -1
  92. package/core/dist/runtime/store/storage-paths.d.ts +17 -0
  93. package/core/dist/runtime/store/storage-paths.d.ts.map +1 -0
  94. package/core/dist/runtime/store/storage-paths.js +52 -0
  95. package/core/dist/runtime/store/storage-paths.js.map +1 -0
  96. package/core/dist/runtime/trajectory-retention.d.ts +257 -0
  97. package/core/dist/runtime/trajectory-retention.d.ts.map +1 -0
  98. package/core/dist/runtime/trajectory-retention.js +598 -0
  99. package/core/dist/runtime/trajectory-retention.js.map +1 -0
  100. package/core/dist/telemetry-event.d.ts +2 -2
  101. package/core/dist/telemetry-event.d.ts.map +1 -1
  102. package/core/dist/telemetry-event.js +5 -0
  103. package/core/dist/telemetry-event.js.map +1 -1
  104. package/core/dist/trajectory-store.d.ts +9 -9
  105. package/core/dist/trajectory-store.d.ts.map +1 -1
  106. package/core/dist/trajectory-store.js +9 -12
  107. package/core/dist/trajectory-store.js.map +1 -1
  108. package/core/package.json +1 -1
  109. package/dist/installers/codex-host-installer.d.ts.map +1 -1
  110. package/dist/installers/codex-host-installer.js +92 -5
  111. package/dist/installers/codex-host-installer.js.map +1 -1
  112. package/dist/installers/mcp-binding-shape-mirror.d.ts +27 -0
  113. package/dist/installers/mcp-binding-shape-mirror.d.ts.map +1 -0
  114. package/dist/installers/mcp-binding-shape-mirror.js +105 -0
  115. package/dist/installers/mcp-binding-shape-mirror.js.map +1 -0
  116. package/dist/skill-catalog.d.ts +35 -0
  117. package/dist/skill-catalog.d.ts.map +1 -0
  118. package/dist/skill-catalog.js +85 -0
  119. package/dist/skill-catalog.js.map +1 -0
  120. package/dist/skill-delivery-parity.d.ts +22 -0
  121. package/dist/skill-delivery-parity.d.ts.map +1 -0
  122. package/dist/skill-delivery-parity.js +31 -0
  123. package/dist/skill-delivery-parity.js.map +1 -0
  124. package/host-runtime/dist/active-principle-prompt.d.ts +8 -0
  125. package/host-runtime/dist/active-principle-prompt.js +15 -5
  126. package/host-runtime/dist/adaptive-decision-protocol.d.ts +142 -0
  127. package/host-runtime/dist/adaptive-decision-protocol.js +190 -0
  128. package/host-runtime/dist/adaptive-priority-provider.d.ts +37 -13
  129. package/host-runtime/dist/adaptive-priority-provider.js +65 -62
  130. package/host-runtime/dist/adaptive-selection.d.ts +67 -62
  131. package/host-runtime/dist/adaptive-selection.js +218 -301
  132. package/host-runtime/dist/adaptive-skip-decision.d.ts +26 -14
  133. package/host-runtime/dist/adaptive-skip-decision.js +33 -29
  134. package/host-runtime/dist/codex-rule-context-provider.js +4 -1
  135. package/host-runtime/dist/governance-observation-store.d.ts +40 -1
  136. package/host-runtime/dist/governance-observation-store.js +188 -9
  137. package/host-runtime/dist/governance-signal-admission.d.ts +19 -3
  138. package/host-runtime/dist/governance-signal-admission.js +12 -4
  139. package/host-runtime/dist/host-tool-declaration.d.ts +18 -2
  140. package/host-runtime/dist/host-tool-declaration.js +67 -11
  141. package/host-runtime/dist/host-tool-semantic-resolver.d.ts +7 -0
  142. package/host-runtime/dist/host-tool-semantic-resolver.js +22 -2
  143. package/host-runtime/dist/index.d.ts +3 -0
  144. package/host-runtime/dist/index.js +14 -0
  145. package/host-runtime/dist/production-rulehost-gate.js +36 -4
  146. package/host-runtime/dist/trajectory-retention.d.ts +147 -0
  147. package/host-runtime/dist/trajectory-retention.js +907 -0
  148. package/host-runtime/package.json +1 -1
  149. package/install-layout/dist/index.d.ts +9 -2
  150. package/install-layout/dist/index.js +26 -9
  151. package/install-layout/dist/mcp-binding-contract.d.ts +91 -0
  152. package/install-layout/dist/mcp-binding-contract.js +230 -0
  153. package/install-layout/package.json +1 -1
  154. package/package.json +4 -4
  155. package/pd-cli/dist/commands/build-trajectory-evidence.d.ts.map +1 -1
  156. package/pd-cli/dist/commands/build-trajectory-evidence.js +17 -11
  157. package/pd-cli/dist/commands/build-trajectory-evidence.js.map +1 -1
  158. package/pd-cli/dist/commands/codex-reconcile.d.ts +7 -0
  159. package/pd-cli/dist/commands/codex-reconcile.d.ts.map +1 -1
  160. package/pd-cli/dist/commands/codex-reconcile.js +11 -2
  161. package/pd-cli/dist/commands/codex-reconcile.js.map +1 -1
  162. package/pd-cli/dist/commands/codex-worker.d.ts.map +1 -1
  163. package/pd-cli/dist/commands/codex-worker.js +35 -0
  164. package/pd-cli/dist/commands/codex-worker.js.map +1 -1
  165. package/pd-cli/dist/commands/command-helpers.d.ts +1 -1
  166. package/pd-cli/dist/commands/command-helpers.js +1 -1
  167. package/pd-cli/dist/commands/errors-list.d.ts +1 -1
  168. package/pd-cli/dist/commands/errors-list.js +1 -1
  169. package/pd-cli/dist/commands/health-mcp.d.ts +23 -1
  170. package/pd-cli/dist/commands/health-mcp.d.ts.map +1 -1
  171. package/pd-cli/dist/commands/health-mcp.js +81 -22
  172. package/pd-cli/dist/commands/health-mcp.js.map +1 -1
  173. package/pd-cli/dist/commands/health.d.ts +1 -1
  174. package/pd-cli/dist/commands/health.d.ts.map +1 -1
  175. package/pd-cli/dist/commands/health.js +12 -5
  176. package/pd-cli/dist/commands/health.js.map +1 -1
  177. package/pd-cli/dist/commands/principles-stats.d.ts +1 -1
  178. package/pd-cli/dist/commands/principles-stats.js +1 -1
  179. package/pd-cli/dist/commands/trajectory-retention.d.ts +23 -0
  180. package/pd-cli/dist/commands/trajectory-retention.d.ts.map +1 -0
  181. package/pd-cli/dist/commands/trajectory-retention.js +159 -0
  182. package/pd-cli/dist/commands/trajectory-retention.js.map +1 -0
  183. package/pd-cli/dist/commands/workbuddy-setup.d.ts +69 -0
  184. package/pd-cli/dist/commands/workbuddy-setup.d.ts.map +1 -0
  185. package/pd-cli/dist/commands/workbuddy-setup.js +379 -0
  186. package/pd-cli/dist/commands/workbuddy-setup.js.map +1 -0
  187. package/pd-cli/dist/commands/workbuddy-worker.d.ts.map +1 -1
  188. package/pd-cli/dist/commands/workbuddy-worker.js +42 -6
  189. package/pd-cli/dist/commands/workbuddy-worker.js.map +1 -1
  190. package/pd-cli/dist/index.d.ts +1 -7
  191. package/pd-cli/dist/index.d.ts.map +1 -1
  192. package/pd-cli/dist/index.js +15 -1201
  193. package/pd-cli/dist/index.js.map +1 -1
  194. package/pd-cli/dist/program.d.ts +17 -0
  195. package/pd-cli/dist/program.d.ts.map +1 -0
  196. package/pd-cli/dist/program.js +1263 -0
  197. package/pd-cli/dist/program.js.map +1 -0
  198. package/pd-cli/dist/services/delivery-surfaces.d.ts.map +1 -1
  199. package/pd-cli/dist/services/delivery-surfaces.js +7 -5
  200. package/pd-cli/dist/services/delivery-surfaces.js.map +1 -1
  201. package/pd-cli/dist/services/version-report.d.ts.map +1 -1
  202. package/pd-cli/dist/services/version-report.js +30 -4
  203. package/pd-cli/dist/services/version-report.js.map +1 -1
  204. package/pd-cli/package.json +1 -1
  205. package/pd-mcp-server/dist/version.d.ts +1 -1
  206. package/pd-mcp-server/dist/version.js +1 -1
  207. package/pd-mcp-server/package.json +3 -1
  208. package/plugin/dist/bundle.js +477 -471
  209. package/plugin/dist/constants/tools.d.ts +8 -1
  210. package/plugin/dist/core/trajectory-retention-trigger.d.ts +13 -0
  211. package/plugin/dist/core/trajectory.d.ts +14 -0
  212. package/plugin/dist/hooks/gate-block-helper.d.ts +17 -0
  213. package/plugin/dist/hooks/gate.d.ts +7 -2
  214. package/plugin/dist/host-runtime/openclaw-host-runtime.d.ts +1 -0
  215. package/plugin/dist/index.d.ts +5 -0
  216. package/plugin/dist/openclaw.plugin.json +1 -1
  217. package/plugin/dist/rulehost-evidence.js +29 -23
  218. package/plugin/dist/templates/langs/en/skills/pd-cli-operator/SKILL.md +16 -5
  219. package/plugin/dist/templates/langs/en/skills/pd-control/SKILL.md +7 -6
  220. package/plugin/dist/templates/langs/en/skills/pd-pain-signal/SKILL.md +141 -28
  221. package/plugin/dist/templates/langs/en/skills/pd-review/SKILL.md +15 -1
  222. package/plugin/dist/templates/langs/zh/skills/pd-cli-operator/SKILL.md +16 -5
  223. package/plugin/dist/templates/langs/zh/skills/pd-control/SKILL.md +7 -6
  224. package/plugin/dist/templates/langs/zh/skills/pd-pain-signal/SKILL.md +142 -29
  225. package/plugin/dist/templates/langs/zh/skills/pd-review/SKILL.md +15 -1
  226. package/plugin/openclaw.plugin.json +1 -1
  227. package/plugin/package.json +1 -1
  228. package/plugin/templates/langs/en/skills/pd-cli-operator/SKILL.md +16 -5
  229. package/plugin/templates/langs/en/skills/pd-control/SKILL.md +7 -6
  230. package/plugin/templates/langs/en/skills/pd-pain-signal/SKILL.md +141 -28
  231. package/plugin/templates/langs/en/skills/pd-review/SKILL.md +15 -1
  232. package/plugin/templates/langs/zh/skills/pd-cli-operator/SKILL.md +16 -5
  233. package/plugin/templates/langs/zh/skills/pd-control/SKILL.md +7 -6
  234. package/plugin/templates/langs/zh/skills/pd-pain-signal/SKILL.md +142 -29
  235. package/plugin/templates/langs/zh/skills/pd-review/SKILL.md +15 -1
  236. package/release-manager/dist/installers/codex-host-installer.js +92 -5
  237. package/release-manager/dist/installers/mcp-binding-shape-mirror.js +105 -0
  238. package/release-manager/package.json +1 -1
  239. package/workbuddy-adapter/dist/codec/input-decoder.d.ts +10 -0
  240. package/workbuddy-adapter/dist/codec/input-decoder.js +62 -5
  241. package/workbuddy-adapter/dist/host-adapter.js +1 -0
  242. package/workbuddy-adapter/dist/index.d.ts +1 -0
  243. package/workbuddy-adapter/dist/index.js +1 -0
  244. package/workbuddy-adapter/dist/ingestion/catch-up.d.ts +25 -0
  245. package/workbuddy-adapter/dist/ingestion/catch-up.js +161 -0
  246. package/workbuddy-adapter/dist/ingestion/encode-cwd.d.ts +6 -0
  247. package/workbuddy-adapter/dist/ingestion/encode-cwd.js +39 -0
  248. package/workbuddy-adapter/dist/ingestion/index.d.ts +13 -0
  249. package/workbuddy-adapter/dist/ingestion/index.js +13 -0
  250. package/workbuddy-adapter/dist/ingestion/ingestion.d.ts +46 -0
  251. package/workbuddy-adapter/dist/ingestion/ingestion.js +135 -0
  252. package/workbuddy-adapter/dist/ingestion/transcript-decoder.d.ts +70 -0
  253. package/workbuddy-adapter/dist/ingestion/transcript-decoder.js +554 -0
  254. package/workbuddy-adapter/dist/ingestion/transcript-path.d.ts +39 -0
  255. package/workbuddy-adapter/dist/ingestion/transcript-path.js +117 -0
  256. package/workbuddy-adapter/dist/ingestion/transcript-source.d.ts +15 -0
  257. package/workbuddy-adapter/dist/ingestion/transcript-source.js +152 -0
  258. package/workbuddy-adapter/dist/pd-hook.d.ts +8 -0
  259. package/workbuddy-adapter/dist/pd-hook.js +59 -2
  260. package/workbuddy-adapter/dist/worker/workspace-worker.d.ts +9 -0
  261. package/workbuddy-adapter/dist/worker/workspace-worker.js +46 -17
  262. package/workbuddy-adapter/package.json +1 -1
  263. package/workbuddy-adapter/plugin/hooks/hooks.json +11 -0
  264. package/workbuddy-adapter/plugin/skills/pd-cli-operator/SKILL.md +57 -19
  265. package/workbuddy-adapter/plugin/skills/pd-control/SKILL.md +21 -9
  266. package/workbuddy-adapter/plugin/skills/pd-pain-signal/SKILL.md +72 -61
  267. package/workbuddy-adapter/plugin/skills/pd-review/SKILL.md +27 -12
@@ -0,0 +1,1263 @@
1
+ /**
2
+ * pd CLI — Principles Disciple command-line interface.
3
+ *
4
+ * Usage:
5
+ * pd pain record --reason <text> [--score N] [--source manual]
6
+ */
7
+ import { Command, Option } from 'commander';
8
+ import { handlePainRecord } from './commands/pain-record.js';
9
+ import { handlePainExplicit } from './commands/pain-explicit.js';
10
+ import { registerPainRetryCommand } from './commands/pain-retry.js';
11
+ import { handlePainRecall, parsePainRecallLimit } from './commands/pain-recall.js';
12
+ import { handlePainEvidence } from './commands/pain-evidence.js';
13
+ import { handlePainList } from './commands/pain-list.js';
14
+ import { handleSamplesList } from './commands/samples-list.js';
15
+ import { handleSamplesReview } from './commands/samples-review.js';
16
+ import { handleEvolutionTasksList } from './commands/evolution-tasks-list.js';
17
+ import { handleEvolutionTasksShow } from './commands/evolution-tasks-show.js';
18
+ import { registerHealthCommand } from './commands/health.js';
19
+ import { registerVersionCommand } from './commands/version.js';
20
+ import { buildVersionReport, formatShortVersion, VersionReportError } from './services/version-report.js';
21
+ import { handleTaskShow, registerTaskListCommand } from './commands/task.js';
22
+ import { handleRunList, handleRunShow } from './commands/run.js';
23
+ import { handleTrajectoryLocate } from './commands/trajectory.js';
24
+ import { handleTrajectoryMaintain, handleTrajectoryRetentionStatus, handleTrajectoryVacuum, } from './commands/trajectory-retention.js';
25
+ import { handleHistoryQuery } from './commands/history.js';
26
+ import { handleContextBuild } from './commands/context.js';
27
+ import { handleLegacyImportOpenClaw } from './commands/legacy-import.js';
28
+ import { handleLegacyCleanup } from './commands/legacy-cleanup.js';
29
+ import { handleDiagnoseStatus, handleDiagnoseRun } from './commands/diagnose.js';
30
+ import { registerRuntimeProbeCommand } from './commands/runtime.js';
31
+ import { handleFlowShow } from './commands/flow.js';
32
+ import { handleTraceShow } from './commands/trace.js';
33
+ import { handlePruningReport, handlePruningExplain, handlePruningOrphans } from './commands/runtime-pruning.js';
34
+ import { handleRuntimeHealthSnapshot } from './commands/runtime-health-snapshot.js';
35
+ import { handleRuntimeUat } from './commands/runtime-uat.js';
36
+ import { handleRuntimeInternalizationQueue } from './commands/runtime-internalization-queue.js';
37
+ import { handleRuntimeInternalizationWakeOnce } from './commands/runtime-internalization-wake-once.js';
38
+ import { handleRuntimeInternalizationRunOnce } from './commands/runtime-internalization-run-once.js';
39
+ import { handleRuntimeInternalizationRetry } from './commands/runtime-internalization-retry.js';
40
+ import { registerRuntimeInternalizationAuditArtificerEvidenceCommand } from './commands/runtime-internalization-audit-artificer-evidence.js';
41
+ import { registerRuntimeInternalizationEvidenceCommand } from './commands/runtime-internalization-evidence.js';
42
+ import { registerRunRuleHostCommand } from './commands/runtime-internalization-run-rulehost.js';
43
+ import { handleCandidateList, handleCandidateShow, handleCandidateIntake, handleCandidateReview, handleCandidateAudit, handleCandidateRepair, handleCandidateRoute, handleCandidateInternalize, handleCandidateInternalizationBackfill } from './commands/candidate.js';
44
+ import { handleArtifactShow } from './commands/artifact.js';
45
+ import { handleRuntimeCanary } from './commands/runtime-canary.js';
46
+ import { handleRuntimeSyntheticBaseline } from './commands/runtime-synthetic-baseline.js';
47
+ import { handleRuntimePainFlood } from './commands/runtime-pain-flood-simulation.js';
48
+ import { handleRuntimeInternalizationIntegrity } from './commands/runtime-internalization-integrity.js';
49
+ import { handleRuntimeInternalizationIntegrityRepair } from './commands/runtime-internalization-integrity-repair.js';
50
+ import { handleRuntimeInternalizationEnqueueSuccessors } from './commands/runtime-internalization-enqueue-successors.js';
51
+ import { handleRuntimeDiagnosticsExport } from './commands/runtime-diagnostics-export.js';
52
+ import { handleMcpLogsExport } from './commands/mcp-logs-export.js';
53
+ import { registerRuntimeCompatibilityScanCommand } from './commands/runtime-compatibility-scan.js';
54
+ import { handleRuntimeRecoverySweep } from './commands/runtime-recovery.js';
55
+ import { handleRuntimeRecoveryFailedTasks } from './commands/runtime-recovery-failed-tasks.js';
56
+ import { registerRuntimeRecoveryFailedTaskCommand } from './commands/runtime-recovery-failed-task.js';
57
+ import { handleRuntimeArtifactRepair } from './commands/runtime-artifact-repair.js';
58
+ import { handleRuntimeActivationDeactivate, handleRuntimeActivationList, handleRuntimeActivationEdit, registerRuntimeActivationPromoteCommand, registerRuntimeActivationDeactivateCommand, registerRuntimeActivationListCommand, registerRuntimeActivationJournalCommand, registerRuntimeActivationLinkCommand, registerRuntimeActivationDispatchCommand, registerRuntimeActivationApproveCommand, } from './commands/runtime-activation.js';
59
+ import { handleProvenChannelBaseline } from './commands/proven-channel-baseline.js';
60
+ import { handleDemoStoryA } from './commands/demo-story-a.js';
61
+ import { handleRuntimeFeaturesStatus } from './commands/runtime-features.js';
62
+ import { handleConfigDoctor } from './commands/config-doctor.js';
63
+ import { registerMvpCommands } from './commands/mvp-smoke.js';
64
+ import { registerRulecodeCommand } from './commands/rulecode.js';
65
+ import { registerIntentCommand } from './commands/intent.js';
66
+ import { registerErrorsListCommand } from './commands/errors-list.js';
67
+ import { registerPrinciplesCommand } from './commands/principles-stats.js';
68
+ import { registerTelemetryCommand } from './commands/telemetry.js';
69
+ import { createRequire } from 'module';
70
+ const require = createRequire(import.meta.url);
71
+ const pkg = require('../package.json');
72
+ export const program = new Command();
73
+ // SPEC §12: `pd --version` prints the canonical product version when a
74
+ // supported installation exists; a development checkout falls back to the
75
+ // CLI package version with an explicit marker instead of impersonating an
76
+ // installed release.
77
+ export function handleVersionFlag(args) {
78
+ if (!args.includes('--version') && !args.includes('-V'))
79
+ return false;
80
+ try {
81
+ console.log(formatShortVersion(buildVersionReport()));
82
+ return true;
83
+ }
84
+ catch (error) {
85
+ if (error instanceof VersionReportError && error.reason === 'not_installed') {
86
+ console.log(`Principles Disciple ${pkg.version} (development-checkout)`);
87
+ return true;
88
+ }
89
+ if (error instanceof VersionReportError) {
90
+ console.error(error.message);
91
+ console.error(`Next: ${error.nextAction}`);
92
+ process.exitCode = 1;
93
+ return true;
94
+ }
95
+ throw error;
96
+ }
97
+ }
98
+ program
99
+ .name('pd')
100
+ .description('PD CLI — Pain recording, sample management, and evolution task history')
101
+ .option('-V, --version', 'output the canonical PD product version')
102
+ .enablePositionalOptions();
103
+ registerVersionCommand(program);
104
+ const painCmd = program
105
+ .command('pain')
106
+ .description('Pain signal management');
107
+ painCmd
108
+ .command('record')
109
+ .description('Record a pain signal via Runtime v2 bridge')
110
+ .option('-r, --reason <text>', 'Reason for the pain signal (required)')
111
+ .option('-s, --score <number>', 'Pain score 0-100', parseInt)
112
+ .option('-S, --source <text>', 'Source of the pain signal', 'manual')
113
+ .option('-w, --workspace <path>', 'Workspace directory')
114
+ .option('--session <id>', 'Session ID to bind (validated against this workspace\'s trajectory.db; without it the record is unbound: no trajectory evidence, candidates likely gated by the admission threshold)')
115
+ .option('--host <kind>', 'PRI-743: explicit host attribution (openclaw | codex). openclaw = default attribution without the disclosure warning; codex requires the real Codex lineage (--rollout-id, --host-turn-id, and --session as the root session).', undefined)
116
+ .option('--rollout-id <id>', 'PRI-743: Codex rollout identity — required by --host codex', undefined)
117
+ .option('--host-turn-id <id>', 'PRI-743: Codex turn id — required by --host codex', undefined)
118
+ .option('--logical-key <key>', 'PRI-743: Codex logical observation key override for --host codex (default: codex|<rollout-id>|<host-turn-id>|user)', undefined)
119
+ .option('--owner-statement <text>', 'SPEC-CODEX-PAIN-CLOSURE-001 CR-02: the Owner verbatim statement (explicit submission, max 500 chars, rejected when longer — never truncated). It satisfies only the empty-input-evidence admission condition and is disclosed as an unverified owner_statement.', undefined)
120
+ .option('--wait', 'Wait for diagnosis to complete (sync mode, overrides async flag)')
121
+ .option('--json', 'Output raw JSON')
122
+ .action(async (opts) => {
123
+ await handlePainRecord(opts);
124
+ });
125
+ painCmd
126
+ .command('explicit')
127
+ .description('Register an explicit Owner pain statement from the live Codex turn context (agent-assisted, no prefix; same admission chain as PD记录痛苦: — takes no lineage flags)')
128
+ .option('--statement <text>', 'Owner verbatim statement (1-500 chars, required; rejected when longer — never truncated)')
129
+ .option('-w, --workspace <path>', 'Workspace directory')
130
+ .option('--json', 'Output raw JSON')
131
+ .action(async (opts) => {
132
+ await handlePainExplicit(opts);
133
+ });
134
+ registerPainRetryCommand(painCmd);
135
+ painCmd
136
+ .command('list')
137
+ .description('List canonical pain events with host attribution (PRI-640)')
138
+ .option('-w, --workspace <path>', 'Workspace directory')
139
+ .option('-l, --limit <number>', 'Max entries to show (default: 20)', parseInt)
140
+ .option('--host <kind>', 'Filter by host: openclaw | codex | workbuddy | unknown')
141
+ .option('--json', 'Output raw JSON')
142
+ .action(async (opts) => {
143
+ await handlePainList(opts);
144
+ });
145
+ painCmd
146
+ .command('evidence')
147
+ .description('Show recent TRIGGER_DECISION log entries — pain admission gate decisions only (PEAT-B2)')
148
+ .option('-w, --workspace <path>', 'Workspace directory')
149
+ .option('-l, --limit <number>', 'Max entries to show (default: 20)', parseInt)
150
+ .option('--json', 'Output raw JSON')
151
+ .action(async (opts) => {
152
+ await handlePainEvidence(opts);
153
+ });
154
+ // SPEC-PD-PAIN-RECALL-CLI-001: on-demand, read-only recall of the historical
155
+ // pains a principle verifiably derives from. Uses .option() (not
156
+ // .requiredOption()) so missing-flag errors produce structured JSON via the
157
+ // handler (same convention as activation edit, P2 #5).
158
+ painCmd
159
+ .command('recall')
160
+ .description('Recall historical pains verifiably associated with a principle (read-only)')
161
+ .option('--principle-id <id>', 'Canonical ledger principle id (required)')
162
+ .option('--pain-id <id>', 'Filter to one pain within this principle\'s verified associations')
163
+ .option('--context <text>', 'Current question — deterministic local re-ranking only, never creates associations')
164
+ // Strict integer parser (SPEC §3.3): non-integers become NaN and are
165
+ // rejected by the handler; never `parseInt` — Commander passes the previous
166
+ // option value as the parser's second argument, which parseInt would treat
167
+ // as a radix on repeated flags.
168
+ .option('-l, --limit <n>', 'Max results (default 3, 1-10)', parsePainRecallLimit)
169
+ .option('-w, --workspace <path>', 'Workspace directory')
170
+ .option('--json', 'Output raw JSON')
171
+ .action(async (opts) => {
172
+ await handlePainRecall(opts);
173
+ });
174
+ const samplesCmd = program
175
+ .command('samples', { hidden: true })
176
+ .description('Correction sample management');
177
+ samplesCmd
178
+ .command('list')
179
+ .description('List correction samples')
180
+ .option('-s, --status <pending|approved|rejected>', 'Filter by review status', 'pending')
181
+ .action(async (opts) => {
182
+ await handleSamplesList(opts);
183
+ });
184
+ samplesCmd
185
+ .command('review')
186
+ .description('Review a correction sample')
187
+ .argument('<sample-id>', 'The sample ID to review')
188
+ .argument('<approve|reject>', 'Review decision')
189
+ .argument('[note]', 'Optional review note')
190
+ .action(async (sampleId, decision, note) => {
191
+ if (decision !== 'approve' && decision !== 'reject') {
192
+ console.error('Error: decision must be "approve" or "reject"');
193
+ process.exit(1);
194
+ }
195
+ await handleSamplesReview({ sampleId, decision: decision === 'approve' ? 'approved' : 'rejected', note });
196
+ });
197
+ // ── Evolution task reader (hidden) ────────────────────────────────────────────
198
+ // PRI-752 review: the worker is gone (flag retired to `gone`), but this
199
+ // read-only surface stays for historical `evolution_tasks` rows in already-
200
+ // provisioned workspaces — data-retention disposition is a separate Owner
201
+ // decision (PRI-737 reality audit §7.3). Table schema + quality-scorecard
202
+ // reader are retained accordingly.
203
+ const evolutionCmd = program
204
+ .command('evolution', { hidden: true })
205
+ .description('Evolution task management (historical data reader)');
206
+ const tasksCmd = evolutionCmd
207
+ .command('tasks')
208
+ .description('List and show evolution tasks');
209
+ tasksCmd
210
+ .command('list')
211
+ .description('List evolution tasks')
212
+ .option('-s, --status <status>', 'Filter by status (pending|in_progress|completed|all)', 'all')
213
+ .option('-l, --limit <number>', 'Maximum tasks to return', parseInt, 50)
214
+ .option('-f, --date-from <date>', 'Filter tasks created on or after this date')
215
+ .option('-t, --date-to <date>', 'Filter tasks created on or before this date')
216
+ .action(async (opts) => {
217
+ await handleEvolutionTasksList(opts);
218
+ });
219
+ tasksCmd
220
+ .command('show')
221
+ .description('Show full details for an evolution task')
222
+ .argument('<id>', 'Task ID (numeric or string taskId)')
223
+ .action(async (id, _opts) => {
224
+ await handleEvolutionTasksShow({ id });
225
+ });
226
+ registerHealthCommand(program);
227
+ // ── Anonymous Product Telemetry v1 control plane (PRI-595~603) ────────────────
228
+ registerTelemetryCommand(program);
229
+ // ── Runtime v2 task/run commands ──────────────────────────────────────────────鈹€鈹€鈹€鈹€鈹€鈹€
230
+ const rtTaskCmd = program
231
+ .command('task')
232
+ .description('Runtime v2 task inspection');
233
+ registerTaskListCommand(rtTaskCmd);
234
+ rtTaskCmd
235
+ .command('show <taskId>')
236
+ .description('Show detailed task information')
237
+ .option('-w, --workspace <path>', 'Workspace directory')
238
+ .option('--json', 'Output raw JSON')
239
+ .action(async (taskId, opts) => {
240
+ await handleTaskShow({ id: taskId, json: opts.json, workspace: opts.workspace });
241
+ });
242
+ const rtRunCmd = program
243
+ .command('run', { hidden: true })
244
+ .description('Runtime v2 run inspection');
245
+ rtRunCmd
246
+ .command('list <taskId>')
247
+ .description('List all runs for a task')
248
+ .option('-w, --workspace <path>', 'Workspace directory')
249
+ .action(async (taskId, opts) => {
250
+ await handleRunList({ taskId, workspace: opts.workspace });
251
+ });
252
+ rtRunCmd
253
+ .command('show <runId>')
254
+ .description('Show detailed run information')
255
+ .option('-w, --workspace <path>', 'Workspace directory')
256
+ .action(async (runId, opts) => {
257
+ await handleRunShow({ id: runId, workspace: opts.workspace });
258
+ });
259
+ // ── Runtime v2 trajectory/history/context commands ────────────────────────────鈹€鈹€
260
+ const trajectoryCmd = program
261
+ .command('trajectory', { hidden: true })
262
+ .description('Runtime v2 trajectory location');
263
+ trajectoryCmd
264
+ .command('locate')
265
+ .description('Locate a trajectory by task ID, run ID, or time range')
266
+ .option('-t, --task <taskId>', 'Locate by task ID')
267
+ .option('-r, --run <runId>', 'Locate by run ID')
268
+ .option('--from <date>', 'Start of time range (ISO string)')
269
+ .option('--to <date>', 'End of time range (ISO string)')
270
+ .option('-w, --workspace <path>', 'Workspace directory')
271
+ .option('--json', 'Output raw JSON')
272
+ .action(async (opts) => {
273
+ await handleTrajectoryLocate(opts);
274
+ });
275
+ // SPEC-PD-TR-001 — bounded trajectory retention (never scheduled from a hook).
276
+ trajectoryCmd
277
+ .command('maintain')
278
+ .description('Run one trajectory retention sweep now (fallback for workspaces without a running worker)')
279
+ .option('-w, --workspace <path>', 'Workspace directory')
280
+ .option('--json', 'Output raw JSON')
281
+ .action(async (opts) => {
282
+ await handleTrajectoryMaintain(opts);
283
+ });
284
+ const retentionCmd = trajectoryCmd
285
+ .command('retention')
286
+ .description('Trajectory retention status');
287
+ retentionCmd
288
+ .command('status')
289
+ .description('Show the retention policy, marker and currently expired row counts (read-only)')
290
+ .option('-w, --workspace <path>', 'Workspace directory')
291
+ .option('--json', 'Output raw JSON')
292
+ .action(async (opts) => {
293
+ await handleTrajectoryRetentionStatus(opts);
294
+ });
295
+ trajectoryCmd
296
+ .command('vacuum')
297
+ .description('Reclaim disk space (explicit only; dry run unless --yes)')
298
+ .option('-w, --workspace <path>', 'Workspace directory')
299
+ .option('--yes', 'Actually run VACUUM (requires 2 x file size + 10% free space)')
300
+ .option('--json', 'Output raw JSON')
301
+ .action(async (opts) => {
302
+ await handleTrajectoryVacuum(opts);
303
+ });
304
+ const historyCmd = program
305
+ .command('history', { hidden: true })
306
+ .description('Runtime v2 history query');
307
+ historyCmd
308
+ .command('query <taskId>')
309
+ .description('Query run history for a task')
310
+ .option('-l, --limit <number>', 'Limit number of entries', parseInt)
311
+ .option('-c, --cursor <cursor>', 'Pagination cursor')
312
+ .option('--from <date>', 'Start of time range (ISO string)')
313
+ .option('--to <date>', 'End of time range (ISO string)')
314
+ .option('-w, --workspace <path>', 'Workspace directory')
315
+ .option('--json', 'Output raw JSON')
316
+ .action(async (taskId, opts) => {
317
+ await handleHistoryQuery(taskId, opts);
318
+ });
319
+ const contextCmd = program
320
+ .command('context', { hidden: true })
321
+ .description('Runtime v2 context assembly');
322
+ contextCmd
323
+ .command('build <taskId>')
324
+ .description('Assemble diagnostician context for a task')
325
+ .option('-w, --workspace <path>', 'Workspace directory')
326
+ .option('--json', 'Output raw JSON')
327
+ .action(async (taskId, opts) => {
328
+ await handleContextBuild(taskId, opts);
329
+ });
330
+ // ── Legacy import command ──────────────────────────────────────────────────────鈹€鈹€鈹€鈹€鈹€鈹€鈹€
331
+ const legacyCmd = program
332
+ .command('legacy', { hidden: true })
333
+ .description('Legacy data management (import and cleanup)');
334
+ const importCmd = legacyCmd.command('import');
335
+ importCmd
336
+ .command('openclaw')
337
+ .description('Import OpenClaw legacy data into PD Runtime v2 SQLite. ' +
338
+ 'Run this once per workspace before using trajectory/history/context commands.')
339
+ .option('-w, --workspace <path>', 'Workspace directory (required)')
340
+ .option('--json', 'Output raw JSON')
341
+ .action(async (opts) => {
342
+ await handleLegacyImportOpenClaw(opts);
343
+ });
344
+ // ── Diagnostician run/status commands ─────────────────────────────────────────鈹€鈹€鈹€鈹€
345
+ const diagnoseCmd = program
346
+ .command('diagnose')
347
+ .description('Diagnostician execution and status inspection');
348
+ diagnoseCmd
349
+ .command('status')
350
+ .description('Inspect diagnostician task status')
351
+ .requiredOption('-t, --task-id <taskId>', 'Task ID to inspect')
352
+ .option('-w, --workspace <path>', 'Workspace directory')
353
+ .option('--stalled-threshold <seconds>', 'Age threshold in seconds for classifying task as stalled')
354
+ .option('--json', 'Output raw JSON')
355
+ .action(async (opts) => {
356
+ await handleDiagnoseStatus(opts);
357
+ });
358
+ diagnoseCmd
359
+ .command('run')
360
+ .description('Execute diagnostician runner for a task')
361
+ .requiredOption('-t, --task-id <taskId>', 'Task ID to execute')
362
+ .option('-w, --workspace <path>', 'Workspace directory')
363
+ .option('-r, --runtime <kind>', "Runtime kind: 'pi-ai', 'test-double'. If omitted, resolved from .pd/config.yaml; refuses if no binding (no test-double default).")
364
+ .option('--provider <name>', 'LLM provider (e.g., openrouter) — for pi-ai, falls back to policy')
365
+ .option('--model <id>', 'Model ID (e.g., anthropic/claude-sonnet-4) — for pi-ai, falls back to policy')
366
+ .option('--apiKeyEnv <name>', 'Env var name for API key — for pi-ai, falls back to policy')
367
+ .option('--baseUrl <url>', 'Custom base URL — for pi-ai, falls back to policy')
368
+ .option('--maxRetries <n>', 'Max retry attempts for LLM failures — for pi-ai, falls back to policy', parseInt)
369
+ .option('--timeoutMs <ms>', 'Timeout in milliseconds — for pi-ai, falls back to policy', parseInt)
370
+ .option('--no-intake', 'Skip candidate intake after successful diagnosis')
371
+ .option('--preflight', 'Read-only check that a run would be accepted (no lease, no state write, no model call)')
372
+ .option('--json', 'Output raw JSON')
373
+ .action(async (opts) => {
374
+ await handleDiagnoseRun(opts);
375
+ });
376
+ // ── Runtime probe command (HG-01 HARD GATE) ───────────────────────────────────鈹€鈹€鈹€鈹€
377
+ const runtimeCmd = program
378
+ .command('runtime')
379
+ .description('Runtime inspection and health checks');
380
+ runtimeCmd
381
+ .command('canary', { hidden: true })
382
+ .description('One-shot control plane health canary')
383
+ .option('-w, --workspace <path>', 'Workspace directory')
384
+ .option('--json', 'Output raw JSON')
385
+ .action(async (opts) => {
386
+ await handleRuntimeCanary({ workspace: opts.workspace, json: opts.json });
387
+ });
388
+ // pd runtime init — Initialize all PD SQLite databases for a workspace.
389
+ // Lazy import: avoids loading `principles-disciple` at module init time, which
390
+ // would crash `pd --version` in packaged installs where the plugin's transitive
391
+ // deps are not resolvable from pd-cli's node_modules. The import only executes
392
+ // when `pd runtime init` is actually invoked.
393
+ runtimeCmd
394
+ .command('init')
395
+ .description('Initialize all PD SQLite databases (state.db, trajectory.db)')
396
+ .option('-w, --workspace <path>', 'Workspace directory')
397
+ .option('--dry-run', 'Show what would be initialized without writing (default)')
398
+ .option('--confirm', 'Actually initialize the databases (required to write)')
399
+ .option('--json', 'Output raw JSON')
400
+ .action(async (opts) => {
401
+ const { handleRuntimeInit } = await import('./commands/runtime-init.js');
402
+ await handleRuntimeInit({
403
+ workspace: opts.workspace,
404
+ dryRun: opts.dryRun === true,
405
+ confirm: opts.confirm === true,
406
+ json: opts.json === true,
407
+ });
408
+ });
409
+ registerRuntimeCompatibilityScanCommand(runtimeCmd);
410
+ const synthCmd = runtimeCmd
411
+ .command('synthetic', { hidden: true })
412
+ .description('Synthetic workload baseline commands');
413
+ synthCmd
414
+ .command('baseline')
415
+ .description('Run synthetic PD workload baseline (PRI-206) — deterministic, no LLM required')
416
+ .option('-w, --workspace <path>', 'Workspace directory (default: temp workspace)')
417
+ .option('--json', 'Output raw JSON')
418
+ .action(async (opts) => {
419
+ await handleRuntimeSyntheticBaseline({ workspace: opts.workspace, json: opts.json });
420
+ });
421
+ synthCmd
422
+ .command('flood')
423
+ .description('Run pain flood simulation (PRI-208) — deterministic dedup/stress test, no LLM required')
424
+ .option('-w, --workspace <path>', 'Workspace directory (default: temp workspace)')
425
+ .option('--json', 'Output raw JSON')
426
+ .option('--identical-count <n>', 'Number of identical pain signals (default: 10)', parseInt)
427
+ .option('--similar-count <n>', 'Number of similar pain signals (default: 10)', parseInt)
428
+ .option('--stress-count <n>', 'Number of stress test pain signals (default: 50)', parseInt)
429
+ .action(async (opts) => {
430
+ await handleRuntimePainFlood({
431
+ workspace: opts.workspace,
432
+ json: opts.json,
433
+ identicalCount: opts.identicalCount,
434
+ similarCount: opts.similarCount,
435
+ stressCount: opts.stressCount,
436
+ });
437
+ });
438
+ synthCmd
439
+ .command('proven-channel')
440
+ .description('Run MVP activation continuity baseline (PRI-240) — deterministic, no LLM required')
441
+ .option('-w, --workspace <path>', 'Workspace directory (default: temp workspace)')
442
+ .option('--json', 'Output raw JSON')
443
+ .option('--channels <channels>', 'Comma-separated channel list (prompt,code_tool_hook,defer_archive)')
444
+ .action(async (opts) => {
445
+ await handleProvenChannelBaseline({
446
+ workspace: opts.workspace,
447
+ json: opts.json,
448
+ channels: opts.channels,
449
+ });
450
+ });
451
+ runtimeCmd
452
+ .command('features')
453
+ .description('Show feature flag status (PRI-239)')
454
+ .option('-w, --workspace <path>', 'Workspace directory')
455
+ .option('--json', 'Output raw JSON')
456
+ .action(async (opts) => {
457
+ await handleRuntimeFeaturesStatus({
458
+ workspace: opts.workspace,
459
+ json: opts.json,
460
+ });
461
+ });
462
+ // ── PRI-455: Promoted owner commands (trace + activation) ────────────────────
463
+ // These are promoted from runtime subcommands to top-level for discoverability.
464
+ // The old paths (pd runtime trace show, pd runtime activation list) remain as
465
+ // hidden aliases — they still work but are not shown in --help.
466
+ const traceTopCmd = program
467
+ .command('trace')
468
+ .description('Trace full pain-to-ledger chain (Story A\' Step 6: Observe)');
469
+ traceTopCmd
470
+ .command('show')
471
+ .description('Show full trace for a pain ID')
472
+ .requiredOption('--pain-id <id>', 'Pain ID to trace')
473
+ .option('-w, --workspace <path>', 'Workspace directory')
474
+ .option('--json', 'Output raw JSON')
475
+ .action(async (opts) => {
476
+ await handleTraceShow({ painId: opts.painId, workspace: opts.workspace, json: opts.json });
477
+ });
478
+ const activationTopCmd = program
479
+ .command('activation')
480
+ .description('Activation management — list active activations, deactivate (Story A\' Steps 5-6)');
481
+ registerRuntimeActivationListCommand(activationTopCmd);
482
+ // PRI-1109: read-only journal reconciliation (no writes, no model runs).
483
+ registerRuntimeActivationJournalCommand(activationTopCmd);
484
+ // PRI-1114: read-only behavior evidence linkage (no writes, no model runs).
485
+ registerRuntimeActivationLinkCommand(activationTopCmd);
486
+ registerRuntimeActivationDeactivateCommand(activationTopCmd);
487
+ // Bug-M fix: CLI closed loop — approve a pending approval and dispatch its activation.
488
+ // Reuses the same ApprovalQueue + ApprovalCompletionService as the Console model.
489
+ registerRuntimeActivationApproveCommand(activationTopCmd);
490
+ registerRuntimeActivationPromoteCommand(activationTopCmd);
491
+ const configCmd = program
492
+ .command('config')
493
+ .description('PD configuration discovery and diagnosis');
494
+ configCmd
495
+ .command('doctor')
496
+ .description('Show PD + OpenClaw config locations, feature flags, and provider connectivity (PRI-299)')
497
+ .option('-w, --workspace <path>', 'Workspace directory')
498
+ .option('--json', 'Output raw JSON')
499
+ .action(async (opts) => {
500
+ await handleConfigDoctor({ workspace: opts.workspace, json: opts.json });
501
+ });
502
+ const demoCmd = program
503
+ .command('demo', { hidden: true })
504
+ .description('Demo scenarios for MVP validation');
505
+ demoCmd
506
+ .command('story-a')
507
+ .alias('first-principle')
508
+ .description('Run Story A\'s proven-channel demo (PRI-246) — full evidence→proposal→approval→activation→observation chain')
509
+ .option('-w, --workspace <path>', 'Workspace directory (default: temp workspace)')
510
+ .option('--json', 'Output raw JSON')
511
+ .option('--channels <channels>', 'Comma-separated channel list (prompt,code_tool_hook,defer_archive)')
512
+ .option('--allow-demo-write-to-existing-workspace', 'Developer override: permit writing demo artifacts into a workspace that already contains PD state (demo isolation guard)')
513
+ .action(async (opts) => {
514
+ await handleDemoStoryA({
515
+ workspace: opts.workspace,
516
+ json: opts.json,
517
+ channels: opts.channels,
518
+ allowDemoWriteToExistingWorkspace: opts.allowDemoWriteToExistingWorkspace === true,
519
+ });
520
+ });
521
+ registerRuntimeProbeCommand(runtimeCmd);
522
+ const flowCmd = runtimeCmd
523
+ .command('flow', { hidden: true })
524
+ .description('Workflow funnel inspection');
525
+ flowCmd
526
+ .command('show')
527
+ .description('Show all workflow funnel definitions from workflows.yaml')
528
+ .option('-w, --workspace <path>', 'Workspace directory')
529
+ .option('--json', 'Output raw JSON')
530
+ .action(async (opts) => {
531
+ await handleFlowShow(opts);
532
+ });
533
+ const traceCmd = runtimeCmd
534
+ .command('trace', { hidden: true })
535
+ .description('Trace full pain-to-ledger chain (hidden alias — use pd trace show)');
536
+ traceCmd
537
+ .command('show')
538
+ .description('Show full trace for a pain ID')
539
+ .requiredOption('--pain-id <id>', 'Pain ID to trace')
540
+ .option('-w, --workspace <path>', 'Workspace directory')
541
+ .option('--json', 'Output raw JSON')
542
+ .action(async (opts) => {
543
+ await handleTraceShow({ painId: opts.painId, workspace: opts.workspace, json: opts.json });
544
+ });
545
+ runtimeCmd
546
+ .command('uat', { hidden: true })
547
+ .description('Runtime V2 chain UAT baseline runner')
548
+ .option('-w, --workspace <path>', 'Workspace directory')
549
+ .option('--count <n>', 'Number of iterations (default: 5, max: 50)', parseInt)
550
+ .option('--min-success-rate <rate>', 'Minimum success rate threshold (default: 1.0)', parseFloat)
551
+ .option('--json', 'Output machine-readable JSON summary')
552
+ .option('--allow-production-workspace-for-uat', 'DANGEROUS: Allow UAT to write to production workspace (NOT RECOMMENDED)')
553
+ .action(async (opts) => {
554
+ await handleRuntimeUat({
555
+ workspace: opts.workspace,
556
+ count: opts.count,
557
+ minSuccessRate: opts.minSuccessRate,
558
+ json: opts.json,
559
+ allowProductionWorkspaceForUat: opts.allowProductionWorkspaceForUat,
560
+ });
561
+ });
562
+ const runtimeHealthCmd = runtimeCmd
563
+ .command('health', { hidden: true })
564
+ .description('Runtime V2 health inspection');
565
+ runtimeHealthCmd
566
+ .command('snapshot')
567
+ .description('Operator health snapshot combining chain, ledger, and pruning status')
568
+ .option('-w, --workspace <path>', 'Workspace directory')
569
+ .option('--json', 'Output raw JSON')
570
+ .action(async (opts) => {
571
+ await handleRuntimeHealthSnapshot({ workspace: opts.workspace, json: opts.json });
572
+ });
573
+ // ── pd codex reconcile — Codex governance continuation recovery ───────────────
574
+ // Codex Governance Closure Slice B (PRI-623, SPEC §13/§20): runs the idempotent
575
+ // cross-store reconciliation pass (admitted pain → missing Diagnostician task,
576
+ // task-before-link, pending promotion tails) exposed for the CLI now and the
577
+ // Slice C Companion worker later.
578
+ const codexCmd = program
579
+ .command('codex')
580
+ .description('Codex host governance operations');
581
+ // ── pd codex setup — consent UX for conversation ingestion (Slice D) ─────────
582
+ // PRI-625, SPEC rev 2 §17 + G2A frozen disclosure: the ONE authority that can
583
+ // enable codex_conversation_ingestion — presents the frozen disclosure and
584
+ // records the explicit Owner decision BEFORE flipping the flag. Declining
585
+ // leaves all existing governance unchanged and reads no transcript.
586
+ codexCmd
587
+ .command('setup')
588
+ .description('Present the frozen ingestion disclosure and record the explicit consent decision (accept enables codex_conversation_ingestion; decline keeps everything off)')
589
+ .option('-w, --workspace <path>', 'Workspace directory')
590
+ .option('--accept', 'Explicitly accept after the disclosure has been presented (non-interactive)')
591
+ .option('--decline', 'Explicitly decline; the ingestion flag stays off and no transcript is ever read')
592
+ .option('--show-disclosure', 'Print the frozen disclosure text (zh default, --lang en) and exit without mutating anything')
593
+ .option('--lang <zh|en>', 'Disclosure language for presentation', undefined)
594
+ .option('--json', 'Output raw JSON (decision must be explicit: --accept or --decline)')
595
+ .action(async (opts) => {
596
+ const { handleCodexSetup } = await import('./commands/codex-setup.js');
597
+ await handleCodexSetup({
598
+ workspace: opts.workspace,
599
+ json: opts.json === true,
600
+ accept: opts.accept === true,
601
+ decline: opts.decline === true,
602
+ showDisclosure: opts.showDisclosure === true,
603
+ ...(typeof opts.lang === 'string' ? { lang: opts.lang } : {}),
604
+ });
605
+ });
606
+ codexCmd
607
+ .command('reconcile')
608
+ .description('Reconcile admitted Codex pains with Diagnostician tasks and promotion tails (idempotent)')
609
+ .option('-w, --workspace <path>', 'Workspace directory')
610
+ .option('--limit <n>', 'Maximum admitted pains to reconcile per pass (1-200, default 50)')
611
+ .option('--json', 'Output raw JSON')
612
+ .action(async (opts) => {
613
+ const { handleCodexReconcile } = await import('./commands/codex-reconcile.js');
614
+ const limit = typeof opts.limit === 'string' ? Number.parseInt(opts.limit, 10) : undefined;
615
+ await handleCodexReconcile({
616
+ workspace: opts.workspace,
617
+ json: opts.json === true,
618
+ ...(limit !== undefined && Number.isInteger(limit) ? { limit } : {}),
619
+ });
620
+ });
621
+ // ── pd codex ingest catch-up — bounded manual transcript lag recovery ────────
622
+ // Codex Governance Closure Slice C (PRI-624, SPEC §15): the manual-mode
623
+ // counterpart of the Companion worker's catch-up step. Zero transcript I/O
624
+ // when codex_conversation_ingestion is disabled.
625
+ const codexIngestCmd = codexCmd
626
+ .command('ingest')
627
+ .description('Codex conversation-ingestion operations');
628
+ codexIngestCmd
629
+ .command('catch-up')
630
+ .description('Catch up transcript lag from durable checkpoints (bounded, non-destructive, no LLM)')
631
+ .option('-w, --workspace <path>', 'Workspace directory')
632
+ .option('--max-rollouts <n>', 'Maximum rollouts to catch up per pass (1-32, default 8)')
633
+ .option('--json', 'Output raw JSON')
634
+ .action(async (opts) => {
635
+ const { handleCodexIngestCatchUp } = await import('./commands/codex-ingest-catchup.js');
636
+ const maxRollouts = typeof opts.maxRollouts === 'string' ? Number.parseInt(opts.maxRollouts, 10) : undefined;
637
+ await handleCodexIngestCatchUp({
638
+ workspace: opts.workspace,
639
+ json: opts.json === true,
640
+ ...(maxRollouts !== undefined && Number.isInteger(maxRollouts) ? { maxRollouts } : {}),
641
+ });
642
+ });
643
+ // ── pd codex ingest quarantine — audited recovery for invalid records ────────
644
+ // Codex Governance Closure Slice D (PRI-625, SPEC §15): dry-run by default,
645
+ // --confirm required to mutate; records digest/reason/operator/timestamp/gap;
646
+ // never edits the Codex transcript; promoted evidence is refused.
647
+ codexIngestCmd
648
+ .command('quarantine')
649
+ .description('Quarantine a permanently invalid governance observation (dry-run by default; --confirm to apply; never touches the transcript)')
650
+ .option('-w, --workspace <path>', 'Workspace directory')
651
+ .option('--rollout <id>', 'Rollout identity that owns the record (required)')
652
+ .option('--record <id>', 'Numeric governance_observations.id to quarantine (required)')
653
+ .option('--reason <text>', 'Why the record is permanently invalid, 1-200 chars (required)')
654
+ .option('--operator <id>', 'Operator identity recorded in the audit metadata (default: current OS user)')
655
+ .option('--confirm', 'Apply the quarantine; without this flag the command is a dry run')
656
+ .option('--json', 'Output raw JSON')
657
+ .action(async (opts) => {
658
+ const { handleCodexIngestQuarantine } = await import('./commands/codex-ingest-quarantine.js');
659
+ await handleCodexIngestQuarantine({
660
+ workspace: opts.workspace,
661
+ rollout: opts.rollout,
662
+ record: opts.record,
663
+ reason: opts.reason,
664
+ ...(typeof opts.operator === 'string' ? { operator: opts.operator } : {}),
665
+ confirm: opts.confirm === true,
666
+ json: opts.json === true,
667
+ });
668
+ });
669
+ // ── pd codex worker — Workspace-scoped governance worker ─────────────────────
670
+ // Codex Governance Closure Slice C (PRI-624, SPEC §13; ADR-0020 §11.1): the
671
+ // one Owner-approved background worker (catch-up → reconciliation → one
672
+ // Diagnostician execution → one bounded downstream consumer cycle). The
673
+ // Companion spawns this per registered workspace; --once is the manual and
674
+ // supervised-restart form.
675
+ codexCmd
676
+ .command('worker')
677
+ .description('Run the Codex workspace governance worker (catch-up, reconciliation, diagnostician, downstream)')
678
+ .option('-w, --workspace <path>', 'Workspace directory')
679
+ .option('--once', 'Run exactly one bounded cycle and exit')
680
+ .option('--interval <ms>', 'Cycle interval for continuous mode (default 120000, minimum 1000)')
681
+ .option('--status', 'Report the SPEC §15 worker mode without executing anything')
682
+ .option('--json', 'Output raw JSON')
683
+ .action(async (opts) => {
684
+ const { handleCodexWorker } = await import('./commands/codex-worker.js');
685
+ const intervalMs = typeof opts.interval === 'string' ? Number.parseInt(opts.interval, 10) : undefined;
686
+ await handleCodexWorker({
687
+ workspace: opts.workspace,
688
+ json: opts.json === true,
689
+ once: opts.once === true,
690
+ status: opts.status === true,
691
+ ...(intervalMs !== undefined && Number.isInteger(intervalMs) ? { intervalMs } : {}),
692
+ });
693
+ });
694
+ // ── pd workbuddy — WorkBuddy host governance operations ──────────────────────
695
+ // SPEC workbuddy-host-adapter §5 Part 5 (ADR-0020 third host): reconciliation,
696
+ // transcript catch-up, diagnostician and downstream reuse the shared
697
+ // authorities. PRI-1171 P2 tickets ⑤/⑥ add transcript ingestion, so the setup
698
+ // command below is the SUPPORTED entry point for its consent record and
699
+ // feature flag (default off) — a convention, not an enforced boundary.
700
+ const workbuddyCmd = program
701
+ .command('workbuddy')
702
+ .description('WorkBuddy host governance operations');
703
+ workbuddyCmd
704
+ .command('setup')
705
+ .description('Present the WorkBuddy ingestion disclosure and record the explicit Owner decision (accept enables workbuddy_conversation_ingestion; decline keeps everything off)')
706
+ .option('-w, --workspace <path>', 'Governance workspace directory')
707
+ .option('--accept', 'Explicitly accept after the disclosure has been presented')
708
+ .option('--decline', 'Explicitly decline; the ingestion flag stays off and no transcript is ever read')
709
+ .option('--show-disclosure', 'Print the disclosure text and exit without mutating anything')
710
+ .option('--json', 'Output raw JSON (decision must be explicit: --accept or --decline)')
711
+ .action(async (opts) => {
712
+ const { handleWorkbuddySetup } = await import('./commands/workbuddy-setup.js');
713
+ await handleWorkbuddySetup({
714
+ workspace: opts.workspace,
715
+ json: opts.json === true,
716
+ accept: opts.accept === true,
717
+ decline: opts.decline === true,
718
+ showDisclosure: opts.showDisclosure === true,
719
+ });
720
+ });
721
+ workbuddyCmd
722
+ .command('worker')
723
+ .description('Run the WorkBuddy governance worker (transcript catch-up, reconciliation, diagnostician, downstream)')
724
+ .option('-w, --workspace <path>', 'Governance workspace directory (default: the WorkBuddy governance workspace)')
725
+ .option('--once', 'Run exactly one bounded cycle and exit')
726
+ .option('--interval <ms>', 'Cycle interval for continuous mode (default 120000, minimum 1000)')
727
+ .option('--status', 'Report the §15 worker mode without executing anything')
728
+ .option('--json', 'Output raw JSON')
729
+ .action(async (opts) => {
730
+ const { handleWorkbuddyWorker } = await import('./commands/workbuddy-worker.js');
731
+ const intervalMs = typeof opts.interval === 'string' ? Number.parseInt(opts.interval, 10) : undefined;
732
+ await handleWorkbuddyWorker({
733
+ workspace: opts.workspace,
734
+ json: opts.json === true,
735
+ once: opts.once === true,
736
+ status: opts.status === true,
737
+ ...(intervalMs !== undefined && Number.isInteger(intervalMs) ? { intervalMs } : {}),
738
+ });
739
+ });
740
+ const internalizationCmd = runtimeCmd
741
+ .command('internalization')
742
+ .description('Internalization Engine operator visibility');
743
+ internalizationCmd
744
+ .command('queue')
745
+ .description('Show PI task queue health snapshot')
746
+ .option('-w, --workspace <path>', 'Workspace directory')
747
+ .option('--json', 'Output raw JSON')
748
+ .action(async (opts) => {
749
+ await handleRuntimeInternalizationQueue({ workspace: opts.workspace, json: opts.json });
750
+ });
751
+ internalizationCmd
752
+ .command('wake-once')
753
+ .description('Dry-run lease evaluation for the next leasable PI task')
754
+ .option('-w, --workspace <path>', 'Workspace directory')
755
+ .option('--dry-run', 'Evaluate lease without acquiring (required)', false)
756
+ .option('--json', 'Output raw JSON')
757
+ .action(async (opts) => {
758
+ await handleRuntimeInternalizationWakeOnce({ workspace: opts.workspace, dryRun: opts.dryRun, json: opts.json });
759
+ });
760
+ internalizationCmd
761
+ .command('retry')
762
+ .description('Requeue a needs_human_review task (owner attention queue out-edge)')
763
+ .option('-w, --workspace <path>', 'Workspace directory')
764
+ .requiredOption('--task <taskId>', 'Task id to requeue')
765
+ .option('--confirm', 'Actually requeue (default is dry-run)')
766
+ .option('--json', 'Output as JSON')
767
+ .action(async (opts) => {
768
+ await handleRuntimeInternalizationRetry({ workspace: opts.workspace, taskId: opts.task, confirm: opts.confirm, json: opts.json });
769
+ });
770
+ internalizationCmd
771
+ .command('run-once')
772
+ .description('Wake-and-run: lease the next PI task and execute it')
773
+ .option('-w, --workspace <path>', 'Workspace directory')
774
+ .option('--runner <kind>', 'Runner kind to execute (default: dreamer)', 'dreamer')
775
+ .option('--runtime <kind>', 'Runtime adapter kind: config (from .pd/config.yaml), pi-ai, test-double (default: config)', 'config')
776
+ .option('--allow-test-double', 'Acknowledge that test-double runtime will mutate real queue state')
777
+ .option('--no-enqueue-next', 'Skip successor enqueue after successful runner (default: auto-enqueue)')
778
+ .option('--timeout-ms <ms>', 'Runner timeout in milliseconds (default: 300000, overrides workflows.yaml)', parseInt)
779
+ .option('--json', 'Output raw JSON')
780
+ .action(async (opts) => {
781
+ await handleRuntimeInternalizationRunOnce({ workspace: opts.workspace, json: opts.json, runtime: opts.runtime, runner: opts.runner, allowTestDouble: opts.allowTestDouble, enqueueNext: opts.enqueueNext, timeoutMs: opts.timeoutMs });
782
+ });
783
+ registerRunRuleHostCommand(internalizationCmd);
784
+ // PRI-985 (SPEC-PD-IAER-001 FR-09): read-only history audit of
785
+ // behavior_example_pack_missing failures, aggregated by task.
786
+ registerRuntimeInternalizationAuditArtificerEvidenceCommand(internalizationCmd);
787
+ // PRI-983 (SPEC-PD-IAER-001 FR-03/FR-06): Owner evidence attach/resume
788
+ // (list / attach / resume — all default dry-run, --confirm mutates).
789
+ registerRuntimeInternalizationEvidenceCommand(internalizationCmd);
790
+ internalizationCmd
791
+ .command('integrity')
792
+ .description('Check internalization chain integrity')
793
+ .option('-w, --workspace <path>', 'Workspace directory')
794
+ .option('--json', 'Output raw JSON')
795
+ .action(async (opts) => {
796
+ await handleRuntimeInternalizationIntegrity({ workspace: opts.workspace, json: opts.json });
797
+ });
798
+ internalizationCmd
799
+ .command('integrity-repair')
800
+ .description('Repair broken internalization chain links (operator repair path)')
801
+ .option('-w, --workspace <path>', 'Workspace directory')
802
+ .option('--dry-run', 'Report only, no modifications')
803
+ .option('--confirm', 'Actually repair broken links')
804
+ .option('--json', 'Output raw JSON')
805
+ .action(async (opts) => {
806
+ await handleRuntimeInternalizationIntegrityRepair({ workspace: opts.workspace, confirm: opts.confirm, dryRun: opts.dryRun, json: opts.json });
807
+ });
808
+ internalizationCmd
809
+ .command('enqueue-successors')
810
+ .description('Enqueue successor tasks for succeeded internalization tasks missing successors')
811
+ .option('-w, --workspace <path>', 'Workspace directory')
812
+ .option('--dry-run', 'Report only, no modifications (default)')
813
+ .option('--confirm', 'Actually create successor tasks')
814
+ .option('--json', 'Output raw JSON')
815
+ .action(async (opts) => {
816
+ await handleRuntimeInternalizationEnqueueSuccessors({ workspace: opts.workspace, dryRun: opts.dryRun, confirm: opts.confirm, json: opts.json });
817
+ });
818
+ const activationCmd = runtimeCmd
819
+ .command('activation', { hidden: true })
820
+ .description('Activation dispatch operations (hidden — use pd activation for list/deactivate)');
821
+ registerRuntimeActivationDispatchCommand(activationCmd);
822
+ // PRI-408 Contract E: Owner-initiated rollback/deactivate of an activation.
823
+ // Idempotent — calling twice on the same ID is safe and returns ok=false with reason.
824
+ activationCmd
825
+ .command('deactivate')
826
+ .description('Deactivate (rollback) an active activation — idempotent (PRI-408 Contract E)')
827
+ .option('-a, --activation-id <id>', 'Activation ID to deactivate')
828
+ .option('-w, --workspace <path>', 'Workspace directory')
829
+ .option('--json', 'Output raw JSON')
830
+ .action(async (opts) => {
831
+ await handleRuntimeActivationDeactivate({
832
+ workspace: opts.workspace,
833
+ activationId: opts.activationId,
834
+ json: opts.json,
835
+ });
836
+ });
837
+ // PRI-408 Contract D: Owner observability — list current activations.
838
+ activationCmd
839
+ .command('list')
840
+ .description('List activations (default: active only) — PRI-408 Contract D observability')
841
+ .option('-w, --workspace <path>', 'Workspace directory')
842
+ .option('-c, --channel <channel>', 'Filter by channel (prompt|code_tool_hook)')
843
+ .option('--include-deactivated', 'Include deactivated records in output')
844
+ .option('--json', 'Output raw JSON')
845
+ .action(async (opts) => {
846
+ await handleRuntimeActivationList({
847
+ workspace: opts.workspace,
848
+ channel: opts.channel,
849
+ includeDeactivated: opts.includeDeactivated,
850
+ json: opts.json,
851
+ });
852
+ });
853
+ // P1 #2 fix: Owner edit entry point — swap a pending approval's artifact.
854
+ // Required because ApprovalQueue.edit() was dead code with no CLI/OpenClaw entry.
855
+ // P2 #5: use .option() instead of .requiredOption() so missing-flag errors
856
+ // produce structured JSON output via the handler, not Commander's pre-handler exit.
857
+ activationCmd
858
+ .command('edit')
859
+ .description('Edit a pending approval to swap its artifact — P1 #2 owner edit entry point')
860
+ .option('-a, --approval-id <id>', 'Approval ID to edit (must be pending)')
861
+ .option('-n, --new-artifact-id <id>', 'New PIArtifact ID to swap to')
862
+ .option('-r, --edit-reason <text>', 'Reason for the edit')
863
+ .option('-w, --workspace <path>', 'Workspace directory')
864
+ .option('--json', 'Output raw JSON')
865
+ .action(async (opts) => {
866
+ await handleRuntimeActivationEdit({
867
+ workspace: opts.workspace,
868
+ approvalId: opts.approvalId,
869
+ newArtifactId: opts.newArtifactId,
870
+ editReason: opts.editReason,
871
+ json: opts.json,
872
+ });
873
+ });
874
+ const diagnosticsCmd = runtimeCmd
875
+ .command('diagnostics', { hidden: true })
876
+ .description('Control plane diagnostic bundle operations');
877
+ // PRI-674: visible (was hidden) — the only recovery re-entry point for an
878
+ // Owner without Console access; hidden-ness left failed diagnostician tasks
879
+ // undiscoverable.
880
+ const recoveryCmd = runtimeCmd
881
+ .command('recovery')
882
+ .description('Runtime V2 recovery operations (expired-lease sweep, failed-task recovery)');
883
+ // PRI-555 phase 1: dry-run-only artifact identity drift repair planner.
884
+ runtimeCmd
885
+ .command('artifact-repair')
886
+ .description('Plan repairs for unreachable scribe artifacts (dry-run only; writes migration-plan.json, never modifies state.db)')
887
+ .option('-w, --workspace <path>', 'Workspace directory')
888
+ .option('--dry-run', 'Build migration-plan.json only (default)')
889
+ .option('--confirm', 'Not implemented in this phase — refused')
890
+ .option('--out <path>', 'Output path for migration-plan.json (default: ./migration-plan.json)')
891
+ .option('--json', 'Output raw JSON')
892
+ .action(async (opts) => {
893
+ await handleRuntimeArtifactRepair({
894
+ workspace: opts.workspace,
895
+ dryRun: opts.dryRun,
896
+ confirm: opts.confirm,
897
+ out: opts.out,
898
+ json: opts.json,
899
+ });
900
+ });
901
+ recoveryCmd
902
+ .command('sweep')
903
+ .description('Detect and optionally recover expired leases')
904
+ .option('-w, --workspace <path>', 'Workspace directory')
905
+ .option('--dry-run', 'Report only, no modifications (default)')
906
+ .option('--confirm', 'Actually recover expired leases')
907
+ .option('--json', 'Output raw JSON')
908
+ .action(async (opts) => {
909
+ await handleRuntimeRecoverySweep({ workspace: opts.workspace, dryRun: opts.dryRun, confirm: opts.confirm, json: opts.json });
910
+ });
911
+ recoveryCmd
912
+ .command('failed-tasks')
913
+ .description('Recover failed internalization and diagnostician tasks')
914
+ .option('-w, --workspace <path>', 'Workspace directory')
915
+ .option('--dry-run', 'Report only, no modifications (default)')
916
+ .option('--confirm', 'Actually recover failed tasks')
917
+ .option('--force', 'Force recovery of tasks that exhausted max attempts')
918
+ .option('--json', 'Output raw JSON')
919
+ .action(async (opts) => {
920
+ await handleRuntimeRecoveryFailedTasks({
921
+ workspace: opts.workspace,
922
+ dryRun: opts.dryRun,
923
+ confirm: opts.confirm,
924
+ force: opts.force,
925
+ json: opts.json,
926
+ });
927
+ });
928
+ // PRI-991: exact single-task counterpart of `failed-tasks`. A batch --force
929
+ // resets the budget of EVERY exhausted failed task; this command recovers
930
+ // exactly one Owner-selected task (CAS-guarded, audited, dry-run default).
931
+ registerRuntimeRecoveryFailedTaskCommand(recoveryCmd);
932
+ diagnosticsCmd
933
+ .command('export')
934
+ .description('Export diagnostic bundle for AI assistant analysis')
935
+ .option('-w, --workspace <path>', 'Workspace directory')
936
+ .option('--out <dir>', 'Output directory (must be within workspace)')
937
+ .option('--json', 'Output raw JSON')
938
+ .action(async (opts) => {
939
+ await handleRuntimeDiagnosticsExport({ workspace: opts.workspace, out: opts.out, json: opts.json });
940
+ });
941
+ const pruningCmd = runtimeCmd
942
+ .command('pruning', { hidden: true })
943
+ .description('Non-destructive pruning metrics and health signals');
944
+ pruningCmd
945
+ .command('report')
946
+ .description('Show pruning health report — watch/review principle signals')
947
+ .option('-w, --workspace <path>', 'Workspace directory')
948
+ .option('--json', 'Output raw JSON')
949
+ .action((opts) => {
950
+ handlePruningReport({ workspace: opts.workspace, json: opts.json });
951
+ });
952
+ pruningCmd
953
+ .command('explain')
954
+ .description('Explain why a specific principle was flagged')
955
+ .requiredOption('--principle-id <id>', 'Principle ID to explain')
956
+ .option('-w, --workspace <path>', 'Workspace directory')
957
+ .option('--json', 'Output raw JSON')
958
+ .action((opts) => {
959
+ handlePruningExplain({ principleId: opts.principleId, workspace: opts.workspace, json: opts.json });
960
+ });
961
+ pruningCmd
962
+ .command('orphans')
963
+ .description('List orphan derived candidates not found in state.db')
964
+ .option('-w, --workspace <path>', 'Workspace directory')
965
+ .option('--dry-run', 'Report only, no modifications (default)')
966
+ .option('--confirm', 'Actually remove orphan references from ledger')
967
+ .option('--json', 'Output raw JSON')
968
+ .action((opts) => {
969
+ handlePruningOrphans({
970
+ workspace: opts.workspace,
971
+ dryRun: opts.dryRun,
972
+ confirm: opts.confirm,
973
+ json: opts.json,
974
+ });
975
+ });
976
+ // ── Candidate inspection commands ─────────────────────────────────────────────
977
+ const candidateCmd = program
978
+ .command('candidate')
979
+ .description('Principle candidate inspection');
980
+ candidateCmd
981
+ .command('list')
982
+ .description('List principle candidates for a task')
983
+ .requiredOption('-t, --task-id <taskId>', 'Task ID to query')
984
+ .option('-w, --workspace <path>', 'Workspace directory')
985
+ .option('--json', 'Output raw JSON')
986
+ .action(async (opts) => {
987
+ await handleCandidateList(opts);
988
+ });
989
+ candidateCmd
990
+ .command('show [candidateId]')
991
+ .description('Show detail for a single principle candidate')
992
+ .requiredOption('-w, --workspace <path>', 'Workspace directory')
993
+ .option('--candidate-id <id>', 'Candidate ID (alternative to positional arg)')
994
+ .option('--json', 'Output raw JSON')
995
+ .action(async (candidateId, opts) => {
996
+ const resolvedId = opts.candidateId ?? candidateId;
997
+ if (!resolvedId) {
998
+ console.error('Error: candidate ID is required (positional or --candidate-id)');
999
+ process.exitCode = 1;
1000
+ return;
1001
+ }
1002
+ if (candidateId && opts.candidateId && candidateId !== opts.candidateId) {
1003
+ console.error(`Error: conflicting candidate IDs: positional="${candidateId}", --candidate-id="${opts.candidateId}"`);
1004
+ process.exitCode = 1;
1005
+ return;
1006
+ }
1007
+ await handleCandidateShow({ candidateId: resolvedId, ...opts });
1008
+ });
1009
+ candidateCmd
1010
+ .command('intake')
1011
+ .description('Intake a principle candidate into the ledger')
1012
+ .requiredOption('--candidate-id <id>', 'Candidate ID to intake')
1013
+ .option('-w, --workspace <path>', 'Workspace directory')
1014
+ .option('--json', 'Output as JSON')
1015
+ .option('--dry-run', 'Show what would be written without writing')
1016
+ .action(async (opts) => {
1017
+ await handleCandidateIntake(opts);
1018
+ });
1019
+ // PRI-917 PR3A: the Owner reuse decision surface (SPEC §18 — interaction
1020
+ // layer only; the durable authority stays Principle.reuseEvidence[]).
1021
+ candidateCmd
1022
+ .command('review')
1023
+ .description('Review a candidate\'s reuse proposal and optionally record the Owner decision (reuse|create)')
1024
+ .requiredOption('--candidate-id <id>', 'Candidate ID to review')
1025
+ .option('-w, --workspace <path>', 'Workspace directory')
1026
+ .option('--json', 'Output as JSON')
1027
+ .addOption(new Option('--decide <decision>', 'Record the Owner decision (omit for read-only proposal view)').choices(['reuse', 'create']))
1028
+ .option('--principle-id <id>', 'Existing Principle to reuse (required with --decide reuse)')
1029
+ .option('--reason <text>', 'Why the Owner resolved this candidate (required with --decide)')
1030
+ .action(async (opts) => {
1031
+ await handleCandidateReview(opts);
1032
+ });
1033
+ candidateCmd
1034
+ .command('audit')
1035
+ .description('Audit candidate/ledger consistency for Runtime v2')
1036
+ .option('-w, --workspace <path>', 'Workspace directory')
1037
+ .option('--json', 'Output as JSON')
1038
+ .action(async (opts) => {
1039
+ await handleCandidateAudit(opts);
1040
+ });
1041
+ candidateCmd
1042
+ .command('repair')
1043
+ .description('Repair consumed candidate with missing ledger entry')
1044
+ .requiredOption('--candidate-id <id>', 'Candidate ID to repair')
1045
+ .option('-w, --workspace <path>', 'Workspace directory')
1046
+ .option('--json', 'Output as JSON')
1047
+ .action(async (opts) => {
1048
+ await handleCandidateRepair(opts);
1049
+ });
1050
+ candidateCmd
1051
+ .command('route')
1052
+ .description('Show internalization route decision for a candidate')
1053
+ .requiredOption('--candidate-id <id>', 'Candidate ID to inspect')
1054
+ .option('-w, --workspace <path>', 'Workspace directory')
1055
+ .option('--json', 'Output as JSON')
1056
+ .action(async (opts) => {
1057
+ await handleCandidateRoute(opts);
1058
+ });
1059
+ candidateCmd
1060
+ .command('internalize')
1061
+ .description('Seed internalization Dreamer task from a candidate')
1062
+ .requiredOption('--candidate-id <id>', 'Candidate ID to internalize')
1063
+ .option('-w, --workspace <path>', 'Workspace directory')
1064
+ .option('--json', 'Output as JSON')
1065
+ .option('--dry-run', 'Preview without writing to database')
1066
+ .action(async (opts) => {
1067
+ await handleCandidateInternalize(opts);
1068
+ });
1069
+ const candidateInternalizationCmd = candidateCmd
1070
+ .command('internalization')
1071
+ .description('Internalization pipeline operations for candidates');
1072
+ candidateInternalizationCmd
1073
+ .command('backfill')
1074
+ .description('Backfill dreamer tasks for consumed candidates created before Internalization Engine')
1075
+ .option('-w, --workspace <path>', 'Workspace directory')
1076
+ .option('--dry-run', 'Report only, no modifications (default)')
1077
+ .option('--confirm', 'Actually create missing dreamer tasks')
1078
+ .option('--include-pending', 'Include pending candidates (intake first, then seed dreamer)')
1079
+ .option('--json', 'Output as JSON')
1080
+ .action(async (opts) => {
1081
+ await handleCandidateInternalizationBackfill({ workspace: opts.workspace, dryRun: opts.dryRun, confirm: opts.confirm, includePending: opts.includePending, json: opts.json });
1082
+ });
1083
+ // ── Artifact inspection commands ──────────────────────────────────────────────
1084
+ const artifactCmd = program
1085
+ .command('artifact', { hidden: true })
1086
+ .description('Artifact registry inspection');
1087
+ artifactCmd
1088
+ .command('show <artifactId>')
1089
+ .description('Show artifact content and its associated candidates')
1090
+ .requiredOption('-w, --workspace <path>', 'Workspace directory')
1091
+ .option('--json', 'Output raw JSON')
1092
+ .action(async (artifactId, opts) => {
1093
+ await handleArtifactShow({ artifactId, ...opts });
1094
+ });
1095
+ const _legacyCleanupCmd = legacyCmd
1096
+ .command('cleanup')
1097
+ .description('Clean legacy empathy/diagnostician artifacts and V1 Artificer artifacts from workspace')
1098
+ .requiredOption('-w, --workspace <path>', 'Workspace directory')
1099
+ .option('--dry-run', 'Show what would be cleaned without applying (default)')
1100
+ .option('--apply', 'Actually apply the cleanup')
1101
+ .option('--json', 'Output raw JSON')
1102
+ .action(async (opts) => {
1103
+ // CLI gate rule 4: --dry-run and --apply are mutually exclusive
1104
+ if (opts.dryRun && opts.apply) {
1105
+ const msg = 'Error: --dry-run and --apply are mutually exclusive';
1106
+ if (opts.json) {
1107
+ console.log(JSON.stringify({ status: 'failed', reason: msg, nextAction: 'Specify either --dry-run or --apply, not both' }, null, 2));
1108
+ }
1109
+ else {
1110
+ console.error(msg);
1111
+ }
1112
+ process.exitCode = 1;
1113
+ return;
1114
+ }
1115
+ // Default to dry-run if neither flag is set (CLI gate rule 4).
1116
+ // Pass undefined through — the handler's logic
1117
+ // (opts.apply === true ? false : opts.dryRun !== false) correctly
1118
+ // defaults to dry-run when both are undefined.
1119
+ await handleLegacyCleanup({
1120
+ workspacePath: opts.workspace,
1121
+ dryRun: opts.dryRun,
1122
+ apply: opts.apply,
1123
+ json: opts.json ?? false,
1124
+ });
1125
+ });
1126
+ // ─── MVP Smoke (PRI-397) ────────────────────────────────────────────────────
1127
+ registerMvpCommands(program);
1128
+ // ─── RuleCode CLI (PRI-439 Phase 5) ─────────────────────────────────────────
1129
+ // Read-only commands: spec, validate, replay. No DB mutation, no artifact writes.
1130
+ registerRulecodeCommand(program);
1131
+ // ─── Intent Engineering (PRI-466) ───────────────────────────────────────────
1132
+ // Owner-authored INTENT.md management: init (create), show (read-only summary).
1133
+ registerIntentCommand(program);
1134
+ // ─── Errors List (Task 14: Feedback Pipeline Observability) ────────────────
1135
+ // Operator diagnostic: aggregates SQLite failed/needs_human_review tasks +
1136
+ // worker-status.json errors array. Read-only.
1137
+ registerErrorsListCommand(program);
1138
+ // ─── Principles Stats (PRI-562 Phase 0) ─────────────────────────────────────
1139
+ // Owner-facing observability: principle injection volume/cost/duplicates/
1140
+ // application evidence. Read-only aggregation over event logs + receipt ledger.
1141
+ registerPrinciplesCommand(program);
1142
+ const consoleCmd = program
1143
+ .command('console')
1144
+ .description('Start the pd-console web UI for principle review (default: fallback launcher)')
1145
+ .passThroughOptions()
1146
+ .option('-w, --workspace <path>', 'Workspace directory')
1147
+ .option('-p, --port <port>', 'Port to listen on', '3100')
1148
+ .option('--no-auth', 'Disable authentication (local dev only)')
1149
+ .option('--json', 'Output JSON status', false);
1150
+ consoleCmd
1151
+ .command('start')
1152
+ .description('Legacy launcher — start the pd-console on the requested port (no reuse, no browser open)')
1153
+ .option('-w, --workspace <path>', 'Workspace directory')
1154
+ .option('-p, --port <port>', 'Port to listen on', '3100')
1155
+ .option('--no-auth', 'Disable authentication (local dev only)')
1156
+ .option('--json', 'Output JSON status', false)
1157
+ .action(async (opts) => {
1158
+ const { handleConsole } = await import('./commands/console.js');
1159
+ await handleConsole({
1160
+ workspace: opts.workspace,
1161
+ port: opts.port,
1162
+ noAuth: opts.auth === false,
1163
+ json: opts.json,
1164
+ });
1165
+ });
1166
+ // PRI-300: seed-friendly Console launcher with reuse + auto-port + browser open
1167
+ consoleCmd
1168
+ .command('open')
1169
+ .description('Open the pd-console in your browser (PRI-300) — auto-port, reuses running console, loopback-only')
1170
+ .option('-w, --workspace <path>', 'Workspace directory')
1171
+ .option('-p, --port <port>', 'Preferred port (default 3100; auto-falls back to next free port)')
1172
+ .option('--host <host>', 'Loopback host (default 127.0.0.1; non-loopback refused)')
1173
+ .option('--no-auth', 'Disable authentication (local dev only)')
1174
+ .option('--token <token>', 'Auth token for the Console (or set PD_CONSOLE_TOKEN env var)')
1175
+ .option('--no-browser', 'Do not open the system browser on success')
1176
+ .option('--json', 'Output JSON status (suppresses browser open)', false)
1177
+ .action(async (opts) => {
1178
+ const { handleConsoleOpen } = await import('./commands/console.js');
1179
+ await handleConsoleOpen({
1180
+ workspace: opts.workspace,
1181
+ port: opts.port,
1182
+ host: opts.host,
1183
+ noAuth: opts.auth === false,
1184
+ token: opts.token,
1185
+ noBrowser: opts.browser === false,
1186
+ json: opts.json,
1187
+ });
1188
+ });
1189
+ // Default `pd console` → legacy launcher (backward compat)
1190
+ consoleCmd.action(async (opts) => {
1191
+ const { handleConsole } = await import('./commands/console.js');
1192
+ await handleConsole({
1193
+ workspace: opts.workspace,
1194
+ port: opts.port,
1195
+ noAuth: opts.auth === false,
1196
+ json: opts.json,
1197
+ });
1198
+ });
1199
+ // ─── Quality Scorecard (PRI-361) ──────────────────────────────────
1200
+ const qualityCmd = program
1201
+ .command('quality', { hidden: true })
1202
+ .description('Quality scoring and evaluation');
1203
+ qualityCmd
1204
+ .command('scorecard')
1205
+ .description('Generate quality scorecard report for PD pain→diagnosis→principle chain')
1206
+ .option('-w, --workspace <path>', 'Workspace directory')
1207
+ .option('--local-model <id>', 'LM Studio model ID', 'qwen3.6-27b-mtp')
1208
+ .option('--local-url <url>', 'LM Studio base URL', 'http://localhost:12341/v1')
1209
+ .option('--strong-model <id>', 'Strong model for adjudication (provider/model)')
1210
+ .option('--skip-strong-model', 'Skip strong model adjudication', false)
1211
+ .option('--min-score <n>', 'Minimum pain score to evaluate', '50')
1212
+ .option('--limit <n>', 'Max episodes to evaluate (0=all)', '0')
1213
+ .option('--format <fmt>', 'Output format: json, markdown, html', 'markdown')
1214
+ .option('--output <path>', 'Output file path')
1215
+ .option('--json', 'Output as JSON', false)
1216
+ .action(async (opts) => {
1217
+ const { handleQualityScorecard } = await import('./commands/quality-scorecard.js');
1218
+ await handleQualityScorecard(opts);
1219
+ });
1220
+ // ─── PD MCP durable logs (observability export) ───────────────────
1221
+ // One command that turns the on-disk MCP JSONL logs into a single bounded zip
1222
+ // the Owner can send to an agent for offline analysis.
1223
+ const mcpCmd = program
1224
+ .command('mcp')
1225
+ .description('PD MCP server operations');
1226
+ const mcpLogsCmd = mcpCmd
1227
+ .command('logs')
1228
+ .description('Inspect durable PD MCP logs');
1229
+ mcpLogsCmd
1230
+ .command('export')
1231
+ .description('Bundle the last N days of PD MCP logs into one zip (≤20 MiB, sanitized)')
1232
+ .option('--days <n>', 'Days of history to include (1-365)', '7')
1233
+ .option('-o, --out <path>', 'Output .zip path, or a directory to write the default file name into')
1234
+ .option('--json', 'Output raw JSON')
1235
+ .action(async (opts) => {
1236
+ const parsedDays = Number.parseInt(opts.days, 10);
1237
+ if (!Number.isInteger(parsedDays) || parsedDays < 1 || parsedDays > 365) {
1238
+ console.error('--days must be an integer between 1 and 365');
1239
+ process.exitCode = 1;
1240
+ return;
1241
+ }
1242
+ try {
1243
+ await handleMcpLogsExport({
1244
+ days: parsedDays,
1245
+ out: opts.out,
1246
+ json: opts.json === true,
1247
+ });
1248
+ }
1249
+ catch (error) {
1250
+ console.error(`MCP log export failed: ${error instanceof Error ? error.message : String(error)}`);
1251
+ process.exitCode = 1;
1252
+ }
1253
+ });
1254
+ /**
1255
+ * The real command tree, exported for registration tests (cli-7).
1256
+ *
1257
+ * Tests must parse THIS object: a hand-copied command tree in a test can stay
1258
+ * green after the real command name or a flag is renamed (review finding 12).
1259
+ */
1260
+ export function buildPdProgram() {
1261
+ return program;
1262
+ }
1263
+ //# sourceMappingURL=program.js.map