@principles/pd-cli 1.133.0 → 1.135.0

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 (215) hide show
  1. package/dist/commands/__tests__/intent-flag-wiring.test.js +74 -3
  2. package/dist/commands/__tests__/intent-flag-wiring.test.js.map +1 -1
  3. package/dist/commands/__tests__/pain-retry-maxTokens-flag.test.d.ts +2 -0
  4. package/dist/commands/__tests__/pain-retry-maxTokens-flag.test.d.ts.map +1 -0
  5. package/dist/commands/__tests__/pain-retry-maxTokens-flag.test.js +60 -0
  6. package/dist/commands/__tests__/pain-retry-maxTokens-flag.test.js.map +1 -0
  7. package/dist/commands/__tests__/rulecode-flag-wiring.test.js +11 -4
  8. package/dist/commands/__tests__/rulecode-flag-wiring.test.js.map +1 -1
  9. package/dist/commands/__tests__/run-rulehost-flag-wiring.test.js +9 -0
  10. package/dist/commands/__tests__/run-rulehost-flag-wiring.test.js.map +1 -1
  11. package/dist/commands/admission-gate.d.ts +24 -0
  12. package/dist/commands/admission-gate.d.ts.map +1 -0
  13. package/dist/commands/admission-gate.js +29 -0
  14. package/dist/commands/admission-gate.js.map +1 -0
  15. package/dist/commands/candidate.d.ts.map +1 -1
  16. package/dist/commands/candidate.js +72 -6
  17. package/dist/commands/candidate.js.map +1 -1
  18. package/dist/commands/console.d.ts.map +1 -1
  19. package/dist/commands/console.js +42 -0
  20. package/dist/commands/console.js.map +1 -1
  21. package/dist/commands/demo-story-a.d.ts.map +1 -1
  22. package/dist/commands/demo-story-a.js +4 -2
  23. package/dist/commands/demo-story-a.js.map +1 -1
  24. package/dist/commands/diagnose.d.ts.map +1 -1
  25. package/dist/commands/diagnose.js +155 -8
  26. package/dist/commands/diagnose.js.map +1 -1
  27. package/dist/commands/errors-list.d.ts +25 -0
  28. package/dist/commands/errors-list.d.ts.map +1 -0
  29. package/dist/commands/errors-list.js +368 -0
  30. package/dist/commands/errors-list.js.map +1 -0
  31. package/dist/commands/health-codex.d.ts +7 -0
  32. package/dist/commands/health-codex.d.ts.map +1 -0
  33. package/dist/commands/health-codex.js +209 -0
  34. package/dist/commands/health-codex.js.map +1 -0
  35. package/dist/commands/health.d.ts +24 -0
  36. package/dist/commands/health.d.ts.map +1 -1
  37. package/dist/commands/health.js +48 -0
  38. package/dist/commands/health.js.map +1 -1
  39. package/dist/commands/intent.d.ts +21 -4
  40. package/dist/commands/intent.d.ts.map +1 -1
  41. package/dist/commands/intent.js +88 -27
  42. package/dist/commands/intent.js.map +1 -1
  43. package/dist/commands/pain-evidence.d.ts +6 -0
  44. package/dist/commands/pain-evidence.d.ts.map +1 -1
  45. package/dist/commands/pain-evidence.js +6 -0
  46. package/dist/commands/pain-evidence.js.map +1 -1
  47. package/dist/commands/pain-record.d.ts.map +1 -1
  48. package/dist/commands/pain-record.js +21 -0
  49. package/dist/commands/pain-record.js.map +1 -1
  50. package/dist/commands/pain-retry.d.ts +4 -0
  51. package/dist/commands/pain-retry.d.ts.map +1 -1
  52. package/dist/commands/pain-retry.js +327 -32
  53. package/dist/commands/pain-retry.js.map +1 -1
  54. package/dist/commands/proven-channel-baseline.d.ts.map +1 -1
  55. package/dist/commands/proven-channel-baseline.js +4 -2
  56. package/dist/commands/proven-channel-baseline.js.map +1 -1
  57. package/dist/commands/runtime-activation.d.ts +30 -0
  58. package/dist/commands/runtime-activation.d.ts.map +1 -1
  59. package/dist/commands/runtime-activation.js +567 -11
  60. package/dist/commands/runtime-activation.js.map +1 -1
  61. package/dist/commands/runtime-canary.d.ts.map +1 -1
  62. package/dist/commands/runtime-canary.js +32 -7
  63. package/dist/commands/runtime-canary.js.map +1 -1
  64. package/dist/commands/runtime-health-snapshot.d.ts.map +1 -1
  65. package/dist/commands/runtime-health-snapshot.js +4 -2
  66. package/dist/commands/runtime-health-snapshot.js.map +1 -1
  67. package/dist/commands/runtime-init.d.ts +43 -0
  68. package/dist/commands/runtime-init.d.ts.map +1 -0
  69. package/dist/commands/runtime-init.js +264 -0
  70. package/dist/commands/runtime-init.js.map +1 -0
  71. package/dist/commands/runtime-internalization-context-trace.d.ts +25 -0
  72. package/dist/commands/runtime-internalization-context-trace.d.ts.map +1 -0
  73. package/dist/commands/runtime-internalization-context-trace.js +374 -0
  74. package/dist/commands/runtime-internalization-context-trace.js.map +1 -0
  75. package/dist/commands/runtime-internalization-enqueue-successors.d.ts.map +1 -1
  76. package/dist/commands/runtime-internalization-enqueue-successors.js +3 -1
  77. package/dist/commands/runtime-internalization-enqueue-successors.js.map +1 -1
  78. package/dist/commands/runtime-internalization-integrity.d.ts.map +1 -1
  79. package/dist/commands/runtime-internalization-integrity.js +4 -2
  80. package/dist/commands/runtime-internalization-integrity.js.map +1 -1
  81. package/dist/commands/runtime-internalization-run-once.d.ts.map +1 -1
  82. package/dist/commands/runtime-internalization-run-once.js +20 -5
  83. package/dist/commands/runtime-internalization-run-once.js.map +1 -1
  84. package/dist/commands/runtime-internalization-run-rulehost.d.ts +1 -0
  85. package/dist/commands/runtime-internalization-run-rulehost.d.ts.map +1 -1
  86. package/dist/commands/runtime-internalization-run-rulehost.js +149 -6
  87. package/dist/commands/runtime-internalization-run-rulehost.js.map +1 -1
  88. package/dist/commands/runtime-uat.d.ts.map +1 -1
  89. package/dist/commands/runtime-uat.guard.test.js +13 -15
  90. package/dist/commands/runtime-uat.guard.test.js.map +1 -1
  91. package/dist/commands/runtime-uat.js +4 -3
  92. package/dist/commands/runtime-uat.js.map +1 -1
  93. package/dist/config-reader.js +1 -1
  94. package/dist/config-reader.js.map +1 -1
  95. package/dist/index.js +54 -78
  96. package/dist/index.js.map +1 -1
  97. package/dist/services/__tests__/evaluator-runner-deps.test.d.ts +2 -0
  98. package/dist/services/__tests__/evaluator-runner-deps.test.d.ts.map +1 -0
  99. package/dist/services/__tests__/evaluator-runner-deps.test.js +304 -0
  100. package/dist/services/__tests__/evaluator-runner-deps.test.js.map +1 -0
  101. package/dist/services/__tests__/rulehost-readiness.test.js.map +1 -1
  102. package/dist/services/__tests__/runtime-adapter-resolver.test.js.map +1 -1
  103. package/dist/services/config-doctor.d.ts.map +1 -1
  104. package/dist/services/config-doctor.js +9 -2
  105. package/dist/services/config-doctor.js.map +1 -1
  106. package/dist/services/console-launcher.d.ts +6 -0
  107. package/dist/services/console-launcher.d.ts.map +1 -1
  108. package/dist/services/console-launcher.js.map +1 -1
  109. package/dist/services/pain-flood-simulation-runner.d.ts.map +1 -1
  110. package/dist/services/pain-flood-simulation-runner.js +9 -0
  111. package/dist/services/pain-flood-simulation-runner.js.map +1 -1
  112. package/dist/services/pd-config-loader.js +2 -2
  113. package/dist/services/pd-config-loader.js.map +1 -1
  114. package/dist/services/proven-channel-baseline-runner.d.ts.map +1 -1
  115. package/dist/services/proven-channel-baseline-runner.js +10 -2
  116. package/dist/services/proven-channel-baseline-runner.js.map +1 -1
  117. package/dist/services/quality-scorecard/data-extractor.js.map +1 -1
  118. package/dist/services/resolve-runtime-from-pd-config.js.map +1 -1
  119. package/dist/services/rulehost-pipeline-runner.d.ts +77 -1
  120. package/dist/services/rulehost-pipeline-runner.d.ts.map +1 -1
  121. package/dist/services/rulehost-pipeline-runner.js +111 -7
  122. package/dist/services/rulehost-pipeline-runner.js.map +1 -1
  123. package/dist/services/rulehost-readiness.js.map +1 -1
  124. package/dist/services/runtime-adapter-resolver.d.ts +1 -0
  125. package/dist/services/runtime-adapter-resolver.d.ts.map +1 -1
  126. package/dist/services/runtime-adapter-resolver.js +3 -0
  127. package/dist/services/runtime-adapter-resolver.js.map +1 -1
  128. package/dist/services/synthetic-baseline-runner.d.ts.map +1 -1
  129. package/dist/services/synthetic-baseline-runner.js +11 -0
  130. package/dist/services/synthetic-baseline-runner.js.map +1 -1
  131. package/dist/utils/production-workspace-guard.d.ts +4 -4
  132. package/dist/utils/production-workspace-guard.d.ts.map +1 -1
  133. package/dist/utils/production-workspace-guard.js +19 -16
  134. package/dist/utils/production-workspace-guard.js.map +1 -1
  135. package/dist/utils/production-workspace-guard.test.js +54 -19
  136. package/dist/utils/production-workspace-guard.test.js.map +1 -1
  137. package/package.json +8 -5
  138. package/src/commands/__tests__/intent-flag-wiring.test.ts +88 -3
  139. package/src/commands/__tests__/pain-retry-maxTokens-flag.test.ts +73 -0
  140. package/src/commands/__tests__/rulecode-flag-wiring.test.ts +31 -24
  141. package/src/commands/__tests__/run-rulehost-flag-wiring.test.ts +12 -0
  142. package/src/commands/admission-gate.ts +30 -0
  143. package/src/commands/candidate.ts +74 -6
  144. package/src/commands/console.ts +41 -0
  145. package/src/commands/demo-story-a.ts +4 -2
  146. package/src/commands/diagnose.ts +158 -10
  147. package/src/commands/errors-list.ts +440 -0
  148. package/src/commands/health-codex.ts +249 -0
  149. package/src/commands/health.ts +60 -0
  150. package/src/commands/intent.ts +98 -29
  151. package/src/commands/pain-evidence.ts +6 -0
  152. package/src/commands/pain-record.ts +21 -0
  153. package/src/commands/pain-retry.ts +353 -35
  154. package/src/commands/proven-channel-baseline.ts +4 -2
  155. package/src/commands/runtime-activation.ts +657 -12
  156. package/src/commands/runtime-canary.ts +31 -5
  157. package/src/commands/runtime-health-snapshot.ts +4 -2
  158. package/src/commands/runtime-init.ts +305 -0
  159. package/src/commands/runtime-internalization-context-trace.ts +445 -0
  160. package/src/commands/runtime-internalization-enqueue-successors.ts +3 -1
  161. package/src/commands/runtime-internalization-integrity.ts +4 -2
  162. package/src/commands/runtime-internalization-run-once.ts +20 -5
  163. package/src/commands/runtime-internalization-run-rulehost.ts +159 -6
  164. package/src/commands/runtime-uat.guard.test.ts +14 -16
  165. package/src/commands/runtime-uat.ts +4 -3
  166. package/src/config-reader.ts +1 -1
  167. package/src/index.ts +69 -78
  168. package/src/services/__tests__/evaluator-runner-deps.test.ts +341 -0
  169. package/src/services/config-doctor.ts +9 -2
  170. package/src/services/console-launcher.ts +6 -0
  171. package/src/services/pain-flood-simulation-runner.ts +9 -0
  172. package/src/services/pd-config-loader.ts +2 -2
  173. package/src/services/proven-channel-baseline-runner.ts +10 -3
  174. package/src/services/rulehost-pipeline-runner.ts +157 -6
  175. package/src/services/runtime-adapter-resolver.ts +4 -0
  176. package/src/services/synthetic-baseline-runner.ts +11 -0
  177. package/src/utils/production-workspace-guard.test.ts +62 -20
  178. package/src/utils/production-workspace-guard.ts +19 -16
  179. package/tests/bdd/cli-contract.steps.ts +343 -0
  180. package/tests/bdd/context-trace.steps.ts +229 -0
  181. package/tests/bdd/support/gherkin-loader.ts +147 -0
  182. package/tests/bdd/support/repo-root.ts +62 -0
  183. package/tests/bdd/support/vitest-bdd.ts +179 -0
  184. package/tests/commands/admission-gate-coverage.test.ts +79 -0
  185. package/tests/commands/candidate-audit-repair.test.ts +77 -0
  186. package/tests/commands/candidate-intake.test.ts +155 -10
  187. package/tests/commands/candidate-internalization-backfill.test.ts +30 -0
  188. package/tests/commands/cli-help-snapshot.test.ts +15 -1
  189. package/tests/commands/console-open.test.ts +229 -32
  190. package/tests/commands/diagnose.test.ts +619 -14
  191. package/tests/commands/errors-list.test.ts +678 -0
  192. package/tests/commands/health-codex.test.ts +243 -0
  193. package/tests/commands/health-host-wiring.test.ts +76 -0
  194. package/tests/commands/intent.test.ts +4 -4
  195. package/tests/commands/pain-record.test.ts +80 -0
  196. package/tests/commands/pain-retry.test.ts +94 -3
  197. package/tests/commands/run-rulehost-handler.test.ts +133 -0
  198. package/tests/commands/runtime-activation-approve-flag-wiring.test.ts +227 -0
  199. package/tests/commands/runtime-activation-deactivate-flag-wiring.test.ts +167 -0
  200. package/tests/commands/runtime-activation-dispatch-flag-wiring.test.ts +262 -0
  201. package/tests/commands/runtime-activation-list-flag-wiring.test.ts +193 -0
  202. package/tests/commands/runtime-activation-promote-flag-wiring.test.ts +222 -0
  203. package/tests/commands/runtime-activation.test.ts +1090 -5
  204. package/tests/commands/runtime-canary.test.ts +50 -0
  205. package/tests/commands/runtime-features.test.ts +2 -0
  206. package/tests/commands/runtime-init-empty-workspace.test.ts +234 -0
  207. package/tests/commands/runtime-init.test.ts +346 -0
  208. package/tests/commands/runtime-internalization-context-trace.test.ts +110 -0
  209. package/tests/commands/runtime-internalization.test.ts +2 -2
  210. package/tests/config-reader.test.ts +6 -5
  211. package/tests/e2e/cross-package-acceptance.test.ts +55 -13
  212. package/tests/services/mainline-snapshot-assembler.test.ts +6 -3
  213. package/tests/services/resolve-runtime-from-pd-config.test.ts +2 -0
  214. package/tests/services/rulehost-pipeline-runner.test.ts +1 -1
  215. package/vitest.config.ts +1 -1
