@principles/pd-cli 1.152.12 → 1.152.13

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 (296) hide show
  1. package/package.json +13 -7
  2. package/CHANGELOG.md +0 -23
  3. package/dist/commands/__tests__/intent-flag-wiring.test.d.ts +0 -9
  4. package/dist/commands/__tests__/intent-flag-wiring.test.d.ts.map +0 -1
  5. package/dist/commands/__tests__/intent-flag-wiring.test.js +0 -237
  6. package/dist/commands/__tests__/intent-flag-wiring.test.js.map +0 -1
  7. package/dist/commands/__tests__/legacy-cleanup.test.d.ts +0 -18
  8. package/dist/commands/__tests__/legacy-cleanup.test.d.ts.map +0 -1
  9. package/dist/commands/__tests__/legacy-cleanup.test.js +0 -467
  10. package/dist/commands/__tests__/legacy-cleanup.test.js.map +0 -1
  11. package/dist/commands/__tests__/mvp-smoke.test.d.ts +0 -15
  12. package/dist/commands/__tests__/mvp-smoke.test.d.ts.map +0 -1
  13. package/dist/commands/__tests__/mvp-smoke.test.js +0 -262
  14. package/dist/commands/__tests__/mvp-smoke.test.js.map +0 -1
  15. package/dist/commands/__tests__/pain-retry-maxTokens-flag.test.d.ts +0 -2
  16. package/dist/commands/__tests__/pain-retry-maxTokens-flag.test.d.ts.map +0 -1
  17. package/dist/commands/__tests__/pain-retry-maxTokens-flag.test.js +0 -60
  18. package/dist/commands/__tests__/pain-retry-maxTokens-flag.test.js.map +0 -1
  19. package/dist/commands/__tests__/rulecode-flag-wiring.test.d.ts +0 -21
  20. package/dist/commands/__tests__/rulecode-flag-wiring.test.d.ts.map +0 -1
  21. package/dist/commands/__tests__/rulecode-flag-wiring.test.js +0 -186
  22. package/dist/commands/__tests__/rulecode-flag-wiring.test.js.map +0 -1
  23. package/dist/commands/__tests__/rulecode-handler.test.d.ts +0 -16
  24. package/dist/commands/__tests__/rulecode-handler.test.d.ts.map +0 -1
  25. package/dist/commands/__tests__/rulecode-handler.test.js +0 -285
  26. package/dist/commands/__tests__/rulecode-handler.test.js.map +0 -1
  27. package/dist/commands/__tests__/run-rulehost-flag-wiring.test.d.ts +0 -24
  28. package/dist/commands/__tests__/run-rulehost-flag-wiring.test.d.ts.map +0 -1
  29. package/dist/commands/__tests__/run-rulehost-flag-wiring.test.js +0 -232
  30. package/dist/commands/__tests__/run-rulehost-flag-wiring.test.js.map +0 -1
  31. package/dist/commands/__tests__/runtime-activation-nextaction.test.d.ts +0 -15
  32. package/dist/commands/__tests__/runtime-activation-nextaction.test.d.ts.map +0 -1
  33. package/dist/commands/__tests__/runtime-activation-nextaction.test.js +0 -73
  34. package/dist/commands/__tests__/runtime-activation-nextaction.test.js.map +0 -1
  35. package/dist/commands/__tests__/runtime-probe-config.test.d.ts +0 -20
  36. package/dist/commands/__tests__/runtime-probe-config.test.d.ts.map +0 -1
  37. package/dist/commands/__tests__/runtime-probe-config.test.js +0 -389
  38. package/dist/commands/__tests__/runtime-probe-config.test.js.map +0 -1
  39. package/dist/commands/__tests__/telemetry-flag-wiring.test.d.ts +0 -9
  40. package/dist/commands/__tests__/telemetry-flag-wiring.test.d.ts.map +0 -1
  41. package/dist/commands/__tests__/telemetry-flag-wiring.test.js +0 -76
  42. package/dist/commands/__tests__/telemetry-flag-wiring.test.js.map +0 -1
  43. package/dist/commands/__tests__/version.test.d.ts +0 -2
  44. package/dist/commands/__tests__/version.test.d.ts.map +0 -1
  45. package/dist/commands/__tests__/version.test.js +0 -238
  46. package/dist/commands/__tests__/version.test.js.map +0 -1
  47. package/dist/commands/runtime-uat.guard.test.d.ts +0 -2
  48. package/dist/commands/runtime-uat.guard.test.d.ts.map +0 -1
  49. package/dist/commands/runtime-uat.guard.test.js +0 -153
  50. package/dist/commands/runtime-uat.guard.test.js.map +0 -1
  51. package/dist/services/__tests__/cli-output.test.d.ts +0 -18
  52. package/dist/services/__tests__/cli-output.test.d.ts.map +0 -1
  53. package/dist/services/__tests__/cli-output.test.js +0 -103
  54. package/dist/services/__tests__/cli-output.test.js.map +0 -1
  55. package/dist/services/__tests__/evaluator-runner-deps.test.d.ts +0 -2
  56. package/dist/services/__tests__/evaluator-runner-deps.test.d.ts.map +0 -1
  57. package/dist/services/__tests__/evaluator-runner-deps.test.js +0 -343
  58. package/dist/services/__tests__/evaluator-runner-deps.test.js.map +0 -1
  59. package/dist/services/__tests__/rulehost-readiness.test.d.ts +0 -2
  60. package/dist/services/__tests__/rulehost-readiness.test.d.ts.map +0 -1
  61. package/dist/services/__tests__/rulehost-readiness.test.js +0 -311
  62. package/dist/services/__tests__/rulehost-readiness.test.js.map +0 -1
  63. package/dist/services/__tests__/runtime-adapter-resolver.test.d.ts +0 -18
  64. package/dist/services/__tests__/runtime-adapter-resolver.test.d.ts.map +0 -1
  65. package/dist/services/__tests__/runtime-adapter-resolver.test.js +0 -673
  66. package/dist/services/__tests__/runtime-adapter-resolver.test.js.map +0 -1
  67. package/dist/utils/production-workspace-guard.test.d.ts +0 -2
  68. package/dist/utils/production-workspace-guard.test.d.ts.map +0 -1
  69. package/dist/utils/production-workspace-guard.test.js +0 -137
  70. package/dist/utils/production-workspace-guard.test.js.map +0 -1
  71. package/scripts/llm-dogfood.ts +0 -456
  72. package/scripts/migrate-illegal-expected-decision.ts +0 -252
  73. package/src/commands/__tests__/intent-flag-wiring.test.ts +0 -282
  74. package/src/commands/__tests__/legacy-cleanup.test.ts +0 -602
  75. package/src/commands/__tests__/mvp-smoke.test.ts +0 -300
  76. package/src/commands/__tests__/pain-retry-maxTokens-flag.test.ts +0 -73
  77. package/src/commands/__tests__/rulecode-flag-wiring.test.ts +0 -237
  78. package/src/commands/__tests__/rulecode-handler.test.ts +0 -369
  79. package/src/commands/__tests__/run-rulehost-flag-wiring.test.ts +0 -292
  80. package/src/commands/__tests__/runtime-activation-nextaction.test.ts +0 -81
  81. package/src/commands/__tests__/runtime-probe-config.test.ts +0 -432
  82. package/src/commands/__tests__/telemetry-flag-wiring.test.ts +0 -84
  83. package/src/commands/__tests__/version.test.ts +0 -251
  84. package/src/commands/admission-gate.ts +0 -30
  85. package/src/commands/artifact.ts +0 -82
  86. package/src/commands/build-trajectory-evidence.ts +0 -298
  87. package/src/commands/candidate.ts +0 -1250
  88. package/src/commands/codex-ingest-catchup.ts +0 -114
  89. package/src/commands/codex-ingest-quarantine.ts +0 -127
  90. package/src/commands/codex-reconcile.ts +0 -84
  91. package/src/commands/codex-setup.ts +0 -476
  92. package/src/commands/codex-worker.ts +0 -185
  93. package/src/commands/command-helpers.ts +0 -24
  94. package/src/commands/config-doctor.ts +0 -193
  95. package/src/commands/console.ts +0 -797
  96. package/src/commands/context.ts +0 -72
  97. package/src/commands/demo-story-a.ts +0 -241
  98. package/src/commands/diagnose.ts +0 -756
  99. package/src/commands/errors-list.ts +0 -441
  100. package/src/commands/evolution-tasks-list.ts +0 -48
  101. package/src/commands/evolution-tasks-show.ts +0 -62
  102. package/src/commands/flow.ts +0 -60
  103. package/src/commands/health-codex.ts +0 -576
  104. package/src/commands/health.ts +0 -315
  105. package/src/commands/history.ts +0 -63
  106. package/src/commands/intent.ts +0 -457
  107. package/src/commands/legacy-cleanup.ts +0 -531
  108. package/src/commands/legacy-import.ts +0 -104
  109. package/src/commands/mvp-smoke.ts +0 -160
  110. package/src/commands/pain-evidence.ts +0 -226
  111. package/src/commands/pain-list.ts +0 -239
  112. package/src/commands/pain-record.ts +0 -612
  113. package/src/commands/pain-retry.ts +0 -916
  114. package/src/commands/principles-stats.ts +0 -700
  115. package/src/commands/proven-channel-baseline.ts +0 -115
  116. package/src/commands/quality-scorecard.ts +0 -272
  117. package/src/commands/remediation-output.ts +0 -66
  118. package/src/commands/rulecode.ts +0 -465
  119. package/src/commands/run.ts +0 -89
  120. package/src/commands/runtime-activation.ts +0 -1629
  121. package/src/commands/runtime-artifact-repair.ts +0 -524
  122. package/src/commands/runtime-canary.ts +0 -395
  123. package/src/commands/runtime-compatibility-scan.ts +0 -105
  124. package/src/commands/runtime-diagnostics-export.ts +0 -229
  125. package/src/commands/runtime-features.ts +0 -153
  126. package/src/commands/runtime-gfi-snapshot.ts +0 -135
  127. package/src/commands/runtime-health-snapshot.ts +0 -108
  128. package/src/commands/runtime-init.ts +0 -429
  129. package/src/commands/runtime-internalization-enqueue-successors.ts +0 -530
  130. package/src/commands/runtime-internalization-integrity-repair.ts +0 -79
  131. package/src/commands/runtime-internalization-integrity.ts +0 -107
  132. package/src/commands/runtime-internalization-queue.ts +0 -135
  133. package/src/commands/runtime-internalization-retry.ts +0 -191
  134. package/src/commands/runtime-internalization-run-once.ts +0 -791
  135. package/src/commands/runtime-internalization-run-rulehost.ts +0 -749
  136. package/src/commands/runtime-internalization-wake-once.ts +0 -87
  137. package/src/commands/runtime-pain-flood-simulation.ts +0 -121
  138. package/src/commands/runtime-pruning.ts +0 -438
  139. package/src/commands/runtime-recovery-failed-tasks.ts +0 -258
  140. package/src/commands/runtime-recovery.ts +0 -109
  141. package/src/commands/runtime-synthetic-baseline.ts +0 -70
  142. package/src/commands/runtime-uat.guard.test.ts +0 -175
  143. package/src/commands/runtime-uat.ts +0 -380
  144. package/src/commands/runtime.ts +0 -473
  145. package/src/commands/samples-list.ts +0 -39
  146. package/src/commands/samples-review.ts +0 -36
  147. package/src/commands/task.ts +0 -271
  148. package/src/commands/telemetry.ts +0 -349
  149. package/src/commands/trace.ts +0 -174
  150. package/src/commands/trajectory-db-unavailable.ts +0 -19
  151. package/src/commands/trajectory.ts +0 -64
  152. package/src/commands/version.ts +0 -49
  153. package/src/config-reader.ts +0 -122
  154. package/src/index.ts +0 -1276
  155. package/src/legacy/legacy-import.ts +0 -179
  156. package/src/legacy/session-history-import.ts +0 -203
  157. package/src/resolve-workspace.ts +0 -106
  158. package/src/services/__tests__/cli-output.test.ts +0 -130
  159. package/src/services/__tests__/evaluator-runner-deps.test.ts +0 -382
  160. package/src/services/__tests__/rulehost-readiness.test.ts +0 -363
  161. package/src/services/__tests__/runtime-adapter-resolver.test.ts +0 -793
  162. package/src/services/cli-output.ts +0 -95
  163. package/src/services/config-doctor.ts +0 -697
  164. package/src/services/console-launcher.ts +0 -537
  165. package/src/services/demo-rule-compiler.ts +0 -40
  166. package/src/services/demo-story-a-runner.ts +0 -471
  167. package/src/services/mainline-snapshot-assembler.ts +0 -579
  168. package/src/services/pain-flood-simulation-runner.ts +0 -462
  169. package/src/services/pd-config-loader.ts +0 -433
  170. package/src/services/proven-channel-baseline-runner.ts +0 -157
  171. package/src/services/quality-scorecard/data-extractor.ts +0 -150
  172. package/src/services/quality-scorecard/local-evaluator.ts +0 -142
  173. package/src/services/quality-scorecard/strong-model-gate.ts +0 -202
  174. package/src/services/resolve-runtime-from-pd-config.ts +0 -230
  175. package/src/services/rulehost-pipeline-runner.ts +0 -1214
  176. package/src/services/rulehost-readiness.ts +0 -326
  177. package/src/services/runtime-adapter-resolver.ts +0 -364
  178. package/src/services/synthetic-baseline-runner.ts +0 -400
  179. package/src/services/version-report.ts +0 -253
  180. package/src/services/workspace-tool-semantics.ts +0 -26
  181. package/src/utils/path-security.ts +0 -96
  182. package/src/utils/production-workspace-guard.test.ts +0 -157
  183. package/src/utils/production-workspace-guard.ts +0 -210
  184. package/tests/bdd/cli-contract.steps.ts +0 -346
  185. package/tests/bdd/principles-stats.steps.ts +0 -211
  186. package/tests/bdd/support/gherkin-loader.ts +0 -147
  187. package/tests/bdd/support/repo-root.ts +0 -62
  188. package/tests/bdd/support/vitest-bdd.ts +0 -179
  189. package/tests/commands/admission-gate-coverage.test.ts +0 -79
  190. package/tests/commands/build-trajectory-evidence.test.ts +0 -508
  191. package/tests/commands/candidate-audit-repair.test.ts +0 -421
  192. package/tests/commands/candidate-intake.test.ts +0 -732
  193. package/tests/commands/candidate-internalization-backfill.test.ts +0 -548
  194. package/tests/commands/candidate-internalize-lineage.test.ts +0 -628
  195. package/tests/commands/candidate-internalize.test.ts +0 -299
  196. package/tests/commands/candidate-route.test.ts +0 -329
  197. package/tests/commands/candidate-show.test.ts +0 -95
  198. package/tests/commands/cli-command-tree.test.ts +0 -144
  199. package/tests/commands/cli-help-snapshot.test.ts +0 -155
  200. package/tests/commands/cli-skill-contract.test.ts +0 -121
  201. package/tests/commands/codex-consent-reversibility.steps.test.ts +0 -299
  202. package/tests/commands/codex-ingest-quarantine.test.ts +0 -136
  203. package/tests/commands/codex-setup.test.ts +0 -297
  204. package/tests/commands/codex-worker-daemon.test.ts +0 -95
  205. package/tests/commands/codex-worker-registration.test.ts +0 -207
  206. package/tests/commands/config-doctor.test.ts +0 -336
  207. package/tests/commands/console-launcher-edge-cases.test.ts +0 -388
  208. package/tests/commands/console-open.test.ts +0 -1381
  209. package/tests/commands/context.test.ts +0 -114
  210. package/tests/commands/demo-story-a.test.ts +0 -318
  211. package/tests/commands/diagnose.test.ts +0 -1803
  212. package/tests/commands/errors-list.test.ts +0 -679
  213. package/tests/commands/evolution-tasks-list.test.ts +0 -41
  214. package/tests/commands/evolution-tasks-show.test.ts +0 -46
  215. package/tests/commands/health-codex.test.ts +0 -349
  216. package/tests/commands/health-host-wiring.test.ts +0 -76
  217. package/tests/commands/health-reliability.test.ts +0 -99
  218. package/tests/commands/health.test.ts +0 -413
  219. package/tests/commands/intent.test.ts +0 -321
  220. package/tests/commands/legacy-cleanup.test.ts +0 -148
  221. package/tests/commands/pain-evidence.test.ts +0 -518
  222. package/tests/commands/pain-list.test.ts +0 -219
  223. package/tests/commands/pain-record-async.test.ts +0 -335
  224. package/tests/commands/pain-record-session-parser.test.ts +0 -228
  225. package/tests/commands/pain-record.test.ts +0 -851
  226. package/tests/commands/pain-retry.test.ts +0 -1121
  227. package/tests/commands/plugin-config-resolution-cutover.test.ts +0 -229
  228. package/tests/commands/pri-393-runtime-config-unification.test.ts +0 -443
  229. package/tests/commands/principles-stats-wiring.test.ts +0 -135
  230. package/tests/commands/principles-stats.test.ts +0 -274
  231. package/tests/commands/product-path-regression.test.ts +0 -86
  232. package/tests/commands/proven-channel-baseline.test.ts +0 -441
  233. package/tests/commands/rulecode.test.ts +0 -177
  234. package/tests/commands/run-rulehost-handler.test.ts +0 -908
  235. package/tests/commands/runtime-activation-approve-flag-wiring.test.ts +0 -227
  236. package/tests/commands/runtime-activation-deactivate-flag-wiring.test.ts +0 -167
  237. package/tests/commands/runtime-activation-dispatch-flag-wiring.test.ts +0 -262
  238. package/tests/commands/runtime-activation-governance-audit.test.ts +0 -95
  239. package/tests/commands/runtime-activation-list-flag-wiring.test.ts +0 -193
  240. package/tests/commands/runtime-activation-promote-flag-wiring.test.ts +0 -248
  241. package/tests/commands/runtime-activation-shadow-telemetry.test.ts +0 -130
  242. package/tests/commands/runtime-activation.test.ts +0 -2052
  243. package/tests/commands/runtime-artifact-repair-registration.test.ts +0 -74
  244. package/tests/commands/runtime-artifact-repair.test.ts +0 -404
  245. package/tests/commands/runtime-canary.test.ts +0 -430
  246. package/tests/commands/runtime-compatibility-scan.test.ts +0 -146
  247. package/tests/commands/runtime-diagnostics-export.test.ts +0 -175
  248. package/tests/commands/runtime-features.test.ts +0 -249
  249. package/tests/commands/runtime-health-snapshot.test.ts +0 -358
  250. package/tests/commands/runtime-init-empty-workspace.test.ts +0 -252
  251. package/tests/commands/runtime-init.test.ts +0 -420
  252. package/tests/commands/runtime-internalization-enqueue-successors.test.ts +0 -782
  253. package/tests/commands/runtime-internalization-integrity-repair.test.ts +0 -239
  254. package/tests/commands/runtime-internalization-integrity.test.ts +0 -140
  255. package/tests/commands/runtime-internalization-queue.test.ts +0 -380
  256. package/tests/commands/runtime-internalization-retry-owner-authority.test.ts +0 -431
  257. package/tests/commands/runtime-internalization-run-once-evaluator-parity.test.ts +0 -269
  258. package/tests/commands/runtime-internalization-run-once-language.test.ts +0 -303
  259. package/tests/commands/runtime-internalization-run-once-real-config.test.ts +0 -237
  260. package/tests/commands/runtime-internalization-run-once-rollout-parity.test.ts +0 -706
  261. package/tests/commands/runtime-internalization-run-once.test.ts +0 -1791
  262. package/tests/commands/runtime-internalization-wake-once.test.ts +0 -171
  263. package/tests/commands/runtime-internalization.test.ts +0 -53
  264. package/tests/commands/runtime-pain-flood-simulation.test.ts +0 -418
  265. package/tests/commands/runtime-pruning.test.ts +0 -694
  266. package/tests/commands/runtime-recovery-failed-tasks.test.ts +0 -328
  267. package/tests/commands/runtime-recovery.test.ts +0 -120
  268. package/tests/commands/runtime-synthetic-baseline.test.ts +0 -249
  269. package/tests/commands/runtime-uat.test.ts +0 -397
  270. package/tests/commands/runtime.test.ts +0 -392
  271. package/tests/commands/samples-list.test.ts +0 -43
  272. package/tests/commands/samples-review.test.ts +0 -41
  273. package/tests/commands/task.test.ts +0 -153
  274. package/tests/commands/telemetry.test.ts +0 -190
  275. package/tests/commands/trace.test.ts +0 -316
  276. package/tests/config-reader.test.ts +0 -143
  277. package/tests/e2e/candidate-intake-e2e.test.ts +0 -338
  278. package/tests/e2e/cli-full-flow.test.ts +0 -233
  279. package/tests/e2e/cross-package-acceptance.test.ts +0 -635
  280. package/tests/helpers/pd-cli-path.ts +0 -5
  281. package/tests/pd-cli-smoke.test.ts +0 -13
  282. package/tests/resolve-workspace.test.ts +0 -196
  283. package/tests/services/config-doctor-signal-health.test.ts +0 -109
  284. package/tests/services/console-launcher.test.ts +0 -114
  285. package/tests/services/demo-rule-compiler.test.ts +0 -242
  286. package/tests/services/mainline-snapshot-assembler.test.ts +0 -572
  287. package/tests/services/pd-config-loader.test.ts +0 -505
  288. package/tests/services/proven-channel-baseline-runner.test.ts +0 -30
  289. package/tests/services/quality-scorecard/strong-model-gate.test.ts +0 -133
  290. package/tests/services/resolve-runtime-from-pd-config.test.ts +0 -485
  291. package/tests/services/rulehost-pipeline-e2e.test.ts +0 -538
  292. package/tests/services/rulehost-pipeline-runner.test.ts +0 -1242
  293. package/tests/services/workspace-tool-semantics.test.ts +0 -76
  294. package/tests/utils/path-security.test.ts +0 -180
  295. package/tsconfig.json +0 -26
  296. package/vitest.config.ts +0 -10
