@principles/pd-cli 1.152.11 → 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 (303) hide show
  1. package/dist/commands/candidate.d.ts +3 -3
  2. package/dist/commands/candidate.d.ts.map +1 -1
  3. package/dist/commands/candidate.js +9 -21
  4. package/dist/commands/candidate.js.map +1 -1
  5. package/dist/index.js +0 -0
  6. package/dist/services/rulehost-pipeline-runner.d.ts.map +1 -1
  7. package/dist/services/rulehost-pipeline-runner.js +4 -17
  8. package/dist/services/rulehost-pipeline-runner.js.map +1 -1
  9. package/package.json +13 -7
  10. package/dist/commands/__tests__/intent-flag-wiring.test.d.ts +0 -9
  11. package/dist/commands/__tests__/intent-flag-wiring.test.d.ts.map +0 -1
  12. package/dist/commands/__tests__/intent-flag-wiring.test.js +0 -237
  13. package/dist/commands/__tests__/intent-flag-wiring.test.js.map +0 -1
  14. package/dist/commands/__tests__/legacy-cleanup.test.d.ts +0 -18
  15. package/dist/commands/__tests__/legacy-cleanup.test.d.ts.map +0 -1
  16. package/dist/commands/__tests__/legacy-cleanup.test.js +0 -467
  17. package/dist/commands/__tests__/legacy-cleanup.test.js.map +0 -1
  18. package/dist/commands/__tests__/mvp-smoke.test.d.ts +0 -15
  19. package/dist/commands/__tests__/mvp-smoke.test.d.ts.map +0 -1
  20. package/dist/commands/__tests__/mvp-smoke.test.js +0 -262
  21. package/dist/commands/__tests__/mvp-smoke.test.js.map +0 -1
  22. package/dist/commands/__tests__/pain-retry-maxTokens-flag.test.d.ts +0 -2
  23. package/dist/commands/__tests__/pain-retry-maxTokens-flag.test.d.ts.map +0 -1
  24. package/dist/commands/__tests__/pain-retry-maxTokens-flag.test.js +0 -60
  25. package/dist/commands/__tests__/pain-retry-maxTokens-flag.test.js.map +0 -1
  26. package/dist/commands/__tests__/rulecode-flag-wiring.test.d.ts +0 -21
  27. package/dist/commands/__tests__/rulecode-flag-wiring.test.d.ts.map +0 -1
  28. package/dist/commands/__tests__/rulecode-flag-wiring.test.js +0 -186
  29. package/dist/commands/__tests__/rulecode-flag-wiring.test.js.map +0 -1
  30. package/dist/commands/__tests__/rulecode-handler.test.d.ts +0 -16
  31. package/dist/commands/__tests__/rulecode-handler.test.d.ts.map +0 -1
  32. package/dist/commands/__tests__/rulecode-handler.test.js +0 -285
  33. package/dist/commands/__tests__/rulecode-handler.test.js.map +0 -1
  34. package/dist/commands/__tests__/run-rulehost-flag-wiring.test.d.ts +0 -24
  35. package/dist/commands/__tests__/run-rulehost-flag-wiring.test.d.ts.map +0 -1
  36. package/dist/commands/__tests__/run-rulehost-flag-wiring.test.js +0 -232
  37. package/dist/commands/__tests__/run-rulehost-flag-wiring.test.js.map +0 -1
  38. package/dist/commands/__tests__/runtime-activation-nextaction.test.d.ts +0 -15
  39. package/dist/commands/__tests__/runtime-activation-nextaction.test.d.ts.map +0 -1
  40. package/dist/commands/__tests__/runtime-activation-nextaction.test.js +0 -73
  41. package/dist/commands/__tests__/runtime-activation-nextaction.test.js.map +0 -1
  42. package/dist/commands/__tests__/runtime-probe-config.test.d.ts +0 -20
  43. package/dist/commands/__tests__/runtime-probe-config.test.d.ts.map +0 -1
  44. package/dist/commands/__tests__/runtime-probe-config.test.js +0 -389
  45. package/dist/commands/__tests__/runtime-probe-config.test.js.map +0 -1
  46. package/dist/commands/__tests__/telemetry-flag-wiring.test.d.ts +0 -9
  47. package/dist/commands/__tests__/telemetry-flag-wiring.test.d.ts.map +0 -1
  48. package/dist/commands/__tests__/telemetry-flag-wiring.test.js +0 -76
  49. package/dist/commands/__tests__/telemetry-flag-wiring.test.js.map +0 -1
  50. package/dist/commands/__tests__/version.test.d.ts +0 -2
  51. package/dist/commands/__tests__/version.test.d.ts.map +0 -1
  52. package/dist/commands/__tests__/version.test.js +0 -238
  53. package/dist/commands/__tests__/version.test.js.map +0 -1
  54. package/dist/commands/runtime-uat.guard.test.d.ts +0 -2
  55. package/dist/commands/runtime-uat.guard.test.d.ts.map +0 -1
  56. package/dist/commands/runtime-uat.guard.test.js +0 -153
  57. package/dist/commands/runtime-uat.guard.test.js.map +0 -1
  58. package/dist/services/__tests__/cli-output.test.d.ts +0 -18
  59. package/dist/services/__tests__/cli-output.test.d.ts.map +0 -1
  60. package/dist/services/__tests__/cli-output.test.js +0 -103
  61. package/dist/services/__tests__/cli-output.test.js.map +0 -1
  62. package/dist/services/__tests__/evaluator-runner-deps.test.d.ts +0 -2
  63. package/dist/services/__tests__/evaluator-runner-deps.test.d.ts.map +0 -1
  64. package/dist/services/__tests__/evaluator-runner-deps.test.js +0 -343
  65. package/dist/services/__tests__/evaluator-runner-deps.test.js.map +0 -1
  66. package/dist/services/__tests__/rulehost-readiness.test.d.ts +0 -2
  67. package/dist/services/__tests__/rulehost-readiness.test.d.ts.map +0 -1
  68. package/dist/services/__tests__/rulehost-readiness.test.js +0 -311
  69. package/dist/services/__tests__/rulehost-readiness.test.js.map +0 -1
  70. package/dist/services/__tests__/runtime-adapter-resolver.test.d.ts +0 -18
  71. package/dist/services/__tests__/runtime-adapter-resolver.test.d.ts.map +0 -1
  72. package/dist/services/__tests__/runtime-adapter-resolver.test.js +0 -673
  73. package/dist/services/__tests__/runtime-adapter-resolver.test.js.map +0 -1
  74. package/dist/utils/production-workspace-guard.test.d.ts +0 -2
  75. package/dist/utils/production-workspace-guard.test.d.ts.map +0 -1
  76. package/dist/utils/production-workspace-guard.test.js +0 -137
  77. package/dist/utils/production-workspace-guard.test.js.map +0 -1
  78. package/scripts/llm-dogfood.ts +0 -456
  79. package/scripts/migrate-illegal-expected-decision.ts +0 -252
  80. package/src/commands/__tests__/intent-flag-wiring.test.ts +0 -282
  81. package/src/commands/__tests__/legacy-cleanup.test.ts +0 -602
  82. package/src/commands/__tests__/mvp-smoke.test.ts +0 -300
  83. package/src/commands/__tests__/pain-retry-maxTokens-flag.test.ts +0 -73
  84. package/src/commands/__tests__/rulecode-flag-wiring.test.ts +0 -237
  85. package/src/commands/__tests__/rulecode-handler.test.ts +0 -369
  86. package/src/commands/__tests__/run-rulehost-flag-wiring.test.ts +0 -292
  87. package/src/commands/__tests__/runtime-activation-nextaction.test.ts +0 -81
  88. package/src/commands/__tests__/runtime-probe-config.test.ts +0 -432
  89. package/src/commands/__tests__/telemetry-flag-wiring.test.ts +0 -84
  90. package/src/commands/__tests__/version.test.ts +0 -251
  91. package/src/commands/admission-gate.ts +0 -30
  92. package/src/commands/artifact.ts +0 -82
  93. package/src/commands/build-trajectory-evidence.ts +0 -298
  94. package/src/commands/candidate.ts +0 -1260
  95. package/src/commands/codex-ingest-catchup.ts +0 -114
  96. package/src/commands/codex-ingest-quarantine.ts +0 -127
  97. package/src/commands/codex-reconcile.ts +0 -84
  98. package/src/commands/codex-setup.ts +0 -476
  99. package/src/commands/codex-worker.ts +0 -185
  100. package/src/commands/command-helpers.ts +0 -24
  101. package/src/commands/config-doctor.ts +0 -193
  102. package/src/commands/console.ts +0 -797
  103. package/src/commands/context.ts +0 -72
  104. package/src/commands/demo-story-a.ts +0 -241
  105. package/src/commands/diagnose.ts +0 -756
  106. package/src/commands/errors-list.ts +0 -441
  107. package/src/commands/evolution-tasks-list.ts +0 -48
  108. package/src/commands/evolution-tasks-show.ts +0 -62
  109. package/src/commands/flow.ts +0 -60
  110. package/src/commands/health-codex.ts +0 -576
  111. package/src/commands/health.ts +0 -315
  112. package/src/commands/history.ts +0 -63
  113. package/src/commands/intent.ts +0 -457
  114. package/src/commands/legacy-cleanup.ts +0 -531
  115. package/src/commands/legacy-import.ts +0 -104
  116. package/src/commands/mvp-smoke.ts +0 -160
  117. package/src/commands/pain-evidence.ts +0 -226
  118. package/src/commands/pain-list.ts +0 -239
  119. package/src/commands/pain-record.ts +0 -612
  120. package/src/commands/pain-retry.ts +0 -916
  121. package/src/commands/principles-stats.ts +0 -700
  122. package/src/commands/proven-channel-baseline.ts +0 -115
  123. package/src/commands/quality-scorecard.ts +0 -272
  124. package/src/commands/remediation-output.ts +0 -66
  125. package/src/commands/rulecode.ts +0 -465
  126. package/src/commands/run.ts +0 -89
  127. package/src/commands/runtime-activation.ts +0 -1629
  128. package/src/commands/runtime-artifact-repair.ts +0 -524
  129. package/src/commands/runtime-canary.ts +0 -395
  130. package/src/commands/runtime-compatibility-scan.ts +0 -105
  131. package/src/commands/runtime-diagnostics-export.ts +0 -229
  132. package/src/commands/runtime-features.ts +0 -153
  133. package/src/commands/runtime-gfi-snapshot.ts +0 -135
  134. package/src/commands/runtime-health-snapshot.ts +0 -108
  135. package/src/commands/runtime-init.ts +0 -429
  136. package/src/commands/runtime-internalization-enqueue-successors.ts +0 -530
  137. package/src/commands/runtime-internalization-integrity-repair.ts +0 -79
  138. package/src/commands/runtime-internalization-integrity.ts +0 -107
  139. package/src/commands/runtime-internalization-queue.ts +0 -135
  140. package/src/commands/runtime-internalization-retry.ts +0 -191
  141. package/src/commands/runtime-internalization-run-once.ts +0 -791
  142. package/src/commands/runtime-internalization-run-rulehost.ts +0 -749
  143. package/src/commands/runtime-internalization-wake-once.ts +0 -87
  144. package/src/commands/runtime-pain-flood-simulation.ts +0 -121
  145. package/src/commands/runtime-pruning.ts +0 -438
  146. package/src/commands/runtime-recovery-failed-tasks.ts +0 -258
  147. package/src/commands/runtime-recovery.ts +0 -109
  148. package/src/commands/runtime-synthetic-baseline.ts +0 -70
  149. package/src/commands/runtime-uat.guard.test.ts +0 -175
  150. package/src/commands/runtime-uat.ts +0 -380
  151. package/src/commands/runtime.ts +0 -473
  152. package/src/commands/samples-list.ts +0 -39
  153. package/src/commands/samples-review.ts +0 -36
  154. package/src/commands/task.ts +0 -271
  155. package/src/commands/telemetry.ts +0 -349
  156. package/src/commands/trace.ts +0 -174
  157. package/src/commands/trajectory-db-unavailable.ts +0 -19
  158. package/src/commands/trajectory.ts +0 -64
  159. package/src/commands/version.ts +0 -49
  160. package/src/config-reader.ts +0 -122
  161. package/src/index.ts +0 -1276
  162. package/src/legacy/legacy-import.ts +0 -179
  163. package/src/legacy/session-history-import.ts +0 -203
  164. package/src/resolve-workspace.ts +0 -106
  165. package/src/services/__tests__/cli-output.test.ts +0 -130
  166. package/src/services/__tests__/evaluator-runner-deps.test.ts +0 -382
  167. package/src/services/__tests__/rulehost-readiness.test.ts +0 -363
  168. package/src/services/__tests__/runtime-adapter-resolver.test.ts +0 -793
  169. package/src/services/cli-output.ts +0 -95
  170. package/src/services/config-doctor.ts +0 -697
  171. package/src/services/console-launcher.ts +0 -537
  172. package/src/services/demo-rule-compiler.ts +0 -40
  173. package/src/services/demo-story-a-runner.ts +0 -471
  174. package/src/services/mainline-snapshot-assembler.ts +0 -579
  175. package/src/services/pain-flood-simulation-runner.ts +0 -462
  176. package/src/services/pd-config-loader.ts +0 -433
  177. package/src/services/proven-channel-baseline-runner.ts +0 -157
  178. package/src/services/quality-scorecard/data-extractor.ts +0 -150
  179. package/src/services/quality-scorecard/local-evaluator.ts +0 -142
  180. package/src/services/quality-scorecard/strong-model-gate.ts +0 -202
  181. package/src/services/resolve-runtime-from-pd-config.ts +0 -230
  182. package/src/services/rulehost-pipeline-runner.ts +0 -1216
  183. package/src/services/rulehost-readiness.ts +0 -326
  184. package/src/services/runtime-adapter-resolver.ts +0 -364
  185. package/src/services/synthetic-baseline-runner.ts +0 -400
  186. package/src/services/version-report.ts +0 -253
  187. package/src/services/workspace-tool-semantics.ts +0 -26
  188. package/src/utils/path-security.ts +0 -96
  189. package/src/utils/production-workspace-guard.test.ts +0 -157
  190. package/src/utils/production-workspace-guard.ts +0 -210
  191. package/tests/bdd/cli-contract.steps.ts +0 -346
  192. package/tests/bdd/principles-stats.steps.ts +0 -211
  193. package/tests/bdd/support/gherkin-loader.ts +0 -147
  194. package/tests/bdd/support/repo-root.ts +0 -62
  195. package/tests/bdd/support/vitest-bdd.ts +0 -179
  196. package/tests/commands/admission-gate-coverage.test.ts +0 -79
  197. package/tests/commands/build-trajectory-evidence.test.ts +0 -508
  198. package/tests/commands/candidate-audit-repair.test.ts +0 -421
  199. package/tests/commands/candidate-intake.test.ts +0 -732
  200. package/tests/commands/candidate-internalization-backfill.test.ts +0 -548
  201. package/tests/commands/candidate-internalize-lineage.test.ts +0 -565
  202. package/tests/commands/candidate-internalize.test.ts +0 -299
  203. package/tests/commands/candidate-route.test.ts +0 -329
  204. package/tests/commands/candidate-show.test.ts +0 -95
  205. package/tests/commands/cli-command-tree.test.ts +0 -144
  206. package/tests/commands/cli-help-snapshot.test.ts +0 -155
  207. package/tests/commands/cli-skill-contract.test.ts +0 -121
  208. package/tests/commands/codex-consent-reversibility.steps.test.ts +0 -299
  209. package/tests/commands/codex-ingest-quarantine.test.ts +0 -136
  210. package/tests/commands/codex-setup.test.ts +0 -297
  211. package/tests/commands/codex-worker-daemon.test.ts +0 -95
  212. package/tests/commands/codex-worker-registration.test.ts +0 -207
  213. package/tests/commands/config-doctor.test.ts +0 -336
  214. package/tests/commands/console-launcher-edge-cases.test.ts +0 -388
  215. package/tests/commands/console-open.test.ts +0 -1381
  216. package/tests/commands/context.test.ts +0 -114
  217. package/tests/commands/demo-story-a.test.ts +0 -318
  218. package/tests/commands/diagnose.test.ts +0 -1803
  219. package/tests/commands/errors-list.test.ts +0 -679
  220. package/tests/commands/evolution-tasks-list.test.ts +0 -41
  221. package/tests/commands/evolution-tasks-show.test.ts +0 -46
  222. package/tests/commands/health-codex.test.ts +0 -349
  223. package/tests/commands/health-host-wiring.test.ts +0 -76
  224. package/tests/commands/health-reliability.test.ts +0 -99
  225. package/tests/commands/health.test.ts +0 -413
  226. package/tests/commands/intent.test.ts +0 -321
  227. package/tests/commands/legacy-cleanup.test.ts +0 -148
  228. package/tests/commands/pain-evidence.test.ts +0 -518
  229. package/tests/commands/pain-list.test.ts +0 -219
  230. package/tests/commands/pain-record-async.test.ts +0 -335
  231. package/tests/commands/pain-record-session-parser.test.ts +0 -228
  232. package/tests/commands/pain-record.test.ts +0 -851
  233. package/tests/commands/pain-retry.test.ts +0 -1121
  234. package/tests/commands/plugin-config-resolution-cutover.test.ts +0 -229
  235. package/tests/commands/pri-393-runtime-config-unification.test.ts +0 -443
  236. package/tests/commands/principles-stats-wiring.test.ts +0 -135
  237. package/tests/commands/principles-stats.test.ts +0 -274
  238. package/tests/commands/product-path-regression.test.ts +0 -86
  239. package/tests/commands/proven-channel-baseline.test.ts +0 -441
  240. package/tests/commands/rulecode.test.ts +0 -177
  241. package/tests/commands/run-rulehost-handler.test.ts +0 -908
  242. package/tests/commands/runtime-activation-approve-flag-wiring.test.ts +0 -227
  243. package/tests/commands/runtime-activation-deactivate-flag-wiring.test.ts +0 -167
  244. package/tests/commands/runtime-activation-dispatch-flag-wiring.test.ts +0 -262
  245. package/tests/commands/runtime-activation-governance-audit.test.ts +0 -95
  246. package/tests/commands/runtime-activation-list-flag-wiring.test.ts +0 -193
  247. package/tests/commands/runtime-activation-promote-flag-wiring.test.ts +0 -248
  248. package/tests/commands/runtime-activation-shadow-telemetry.test.ts +0 -130
  249. package/tests/commands/runtime-activation.test.ts +0 -2052
  250. package/tests/commands/runtime-artifact-repair-registration.test.ts +0 -74
  251. package/tests/commands/runtime-artifact-repair.test.ts +0 -404
  252. package/tests/commands/runtime-canary.test.ts +0 -430
  253. package/tests/commands/runtime-compatibility-scan.test.ts +0 -146
  254. package/tests/commands/runtime-diagnostics-export.test.ts +0 -175
  255. package/tests/commands/runtime-features.test.ts +0 -249
  256. package/tests/commands/runtime-health-snapshot.test.ts +0 -358
  257. package/tests/commands/runtime-init-empty-workspace.test.ts +0 -252
  258. package/tests/commands/runtime-init.test.ts +0 -420
  259. package/tests/commands/runtime-internalization-enqueue-successors.test.ts +0 -782
  260. package/tests/commands/runtime-internalization-integrity-repair.test.ts +0 -239
  261. package/tests/commands/runtime-internalization-integrity.test.ts +0 -140
  262. package/tests/commands/runtime-internalization-queue.test.ts +0 -380
  263. package/tests/commands/runtime-internalization-retry-owner-authority.test.ts +0 -431
  264. package/tests/commands/runtime-internalization-run-once-evaluator-parity.test.ts +0 -269
  265. package/tests/commands/runtime-internalization-run-once-language.test.ts +0 -303
  266. package/tests/commands/runtime-internalization-run-once-real-config.test.ts +0 -237
  267. package/tests/commands/runtime-internalization-run-once-rollout-parity.test.ts +0 -706
  268. package/tests/commands/runtime-internalization-run-once.test.ts +0 -1791
  269. package/tests/commands/runtime-internalization-wake-once.test.ts +0 -171
  270. package/tests/commands/runtime-internalization.test.ts +0 -53
  271. package/tests/commands/runtime-pain-flood-simulation.test.ts +0 -418
  272. package/tests/commands/runtime-pruning.test.ts +0 -694
  273. package/tests/commands/runtime-recovery-failed-tasks.test.ts +0 -328
  274. package/tests/commands/runtime-recovery.test.ts +0 -120
  275. package/tests/commands/runtime-synthetic-baseline.test.ts +0 -249
  276. package/tests/commands/runtime-uat.test.ts +0 -397
  277. package/tests/commands/runtime.test.ts +0 -392
  278. package/tests/commands/samples-list.test.ts +0 -43
  279. package/tests/commands/samples-review.test.ts +0 -41
  280. package/tests/commands/task.test.ts +0 -153
  281. package/tests/commands/telemetry.test.ts +0 -190
  282. package/tests/commands/trace.test.ts +0 -316
  283. package/tests/config-reader.test.ts +0 -143
  284. package/tests/e2e/candidate-intake-e2e.test.ts +0 -338
  285. package/tests/e2e/cli-full-flow.test.ts +0 -233
  286. package/tests/e2e/cross-package-acceptance.test.ts +0 -635
  287. package/tests/helpers/pd-cli-path.ts +0 -5
  288. package/tests/pd-cli-smoke.test.ts +0 -13
  289. package/tests/resolve-workspace.test.ts +0 -196
  290. package/tests/services/config-doctor-signal-health.test.ts +0 -109
  291. package/tests/services/console-launcher.test.ts +0 -114
  292. package/tests/services/demo-rule-compiler.test.ts +0 -242
  293. package/tests/services/mainline-snapshot-assembler.test.ts +0 -572
  294. package/tests/services/pd-config-loader.test.ts +0 -505
  295. package/tests/services/proven-channel-baseline-runner.test.ts +0 -30
  296. package/tests/services/quality-scorecard/strong-model-gate.test.ts +0 -133
  297. package/tests/services/resolve-runtime-from-pd-config.test.ts +0 -485
  298. package/tests/services/rulehost-pipeline-e2e.test.ts +0 -538
  299. package/tests/services/rulehost-pipeline-runner.test.ts +0 -1175
  300. package/tests/services/workspace-tool-semantics.test.ts +0 -76
  301. package/tests/utils/path-security.test.ts +0 -180
  302. package/tsconfig.json +0 -26
  303. package/vitest.config.ts +0 -9