@@ -1,14 +1,31 @@
1
1
  import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
2
2
 
3
+ const mockRuleHostWriterConfigs = vi.hoisted(() => [] as Array<{ featureFlagProbe?: (flagId: string) => boolean }>);
4
+ const mockFeatureFlags = vi.hoisted(() => ({
5
+ flags: { rulecode_context_v2: { id: 'rulecode_context_v2', category: 'quiet' as const, enabled: true, since: '2026-06-27', description: 'test' } },
6
+ }));
7
+
3
8
  const mockGetArtifactById = vi.fn();
4
9
  const mockClose = vi.fn().mockResolvedValue(undefined);
5
10
  const mockApprovalEdit = vi.fn();
6
11
  const mockApprovalGetById = vi.fn();
12
+ const mockApprovalApprove = vi.fn();
13
+ const mockApprovalResetToPending = vi.fn();
14
+ const mockCompletionComplete = vi.fn();
15
+ const mockPromoteActivation = vi.fn().mockResolvedValue(true);
16
+ const mockListCodeToolHookActivations = vi.fn().mockResolvedValue([
17
+ { 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 },
18
+ ]);
7
19
 
8
20
  vi.mock('../../src/resolve-workspace.js', () => ({
9
21
  resolveWorkspaceDir: vi.fn().mockReturnValue('/fake/workspace'),
10
22
  }));
11
23
 
24
+ vi.mock('../../src/services/pd-config-loader.js', () => ({
25
+ loadPdConfig: vi.fn().mockReturnValue({ ok: true, effective: {} }),
26
+ computeFlagsFromLoadResult: vi.fn().mockReturnValue(mockFeatureFlags),
27
+ }));
28
+
12
29
  vi.mock('@principles/core/runtime-v2', async (importOriginal) => {
13
30
  const original = await importOriginal() as Record<string, unknown>;
14
31
  return {
@@ -38,9 +55,8 @@ vi.mock('@principles/core/runtime-v2', async (importOriginal) => {
38
55
  listPromptActivations: vi.fn().mockResolvedValue([
39
56
  { activationId: 'act-prompt-1', artifactId: 'art-001', channel: 'prompt', action: 'prompt', targetRef: 'P_001', activatedAt: '2026-06-18T00:00:00.000Z', deactivatedAt: null },
40
57
  ]),
41
- listCodeToolHookActivations: vi.fn().mockResolvedValue([
42
- { 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 },
43
- ]),
58
+ listCodeToolHookActivations: mockListCodeToolHookActivations,
59
+ promoteActivation: mockPromoteActivation,
44
60
  listAllActivations: vi.fn().mockResolvedValue([
45
61
  { activationId: 'act-prompt-1', artifactId: 'art-001', channel: 'prompt', action: 'prompt', targetRef: 'P_001', activatedAt: '2026-06-18T00:00:00.000Z', deactivatedAt: null },
46
62
  { 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 },
@@ -66,17 +82,27 @@ vi.mock('@principles/core/runtime-v2', async (importOriginal) => {
66
82
  return { decision: 'activated', activationId: 'act-001', action: 'prompt', targetRef: 'P_001' };
67
83
  }
68
84
  if (args.channel === 'code_tool_hook') {
69
- return { decision: 'refused', activationId: 'act-001', action: 'none', targetRef: 'P_001', reason: 'activation_state_read_failed', riskLevel: 'high', channel: 'code_tool_hook' };
85
+ 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' };
70
86
  }
71
87
  return { decision: 'would_activate', activationId: 'act-001', action: 'prompt', targetRef: 'P_001' };
72
88
  }),
73
89
  };
74
90
  }),
91
+ ApprovalQueue: vi.fn().mockImplementation(function () {
92
+ return { approve: mockApprovalApprove, resetToPending: mockApprovalResetToPending };
93
+ }),
94
+ ApprovalCompletionService: vi.fn().mockImplementation(function () {
95
+ return { completeApproval: mockCompletionComplete };
96
+ }),
97
+ RuleHostWriter: vi.fn().mockImplementation(function (config) {
98
+ mockRuleHostWriterConfigs.push(config);
99
+ return { channel: 'code_tool_hook' };
100
+ }),
75
101
  resolveOutputLanguage: vi.fn().mockReturnValue({ outputLanguage: 'zh-CN' }),
76
102
  };
77
103
  });