@@ -1,1629 +0,0 @@
1
- import * as path from 'path';
2
- import * as fs from 'node:fs';
3
- import { createHash, randomUUID } from 'node:crypto';
4
- import type { Command } from 'commander';
5
- import {
6
- RuntimeStateManager,
7
- ActivationDispatcher,
8
- PromptWriter,
9
- DeferArchiveWriter,
10
- RuleHostWriter,
11
- createProductionGateDeps,
12
- SqliteActivationStateStore,
13
- SqliteApprovalQueueStore,
14
- SqlitePIArtifactStore,
15
- ApprovalQueue,
16
- ApprovalCompletionService,
17
- isArtifactRevisionOf,
18
- extractEvidenceRefs,
19
- extractPrincipleId,
20
- isFeatureEnabled,
21
- RuleCodeOwnerDecisionService,
22
- PromotionReadinessReader,
23
- SqliteActivationSafetyStore,
24
- collectOpenClawPromotionChecks,
25
- summarizeRuleCodeShadowEvents,
26
- buildPromotionEvidenceSnapshot,
27
- } from '@principles/core/runtime-v2';
28
- import { resolveOwnerIdentity, defaultOwnerIdentityHomeDir } from '@principles/core/runtime-v2';
29
- import type {
30
- ActivationDecision,
31
- PIArtifactSnapshot,
32
- RolloutActivationDecision,
33
- ApprovalDecisionResult,
34
- ApprovalCompletionResult,
35
- } from '@principles/core/runtime-v2';
36
- import type { PIArtifactRecord, ActivationStatusRecord, PromotionEvidenceSnapshot } from '@principles/core/runtime-v2';
37
- import { resolvePromotionHostLiveness } from '@principles/host-runtime';
38
- import { authorizeGovernanceAction, writeGovernanceAction } from 'principles-disciple/governance-audit';
39
- import { resolveWorkspaceDir } from '../resolve-workspace.js';
40
- import { loadPdConfig, computeFlagsFromLoadResult } from '../services/pd-config-loader.js';
41
- import { resolveWorkspaceToolSemantics } from '../services/workspace-tool-semantics.js';
42
-
43
- /**
44
- * Type guard for parsed JSON objects (rc-2-no-as-bypass).
45
- * Replaces `as Record<string, unknown>` casts on untrusted contentJson.
46
- */
47
- function isRecord(value: unknown): value is Record<string, unknown> {
48
- return value !== null && value !== undefined && typeof value === 'object' && !Array.isArray(value);
49
- }
50
-
51
- function unavailableShadowSummary(): PromotionEvidenceSnapshot['shadowSummary'] {
52
- return {
53
- observed: null, matched: null, wouldBlock: null, wouldAllow: null,
54
- requireApproval: null, autoCorrect: null, errors: null, neutralControl: null,
55
- firstObservedAt: null, lastObservedAt: null,
56
- };
57
- }
58
-
59
- /**
60
- * PRI-577: RuleCode event telemetry candidate directories, in priority order.
61
- *
62
- * Runtime V2 convention is `.pd/logs`, but the v1 EventLog writer
63
- * (openclaw-plugin `src/core/event-log.ts`) still emits `events_*.jsonl` under
64
- * `.state/logs`. No production code ever created `.pd/logs`, so scanning only
65
- * that path made every shadow metric report "unavailable" while 2500+ real
66
- * evaluations sat unread in `.state/logs`. Readers scan both candidates until
67
- * the writer migrates (ERR-031: both readers derive from this same list).
68
- */
69
- export const RULECODE_EVENT_LOG_CANDIDATE_DIRS: readonly string[] = ['.pd/logs', '.state/logs'];
70
-
71
- export interface CollectedRuleCodeEventEntries {
72
- entries: unknown[];
73
- /** Number of candidate directories that actually exist on disk. */
74
- sourceDirsFound: number;
75
- }
76
-
77
- /**
78
- * Collect rulehost telemetry entries from all candidate log directories.
79
- * Malformed lines are excluded individually. A directory counts as a source
80
- * only after it can be enumerated, so an unreadable path cannot be mistaken
81
- * for a healthy channel with zero events (ERR-002).
82
- *
83
- * Exact lines copied between candidate directories are deduplicated by
84
- * priority. Different events in same-named daily files are retained.
85
- */
86
- export function collectRuleCodeEventEntries(workspaceDir: string): CollectedRuleCodeEventEntries {
87
- const entries: unknown[] = [];
88
- let sourceDirsFound = 0;
89
- const higherPriorityLines = new Set<string>();
90
- for (const candidate of RULECODE_EVENT_LOG_CANDIDATE_DIRS) {
91
- const logsDir = path.join(workspaceDir, ...candidate.split('/'));
92
- if (!fs.existsSync(logsDir)) continue;
93
- try {
94
- const files = fs.readdirSync(logsDir)
95
- .filter(name => /^events_.*\.jsonl$/.test(name))
96
- .sort()
97
- .slice(-7);
98
- sourceDirsFound += 1;
99
- const currentSourceLines: string[] = [];
100
- for (const file of files) {
101
- const lines = fs.readFileSync(path.join(logsDir, file), 'utf8').split('\n').filter(Boolean);
102
- for (const line of lines) {
103
- currentSourceLines.push(line);
104
- if (higherPriorityLines.has(line)) continue;
105
- try { entries.push(JSON.parse(line) as unknown); } catch { /* exclude malformed telemetry */ }
106
- }
107
- }
108
- for (const line of currentSourceLines) higherPriorityLines.add(line);
109
- } catch { /* unreadable directory contributes no entries */ }
110
- }
111
- return { entries, sourceDirsFound };
112
- }
113
-
114
- /** Exported for PRI-577 regression tests and reuse by promote evidence assembly. */
115
- export function readShadowSummaryForActivation(workspaceDir: string, activationId: string): PromotionEvidenceSnapshot['shadowSummary'] {
116
- const { entries, sourceDirsFound } = collectRuleCodeEventEntries(workspaceDir);
117
- if (sourceDirsFound === 0) return unavailableShadowSummary();
118
- return summarizeRuleCodeShadowEvents(entries, activationId);
119
- }
120
-
121
- interface ActivationDispatchOptions {
122
- workspace?: string;
123
- artifactId?: string;
124
-
125
-
126
- channel?: string;
127
- dryRun?: boolean;
128
- confirm?: boolean;
129
- json?: boolean;
130
- }
131
-
132
- function mapRolloutDecision(reviewDecision: string | undefined): RolloutActivationDecision {
133
- // P0-E (MVP_CORE_LOOP_CONTRACT INV-04): needs_revision 绝不映射 require_approval。
134
- // 旧映射让"需修改"的评审结论伪装成正常审批进入 approval 队列(审计 ISSUE-027)。
135
- // needs_revision 的出边是 revision loop(自动 reopen 修订目标),由
136
- // rollout-reviewer-runner.handleRevisionRouting / auto-consumer 承担;
137
- // CLI dispatch 对 needs_revision artifact 一律 refuse(structured reason + nextAction)。
138
- if (!reviewDecision) return 'require_approval';
139
- if (reviewDecision === 'approve_rollout') return 'auto_activate';
140
- if (reviewDecision === 'reject') return 'reject';
141
- return 'require_approval';
142
- }
143
-
144
- /** 提取 artifact 上的原始 review decision(未映射),用于 needs_revision 拒绝分支 */
145
- function extractRawRolloutReviewDecision(artifact: PIArtifactRecord): string | null {
146
- try {
147
- const parsed = JSON.parse(artifact.contentJson) as Record<string, unknown>;
148
- if (parsed && typeof parsed === 'object') {
149
- const review = parsed.review as Record<string, unknown> | undefined;
150
- if (review && typeof review.decision === 'string') {
151
- return review.decision;
152
- }
153
- if (typeof parsed.rolloutDecision === 'string') {
154
- return parsed.rolloutDecision;
155
- }
156
- }
157
- } catch {
158
- return null;
159
- }
160
- return null;
161
- }
162
-
163
- function extractRolloutDecisionFromArtifact(artifact: PIArtifactRecord): RolloutActivationDecision {
164
- return mapRolloutDecision(extractRawRolloutReviewDecision(artifact) ?? undefined);
165
- }
166
-
167
- function toSnapshot(record: PIArtifactRecord): PIArtifactSnapshot {
168
- return {
169
- artifactId: record.artifactId,
170
- artifactKind: record.artifactKind,
171
- sourceTaskId: record.sourceTaskId,
172
- sourcePrincipleId: record.sourcePrincipleId,
173
- sourceRuleId: record.sourceRuleId,
174
- lineageArtifactIds: record.lineageArtifactIds,
175
- validationStatus: record.validationStatus,
176
- contentJson: record.contentJson,
177
- createdAt: record.createdAt,
178
- updatedAt: record.updatedAt,
179
- };
180
- }
181
-
182
- function formatTextOutput(result: ActivationDecision): string {
183
- const lines: string[] = [];
184
- switch (result.decision) {
185
- case 'would_activate':
186
- lines.push(`Activation: would_activate`);
187
- lines.push(` activationId: ${result.activationId}`);
188
- lines.push(` action: ${result.action}`);
189
- lines.push(` targetRef: ${result.targetRef}`);
190
- break;
191
- case 'activated':
192
- lines.push(`Activation: activated`);
193
- lines.push(` activationId: ${result.activationId}`);
194
- lines.push(` action: ${result.action}`);
195
- lines.push(` targetRef: ${result.targetRef}`);
196
- break;
197
- case 'already_activated':
198
- lines.push(`Activation: already_activated`);
199
- lines.push(` activationId: ${result.activationId}`);
200
- lines.push(` action: ${result.action}`);
201
- lines.push(` targetRef: ${result.targetRef}`);
202
- break;
203
- case 'refused':
204
- lines.push(`Activation: refused`);
205
- lines.push(` reason: ${result.reason}`);
206
- if (result.riskLevel) lines.push(` riskLevel: ${result.riskLevel}`);
207
- if (result.channel) lines.push(` channel: ${result.channel}`);
208
- break;
209
- case 'invalid_artifact':
210
- lines.push(`Activation: invalid_artifact`);
211
- lines.push(` reason: ${result.reason}`);
212
- break;
213
- }
214
- return lines.join('\n');
215
- }
216
-
217
- function isNegativeDecision(decision: ActivationDecision['decision']): boolean {
218
- return decision === 'refused' || decision === 'invalid_artifact';
219
- }
220
-
221
- export async function handleRuntimeActivationDispatch(opts: ActivationDispatchOptions): Promise<void> {
222
- if (opts.dryRun && opts.confirm) {
223
- console.error('Error: --dry-run and --confirm are mutually exclusive');
224
- process.exitCode = 1;
225
- return;
226
- }
227
-
228
- if (!opts.artifactId) {
229
- console.error('Error: --artifact-id is required');
230
- process.exitCode = 1;
231
- return;
232
- }
233
-
234
- const confirm = opts.confirm === true;
235
- const channel = (opts.channel ?? 'prompt') as 'prompt' | 'defer_archive' | 'skill' | 'code_tool_hook';
236
-
237
- const workspaceDir = opts.workspace ? path.resolve(opts.workspace) : resolveWorkspaceDir();
238
- const stateManager = new RuntimeStateManager({ workspaceDir });
239
-
240
- // PRI-634-F R2 (review P1): code_tool_hook activation resolves the host
241
- // tool registry from DURABLE workspace provenance (the declaration the
242
- // host persisted). Refuse — never guess a host, never silently skip the
243
- // reliability validation — when it is unavailable.
244
- const toolSemanticsResolution = resolveWorkspaceToolSemantics(workspaceDir);
245
- if (channel === 'code_tool_hook' && !toolSemanticsResolution.ok) {
246
- const refused: ActivationDecision = {
247
- decision: 'refused',
248
- reason: toolSemanticsResolution.reason,
249
- nextAction: toolSemanticsResolution.nextAction,
250
- channel,
251
- };
252
- if (opts.json) {
253
- console.log(JSON.stringify(refused, null, 2));
254
- } else {
255
- console.log(formatTextOutput(refused));
256
- console.log(' nextAction: ' + toolSemanticsResolution.nextAction);
257
- }
258
- process.exitCode = 1;
259
- return;
260
- }
261
- const workspaceToolSemantics = toolSemanticsResolution.ok ? toolSemanticsResolution.registry : undefined;
262
-
263
- try {
264
- await stateManager.initialize();
265
- const artifactRecord = await stateManager.piArtifactStore.getArtifactById(opts.artifactId);
266
- if (!artifactRecord) {
267
- const result: ActivationDecision = { decision: 'invalid_artifact', reason: 'artifact_not_found' };
268
- if (opts.json) {
269
- console.log(JSON.stringify(result, null, 2));
270
- } else {
271
- console.log(formatTextOutput(result));
272
- }
273
- process.exitCode = 1;
274
- return;
275
- }
276
-
277
- const artifactSnapshot = toSnapshot(artifactRecord);
278
-
279
- // P0-E: needs_revision artifact 不允许手动 dispatch 入 approval (INV-04)。
280
- // 出边是 revision loop: auto-consumer 会自动 reopen 修订目标;
281
- // 手动场景给出结构化 next action (cli-6)。
282
- const rawReviewDecision = extractRawRolloutReviewDecision(artifactRecord);
283
- if (rawReviewDecision === 'needs_revision') {
284
- const refused: ActivationDecision = {
285
- decision: 'refused',
286
- reason: 'rollout_needs_revision_not_dispatchable',
287
- nextAction: 'Revision is handled by the automatic revision loop (rollout_reviewer reopens scribe/artificer). Inspect: pd runtime internalization list --json; advance manually: pd runtime internalization run-once --runner rollout_reviewer',
288
- channel,
289
- riskLevel: channel === 'code_tool_hook' ? 'high' : channel === 'skill' ? 'medium' : 'low',
290
- };
291
- if (opts.json) {
292
- console.log(JSON.stringify(refused, null, 2));
293
- } else {
294
- console.log(formatTextOutput(refused));
295
- console.log(' nextAction: ' + refused.nextAction);
296
- }
297
- process.exitCode = 1;
298
- return;
299
- }
300
-
301
- const rolloutDecision = extractRolloutDecisionFromArtifact(artifactRecord);
302
-
303
- const artifactReadModel = {
304
- getArtifactById: async (id: string): Promise<PIArtifactSnapshot | null> => {
305
- if (id === opts.artifactId) return artifactSnapshot;
306
- const rec = await stateManager.piArtifactStore.getArtifactById(id);
307
- return rec ? toSnapshot(rec) : null;
308
- },
309
- };
310
-
311
- const activationStateStore = new SqliteActivationStateStore(stateManager.connection);
312
- const approvalQueueStore = new SqliteApprovalQueueStore(stateManager.connection);
313
- const featureFlags = computeFlagsFromLoadResult(loadPdConfig(workspaceDir));
314
- // Wire all three MVP-Core writers, including RuleHostWriter for code_tool_hook.
315
- // PRI-408: fixes P0 breakpoint where code_tool_hook channel could not activate.
316
- const dispatcher = new ActivationDispatcher(
317
- artifactReadModel,
318
- activationStateStore,
319
- {
320
- writers: [
321
- new PromptWriter(),
322
- new RuleHostWriter({
323
- // PRI-634-F R2: registry from durable host provenance (the host
324
- // declaration persisted in the workspace) + the real workspace
325
- // root — production-identical replay and tool-existence
326
- // validation. No host is guessed (review P1).
327
- gateDeps: createProductionGateDeps({
328
- projectDir: workspaceDir,
329
- ...(workspaceToolSemantics ? { toolSemantics: workspaceToolSemantics } : {}),
330
- }),
331
- featureFlagProbe: (flagId) => featureFlags.flags[flagId]?.enabled === true,
332
- projectDir: workspaceDir,
333
- ...(workspaceToolSemantics ? { toolSemantics: workspaceToolSemantics } : {}),
334
- }),
335
- new DeferArchiveWriter(),
336
- ],
337
- approvalQueueStore,
338
- },
339
- );
340
-
341
- const result = await dispatcher.dispatch({
342
- artifactId: opts.artifactId,
343
- channel,
344
- rolloutDecision,
345
- actor: { kind: 'system', source: 'rollout_reviewer' },
346
- now: new Date().toISOString(),
347
- confirm,
348
- });
349
-
350
- if (opts.json) {
351
- console.log(JSON.stringify(result, null, 2));
352
- } else {
353
- console.log(formatTextOutput(result));
354
- }
355
-
356
- if (isNegativeDecision(result.decision)) {
357
- process.exitCode = 1;
358
- }
359
- } finally {
360
- await stateManager.close();
361
- }
362
- }
363
-
364
- // ── Deactivate Command (PRI-408 Contract E) ─────────────────────────────────
365
-
366
- interface ActivationDeactivateOptions {
367
- workspace?: string;
368
- activationId?: string;
369
- reasonCode?: string;
370
- json?: boolean;
371
- }
372
-
373
- export interface DeactivateResult {
374
- ok: boolean;
375
- activationId: string;
376
- deactivatedAt?: string;
377
- reason?: string;
378
- nextAction?: string;
379
- }
380
-
381
- export async function handleRuntimeActivationDeactivate(opts: ActivationDeactivateOptions): Promise<void> {
382
- if (!opts.activationId) {
383
- const result: DeactivateResult = {
384
- ok: false,
385
- activationId: '',
386
- reason: 'activation_id_required',
387
- nextAction: 'Provide --activation-id <id> from `pd activation list`',
388
- };
389
- if (opts.json) {
390
- console.log(JSON.stringify(result, null, 2));
391
- } else {
392
- console.error(`Error: --activation-id is required`);
393
- console.error(`Next action: ${result.nextAction}`);
394
- }
395
- process.exitCode = 1;
396
- return;
397
- }
398
-
399
- const workspaceDir = opts.workspace ? path.resolve(opts.workspace) : resolveWorkspaceDir();
400
- const stateManager = new RuntimeStateManager({ workspaceDir });
401
-
402
- try {
403
- await stateManager.initialize();
404
- const activationStateStore = new SqliteActivationStateStore(stateManager.connection);
405
- const deactivatedAt = new Date().toISOString();
406
-
407
- try {
408
- writeGovernanceAction(path.join(workspaceDir, '.pd'), {
409
- action: 'deactivate',
410
- activationId: opts.activationId,
411
- actor: 'cli',
412
- reasonCode: opts.reasonCode?.trim() || 'cli_deactivate_requested',
413
- outcome: 'authorized',
414
- });
415
- } catch (auditErr: unknown) {
416
- const message = auditErr instanceof Error ? auditErr.message : String(auditErr);
417
- const result: DeactivateResult = {
418
- ok: false,
419
- activationId: opts.activationId,
420
- reason: `governance_audit_failed: ${message}`,
421
- nextAction: 'Restore access to .pd/logs and retry; the activation was not changed.',
422
- };
423
- if (opts.json) console.log(JSON.stringify(result, null, 2));
424
- else {
425
- console.error(`Error: ${result.reason}`);
426
- console.error(`Next action: ${result.nextAction}`);
427
- }
428
- process.exitCode = 1;
429
- return;
430
- }
431
-
432
- // Idempotent deactivate: returns false if already deactivated or not found.
433
- // Both cases are safe to call repeatedly (Contract E: rollback must be idempotent).
434
- const success = await activationStateStore.deactivateActivation(opts.activationId, deactivatedAt);
435
-
436
- const result: DeactivateResult = success
437
- ? { ok: true, activationId: opts.activationId, deactivatedAt }
438
- : {
439
- ok: false,
440
- activationId: opts.activationId,
441
- reason: 'not_found_or_already_deactivated',
442
- nextAction: 'Check activation ID with `pd activation list`, or it may already be deactivated',
443
- };
444
-
445
- if (opts.json) {
446
- // Strict JSON mode: exactly one parseable JSON object on stdout
447
- console.log(JSON.stringify(result, null, 2));
448
- } else {
449
- if (success) {
450
- console.log(`Deactivated: ${opts.activationId}`);
451
- console.log(` deactivatedAt: ${deactivatedAt}`);
452
- } else {
453
- console.log(`Not deactivated: ${opts.activationId}`);
454
- console.log(` reason: ${result.reason}`);
455
- console.log(` nextAction: ${result.nextAction}`);
456
- }
457
- }
458
-
459
- if (!success) {
460
- process.exitCode = 1;
461
- }
462
- } catch (err: unknown) {
463
- // P2 #5: initialize/DB exceptions must not break --json contract.
464
- const errMsg = err instanceof Error ? err.message : String(err);
465
- const result: DeactivateResult = {
466
- ok: false,
467
- activationId: opts.activationId,
468
- reason: `initialize_failed: ${errMsg}`,
469
- nextAction: 'Check workspace directory and DB integrity. Try `pd runtime diagnostics`.',
470
- };
471
- if (opts.json) {
472
- console.log(JSON.stringify(result, null, 2));
473
- } else {
474
- console.error(`Error: ${result.reason}`);
475
- console.error(`Next action: ${result.nextAction}`);
476
- }
477
- process.exitCode = 1;
478
- } finally {
479
- await stateManager.close();
480
- }
481
- }
482
-
483
- export interface ActivationPromoteOptions {
484
- workspace?: string;
485
- activationId?: string;
486
- dryRun?: boolean;
487
- confirm?: boolean;
488
- json?: boolean;
489
- artifactId?: string;
490
- artifactDigest?: string;
491
- controlVersion?: number;
492
- idempotencyKey?: string;
493
- reasonCode?: string;
494
- note?: string;
495
- }
496
-
497
- export interface ActivationPromoteResult {
498
- ok: boolean;
499
- decision: 'would_promote' | 'promoted' | 'refused';
500
- activationId: string;
501
- promotedAt?: string;
502
- reason?: string;
503
- reasonCode?: string;
504
- summary?: string;
505
- failedChecks?: { checkId: string; reasonCode: string }[];
506
- nextAction?: string;
507
- }
508
-
509
- export async function handleRuntimeActivationPromote(opts: ActivationPromoteOptions): Promise<void> {
510
- const activationId = opts.activationId?.trim() ?? '';
511
- const refuse = (reason: string, nextAction: string, details?: { summary?: string; failedChecks?: { checkId: string; reasonCode: string }[] }): void => {
512
- const result: ActivationPromoteResult = {
513
- ok: false, decision: 'refused', activationId, reason, reasonCode: reason, nextAction,
514
- summary: details?.summary, failedChecks: details?.failedChecks,
515
- };
516
- if (opts.json) console.log(JSON.stringify(result));
517
- else {
518
- console.error(`Promotion refused: ${reason}`);
519
- console.error(`Next action: ${nextAction}`);
520
- }
521
- process.exitCode = 1;
522
- };
523
-
524
- if (!activationId) {
525
- refuse('activation_id_required', 'Provide --activation-id from `pd activation list --channel code_tool_hook`.');
526
- return;
527
- }
528
- if (opts.dryRun === true && opts.confirm === true) {
529
- refuse('dry_run_confirm_mutually_exclusive', 'Choose either --dry-run or --confirm.');
530
- return;
531
- }
532
-
533
- let stateManager: RuntimeStateManager | undefined;
534
- try {
535
- const workspaceDir = opts.workspace ? path.resolve(opts.workspace) : resolveWorkspaceDir();
536
- const flags = computeFlagsFromLoadResult(loadPdConfig(workspaceDir));
537
- // PRI-634-F R2: workspace-provenance registry — readiness evaluates with
538
- // the same tool semantics as dispatch (readiness is a read-model probe,
539
- // so unresolvable provenance degrades to legacy rather than refusing).
540
- const readinessToolSemantics = resolveWorkspaceToolSemantics(workspaceDir);
541
- const workspaceToolSemantics = readinessToolSemantics.ok ? readinessToolSemantics.registry : undefined;
542
- // PRI-813: the promotion host contract comes from the workspace's REAL
543
- // host declarations. A Codex (or multi-host) workspace resolves fail
544
- // closed with a null contract — the promotion checks then report
545
- // runtime_compatibility / runtime_shadow_evidence as NOT passed instead
546
- // of silently inheriting the OpenClaw capability claim.
547
- const promotionHost = resolvePromotionHostLiveness(workspaceDir);
548
- // ADR-0022 (PRI-578): single resolver — env > ~/.pd/owner.json > none
549
- const identity = resolveOwnerIdentity(process.env, defaultOwnerIdentityHomeDir());
550
- const { ownerId, credentialId } = identity;
551
- const consoleToken = process.env.PD_CONSOLE_TOKEN?.trim();
552
- const operatorId = process.env.USERNAME?.trim() || process.env.USER?.trim();
553
- const actor = ownerId && credentialId && consoleToken
554
- ? {
555
- principal: { kind: 'configured_owner' as const, ownerId },
556
- authentication: { method: 'cli_owner_credential' as const, credentialId },
557
- ...(operatorId ? { operator: { kind: 'local_user' as const, operatorId } } : {}),
558
- }
559
- : {
560
- principal: { kind: 'break_glass' as const, reason: 'local_no_auth_emergency' as const },
561
- authentication: { method: 'local_break_glass' as const },
562
- };
563
- const getStateManager = async (): Promise<RuntimeStateManager> => {
564
- if (!stateManager) {
565
- stateManager = new RuntimeStateManager({ workspaceDir, readonly: opts.dryRun === true });
566
- await stateManager.initialize();
567
- }
568
- return stateManager;
569
- };
570
- const service = new RuleCodeOwnerDecisionService({
571
- ownerLiveDecisionEnabled: () => isFeatureEnabled(flags, 'rulecode_owner_live_decision'),
572
- safetyControlsEnabled: () => isFeatureEnabled(flags, 'rulecode_safety_controls'),
573
- evaluateReadiness: async request => {
574
- const manager = await getStateManager();
575
- const activationStore = new SqliteActivationStateStore(manager.connection);
576
- const writer = new RuleHostWriter({
577
- // PRI-634-F R2: readiness replay uses workspace-provenance registry
578
- // + real workspace root, matching the dispatch path exactly.
579
- gateDeps: createProductionGateDeps({
580
- projectDir: workspaceDir,
581
- ...(workspaceToolSemantics ? { toolSemantics: workspaceToolSemantics } : {}),
582
- }),
583
- featureFlagProbe: flagId => isFeatureEnabled(flags, flagId),
584
- projectDir: workspaceDir,
585
- ...(workspaceToolSemantics ? { toolSemantics: workspaceToolSemantics } : {}),
586
- });
587
- const reader = new PromotionReadinessReader({
588
- listCodeToolHookActivations: () => activationStore.listCodeToolHookActivations(false),
589
- getArtifactById: artifactId => manager.piArtifactStore.getArtifactById(artifactId),
590
- computeArtifactDigest: artifact => `sha256:${createHash('sha256').update(JSON.stringify(artifact), 'utf8').digest('hex')}`,
591
- validateProductionArtifact: artifact => writer.canActivate(artifact),
592
- collectHostChecks: async artifact => {
593
- const liveArtifacts: PIArtifactSnapshot[] = [];
594
- const activations = await activationStore.listCodeToolHookActivations(false);
595
- for (const active of activations) {
596
- if (active.action !== 'code_tool_hook_live_activate' || active.deactivatedAt !== null) continue;
597
- const liveArtifact = await manager.piArtifactStore.getArtifactById(active.artifactId);
598
- if (liveArtifact) liveArtifacts.push(liveArtifact);
599
- }
600
- return collectOpenClawPromotionChecks(artifact, {
601
- ownerIdentityConfigured: actor.principal.kind === 'configured_owner'
602
- && actor.authentication.method === 'cli_owner_credential',
603
- safetyControlsEnabled: isFeatureEnabled(flags, 'rulecode_safety_controls'),
604
- hostContract: promotionHost.ok ? promotionHost.hostContract : null,
605
- existingLiveArtifacts: liveArtifacts,
606
- validateProductionArtifact: value => writer.canActivate(value),
607
- });
608
- },
609
- buildEvidenceSnapshot: (checks, artifact, evaluationId) => {
610
- return buildPromotionEvidenceSnapshot({
611
- activationId,
612
- evaluationId,
613
- checks,
614
- artifact,
615
- expectedArtifactDigest: request.expectedArtifactDigest,
616
- ownerIdentity: actor,
617
- hostRuntimeVersion: promotionHost.ok ? promotionHost.hostRuntimeVersion : promotionHost.reason,
618
- shadowSummary: readShadowSummaryForActivation(workspaceDir, activationId),
619
- });
620
- },
621
- newEvaluationId: () => `readiness-${randomUUID()}`,
622
- });
623
- return reader.evaluate(request);
624
- },
625
- commitPromotion: async input => {
626
- const manager = await getStateManager();
627
- return authorizeGovernanceAction(
628
- path.join(workspaceDir, '.pd'),
629
- {
630
- action: 'promote',
631
- activationId,
632
- actor: 'cli',
633
- reasonCode: opts.reasonCode?.trim() ?? '',
634
- outcome: 'authorized',
635
- },
636
- () => new SqliteActivationSafetyStore(manager.connection).commitPromotion(input),
637
- );
638
- },
639
- newDecisionId: () => `decision-${randomUUID()}`,
640
- now: () => new Date().toISOString(),
641
- });
642
- const result = await service.promote({
643
- activationId,
644
- expectedArtifactId: opts.artifactId?.trim() ?? '',
645
- expectedArtifactDigest: opts.artifactDigest?.trim() ?? '',
646
- expectedControlVersion: opts.controlVersion ?? 0,
647
- idempotencyKey: opts.idempotencyKey?.trim() ?? '',
648
- reasonCode: opts.reasonCode?.trim() ?? '',
649
- note: opts.note,
650
- confirmed: opts.confirm === true,
651
- dryRun: opts.dryRun === true,
652
- }, actor);
653
- if (!result.ok) {
654
- refuse(result.reasonCode, result.nextAction, { summary: result.summary, failedChecks: result.failedChecks });
655
- return;
656
- }
657
- if (result.decision === 'would_promote') {
658
- const output: ActivationPromoteResult = {
659
- ok: true, decision: 'would_promote', activationId: result.activationId,
660
- summary: `Readiness ${result.readinessEvaluationId} passed without mutation.`,
661
- nextAction: `Re-run with --confirm using evidence snapshot ${result.evidenceSnapshotDigest}.`,
662
- };
663
- if (opts.json) console.log(JSON.stringify(output));
664
- else console.log(`Would promote: ${result.activationId}`);
665
- return;
666
- }
667
- const output: ActivationPromoteResult = { ok: true, decision: 'promoted', activationId: result.activationId, promotedAt: result.promotedAt };
668
- if (opts.json) console.log(JSON.stringify(output));
669
- else console.log(`Promoted live: ${result.activationId}`);
670
- } catch (err: unknown) {
671
- refuse(
672
- `promotion_failed: ${err instanceof Error ? err.message : String(err)}`,
673
- 'Check workspace configuration and database integrity; no promotion was applied.',
674
- );
675
- } finally {
676
- await stateManager?.close();
677
- }
678
- }
679
-
680
- // ── List Activations Command (PRI-408 Contract D — observability) ────────────
681
-
682
- interface ActivationListOptions {
683
- workspace?: string;
684
- channel?: string;
685
- includeDeactivated?: boolean;
686
- json?: boolean;
687
- }
688
-
689
- export interface ActivationNextActionInput {
690
- deactivatedAt: string | null;
691
- contextVersion: 'v1' | 'v2' | undefined;
692
- v2FlagEnabled: boolean;
693
- mode: 'shadow' | 'live' | undefined;
694
- activationId: string;
695
- }
696
-
697
- export interface ActivationStatusDerivation {
698
- status: 'active' | 'deactivated' | 'suspended_by_flag';
699
- nextAction: string | undefined;
700
- }
701
-
702
- /**
703
- * Derive owner-facing status + nextAction for an activation record.
704
- *
705
- * Extract as a pure function so the CLI hints can be regression-tested.
706
- * Shadow activations point at the Owner decision contract instead of
707
- * advertising a raw lifecycle mutation that can bypass review evidence.
708
- */
709
- export function deriveActivationStatusAndNextAction(
710
- input: ActivationNextActionInput,
711
- ): ActivationStatusDerivation {
712
- const { deactivatedAt, contextVersion, v2FlagEnabled, mode, activationId } = input;
713
- if (deactivatedAt) {
714
- return { status: 'deactivated', nextAction: undefined };
715
- }
716
- if (contextVersion === 'v2' && !v2FlagEnabled) {
717
- return {
718
- status: 'suspended_by_flag',
719
- nextAction: `Enable rulecode_context_v2 flag or deactivate: pd activation deactivate --activation-id ${activationId}`,
720
- };
721
- }
722
- if (mode === 'shadow') {
723
- return {
724
- status: 'active',
725
- nextAction: 'Keep shadow; promotion requires an authenticated Owner decision, immutable evidence bindings, and a passing Promotion Readiness result.',
726
- };
727
- }
728
- if (mode === 'live') {
729
- return {
730
- status: 'active',
731
- nextAction: `pd activation deactivate --activation-id ${activationId}`,
732
- };
733
- }
734
- return { status: 'active', nextAction: undefined };
735
- }
736
-
737
- export async function handleRuntimeActivationList(opts: ActivationListOptions): Promise<void> {
738
- // P2 #5 fix: fail loud on invalid channel instead of silently listing all.
739
- const VALID_CHANNELS = new Set(['prompt', 'code_tool_hook', undefined]);
740
- if (opts.channel !== undefined && !VALID_CHANNELS.has(opts.channel)) {
741
- const result = {
742
- ok: false,
743
- reason: `invalid_channel: ${opts.channel}`,
744
- nextAction: 'Use one of: prompt, code_tool_hook, or omit --channel to list all',
745
- };
746
- if (opts.json) {
747
- console.log(JSON.stringify(result, null, 2));
748
- } else {
749
- console.error(`Error: invalid channel "${opts.channel}"`);
750
- console.error(`Next action: ${result.nextAction}`);
751
- }
752
- process.exitCode = 1;
753
- return;
754
- }
755
-
756
- const workspaceDir = opts.workspace ? path.resolve(opts.workspace) : resolveWorkspaceDir();
757
- const stateManager = new RuntimeStateManager({ workspaceDir });
758
-
759
- try {
760
- await stateManager.initialize();
761
- const activationStateStore = new SqliteActivationStateStore(stateManager.connection);
762
-
763
- // P2 #5 fix: pass includeDeactivated to the store so channel-specific queries
764
- // also return deactivated records when requested. Previously the SQL hardcoded
765
- // `WHERE deactivated_at IS NULL`, making --include-deactivated a no-op for
766
- // channel-filtered queries.
767
- let records;
768
- if (opts.channel === 'prompt') {
769
- records = await activationStateStore.listPromptActivations(opts.includeDeactivated ?? false);
770
- } else if (opts.channel === 'code_tool_hook') {
771
- records = await activationStateStore.listCodeToolHookActivations(opts.includeDeactivated ?? false);
772
- } else {
773
- records = await activationStateStore.listAllActivations();
774
- }
775
-
776
- // For listAllActivations, still apply the includeDeactivated filter at the
777
- // caller level since listAllActivations() does not take the parameter.
778
- const filtered = opts.includeDeactivated
779
- ? records
780
- : records.filter(r => r.deactivatedAt === null);
781
-
782
- // F9-1: Validate artifact_id → pi_artifacts.artifact_id reference for each
783
- // activation. A dangling reference means the activation cannot function
784
- // (RuleHost cannot load implementationCode, dispatcher cannot verify
785
- // lineage). Emit degraded status with reason + nextAction instead of
786
- // silently returning corrupted records (rc-9-no-silent-fallback,
787
- // rc-6-lineage-consistency; related ERR: ERR-002).
788
- const {piArtifactStore} = stateManager;
789
- const uniqueArtifactIds = new Set(filtered.map(r => r.artifactId));
790
- const danglingArtifactIds = new Set<string>();
791
- // PRI-491: Map artifactId to { contextVersion, evidenceRefs } extracted
792
- // from contentJson. rc-1/rc-2: contentJson is parsed as unknown and
793
- // type-narrowed; never `as`-cast without prior typeof check.
794
- const artifactMetadata = new Map<string, { contextVersion: 'v1' | 'v2'; evidenceRefs: string[] | null; principleId: string | null }>();
795
- for (const artifactId of uniqueArtifactIds) {
796
- try {
797
- const artifact = await piArtifactStore.getArtifactById(artifactId);
798
- if (!artifact) {
799
- danglingArtifactIds.add(artifactId);
800
- continue;
801
- }
802
- // PRI-491: Parse contentJson to extract contextVersion + evidenceRefs.
803
- // rc-1: treat parsed JSON as unknown; rc-2: narrow with typeof before use.
804
- let parsedContent: Record<string, unknown> | null = null;
805
- try {
806
- const parsed: unknown = JSON.parse(artifact.contentJson);
807
- if (isRecord(parsed)) {
808
- parsedContent = parsed;
809
- }
810
- } catch {
811
- // Malformed contentJson - treat as no metadata (not dangling, just unreadable)
812
- }
813
- const requiresCtxV2 = parsedContent !== null
814
- && Object.hasOwn(parsedContent, 'requiresContextVersion')
815
- && parsedContent.requiresContextVersion === 2;
816
- const contextVersion: 'v1' | 'v2' = requiresCtxV2 ? 'v2' : 'v1';
817
- const evidenceRefs = parsedContent !== null ? extractEvidenceRefs(parsedContent) : null;
818
- // PRI-500: extract principleId to match Console's ActivationRecord field.
819
- // Uses extractPrincipleId (4-step fallback) so dreamer artifacts whose
820
- // sourcePrincipleId was stripped still resolve via contentJson.
821
- const principleId = extractPrincipleId(toSnapshot(artifact));
822
- artifactMetadata.set(artifactId, { contextVersion, evidenceRefs, principleId });
823
- } catch {
824
- // Treat lookup failure as dangling - fail loud rather than silent (rc-9).
825
- danglingArtifactIds.add(artifactId);
826
- }
827
- }
828
- const hasDangling = danglingArtifactIds.size > 0;
829
-
830
- // PRI-491: Probe rulecode_context_v2 flag to determine suspended_by_flag
831
- // status for v2 activations. When the flag is off, v2 activations are
832
- // suspended (not executing) even though they remain active in the DB.
833
- const featureFlags = computeFlagsFromLoadResult(loadPdConfig(workspaceDir));
834
- const v2FlagEnabled = featureFlags.flags.rulecode_context_v2?.enabled === true;
835
-
836
- // PRI-491: Enriched activation record with owner-observable fields.
837
- // mode/status/contextVersion/evidenceRefs/nextAction let the owner
838
- // understand rule state without reading SQLite or logs.
839
- interface AnnotatedActivation extends ActivationStatusRecord {
840
- principleId?: string;
841
- mode?: 'shadow' | 'live';
842
- status: 'active' | 'deactivated' | 'suspended_by_flag';
843
- contextVersion?: 'v1' | 'v2';
844
- evidenceRefs?: string[];
845
- evidenceSummary?: string;
846
- nextAction?: string;
847
- warning?: string;
848
- }
849
- const annotated: AnnotatedActivation[] = filtered.map(r => {
850
- // Derive mode from action (shadow_activate -> shadow, live_activate -> live)
851
- const mode: 'shadow' | 'live' | undefined = r.action === 'code_tool_hook_shadow_activate'
852
- ? 'shadow'
853
- : r.action === 'code_tool_hook_live_activate'
854
- ? 'live'
855
- : undefined;
856
-
857
- // Look up artifact metadata (contextVersion, evidenceRefs)
858
- const meta = artifactMetadata.get(r.artifactId);
859
- const contextVersion = meta?.contextVersion;
860
- const evidenceRefs = meta?.evidenceRefs ?? undefined;
861
- const evidenceSummary = evidenceRefs && evidenceRefs.length > 0
862
- ? `${evidenceRefs.length} evidence ref(s): ${evidenceRefs.slice(0, 3).join(', ')}${evidenceRefs.length > 3 ? '...' : ''}`
863
- : undefined;
864
-
865
- // Derive status: deactivated > suspended_by_flag > active
866
- const { status, nextAction } = deriveActivationStatusAndNextAction({
867
- deactivatedAt: r.deactivatedAt,
868
- contextVersion,
869
- v2FlagEnabled,
870
- mode,
871
- activationId: r.activationId,
872
- });
873
-
874
- const record: AnnotatedActivation = {
875
- ...r,
876
- principleId: meta?.principleId ?? 'unlinked',
877
- mode,
878
- status,
879
- contextVersion,
880
- evidenceRefs,
881
- evidenceSummary,
882
- nextAction,
883
- };
884
- if (danglingArtifactIds.has(r.artifactId)) {
885
- record.warning = `artifact_id "${r.artifactId}" does not exist in pi_artifacts - activation is orphaned`;
886
- }
887
- return record;
888
- });
889
-
890
- if (opts.json) {
891
- // Strict JSON mode: exactly one parseable JSON object on stdout.
892
- // When dangling references are detected, emit degraded status with
893
- // reason + nextAction so operators can act on the corruption (rc-9,
894
- // cli-6-output-next-action).
895
- const payload: Record<string, unknown> = { activations: annotated };
896
- if (hasDangling) {
897
- payload.status = 'degraded';
898
- payload.reason = `${danglingArtifactIds.size} activation(s) reference non-existent artifact_id(s): ${Array.from(danglingArtifactIds).join(', ')}`;
899
- payload.nextAction = 'Run `pd runtime internalization integrity` for full chain diagnostics. Consider deactivating orphaned activations via `pd runtime activation deactivate` or restoring the missing artifacts.';
900
- } else {
901
- payload.status = 'ok';
902
- }
903
- console.log(JSON.stringify(payload, null, 2));
904
- } else {
905
- if (annotated.length === 0) {
906
- console.log('No active activations found.');
907
- } else {
908
- for (const r of annotated) {
909
- // PRI-491: Text output shows mode/status/contextVersion so the owner
910
- // can tell at a glance whether a rule will block now.
911
- const statusLabel = r.deactivatedAt
912
- ? `[DEACTIVATED ${r.deactivatedAt}]`
913
- : r.status === 'suspended_by_flag'
914
- ? `[SUSPENDED by flag]`
915
- : `[ACTIVE]`;
916
- const modeLabel = r.mode ? ` (${r.mode})` : '';
917
- console.log(`${statusLabel}${modeLabel} ${r.activationId}`);
918
- console.log(` principleId: ${r.principleId ?? 'unlinked'}`);
919
- console.log(` artifactId: ${r.artifactId}`);
920
- console.log(` channel: ${r.channel}`);
921
- console.log(` action: ${r.action}`);
922
- console.log(` targetRef: ${r.targetRef}`);
923
- console.log(` activatedAt: ${r.activatedAt}`);
924
- if (r.promotedAt) {
925
- console.log(` promotedAt: ${r.promotedAt}`);
926
- }
927
- if (r.contextVersion) {
928
- console.log(` contextVersion: ${r.contextVersion}`);
929
- }
930
- if (r.evidenceSummary) {
931
- console.log(` evidence: ${r.evidenceSummary}`);
932
- }
933
- if (r.nextAction) {
934
- console.log(` nextAction: ${r.nextAction}`);
935
- }
936
- if (r.warning) {
937
- console.log(` WARNING: ${r.warning}`);
938
- }
939
- console.log('');
940
- }
941
- if (hasDangling) {
942
- console.error(`Warning: ${danglingArtifactIds.size} activation(s) reference non-existent artifact_id(s).`);
943
- console.error(`Next action: Run \`pd runtime internalization integrity\` for full chain diagnostics. Consider deactivating orphaned activations or restoring missing artifacts.`);
944
- }
945
- }
946
- }
947
- } catch (err: unknown) {
948
- // P2 #5: initialize/DB exceptions must not break --json contract.
949
- const errMsg = err instanceof Error ? err.message : String(err);
950
- const result = {
951
- ok: false,
952
- reason: `initialize_failed: ${errMsg}`,
953
- nextAction: 'Check workspace directory and DB integrity. Try `pd runtime diagnostics`.',
954
- };
955
- if (opts.json) {
956
- console.log(JSON.stringify(result, null, 2));
957
- } else {
958
- console.error(`Error: ${result.reason}`);
959
- console.error(`Next action: ${result.nextAction}`);
960
- }
961
- process.exitCode = 1;
962
- } finally {
963
- await stateManager.close();
964
- }
965
- }
966
-
967
- // ── Edit Pending Approval Command (P1 #2 fix — Owner edit entry point) ──────
968
-
969
- interface ActivationEditOptions {
970
- workspace?: string;
971
- approvalId?: string;
972
- newArtifactId?: string;
973
- editReason?: string;
974
- json?: boolean;
975
- }
976
-
977
- export interface EditApprovalResult {
978
- ok: boolean;
979
- approvalId?: string;
980
- newArtifactId?: string;
981
- previousArtifactId?: string;
982
- editedAt?: string;
983
- reason?: string;
984
- nextAction?: string;
985
- }
986
-
987
- export async function handleRuntimeActivationEdit(opts: ActivationEditOptions): Promise<void> {
988
- if (!opts.approvalId) {
989
- const result: EditApprovalResult = {
990
- ok: false,
991
- reason: 'approval_id_required',
992
- nextAction: 'Provide --approval-id <id> from Console approvals page',
993
- };
994
- if (opts.json) {
995
- console.log(JSON.stringify(result, null, 2));
996
- } else {
997
- console.error('Error: --approval-id is required');
998
- console.error(`Next action: ${result.nextAction}`);
999
- }
1000
- process.exitCode = 1;
1001
- return;
1002
- }
1003
-
1004
- if (!opts.newArtifactId) {
1005
- const result: EditApprovalResult = {
1006
- ok: false,
1007
- reason: 'new_artifact_id_required',
1008
- nextAction: 'Create a new artifact first (e.g. via pd candidate intake), then pass its ID with --new-artifact-id',
1009
- };
1010
- if (opts.json) {
1011
- console.log(JSON.stringify(result, null, 2));
1012
- } else {
1013
- console.error('Error: --new-artifact-id is required');
1014
- console.error(`Next action: ${result.nextAction}`);
1015
- }
1016
- process.exitCode = 1;
1017
- return;
1018
- }
1019
-
1020
- if (!opts.editReason) {
1021
- const result: EditApprovalResult = {
1022
- ok: false,
1023
- reason: 'edit_reason_required',
1024
- nextAction: 'Provide --edit-reason explaining why the artifact is being revised',
1025
- };
1026
- if (opts.json) {
1027
- console.log(JSON.stringify(result, null, 2));
1028
- } else {
1029
- console.error('Error: --edit-reason is required');
1030
- console.error(`Next action: ${result.nextAction}`);
1031
- }
1032
- process.exitCode = 1;
1033
- return;
1034
- }
1035
-
1036
- const workspaceDir = opts.workspace ? path.resolve(opts.workspace) : resolveWorkspaceDir();
1037
- const stateManager = new RuntimeStateManager({ workspaceDir });
1038
-
1039
- try {
1040
- await stateManager.initialize();
1041
- const approvalStore = new SqliteApprovalQueueStore(stateManager.connection);
1042
- const artifactStore = new SqlitePIArtifactStore(stateManager.connection);
1043
- const now = new Date().toISOString();
1044
-
1045
- // P1 #2: validate the new artifact before swapping the approval pointer.
1046
- // The new artifact must exist, be validated, and have lineage consistent
1047
- // with the original approval's artifact (same sourceTaskId).
1048
- const existingApproval = await approvalStore.getById(opts.approvalId);
1049
- if (!existingApproval) {
1050
- const result: EditApprovalResult = {
1051
- ok: false,
1052
- approvalId: opts.approvalId,
1053
- reason: 'not_found',
1054
- nextAction: 'Check the approval ID on Console approvals page',
1055
- };
1056
- if (opts.json) {
1057
- console.log(JSON.stringify(result, null, 2));
1058
- } else {
1059
- console.error(`Edit refused: ${result.reason}`);
1060
- console.error(`Next action: ${result.nextAction}`);
1061
- }
1062
- process.exitCode = 1;
1063
- await stateManager.close();
1064
- return;
1065
- }
1066
- if (existingApproval.status !== 'pending') {
1067
- const result: EditApprovalResult = {
1068
- ok: false,
1069
- approvalId: opts.approvalId,
1070
- reason: 'already_decided',
1071
- nextAction: `Approval is already decided (status: ${existingApproval.status}). Only pending approvals can be edited.`,
1072
- };
1073
- if (opts.json) {
1074
- console.log(JSON.stringify(result, null, 2));
1075
- } else {
1076
- console.error(`Edit refused: ${result.reason}`);
1077
- console.error(`Next action: ${result.nextAction}`);
1078
- }
1079
- process.exitCode = 1;
1080
- await stateManager.close();
1081
- return;
1082
- }
1083
-
1084
- const newArtifact = await artifactStore.getArtifactById(opts.newArtifactId);
1085
- if (!newArtifact) {
1086
- const result: EditApprovalResult = {
1087
- ok: false,
1088
- approvalId: opts.approvalId,
1089
- reason: 'artifact_not_found',
1090
- nextAction: `Artifact ${opts.newArtifactId} does not exist. Create it first via pd candidate intake.`,
1091
- };
1092
- if (opts.json) {
1093
- console.log(JSON.stringify(result, null, 2));
1094
- } else {
1095
- console.error(`Edit refused: ${result.reason}`);
1096
- console.error(`Next action: ${result.nextAction}`);
1097
- }
1098
- process.exitCode = 1;
1099
- await stateManager.close();
1100
- return;
1101
- }
1102
- if (newArtifact.validationStatus !== 'validated') {
1103
- const result: EditApprovalResult = {
1104
- ok: false,
1105
- approvalId: opts.approvalId,
1106
- reason: `artifact_not_validated: ${newArtifact.validationStatus}`,
1107
- nextAction: `Artifact ${opts.newArtifactId} has validationStatus '${newArtifact.validationStatus}'. Run the production gate to validate it first.`,
1108
- };
1109
- if (opts.json) {
1110
- console.log(JSON.stringify(result, null, 2));
1111
- } else {
1112
- console.error(`Edit refused: ${result.reason}`);
1113
- console.error(`Next action: ${result.nextAction}`);
1114
- }
1115
- process.exitCode = 1;
1116
- await stateManager.close();
1117
- return;
1118
- }
1119
- const originalArtifact = await artifactStore.getArtifactById(existingApproval.artifactId);
1120
- if (!originalArtifact || !isArtifactRevisionOf(newArtifact, originalArtifact)) {
1121
- const result: EditApprovalResult = {
1122
- ok: false,
1123
- approvalId: opts.approvalId,
1124
- reason: 'artifact_lineage_mismatch',
1125
- nextAction: originalArtifact
1126
- ? `Artifact ${opts.newArtifactId} must reference ${originalArtifact.artifactId} or its source principle.`
1127
- : `Original artifact ${existingApproval.artifactId} is missing; restore it before editing this approval.`,
1128
- };
1129
- if (opts.json) {
1130
- console.log(JSON.stringify(result, null, 2));
1131
- } else {
1132
- console.error(`Edit refused: ${result.reason}`);
1133
- console.error(`Next action: ${result.nextAction}`);
1134
- }
1135
- process.exitCode = 1;
1136
- await stateManager.close();
1137
- return;
1138
- }
1139
-
1140
- let editResult;
1141
- try {
1142
- editResult = await approvalStore.edit({
1143
- approvalId: opts.approvalId,
1144
- editedBy: 'operator',
1145
- newArtifactId: opts.newArtifactId,
1146
- editReason: opts.editReason,
1147
- now,
1148
- });
1149
- } catch (err: unknown) {
1150
- const errMsg = err instanceof Error ? err.message : String(err);
1151
- const result: EditApprovalResult = {
1152
- ok: false,
1153
- approvalId: opts.approvalId,
1154
- reason: `edit_failed: ${errMsg}`,
1155
- nextAction: 'Check workspace DB integrity and that the approval + new artifact exist',
1156
- };
1157
- if (opts.json) {
1158
- console.log(JSON.stringify(result, null, 2));
1159
- } else {
1160
- console.error(`Edit failed: ${result.reason}`);
1161
- console.error(`Next action: ${result.nextAction}`);
1162
- }
1163
- process.exitCode = 1;
1164
- return;
1165
- }
1166
-
1167
- if (!editResult.ok) {
1168
- const result: EditApprovalResult = {
1169
- ok: false,
1170
- approvalId: opts.approvalId,
1171
- reason: editResult.error,
1172
- nextAction: editResult.error === 'not_found'
1173
- ? 'Check the approval ID on Console approvals page'
1174
- : `Approval is already decided (status: ${editResult.status ?? 'unknown'}). Only pending approvals can be edited.`,
1175
- };
1176
- if (opts.json) {
1177
- console.log(JSON.stringify(result, null, 2));
1178
- } else {
1179
- console.error(`Edit refused: ${result.reason}`);
1180
- console.error(`Next action: ${result.nextAction}`);
1181
- }
1182
- process.exitCode = 1;
1183
- return;
1184
- }
1185
-
1186
- const result: EditApprovalResult = {
1187
- ok: true,
1188
- approvalId: editResult.record.approvalId,
1189
- newArtifactId: editResult.record.artifactId,
1190
- previousArtifactId: editResult.record.previousArtifactId ?? undefined,
1191
- editedAt: editResult.record.editedAt ?? now,
1192
- };
1193
-
1194
- if (opts.json) {
1195
- console.log(JSON.stringify(result, null, 2));
1196
- } else {
1197
- console.log(`Approval edited: ${result.approvalId}`);
1198
- console.log(` newArtifactId: ${result.newArtifactId}`);
1199
- if (result.previousArtifactId) {
1200
- console.log(` previousArtifactId: ${result.previousArtifactId}`);
1201
- }
1202
- console.log(` editedAt: ${result.editedAt}`);
1203
- console.log('Next action: review the new artifact, then run `pd activation approve --approval-id <id>` to approve and dispatch');
1204
- }
1205
- } catch (err: unknown) {
1206
- // P2 #5: initialize/DB exceptions must not break --json contract.
1207
- const errMsg = err instanceof Error ? err.message : String(err);
1208
- const result: EditApprovalResult = {
1209
- ok: false,
1210
- approvalId: opts.approvalId,
1211
- reason: `initialize_failed: ${errMsg}`,
1212
- nextAction: 'Check workspace directory and DB integrity. Try `pd runtime diagnostics`.',
1213
- };
1214
- if (opts.json) {
1215
- console.log(JSON.stringify(result, null, 2));
1216
- } else {
1217
- console.error(`Error: ${result.reason}`);
1218
- console.error(`Next action: ${result.nextAction}`);
1219
- }
1220
- process.exitCode = 1;
1221
- } finally {
1222
- await stateManager.close();
1223
- }
1224
- }
1225
-
1226
- // ── Approve Command (Bug-M fix: CLI closed loop) ──────────────────────────────
1227
- //
1228
- // Bug-M root cause: `pd activation` had dispatch/list/edit/deactivate but no
1229
- // `approve`. Owners who completed `dispatch → edit` via CLI had to switch to
1230
- // Console to approve. This handler closes the CLI loop by reusing the same
1231
- // ApprovalQueue + ApprovalCompletionService that the Console model uses,
1232
- // without depending on the pd-console package (which is a private Web UI).
1233
-
1234
- interface ActivationApproveOptions {
1235
- workspace?: string;
1236
- approvalId?: string;
1237
- decidedBy?: string;
1238
- note?: string;
1239
- json?: boolean;
1240
- }
1241
-
1242
- interface ApproveResult {
1243
- ok: boolean;
1244
- approvalId: string;
1245
- activationId?: string;
1246
- decision?: string;
1247
- reason?: string;
1248
- nextAction?: string;
1249
- approvalRolledBack?: boolean;
1250
- }
1251
-
1252
- export async function handleActivationApprove(opts: ActivationApproveOptions): Promise<void> {
1253
- if (!opts.approvalId) {
1254
- const result: ApproveResult = {
1255
- ok: false,
1256
- approvalId: '',
1257
- reason: 'approval_id_required',
1258
- nextAction: 'Provide --approval-id <id>. Run `pd approval list` to see pending approvals.',
1259
- };
1260
- if (opts.json) {
1261
- console.log(JSON.stringify(result, null, 2));
1262
- } else {
1263
- console.error('Error: --approval-id is required');
1264
- console.error(`Next action: ${result.nextAction}`);
1265
- }
1266
- process.exitCode = 1;
1267
- return;
1268
- }
1269
-
1270
- const decidedBy = opts.decidedBy ?? 'cli-operator';
1271
- // CodeRabbit review fix (cli-1-strict-json): declare stateManager outside
1272
- // try so the finally block can close it, but resolve workspace INSIDE try
1273
- // so resolveWorkspaceDir() failures are caught and routed through --json.
1274
- let stateManager: RuntimeStateManager | null = null;
1275
-
1276
- try {
1277
- const workspaceDir = opts.workspace ? path.resolve(opts.workspace) : resolveWorkspaceDir();
1278
- stateManager = new RuntimeStateManager({ workspaceDir });
1279
- await stateManager.initialize();
1280
- const sqliteConn = stateManager.connection;
1281
- const approvalQueueStore = new SqliteApprovalQueueStore(sqliteConn);
1282
- const queue = new ApprovalQueue(approvalQueueStore);
1283
-
1284
- // PRI-634-F R2 (review P1): a code_tool_hook approval completing into an
1285
- // activation must resolve the host tool registry from workspace
1286
- // provenance — refuse BEFORE the approval write when unavailable, so no
1287
- // half-approved state is created and the operator gets a nextAction.
1288
- const pendingApproval = await queue.getById(opts.approvalId);
1289
- const approvalChannel = pendingApproval?.channel;
1290
- const approveToolSemantics = resolveWorkspaceToolSemantics(workspaceDir);
1291
- if (approvalChannel === 'code_tool_hook' && !approveToolSemantics.ok) {
1292
- const result: ApproveResult = {
1293
- ok: false,
1294
- approvalId: opts.approvalId,
1295
- reason: approveToolSemantics.reason,
1296
- nextAction: approveToolSemantics.nextAction,
1297
- };
1298
- if (opts.json) {
1299
- console.log(JSON.stringify(result, null, 2));
1300
- } else {
1301
- console.log(`approvalId: ${result.approvalId}`);
1302
- console.log(` reason: ${result.reason}`);
1303
- console.log(` nextAction: ${result.nextAction}`);
1304
- }
1305
- process.exitCode = 1;
1306
- return;
1307
- }
1308
- const workspaceToolSemantics = approveToolSemantics.ok ? approveToolSemantics.registry : undefined;
1309
-
1310
- // Step 1: approve the pending approval record.
1311
- let approvalResult: ApprovalDecisionResult;
1312
- try {
1313
- approvalResult = await queue.approve(opts.approvalId, decidedBy, opts.note);
1314
- } catch (err) {
1315
- const errMsg = err instanceof Error ? err.message : String(err);
1316
- const result: ApproveResult = {
1317
- ok: false,
1318
- approvalId: opts.approvalId,
1319
- reason: `approve_write_failed: ${errMsg}`,
1320
- nextAction: 'Check workspace DB integrity. Try `pd runtime diagnostics`.',
1321
- };
1322
- if (opts.json) {
1323
- console.log(JSON.stringify(result, null, 2));
1324
- } else {
1325
- console.error(`Error: ${result.reason}`);
1326
- console.error(`Next action: ${result.nextAction}`);
1327
- }
1328
- process.exitCode = 1;
1329
- return;
1330
- }
1331
-
1332
- if (!approvalResult.ok) {
1333
- // Map ApprovalDecisionResult errors to ApproveResult (rc-3 fail-loud).
1334
- // ApprovalDecisionResult.error is the discriminated union 'not_found' | 'already_decided';
1335
- // both branches are exhaustive, so no third case is reachable at runtime.
1336
- const reason = approvalResult.error === 'not_found'
1337
- ? 'approval_not_found'
1338
- : `already_decided: status is ${approvalResult.status ?? 'unknown'}`;
1339
- const nextAction = approvalResult.error === 'not_found'
1340
- ? 'Check the approval ID. Run `pd approval list` to see pending approvals.'
1341
- : 'Only pending approvals can be approved. The approval is already decided.';
1342
- const result: ApproveResult = {
1343
- ok: false,
1344
- approvalId: opts.approvalId,
1345
- reason,
1346
- nextAction,
1347
- };
1348
- if (opts.json) {
1349
- console.log(JSON.stringify(result, null, 2));
1350
- } else {
1351
- console.error(`Error: ${result.reason}`);
1352
- console.error(`Next action: ${result.nextAction}`);
1353
- }
1354
- process.exitCode = 1;
1355
- return;
1356
- }
1357
-
1358
- // Step 2: dispatch activation via ApprovalCompletionService (handles
1359
- // idempotency, feature flag, and rollback on failure).
1360
- const activationStateStore = new SqliteActivationStateStore(sqliteConn);
1361
- const piArtifactStore = new SqlitePIArtifactStore(sqliteConn);
1362
- const artifactReadModel = {
1363
- getArtifactById: async (id: string): Promise<PIArtifactSnapshot | null> => {
1364
- const rec = await piArtifactStore.getArtifactById(id);
1365
- return rec ? toSnapshot(rec) : null;
1366
- },
1367
- };
1368
- // PRI-489: inject the real workspace `rulecode_context_v2` feature flag
1369
- // probe into the approve path's RuleHostWriter — same wiring as the
1370
- // dispatch path (handleRuntimeActivationDispatch) and the Console model
1371
- // (ApprovalsConsoleModel.dispatchActivationAfterApproval). Previously
1372
- // this path constructed RuleHostWriter without the probe, so a v2
1373
- // artifact in a flag-off workspace would pass canActivate here while
1374
- // being rejected by dispatch/Console — an inconsistent contract that
1375
- // violated ERR-024 (validator wired in one enforcement path but not
1376
- // another) and ERR-089 (sibling approval path diverged from dispatch).
1377
- const featureFlags = computeFlagsFromLoadResult(loadPdConfig(workspaceDir));
1378
- const dispatcher = new ActivationDispatcher(
1379
- artifactReadModel,
1380
- activationStateStore,
1381
- {
1382
- writers: [
1383
- new PromptWriter(),
1384
- new RuleHostWriter({
1385
- // PRI-634-F R2: registry from durable host provenance (the host
1386
- // declaration persisted in the workspace) + the real workspace
1387
- // root — production-identical replay and tool-existence
1388
- // validation. No host is guessed (review P1).
1389
- gateDeps: createProductionGateDeps({
1390
- projectDir: workspaceDir,
1391
- ...(workspaceToolSemantics ? { toolSemantics: workspaceToolSemantics } : {}),
1392
- }),
1393
- featureFlagProbe: (flagId) => featureFlags.flags[flagId]?.enabled === true,
1394
- projectDir: workspaceDir,
1395
- ...(workspaceToolSemantics ? { toolSemantics: workspaceToolSemantics } : {}),
1396
- }),
1397
- new DeferArchiveWriter(),
1398
- ],
1399
- approvalQueueStore,
1400
- },
1401
- );
1402
- const completionService = new ApprovalCompletionService(
1403
- approvalQueueStore,
1404
- dispatcher,
1405
- activationStateStore,
1406
- );
1407
-
1408
- let completionResult: ApprovalCompletionResult;
1409
- try {
1410
- completionResult = await completionService.completeApproval({
1411
- approvalId: opts.approvalId,
1412
- actor: { kind: 'human', userId: decidedBy },
1413
- now: new Date().toISOString(),
1414
- });
1415
- } catch (err) {
1416
- // CodeRabbit review fix (cli-5-failure-no-mutation): approval was
1417
- // written but completion threw unexpectedly. Roll back the approval to
1418
- // 'pending' so the operator can retry without a stale 'approved' record
1419
- // that has no activation. Mirrors ApprovalsConsoleModel.approve() L168-182.
1420
- const errMsg = err instanceof Error ? err.message : String(err);
1421
- let approvalRolledBack = false;
1422
- try {
1423
- const rollbackResult = await queue.resetToPending(opts.approvalId);
1424
- approvalRolledBack = rollbackResult.ok;
1425
- } catch { /* best-effort rollback */ }
1426
- const result: ApproveResult = {
1427
- ok: false,
1428
- approvalId: opts.approvalId,
1429
- reason: `activation_completion_failed: ${errMsg}`,
1430
- nextAction: approvalRolledBack
1431
- ? 'Approval rolled back to pending. Fix the issue and re-run `pd activation approve --approval-id <id>`.'
1432
- : `Approval remains 'approved'. Run \`pd activation dispatch --artifact-id ${approvalResult.record.artifactId} --confirm\` to retry activation.`,
1433
- approvalRolledBack,
1434
- };
1435
- if (opts.json) {
1436
- console.log(JSON.stringify(result, null, 2));
1437
- } else {
1438
- console.error(`Error: ${result.reason}`);
1439
- console.error(`Next action: ${result.nextAction}`);
1440
- }
1441
- process.exitCode = 1;
1442
- return;
1443
- }
1444
-
1445
- if (!completionResult.ok) {
1446
- // CodeRabbit review fix (cli-5-failure-no-mutation): activation
1447
- // returned !ok. Roll back the approval to 'pending' so the operator
1448
- // can retry without a stale 'approved' record. Mirrors
1449
- // ApprovalsConsoleModel.approve() L168-182.
1450
- let approvalRolledBack = false;
1451
- try {
1452
- const rollbackResult = await queue.resetToPending(opts.approvalId);
1453
- approvalRolledBack = rollbackResult.ok;
1454
- } catch { /* best-effort rollback */ }
1455
- const result: ApproveResult = {
1456
- ok: false,
1457
- approvalId: opts.approvalId,
1458
- reason: `activation_failed: ${completionResult.reason}`,
1459
- nextAction: approvalRolledBack
1460
- ? `Approval rolled back to pending. ${completionResult.nextAction ?? 'Fix the issue and re-run `pd activation approve --approval-id <id>`.'}`
1461
- : `Approval remains 'approved'. ${completionResult.nextAction ?? 'Check the artifact validation status and retry.'}`,
1462
- approvalRolledBack,
1463
- };
1464
- if (opts.json) {
1465
- console.log(JSON.stringify(result, null, 2));
1466
- } else {
1467
- console.error(`Error: ${result.reason}`);
1468
- console.error(`Next action: ${result.nextAction}`);
1469
- }
1470
- process.exitCode = 1;
1471
- return;
1472
- }
1473
-
1474
- // Step 3: success — surface activation result.
1475
- const result: ApproveResult = {
1476
- ok: true,
1477
- approvalId: opts.approvalId,
1478
- activationId: completionResult.activationId,
1479
- decision: completionResult.decision.decision,
1480
- nextAction: 'pd activation list',
1481
- };
1482
- if (opts.json) {
1483
- console.log(JSON.stringify(result, null, 2));
1484
- } else {
1485
- console.log(`Approval approved: ${result.approvalId}`);
1486
- console.log(` activationId: ${result.activationId ?? 'N/A'}`);
1487
- console.log(` decision: ${result.decision}`);
1488
- console.log(`Next action: ${result.nextAction}`);
1489
- }
1490
- } catch (err: unknown) {
1491
- // P2 #5: initialize/DB exceptions must not break --json contract.
1492
- const errMsg = err instanceof Error ? err.message : String(err);
1493
- const result: ApproveResult = {
1494
- ok: false,
1495
- approvalId: opts.approvalId ?? '',
1496
- reason: `initialize_failed: ${errMsg}`,
1497
- nextAction: 'Check workspace directory and DB integrity. Try `pd runtime diagnostics`.',
1498
- };
1499
- if (opts.json) {
1500
- console.log(JSON.stringify(result, null, 2));
1501
- } else {
1502
- console.error(`Error: ${result.reason}`);
1503
- console.error(`Next action: ${result.nextAction}`);
1504
- }
1505
- process.exitCode = 1;
1506
- } finally {
1507
- // stateManager may be null if resolveWorkspaceDir() threw before assignment.
1508
- await stateManager?.close();
1509
- }
1510
- }
1511
-
1512
- // ── Commander Wiring (CLI gate rule 7: test the real command wiring) ─────────
1513
- //
1514
- // Extracted so parser-level tests can exercise the actual flag registration
1515
- // without importing all of `index.ts`. Mirrors `registerRunRuleHostCommand`.
1516
-
1517
- export function registerRuntimeActivationPromoteCommand(parent: Command): Command {
1518
- return parent
1519
- .command('promote')
1520
- .description('Promote a code_tool_hook activation from shadow observation to live blocking')
1521
- .requiredOption('--activation-id <id>', 'Shadow activation ID to promote')
1522
- .option('-w, --workspace <path>', 'Workspace directory')
1523
- .option('--dry-run', 'Validate eligibility without changing activation state')
1524
- .option('--confirm', 'Confirm promotion to live blocking')
1525
- .option('--artifact-id <id>', 'Expected artifact ID from Owner review')
1526
- .option('--artifact-digest <digest>', 'Expected artifact digest from Owner review')
1527
- .option('--control-version <n>', 'Expected activation control version', (value) => Number.parseInt(value, 10))
1528
- .option('--idempotency-key <key>', 'Idempotency key for the Owner decision')
1529
- .option('--reason <code>', 'Owner decision reason code')
1530
- .option('--note <text>', 'Required CLI Owner review note')
1531
- .option('--json', 'Output raw JSON')
1532
- .action(async (opts) => {
1533
- await handleRuntimeActivationPromote({
1534
- activationId: opts.activationId,
1535
- workspace: opts.workspace,
1536
- dryRun: opts.dryRun,
1537
- confirm: opts.confirm,
1538
- json: opts.json,
1539
- artifactId: opts.artifactId,
1540
- artifactDigest: opts.artifactDigest,
1541
- controlVersion: opts.controlVersion,
1542
- idempotencyKey: opts.idempotencyKey,
1543
- reasonCode: opts.reason,
1544
- note: opts.note,
1545
- });
1546
- });
1547
- }
1548
-
1549
- // PRI-493: Extracted helpers for parser-level flag-wiring tests (cli-7).
1550
- // Mirrors registerRuntimeActivationPromoteCommand — single source of truth
1551
- // shared with index.ts. Flag typos in production surface at parseAsync time.
1552
-
1553
- export function registerRuntimeActivationDeactivateCommand(parent: Command): Command {
1554
- return parent
1555
- .command('deactivate')
1556
- .description('Deactivate an activation by activation ID')
1557
- .requiredOption('--activation-id <id>', 'Activation ID to deactivate')
1558
- .option('--reason-code <code>', 'Structured governance reason code (default: cli_deactivate_requested)')
1559
- .option('-w, --workspace <path>', 'Workspace directory')
1560
- .option('--json', 'Output raw JSON')
1561
- .action(async (opts) => {
1562
- await handleRuntimeActivationDeactivate({
1563
- activationId: opts.activationId,
1564
- workspace: opts.workspace,
1565
- reasonCode: opts.reasonCode,
1566
- json: opts.json,
1567
- });
1568
- });
1569
- }
1570
-
1571
- export function registerRuntimeActivationListCommand(parent: Command): Command {
1572
- return parent
1573
- .command('list')
1574
- .description('List all activations for a workspace')
1575
- .option('-w, --workspace <path>', 'Workspace directory')
1576
- .option('-c, --channel <channel>', 'Filter by channel (prompt|code_tool_hook)')
1577
- .option('--include-deactivated', 'Include deactivated records in output')
1578
- .option('--json', 'Output raw JSON')
1579
- .action(async (opts) => {
1580
- await handleRuntimeActivationList({
1581
- workspace: opts.workspace,
1582
- channel: opts.channel,
1583
- includeDeactivated: opts.includeDeactivated,
1584
- json: opts.json,
1585
- });
1586
- });
1587
- }
1588
-
1589
- export function registerRuntimeActivationDispatchCommand(parent: Command): Command {
1590
- return parent
1591
- .command('dispatch')
1592
- .description('Dispatch a rollout-reviewed artifact: queues Owner approval (activation requires approval; PRI-811 Phase B)')
1593
- .option('-a, --artifact-id <id>', 'PIArtifact ID to activate')
1594
- .option('-w, --workspace <path>', 'Workspace directory')
1595
- .option('-c, --channel <channel>', 'Activation channel (prompt|defer_archive)', 'prompt')
1596
- .option('--dry-run', 'Dry-run mode (default, no writes)')
1597
- .option('--confirm', 'Confirm and write the approval-queue entry')
1598
- .option('--json', 'Output raw JSON')
1599
- .action(async (opts) => {
1600
- await handleRuntimeActivationDispatch({
1601
- workspace: opts.workspace,
1602
- artifactId: opts.artifactId,
1603
- channel: opts.channel,
1604
- dryRun: opts.dryRun,
1605
- confirm: opts.confirm,
1606
- json: opts.json,
1607
- });
1608
- });
1609
- }
1610
-
1611
- export function registerRuntimeActivationApproveCommand(parent: Command): Command {
1612
- return parent
1613
- .command('approve')
1614
- .description('Approve a pending approval and dispatch its activation')
1615
- .requiredOption('-a, --approval-id <id>', 'Approval ID to approve')
1616
- .option('--decided-by <user>', 'Reviewer name (default: cli-operator)')
1617
- .option('--note <text>', 'Optional approval note')
1618
- .option('-w, --workspace <path>', 'Workspace directory')
1619
- .option('--json', 'Output raw JSON')
1620
- .action(async (opts) => {
1621
- await handleActivationApprove({
1622
- approvalId: opts.approvalId,
1623
- decidedBy: opts.decidedBy,
1624
- note: opts.note,
1625
- workspace: opts.workspace,
1626
- json: opts.json,
1627
- });
1628
- });
1629
- }