@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,326 +0,0 @@
1
- /**
2
- * RuleHost Readiness Resolver — PRI-461
3
- *
4
- * Checks all preconditions for `run-rulehost` BEFORE constructing adapters,
5
- * returning one of three user-visible statuses:
6
- * - `ready`: all agents enabled with pi-ai profiles and API keys; code-rule capability ON
7
- * - `text_principle_only`: dreamer/philosopher/scribe ready, but code-rule capability OFF
8
- * (flag disabled, or artificer/evaluator not ready)
9
- * - `refused`: dreamer/philosopher/scribe chain broken (disabled, wrong profile, missing API key,
10
- * or config malformed)
11
- *
12
- * This module NEVER throws. It always returns a structured result with reason + nextAction,
13
- * so the CLI handler can emit a clear status instead of an opaque adapter-resolution failure.
14
- *
15
- * ERR refs:
16
- * - EP-02 / ERR-024, ERR-025: wired into the production handler path (runtime-internalization-run-rulehost.ts)
17
- * - EP-03: refused/text_principle_only include reason + nextAction
18
- * - EP-07: uses the same config source as the pipeline (resolveRuntimeFromPdConfig)
19
- * - EP-09: tests cover the default installed config pattern
20
- */
21
-
22
- import {
23
- resolveAgentRuntimeBinding,
24
- checkAgentRuntimeReadiness,
25
- computeFeatureFlagsFromConfig,
26
- isFeatureEnabled,
27
- } from '@principles/core/runtime-v2';
28
- import type {
29
- EffectivePdConfig,
30
- RuntimeProfile,
31
- } from '@principles/core/runtime-v2';
32
- import { resolveRuntimeFromPdConfig } from './resolve-runtime-from-pd-config.js';
33
-
34
- // ── Types ────────────────────────────────────────────────────────────────────
35
-
36
- export type RuleHostReadinessStatus = 'ready' | 'text_principle_only' | 'refused';
37
-
38
- export interface AgentReadiness {
39
- readonly status: 'ready' | 'disabled' | 'not_ready' | 'needs_setup' | 'wrong_profile_type';
40
- readonly reason?: string;
41
- readonly nextAction?: string;
42
- readonly profileId?: string;
43
- readonly profileType?: string;
44
- }
45
-
46
- export interface CodeRuleCapabilityReadiness {
47
- readonly enabled: boolean;
48
- readonly disabledReason?: string;
49
- }
50
-
51
- export interface RuleHostReadinessResult {
52
- readonly status: RuleHostReadinessStatus;
53
- readonly reason: string;
54
- readonly nextAction: string;
55
- readonly agentStatuses: {
56
- readonly dreamer: AgentReadiness;
57
- readonly philosopher: AgentReadiness;
58
- readonly scribe: AgentReadiness;
59
- readonly artificer: AgentReadiness;
60
- readonly evaluator: AgentReadiness;
61
- };
62
- readonly codeRuleCapability: CodeRuleCapabilityReadiness;
63
- }
64
-
65
- /**
66
- * The 5 internal agents that RuleHost readiness checks.
67
- * Narrowed from InternalAgentName so array iteration indexes a known-shape map.
68
- */
69
- type RuleHostAgentName = 'dreamer' | 'philosopher' | 'scribe' | 'artificer' | 'evaluator';
70
-
71
- /**
72
- * Mutable builder type for agentStatuses during construction.
73
- * The readonly RuleHostReadinessResult['agentStatuses'] is assigned from this.
74
- */
75
- interface AgentStatusesMap {
76
- dreamer: AgentReadiness;
77
- philosopher: AgentReadiness;
78
- scribe: AgentReadiness;
79
- artificer: AgentReadiness;
80
- evaluator: AgentReadiness;
81
- }
82
-
83
- // ── Constants ─────────────────────────────────────────────────────────────────
84
-
85
- /**
86
- * Agents required for the text-principle path (dreamer → philosopher → scribe).
87
- * If any of these is not ready, the pipeline cannot produce even text principles.
88
- */
89
- const REQUIRED_AGENTS: readonly RuleHostAgentName[] = ['dreamer', 'philosopher', 'scribe'];
90
-
91
- /**
92
- * Agents required for the code-rule capability (artificer + evaluator).
93
- * Both must be ready for the adversarial loop to run.
94
- */
95
- const CODE_RULE_AGENTS: readonly RuleHostAgentName[] = ['artificer', 'evaluator'];
96
-
97
- // ── Implementation ────────────────────────────────────────────────────────────
98
-
99
- /**
100
- * Check a single agent's readiness for the RuleHost pipeline.
101
- *
102
- * Checks (in order):
103
- * 1. Agent enabled (via resolveAgentRuntimeBinding)
104
- * 2. Profile exists (via resolveAgentRuntimeBinding)
105
- * 3. Profile type is 'pi-ai' (RuleHost needs PiAiRuntimeAdapter)
106
- * 4. Profile is ready (via checkAgentRuntimeReadiness — provider/model/apiKeyEnv set, env var exists)
107
- *
108
- * Returns a structured AgentReadiness result. Never throws.
109
- */
110
- function checkAgentReadiness(
111
- effective: EffectivePdConfig,
112
- agentName: RuleHostAgentName,
113
- getEnvVar: (name: string) => string | undefined,
114
- ): AgentReadiness {
115
- const binding = resolveAgentRuntimeBinding(effective, agentName);
116
-
117
- if (!binding.ok) {
118
- return {
119
- status: binding.readiness === 'disabled' ? 'disabled' : binding.readiness === 'needs_setup' ? 'needs_setup' : 'not_ready',
120
- reason: binding.reason,
121
- nextAction: binding.nextAction,
122
- };
123
- }
124
-
125
- const profile: RuntimeProfile = binding.profile;
126
- const profileType = profile.type;
127
-
128
- // RuleHost pipeline constructs PiAiRuntimeAdapter instances, so the profile
129
- // must be pi-ai. OpenClaw profiles delegate to OpenClaw's own runtime, which
130
- // is not available in the RuleHost pipeline context.
131
- if (profileType !== 'pi-ai') {
132
- return {
133
- status: 'wrong_profile_type',
134
- reason: `Agent '${agentName}' uses profile '${binding.profileId}' with type '${profileType}', but RuleHost requires pi-ai profile type`,
135
- nextAction: `Add a pi-ai runtime profile to .pd/config.yaml and assign it to ${agentName} via internalAgents.agents.${agentName}.runtimeProfile`,
136
- profileId: binding.profileId,
137
- profileType,
138
- };
139
- }
140
-
141
- const readiness = checkAgentRuntimeReadiness(profile, getEnvVar);
142
- if (readiness.readiness !== 'ready') {
143
- return {
144
- status: readiness.readiness === 'needs_setup' ? 'needs_setup' : 'not_ready',
145
- reason: readiness.reason,
146
- nextAction: readiness.nextAction,
147
- profileId: binding.profileId,
148
- profileType,
149
- };
150
- }
151
-
152
- return {
153
- status: 'ready',
154
- profileId: binding.profileId,
155
- profileType,
156
- };
157
- }
158
-
159
- // ── Helpers (defined before public function to satisfy no-use-before-define) ──
160
-
161
- interface ReadinessResultParts {
162
- readonly agentStatuses: AgentStatusesMap;
163
- readonly codeRuleCapability: CodeRuleCapabilityReadiness;
164
- }
165
-
166
- function emptyAgentStatuses(): AgentStatusesMap {
167
- const empty: AgentReadiness = { status: 'not_ready', reason: 'not checked' };
168
- return {
169
- dreamer: empty,
170
- philosopher: empty,
171
- scribe: empty,
172
- artificer: empty,
173
- evaluator: empty,
174
- };
175
- }
176
-
177
- function buildRefusedResult(
178
- reason: string,
179
- nextAction: string,
180
- parts: ReadinessResultParts,
181
- ): RuleHostReadinessResult {
182
- return {
183
- status: 'refused',
184
- reason,
185
- nextAction,
186
- agentStatuses: parts.agentStatuses,
187
- codeRuleCapability: parts.codeRuleCapability,
188
- };
189
- }
190
-
191
- function buildTextPrincipleOnlyResult(
192
- reason: string,
193
- nextAction: string,
194
- parts: ReadinessResultParts,
195
- ): RuleHostReadinessResult {
196
- return {
197
- status: 'text_principle_only',
198
- reason,
199
- nextAction,
200
- agentStatuses: parts.agentStatuses,
201
- codeRuleCapability: parts.codeRuleCapability,
202
- };
203
- }
204
-
205
- function resolveRuleHostReadinessUnchecked(
206
- workspaceDir: string,
207
- getEnvVar: (name: string) => string | undefined,
208
- ): RuleHostReadinessResult {
209
- // ── Step 1: Load config ──
210
- const { configLoadResult } = resolveRuntimeFromPdConfig(workspaceDir, { getEnvVar });
211
-
212
- if (!configLoadResult.ok) {
213
- const [firstError] = configLoadResult.errors;
214
- const reason = `config_malformed: ${firstError?.reason ?? 'unknown config error'}`;
215
- const nextAction = firstError?.nextAction ?? 'Fix .pd/config.yaml syntax and retry';
216
- return buildRefusedResult(reason, nextAction, {
217
- agentStatuses: emptyAgentStatuses(),
218
- codeRuleCapability: { enabled: false, disabledReason: 'config_malformed' },
219
- });
220
- }
221
-
222
- const { effective } = configLoadResult;
223
-
224
- // ── Step 2: Check required agents (dreamer, philosopher, scribe) ──
225
- // Start with all 5 keys set to 'not checked'; updated as each agent is checked.
226
- const agentStatuses: AgentStatusesMap = emptyAgentStatuses();
227
- const requiredFailures: string[] = [];
228
-
229
- for (const agentName of REQUIRED_AGENTS) {
230
- const readiness = checkAgentReadiness(effective, agentName, getEnvVar);
231
- agentStatuses[agentName] = readiness;
232
- if (readiness.status !== 'ready') {
233
- requiredFailures.push(`${agentName}: ${readiness.reason ?? readiness.status}`);
234
- }
235
- }
236
-
237
- if (requiredFailures.length > 0) {
238
- const reason = `required_agents_not_ready: ${requiredFailures.join('; ')}`;
239
- const nextAction = `Fix the following agent issues in .pd/config.yaml: ${requiredFailures.join('; ')}. RuleHost requires dreamer, philosopher, and scribe agents to be enabled with pi-ai runtime profiles and valid API keys.`;
240
- return buildRefusedResult(reason, nextAction, {
241
- agentStatuses,
242
- codeRuleCapability: { enabled: false, disabledReason: 'required_agents_not_ready' },
243
- });
244
- }
245
-
246
- // ── Step 3: Check code_rule_capability feature flag ──
247
- const featureFlags = computeFeatureFlagsFromConfig(effective);
248
- if (!isFeatureEnabled(featureFlags, 'code_rule_capability')) {
249
- const reason = 'code_rule_capability feature flag is disabled';
250
- const nextAction = "Enable code_rule_capability in .pd/config.yaml features.code_rule_capability.enabled to run the full adversarial pipeline. Text-principle-only mode is available.";
251
- // Still check artificer/evaluator for reporting, but they don't affect the status
252
- for (const agentName of CODE_RULE_AGENTS) {
253
- agentStatuses[agentName] = checkAgentReadiness(effective, agentName, getEnvVar);
254
- }
255
- return buildTextPrincipleOnlyResult(reason, nextAction, {
256
- agentStatuses,
257
- codeRuleCapability: { enabled: false, disabledReason: reason },
258
- });
259
- }
260
-
261
- // ── Step 4: Check code-rule agents (artificer, evaluator) ──
262
- const codeRuleFailures: string[] = [];
263
-
264
- for (const agentName of CODE_RULE_AGENTS) {
265
- const readiness = checkAgentReadiness(effective, agentName, getEnvVar);
266
- agentStatuses[agentName] = readiness;
267
- if (readiness.status !== 'ready') {
268
- codeRuleFailures.push(`${agentName}: ${readiness.reason ?? readiness.status}`);
269
- }
270
- }
271
-
272
- if (codeRuleFailures.length > 0) {
273
- const reason = `code_rule_agents_not_ready: ${codeRuleFailures.join('; ')}`;
274
- const nextAction = `Fix the following agent issues to enable code-rule capability: ${codeRuleFailures.join('; ')}. Text-principle-only mode is available with the current configuration.`;
275
- return buildTextPrincipleOnlyResult(reason, nextAction, {
276
- agentStatuses,
277
- codeRuleCapability: { enabled: false, disabledReason: reason },
278
- });
279
- }
280
-
281
- // ── Step 5: All checks pass → ready ──
282
- return {
283
- status: 'ready',
284
- reason: 'All agents ready with pi-ai profiles and valid API keys. Code-rule capability is ON.',
285
- nextAction: 'Pass --confirm to run the full pipeline.',
286
- agentStatuses,
287
- codeRuleCapability: { enabled: true },
288
- };
289
- }
290
-
291
- /**
292
- * Resolve RuleHost readiness from the workspace's .pd/config.yaml.
293
- *
294
- * This is the production entry point called by the `run-rulehost` handler
295
- * BEFORE constructing any adapters. It returns a structured result so the
296
- * handler can emit a clear status instead of an opaque adapter-resolution failure.
297
- *
298
- * This function NEVER throws. Any unexpected exception from config loading,
299
- * feature-flag computation, agent checks, or getEnvVar is caught and converted
300
- * to a `refused` result with reason + nextAction (Runtime Contract #9).
301
- *
302
- * @param workspaceDir - The workspace directory containing .pd/config.yaml
303
- * @param getEnvVar - Env var accessor, defaults to process.env. Injected for testability.
304
- * @returns Structured readiness result. Never throws.
305
- */
306
- export function resolveRuleHostReadiness(
307
- workspaceDir: string,
308
- getEnvVar: (name: string) => string | undefined = (name) => process.env[name],
309
- ): RuleHostReadinessResult {
310
- try {
311
- return resolveRuleHostReadinessUnchecked(workspaceDir, getEnvVar);
312
- } catch (error: unknown) {
313
- const message =
314
- error instanceof Error && error.message.length > 0
315
- ? error.message
316
- : 'unknown readiness resolution error';
317
- return buildRefusedResult(
318
- `readiness_resolution_failed: ${message}`,
319
- 'Fix the readiness resolution error and retry. Run `pd config doctor` for diagnostics.',
320
- {
321
- agentStatuses: emptyAgentStatuses(),
322
- codeRuleCapability: { enabled: false, disabledReason: 'readiness_resolution_failed' },
323
- },
324
- );
325
- }
326
- }
@@ -1,364 +0,0 @@
1
- /**
2
- * PRI-431 Step 3: Shared runtime-adapter resolver.
3
- *
4
- * Extracted from duplicated `resolveRuntimeAdapter` in:
5
- * - packages/pd-cli/src/commands/runtime-internalization-run-once.ts (L222-551)
6
- * - packages/pd-cli/src/commands/diagnose.ts (L186-334, inline)
7
- *
8
- * Design decisions:
9
- * - Test-double payloads stay call-site-specific via `testDoublePayloadBuilder` callback.
10
- * The 7 internalization runner payloads (philosopher/scribe/artificer/...) are unique
11
- * to run-once.ts; the diagnostician payload is unique to diagnose.ts. Unifying them
12
- * would couple unrelated domains.
13
- * - CLI-gate concerns (process.exit, telemetry, help text) stay at call sites.
14
- * This resolver throws structured `ConfigResolutionError` that handlers translate.
15
- * - Lives in pd-cli/services (NOT core) because it constructs adapters and reads
16
- * PD config via `loadPdConfig` + `computeFlagsFromLoadResult`, which are pd-cli services.
17
- *
18
- * ERR refs:
19
- * - ERR-001 (no any): all types explicit
20
- * - ERR-005 (no as bypass): no type casts
21
- * - ERR-009 (fail-loud): ConfigResolutionError thrown with structured fields
22
- * - ERR-013 (Object.hasOwn): feature flag check uses Object.hasOwn
23
- * - ERR-002 (graceful degradation with reason): structured error includes reason + nextAction
24
- */
25
-
26
- import {
27
- TestDoubleRuntimeAdapter,
28
- PiAiRuntimeAdapter,
29
- OpenClawCliRuntimeAdapter,
30
- L2AgentLoopAdapter,
31
- buildL2PrincipleReaderFromLedger,
32
- isRuntimeConfigError,
33
- validateRuntimeConfig,
34
- } from '@principles/core/runtime-v2';
35
- import type { PDRuntimeAdapter, PdL2ArtifactReader, RuntimeConfig, RuntimeConfigResult, InternalAgentName } from '@principles/core/runtime-v2';
36
- import { loadLedger } from '@principles/core/principle-tree-ledger';
37
- import { loadPdConfig, computeFlagsFromLoadResult } from './pd-config-loader.js';
38
- import { resolveRuntimeFromPdConfig } from './resolve-runtime-from-pd-config.js';
39
- import type { ResolvedRuntimeFromPdConfig } from './resolve-runtime-from-pd-config.js';
40
-
41
- // ── Error class ────────────────────────────────────────────────────────────
42
-
43
- export type ConfigResolutionErrorKind =
44
- | 'missing-fields'
45
- | 'invalid-config'
46
- | 'unsupported-runtime'
47
- | 'test-double-refused';
48
-
49
- export interface ConfigResolutionErrorDetails {
50
- /** Required fields that are missing (for 'missing-fields' kind). */
51
- missing?: string[];
52
- /** Structured next action for the operator (CLI Operator Gate rule #6). */
53
- nextAction?: string;
54
- }
55
-
56
- export class ConfigResolutionError extends Error {
57
- readonly kind: ConfigResolutionErrorKind;
58
- readonly missing?: string[];
59
- readonly nextAction?: string;
60
-
61
- constructor(
62
- message: string,
63
- kind: ConfigResolutionErrorKind,
64
- details?: ConfigResolutionErrorDetails,
65
- ) {
66
- super(message);
67
- this.name = 'ConfigResolutionError';
68
- this.kind = kind;
69
- this.missing = details?.missing;
70
- this.nextAction = details?.nextAction;
71
- }
72
- }
73
-
74
- // ── Options interface ──────────────────────────────────────────────────────
75
-
76
- export interface ResolveAdapterOptions {
77
- /** Runtime kind: 'test-double' | 'pi-ai' | 'openclaw-cli' | 'config' */
78
- runtimeKind: string;
79
- /** Workspace directory (for config resolution + feature flags) */
80
- workspaceDir: string;
81
- /** Runner kind (for L2 dreamer routing). Optional. */
82
- runnerKind?: string;
83
- /**
84
- * PRI-719: internal agent whose runtimeProfile binding resolves
85
- * (default 'diagnostician'). run-once passes the selected runner's agent
86
- * so each stage executes on its own declared profile.
87
- */
88
- agentName?: InternalAgentName;
89
- /**
90
- * PRI-719 review: resolve the binding even when the agent is disabled —
91
- * peer execution scope is the internalization_full_chain flag (auto-
92
- * consumer AND explicit run-once), not agents[kind].enabled. Omitted by
93
- * non-peer callers (probe/diagnose) which keep honoring `enabled`.
94
- */
95
- ignoreAgentEnabled?: boolean;
96
- /** CLI timeout override. Takes precedence over config timeoutMs. */
97
- timeoutMs?: number;
98
- /**
99
- * Whether test-double runtime is allowed. Default: false.
100
- * When false, 'test-double' runtimeKind throws ConfigResolutionError.
101
- */
102
- allowTestDouble?: boolean;
103
- /**
104
- * Call-site-specific test-double payload builder.
105
- * Required when runtimeKind === 'test-double' and allowTestDouble === true.
106
- * Receives the full opts object so the builder can access taskId, runnerKind, etc.
107
- */
108
- testDoublePayloadBuilder?: (opts: ResolveAdapterOptions) => PDRuntimeAdapter;
109
- /**
110
- * CLI overrides for pi-ai runtime (from --provider, --model, etc. flags).
111
- * When provided, these take precedence over config values.
112
- */
113
- piAiOverrides?: {
114
- provider?: string;
115
- model?: string;
116
- apiKeyEnv?: string;
117
- baseUrl?: string;
118
- maxRetries?: number;
119
- maxTokens?: number;
120
- };
121
- /**
122
- * CLI override for openclaw mode (from --openclaw-local / --openclaw-gateway flags).
123
- * When provided, takes precedence over config openclawMode.
124
- */
125
- openclawMode?: 'local' | 'gateway';
126
- /** PRI-419: L2 artifact reader (only used when l2_dreamer is on). */
127
- l2ArtifactReader?: PdL2ArtifactReader;
128
- /** PRI-419: workspace stateDir for L2 principle reader (only used when l2_dreamer is on). */
129
- l2StateDir?: string;
130
- /** PRI-431 Step 1d: CLI agentId override for openclaw-cli (from --agent flag). Default: 'main'. */
131
- agentId?: string;
132
- /**
133
- * PRI-431 Step 1d: Whether config resolution errors are tolerated (proceed with CLI overrides alone).
134
- * When true, pi-ai branch skips validateRuntimeConfig and uses manual missing-field check.
135
- * Default: false (config errors throw ConfigResolutionError).
136
- */
137
- configOptional?: boolean;
138
- /**
139
- * PRI-431 Step 1d: Whether to validate that process.env[apiKeyEnv] is set before
140
- * constructing PiAiRuntimeAdapter. Default: false (env var check stays at call site for backward compat).
141
- */
142
- validateApiKeyEnv?: boolean;
143
- /**
144
- * PRI-431 Step 1d: Callback invoked with the full resolved config object (including legacyWarnings)
145
- * after successful config resolution. Useful for telemetry, legacyWarnings printing, etc.
146
- * NOT called for test-double branch (no config resolution).
147
- * Called even when config returns error IF configOptional is true.
148
- */
149
- onConfigResolved?: (resolved: ResolvedRuntimeFromPdConfig) => void;
150
- }
151
-
152
- // ── Resolver function ──────────────────────────────────────────────────────
153
-
154
- export function resolveRuntimeAdapterFromConfig(opts: ResolveAdapterOptions): PDRuntimeAdapter {
155
- // ── test-double branch ──────────────────────────────────────────────────
156
- if (opts.runtimeKind === 'test-double') {
157
- if (!opts.allowTestDouble) {
158
- throw new ConfigResolutionError(
159
- 'runtimeKind "test-double" requires allowTestDouble=true.',
160
- 'test-double-refused',
161
- { nextAction: 'Pass --allow-test-double or use a production runtime kind.' },
162
- );
163
- }
164
- if (!opts.testDoublePayloadBuilder) {
165
- throw new ConfigResolutionError(
166
- 'runtimeKind "test-double" requires testDoublePayloadBuilder callback.',
167
- 'missing-fields',
168
- {
169
- missing: ['testDoublePayloadBuilder'],
170
- nextAction:
171
- 'Provide a testDoublePayloadBuilder function that constructs the test-double adapter.',
172
- },
173
- );
174
- }
175
- return opts.testDoublePayloadBuilder(opts);
176
- }
177
-
178
- // ── Resolve config from .pd/config.yaml (for pi-ai, openclaw-cli, config) ──
179
- const resolved = resolveRuntimeFromPdConfig(opts.workspaceDir, {
180
- agentName: opts.agentName,
181
- ignoreAgentEnabled: opts.ignoreAgentEnabled,
182
- });
183
- const configResult: RuntimeConfigResult = resolved.result;
184
-
185
- // PRI-431 Step 1d: invoke onConfigResolved callback (for telemetry, legacyWarnings, etc.)
186
- opts.onConfigResolved?.(resolved);
187
-
188
- if (isRuntimeConfigError(configResult)) {
189
- if (!opts.configOptional) {
190
- throw new ConfigResolutionError(
191
- `Config resolution from .pd/config.yaml failed: ${configResult.reason}. ${configResult.message}`,
192
- 'invalid-config',
193
- { nextAction: configResult.nextAction },
194
- );
195
- }
196
- // configOptional=true: proceed with CLI overrides alone (pi-ai branch handles missing fields)
197
- }
198
-
199
- // ── pi-ai branch ────────────────────────────────────────────────────────
200
- // When runtimeKind === 'config', configResult must be a valid RuntimeConfig
201
- // (if it were an error and !configOptional, we threw above; if configOptional,
202
- // the caller passes an explicit runtimeKind, never 'config'). The type guard
203
- // also narrows for TypeScript.
204
- const isPiAi =
205
- opts.runtimeKind === 'pi-ai' ||
206
- (opts.runtimeKind === 'config' &&
207
- !isRuntimeConfigError(configResult) &&
208
- configResult.runtimeKind === 'pi-ai');
209
- if (isPiAi) {
210
- // PRI-431 Step 1d + PR review fix: validateRuntimeConfig is only called when
211
- // config is valid AND configOptional is false. When configOptional=true (diagnose.ts),
212
- // skip validateRuntimeConfig to match the original diagnose.ts behavior (which never
213
- // called it — only did a manual missing-field check on merged values). This avoids
214
- // a behavior change where validateRuntimeConfig would reject configs missing baseUrl
215
- // for non-built-in providers, even when the user passes --baseUrl on the CLI.
216
- if (!opts.configOptional && !isRuntimeConfigError(configResult)) {
217
- try {
218
- validateRuntimeConfig(configResult);
219
- } catch (err) {
220
- throw new ConfigResolutionError(
221
- err instanceof Error ? err.message : String(err),
222
- 'invalid-config',
223
- );
224
- }
225
- }
226
-
227
- // Merge CLI overrides with config values (overrides take precedence)
228
- // When configOptional and config failed, configResult fields are unavailable — use empty object
229
- const configFields: Partial<RuntimeConfig> = isRuntimeConfigError(configResult) ? {} : configResult;
230
- const provider = opts.piAiOverrides?.provider ?? configFields.provider;
231
- const model = opts.piAiOverrides?.model ?? configFields.model;
232
- const apiKeyEnv = opts.piAiOverrides?.apiKeyEnv ?? configFields.apiKeyEnv;
233
- const baseUrl = opts.piAiOverrides?.baseUrl ?? configFields.baseUrl;
234
- const maxRetries = opts.piAiOverrides?.maxRetries ?? configFields.maxRetries;
235
- const maxTokens = opts.piAiOverrides?.maxTokens ?? configFields.maxTokens;
236
- const adapterTimeoutMs = opts.timeoutMs ?? configFields.timeoutMs;
237
-
238
- // PRI-431 Step 1d + PR review fix: manual missing-field check on MERGED values
239
- // when configOptional=true. The original diagnose.ts always did this check on merged
240
- // values (not just when config failed), so we replicate that here. This covers both
241
- // the "config failed" case and the "config valid but missing fields not in config" case.
242
- if (opts.configOptional) {
243
- const missing: string[] = [];
244
- if (!provider) missing.push('provider');
245
- if (!model) missing.push('model');
246
- if (!apiKeyEnv) missing.push('apiKeyEnv');
247
- if (missing.length > 0) {
248
- throw new ConfigResolutionError(
249
- `Missing required pi-ai config: ${missing.join(', ')}.`,
250
- 'missing-fields',
251
- {
252
- missing,
253
- nextAction:
254
- 'Pass --provider, --model, --apiKeyEnv flags or configure .pd/config.yaml runtime profile.',
255
- },
256
- );
257
- }
258
- }
259
-
260
- // PRI-431 Step 1d: validate API key env var when requested
261
- if (opts.validateApiKeyEnv && apiKeyEnv && !process.env[apiKeyEnv]) {
262
- throw new ConfigResolutionError(
263
- `Environment variable '${apiKeyEnv}' is not set.`,
264
- 'invalid-config',
265
- {
266
- nextAction:
267
- 'Set the env var (e.g., export OPENAI_API_KEY=...) or choose a different apiKeyEnv.',
268
- },
269
- );
270
- }
271
-
272
- // PRI-419: L2 dreamer sub-branch — when l2_dreamer flag is on AND this is the
273
- // dreamer runner, route through the L2 multi-turn agent loop adapter.
274
- // Other runners (philosopher/scribe/...) stay on L1.
275
- if (opts.runnerKind === 'dreamer' && opts.l2ArtifactReader && opts.l2StateDir) {
276
- const effectiveFlags = computeFlagsFromLoadResult(loadPdConfig(opts.workspaceDir));
277
- const l2FlagDef = Object.hasOwn(effectiveFlags.flags, 'l2_dreamer')
278
- ? effectiveFlags.flags.l2_dreamer
279
- : undefined;
280
- const l2Flag = l2FlagDef ? l2FlagDef.enabled : false;
281
- if (l2Flag) {
282
- return new L2AgentLoopAdapter(
283
- {
284
- provider: String(provider),
285
- model: String(model),
286
- apiKeyEnv: String(apiKeyEnv),
287
- baseUrl,
288
- workspace: opts.workspaceDir,
289
- totalBudgetMs: adapterTimeoutMs,
290
- // PRI-633: profile systemPrompt rides as the append layer.
291
- ...(configFields.systemPrompt ? { systemPrompt: configFields.systemPrompt } : {}),
292
- },
293
- {
294
- artifactReader: opts.l2ArtifactReader,
295
- principleReader: buildL2PrincipleReaderFromLedger(loadLedger(opts.l2StateDir)),
296
- },
297
- );
298
- }
299
- }
300
-
301
- return new PiAiRuntimeAdapter({
302
- provider: String(provider),
303
- model: String(model),
304
- apiKeyEnv: String(apiKeyEnv),
305
- maxRetries,
306
- maxTokens,
307
- timeoutMs: adapterTimeoutMs,
308
- baseUrl,
309
- workspace: opts.workspaceDir,
310
- // PRI-758: profile reasoning level rides to pi-ai (always-thinking zai models).
311
- ...(configFields.reasoning !== undefined ? { reasoning: configFields.reasoning } : {}),
312
- ...(configFields.systemPrompt ? { systemPrompt: configFields.systemPrompt } : {}),
313
- });
314
- }
315
-
316
- // ── openclaw-cli branch ─────────────────────────────────────────────────
317
- const isOpenClawCli =
318
- opts.runtimeKind === 'openclaw-cli' ||
319
- (opts.runtimeKind === 'config' &&
320
- !isRuntimeConfigError(configResult) &&
321
- configResult.runtimeKind === 'openclaw-cli');
322
- if (isOpenClawCli) {
323
- // PRI-431 Step 1d: handle configOptional — when config failed, configFields is empty
324
- const openclawConfigFields: Partial<RuntimeConfig> = isRuntimeConfigError(configResult)
325
- ? {}
326
- : configResult;
327
- // CLI override takes precedence over config
328
- const openclawMode = opts.openclawMode ?? openclawConfigFields.openclawMode;
329
- if (!openclawMode) {
330
- throw new ConfigResolutionError(
331
- "runtimeKind 'openclaw-cli' requires openclawMode.",
332
- 'missing-fields',
333
- {
334
- missing: ['openclawMode'],
335
- nextAction:
336
- 'Add openclawMode: local|gateway to your .pd/config.yaml runtime profile or use --openclaw-local/--openclaw-gateway flags.',
337
- },
338
- );
339
- }
340
- // PRI-431 Step 1d: only pass agentId when explicitly provided (backward compat with run-once.ts)
341
- const openclawAdapterOpts: {
342
- runtimeMode: 'local' | 'gateway';
343
- workspaceDir: string;
344
- agentId?: string;
345
- } = {
346
- runtimeMode: openclawMode,
347
- workspaceDir: opts.workspaceDir,
348
- };
349
- if (opts.agentId !== undefined) {
350
- openclawAdapterOpts.agentId = opts.agentId;
351
- }
352
- return new OpenClawCliRuntimeAdapter(openclawAdapterOpts);
353
- }
354
-
355
- // ── Unsupported runtime ────────────────────────────────────────────────
356
- throw new Error(
357
- `Unsupported runtime kind: ${opts.runtimeKind}. Supported: test-double, pi-ai, openclaw-cli, config`,
358
- );
359
- }
360
-
361
- // ── Re-exports for call-site convenience ───────────────────────────────────
362
- // These allow call sites to import everything from one module.
363
- export type { RuntimeConfig, RuntimeConfigResult };
364
- export { TestDoubleRuntimeAdapter, isRuntimeConfigError, validateRuntimeConfig };