78
104
 
79
- import { handleRuntimeActivationDispatch, handleRuntimeActivationDeactivate, handleRuntimeActivationList, handleRuntimeActivationEdit } from '../../src/commands/runtime-activation.js';
105
+ import { handleRuntimeActivationDispatch, handleRuntimeActivationDeactivate, handleRuntimeActivationList, handleRuntimeActivationEdit, handleActivationApprove, handleRuntimeActivationPromote, registerRuntimeActivationDispatchCommand, registerRuntimeActivationDeactivateCommand, registerRuntimeActivationPromoteCommand, registerRuntimeActivationListCommand } from '../../src/commands/runtime-activation.js';
80
106
 
81
107
  const WS = '/fake/workspace';
82
108
 
@@ -101,11 +127,24 @@ describe('handleRuntimeActivationDispatch', () => {
101
127
 
102
128
  beforeEach(() => {
103
129
  vi.clearAllMocks();
130
+ mockRuleHostWriterConfigs.length = 0;
104
131
  consoleLogSpy = vi.spyOn(console, 'log').mockImplementation(() => {});
105
132
  consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
106
133
  mockGetArtifactById.mockResolvedValue(makeArtifact());
107
134
  });
108
135
 
136
+ it('wires the effective workspace feature flags into RuleHostWriter', async () => {
137
+ await handleRuntimeActivationDispatch({
138
+ workspace: WS,
139
+ artifactId: 'art-001',
140
+ channel: 'code_tool_hook',
141
+ json: true,
142
+ });
143
+
144
+ expect(mockRuleHostWriterConfigs).toHaveLength(1);
145
+ expect(mockRuleHostWriterConfigs[0]?.featureFlagProbe?.('rulecode_context_v2')).toBe(true);
146
+ });
147
+
109
148
  afterEach(() => {
110
149
  consoleLogSpy.mockRestore();
111
150
  consoleErrorSpy.mockRestore();
@@ -218,6 +257,50 @@ describe('handleRuntimeActivationDispatch', () => {
218
257
  expect(text).toContain('Activation:');
219
258
  expect(text).toContain('would_activate');
220
259
  });
260
+
261
+ // PRI-493 cli-5 no-mutation: missing-artifact failure path must not construct
262
+ // the activation state store or dispatcher. Production code returns before
263
+ // instantiating either (runtime-activation.ts lines 148-157). ERR-088
264
+ // positive path marker: assert the constructors were never invoked, not just
265
+ // that the output shape is invalid_artifact.
266
+ it('missing-artifact failure path does not construct SqliteActivationStateStore or ActivationDispatcher', async () => {
267
+ mockGetArtifactById.mockResolvedValue(null);
268
+ const { SqliteActivationStateStore, ActivationDispatcher } = await import('@principles/core/runtime-v2');
269
+
270
+ vi.mocked(SqliteActivationStateStore).mockClear();
271
+ vi.mocked(ActivationDispatcher).mockClear();
272
+
273
+ await handleRuntimeActivationDispatch({
274
+ workspace: WS,
275
+ artifactId: 'nonexistent',
276
+ channel: 'prompt',
277
+ json: true,
278
+ });
279
+
280
+ expect(SqliteActivationStateStore).not.toHaveBeenCalled();
281
+ expect(ActivationDispatcher).not.toHaveBeenCalled();
282
+ expect(process.exitCode).toBe(1);
283
+ });
284
+
285
+ // PRI-493 cli-5 no-mutation: --dry-run/--confirm mutex failure must not open
286
+ // any DB-backed store. Production code exits before stateManager.initialize()
287
+ // (runtime-activation.ts lines 127-131). ERR-088 positive marker.
288
+ it('mutex failure path (--dry-run + --confirm) does not construct RuntimeStateManager', async () => {
289
+ const { RuntimeStateManager } = await import('@principles/core/runtime-v2');
290
+ vi.mocked(RuntimeStateManager).mockClear();
291
+
292
+ await handleRuntimeActivationDispatch({
293
+ workspace: WS,
294
+ artifactId: 'art-001',
295
+ channel: 'prompt',
296
+ dryRun: true,
297
+ confirm: true,
298
+ json: true,
299
+ });
300
+
301
+ expect(RuntimeStateManager).not.toHaveBeenCalled();
302
+ expect(process.exitCode).toBe(1);
303
+ });
221
304
  });
222
305
 
223
306
  // PRI-408 Contract E: Deactivate (rollback) command tests
@@ -311,6 +394,38 @@ describe('handleRuntimeActivationDeactivate', () => {
311
394
  expect(text).toContain('Deactivated: act-001');
312
395
  expect(text).toContain('deactivatedAt:');
313
396
  });
397
+
398
+ // PRI-493 cli-5 no-mutation: not-found failure path must not call insert on
399
+ // the activation state store. Production code (runtime-activation.ts
400
+ // lines 253-267) calls deactivateActivation which returns false; no other
401
+ // mutating method should be invoked. ERR-088 positive path marker: capture
402
+ // the store instance and assert insert was never called.
403
+ it('not-found failure path does not call insert on the activation store', async () => {
404
+ const { SqliteActivationStateStore } = await import('@principles/core/runtime-v2');
405
+ const capturedInsert = vi.fn().mockResolvedValue(undefined);
406
+ const capturedDeactivate = vi.fn().mockResolvedValue(false);
407
+ vi.mocked(SqliteActivationStateStore).mockImplementationOnce(function () {
408
+ return {
409
+ findByArtifactId: vi.fn().mockResolvedValue(null),
410
+ insert: capturedInsert,
411
+ deactivateActivation: capturedDeactivate,
412
+ listPromptActivations: vi.fn().mockResolvedValue([]),
413
+ listCodeToolHookActivations: vi.fn().mockResolvedValue([]),
414
+ listAllActivations: vi.fn().mockResolvedValue([]),
415
+ } as never;
416
+ });
417
+
418
+ await handleRuntimeActivationDeactivate({
419
+ workspace: WS,
420
+ activationId: 'act-gone',
421
+ json: true,
422
+ });
423
+
424
+ expect(capturedDeactivate).toHaveBeenCalledTimes(1);
425
+ expect(capturedDeactivate).toHaveBeenCalledWith('act-gone', expect.any(String));
426
+ expect(capturedInsert).not.toHaveBeenCalled();
427
+ expect(process.exitCode).toBe(1);
428
+ });
314
429
  });
315
430
 
316
431
  // PRI-408 Contract D: List activations (observability) command tests
