@principles/pd-cli 1.152.12 → 1.152.14

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 (305) hide show
  1. package/dist/commands/candidate.d.ts.map +1 -1
  2. package/dist/commands/candidate.js +34 -7
  3. package/dist/commands/candidate.js.map +1 -1
  4. package/dist/commands/diagnose.d.ts.map +1 -1
  5. package/dist/commands/diagnose.js +23 -7
  6. package/dist/commands/diagnose.js.map +1 -1
  7. package/dist/commands/pain-retry.d.ts.map +1 -1
  8. package/dist/commands/pain-retry.js +21 -7
  9. package/dist/commands/pain-retry.js.map +1 -1
  10. package/package.json +13 -7
  11. package/CHANGELOG.md +0 -23
  12. package/dist/commands/__tests__/intent-flag-wiring.test.d.ts +0 -9
  13. package/dist/commands/__tests__/intent-flag-wiring.test.d.ts.map +0 -1
  14. package/dist/commands/__tests__/intent-flag-wiring.test.js +0 -237
  15. package/dist/commands/__tests__/intent-flag-wiring.test.js.map +0 -1
  16. package/dist/commands/__tests__/legacy-cleanup.test.d.ts +0 -18
  17. package/dist/commands/__tests__/legacy-cleanup.test.d.ts.map +0 -1
  18. package/dist/commands/__tests__/legacy-cleanup.test.js +0 -467
  19. package/dist/commands/__tests__/legacy-cleanup.test.js.map +0 -1
  20. package/dist/commands/__tests__/mvp-smoke.test.d.ts +0 -15
  21. package/dist/commands/__tests__/mvp-smoke.test.d.ts.map +0 -1
  22. package/dist/commands/__tests__/mvp-smoke.test.js +0 -262
  23. package/dist/commands/__tests__/mvp-smoke.test.js.map +0 -1
  24. package/dist/commands/__tests__/pain-retry-maxTokens-flag.test.d.ts +0 -2
  25. package/dist/commands/__tests__/pain-retry-maxTokens-flag.test.d.ts.map +0 -1
  26. package/dist/commands/__tests__/pain-retry-maxTokens-flag.test.js +0 -60
  27. package/dist/commands/__tests__/pain-retry-maxTokens-flag.test.js.map +0 -1
  28. package/dist/commands/__tests__/rulecode-flag-wiring.test.d.ts +0 -21
  29. package/dist/commands/__tests__/rulecode-flag-wiring.test.d.ts.map +0 -1
  30. package/dist/commands/__tests__/rulecode-flag-wiring.test.js +0 -186
  31. package/dist/commands/__tests__/rulecode-flag-wiring.test.js.map +0 -1
  32. package/dist/commands/__tests__/rulecode-handler.test.d.ts +0 -16
  33. package/dist/commands/__tests__/rulecode-handler.test.d.ts.map +0 -1
  34. package/dist/commands/__tests__/rulecode-handler.test.js +0 -285
  35. package/dist/commands/__tests__/rulecode-handler.test.js.map +0 -1
  36. package/dist/commands/__tests__/run-rulehost-flag-wiring.test.d.ts +0 -24
  37. package/dist/commands/__tests__/run-rulehost-flag-wiring.test.d.ts.map +0 -1
  38. package/dist/commands/__tests__/run-rulehost-flag-wiring.test.js +0 -232
  39. package/dist/commands/__tests__/run-rulehost-flag-wiring.test.js.map +0 -1
  40. package/dist/commands/__tests__/runtime-activation-nextaction.test.d.ts +0 -15
  41. package/dist/commands/__tests__/runtime-activation-nextaction.test.d.ts.map +0 -1
  42. package/dist/commands/__tests__/runtime-activation-nextaction.test.js +0 -73
  43. package/dist/commands/__tests__/runtime-activation-nextaction.test.js.map +0 -1
  44. package/dist/commands/__tests__/runtime-probe-config.test.d.ts +0 -20
  45. package/dist/commands/__tests__/runtime-probe-config.test.d.ts.map +0 -1
  46. package/dist/commands/__tests__/runtime-probe-config.test.js +0 -389
  47. package/dist/commands/__tests__/runtime-probe-config.test.js.map +0 -1
  48. package/dist/commands/__tests__/telemetry-flag-wiring.test.d.ts +0 -9
  49. package/dist/commands/__tests__/telemetry-flag-wiring.test.d.ts.map +0 -1
  50. package/dist/commands/__tests__/telemetry-flag-wiring.test.js +0 -76
  51. package/dist/commands/__tests__/telemetry-flag-wiring.test.js.map +0 -1
  52. package/dist/commands/__tests__/version.test.d.ts +0 -2
  53. package/dist/commands/__tests__/version.test.d.ts.map +0 -1
  54. package/dist/commands/__tests__/version.test.js +0 -238
  55. package/dist/commands/__tests__/version.test.js.map +0 -1
  56. package/dist/commands/runtime-uat.guard.test.d.ts +0 -2
  57. package/dist/commands/runtime-uat.guard.test.d.ts.map +0 -1
  58. package/dist/commands/runtime-uat.guard.test.js +0 -153
  59. package/dist/commands/runtime-uat.guard.test.js.map +0 -1
  60. package/dist/services/__tests__/cli-output.test.d.ts +0 -18
  61. package/dist/services/__tests__/cli-output.test.d.ts.map +0 -1
  62. package/dist/services/__tests__/cli-output.test.js +0 -103
  63. package/dist/services/__tests__/cli-output.test.js.map +0 -1
  64. package/dist/services/__tests__/evaluator-runner-deps.test.d.ts +0 -2
  65. package/dist/services/__tests__/evaluator-runner-deps.test.d.ts.map +0 -1
  66. package/dist/services/__tests__/evaluator-runner-deps.test.js +0 -343
  67. package/dist/services/__tests__/evaluator-runner-deps.test.js.map +0 -1
  68. package/dist/services/__tests__/rulehost-readiness.test.d.ts +0 -2
  69. package/dist/services/__tests__/rulehost-readiness.test.d.ts.map +0 -1
  70. package/dist/services/__tests__/rulehost-readiness.test.js +0 -311
  71. package/dist/services/__tests__/rulehost-readiness.test.js.map +0 -1
  72. package/dist/services/__tests__/runtime-adapter-resolver.test.d.ts +0 -18
  73. package/dist/services/__tests__/runtime-adapter-resolver.test.d.ts.map +0 -1
  74. package/dist/services/__tests__/runtime-adapter-resolver.test.js +0 -673
  75. package/dist/services/__tests__/runtime-adapter-resolver.test.js.map +0 -1
  76. package/dist/utils/production-workspace-guard.test.d.ts +0 -2
  77. package/dist/utils/production-workspace-guard.test.d.ts.map +0 -1
  78. package/dist/utils/production-workspace-guard.test.js +0 -137
  79. package/dist/utils/production-workspace-guard.test.js.map +0 -1
  80. package/scripts/llm-dogfood.ts +0 -456
  81. package/scripts/migrate-illegal-expected-decision.ts +0 -252
  82. package/src/commands/__tests__/intent-flag-wiring.test.ts +0 -282
  83. package/src/commands/__tests__/legacy-cleanup.test.ts +0 -602
  84. package/src/commands/__tests__/mvp-smoke.test.ts +0 -300
  85. package/src/commands/__tests__/pain-retry-maxTokens-flag.test.ts +0 -73
  86. package/src/commands/__tests__/rulecode-flag-wiring.test.ts +0 -237
  87. package/src/commands/__tests__/rulecode-handler.test.ts +0 -369
  88. package/src/commands/__tests__/run-rulehost-flag-wiring.test.ts +0 -292
  89. package/src/commands/__tests__/runtime-activation-nextaction.test.ts +0 -81
  90. package/src/commands/__tests__/runtime-probe-config.test.ts +0 -432
  91. package/src/commands/__tests__/telemetry-flag-wiring.test.ts +0 -84
  92. package/src/commands/__tests__/version.test.ts +0 -251
  93. package/src/commands/admission-gate.ts +0 -30
  94. package/src/commands/artifact.ts +0 -82
  95. package/src/commands/build-trajectory-evidence.ts +0 -298
  96. package/src/commands/candidate.ts +0 -1250
  97. package/src/commands/codex-ingest-catchup.ts +0 -114
  98. package/src/commands/codex-ingest-quarantine.ts +0 -127
  99. package/src/commands/codex-reconcile.ts +0 -84
  100. package/src/commands/codex-setup.ts +0 -476
  101. package/src/commands/codex-worker.ts +0 -185
  102. package/src/commands/command-helpers.ts +0 -24
  103. package/src/commands/config-doctor.ts +0 -193
  104. package/src/commands/console.ts +0 -797
  105. package/src/commands/context.ts +0 -72
  106. package/src/commands/demo-story-a.ts +0 -241
  107. package/src/commands/diagnose.ts +0 -756
  108. package/src/commands/errors-list.ts +0 -441
  109. package/src/commands/evolution-tasks-list.ts +0 -48
  110. package/src/commands/evolution-tasks-show.ts +0 -62
  111. package/src/commands/flow.ts +0 -60
  112. package/src/commands/health-codex.ts +0 -576
  113. package/src/commands/health.ts +0 -315
  114. package/src/commands/history.ts +0 -63
  115. package/src/commands/intent.ts +0 -457
  116. package/src/commands/legacy-cleanup.ts +0 -531
  117. package/src/commands/legacy-import.ts +0 -104
  118. package/src/commands/mvp-smoke.ts +0 -160
  119. package/src/commands/pain-evidence.ts +0 -226
  120. package/src/commands/pain-list.ts +0 -239
  121. package/src/commands/pain-record.ts +0 -612
  122. package/src/commands/pain-retry.ts +0 -916
  123. package/src/commands/principles-stats.ts +0 -700
  124. package/src/commands/proven-channel-baseline.ts +0 -115
  125. package/src/commands/quality-scorecard.ts +0 -272
  126. package/src/commands/remediation-output.ts +0 -66
  127. package/src/commands/rulecode.ts +0 -465
  128. package/src/commands/run.ts +0 -89
  129. package/src/commands/runtime-activation.ts +0 -1629
  130. package/src/commands/runtime-artifact-repair.ts +0 -524
  131. package/src/commands/runtime-canary.ts +0 -395
  132. package/src/commands/runtime-compatibility-scan.ts +0 -105
  133. package/src/commands/runtime-diagnostics-export.ts +0 -229
  134. package/src/commands/runtime-features.ts +0 -153
  135. package/src/commands/runtime-gfi-snapshot.ts +0 -135
  136. package/src/commands/runtime-health-snapshot.ts +0 -108
  137. package/src/commands/runtime-init.ts +0 -429
  138. package/src/commands/runtime-internalization-enqueue-successors.ts +0 -530
  139. package/src/commands/runtime-internalization-integrity-repair.ts +0 -79
  140. package/src/commands/runtime-internalization-integrity.ts +0 -107
  141. package/src/commands/runtime-internalization-queue.ts +0 -135
  142. package/src/commands/runtime-internalization-retry.ts +0 -191
  143. package/src/commands/runtime-internalization-run-once.ts +0 -791
  144. package/src/commands/runtime-internalization-run-rulehost.ts +0 -749
  145. package/src/commands/runtime-internalization-wake-once.ts +0 -87
  146. package/src/commands/runtime-pain-flood-simulation.ts +0 -121
  147. package/src/commands/runtime-pruning.ts +0 -438
  148. package/src/commands/runtime-recovery-failed-tasks.ts +0 -258
  149. package/src/commands/runtime-recovery.ts +0 -109
  150. package/src/commands/runtime-synthetic-baseline.ts +0 -70
  151. package/src/commands/runtime-uat.guard.test.ts +0 -175
  152. package/src/commands/runtime-uat.ts +0 -380
  153. package/src/commands/runtime.ts +0 -473
  154. package/src/commands/samples-list.ts +0 -39
  155. package/src/commands/samples-review.ts +0 -36
  156. package/src/commands/task.ts +0 -271
  157. package/src/commands/telemetry.ts +0 -349
  158. package/src/commands/trace.ts +0 -174
  159. package/src/commands/trajectory-db-unavailable.ts +0 -19
  160. package/src/commands/trajectory.ts +0 -64
  161. package/src/commands/version.ts +0 -49
  162. package/src/config-reader.ts +0 -122
  163. package/src/index.ts +0 -1276
  164. package/src/legacy/legacy-import.ts +0 -179
  165. package/src/legacy/session-history-import.ts +0 -203
  166. package/src/resolve-workspace.ts +0 -106
  167. package/src/services/__tests__/cli-output.test.ts +0 -130
  168. package/src/services/__tests__/evaluator-runner-deps.test.ts +0 -382
  169. package/src/services/__tests__/rulehost-readiness.test.ts +0 -363
  170. package/src/services/__tests__/runtime-adapter-resolver.test.ts +0 -793
  171. package/src/services/cli-output.ts +0 -95
  172. package/src/services/config-doctor.ts +0 -697
  173. package/src/services/console-launcher.ts +0 -537
  174. package/src/services/demo-rule-compiler.ts +0 -40
  175. package/src/services/demo-story-a-runner.ts +0 -471
  176. package/src/services/mainline-snapshot-assembler.ts +0 -579
  177. package/src/services/pain-flood-simulation-runner.ts +0 -462
  178. package/src/services/pd-config-loader.ts +0 -433
  179. package/src/services/proven-channel-baseline-runner.ts +0 -157
  180. package/src/services/quality-scorecard/data-extractor.ts +0 -150
  181. package/src/services/quality-scorecard/local-evaluator.ts +0 -142
  182. package/src/services/quality-scorecard/strong-model-gate.ts +0 -202
  183. package/src/services/resolve-runtime-from-pd-config.ts +0 -230
  184. package/src/services/rulehost-pipeline-runner.ts +0 -1214
  185. package/src/services/rulehost-readiness.ts +0 -326
  186. package/src/services/runtime-adapter-resolver.ts +0 -364
  187. package/src/services/synthetic-baseline-runner.ts +0 -400
  188. package/src/services/version-report.ts +0 -253
  189. package/src/services/workspace-tool-semantics.ts +0 -26
  190. package/src/utils/path-security.ts +0 -96
  191. package/src/utils/production-workspace-guard.test.ts +0 -157
  192. package/src/utils/production-workspace-guard.ts +0 -210
  193. package/tests/bdd/cli-contract.steps.ts +0 -346
  194. package/tests/bdd/principles-stats.steps.ts +0 -211
  195. package/tests/bdd/support/gherkin-loader.ts +0 -147
  196. package/tests/bdd/support/repo-root.ts +0 -62
  197. package/tests/bdd/support/vitest-bdd.ts +0 -179
  198. package/tests/commands/admission-gate-coverage.test.ts +0 -79
  199. package/tests/commands/build-trajectory-evidence.test.ts +0 -508
  200. package/tests/commands/candidate-audit-repair.test.ts +0 -421
  201. package/tests/commands/candidate-intake.test.ts +0 -732
  202. package/tests/commands/candidate-internalization-backfill.test.ts +0 -548
  203. package/tests/commands/candidate-internalize-lineage.test.ts +0 -628
  204. package/tests/commands/candidate-internalize.test.ts +0 -299
  205. package/tests/commands/candidate-route.test.ts +0 -329
  206. package/tests/commands/candidate-show.test.ts +0 -95
  207. package/tests/commands/cli-command-tree.test.ts +0 -144
  208. package/tests/commands/cli-help-snapshot.test.ts +0 -155
  209. package/tests/commands/cli-skill-contract.test.ts +0 -121
  210. package/tests/commands/codex-consent-reversibility.steps.test.ts +0 -299
  211. package/tests/commands/codex-ingest-quarantine.test.ts +0 -136
  212. package/tests/commands/codex-setup.test.ts +0 -297
  213. package/tests/commands/codex-worker-daemon.test.ts +0 -95
  214. package/tests/commands/codex-worker-registration.test.ts +0 -207
  215. package/tests/commands/config-doctor.test.ts +0 -336
  216. package/tests/commands/console-launcher-edge-cases.test.ts +0 -388
  217. package/tests/commands/console-open.test.ts +0 -1381
  218. package/tests/commands/context.test.ts +0 -114
  219. package/tests/commands/demo-story-a.test.ts +0 -318
  220. package/tests/commands/diagnose.test.ts +0 -1803
  221. package/tests/commands/errors-list.test.ts +0 -679
  222. package/tests/commands/evolution-tasks-list.test.ts +0 -41
  223. package/tests/commands/evolution-tasks-show.test.ts +0 -46
  224. package/tests/commands/health-codex.test.ts +0 -349
  225. package/tests/commands/health-host-wiring.test.ts +0 -76
  226. package/tests/commands/health-reliability.test.ts +0 -99
  227. package/tests/commands/health.test.ts +0 -413
  228. package/tests/commands/intent.test.ts +0 -321
  229. package/tests/commands/legacy-cleanup.test.ts +0 -148
  230. package/tests/commands/pain-evidence.test.ts +0 -518
  231. package/tests/commands/pain-list.test.ts +0 -219
  232. package/tests/commands/pain-record-async.test.ts +0 -335
  233. package/tests/commands/pain-record-session-parser.test.ts +0 -228
  234. package/tests/commands/pain-record.test.ts +0 -851
  235. package/tests/commands/pain-retry.test.ts +0 -1121
  236. package/tests/commands/plugin-config-resolution-cutover.test.ts +0 -229
  237. package/tests/commands/pri-393-runtime-config-unification.test.ts +0 -443
  238. package/tests/commands/principles-stats-wiring.test.ts +0 -135
  239. package/tests/commands/principles-stats.test.ts +0 -274
  240. package/tests/commands/product-path-regression.test.ts +0 -86
  241. package/tests/commands/proven-channel-baseline.test.ts +0 -441
  242. package/tests/commands/rulecode.test.ts +0 -177
  243. package/tests/commands/run-rulehost-handler.test.ts +0 -908
  244. package/tests/commands/runtime-activation-approve-flag-wiring.test.ts +0 -227
  245. package/tests/commands/runtime-activation-deactivate-flag-wiring.test.ts +0 -167
  246. package/tests/commands/runtime-activation-dispatch-flag-wiring.test.ts +0 -262
  247. package/tests/commands/runtime-activation-governance-audit.test.ts +0 -95
  248. package/tests/commands/runtime-activation-list-flag-wiring.test.ts +0 -193
  249. package/tests/commands/runtime-activation-promote-flag-wiring.test.ts +0 -248
  250. package/tests/commands/runtime-activation-shadow-telemetry.test.ts +0 -130
  251. package/tests/commands/runtime-activation.test.ts +0 -2052
  252. package/tests/commands/runtime-artifact-repair-registration.test.ts +0 -74
  253. package/tests/commands/runtime-artifact-repair.test.ts +0 -404
  254. package/tests/commands/runtime-canary.test.ts +0 -430
  255. package/tests/commands/runtime-compatibility-scan.test.ts +0 -146
  256. package/tests/commands/runtime-diagnostics-export.test.ts +0 -175
  257. package/tests/commands/runtime-features.test.ts +0 -249
  258. package/tests/commands/runtime-health-snapshot.test.ts +0 -358
  259. package/tests/commands/runtime-init-empty-workspace.test.ts +0 -252
  260. package/tests/commands/runtime-init.test.ts +0 -420
  261. package/tests/commands/runtime-internalization-enqueue-successors.test.ts +0 -782
  262. package/tests/commands/runtime-internalization-integrity-repair.test.ts +0 -239
  263. package/tests/commands/runtime-internalization-integrity.test.ts +0 -140
  264. package/tests/commands/runtime-internalization-queue.test.ts +0 -380
  265. package/tests/commands/runtime-internalization-retry-owner-authority.test.ts +0 -431
  266. package/tests/commands/runtime-internalization-run-once-evaluator-parity.test.ts +0 -269
  267. package/tests/commands/runtime-internalization-run-once-language.test.ts +0 -303
  268. package/tests/commands/runtime-internalization-run-once-real-config.test.ts +0 -237
  269. package/tests/commands/runtime-internalization-run-once-rollout-parity.test.ts +0 -706
  270. package/tests/commands/runtime-internalization-run-once.test.ts +0 -1791
  271. package/tests/commands/runtime-internalization-wake-once.test.ts +0 -171
  272. package/tests/commands/runtime-internalization.test.ts +0 -53
  273. package/tests/commands/runtime-pain-flood-simulation.test.ts +0 -418
  274. package/tests/commands/runtime-pruning.test.ts +0 -694
  275. package/tests/commands/runtime-recovery-failed-tasks.test.ts +0 -328
  276. package/tests/commands/runtime-recovery.test.ts +0 -120
  277. package/tests/commands/runtime-synthetic-baseline.test.ts +0 -249
  278. package/tests/commands/runtime-uat.test.ts +0 -397
  279. package/tests/commands/runtime.test.ts +0 -392
  280. package/tests/commands/samples-list.test.ts +0 -43
  281. package/tests/commands/samples-review.test.ts +0 -41
  282. package/tests/commands/task.test.ts +0 -153
  283. package/tests/commands/telemetry.test.ts +0 -190
  284. package/tests/commands/trace.test.ts +0 -316
  285. package/tests/config-reader.test.ts +0 -143
  286. package/tests/e2e/candidate-intake-e2e.test.ts +0 -338
  287. package/tests/e2e/cli-full-flow.test.ts +0 -233
  288. package/tests/e2e/cross-package-acceptance.test.ts +0 -635
  289. package/tests/helpers/pd-cli-path.ts +0 -5
  290. package/tests/pd-cli-smoke.test.ts +0 -13
  291. package/tests/resolve-workspace.test.ts +0 -196
  292. package/tests/services/config-doctor-signal-health.test.ts +0 -109
  293. package/tests/services/console-launcher.test.ts +0 -114
  294. package/tests/services/demo-rule-compiler.test.ts +0 -242
  295. package/tests/services/mainline-snapshot-assembler.test.ts +0 -572
  296. package/tests/services/pd-config-loader.test.ts +0 -505
  297. package/tests/services/proven-channel-baseline-runner.test.ts +0 -30
  298. package/tests/services/quality-scorecard/strong-model-gate.test.ts +0 -133
  299. package/tests/services/resolve-runtime-from-pd-config.test.ts +0 -485
  300. package/tests/services/rulehost-pipeline-e2e.test.ts +0 -538
  301. package/tests/services/rulehost-pipeline-runner.test.ts +0 -1242
  302. package/tests/services/workspace-tool-semantics.test.ts +0 -76
  303. package/tests/utils/path-security.test.ts +0 -180
  304. package/tsconfig.json +0 -26
  305. package/vitest.config.ts +0 -10