@@ -1,908 +0,0 @@
1
- /**
2
- * handleRunRuleHost behaviour tests (PRI-429) — input validation gates,
3
- * dry-run output, and capability branches.
4
- *
5
- * The existing flag-wiring test only proves Commander parses the flags.
6
- * This file verifies the handler's behavioural gates:
7
- * - mutual exclusivity of --dry-run and --confirm
8
- * - required pain-id (and whitespace-only forms)
9
- * - channel allowlist enforcement
10
- * - --max-rounds / --timeout-ms positive-integer validation
11
- * - default dry-run output (both plain-text and JSON)
12
- * - --json output parses as a single JSON object
13
- *
14
- * These gates are the CLI-gate contract for run-rulehost. If any of them
15
- * regress, operators silently get undefined behaviour instead of a clear
16
- * error + next-action recommendation.
17
- */
18
- import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
19
- import * as fs from 'node:fs';
20
- import * as path from 'node:path';
21
- import * as os from 'node:os';
22
- import * as yaml from 'js-yaml';
23
- import { handleRunRuleHost } from '../../src/commands/runtime-internalization-run-rulehost.js';
24
-
25
- // ── workspace helpers ─────────────────────────────────────────────────────
26
-
27
- function mkTmpDir(): string {
28
- return fs.mkdtempSync(path.join(os.tmpdir(), 'pd-rulehost-handler-'));
29
- }
30
-
31
- function writeMinimalValidConfig(workspaceDir: string): void {
32
- const configDir = path.join(workspaceDir, '.pd');
33
- fs.mkdirSync(configDir, { recursive: true });
34
- const cfg = {
35
- version: 1,
36
- features: {
37
- prompt: { category: 'core', enabled: true },
38
- code_tool_hook: { category: 'core', enabled: true },
39
- defer_archive: { category: 'core', enabled: true },
40
- },
41
- workspace: { default: workspaceDir },
42
- runtimeProfiles: {
43
- 'pi-ai.default': { type: 'pi-ai', provider: 'anthropic', model: 'claude-sonnet', apiKeyEnv: 'ANTHROPIC_API_KEY' },
44
- },
45
- internalAgents: {
46
- defaultRuntime: 'pi-ai.default',
47
- agents: {
48
- dreamer: { enabled: true, runtimeProfile: 'pi-ai.default' },
49
- philosopher: { enabled: true, runtimeProfile: 'pi-ai.default' },
50
- scribe: { enabled: true, runtimeProfile: 'pi-ai.default' },
51
- evaluator: { enabled: true, runtimeProfile: 'pi-ai.default' },
52
- },
53
- },
54
- };
55
- fs.writeFileSync(path.join(configDir, 'config.yaml'), yaml.dump(cfg), 'utf8');
56
- }
57
-
58
- // ── stdout/stderr capture helpers ──────────────────────────────────────
59
-
60
- interface StdIoState {
61
- stdout: string;
62
- stderr: string;
63
- exitCode: number | undefined;
64
- }
65
-
66
- function parseJsonObject(text: string): Record<string, unknown> {
67
- const parsed: unknown = JSON.parse(text);
68
- if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) {
69
- throw new Error('stdout is not a JSON object');
70
- }
71
- return parsed;
72
- }
73
-
74
- /** Type guard: narrows `unknown` to `Record<string, unknown>` without `as`. */
75
- function isRecord(value: unknown): value is Record<string, unknown> {
76
- return typeof value === 'object' && value !== null && !Array.isArray(value);
77
- }
78
-
79
- function captureStdio(fn: () => Promise<void>): Promise<StdIoState> {
80
- return new Promise((resolve, reject) => {
81
- const origExitCode = process.exitCode;
82
- process.exitCode = undefined;
83
- let stdout = '';
84
- let stderr = '';
85
- const stdoutSpy = vi.spyOn(process.stdout, 'write').mockImplementation((chunk: string | Uint8Array) => {
86
- stdout += typeof chunk === 'string' ? chunk : chunk.toString();
87
- return true;
88
- });
89
- const stderrSpy = vi.spyOn(process.stderr, 'write').mockImplementation((chunk: string | Uint8Array) => {
90
- stderr += typeof chunk === 'string' ? chunk : chunk.toString();
91
- return true;
92
- });
93
- const consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation((...args: unknown[]) => {
94
- stderr += args.map((a) => (typeof a === 'string' ? a : String(a))).join(' ') + '\n';
95
- });
96
- fn()
97
- .then(() => {
98
- const captured = { stdout, stderr, exitCode: process.exitCode };
99
- stdoutSpy.mockRestore();
100
- stderrSpy.mockRestore();
101
- consoleErrorSpy.mockRestore();
102
- process.exitCode = origExitCode;
103
- resolve(captured);
104
- })
105
- .catch((err) => {
106
- stdoutSpy.mockRestore();
107
- stderrSpy.mockRestore();
108
- consoleErrorSpy.mockRestore();
109
- process.exitCode = origExitCode;
110
- reject(err);
111
- });
112
- });
113
- }
114
-
115
- describe('handleRunRuleHost — input validation gates', () => {
116
- it('sets exitCode=1 and emits an error when both --dry-run and --confirm are passed (plain text)', async () => {
117
- const { stdout, stderr, exitCode } = await captureStdio(() =>
118
- handleRunRuleHost({ painId: 'pain-1', dryRun: true, confirm: true }),
119
- );
120
- expect(exitCode).toBe(1);
121
- // plain-text mode: error on stderr includes 'mutually exclusive'
122
- expect(stderr).toMatch(/mutually exclusive/i);
123
- // stdout must not contain JSON object (handler writes to stderr).
124
- expect(stdout.trim()).toBe('');
125
- });
126
-
127
- it('sets exitCode=1 and emits a JSON object when both --dry-run and --confirm are passed with --json', async () => {
128
- const { stdout, exitCode } = await captureStdio(() =>
129
- handleRunRuleHost({ painId: 'pain-1', dryRun: true, confirm: true, json: true }),
130
- );
131
- expect(exitCode).toBe(1);
132
- const payload = parseJsonObject(stdout.trim());
133
- expect(payload.status).toBe('failed');
134
- expect(payload.nextAction).toBeDefined();
135
- expect(typeof payload.reason).toBe('string');
136
- });
137
-
138
- it('sets exitCode=1 when --pain-id is missing (falsy string)', async () => {
139
- const { exitCode } = await captureStdio(() => handleRunRuleHost({ painId: '' }));
140
- expect(exitCode).toBe(1);
141
- });
142
-
143
- it('sets exitCode=1 when --pain-id is whitespace-only', async () => {
144
- const { exitCode } = await captureStdio(() => handleRunRuleHost({ painId: ' \t ' }));
145
- expect(exitCode).toBe(1);
146
- });
147
-
148
- it('sets exitCode=1 for unsupported channels (plain-text mode)', async () => {
149
- const { exitCode, stderr } = await captureStdio(() =>
150
- handleRunRuleHost({ painId: 'pain-1', channel: 'wizard' }),
151
- );
152
- expect(exitCode).toBe(1);
153
- expect(stderr).toMatch(/wizard/);
154
- });
155
-
156
- it('sets exitCode=1 for unsupported channels (JSON mode)', async () => {
157
- const { stdout, exitCode } = await captureStdio(() =>
158
- handleRunRuleHost({ painId: 'pain-1', channel: 'wizard', json: true }),
159
- );
160
- expect(exitCode).toBe(1);
161
- const payload = parseJsonObject(stdout.trim());
162
- expect(payload.status).toBe('failed');
163
- expect(payload.reason).toMatch(/wizard/);
164
- });
165
-
166
- it('sets exitCode=1 when --max-rounds is zero', async () => {
167
- const { exitCode } = await captureStdio(() =>
168
- handleRunRuleHost({ painId: 'pain-1', maxRounds: 0, dryRun: true }));
169
- expect(exitCode).toBe(1);
170
- });
171
-
172
- it('sets exitCode=1 when --max-rounds is negative', async () => {
173
- const { exitCode } = await captureStdio(() =>
174
- handleRunRuleHost({ painId: 'pain-1', maxRounds: -5, dryRun: true }));
175
- expect(exitCode).toBe(1);
176
- });
177
-
178
- it('sets exitCode=1 when --timeout-ms is zero', async () => {
179
- const { exitCode } = await captureStdio(() =>
180
- handleRunRuleHost({ painId: 'pain-1', timeoutMs: 0, dryRun: true }));
181
- expect(exitCode).toBe(1);
182
- });
183
-
184
- it('sets exitCode=1 when --timeout-ms is negative', async () => {
185
- const { exitCode } = await captureStdio(() =>
186
- handleRunRuleHost({ painId: 'pain-1', timeoutMs: -100, dryRun: true }));
187
- expect(exitCode).toBe(1);
188
- });
189
-
190
- it.each([
191
- ['NaN maxRounds', { maxRounds: Number.NaN }],
192
- ['fractional maxRounds', { maxRounds: 1.5 }],
193
- ['NaN timeoutMs', { timeoutMs: Number.NaN }],
194
- ['fractional timeoutMs', { timeoutMs: 1.5 }],
195
- ])('sets exitCode=1 for %s', async (_label, invalidOption) => {
196
- const { exitCode } = await captureStdio(() =>
197
- handleRunRuleHost({ painId: 'pain-1', dryRun: true, ...invalidOption }),
198
- );
199
- expect(exitCode).toBe(1);
200
- });
201
- });
202
-
203
- describe('handleRunRuleHost — dry-run mode output shape (with minimal pd-config.yaml', () => {
204
- let workspaceDir: string;
205
- let savedEnv: NodeJS.ProcessEnv;
206
-
207
- beforeEach(() => {
208
- workspaceDir = mkTmpDir();
209
- writeMinimalValidConfig(workspaceDir);
210
- savedEnv = { ...process.env };
211
- process.env.ANTHROPIC_API_KEY = 'sk-ant-test-key';
212
- });
213
-
214
- afterEach(() => {
215
- process.env = savedEnv;
216
- try { fs.rmSync(workspaceDir, { recursive: true, force: true }); } catch { /* ignore */ }
217
- });
218
-
219
- it('emits a single JSON object in --json dry-run mode', async () => {
220
- const { stdout, exitCode } = await captureStdio(() =>
221
- handleRunRuleHost({ painId: 'pain-1', dryRun: true, json: true, workspace: workspaceDir }),
222
- );
223
- const payload = parseJsonObject(stdout.trim());
224
- expect(payload.status).toBe('dry_run');
225
- expect(typeof payload.capabilityStatus).toBe('string');
226
- expect(typeof payload.nextAction).toBe('string');
227
- expect(payload.painId).toBe('pain-1');
228
- // Must not be error-exit for a valid dry-run.
229
- expect(exitCode).toBeUndefined();
230
- });
231
-
232
- it('does NOT emit JSON on stdout in plain-text dry-run mode', async () => {
233
- const { stdout } = await captureStdio(() =>
234
- handleRunRuleHost({ painId: 'pain-1', dryRun: true, workspace: workspaceDir }),
235
- );
236
- expect(stdout).toMatch(/RuleHost Pipeline/);
237
- // Plain text output should not start with '{'
238
- expect(() => JSON.parse(stdout.trim())).toThrow();
239
- });
240
-
241
- it('defaults to dry-run behaviour when neither --dry-run nor --confirm is passed', async () => {
242
- const { stdout } = await captureStdio(() =>
243
- handleRunRuleHost({ painId: 'pain-1', json: true, workspace: workspaceDir }),
244
- );
245
- const payload = parseJsonObject(stdout.trim());
246
- expect(payload.status).toBe('dry_run');
247
- });
248
-
249
- it('accepts the three supported channels and passes config', async () => {
250
- for (const channel of ['prompt', 'code_tool_hook', 'defer_archive'] as const) {
251
- const { exitCode } = await captureStdio(() =>
252
- handleRunRuleHost({ painId: 'pain-1', channel, dryRun: true, workspace: workspaceDir }),
253
- );
254
- // Channel gate passed — exitCode should not be 1 for supported channels.
255
- expect(exitCode).toBeUndefined();
256
- }
257
- });
258
- });
259
-
260
- // ── PRI-461: readiness integration tests ──────────────────────────────────
261
- //
262
- // Verifies the handler emits the three readiness statuses (ready /
263
- // text_principle_only / refused) with the correct exit codes and JSON shape.
264
- // These tests exercise the full path: config → resolveRuleHostReadiness →
265
- // handler output, ensuring the readiness gate is wired into production code
266
- // (EP-02) and that refused statuses fail loud with reason + nextAction (EP-03).
267
-
268
- function writeFullReadyConfig(workspaceDir: string): void {
269
- const configDir = path.join(workspaceDir, '.pd');
270
- fs.mkdirSync(configDir, { recursive: true });
271
- const cfg = {
272
- version: 1,
273
- features: {
274
- prompt: { category: 'core', enabled: true },
275
- code_tool_hook: { category: 'core', enabled: true },
276
- defer_archive: { category: 'core', enabled: true },
277
- code_rule_capability: { category: 'core', enabled: true },
278
- },
279
- workspace: { default: workspaceDir },
280
- runtimeProfiles: {
281
- 'pi-ai.default': { type: 'pi-ai', provider: 'anthropic', model: 'claude-sonnet', apiKeyEnv: 'ANTHROPIC_API_KEY' },
282
- },
283
- internalAgents: {
284
- defaultRuntime: 'pi-ai.default',
285
- agents: {
286
- dreamer: { enabled: true, runtimeProfile: 'pi-ai.default' },
287
- philosopher: { enabled: true, runtimeProfile: 'pi-ai.default' },
288
- scribe: { enabled: true, runtimeProfile: 'pi-ai.default' },
289
- artificer: { enabled: true, runtimeProfile: 'pi-ai.default' },
290
- evaluator: { enabled: true, runtimeProfile: 'pi-ai.default' },
291
- },
292
- },
293
- };
294
- fs.writeFileSync(path.join(configDir, 'config.yaml'), yaml.dump(cfg), 'utf8');
295
- }
296
-
297
- function writeTextPrincipleOnlyConfig(workspaceDir: string): void {
298
- // code_rule_capability explicitly OFF → text_principle_only
299
- const configDir = path.join(workspaceDir, '.pd');
300
- fs.mkdirSync(configDir, { recursive: true });
301
- const cfg = {
302
- version: 1,
303
- features: {
304
- prompt: { category: 'core', enabled: true },
305
- code_tool_hook: { category: 'core', enabled: true },
306
- defer_archive: { category: 'core', enabled: true },
307
- code_rule_capability: { category: 'core', enabled: false },
308
- },
309
- workspace: { default: workspaceDir },
310
- runtimeProfiles: {
311
- 'pi-ai.default': { type: 'pi-ai', provider: 'anthropic', model: 'claude-sonnet', apiKeyEnv: 'ANTHROPIC_API_KEY' },
312
- },
313
- internalAgents: {
314
- defaultRuntime: 'pi-ai.default',
315
- agents: {
316
- dreamer: { enabled: true, runtimeProfile: 'pi-ai.default' },
317
- philosopher: { enabled: true, runtimeProfile: 'pi-ai.default' },
318
- scribe: { enabled: true, runtimeProfile: 'pi-ai.default' },
319
- artificer: { enabled: true, runtimeProfile: 'pi-ai.default' },
320
- evaluator: { enabled: true, runtimeProfile: 'pi-ai.default' },
321
- },
322
- },
323
- };
324
- fs.writeFileSync(path.join(configDir, 'config.yaml'), yaml.dump(cfg), 'utf8');
325
- }
326
-
327
- function writeEvaluatorDisabledConfig(workspaceDir: string): void {
328
- const configDir = path.join(workspaceDir, '.pd');
329
- fs.mkdirSync(configDir, { recursive: true });
330
- const cfg = {
331
- version: 1,
332
- features: {
333
- prompt: { category: 'core', enabled: true },
334
- code_tool_hook: { category: 'core', enabled: true },
335
- defer_archive: { category: 'core', enabled: true },
336
- code_rule_capability: { category: 'core', enabled: true },
337
- },
338
- workspace: { default: workspaceDir },
339
- runtimeProfiles: {
340
- 'pi-ai.default': { type: 'pi-ai', provider: 'anthropic', model: 'claude-sonnet', apiKeyEnv: 'ANTHROPIC_API_KEY' },
341
- },
342
- internalAgents: {
343
- defaultRuntime: 'pi-ai.default',
344
- agents: {
345
- dreamer: { enabled: true, runtimeProfile: 'pi-ai.default' },
346
- philosopher: { enabled: true, runtimeProfile: 'pi-ai.default' },
347
- scribe: { enabled: true, runtimeProfile: 'pi-ai.default' },
348
- artificer: { enabled: true, runtimeProfile: 'pi-ai.default' },
349
- evaluator: { enabled: false, runtimeProfile: 'pi-ai.default' },
350
- },
351
- },
352
- };
353
- fs.writeFileSync(path.join(configDir, 'config.yaml'), yaml.dump(cfg), 'utf8');
354
- }
355
-
356
- function writeRefusedConfig(workspaceDir: string): void {
357
- // dreamer disabled → required agent missing → refused
358
- const configDir = path.join(workspaceDir, '.pd');
359
- fs.mkdirSync(configDir, { recursive: true });
360
- const cfg = {
361
- version: 1,
362
- features: {
363
- prompt: { category: 'core', enabled: true },
364
- code_tool_hook: { category: 'core', enabled: true },
365
- defer_archive: { category: 'core', enabled: true },
366
- code_rule_capability: { category: 'core', enabled: true },
367
- },
368
- workspace: { default: workspaceDir },
369
- runtimeProfiles: {
370
- 'pi-ai.default': { type: 'pi-ai', provider: 'anthropic', model: 'claude-sonnet', apiKeyEnv: 'ANTHROPIC_API_KEY' },
371
- },
372
- internalAgents: {
373
- defaultRuntime: 'pi-ai.default',
374
- agents: {
375
- dreamer: { enabled: false, runtimeProfile: 'pi-ai.default' },
376
- philosopher: { enabled: true, runtimeProfile: 'pi-ai.default' },
377
- scribe: { enabled: true, runtimeProfile: 'pi-ai.default' },
378
- artificer: { enabled: true, runtimeProfile: 'pi-ai.default' },
379
- evaluator: { enabled: true, runtimeProfile: 'pi-ai.default' },
380
- },
381
- },
382
- };
383
- fs.writeFileSync(path.join(configDir, 'config.yaml'), yaml.dump(cfg), 'utf8');
384
- }
385
-
386
- describe('handleRunRuleHost — PRI-461 readiness integration', () => {
387
- let workspaceDir: string;
388
- let savedEnv: NodeJS.ProcessEnv;
389
-
390
- beforeEach(() => {
391
- workspaceDir = mkTmpDir();
392
- savedEnv = { ...process.env };
393
- process.env.ANTHROPIC_API_KEY = 'sk-ant-test-key';
394
- });
395
-
396
- afterEach(() => {
397
- process.env = savedEnv;
398
- try { fs.rmSync(workspaceDir, { recursive: true, force: true }); } catch { /* ignore */ }
399
- });
400
-
401
- // ── ready ───────────────────────────────────────────────────────────────
402
-
403
- it('emits readiness=ready in --json dry-run when all agents and code-rule capability are ON', async () => {
404
- writeFullReadyConfig(workspaceDir);
405
- const { stdout, exitCode } = await captureStdio(() =>
406
- handleRunRuleHost({ painId: 'pain-1', dryRun: true, json: true, workspace: workspaceDir }),
407
- );
408
- const payload = parseJsonObject(stdout.trim());
409
- expect(payload.status).toBe('dry_run');
410
- expect(payload.readinessStatus).toBe('ready');
411
- const readiness = payload.readiness;
412
- expect(isRecord(readiness)).toBe(true);
413
- if (!isRecord(readiness)) {
414
- throw new Error('readiness is not a record');
415
- }
416
- expect(readiness.status).toBe('ready');
417
- expect(exitCode).toBeUndefined();
418
- });
419
-
420
- it('emits readiness=ready in plain-text dry-run output', async () => {
421
- writeFullReadyConfig(workspaceDir);
422
- const { stdout } = await captureStdio(() =>
423
- handleRunRuleHost({ painId: 'pain-1', dryRun: true, workspace: workspaceDir }),
424
- );
425
- expect(stdout).toMatch(/readiness:\s*READY/i);
426
- });
427
-
428
- // ── text_principle_only ─────────────────────────────────────────────────
429
-
430
- it('emits readiness=text_principle_only in --json dry-run when code_rule_capability is OFF', async () => {
431
- writeTextPrincipleOnlyConfig(workspaceDir);
432
- const { stdout, exitCode } = await captureStdio(() =>
433
- handleRunRuleHost({ painId: 'pain-1', dryRun: true, json: true, workspace: workspaceDir }),
434
- );
435
- const payload = parseJsonObject(stdout.trim());
436
- expect(payload.status).toBe('dry_run');
437
- expect(payload.readinessStatus).toBe('text_principle_only');
438
- const readiness = payload.readiness;
439
- expect(isRecord(readiness)).toBe(true);
440
- if (!isRecord(readiness)) {
441
- throw new Error('readiness is not a record');
442
- }
443
- expect(readiness.status).toBe('text_principle_only');
444
- expect(typeof readiness.reason).toBe('string');
445
- expect(typeof readiness.nextAction).toBe('string');
446
- expect(exitCode).toBeUndefined();
447
- });
448
-
449
- it('does not reclassify evaluator-disabled text_principle_only as runtime resolution failure', async () => {
450
- writeEvaluatorDisabledConfig(workspaceDir);
451
- const { stdout, exitCode } = await captureStdio(() =>
452
- handleRunRuleHost({ painId: 'pain-1', dryRun: true, json: true, workspace: workspaceDir }),
453
- );
454
- const payload = parseJsonObject(stdout.trim());
455
- expect(payload.status).toBe('dry_run');
456
- expect(payload.readinessStatus).toBe('text_principle_only');
457
- const readiness = payload.readiness;
458
- expect(isRecord(readiness)).toBe(true);
459
- if (!isRecord(readiness)) {
460
- throw new Error('readiness is not a record');
461
- }
462
- expect(readiness.status).toBe('text_principle_only');
463
- expect(String(readiness.reason)).toContain('evaluator');
464
- expect(String(payload.capabilityStatus)).toContain('evaluator');
465
- expect(exitCode).toBeUndefined();
466
- });
467
-
468
- it('emits readiness=text_principle_only in plain-text dry-run output', async () => {
469
- writeTextPrincipleOnlyConfig(workspaceDir);
470
- const { stdout } = await captureStdio(() =>
471
- handleRunRuleHost({ painId: 'pain-1', dryRun: true, workspace: workspaceDir }),
472
- );
473
- expect(stdout).toMatch(/readiness:\s*TEXT_PRINCIPLE_ONLY/i);
474
- });
475
-
476
- // ── refused ─────────────────────────────────────────────────────────────
477
-
478
- it('exits with code=1 and emits status=refused in --json when dreamer is disabled', async () => {
479
- writeRefusedConfig(workspaceDir);
480
- const { stdout, exitCode } = await captureStdio(() =>
481
- handleRunRuleHost({ painId: 'pain-1', dryRun: true, json: true, workspace: workspaceDir }),
482
- );
483
- const payload = parseJsonObject(stdout.trim());
484
- expect(payload.status).toBe('refused');
485
- expect(typeof payload.reason).toBe('string');
486
- expect(typeof payload.nextAction).toBe('string');
487
- expect(exitCode).toBe(1);
488
- });
489
-
490
- it('exits with code=1 and emits REFUSED in plain-text when dreamer is disabled', async () => {
491
- writeRefusedConfig(workspaceDir);
492
- const { stderr, exitCode } = await captureStdio(() =>
493
- handleRunRuleHost({ painId: 'pain-1', dryRun: true, workspace: workspaceDir }),
494
- );
495
- expect(stderr).toMatch(/REFUSED/i);
496
- expect(stderr).toMatch(/dreamer/i);
497
- expect(exitCode).toBe(1);
498
- });
499
-
500
- it('refused status includes the full readiness object in --json output', async () => {
501
- writeRefusedConfig(workspaceDir);
502
- const { stdout } = await captureStdio(() =>
503
- handleRunRuleHost({ painId: 'pain-1', dryRun: true, json: true, workspace: workspaceDir }),
504
- );
505
- const payload = parseJsonObject(stdout.trim());
506
- expect(payload.readiness).toBeDefined();
507
- const readiness = payload.readiness;
508
- expect(isRecord(readiness)).toBe(true);
509
- if (!isRecord(readiness)) {
510
- throw new Error('readiness is not a record');
511
- }
512
- expect(readiness.status).toBe('refused');
513
- expect(readiness.agentStatuses).toBeDefined();
514
- });
515
-
516
- it('refused status does NOT attempt pipeline execution or adapter construction', async () => {
517
- // If the handler tried to construct adapters with a disabled dreamer,
518
- // resolveRunRuleHostRuntime would throw. The readiness gate must prevent
519
- // that by exiting before resolveRunRuleHostRuntime is called.
520
- writeRefusedConfig(workspaceDir);
521
- const { stdout, exitCode } = await captureStdio(() =>
522
- handleRunRuleHost({ painId: 'pain-1', dryRun: true, json: true, workspace: workspaceDir }),
523
- );
524
- const payload = parseJsonObject(stdout.trim());
525
- // Must be 'refused', NOT 'failed' with 'agent_runtime_resolution_failed'
526
- expect(payload.status).toBe('refused');
527
- expect(payload.reason).not.toMatch(/agent_runtime_resolution_failed/);
528
- expect(exitCode).toBe(1);
529
- });
530
- });
531
-
532
- // ── PR #1122: behavior-examples fail-fast + v2-aware text output ──────────
533
- //
534
- // CodeRabbit PR2 Comment 1 (P1): when --behavior-examples is provided but the
535
- // file is missing or contains invalid JSON, the handler MUST return a
536
- // structured error immediately instead of silently degrading to
537
- // text_principle_only (rc-9-no-silent-fallback).
538
- //
539
- // CodeRabbit PR2 Comment 2 (P2): the text dry-run branch must use the same
540
- // v2-aware capabilityStatus source as the JSON branch (behaviorExamplesReason-
541
- // aware), not the stale resolvedRuntime.capabilityStatus.
542
- //
543
- // These tests require `rulecode_context_v2` enabled so the handler enters the
544
- // v2 path where --behavior-examples is honored.
545
-
546
- function writeContextV2EnabledConfig(workspaceDir: string): void {
547
- const configDir = path.join(workspaceDir, '.pd');
548
- fs.mkdirSync(configDir, { recursive: true });
549
- const cfg = {
550
- version: 1,
551
- features: {
552
- prompt: { category: 'core', enabled: true },
553
- code_tool_hook: { category: 'core', enabled: true },
554
- defer_archive: { category: 'core', enabled: true },
555
- code_rule_capability: { category: 'core', enabled: true },
556
- rulecode_context_v2: { category: 'core', enabled: true },
557
- },
558
- workspace: { default: workspaceDir },
559
- runtimeProfiles: {
560
- 'pi-ai.default': { type: 'pi-ai', provider: 'anthropic', model: 'claude-sonnet', apiKeyEnv: 'ANTHROPIC_API_KEY' },
561
- },
562
- internalAgents: {
563
- defaultRuntime: 'pi-ai.default',
564
- agents: {
565
- dreamer: { enabled: true, runtimeProfile: 'pi-ai.default' },
566
- philosopher: { enabled: true, runtimeProfile: 'pi-ai.default' },
567
- scribe: { enabled: true, runtimeProfile: 'pi-ai.default' },
568
- artificer: { enabled: true, runtimeProfile: 'pi-ai.default' },
569
- evaluator: { enabled: true, runtimeProfile: 'pi-ai.default' },
570
- },
571
- },
572
- };
573
- fs.writeFileSync(path.join(configDir, 'config.yaml'), yaml.dump(cfg), 'utf8');
574
- }
575
-
576
- function writeContextV2KillSwitchConfig(workspaceDir: string): void {
577
- const configDir = path.join(workspaceDir, '.pd');
578
- fs.mkdirSync(configDir, { recursive: true });
579
- const cfg = {
580
- version: 1,
581
- features: {
582
- prompt: { category: 'core', enabled: true },
583
- code_tool_hook: { category: 'core', enabled: true },
584
- defer_archive: { category: 'core', enabled: true },
585
- code_rule_capability: { category: 'core', enabled: true },
586
- // PRI-780: explicit kill switch (the flag itself defaults ON).
587
- rulecode_context_v2: { category: 'quiet', enabled: false },
588
- },
589
- workspace: { default: workspaceDir },
590
- runtimeProfiles: {
591
- 'pi-ai.default': { type: 'pi-ai', provider: 'anthropic', model: 'claude-sonnet', apiKeyEnv: 'ANTHROPIC_API_KEY' },
592
- },
593
- internalAgents: {
594
- defaultRuntime: 'pi-ai.default',
595
- agents: {
596
- dreamer: { enabled: true, runtimeProfile: 'pi-ai.default' },
597
- philosopher: { enabled: true, runtimeProfile: 'pi-ai.default' },
598
- scribe: { enabled: true, runtimeProfile: 'pi-ai.default' },
599
- artificer: { enabled: true, runtimeProfile: 'pi-ai.default' },
600
- evaluator: { enabled: true, runtimeProfile: 'pi-ai.default' },
601
- },
602
- },
603
- };
604
- fs.writeFileSync(path.join(configDir, 'config.yaml'), yaml.dump(cfg), 'utf8');
605
- }
606
-
607
- describe('handleRunRuleHost — PR #1122 behavior-examples fail-fast (CodeRabbit Comment 1+2)', () => {
608
- let workspaceDir: string;
609
- let savedEnv: NodeJS.ProcessEnv;
610
-
611
- beforeEach(() => {
612
- workspaceDir = mkTmpDir();
613
- savedEnv = { ...process.env };
614
- process.env.ANTHROPIC_API_KEY = 'sk-ant-test-key';
615
- });
616
-
617
- afterEach(() => {
618
- process.env = savedEnv;
619
- try { fs.rmSync(workspaceDir, { recursive: true, force: true }); } catch { /* ignore */ }
620
- });
621
-
622
- it('returns status=failed with behavior_examples_unreadable reason in --json mode when --behavior-examples file does not exist', async () => {
623
- writeContextV2EnabledConfig(workspaceDir);
624
- const missingPath = path.join(workspaceDir, 'nonexistent-examples.json');
625
- const { stdout, exitCode } = await captureStdio(() =>
626
- handleRunRuleHost({
627
- painId: 'pain-1',
628
- dryRun: true,
629
- json: true,
630
- workspace: workspaceDir,
631
- behaviorExamples: missingPath,
632
- }),
633
- );
634
- const payload = parseJsonObject(stdout.trim());
635
- expect(payload.status).toBe('failed');
636
- expect(typeof payload.reason).toBe('string');
637
- expect(payload.reason).toMatch(/^behavior_examples_unreadable:/);
638
- expect(typeof payload.nextAction).toBe('string');
639
- expect(exitCode).toBe(1);
640
- });
641
-
642
- it('returns status=failed with behavior_examples_invalid reason in --json mode when --behavior-examples file has invalid JSON shape', async () => {
643
- writeContextV2EnabledConfig(workspaceDir);
644
- const examplesPath = path.join(workspaceDir, 'bad-examples.json');
645
- // Valid JSON but missing required fields → behavior_examples_invalid: ...
646
- fs.writeFileSync(examplesPath, JSON.stringify({ foo: 'bar' }), 'utf8');
647
- const { stdout, exitCode } = await captureStdio(() =>
648
- handleRunRuleHost({
649
- painId: 'pain-1',
650
- dryRun: true,
651
- json: true,
652
- workspace: workspaceDir,
653
- behaviorExamples: examplesPath,
654
- }),
655
- );
656
- const payload = parseJsonObject(stdout.trim());
657
- expect(payload.status).toBe('failed');
658
- expect(payload.reason).toMatch(/^behavior_examples_invalid:/);
659
- expect(exitCode).toBe(1);
660
- });
661
-
662
- it('emits error on stderr in plain-text mode when --behavior-examples file does not exist', async () => {
663
- writeContextV2EnabledConfig(workspaceDir);
664
- const missingPath = path.join(workspaceDir, 'nonexistent-examples.json');
665
- const { stdout, stderr, exitCode } = await captureStdio(() =>
666
- handleRunRuleHost({
667
- painId: 'pain-1',
668
- dryRun: true,
669
- workspace: workspaceDir,
670
- behaviorExamples: missingPath,
671
- }),
672
- );
673
- expect(exitCode).toBe(1);
674
- expect(stderr).toMatch(/behavior_examples_unreadable:/);
675
- // Plain-text mode must NOT emit a JSON object on stdout.
676
- expect(stdout.trim()).toBe('');
677
- });
678
-
679
- it('text dry-run output uses v2-aware capabilityStatus when --behavior-examples is missing (CodeRabbit Comment 2)', async () => {
680
- // With contextV2Enabled=true and no --behavior-examples, the handler sets
681
- // behaviorExamplesReason='behavior_examples_missing'. The text dry-run
682
- // branch must derive capabilityStatus from the EFFECTIVE capability
683
- // (PRI-780 review M2), surfacing the reason — not the stale
684
- // resolvedRuntime.capabilityStatus ("ON").
685
- writeContextV2EnabledConfig(workspaceDir);
686
- const { stdout } = await captureStdio(() =>
687
- handleRunRuleHost({
688
- painId: 'pain-1',
689
- dryRun: true,
690
- workspace: workspaceDir,
691
- }),
692
- );
693
- expect(stdout).toMatch(/code_rule_capability: OFF \(behavior_examples_missing;/);
694
- expect(stdout).not.toMatch(/code_rule_capability: ON/);
695
- });
696
-
697
- it('PRI-780 M2: kill-switch dry-run reports OFF with the kill-switch reason, never ON', async () => {
698
- writeContextV2KillSwitchConfig(workspaceDir);
699
- const { stdout } = await captureStdio(() =>
700
- handleRunRuleHost({
701
- painId: 'pain-1',
702
- dryRun: true,
703
- workspace: workspaceDir,
704
- }),
705
- );
706
- expect(stdout).toMatch(/code_rule_capability: OFF \(rulecode_context_v2_disabled/);
707
- expect(stdout).not.toMatch(/code_rule_capability: ON/);
708
- // Codex review round 2 P2: the plain-text "Next" line must derive from the
709
- // EFFECTIVE capability too — confirmation cannot run the code-rule pipeline.
710
- expect(stdout).not.toMatch(/Next: pass --confirm to actually run the pipeline/);
711
- expect(stdout).toMatch(/Next: fix the code-rule capability issue above/);
712
- });
713
- });
714
-
715
- // ── PRI-657: production-identical gateDeps wiring (cli-7 real wiring) ──────
716
- //
717
- // The ArtificerL2Adapter's self-validation replay must use the SAME gate
718
- // semantics as the activation gate: createProductionGateDeps({toolSemantics,
719
- // projectDir}) resolved from the workspace host declaration (mirrors
720
- // internalization-consumer-cycle.ts). Previously it used createSandboxGateDeps()
721
- // with no workspace semantics — rules validated against a different tool
722
- // vocabulary than the one they will be activated under.
723
- // These tests drive the REAL handler (confirm path) and assert the constructor
724
- // options the command actually passes (EP-02/EP-04). On resolver failure the
725
- // command degrades observably to the baseline gate (rc-9: structured reason +
726
- // nextAction on stderr) while stdout keeps exactly one JSON object (cli-1).
727
- // NOTE: vitest hoists the vi.mock calls file-wide, so the stubs below also
728
- // apply to the other describes in this file — safe today because none of them
729
- // reach the adapter/pipeline paths; a future test needing the real
730
- // ArtificerL2Adapter or runRuleHostPipeline must live in its own file.
731
-
732
- const hoisted657 = vi.hoisted(() => {
733
- const artificerL2Calls: unknown[] = [];
734
- const gateDepsSentinel = { kind: 'production-gate-deps-stub' };
735
- return {
736
- artificerL2Calls,
737
- gateDepsSentinel,
738
- mockResolveWorkspaceHostToolSemantics: vi.fn(() => ({
739
- ok: false,
740
- reason: 'no_host_declaration: test default (no persisted declaration)',
741
- nextAction: 'test default — assert the baseline-gate degradation path',
742
- })),
743
- mockCreateProductionGateDeps: vi.fn(() => gateDepsSentinel),
744
- mockCreateSandboxGateDeps: vi.fn(() => ({ kind: 'sandbox-gate-deps-stub' })),
745
- mockRunRuleHostPipeline: vi.fn(),
746
- };
747
- });
748
-
749
- vi.mock('@principles/core/runtime-v2', async (importOriginal) => {
750
- const original = await importOriginal<typeof import('@principles/core/runtime-v2')>();
751
- class MockArtificerL2Adapter {
752
- constructor(options: unknown) {
753
- hoisted657.artificerL2Calls.push(options);
754
- }
755
- }
756
- return {
757
- ...original,
758
- ArtificerL2Adapter: MockArtificerL2Adapter,
759
- createProductionGateDeps: hoisted657.mockCreateProductionGateDeps,
760
- };
761
- });
762
-
763
- vi.mock('@principles/host-runtime', async (importOriginal) => {
764
- const original = await importOriginal<typeof import('@principles/host-runtime')>();
765
- return {
766
- ...original,
767
- resolveWorkspaceHostToolSemantics: hoisted657.mockResolveWorkspaceHostToolSemantics,
768
- WorkspaceTelemetryEmitter: class MockWorkspaceTelemetryEmitter {
769
- constructor(_emitter: unknown, _workspaceDir: unknown, _onError: unknown) { /* no-op */ }
770
- },
771
- };
772
- });
773
-
774
- vi.mock('../../src/services/rulehost-pipeline-runner.js', async (importOriginal) => {
775
- const original = await importOriginal<typeof import('../../src/services/rulehost-pipeline-runner.js')>();
776
- return {
777
- ...original,
778
- runRuleHostPipeline: hoisted657.mockRunRuleHostPipeline,
779
- createSandboxGateDeps: hoisted657.mockCreateSandboxGateDeps,
780
- };
781
- });
782
-
783
- describe('handleRunRuleHost — PRI-657 production-identical gateDeps wiring', () => {
784
- let workspaceDir: string;
785
- let savedEnv: NodeJS.ProcessEnv;
786
-
787
- const fakeRegistry = { resolve: vi.fn(), hostMappings: vi.fn().mockReturnValue([]) };
788
- const pipelineReadyResult = {
789
- decision: 'candidate_ready_for_owner_review',
790
- painId: 'pain-1',
791
- stages: [],
792
- scribeTaskId: 'scribe-1',
793
- ruleArtifactId: 'pi-rule-1' as string | null,
794
- principleArtifactId: null as string | null,
795
- approvalId: 'apr-1' as string | null,
796
- degradationReason: null as string | null,
797
- };
798
-
799
- beforeEach(() => {
800
- vi.clearAllMocks();
801
- hoisted657.artificerL2Calls.length = 0;
802
- workspaceDir = mkTmpDir();
803
- writeFullReadyConfig(workspaceDir);
804
- savedEnv = { ...process.env };
805
- process.env.ANTHROPIC_API_KEY = 'sk-ant-test-key';
806
- hoisted657.mockRunRuleHostPipeline.mockResolvedValue(pipelineReadyResult);
807
- });
808
-
809
- afterEach(() => {
810
- process.env = savedEnv;
811
- try { fs.rmSync(workspaceDir, { recursive: true, force: true }); } catch { /* ignore */ }
812
- });
813
-
814
- function firstArtificerL2Options(): Record<string, unknown> {
815
- expect(hoisted657.artificerL2Calls).toHaveLength(1);
816
- const options = hoisted657.artificerL2Calls[0];
817
- if (!isRecord(options)) throw new Error('ArtificerL2Adapter options are not a record');
818
- return options;
819
- }
820
-
821
- it('wires the workspace host-tool-semantics registry + projectDir into ArtificerL2 gateDeps (production parity)', async () => {
822
- hoisted657.mockResolveWorkspaceHostToolSemantics.mockReturnValue({ ok: true, registry: fakeRegistry, hostKinds: ['codex'] });
823
-
824
- const { stdout, exitCode } = await captureStdio(() =>
825
- handleRunRuleHost({ painId: 'pain-1', confirm: true, json: true, workspace: workspaceDir }),
826
- );
827
-
828
- expect(hoisted657.mockResolveWorkspaceHostToolSemantics).toHaveBeenCalledWith(workspaceDir);
829
- expect(hoisted657.mockCreateProductionGateDeps).toHaveBeenCalledWith({ toolSemantics: fakeRegistry, projectDir: workspaceDir });
830
- expect(hoisted657.mockCreateSandboxGateDeps).not.toHaveBeenCalled();
831
- expect(firstArtificerL2Options().gateDeps).toBe(hoisted657.gateDepsSentinel);
832
-
833
- // cli-1: stdout stays exactly one parseable JSON result.
834
- const payload = parseJsonObject(stdout.trim());
835
- expect(payload.status).toBe('candidate_ready_for_owner_review');
836
- expect(exitCode).toBeUndefined();
837
- });
838
-
839
- it('degrades observably to the baseline gate when workspace host semantics are unresolvable (rc-9 + cli-1)', async () => {
840
- hoisted657.mockResolveWorkspaceHostToolSemantics.mockReturnValue({
841
- ok: false,
842
- reason: 'no_host_declaration: no persisted host tool declaration for this workspace',
843
- nextAction: 'run `pd runtime host-declare` (or activate via a host) then re-run',
844
- });
845
-
846
- const { stdout, stderr, exitCode } = await captureStdio(() =>
847
- handleRunRuleHost({ painId: 'pain-1', confirm: true, json: true, workspace: workspaceDir }),
848
- );
849
-
850
- // Baseline gate: createProductionGateDeps with NO options (the registry is
851
- // absent, so a wrong-host vocabulary must not be guessed).
852
- expect(hoisted657.mockCreateProductionGateDeps).toHaveBeenCalledWith();
853
- expect(hoisted657.mockCreateSandboxGateDeps).not.toHaveBeenCalled();
854
- expect(firstArtificerL2Options().gateDeps).toBe(hoisted657.gateDepsSentinel);
855
-
856
- // rc-9: the degradation carries reason + nextAction on stderr.
857
- expect(stderr).toContain('no_host_declaration');
858
- expect(stderr).toContain('host-declare');
859
-
860
- // cli-1: stderr noise must not leak into the machine-readable stdout.
861
- const payload = parseJsonObject(stdout.trim());
862
- expect(payload.status).toBe('candidate_ready_for_owner_review');
863
- expect(exitCode).toBeUndefined();
864
- });
865
- });
866
-
867
- // ── Owner Decision v1 review fix (Codex P1): identity-gated publication ─────
868
-
869
- describe('describePublicationOutcome — identity-gated refusal reporting (Codex P1)', () => {
870
- const baseResult = {
871
- decision: 'candidate_ready_for_owner_review' as const,
872
- painId: 'pain-1',
873
- stages: [],
874
- scribeTaskId: 'scribe-1',
875
- ruleArtifactId: 'pi-rule-1' as string | null,
876
- principleArtifactId: null as string | null,
877
- approvalId: null as string | null,
878
- degradationReason: null as string | null,
879
- };
880
-
881
- it('flags the identity-blocked state and provides a repair nextAction', async () => {
882
- const { describePublicationOutcome } = await import('../../src/commands/runtime-internalization-run-rulehost.js');
883
- const outcome = describePublicationOutcome({
884
- ...baseResult,
885
- degradationReason: 'identity_binding_unverified: ledger_missing. Rule artifact NOT enqueued for Owner review (governance publication boundary).',
886
- });
887
- expect(outcome.blocked).toBe(true);
888
- expect(outcome.nextAction).toContain('NOT enqueued');
889
- expect(outcome.nextAction).toContain('re-run');
890
- });
891
-
892
- it('does not flag a healthy ready result with a real approval id', async () => {
893
- const { describePublicationOutcome } = await import('../../src/commands/runtime-internalization-run-rulehost.js');
894
- const outcome = describePublicationOutcome({ ...baseResult, approvalId: 'apr-1' });
895
- expect(outcome.blocked).toBe(false);
896
- });
897
-
898
- it('text output for the identity-blocked result never claims WAITING for owner review', async () => {
899
- const { formatTextOutput } = await import('../../src/commands/runtime-internalization-run-rulehost.js');
900
- const text = formatTextOutput({
901
- ...baseResult,
902
- degradationReason: 'identity_binding_unverified: ledger_missing. Rule artifact NOT enqueued for Owner review (governance publication boundary).',
903
- });
904
- expect(text).toContain('PUBLICATION REFUSED');
905
- expect(text).not.toContain('WAITING for owner review');
906
- expect(text).toContain('NOT enqueued for Owner review');
907
- });
908
- });