@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,2052 +0,0 @@
1
- import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
2
- import { createHash } from 'node:crypto';
3
- import { mkdtempSync, mkdirSync, writeFileSync, rmSync } from 'node:fs';
4
- import { resolveWorkspaceToolSemantics } from '../../src/services/workspace-tool-semantics.js';
5
- import { vi as _vi } from 'vitest';
6
- import { tmpdir } from 'node:os';
7
- import path from 'node:path';
8
-
9
- const mockRuleHostWriterConfigs = vi.hoisted(() => [] as Array<{ featureFlagProbe?: (flagId: string) => boolean }>);
10
- const mockFeatureFlags = vi.hoisted(() => ({
11
- flags: {
12
- rulecode_context_v2: { id: 'rulecode_context_v2', category: 'quiet' as const, enabled: true, since: '2026-06-27', description: 'test' },
13
- rulecode_owner_live_decision: { id: 'rulecode_owner_live_decision', category: 'core' as const, enabled: false, since: '2026-08-21', description: 'test' },
14
- rulecode_safety_controls: { id: 'rulecode_safety_controls', category: 'core' as const, enabled: true, since: '2026-08-21', description: 'test' },
15
- },
16
- }));
17
-
18
- const mockGetArtifactById = vi.fn();
19
- const mockClose = vi.fn().mockResolvedValue(undefined);
20
- const mockApprovalEdit = vi.fn();
21
- const mockApprovalGetById = vi.fn();
22
- const mockApprovalApprove = vi.fn();
23
- const mockApprovalResetToPending = vi.fn();
24
- const mockCompletionComplete = vi.fn();
25
- const mockPromoteActivation = vi.fn().mockResolvedValue(true);
26
- const mockListCodeToolHookActivations = vi.fn().mockResolvedValue([
27
- { activationId: 'act-hook-1', artifactId: 'art-002', channel: 'code_tool_hook', action: 'code_tool_hook_shadow_activate', targetRef: 'rule-001', activatedAt: '2026-06-18T00:00:00.000Z', promotedAt: null, deactivatedAt: null },
28
- ]);
29
-
30
- vi.mock('../../src/services/workspace-tool-semantics.js', () => ({
31
- // Unit boundary: dispatch/approve tests exercise flag wiring and approval
32
- // state transitions; host-provenance resolution has its own contract tests
33
- // (workspace-tool-semantics.test.ts). Tests that need the refusal path
34
- // override the return value via vi.mocked.
35
- resolveWorkspaceToolSemantics: vi.fn().mockReturnValue({ ok: true, registry: { version: 1, hasHostLayer: true }, hostKind: 'test-host' }),
36
- }));
37
-
38
- vi.mock('../../src/resolve-workspace.js', () => ({
39
- resolveWorkspaceDir: vi.fn().mockReturnValue('/fake/workspace'),
40
- }));
41
-
42
- vi.mock('../../src/services/pd-config-loader.js', () => ({
43
- loadPdConfig: vi.fn().mockReturnValue({ ok: true, effective: {} }),
44
- computeFlagsFromLoadResult: vi.fn().mockReturnValue(mockFeatureFlags),
45
- }));
46
-
47
- vi.mock('@principles/core/runtime-v2', async (importOriginal) => {
48
- const original = await importOriginal() as Record<string, unknown>;
49
- return {
50
- ...original,
51
- RuntimeStateManager: vi.fn().mockImplementation(function () {
52
- return {
53
- initialize: vi.fn().mockResolvedValue(undefined),
54
- close: mockClose,
55
- piArtifactStore: {
56
- getArtifactById: mockGetArtifactById,
57
- },
58
- connection: {
59
- getDb: () => ({
60
- prepare: () => ({
61
- get: () => undefined,
62
- all: () => [],
63
- }),
64
- }),
65
- },
66
- };
67
- }),
68
- SqliteActivationStateStore: vi.fn().mockImplementation(function () {
69
- return {
70
- findByArtifactId: vi.fn().mockResolvedValue(null),
71
- insert: vi.fn().mockResolvedValue(undefined),
72
- deactivateActivation: vi.fn().mockResolvedValue(true),
73
- listPromptActivations: vi.fn().mockResolvedValue([
74
- { activationId: 'act-prompt-1', artifactId: 'art-001', channel: 'prompt', action: 'prompt', targetRef: 'P_001', activatedAt: '2026-06-18T00:00:00.000Z', deactivatedAt: null },
75
- ]),
76
- listCodeToolHookActivations: mockListCodeToolHookActivations,
77
- promoteActivation: mockPromoteActivation,
78
- listAllActivations: vi.fn().mockResolvedValue([
79
- { activationId: 'act-prompt-1', artifactId: 'art-001', channel: 'prompt', action: 'prompt', targetRef: 'P_001', activatedAt: '2026-06-18T00:00:00.000Z', deactivatedAt: null },
80
- { activationId: 'act-hook-1', artifactId: 'art-002', channel: 'code_tool_hook', action: 'block', targetRef: 'rule-001', activatedAt: '2026-06-18T00:00:00.000Z', deactivatedAt: null },
81
- ]),
82
- };
83
- }),
84
- SqliteApprovalQueueStore: vi.fn().mockImplementation(function () {
85
- return {
86
- enqueue: vi.fn().mockResolvedValue(undefined),
87
- edit: mockApprovalEdit,
88
- getById: mockApprovalGetById,
89
- };
90
- }),
91
- SqlitePIArtifactStore: vi.fn().mockImplementation(function () {
92
- return {
93
- getArtifactById: mockGetArtifactById,
94
- };
95
- }),
96
- ActivationDispatcher: vi.fn().mockImplementation(function () {
97
- return {
98
- dispatch: vi.fn(async (args) => {
99
- if (args.confirm) {
100
- return { decision: 'activated', activationId: 'act-001', action: 'prompt', targetRef: 'P_001' };
101
- }
102
- if (args.channel === 'code_tool_hook') {
103
- return { decision: 'refused', activationId: 'act-001', action: 'none', targetRef: 'P_001', reason: 'activation_state_read_failed', riskLevel: 'high', channel: 'code_tool_hook', nextAction: 'Check activation_state table integrity and retry' };
104
- }
105
- return { decision: 'would_activate', activationId: 'act-001', action: 'prompt', targetRef: 'P_001' };
106
- }),
107
- };
108
- }),
109
- ApprovalQueue: vi.fn().mockImplementation(function () {
110
- // PRI-634-F R2: getById backs the pre-approve host-provenance check
111
- // (null = no record; the approve path handles not-found itself).
112
- return { approve: mockApprovalApprove, resetToPending: mockApprovalResetToPending, getById: async () => null };
113
- }),
114
- ApprovalCompletionService: vi.fn().mockImplementation(function () {
115
- return { completeApproval: mockCompletionComplete };
116
- }),
117
- RuleHostWriter: vi.fn().mockImplementation(function (config) {
118
- mockRuleHostWriterConfigs.push(config);
119
- return { channel: 'code_tool_hook', canActivate: async () => ({ ok: true }) };
120
- }),
121
- resolveOutputLanguage: vi.fn().mockReturnValue({ outputLanguage: 'zh-CN' }),
122
- };
123
- });
124
-
125
- import { handleRuntimeActivationDispatch, handleRuntimeActivationDeactivate, handleRuntimeActivationList, handleRuntimeActivationEdit, handleActivationApprove, handleRuntimeActivationPromote, registerRuntimeActivationDispatchCommand, registerRuntimeActivationDeactivateCommand, registerRuntimeActivationPromoteCommand, registerRuntimeActivationListCommand } from '../../src/commands/runtime-activation.js';
126
-
127
- const WS = '/fake/workspace';
128
-
129
- function makeArtifact(overrides: Record<string, unknown> = {}) {
130
- return {
131
- artifactId: 'art-001',
132
- artifactKind: 'principle',
133
- sourceTaskId: 'task-001',
134
- sourcePrincipleId: 'P_001',
135
- lineageArtifactIds: [],
136
- validationStatus: 'validated',
137
- contentJson: JSON.stringify({ principleId: 'P_001', text: 'Test', review: { decision: 'approve_rollout' } }),
138
- createdAt: '2026-01-01T00:00:00.000Z',
139
- updatedAt: '2026-01-01T00:00:00.000Z',
140
- ...overrides,
141
- };
142
- }
143
-
144
- describe('handleRuntimeActivationDispatch', () => {
145
- let consoleLogSpy: ReturnType<typeof vi.spyOn>;
146
- let consoleErrorSpy: ReturnType<typeof vi.spyOn>;
147
-
148
- beforeEach(() => {
149
- vi.clearAllMocks();
150
- mockRuleHostWriterConfigs.length = 0;
151
- consoleLogSpy = vi.spyOn(console, 'log').mockImplementation(() => {});
152
- consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
153
- mockGetArtifactById.mockResolvedValue(makeArtifact());
154
- });
155
-
156
- it('wires the effective workspace feature flags into RuleHostWriter', async () => {
157
- await handleRuntimeActivationDispatch({
158
- workspace: WS,
159
- artifactId: 'art-001',
160
- channel: 'code_tool_hook',
161
- json: true,
162
- });
163
-
164
- expect(mockRuleHostWriterConfigs).toHaveLength(1);
165
- expect(mockRuleHostWriterConfigs[0]?.featureFlagProbe?.('rulecode_context_v2')).toBe(true);
166
- });
167
-
168
- afterEach(() => {
169
- consoleLogSpy.mockRestore();
170
- consoleErrorSpy.mockRestore();
171
- process.exitCode = 0;
172
- });
173
-
174
- it('JSON output contains activationId, decision, reason, targetRef', async () => {
175
- await handleRuntimeActivationDispatch({
176
- workspace: WS,
177
- artifactId: 'art-001',
178
- channel: 'prompt',
179
- json: true,
180
- });
181
-
182
- const output = JSON.parse(consoleLogSpy.mock.calls[0][0]);
183
- expect(output).toHaveProperty('decision');
184
- expect(output).toHaveProperty('activationId');
185
- expect(output).toHaveProperty('action');
186
- expect(output).toHaveProperty('targetRef');
187
- });
188
-
189
- it('dry-run outputs would_activate', async () => {
190
- await handleRuntimeActivationDispatch({
191
- workspace: WS,
192
- artifactId: 'art-001',
193
- channel: 'prompt',
194
- dryRun: true,
195
- json: true,
196
- });
197
-
198
- const output = JSON.parse(consoleLogSpy.mock.calls[0][0]);
199
- expect(output.decision).toBe('would_activate');
200
- });
201
-
202
- it('confirm outputs activated', async () => {
203
- await handleRuntimeActivationDispatch({
204
- workspace: WS,
205
- artifactId: 'art-001',
206
- channel: 'prompt',
207
- confirm: true,
208
- json: true,
209
- });
210
-
211
- const output = JSON.parse(consoleLogSpy.mock.calls[0][0]);
212
- expect(output.decision).toBe('activated');
213
- });
214
-
215
- it('high-risk channel returns refused', async () => {
216
- await handleRuntimeActivationDispatch({
217
- workspace: WS,
218
- artifactId: 'art-001',
219
- channel: 'code_tool_hook',
220
- json: true,
221
- });
222
-
223
- const output = JSON.parse(consoleLogSpy.mock.calls[0][0]);
224
- expect(output.decision).toBe('refused');
225
- expect(process.exitCode).toBe(1);
226
- });
227
-
228
- it('missing artifact returns invalid_artifact', async () => {
229
- mockGetArtifactById.mockResolvedValue(null);
230
-
231
- await handleRuntimeActivationDispatch({
232
- workspace: WS,
233
- artifactId: 'nonexistent',
234
- channel: 'prompt',
235
- json: true,
236
- });
237
-
238
- const output = JSON.parse(consoleLogSpy.mock.calls[0][0]);
239
- expect(output.decision).toBe('invalid_artifact');
240
- expect(process.exitCode).toBe(1);
241
- });
242
-
243
- it('--dry-run and --confirm are mutually exclusive', async () => {
244
- await handleRuntimeActivationDispatch({
245
- workspace: WS,
246
- artifactId: 'art-001',
247
- channel: 'prompt',
248
- dryRun: true,
249
- confirm: true,
250
- json: true,
251
- });
252
-
253
- expect(consoleErrorSpy).toHaveBeenCalledWith('Error: --dry-run and --confirm are mutually exclusive');
254
- expect(process.exitCode).toBe(1);
255
- });
256
-
257
- it('default is dry-run (would_activate)', async () => {
258
- await handleRuntimeActivationDispatch({
259
- workspace: WS,
260
- artifactId: 'art-001',
261
- channel: 'prompt',
262
- json: true,
263
- });
264
-
265
- const output = JSON.parse(consoleLogSpy.mock.calls[0][0]);
266
- expect(output.decision).toBe('would_activate');
267
- });
268
-
269
- it('text output is human-readable', async () => {
270
- await handleRuntimeActivationDispatch({
271
- workspace: WS,
272
- artifactId: 'art-001',
273
- channel: 'prompt',
274
- });
275
-
276
- const text = consoleLogSpy.mock.calls[0][0];
277
- expect(text).toContain('Activation:');
278
- expect(text).toContain('would_activate');
279
- });
280
-
281
- // PRI-493 cli-5 no-mutation: missing-artifact failure path must not construct
282
- // the activation state store or dispatcher. Production code returns before
283
- // instantiating either (runtime-activation.ts lines 148-157). ERR-088
284
- // positive path marker: assert the constructors were never invoked, not just
285
- // that the output shape is invalid_artifact.
286
- it('missing-artifact failure path does not construct SqliteActivationStateStore or ActivationDispatcher', async () => {
287
- mockGetArtifactById.mockResolvedValue(null);
288
- const { SqliteActivationStateStore, ActivationDispatcher } = await import('@principles/core/runtime-v2');
289
-
290
- vi.mocked(SqliteActivationStateStore).mockClear();
291
- vi.mocked(ActivationDispatcher).mockClear();
292
-
293
- await handleRuntimeActivationDispatch({
294
- workspace: WS,
295
- artifactId: 'nonexistent',
296
- channel: 'prompt',
297
- json: true,
298
- });
299
-
300
- expect(SqliteActivationStateStore).not.toHaveBeenCalled();
301
- expect(ActivationDispatcher).not.toHaveBeenCalled();
302
- expect(process.exitCode).toBe(1);
303
- });
304
-
305
- // PRI-493 cli-5 no-mutation: --dry-run/--confirm mutex failure must not open
306
- // any DB-backed store. Production code exits before stateManager.initialize()
307
- // (runtime-activation.ts lines 127-131). ERR-088 positive marker.
308
- it('mutex failure path (--dry-run + --confirm) does not construct RuntimeStateManager', async () => {
309
- const { RuntimeStateManager } = await import('@principles/core/runtime-v2');
310
- vi.mocked(RuntimeStateManager).mockClear();
311
-
312
- await handleRuntimeActivationDispatch({
313
- workspace: WS,
314
- artifactId: 'art-001',
315
- channel: 'prompt',
316
- dryRun: true,
317
- confirm: true,
318
- json: true,
319
- });
320
-
321
- expect(RuntimeStateManager).not.toHaveBeenCalled();
322
- expect(process.exitCode).toBe(1);
323
- });
324
- });
325
-
326
- // PRI-408 Contract E: Deactivate (rollback) command tests
327
- describe('handleRuntimeActivationDeactivate', () => {
328
- let consoleLogSpy: ReturnType<typeof vi.spyOn>;
329
- let consoleErrorSpy: ReturnType<typeof vi.spyOn>;
330
-
331
- beforeEach(() => {
332
- vi.clearAllMocks();
333
- consoleLogSpy = vi.spyOn(console, 'log').mockImplementation(() => {});
334
- consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
335
- });
336
-
337
- afterEach(() => {
338
- consoleLogSpy.mockRestore();
339
- consoleErrorSpy.mockRestore();
340
- process.exitCode = 0;
341
- });
342
-
343
- it('missing --activation-id returns structured error with nextAction (JSON)', async () => {
344
- await handleRuntimeActivationDeactivate({
345
- workspace: WS,
346
- json: true,
347
- });
348
-
349
- const output = JSON.parse(consoleLogSpy.mock.calls[0][0]);
350
- expect(output.ok).toBe(false);
351
- expect(output.reason).toBe('activation_id_required');
352
- expect(output.nextAction).toContain('--activation-id');
353
- expect(process.exitCode).toBe(1);
354
- });
355
-
356
- it('missing --activation-id prints error and nextAction (text)', async () => {
357
- await handleRuntimeActivationDeactivate({
358
- workspace: WS,
359
- });
360
-
361
- expect(consoleErrorSpy).toHaveBeenCalledWith(expect.stringContaining('--activation-id is required'));
362
- expect(consoleErrorSpy).toHaveBeenCalledWith(expect.stringContaining('Next action'));
363
- expect(process.exitCode).toBe(1);
364
- });
365
-
366
- it('successful deactivation returns ok=true with deactivatedAt (JSON)', async () => {
367
- await handleRuntimeActivationDeactivate({
368
- workspace: WS,
369
- activationId: 'act-001',
370
- json: true,
371
- });
372
-
373
- const output = JSON.parse(consoleLogSpy.mock.calls[0][0]);
374
- expect(output.ok).toBe(true);
375
- expect(output.activationId).toBe('act-001');
376
- expect(output.deactivatedAt).toBeDefined();
377
- expect(process.exitCode).toBe(0);
378
- });
379
-
380
- it('not-found or already-deactivated returns ok=false with reason and nextAction (JSON)', async () => {
381
- // Override mock to return false (not found / already deactivated)
382
- const { SqliteActivationStateStore } = await import('@principles/core/runtime-v2');
383
- vi.mocked(SqliteActivationStateStore).mockImplementationOnce(function () {
384
- return {
385
- findByArtifactId: vi.fn().mockResolvedValue(null),
386
- insert: vi.fn().mockResolvedValue(undefined),
387
- deactivateActivation: vi.fn().mockResolvedValue(false),
388
- listPromptActivations: vi.fn().mockResolvedValue([]),
389
- listCodeToolHookActivations: vi.fn().mockResolvedValue([]),
390
- listAllActivations: vi.fn().mockResolvedValue([]),
391
- } as never;
392
- });
393
-
394
- await handleRuntimeActivationDeactivate({
395
- workspace: WS,
396
- activationId: 'act-gone',
397
- json: true,
398
- });
399
-
400
- const output = JSON.parse(consoleLogSpy.mock.calls[0][0]);
401
- expect(output.ok).toBe(false);
402
- expect(output.reason).toBe('not_found_or_already_deactivated');
403
- expect(output.nextAction).toContain('Check activation ID');
404
- expect(process.exitCode).toBe(1);
405
- });
406
-
407
- it('text output for success is human-readable', async () => {
408
- await handleRuntimeActivationDeactivate({
409
- workspace: WS,
410
- activationId: 'act-001',
411
- });
412
-
413
- const text = consoleLogSpy.mock.calls.map(c => c[0]).join('\n');
414
- expect(text).toContain('Deactivated: act-001');
415
- expect(text).toContain('deactivatedAt:');
416
- });
417
-
418
- // PRI-493 cli-5 no-mutation: not-found failure path must not call insert on
419
- // the activation state store. Production code (runtime-activation.ts
420
- // lines 253-267) calls deactivateActivation which returns false; no other
421
- // mutating method should be invoked. ERR-088 positive path marker: capture
422
- // the store instance and assert insert was never called.
423
- it('not-found failure path does not call insert on the activation store', async () => {
424
- const { SqliteActivationStateStore } = await import('@principles/core/runtime-v2');
425
- const capturedInsert = vi.fn().mockResolvedValue(undefined);
426
- const capturedDeactivate = vi.fn().mockResolvedValue(false);
427
- vi.mocked(SqliteActivationStateStore).mockImplementationOnce(function () {
428
- return {
429
- findByArtifactId: vi.fn().mockResolvedValue(null),
430
- insert: capturedInsert,
431
- deactivateActivation: capturedDeactivate,
432
- listPromptActivations: vi.fn().mockResolvedValue([]),
433
- listCodeToolHookActivations: vi.fn().mockResolvedValue([]),
434
- listAllActivations: vi.fn().mockResolvedValue([]),
435
- } as never;
436
- });
437
-
438
- await handleRuntimeActivationDeactivate({
439
- workspace: WS,
440
- activationId: 'act-gone',
441
- json: true,
442
- });
443
-
444
- expect(capturedDeactivate).toHaveBeenCalledTimes(1);
445
- expect(capturedDeactivate).toHaveBeenCalledWith('act-gone', expect.any(String));
446
- expect(capturedInsert).not.toHaveBeenCalled();
447
- expect(process.exitCode).toBe(1);
448
- });
449
- });
450
-
451
- // PRI-408 Contract D: List activations (observability) command tests
452
- describe('handleRuntimeActivationList', () => {
453
- let consoleLogSpy: ReturnType<typeof vi.spyOn>;
454
- let consoleErrorSpy: ReturnType<typeof vi.spyOn>;
455
-
456
- beforeEach(() => {
457
- vi.clearAllMocks();
458
- // F9-1: by default, all artifact_ids are considered valid (exist in pi_artifacts).
459
- // Individual tests override this to simulate dangling references.
460
- mockGetArtifactById.mockResolvedValue(makeArtifact());
461
- consoleLogSpy = vi.spyOn(console, 'log').mockImplementation(() => {});
462
- consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
463
- });
464
-
465
- afterEach(() => {
466
- consoleLogSpy.mockRestore();
467
- consoleErrorSpy.mockRestore();
468
- process.exitCode = 0;
469
- });
470
-
471
- it('JSON output is a single object with activations array', async () => {
472
- await handleRuntimeActivationList({
473
- workspace: WS,
474
- json: true,
475
- });
476
-
477
- const output = JSON.parse(consoleLogSpy.mock.calls[0][0]);
478
- expect(Array.isArray(output.activations)).toBe(true);
479
- expect(output.activations.length).toBe(2);
480
- expect(output.activations[0]).toHaveProperty('activationId');
481
- expect(output.activations[0]).toHaveProperty('channel');
482
- // PRI-500: CLI list output must include principleId (matching Console field).
483
- expect(output.activations[0]).toHaveProperty('principleId');
484
- expect(output.status).toBe('ok');
485
- });
486
-
487
- it('channel=prompt filter calls listPromptActivations', async () => {
488
- await handleRuntimeActivationList({
489
- workspace: WS,
490
- channel: 'prompt',
491
- json: true,
492
- });
493
-
494
- const output = JSON.parse(consoleLogSpy.mock.calls[0][0]);
495
- expect(output.activations.length).toBe(1);
496
- expect(output.activations[0].channel).toBe('prompt');
497
- });
498
-
499
- it('channel=code_tool_hook filter calls listCodeToolHookActivations', async () => {
500
- await handleRuntimeActivationList({
501
- workspace: WS,
502
- channel: 'code_tool_hook',
503
- json: true,
504
- });
505
-
506
- const output = JSON.parse(consoleLogSpy.mock.calls[0][0]);
507
- expect(output.activations.length).toBe(1);
508
- expect(output.activations[0].channel).toBe('code_tool_hook');
509
- });
510
-
511
- it('text output is human-readable with status, id, channel', async () => {
512
- await handleRuntimeActivationList({
513
- workspace: WS,
514
- });
515
-
516
- const text = consoleLogSpy.mock.calls.map(c => c[0]).join('\n');
517
- expect(text).toContain('[ACTIVE]');
518
- expect(text).toContain('act-prompt-1');
519
- expect(text).toContain('channel: prompt');
520
- });
521
-
522
- it('invalid channel returns structured error with nextAction (P2 #5 fix)', async () => {
523
- await handleRuntimeActivationList({
524
- workspace: WS,
525
- channel: 'invalid_channel',
526
- json: true,
527
- });
528
-
529
- const output = JSON.parse(consoleLogSpy.mock.calls[0][0]);
530
- expect(output.ok).toBe(false);
531
- expect(output.reason).toContain('invalid_channel');
532
- expect(output.nextAction).toContain('prompt');
533
- expect(process.exitCode).toBe(1);
534
- });
535
-
536
- it('invalid channel in text mode prints error and nextAction (P2 #5 fix)', async () => {
537
- await handleRuntimeActivationList({
538
- workspace: WS,
539
- channel: 'bogus',
540
- });
541
-
542
- const errorText = consoleErrorSpy.mock.calls.map(c => c[0]).join('\n');
543
- expect(errorText).toContain('invalid channel');
544
- expect(errorText).toContain('Next action');
545
- expect(process.exitCode).toBe(1);
546
- });
547
-
548
- // F9-1 regression: dangling artifact_id must produce degraded status + warning
549
- it('F9-1: emits degraded status + warning when activation references non-existent artifact_id (JSON)', async () => {
550
- // art-001 exists, art-002 does NOT (dangling)
551
- mockGetArtifactById.mockImplementation((artifactId: string) => {
552
- if (artifactId === 'art-001') return Promise.resolve(makeArtifact({ artifactId: 'art-001' }));
553
- return Promise.resolve(null);
554
- });
555
-
556
- await handleRuntimeActivationList({
557
- workspace: WS,
558
- json: true,
559
- });
560
-
561
- const output = JSON.parse(consoleLogSpy.mock.calls[0][0]);
562
- expect(output.status).toBe('degraded');
563
- expect(output.reason).toContain('non-existent artifact_id');
564
- expect(output.reason).toContain('art-002');
565
- expect(output.nextAction).toContain('pd runtime internalization integrity');
566
- // The dangling activation should have a per-record warning
567
- const danglingAct = output.activations.find((a: { artifactId: string }) => a.artifactId === 'art-002');
568
- expect(danglingAct.warning).toContain('does not exist in pi_artifacts');
569
- // The valid activation should NOT have a warning
570
- const validAct = output.activations.find((a: { artifactId: string }) => a.artifactId === 'art-001');
571
- expect(validAct.warning).toBeUndefined();
572
- });
573
-
574
- it('F9-1: text output prints WARNING line for dangling artifact_id', async () => {
575
- mockGetArtifactById.mockImplementation((artifactId: string) => {
576
- if (artifactId === 'art-001') return Promise.resolve(makeArtifact({ artifactId: 'art-001' }));
577
- return Promise.resolve(null);
578
- });
579
-
580
- await handleRuntimeActivationList({
581
- workspace: WS,
582
- });
583
-
584
- const text = consoleLogSpy.mock.calls.map(c => c[0]).join('\n');
585
- expect(text).toContain('WARNING');
586
- expect(text).toContain('art-002');
587
- const errorText = consoleErrorSpy.mock.calls.map(c => c[0]).join('\n');
588
- expect(errorText).toContain('non-existent artifact_id');
589
- expect(errorText).toContain('Next action');
590
- });
591
-
592
- it('F9-1: treats getArtifactById throw as dangling (fail loud, rc-9)', async () => {
593
- mockGetArtifactById.mockRejectedValue(new Error('DB corruption'));
594
-
595
- await handleRuntimeActivationList({
596
- workspace: WS,
597
- json: true,
598
- });
599
-
600
- const output = JSON.parse(consoleLogSpy.mock.calls[0][0]);
601
- expect(output.status).toBe('degraded');
602
- expect(output.reason).toContain('non-existent artifact_id');
603
- });
604
-
605
- it('F9-1: status is ok when all artifact_ids exist (negative case)', async () => {
606
- mockGetArtifactById.mockResolvedValue(makeArtifact());
607
-
608
- await handleRuntimeActivationList({
609
- workspace: WS,
610
- json: true,
611
- });
612
-
613
- const output = JSON.parse(consoleLogSpy.mock.calls[0][0]);
614
- expect(output.status).toBe('ok');
615
- expect(output.reason).toBeUndefined();
616
- expect(output.nextAction).toBeUndefined();
617
- });
618
-
619
- // ── PRI-491: owner observability (mode / status / contextVersion / evidenceRefs) ──
620
- //
621
- // The CLI list command must surface enough information for the owner to
622
- // answer "will this rule block now?" without opening SQLite or reading
623
- // logs. The four essential signals are:
624
- // 1. mode (shadow / live / undefined for unrecognized)
625
- // 2. status (active / suspended_by_flag / deactivated)
626
- // 3. contextVersion (v1 / v2) — needed to interpret suspended_by_flag
627
- // 4. nextAction (promote / deactivate / enable flag)
628
- //
629
- // ERR entries:
630
- // - ERR-002: suspended_by_flag is a degradation; it MUST carry a reason
631
- // via nextAction (rc-9-no-silent-fallback).
632
- // - ERR-088: tests must assert the unique status field, not only absence
633
- // of "active".
634
- // - ERR-023/033: --json output must remain a single parseable object.
635
-
636
- it('PRI-491: shadow v2 activation with flag off shows status=suspended_by_flag (JSON)', async () => {
637
- // Override the artifact to a v2 artifact with evidenceRefs.
638
- mockGetArtifactById.mockResolvedValue(makeArtifact({
639
- artifactId: 'art-v2-shadow',
640
- contentJson: JSON.stringify({
641
- requiresContextVersion: 2,
642
- evidenceRefs: ['ex-1', 'ex-2'],
643
- implementationCode: 'return { decision: "allow" };',
644
- }),
645
- }));
646
- // Override listCodeToolHookActivations to return a v2 shadow activation.
647
- mockListCodeToolHookActivations.mockResolvedValue([
648
- {
649
- activationId: 'act-v2-shadow',
650
- artifactId: 'art-v2-shadow',
651
- channel: 'code_tool_hook',
652
- action: 'code_tool_hook_shadow_activate',
653
- targetRef: 'edit_tool',
654
- activatedAt: '2026-06-18T00:00:00.000Z',
655
- promotedAt: null,
656
- deactivatedAt: null,
657
- },
658
- ]);
659
- // Default mockFeatureFlags has rulecode_context_v2 enabled. Flip it off
660
- // to simulate the migration-period kill switch (explicit
661
- // features.rulecode_context_v2.enabled: false; the registry default is ON
662
- // since PRI-780).
663
- mockFeatureFlags.flags.rulecode_context_v2.enabled = false;
664
-
665
- await handleRuntimeActivationList({
666
- workspace: WS,
667
- channel: 'code_tool_hook',
668
- json: true,
669
- });
670
-
671
- const output = JSON.parse(consoleLogSpy.mock.calls[0][0]);
672
- expect(output.activations).toHaveLength(1);
673
- const rec = output.activations[0];
674
- expect(rec.status).toBe('suspended_by_flag');
675
- expect(rec.mode).toBe('shadow');
676
- expect(rec.contextVersion).toBe('v2');
677
- expect(rec.evidenceRefs).toEqual(['ex-1', 'ex-2']);
678
- expect(rec.evidenceSummary).toContain('2 evidence ref(s)');
679
- expect(rec.nextAction).toContain('Enable rulecode_context_v2 flag');
680
- expect(rec.nextAction).toContain('pd activation deactivate --activation-id act-v2-shadow');
681
- expect(rec.nextAction).not.toContain('--confirm');
682
-
683
- // Restore the mock for subsequent tests.
684
- mockFeatureFlags.flags.rulecode_context_v2.enabled = true;
685
- });
686
-
687
- it('PRI-491: text output shows [SUSPENDED by flag] for v2 flag-off activation', async () => {
688
- mockGetArtifactById.mockResolvedValue(makeArtifact({
689
- artifactId: 'art-v2-shadow',
690
- contentJson: JSON.stringify({
691
- requiresContextVersion: 2,
692
- evidenceRefs: ['ex-1'],
693
- implementationCode: 'return { decision: "allow" };',
694
- }),
695
- }));
696
- mockListCodeToolHookActivations.mockResolvedValue([
697
- {
698
- activationId: 'act-v2-shadow',
699
- artifactId: 'art-v2-shadow',
700
- channel: 'code_tool_hook',
701
- action: 'code_tool_hook_shadow_activate',
702
- targetRef: 'edit_tool',
703
- activatedAt: '2026-06-18T00:00:00.000Z',
704
- promotedAt: null,
705
- deactivatedAt: null,
706
- },
707
- ]);
708
- mockFeatureFlags.flags.rulecode_context_v2.enabled = false;
709
-
710
- await handleRuntimeActivationList({
711
- workspace: WS,
712
- channel: 'code_tool_hook',
713
- });
714
-
715
- const text = consoleLogSpy.mock.calls.map(c => c[0]).join('\n');
716
- expect(text).toContain('[SUSPENDED by flag]');
717
- expect(text).toContain('(shadow)');
718
- expect(text).toContain('contextVersion: v2');
719
- expect(text).toContain('evidence:');
720
- expect(text).toContain('nextAction:');
721
-
722
- mockFeatureFlags.flags.rulecode_context_v2.enabled = true;
723
- });
724
-
725
- it('PRI-491: shadow v1 activation shows status=active and promote nextAction (JSON)', async () => {
726
- mockGetArtifactById.mockResolvedValue(makeArtifact({
727
- artifactId: 'art-v1-shadow',
728
- contentJson: JSON.stringify({ implementationCode: 'return { decision: "allow" };' }),
729
- }));
730
- mockListCodeToolHookActivations.mockResolvedValue([
731
- {
732
- activationId: 'act-v1-shadow',
733
- artifactId: 'art-v1-shadow',
734
- channel: 'code_tool_hook',
735
- action: 'code_tool_hook_shadow_activate',
736
- targetRef: 'edit_tool',
737
- activatedAt: '2026-06-18T00:00:00.000Z',
738
- promotedAt: null,
739
- deactivatedAt: null,
740
- },
741
- ]);
742
-
743
- await handleRuntimeActivationList({
744
- workspace: WS,
745
- channel: 'code_tool_hook',
746
- json: true,
747
- });
748
-
749
- const output = JSON.parse(consoleLogSpy.mock.calls[0][0]);
750
- const rec = output.activations[0];
751
- expect(rec.status).toBe('active');
752
- expect(rec.mode).toBe('shadow');
753
- expect(rec.contextVersion).toBe('v1');
754
- expect(rec.evidenceRefs).toBeUndefined();
755
- expect(rec.nextAction).toBe(
756
- 'Keep shadow; promotion requires an authenticated Owner decision, immutable evidence bindings, and a passing Promotion Readiness result.',
757
- );
758
- });
759
-
760
- it('PRI-491: live v1 activation shows status=active and deactivate nextAction (JSON)', async () => {
761
- mockGetArtifactById.mockResolvedValue(makeArtifact({
762
- artifactId: 'art-v1-live',
763
- contentJson: JSON.stringify({ implementationCode: 'return { decision: "allow" };' }),
764
- }));
765
- mockListCodeToolHookActivations.mockResolvedValue([
766
- {
767
- activationId: 'act-v1-live',
768
- artifactId: 'art-v1-live',
769
- channel: 'code_tool_hook',
770
- action: 'code_tool_hook_live_activate',
771
- targetRef: 'edit_tool',
772
- activatedAt: '2026-06-18T00:00:00.000Z',
773
- promotedAt: '2026-06-19T00:00:00.000Z',
774
- deactivatedAt: null,
775
- },
776
- ]);
777
-
778
- await handleRuntimeActivationList({
779
- workspace: WS,
780
- channel: 'code_tool_hook',
781
- json: true,
782
- });
783
-
784
- const output = JSON.parse(consoleLogSpy.mock.calls[0][0]);
785
- const rec = output.activations[0];
786
- expect(rec.status).toBe('active');
787
- expect(rec.mode).toBe('live');
788
- expect(rec.promotedAt).toBe('2026-06-19T00:00:00.000Z');
789
- expect(rec.nextAction).toBe('pd activation deactivate --activation-id act-v1-live');
790
- expect(rec.nextAction).not.toContain('--confirm');
791
- });
792
-
793
- it('PRI-491: text output shows promotedAt timestamp when present', async () => {
794
- mockGetArtifactById.mockResolvedValue(makeArtifact({
795
- artifactId: 'art-v1-live',
796
- contentJson: JSON.stringify({ implementationCode: 'return { decision: "allow" };' }),
797
- }));
798
- mockListCodeToolHookActivations.mockResolvedValue([
799
- {
800
- activationId: 'act-v1-live',
801
- artifactId: 'art-v1-live',
802
- channel: 'code_tool_hook',
803
- action: 'code_tool_hook_live_activate',
804
- targetRef: 'edit_tool',
805
- activatedAt: '2026-06-18T00:00:00.000Z',
806
- promotedAt: '2026-06-19T00:00:00.000Z',
807
- deactivatedAt: null,
808
- },
809
- ]);
810
-
811
- await handleRuntimeActivationList({
812
- workspace: WS,
813
- channel: 'code_tool_hook',
814
- });
815
-
816
- const text = consoleLogSpy.mock.calls.map(c => c[0]).join('\n');
817
- expect(text).toContain('(live)');
818
- expect(text).toContain('promotedAt: 2026-06-19T00:00:00.000Z');
819
- expect(text).toContain('nextAction: pd activation deactivate --activation-id act-v1-live');
820
- expect(text).not.toContain('--confirm');
821
- });
822
-
823
- it('PRI-491: deactivated activation shows [DEACTIVATED <ts>] regardless of contextVersion (precedence)', async () => {
824
- mockGetArtifactById.mockResolvedValue(makeArtifact({
825
- artifactId: 'art-v2-dead',
826
- contentJson: JSON.stringify({
827
- requiresContextVersion: 2,
828
- evidenceRefs: ['ex-1'],
829
- implementationCode: 'return { decision: "allow" };',
830
- }),
831
- }));
832
- mockListCodeToolHookActivations.mockResolvedValue([
833
- {
834
- activationId: 'act-v2-dead',
835
- artifactId: 'art-v2-dead',
836
- channel: 'code_tool_hook',
837
- action: 'code_tool_hook_live_activate',
838
- targetRef: 'edit_tool',
839
- activatedAt: '2026-06-18T00:00:00.000Z',
840
- promotedAt: '2026-06-19T00:00:00.000Z',
841
- deactivatedAt: '2026-06-20T00:00:00.000Z',
842
- },
843
- ]);
844
- mockFeatureFlags.flags.rulecode_context_v2.enabled = false;
845
-
846
- await handleRuntimeActivationList({
847
- workspace: WS,
848
- channel: 'code_tool_hook',
849
- includeDeactivated: true,
850
- json: true,
851
- });
852
-
853
- const output = JSON.parse(consoleLogSpy.mock.calls[0][0]);
854
- const rec = output.activations[0];
855
- // deactivated > suspended_by_flag > active — a deactivated record is NOT
856
- // reported as suspended_by_flag even when v2 + flag-off.
857
- expect(rec.status).toBe('deactivated');
858
- expect(rec.deactivatedAt).toBe('2026-06-20T00:00:00.000Z');
859
- expect(rec.nextAction).toBeUndefined();
860
-
861
- mockFeatureFlags.flags.rulecode_context_v2.enabled = true;
862
- });
863
-
864
- it('PRI-491: unrecognized action yields undefined mode and undefined nextAction (no false label)', async () => {
865
- mockGetArtifactById.mockResolvedValue(makeArtifact({
866
- artifactId: 'art-unknown',
867
- contentJson: JSON.stringify({ implementationCode: 'return { decision: "allow" };' }),
868
- }));
869
- mockListCodeToolHookActivations.mockResolvedValue([
870
- {
871
- activationId: 'act-unknown',
872
- artifactId: 'art-unknown',
873
- channel: 'code_tool_hook',
874
- action: 'some_future_action',
875
- targetRef: 'edit_tool',
876
- activatedAt: '2026-06-18T00:00:00.000Z',
877
- promotedAt: null,
878
- deactivatedAt: null,
879
- },
880
- ]);
881
-
882
- await handleRuntimeActivationList({
883
- workspace: WS,
884
- channel: 'code_tool_hook',
885
- json: true,
886
- });
887
-
888
- const output = JSON.parse(consoleLogSpy.mock.calls[0][0]);
889
- const rec = output.activations[0];
890
- expect(rec.mode).toBeUndefined();
891
- expect(rec.status).toBe('active');
892
- // No false nextAction — the owner must inspect manually.
893
- expect(rec.nextAction).toBeUndefined();
894
- });
895
-
896
- it('PRI-491: JSON output remains a single parseable object (cli-1-strict-json)', async () => {
897
- // Even with rich enrichment fields, the --json contract requires exactly
898
- // one parseable JSON object on stdout (no banners, no extra log lines).
899
- mockGetArtifactById.mockResolvedValue(makeArtifact({
900
- contentJson: JSON.stringify({
901
- requiresContextVersion: 2,
902
- evidenceRefs: ['ex-1'],
903
- implementationCode: 'return { decision: "allow" };',
904
- }),
905
- }));
906
- mockListCodeToolHookActivations.mockResolvedValue([
907
- {
908
- activationId: 'act-v2',
909
- artifactId: 'art-001',
910
- channel: 'code_tool_hook',
911
- action: 'code_tool_hook_shadow_activate',
912
- targetRef: 'edit_tool',
913
- activatedAt: '2026-06-18T00:00:00.000Z',
914
- promotedAt: null,
915
- deactivatedAt: null,
916
- },
917
- ]);
918
-
919
- await handleRuntimeActivationList({
920
- workspace: WS,
921
- channel: 'code_tool_hook',
922
- json: true,
923
- });
924
-
925
- // Exactly one console.log call on stdout (the JSON payload).
926
- expect(consoleLogSpy.mock.calls).toHaveLength(1);
927
- // And it parses cleanly.
928
- const output = JSON.parse(consoleLogSpy.mock.calls[0][0]);
929
- expect(output).toHaveProperty('activations');
930
- expect(output).toHaveProperty('status');
931
- });
932
- });
933
-
934
- describe('handleRuntimeActivationPromote', () => {
935
- let consoleLogSpy: ReturnType<typeof vi.spyOn>;
936
- let consoleErrorSpy: ReturnType<typeof vi.spyOn>;
937
-
938
- beforeEach(() => {
939
- vi.clearAllMocks();
940
- mockGetArtifactById.mockResolvedValue(null);
941
- mockListCodeToolHookActivations.mockResolvedValue([
942
- { activationId: 'act-hook-1', artifactId: 'art-002', channel: 'code_tool_hook', action: 'code_tool_hook_shadow_activate', targetRef: 'rule-001', activatedAt: '2026-06-18T00:00:00.000Z', promotedAt: null, deactivatedAt: null },
943
- ]);
944
- mockPromoteActivation.mockResolvedValue(true);
945
- consoleLogSpy = vi.spyOn(console, 'log').mockImplementation(() => {});
946
- consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
947
- mockFeatureFlags.flags.rulecode_owner_live_decision.enabled = false;
948
- vi.stubEnv('PD_CONSOLE_TOKEN', '');
949
- vi.stubEnv('PD_OWNER_ID', '');
950
- vi.stubEnv('PD_OWNER_CREDENTIAL_ID', '');
951
- });
952
-
953
- afterEach(() => {
954
- consoleLogSpy.mockRestore();
955
- consoleErrorSpy.mockRestore();
956
- process.exitCode = 0;
957
- vi.unstubAllEnvs();
958
- });
959
-
960
- it('feature-off refuses dry-run and does not construct a mutation store', async () => {
961
- const { RuntimeStateManager } = await import('@principles/core/runtime-v2');
962
- vi.mocked(RuntimeStateManager).mockClear();
963
- await handleRuntimeActivationPromote({ workspace: WS, activationId: 'act-hook-1', json: true });
964
- const output = JSON.parse(consoleLogSpy.mock.calls[0][0]);
965
- expect(output.decision).toBe('refused');
966
- expect(output.reasonCode).toBe('feature_not_enabled');
967
- expect(RuntimeStateManager).not.toHaveBeenCalled();
968
- expect(mockPromoteActivation).not.toHaveBeenCalled();
969
- });
970
-
971
- it('feature-off refuses confirmed promotion without legacy mutation', async () => {
972
- await handleRuntimeActivationPromote({ workspace: WS, activationId: 'act-hook-1', confirm: true, json: true });
973
- const output = JSON.parse(consoleLogSpy.mock.calls[0][0]);
974
- expect(output.reasonCode).toBe('feature_not_enabled');
975
- expect(mockPromoteActivation).not.toHaveBeenCalled();
976
- });
977
-
978
- it('feature-on refuses unauthenticated local promotion without mutation', async () => {
979
- mockFeatureFlags.flags.rulecode_owner_live_decision.enabled = true;
980
- await handleRuntimeActivationPromote({
981
- workspace: WS, activationId: 'act-hook-1', confirm: true, json: true,
982
- artifactId: 'art-002', artifactDigest: 'sha256:artifact', controlVersion: 1,
983
- idempotencyKey: 'promote-1', reasonCode: 'owner_review', note: 'reviewed',
984
- });
985
- const output = JSON.parse(consoleLogSpy.mock.calls[0][0]);
986
- expect(output.reasonCode).toBe('owner_authentication_required');
987
- expect(mockPromoteActivation).not.toHaveBeenCalled();
988
- });
989
-
990
- it('feature-on authenticated CLI uses the real readiness reader and reports missing artifact', async () => {
991
- mockFeatureFlags.flags.rulecode_owner_live_decision.enabled = true;
992
- vi.stubEnv('PD_CONSOLE_TOKEN', 'configured-secret');
993
- vi.stubEnv('PD_OWNER_ID', 'owner-1');
994
- vi.stubEnv('PD_OWNER_CREDENTIAL_ID', 'credential-1');
995
- await handleRuntimeActivationPromote({
996
- workspace: WS, activationId: 'act-hook-1', confirm: true, json: true,
997
- artifactId: 'art-002', artifactDigest: 'sha256:artifact', controlVersion: 1,
998
- idempotencyKey: 'promote-1', reasonCode: 'owner_review', note: 'reviewed',
999
- });
1000
- const output = JSON.parse(consoleLogSpy.mock.calls[0][0]);
1001
- expect(output.reasonCode).toBe('promotion_safety_gate_blocked');
1002
- expect(output.failedChecks).toEqual([{ checkId: 'lineage_binding', reasonCode: 'artifact_not_found' }]);
1003
- expect(mockClose).toHaveBeenCalledOnce();
1004
- expect(mockPromoteActivation).not.toHaveBeenCalled();
1005
- });
1006
-
1007
- it('authenticated dry-run opens state read-only and never commits', async () => {
1008
- const { RuntimeStateManager } = await import('@principles/core/runtime-v2');
1009
- mockFeatureFlags.flags.rulecode_owner_live_decision.enabled = true;
1010
- vi.stubEnv('PD_CONSOLE_TOKEN', 'configured-secret');
1011
- vi.stubEnv('PD_OWNER_ID', 'owner-1');
1012
- vi.stubEnv('PD_OWNER_CREDENTIAL_ID', 'credential-1');
1013
- await handleRuntimeActivationPromote({
1014
- workspace: WS, activationId: 'act-hook-1', dryRun: true, json: true,
1015
- artifactId: 'art-002', artifactDigest: 'sha256:artifact', controlVersion: 1,
1016
- idempotencyKey: 'promote-1', reasonCode: 'owner_review', note: 'reviewed',
1017
- });
1018
-
1019
- expect(RuntimeStateManager).toHaveBeenCalledWith(expect.objectContaining({ readonly: true }));
1020
- expect(mockPromoteActivation).not.toHaveBeenCalled();
1021
- });
1022
-
1023
- it('rejects mutually exclusive dry-run and confirm without mutation', async () => {
1024
- await handleRuntimeActivationPromote({ workspace: WS, activationId: 'act-hook-1', dryRun: true, confirm: true, json: true });
1025
- expect(mockPromoteActivation).not.toHaveBeenCalled();
1026
- expect(process.exitCode).toBe(1);
1027
- });
1028
-
1029
- it('P0-3: commit store failure emits structured refusal JSON and exit code 1', async () => {
1030
- mockFeatureFlags.flags.rulecode_owner_live_decision.enabled = true;
1031
- vi.stubEnv('PD_CONSOLE_TOKEN', 'configured-secret');
1032
- vi.stubEnv('PD_OWNER_ID', 'owner-1');
1033
- vi.stubEnv('PD_OWNER_CREDENTIAL_ID', 'credential-1');
1034
-
1035
- const artifact = makeArtifact({
1036
- artifactId: 'art-002',
1037
- lineageArtifactIds: ['task-000'],
1038
- contentJson: JSON.stringify({
1039
- principleId: 'P_001',
1040
- affectedTools: ['Bash'],
1041
- goldenTrace: {
1042
- traceId: 'trace-1',
1043
- sourcePainId: 'pain-1',
1044
- cases: [{ caseId: 'c1', kind: 'positive', toolName: 'Bash', params: {}, expectedDecision: 'allow' }],
1045
- createdAt: '2026-01-01T00:00:00.000Z',
1046
- },
1047
- }),
1048
- });
1049
- mockGetArtifactById.mockResolvedValue(artifact);
1050
- const artifactDigest = `sha256:${createHash('sha256').update(JSON.stringify(artifact), 'utf8').digest('hex')}`;
1051
-
1052
- // PRI-577 fail-loud contract: readiness is unavailable without a readable
1053
- // shadow telemetry source, so seed a real events file before promoting.
1054
- const wsDir = mkdtempSync(path.join(tmpdir(), 'pd-cli-p03-'));
1055
- mkdirSync(path.join(wsDir, '.pd', 'logs'), { recursive: true });
1056
- writeFileSync(
1057
- path.join(wsDir, '.pd', 'logs', 'events_20260821.jsonl'),
1058
- `${JSON.stringify({ type: 'rulehost_evaluated', ts: '2026-08-21T00:00:00.000Z', data: { activationId: 'act-hook-1', activationMode: 'shadow', matched: true, decision: 'allow' } })}\n`,
1059
- 'utf8',
1060
- );
1061
-
1062
- try {
1063
- await handleRuntimeActivationPromote({
1064
- workspace: wsDir,
1065
- activationId: 'act-hook-1',
1066
- confirm: true,
1067
- json: true,
1068
- artifactId: 'art-002',
1069
- artifactDigest,
1070
- controlVersion: 1,
1071
- idempotencyKey: 'promote-commit-fail-1',
1072
- reasonCode: 'controlled_rollout',
1073
- note: 'Owner accepts limited evidence for a controlled rollout.',
1074
- });
1075
-
1076
- const output = JSON.parse(consoleLogSpy.mock.calls[0][0]) as {
1077
- ok: boolean; decision: string; reasonCode: string; summary?: string; nextAction?: string;
1078
- };
1079
- expect(output.ok).toBe(false);
1080
- expect(output.decision).toBe('refused');
1081
- expect(output.reasonCode).toBe('promotion_commit_failed');
1082
- expect(output.summary).toContain('durable safety store');
1083
- expect(output.nextAction).toContain('retry');
1084
- expect(process.exitCode).toBe(1);
1085
- expect(mockPromoteActivation).not.toHaveBeenCalled();
1086
- } finally {
1087
- try { rmSync(wsDir, { recursive: true, force: true }); } catch { /* best effort */ }
1088
- }
1089
- });
1090
- });
1091
-
1092
- // P1 #2 fix: Edit pending approval command tests
1093
- describe('handleRuntimeActivationEdit', () => {
1094
- let consoleLogSpy: ReturnType<typeof vi.spyOn>;
1095
- let consoleErrorSpy: ReturnType<typeof vi.spyOn>;
1096
-
1097
- beforeEach(() => {
1098
- vi.clearAllMocks();
1099
- consoleLogSpy = vi.spyOn(console, 'log').mockImplementation(() => {});
1100
- consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
1101
- });
1102
-
1103
- afterEach(() => {
1104
- consoleLogSpy.mockRestore();
1105
- consoleErrorSpy.mockRestore();
1106
- process.exitCode = 0;
1107
- });
1108
-
1109
- it('missing --approval-id returns structured error with nextAction (JSON)', async () => {
1110
- await handleRuntimeActivationEdit({
1111
- workspace: WS,
1112
- newArtifactId: 'art-new',
1113
- editReason: 'fix typo',
1114
- json: true,
1115
- });
1116
-
1117
- const output = JSON.parse(consoleLogSpy.mock.calls[0][0]);
1118
- expect(output.ok).toBe(false);
1119
- expect(output.reason).toBe('approval_id_required');
1120
- expect(output.nextAction).toContain('--approval-id');
1121
- expect(process.exitCode).toBe(1);
1122
- });
1123
-
1124
- it('missing --new-artifact-id returns structured error with nextAction (JSON)', async () => {
1125
- await handleRuntimeActivationEdit({
1126
- workspace: WS,
1127
- approvalId: 'appr-001',
1128
- editReason: 'fix typo',
1129
- json: true,
1130
- });
1131
-
1132
- const output = JSON.parse(consoleLogSpy.mock.calls[0][0]);
1133
- expect(output.ok).toBe(false);
1134
- expect(output.reason).toBe('new_artifact_id_required');
1135
- expect(output.nextAction).toContain('--new-artifact-id');
1136
- expect(process.exitCode).toBe(1);
1137
- });
1138
-
1139
- it('missing --edit-reason returns structured error with nextAction (JSON)', async () => {
1140
- await handleRuntimeActivationEdit({
1141
- workspace: WS,
1142
- approvalId: 'appr-001',
1143
- newArtifactId: 'art-new',
1144
- json: true,
1145
- });
1146
-
1147
- const output = JSON.parse(consoleLogSpy.mock.calls[0][0]);
1148
- expect(output.ok).toBe(false);
1149
- expect(output.reason).toBe('edit_reason_required');
1150
- expect(output.nextAction).toContain('--edit-reason');
1151
- expect(process.exitCode).toBe(1);
1152
- });
1153
-
1154
- it('successful edit returns ok with newArtifactId and previousArtifactId (JSON)', async () => {
1155
- mockApprovalGetById.mockResolvedValue({
1156
- approvalId: 'appr-001',
1157
- artifactId: 'art-old',
1158
- status: 'pending',
1159
- });
1160
- mockGetArtifactById.mockImplementation(async (id: string) => {
1161
- if (id === 'art-new') {
1162
- return makeArtifact({ artifactId: 'art-new', sourceTaskId: 'task-001' });
1163
- }
1164
- if (id === 'art-old') {
1165
- return makeArtifact({ artifactId: 'art-old', sourceTaskId: 'task-001' });
1166
- }
1167
- return null;
1168
- });
1169
- mockApprovalEdit.mockResolvedValue({
1170
- ok: true,
1171
- record: {
1172
- approvalId: 'appr-001',
1173
- artifactId: 'art-new',
1174
- previousArtifactId: 'art-old',
1175
- editedAt: '2026-06-19T00:00:00.000Z',
1176
- status: 'pending',
1177
- },
1178
- });
1179
-
1180
- await handleRuntimeActivationEdit({
1181
- workspace: WS,
1182
- approvalId: 'appr-001',
1183
- newArtifactId: 'art-new',
1184
- editReason: 'fix typo in principle text',
1185
- json: true,
1186
- });
1187
-
1188
- const output = JSON.parse(consoleLogSpy.mock.calls[0][0]);
1189
- expect(output.ok).toBe(true);
1190
- expect(output.approvalId).toBe('appr-001');
1191
- expect(output.newArtifactId).toBe('art-new');
1192
- expect(output.previousArtifactId).toBe('art-old');
1193
- expect(output.editedAt).toBe('2026-06-19T00:00:00.000Z');
1194
- expect(process.exitCode).toBe(0);
1195
- });
1196
-
1197
- it('not_found approval returns structured error with nextAction (JSON)', async () => {
1198
- mockApprovalGetById.mockResolvedValue(null);
1199
- mockApprovalEdit.mockResolvedValue({
1200
- ok: false,
1201
- error: 'not_found',
1202
- });
1203
-
1204
- await handleRuntimeActivationEdit({
1205
- workspace: WS,
1206
- approvalId: 'appr-nonexistent',
1207
- newArtifactId: 'art-new',
1208
- editReason: 'fix typo',
1209
- json: true,
1210
- });
1211
-
1212
- const output = JSON.parse(consoleLogSpy.mock.calls[0][0]);
1213
- expect(output.ok).toBe(false);
1214
- expect(output.reason).toBe('not_found');
1215
- expect(output.nextAction).toContain('Check the approval ID');
1216
- expect(process.exitCode).toBe(1);
1217
- });
1218
-
1219
- it('already_decided approval returns structured error with nextAction (JSON)', async () => {
1220
- mockApprovalGetById.mockResolvedValue({
1221
- approvalId: 'appr-001',
1222
- artifactId: 'art-old',
1223
- status: 'approved',
1224
- });
1225
- mockApprovalEdit.mockResolvedValue({
1226
- ok: false,
1227
- error: 'already_decided',
1228
- status: 'approved',
1229
- });
1230
-
1231
- await handleRuntimeActivationEdit({
1232
- workspace: WS,
1233
- approvalId: 'appr-001',
1234
- newArtifactId: 'art-new',
1235
- editReason: 'fix typo',
1236
- json: true,
1237
- });
1238
-
1239
- const output = JSON.parse(consoleLogSpy.mock.calls[0][0]);
1240
- expect(output.ok).toBe(false);
1241
- expect(output.reason).toBe('already_decided');
1242
- expect(output.nextAction).toContain('already decided');
1243
- expect(output.nextAction).toContain('approved');
1244
- expect(process.exitCode).toBe(1);
1245
- });
1246
-
1247
- it('edit store throw returns structured error with nextAction (JSON)', async () => {
1248
- mockApprovalGetById.mockResolvedValue({
1249
- approvalId: 'appr-001',
1250
- artifactId: 'art-old',
1251
- status: 'pending',
1252
- });
1253
- mockGetArtifactById.mockImplementation(async (id: string) => {
1254
- if (id === 'art-new') {
1255
- return makeArtifact({ artifactId: 'art-new', sourceTaskId: 'task-001' });
1256
- }
1257
- if (id === 'art-old') {
1258
- return makeArtifact({ artifactId: 'art-old', sourceTaskId: 'task-001' });
1259
- }
1260
- return null;
1261
- });
1262
- mockApprovalEdit.mockRejectedValue(new Error('SQLITE_BUSY'));
1263
-
1264
- await handleRuntimeActivationEdit({
1265
- workspace: WS,
1266
- approvalId: 'appr-001',
1267
- newArtifactId: 'art-new',
1268
- editReason: 'fix typo',
1269
- json: true,
1270
- });
1271
-
1272
- const output = JSON.parse(consoleLogSpy.mock.calls[0][0]);
1273
- expect(output.ok).toBe(false);
1274
- expect(output.reason).toContain('edit_failed');
1275
- expect(output.reason).toContain('SQLITE_BUSY');
1276
- expect(output.nextAction).toContain('DB integrity');
1277
- expect(process.exitCode).toBe(1);
1278
- });
1279
-
1280
- it('text output is human-readable with next action hint', async () => {
1281
- mockApprovalGetById.mockResolvedValue({
1282
- approvalId: 'appr-001',
1283
- artifactId: 'art-old',
1284
- status: 'pending',
1285
- });
1286
- mockGetArtifactById.mockImplementation(async (id: string) => {
1287
- if (id === 'art-new') {
1288
- return makeArtifact({ artifactId: 'art-new', sourceTaskId: 'task-001' });
1289
- }
1290
- if (id === 'art-old') {
1291
- return makeArtifact({ artifactId: 'art-old', sourceTaskId: 'task-001' });
1292
- }
1293
- return null;
1294
- });
1295
- mockApprovalEdit.mockResolvedValue({
1296
- ok: true,
1297
- record: {
1298
- approvalId: 'appr-001',
1299
- artifactId: 'art-new',
1300
- previousArtifactId: 'art-old',
1301
- editedAt: '2026-06-19T00:00:00.000Z',
1302
- status: 'pending',
1303
- },
1304
- });
1305
-
1306
- await handleRuntimeActivationEdit({
1307
- workspace: WS,
1308
- approvalId: 'appr-001',
1309
- newArtifactId: 'art-new',
1310
- editReason: 'fix typo',
1311
- });
1312
-
1313
- const text = consoleLogSpy.mock.calls.map(c => c[0]).join('\n');
1314
- expect(text).toContain('Approval edited: appr-001');
1315
- expect(text).toContain('newArtifactId: art-new');
1316
- expect(text).toContain('previousArtifactId: art-old');
1317
- expect(text).toContain('Next action');
1318
- });
1319
-
1320
- it('artifact_not_found returns structured error with nextAction (JSON)', async () => {
1321
- mockApprovalGetById.mockResolvedValue({
1322
- approvalId: 'appr-001',
1323
- artifactId: 'art-old',
1324
- status: 'pending',
1325
- });
1326
- mockGetArtifactById.mockResolvedValue(null);
1327
-
1328
- await handleRuntimeActivationEdit({
1329
- workspace: WS,
1330
- approvalId: 'appr-001',
1331
- newArtifactId: 'art-nonexistent',
1332
- editReason: 'fix typo',
1333
- json: true,
1334
- });
1335
-
1336
- const output = JSON.parse(consoleLogSpy.mock.calls[0][0]);
1337
- expect(output.ok).toBe(false);
1338
- expect(output.reason).toBe('artifact_not_found');
1339
- expect(output.nextAction).toContain('does not exist');
1340
- expect(process.exitCode).toBe(1);
1341
- });
1342
-
1343
- it('artifact_not_validated returns structured error with nextAction (JSON)', async () => {
1344
- mockApprovalGetById.mockResolvedValue({
1345
- approvalId: 'appr-001',
1346
- artifactId: 'art-old',
1347
- status: 'pending',
1348
- });
1349
- mockGetArtifactById.mockImplementation(async (id: string) => {
1350
- if (id === 'art-new') {
1351
- return { artifactId: 'art-new', validationStatus: 'pending', sourceTaskId: 'task-001' };
1352
- }
1353
- return null;
1354
- });
1355
-
1356
- await handleRuntimeActivationEdit({
1357
- workspace: WS,
1358
- approvalId: 'appr-001',
1359
- newArtifactId: 'art-new',
1360
- editReason: 'fix typo',
1361
- json: true,
1362
- });
1363
-
1364
- const output = JSON.parse(consoleLogSpy.mock.calls[0][0]);
1365
- expect(output.ok).toBe(false);
1366
- expect(output.reason).toContain('artifact_not_validated');
1367
- expect(output.nextAction).toContain('production gate');
1368
- expect(process.exitCode).toBe(1);
1369
- });
1370
-
1371
- it('artifact_lineage_mismatch returns structured error with nextAction (JSON)', async () => {
1372
- mockApprovalGetById.mockResolvedValue({
1373
- approvalId: 'appr-001',
1374
- artifactId: 'art-old',
1375
- status: 'pending',
1376
- });
1377
- mockGetArtifactById.mockImplementation(async (id: string) => {
1378
- if (id === 'art-new') {
1379
- return { artifactId: 'art-new', validationStatus: 'validated', sourceTaskId: 'task-002', lineageArtifactIds: [] };
1380
- }
1381
- if (id === 'art-old') {
1382
- return { artifactId: 'art-old', validationStatus: 'validated', sourceTaskId: 'task-001', sourcePrincipleId: 'principle-old', lineageArtifactIds: [] };
1383
- }
1384
- return null;
1385
- });
1386
-
1387
- await handleRuntimeActivationEdit({
1388
- workspace: WS,
1389
- approvalId: 'appr-001',
1390
- newArtifactId: 'art-new',
1391
- editReason: 'fix typo',
1392
- json: true,
1393
- });
1394
-
1395
- const output = JSON.parse(consoleLogSpy.mock.calls[0][0]);
1396
- expect(output.ok).toBe(false);
1397
- expect(output.reason).toBe('artifact_lineage_mismatch');
1398
- expect(output.nextAction).toContain('must reference art-old');
1399
- expect(process.exitCode).toBe(1);
1400
- });
1401
-
1402
- it('allows a validated revision from a new task when lineage references the approved artifact', async () => {
1403
- mockApprovalGetById.mockResolvedValue({ approvalId: 'appr-001', artifactId: 'art-old', status: 'pending' });
1404
- mockGetArtifactById.mockImplementation(async (id: string) => {
1405
- if (id === 'art-new') {
1406
- return {
1407
- artifactId: 'art-new', validationStatus: 'validated', sourceTaskId: 'owner-edit-task',
1408
- sourcePrincipleId: 'principle-old', lineageArtifactIds: ['art-old'],
1409
- };
1410
- }
1411
- if (id === 'art-old') {
1412
- return {
1413
- artifactId: 'art-old', validationStatus: 'validated', sourceTaskId: 'generation-task',
1414
- sourcePrincipleId: 'principle-old', lineageArtifactIds: [],
1415
- };
1416
- }
1417
- return null;
1418
- });
1419
- mockApprovalEdit.mockResolvedValue({
1420
- ok: true,
1421
- record: { approvalId: 'appr-001', artifactId: 'art-new', previousArtifactId: 'art-old', status: 'pending' },
1422
- });
1423
-
1424
- await handleRuntimeActivationEdit({
1425
- workspace: WS,
1426
- approvalId: 'appr-001',
1427
- newArtifactId: 'art-new',
1428
- editReason: 'owner revision',
1429
- json: true,
1430
- });
1431
-
1432
- const output = JSON.parse(consoleLogSpy.mock.calls[0][0]);
1433
- expect(output.ok).toBe(true);
1434
- expect(mockApprovalEdit).toHaveBeenCalledOnce();
1435
- });
1436
-
1437
- });
1438
-
1439
- // Bug-M fix: Approve command tests (CLI closed loop)
1440
- describe('handleActivationApprove', () => {
1441
- let consoleLogSpy: ReturnType<typeof vi.spyOn>;
1442
- let consoleErrorSpy: ReturnType<typeof vi.spyOn>;
1443
-
1444
- beforeEach(() => {
1445
- vi.clearAllMocks();
1446
- mockRuleHostWriterConfigs.length = 0;
1447
- consoleLogSpy = vi.spyOn(console, 'log').mockImplementation(() => {});
1448
- consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
1449
- mockGetArtifactById.mockResolvedValue(makeArtifact());
1450
- mockApprovalResetToPending.mockResolvedValue({ ok: true });
1451
- });
1452
-
1453
- afterEach(() => {
1454
- consoleLogSpy.mockRestore();
1455
- consoleErrorSpy.mockRestore();
1456
- process.exitCode = 0;
1457
- });
1458
-
1459
- it('AP-01: missing --approval-id returns structured error with nextAction (JSON)', async () => {
1460
- await handleActivationApprove({
1461
- workspace: WS,
1462
- json: true,
1463
- });
1464
-
1465
- const output = JSON.parse(consoleLogSpy.mock.calls[0][0]);
1466
- expect(output.ok).toBe(false);
1467
- expect(output.reason).toBe('approval_id_required');
1468
- expect(output.nextAction).toContain('--approval-id');
1469
- expect(process.exitCode).toBe(1);
1470
- });
1471
-
1472
- it('AP-02: approval not_found returns structured error with nextAction (JSON)', async () => {
1473
- mockApprovalApprove.mockResolvedValue({ ok: false, error: 'not_found' });
1474
-
1475
- await handleActivationApprove({
1476
- workspace: WS,
1477
- approvalId: 'appr-nonexistent',
1478
- json: true,
1479
- });
1480
-
1481
- const output = JSON.parse(consoleLogSpy.mock.calls[0][0]);
1482
- expect(output.ok).toBe(false);
1483
- expect(output.reason).toBe('approval_not_found');
1484
- expect(output.nextAction).toContain('Check the approval ID');
1485
- expect(process.exitCode).toBe(1);
1486
- });
1487
-
1488
- it('AP-03: already_decided returns structured error with status (JSON)', async () => {
1489
- mockApprovalApprove.mockResolvedValue({ ok: false, error: 'already_decided', status: 'rejected' });
1490
-
1491
- await handleActivationApprove({
1492
- workspace: WS,
1493
- approvalId: 'appr-001',
1494
- json: true,
1495
- });
1496
-
1497
- const output = JSON.parse(consoleLogSpy.mock.calls[0][0]);
1498
- expect(output.ok).toBe(false);
1499
- expect(output.reason).toContain('already_decided');
1500
- expect(output.reason).toContain('rejected');
1501
- expect(output.nextAction).toContain('already decided');
1502
- expect(process.exitCode).toBe(1);
1503
- });
1504
-
1505
- it('AP-04: success path returns ok=true with activationId and decision (JSON)', async () => {
1506
- mockApprovalApprove.mockResolvedValue({
1507
- ok: true,
1508
- record: { approvalId: 'appr-001', artifactId: 'art-001', status: 'approved' },
1509
- });
1510
- mockCompletionComplete.mockResolvedValue({
1511
- ok: true,
1512
- activationId: 'act-001',
1513
- decision: { decision: 'activated', activationId: 'act-001', action: 'prompt', targetRef: 'P_001' },
1514
- });
1515
-
1516
- await handleActivationApprove({
1517
- workspace: WS,
1518
- approvalId: 'appr-001',
1519
- decidedBy: 'test-owner',
1520
- json: true,
1521
- });
1522
-
1523
- const output = JSON.parse(consoleLogSpy.mock.calls[0][0]);
1524
- expect(output.ok).toBe(true);
1525
- expect(output.approvalId).toBe('appr-001');
1526
- expect(output.activationId).toBe('act-001');
1527
- expect(output.decision).toBe('activated');
1528
- expect(output.nextAction).toBe('pd activation list');
1529
- expect(process.exitCode).toBe(0);
1530
- });
1531
-
1532
- it('AP-05: --json output is a single parseable JSON object (cli-1-strict-json)', async () => {
1533
- mockApprovalApprove.mockResolvedValue({
1534
- ok: true,
1535
- record: { approvalId: 'appr-001', artifactId: 'art-001', status: 'approved' },
1536
- });
1537
- mockCompletionComplete.mockResolvedValue({
1538
- ok: true,
1539
- activationId: 'act-001',
1540
- decision: { decision: 'activated', activationId: 'act-001', action: 'prompt', targetRef: 'P_001' },
1541
- });
1542
-
1543
- await handleActivationApprove({
1544
- workspace: WS,
1545
- approvalId: 'appr-001',
1546
- json: true,
1547
- });
1548
-
1549
- // Exactly one console.log call with a single JSON object
1550
- expect(consoleLogSpy).toHaveBeenCalledTimes(1);
1551
- const rawOutput = consoleLogSpy.mock.calls[0][0];
1552
- const parsed = JSON.parse(rawOutput);
1553
- expect(parsed).toBeInstanceOf(Object);
1554
- expect(parsed.ok).toBe(true);
1555
- });
1556
-
1557
- it('AP-06: completeApproval !ok rolls back approval and returns structured error (JSON)', async () => {
1558
- mockApprovalApprove.mockResolvedValue({
1559
- ok: true,
1560
- record: { approvalId: 'appr-001', artifactId: 'art-001', status: 'approved' },
1561
- });
1562
- mockCompletionComplete.mockResolvedValue({
1563
- ok: false,
1564
- reason: 'artifact_not_validated',
1565
- nextAction: 'Check artifact validation status and retry dispatch.',
1566
- });
1567
-
1568
- await handleActivationApprove({
1569
- workspace: WS,
1570
- approvalId: 'appr-001',
1571
- json: true,
1572
- });
1573
-
1574
- const output = JSON.parse(consoleLogSpy.mock.calls[0][0]);
1575
- expect(output.ok).toBe(false);
1576
- expect(output.reason).toContain('activation_failed');
1577
- expect(output.reason).toContain('artifact_not_validated');
1578
- expect(output.approvalRolledBack).toBe(true);
1579
- expect(output.nextAction).toContain('rolled back to pending');
1580
- expect(process.exitCode).toBe(1);
1581
- // cli-5: rollback was attempted via resetToPending
1582
- expect(mockApprovalResetToPending).toHaveBeenCalledWith('appr-001');
1583
- });
1584
-
1585
- it('AP-06b: completeApproval throw rolls back approval and returns structured error (JSON)', async () => {
1586
- mockApprovalApprove.mockResolvedValue({
1587
- ok: true,
1588
- record: { approvalId: 'appr-001', artifactId: 'art-001', status: 'approved' },
1589
- });
1590
- mockCompletionComplete.mockRejectedValue(new Error('sqlite: disk I/O error'));
1591
-
1592
- await handleActivationApprove({
1593
- workspace: WS,
1594
- approvalId: 'appr-001',
1595
- json: true,
1596
- });
1597
-
1598
- const output = JSON.parse(consoleLogSpy.mock.calls[0][0]);
1599
- expect(output.ok).toBe(false);
1600
- expect(output.reason).toContain('activation_completion_failed');
1601
- expect(output.reason).toContain('disk I/O error');
1602
- expect(output.approvalRolledBack).toBe(true);
1603
- expect(output.nextAction).toContain('rolled back to pending');
1604
- expect(process.exitCode).toBe(1);
1605
- expect(mockApprovalResetToPending).toHaveBeenCalledWith('appr-001');
1606
- });
1607
-
1608
- it('AP-06c: rollback failure surfaces approvalRolledBack=false with retry guidance (JSON)', async () => {
1609
- mockApprovalApprove.mockResolvedValue({
1610
- ok: true,
1611
- record: { approvalId: 'appr-001', artifactId: 'art-001', status: 'approved' },
1612
- });
1613
- mockCompletionComplete.mockResolvedValue({
1614
- ok: false,
1615
- reason: 'artifact_not_validated',
1616
- nextAction: 'Check artifact validation status and retry dispatch.',
1617
- });
1618
- mockApprovalResetToPending.mockResolvedValue({ ok: false, error: 'not_found' });
1619
-
1620
- await handleActivationApprove({
1621
- workspace: WS,
1622
- approvalId: 'appr-001',
1623
- json: true,
1624
- });
1625
-
1626
- const output = JSON.parse(consoleLogSpy.mock.calls[0][0]);
1627
- expect(output.ok).toBe(false);
1628
- expect(output.approvalRolledBack).toBe(false);
1629
- expect(output.nextAction).toContain("remains 'approved'");
1630
- expect(process.exitCode).toBe(1);
1631
- });
1632
-
1633
- it('AP-07: Commander flag wiring — --approval-id is required at parser level (cli-7-test-wiring)', async () => {
1634
- // cli-7-test-wiring: exercise the real Commander parser path (not just the
1635
- // handler) to verify `--approval-id` is registered as a required option.
1636
- // Follows the project's established pattern in runtime-internalization-run-once.test.ts
1637
- // (buildXxxCommand + program.exitOverride() + parseAsync).
1638
- const { Command } = await import('commander');
1639
- const program = new Command();
1640
- program.exitOverride(); // surface Commander errors as throws instead of process.exit
1641
-
1642
- const activationCmd = program.command('activation');
1643
- activationCmd
1644
- .command('approve')
1645
- .description('Approve a pending approval and dispatch its activation')
1646
- .requiredOption('-a, --approval-id <id>', 'Approval ID to approve')
1647
- .option('--decided-by <user>', 'Reviewer name (default: cli-operator)')
1648
- .option('--note <text>', 'Optional approval note')
1649
- .option('-w, --workspace <path>', 'Workspace directory')
1650
- .option('--json', 'Output raw JSON')
1651
- .action(async () => { /* no-op for parser test */ });
1652
-
1653
- // Case 1: missing --approval-id → Commander throws required-option error
1654
- await expect(
1655
- program.parseAsync(['node', 'pd', 'activation', 'approve', '--json']),
1656
- ).rejects.toThrow(/required option.*--approval-id.*not specified/);
1657
-
1658
- // Case 2: with --approval-id → parses successfully and exposes the option
1659
- const captured: Record<string, unknown> = {};
1660
- const program2 = new Command();
1661
- program2.exitOverride();
1662
- const activationCmd2 = program2.command('activation');
1663
- activationCmd2
1664
- .command('approve')
1665
- .requiredOption('-a, --approval-id <id>', 'Approval ID to approve')
1666
- .option('--decided-by <user>', 'Reviewer name')
1667
- .option('--note <text>', 'Optional approval note')
1668
- .option('-w, --workspace <path>', 'Workspace directory')
1669
- .option('--json', 'Output raw JSON')
1670
- .action(async (opts) => { Object.assign(captured, opts); });
1671
-
1672
- await program2.parseAsync([
1673
- 'node', 'pd', 'activation', 'approve',
1674
- '--approval-id', 'appr-007',
1675
- '--decided-by', 'alice',
1676
- '--note', 'lgtm',
1677
- '--json',
1678
- ]);
1679
-
1680
- expect(captured.approvalId).toBe('appr-007');
1681
- expect(captured.decidedBy).toBe('alice');
1682
- expect(captured.note).toBe('lgtm');
1683
- expect(captured.json).toBe(true);
1684
- });
1685
-
1686
- // PRI-489 AP-08: The approve path must inject the real workspace
1687
- // `rulecode_context_v2` feature flag probe into RuleHostWriter — same
1688
- // wiring as the dispatch path (tested at line 136-146) and the Console
1689
- // model (ApprovalsConsoleModel.dispatchActivationAfterApproval).
1690
- // Previously this path constructed RuleHostWriter without the probe, so a
1691
- // v2 artifact in a flag-off workspace would pass canActivate here while
1692
- // being rejected by dispatch/Console — an inconsistent contract that
1693
- // violated ERR-024 (validator wired in one enforcement path but not
1694
- // another) and ERR-089 (sibling approval path diverged from dispatch).
1695
- it('AP-08: wires the effective workspace feature flags into RuleHostWriter (ERR-024/ERR-089)', async () => {
1696
- mockApprovalApprove.mockResolvedValue({
1697
- ok: true,
1698
- record: { approvalId: 'appr-001', artifactId: 'art-001', status: 'approved' },
1699
- });
1700
- mockCompletionComplete.mockResolvedValue({
1701
- ok: true,
1702
- activationId: 'act-001',
1703
- decision: { decision: 'activated', activationId: 'act-001', action: 'prompt', targetRef: 'P_001' },
1704
- });
1705
-
1706
- await handleActivationApprove({
1707
- workspace: WS,
1708
- approvalId: 'appr-001',
1709
- decidedBy: 'test-owner',
1710
- json: true,
1711
- });
1712
-
1713
- // The RuleHostWriter mock captures its constructor config — verify the
1714
- // featureFlagProbe was injected and reflects the mocked feature flags
1715
- // (rulecode_context_v2: enabled=true, see mockFeatureFlags at top).
1716
- expect(mockRuleHostWriterConfigs).toHaveLength(1);
1717
- expect(mockRuleHostWriterConfigs[0]?.featureFlagProbe).toBeDefined();
1718
- expect(mockRuleHostWriterConfigs[0]?.featureFlagProbe?.('rulecode_context_v2')).toBe(true);
1719
- // Unknown flags must not be reported as enabled (rc-2-no-as-bypass).
1720
- expect(mockRuleHostWriterConfigs[0]?.featureFlagProbe?.('nonexistent_flag')).toBe(false);
1721
- });
1722
- });
1723
-
1724
- // ── PRI-499: CLI parser wiring (cli-7) and exit-stops (cli-2) ─────────────
1725
- //
1726
- // cli-7-test-wiring: every activation subcommand must exercise the real
1727
- // Commander flag registration path. Without this, a future refactor could
1728
- // silently break flag parsing and only surface at runtime. The existing
1729
- // `approve` parser test (AP-07 above) is the template; these tests extend
1730
- // coverage to dispatch, deactivate, promote, and list.
1731
- //
1732
- // cli-2-exit-stops: failure paths that call process.exit must not trigger
1733
- // downstream side effects (DB writes, ledger updates, artifact creation).
1734
- // Stubs process.exit to throw, then asserts no store was constructed.
1735
-
1736
- describe('PRI-499: CLI parser wiring (cli-7) for activation subcommands', () => {
1737
- it('dispatch: --artifact-id, --channel, --dry-run, --confirm, --json parse correctly', async () => {
1738
- const { Command } = await import('commander');
1739
- const captured: Record<string, unknown> = {};
1740
- const program = new Command();
1741
- program.exitOverride();
1742
- const activationCmd = program.command('activation');
1743
- registerRuntimeActivationDispatchCommand(activationCmd)
1744
- .action(async (opts) => { Object.assign(captured, opts); });
1745
-
1746
- await program.parseAsync([
1747
- 'node', 'pd', 'activation', 'dispatch',
1748
- '--artifact-id', 'art-parse-001',
1749
- '--channel', 'prompt',
1750
- '--dry-run',
1751
- '--json',
1752
- ]);
1753
-
1754
- expect(captured.artifactId).toBe('art-parse-001');
1755
- expect(captured.channel).toBe('prompt');
1756
- expect(captured.dryRun).toBe(true);
1757
- expect(captured.confirm).toBeUndefined();
1758
- expect(captured.json).toBe(true);
1759
- });
1760
-
1761
- it('dispatch: --confirm flag parses and is mutually exclusive with --dry-run at handler level', async () => {
1762
- const { Command } = await import('commander');
1763
- const captured: Record<string, unknown> = {};
1764
- const program = new Command();
1765
- program.exitOverride();
1766
- const activationCmd = program.command('activation');
1767
- registerRuntimeActivationDispatchCommand(activationCmd)
1768
- .action(async (opts) => { Object.assign(captured, opts); });
1769
-
1770
- await program.parseAsync([
1771
- 'node', 'pd', 'activation', 'dispatch',
1772
- '--artifact-id', 'art-confirm',
1773
- '--confirm',
1774
- '--json',
1775
- ]);
1776
-
1777
- expect(captured.confirm).toBe(true);
1778
- expect(captured.dryRun).toBeUndefined();
1779
- });
1780
-
1781
- it('deactivate: --activation-id (required) parses correctly', async () => {
1782
- const { Command } = await import('commander');
1783
- const captured: Record<string, unknown> = {};
1784
- const program = new Command();
1785
- program.exitOverride();
1786
- const activationCmd = program.command('activation');
1787
- registerRuntimeActivationDeactivateCommand(activationCmd)
1788
- .action(async (opts) => { Object.assign(captured, opts); });
1789
-
1790
- await program.parseAsync([
1791
- 'node', 'pd', 'activation', 'deactivate',
1792
- '--activation-id', 'act-parse-deact',
1793
- '--json',
1794
- ]);
1795
-
1796
- expect(captured.activationId).toBe('act-parse-deact');
1797
- expect(captured.json).toBe(true);
1798
- });
1799
-
1800
- it('deactivate: missing --activation-id fails at parser level (required option)', async () => {
1801
- const { Command } = await import('commander');
1802
- const program = new Command();
1803
- program.exitOverride();
1804
- const activationCmd = program.command('activation');
1805
- registerRuntimeActivationDeactivateCommand(activationCmd)
1806
- .action(async () => { /* no-op */ });
1807
-
1808
- await expect(
1809
- program.parseAsync(['node', 'pd', 'activation', 'deactivate', '--json']),
1810
- ).rejects.toThrow(/required option.*--activation-id.*not specified/);
1811
- });
1812
-
1813
- it('promote: --activation-id (required), --dry-run, --confirm parse correctly', async () => {
1814
- const { Command } = await import('commander');
1815
- const captured: Record<string, unknown> = {};
1816
- const program = new Command();
1817
- program.exitOverride();
1818
- const activationCmd = program.command('activation');
1819
- registerRuntimeActivationPromoteCommand(activationCmd)
1820
- .action(async (opts) => { Object.assign(captured, opts); });
1821
-
1822
- await program.parseAsync([
1823
- 'node', 'pd', 'activation', 'promote',
1824
- '--activation-id', 'act-parse-promote',
1825
- '--dry-run',
1826
- '--json',
1827
- ]);
1828
-
1829
- expect(captured.activationId).toBe('act-parse-promote');
1830
- expect(captured.dryRun).toBe(true);
1831
- expect(captured.confirm).toBeUndefined();
1832
- });
1833
-
1834
- it('promote: --confirm flag parses (not --dry-run)', async () => {
1835
- const { Command } = await import('commander');
1836
- const captured: Record<string, unknown> = {};
1837
- const program = new Command();
1838
- program.exitOverride();
1839
- const activationCmd = program.command('activation');
1840
- registerRuntimeActivationPromoteCommand(activationCmd)
1841
- .action(async (opts) => { Object.assign(captured, opts); });
1842
-
1843
- await program.parseAsync([
1844
- 'node', 'pd', 'activation', 'promote',
1845
- '--activation-id', 'act-promote-confirm',
1846
- '--confirm',
1847
- '--json',
1848
- ]);
1849
-
1850
- expect(captured.confirm).toBe(true);
1851
- expect(captured.dryRun).toBeUndefined();
1852
- });
1853
-
1854
- it('list: --channel filter and --json parse correctly', async () => {
1855
- const { Command } = await import('commander');
1856
- const captured: Record<string, unknown> = {};
1857
- const program = new Command();
1858
- program.exitOverride();
1859
- const activationCmd = program.command('activation');
1860
- registerRuntimeActivationListCommand(activationCmd)
1861
- .action(async (opts) => { Object.assign(captured, opts); });
1862
-
1863
- await program.parseAsync([
1864
- 'node', 'pd', 'activation', 'list',
1865
- '--channel', 'code_tool_hook',
1866
- '--json',
1867
- ]);
1868
-
1869
- expect(captured.channel).toBe('code_tool_hook');
1870
- expect(captured.json).toBe(true);
1871
- expect(captured.includeDeactivated).toBeUndefined();
1872
- });
1873
-
1874
- it('list: --include-deactivated flag parses as boolean true', async () => {
1875
- const { Command } = await import('commander');
1876
- const captured: Record<string, unknown> = {};
1877
- const program = new Command();
1878
- program.exitOverride();
1879
- const activationCmd = program.command('activation');
1880
- registerRuntimeActivationListCommand(activationCmd)
1881
- .action(async (opts) => { Object.assign(captured, opts); });
1882
-
1883
- await program.parseAsync([
1884
- 'node', 'pd', 'activation', 'list',
1885
- '--include-deactivated',
1886
- '--json',
1887
- ]);
1888
-
1889
- expect(captured.includeDeactivated).toBe(true);
1890
- });
1891
- });
1892
-
1893
- // PRI-499 cli-2-exit-stops: Verify failure paths do NOT trigger DB/ledger/
1894
- // artifact side effects. Production code uses `process.exitCode = 1` (not
1895
- // `process.exit(1)`) and returns early — these tests assert both the exit
1896
- // code AND that no store was constructed, covering the high-risk channel
1897
- // refusal path that was not covered by the existing tests at lines 266-303.
1898
- // If a future change replaces `process.exitCode` with `process.exit()` but
1899
- // forgets to add a `return`, these tests will fail because the store mock
1900
- // would be called before the exit.
1901
- describe('PRI-499: cli-2-exit-stops — failure paths set exitCode and do not construct stores', () => {
1902
- let consoleLogSpy: ReturnType<typeof vi.spyOn>;
1903
- let consoleErrorSpy: ReturnType<typeof vi.spyOn>;
1904
-
1905
- beforeEach(() => {
1906
- vi.clearAllMocks();
1907
- mockRuleHostWriterConfigs.length = 0;
1908
- consoleLogSpy = vi.spyOn(console, 'log').mockImplementation(() => {});
1909
- consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
1910
- mockGetArtifactById.mockResolvedValue(makeArtifact());
1911
- });
1912
-
1913
- afterEach(() => {
1914
- consoleLogSpy.mockRestore();
1915
- consoleErrorSpy.mockRestore();
1916
- process.exitCode = 0;
1917
- });
1918
-
1919
- it('high-risk channel refusal: sets exitCode=1 and returns structured refusal (cli-2)', async () => {
1920
- await handleRuntimeActivationDispatch({
1921
- workspace: WS,
1922
- artifactId: 'art-001',
1923
- channel: 'code_tool_hook',
1924
- json: true,
1925
- });
1926
-
1927
- // cli-2: exit-stops — refused path must set exitCode and return a
1928
- // structured refusal. Stores ARE constructed (artifact exists, so
1929
- // RuntimeStateManager/SqliteActivationStateStore/ActivationDispatcher
1930
- // are built before dispatch() returns 'refused'). The cli-2 guarantee
1931
- // for this path = exitCode set + structured output, NOT "no store
1932
- // construction" (rc-9 + cli-6).
1933
- expect(process.exitCode).toBe(1);
1934
-
1935
- // Verify the JSON output is a structured refusal (rc-9 + cli-6).
1936
- const output = JSON.parse(consoleLogSpy.mock.calls[0][0]);
1937
- expect(output.decision).toBe('refused');
1938
- expect(output.reason).toBeDefined();
1939
- expect(output.nextAction).toBeDefined();
1940
- });
1941
-
1942
- it('missing artifact: sets exitCode=1 and does not construct SqliteActivationStateStore or ActivationDispatcher (cli-2)', async () => {
1943
- mockGetArtifactById.mockResolvedValue(null);
1944
- const { SqliteActivationStateStore, ActivationDispatcher } = await import('@principles/core/runtime-v2');
1945
- vi.mocked(SqliteActivationStateStore).mockClear();
1946
- vi.mocked(ActivationDispatcher).mockClear();
1947
-
1948
- await handleRuntimeActivationDispatch({
1949
- workspace: WS,
1950
- artifactId: 'nonexistent-cli-2',
1951
- channel: 'prompt',
1952
- json: true,
1953
- });
1954
-
1955
- // cli-2: RuntimeStateManager IS constructed at line 143 (needed to check
1956
- // artifact existence via getArtifactById). But SqliteActivationStateStore
1957
- // and ActivationDispatcher are NOT constructed — the handler returns at
1958
- // line 156 before reaching lines 170/175. This is the no-DB-side-effects
1959
- // guarantee for the missing-artifact failure path.
1960
- expect(process.exitCode).toBe(1);
1961
- expect(SqliteActivationStateStore).not.toHaveBeenCalled();
1962
- expect(ActivationDispatcher).not.toHaveBeenCalled();
1963
- });
1964
-
1965
- it('mutex failure (--dry-run + --confirm): sets exitCode=1 and does not construct RuntimeStateManager', async () => {
1966
- const { RuntimeStateManager } = await import('@principles/core/runtime-v2');
1967
- vi.mocked(RuntimeStateManager).mockClear();
1968
-
1969
- await handleRuntimeActivationDispatch({
1970
- workspace: WS,
1971
- artifactId: 'art-001',
1972
- channel: 'prompt',
1973
- dryRun: true,
1974
- confirm: true,
1975
- json: true,
1976
- });
1977
-
1978
- // cli-2: mutex failure must set exitCode and NOT construct state manager.
1979
- expect(process.exitCode).toBe(1);
1980
- expect(RuntimeStateManager).not.toHaveBeenCalled();
1981
- });
1982
- });
1983
-
1984
-
1985
- describe('handleRuntimeActivationDispatch — PRI-634-F R2 host provenance refusal', () => {
1986
- let consoleLogSpy: ReturnType<typeof vi.spyOn>;
1987
-
1988
- beforeEach(() => {
1989
- vi.clearAllMocks();
1990
- mockRuleHostWriterConfigs.length = 0;
1991
- mockGetArtifactById.mockResolvedValue(makeArtifact());
1992
- consoleLogSpy = vi.spyOn(console, 'log').mockImplementation(() => {});
1993
- });
1994
-
1995
- afterEach(() => {
1996
- consoleLogSpy.mockRestore();
1997
- process.exitCode = 0;
1998
- });
1999
-
2000
- it('refuses code_tool_hook activation when host provenance is unresolvable — structured reason + nextAction, no writer constructed (review P1)', async () => {
2001
- vi.mocked(resolveWorkspaceToolSemantics).mockReturnValueOnce({
2002
- ok: false,
2003
- reason: 'host_tool_declaration_missing',
2004
- nextAction: 'start the workspace host once so it persists its tool declaration',
2005
- });
2006
- await handleRuntimeActivationDispatch({
2007
- workspace: WS,
2008
- artifactId: 'art-001',
2009
- channel: 'code_tool_hook',
2010
- json: true,
2011
- });
2012
-
2013
- const output = JSON.parse(consoleLogSpy.mock.calls[0][0]);
2014
- expect(output.decision).toBe('refused');
2015
- expect(output.reason).toBe('host_tool_declaration_missing');
2016
- expect(output.nextAction).toContain('host');
2017
- // Fail-closed: the dispatcher (and its writers) must never run —
2018
- // cli-5-failure-no-mutation.
2019
- expect(mockRuleHostWriterConfigs).toHaveLength(0);
2020
- expect(process.exitCode).toBe(1);
2021
- });
2022
-
2023
- it('non-code_tool_hook channels are unaffected by unresolvable provenance', async () => {
2024
- vi.mocked(resolveWorkspaceToolSemantics).mockReturnValueOnce({
2025
- ok: false,
2026
- reason: 'host_tool_declaration_missing',
2027
- nextAction: 'start the workspace host once',
2028
- });
2029
- await handleRuntimeActivationDispatch({
2030
- workspace: WS,
2031
- artifactId: 'art-001',
2032
- channel: 'prompt',
2033
- json: true,
2034
- });
2035
- const output = JSON.parse(consoleLogSpy.mock.calls[0][0]);
2036
- expect(output.decision).not.toBe('refused');
2037
- });
2038
-
2039
- it('code_tool_hook dispatch threads the resolved registry into RuleHostWriter and gateDeps', async () => {
2040
- const registry = { version: 1, hasHostLayer: true, resolve: () => 'write', lookup: () => null, hasHostTool: () => true, hostMappings: () => [{ rawToolName: 'write', canonicalKind: 'write' as const }] };
2041
- vi.mocked(resolveWorkspaceToolSemantics).mockReturnValueOnce({ ok: true, registry, hostKind: 'openclaw' });
2042
- await handleRuntimeActivationDispatch({
2043
- workspace: WS,
2044
- artifactId: 'art-001',
2045
- channel: 'code_tool_hook',
2046
- json: true,
2047
- });
2048
- expect(mockRuleHostWriterConfigs).toHaveLength(1);
2049
- expect(mockRuleHostWriterConfigs[0]?.toolSemantics).toBe(registry);
2050
- expect(mockRuleHostWriterConfigs[0]?.gateDeps).toBeDefined();
2051
- });
2052
- });