@principles/pd-cli 1.152.12 → 1.152.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (296) hide show
  1. package/package.json +13 -7
  2. package/CHANGELOG.md +0 -23
  3. package/dist/commands/__tests__/intent-flag-wiring.test.d.ts +0 -9
  4. package/dist/commands/__tests__/intent-flag-wiring.test.d.ts.map +0 -1
  5. package/dist/commands/__tests__/intent-flag-wiring.test.js +0 -237
  6. package/dist/commands/__tests__/intent-flag-wiring.test.js.map +0 -1
  7. package/dist/commands/__tests__/legacy-cleanup.test.d.ts +0 -18
  8. package/dist/commands/__tests__/legacy-cleanup.test.d.ts.map +0 -1
  9. package/dist/commands/__tests__/legacy-cleanup.test.js +0 -467
  10. package/dist/commands/__tests__/legacy-cleanup.test.js.map +0 -1
  11. package/dist/commands/__tests__/mvp-smoke.test.d.ts +0 -15
  12. package/dist/commands/__tests__/mvp-smoke.test.d.ts.map +0 -1
  13. package/dist/commands/__tests__/mvp-smoke.test.js +0 -262
  14. package/dist/commands/__tests__/mvp-smoke.test.js.map +0 -1
  15. package/dist/commands/__tests__/pain-retry-maxTokens-flag.test.d.ts +0 -2
  16. package/dist/commands/__tests__/pain-retry-maxTokens-flag.test.d.ts.map +0 -1
  17. package/dist/commands/__tests__/pain-retry-maxTokens-flag.test.js +0 -60
  18. package/dist/commands/__tests__/pain-retry-maxTokens-flag.test.js.map +0 -1
  19. package/dist/commands/__tests__/rulecode-flag-wiring.test.d.ts +0 -21
  20. package/dist/commands/__tests__/rulecode-flag-wiring.test.d.ts.map +0 -1
  21. package/dist/commands/__tests__/rulecode-flag-wiring.test.js +0 -186
  22. package/dist/commands/__tests__/rulecode-flag-wiring.test.js.map +0 -1
  23. package/dist/commands/__tests__/rulecode-handler.test.d.ts +0 -16
  24. package/dist/commands/__tests__/rulecode-handler.test.d.ts.map +0 -1
  25. package/dist/commands/__tests__/rulecode-handler.test.js +0 -285
  26. package/dist/commands/__tests__/rulecode-handler.test.js.map +0 -1
  27. package/dist/commands/__tests__/run-rulehost-flag-wiring.test.d.ts +0 -24
  28. package/dist/commands/__tests__/run-rulehost-flag-wiring.test.d.ts.map +0 -1
  29. package/dist/commands/__tests__/run-rulehost-flag-wiring.test.js +0 -232
  30. package/dist/commands/__tests__/run-rulehost-flag-wiring.test.js.map +0 -1
  31. package/dist/commands/__tests__/runtime-activation-nextaction.test.d.ts +0 -15
  32. package/dist/commands/__tests__/runtime-activation-nextaction.test.d.ts.map +0 -1
  33. package/dist/commands/__tests__/runtime-activation-nextaction.test.js +0 -73
  34. package/dist/commands/__tests__/runtime-activation-nextaction.test.js.map +0 -1
  35. package/dist/commands/__tests__/runtime-probe-config.test.d.ts +0 -20
  36. package/dist/commands/__tests__/runtime-probe-config.test.d.ts.map +0 -1
  37. package/dist/commands/__tests__/runtime-probe-config.test.js +0 -389
  38. package/dist/commands/__tests__/runtime-probe-config.test.js.map +0 -1
  39. package/dist/commands/__tests__/telemetry-flag-wiring.test.d.ts +0 -9
  40. package/dist/commands/__tests__/telemetry-flag-wiring.test.d.ts.map +0 -1
  41. package/dist/commands/__tests__/telemetry-flag-wiring.test.js +0 -76
  42. package/dist/commands/__tests__/telemetry-flag-wiring.test.js.map +0 -1
  43. package/dist/commands/__tests__/version.test.d.ts +0 -2
  44. package/dist/commands/__tests__/version.test.d.ts.map +0 -1
  45. package/dist/commands/__tests__/version.test.js +0 -238
  46. package/dist/commands/__tests__/version.test.js.map +0 -1
  47. package/dist/commands/runtime-uat.guard.test.d.ts +0 -2
  48. package/dist/commands/runtime-uat.guard.test.d.ts.map +0 -1
  49. package/dist/commands/runtime-uat.guard.test.js +0 -153
  50. package/dist/commands/runtime-uat.guard.test.js.map +0 -1
  51. package/dist/services/__tests__/cli-output.test.d.ts +0 -18
  52. package/dist/services/__tests__/cli-output.test.d.ts.map +0 -1
  53. package/dist/services/__tests__/cli-output.test.js +0 -103
  54. package/dist/services/__tests__/cli-output.test.js.map +0 -1
  55. package/dist/services/__tests__/evaluator-runner-deps.test.d.ts +0 -2
  56. package/dist/services/__tests__/evaluator-runner-deps.test.d.ts.map +0 -1
  57. package/dist/services/__tests__/evaluator-runner-deps.test.js +0 -343
  58. package/dist/services/__tests__/evaluator-runner-deps.test.js.map +0 -1
  59. package/dist/services/__tests__/rulehost-readiness.test.d.ts +0 -2
  60. package/dist/services/__tests__/rulehost-readiness.test.d.ts.map +0 -1
  61. package/dist/services/__tests__/rulehost-readiness.test.js +0 -311
  62. package/dist/services/__tests__/rulehost-readiness.test.js.map +0 -1
  63. package/dist/services/__tests__/runtime-adapter-resolver.test.d.ts +0 -18
  64. package/dist/services/__tests__/runtime-adapter-resolver.test.d.ts.map +0 -1
  65. package/dist/services/__tests__/runtime-adapter-resolver.test.js +0 -673
  66. package/dist/services/__tests__/runtime-adapter-resolver.test.js.map +0 -1
  67. package/dist/utils/production-workspace-guard.test.d.ts +0 -2
  68. package/dist/utils/production-workspace-guard.test.d.ts.map +0 -1
  69. package/dist/utils/production-workspace-guard.test.js +0 -137
  70. package/dist/utils/production-workspace-guard.test.js.map +0 -1
  71. package/scripts/llm-dogfood.ts +0 -456
  72. package/scripts/migrate-illegal-expected-decision.ts +0 -252
  73. package/src/commands/__tests__/intent-flag-wiring.test.ts +0 -282
  74. package/src/commands/__tests__/legacy-cleanup.test.ts +0 -602
  75. package/src/commands/__tests__/mvp-smoke.test.ts +0 -300
  76. package/src/commands/__tests__/pain-retry-maxTokens-flag.test.ts +0 -73
  77. package/src/commands/__tests__/rulecode-flag-wiring.test.ts +0 -237
  78. package/src/commands/__tests__/rulecode-handler.test.ts +0 -369
  79. package/src/commands/__tests__/run-rulehost-flag-wiring.test.ts +0 -292
  80. package/src/commands/__tests__/runtime-activation-nextaction.test.ts +0 -81
  81. package/src/commands/__tests__/runtime-probe-config.test.ts +0 -432
  82. package/src/commands/__tests__/telemetry-flag-wiring.test.ts +0 -84
  83. package/src/commands/__tests__/version.test.ts +0 -251
  84. package/src/commands/admission-gate.ts +0 -30
  85. package/src/commands/artifact.ts +0 -82
  86. package/src/commands/build-trajectory-evidence.ts +0 -298
  87. package/src/commands/candidate.ts +0 -1250
  88. package/src/commands/codex-ingest-catchup.ts +0 -114
  89. package/src/commands/codex-ingest-quarantine.ts +0 -127
  90. package/src/commands/codex-reconcile.ts +0 -84
  91. package/src/commands/codex-setup.ts +0 -476
  92. package/src/commands/codex-worker.ts +0 -185
  93. package/src/commands/command-helpers.ts +0 -24
  94. package/src/commands/config-doctor.ts +0 -193
  95. package/src/commands/console.ts +0 -797
  96. package/src/commands/context.ts +0 -72
  97. package/src/commands/demo-story-a.ts +0 -241
  98. package/src/commands/diagnose.ts +0 -756
  99. package/src/commands/errors-list.ts +0 -441
  100. package/src/commands/evolution-tasks-list.ts +0 -48
  101. package/src/commands/evolution-tasks-show.ts +0 -62
  102. package/src/commands/flow.ts +0 -60
  103. package/src/commands/health-codex.ts +0 -576
  104. package/src/commands/health.ts +0 -315
  105. package/src/commands/history.ts +0 -63
  106. package/src/commands/intent.ts +0 -457
  107. package/src/commands/legacy-cleanup.ts +0 -531
  108. package/src/commands/legacy-import.ts +0 -104
  109. package/src/commands/mvp-smoke.ts +0 -160
  110. package/src/commands/pain-evidence.ts +0 -226
  111. package/src/commands/pain-list.ts +0 -239
  112. package/src/commands/pain-record.ts +0 -612
  113. package/src/commands/pain-retry.ts +0 -916
  114. package/src/commands/principles-stats.ts +0 -700
  115. package/src/commands/proven-channel-baseline.ts +0 -115
  116. package/src/commands/quality-scorecard.ts +0 -272
  117. package/src/commands/remediation-output.ts +0 -66
  118. package/src/commands/rulecode.ts +0 -465
  119. package/src/commands/run.ts +0 -89
  120. package/src/commands/runtime-activation.ts +0 -1629
  121. package/src/commands/runtime-artifact-repair.ts +0 -524
  122. package/src/commands/runtime-canary.ts +0 -395
  123. package/src/commands/runtime-compatibility-scan.ts +0 -105
  124. package/src/commands/runtime-diagnostics-export.ts +0 -229
  125. package/src/commands/runtime-features.ts +0 -153
  126. package/src/commands/runtime-gfi-snapshot.ts +0 -135
  127. package/src/commands/runtime-health-snapshot.ts +0 -108
  128. package/src/commands/runtime-init.ts +0 -429
  129. package/src/commands/runtime-internalization-enqueue-successors.ts +0 -530
  130. package/src/commands/runtime-internalization-integrity-repair.ts +0 -79
  131. package/src/commands/runtime-internalization-integrity.ts +0 -107
  132. package/src/commands/runtime-internalization-queue.ts +0 -135
  133. package/src/commands/runtime-internalization-retry.ts +0 -191
  134. package/src/commands/runtime-internalization-run-once.ts +0 -791
  135. package/src/commands/runtime-internalization-run-rulehost.ts +0 -749
  136. package/src/commands/runtime-internalization-wake-once.ts +0 -87
  137. package/src/commands/runtime-pain-flood-simulation.ts +0 -121
  138. package/src/commands/runtime-pruning.ts +0 -438
  139. package/src/commands/runtime-recovery-failed-tasks.ts +0 -258
  140. package/src/commands/runtime-recovery.ts +0 -109
  141. package/src/commands/runtime-synthetic-baseline.ts +0 -70
  142. package/src/commands/runtime-uat.guard.test.ts +0 -175
  143. package/src/commands/runtime-uat.ts +0 -380
  144. package/src/commands/runtime.ts +0 -473
  145. package/src/commands/samples-list.ts +0 -39
  146. package/src/commands/samples-review.ts +0 -36
  147. package/src/commands/task.ts +0 -271
  148. package/src/commands/telemetry.ts +0 -349
  149. package/src/commands/trace.ts +0 -174
  150. package/src/commands/trajectory-db-unavailable.ts +0 -19
  151. package/src/commands/trajectory.ts +0 -64
  152. package/src/commands/version.ts +0 -49
  153. package/src/config-reader.ts +0 -122
  154. package/src/index.ts +0 -1276
  155. package/src/legacy/legacy-import.ts +0 -179
  156. package/src/legacy/session-history-import.ts +0 -203
  157. package/src/resolve-workspace.ts +0 -106
  158. package/src/services/__tests__/cli-output.test.ts +0 -130
  159. package/src/services/__tests__/evaluator-runner-deps.test.ts +0 -382
  160. package/src/services/__tests__/rulehost-readiness.test.ts +0 -363
  161. package/src/services/__tests__/runtime-adapter-resolver.test.ts +0 -793
  162. package/src/services/cli-output.ts +0 -95
  163. package/src/services/config-doctor.ts +0 -697
  164. package/src/services/console-launcher.ts +0 -537
  165. package/src/services/demo-rule-compiler.ts +0 -40
  166. package/src/services/demo-story-a-runner.ts +0 -471
  167. package/src/services/mainline-snapshot-assembler.ts +0 -579
  168. package/src/services/pain-flood-simulation-runner.ts +0 -462
  169. package/src/services/pd-config-loader.ts +0 -433
  170. package/src/services/proven-channel-baseline-runner.ts +0 -157
  171. package/src/services/quality-scorecard/data-extractor.ts +0 -150
  172. package/src/services/quality-scorecard/local-evaluator.ts +0 -142
  173. package/src/services/quality-scorecard/strong-model-gate.ts +0 -202
  174. package/src/services/resolve-runtime-from-pd-config.ts +0 -230
  175. package/src/services/rulehost-pipeline-runner.ts +0 -1214
  176. package/src/services/rulehost-readiness.ts +0 -326
  177. package/src/services/runtime-adapter-resolver.ts +0 -364
  178. package/src/services/synthetic-baseline-runner.ts +0 -400
  179. package/src/services/version-report.ts +0 -253
  180. package/src/services/workspace-tool-semantics.ts +0 -26
  181. package/src/utils/path-security.ts +0 -96
  182. package/src/utils/production-workspace-guard.test.ts +0 -157
  183. package/src/utils/production-workspace-guard.ts +0 -210
  184. package/tests/bdd/cli-contract.steps.ts +0 -346
  185. package/tests/bdd/principles-stats.steps.ts +0 -211
  186. package/tests/bdd/support/gherkin-loader.ts +0 -147
  187. package/tests/bdd/support/repo-root.ts +0 -62
  188. package/tests/bdd/support/vitest-bdd.ts +0 -179
  189. package/tests/commands/admission-gate-coverage.test.ts +0 -79
  190. package/tests/commands/build-trajectory-evidence.test.ts +0 -508
  191. package/tests/commands/candidate-audit-repair.test.ts +0 -421
  192. package/tests/commands/candidate-intake.test.ts +0 -732
  193. package/tests/commands/candidate-internalization-backfill.test.ts +0 -548
  194. package/tests/commands/candidate-internalize-lineage.test.ts +0 -628
  195. package/tests/commands/candidate-internalize.test.ts +0 -299
  196. package/tests/commands/candidate-route.test.ts +0 -329
  197. package/tests/commands/candidate-show.test.ts +0 -95
  198. package/tests/commands/cli-command-tree.test.ts +0 -144
  199. package/tests/commands/cli-help-snapshot.test.ts +0 -155
  200. package/tests/commands/cli-skill-contract.test.ts +0 -121
  201. package/tests/commands/codex-consent-reversibility.steps.test.ts +0 -299
  202. package/tests/commands/codex-ingest-quarantine.test.ts +0 -136
  203. package/tests/commands/codex-setup.test.ts +0 -297
  204. package/tests/commands/codex-worker-daemon.test.ts +0 -95
  205. package/tests/commands/codex-worker-registration.test.ts +0 -207
  206. package/tests/commands/config-doctor.test.ts +0 -336
  207. package/tests/commands/console-launcher-edge-cases.test.ts +0 -388
  208. package/tests/commands/console-open.test.ts +0 -1381
  209. package/tests/commands/context.test.ts +0 -114
  210. package/tests/commands/demo-story-a.test.ts +0 -318
  211. package/tests/commands/diagnose.test.ts +0 -1803
  212. package/tests/commands/errors-list.test.ts +0 -679
  213. package/tests/commands/evolution-tasks-list.test.ts +0 -41
  214. package/tests/commands/evolution-tasks-show.test.ts +0 -46
  215. package/tests/commands/health-codex.test.ts +0 -349
  216. package/tests/commands/health-host-wiring.test.ts +0 -76
  217. package/tests/commands/health-reliability.test.ts +0 -99
  218. package/tests/commands/health.test.ts +0 -413
  219. package/tests/commands/intent.test.ts +0 -321
  220. package/tests/commands/legacy-cleanup.test.ts +0 -148
  221. package/tests/commands/pain-evidence.test.ts +0 -518
  222. package/tests/commands/pain-list.test.ts +0 -219
  223. package/tests/commands/pain-record-async.test.ts +0 -335
  224. package/tests/commands/pain-record-session-parser.test.ts +0 -228
  225. package/tests/commands/pain-record.test.ts +0 -851
  226. package/tests/commands/pain-retry.test.ts +0 -1121
  227. package/tests/commands/plugin-config-resolution-cutover.test.ts +0 -229
  228. package/tests/commands/pri-393-runtime-config-unification.test.ts +0 -443
  229. package/tests/commands/principles-stats-wiring.test.ts +0 -135
  230. package/tests/commands/principles-stats.test.ts +0 -274
  231. package/tests/commands/product-path-regression.test.ts +0 -86
  232. package/tests/commands/proven-channel-baseline.test.ts +0 -441
  233. package/tests/commands/rulecode.test.ts +0 -177
  234. package/tests/commands/run-rulehost-handler.test.ts +0 -908
  235. package/tests/commands/runtime-activation-approve-flag-wiring.test.ts +0 -227
  236. package/tests/commands/runtime-activation-deactivate-flag-wiring.test.ts +0 -167
  237. package/tests/commands/runtime-activation-dispatch-flag-wiring.test.ts +0 -262
  238. package/tests/commands/runtime-activation-governance-audit.test.ts +0 -95
  239. package/tests/commands/runtime-activation-list-flag-wiring.test.ts +0 -193
  240. package/tests/commands/runtime-activation-promote-flag-wiring.test.ts +0 -248
  241. package/tests/commands/runtime-activation-shadow-telemetry.test.ts +0 -130
  242. package/tests/commands/runtime-activation.test.ts +0 -2052
  243. package/tests/commands/runtime-artifact-repair-registration.test.ts +0 -74
  244. package/tests/commands/runtime-artifact-repair.test.ts +0 -404
  245. package/tests/commands/runtime-canary.test.ts +0 -430
  246. package/tests/commands/runtime-compatibility-scan.test.ts +0 -146
  247. package/tests/commands/runtime-diagnostics-export.test.ts +0 -175
  248. package/tests/commands/runtime-features.test.ts +0 -249
  249. package/tests/commands/runtime-health-snapshot.test.ts +0 -358
  250. package/tests/commands/runtime-init-empty-workspace.test.ts +0 -252
  251. package/tests/commands/runtime-init.test.ts +0 -420
  252. package/tests/commands/runtime-internalization-enqueue-successors.test.ts +0 -782
  253. package/tests/commands/runtime-internalization-integrity-repair.test.ts +0 -239
  254. package/tests/commands/runtime-internalization-integrity.test.ts +0 -140
  255. package/tests/commands/runtime-internalization-queue.test.ts +0 -380
  256. package/tests/commands/runtime-internalization-retry-owner-authority.test.ts +0 -431
  257. package/tests/commands/runtime-internalization-run-once-evaluator-parity.test.ts +0 -269
  258. package/tests/commands/runtime-internalization-run-once-language.test.ts +0 -303
  259. package/tests/commands/runtime-internalization-run-once-real-config.test.ts +0 -237
  260. package/tests/commands/runtime-internalization-run-once-rollout-parity.test.ts +0 -706
  261. package/tests/commands/runtime-internalization-run-once.test.ts +0 -1791
  262. package/tests/commands/runtime-internalization-wake-once.test.ts +0 -171
  263. package/tests/commands/runtime-internalization.test.ts +0 -53
  264. package/tests/commands/runtime-pain-flood-simulation.test.ts +0 -418
  265. package/tests/commands/runtime-pruning.test.ts +0 -694
  266. package/tests/commands/runtime-recovery-failed-tasks.test.ts +0 -328
  267. package/tests/commands/runtime-recovery.test.ts +0 -120
  268. package/tests/commands/runtime-synthetic-baseline.test.ts +0 -249
  269. package/tests/commands/runtime-uat.test.ts +0 -397
  270. package/tests/commands/runtime.test.ts +0 -392
  271. package/tests/commands/samples-list.test.ts +0 -43
  272. package/tests/commands/samples-review.test.ts +0 -41
  273. package/tests/commands/task.test.ts +0 -153
  274. package/tests/commands/telemetry.test.ts +0 -190
  275. package/tests/commands/trace.test.ts +0 -316
  276. package/tests/config-reader.test.ts +0 -143
  277. package/tests/e2e/candidate-intake-e2e.test.ts +0 -338
  278. package/tests/e2e/cli-full-flow.test.ts +0 -233
  279. package/tests/e2e/cross-package-acceptance.test.ts +0 -635
  280. package/tests/helpers/pd-cli-path.ts +0 -5
  281. package/tests/pd-cli-smoke.test.ts +0 -13
  282. package/tests/resolve-workspace.test.ts +0 -196
  283. package/tests/services/config-doctor-signal-health.test.ts +0 -109
  284. package/tests/services/console-launcher.test.ts +0 -114
  285. package/tests/services/demo-rule-compiler.test.ts +0 -242
  286. package/tests/services/mainline-snapshot-assembler.test.ts +0 -572
  287. package/tests/services/pd-config-loader.test.ts +0 -505
  288. package/tests/services/proven-channel-baseline-runner.test.ts +0 -30
  289. package/tests/services/quality-scorecard/strong-model-gate.test.ts +0 -133
  290. package/tests/services/resolve-runtime-from-pd-config.test.ts +0 -485
  291. package/tests/services/rulehost-pipeline-e2e.test.ts +0 -538
  292. package/tests/services/rulehost-pipeline-runner.test.ts +0 -1242
  293. package/tests/services/workspace-tool-semantics.test.ts +0 -76
  294. package/tests/utils/path-security.test.ts +0 -180
  295. package/tsconfig.json +0 -26
  296. package/vitest.config.ts +0 -10