@@ -1,749 +0,0 @@
1
- /**
2
- * Command handler: `pd runtime internalization run-rulehost`
3
- *
4
- * Drives a pain signal all the way to a validated rule artifact in one call:
5
- * pain → dreamer → philosopher → scribe → artificer↔evaluator adversarial loop
6
- *
7
- * This is the production entry point for the code_tool_hook channel. It wraps
8
- * runRuleHostPipeline (the service) and constructs the PiAi runtime adapter
9
- * from .pd/config.yaml (same resolution path as run-once).
10
- *
11
- * Atomic capability (per user correction 2026-06-18):
12
- * ArtificerL2 + Evaluator are atomic — both must run or neither runs.
13
- * The CLI resolves per-agent config (enabled/runtimeProfile) for artificer
14
- * and evaluator. When both are enabled, it constructs the ArtificerL2Adapter
15
- * via buildArtificerL2GenerateCode and passes CodeRuleCapability.enabled=true.
16
- * When either is disabled, it passes CodeRuleCapability.enabled=false with a
17
- * structured reason, and the pipeline degrades to text-principle-only.
18
- *
19
- * CLI gate compliance:
20
- * - --json mode emits exactly one JSON object on stdout
21
- * - exit paths return after setting process.exitCode (no fall-through)
22
- * - failure paths include a structured reason + next action
23
- * - --dry-run is default; --confirm required for mutation
24
- * - --dry-run and --confirm are mutually exclusive
25
- */
26
- import * as path from 'path';
27
- import * as fs from 'node:fs';
28
- import type { Command } from 'commander';
29
- import { runRuleHostPipeline } from '../services/rulehost-pipeline-runner.js';
30
- import type { RuleHostPipelineResult, CodeRuleCapability, RuleHostAgentAdapters } from '../services/rulehost-pipeline-runner.js';
31
- import {
32
- PiAiRuntimeAdapter,
33
- ArtificerL2Adapter,
34
- DefaultArtificerValidator,
35
- createProductionGateDeps,
36
- resolveAgentRuntimeBinding,
37
- computeFeatureFlagsFromConfig,
38
- isFeatureEnabled,
39
- } from '@principles/core/runtime-v2';
40
- import type { EffectivePdConfig, InternalAgentName, PDRuntimeAdapter } from '@principles/core/runtime-v2';
41
- import type { BehaviorExamplePack } from '@principles/core/runtime-v2';
42
- import { storeEmitter } from '@principles/core/runtime-v2';
43
- import { WorkspaceTelemetryEmitter, resolveWorkspaceHostToolSemantics } from '@principles/host-runtime';
44
- import { resolveRuntimeFromPdConfig } from '../services/resolve-runtime-from-pd-config.js';
45
- import { resolveRuleHostReadiness } from '../services/rulehost-readiness.js';
46
- import type { RuleHostReadinessResult } from '../services/rulehost-readiness.js';
47
-
48
- export interface RunRuleHostOptions {
49
- workspace?: string;
50
- painId: string;
51
- channel?: string;
52
- maxRounds?: number;
53
- timeoutMs?: number;
54
- behaviorExamples?: string;
55
- json?: boolean;
56
- /** Dry-run mode (default). Validates inputs + config, reports capability status, does NOT run the pipeline. */
57
- dryRun?: boolean;
58
- /** Confirm mutation — actually run the pipeline. Mutually exclusive with --dry-run. */
59
- confirm?: boolean;
60
- }
61
-
62
- const DEFAULT_WORKSPACE = process.cwd();
63
- const SUPPORTED_CHANNELS = new Set(['prompt', 'code_tool_hook', 'defer_archive']);
64
-
65
- type RuleHostChannel = 'prompt' | 'code_tool_hook' | 'defer_archive';
66
-
67
- function resolveWorkspace(opts: RunRuleHostOptions): string {
68
- return opts.workspace ? path.resolve(opts.workspace) : DEFAULT_WORKSPACE;
69
- }
70
-
71
- interface ResolvedRunRuleHostRuntime {
72
- readonly agentAdapters: RuleHostAgentAdapters;
73
- readonly agentRuntimeProfiles: Partial<Record<InternalAgentName, string>>;
74
- readonly capability: CodeRuleCapability;
75
- readonly capabilityStatus: string;
76
- readonly contextV2Enabled: boolean;
77
- }
78
-
79
- interface OwnerBehaviorExamplesInput {
80
- readonly ownerDesiredOutcome: string;
81
- readonly sourceNegativeToolCallId: number;
82
- readonly positiveToolCallIds: readonly number[];
83
- }
84
-
85
- type OwnerBehaviorExamplesResult =
86
- | { readonly ok: true; readonly value: OwnerBehaviorExamplesInput }
87
- | { readonly ok: false; readonly reason: string };
88
-
89
- function isRecord(value: unknown): value is Record<string, unknown> {
90
- return typeof value === 'object' && value !== null && !Array.isArray(value);
91
- }
92
-
93
- function readOwnerBehaviorExamples(filePath: string): OwnerBehaviorExamplesResult {
94
- let parsed: unknown;
95
- try {
96
- parsed = JSON.parse(fs.readFileSync(filePath, 'utf8'));
97
- } catch (error) {
98
- return { ok: false, reason: `behavior_examples_unreadable: ${error instanceof Error ? error.message : String(error)}` };
99
- }
100
- if (!isRecord(parsed)) return { ok: false, reason: 'behavior_examples_invalid: root must be an object' };
101
- if (typeof parsed.ownerDesiredOutcome !== 'string' || parsed.ownerDesiredOutcome.trim() === '') {
102
- return { ok: false, reason: 'behavior_examples_invalid: ownerDesiredOutcome must be a non-empty string' };
103
- }
104
- if (!Number.isSafeInteger(parsed.sourceNegativeToolCallId) || Number(parsed.sourceNegativeToolCallId) <= 0) {
105
- return { ok: false, reason: 'behavior_examples_invalid: sourceNegativeToolCallId must be a positive integer' };
106
- }
107
- if (!Array.isArray(parsed.positiveToolCallIds) || parsed.positiveToolCallIds.length === 0 || parsed.positiveToolCallIds.length > 3
108
- || parsed.positiveToolCallIds.some((id) => !Number.isSafeInteger(id) || Number(id) <= 0)) {
109
- return { ok: false, reason: 'behavior_examples_invalid: positiveToolCallIds must contain 1 to 3 positive integers' };
110
- }
111
- return {
112
- ok: true,
113
- value: {
114
- ownerDesiredOutcome: parsed.ownerDesiredOutcome,
115
- sourceNegativeToolCallId: Number(parsed.sourceNegativeToolCallId),
116
- positiveToolCallIds: parsed.positiveToolCallIds.map((id) => Number(id)),
117
- },
118
- };
119
- }
120
-
121
- function resolvePiAiAgentAdapter(
122
- effective: EffectivePdConfig,
123
- agentName: InternalAgentName,
124
- options: { readonly workspaceDir: string; readonly timeoutMs: number | undefined },
125
- ): { adapter: PDRuntimeAdapter; profileId: string } {
126
- const binding = resolveAgentRuntimeBinding(effective, agentName);
127
- if (!binding.ok) {
128
- throw new Error(`${agentName}: ${binding.reason}. nextAction: ${binding.nextAction}`);
129
- }
130
- if (binding.profile.type !== 'pi-ai') {
131
- throw new Error(`${agentName}: runtime profile '${binding.profileId}' must be pi-ai (got '${binding.profile.type}')`);
132
- }
133
- if (!process.env[binding.profile.apiKeyEnv]) {
134
- throw new Error(`${agentName}: apiKeyEnv '${binding.profile.apiKeyEnv}' is not set`);
135
- }
136
- return {
137
- profileId: binding.profileId,
138
- adapter: new PiAiRuntimeAdapter({
139
- provider: binding.profile.provider,
140
- model: binding.profile.model,
141
- apiKeyEnv: binding.profile.apiKeyEnv,
142
- maxRetries: binding.profile.maxRetries,
143
- // Forward profile maxTokens: pi-ai only sends max_tokens when the caller
144
- // sets it — omitting it lets the provider apply its own (small) default
145
- // output cap, truncating long JSON outputs (EP002-R3 scribe intentContract).
146
- // Parity with the consumer-cycle adapter (PRI-758 CodeRabbit P2).
147
- ...(binding.profile.maxTokens !== undefined ? { maxTokens: binding.profile.maxTokens } : {}),
148
- timeoutMs: options.timeoutMs ?? binding.profile.timeoutMs,
149
- baseUrl: binding.profile.baseUrl,
150
- workspace: options.workspaceDir,
151
- // PRI-633: profile systemPrompt rides as the append layer.
152
- ...(binding.profile.systemPrompt ? { systemPrompt: binding.profile.systemPrompt } : {}),
153
- }),
154
- };
155
- }
156
-
157
- /**
158
- * Resolve the code-rule capability (atomic: ArtificerL2 + Evaluator).
159
- *
160
- * Checks per-agent config for artificer and evaluator. When both are enabled,
161
- * constructs the ArtificerL2Adapter via buildArtificerL2GenerateCode. When
162
- * either is disabled, returns a disabled capability with a structured reason.
163
- *
164
- * Returns the capability AND a human-readable status summary for dry-run output.
165
- */
166
- function resolveRunRuleHostRuntime(
167
- workspaceDir: string,
168
- timeoutMs: number | undefined,
169
- readiness: RuleHostReadinessResult,
170
- ): ResolvedRunRuleHostRuntime {
171
- const { configLoadResult } = resolveRuntimeFromPdConfig(workspaceDir);
172
-
173
- if (!configLoadResult.ok) {
174
- throw new Error('config_malformed — cannot resolve agent bindings');
175
- }
176
-
177
- const { effective } = configLoadResult;
178
- const featureFlags = computeFeatureFlagsFromConfig(effective);
179
- const contextV2Enabled = isFeatureEnabled(featureFlags, 'rulecode_context_v2');
180
- const adapterOptions = { workspaceDir, timeoutMs };
181
- const dreamer = resolvePiAiAgentAdapter(effective, 'dreamer', adapterOptions);
182
- const philosopher = resolvePiAiAgentAdapter(effective, 'philosopher', adapterOptions);
183
- const scribe = resolvePiAiAgentAdapter(effective, 'scribe', adapterOptions);
184
- const agentRuntimeProfiles: Partial<Record<InternalAgentName, string>> = {
185
- dreamer: dreamer.profileId,
186
- philosopher: philosopher.profileId,
187
- scribe: scribe.profileId,
188
- };
189
- if (readiness.status === 'text_principle_only') {
190
- return {
191
- agentAdapters: { dreamer: dreamer.adapter, philosopher: philosopher.adapter, scribe: scribe.adapter, evaluator: scribe.adapter },
192
- agentRuntimeProfiles,
193
- capability: { enabled: false, disabledReason: readiness.reason },
194
- capabilityStatus: `code_rule_capability: OFF (${readiness.reason})`,
195
- contextV2Enabled,
196
- };
197
- }
198
- if (!isFeatureEnabled(featureFlags, 'code_rule_capability')) {
199
- return {
200
- agentAdapters: { dreamer: dreamer.adapter, philosopher: philosopher.adapter, scribe: scribe.adapter, evaluator: scribe.adapter },
201
- agentRuntimeProfiles,
202
- capability: { enabled: false, disabledReason: 'code_rule_capability feature flag is disabled' },
203
- capabilityStatus: 'code_rule_capability: OFF (feature flag disabled)',
204
- contextV2Enabled,
205
- };
206
- }
207
-
208
- const artificerBinding = resolveAgentRuntimeBinding(effective, 'artificer');
209
- const evaluatorBinding = resolveAgentRuntimeBinding(effective, 'evaluator');
210
-
211
- // Both must be enabled (atomic capability).
212
- if (!artificerBinding.ok) {
213
- return {
214
- agentAdapters: { dreamer: dreamer.adapter, philosopher: philosopher.adapter, scribe: scribe.adapter, evaluator: scribe.adapter },
215
- agentRuntimeProfiles,
216
- capability: { enabled: false, disabledReason: `artificer agent disabled: ${artificerBinding.reason}` },
217
- capabilityStatus: `code_rule_capability: OFF (artificer disabled — ${artificerBinding.reason})`,
218
- contextV2Enabled,
219
- };
220
- }
221
- if (!evaluatorBinding.ok) {
222
- return {
223
- agentAdapters: { dreamer: dreamer.adapter, philosopher: philosopher.adapter, scribe: scribe.adapter, evaluator: scribe.adapter },
224
- agentRuntimeProfiles,
225
- capability: { enabled: false, disabledReason: `evaluator agent disabled: ${evaluatorBinding.reason}` },
226
- capabilityStatus: `code_rule_capability: OFF (evaluator disabled — ${evaluatorBinding.reason})`,
227
- contextV2Enabled,
228
- };
229
- }
230
-
231
- // Both enabled — construct the ArtificerL2Adapter.
232
- // Resolve the artificer's runtime profile to get provider/model/apiKeyEnv.
233
- const { profile: artificerProfile } = artificerBinding;
234
- if (artificerProfile.type !== 'pi-ai') {
235
- return {
236
- agentAdapters: { dreamer: dreamer.adapter, philosopher: philosopher.adapter, scribe: scribe.adapter, evaluator: scribe.adapter },
237
- agentRuntimeProfiles,
238
- capability: { enabled: false, disabledReason: `artificer runtime profile is not pi-ai (got '${artificerProfile.type}')` },
239
- capabilityStatus: `code_rule_capability: OFF (artificer profile type='${artificerProfile.type}', expected pi-ai)`,
240
- contextV2Enabled,
241
- };
242
- }
243
-
244
- const apiKey = process.env[artificerProfile.apiKeyEnv];
245
- if (!apiKey) {
246
- return {
247
- agentAdapters: { dreamer: dreamer.adapter, philosopher: philosopher.adapter, scribe: scribe.adapter, evaluator: scribe.adapter },
248
- agentRuntimeProfiles,
249
- capability: { enabled: false, disabledReason: `artificer apiKeyEnv '${artificerProfile.apiKeyEnv}' is not set in environment` },
250
- capabilityStatus: `code_rule_capability: OFF (artificer apiKeyEnv '${artificerProfile.apiKeyEnv}' not set)`,
251
- contextV2Enabled,
252
- };
253
- }
254
-
255
- const evaluator = resolvePiAiAgentAdapter(effective, 'evaluator', adapterOptions);
256
- agentRuntimeProfiles.artificer = artificerBinding.profileId;
257
- agentRuntimeProfiles.evaluator = evaluator.profileId;
258
-
259
- // PRI-795 review P1: the CLI process is one-shot — without a durable sink
260
- // the artificer_l2_complete evidence (abortOwner/budget/elapsed/stopReason/
261
- // tokenUsage) dies with the process, repeating the EP002-R3
262
- // "nothing recoverable after a failure" investigation gap. Reuse the
263
- // host-runtime workspace-scoped emitter so completions land in
264
- // <workspaceDir>/.pd/telemetry/critical-events.jsonl.
265
- const artificerEmitter = new WorkspaceTelemetryEmitter(storeEmitter, workspaceDir, (detail) => {
266
- console.error(`[run-rulehost] workspace telemetry persist failed: ${detail}`);
267
- });
268
-
269
- // PRI-657: production-identical gate deps — the L2 self-validation replay
270
- // must cross the same tool semantics as the activation gate (mirrors
271
- // internalization-consumer-cycle.ts). An unresolvable workspace host
272
- // declaration degrades OBSERVABLY to the baseline gate with reason +
273
- // nextAction on stderr (rc-9; stdout stays pure JSON — cli-1). Acceptable
274
- // here because this is generation-time self-validation; the activation
275
- // gate remains fail-loud downstream.
276
- const hostSemantics = resolveWorkspaceHostToolSemantics(workspaceDir);
277
- if (!hostSemantics.ok) {
278
- console.error(`[run-rulehost] artificer self-validation without host tool semantics: ${hostSemantics.reason} — ${hostSemantics.nextAction}`);
279
- }
280
- const artificerGateDeps = hostSemantics.ok
281
- ? createProductionGateDeps({ toolSemantics: hostSemantics.registry, projectDir: workspaceDir })
282
- : createProductionGateDeps();
283
-
284
- const artificerAdapter = new ArtificerL2Adapter({
285
- provider: artificerProfile.provider,
286
- model: artificerProfile.model,
287
- apiKeyEnv: artificerProfile.apiKeyEnv,
288
- baseUrl: artificerProfile.baseUrl,
289
- gateDeps: artificerGateDeps,
290
- validator: new DefaultArtificerValidator(),
291
- // PRI-795: fall back to the profile's timeoutMs when --timeout-ms is not
292
- // given — parity with resolvePiAiAgentAdapter above. Previously the raw
293
- // CLI option (possibly undefined) was passed, silently dropping the L2
294
- // loop onto the adapter's 300s default regardless of the profile.
295
- totalBudgetMs: timeoutMs ?? artificerProfile.timeoutMs,
296
- // Forward profile maxTokens — parity with the consumer-cycle adapter;
297
- // omitting it truncates long artificer JSON at the provider's default cap.
298
- ...(artificerProfile.maxTokens !== undefined ? { maxTokens: artificerProfile.maxTokens } : {}),
299
- // PRI-795: forward profile reasoning so always-thinking models get a
300
- // bounded thinking level on the L2 loop too — parity with the
301
- // PiAiRuntimeAdapter wiring (it was previously L2-dropped).
302
- ...(artificerProfile.reasoning !== undefined ? { reasoning: artificerProfile.reasoning } : {}),
303
- eventEmitter: artificerEmitter,
304
- });
305
-
306
- return {
307
- agentAdapters: { dreamer: dreamer.adapter, philosopher: philosopher.adapter, scribe: scribe.adapter, evaluator: evaluator.adapter },
308
- agentRuntimeProfiles,
309
- capability: { enabled: true, artificerAdapter },
310
- capabilityStatus: `code_rule_capability: ON (artificer profile='${artificerBinding.profileId}', evaluator profile='${evaluatorBinding.profileId}')`,
311
- contextV2Enabled,
312
- };
313
- }
314
-
315
- /**
316
- * Owner Decision Experience v1 review fix (Codex P1): derive the PUBLICATION
317
- * outcome from the pipeline result. The generation can fully succeed while the
318
- * governance publication (approval enqueue) is REFUSED by the Phase A identity
319
- * boundary — that state must never be presented as "waiting for owner review".
320
- * Exported pure so the CLI output contract is testable without spawning the
321
- * command (cli-7).
322
- */
323
- export function describePublicationOutcome(result: RuleHostPipelineResult): {
324
- blocked: boolean;
325
- nextAction: string;
326
- } {
327
- const identityBlocked = result.decision === 'candidate_ready_for_owner_review'
328
- && result.approvalId === null
329
- && (result.degradationReason ?? '').includes('identity_binding_unverified');
330
- if (identityBlocked) {
331
- return {
332
- blocked: true,
333
- nextAction: 'Identity binding could not be verified, so the artifact was NOT enqueued for Owner review. Artifacts are preserved; repair the ledger identity for this candidate and re-run this pipeline to publish.',
334
- };
335
- }
336
- return { blocked: false, nextAction: '' };
337
- }
338
-
339
- export function formatTextOutput(result: RuleHostPipelineResult): string {
340
- const lines: string[] = [];
341
- const isReady = result.decision === 'candidate_ready_for_owner_review';
342
- // Owner Decision Experience v1 review fix (Codex P1): an identity-gated
343
- // refusal keeps the service decision but did NOT enqueue an approval —
344
- // reporting it as plain success ("WAITING for owner review") lied to the
345
- // operator. The publication outcome is derived explicitly and reported.
346
- const publication = describePublicationOutcome(result);
347
- const icon = publication.blocked ? '⚠' : isReady ? '✓' : result.decision === 'text_principle_only' ? '⚠' : '✗';
348
- lines.push('RuleHost Pipeline (PRI-429)');
349
- lines.push(`pain: ${result.painId}`);
350
- lines.push(`OVERALL: ${icon} ${result.decision.toUpperCase()}${publication.blocked ? ' (PUBLICATION REFUSED)' : ''}`);
351
- lines.push('');
352
-
353
- for (const stage of result.stages) {
354
- const sIcon = stage.status === 'succeeded' ? '✓' : stage.status === 'degraded' ? '⚠' : stage.status === 'skipped' ? '○' : '✗';
355
- lines.push(` ${sIcon} ${stage.name}: ${stage.status}`);
356
- if (stage.reason) lines.push(` reason: ${stage.reason}`);
357
- }
358
- lines.push('');
359
- lines.push(`ruleArtifactId: ${result.ruleArtifactId ?? '(none)'}`);
360
- lines.push(`principleArtifactId: ${result.principleArtifactId ?? '(none)'}`);
361
- if (result.approvalId) {
362
- lines.push(`approvalId: ${result.approvalId}`);
363
- }
364
- if (result.degradationReason) {
365
- lines.push(`degradationReason: ${result.degradationReason}`);
366
- }
367
- if (publication.blocked) {
368
- lines.push('');
369
- lines.push(`Next: ${publication.nextAction}`);
370
- } else if (result.decision === 'candidate_ready_for_owner_review') {
371
- lines.push('');
372
- lines.push('Next: the rule artifact is validated and WAITING for owner review. This is NOT owner approval.');
373
- } else if (result.decision === 'text_principle_only') {
374
- lines.push('');
375
- if (result.approvalId) {
376
- lines.push(`Next: code-rule capability is OFF. Text principle enqueued for Owner review in the approval queue (${result.approvalId}). Approve it in the Console.`);
377
- } else {
378
- lines.push('Next: code-rule capability is OFF and the text principle could NOT be enqueued. Check degradationReason.');
379
- }
380
- } else {
381
- lines.push('');
382
- lines.push('Next: generation rejected. Check degradationReason. Principle artifact may still exist for prompt-channel fallback.');
383
- }
384
- return lines.join('\n');
385
- }
386
-
387
- interface DryRunFormatInput {
388
- readonly opts: RunRuleHostOptions;
389
- readonly capabilityStatus: string;
390
- readonly workspaceDir: string;
391
- readonly readiness: RuleHostReadinessResult;
392
- /** PRI-780 review: the EFFECTIVE code-rule capability — conditions the ready "Next" line. */
393
- readonly capabilityEnabled: boolean;
394
- }
395
-
396
- function formatDryRunOutput(input: DryRunFormatInput): string {
397
- const { opts, capabilityStatus, workspaceDir, readiness, capabilityEnabled } = input;
398
- const lines: string[] = [];
399
- lines.push('RuleHost Pipeline (PRI-429) — DRY RUN');
400
- lines.push(`pain: ${opts.painId}`);
401
- lines.push(`workspace: ${workspaceDir}`);
402
- lines.push(`channel: ${opts.channel ?? 'code_tool_hook'}`);
403
- lines.push(`readiness: ${readiness.status.toUpperCase()}`);
404
- if (readiness.status !== 'ready') {
405
- lines.push(` reason: ${readiness.reason}`);
406
- lines.push(` nextAction: ${readiness.nextAction}`);
407
- }
408
- lines.push(capabilityStatus);
409
- lines.push('');
410
- lines.push('No tasks created, no LLM calls made, no artifacts written.');
411
- if (readiness.status === 'ready') {
412
- // PRI-780 review: derive the next action from the EFFECTIVE capability —
413
- // a kill-switched / BEP-missing workspace cannot run the code-rule
414
- // pipeline on --confirm, only text-principle-only internalization.
415
- lines.push(capabilityEnabled
416
- ? 'Next: pass --confirm to actually run the pipeline.'
417
- : 'Next: fix the code-rule capability issue above; --confirm runs text-principle-only internalization.');
418
- } else if (readiness.status === 'text_principle_only') {
419
- lines.push('Next: pass --confirm to run in text-principle-only mode, or fix the issues above to enable full pipeline.');
420
- } else {
421
- lines.push('Next: fix the readiness issues above before running the pipeline.');
422
- }
423
- return lines.join('\n');
424
- }
425
-
426
- export async function handleRunRuleHost(opts: RunRuleHostOptions): Promise<void> {
427
- // ── Validate dry-run/confirm mutual exclusivity (CLI gate rule 4) ──
428
- if (opts.dryRun && opts.confirm) {
429
- if (opts.json) {
430
- process.stdout.write(JSON.stringify({ status: 'failed', reason: '--dry-run and --confirm are mutually exclusive', nextAction: 'pass either --dry-run or --confirm, not both' }) + '\n');
431
- } else {
432
- console.error('Error: --dry-run and --confirm are mutually exclusive. Pass either one, not both.');
433
- }
434
- process.exitCode = 1;
435
- return;
436
- }
437
-
438
- // ── Validate inputs ──
439
- if (!opts.painId || opts.painId.trim() === '') {
440
- if (opts.json) {
441
- process.stdout.write(JSON.stringify({ status: 'failed', reason: 'painId is required', nextAction: 'pass --pain-id <id> (run pd pain record first)' }) + '\n');
442
- } else {
443
- console.error('Error: --pain-id is required. Run `pd pain record` first to seed a pain signal.');
444
- }
445
- process.exitCode = 1;
446
- return;
447
- }
448
-
449
- const channel = opts.channel ?? 'code_tool_hook';
450
- if (!SUPPORTED_CHANNELS.has(channel)) {
451
- if (opts.json) {
452
- process.stdout.write(JSON.stringify({ status: 'failed', reason: `unsupported channel: ${channel}`, nextAction: 'use one of prompt|code_tool_hook|defer_archive' }) + '\n');
453
- } else {
454
- console.error(`Error: unsupported channel '${channel}'. Use one of: prompt, code_tool_hook, defer_archive.`);
455
- }
456
- process.exitCode = 1;
457
- return;
458
- }
459
-
460
- // Validate numeric opts (Commander parseInt can yield NaN for non-numeric input).
461
- if (opts.maxRounds !== undefined && (!Number.isInteger(opts.maxRounds) || opts.maxRounds <= 0)) {
462
- if (opts.json) {
463
- process.stdout.write(JSON.stringify({ status: 'failed', reason: `invalid --max-rounds: ${opts.maxRounds}`, nextAction: 'pass a positive integer (PRD cap = 2)' }) + '\n');
464
- } else {
465
- console.error(`Error: --max-rounds must be a positive integer (got ${opts.maxRounds}).`);
466
- }
467
- process.exitCode = 1;
468
- return;
469
- }
470
- if (opts.timeoutMs !== undefined && (!Number.isInteger(opts.timeoutMs) || opts.timeoutMs <= 0)) {
471
- if (opts.json) {
472
- process.stdout.write(JSON.stringify({ status: 'failed', reason: `invalid --timeout-ms: ${opts.timeoutMs}`, nextAction: 'pass a positive integer (default 300000)' }) + '\n');
473
- } else {
474
- console.error(`Error: --timeout-ms must be a positive integer (got ${opts.timeoutMs}).`);
475
- }
476
- process.exitCode = 1;
477
- return;
478
- }
479
-
480
- const workspaceDir = resolveWorkspace(opts);
481
-
482
- // ── Readiness check (PRI-461) ──
483
- // Check all preconditions BEFORE constructing adapters. This produces a
484
- // structured ready/text_principle_only/refused status instead of an opaque
485
- // agent_runtime_resolution_failed error.
486
- const readiness = resolveRuleHostReadiness(workspaceDir);
487
-
488
- // If refused, emit structured error and exit (CLI gate rule 2 + rule 5).
489
- // Refused means the pipeline cannot run at all — do NOT attempt adapter
490
- // construction or pipeline execution.
491
- if (readiness.status === 'refused') {
492
- if (opts.json) {
493
- process.stdout.write(JSON.stringify({
494
- status: 'refused',
495
- reason: readiness.reason,
496
- nextAction: readiness.nextAction,
497
- readiness,
498
- }) + '\n');
499
- } else {
500
- console.error(`RuleHost readiness: REFUSED`);
501
- console.error(` reason: ${readiness.reason}`);
502
- console.error(` nextAction: ${readiness.nextAction}`);
503
- }
504
- process.exitCode = 1;
505
- return;
506
- }
507
-
508
- // ── Resolve each executed agent from canonical config ──
509
- let resolvedRuntime: ResolvedRunRuleHostRuntime;
510
- try {
511
- resolvedRuntime = resolveRunRuleHostRuntime(workspaceDir, opts.timeoutMs, readiness);
512
- } catch (err) {
513
- const message = err instanceof Error ? err.message : String(err);
514
- if (opts.json) {
515
- process.stdout.write(JSON.stringify({ status: 'failed', reason: 'agent_runtime_resolution_failed', message, nextAction: 'check internalAgents and runtimeProfiles in .pd/config.yaml; run pd config doctor', readiness }) + '\n');
516
- } else {
517
- console.error(`Error: ${message}`);
518
- }
519
- process.exitCode = 1;
520
- return;
521
- }
522
-
523
- let effectiveCapability = resolvedRuntime.capability;
524
- let behaviorExamplePack: BehaviorExamplePack | undefined;
525
- let behaviorExamplesReason: string | undefined;
526
- const behaviorExamplesPath = opts.behaviorExamples
527
- ? path.resolve(workspaceDir, opts.behaviorExamples)
528
- : undefined;
529
-
530
- if (!resolvedRuntime.contextV2Enabled && behaviorExamplesPath) {
531
- const reason = 'behavior_examples_not_allowed: rulecode_context_v2 is disabled (kill switch) and v2 is the only generation contract (PRI-780)';
532
- if (opts.json) {
533
- process.stdout.write(JSON.stringify({ status: 'failed', reason, nextAction: 're-enable rulecode_context_v2 or remove --behavior-examples' }) + '\n');
534
- } else {
535
- console.error(`Error: ${reason}. Re-enable rulecode_context_v2 or remove --behavior-examples.`);
536
- }
537
- process.exitCode = 1;
538
- return;
539
- }
540
-
541
- // PRI-780: the generation contract is v2-only. With the kill switch active
542
- // (explicit rulecode_context_v2 disable) code-rule generation is refused
543
- // with a structured reason — never a silent fallback to an action-only
544
- // (v1) rule. Text-principle internalization continues (capability OFF).
545
- if (!resolvedRuntime.contextV2Enabled) {
546
- effectiveCapability = {
547
- enabled: false,
548
- disabledReason: 'rulecode_context_v2_disabled: kill switch active — v2 is the only RuleCode generation contract (PRI-780); re-enable the flag to generate code rules',
549
- };
550
- } else {
551
- if (!behaviorExamplesPath) {
552
- behaviorExamplesReason = 'behavior_examples_missing';
553
- } else {
554
- const examplesResult = readOwnerBehaviorExamples(behaviorExamplesPath);
555
- if (!examplesResult.ok) {
556
- // P1 fix (CodeRabbit PR2 Comment 1): fail fast on parse failure instead
557
- // of silently degrading to text_principle_only (rc-9-no-silent-fallback).
558
- // examplesResult.reason already carries a stable prefix
559
- // (behavior_examples_unreadable: | behavior_examples_invalid:).
560
- const { reason } = examplesResult;
561
- if (opts.json) {
562
- process.stdout.write(JSON.stringify({
563
- status: 'failed',
564
- reason,
565
- nextAction: 'fix the --behavior-examples JSON payload and retry',
566
- }) + '\n');
567
- } else {
568
- console.error(`Error: ${reason}. Fix the --behavior-examples JSON payload and retry.`);
569
- }
570
- process.exitCode = 1;
571
- return;
572
- }
573
- if (opts.confirm) {
574
- // Lazy import: avoids loading `principles-disciple` at module init
575
- // time. `pd --version` (and the create-principles-disciple smoke
576
- // test) loads this file statically via index.ts; a static import
577
- // would pull the plugin package into every pd startup even when
578
- // `--confirm` is never used. Both install layouts resolve the
579
- // package via a `pd-cli/node_modules/principles-disciple` link
580
- // (release: installer.ts syncPdCli; local dev: sync-plugin.mjs,
581
- // PRI-808).
582
- const { BehaviorExamplePackAssembler, RuleHostEvidenceRegistry } = await import('principles-disciple/rulehost-evidence');
583
- try {
584
- const assembler = new BehaviorExamplePackAssembler({ workspaceDir, stateDir: path.join(workspaceDir, '.state') });
585
- behaviorExamplePack = assembler.assemble({
586
- sourcePainId: opts.painId,
587
- ownerDesiredOutcome: examplesResult.value.ownerDesiredOutcome,
588
- sourceNegativeToolCallId: examplesResult.value.sourceNegativeToolCallId,
589
- positiveToolCallIds: examplesResult.value.positiveToolCallIds,
590
- projectDir: workspaceDir,
591
- });
592
- } catch (error) {
593
- // P1 fix (CodeRabbit PR2 Comment 1): fail fast on assembly failure
594
- // instead of silently degrading to text_principle_only.
595
- const reason = `behavior_examples_unreliable: ${error instanceof Error ? error.message : String(error)}`;
596
- if (opts.json) {
597
- process.stdout.write(JSON.stringify({
598
- status: 'failed',
599
- reason,
600
- nextAction: 'verify pain lineage and tool call IDs reference existing trajectory rows; rerun pd pain record if needed',
601
- }) + '\n');
602
- } else {
603
- console.error(`Error: ${reason}. Verify pain lineage and tool call IDs reference existing trajectory rows; rerun pd pain record if needed.`);
604
- }
605
- process.exitCode = 1;
606
- return;
607
- } finally {
608
- RuleHostEvidenceRegistry.dispose(workspaceDir);
609
- }
610
- }
611
- }
612
- if (behaviorExamplesReason && effectiveCapability.enabled) {
613
- // Only override when code-rule generation would actually run — a more
614
- // fundamental blocker (text_principle_only readiness, disabled agent,
615
- // kill switch) keeps precedence and stays the reported reason.
616
- effectiveCapability = { enabled: false, disabledReason: `${behaviorExamplesReason}; nextAction: provide reliable Owner-labelled tool call IDs with --behavior-examples` };
617
- }
618
- // behaviorExamplesReason is intentionally KEPT even when a more fundamental
619
- // blocker takes precedence: the dry-run behaviorExamples field must still
620
- // report 'unreliable' (M6 — clearing it here masked the evidence problem).
621
- }
622
-
623
- // ── Dry-run mode: report what would happen, don't run the pipeline ──
624
- // Default is dry-run (CLI gate rule 4: mutating commands default to dry-run).
625
- const isDryRun = opts.dryRun || !opts.confirm;
626
- if (isDryRun) {
627
- // PRI-780 review M2: the status string derives from the EFFECTIVE
628
- // capability (kill switch / BEP refusal included), never from the
629
- // pre-flag resolvedRuntime snapshot — otherwise a kill-switched workspace
630
- // would display "ON" with a misleading "pass --confirm" nextAction.
631
- const effectiveCapabilityStatus = effectiveCapability.enabled
632
- ? resolvedRuntime.capabilityStatus
633
- : `code_rule_capability: OFF (${effectiveCapability.disabledReason ?? 'disabled'})`;
634
- if (opts.json) {
635
- process.stdout.write(JSON.stringify({
636
- status: 'dry_run',
637
- painId: opts.painId,
638
- workspace: workspaceDir,
639
- channel,
640
- readiness,
641
- readinessStatus: readiness.status,
642
- capabilityStatus: effectiveCapabilityStatus,
643
- agentRuntimeProfiles: resolvedRuntime.agentRuntimeProfiles,
644
- codeRuleCapability: { enabled: effectiveCapability.enabled, disabledReason: effectiveCapability.disabledReason },
645
- // PRI-780: 'v2' is the only generation contract (observability field).
646
- contextMode: 'v2',
647
- behaviorExamples: behaviorExamplesPath
648
- ? { path: behaviorExamplesPath, status: behaviorExamplesReason ? 'unreliable' : 'provided' }
649
- : { status: resolvedRuntime.contextV2Enabled ? 'missing' : 'not_required' },
650
- nextAction: readiness.status === 'ready'
651
- ? (effectiveCapability.enabled
652
- ? 'pass --confirm to run the full pipeline'
653
- : 'fix the code-rule capability issues above; --confirm runs text-principle-only internalization')
654
- : readiness.status === 'text_principle_only'
655
- ? 'pass --confirm to run in text-principle-only mode (code-rule capability OFF), or fix the issues above to enable full pipeline'
656
- : 'fix the readiness issues above before running the pipeline',
657
- }) + '\n');
658
- } else {
659
- process.stdout.write(formatDryRunOutput({ opts, capabilityStatus: effectiveCapabilityStatus, workspaceDir, readiness, capabilityEnabled: effectiveCapability.enabled }) + '\n');
660
- }
661
- return;
662
- }
663
-
664
- // ── Run the pipeline (--confirm mode) ──
665
- let result: RuleHostPipelineResult;
666
- try {
667
- result = await runRuleHostPipeline({
668
- workspaceDir,
669
- painId: opts.painId,
670
- runtimeAdapter: resolvedRuntime.agentAdapters.dreamer,
671
- agentAdapters: resolvedRuntime.agentAdapters,
672
- codeRuleCapability: effectiveCapability,
673
- behaviorExamplePack,
674
- channel: channel as RuleHostChannel,
675
- maxRounds: opts.maxRounds,
676
- timeoutMs: opts.timeoutMs,
677
- });
678
- } catch (err) {
679
- const message = err instanceof Error ? err.message : String(err);
680
- if (opts.json) {
681
- process.stdout.write(JSON.stringify({ status: 'failed', reason: 'pipeline_threw', message, nextAction: 'check workspace state and retry' }) + '\n');
682
- } else {
683
- console.error(`Error: pipeline failed: ${message}`);
684
- }
685
- process.exitCode = 1;
686
- return;
687
- }
688
-
689
- // ── Output ──
690
- // Owner Decision Experience v1 review fix (Codex P1): an identity-gated
691
- // refusal is a degraded outcome — the JSON carries the structured
692
- // reason/nextAction (cli-6) and the exit code is non-zero so automation
693
- // does not treat an unpublishable artifact as a fully successful run.
694
- const publication = describePublicationOutcome(result);
695
- if (opts.json) {
696
- // Exactly one parseable JSON object on stdout (CLI gate rule 1).
697
- // CLI gate rule 6: degraded/refused results include structured reason + nextAction.
698
- const output = result.decision === 'candidate_ready_for_owner_review'
699
- ? {
700
- status: 'candidate_ready_for_owner_review',
701
- ...result,
702
- ...(publication.blocked
703
- ? { publicationRefused: true, nextAction: publication.nextAction }
704
- : {}),
705
- }
706
- : {
707
- status: result.decision,
708
- ...result,
709
- nextAction: result.decision === 'text_principle_only'
710
- ? (result.approvalId
711
- ? `code-rule capability OFF; text principle enqueued for Owner review (${result.approvalId}). Approve it in the Console.`
712
- : 'code-rule capability OFF and approval enqueue failed; check degradationReason for the manual enqueue command.')
713
- : 'Check degradationReason; principle artifact may still exist for prompt-channel fallback.',
714
- };
715
- process.stdout.write(JSON.stringify(output) + '\n');
716
- } else {
717
- process.stdout.write(formatTextOutput(result) + '\n');
718
- }
719
-
720
- // exit 1 when the run did not fully succeed (not ready, or publication refused).
721
- if (result.decision !== 'candidate_ready_for_owner_review' || publication.blocked) {
722
- process.exitCode = 1;
723
- }
724
- }
725
-
726
- /**
727
- * Register the `pd runtime internalization run-rulehost` subcommand.
728
- *
729
- * Single source of truth for both production (`index.ts`) and parser tests.
730
- * Extracted so parser-level tests can exercise the real flag wiring without
731
- * triggering `program.parse()` at module load (CLI gate rule 7).
732
- */
733
- export function registerRunRuleHostCommand(internalizationCmd: Command): Command {
734
- return internalizationCmd
735
- .command('run-rulehost')
736
- .description('Full-chain: drive a pain signal to a validated rule artifact (pain → dreamer → philosopher → scribe → adversarial loop)')
737
- .option('-w, --workspace <path>', 'Workspace directory')
738
- .requiredOption('--pain-id <id>', 'Pain ID whose internalization chain to drive (run `pd pain record` first)')
739
- .option('--channel <channel>', 'Activation channel: code_tool_hook, prompt, defer_archive (default: code_tool_hook)', 'code_tool_hook')
740
- .option('--max-rounds <n>', 'Max adversarial rounds (PRD cap = 2)', parseInt)
741
- .option('--timeout-ms <ms>', 'Per-LLM-call timeout in milliseconds (default: 300000)', parseInt)
742
- .option('--behavior-examples <json>', 'Owner-labelled negative/positive tool call IDs for RuleContext v2')
743
- .option('--dry-run', 'Validate inputs + config, report capability status, do NOT run the pipeline (default)')
744
- .option('--confirm', 'Actually run the pipeline (mutually exclusive with --dry-run)')
745
- .option('--json', 'Output raw JSON')
746
- .action(async (opts) => {
747
- await handleRunRuleHost({ workspace: opts.workspace, painId: opts.painId, channel: opts.channel, maxRounds: opts.maxRounds, timeoutMs: opts.timeoutMs, behaviorExamples: opts.behaviorExamples, dryRun: opts.dryRun, confirm: opts.confirm, json: opts.json });
748
- });
749
- }