@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,706 +0,0 @@
1
- /**
2
- * PRI-708 — run-once rollout revision routing: cross entry point equivalence.
3
- *
4
- * Owner acceptance (P0 A/B/C): the SAME durable state must produce the SAME
5
- * governance decision whether it travels the production consumer-cycle
6
- * assembly or the run-once CLI entry. Only the LLM boundary is scripted
7
- * (PRI-661 parity-test pattern) — the evaluator stage, the rollout reviewer
8
- * runner, validators, stores and the reopen path are all REAL code against
9
- * REAL SQLite. No runner.run() mocks, no fabricated verdict objects.
10
- *
11
- * P0 A (routing correctness): needs_revision → reopen scribe/artificer,
12
- * identical targetTaskKind / revisionIteration
13
- * / revisionCauseId / payload on both entries.
14
- * P0 B (durable recovery): crash-window resume via the run-once entry —
15
- * same intent → same effect, LLM not re-asked,
16
- * no duplicate reopen (causeId materialize).
17
- * P0 C (exhaustion safety): appliedCount ≥ 2 → rollout_revision_budget_
18
- * exhausted NHR, decision-capable (eligible /
19
- * allowedActions non-empty) — wiring must not
20
- * bypass the revision budget.
21
- */
22
- import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
23
- import * as fs from 'node:fs';
24
- import * as os from 'node:os';
25
- import * as path from 'node:path';
26
- import {
27
- RuntimeStateManager,
28
- InternalizationOrchestrator,
29
- RolloutReviewerRunner,
30
- DefaultRolloutReviewerValidator,
31
- storeEmitter,
32
- hydratePITaskRecord,
33
- createPITaskDiagnosticJson,
34
- mergePITaskMetadata,
35
- reopenTaskForRevision,
36
- collectOwnerDecisionFacts,
37
- deriveOwnerDecisionCapability,
38
- factStoreFromStateManager,
39
- SqliteConnection,
40
- SqliteActivationStateStore,
41
- makeIdempotencyKey,
42
- type PITaskMetadata,
43
- type PDRuntimeAdapter,
44
- type ActivationStatusRecord,
45
- } from '@principles/core/runtime-v2';
46
- import { createRolloutGovernanceDeps, saveHostToolDeclaration } from '@principles/host-runtime';
47
- import { handleRuntimeInternalizationRunOnce } from '../../src/commands/runtime-internalization-run-once.js';
48
-
49
- // ── LLM boundary (the ONLY scripted seam) ────────────────────────────────────
50
- // resolveRuntimeAdapterFromConfig is the CLI's adapter seam; mocking it keeps
51
- // the handler, orchestrator, runners, validators and SQLite stores real while
52
- // making the reviewer/evaluator verdicts deterministic.
53
-
54
- const scriptedPayloads: Record<string, unknown> = {};
55
- const llmCalls: Record<string, number> = {};
56
-
57
- vi.mock('../../src/services/runtime-adapter-resolver.js', () => ({
58
- resolveRuntimeAdapterFromConfig: (input: { runnerKind: string }) => scriptedAdapterFor(input.runnerKind),
59
- }));
60
-
61
- function scriptedAdapterFor(runnerKind: string): PDRuntimeAdapter {
62
- return {
63
- kind: () => 'test-double',
64
- startRun: async () => {
65
- llmCalls[runnerKind] = (llmCalls[runnerKind] ?? 0) + 1;
66
- return {
67
- runId: `run-${runnerKind}-${llmCalls[runnerKind]}`,
68
- runtimeKind: 'test-double',
69
- startedAt: new Date().toISOString(),
70
- };
71
- },
72
- pollRun: async (runId: string) => ({ status: 'succeeded' as const, runId }),
73
- fetchOutput: async (runId: string) => ({ runId, payload: scriptedPayloads[runnerKind] }),
74
- cancelRun: async () => undefined,
75
- } as unknown as PDRuntimeAdapter;
76
- }
77
-
78
- // ── fixture: deterministic lineage + evaluation payload ─────────────────────
79
-
80
- const SCRIBE_ID = 'scribe-parity-1';
81
- const ARTIFICER_ID = 'artificer-parity-1';
82
- const EVAL_ID = 'evaluator-parity-1';
83
- const ROLL_ID_SEED = 'rollout-parity-craft'; // only used by crafted (T3/T4) workspaces
84
- const SCRIBE_ART = 'pi-art-scribe-parity-1';
85
- const ARTIFICER_ART = 'pi-art-artificer-parity-1';
86
- const EVAL_ART = 'pi-art-eval-parity-1';
87
-
88
- function evaluationApprovedPayload(): Record<string, unknown> {
89
- return {
90
- taskId: EVAL_ID,
91
- sourceArtificerArtifactId: ARTIFICER_ART,
92
- evaluation: {
93
- decision: 'approved',
94
- summary: 'parity fixture evaluation',
95
- score: 0.85,
96
- strengths: ['well structured'],
97
- concerns: [],
98
- requiredChanges: [],
99
- },
100
- sourceTrace: { artificerArtifactId: ARTIFICER_ART },
101
- risks: [],
102
- generatedAt: new Date().toISOString(),
103
- };
104
- }
105
-
106
- function rolloutNeedsRevisionPayload(taskId: string, evaluatorArtifactId: string): Record<string, unknown> {
107
- return {
108
- taskId,
109
- sourceEvaluatorArtifactId: evaluatorArtifactId,
110
- review: {
111
- decision: 'needs_revision',
112
- summary: 'parity fixture review',
113
- confidence: 0.7,
114
- requiredChanges: ['Fix the principle wording to cover the observed failure'],
115
- rolloutRisks: ['wording drift'],
116
- safetyChecks: [],
117
- },
118
- sourceTrace: { evaluatorArtifactId },
119
- risks: [],
120
- generatedAt: new Date().toISOString(),
121
- };
122
- }
123
-
124
- async function seedWorkspace(workspaceDir: string): Promise<RuntimeStateManager> {
125
- saveHostToolDeclaration(workspaceDir, {
126
- version: 1,
127
- hostKind: 'openclaw',
128
- mappings: [{ rawToolName: 'Write', canonicalKind: 'write' }],
129
- declaredAt: new Date().toISOString(),
130
- });
131
- const sm = new RuntimeStateManager({ workspaceDir });
132
- await sm.initialize();
133
- await sm.piArtifactStore.upsertArtifact({
134
- artifactId: SCRIBE_ART, artifactKind: 'principle', sourceTaskId: SCRIBE_ID,
135
- lineageArtifactIds: [], validationStatus: 'validated',
136
- contentJson: JSON.stringify({ principleDraft: { title: 'parity-p', statement: '原则正文' } }),
137
- createdAt: new Date().toISOString(), updatedAt: new Date().toISOString(),
138
- });
139
- await sm.piArtifactStore.upsertArtifact({
140
- artifactId: ARTIFICER_ART, artifactKind: 'rule', sourceTaskId: ARTIFICER_ID,
141
- lineageArtifactIds: [SCRIBE_ART], validationStatus: 'validated',
142
- contentJson: JSON.stringify({
143
- implementationPlan: { summary: 'parity plan', targetSurface: 'src/*.ts', changes: [], tests: [], rolloutNotes: [], confidence: 0.8 },
144
- sourceTrace: { scribeArtifactId: SCRIBE_ART },
145
- }),
146
- createdAt: new Date().toISOString(), updatedAt: new Date().toISOString(),
147
- });
148
- const chain: readonly [string, string, string[], 'succeeded' | 'pending'][] = [
149
- [SCRIBE_ID, 'scribe', [], 'succeeded'],
150
- [ARTIFICER_ID, 'artificer', [SCRIBE_ID], 'succeeded'],
151
- [EVAL_ID, 'evaluator', [ARTIFICER_ID], 'pending'],
152
- ];
153
- for (const [id, kind, deps, status] of chain) {
154
- // 先 pending 建 task → lease → succeeded(lease 门只接受 pending/retry_wait)
155
- await sm.createTask({
156
- taskId: id, taskKind: kind, status: 'pending', attemptCount: 0, maxAttempts: 3,
157
- diagnosticJson: createPITaskDiagnosticJson({
158
- dependencyTaskIds: deps, channel: 'prompt', pipelineMode: 'full_chain', timeoutMs: 300_000,
159
- inputArtifactRefs: [], outputArtifactRefs: [], correlationId: 'parity',
160
- }),
161
- });
162
- if (status === 'succeeded') {
163
- await sm.acquireLease({ taskId: id, owner: 'parity-seed', runtimeKind: 'test-double' });
164
- await sm.markTaskSucceeded(id);
165
- }
166
- }
167
- return sm;
168
- }
169
-
170
- /** Real evaluator stage through the REAL run-once handler → real evaluator artifact + real rollout successor task. */
171
- async function driveEvaluatorLeg(workspaceDir: string): Promise<{ rolloutTaskId: string; evaluatorArtifactId: string }> {
172
- scriptedPayloads['evaluator'] = evaluationApprovedPayload();
173
- await handleRuntimeInternalizationRunOnce({
174
- workspace: workspaceDir, runner: 'evaluator', runtime: 'test-double', allowTestDouble: true, json: true,
175
- });
176
- const out = JSON.parse(consoleLogSpy.mock.calls.at(-1)![0] as string) as Record<string, unknown>;
177
- expect(out.decision).toBe('would_lease');
178
- expect(out.enqueueDecision).toBe('successor_created');
179
- expect(out.successorKind).toBe('rollout_reviewer');
180
- return {
181
- rolloutTaskId: (out.successorTaskIds as string[])[0],
182
- evaluatorArtifactId: out.artifactId as string,
183
- };
184
- }
185
-
186
- interface GovernanceOutcome {
187
- rollout: {
188
- status: string;
189
- runnerDecision: string | undefined;
190
- payloadRevisionIteration: number | undefined;
191
- payloadStatus: string | undefined;
192
- payloadTargetKind: string | undefined;
193
- payloadRequiredChanges: readonly string[] | undefined;
194
- intentStatus: string | undefined;
195
- humanReviewContext: PITaskMetadata['humanReviewContext'];
196
- };
197
- scribe: {
198
- status: string;
199
- attemptCount: number;
200
- revisionCount: number;
201
- revisionCauseId: string | undefined;
202
- revisionFeedback: string | undefined;
203
- };
204
- }
205
-
206
- async function readGovernanceOutcome(sm: RuntimeStateManager, rolloutTaskId: string): Promise<GovernanceOutcome> {
207
- const rolloutRaw = await sm.getTask(rolloutTaskId);
208
- expect(rolloutRaw).not.toBeNull();
209
- const rollout = hydratePITaskRecord(rolloutRaw!)!;
210
- const scribeRaw = await sm.getTask(SCRIBE_ID);
211
- const scribe = scribeRaw ? hydratePITaskRecord(scribeRaw) : null;
212
- return {
213
- rollout: {
214
- status: rolloutRaw!.status,
215
- runnerDecision: rollout.runnerDecision,
216
- payloadRevisionIteration: rollout.rolloutRevisionPayload?.revisionIteration,
217
- payloadStatus: rollout.rolloutRevisionPayload?.status,
218
- payloadTargetKind: rollout.rolloutRevisionPayload?.targetTaskKind,
219
- payloadRequiredChanges: rollout.rolloutRevisionPayload?.requiredChanges,
220
- intentStatus: rollout.completionIntent?.status,
221
- humanReviewContext: rollout.humanReviewContext,
222
- },
223
- scribe: {
224
- status: scribeRaw!.status,
225
- attemptCount: scribeRaw!.attemptCount,
226
- revisionCount: scribe?.revisionCount ?? 0,
227
- revisionCauseId: scribe?.revisionCauseId,
228
- revisionFeedback: scribe?.revisionFeedback,
229
- },
230
- };
231
- }
232
-
233
- let consoleLogSpy: ReturnType<typeof vi.spyOn>;
234
-
235
- beforeEach(() => {
236
- for (const key of Object.keys(scriptedPayloads)) delete scriptedPayloads[key];
237
- for (const key of Object.keys(llmCalls)) delete llmCalls[key];
238
- consoleLogSpy = vi.spyOn(console, 'log').mockImplementation(() => {});
239
- vi.spyOn(console, 'error').mockImplementation(() => {});
240
- });
241
-
242
- afterEach(() => {
243
- consoleLogSpy.mockRestore();
244
- vi.restoreAllMocks();
245
- process.exitCode = 0;
246
- });
247
-
248
- // ═══ P0 A — cross entry point equivalence (core AC) ══════════════════════════
249
-
250
- describe('PRI-708 P0-A cross entry point equivalence', () => {
251
- const dirs: string[] = [];
252
- const states: RuntimeStateManager[] = [];
253
-
254
- function makeWorkspace(prefix: string): string {
255
- const dir = fs.mkdtempSync(path.join(os.tmpdir(), prefix));
256
- dirs.push(dir);
257
- return dir;
258
- }
259
-
260
- afterEach(async () => {
261
- for (const sm of states.splice(0)) await sm.close().catch(() => undefined);
262
- for (const dir of dirs.splice(0)) {
263
- try { fs.rmSync(dir, { recursive: true, force: true }); } catch { /* temp */ }
264
- }
265
- });
266
-
267
- it('run-once entry: real evaluator→rollout chain, needs_revision reopens the scribe via canonical routing', async () => {
268
- const ws = makeWorkspace('pd-pri708-runonce-');
269
- const sm = await seedWorkspace(ws);
270
- states.push(sm);
271
-
272
- const { rolloutTaskId, evaluatorArtifactId } = await driveEvaluatorLeg(ws);
273
- scriptedPayloads['rollout_reviewer'] = rolloutNeedsRevisionPayload(rolloutTaskId, evaluatorArtifactId);
274
-
275
- await handleRuntimeInternalizationRunOnce({
276
- workspace: ws, runner: 'rollout_reviewer', runtime: 'test-double', allowTestDouble: true, json: true,
277
- });
278
- const out = JSON.parse(consoleLogSpy.mock.calls.at(-1)![0] as string) as Record<string, unknown>;
279
- expect(out.decision).toBe('would_lease');
280
- expect((out.runnerResult as Record<string, unknown>).status).toBe('succeeded');
281
-
282
- const outcome = await readGovernanceOutcome(sm, rolloutTaskId);
283
- // rollout 侧: governance transition 完成 — 无 NHR、payload applied、intent applied
284
- expect(outcome.rollout.status).toBe('succeeded');
285
- expect(outcome.rollout.runnerDecision).toBe('needs_revision');
286
- expect(outcome.rollout.humanReviewContext).toBeUndefined();
287
- expect(outcome.rollout.payloadRevisionIteration).toBe(1);
288
- expect(outcome.rollout.payloadStatus).toBe('applied');
289
- expect(outcome.rollout.payloadTargetKind).toBe('scribe');
290
- expect(outcome.rollout.payloadRequiredChanges).toEqual(['Fix the principle wording to cover the observed failure']);
291
- expect(outcome.rollout.intentStatus).toBe('applied');
292
- // scribe 侧: 被 reopen(prompt channel → scribe 走到底),反馈携带 requiredChanges
293
- expect(outcome.scribe.status).toBe('pending');
294
- expect(outcome.scribe.attemptCount).toBe(0);
295
- expect(outcome.scribe.revisionCount).toBe(1);
296
- expect(outcome.scribe.revisionCauseId).toBe(`rollout-${rolloutTaskId}-r1`);
297
- expect(outcome.scribe.revisionFeedback).toContain('Fix the principle wording');
298
- });
299
-
300
- it('production consumer-cycle assembly on the SAME durable input produces the IDENTICAL governance outcome', async () => {
301
- const ws = makeWorkspace('pd-pri708-prodcycle-');
302
- const sm = await seedWorkspace(ws);
303
- states.push(sm);
304
-
305
- const { rolloutTaskId, evaluatorArtifactId } = await driveEvaluatorLeg(ws);
306
- scriptedPayloads['rollout_reviewer'] = rolloutNeedsRevisionPayload(rolloutTaskId, evaluatorArtifactId);
307
-
308
- // internalization-consumer-cycle.ts:536-543 的精确装配公式(同工厂 + 同
309
- // options 形;cycle 的 orchestrator 同为 dryRun: true)。
310
- const orchestrator = new InternalizationOrchestrator(
311
- { stateManager: sm },
312
- { owner: 'parity-production', runtimeKind: 'test-double', dryRun: true },
313
- );
314
- const wake = await orchestrator.wakeOnce('rollout_reviewer');
315
- expect(wake.decision).toBe('would_lease');
316
- const runner = new RolloutReviewerRunner(
317
- {
318
- stateManager: sm,
319
- runtimeAdapter: scriptedAdapterFor('rollout_reviewer'),
320
- eventEmitter: storeEmitter,
321
- artifactStore: sm.piArtifactStore,
322
- validator: new DefaultRolloutReviewerValidator(),
323
- ...createRolloutGovernanceDeps(ws, orchestrator, {}),
324
- },
325
- { owner: 'parity-production', runtimeKind: 'test-double', pollIntervalMs: 5, timeoutMs: 15_000 },
326
- );
327
- const result = await runner.run(wake.taskId);
328
- expect(result.status).toBe('succeeded');
329
- await orchestrator.commitNextTaskProposal(wake.taskId);
330
-
331
- const outcome = await readGovernanceOutcome(sm, rolloutTaskId);
332
- expect(outcome.rollout.status).toBe('succeeded');
333
- expect(outcome.rollout.runnerDecision).toBe('needs_revision');
334
- expect(outcome.rollout.humanReviewContext).toBeUndefined();
335
- expect(outcome.rollout.payloadRevisionIteration).toBe(1);
336
- expect(outcome.rollout.payloadStatus).toBe('applied');
337
- expect(outcome.rollout.payloadTargetKind).toBe('scribe');
338
- expect(outcome.rollout.payloadRequiredChanges).toEqual(['Fix the principle wording to cover the observed failure']);
339
- expect(outcome.rollout.intentStatus).toBe('applied');
340
- expect(outcome.scribe.status).toBe('pending');
341
- expect(outcome.scribe.attemptCount).toBe(0);
342
- expect(outcome.scribe.revisionCount).toBe(1);
343
- expect(outcome.scribe.revisionCauseId).toBe(`rollout-${rolloutTaskId}-r1`);
344
- expect(outcome.scribe.revisionFeedback).toContain('Fix the principle wording');
345
- });
346
-
347
- it('EQUIVALENCE: both entries yield byte-identical governance fields for the same durable input', async () => {
348
- const wsA = makeWorkspace('pd-pri708-eq-a-');
349
- const smA = await seedWorkspace(wsA);
350
- states.push(smA);
351
- const wsB = makeWorkspace('pd-pri708-eq-b-');
352
- const smB = await seedWorkspace(wsB);
353
- states.push(smB);
354
-
355
- // 腿 A: run-once(真实 CLI handler)
356
- const legA = await driveEvaluatorLeg(wsA);
357
- scriptedPayloads['rollout_reviewer'] = rolloutNeedsRevisionPayload(legA.rolloutTaskId, legA.evaluatorArtifactId);
358
- await handleRuntimeInternalizationRunOnce({
359
- workspace: wsA, runner: 'rollout_reviewer', runtime: 'test-double', allowTestDouble: true, json: true,
360
- });
361
-
362
- // 腿 B: production consumer-cycle 装配公式
363
- const legB = await driveEvaluatorLeg(wsB);
364
- scriptedPayloads['rollout_reviewer'] = rolloutNeedsRevisionPayload(legB.rolloutTaskId, legB.evaluatorArtifactId);
365
- const orchestrator = new InternalizationOrchestrator(
366
- { stateManager: smB },
367
- { owner: 'parity-production', runtimeKind: 'test-double', dryRun: true },
368
- );
369
- const wake = await orchestrator.wakeOnce('rollout_reviewer');
370
- const runner = new RolloutReviewerRunner(
371
- {
372
- stateManager: smB,
373
- runtimeAdapter: scriptedAdapterFor('rollout_reviewer'),
374
- eventEmitter: storeEmitter,
375
- artifactStore: smB.piArtifactStore,
376
- validator: new DefaultRolloutReviewerValidator(),
377
- ...createRolloutGovernanceDeps(wsB, orchestrator, {}),
378
- },
379
- { owner: 'parity-production', runtimeKind: 'test-double', pollIntervalMs: 5, timeoutMs: 15_000 },
380
- );
381
- expect((await runner.run(wake.taskId)).status).toBe('succeeded');
382
- await orchestrator.commitNextTaskProposal(wake.taskId);
383
-
384
- const outA = await readGovernanceOutcome(smA, legA.rolloutTaskId);
385
- const outB = await readGovernanceOutcome(smB, legB.rolloutTaskId);
386
- // rollout 的 causeId 内嵌各自 workspace 的 taskId — 归一后必须逐字段一致
387
- expect(outA.scribe.revisionCauseId).toBe(`rollout-${legA.rolloutTaskId}-r1`);
388
- expect(outB.scribe.revisionCauseId).toBe(`rollout-${legB.rolloutTaskId}-r1`);
389
- const normalized = (o: GovernanceOutcome, rolloutTaskId: string): GovernanceOutcome => ({
390
- ...o,
391
- scribe: { ...o.scribe, revisionCauseId: o.scribe.revisionCauseId?.replace(rolloutTaskId, '<rolloutTaskId>') },
392
- });
393
- expect(normalized(outA, legA.rolloutTaskId)).toEqual(normalized(outB, legB.rolloutTaskId));
394
- });
395
- });
396
-
397
- // ═══ P0 B — durable recovery (crash window resume) ═══════════════════════════
398
-
399
- describe('PRI-708 P0-B durable recovery through the run-once entry', () => {
400
- let ws: string;
401
- let sm: RuntimeStateManager;
402
-
403
- beforeEach(async () => {
404
- ws = fs.mkdtempSync(path.join(os.tmpdir(), 'pd-pri708-recovery-'));
405
- sm = await seedWorkspace(ws);
406
- // craft 链的 evaluator 无 evaluator leg 驱动 — 真实 lease→succeed 收尾,
407
- // 使 rollout 任务的依赖满足(wakeOnce 才会投放)
408
- await sm.acquireLease({ taskId: EVAL_ID, owner: 'parity-seed', runtimeKind: 'test-double' });
409
- await sm.markTaskSucceeded(EVAL_ID);
410
- // craft 后 rollout 任务不需要 evaluator artifact(resume 不走 buildContext)
411
- await sm.piArtifactStore.upsertArtifact({
412
- artifactId: EVAL_ART, artifactKind: 'principle', sourceTaskId: EVAL_ID,
413
- lineageArtifactIds: [ARTIFICER_ART], validationStatus: 'pending',
414
- contentJson: JSON.stringify({ evaluation: { decision: 'approved', score: 0.9, strengths: [], concerns: [], requiredChanges: [] } }),
415
- createdAt: new Date().toISOString(), updatedAt: new Date().toISOString(),
416
- });
417
- });
418
-
419
- afterEach(async () => {
420
- await sm.close().catch(() => undefined);
421
- try { fs.rmSync(ws, { recursive: true, force: true }); } catch { /* temp */ }
422
- });
423
-
424
- /** craft crash window: verdict+intent durable(pending),effects 未 materialize */
425
- async function craftPendingIntent(): Promise<string> {
426
- await sm.createTask({
427
- taskId: ROLL_ID_SEED, taskKind: 'rollout_reviewer', status: 'pending', attemptCount: 1, maxAttempts: 3,
428
- diagnosticJson: createPITaskDiagnosticJson({
429
- dependencyTaskIds: [EVAL_ID], channel: 'prompt', pipelineMode: 'full_chain', timeoutMs: 300_000,
430
- inputArtifactRefs: [{ artifactType: 'principle', ref: EVAL_ART }], outputArtifactRefs: [], correlationId: 'parity-recovery',
431
- }),
432
- });
433
- await sm.acquireLease({ taskId: ROLL_ID_SEED, owner: 'craft', runtimeKind: 'test-double' });
434
- const runs = await sm.getRunsByTask(ROLL_ID_SEED);
435
- const runId = runs.at(-1)!.runId;
436
- await sm.updateRunOutput(runId, JSON.stringify(rolloutNeedsRevisionPayload(ROLL_ID_SEED, EVAL_ART)));
437
- await sm.releaseLease(ROLL_ID_SEED, 'craft');
438
- const raw = await sm.getTask(ROLL_ID_SEED);
439
- const pi = hydratePITaskRecord(raw!)!;
440
- await sm.updateTaskDiagnosticJson(ROLL_ID_SEED, createPITaskDiagnosticJson(mergePITaskMetadata(pi, {
441
- runnerDecision: 'needs_revision',
442
- completionIntent: {
443
- decision: 'needs_revision', sourceRunId: runId, revisionEpoch: 0, status: 'pending', revisionIteration: 1,
444
- } as PITaskMetadata['completionIntent'],
445
- })));
446
- return runId;
447
- }
448
-
449
- it('crash-before-reopen window: resume applies the SAME effect (reopen) without re-asking the LLM', async () => {
450
- await craftPendingIntent();
451
-
452
- await handleRuntimeInternalizationRunOnce({
453
- workspace: ws, runner: 'rollout_reviewer', runtime: 'test-double', allowTestDouble: true, json: true,
454
- });
455
-
456
- // resume = intent 是 recovery authority — LLM 不得被重新调用
457
- expect(llmCalls['rollout_reviewer'] ?? 0).toBe(0);
458
- const outcome = await readGovernanceOutcome(sm, ROLL_ID_SEED);
459
- expect(outcome.rollout.status).toBe('succeeded');
460
- expect(outcome.rollout.humanReviewContext).toBeUndefined();
461
- expect(outcome.rollout.payloadStatus).toBe('applied');
462
- expect(outcome.rollout.intentStatus).toBe('applied');
463
- expect(outcome.scribe.status).toBe('pending');
464
- expect(outcome.scribe.revisionCount).toBe(1);
465
- expect(outcome.scribe.revisionCauseId).toBe(`rollout-${ROLL_ID_SEED}-r1`);
466
- });
467
-
468
- it('crash-after-reopen window: causeId materialize check — no duplicate reopen on resume', async () => {
469
- await craftPendingIntent();
470
- // reopen 已 materialize、intent 未标 applied 的窗口: 先真实 reopen
471
- await reopenTaskForRevision(sm, SCRIBE_ID, {
472
- revisionFeedback: 'pre-crash reopen', reason: 'rollout_revision_iteration_1',
473
- revisionCauseId: `rollout-${ROLL_ID_SEED}-r1`,
474
- });
475
-
476
- await handleRuntimeInternalizationRunOnce({
477
- workspace: ws, runner: 'rollout_reviewer', runtime: 'test-double', allowTestDouble: true, json: true,
478
- });
479
-
480
- expect(llmCalls['rollout_reviewer'] ?? 0).toBe(0);
481
- const outcome = await readGovernanceOutcome(sm, ROLL_ID_SEED);
482
- expect(outcome.rollout.status).toBe('succeeded');
483
- expect(outcome.rollout.intentStatus).toBe('applied');
484
- // 不得二次 reopen — revisionCount 仍是 1,原反馈不被覆写
485
- expect(outcome.scribe.status).toBe('pending');
486
- expect(outcome.scribe.revisionCount).toBe(1);
487
- expect(outcome.scribe.revisionFeedback).toBe('pre-crash reopen');
488
- });
489
- });
490
-
491
- // ═══ P0 C — exhaustion safety (decision-capable NHR) ═════════════════════════
492
-
493
- describe('PRI-708 P0-C exhaustion safety through the run-once entry', () => {
494
- let ws: string;
495
- let sm: RuntimeStateManager;
496
-
497
- beforeEach(async () => {
498
- ws = fs.mkdtempSync(path.join(os.tmpdir(), 'pd-pri708-budget-'));
499
- sm = await seedWorkspace(ws);
500
- // 同 P0-B: evaluator 真实收尾,rollout 依赖满足
501
- await sm.acquireLease({ taskId: EVAL_ID, owner: 'parity-seed', runtimeKind: 'test-double' });
502
- await sm.markTaskSucceeded(EVAL_ID);
503
- await sm.piArtifactStore.upsertArtifact({
504
- artifactId: EVAL_ART, artifactKind: 'principle', sourceTaskId: EVAL_ID,
505
- lineageArtifactIds: [ARTIFICER_ART], validationStatus: 'pending',
506
- contentJson: JSON.stringify({ evaluation: { decision: 'approved', score: 0.9, strengths: [], concerns: [], requiredChanges: [] } }),
507
- createdAt: new Date().toISOString(), updatedAt: new Date().toISOString(),
508
- });
509
- await sm.createTask({
510
- taskId: ROLL_ID_SEED, taskKind: 'rollout_reviewer', status: 'pending', attemptCount: 0, maxAttempts: 3,
511
- diagnosticJson: createPITaskDiagnosticJson({
512
- dependencyTaskIds: [EVAL_ID], channel: 'prompt', pipelineMode: 'full_chain', timeoutMs: 300_000,
513
- inputArtifactRefs: [{ artifactType: 'principle', ref: EVAL_ART }], outputArtifactRefs: [], correlationId: 'parity-budget',
514
- // 预算证据: 两轮修订已 applied
515
- rolloutRevisionPayload: {
516
- requiredChanges: ['前两轮'], revisionIteration: 2, sourceRolloutTaskId: ROLL_ID_SEED,
517
- sourceArtifactId: EVAL_ART, targetTaskKind: 'scribe', status: 'applied',
518
- },
519
- revisionCount: 1,
520
- }),
521
- });
522
- });
523
-
524
- afterEach(async () => {
525
- await sm.close().catch(() => undefined);
526
- try { fs.rmSync(ws, { recursive: true, force: true }); } catch { /* temp */ }
527
- });
528
-
529
- it('budget exhausted (appliedCount>=2): rollout_revision_budget_exhausted NHR — decision-capable, NOT recovery', async () => {
530
- scriptedPayloads['rollout_reviewer'] = rolloutNeedsRevisionPayload(ROLL_ID_SEED, EVAL_ART);
531
- await handleRuntimeInternalizationRunOnce({
532
- workspace: ws, runner: 'rollout_reviewer', runtime: 'test-double', allowTestDouble: true, json: true,
533
- });
534
-
535
- // 预算不被新接线绕过: scribe 未被 reopen
536
- const outcome = await readGovernanceOutcome(sm, ROLL_ID_SEED);
537
- expect(outcome.scribe.revisionCount).toBe(0);
538
- expect(outcome.scribe.status).toBe('succeeded');
539
- // 任务落 NHR,reasonCode 规范化为 decision-capable 集合成员
540
- const raw = await sm.getTask(ROLL_ID_SEED);
541
- expect(raw!.status).toBe('needs_human_review');
542
- const pi = hydratePITaskRecord(raw!)!;
543
- expect(pi.humanReviewContext?.reasonCode).toBe('rollout_revision_budget_exhausted');
544
-
545
- // Owner 裁决能力: eligible=true、allowedActions 非空(生产同一 capability 函数)
546
- const facts = await collectOwnerDecisionFacts(factStoreFromStateManager(sm), ROLL_ID_SEED);
547
- expect(facts).not.toBeNull();
548
- const capability = deriveOwnerDecisionCapability(facts!);
549
- expect(capability.eligible).toBe(true);
550
- expect(capability.attention).toBe('owner_decision');
551
- expect(capability.allowedActions.length).toBeGreaterThan(0);
552
- expect(capability.allowedActions).toContain('accept_current');
553
- });
554
- });
555
-
556
- // ═══ PRI-713 — dispatch wiring parity (approve_rollout → ActivationDispatcher) ═
557
-
558
- function rolloutApprovePayload(taskId: string, evaluatorArtifactId: string): Record<string, unknown> {
559
- return {
560
- taskId,
561
- sourceEvaluatorArtifactId: evaluatorArtifactId,
562
- review: {
563
- decision: 'approve_rollout',
564
- summary: 'parity fixture approve',
565
- confidence: 0.9,
566
- requiredChanges: [],
567
- rolloutRisks: [],
568
- safetyChecks: [],
569
- },
570
- sourceTrace: { evaluatorArtifactId },
571
- risks: [],
572
- generatedAt: new Date().toISOString(),
573
- };
574
- }
575
-
576
- interface DispatchOutcome {
577
- rolloutStatus: string;
578
- humanReviewReasonCode: string | undefined;
579
- activation: ActivationStatusRecord | null;
580
- }
581
-
582
- /** Read the durable dispatch outcome: rollout task state + persisted activation record. */
583
- async function readDispatchOutcome(sm: RuntimeStateManager, workspaceDir: string, rolloutTaskId: string): Promise<DispatchOutcome> {
584
- const raw = await sm.getTask(rolloutTaskId);
585
- expect(raw).not.toBeNull();
586
- const pi = hydratePITaskRecord(raw!)!;
587
- const connection = new SqliteConnection(workspaceDir);
588
- try {
589
- const activationStore = new SqliteActivationStateStore(connection);
590
- const activation = await activationStore.getActivationStatus(makeIdempotencyKey(SCRIBE_ART, 'prompt'));
591
- return {
592
- rolloutStatus: raw!.status,
593
- humanReviewReasonCode: pi.humanReviewContext?.reasonCode,
594
- activation,
595
- };
596
- } finally {
597
- try { connection.close(); } catch { /* best-effort */ }
598
- }
599
- }
600
-
601
- /** PRI-811 Phase B: read the pending approval row a rollout recommendation must produce. */
602
- async function readPendingApproval(
603
- workspaceDir: string,
604
- artifactId: string,
605
- channel: 'prompt' | 'code_tool_hook' | 'defer_archive',
606
- ): Promise<{ artifactId: string; channel: string; status: string } | null> {
607
- const connection = new SqliteConnection(workspaceDir);
608
- try {
609
- const rows = connection.getDb().prepare(
610
- 'SELECT artifact_id, channel, status FROM approvals WHERE artifact_id = ? AND channel = ? AND status = \'pending\''
611
- ).all(artifactId, channel) as unknown;
612
- if (!Array.isArray(rows) || rows.length === 0) return null;
613
- const row: unknown = rows[0];
614
- if (typeof row !== 'object' || row === null || Array.isArray(row)) return null;
615
- const record = row as Record<string, unknown>;
616
- return {
617
- artifactId: String(record['artifact_id']),
618
- channel: String(record['channel']),
619
- status: String(record['status']),
620
- };
621
- } finally {
622
- try { connection.close(); } catch { /* best-effort */ }
623
- }
624
- }
625
-
626
- describe('PRI-713 dispatch parity: approve_rollout through the run-once entry', () => {
627
- const dirs: string[] = [];
628
- const states: RuntimeStateManager[] = [];
629
-
630
- function makeWorkspace(prefix: string): string {
631
- const dir = fs.mkdtempSync(path.join(os.tmpdir(), prefix));
632
- dirs.push(dir);
633
- return dir;
634
- }
635
-
636
- afterEach(async () => {
637
- for (const sm of states.splice(0)) await sm.close().catch(() => undefined);
638
- for (const dir of dirs.splice(0)) {
639
- try { fs.rmSync(dir, { recursive: true, force: true }); } catch { /* temp */ }
640
- }
641
- });
642
-
643
- it('run-once entry: approve_rollout completes governance via the canonical ActivationDispatcher (no NHR)', async () => {
644
- const ws = makeWorkspace('pd-pri713-runonce-');
645
- const sm = await seedWorkspace(ws);
646
- states.push(sm);
647
-
648
- const { rolloutTaskId, evaluatorArtifactId } = await driveEvaluatorLeg(ws);
649
- scriptedPayloads['rollout_reviewer'] = rolloutApprovePayload(rolloutTaskId, evaluatorArtifactId);
650
-
651
- await handleRuntimeInternalizationRunOnce({
652
- workspace: ws, runner: 'rollout_reviewer', runtime: 'test-double', allowTestDouble: true, json: true,
653
- });
654
-
655
- const outcome = await readDispatchOutcome(sm, ws, rolloutTaskId);
656
- // rollout 侧: dispatch 完成治理迁移 — 无 NHR、任务 succeeded
657
- expect(outcome.rolloutStatus).toBe('succeeded');
658
- expect(outcome.humanReviewReasonCode).toBeUndefined();
659
- // PRI-811 Phase B: prompt 渠道推荐只入 approval 队列, activations 表无行;
660
- // 幂等键 = <scribe artifact>::prompt 等待 Owner 批准
661
- expect(outcome.activation).toBeNull();
662
- const pending = await readPendingApproval(ws, SCRIBE_ART, 'prompt');
663
- expect(pending).not.toBeNull();
664
- expect(pending!.artifactId).toBe(SCRIBE_ART);
665
- expect(pending!.channel).toBe('prompt');
666
- });
667
-
668
- it('EQUIVALENCE: production consumer-cycle assembly on the same durable input yields the same dispatch outcome', async () => {
669
- const ws = makeWorkspace('pd-pri713-prodcycle-');
670
- const sm = await seedWorkspace(ws);
671
- states.push(sm);
672
-
673
- const { rolloutTaskId, evaluatorArtifactId } = await driveEvaluatorLeg(ws);
674
- scriptedPayloads['rollout_reviewer'] = rolloutApprovePayload(rolloutTaskId, evaluatorArtifactId);
675
-
676
- // internalization-consumer-cycle.ts 的装配公式(同工厂 + 同 options 形)
677
- const orchestrator = new InternalizationOrchestrator(
678
- { stateManager: sm },
679
- { owner: 'parity-production', runtimeKind: 'test-double', dryRun: true },
680
- );
681
- const wake = await orchestrator.wakeOnce('rollout_reviewer');
682
- expect(wake.decision).toBe('would_lease');
683
- const runner = new RolloutReviewerRunner(
684
- {
685
- stateManager: sm,
686
- runtimeAdapter: scriptedAdapterFor('rollout_reviewer'),
687
- eventEmitter: storeEmitter,
688
- artifactStore: sm.piArtifactStore,
689
- validator: new DefaultRolloutReviewerValidator(),
690
- ...createRolloutGovernanceDeps(ws, orchestrator, {}),
691
- },
692
- { owner: 'parity-production', runtimeKind: 'test-double', pollIntervalMs: 5, timeoutMs: 15_000 },
693
- );
694
- expect((await runner.run(wake.taskId)).status).toBe('succeeded');
695
- await orchestrator.commitNextTaskProposal(wake.taskId);
696
-
697
- const outcome = await readDispatchOutcome(sm, ws, rolloutTaskId);
698
- expect(outcome.rolloutStatus).toBe('succeeded');
699
- expect(outcome.humanReviewReasonCode).toBeUndefined();
700
- expect(outcome.activation).toBeNull();
701
- const pending = await readPendingApproval(ws, SCRIBE_ART, 'prompt');
702
- expect(pending).not.toBeNull();
703
- expect(pending!.artifactId).toBe(SCRIBE_ART);
704
- expect(pending!.channel).toBe('prompt');
705
- });
706
- });