@@ -320,6 +435,9 @@ describe('handleRuntimeActivationList', () => {
320
435
 
321
436
  beforeEach(() => {
322
437
  vi.clearAllMocks();
438
+ // F9-1: by default, all artifact_ids are considered valid (exist in pi_artifacts).
439
+ // Individual tests override this to simulate dangling references.
440
+ mockGetArtifactById.mockResolvedValue(makeArtifact());
323
441
  consoleLogSpy = vi.spyOn(console, 'log').mockImplementation(() => {});
324
442
  consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
325
443
  });
@@ -341,6 +459,9 @@ describe('handleRuntimeActivationList', () => {
341
459
  expect(output.activations.length).toBe(2);
342
460
  expect(output.activations[0]).toHaveProperty('activationId');
343
461
  expect(output.activations[0]).toHaveProperty('channel');
462
+ // PRI-500: CLI list output must include principleId (matching Console field).
463
+ expect(output.activations[0]).toHaveProperty('principleId');
464
+ expect(output.status).toBe('ok');
344
465
  });
345
466
 
346
467
  it('channel=prompt filter calls listPromptActivations', async () => {
@@ -403,6 +524,425 @@ describe('handleRuntimeActivationList', () => {
403
524
  expect(errorText).toContain('Next action');
404
525
  expect(process.exitCode).toBe(1);
405
526
  });
527
+
528
+ // F9-1 regression: dangling artifact_id must produce degraded status + warning
529
+ it('F9-1: emits degraded status + warning when activation references non-existent artifact_id (JSON)', async () => {
530
+ // art-001 exists, art-002 does NOT (dangling)
531
+ mockGetArtifactById.mockImplementation((artifactId: string) => {
532
+ if (artifactId === 'art-001') return Promise.resolve(makeArtifact({ artifactId: 'art-001' }));
533
+ return Promise.resolve(null);
534
+ });
535
+
536
+ await handleRuntimeActivationList({
537
+ workspace: WS,
538
+ json: true,
539
+ });
540
+
541
+ const output = JSON.parse(consoleLogSpy.mock.calls[0][0]);
542
+ expect(output.status).toBe('degraded');
543
+ expect(output.reason).toContain('non-existent artifact_id');
544
+ expect(output.reason).toContain('art-002');
545
+ expect(output.nextAction).toContain('pd runtime internalization integrity');
546
+ // The dangling activation should have a per-record warning
547
+ const danglingAct = output.activations.find((a: { artifactId: string }) => a.artifactId === 'art-002');
548
+ expect(danglingAct.warning).toContain('does not exist in pi_artifacts');
549
+ // The valid activation should NOT have a warning
550
+ const validAct = output.activations.find((a: { artifactId: string }) => a.artifactId === 'art-001');
551
+ expect(validAct.warning).toBeUndefined();
552
+ });
553
+
554
+ it('F9-1: text output prints WARNING line for dangling artifact_id', async () => {
555
+ mockGetArtifactById.mockImplementation((artifactId: string) => {
556
+ if (artifactId === 'art-001') return Promise.resolve(makeArtifact({ artifactId: 'art-001' }));
557
+ return Promise.resolve(null);
558
+ });
559
+
560
+ await handleRuntimeActivationList({
561
+ workspace: WS,
562
+ });
563
+
564
+ const text = consoleLogSpy.mock.calls.map(c => c[0]).join('\n');
565
+ expect(text).toContain('WARNING');
566
+ expect(text).toContain('art-002');
567
+ const errorText = consoleErrorSpy.mock.calls.map(c => c[0]).join('\n');
568
+ expect(errorText).toContain('non-existent artifact_id');
569
+ expect(errorText).toContain('Next action');
570
+ });
571
+
572
+ it('F9-1: treats getArtifactById throw as dangling (fail loud, rc-9)', async () => {
573
+ mockGetArtifactById.mockRejectedValue(new Error('DB corruption'));
574
+
575
+ await handleRuntimeActivationList({
576
+ workspace: WS,
577
+ json: true,
578
+ });
579
+
580
+ const output = JSON.parse(consoleLogSpy.mock.calls[0][0]);
581
+ expect(output.status).toBe('degraded');
582
+ expect(output.reason).toContain('non-existent artifact_id');
583
+ });
584
+
585
+ it('F9-1: status is ok when all artifact_ids exist (negative case)', async () => {
586
+ mockGetArtifactById.mockResolvedValue(makeArtifact());
587
+
588
+ await handleRuntimeActivationList({
589
+ workspace: WS,
590
+ json: true,
591
+ });
592
+
593
+ const output = JSON.parse(consoleLogSpy.mock.calls[0][0]);
594
+ expect(output.status).toBe('ok');
595
+ expect(output.reason).toBeUndefined();
596
+ expect(output.nextAction).toBeUndefined();
597
+ });
598
+
599
+ // ── PRI-491: owner observability (mode / status / contextVersion / evidenceRefs) ──
600
+ //
601
+ // The CLI list command must surface enough information for the owner to
602
+ // answer "will this rule block now?" without opening SQLite or reading
603
+ // logs. The four essential signals are:
604
+ // 1. mode (shadow / live / undefined for unrecognized)
605
+ // 2. status (active / suspended_by_flag / deactivated)
606
+ // 3. contextVersion (v1 / v2) — needed to interpret suspended_by_flag
607
+ // 4. nextAction (promote / deactivate / enable flag)
608
+ //
609
+ // ERR entries:
610
+ // - ERR-002: suspended_by_flag is a degradation; it MUST carry a reason
611
+ // via nextAction (rc-9-no-silent-fallback).
612
+ // - ERR-088: tests must assert the unique status field, not only absence
613
+ // of "active".
614
+ // - ERR-023/033: --json output must remain a single parseable object.
615
+
616
+ it('PRI-491: shadow v2 activation with flag off shows status=suspended_by_flag (JSON)', async () => {
617
+ // Override the artifact to a v2 artifact with evidenceRefs.
618
+ mockGetArtifactById.mockResolvedValue(makeArtifact({
619
+ artifactId: 'art-v2-shadow',
620
+ contentJson: JSON.stringify({
621
+ requiresContextVersion: 2,
622
+ evidenceRefs: ['ex-1', 'ex-2'],
623
+ implementationCode: 'return { decision: "allow" };',
624
+ }),
625
+ }));
626
+ // Override listCodeToolHookActivations to return a v2 shadow activation.
627
+ mockListCodeToolHookActivations.mockResolvedValue([
628
+ {
629
+ activationId: 'act-v2-shadow',
630
+ artifactId: 'art-v2-shadow',
631
+ channel: 'code_tool_hook',
632
+ action: 'code_tool_hook_shadow_activate',
633
+ targetRef: 'edit_tool',
634
+ activatedAt: '2026-06-18T00:00:00.000Z',
635
+ promotedAt: null,
636
+ deactivatedAt: null,
637
+ },
638
+ ]);
639
+ // Default mockFeatureFlags has rulecode_context_v2 enabled. Flip it off
640
+ // to simulate the production default (the flag is quiet/default-off).
641
+ mockFeatureFlags.flags.rulecode_context_v2.enabled = false;
642
+
643
+ await handleRuntimeActivationList({
644
+ workspace: WS,
645
+ channel: 'code_tool_hook',
646
+ json: true,
647
+ });
648
+
649
+ const output = JSON.parse(consoleLogSpy.mock.calls[0][0]);
650
+ expect(output.activations).toHaveLength(1);
651
+ const rec = output.activations[0];
652
+ expect(rec.status).toBe('suspended_by_flag');
653
+ expect(rec.mode).toBe('shadow');
654
+ expect(rec.contextVersion).toBe('v2');
655
+ expect(rec.evidenceRefs).toEqual(['ex-1', 'ex-2']);
656
+ expect(rec.evidenceSummary).toContain('2 evidence ref(s)');
657
+ expect(rec.nextAction).toContain('Enable rulecode_context_v2 flag');
658
+ expect(rec.nextAction).toContain('pd activation deactivate --activation-id act-v2-shadow --confirm');
659
+
660
+ // Restore the mock for subsequent tests.
661
+ mockFeatureFlags.flags.rulecode_context_v2.enabled = true;
662
+ });
663
+
664
+ it('PRI-491: text output shows [SUSPENDED by flag] for v2 flag-off activation', async () => {
665
+ mockGetArtifactById.mockResolvedValue(makeArtifact({
666
+ artifactId: 'art-v2-shadow',
667
+ contentJson: JSON.stringify({
668
+ requiresContextVersion: 2,
669
+ evidenceRefs: ['ex-1'],
670
+ implementationCode: 'return { decision: "allow" };',
671
+ }),
672
+ }));
673
+ mockListCodeToolHookActivations.mockResolvedValue([
674
+ {
675
+ activationId: 'act-v2-shadow',
676
+ artifactId: 'art-v2-shadow',
677
+ channel: 'code_tool_hook',
678
+ action: 'code_tool_hook_shadow_activate',
679
+ targetRef: 'edit_tool',
680
+ activatedAt: '2026-06-18T00:00:00.000Z',
681
+ promotedAt: null,
682
+ deactivatedAt: null,
683
+ },
684
+ ]);
685
+ mockFeatureFlags.flags.rulecode_context_v2.enabled = false;
686
+
687
+ await handleRuntimeActivationList({
688
+ workspace: WS,
689
+ channel: 'code_tool_hook',
690
+ });
691
+
692
+ const text = consoleLogSpy.mock.calls.map(c => c[0]).join('\n');
693
+ expect(text).toContain('[SUSPENDED by flag]');
694
+ expect(text).toContain('(shadow)');
695
+ expect(text).toContain('contextVersion: v2');
696
+ expect(text).toContain('evidence:');
697
+ expect(text).toContain('nextAction:');
698
+
699
+ mockFeatureFlags.flags.rulecode_context_v2.enabled = true;
700
+ });
701
+
702
+ it('PRI-491: shadow v1 activation shows status=active and promote nextAction (JSON)', async () => {
703
+ mockGetArtifactById.mockResolvedValue(makeArtifact({
704
+ artifactId: 'art-v1-shadow',
705
+ contentJson: JSON.stringify({ implementationCode: 'return { decision: "allow" };' }),
706
+ }));
707
+ mockListCodeToolHookActivations.mockResolvedValue([
708
+ {
709
+ activationId: 'act-v1-shadow',
710
+ artifactId: 'art-v1-shadow',
711
+ channel: 'code_tool_hook',
712
+ action: 'code_tool_hook_shadow_activate',
713
+ targetRef: 'edit_tool',
714
+ activatedAt: '2026-06-18T00:00:00.000Z',
715
+ promotedAt: null,
716
+ deactivatedAt: null,
717
+ },
718
+ ]);
719
+
720
+ await handleRuntimeActivationList({
721
+ workspace: WS,
722
+ channel: 'code_tool_hook',
723
+ json: true,
724
+ });
725
+
726
+ const output = JSON.parse(consoleLogSpy.mock.calls[0][0]);
727
+ const rec = output.activations[0];
728
+ expect(rec.status).toBe('active');
729
+ expect(rec.mode).toBe('shadow');
730
+ expect(rec.contextVersion).toBe('v1');
731
+ expect(rec.evidenceRefs).toBeUndefined();
732
+ expect(rec.nextAction).toBe('pd activation promote --activation-id act-v1-shadow --confirm');
733
+ });
734
+
735
+ it('PRI-491: live v1 activation shows status=active and deactivate nextAction (JSON)', async () => {
736
+ mockGetArtifactById.mockResolvedValue(makeArtifact({
737
+ artifactId: 'art-v1-live',
738
+ contentJson: JSON.stringify({ implementationCode: 'return { decision: "allow" };' }),
739
+ }));
740
+ mockListCodeToolHookActivations.mockResolvedValue([
741
+ {
742
+ activationId: 'act-v1-live',
743
+ artifactId: 'art-v1-live',
744
+ channel: 'code_tool_hook',
745
+ action: 'code_tool_hook_live_activate',
746
+ targetRef: 'edit_tool',
747
+ activatedAt: '2026-06-18T00:00:00.000Z',
748
+ promotedAt: '2026-06-19T00:00:00.000Z',
749
+ deactivatedAt: null,
750
+ },
751
+ ]);
752
+
753
+ await handleRuntimeActivationList({
754
+ workspace: WS,
755
+ channel: 'code_tool_hook',
756
+ json: true,
757
+ });
758
+
759
+ const output = JSON.parse(consoleLogSpy.mock.calls[0][0]);
760
+ const rec = output.activations[0];
761
+ expect(rec.status).toBe('active');
762
+ expect(rec.mode).toBe('live');
763
+ expect(rec.promotedAt).toBe('2026-06-19T00:00:00.000Z');
764
+ expect(rec.nextAction).toBe('pd activation deactivate --activation-id act-v1-live --confirm');
765
+ });
766
+
767
+ it('PRI-491: text output shows promotedAt timestamp when present', async () => {
768
+ mockGetArtifactById.mockResolvedValue(makeArtifact({
769
+ artifactId: 'art-v1-live',
770
+ contentJson: JSON.stringify({ implementationCode: 'return { decision: "allow" };' }),
771
+ }));
772
+ mockListCodeToolHookActivations.mockResolvedValue([
773
+ {
774
+ activationId: 'act-v1-live',
775
+ artifactId: 'art-v1-live',
776
+ channel: 'code_tool_hook',
777
+ action: 'code_tool_hook_live_activate',
778
+ targetRef: 'edit_tool',
779
+ activatedAt: '2026-06-18T00:00:00.000Z',
780
+ promotedAt: '2026-06-19T00:00:00.000Z',
781
+ deactivatedAt: null,
782
+ },
783
+ ]);
784
+
785
+ await handleRuntimeActivationList({
786
+ workspace: WS,
787
+ channel: 'code_tool_hook',
788
+ });
789
+
790
+ const text = consoleLogSpy.mock.calls.map(c => c[0]).join('\n');
791
+ expect(text).toContain('(live)');
792
+ expect(text).toContain('promotedAt: 2026-06-19T00:00:00.000Z');
793
+ expect(text).toContain('nextAction: pd activation deactivate --activation-id act-v1-live --confirm');
794
+ });
795
+
796
+ it('PRI-491: deactivated activation shows [DEACTIVATED <ts>] regardless of contextVersion (precedence)', async () => {
797
+ mockGetArtifactById.mockResolvedValue(makeArtifact({
798
+ artifactId: 'art-v2-dead',
799
+ contentJson: JSON.stringify({
800
+ requiresContextVersion: 2,
801
+ evidenceRefs: ['ex-1'],
802
+ implementationCode: 'return { decision: "allow" };',
803
+ }),
804
+ }));
805
+ mockListCodeToolHookActivations.mockResolvedValue([
806
+ {
807
+ activationId: 'act-v2-dead',
808
+ artifactId: 'art-v2-dead',
809
+ channel: 'code_tool_hook',
810
+ action: 'code_tool_hook_live_activate',
811
+ targetRef: 'edit_tool',
812
+ activatedAt: '2026-06-18T00:00:00.000Z',
813
+ promotedAt: '2026-06-19T00:00:00.000Z',
814
+ deactivatedAt: '2026-06-20T00:00:00.000Z',
815
+ },
816
+ ]);
817
+ mockFeatureFlags.flags.rulecode_context_v2.enabled = false;
818
+
819
+ await handleRuntimeActivationList({
820
+ workspace: WS,
821
+ channel: 'code_tool_hook',
822
+ includeDeactivated: true,
823
+ json: true,
824
+ });
825
+
826
+ const output = JSON.parse(consoleLogSpy.mock.calls[0][0]);
827
+ const rec = output.activations[0];
828
+ // deactivated > suspended_by_flag > active — a deactivated record is NOT
829
+ // reported as suspended_by_flag even when v2 + flag-off.
830
+ expect(rec.status).toBe('deactivated');
831
+ expect(rec.deactivatedAt).toBe('2026-06-20T00:00:00.000Z');
832
+ expect(rec.nextAction).toBeUndefined();
833
+
834
+ mockFeatureFlags.flags.rulecode_context_v2.enabled = true;
835
+ });
836
+
837
+ it('PRI-491: unrecognized action yields undefined mode and undefined nextAction (no false label)', async () => {
838
+ mockGetArtifactById.mockResolvedValue(makeArtifact({
839
+ artifactId: 'art-unknown',
840
+ contentJson: JSON.stringify({ implementationCode: 'return { decision: "allow" };' }),
841
+ }));
842
+ mockListCodeToolHookActivations.mockResolvedValue([
843
+ {
844
+ activationId: 'act-unknown',
845
+ artifactId: 'art-unknown',
846
+ channel: 'code_tool_hook',
847
+ action: 'some_future_action',
848
+ targetRef: 'edit_tool',
849
+ activatedAt: '2026-06-18T00:00:00.000Z',
850
+ promotedAt: null,
851
+ deactivatedAt: null,
852
+ },
853
+ ]);
854
+
855
+ await handleRuntimeActivationList({
856
+ workspace: WS,
857
+ channel: 'code_tool_hook',
858
+ json: true,
859
+ });
860
+
861
+ const output = JSON.parse(consoleLogSpy.mock.calls[0][0]);
862
+ const rec = output.activations[0];
863
+ expect(rec.mode).toBeUndefined();
864
+ expect(rec.status).toBe('active');
865
+ // No false nextAction — the owner must inspect manually.
866
+ expect(rec.nextAction).toBeUndefined();
867
+ });
868
+
869
+ it('PRI-491: JSON output remains a single parseable object (cli-1-strict-json)', async () => {
870
+ // Even with rich enrichment fields, the --json contract requires exactly
871
+ // one parseable JSON object on stdout (no banners, no extra log lines).
872
+ mockGetArtifactById.mockResolvedValue(makeArtifact({
873
+ contentJson: JSON.stringify({
874
+ requiresContextVersion: 2,
875
+ evidenceRefs: ['ex-1'],
876
+ implementationCode: 'return { decision: "allow" };',
877
+ }),
878
+ }));
879
+ mockListCodeToolHookActivations.mockResolvedValue([
880
+ {
881
+ activationId: 'act-v2',
882
+ artifactId: 'art-001',
883
+ channel: 'code_tool_hook',
884
+ action: 'code_tool_hook_shadow_activate',
885
+ targetRef: 'edit_tool',
886
+ activatedAt: '2026-06-18T00:00:00.000Z',
887
+ promotedAt: null,
888
+ deactivatedAt: null,
889
+ },
890
+ ]);
891
+
892
+ await handleRuntimeActivationList({
893
+ workspace: WS,
894
+ channel: 'code_tool_hook',
895
+ json: true,
896
+ });
897
+
898
+ // Exactly one console.log call on stdout (the JSON payload).
899
+ expect(consoleLogSpy.mock.calls).toHaveLength(1);
900
+ // And it parses cleanly.
901
+ const output = JSON.parse(consoleLogSpy.mock.calls[0][0]);
902
+ expect(output).toHaveProperty('activations');
903
+ expect(output).toHaveProperty('status');
904
+ });
905
+ });
906
+
907
+ describe('handleRuntimeActivationPromote', () => {
908
+ let consoleLogSpy: ReturnType<typeof vi.spyOn>;
909
+ let consoleErrorSpy: ReturnType<typeof vi.spyOn>;
910
+
911
+ beforeEach(() => {
912
+ vi.clearAllMocks();
913
+ mockListCodeToolHookActivations.mockResolvedValue([
914
+ { 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 },
915
+ ]);
916
+ mockPromoteActivation.mockResolvedValue(true);
917
+ consoleLogSpy = vi.spyOn(console, 'log').mockImplementation(() => {});
918
+ consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
919
+ });
920
+
921
+ afterEach(() => {
922
+ consoleLogSpy.mockRestore();
923
+ consoleErrorSpy.mockRestore();
924
+ process.exitCode = 0;
925
+ });
926
+
927
+ it('defaults to dry-run and does not mutate activation state', async () => {
928
+ await handleRuntimeActivationPromote({ workspace: WS, activationId: 'act-hook-1', json: true });
929
+ const output = JSON.parse(consoleLogSpy.mock.calls[0][0]);
930
+ expect(output.decision).toBe('would_promote');
931
+ expect(mockPromoteActivation).not.toHaveBeenCalled();
932
+ });
933
+
934
+ it('promotes an eligible shadow activation when confirmed', async () => {
935
+ await handleRuntimeActivationPromote({ workspace: WS, activationId: 'act-hook-1', confirm: true, json: true });
936
+ const output = JSON.parse(consoleLogSpy.mock.calls[0][0]);
937
+ expect(output.decision).toBe('promoted');
938
+ expect(mockPromoteActivation).toHaveBeenCalledWith('act-hook-1', expect.any(String));
939
+ });
940
+
941
+ it('rejects mutually exclusive dry-run and confirm without mutation', async () => {
942
+ await handleRuntimeActivationPromote({ workspace: WS, activationId: 'act-hook-1', dryRun: true, confirm: true, json: true });
943
+ expect(mockPromoteActivation).not.toHaveBeenCalled();
944
+ expect(process.exitCode).toBe(1);
945
+ });
406
946
  });
407
947
 
408
948
  // P1 #2 fix: Edit pending approval command tests
@@ -751,3 +1291,548 @@ describe('handleRuntimeActivationEdit', () => {
751
1291
  });
752
1292
 
753
1293
  });
