@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,851 +0,0 @@
1
- /**
2
- * pd pain record command unit tests.
3
- *
4
- * Tests the CLI adapter layer: validation, service delegation, output formatting.
5
- * PainToPrincipleService is mocked — its own contract is tested separately.
6
- */
7
- import { describe, it, expect, vi, beforeEach } from 'vitest';
8
-
9
- // ── Mock setup ──────────────────────────────────────────────────────────────
10
-
11
- let mockRecordPainResult: PainToPrincipleOutput;
12
- let lastRecordPainInput: PainToPrincipleInput | null = null;
13
-
14
- vi.mock('../../src/resolve-workspace.js', () => ({
15
- resolveWorkspaceDir: vi.fn().mockReturnValue('/tmp/fake-workspace'),
16
- }));
17
-
18
- vi.mock('fs', () => ({
19
- existsSync: vi.fn().mockReturnValue(false),
20
- readFileSync: vi.fn(),
21
- }));
22
-
23
- vi.mock('../../src/commands/build-trajectory-evidence.js', () => ({
24
- acquireTrajectoryEvidenceFromDb: vi.fn().mockReturnValue({
25
- status: 'available',
26
- entries: [
27
- { sourceRef: 'owner_message:2026-01-01T10:00:00Z', note: 'Owner correction' },
28
- { sourceRef: 'agent_turn:2026-01-01T10:01:00Z', note: 'assistant evidence' },
29
- ],
30
- }),
31
- }));
32
-
33
- vi.mock('@principles/core/runtime-v2', async (importOriginal) => {
34
- // PRI-642 review blocker 1: the CLI now evaluates ingress semantics via
35
- // the REAL core evaluatePainIngress (the shared authority) — only the
36
- // service/IO classes are mocked.
37
- const actual = await importOriginal<typeof import('@principles/core/runtime-v2')>();
38
- return {
39
- ...actual,
40
- PainToPrincipleService: vi.fn().mockImplementation(function() {
41
- return {
42
- recordPain: vi.fn(async (input: PainToPrincipleInput) => {
43
- lastRecordPainInput = input;
44
- return mockRecordPainResult;
45
- }),
46
- };
47
- }),
48
- PrincipleTreeLedgerAdapter: vi.fn().mockImplementation(function() { return {}; }),
49
- computeEffectivePdConfig: vi.fn().mockReturnValue({
50
- runtimeKind: 'pi-ai',
51
- provider: 'test-provider',
52
- model: 'test-model',
53
- apiKeyEnv: 'TEST_KEY',
54
- timeoutMs: 300000,
55
- agentId: 'main',
56
- language: 'zh-CN',
57
- warnings: [],
58
- }),
59
- resolveRuntimeConfig: vi.fn().mockReturnValue({
60
- runtimeKind: 'pi-ai',
61
- provider: 'test-provider',
62
- model: 'test-model',
63
- apiKeyEnv: 'TEST_KEY',
64
- timeoutMs: 300000,
65
- agentId: 'main',
66
- }),
67
- isRuntimeConfigError: vi.fn().mockReturnValue(false),
68
- isBuiltinPiAiProvider: vi.fn().mockReturnValue(true),
69
- resolveOutputLanguage: vi.fn().mockReturnValue({ outputLanguage: 'zh-CN' }),
70
- isFeatureEnabled: vi.fn().mockReturnValue(false),
71
- };
72
- });
73
-
74
- vi.mock('../../src/services/pd-config-loader.js', () => ({
75
- loadPdConfig: vi.fn().mockReturnValue({
76
- ok: true,
77
- effective: { config: {}, source: 'defaults', warnings: [] },
78
- source: 'defaults',
79
- configPath: '/tmp/fake-workspace/.pd/config.yaml',
80
- warnings: [],
81
- legacyFilesDetected: [],
82
- }),
83
- computeFlagsFromLoadResult: vi.fn().mockReturnValue({
84
- flags: {},
85
- enabledChannels: [],
86
- warnings: [],
87
- }),
88
- }));
89
-
90
- import { handlePainRecord } from '../../src/commands/pain-record.js';
91
- import { isBuiltinPiAiProvider, type PainToPrincipleOutput, type PainToPrincipleInput } from '@principles/core/runtime-v2';
92
- import type { FailureCategory } from '@principles/core/runtime-v2';
93
- import { acquireTrajectoryEvidenceFromDb } from '../../src/commands/build-trajectory-evidence.js';
94
-
95
- // ── Helpers ─────────────────────────────────────────────────────────────────
96
-
97
- function mockProcessExit() {
98
- return vi.spyOn(process, 'exit').mockImplementation((() => undefined) as () => never);
99
- }
100
-
101
- const SUCCEEDED_RESULT: PainToPrincipleOutput = {
102
- status: 'succeeded',
103
- painId: 'manual_123_abc',
104
- taskId: 'diagnosis_manual_123_abc',
105
- runId: 'run-001',
106
- artifactId: 'art-001',
107
- candidateIds: ['c1'],
108
- ledgerEntryIds: ['l1'],
109
- observabilityWarnings: [],
110
- latencyMs: 42,
111
- };
112
-
113
- function makeFailedResult(overrides?: Partial<PainToPrincipleOutput>): PainToPrincipleOutput {
114
- return {
115
- status: 'failed',
116
- painId: 'manual_123_abc',
117
- taskId: 'diagnosis_manual_123_abc',
118
- candidateIds: [],
119
- ledgerEntryIds: [],
120
- message: 'something went wrong',
121
- observabilityWarnings: [],
122
- failureCategory: 'runtime_unavailable' as FailureCategory,
123
- latencyMs: 10,
124
- ...overrides,
125
- };
126
- }
127
-
128
- function makeSkippedResult(overrides?: Partial<PainToPrincipleOutput>): PainToPrincipleOutput {
129
- return {
130
- status: 'skipped',
131
- painId: 'manual_123_abc',
132
- taskId: 'diagnosis_manual_123_abc',
133
- candidateIds: [],
134
- ledgerEntryIds: [],
135
- message: 'already leased',
136
- observabilityWarnings: [],
137
- latencyMs: 5,
138
- ...overrides,
139
- };
140
- }
141
-
142
- // ── Tests ───────────────────────────────────────────────────────────────────
143
-
144
- describe('pd pain record', () => {
145
- beforeEach(() => {
146
- vi.clearAllMocks();
147
- mockRecordPainResult = { ...SUCCEEDED_RESULT };
148
- lastRecordPainInput = null;
149
- });
150
-
151
- // 1. --reason required
152
- it('exits 1 when --reason is missing', async () => {
153
- const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
154
- const exitSpy = mockProcessExit();
155
-
156
- await handlePainRecord({ reason: undefined });
157
-
158
- expect(errorSpy).toHaveBeenCalledWith(expect.stringContaining('--reason'));
159
- expect(exitSpy).toHaveBeenCalledWith(1);
160
-
161
- errorSpy.mockRestore();
162
- exitSpy.mockRestore();
163
- });
164
-
165
- // 2. --score out of range
166
- it('exits 1 when --score is out of range', async () => {
167
- const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
168
- const exitSpy = mockProcessExit();
169
-
170
- await handlePainRecord({ reason: 'test', score: 150 });
171
-
172
- expect(errorSpy).toHaveBeenCalledWith(expect.stringContaining('--score'));
173
- expect(exitSpy).toHaveBeenCalledWith(1);
174
-
175
- errorSpy.mockRestore();
176
- exitSpy.mockRestore();
177
- });
178
-
179
- // 3. Happy path --json output
180
- it('outputs JSON with all fields on success (--json)', async () => {
181
- const logSpy = vi.spyOn(console, 'log').mockImplementation(() => {});
182
- const exitSpy = mockProcessExit();
183
-
184
- await handlePainRecord({ reason: 'test pain', json: true });
185
-
186
- expect(logSpy).toHaveBeenCalled();
187
- const jsonOutput = JSON.parse(logSpy.mock.calls[0][0]);
188
- expect(jsonOutput.status).toBe('succeeded');
189
- expect(jsonOutput.painId).toBe('manual_123_abc');
190
- expect(jsonOutput.taskId).toBe('diagnosis_manual_123_abc');
191
- expect(jsonOutput.runId).toBe('run-001');
192
- expect(jsonOutput.artifactId).toBe('art-001');
193
- expect(jsonOutput.candidateIds).toEqual(['c1']);
194
- expect(jsonOutput.ledgerEntryIds).toEqual(['l1']);
195
- expect(jsonOutput.observabilityWarnings).toEqual([]);
196
- expect(jsonOutput.latencyMs).toBe(42);
197
- expect(exitSpy).not.toHaveBeenCalledWith(1);
198
-
199
- logSpy.mockRestore();
200
- exitSpy.mockRestore();
201
- });
202
-
203
- // 4. Happy path text output
204
- it('outputs human-readable summary on success (text)', async () => {
205
- const logSpy = vi.spyOn(console, 'log').mockImplementation(() => {});
206
- const exitSpy = mockProcessExit();
207
-
208
- await handlePainRecord({ reason: 'test pain' });
209
-
210
- expect(logSpy).toHaveBeenCalledWith(expect.stringContaining('[OK]'));
211
- expect(logSpy).toHaveBeenCalledWith(expect.stringContaining('manual_123_abc'));
212
- expect(exitSpy).not.toHaveBeenCalledWith(1);
213
-
214
- logSpy.mockRestore();
215
- exitSpy.mockRestore();
216
- });
217
-
218
- // 5. Failed exits 1 with --json
219
- it('exits 1 on failed status (--json)', async () => {
220
- mockRecordPainResult = makeFailedResult();
221
- const logSpy = vi.spyOn(console, 'log').mockImplementation(() => {});
222
- const exitSpy = mockProcessExit();
223
-
224
- await handlePainRecord({ reason: 'test pain', json: true });
225
-
226
- const jsonOutput = JSON.parse(logSpy.mock.calls[0][0]);
227
- expect(jsonOutput.status).toBe('failed');
228
- expect(exitSpy).toHaveBeenCalledWith(1);
229
-
230
- logSpy.mockRestore();
231
- exitSpy.mockRestore();
232
- });
233
-
234
- // 6. Failed exits 1 (text)
235
- it('exits 1 on failed status (text)', async () => {
236
- mockRecordPainResult = makeFailedResult();
237
- const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
238
- const exitSpy = mockProcessExit();
239
-
240
- await handlePainRecord({ reason: 'test pain' });
241
-
242
- const firstErrorArg = errorSpy.mock.calls[0]?.[0] ?? '';
243
- expect(firstErrorArg).toContain('[FAIL]');
244
- expect(exitSpy).toHaveBeenCalledWith(1);
245
-
246
- errorSpy.mockRestore();
247
- exitSpy.mockRestore();
248
- });
249
-
250
- // 7. config_missing shows diagnostic guidance
251
- it('shows diagnostic guidance on config_missing failure', async () => {
252
- mockRecordPainResult = makeFailedResult({
253
- failureCategory: 'config_missing' as FailureCategory,
254
- message: 'API key not found in env',
255
- });
256
- const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
257
- const exitSpy = mockProcessExit();
258
-
259
- await handlePainRecord({ reason: 'test pain' });
260
-
261
- const allErrorOutput = errorSpy.mock.calls.map(c => c.join(' ')).join('\n');
262
- expect(allErrorOutput).toContain('Error: Pain signal failed');
263
- expect(exitSpy).toHaveBeenCalledWith(1);
264
-
265
- errorSpy.mockRestore();
266
- exitSpy.mockRestore();
267
- });
268
-
269
- // 7a. config_missing with RuntimeConfigError exits non-zero (text)
270
- it('exits 1 on config_missing with RuntimeConfigError (text)', async () => {
271
- mockRecordPainResult = makeFailedResult({
272
- failureCategory: 'config_missing' as FailureCategory,
273
- message: 'API key not found in env',
274
- });
275
- const { isRuntimeConfigError, resolveRuntimeConfig } = await import('@principles/core/runtime-v2');
276
- vi.mocked(isRuntimeConfigError).mockReturnValueOnce(true);
277
- vi.mocked(resolveRuntimeConfig).mockReturnValueOnce({
278
- ok: false,
279
- reason: 'missing_openclaw_mode',
280
- message: 'runtimeKind is openclaw-cli but no mode specified',
281
- nextAction: 'Provide exactly one mode',
282
- });
283
- const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
284
- const exitSpy = mockProcessExit();
285
-
286
- await handlePainRecord({ reason: 'test pain' });
287
-
288
- expect(exitSpy).toHaveBeenCalledWith(1);
289
-
290
- errorSpy.mockRestore();
291
- exitSpy.mockRestore();
292
- });
293
-
294
- // 7b. config_missing with RuntimeConfigError outputs JSON (--json)
295
- it('outputs JSON with configError on config_missing + RuntimeConfigError (--json)', async () => {
296
- mockRecordPainResult = makeFailedResult({
297
- failureCategory: 'config_missing' as FailureCategory,
298
- message: 'API key not found in env',
299
- });
300
- const { isRuntimeConfigError, resolveRuntimeConfig } = await import('@principles/core/runtime-v2');
301
- vi.mocked(isRuntimeConfigError).mockReturnValueOnce(true);
302
- vi.mocked(resolveRuntimeConfig).mockReturnValueOnce({
303
- ok: false,
304
- reason: 'missing_openclaw_mode',
305
- message: 'runtimeKind is openclaw-cli but no mode specified',
306
- nextAction: 'Provide exactly one mode',
307
- });
308
- const logSpy = vi.spyOn(console, 'log').mockImplementation(() => {});
309
- const exitSpy = mockProcessExit();
310
-
311
- await handlePainRecord({ reason: 'test pain', json: true });
312
-
313
- const jsonOutput = JSON.parse(logSpy.mock.calls[0][0]);
314
- expect(jsonOutput.status).toBe('failed');
315
- expect(jsonOutput.failureCategory).toBe('config_missing');
316
- expect(jsonOutput.configError).toBeDefined();
317
- expect(jsonOutput.configError.reason).toBe('missing_openclaw_mode');
318
- expect(jsonOutput.configError.nextAction).toBe('Provide exactly one mode');
319
- expect(exitSpy).toHaveBeenCalledWith(1);
320
-
321
- logSpy.mockRestore();
322
- exitSpy.mockRestore();
323
- });
324
-
325
- // 8. skipped status outputs [SKIP] and does not exit 1
326
- it('outputs [SKIP] on skipped status (text)', async () => {
327
- mockRecordPainResult = makeSkippedResult();
328
- const logSpy = vi.spyOn(console, 'log').mockImplementation(() => {});
329
- const exitSpy = mockProcessExit();
330
-
331
- await handlePainRecord({ reason: 'test pain' });
332
-
333
- const allOutput = logSpy.mock.calls.map(c => c.join(' ')).join(' ');
334
- expect(allOutput).toContain('[SKIP]');
335
- expect(exitSpy).not.toHaveBeenCalledWith(1);
336
-
337
- logSpy.mockRestore();
338
- exitSpy.mockRestore();
339
- });
340
-
341
- // 9. skipped status with --json does not exit 1
342
- it('outputs skipped status in JSON without exit 1', async () => {
343
- mockRecordPainResult = makeSkippedResult();
344
- const logSpy = vi.spyOn(console, 'log').mockImplementation(() => {});
345
- const exitSpy = mockProcessExit();
346
-
347
- await handlePainRecord({ reason: 'test pain', json: true });
348
-
349
- const jsonOutput = JSON.parse(logSpy.mock.calls[0][0]);
350
- expect(jsonOutput.status).toBe('skipped');
351
- expect(exitSpy).not.toHaveBeenCalledWith(1);
352
-
353
- logSpy.mockRestore();
354
- exitSpy.mockRestore();
355
- });
356
-
357
- // 10. recordPain called with correct arguments
358
- it('passes correct arguments to recordPain', async () => {
359
- await handlePainRecord({ reason: 'test pain', score: 90, source: 'ci' });
360
-
361
- expect(lastRecordPainInput).toBeTruthy();
362
- expect(lastRecordPainInput!.painType).toBe('user_frustration');
363
- expect(lastRecordPainInput!.source).toBe('ci');
364
- expect(lastRecordPainInput!.reason).toBe('test pain');
365
- expect(lastRecordPainInput!.score).toBe(90);
366
- // PRI-642: no --session means an explicit unbound Owner report — the
367
- // 'cli' sentinel session must NOT be fabricated (SPEC §7.4).
368
- expect(lastRecordPainInput!.sessionId).toBeUndefined();
369
- expect(lastRecordPainInput!.agentId).toBe('pd-cli');
370
- // …and no placeholder evidence entry may be submitted.
371
- expect(lastRecordPainInput!.evidence).toEqual([]);
372
- expect(lastRecordPainInput!.recordObservability).toBe(false);
373
- expect(lastRecordPainInput!.provenance).toBe('owner_reported_no_host_trace');
374
- });
375
-
376
- // ── PRI-341 → PRI-642: evidence passthrough and --session flag ─────────────
377
-
378
- // 用例 C: recordPain receives bound provenance + validated evidence when a real session is provided
379
- it('C: passes bound provenance and evidence to recordPain when --session resolves available', async () => {
380
- const logSpy = vi.spyOn(console, 'log').mockImplementation(() => {});
381
- const exitSpy = mockProcessExit();
382
-
383
- await handlePainRecord({ reason: 'test pain', session: 'sess-123', json: true });
384
-
385
- expect(lastRecordPainInput).toBeTruthy();
386
- expect(acquireTrajectoryEvidenceFromDb).toHaveBeenCalled();
387
- expect(lastRecordPainInput!.evidence).toBeTruthy();
388
- expect(lastRecordPainInput!.evidence!.length).toBeGreaterThan(0);
389
- expect(lastRecordPainInput!.evidence![0].sourceRef).not.toBe('owner_reported:cli');
390
- expect(lastRecordPainInput!.sessionId).toBe('sess-123');
391
- // SPEC §7.3: provenance must be derived from the validated result —
392
- // a real session is host-context-bound, never owner_reported_no_host_trace.
393
- expect(lastRecordPainInput!.provenance).toBe('host_context_bound');
394
- // PRI-640/SPEC §8.3: the bound path attributes the OpenClaw trajectory.
395
- expect(lastRecordPainInput!.hostKind).toBe('openclaw');
396
- expect(lastRecordPainInput!.recordObservability).toBe(true);
397
-
398
- logSpy.mockRestore();
399
- exitSpy.mockRestore();
400
- });
401
-
402
- // ── PRI-743: explicit --host attribution ──────────────────────────────────
403
-
404
- it('PRI-743: --host openclaw records without the default-assumption disclosure', async () => {
405
- const logSpy = vi.spyOn(console, 'log').mockImplementation(() => {});
406
- const exitSpy = mockProcessExit();
407
-
408
- await handlePainRecord({ reason: 'explicit openclaw', session: 'sess-oc', host: 'openclaw', json: true });
409
-
410
- expect(lastRecordPainInput).toBeTruthy();
411
- expect(lastRecordPainInput!.sessionId).toBe('sess-oc');
412
- expect(lastRecordPainInput!.hostKind).toBe('openclaw');
413
- expect(lastRecordPainInput!.provenance).toBe('host_context_bound');
414
-
415
- const jsonOutput = JSON.parse(logSpy.mock.calls[0][0]) as { hostAttribution?: string; warnings?: string[] };
416
- expect(jsonOutput.hostAttribution).toBe('openclaw');
417
- expect((jsonOutput.warnings ?? []).some((w) => w.includes('host kind not specified, defaulting to openclaw'))).toBe(false);
418
-
419
- logSpy.mockRestore();
420
- exitSpy.mockRestore();
421
- });
422
-
423
- it('PRI-743: --host codex records host_kind=codex with the caller-supplied Codex lineage', async () => {
424
- const logSpy = vi.spyOn(console, 'log').mockImplementation(() => {});
425
- const exitSpy = mockProcessExit();
426
-
427
- await handlePainRecord({
428
- reason: 'codex mistake',
429
- session: 'codex-root-sess',
430
- host: 'codex',
431
- rolloutId: 'rollout-abc',
432
- hostTurnId: 'turn-7',
433
- json: true,
434
- });
435
-
436
- expect(lastRecordPainInput).toBeTruthy();
437
- expect(lastRecordPainInput!.hostKind).toBe('codex');
438
- expect(lastRecordPainInput!.sessionId).toBe('codex-root-sess');
439
- expect(lastRecordPainInput!.provenance).toBe('host_context_bound');
440
- expect(lastRecordPainInput!.recordObservability).toBe(true);
441
- // The CLI must NOT read the OpenClaw trajectory for a Codex attribution.
442
- expect(acquireTrajectoryEvidenceFromDb).not.toHaveBeenCalled();
443
- // Codex lineage is retained unflattened in the versioned payload (SPEC §8.1);
444
- // the derived key mirrors the ingestion rule (codex|<rollout>|<turn>|user).
445
- expect(lastRecordPainInput!.painIngress.correlation).toEqual({
446
- status: 'bound',
447
- hostKind: 'codex',
448
- rootSessionId: 'codex-root-sess',
449
- rolloutIdentity: 'rollout-abc',
450
- logicalObservationKey: 'codex|rollout-abc|turn-7|user',
451
- hostTurnId: 'turn-7',
452
- });
453
- // The degraded-but-honest path still submits (no fabricated evidence).
454
- expect(lastRecordPainInput!.evidence).toEqual([]);
455
- expect(exitSpy).not.toHaveBeenCalledWith(1);
456
-
457
- logSpy.mockRestore();
458
- exitSpy.mockRestore();
459
- });
460
-
461
- it('PRI-743: --host codex without the Codex lineage fails loudly before any mutation', async () => {
462
- const logSpy = vi.spyOn(console, 'log').mockImplementation(() => {});
463
- const exitSpy = mockProcessExit();
464
-
465
- await handlePainRecord({ reason: 'codex mistake', host: 'codex', json: true });
466
-
467
- // cli-1: exactly one JSON object on stdout
468
- expect(logSpy).toHaveBeenCalledTimes(1);
469
- const jsonOutput = JSON.parse(logSpy.mock.calls[0][0]) as { status: string; reason: string; nextAction: string; message: string };
470
- expect(jsonOutput).toMatchObject({ status: 'failed', reason: 'codex_lineage_required' });
471
- expect(jsonOutput.message).toContain('--rollout-id');
472
- expect(jsonOutput.nextAction).toContain('--host-turn-id');
473
- // cli-2/cli-5: stopped before any evidence acquisition or service mutation
474
- expect(lastRecordPainInput).toBeNull();
475
- expect(acquireTrajectoryEvidenceFromDb).not.toHaveBeenCalled();
476
- expect(exitSpy).toHaveBeenCalledWith(1);
477
-
478
- logSpy.mockRestore();
479
- exitSpy.mockRestore();
480
- });
481
-
482
- it('PRI-743: --host codex with PARTIAL lineage still fails loudly (only the missing flag is reported)', async () => {
483
- const logSpy = vi.spyOn(console, 'log').mockImplementation(() => {});
484
- const exitSpy = mockProcessExit();
485
-
486
- await handlePainRecord({ reason: 'codex mistake', session: 'codex-root', host: 'codex', rolloutId: 'rollout-abc', json: true });
487
-
488
- const jsonOutput = JSON.parse(logSpy.mock.calls[0][0]) as { status: string; reason: string; message: string };
489
- expect(jsonOutput).toMatchObject({ status: 'failed', reason: 'codex_lineage_required' });
490
- expect(jsonOutput.message).toContain('--host-turn-id');
491
- expect(jsonOutput.message).not.toContain('--rollout-id');
492
- expect(lastRecordPainInput).toBeNull();
493
- expect(exitSpy).toHaveBeenCalledWith(1);
494
-
495
- logSpy.mockRestore();
496
- exitSpy.mockRestore();
497
- });
498
-
499
- // Task test #3/#4: legacy call compatibility — the pre-PRI-743 invocation
500
- // (`--reason … --session …`, no --host) keeps host_kind=openclaw and only
501
- // gains the disclosure wording.
502
- it('PRI-743: legacy call omitting --host keeps the openclaw default but discloses it (rc-9)', async () => {
503
- const logSpy = vi.spyOn(console, 'log').mockImplementation(() => {});
504
- const exitSpy = mockProcessExit();
505
-
506
- await handlePainRecord({ reason: 'legacy path', session: 'sess-123', json: true });
507
-
508
- expect(lastRecordPainInput).toBeTruthy();
509
- expect(lastRecordPainInput!.hostKind).toBe('openclaw');
510
- const jsonOutput = JSON.parse(logSpy.mock.calls[0][0]) as { hostAttribution?: string; warnings?: string[] };
511
- expect(jsonOutput.hostAttribution).toBe('openclaw');
512
- expect((jsonOutput.warnings ?? []).some((w) => w.includes('host kind not specified, defaulting to openclaw') && w.includes('--host codex'))).toBe(true);
513
-
514
- logSpy.mockRestore();
515
- exitSpy.mockRestore();
516
- });
517
-
518
- it('PRI-743: an invalid --host value fails loudly before any mutation (cli-5/cli-6)', async () => {
519
- const logSpy = vi.spyOn(console, 'log').mockImplementation(() => {});
520
- const exitSpy = mockProcessExit();
521
-
522
- await handlePainRecord({ reason: 'typo host', session: 'sess-123', host: 'claude', json: true });
523
-
524
- // cli-1: exactly one JSON object on stdout
525
- expect(logSpy).toHaveBeenCalledTimes(1);
526
- const jsonOutput = JSON.parse(logSpy.mock.calls[0][0]) as { status: string; reason: string; nextAction: string };
527
- expect(jsonOutput).toMatchObject({ status: 'failed', reason: 'invalid_host_kind' });
528
- expect(jsonOutput.nextAction).toContain('--host codex');
529
- // cli-2/cli-5: execution stopped before any evidence acquisition or service mutation
530
- expect(lastRecordPainInput).toBeNull();
531
- expect(acquireTrajectoryEvidenceFromDb).not.toHaveBeenCalled();
532
- expect(exitSpy).toHaveBeenCalledWith(1);
533
-
534
- logSpy.mockRestore();
535
- exitSpy.mockRestore();
536
- });
537
-
538
- // 用例 C2 (PRI-642 rewrite): without session, no sentinel session, no
539
- // placeholder evidence — an honest unbound Owner report (SPEC §7.4).
540
- it('C2: submits an honest unbound report when no --session provided', async () => {
541
- const logSpy = vi.spyOn(console, 'log').mockImplementation(() => {});
542
- const exitSpy = mockProcessExit();
543
-
544
- await handlePainRecord({ reason: 'test pain', json: true });
545
-
546
- expect(lastRecordPainInput).toBeTruthy();
547
- expect(lastRecordPainInput!.sessionId).toBeUndefined();
548
- expect(lastRecordPainInput!.evidence).toEqual([]);
549
- expect(lastRecordPainInput!.recordObservability).toBe(false);
550
- expect(lastRecordPainInput!.provenance).toBe('owner_reported_no_host_trace');
551
-
552
- const jsonOutput = JSON.parse(logSpy.mock.calls[0][0]);
553
- // SPEC §7.4: disclose context_unbound and recommend --session.
554
- const warnings = JSON.stringify(jsonOutput);
555
- expect(warnings).toMatch(/context_unbound/);
556
- expect(warnings).toMatch(/--session/);
557
-
558
- logSpy.mockRestore();
559
- exitSpy.mockRestore();
560
- });
561
-
562
- // ── PRI-642 Scope A: explicit-session validation (SPEC §7.3, §12.1.3–12.1.4) ─
563
-
564
- it('fails with session_not_found before any task/candidate mutation when --session does not exist', async () => {
565
- vi.mocked(acquireTrajectoryEvidenceFromDb).mockReturnValueOnce({
566
- status: 'unavailable',
567
- reasonCode: 'session_not_found',
568
- detail: 'session not present in trajectory.db sessions table',
569
- binding: 'unverified',
570
- } as any);
571
- const logSpy = vi.spyOn(console, 'log').mockImplementation(() => {});
572
- const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
573
- const exitSpy = mockProcessExit();
574
-
575
- await handlePainRecord({ reason: 'test pain', session: 'missing-session', json: true });
576
-
577
- // cli-1: exactly one JSON object on stdout
578
- expect(logSpy).toHaveBeenCalledTimes(1);
579
- const jsonOutput = JSON.parse(logSpy.mock.calls[0][0]);
580
- expect(jsonOutput.status).toBe('failed');
581
- expect(jsonOutput.reason).toBe('session_not_found');
582
- expect(jsonOutput.nextAction).toBeTruthy();
583
- // PRI-783: the next action must not recommend retrying the exact path
584
- // that just failed (`pd pain record --session`).
585
- expect(jsonOutput.nextAction).not.toMatch(/pd pain record --session/);
586
- // cli-2/cli-5: execution stopped — no service mutation, exit 1
587
- expect(lastRecordPainInput).toBeNull();
588
- expect(exitSpy).toHaveBeenCalledWith(1);
589
-
590
- logSpy.mockRestore();
591
- errorSpy.mockRestore();
592
- exitSpy.mockRestore();
593
- });
594
-
595
- it('fails before any mutation on session_not_found even when process.exit is stubbed to a no-op', async () => {
596
- vi.mocked(acquireTrajectoryEvidenceFromDb).mockReturnValueOnce({
597
- status: 'unavailable',
598
- reasonCode: 'session_not_found',
599
- detail: 'session not present',
600
- binding: 'unverified',
601
- } as any);
602
- const logSpy = vi.spyOn(console, 'log').mockImplementation(() => {});
603
- const exitSpy = mockProcessExit();
604
-
605
- await handlePainRecord({ reason: 'test pain', session: 'missing-session', json: true });
606
-
607
- // cli-2: with process.exit stubbed, control flow must still stop —
608
- // recordPain was never invoked and stdout carries exactly one object.
609
- expect(lastRecordPainInput).toBeNull();
610
- expect(logSpy).toHaveBeenCalledTimes(1);
611
- logSpy.mockRestore();
612
- exitSpy.mockRestore();
613
- });
614
-
615
- it('degrades to a bound, honest empty-evidence submission on empty_trajectory (PRI-783: a verified session must not be refused)', async () => {
616
- // SPEC §8.2: binding failure and evidence failure are separate axes — a
617
- // real session with no usable evidence rows is bound + unavailable
618
- // (row 4, degrade), not unbound (row 5, refuse). PRI-783 Owner
619
- // directive: a correct current session id is sufficient; empty evidence
620
- // must not hard-refuse the report.
621
- vi.mocked(acquireTrajectoryEvidenceFromDb).mockReturnValueOnce({
622
- status: 'unavailable',
623
- reasonCode: 'empty_trajectory',
624
- detail: 'session exists but no usable evidence',
625
- binding: 'verified',
626
- } as any);
627
- const logSpy = vi.spyOn(console, 'log').mockImplementation(() => {});
628
- const exitSpy = mockProcessExit();
629
-
630
- await handlePainRecord({ reason: 'test pain', session: 'quiet-session', json: true });
631
-
632
- // Bound correlation with honest empty evidence — nothing fabricated.
633
- expect(lastRecordPainInput).not.toBeNull();
634
- expect(lastRecordPainInput!.sessionId).toBe('quiet-session');
635
- expect(lastRecordPainInput!.hostKind).toBe('openclaw');
636
- expect(lastRecordPainInput!.evidence).toEqual([]);
637
- expect(lastRecordPainInput!.painIngress.correlation.status).toBe('bound');
638
- expect(lastRecordPainInput!.painIngress.evidenceClass).toEqual({
639
- status: 'unavailable',
640
- reason: 'empty_trajectory',
641
- });
642
- // Degradation is disclosed, and the report is NOT refused.
643
- const jsonOutput = JSON.parse(logSpy.mock.calls[0][0]);
644
- expect(jsonOutput.status).toBe('succeeded');
645
- expect(String(jsonOutput.warning ?? '')).toMatch(/empty_trajectory/);
646
- expect(exitSpy).not.toHaveBeenCalledWith(1);
647
-
648
- logSpy.mockRestore();
649
- exitSpy.mockRestore();
650
- });
651
-
652
- it('degrades on evidence_read_failed when the binding was verified (tables unreadable after the sessions check)', async () => {
653
- // SPEC §8.2 note: a real session with an unreadable trajectory is
654
- // bound + unavailable — the sessions row was found, only the evidence
655
- // read failed.
656
- vi.mocked(acquireTrajectoryEvidenceFromDb).mockReturnValueOnce({
657
- status: 'unavailable',
658
- reasonCode: 'evidence_read_failed',
659
- detail: 'trajectory_tables_unreadable',
660
- binding: 'verified',
661
- } as any);
662
- const logSpy = vi.spyOn(console, 'log').mockImplementation(() => {});
663
- const exitSpy = mockProcessExit();
664
-
665
- await handlePainRecord({ reason: 'test pain', session: 'sess-x', json: true });
666
-
667
- expect(lastRecordPainInput).not.toBeNull();
668
- expect(lastRecordPainInput!.sessionId).toBe('sess-x');
669
- expect(lastRecordPainInput!.evidence).toEqual([]);
670
- expect(lastRecordPainInput!.painIngress.correlation.status).toBe('bound');
671
- expect(lastRecordPainInput!.painIngress.evidenceClass).toEqual({
672
- status: 'unavailable',
673
- reason: 'evidence_read_failed',
674
- });
675
- const jsonOutput = JSON.parse(logSpy.mock.calls[0][0]);
676
- expect(jsonOutput.status).toBe('succeeded');
677
- expect(String(jsonOutput.warning ?? '')).toMatch(/evidence_read_failed/);
678
- expect(exitSpy).not.toHaveBeenCalledWith(1);
679
-
680
- logSpy.mockRestore();
681
- exitSpy.mockRestore();
682
- });
683
-
684
- it.each([
685
- ['trajectory_unavailable', 'no trajectory.db at workspace .state'],
686
- ['evidence_read_failed', 'trajectory_db_unreadable: file is not a database'],
687
- ] as const)('refuses %s when the binding is UNVERIFIED (PRI-783 review P1: no verified session, no bound claim)', async (reasonCode, detail) => {
688
- // PRI-783 review P1: when trajectory.db is missing or unopenable the id
689
- // could not be verified. Claiming bound here would let the observability
690
- // writer persist the unverified id into a freshly created trajectory.db —
691
- // a self-proving loop. It must refuse instead.
692
- vi.mocked(acquireTrajectoryEvidenceFromDb).mockReturnValueOnce({
693
- status: 'unavailable',
694
- reasonCode,
695
- detail,
696
- binding: 'unverified',
697
- } as any);
698
- const logSpy = vi.spyOn(console, 'log').mockImplementation(() => {});
699
- const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
700
- const exitSpy = mockProcessExit();
701
-
702
- await handlePainRecord({ reason: 'test pain', session: 'sess-x', json: true });
703
-
704
- // Refused before any mutation, with honest next guidance.
705
- expect(lastRecordPainInput).toBeNull();
706
- const jsonOutput = JSON.parse(logSpy.mock.calls[0][0]);
707
- expect(jsonOutput.status).toBe('failed');
708
- expect(jsonOutput.reason).toBe(reasonCode);
709
- expect(jsonOutput.nextAction).not.toMatch(/pd pain record --session/);
710
- expect(exitSpy).toHaveBeenCalledWith(1);
711
-
712
- logSpy.mockRestore();
713
- errorSpy.mockRestore();
714
- exitSpy.mockRestore();
715
- });
716
-
717
- // ── PRI-642 Scope A (SPEC §12.1.6): generated-but-unadmitted candidates must
718
- // not be reported as completed internalization. ─────────────────────────────
719
-
720
- it('warns that no candidate was admitted/internalized when all candidates are gated', async () => {
721
- mockRecordPainResult = {
722
- ...SUCCEEDED_RESULT,
723
- candidateIds: ['c1', 'c2', 'c3', 'c4'],
724
- ledgerEntryIds: [],
725
- admissionResults: [
726
- { candidateId: 'c1', recommendationKind: 'prompt', admission: { decision: 'needs_evidence', reason: 'confidence_below_threshold:0.45<0.50', nextAction: 'add evidence', evidenceStatus: 'host_context_bound' } },
727
- { candidateId: 'c2', recommendationKind: 'prompt', admission: { decision: 'deferred', reason: 'recommendation_kind_defer_not_actionable', nextAction: 'none', evidenceStatus: 'host_context_bound' } },
728
- { candidateId: 'c3', recommendationKind: 'prompt', admission: { decision: 'needs_evidence', reason: 'input_evidence_empty', nextAction: 'add evidence', evidenceStatus: 'host_context_bound' } },
729
- { candidateId: 'c4', recommendationKind: 'prompt', admission: { decision: 'needs_evidence', reason: 'confidence_below_threshold:0.45<0.50', nextAction: 'add evidence', evidenceStatus: 'host_context_bound' } },
730
- ],
731
- } as PainToPrincipleOutput;
732
- const logSpy = vi.spyOn(console, 'log').mockImplementation(() => {});
733
- const exitSpy = mockProcessExit();
734
-
735
- await handlePainRecord({ reason: 'test pain', json: true });
736
-
737
- const allOutput = logSpy.mock.calls.map(c => c.join(' ')).join(' ');
738
- // Explicit admission summary; must not read as completed internalization.
739
- expect(allOutput).toMatch(/0 (?:of|\/) 4|admitted.*0|0.*admitted/i);
740
- const jsonOutput = JSON.parse(logSpy.mock.calls.at(-1)![0] ?? '{}');
741
- const jsonStr = JSON.stringify(jsonOutput);
742
- expect(jsonStr).toMatch(/no candidate was admitted|admitted:\s*0/i);
743
-
744
- logSpy.mockRestore();
745
- exitSpy.mockRestore();
746
- });
747
-
748
- // ── Bug-P fix: reason length validation ──────────────────────────────────
749
-
750
- // RL-01: reason length within limit processes normally
751
- it('RL-01: accepts reason with length ≤ 500 (boundary)', async () => {
752
- const logSpy = vi.spyOn(console, 'log').mockImplementation(() => {});
753
- const exitSpy = mockProcessExit();
754
-
755
- const reason500 = 'a'.repeat(500);
756
- await handlePainRecord({ reason: reason500, json: true });
757
-
758
- expect(exitSpy).not.toHaveBeenCalledWith(1);
759
- expect(logSpy).toHaveBeenCalled();
760
-
761
- logSpy.mockRestore();
762
- exitSpy.mockRestore();
763
- });
764
-
765
- // RL-02: reason length over limit exits 1 with error message
766
- it('RL-02: exits 1 when reason length > 500', async () => {
767
- const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
768
- const exitSpy = mockProcessExit();
769
-
770
- const reason501 = 'a'.repeat(501);
771
- await handlePainRecord({ reason: reason501 });
772
-
773
- expect(errorSpy).toHaveBeenCalledWith(expect.stringContaining('must be at most 500 characters'));
774
- expect(errorSpy).toHaveBeenCalledWith(expect.stringContaining('got 501'));
775
- expect(errorSpy).toHaveBeenCalledWith(expect.stringContaining('Next action'));
776
- expect(exitSpy).toHaveBeenCalledWith(1);
777
-
778
- errorSpy.mockRestore();
779
- exitSpy.mockRestore();
780
- });
781
-
782
- // RL-03: short reason processes normally (smoke test)
783
- it('RL-03: accepts short reason without error', async () => {
784
- const logSpy = vi.spyOn(console, 'log').mockImplementation(() => {});
785
- const exitSpy = mockProcessExit();
786
-
787
- await handlePainRecord({ reason: 'short reason', json: true });
788
-
789
- expect(exitSpy).not.toHaveBeenCalledWith(1);
790
- expect(logSpy).toHaveBeenCalled();
791
-
792
- logSpy.mockRestore();
793
- exitSpy.mockRestore();
794
- });
795
-
796
- // RL-04: CodeRabbit review fix — --json mode emits structured JSON (cli-1, cli-2, cli-5)
797
- it('RL-04: --json mode emits structured JSON on reason_too_long and stops execution', async () => {
798
- const logSpy = vi.spyOn(console, 'log').mockImplementation(() => {});
799
- const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
800
- const exitSpy = mockProcessExit();
801
-
802
- const reason501 = 'a'.repeat(501);
803
- await handlePainRecord({ reason: reason501, json: true });
804
-
805
- // cli-1: exactly one JSON object on stdout
806
- expect(logSpy).toHaveBeenCalledTimes(1);
807
- const jsonOutput = JSON.parse(logSpy.mock.calls[0][0]);
808
- expect(jsonOutput.status).toBe('failed');
809
- expect(jsonOutput.reason).toBe('reason_too_long');
810
- expect(jsonOutput.message).toContain('must be at most 500 characters');
811
- expect(jsonOutput.message).toContain('got 501');
812
- expect(jsonOutput.nextAction).toContain('Shorten the reason text');
813
-
814
- // cli-2: execution stopped — recordPain must NOT have been called
815
- expect(lastRecordPainInput).toBeNull();
816
-
817
- // cli-5: failure path exits 1
818
- expect(exitSpy).toHaveBeenCalledWith(1);
819
-
820
- // No text leaked to stderr
821
- expect(errorSpy).not.toHaveBeenCalled();
822
-
823
- logSpy.mockRestore();
824
- errorSpy.mockRestore();
825
- exitSpy.mockRestore();
826
- });
827
-
828
- // 9. PRI-621 PR2: the provider catalog is queried through @principles/core.
829
- // A provider outside the builtin pi-ai catalog without baseUrl is reported
830
- // as missing configuration — it must not be silently accepted.
831
- it('reports baseUrl as missing configuration for a non-builtin provider', async () => {
832
- mockRecordPainResult = makeFailedResult({
833
- failureCategory: 'config_missing' as FailureCategory,
834
- message: 'provider not in builtin catalog',
835
- });
836
- vi.mocked(isBuiltinPiAiProvider).mockReturnValue(false);
837
- const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
838
- const exitSpy = mockProcessExit();
839
-
840
- await handlePainRecord({ reason: 'test pain' });
841
-
842
- const printed = errorSpy.mock.calls.map((c) => String(c[0])).join('\n');
843
- expect(printed).toContain('Missing configuration:');
844
- expect(printed).toContain('- baseUrl');
845
- expect(exitSpy).toHaveBeenCalledWith(1);
846
-
847
- vi.mocked(isBuiltinPiAiProvider).mockReturnValue(true);
848
- errorSpy.mockRestore();
849
- exitSpy.mockRestore();
850
- });
851
- });