@principles/pd-cli 1.152.12 → 1.152.14

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (305) hide show
  1. package/dist/commands/candidate.d.ts.map +1 -1
  2. package/dist/commands/candidate.js +34 -7
  3. package/dist/commands/candidate.js.map +1 -1
  4. package/dist/commands/diagnose.d.ts.map +1 -1
  5. package/dist/commands/diagnose.js +23 -7
  6. package/dist/commands/diagnose.js.map +1 -1
  7. package/dist/commands/pain-retry.d.ts.map +1 -1
  8. package/dist/commands/pain-retry.js +21 -7
  9. package/dist/commands/pain-retry.js.map +1 -1
  10. package/package.json +13 -7
  11. package/CHANGELOG.md +0 -23
  12. package/dist/commands/__tests__/intent-flag-wiring.test.d.ts +0 -9
  13. package/dist/commands/__tests__/intent-flag-wiring.test.d.ts.map +0 -1
  14. package/dist/commands/__tests__/intent-flag-wiring.test.js +0 -237
  15. package/dist/commands/__tests__/intent-flag-wiring.test.js.map +0 -1
  16. package/dist/commands/__tests__/legacy-cleanup.test.d.ts +0 -18
  17. package/dist/commands/__tests__/legacy-cleanup.test.d.ts.map +0 -1
  18. package/dist/commands/__tests__/legacy-cleanup.test.js +0 -467
  19. package/dist/commands/__tests__/legacy-cleanup.test.js.map +0 -1
  20. package/dist/commands/__tests__/mvp-smoke.test.d.ts +0 -15
  21. package/dist/commands/__tests__/mvp-smoke.test.d.ts.map +0 -1
  22. package/dist/commands/__tests__/mvp-smoke.test.js +0 -262
  23. package/dist/commands/__tests__/mvp-smoke.test.js.map +0 -1
  24. package/dist/commands/__tests__/pain-retry-maxTokens-flag.test.d.ts +0 -2
  25. package/dist/commands/__tests__/pain-retry-maxTokens-flag.test.d.ts.map +0 -1
  26. package/dist/commands/__tests__/pain-retry-maxTokens-flag.test.js +0 -60
  27. package/dist/commands/__tests__/pain-retry-maxTokens-flag.test.js.map +0 -1
  28. package/dist/commands/__tests__/rulecode-flag-wiring.test.d.ts +0 -21
  29. package/dist/commands/__tests__/rulecode-flag-wiring.test.d.ts.map +0 -1
  30. package/dist/commands/__tests__/rulecode-flag-wiring.test.js +0 -186
  31. package/dist/commands/__tests__/rulecode-flag-wiring.test.js.map +0 -1
  32. package/dist/commands/__tests__/rulecode-handler.test.d.ts +0 -16
  33. package/dist/commands/__tests__/rulecode-handler.test.d.ts.map +0 -1
  34. package/dist/commands/__tests__/rulecode-handler.test.js +0 -285
  35. package/dist/commands/__tests__/rulecode-handler.test.js.map +0 -1
  36. package/dist/commands/__tests__/run-rulehost-flag-wiring.test.d.ts +0 -24
  37. package/dist/commands/__tests__/run-rulehost-flag-wiring.test.d.ts.map +0 -1
  38. package/dist/commands/__tests__/run-rulehost-flag-wiring.test.js +0 -232
  39. package/dist/commands/__tests__/run-rulehost-flag-wiring.test.js.map +0 -1
  40. package/dist/commands/__tests__/runtime-activation-nextaction.test.d.ts +0 -15
  41. package/dist/commands/__tests__/runtime-activation-nextaction.test.d.ts.map +0 -1
  42. package/dist/commands/__tests__/runtime-activation-nextaction.test.js +0 -73
  43. package/dist/commands/__tests__/runtime-activation-nextaction.test.js.map +0 -1
  44. package/dist/commands/__tests__/runtime-probe-config.test.d.ts +0 -20
  45. package/dist/commands/__tests__/runtime-probe-config.test.d.ts.map +0 -1
  46. package/dist/commands/__tests__/runtime-probe-config.test.js +0 -389
  47. package/dist/commands/__tests__/runtime-probe-config.test.js.map +0 -1
  48. package/dist/commands/__tests__/telemetry-flag-wiring.test.d.ts +0 -9
  49. package/dist/commands/__tests__/telemetry-flag-wiring.test.d.ts.map +0 -1
  50. package/dist/commands/__tests__/telemetry-flag-wiring.test.js +0 -76
  51. package/dist/commands/__tests__/telemetry-flag-wiring.test.js.map +0 -1
  52. package/dist/commands/__tests__/version.test.d.ts +0 -2
  53. package/dist/commands/__tests__/version.test.d.ts.map +0 -1
  54. package/dist/commands/__tests__/version.test.js +0 -238
  55. package/dist/commands/__tests__/version.test.js.map +0 -1
  56. package/dist/commands/runtime-uat.guard.test.d.ts +0 -2
  57. package/dist/commands/runtime-uat.guard.test.d.ts.map +0 -1
  58. package/dist/commands/runtime-uat.guard.test.js +0 -153
  59. package/dist/commands/runtime-uat.guard.test.js.map +0 -1
  60. package/dist/services/__tests__/cli-output.test.d.ts +0 -18
  61. package/dist/services/__tests__/cli-output.test.d.ts.map +0 -1
  62. package/dist/services/__tests__/cli-output.test.js +0 -103
  63. package/dist/services/__tests__/cli-output.test.js.map +0 -1
  64. package/dist/services/__tests__/evaluator-runner-deps.test.d.ts +0 -2
  65. package/dist/services/__tests__/evaluator-runner-deps.test.d.ts.map +0 -1
  66. package/dist/services/__tests__/evaluator-runner-deps.test.js +0 -343
  67. package/dist/services/__tests__/evaluator-runner-deps.test.js.map +0 -1
  68. package/dist/services/__tests__/rulehost-readiness.test.d.ts +0 -2
  69. package/dist/services/__tests__/rulehost-readiness.test.d.ts.map +0 -1
  70. package/dist/services/__tests__/rulehost-readiness.test.js +0 -311
  71. package/dist/services/__tests__/rulehost-readiness.test.js.map +0 -1
  72. package/dist/services/__tests__/runtime-adapter-resolver.test.d.ts +0 -18
  73. package/dist/services/__tests__/runtime-adapter-resolver.test.d.ts.map +0 -1
  74. package/dist/services/__tests__/runtime-adapter-resolver.test.js +0 -673
  75. package/dist/services/__tests__/runtime-adapter-resolver.test.js.map +0 -1
  76. package/dist/utils/production-workspace-guard.test.d.ts +0 -2
  77. package/dist/utils/production-workspace-guard.test.d.ts.map +0 -1
  78. package/dist/utils/production-workspace-guard.test.js +0 -137
  79. package/dist/utils/production-workspace-guard.test.js.map +0 -1
  80. package/scripts/llm-dogfood.ts +0 -456
  81. package/scripts/migrate-illegal-expected-decision.ts +0 -252
  82. package/src/commands/__tests__/intent-flag-wiring.test.ts +0 -282
  83. package/src/commands/__tests__/legacy-cleanup.test.ts +0 -602
  84. package/src/commands/__tests__/mvp-smoke.test.ts +0 -300
  85. package/src/commands/__tests__/pain-retry-maxTokens-flag.test.ts +0 -73
  86. package/src/commands/__tests__/rulecode-flag-wiring.test.ts +0 -237
  87. package/src/commands/__tests__/rulecode-handler.test.ts +0 -369
  88. package/src/commands/__tests__/run-rulehost-flag-wiring.test.ts +0 -292
  89. package/src/commands/__tests__/runtime-activation-nextaction.test.ts +0 -81
  90. package/src/commands/__tests__/runtime-probe-config.test.ts +0 -432
  91. package/src/commands/__tests__/telemetry-flag-wiring.test.ts +0 -84
  92. package/src/commands/__tests__/version.test.ts +0 -251
  93. package/src/commands/admission-gate.ts +0 -30
  94. package/src/commands/artifact.ts +0 -82
  95. package/src/commands/build-trajectory-evidence.ts +0 -298
  96. package/src/commands/candidate.ts +0 -1250
  97. package/src/commands/codex-ingest-catchup.ts +0 -114
  98. package/src/commands/codex-ingest-quarantine.ts +0 -127
  99. package/src/commands/codex-reconcile.ts +0 -84
  100. package/src/commands/codex-setup.ts +0 -476
  101. package/src/commands/codex-worker.ts +0 -185
  102. package/src/commands/command-helpers.ts +0 -24
  103. package/src/commands/config-doctor.ts +0 -193
  104. package/src/commands/console.ts +0 -797
  105. package/src/commands/context.ts +0 -72
  106. package/src/commands/demo-story-a.ts +0 -241
  107. package/src/commands/diagnose.ts +0 -756
  108. package/src/commands/errors-list.ts +0 -441
  109. package/src/commands/evolution-tasks-list.ts +0 -48
  110. package/src/commands/evolution-tasks-show.ts +0 -62
  111. package/src/commands/flow.ts +0 -60
  112. package/src/commands/health-codex.ts +0 -576
  113. package/src/commands/health.ts +0 -315
  114. package/src/commands/history.ts +0 -63
  115. package/src/commands/intent.ts +0 -457
  116. package/src/commands/legacy-cleanup.ts +0 -531
  117. package/src/commands/legacy-import.ts +0 -104
  118. package/src/commands/mvp-smoke.ts +0 -160
  119. package/src/commands/pain-evidence.ts +0 -226
  120. package/src/commands/pain-list.ts +0 -239
  121. package/src/commands/pain-record.ts +0 -612
  122. package/src/commands/pain-retry.ts +0 -916
  123. package/src/commands/principles-stats.ts +0 -700
  124. package/src/commands/proven-channel-baseline.ts +0 -115
  125. package/src/commands/quality-scorecard.ts +0 -272
  126. package/src/commands/remediation-output.ts +0 -66
  127. package/src/commands/rulecode.ts +0 -465
  128. package/src/commands/run.ts +0 -89
  129. package/src/commands/runtime-activation.ts +0 -1629
  130. package/src/commands/runtime-artifact-repair.ts +0 -524
  131. package/src/commands/runtime-canary.ts +0 -395
  132. package/src/commands/runtime-compatibility-scan.ts +0 -105
  133. package/src/commands/runtime-diagnostics-export.ts +0 -229
  134. package/src/commands/runtime-features.ts +0 -153
  135. package/src/commands/runtime-gfi-snapshot.ts +0 -135
  136. package/src/commands/runtime-health-snapshot.ts +0 -108
  137. package/src/commands/runtime-init.ts +0 -429
  138. package/src/commands/runtime-internalization-enqueue-successors.ts +0 -530
  139. package/src/commands/runtime-internalization-integrity-repair.ts +0 -79
  140. package/src/commands/runtime-internalization-integrity.ts +0 -107
  141. package/src/commands/runtime-internalization-queue.ts +0 -135
  142. package/src/commands/runtime-internalization-retry.ts +0 -191
  143. package/src/commands/runtime-internalization-run-once.ts +0 -791
  144. package/src/commands/runtime-internalization-run-rulehost.ts +0 -749
  145. package/src/commands/runtime-internalization-wake-once.ts +0 -87
  146. package/src/commands/runtime-pain-flood-simulation.ts +0 -121
  147. package/src/commands/runtime-pruning.ts +0 -438
  148. package/src/commands/runtime-recovery-failed-tasks.ts +0 -258
  149. package/src/commands/runtime-recovery.ts +0 -109
  150. package/src/commands/runtime-synthetic-baseline.ts +0 -70
  151. package/src/commands/runtime-uat.guard.test.ts +0 -175
  152. package/src/commands/runtime-uat.ts +0 -380
  153. package/src/commands/runtime.ts +0 -473
  154. package/src/commands/samples-list.ts +0 -39
  155. package/src/commands/samples-review.ts +0 -36
  156. package/src/commands/task.ts +0 -271
  157. package/src/commands/telemetry.ts +0 -349
  158. package/src/commands/trace.ts +0 -174
  159. package/src/commands/trajectory-db-unavailable.ts +0 -19
  160. package/src/commands/trajectory.ts +0 -64
  161. package/src/commands/version.ts +0 -49
  162. package/src/config-reader.ts +0 -122
  163. package/src/index.ts +0 -1276
  164. package/src/legacy/legacy-import.ts +0 -179
  165. package/src/legacy/session-history-import.ts +0 -203
  166. package/src/resolve-workspace.ts +0 -106
  167. package/src/services/__tests__/cli-output.test.ts +0 -130
  168. package/src/services/__tests__/evaluator-runner-deps.test.ts +0 -382
  169. package/src/services/__tests__/rulehost-readiness.test.ts +0 -363
  170. package/src/services/__tests__/runtime-adapter-resolver.test.ts +0 -793
  171. package/src/services/cli-output.ts +0 -95
  172. package/src/services/config-doctor.ts +0 -697
  173. package/src/services/console-launcher.ts +0 -537
  174. package/src/services/demo-rule-compiler.ts +0 -40
  175. package/src/services/demo-story-a-runner.ts +0 -471
  176. package/src/services/mainline-snapshot-assembler.ts +0 -579
  177. package/src/services/pain-flood-simulation-runner.ts +0 -462
  178. package/src/services/pd-config-loader.ts +0 -433
  179. package/src/services/proven-channel-baseline-runner.ts +0 -157
  180. package/src/services/quality-scorecard/data-extractor.ts +0 -150
  181. package/src/services/quality-scorecard/local-evaluator.ts +0 -142
  182. package/src/services/quality-scorecard/strong-model-gate.ts +0 -202
  183. package/src/services/resolve-runtime-from-pd-config.ts +0 -230
  184. package/src/services/rulehost-pipeline-runner.ts +0 -1214
  185. package/src/services/rulehost-readiness.ts +0 -326
  186. package/src/services/runtime-adapter-resolver.ts +0 -364
  187. package/src/services/synthetic-baseline-runner.ts +0 -400
  188. package/src/services/version-report.ts +0 -253
  189. package/src/services/workspace-tool-semantics.ts +0 -26
  190. package/src/utils/path-security.ts +0 -96
  191. package/src/utils/production-workspace-guard.test.ts +0 -157
  192. package/src/utils/production-workspace-guard.ts +0 -210
  193. package/tests/bdd/cli-contract.steps.ts +0 -346
  194. package/tests/bdd/principles-stats.steps.ts +0 -211
  195. package/tests/bdd/support/gherkin-loader.ts +0 -147
  196. package/tests/bdd/support/repo-root.ts +0 -62
  197. package/tests/bdd/support/vitest-bdd.ts +0 -179
  198. package/tests/commands/admission-gate-coverage.test.ts +0 -79
  199. package/tests/commands/build-trajectory-evidence.test.ts +0 -508
  200. package/tests/commands/candidate-audit-repair.test.ts +0 -421
  201. package/tests/commands/candidate-intake.test.ts +0 -732
  202. package/tests/commands/candidate-internalization-backfill.test.ts +0 -548
  203. package/tests/commands/candidate-internalize-lineage.test.ts +0 -628
  204. package/tests/commands/candidate-internalize.test.ts +0 -299
  205. package/tests/commands/candidate-route.test.ts +0 -329
  206. package/tests/commands/candidate-show.test.ts +0 -95
  207. package/tests/commands/cli-command-tree.test.ts +0 -144
  208. package/tests/commands/cli-help-snapshot.test.ts +0 -155
  209. package/tests/commands/cli-skill-contract.test.ts +0 -121
  210. package/tests/commands/codex-consent-reversibility.steps.test.ts +0 -299
  211. package/tests/commands/codex-ingest-quarantine.test.ts +0 -136
  212. package/tests/commands/codex-setup.test.ts +0 -297
  213. package/tests/commands/codex-worker-daemon.test.ts +0 -95
  214. package/tests/commands/codex-worker-registration.test.ts +0 -207
  215. package/tests/commands/config-doctor.test.ts +0 -336
  216. package/tests/commands/console-launcher-edge-cases.test.ts +0 -388
  217. package/tests/commands/console-open.test.ts +0 -1381
  218. package/tests/commands/context.test.ts +0 -114
  219. package/tests/commands/demo-story-a.test.ts +0 -318
  220. package/tests/commands/diagnose.test.ts +0 -1803
  221. package/tests/commands/errors-list.test.ts +0 -679
  222. package/tests/commands/evolution-tasks-list.test.ts +0 -41
  223. package/tests/commands/evolution-tasks-show.test.ts +0 -46
  224. package/tests/commands/health-codex.test.ts +0 -349
  225. package/tests/commands/health-host-wiring.test.ts +0 -76
  226. package/tests/commands/health-reliability.test.ts +0 -99
  227. package/tests/commands/health.test.ts +0 -413
  228. package/tests/commands/intent.test.ts +0 -321
  229. package/tests/commands/legacy-cleanup.test.ts +0 -148
  230. package/tests/commands/pain-evidence.test.ts +0 -518
  231. package/tests/commands/pain-list.test.ts +0 -219
  232. package/tests/commands/pain-record-async.test.ts +0 -335
  233. package/tests/commands/pain-record-session-parser.test.ts +0 -228
  234. package/tests/commands/pain-record.test.ts +0 -851
  235. package/tests/commands/pain-retry.test.ts +0 -1121
  236. package/tests/commands/plugin-config-resolution-cutover.test.ts +0 -229
  237. package/tests/commands/pri-393-runtime-config-unification.test.ts +0 -443
  238. package/tests/commands/principles-stats-wiring.test.ts +0 -135
  239. package/tests/commands/principles-stats.test.ts +0 -274
  240. package/tests/commands/product-path-regression.test.ts +0 -86
  241. package/tests/commands/proven-channel-baseline.test.ts +0 -441
  242. package/tests/commands/rulecode.test.ts +0 -177
  243. package/tests/commands/run-rulehost-handler.test.ts +0 -908
  244. package/tests/commands/runtime-activation-approve-flag-wiring.test.ts +0 -227
  245. package/tests/commands/runtime-activation-deactivate-flag-wiring.test.ts +0 -167
  246. package/tests/commands/runtime-activation-dispatch-flag-wiring.test.ts +0 -262
  247. package/tests/commands/runtime-activation-governance-audit.test.ts +0 -95
  248. package/tests/commands/runtime-activation-list-flag-wiring.test.ts +0 -193
  249. package/tests/commands/runtime-activation-promote-flag-wiring.test.ts +0 -248
  250. package/tests/commands/runtime-activation-shadow-telemetry.test.ts +0 -130
  251. package/tests/commands/runtime-activation.test.ts +0 -2052
  252. package/tests/commands/runtime-artifact-repair-registration.test.ts +0 -74
  253. package/tests/commands/runtime-artifact-repair.test.ts +0 -404
  254. package/tests/commands/runtime-canary.test.ts +0 -430
  255. package/tests/commands/runtime-compatibility-scan.test.ts +0 -146
  256. package/tests/commands/runtime-diagnostics-export.test.ts +0 -175
  257. package/tests/commands/runtime-features.test.ts +0 -249
  258. package/tests/commands/runtime-health-snapshot.test.ts +0 -358
  259. package/tests/commands/runtime-init-empty-workspace.test.ts +0 -252
  260. package/tests/commands/runtime-init.test.ts +0 -420
  261. package/tests/commands/runtime-internalization-enqueue-successors.test.ts +0 -782
  262. package/tests/commands/runtime-internalization-integrity-repair.test.ts +0 -239
  263. package/tests/commands/runtime-internalization-integrity.test.ts +0 -140
  264. package/tests/commands/runtime-internalization-queue.test.ts +0 -380
  265. package/tests/commands/runtime-internalization-retry-owner-authority.test.ts +0 -431
  266. package/tests/commands/runtime-internalization-run-once-evaluator-parity.test.ts +0 -269
  267. package/tests/commands/runtime-internalization-run-once-language.test.ts +0 -303
  268. package/tests/commands/runtime-internalization-run-once-real-config.test.ts +0 -237
  269. package/tests/commands/runtime-internalization-run-once-rollout-parity.test.ts +0 -706
  270. package/tests/commands/runtime-internalization-run-once.test.ts +0 -1791
  271. package/tests/commands/runtime-internalization-wake-once.test.ts +0 -171
  272. package/tests/commands/runtime-internalization.test.ts +0 -53
  273. package/tests/commands/runtime-pain-flood-simulation.test.ts +0 -418
  274. package/tests/commands/runtime-pruning.test.ts +0 -694
  275. package/tests/commands/runtime-recovery-failed-tasks.test.ts +0 -328
  276. package/tests/commands/runtime-recovery.test.ts +0 -120
  277. package/tests/commands/runtime-synthetic-baseline.test.ts +0 -249
  278. package/tests/commands/runtime-uat.test.ts +0 -397
  279. package/tests/commands/runtime.test.ts +0 -392
  280. package/tests/commands/samples-list.test.ts +0 -43
  281. package/tests/commands/samples-review.test.ts +0 -41
  282. package/tests/commands/task.test.ts +0 -153
  283. package/tests/commands/telemetry.test.ts +0 -190
  284. package/tests/commands/trace.test.ts +0 -316
  285. package/tests/config-reader.test.ts +0 -143
  286. package/tests/e2e/candidate-intake-e2e.test.ts +0 -338
  287. package/tests/e2e/cli-full-flow.test.ts +0 -233
  288. package/tests/e2e/cross-package-acceptance.test.ts +0 -635
  289. package/tests/helpers/pd-cli-path.ts +0 -5
  290. package/tests/pd-cli-smoke.test.ts +0 -13
  291. package/tests/resolve-workspace.test.ts +0 -196
  292. package/tests/services/config-doctor-signal-health.test.ts +0 -109
  293. package/tests/services/console-launcher.test.ts +0 -114
  294. package/tests/services/demo-rule-compiler.test.ts +0 -242
  295. package/tests/services/mainline-snapshot-assembler.test.ts +0 -572
  296. package/tests/services/pd-config-loader.test.ts +0 -505
  297. package/tests/services/proven-channel-baseline-runner.test.ts +0 -30
  298. package/tests/services/quality-scorecard/strong-model-gate.test.ts +0 -133
  299. package/tests/services/resolve-runtime-from-pd-config.test.ts +0 -485
  300. package/tests/services/rulehost-pipeline-e2e.test.ts +0 -538
  301. package/tests/services/rulehost-pipeline-runner.test.ts +0 -1242
  302. package/tests/services/workspace-tool-semantics.test.ts +0 -76
  303. package/tests/utils/path-security.test.ts +0 -180
  304. package/tsconfig.json +0 -26
  305. package/vitest.config.ts +0 -10