1294
+
1295
+ // Bug-M fix: Approve command tests (CLI closed loop)
1296
+ describe('handleActivationApprove', () => {
1297
+ let consoleLogSpy: ReturnType<typeof vi.spyOn>;
1298
+ let consoleErrorSpy: ReturnType<typeof vi.spyOn>;
1299
+
1300
+ beforeEach(() => {
1301
+ vi.clearAllMocks();
1302
+ mockRuleHostWriterConfigs.length = 0;
1303
+ consoleLogSpy = vi.spyOn(console, 'log').mockImplementation(() => {});
1304
+ consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
1305
+ mockGetArtifactById.mockResolvedValue(makeArtifact());
1306
+ mockApprovalResetToPending.mockResolvedValue({ ok: true });
1307
+ });
1308
+
1309
+ afterEach(() => {
1310
+ consoleLogSpy.mockRestore();
1311
+ consoleErrorSpy.mockRestore();
1312
+ process.exitCode = 0;
1313
+ });
1314
+
1315
+ it('AP-01: missing --approval-id returns structured error with nextAction (JSON)', async () => {
1316
+ await handleActivationApprove({
1317
+ workspace: WS,
1318
+ json: true,
1319
+ });
1320
+
1321
+ const output = JSON.parse(consoleLogSpy.mock.calls[0][0]);
1322
+ expect(output.ok).toBe(false);
1323
+ expect(output.reason).toBe('approval_id_required');
1324
+ expect(output.nextAction).toContain('--approval-id');
1325
+ expect(process.exitCode).toBe(1);
1326
+ });
1327
+
1328
+ it('AP-02: approval not_found returns structured error with nextAction (JSON)', async () => {
1329
+ mockApprovalApprove.mockResolvedValue({ ok: false, error: 'not_found' });
1330
+
1331
+ await handleActivationApprove({
1332
+ workspace: WS,
1333
+ approvalId: 'appr-nonexistent',
1334
+ json: true,
1335
+ });
1336
+
1337
+ const output = JSON.parse(consoleLogSpy.mock.calls[0][0]);
1338
+ expect(output.ok).toBe(false);
1339
+ expect(output.reason).toBe('approval_not_found');
1340
+ expect(output.nextAction).toContain('Check the approval ID');
1341
+ expect(process.exitCode).toBe(1);
1342
+ });
1343
+
1344
+ it('AP-03: already_decided returns structured error with status (JSON)', async () => {
1345
+ mockApprovalApprove.mockResolvedValue({ ok: false, error: 'already_decided', status: 'rejected' });
1346
+
1347
+ await handleActivationApprove({
1348
+ workspace: WS,
1349
+ approvalId: 'appr-001',
1350
+ json: true,
1351
+ });
1352
+
1353
+ const output = JSON.parse(consoleLogSpy.mock.calls[0][0]);
1354
+ expect(output.ok).toBe(false);
1355
+ expect(output.reason).toContain('already_decided');
1356
+ expect(output.reason).toContain('rejected');
1357
+ expect(output.nextAction).toContain('already decided');
1358
+ expect(process.exitCode).toBe(1);
1359
+ });
1360
+
1361
+ it('AP-04: success path returns ok=true with activationId and decision (JSON)', async () => {
1362
+ mockApprovalApprove.mockResolvedValue({
1363
+ ok: true,
1364
+ record: { approvalId: 'appr-001', artifactId: 'art-001', status: 'approved' },
1365
+ });
1366
+ mockCompletionComplete.mockResolvedValue({
1367
+ ok: true,
1368
+ activationId: 'act-001',
1369
+ decision: { decision: 'activated', activationId: 'act-001', action: 'prompt', targetRef: 'P_001' },
1370
+ });
1371
+
1372
+ await handleActivationApprove({
1373
+ workspace: WS,
1374
+ approvalId: 'appr-001',
1375
+ decidedBy: 'test-owner',
1376
+ json: true,
1377
+ });
1378
+
1379
+ const output = JSON.parse(consoleLogSpy.mock.calls[0][0]);
1380
+ expect(output.ok).toBe(true);
1381
+ expect(output.approvalId).toBe('appr-001');
1382
+ expect(output.activationId).toBe('act-001');
1383
+ expect(output.decision).toBe('activated');
1384
+ expect(output.nextAction).toBe('pd activation list');
1385
+ expect(process.exitCode).toBe(0);
1386
+ });
1387
+
1388
+ it('AP-05: --json output is a single parseable JSON object (cli-1-strict-json)', async () => {
1389
+ mockApprovalApprove.mockResolvedValue({
1390
+ ok: true,
1391
+ record: { approvalId: 'appr-001', artifactId: 'art-001', status: 'approved' },
1392
+ });
1393
+ mockCompletionComplete.mockResolvedValue({
1394
+ ok: true,
1395
+ activationId: 'act-001',
1396
+ decision: { decision: 'activated', activationId: 'act-001', action: 'prompt', targetRef: 'P_001' },
1397
+ });
1398
+
1399
+ await handleActivationApprove({
1400
+ workspace: WS,
1401
+ approvalId: 'appr-001',
1402
+ json: true,
1403
+ });
1404
+
1405
+ // Exactly one console.log call with a single JSON object
1406
+ expect(consoleLogSpy).toHaveBeenCalledTimes(1);
1407
+ const rawOutput = consoleLogSpy.mock.calls[0][0];
1408
+ const parsed = JSON.parse(rawOutput);
1409
+ expect(parsed).toBeInstanceOf(Object);
1410
+ expect(parsed.ok).toBe(true);
1411
+ });
1412
+
1413
+ it('AP-06: completeApproval !ok rolls back approval and returns structured error (JSON)', async () => {
1414
+ mockApprovalApprove.mockResolvedValue({
1415
+ ok: true,
1416
+ record: { approvalId: 'appr-001', artifactId: 'art-001', status: 'approved' },
1417
+ });
1418
+ mockCompletionComplete.mockResolvedValue({
1419
+ ok: false,
1420
+ reason: 'artifact_not_validated',
1421
+ nextAction: 'Check artifact validation status and retry dispatch.',
1422
+ });
1423
+
1424
+ await handleActivationApprove({
1425
+ workspace: WS,
1426
+ approvalId: 'appr-001',
1427
+ json: true,
1428
+ });
1429
+
1430
+ const output = JSON.parse(consoleLogSpy.mock.calls[0][0]);
1431
+ expect(output.ok).toBe(false);
1432
+ expect(output.reason).toContain('activation_failed');
1433
+ expect(output.reason).toContain('artifact_not_validated');
1434
+ expect(output.approvalRolledBack).toBe(true);
1435
+ expect(output.nextAction).toContain('rolled back to pending');
1436
+ expect(process.exitCode).toBe(1);
1437
+ // cli-5: rollback was attempted via resetToPending
1438
+ expect(mockApprovalResetToPending).toHaveBeenCalledWith('appr-001');
1439
+ });
1440
+
1441
+ it('AP-06b: completeApproval throw rolls back approval and returns structured error (JSON)', async () => {
1442
+ mockApprovalApprove.mockResolvedValue({
1443
+ ok: true,
1444
+ record: { approvalId: 'appr-001', artifactId: 'art-001', status: 'approved' },
1445
+ });
1446
+ mockCompletionComplete.mockRejectedValue(new Error('sqlite: disk I/O error'));
1447
+
1448
+ await handleActivationApprove({
1449
+ workspace: WS,
1450
+ approvalId: 'appr-001',
1451
+ json: true,
1452
+ });
1453
+
1454
+ const output = JSON.parse(consoleLogSpy.mock.calls[0][0]);
1455
+ expect(output.ok).toBe(false);
1456
+ expect(output.reason).toContain('activation_completion_failed');
1457
+ expect(output.reason).toContain('disk I/O error');
1458
+ expect(output.approvalRolledBack).toBe(true);
1459
+ expect(output.nextAction).toContain('rolled back to pending');
1460
+ expect(process.exitCode).toBe(1);
1461
+ expect(mockApprovalResetToPending).toHaveBeenCalledWith('appr-001');
1462
+ });
1463
+
1464
+ it('AP-06c: rollback failure surfaces approvalRolledBack=false with retry guidance (JSON)', async () => {
1465
+ mockApprovalApprove.mockResolvedValue({
1466
+ ok: true,
1467
+ record: { approvalId: 'appr-001', artifactId: 'art-001', status: 'approved' },
1468
+ });
1469
+ mockCompletionComplete.mockResolvedValue({
1470
+ ok: false,
1471
+ reason: 'artifact_not_validated',
1472
+ nextAction: 'Check artifact validation status and retry dispatch.',
1473
+ });
1474
+ mockApprovalResetToPending.mockResolvedValue({ ok: false, error: 'not_found' });
1475
+
1476
+ await handleActivationApprove({
1477
+ workspace: WS,
1478
+ approvalId: 'appr-001',
1479
+ json: true,
1480
+ });
1481
+
1482
+ const output = JSON.parse(consoleLogSpy.mock.calls[0][0]);
1483
+ expect(output.ok).toBe(false);
1484
+ expect(output.approvalRolledBack).toBe(false);
1485
+ expect(output.nextAction).toContain("remains 'approved'");
1486
+ expect(process.exitCode).toBe(1);
1487
+ });
1488
+
1489
+ it('AP-07: Commander flag wiring — --approval-id is required at parser level (cli-7-test-wiring)', async () => {
1490
+ // cli-7-test-wiring: exercise the real Commander parser path (not just the
1491
+ // handler) to verify `--approval-id` is registered as a required option.
1492
+ // Follows the project's established pattern in runtime-internalization-run-once.test.ts
1493
+ // (buildXxxCommand + program.exitOverride() + parseAsync).
1494
+ const { Command } = await import('commander');
1495
+ const program = new Command();
1496
+ program.exitOverride(); // surface Commander errors as throws instead of process.exit
1497
+
1498
+ const activationCmd = program.command('activation');
1499
+ activationCmd
1500
+ .command('approve')
1501
+ .description('Approve a pending approval and dispatch its activation')
1502
+ .requiredOption('-a, --approval-id <id>', 'Approval ID to approve')
1503
+ .option('--decided-by <user>', 'Reviewer name (default: cli-operator)')
1504
+ .option('--note <text>', 'Optional approval note')
1505
+ .option('-w, --workspace <path>', 'Workspace directory')
1506
+ .option('--json', 'Output raw JSON')
1507
+ .action(async () => { /* no-op for parser test */ });
1508
+
1509
+ // Case 1: missing --approval-id → Commander throws required-option error
1510
+ await expect(
1511
+ program.parseAsync(['node', 'pd', 'activation', 'approve', '--json']),
1512
+ ).rejects.toThrow(/required option.*--approval-id.*not specified/);
1513
+
1514
+ // Case 2: with --approval-id → parses successfully and exposes the option
1515
+ const captured: Record<string, unknown> = {};
1516
+ const program2 = new Command();
1517
+ program2.exitOverride();
1518
+ const activationCmd2 = program2.command('activation');
1519
+ activationCmd2
1520
+ .command('approve')
1521
+ .requiredOption('-a, --approval-id <id>', 'Approval ID to approve')
1522
+ .option('--decided-by <user>', 'Reviewer name')
1523
+ .option('--note <text>', 'Optional approval note')
1524
+ .option('-w, --workspace <path>', 'Workspace directory')
1525
+ .option('--json', 'Output raw JSON')
1526
+ .action(async (opts) => { Object.assign(captured, opts); });
1527
+
1528
+ await program2.parseAsync([
1529
+ 'node', 'pd', 'activation', 'approve',
1530
+ '--approval-id', 'appr-007',
1531
+ '--decided-by', 'alice',
1532
+ '--note', 'lgtm',
1533
+ '--json',
1534
+ ]);
1535
+
1536
+ expect(captured.approvalId).toBe('appr-007');
1537
+ expect(captured.decidedBy).toBe('alice');
1538
+ expect(captured.note).toBe('lgtm');
1539
+ expect(captured.json).toBe(true);
1540
+ });
1541
+
1542
+ // PRI-489 AP-08: The approve path must inject the real workspace
1543
+ // `rulecode_context_v2` feature flag probe into RuleHostWriter — same
1544
+ // wiring as the dispatch path (tested at line 136-146) and the Console
1545
+ // model (ApprovalsConsoleModel.dispatchActivationAfterApproval).
1546
+ // Previously this path constructed RuleHostWriter without the probe, so a
1547
+ // v2 artifact in a flag-off workspace would pass canActivate here while
1548
+ // being rejected by dispatch/Console — an inconsistent contract that
1549
+ // violated ERR-024 (validator wired in one enforcement path but not
1550
+ // another) and ERR-089 (sibling approval path diverged from dispatch).
1551
+ it('AP-08: wires the effective workspace feature flags into RuleHostWriter (ERR-024/ERR-089)', async () => {
1552
+ mockApprovalApprove.mockResolvedValue({
1553
+ ok: true,
1554
+ record: { approvalId: 'appr-001', artifactId: 'art-001', status: 'approved' },
1555
+ });
1556
+ mockCompletionComplete.mockResolvedValue({
1557
+ ok: true,
1558
+ activationId: 'act-001',
1559
+ decision: { decision: 'activated', activationId: 'act-001', action: 'prompt', targetRef: 'P_001' },
1560
+ });
1561
+
1562
+ await handleActivationApprove({
1563
+ workspace: WS,
1564
+ approvalId: 'appr-001',
1565
+ decidedBy: 'test-owner',
1566
+ json: true,
1567
+ });
1568
+
1569
+ // The RuleHostWriter mock captures its constructor config — verify the
1570
+ // featureFlagProbe was injected and reflects the mocked feature flags
1571
+ // (rulecode_context_v2: enabled=true, see mockFeatureFlags at top).
1572
+ expect(mockRuleHostWriterConfigs).toHaveLength(1);
1573
+ expect(mockRuleHostWriterConfigs[0]?.featureFlagProbe).toBeDefined();
1574
+ expect(mockRuleHostWriterConfigs[0]?.featureFlagProbe?.('rulecode_context_v2')).toBe(true);
1575
+ // Unknown flags must not be reported as enabled (rc-2-no-as-bypass).
1576
+ expect(mockRuleHostWriterConfigs[0]?.featureFlagProbe?.('nonexistent_flag')).toBe(false);
1577
+ });
1578
+ });
1579
+
1580
+ // ── PRI-499: CLI parser wiring (cli-7) and exit-stops (cli-2) ─────────────
1581
+ //
1582
+ // cli-7-test-wiring: every activation subcommand must exercise the real
1583
+ // Commander flag registration path. Without this, a future refactor could
1584
+ // silently break flag parsing and only surface at runtime. The existing
1585
+ // `approve` parser test (AP-07 above) is the template; these tests extend
1586
+ // coverage to dispatch, deactivate, promote, and list.
1587
+ //
1588
+ // cli-2-exit-stops: failure paths that call process.exit must not trigger
1589
+ // downstream side effects (DB writes, ledger updates, artifact creation).
1590
+ // Stubs process.exit to throw, then asserts no store was constructed.
1591
+
1592
+ describe('PRI-499: CLI parser wiring (cli-7) for activation subcommands', () => {
1593
+ it('dispatch: --artifact-id, --channel, --dry-run, --confirm, --json parse correctly', async () => {
1594
+ const { Command } = await import('commander');
1595
+ const captured: Record<string, unknown> = {};
1596
+ const program = new Command();
1597
+ program.exitOverride();
1598
+ const activationCmd = program.command('activation');
1599
+ registerRuntimeActivationDispatchCommand(activationCmd)
1600
+ .action(async (opts) => { Object.assign(captured, opts); });
1601
+
1602
+ await program.parseAsync([
1603
+ 'node', 'pd', 'activation', 'dispatch',
1604
+ '--artifact-id', 'art-parse-001',
1605
+ '--channel', 'prompt',
1606
+ '--dry-run',
1607
+ '--json',
1608
+ ]);
1609
+
1610
+ expect(captured.artifactId).toBe('art-parse-001');
1611
+ expect(captured.channel).toBe('prompt');
1612
+ expect(captured.dryRun).toBe(true);
1613
+ expect(captured.confirm).toBeUndefined();
1614
+ expect(captured.json).toBe(true);
1615
+ });
1616
+
1617
+ it('dispatch: --confirm flag parses and is mutually exclusive with --dry-run at handler level', async () => {
1618
+ const { Command } = await import('commander');
1619
+ const captured: Record<string, unknown> = {};
1620
+ const program = new Command();
1621
+ program.exitOverride();
1622
+ const activationCmd = program.command('activation');
1623
+ registerRuntimeActivationDispatchCommand(activationCmd)
1624
+ .action(async (opts) => { Object.assign(captured, opts); });
1625
+
1626
+ await program.parseAsync([
1627
+ 'node', 'pd', 'activation', 'dispatch',
1628
+ '--artifact-id', 'art-confirm',
1629
+ '--confirm',
1630
+ '--json',
1631
+ ]);
1632
+
1633
+ expect(captured.confirm).toBe(true);
1634
+ expect(captured.dryRun).toBeUndefined();
1635
+ });
1636
+
1637
+ it('deactivate: --activation-id (required) parses correctly', async () => {
1638
+ const { Command } = await import('commander');
1639
+ const captured: Record<string, unknown> = {};
1640
+ const program = new Command();
1641
+ program.exitOverride();
1642
+ const activationCmd = program.command('activation');
1643
+ registerRuntimeActivationDeactivateCommand(activationCmd)
1644
+ .action(async (opts) => { Object.assign(captured, opts); });
1645
+
1646
+ await program.parseAsync([
1647
+ 'node', 'pd', 'activation', 'deactivate',
1648
+ '--activation-id', 'act-parse-deact',
1649
+ '--json',
1650
+ ]);
1651
+
1652
+ expect(captured.activationId).toBe('act-parse-deact');
1653
+ expect(captured.json).toBe(true);
1654
+ });
1655
+
1656
+ it('deactivate: missing --activation-id fails at parser level (required option)', async () => {
1657
+ const { Command } = await import('commander');
1658
+ const program = new Command();
1659
+ program.exitOverride();
1660
+ const activationCmd = program.command('activation');
1661
+ registerRuntimeActivationDeactivateCommand(activationCmd)
1662
+ .action(async () => { /* no-op */ });
1663
+
1664
+ await expect(
1665
+ program.parseAsync(['node', 'pd', 'activation', 'deactivate', '--json']),
1666
+ ).rejects.toThrow(/required option.*--activation-id.*not specified/);
1667
+ });
1668
+
1669
+ it('promote: --activation-id (required), --dry-run, --confirm parse correctly', async () => {
1670
+ const { Command } = await import('commander');
1671
+ const captured: Record<string, unknown> = {};
1672
+ const program = new Command();
1673
+ program.exitOverride();
1674
+ const activationCmd = program.command('activation');
1675
+ registerRuntimeActivationPromoteCommand(activationCmd)
1676
+ .action(async (opts) => { Object.assign(captured, opts); });
1677
+
1678
+ await program.parseAsync([
1679
+ 'node', 'pd', 'activation', 'promote',
1680
+ '--activation-id', 'act-parse-promote',
1681
+ '--dry-run',
1682
+ '--json',
1683
+ ]);
1684
+
1685
+ expect(captured.activationId).toBe('act-parse-promote');
1686
+ expect(captured.dryRun).toBe(true);
1687
+ expect(captured.confirm).toBeUndefined();
1688
+ });
1689
+
1690
+ it('promote: --confirm flag parses (not --dry-run)', async () => {
1691
+ const { Command } = await import('commander');
1692
+ const captured: Record<string, unknown> = {};
1693
+ const program = new Command();
1694
+ program.exitOverride();
1695
+ const activationCmd = program.command('activation');
1696
+ registerRuntimeActivationPromoteCommand(activationCmd)
1697
+ .action(async (opts) => { Object.assign(captured, opts); });
1698
+
1699
+ await program.parseAsync([
1700
+ 'node', 'pd', 'activation', 'promote',
1701
+ '--activation-id', 'act-promote-confirm',
1702
+ '--confirm',
1703
+ '--json',
1704
+ ]);
1705
+
1706
+ expect(captured.confirm).toBe(true);
1707
+ expect(captured.dryRun).toBeUndefined();
1708
+ });
1709
+
1710
+ it('list: --channel filter and --json parse correctly', async () => {
1711
+ const { Command } = await import('commander');
1712
+ const captured: Record<string, unknown> = {};
1713
+ const program = new Command();
1714
+ program.exitOverride();
1715
+ const activationCmd = program.command('activation');
1716
+ registerRuntimeActivationListCommand(activationCmd)
1717
+ .action(async (opts) => { Object.assign(captured, opts); });
1718
+
1719
+ await program.parseAsync([
1720
+ 'node', 'pd', 'activation', 'list',
1721
+ '--channel', 'code_tool_hook',
1722
+ '--json',
1723
+ ]);
1724
+
1725
+ expect(captured.channel).toBe('code_tool_hook');
1726
+ expect(captured.json).toBe(true);
1727
+ expect(captured.includeDeactivated).toBeUndefined();
1728
+ });
1729
+
1730
+ it('list: --include-deactivated flag parses as boolean true', async () => {
1731
+ const { Command } = await import('commander');
1732
+ const captured: Record<string, unknown> = {};
1733
+ const program = new Command();
1734
+ program.exitOverride();
1735
+ const activationCmd = program.command('activation');
1736
+ registerRuntimeActivationListCommand(activationCmd)
1737
+ .action(async (opts) => { Object.assign(captured, opts); });
1738
+
1739
+ await program.parseAsync([
1740
+ 'node', 'pd', 'activation', 'list',
1741
+ '--include-deactivated',
1742
+ '--json',
1743
+ ]);
1744
+
1745
+ expect(captured.includeDeactivated).toBe(true);
1746
+ });
1747
+ });
1748
+
1749
+ // PRI-499 cli-2-exit-stops: Verify failure paths do NOT trigger DB/ledger/
1750
+ // artifact side effects. Production code uses `process.exitCode = 1` (not
1751
+ // `process.exit(1)`) and returns early — these tests assert both the exit
1752
+ // code AND that no store was constructed, covering the high-risk channel
1753
+ // refusal path that was not covered by the existing tests at lines 266-303.
1754
+ // If a future change replaces `process.exitCode` with `process.exit()` but
1755
+ // forgets to add a `return`, these tests will fail because the store mock
1756
+ // would be called before the exit.
1757
+ describe('PRI-499: cli-2-exit-stops — failure paths set exitCode and do not construct stores', () => {
1758
+ let consoleLogSpy: ReturnType<typeof vi.spyOn>;
1759
+ let consoleErrorSpy: ReturnType<typeof vi.spyOn>;
1760
+
1761
+ beforeEach(() => {
1762
+ vi.clearAllMocks();
1763
+ mockRuleHostWriterConfigs.length = 0;
1764
+ consoleLogSpy = vi.spyOn(console, 'log').mockImplementation(() => {});
1765
+ consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
1766
+ mockGetArtifactById.mockResolvedValue(makeArtifact());
1767
+ });
1768
+
1769
+ afterEach(() => {
1770
+ consoleLogSpy.mockRestore();
1771
+ consoleErrorSpy.mockRestore();
1772
+ process.exitCode = 0;
1773
+ });
1774
+
1775
+ it('high-risk channel refusal: sets exitCode=1 and returns structured refusal (cli-2)', async () => {
1776
+ await handleRuntimeActivationDispatch({
1777
+ workspace: WS,
1778
+ artifactId: 'art-001',
1779
+ channel: 'code_tool_hook',
1780
+ json: true,
1781
+ });
1782
+
1783
+ // cli-2: exit-stops — refused path must set exitCode and return a
1784
+ // structured refusal. Stores ARE constructed (artifact exists, so
1785
+ // RuntimeStateManager/SqliteActivationStateStore/ActivationDispatcher
1786
+ // are built before dispatch() returns 'refused'). The cli-2 guarantee
1787
+ // for this path = exitCode set + structured output, NOT "no store
1788
+ // construction" (rc-9 + cli-6).
1789
+ expect(process.exitCode).toBe(1);
1790
+
1791
+ // Verify the JSON output is a structured refusal (rc-9 + cli-6).
1792
+ const output = JSON.parse(consoleLogSpy.mock.calls[0][0]);
1793
+ expect(output.decision).toBe('refused');
1794
+ expect(output.reason).toBeDefined();
1795
+ expect(output.nextAction).toBeDefined();
1796
+ });
1797
+
1798
+ it('missing artifact: sets exitCode=1 and does not construct SqliteActivationStateStore or ActivationDispatcher (cli-2)', async () => {
1799
+ mockGetArtifactById.mockResolvedValue(null);
1800
+ const { SqliteActivationStateStore, ActivationDispatcher } = await import('@principles/core/runtime-v2');
1801
+ vi.mocked(SqliteActivationStateStore).mockClear();
1802
+ vi.mocked(ActivationDispatcher).mockClear();
1803
+
1804
+ await handleRuntimeActivationDispatch({
1805
+ workspace: WS,
1806
+ artifactId: 'nonexistent-cli-2',
1807
+ channel: 'prompt',
1808
+ json: true,
1809
+ });
1810
+
1811
+ // cli-2: RuntimeStateManager IS constructed at line 143 (needed to check
1812
+ // artifact existence via getArtifactById). But SqliteActivationStateStore
1813
+ // and ActivationDispatcher are NOT constructed — the handler returns at
1814
+ // line 156 before reaching lines 170/175. This is the no-DB-side-effects
1815
+ // guarantee for the missing-artifact failure path.
1816
+ expect(process.exitCode).toBe(1);
1817
+ expect(SqliteActivationStateStore).not.toHaveBeenCalled();
1818
+ expect(ActivationDispatcher).not.toHaveBeenCalled();
1819
+ });
1820
+
1821
+ it('mutex failure (--dry-run + --confirm): sets exitCode=1 and does not construct RuntimeStateManager', async () => {
1822
+ const { RuntimeStateManager } = await import('@principles/core/runtime-v2');
1823
+ vi.mocked(RuntimeStateManager).mockClear();
1824
+
1825
+ await handleRuntimeActivationDispatch({
1826
+ workspace: WS,
1827
+ artifactId: 'art-001',
1828
+ channel: 'prompt',
1829
+ dryRun: true,
1830
+ confirm: true,
1831
+ json: true,
1832
+ });
1833
+
1834
+ // cli-2: mutex failure must set exitCode and NOT construct state manager.
1835
+ expect(process.exitCode).toBe(1);
1836
+ expect(RuntimeStateManager).not.toHaveBeenCalled();
1837
+ });
1838
+ });