@@ -1,1791 +0,0 @@
1
- import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
2
- import * as path from 'path';
3
-
4
- const VALID_DREAMER_CANDIDATES = [{ candidateIndex: 0, badDecision: 'Ignored validation', betterDecision: 'Validate inputs', rationale: 'Prevents errors', confidence: 0.9, riskLevel: 'low' as const, strategicPerspective: 'defensive-programming' }];
5
-
6
- const mockWakeOnce = vi.fn();
7
- const mockRun = vi.fn();
8
- const mockCommitNextTaskProposal = vi.fn().mockResolvedValue({ decision: 'no_successor', sourceTaskId: '', reason: '' });
9
- const mockClose = vi.fn().mockResolvedValue(undefined);
10
- const mockInitialize = vi.fn().mockResolvedValue(undefined);
11
- const mockPiArtifactStore = {
12
- createArtifact: vi.fn().mockResolvedValue({}),
13
- upsertArtifact: vi.fn().mockResolvedValue({}),
14
- getArtifactById: vi.fn().mockResolvedValue(null),
15
- listBySourceTaskId: vi.fn().mockResolvedValue([]),
16
- listLineage: vi.fn().mockResolvedValue([]),
17
- };
18
-
19
- vi.mock('../../src/resolve-workspace.js', () => ({
20
- resolveWorkspaceDir: vi.fn().mockReturnValue('/fake/workspace'),
21
- }));
22
-
23
- const { mockResolveRuntimeFromPdConfig } = vi.hoisted(() => {
24
- const mockResolveRuntimeFromPdConfig = vi.fn().mockReturnValue({
25
- result: {
26
- runtimeKind: 'pi-ai',
27
- provider: 'test-provider',
28
- model: 'test-model',
29
- apiKeyEnv: 'TEST_API_KEY',
30
- timeoutMs: 300_000,
31
- agentId: 'main',
32
- },
33
- legacyWarnings: [],
34
- configSource: '.pd/config.yaml',
35
- configLoadResult: { ok: true, effective: {}, defaults: {}, legacyFilesDetected: [] },
36
- });
37
- return { mockResolveRuntimeFromPdConfig };
38
- });
39
-
40
- vi.mock('../../src/services/resolve-runtime-from-pd-config.js', () => ({
41
- resolveRuntimeFromPdConfig: mockResolveRuntimeFromPdConfig,
42
- }));
43
-
44
- // PRI-460: Mock pd-config-loader so the shared resolver's L2 dreamer sub-branch
45
- // doesn't call the real loadPdConfig (which needs fs access).
46
- vi.mock('../../src/services/pd-config-loader.js', () => ({
47
- loadPdConfig: vi.fn().mockReturnValue({
48
- ok: true,
49
- effective: {},
50
- source: 'defaults',
51
- configPath: '/fake/workspace/.pd/config.yaml',
52
- warnings: [],
53
- legacyFilesDetected: [],
54
- legacyFileNextActions: [],
55
- }),
56
- computeFlagsFromLoadResult: vi.fn().mockReturnValue({
57
- flags: {},
58
- enabledChannels: [],
59
- warnings: [],
60
- }),
61
- }));
62
-
63
- vi.mock('@principles/core/runtime-v2', () => ({
64
- RuntimeStateManager: vi.fn().mockImplementation(function () {
65
- return {
66
- initialize: mockInitialize,
67
- close: mockClose,
68
- connection: {},
69
- taskStore: {},
70
- runStore: {},
71
- piArtifactStore: mockPiArtifactStore,
72
- };
73
- }),
74
- InternalizationOrchestrator: vi.fn().mockImplementation(function () {
75
- return { wakeOnce: mockWakeOnce, commitNextTaskProposal: mockCommitNextTaskProposal };
76
- }),
77
- DreamerRunner: vi.fn().mockImplementation(function () {
78
- return { run: mockRun };
79
- }),
80
- PhilosopherRunner: vi.fn().mockImplementation(function () {
81
- return { run: mockRun };
82
- }),
83
- ScribeRunner: vi.fn().mockImplementation(function () {
84
- return { run: mockRun };
85
- }),
86
- ArtificerRunner: vi.fn().mockImplementation(function () {
87
- return { run: mockRun };
88
- }),
89
- buildArtificerHostSemanticContext: (registry) => ({ hostKinds: [], tools: registry.hostMappings() }),
90
- EvaluatorRunner: vi.fn().mockImplementation(function () {
91
- return { run: mockRun };
92
- }),
93
- RolloutReviewerRunner: vi.fn().mockImplementation(function () {
94
- return { run: mockRun };
95
- }),
96
- StoreEventEmitter: vi.fn().mockImplementation(function () {
97
- return { emitTelemetry: vi.fn() };
98
- }),
99
- PassThroughDreamerValidator: vi.fn().mockImplementation(function () {
100
- return { validate: vi.fn().mockResolvedValue({ valid: true, errors: [] }) };
101
- }),
102
- DefaultDreamerValidator: vi.fn().mockImplementation(function () {
103
- return { validate: vi.fn().mockResolvedValue({ valid: true, errors: [] }) };
104
- }),
105
- DefaultPhilosopherValidator: vi.fn().mockImplementation(function () {
106
- return { validate: vi.fn().mockResolvedValue({ valid: true, errors: [] }) };
107
- }),
108
- DefaultScribeValidator: vi.fn().mockImplementation(function () {
109
- return { validate: vi.fn().mockResolvedValue({ valid: true, errors: [] }) };
110
- }),
111
- DefaultArtificerValidator: vi.fn().mockImplementation(function () {
112
- return { validate: vi.fn().mockResolvedValue({ valid: true, errors: [] }) };
113
- }),
114
- DefaultEvaluatorValidator: vi.fn().mockImplementation(function () {
115
- return { validate: vi.fn().mockResolvedValue({ valid: true, errors: [] }) };
116
- }),
117
- DefaultRolloutReviewerValidator: vi.fn().mockImplementation(function () {
118
- return { validate: vi.fn().mockResolvedValue({ valid: true, errors: [] }) };
119
- }),
120
- TestDoubleRuntimeAdapter: vi.fn().mockImplementation(function () {
121
- return {
122
- kind: vi.fn().mockReturnValue('test-double'),
123
- getCapabilities: vi.fn(),
124
- healthCheck: vi.fn(),
125
- startRun: vi.fn().mockResolvedValue({ runId: 'run-test-001', runtimeKind: 'test-double', startedAt: new Date().toISOString() }),
126
- pollRun: vi.fn().mockResolvedValue({ runId: 'run-test-001', status: 'succeeded' }),
127
- cancelRun: vi.fn().mockResolvedValue(undefined),
128
- fetchOutput: vi.fn().mockResolvedValue({ runId: 'run-test-001', payload: {} }),
129
- fetchArtifacts: vi.fn().mockResolvedValue([]),
130
- };
131
- }),
132
- PiAiRuntimeAdapter: vi.fn().mockImplementation(function () {
133
- return {
134
- kind: vi.fn().mockReturnValue('pi-ai'),
135
- getCapabilities: vi.fn(),
136
- healthCheck: vi.fn(),
137
- startRun: vi.fn().mockResolvedValue({ runId: 'run-pi-001', runtimeKind: 'pi-ai', startedAt: new Date().toISOString() }),
138
- pollRun: vi.fn().mockResolvedValue({ runId: 'run-pi-001', status: 'succeeded' }),
139
- cancelRun: vi.fn().mockResolvedValue(undefined),
140
- fetchOutput: vi.fn().mockResolvedValue({ runId: 'run-pi-001', payload: {} }),
141
- fetchArtifacts: vi.fn().mockResolvedValue([]),
142
- };
143
- }),
144
- OpenClawCliRuntimeAdapter: vi.fn().mockImplementation(function () {
145
- return {
146
- kind: vi.fn().mockReturnValue('openclaw-cli'),
147
- getCapabilities: vi.fn(),
148
- healthCheck: vi.fn(),
149
- startRun: vi.fn().mockResolvedValue({ runId: 'run-oc-001', runtimeKind: 'openclaw-cli', startedAt: new Date().toISOString() }),
150
- pollRun: vi.fn().mockResolvedValue({ runId: 'run-oc-001', status: 'succeeded' }),
151
- cancelRun: vi.fn().mockResolvedValue(undefined),
152
- fetchOutput: vi.fn().mockResolvedValue({ runId: 'run-oc-001', payload: {} }),
153
- fetchArtifacts: vi.fn().mockResolvedValue([]),
154
- };
155
- }),
156
- resolveRuntimeConfig: vi.fn().mockReturnValue({
157
- runtimeKind: 'pi-ai',
158
- timeoutMs: 300_000,
159
- agentId: 'main',
160
- provider: 'test-provider',
161
- model: 'test-model',
162
- apiKeyEnv: 'TEST_API_KEY',
163
- }),
164
- isRuntimeConfigError: vi.fn().mockImplementation((result: unknown) => result != null && typeof result === 'object' && Object.hasOwn(result, 'reason') && !Object.hasOwn(result, 'runtimeKind')),
165
- validateRuntimeConfig: vi.fn(),
166
- resolveRuntimeConfigFromPdConfig: vi.fn().mockReturnValue({ runtimeKind: 'pi-ai', provider: 'test-provider', model: 'test-model', apiKeyEnv: 'TEST_API_KEY', timeoutMs: 300_000, agentId: 'main' }),
167
- // PRI-719: run-once resolves the SELECTED runner's agent binding through
168
- // the per-agent variant — this is the seam the PRI-670 timeout tests mock.
169
- resolveRuntimeConfigForAgent: vi.fn().mockReturnValue({ runtimeKind: 'pi-ai', provider: 'test-provider', model: 'test-model', apiKeyEnv: 'TEST_API_KEY', timeoutMs: 300_000, agentId: 'main' }),
170
- // PRI-719: the real taskKind→agent mapping (stable constant, mirrored here
171
- // because the whole core module is mocked in this file).
172
- AGENT_NAME_FOR_TASK_KIND: {
173
- dreamer: 'dreamer',
174
- philosopher: 'philosopher',
175
- scribe: 'scribe',
176
- artificer: 'artificer',
177
- evaluator: 'evaluator',
178
- rollout_reviewer: 'rolloutReviewer',
179
- },
180
- resolveOutputLanguage: vi.fn().mockReturnValue({ outputLanguage: 'zh-CN' }),
181
- }));
182
-
183
- vi.mock('../../src/config-reader.js', () => ({
184
- readOutputLanguageFromWorkspace: vi.fn().mockReturnValue({ outputLanguage: 'zh-CN' }),
185
- }));
186
-
187
- // PRI-661: run-once now builds the evaluator replay context through the ONE
188
- // host-runtime builder. Mock just that seam here — the unit tests below prove
189
- // dispatch wiring; the real resolver + declaration fixture path is proven by
190
- // runtime-internalization-run-once-evaluator-parity.test.ts.
191
- // PRI-708: same pattern for the canonical rollout governance factory — unit
192
- // tests assert the run-once handler passes its reopen callback through to the
193
- // runner deps; the real factory + real SQLite path is proven by
194
- // runtime-internalization-run-once-rollout-parity.test.ts.
195
- // PRI-713: dispatchActivation rides the same factory; the durable-provenance
196
- // resolver seam is mocked the same way (real path in the parity test).
197
- const { mockCreateEvaluatorRuntimeContext, mockCreateRolloutGovernanceDeps, mockResolveWorkspaceHostToolSemantics } = vi.hoisted(() => {
198
- const mockCreateEvaluatorRuntimeContext = vi.fn().mockReturnValue({
199
- ok: true,
200
- gateDeps: { evaluateInSandbox: vi.fn() },
201
- // PRI-741: the context resolution also carries the single registry
202
- // snapshot the parity projection derives from.
203
- registry: { resolve: vi.fn(), hostMappings: vi.fn().mockReturnValue([{ rawToolName: 'write', canonicalKind: 'write' }]) },
204
- hostKinds: ['openclaw'],
205
- });
206
- const mockCreateRolloutGovernanceDeps = vi.fn().mockReturnValue({
207
- dispatchActivation: vi.fn(),
208
- reopenRevisionTarget: vi.fn(),
209
- });
210
- const mockResolveWorkspaceHostToolSemantics = vi.fn().mockReturnValue({
211
- ok: true,
212
- // PRI-741: the projection reads the host layer via hostMappings() — the
213
- // mock registry carries it like a real buildToolSemanticRegistry product.
214
- registry: { resolve: vi.fn(), hostMappings: vi.fn().mockReturnValue([{ rawToolName: 'write', canonicalKind: 'write' }]) },
215
- hostKinds: ['openclaw'],
216
- });
217
- return { mockCreateEvaluatorRuntimeContext, mockCreateRolloutGovernanceDeps, mockResolveWorkspaceHostToolSemantics };
218
- });
219
- vi.mock('@principles/host-runtime', () => ({
220
- createEvaluatorRuntimeContext: mockCreateEvaluatorRuntimeContext,
221
- createRolloutGovernanceDeps: mockCreateRolloutGovernanceDeps,
222
- resolveWorkspaceHostToolSemantics: mockResolveWorkspaceHostToolSemantics,
223
- }));
224
-
225
- import { handleRuntimeInternalizationRunOnce } from '../../src/commands/runtime-internalization-run-once.js';
226
-
227
- const WS = '/fake/workspace';
228
-
229
- describe('handleRuntimeInternalizationRunOnce', () => {
230
- let consoleLogSpy: ReturnType<typeof vi.spyOn>;
231
- let consoleErrorSpy: ReturnType<typeof vi.spyOn>;
232
-
233
- beforeEach(() => {
234
- vi.clearAllMocks();
235
- process.exitCode = 0;
236
- consoleLogSpy = vi.spyOn(console, 'log').mockImplementation(() => {});
237
- consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
238
- });
239
-
240
- afterEach(() => {
241
- process.exitCode = 0;
242
- consoleLogSpy.mockRestore();
243
- consoleErrorSpy.mockRestore();
244
- });
245
-
246
- it('test-double without --allow-test-double: refuses to execute and exits 1', async () => {
247
- await handleRuntimeInternalizationRunOnce({ workspace: WS, runtime: 'test-double', allowTestDouble: false });
248
-
249
- expect(process.exitCode).toBe(1);
250
- expect(consoleErrorSpy.mock.calls.some((c: string[]) => c[0].includes('test-double runtime mutates real queue state'))).toBe(true);
251
- expect(mockWakeOnce).not.toHaveBeenCalled();
252
- });
253
-
254
- it('default runtime (config) does not require --allow-test-double', async () => {
255
- mockWakeOnce.mockResolvedValue({
256
- decision: 'would_lease',
257
- taskId: 'task-dreamer-001',
258
- taskKind: 'dreamer',
259
- });
260
-
261
- mockRun.mockResolvedValue({
262
- status: 'succeeded',
263
- taskId: 'task-dreamer-001',
264
- runId: 'run-001',
265
- artifactId: 'pi-art-task-dreamer-001-run-001',
266
- resultRef: 'dreamer://run-001',
267
- contextHash: 'ctx-abc',
268
- output: { valid: true, taskId: 'task-dreamer-001', candidates: VALID_DREAMER_CANDIDATES, contextRefs: [], generatedAt: new Date().toISOString() },
269
- attemptCount: 1,
270
- });
271
-
272
- await handleRuntimeInternalizationRunOnce({ workspace: WS, json: true });
273
-
274
- expect(mockWakeOnce).toHaveBeenCalled();
275
- });
276
-
277
- it('test-double with --allow-test-double: proceeds normally', async () => {
278
- mockWakeOnce.mockResolvedValue({
279
- decision: 'would_lease',
280
- taskId: 'task-dreamer-001',
281
- taskKind: 'dreamer',
282
- });
283
-
284
- mockRun.mockResolvedValue({
285
- status: 'succeeded',
286
- taskId: 'task-dreamer-001',
287
- runId: 'run-001',
288
- artifactId: 'pi-art-task-dreamer-001-run-001',
289
- resultRef: 'dreamer://run-001',
290
- contextHash: 'ctx-abc',
291
- output: { valid: true, taskId: 'task-dreamer-001', candidates: VALID_DREAMER_CANDIDATES, contextRefs: [], generatedAt: new Date().toISOString() },
292
- attemptCount: 1,
293
- });
294
-
295
- await handleRuntimeInternalizationRunOnce({ workspace: WS, runtime: 'test-double', allowTestDouble: true, json: true });
296
-
297
- expect(mockWakeOnce).toHaveBeenCalled();
298
- });
299
-
300
- it('unsupported runner kind: exits 1 with error', async () => {
301
- await handleRuntimeInternalizationRunOnce({ workspace: WS, runner: 'invalid-runner', runtime: 'test-double', allowTestDouble: true });
302
-
303
- expect(process.exitCode).toBe(1);
304
- expect(consoleErrorSpy.mock.calls.some((c: string[]) => c[0].includes('unsupported runner kind'))).toBe(true);
305
- });
306
-
307
- it('no_ready_tasks: reports no leasable task and exits 1', async () => {
308
- mockWakeOnce.mockResolvedValue({
309
- decision: 'no_ready_tasks',
310
- inspectedCount: 3,
311
- reason: 'all_blocked',
312
- });
313
-
314
- await handleRuntimeInternalizationRunOnce({ workspace: WS, runtime: 'test-double', allowTestDouble: true, json: true });
315
-
316
- const output = JSON.parse(consoleLogSpy.mock.calls[0][0]);
317
- expect(output.decision).toBe('no_ready_tasks');
318
- expect(process.exitCode).toBe(1);
319
- });
320
-
321
- it('would_lease dreamer task: uses dryRun wakeOnce then DreamerRunner.run leases and executes', async () => {
322
- mockWakeOnce.mockResolvedValue({
323
- decision: 'would_lease',
324
- taskId: 'task-dreamer-001',
325
- taskKind: 'dreamer',
326
- });
327
-
328
- mockRun.mockResolvedValue({
329
- status: 'succeeded',
330
- taskId: 'task-dreamer-001',
331
- runId: 'run-001',
332
- artifactId: 'pi-art-task-dreamer-001-run-001',
333
- resultRef: 'dreamer://run-001',
334
- contextHash: 'ctx-abc',
335
- output: { valid: true, taskId: 'task-dreamer-001', candidates: VALID_DREAMER_CANDIDATES, contextRefs: [], generatedAt: new Date().toISOString() },
336
- attemptCount: 1,
337
- });
338
-
339
- await handleRuntimeInternalizationRunOnce({ workspace: WS, runtime: 'test-double', allowTestDouble: true, json: true });
340
-
341
- expect(mockRun).toHaveBeenCalledWith('task-dreamer-001');
342
-
343
- const output = JSON.parse(consoleLogSpy.mock.calls[0][0]);
344
- expect(output.decision).toBe('would_lease');
345
- expect(output.taskId).toBe('task-dreamer-001');
346
- expect(output.runId).toBe('run-001');
347
- expect(output.artifactId).toBe('pi-art-task-dreamer-001-run-001');
348
- expect(output.resultRef).toBe('dreamer://run-001');
349
- expect(output.runnerResult.status).toBe('succeeded');
350
- });
351
-
352
- it('would_lease dreamer task with runner failure: reports failed result', async () => {
353
- mockWakeOnce.mockResolvedValue({
354
- decision: 'would_lease',
355
- taskId: 'task-dreamer-002',
356
- taskKind: 'dreamer',
357
- });
358
-
359
- mockRun.mockResolvedValue({
360
- status: 'failed',
361
- taskId: 'task-dreamer-002',
362
- errorCategory: 'execution_failed',
363
- failureReason: 'Runtime unavailable',
364
- attemptCount: 1,
365
- });
366
-
367
- await handleRuntimeInternalizationRunOnce({ workspace: WS, runtime: 'test-double', allowTestDouble: true, json: true });
368
-
369
- const output = JSON.parse(consoleLogSpy.mock.calls[0][0]);
370
- expect(output.runnerResult.status).toBe('failed');
371
- expect(output.runnerResult.errorCategory).toBe('execution_failed');
372
- });
373
-
374
- it('text output for succeeded dreamer run includes runId/artifactId/resultRef', async () => {
375
- mockWakeOnce.mockResolvedValue({
376
- decision: 'would_lease',
377
- taskId: 'task-dreamer-003',
378
- taskKind: 'dreamer',
379
- });
380
-
381
- mockRun.mockResolvedValue({
382
- status: 'succeeded',
383
- taskId: 'task-dreamer-003',
384
- runId: 'run-003',
385
- artifactId: 'pi-art-task-dreamer-003-run-003',
386
- resultRef: 'dreamer://run-003',
387
- contextHash: 'ctx-def',
388
- output: { valid: true, taskId: 'task-dreamer-003', candidates: VALID_DREAMER_CANDIDATES, contextRefs: [], generatedAt: new Date().toISOString() },
389
- attemptCount: 1,
390
- });
391
-
392
- await handleRuntimeInternalizationRunOnce({ workspace: WS, runtime: 'test-double', allowTestDouble: true, json: false });
393
-
394
- const text = consoleLogSpy.mock.calls.map((c: string[]) => c[0]).join('\n');
395
- expect(text).toContain('task-dreamer-003');
396
- expect(text).toContain('succeeded');
397
- expect(text).toContain('runId: run-003');
398
- expect(text).toContain('artifactId: pi-art-task-dreamer-003-run-003');
399
- expect(text).toContain('resultRef: dreamer://run-003');
400
- });
401
-
402
- it('lease_conflict: reports conflict and exits 1', async () => {
403
- mockWakeOnce.mockResolvedValue({
404
- decision: 'lease_conflict',
405
- taskId: 'task-dreamer-004',
406
- conflictReason: 'Already leased by another runner',
407
- });
408
-
409
- await handleRuntimeInternalizationRunOnce({ workspace: WS, runtime: 'test-double', allowTestDouble: true, json: true });
410
-
411
- const output = JSON.parse(consoleLogSpy.mock.calls[0][0]);
412
- expect(output.decision).toBe('lease_conflict');
413
- expect(process.exitCode).toBe(1);
414
- });
415
-
416
- it('orchestrator error: exits 1 with error message', async () => {
417
- mockWakeOnce.mockRejectedValue(new Error('store unavailable'));
418
-
419
- await handleRuntimeInternalizationRunOnce({ workspace: WS, runtime: 'test-double', allowTestDouble: true, json: true });
420
-
421
- expect(process.exitCode).toBe(1);
422
- });
423
-
424
- it('uses stateManager.piArtifactStore (durable SQLite) not MemoryPIArtifactStore', async () => {
425
- mockWakeOnce.mockResolvedValue({
426
- decision: 'would_lease',
427
- taskId: 'task-dreamer-005',
428
- taskKind: 'dreamer',
429
- });
430
-
431
- mockRun.mockResolvedValue({
432
- status: 'succeeded',
433
- taskId: 'task-dreamer-005',
434
- runId: 'run-005',
435
- artifactId: 'pi-art-task-dreamer-005-run-005',
436
- resultRef: 'dreamer://run-005',
437
- attemptCount: 1,
438
- });
439
-
440
- await handleRuntimeInternalizationRunOnce({ workspace: WS, runtime: 'test-double', allowTestDouble: true, json: true });
441
-
442
- const DreamerRunnerMock = vi.mocked(
443
- await import('@principles/core/runtime-v2').then(m => m.DreamerRunner),
444
- );
445
- const lastCall = DreamerRunnerMock.mock.calls[DreamerRunnerMock.mock.calls.length - 1];
446
- if (lastCall) {
447
- const deps = lastCall[0] as { artifactStore?: unknown };
448
- expect(deps.artifactStore).toBe(mockPiArtifactStore);
449
- }
450
- });
451
-
452
- it('--runtime pi-ai resolves PiAiRuntimeAdapter', async () => {
453
- mockWakeOnce.mockResolvedValue({
454
- decision: 'would_lease',
455
- taskId: 'task-dreamer-006',
456
- taskKind: 'dreamer',
457
- });
458
-
459
- mockRun.mockResolvedValue({
460
- status: 'succeeded',
461
- taskId: 'task-dreamer-006',
462
- runId: 'run-006',
463
- artifactId: 'pi-art-task-dreamer-006-run-006',
464
- resultRef: 'dreamer://run-006',
465
- attemptCount: 1,
466
- });
467
-
468
- await handleRuntimeInternalizationRunOnce({ workspace: WS, runtime: 'pi-ai', json: true });
469
-
470
- const PiAiMock = vi.mocked(
471
- await import('@principles/core/runtime-v2').then(m => m.PiAiRuntimeAdapter),
472
- );
473
- expect(PiAiMock).toHaveBeenCalled();
474
- });
475
-
476
- it('--runtime openclaw-cli resolves OpenClawCliRuntimeAdapter', async () => {
477
- mockResolveRuntimeFromPdConfig.mockReturnValueOnce({
478
- result: {
479
- runtimeKind: 'openclaw-cli',
480
- openclawMode: 'local',
481
- timeoutMs: 300_000,
482
- agentId: 'main',
483
- },
484
- legacyWarnings: [],
485
- configSource: '.pd/config.yaml',
486
- configLoadResult: { ok: true, effective: {}, defaults: {}, legacyFilesDetected: [] },
487
- });
488
-
489
- mockWakeOnce.mockResolvedValue({
490
- decision: 'would_lease',
491
- taskId: 'task-dreamer-007',
492
- taskKind: 'dreamer',
493
- });
494
-
495
- mockRun.mockResolvedValue({
496
- status: 'succeeded',
497
- taskId: 'task-dreamer-007',
498
- runId: 'run-007',
499
- artifactId: 'pi-art-task-dreamer-007-run-007',
500
- resultRef: 'dreamer://run-007',
501
- attemptCount: 1,
502
- });
503
-
504
- await handleRuntimeInternalizationRunOnce({ workspace: WS, runtime: 'openclaw-cli', json: true });
505
-
506
- const OpenClawMock = vi.mocked(
507
- await import('@principles/core/runtime-v2').then(m => m.OpenClawCliRuntimeAdapter),
508
- );
509
- expect(OpenClawMock).toHaveBeenCalled();
510
- });
511
-
512
- it('--runtime config resolves adapter from .pd/config.yaml with workspace path (PRI-393)', async () => {
513
- mockWakeOnce.mockResolvedValue({
514
- decision: 'would_lease',
515
- taskId: 'task-dreamer-009',
516
- taskKind: 'dreamer',
517
- });
518
-
519
- mockRun.mockResolvedValue({
520
- status: 'succeeded',
521
- taskId: 'task-dreamer-009',
522
- runId: 'run-009',
523
- artifactId: 'pi-art-task-dreamer-009-run-009',
524
- resultRef: 'dreamer://run-009',
525
- attemptCount: 1,
526
- });
527
-
528
- const customWs = '/tmp/test-workspace';
529
- await handleRuntimeInternalizationRunOnce({ workspace: customWs, runtime: 'config', json: true });
530
-
531
- // PRI-393 + PRI-719 (+review): resolveRuntimeFromPdConfig is called with
532
- // the workspace dir AND the selected runner's agent binding under the
533
- // PEER ignoreAgentEnabled semantics (same as the auto-consumer).
534
- expect(mockResolveRuntimeFromPdConfig).toHaveBeenCalledWith(
535
- expect.stringContaining('test-workspace'),
536
- { agentName: 'dreamer', ignoreAgentEnabled: true },
537
- );
538
- });
539
-
540
- it('--runner philosopher dispatches PhilosopherRunner', async () => {
541
- mockWakeOnce.mockResolvedValue({
542
- decision: 'would_lease',
543
- taskId: 'task-phil-001',
544
- taskKind: 'philosopher',
545
- });
546
-
547
- mockRun.mockResolvedValue({
548
- status: 'succeeded',
549
- taskId: 'task-phil-001',
550
- runId: 'run-phil-001',
551
- artifactId: 'pi-art-task-phil-001-run-phil-001',
552
- resultRef: 'philosopher://run-phil-001',
553
- contextHash: 'ctx-phil-abc',
554
- output: {
555
- taskId: 'task-phil-001',
556
- sourceDreamerArtifactId: 'pi-art-dreamer-001',
557
- thesis: 'Test thesis',
558
- principleCandidate: { title: 'T', rationale: 'R', scope: 'S', confidence: 0.9 },
559
- risks: [],
560
- generatedAt: new Date().toISOString(),
561
- },
562
- attemptCount: 1,
563
- });
564
-
565
- await handleRuntimeInternalizationRunOnce({ workspace: WS, runner: 'philosopher', runtime: 'test-double', allowTestDouble: true, json: true });
566
-
567
- const PhilosopherRunnerMock = vi.mocked(
568
- await import('@principles/core/runtime-v2').then(m => m.PhilosopherRunner),
569
- );
570
- expect(PhilosopherRunnerMock).toHaveBeenCalled();
571
- expect(mockRun).toHaveBeenCalledWith('task-phil-001');
572
-
573
- const output = JSON.parse(consoleLogSpy.mock.calls[0][0]);
574
- expect(output.runnerKind).toBe('philosopher');
575
- expect(output.taskId).toBe('task-phil-001');
576
- expect(output.runId).toBe('run-phil-001');
577
- expect(output.artifactId).toBe('pi-art-task-phil-001-run-phil-001');
578
- expect(output.resultRef).toBe('philosopher://run-phil-001');
579
- expect(output.runnerResult.status).toBe('succeeded');
580
- });
581
-
582
- it('--runner philosopher with text output includes key IDs', async () => {
583
- mockWakeOnce.mockResolvedValue({
584
- decision: 'would_lease',
585
- taskId: 'task-phil-002',
586
- taskKind: 'philosopher',
587
- });
588
-
589
- mockRun.mockResolvedValue({
590
- status: 'succeeded',
591
- taskId: 'task-phil-002',
592
- runId: 'run-phil-002',
593
- artifactId: 'pi-art-task-phil-002-run-phil-002',
594
- resultRef: 'philosopher://run-phil-002',
595
- contextHash: 'ctx-phil-def',
596
- output: {
597
- taskId: 'task-phil-002',
598
- sourceDreamerArtifactId: 'pi-art-dreamer-002',
599
- thesis: 'Test thesis',
600
- principleCandidate: { title: 'T', rationale: 'R', scope: 'S', confidence: 0.9 },
601
- risks: [],
602
- generatedAt: new Date().toISOString(),
603
- },
604
- attemptCount: 1,
605
- });
606
-
607
- await handleRuntimeInternalizationRunOnce({ workspace: WS, runner: 'philosopher', runtime: 'test-double', allowTestDouble: true, json: false });
608
-
609
- const text = consoleLogSpy.mock.calls.map((c: string[]) => c[0]).join('\n');
610
- expect(text).toContain('task-phil-002');
611
- expect(text).toContain('succeeded');
612
- expect(text).toContain('runId: run-phil-002');
613
- expect(text).toContain('artifactId: pi-art-task-phil-002-run-phil-002');
614
- expect(text).toContain('resultRef: philosopher://run-phil-002');
615
- });
616
-
617
- it('auto-enqueue: successful dreamer returns successor info by default', async () => {
618
- mockWakeOnce.mockResolvedValue({
619
- decision: 'would_lease',
620
- taskId: 'task-dreamer-enq-001',
621
- taskKind: 'dreamer',
622
- });
623
-
624
- mockRun.mockResolvedValue({
625
- status: 'succeeded',
626
- taskId: 'task-dreamer-enq-001',
627
- runId: 'run-enq-001',
628
- artifactId: 'pi-art-enq-001',
629
- resultRef: 'dreamer://run-enq-001',
630
- contextHash: 'ctx-enq',
631
- output: { valid: true, taskId: 'task-dreamer-enq-001', candidates: VALID_DREAMER_CANDIDATES, contextRefs: [], generatedAt: new Date().toISOString() },
632
- attemptCount: 1,
633
- });
634
-
635
- mockCommitNextTaskProposal.mockResolvedValue({
636
- decision: 'successor_created',
637
- sourceTaskId: 'task-dreamer-enq-001',
638
- successorTaskId: 'task-phil-enq-001',
639
- successorKind: 'philosopher',
640
- });
641
-
642
- await handleRuntimeInternalizationRunOnce({ workspace: WS, runner: 'dreamer', runtime: 'test-double', allowTestDouble: true, enqueueNext: true, json: true });
643
-
644
- const output = JSON.parse(consoleLogSpy.mock.calls[0][0]);
645
- expect(output.enqueueDecision).toBe('successor_created');
646
- expect(output.successorTaskIds![0]).toBe('task-phil-enq-001');
647
- expect(output.successorKind).toBe('philosopher');
648
- });
649
-
650
- it('auto-enqueue: repeated run returns existing successorTaskId', async () => {
651
- mockWakeOnce.mockResolvedValue({
652
- decision: 'would_lease',
653
- taskId: 'task-dreamer-enq-002',
654
- taskKind: 'dreamer',
655
- });
656
-
657
- mockRun.mockResolvedValue({
658
- status: 'succeeded',
659
- taskId: 'task-dreamer-enq-002',
660
- runId: 'run-enq-002',
661
- artifactId: 'pi-art-enq-002',
662
- resultRef: 'dreamer://run-enq-002',
663
- contextHash: 'ctx-enq2',
664
- output: { valid: true, taskId: 'task-dreamer-enq-002', candidates: VALID_DREAMER_CANDIDATES, contextRefs: [], generatedAt: new Date().toISOString() },
665
- attemptCount: 1,
666
- });
667
-
668
- mockCommitNextTaskProposal.mockResolvedValue({
669
- decision: 'successor_exists',
670
- sourceTaskId: 'task-dreamer-enq-002',
671
- successorTaskId: 'task-phil-enq-002',
672
- successorKind: 'philosopher',
673
- });
674
-
675
- await handleRuntimeInternalizationRunOnce({ workspace: WS, runner: 'dreamer', runtime: 'test-double', allowTestDouble: true, enqueueNext: true, json: true });
676
-
677
- const output = JSON.parse(consoleLogSpy.mock.calls[0][0]);
678
- expect(output.enqueueDecision).toBe('successor_exists');
679
- expect(output.successorTaskIds![0]).toBe('task-phil-enq-002');
680
- expect(output.successorKind).toBe('philosopher');
681
- });
682
-
683
- it('auto-enqueue: no_successor does not set successor info', async () => {
684
- mockWakeOnce.mockResolvedValue({
685
- decision: 'would_lease',
686
- taskId: 'task-dreamer-enq-003',
687
- taskKind: 'dreamer',
688
- });
689
-
690
- mockRun.mockResolvedValue({
691
- status: 'succeeded',
692
- taskId: 'task-dreamer-enq-003',
693
- runId: 'run-enq-003',
694
- artifactId: 'pi-art-enq-003',
695
- resultRef: 'dreamer://run-enq-003',
696
- contextHash: 'ctx-enq3',
697
- output: { valid: true, taskId: 'task-dreamer-enq-003', candidates: VALID_DREAMER_CANDIDATES, contextRefs: [], generatedAt: new Date().toISOString() },
698
- attemptCount: 1,
699
- });
700
-
701
- mockCommitNextTaskProposal.mockResolvedValue({
702
- decision: 'no_successor',
703
- sourceTaskId: 'task-dreamer-enq-003',
704
- reason: 'terminal runner',
705
- });
706
-
707
- await handleRuntimeInternalizationRunOnce({ workspace: WS, runner: 'dreamer', runtime: 'test-double', allowTestDouble: true, enqueueNext: true, json: true });
708
-
709
- const output = JSON.parse(consoleLogSpy.mock.calls[0][0]);
710
- expect(output.enqueueDecision).toBe('no_successor');
711
- expect(output.successorTaskIds).toEqual([]);
712
- });
713
-
714
- it('auto-enqueue: failed run does not call commitNextTaskProposal', async () => {
715
- mockWakeOnce.mockResolvedValue({
716
- decision: 'would_lease',
717
- taskId: 'task-dreamer-enq-004',
718
- taskKind: 'dreamer',
719
- });
720
-
721
- mockRun.mockResolvedValue({
722
- status: 'failed',
723
- taskId: 'task-dreamer-enq-004',
724
- errorCategory: 'execution_failed',
725
- failureReason: 'Runtime unavailable',
726
- attemptCount: 1,
727
- });
728
-
729
- await handleRuntimeInternalizationRunOnce({ workspace: WS, runner: 'dreamer', runtime: 'test-double', allowTestDouble: true, enqueueNext: true, json: true });
730
-
731
- expect(mockCommitNextTaskProposal).not.toHaveBeenCalled();
732
- });
733
-
734
- it('auto-enqueue without --allow-test-double still blocked', async () => {
735
- await handleRuntimeInternalizationRunOnce({ workspace: WS, runner: 'dreamer', runtime: 'test-double', enqueueNext: true });
736
-
737
- expect(process.exitCode).toBe(1);
738
- expect(mockWakeOnce).not.toHaveBeenCalled();
739
- });
740
-
741
- it('test-double with --runner philosopher requires --allow-test-double', async () => {
742
- await handleRuntimeInternalizationRunOnce({ workspace: WS, runner: 'philosopher', runtime: 'test-double' });
743
-
744
- expect(process.exitCode).toBe(1);
745
- expect(consoleErrorSpy.mock.calls.some((c: string[]) => c[0].includes('test-double runtime mutates real queue state'))).toBe(true);
746
- expect(mockWakeOnce).not.toHaveBeenCalled();
747
- });
748
-
749
- it('JSON output includes runnerKind field', async () => {
750
- mockWakeOnce.mockResolvedValue({
751
- decision: 'would_lease',
752
- taskId: 'task-dreamer-rk',
753
- taskKind: 'dreamer',
754
- });
755
-
756
- mockRun.mockResolvedValue({
757
- status: 'succeeded',
758
- taskId: 'task-dreamer-rk',
759
- runId: 'run-rk',
760
- artifactId: 'pi-art-rk',
761
- resultRef: 'dreamer://run-rk',
762
- contextHash: 'ctx-rk',
763
- output: { valid: true, taskId: 'task-dreamer-rk', candidates: VALID_DREAMER_CANDIDATES, contextRefs: [], generatedAt: new Date().toISOString() },
764
- attemptCount: 1,
765
- });
766
-
767
- await handleRuntimeInternalizationRunOnce({ workspace: WS, runner: 'dreamer', runtime: 'test-double', allowTestDouble: true, json: true });
768
-
769
- const output = JSON.parse(consoleLogSpy.mock.calls[0][0]);
770
- expect(output.runnerKind).toBe('dreamer');
771
- expect(output.decision).toBe('would_lease');
772
- expect(output.taskId).toBe('task-dreamer-rk');
773
- expect(output.runId).toBe('run-rk');
774
- expect(output.artifactId).toBe('pi-art-rk');
775
- expect(output.resultRef).toBe('dreamer://run-rk');
776
- });
777
-
778
- it('--timeout-ms passes effectiveTimeoutMs to DreamerRunner and output', async () => {
779
- mockWakeOnce.mockResolvedValue({
780
- decision: 'would_lease',
781
- taskId: 'task-dreamer-tm',
782
- taskKind: 'dreamer',
783
- });
784
-
785
- mockRun.mockResolvedValue({
786
- status: 'succeeded',
787
- taskId: 'task-dreamer-tm',
788
- runId: 'run-tm',
789
- artifactId: 'pi-art-tm',
790
- resultRef: 'dreamer://run-tm',
791
- contextHash: 'ctx-tm',
792
- output: { valid: true, taskId: 'task-dreamer-tm', candidates: VALID_DREAMER_CANDIDATES, contextRefs: [], generatedAt: new Date().toISOString() },
793
- attemptCount: 1,
794
- });
795
-
796
- await handleRuntimeInternalizationRunOnce({ workspace: WS, runner: 'dreamer', runtime: 'test-double', allowTestDouble: true, timeoutMs: 180_000, json: true });
797
-
798
- const DreamerRunnerMock = vi.mocked(
799
- await import('@principles/core/runtime-v2').then(m => m.DreamerRunner),
800
- );
801
- const lastCall = DreamerRunnerMock.mock.calls[DreamerRunnerMock.mock.calls.length - 1];
802
- if (lastCall) {
803
- const opts = lastCall[1] as { timeoutMs?: number };
804
- expect(opts.timeoutMs).toBe(180_000);
805
- }
806
-
807
- const output = JSON.parse(consoleLogSpy.mock.calls[0][0]);
808
- expect(output.effectiveTimeoutMs).toBe(180_000);
809
- });
810
-
811
- it('default timeoutMs is 300000 when --timeout-ms not provided', async () => {
812
- mockWakeOnce.mockResolvedValue({
813
- decision: 'would_lease',
814
- taskId: 'task-dreamer-dt',
815
- taskKind: 'dreamer',
816
- });
817
-
818
- mockRun.mockResolvedValue({
819
- status: 'succeeded',
820
- taskId: 'task-dreamer-dt',
821
- runId: 'run-dt',
822
- artifactId: 'pi-art-dt',
823
- resultRef: 'dreamer://run-dt',
824
- contextHash: 'ctx-dt',
825
- output: { valid: true, taskId: 'task-dreamer-dt', candidates: VALID_DREAMER_CANDIDATES, contextRefs: [], generatedAt: new Date().toISOString() },
826
- attemptCount: 1,
827
- });
828
-
829
- await handleRuntimeInternalizationRunOnce({ workspace: WS, runner: 'dreamer', runtime: 'test-double', allowTestDouble: true, json: true });
830
-
831
- const DreamerRunnerMock = vi.mocked(
832
- await import('@principles/core/runtime-v2').then(m => m.DreamerRunner),
833
- );
834
- const lastCall = DreamerRunnerMock.mock.calls[DreamerRunnerMock.mock.calls.length - 1];
835
- if (lastCall) {
836
- const opts = lastCall[1] as { timeoutMs?: number };
837
- expect(opts.timeoutMs).toBe(300_000);
838
- }
839
-
840
- const output = JSON.parse(consoleLogSpy.mock.calls[0][0]);
841
- expect(output.effectiveTimeoutMs).toBe(300_000);
842
- });
843
-
844
- it('PRI-670: profile timeoutMs is the runner deadline when --timeout-ms not provided', async () => {
845
- // The shared resolver returns the diagnostician binding's runtimeProfile
846
- // timeout (mocked here to 600_000 — the local-llamacpp lab shape). Without
847
- // the PRI-670 fix the runner deadline stayed hardcoded at 300s and the
848
- // profile value only reached the adapter as a per-request timeout.
849
- const coreModule = await import('@principles/core/runtime-v2');
850
- vi.mocked(coreModule.resolveRuntimeConfigForAgent).mockReturnValue({
851
- runtimeKind: 'pi-ai', provider: 'test-provider', model: 'test-model',
852
- apiKeyEnv: 'TEST_API_KEY', timeoutMs: 600_000, agentId: 'main',
853
- } as never);
854
-
855
- mockWakeOnce.mockResolvedValue({
856
- decision: 'would_lease',
857
- taskId: 'task-dreamer-pt',
858
- taskKind: 'dreamer',
859
- });
860
- mockRun.mockResolvedValue({
861
- status: 'succeeded',
862
- taskId: 'task-dreamer-pt',
863
- runId: 'run-pt',
864
- artifactId: 'pi-art-pt',
865
- resultRef: 'dreamer://run-pt',
866
- contextHash: 'ctx-pt',
867
- output: { valid: true, taskId: 'task-dreamer-pt', candidates: VALID_DREAMER_CANDIDATES, contextRefs: [], generatedAt: new Date().toISOString() },
868
- attemptCount: 1,
869
- });
870
-
871
- try {
872
- await handleRuntimeInternalizationRunOnce({ workspace: WS, runner: 'dreamer', runtime: 'test-double', allowTestDouble: true, json: true });
873
-
874
- const DreamerRunnerMock = vi.mocked(coreModule.DreamerRunner);
875
- const lastCall = DreamerRunnerMock.mock.calls[DreamerRunnerMock.mock.calls.length - 1];
876
- if (lastCall) {
877
- const opts = lastCall[1] as { timeoutMs?: number };
878
- expect(opts.timeoutMs).toBe(600_000);
879
- }
880
- const output = JSON.parse(consoleLogSpy.mock.calls[0][0]);
881
- expect(output.effectiveTimeoutMs).toBe(600_000);
882
- } finally {
883
- vi.mocked(coreModule.resolveRuntimeConfigForAgent).mockReturnValue({
884
- runtimeKind: 'pi-ai', provider: 'test-provider', model: 'test-model',
885
- apiKeyEnv: 'TEST_API_KEY', timeoutMs: 300_000, agentId: 'main',
886
- } as never);
887
- }
888
- });
889
-
890
- it('PRI-670: --timeout-ms still wins over the profile timeoutMs', async () => {
891
- const coreModule = await import('@principles/core/runtime-v2');
892
- vi.mocked(coreModule.resolveRuntimeConfigForAgent).mockReturnValue({
893
- runtimeKind: 'pi-ai', provider: 'test-provider', model: 'test-model',
894
- apiKeyEnv: 'TEST_API_KEY', timeoutMs: 600_000, agentId: 'main',
895
- } as never);
896
-
897
- mockWakeOnce.mockResolvedValue({
898
- decision: 'would_lease',
899
- taskId: 'task-dreamer-pt2',
900
- taskKind: 'dreamer',
901
- });
902
- mockRun.mockResolvedValue({
903
- status: 'succeeded',
904
- taskId: 'task-dreamer-pt2',
905
- runId: 'run-pt2',
906
- artifactId: 'pi-art-pt2',
907
- resultRef: 'dreamer://run-pt2',
908
- contextHash: 'ctx-pt2',
909
- output: { valid: true, taskId: 'task-dreamer-pt2', candidates: VALID_DREAMER_CANDIDATES, contextRefs: [], generatedAt: new Date().toISOString() },
910
- attemptCount: 1,
911
- });
912
-
913
- try {
914
- await handleRuntimeInternalizationRunOnce({ workspace: WS, runner: 'dreamer', runtime: 'test-double', allowTestDouble: true, timeoutMs: 120_000, json: true });
915
- const output = JSON.parse(consoleLogSpy.mock.calls[0][0]);
916
- expect(output.effectiveTimeoutMs).toBe(120_000);
917
- } finally {
918
- vi.mocked(coreModule.resolveRuntimeConfigForAgent).mockReturnValue({
919
- runtimeKind: 'pi-ai', provider: 'test-provider', model: 'test-model',
920
- apiKeyEnv: 'TEST_API_KEY', timeoutMs: 300_000, agentId: 'main',
921
- } as never);
922
- }
923
- });
924
-
925
- it('timeout source extracted from failureReason on timeout', async () => {
926
- mockWakeOnce.mockResolvedValue({
927
- decision: 'would_lease',
928
- taskId: 'task-dreamer-ts',
929
- taskKind: 'dreamer',
930
- });
931
-
932
- mockRun.mockResolvedValue({
933
- status: 'failed',
934
- taskId: 'task-dreamer-ts',
935
- errorCategory: 'timeout',
936
- failureReason: '[timeout] LLM request timed out after 300000ms (timeoutSource=provider_request)',
937
- attemptCount: 1,
938
- });
939
-
940
- await handleRuntimeInternalizationRunOnce({ workspace: WS, runner: 'dreamer', runtime: 'test-double', allowTestDouble: true, timeoutMs: 300_000, json: true });
941
-
942
- const output = JSON.parse(consoleLogSpy.mock.calls[0][0]);
943
- expect(output.timeoutSource).toBe('provider_request');
944
- expect(output.effectiveTimeoutMs).toBe(300_000);
945
- });
946
-
947
- it('timeout source extracted as runner_poll from abort timeout', async () => {
948
- mockWakeOnce.mockResolvedValue({
949
- decision: 'would_lease',
950
- taskId: 'task-dreamer-rp',
951
- taskKind: 'dreamer',
952
- });
953
-
954
- mockRun.mockResolvedValue({
955
- status: 'failed',
956
- taskId: 'task-dreamer-rp',
957
- errorCategory: 'timeout',
958
- failureReason: '[timeout] LLM request timed out after 300000ms (timeoutSource=runner_poll)',
959
- attemptCount: 1,
960
- });
961
-
962
- await handleRuntimeInternalizationRunOnce({ workspace: WS, runner: 'dreamer', runtime: 'test-double', allowTestDouble: true, json: true });
963
-
964
- const output = JSON.parse(consoleLogSpy.mock.calls[0][0]);
965
- expect(output.timeoutSource).toBe('runner_poll');
966
- });
967
-
968
- it('--timeout-ms overrides .pd/config.yaml timeoutMs for PiAiRuntimeAdapter (PRI-393)', async () => {
969
- mockWakeOnce.mockResolvedValue({
970
- decision: 'would_lease',
971
- taskId: 'task-dreamer-ov',
972
- taskKind: 'dreamer',
973
- });
974
-
975
- mockRun.mockResolvedValue({
976
- status: 'succeeded',
977
- taskId: 'task-dreamer-ov',
978
- runId: 'run-ov',
979
- artifactId: 'pi-art-ov',
980
- resultRef: 'dreamer://run-ov',
981
- contextHash: 'ctx-ov',
982
- output: { valid: true, taskId: 'task-dreamer-ov', candidates: VALID_DREAMER_CANDIDATES, contextRefs: [], generatedAt: new Date().toISOString() },
983
- attemptCount: 1,
984
- });
985
-
986
- await handleRuntimeInternalizationRunOnce({ workspace: WS, runner: 'dreamer', runtime: 'config', timeoutMs: 240_000, json: true });
987
-
988
- const PiAiMock = vi.mocked(
989
- await import('@principles/core/runtime-v2').then(m => m.PiAiRuntimeAdapter),
990
- );
991
- const lastCall = PiAiMock.mock.calls[PiAiMock.mock.calls.length - 1];
992
- if (lastCall) {
993
- const config = lastCall[0] as { timeoutMs?: number };
994
- expect(config.timeoutMs).toBe(240_000);
995
- }
996
-
997
- const output = JSON.parse(consoleLogSpy.mock.calls[0][0]);
998
- expect(output.effectiveTimeoutMs).toBe(240_000);
999
- });
1000
-
1001
- it('--runner scribe dispatches ScribeRunner', async () => {
1002
- mockWakeOnce.mockResolvedValue({
1003
- decision: 'would_lease',
1004
- taskId: 'task-scribe-001',
1005
- taskKind: 'scribe',
1006
- });
1007
-
1008
- mockRun.mockResolvedValue({
1009
- status: 'succeeded',
1010
- taskId: 'task-scribe-001',
1011
- runId: 'run-scribe-001',
1012
- artifactId: 'pi-art-task-scribe-001-run-scribe-001',
1013
- resultRef: 'scribe://run-scribe-001',
1014
- contextHash: 'ctx-scribe-abc',
1015
- output: {
1016
- taskId: 'task-scribe-001',
1017
- sourcePhilosopherArtifactId: 'pi-art-phil-001',
1018
- principleDraft: { title: 'T', statement: 'S', rationale: 'R', applicability: [], antiPatterns: [], confidence: 0.9 },
1019
- sourceTrace: { philosopherArtifactId: 'pi-art-phil-001' },
1020
- risks: [],
1021
- generatedAt: new Date().toISOString(),
1022
- },
1023
- attemptCount: 1,
1024
- });
1025
-
1026
- await handleRuntimeInternalizationRunOnce({ workspace: WS, runner: 'scribe', runtime: 'test-double', allowTestDouble: true, json: true });
1027
-
1028
- const ScribeRunnerMock = vi.mocked(
1029
- await import('@principles/core/runtime-v2').then(m => m.ScribeRunner),
1030
- );
1031
- expect(ScribeRunnerMock).toHaveBeenCalled();
1032
- expect(mockRun).toHaveBeenCalledWith('task-scribe-001');
1033
-
1034
- const output = JSON.parse(consoleLogSpy.mock.calls[0][0]);
1035
- expect(output.runnerKind).toBe('scribe');
1036
- expect(output.taskId).toBe('task-scribe-001');
1037
- expect(output.runId).toBe('run-scribe-001');
1038
- expect(output.artifactId).toBe('pi-art-task-scribe-001-run-scribe-001');
1039
- expect(output.resultRef).toBe('scribe://run-scribe-001');
1040
- expect(output.runnerResult.status).toBe('succeeded');
1041
- });
1042
-
1043
- it('auto-enqueue: --runner scribe creates artificer successor', async () => {
1044
- mockWakeOnce.mockResolvedValue({
1045
- decision: 'would_lease',
1046
- taskId: 'task-scribe-enq-001',
1047
- taskKind: 'scribe',
1048
- });
1049
-
1050
- mockRun.mockResolvedValue({
1051
- status: 'succeeded',
1052
- taskId: 'task-scribe-enq-001',
1053
- runId: 'run-scribe-enq-001',
1054
- artifactId: 'pi-art-scribe-enq-001',
1055
- resultRef: 'scribe://run-scribe-enq-001',
1056
- contextHash: 'ctx-enq',
1057
- output: {
1058
- taskId: 'task-scribe-enq-001',
1059
- sourcePhilosopherArtifactId: 'pi-art-phil-enq-001',
1060
- principleDraft: { title: 'T', statement: 'S', rationale: 'R', applicability: [], antiPatterns: [], confidence: 0.9 },
1061
- sourceTrace: { philosopherArtifactId: 'pi-art-phil-enq-001' },
1062
- risks: [],
1063
- generatedAt: new Date().toISOString(),
1064
- },
1065
- attemptCount: 1,
1066
- });
1067
-
1068
- mockCommitNextTaskProposal.mockResolvedValue({
1069
- decision: 'successor_created',
1070
- sourceTaskId: 'task-scribe-enq-001',
1071
- successorTaskId: 'task-artificer-enq-001',
1072
- successorKind: 'artificer',
1073
- });
1074
-
1075
- await handleRuntimeInternalizationRunOnce({ workspace: WS, runner: 'scribe', runtime: 'test-double', allowTestDouble: true, enqueueNext: true, json: true });
1076
-
1077
- const output = JSON.parse(consoleLogSpy.mock.calls[0][0]);
1078
- expect(output.enqueueDecision).toBe('successor_created');
1079
- expect(output.successorTaskIds![0]).toBe('task-artificer-enq-001');
1080
- expect(output.successorKind).toBe('artificer');
1081
- });
1082
-
1083
- it('run-once source imports EvaluatorRunner for dispatch', async () => {
1084
- const { existsSync, readFileSync } = await import('node:fs');
1085
- const { resolve } = await import('node:path');
1086
- const srcPath = resolve(__dirname, '../../src/commands/runtime-internalization-run-once.ts');
1087
- if (!existsSync(srcPath)) return;
1088
- const src = readFileSync(srcPath, 'utf-8');
1089
- expect(src).toContain('EvaluatorRunner');
1090
- expect(src).toContain('DefaultEvaluatorValidator');
1091
- });
1092
-
1093
- it('--runner artificer dispatches ArtificerRunner', async () => {
1094
- mockWakeOnce.mockResolvedValue({
1095
- decision: 'would_lease',
1096
- taskId: 'task-artificer-001',
1097
- taskKind: 'artificer',
1098
- });
1099
-
1100
- mockRun.mockResolvedValue({
1101
- status: 'succeeded',
1102
- taskId: 'task-artificer-001',
1103
- runId: 'run-artificer-001',
1104
- artifactId: 'pi-art-task-artificer-001-run-artificer-001',
1105
- resultRef: 'artificer://run-artificer-001',
1106
- contextHash: 'ctx-artificer-abc',
1107
- output: {
1108
- taskId: 'task-artificer-001',
1109
- sourceScribeArtifactId: 'pi-art-scribe-001',
1110
- implementationPlan: {
1111
- summary: 'Test implementation summary',
1112
- targetSurface: 'src/test/*.ts',
1113
- changes: ['Add validation'],
1114
- tests: ['Unit test for validation'],
1115
- rolloutNotes: ['Deploy behind feature flag'],
1116
- confidence: 0.8,
1117
- },
1118
- sourceTrace: { scribeArtifactId: 'pi-art-scribe-001' },
1119
- risks: [],
1120
- generatedAt: new Date().toISOString(),
1121
- },
1122
- attemptCount: 1,
1123
- });
1124
-
1125
- await handleRuntimeInternalizationRunOnce({ workspace: WS, runner: 'artificer', runtime: 'test-double', allowTestDouble: true, json: true });
1126
-
1127
- const ArtificerRunnerMock = vi.mocked(
1128
- await import('@principles/core/runtime-v2').then(m => m.ArtificerRunner),
1129
- );
1130
- expect(ArtificerRunnerMock).toHaveBeenCalled();
1131
- expect(mockRun).toHaveBeenCalledWith('task-artificer-001');
1132
-
1133
- const output = JSON.parse(consoleLogSpy.mock.calls[0][0]);
1134
- expect(output.runnerKind).toBe('artificer');
1135
- expect(output.taskId).toBe('task-artificer-001');
1136
- expect(output.runId).toBe('run-artificer-001');
1137
- expect(output.artifactId).toBe('pi-art-task-artificer-001-run-artificer-001');
1138
- expect(output.resultRef).toBe('artificer://run-artificer-001');
1139
- expect(output.runnerResult.status).toBe('succeeded');
1140
- });
1141
-
1142
- it('auto-enqueue: --runner artificer returns successor decision', async () => {
1143
- mockWakeOnce.mockResolvedValue({
1144
- decision: 'would_lease',
1145
- taskId: 'task-artificer-enq-001',
1146
- taskKind: 'artificer',
1147
- });
1148
-
1149
- mockRun.mockResolvedValue({
1150
- status: 'succeeded',
1151
- taskId: 'task-artificer-enq-001',
1152
- runId: 'run-artificer-enq-001',
1153
- artifactId: 'pi-art-artificer-enq-001',
1154
- resultRef: 'artificer://run-artificer-enq-001',
1155
- contextHash: 'ctx-enq',
1156
- output: {
1157
- taskId: 'task-artificer-enq-001',
1158
- sourceScribeArtifactId: 'pi-art-scribe-enq-001',
1159
- implementationPlan: {
1160
- summary: 'Test implementation summary',
1161
- targetSurface: 'src/test/*.ts',
1162
- changes: ['Add validation'],
1163
- tests: ['Unit test for validation'],
1164
- rolloutNotes: ['Deploy behind feature flag'],
1165
- confidence: 0.8,
1166
- },
1167
- sourceTrace: { scribeArtifactId: 'pi-art-scribe-enq-001' },
1168
- risks: [],
1169
- generatedAt: new Date().toISOString(),
1170
- },
1171
- attemptCount: 1,
1172
- });
1173
-
1174
- mockCommitNextTaskProposal.mockResolvedValue({
1175
- decision: 'successor_created',
1176
- sourceTaskId: 'task-artificer-enq-001',
1177
- successorTaskId: 'task-evaluator-enq-001',
1178
- successorKind: 'evaluator',
1179
- });
1180
-
1181
- await handleRuntimeInternalizationRunOnce({ workspace: WS, runner: 'artificer', runtime: 'test-double', allowTestDouble: true, enqueueNext: true, json: true });
1182
-
1183
- const output = JSON.parse(consoleLogSpy.mock.calls[0][0]);
1184
- expect(output.enqueueDecision).toBe('successor_created');
1185
- expect(output.successorTaskIds![0]).toBe('task-evaluator-enq-001');
1186
- expect(output.successorKind).toBe('evaluator');
1187
- });
1188
-
1189
- it('wakeOnce is called with runnerKind as taskKind filter', async () => {
1190
- mockWakeOnce.mockResolvedValue({
1191
- decision: 'would_lease',
1192
- taskId: 'task-artificer-filter',
1193
- taskKind: 'artificer',
1194
- });
1195
-
1196
- mockRun.mockResolvedValue({
1197
- status: 'succeeded',
1198
- taskId: 'task-artificer-filter',
1199
- runId: 'run-filter',
1200
- artifactId: 'pi-art-filter',
1201
- resultRef: 'artificer://run-filter',
1202
- contextHash: 'ctx-filter',
1203
- output: {
1204
- taskId: 'task-artificer-filter',
1205
- sourceScribeArtifactId: 'pi-art-scribe-filter',
1206
- implementationPlan: {
1207
- summary: 'Test',
1208
- targetSurface: 'src/test.ts',
1209
- changes: [],
1210
- tests: [],
1211
- rolloutNotes: [],
1212
- confidence: 0.8,
1213
- },
1214
- sourceTrace: { scribeArtifactId: 'pi-art-scribe-filter' },
1215
- risks: [],
1216
- generatedAt: new Date().toISOString(),
1217
- },
1218
- attemptCount: 1,
1219
- });
1220
-
1221
- await handleRuntimeInternalizationRunOnce({ workspace: WS, runner: 'artificer', runtime: 'test-double', allowTestDouble: true, json: true });
1222
-
1223
- expect(mockWakeOnce).toHaveBeenCalledWith('artificer');
1224
- });
1225
-
1226
- it('--runner evaluator dispatches EvaluatorRunner', async () => {
1227
- mockWakeOnce.mockResolvedValue({
1228
- decision: 'would_lease',
1229
- taskId: 'task-evaluator-001',
1230
- taskKind: 'evaluator',
1231
- });
1232
-
1233
- mockRun.mockResolvedValue({
1234
- status: 'succeeded',
1235
- taskId: 'task-evaluator-001',
1236
- runId: 'run-evaluator-001',
1237
- artifactId: 'pi-art-task-evaluator-001-run-evaluator-001',
1238
- resultRef: 'evaluator://run-evaluator-001',
1239
- contextHash: 'ctx-evaluator-abc',
1240
- output: {
1241
- taskId: 'task-evaluator-001',
1242
- sourceArtificerArtifactId: 'pi-art-artificer-001',
1243
- evaluation: {
1244
- decision: 'approved',
1245
- summary: 'Test evaluation summary',
1246
- score: 0.85,
1247
- strengths: ['Well-structured plan'],
1248
- concerns: [],
1249
- requiredChanges: [],
1250
- },
1251
- sourceTrace: { artificerArtifactId: 'pi-art-artificer-001' },
1252
- risks: [],
1253
- generatedAt: new Date().toISOString(),
1254
- },
1255
- attemptCount: 1,
1256
- });
1257
-
1258
- await handleRuntimeInternalizationRunOnce({ workspace: WS, runner: 'evaluator', runtime: 'test-double', allowTestDouble: true, json: true });
1259
-
1260
- const EvaluatorRunnerMock = vi.mocked(
1261
- await import('@principles/core/runtime-v2').then(m => m.EvaluatorRunner),
1262
- );
1263
- expect(EvaluatorRunnerMock).toHaveBeenCalled();
1264
- expect(mockRun).toHaveBeenCalledWith('task-evaluator-001');
1265
-
1266
- const output = JSON.parse(consoleLogSpy.mock.calls[0][0]);
1267
- expect(output.runnerKind).toBe('evaluator');
1268
- expect(output.taskId).toBe('task-evaluator-001');
1269
- expect(output.runId).toBe('run-evaluator-001');
1270
- expect(output.artifactId).toBe('pi-art-task-evaluator-001-run-evaluator-001');
1271
- expect(output.resultRef).toBe('evaluator://run-evaluator-001');
1272
- expect(output.runnerResult.status).toBe('succeeded');
1273
- });
1274
-
1275
- it('--runner evaluator refuses BEFORE leasing when the runtime context is unresolvable (PRI-661)', async () => {
1276
- mockCreateEvaluatorRuntimeContext.mockReturnValueOnce({
1277
- ok: false,
1278
- reason: 'host_tool_declaration_missing',
1279
- nextAction: 'start a host (OpenClaw/Codex) once so it persists its tool declaration',
1280
- });
1281
-
1282
- await handleRuntimeInternalizationRunOnce({ workspace: WS, runner: 'evaluator', runtime: 'test-double', allowTestDouble: true, json: true });
1283
-
1284
- // cli-5: refusal must not lease/advance any task.
1285
- expect(mockWakeOnce).not.toHaveBeenCalled();
1286
- const EvaluatorRunnerMock = vi.mocked(
1287
- await import('@principles/core/runtime-v2').then(m => m.EvaluatorRunner),
1288
- );
1289
- expect(EvaluatorRunnerMock).not.toHaveBeenCalled();
1290
-
1291
- const output = JSON.parse(consoleLogSpy.mock.calls[0][0]);
1292
- expect(output.decision).toBe('refused');
1293
- expect(output.reason).toBe('host_tool_declaration_missing');
1294
- expect(output.nextAction).toContain('host');
1295
- });
1296
-
1297
- it('auto-enqueue: --runner evaluator returns successor decision', async () => {
1298
- mockWakeOnce.mockResolvedValue({
1299
- decision: 'would_lease',
1300
- taskId: 'task-evaluator-enq-001',
1301
- taskKind: 'evaluator',
1302
- });
1303
-
1304
- mockRun.mockResolvedValue({
1305
- status: 'succeeded',
1306
- taskId: 'task-evaluator-enq-001',
1307
- runId: 'run-evaluator-enq-001',
1308
- artifactId: 'pi-art-evaluator-enq-001',
1309
- resultRef: 'evaluator://run-evaluator-enq-001',
1310
- contextHash: 'ctx-enq',
1311
- output: {
1312
- taskId: 'task-evaluator-enq-001',
1313
- sourceArtificerArtifactId: 'pi-art-artificer-enq-001',
1314
- evaluation: {
1315
- decision: 'approved',
1316
- summary: 'Test evaluation summary',
1317
- score: 0.85,
1318
- strengths: ['Well-structured plan'],
1319
- concerns: [],
1320
- requiredChanges: [],
1321
- },
1322
- sourceTrace: { artificerArtifactId: 'pi-art-artificer-enq-001' },
1323
- risks: [],
1324
- generatedAt: new Date().toISOString(),
1325
- },
1326
- attemptCount: 1,
1327
- });
1328
-
1329
- mockCommitNextTaskProposal.mockResolvedValue({
1330
- decision: 'successor_created',
1331
- sourceTaskId: 'task-evaluator-enq-001',
1332
- successorTaskId: 'task-rollout-reviewer-enq-001',
1333
- successorKind: 'rollout_reviewer',
1334
- });
1335
-
1336
- await handleRuntimeInternalizationRunOnce({ workspace: WS, runner: 'evaluator', runtime: 'test-double', allowTestDouble: true, enqueueNext: true, json: true });
1337
-
1338
- const output = JSON.parse(consoleLogSpy.mock.calls[0][0]);
1339
- expect(output.enqueueDecision).toBe('successor_created');
1340
- expect(output.successorTaskIds![0]).toBe('task-rollout-reviewer-enq-001');
1341
- expect(output.successorKind).toBe('rollout_reviewer');
1342
- });
1343
-
1344
- it('--runner rollout_reviewer dispatches RolloutReviewerRunner', async () => {
1345
- mockWakeOnce.mockResolvedValue({
1346
- decision: 'would_lease',
1347
- taskId: 'task-rollout-reviewer-001',
1348
- taskKind: 'rollout_reviewer',
1349
- });
1350
-
1351
- mockRun.mockResolvedValue({
1352
- status: 'succeeded',
1353
- taskId: 'task-rollout-reviewer-001',
1354
- runId: 'run-rollout-reviewer-001',
1355
- artifactId: 'pi-art-task-rollout-reviewer-001-run-rollout-reviewer-001',
1356
- resultRef: 'rollout-reviewer://run-rollout-reviewer-001',
1357
- contextHash: 'ctx-rr-abc',
1358
- output: {
1359
- taskId: 'task-rollout-reviewer-001',
1360
- sourceEvaluatorArtifactId: 'pi-art-evaluator-001',
1361
- review: {
1362
- decision: 'approve_rollout',
1363
- summary: 'Test rollout review summary',
1364
- confidence: 0.9,
1365
- requiredChanges: [],
1366
- rolloutRisks: [],
1367
- safetyChecks: ['Verify feature flag is properly configured'],
1368
- },
1369
- sourceTrace: { evaluatorArtifactId: 'pi-art-evaluator-001' },
1370
- risks: [],
1371
- generatedAt: new Date().toISOString(),
1372
- },
1373
- attemptCount: 1,
1374
- });
1375
-
1376
- await handleRuntimeInternalizationRunOnce({ workspace: WS, runner: 'rollout_reviewer', runtime: 'test-double', allowTestDouble: true, json: true });
1377
-
1378
- const RolloutReviewerRunnerMock = vi.mocked(
1379
- await import('@principles/core/runtime-v2').then(m => m.RolloutReviewerRunner),
1380
- );
1381
- expect(RolloutReviewerRunnerMock).toHaveBeenCalled();
1382
- expect(mockRun).toHaveBeenCalledWith('task-rollout-reviewer-001');
1383
-
1384
- // PRI-708: the run-once rollout entry must wire the canonical revision
1385
- // routing callback from the ONE host-runtime factory (the same builder the
1386
- // consumer cycle spreads).
1387
- // PRI-713: the same factory now also supplies the canonical
1388
- // dispatchActivation (approve_rollout → ActivationDispatcher with the
1389
- // Owner gate intact) — wired from the durable workspace provenance
1390
- // resolver, exactly as the consumer cycle injects it.
1391
- expect(mockCreateRolloutGovernanceDeps).toHaveBeenCalledTimes(1);
1392
- expect(mockResolveWorkspaceHostToolSemantics).toHaveBeenCalledWith(path.resolve(WS));
1393
- const rolloutDeps = RolloutReviewerRunnerMock.mock.calls[0][0];
1394
- expect(rolloutDeps.reopenRevisionTarget).toBeTypeOf('function');
1395
- expect(rolloutDeps.dispatchActivation).toBeTypeOf('function');
1396
-
1397
- const output = JSON.parse(consoleLogSpy.mock.calls[0][0]);
1398
- expect(output.runnerKind).toBe('rollout_reviewer');
1399
- expect(output.taskId).toBe('task-rollout-reviewer-001');
1400
- expect(output.runId).toBe('run-rollout-reviewer-001');
1401
- expect(output.artifactId).toBe('pi-art-task-rollout-reviewer-001-run-rollout-reviewer-001');
1402
- expect(output.resultRef).toBe('rollout-reviewer://run-rollout-reviewer-001');
1403
- expect(output.runnerResult.status).toBe('succeeded');
1404
- });
1405
-
1406
- it('auto-enqueue: --runner rollout_reviewer returns no_successor for prompt channel', async () => {
1407
- mockWakeOnce.mockResolvedValue({
1408
- decision: 'would_lease',
1409
- taskId: 'task-rollout-reviewer-enq-001',
1410
- taskKind: 'rollout_reviewer',
1411
- });
1412
-
1413
- mockRun.mockResolvedValue({
1414
- status: 'succeeded',
1415
- taskId: 'task-rollout-reviewer-enq-001',
1416
- runId: 'run-rollout-reviewer-enq-001',
1417
- artifactId: 'pi-art-rollout-reviewer-enq-001',
1418
- resultRef: 'rollout-reviewer://run-rollout-reviewer-enq-001',
1419
- contextHash: 'ctx-enq',
1420
- output: {
1421
- taskId: 'task-rollout-reviewer-enq-001',
1422
- sourceEvaluatorArtifactId: 'pi-art-evaluator-enq-001',
1423
- review: {
1424
- decision: 'approve_rollout',
1425
- summary: 'Test rollout review summary',
1426
- confidence: 0.9,
1427
- requiredChanges: [],
1428
- rolloutRisks: [],
1429
- safetyChecks: ['Verify feature flag is properly configured'],
1430
- },
1431
- sourceTrace: { evaluatorArtifactId: 'pi-art-evaluator-enq-001' },
1432
- risks: [],
1433
- generatedAt: new Date().toISOString(),
1434
- },
1435
- attemptCount: 1,
1436
- });
1437
-
1438
- mockCommitNextTaskProposal.mockResolvedValue({
1439
- decision: 'no_successor',
1440
- sourceTaskId: 'task-rollout-reviewer-enq-001',
1441
- reason: 'No valid successor in job graph for this task kind and channel',
1442
- });
1443
-
1444
- await handleRuntimeInternalizationRunOnce({ workspace: WS, runner: 'rollout_reviewer', runtime: 'test-double', allowTestDouble: true, enqueueNext: true, json: true });
1445
-
1446
- const output = JSON.parse(consoleLogSpy.mock.calls[0][0]);
1447
- expect(output.enqueueDecision).toBe('no_successor');
1448
- });
1449
-
1450
- it('--runtime config with missing config outputs structured JSON error', async () => {
1451
- // PRI-393: mock resolveRuntimeFromPdConfig to return config error
1452
- mockResolveRuntimeFromPdConfig.mockReturnValueOnce({
1453
- result: {
1454
- reason: 'explicit_config_missing',
1455
- message: 'runtime=config requested but no .pd/config.yaml runtime binding found',
1456
- nextAction: 'Add runtime binding to .pd/config.yaml',
1457
- },
1458
- legacyWarnings: [],
1459
- configSource: '.pd/config.yaml',
1460
- configLoadResult: { ok: false, effective: {}, defaults: {}, legacyFilesDetected: [] },
1461
- });
1462
-
1463
- mockWakeOnce.mockResolvedValue({
1464
- decision: 'would_lease',
1465
- taskId: 'task-dreamer-cfg-err',
1466
- taskKind: 'dreamer',
1467
- });
1468
-
1469
- await handleRuntimeInternalizationRunOnce({ workspace: WS, runtime: 'config', json: true });
1470
-
1471
- const output = JSON.parse(consoleLogSpy.mock.calls[0][0]);
1472
- expect(output.decision).toBe('config_error');
1473
- expect(output.reason).toContain('explicit_config_missing');
1474
- expect(output.nextAction).toBeTruthy();
1475
- expect(process.exitCode).toBe(1);
1476
- });
1477
-
1478
- it('--runtime config with missing config outputs text error', async () => {
1479
- // PRI-393: mock resolveRuntimeFromPdConfig to return config error
1480
- mockResolveRuntimeFromPdConfig.mockReturnValueOnce({
1481
- result: {
1482
- reason: 'explicit_config_missing',
1483
- message: 'runtime=config requested but no .pd/config.yaml runtime binding found',
1484
- nextAction: 'Add runtime binding to .pd/config.yaml',
1485
- },
1486
- legacyWarnings: [],
1487
- configSource: '.pd/config.yaml',
1488
- configLoadResult: { ok: false, effective: {}, defaults: {}, legacyFilesDetected: [] },
1489
- });
1490
-
1491
- mockWakeOnce.mockResolvedValue({
1492
- decision: 'would_lease',
1493
- taskId: 'task-dreamer-cfg-err2',
1494
- taskKind: 'dreamer',
1495
- });
1496
-
1497
- await handleRuntimeInternalizationRunOnce({ workspace: WS, runtime: 'config', json: false });
1498
-
1499
- expect(consoleErrorSpy.mock.calls.some((c: string[]) => c[0].includes('explicit_config_missing'))).toBe(true);
1500
- expect(process.exitCode).toBe(1);
1501
- });
1502
-
1503
- it('runtime execution error outputs runtime_error in JSON mode', async () => {
1504
- mockWakeOnce.mockResolvedValue({
1505
- decision: 'would_lease',
1506
- taskId: 'task-dreamer-rt-err',
1507
- taskKind: 'dreamer',
1508
- });
1509
- mockRun.mockRejectedValueOnce(new Error('artifact write failed: disk full'));
1510
-
1511
- await handleRuntimeInternalizationRunOnce({ workspace: WS, runner: 'dreamer', runtime: 'test-double', allowTestDouble: true, json: true });
1512
-
1513
- const output = JSON.parse(consoleLogSpy.mock.calls[0][0]);
1514
- expect(output.decision).toBe('runtime_error');
1515
- expect(output.reason).toContain('artifact write failed');
1516
- expect(output.nextAction).toBeTruthy();
1517
- expect(process.exitCode).toBe(1);
1518
- });
1519
-
1520
- // === Default enqueue successor tests ===
1521
-
1522
- it('default behavior (no --no-enqueue-next) auto-enqueues successor on runner success', async () => {
1523
- mockWakeOnce.mockResolvedValue({
1524
- decision: 'would_lease',
1525
- taskId: 'task-dreamer-auto-001',
1526
- taskKind: 'dreamer',
1527
- });
1528
-
1529
- mockRun.mockResolvedValue({
1530
- status: 'succeeded',
1531
- taskId: 'task-dreamer-auto-001',
1532
- runId: 'run-auto-001',
1533
- artifactId: 'pi-art-auto-001',
1534
- resultRef: 'dreamer://run-auto-001',
1535
- contextHash: 'ctx-auto',
1536
- output: { valid: true, taskId: 'task-dreamer-auto-001', candidates: VALID_DREAMER_CANDIDATES, contextRefs: [], generatedAt: new Date().toISOString() },
1537
- attemptCount: 1,
1538
- });
1539
-
1540
- mockCommitNextTaskProposal.mockResolvedValue({
1541
- decision: 'successor_created',
1542
- sourceTaskId: 'task-dreamer-auto-001',
1543
- successorTaskId: 'task-phil-auto-001',
1544
- successorKind: 'philosopher',
1545
- });
1546
-
1547
- // No enqueueNext specified — default should auto-enqueue
1548
- await handleRuntimeInternalizationRunOnce({ workspace: WS, runner: 'dreamer', runtime: 'test-double', allowTestDouble: true, json: true });
1549
-
1550
- const output = JSON.parse(consoleLogSpy.mock.calls[0][0]);
1551
- expect(output.successorEnqueueAttempted).toBe(true);
1552
- expect(output.successorTasksCreated).toBe(1);
1553
- expect(output.successorTaskIds).toContain('task-phil-auto-001');
1554
- expect(output.enqueueDecision).toBe('successor_created');
1555
- expect(output.successorKind).toBe('philosopher');
1556
- expect(mockCommitNextTaskProposal).toHaveBeenCalledWith('task-dreamer-auto-001');
1557
- });
1558
-
1559
- it('--no-enqueue-next (enqueueNext: false) skips successor enqueue', async () => {
1560
- mockWakeOnce.mockResolvedValue({
1561
- decision: 'would_lease',
1562
- taskId: 'task-dreamer-skip-001',
1563
- taskKind: 'dreamer',
1564
- });
1565
-
1566
- mockRun.mockResolvedValue({
1567
- status: 'succeeded',
1568
- taskId: 'task-dreamer-skip-001',
1569
- runId: 'run-skip-001',
1570
- artifactId: 'pi-art-skip-001',
1571
- resultRef: 'dreamer://run-skip-001',
1572
- contextHash: 'ctx-skip',
1573
- output: { valid: true, taskId: 'task-dreamer-skip-001', candidates: VALID_DREAMER_CANDIDATES, contextRefs: [], generatedAt: new Date().toISOString() },
1574
- attemptCount: 1,
1575
- });
1576
-
1577
- await handleRuntimeInternalizationRunOnce({ workspace: WS, runner: 'dreamer', runtime: 'test-double', allowTestDouble: true, enqueueNext: false, json: true });
1578
-
1579
- const output = JSON.parse(consoleLogSpy.mock.calls[0][0]);
1580
- expect(output.successorEnqueueAttempted).toBe(false);
1581
- expect(output.nextAction).toContain('--no-enqueue-next');
1582
- expect(mockCommitNextTaskProposal).not.toHaveBeenCalled();
1583
- });
1584
-
1585
- it('successor enqueue failure outputs partial_success with reason and nextAction', async () => {
1586
- mockWakeOnce.mockResolvedValue({
1587
- decision: 'would_lease',
1588
- taskId: 'task-dreamer-fail-001',
1589
- taskKind: 'dreamer',
1590
- });
1591
-
1592
- mockRun.mockResolvedValue({
1593
- status: 'succeeded',
1594
- taskId: 'task-dreamer-fail-001',
1595
- runId: 'run-fail-001',
1596
- artifactId: 'pi-art-fail-001',
1597
- resultRef: 'dreamer://run-fail-001',
1598
- contextHash: 'ctx-fail',
1599
- output: { valid: true, taskId: 'task-dreamer-fail-001', candidates: VALID_DREAMER_CANDIDATES, contextRefs: [], generatedAt: new Date().toISOString() },
1600
- attemptCount: 1,
1601
- });
1602
-
1603
- mockCommitNextTaskProposal.mockRejectedValue(new Error('database locked'));
1604
-
1605
- await handleRuntimeInternalizationRunOnce({ workspace: WS, runner: 'dreamer', runtime: 'test-double', allowTestDouble: true, json: true });
1606
-
1607
- const output = JSON.parse(consoleLogSpy.mock.calls[0][0]);
1608
- expect(output.decision).toBe('partial_success');
1609
- expect(output.successorEnqueueAttempted).toBe(true);
1610
- expect(output.enqueueDecision).toBe('enqueue_failed');
1611
- expect(output.enqueueReason).toContain('database locked');
1612
- expect(output.nextAction).toContain('enqueue-successors');
1613
- expect(output.successorTasksCreated).toBe(0);
1614
- expect(output.successorTaskIds).toEqual([]);
1615
- });
1616
-
1617
- it('runner failure never enqueues successor (default behavior)', async () => {
1618
- mockWakeOnce.mockResolvedValue({
1619
- decision: 'would_lease',
1620
- taskId: 'task-dreamer-nofail-001',
1621
- taskKind: 'dreamer',
1622
- });
1623
-
1624
- mockRun.mockResolvedValue({
1625
- status: 'failed',
1626
- taskId: 'task-dreamer-nofail-001',
1627
- errorCategory: 'execution_failed',
1628
- failureReason: 'Runtime unavailable',
1629
- attemptCount: 1,
1630
- });
1631
-
1632
- // Default behavior (no --no-enqueue-next)
1633
- await handleRuntimeInternalizationRunOnce({ workspace: WS, runner: 'dreamer', runtime: 'test-double', allowTestDouble: true, json: true });
1634
-
1635
- expect(mockCommitNextTaskProposal).not.toHaveBeenCalled();
1636
- const output = JSON.parse(consoleLogSpy.mock.calls[0][0]);
1637
- expect(output.successorEnqueueAttempted).toBeUndefined();
1638
- });
1639
-
1640
- it('JSON output is single parseable JSON with successor fields', async () => {
1641
- mockWakeOnce.mockResolvedValue({
1642
- decision: 'would_lease',
1643
- taskId: 'task-dreamer-json-001',
1644
- taskKind: 'dreamer',
1645
- });
1646
-
1647
- mockRun.mockResolvedValue({
1648
- status: 'succeeded',
1649
- taskId: 'task-dreamer-json-001',
1650
- runId: 'run-json-001',
1651
- artifactId: 'pi-art-json-001',
1652
- resultRef: 'dreamer://run-json-001',
1653
- contextHash: 'ctx-json',
1654
- output: { valid: true, taskId: 'task-dreamer-json-001', candidates: VALID_DREAMER_CANDIDATES, contextRefs: [], generatedAt: new Date().toISOString() },
1655
- attemptCount: 1,
1656
- });
1657
-
1658
- mockCommitNextTaskProposal.mockResolvedValue({
1659
- decision: 'successor_created',
1660
- sourceTaskId: 'task-dreamer-json-001',
1661
- successorTaskId: 'task-phil-json-001',
1662
- successorKind: 'philosopher',
1663
- });
1664
-
1665
- await handleRuntimeInternalizationRunOnce({ workspace: WS, runner: 'dreamer', runtime: 'test-double', allowTestDouble: true, json: true });
1666
-
1667
- const rawOutput = consoleLogSpy.mock.calls[0][0];
1668
- // Must be single parseable JSON
1669
- const output = JSON.parse(rawOutput);
1670
- expect(output).toHaveProperty('successorEnqueueAttempted');
1671
- expect(output).toHaveProperty('successorTasksCreated');
1672
- expect(output).toHaveProperty('successorTaskIds');
1673
- // nextAction may be undefined when successor is successfully created
1674
- // but must be present on partial_success / no_successor / skipped
1675
- });
1676
-
1677
- it('text output for auto-enqueue shows successor info', async () => {
1678
- mockWakeOnce.mockResolvedValue({
1679
- decision: 'would_lease',
1680
- taskId: 'task-dreamer-text-001',
1681
- taskKind: 'dreamer',
1682
- });
1683
-
1684
- mockRun.mockResolvedValue({
1685
- status: 'succeeded',
1686
- taskId: 'task-dreamer-text-001',
1687
- runId: 'run-text-001',
1688
- artifactId: 'pi-art-text-001',
1689
- resultRef: 'dreamer://run-text-001',
1690
- contextHash: 'ctx-text',
1691
- output: { valid: true, taskId: 'task-dreamer-text-001', candidates: VALID_DREAMER_CANDIDATES, contextRefs: [], generatedAt: new Date().toISOString() },
1692
- attemptCount: 1,
1693
- });
1694
-
1695
- mockCommitNextTaskProposal.mockResolvedValue({
1696
- decision: 'successor_created',
1697
- sourceTaskId: 'task-dreamer-text-001',
1698
- successorTaskId: 'task-phil-text-001',
1699
- successorKind: 'philosopher',
1700
- });
1701
-
1702
- await handleRuntimeInternalizationRunOnce({ workspace: WS, runner: 'dreamer', runtime: 'test-double', allowTestDouble: true, json: false });
1703
-
1704
- const text = consoleLogSpy.mock.calls.map((c: string[]) => c[0]).join('\n');
1705
- expect(text).toContain('successor: task-phil-text-001');
1706
- expect(text).toContain('enqueue_attempted: true');
1707
- expect(text).toContain('successors_created: 1');
1708
- });
1709
- });
1710
-
1711
- // === Commander parser-level tests for --no-enqueue-next ===
1712
- // These tests verify that Commander correctly maps --no-enqueue-next to opts.enqueueNext.
1713
- // They exercise the real Commander parsing path, NOT the handler directly.
1714
- // See ERR-063: previous code used opts.noEnqueueNext (always undefined) instead of opts.enqueueNext.
1715
-
1716
- describe('Commander --no-enqueue-next parser wiring', () => {
1717
- function buildRunOnceCommand(capturedOpts: Record<string, unknown>) {
1718
- // eslint-disable-next-line @typescript-eslint/no-require-imports
1719
- const { Command } = require('commander') as typeof import('commander');
1720
- const program = new Command();
1721
- program.exitOverride(); // prevent process.exit during tests
1722
-
1723
- const internalizationCmd = program.command('internalization');
1724
- internalizationCmd
1725
- .command('run-once')
1726
- .description('Wake-and-run: lease the next PI task and execute it')
1727
- .option('-w, --workspace <path>', 'Workspace directory')
1728
- .option('--runner <kind>', 'Runner kind', 'dreamer')
1729
- .option('--runtime <kind>', 'Runtime adapter kind', 'config')
1730
- .option('--allow-test-double', 'Acknowledge test-double runtime')
1731
- .option('--no-enqueue-next', 'Skip successor enqueue after successful runner')
1732
- .option('--timeout-ms <ms>', 'Runner timeout', parseInt)
1733
- .option('--json', 'Output raw JSON')
1734
- .action(async (opts) => {
1735
- Object.assign(capturedOpts, opts);
1736
- });
1737
-
1738
- return program;
1739
- }
1740
-
1741
- it('with --no-enqueue-next, Commander sets enqueueNext=false', async () => {
1742
- const captured: Record<string, unknown> = {};
1743
- const program = buildRunOnceCommand(captured);
1744
-
1745
- await program.parseAsync([
1746
- 'node', 'pd', 'internalization', 'run-once',
1747
- '--no-enqueue-next',
1748
- '--workspace', '/tmp/test',
1749
- '--runtime', 'test-double',
1750
- '--allow-test-double',
1751
- '--json',
1752
- ]);
1753
-
1754
- expect(captured).toHaveProperty('enqueueNext', false);
1755
- expect(captured).not.toHaveProperty('noEnqueueNext');
1756
- });
1757
-
1758
- it('without --no-enqueue-next, Commander sets enqueueNext=true (default)', async () => {
1759
- const captured: Record<string, unknown> = {};
1760
- const program = buildRunOnceCommand(captured);
1761
-
1762
- await program.parseAsync([
1763
- 'node', 'pd', 'internalization', 'run-once',
1764
- '--workspace', '/tmp/test',
1765
- '--runtime', 'test-double',
1766
- '--allow-test-double',
1767
- '--json',
1768
- ]);
1769
-
1770
- expect(captured).toHaveProperty('enqueueNext', true);
1771
- });
1772
-
1773
- it('opts has no noEnqueueNext property regardless of flag presence', async () => {
1774
- const capturedWith: Record<string, unknown> = {};
1775
- const programWith = buildRunOnceCommand(capturedWith);
1776
- await programWith.parseAsync([
1777
- 'node', 'pd', 'internalization', 'run-once',
1778
- '--no-enqueue-next', '--workspace', '/tmp/test',
1779
- ]);
1780
-
1781
- const capturedWithout: Record<string, unknown> = {};
1782
- const programWithout = buildRunOnceCommand(capturedWithout);
1783
- await programWithout.parseAsync([
1784
- 'node', 'pd', 'internalization', 'run-once',
1785
- '--workspace', '/tmp/test',
1786
- ]);
1787
-
1788
- expect(capturedWith).not.toHaveProperty('noEnqueueNext');
1789
- expect(capturedWithout).not.toHaveProperty('noEnqueueNext');
1790
- });
1791
- });