@@ -1,346 +0,0 @@
1
- /**
2
- * BDD step definitions for CLI strict JSON output contract (cli-1-strict-json).
3
- *
4
- * Approach: Command + mocks (NOT real CLI subprocess execution).
5
- * Reuses the exact same mock pattern as tests/commands/pain-retry.test.ts:
6
- * - vi.hoisted() + vi.mock() to stub @principles/core/runtime-v2 and friends
7
- * - Import handlePainRetry directly and call it in-process
8
- * - Capture console.log via vi.spyOn to verify stdout JSON contract
9
- *
10
- * Rationale: pd pain retry needs a real workspace + pain-id + config to execute
11
- * as a subprocess. Testing the JSON output contract in-process with mocks is
12
- * more reliable and follows the established pattern in this repo.
13
- */
14
- import { vi, expect } from 'vitest';
15
- import { Command } from 'commander';
16
- import { readFileSync } from 'node:fs';
17
- import { createStepRegistry, defineFeature } from './support/vitest-bdd.js';
18
- import { resolveFeaturePath } from './support/repo-root.js';
19
-
20
- // ── Mocks (mirrors tests/commands/pain-retry.test.ts) ──────────────────────────
21
-
22
- const {
23
- MockRuntimeStateManager,
24
- mockGetTask,
25
- mockGetCandidatesByTaskId,
26
- mockUpdateCandidateStatus,
27
- mockGetRunsByTask,
28
- } = vi.hoisted(() => {
29
- const mockGetTask = vi.fn().mockResolvedValue(null);
30
- const mockGetCandidatesByTaskId = vi.fn().mockResolvedValue([]);
31
- const mockUpdateCandidateStatus = vi.fn().mockResolvedValue(undefined);
32
- const mockGetRunsByTask = vi.fn().mockResolvedValue([]);
33
-
34
- class MockRuntimeStateManager {
35
- initialize = vi.fn().mockResolvedValue(undefined);
36
- close = vi.fn().mockResolvedValue(undefined);
37
- getTask = mockGetTask;
38
- getCandidatesByTaskId = mockGetCandidatesByTaskId;
39
- updateCandidateStatus = mockUpdateCandidateStatus;
40
- getRunsByTask = mockGetRunsByTask;
41
- connection = {} as Record<string, unknown>;
42
- taskStore = {};
43
- runStore = {};
44
- }
45
- return {
46
- MockRuntimeStateManager,
47
- mockGetTask,
48
- mockGetCandidatesByTaskId,
49
- mockUpdateCandidateStatus,
50
- mockGetRunsByTask,
51
- };
52
- }, { validateType: true });
53
-
54
- const { mockIntake, MockCandidateIntakeService } = vi.hoisted(() => {
55
- const mockIntake = vi.fn();
56
- function MockCandidateIntakeService(this: unknown) {
57
- return { intake: mockIntake };
58
- }
59
- MockCandidateIntakeService.prototype = {};
60
- return { mockIntake, MockCandidateIntakeService };
61
- });
62
-
63
- const { MockPrincipleTreeLedgerAdapter } = vi.hoisted(() => {
64
- function MockPrincipleTreeLedgerAdapter(this: unknown) {
65
- return {};
66
- }
67
- MockPrincipleTreeLedgerAdapter.prototype = {};
68
- return { MockPrincipleTreeLedgerAdapter };
69
- });
70
-
71
- const { mockRun, mockResolveRuntimeConfig, mockResolveRuntimeFromPdConfig } = vi.hoisted(() => {
72
- const mockRun = vi.fn().mockResolvedValue({
73
- status: 'succeeded',
74
- taskId: 'diagnosis_test-pain-1',
75
- runId: 'run-retry-1',
76
- contextHash: 'abc123',
77
- });
78
- const mockResolveRuntimeConfig = vi.fn().mockReturnValue({
79
- runtimeKind: 'pi-ai',
80
- provider: 'test-provider',
81
- model: 'test-model',
82
- apiKeyEnv: 'TEST_KEY',
83
- timeoutMs: 300000,
84
- agentId: 'main',
85
- });
86
- const mockResolveRuntimeFromPdConfig = vi.fn().mockReturnValue({
87
- result: {
88
- runtimeKind: 'pi-ai',
89
- provider: 'test-provider',
90
- model: 'test-model',
91
- apiKeyEnv: 'TEST_KEY',
92
- timeoutMs: 300000,
93
- agentId: 'main',
94
- },
95
- legacyWarnings: [],
96
- configSource: '.pd/config.yaml',
97
- configLoadResult: { ok: true, effective: {}, defaults: {}, legacyFilesDetected: [] },
98
- });
99
- return { mockRun, mockResolveRuntimeConfig, mockResolveRuntimeFromPdConfig };
100
- });
101
-
102
- vi.mock('../../src/resolve-workspace.js', () => ({
103
- resolveWorkspaceDir: vi.fn().mockReturnValue('/tmp/fake-workspace'),
104
- }));
105
-
106
- vi.mock('@principles/core/runtime-v2', () => {
107
- return {
108
- RuntimeStateManager: vi.fn().mockImplementation(function () {
109
- return new MockRuntimeStateManager();
110
- }),
111
- SqliteHistoryQuery: vi.fn().mockImplementation(function () { return {}; }),
112
- SqliteContextAssembler: vi.fn().mockImplementation(function () { return {}; }),
113
- SqliteDiagnosticianCommitter: vi.fn().mockImplementation(function () { return {}; }),
114
- SqliteTrajectoryLocator: vi.fn().mockImplementation(function () { return {}; }),
115
- SqliteSourceTraceLocator: vi.fn().mockImplementation(function () { return {}; }),
116
- // Dead-letter store mock: getByPainId returns null so the implementation
117
- // produces status='not_found' with reason='task_not_found' for the
118
- // "失败命令的 --json 输出含 reason 和 nextAction" scenario.
119
- SqliteDeadLetterStore: vi.fn().mockImplementation(function () {
120
- return { getByPainId: vi.fn().mockReturnValue(null) };
121
- }),
122
- PainSignalBridge: vi.fn().mockImplementation(function () { return {}; }),
123
- StoreEventEmitter: vi.fn().mockImplementation(function () { return {}; }),
124
- storeEmitter: { emitTelemetry: vi.fn() },
125
- SplitDiagnosticianRunner: vi.fn().mockImplementation(function () { return {}; }),
126
- DiagRootCauseRunner: vi.fn().mockImplementation(function () { return {}; }),
127
- DiagDistillerRunner: vi.fn().mockImplementation(function () { return {}; }),
128
- DiagRouterRunner: vi.fn().mockImplementation(function () { return {}; }),
129
- DefaultDiagRootCauseValidator: vi.fn().mockImplementation(function () { return {}; }),
130
- DefaultDiagDistillerValidator: vi.fn().mockImplementation(function () { return {}; }),
131
- DisabledDiagnosticianRunner: vi.fn().mockImplementation(function () { return {}; }),
132
- TestDoubleRuntimeAdapter: vi.fn().mockImplementation(function () { return {}; }),
133
- OpenClawCliRuntimeAdapter: vi.fn().mockImplementation(function () { return {}; }),
134
- PiAiRuntimeAdapter: vi.fn().mockImplementation(function () { return {}; }),
135
- SPLIT_PIPELINE_TOTAL_TIMEOUT_MS: 300000,
136
- // PRI-638: capability gate — available by default so the BDD scenarios
137
- // exercise the pre-existing success/failure JSON contracts unchanged.
138
- resolveDiagnosticianCapability: vi.fn(() => ({ available: true })),
139
- PDRuntimeError: class PDRuntimeError extends Error {
140
- constructor(public category: string, message: string) {
141
- super(message);
142
- this.name = 'PDRuntimeError';
143
- }
144
- },
145
- CandidateIntakeService: MockCandidateIntakeService,
146
- resolveRuntimeConfig: mockResolveRuntimeConfig,
147
- isRuntimeConfigError: vi.fn().mockReturnValue(false),
148
- isFeatureEnabled: vi.fn().mockReturnValue(true),
149
- resolveOutputLanguage: vi.fn().mockReturnValue({ outputLanguage: 'zh-CN' }),
150
- validatePdConfig: vi.fn().mockReturnValue({ valid: true, errors: [] }),
151
- computeEffectivePdConfig: vi.fn().mockReturnValue({ config: {}, source: 'defaults', warnings: [] }),
152
- computeFeatureFlagsFromConfig: vi.fn().mockReturnValue({}),
153
- redactPdConfig: vi.fn().mockImplementation((c) => c),
154
- run: mockRun,
155
- status: vi.fn(),
156
- PrincipleTreeLedgerAdapter: MockPrincipleTreeLedgerAdapter,
157
- };
158
- });
159
-
160
- vi.mock('../../src/config-reader.js', () => ({
161
- readOutputLanguageFromWorkspace: vi.fn().mockReturnValue({ outputLanguage: 'zh-CN' }),
162
- }));
163
-
164
- vi.mock('../../src/services/resolve-runtime-from-pd-config.js', () => ({
165
- resolveRuntimeFromPdConfig: mockResolveRuntimeFromPdConfig,
166
- }));
167
-
168
- import { registerPainRetryCommand } from '../../src/commands/pain-retry.js';
169
-
170
- // ── Test data ──────────────────────────────────────────────────────────────────
171
-
172
- const RETRY_WAIT_TASK = {
173
- taskId: 'diagnosis_pain-001',
174
- taskKind: 'diagnostician',
175
- status: 'retry_wait' as const,
176
- attemptCount: 1,
177
- maxAttempts: 3,
178
- lastError: 'output_invalid',
179
- leaseOwner: null,
180
- leaseExpiresAt: null,
181
- resultRef: null,
182
- createdAt: new Date().toISOString(),
183
- updatedAt: new Date().toISOString(),
184
- };
185
-
186
- // ── Helpers ────────────────────────────────────────────────────────────────────
187
-
188
- /** Reset all mocks to a clean default state for the next scenario. */
189
- function resetMocksForScenario(painId: string): void {
190
- vi.clearAllMocks();
191
-
192
- mockResolveRuntimeConfig.mockReturnValue({
193
- runtimeKind: 'pi-ai',
194
- provider: 'test-provider',
195
- model: 'test-model',
196
- apiKeyEnv: 'TEST_KEY',
197
- timeoutMs: 300000,
198
- agentId: 'main',
199
- });
200
- mockResolveRuntimeFromPdConfig.mockReturnValue({
201
- result: {
202
- runtimeKind: 'pi-ai',
203
- provider: 'test-provider',
204
- model: 'test-model',
205
- apiKeyEnv: 'TEST_KEY',
206
- timeoutMs: 300000,
207
- agentId: 'main',
208
- },
209
- legacyWarnings: [],
210
- configSource: '.pd/config.yaml',
211
- configLoadResult: { ok: true, effective: {}, defaults: {}, legacyFilesDetected: [] },
212
- });
213
- mockGetCandidatesByTaskId.mockResolvedValue([]);
214
- mockUpdateCandidateStatus.mockResolvedValue(undefined);
215
- mockGetRunsByTask.mockResolvedValue([]);
216
- mockIntake.mockReset();
217
-
218
- if (painId === 'nonexistent') {
219
- // Failure scenario: task not found
220
- mockGetTask.mockResolvedValue(null);
221
- } else {
222
- // Success scenario: retry_wait task → succeeded
223
- mockGetTask.mockResolvedValue({
224
- ...RETRY_WAIT_TASK,
225
- taskId: `diagnosis_${painId}`,
226
- });
227
- mockRun.mockResolvedValue({
228
- status: 'succeeded',
229
- taskId: `diagnosis_${painId}`,
230
- runId: 'run-retry-1',
231
- contextHash: 'abc123',
232
- });
233
- }
234
- }
235
-
236
- // ── Step definitions ───────────────────────────────────────────────────────────
237
-
238
- const registry = createStepRegistry();
239
-
240
- registry.given('一个可用的 pd-cli 可执行文件', () => {
241
- if (typeof registerPainRetryCommand !== 'function') {
242
- throw new Error('pd-cli pain retry registration not available');
243
- }
244
- });
245
-
246
- registry.when(/operator 执行 "(.+)"/, async (ctx, command: string) => {
247
- const argv = command.trim().split(/\s+/);
248
- if (argv.shift() !== 'pd') {
249
- throw new Error(`expected command to start with pd: ${command}`);
250
- }
251
- const painIdIndex = argv.indexOf('--pain-id');
252
- const painId = painIdIndex >= 0 ? argv[painIdIndex + 1] : '';
253
- resetMocksForScenario(painId);
254
-
255
- const logSpy = vi.spyOn(console, 'log').mockImplementation(() => {});
256
- const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
257
- const exitSpy = vi.spyOn(process, 'exit').mockImplementation((() => undefined) as () => never);
258
-
259
- try {
260
- const program = new Command().name('pd').exitOverride();
261
- registerPainRetryCommand(program.command('pain'));
262
- await program.parseAsync(['node', 'pd', ...argv]);
263
- } finally {
264
- expect(exitSpy).not.toHaveBeenCalledWith(0);
265
- }
266
-
267
- const allLogCalls = logSpy.mock.calls.map((c) => String(c[0]));
268
- const jsonCall = allLogCalls.find((s) => {
269
- try { JSON.parse(s); return true; } catch { return false; }
270
- });
271
- // cli-1: 统计 stdout 上可解析为 JSON 的调用数,用于 Then 步骤验证"恰好一个"
272
- const jsonCallCount = allLogCalls.filter((s) => {
273
- try { JSON.parse(s); return true; } catch { return false; }
274
- }).length;
275
- const stdout = allLogCalls.join('\n');
276
- const stderr = errorSpy.mock.calls.map((c) => String(c[0])).join('\n');
277
- ctx.state.cliResult = { stdout, stderr, jsonCallCount, allLogCallCount: allLogCalls.length };
278
-
279
- // Restore spies so Then steps don't capture new calls
280
- logSpy.mockRestore();
281
- errorSpy.mockRestore();
282
- exitSpy.mockRestore();
283
- });
284
-
285
- registry.then('stdout 是严格的单一 JSON 对象', (ctx) => {
286
- const result = ctx.state.cliResult as {
287
- stdout: string;
288
- jsonCallCount: number;
289
- allLogCallCount: number;
290
- };
291
- const out = result.stdout.trim();
292
- // Must start with { and parse as a non-null object
293
- expect(out.startsWith('{')).toBe(true);
294
- const parsed = JSON.parse(out);
295
- expect(typeof parsed).toBe('object');
296
- expect(parsed).not.toBeNull();
297
- expect(result.allLogCallCount).toBe(1);
298
- expect(result.jsonCallCount).toBe(1);
299
- });
300
-
301
- registry.then('该 JSON 对象可以被 JSON.parse 解析', (ctx) => {
302
- const result = ctx.state.cliResult as { stdout: string };
303
- expect(() => JSON.parse(result.stdout.trim())).not.toThrow();
304
- });
305
-
306
- registry.then('stdout 不包含任何 banner 或 heading', (ctx) => {
307
- const result = ctx.state.cliResult as { stdout: string };
308
- const out = result.stdout.trim();
309
- expect(out.startsWith('===')).toBe(false);
310
- expect(out.startsWith('#')).toBe(false);
311
- expect(out.startsWith('PD CLI')).toBe(false);
312
- expect(out.startsWith('pd ')).toBe(false);
313
- // Strict JSON output must start with {
314
- expect(out.startsWith('{')).toBe(true);
315
- });
316
-
317
- registry.then('该 JSON 对象的 status 字段表示失败', (ctx) => {
318
- const result = ctx.state.cliResult as { stdout: string };
319
- const parsed = JSON.parse(result.stdout.trim());
320
- expect(parsed).toHaveProperty('status');
321
- expect(parsed.status).not.toBe('succeeded');
322
- });
323
-
324
- registry.then('该 JSON 对象包含 reason 字段', (ctx) => {
325
- const result = ctx.state.cliResult as { stdout: string };
326
- const parsed = JSON.parse(result.stdout.trim());
327
- expect(parsed).toHaveProperty('reason');
328
- expect(typeof parsed.reason).toBe('string');
329
- expect(parsed.reason.length).toBeGreaterThan(0);
330
- });
331
-
332
- registry.then('该 JSON 对象包含 nextAction 字段', (ctx) => {
333
- const result = ctx.state.cliResult as { stdout: string };
334
- const parsed = JSON.parse(result.stdout.trim());
335
- expect(parsed).toHaveProperty('nextAction');
336
- expect(typeof parsed.nextAction).toBe('string');
337
- expect(parsed.nextAction.length).toBeGreaterThan(0);
338
- });
339
-
340
- // ── Load and register feature ──────────────────────────────────────────────────
341
-
342
- const featureText = readFileSync(
343
- resolveFeaturePath('docs/specs/features/cli/json-output.feature'),
344
- 'utf8'
345
- );
346
- defineFeature(featureText, registry);
@@ -1,211 +0,0 @@
1
- /**
2
- * BDD step definitions for `pd principles stats` (PRI-562 Phase 0,
3
- * cli-1/cli-5/cli-6 contract).
4
- *
5
- * Approach: in-process handler invocation against real temp-workspace
6
- * fixtures (same pattern as tests/commands/principles-stats.test.ts —
7
- * real event JSONL + real SqliteConnection-bootstrap schema, no heavy mocks).
8
- *
9
- * @see docs/specs/features/cli/principles-stats.feature
10
- */
11
- import { vi, expect } from 'vitest';
12
- import * as fs from 'fs';
13
- import * as os from 'os';
14
- import * as path from 'path';
15
- import Database from 'better-sqlite3';
16
- import { SqliteConnection } from '@principles/core';
17
- import { readFileSync } from 'node:fs';
18
- import { createStepRegistry, defineFeature } from './support/vitest-bdd.js';
19
- import { resolveFeaturePath } from './support/repo-root.js';
20
- import { handlePrinciplesStats } from '../../src/commands/principles-stats.js';
21
-
22
- const registry = createStepRegistry();
23
-
24
- interface WsState {
25
- ws?: string;
26
- dbBytesBefore?: Buffer;
27
- ledgerRowsBefore?: number;
28
- }
29
-
30
- const state: WsState = {};
31
-
32
- function localDateString(d: Date): string {
33
- const y = d.getFullYear();
34
- const m = String(d.getMonth() + 1).padStart(2, '0');
35
- const day = String(d.getDate()).padStart(2, '0');
36
- return `${y}-${m}-${day}`;
37
- }
38
-
39
- let stdoutText = '';
40
- let stderrText = '';
41
- let lastExitCode: number | undefined;
42
-
43
- function makeFixtureWorkspace(): string {
44
- const root = fs.mkdtempSync(path.join(os.tmpdir(), 'pd-principles-bdd-'));
45
- const today = localDateString(new Date());
46
- const logsDir = path.join(root, '.state', 'logs');
47
- fs.mkdirSync(logsDir, { recursive: true });
48
- const event = JSON.stringify({
49
- ts: Date.now(),
50
- date: today,
51
- type: 'runtime_v2_prompt_activations_injected',
52
- category: 'injected',
53
- sessionId: 'bdd-s1',
54
- data: {
55
- sessionId: 'bdd-s1',
56
- principleIds: ['p1', 'p2'],
57
- injectedCount: 2,
58
- skippedWarnings: [],
59
- injectedCharCount: 420,
60
- budget: 2000,
61
- legacySelectedCount: 1,
62
- legacyTotalChars: 300,
63
- legacyTruncated: false,
64
- v2Truncated: false,
65
- crossBlockDuplicateIds: ['p2'],
66
- },
67
- });
68
- fs.writeFileSync(path.join(logsDir, `events_${today}.jsonl`), [event, ''].join('\n'), 'utf8');
69
-
70
- fs.mkdirSync(path.join(root, '.pd'), { recursive: true });
71
- const connection = new SqliteConnection({ workspaceDir: root });
72
- const db = connection.getDb();
73
- const insert = db.prepare(
74
- `INSERT INTO principle_applications (principle_id, channel, level, kind, session_id, created_at)
75
- VALUES (?, 'prompt', ?, ?, ?, ?)`,
76
- );
77
- insert.run('p1', 'presence', 'prompt_injected', 'bdd-s1', new Date().toISOString());
78
- insert.run('p2', 'presence', 'prompt_injected', 'bdd-s1', new Date().toISOString());
79
- insert.run('p2', 'effect', 'self_reported', 'bdd-s1', new Date().toISOString());
80
- connection.close();
81
- return root;
82
- }
83
-
84
- // ── Given ────────────────────────────────────────────────────────────────────
85
-
86
- registry.given('一个可用的 pd-cli 可执行文件', () => {
87
- state.ws = undefined;
88
- });
89
-
90
- registry.given('一个包含已知注入事件与回执账本的临时工作区', () => {
91
- state.ws = makeFixtureWorkspace();
92
- const dbPath = path.join(state.ws, '.pd', 'state.db');
93
- state.dbBytesBefore = readFileSync(dbPath);
94
- const db = new Database(dbPath, { readonly: true });
95
- state.ledgerRowsBefore =
96
- (db.prepare('SELECT COUNT(*) AS n FROM principle_applications').get() as { n: number }).n;
97
- db.close();
98
- });
99
-
100
- registry.given('一个空的临时工作区', () => {
101
- state.ws = fs.mkdtempSync(path.join(os.tmpdir(), 'pd-principles-bdd-empty-'));
102
- });
103
-
104
- // ── When ─────────────────────────────────────────────────────────────────────
105
-
106
- registry.when(/operator 执行 "pd principles stats( --json)?"/, async (_ctx, jsonFlag) => {
107
- const logSpy = vi.spyOn(console, 'log').mockImplementation(() => {});
108
- const errSpy = vi.spyOn(process.stderr, 'write').mockImplementation(() => true);
109
- const originalExitCode = process.exitCode;
110
- process.exitCode = undefined;
111
- try {
112
- await handlePrinciplesStats({ workspace: state.ws, json: !!jsonFlag });
113
- } finally {
114
- stdoutText = logSpy.mock.calls.map((c) => String(c[0])).join('');
115
- stderrText = errSpy.mock.calls.map((c) => String(c[0])).join('');
116
- logSpy.mockRestore();
117
- errSpy.mockRestore();
118
- lastExitCode = process.exitCode;
119
- process.exitCode = originalExitCode;
120
- }
121
- });
122
-
123
- // ── Then ─────────────────────────────────────────────────────────────────────
124
-
125
- registry.then('stdout 是严格的单一 JSON 对象', () => {
126
- expect(lastExitCode).toBeUndefined();
127
- expect(stderrText).toBe('');
128
- expect(stdoutText.trim().startsWith('{')).toBe(true);
129
- expect(stdoutText.trim().endsWith('}')).toBe(true);
130
- });
131
-
132
- registry.then('该 JSON 对象可以被 JSON.parse 解析', () => {
133
- expect(() => JSON.parse(stdoutText)).not.toThrow();
134
- });
135
-
136
- registry.then('stdout 不包含任何 banner 或 heading', () => {
137
- const text = stdoutText.replace(/^\s*\{[\s\S]*\}\s*$/, '');
138
- expect(text).toBe('');
139
- });
140
-
141
- function getParsed(): Record<string, unknown> {
142
- // rc-1/rc-2: narrow from unknown via runtime guards before touching fields.
143
- const parsed: unknown = JSON.parse(stdoutText);
144
- if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) {
145
- throw new Error(`Expected JSON object in stdout but got: ${typeof parsed}`);
146
- }
147
- // runtime-contract-exempt: ERR-001 narrowed from unknown via typeof + Array.isArray check above (test-only helper on trusted stdout JSON)
148
- return parsed as Record<string, unknown>;
149
- }
150
-
151
- registry.then('该 JSON 对象的 ok 字段为 true', () => {
152
- expect(getParsed().ok).toBe(true);
153
- });
154
-
155
- registry.then('该 JSON 对象包含 injections 指标组', () => {
156
- expect(typeof getParsed().injections).toBe('object');
157
- });
158
-
159
- registry.then('该 JSON 对象包含 chars 指标组', () => {
160
- expect(typeof getParsed().chars).toBe('object');
161
- });
162
-
163
- registry.then('该 JSON 对象包含 duplicates 指标组', () => {
164
- expect(typeof getParsed().duplicates).toBe('object');
165
- });
166
-
167
- registry.then('该 JSON 对象包含 applicationCorrelation 指标组', () => {
168
- expect(typeof getParsed().applicationCorrelation).toBe('object');
169
- });
170
-
171
- registry.then('数据库未被修改', () => {
172
- const dbPath = path.join(state.ws as string, '.pd', 'state.db');
173
- expect(readFileSync(dbPath).equals(state.dbBytesBefore)).toBe(true);
174
- });
175
-
176
- registry.then('ledger 未被修改', () => {
177
- const db = new Database(path.join(state.ws as string, '.pd', 'state.db'), { readonly: true });
178
- const n = (db.prepare('SELECT COUNT(*) AS n FROM principle_applications').get() as { n: number }).n;
179
- db.close();
180
- expect(n).toBe(state.ledgerRowsBefore);
181
- });
182
-
183
- registry.then('未入队新任务', () => {
184
- // Read-only command: no queue writes anywhere. Guarded by the DB-bytes
185
- // comparison above; nothing further to assert without a tasks table.
186
- expect(state.dbBytesBefore).toBeDefined();
187
- });
188
-
189
- registry.then('未创建后继任务', () => {
190
- expect(state.dbBytesBefore).toBeDefined();
191
- });
192
-
193
- registry.then('该 JSON 对象的 status 字段为 "degraded"', () => {
194
- expect(getParsed().status).toBe('degraded');
195
- });
196
-
197
- registry.then('该 JSON 对象包含 nextAction 字段', () => {
198
- expect(typeof getParsed().nextAction).toBe('string');
199
- expect((getParsed().nextAction as string).length).toBeGreaterThan(0);
200
- });
201
-
202
- registry.then('nextAction 说明如何启用 receipt flag 或先产生注入数据', () => {
203
- const nextAction = getParsed().nextAction as string;
204
- expect(nextAction.includes('.pd/config.yaml') || nextAction.includes('Run PD')).toBe(true);
205
- });
206
-
207
- // ── Define Feature ───────────────────────────────────────────────────────────
208
-
209
- const featurePath = resolveFeaturePath('docs/specs/features/cli/principles-stats.feature');
210
- const featureText = readFileSync(featurePath, 'utf8');
211
- defineFeature(featureText, registry);