@principles/pd-cli 1.152.11 → 1.152.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (303) hide show
  1. package/dist/commands/candidate.d.ts +3 -3
  2. package/dist/commands/candidate.d.ts.map +1 -1
  3. package/dist/commands/candidate.js +9 -21
  4. package/dist/commands/candidate.js.map +1 -1
  5. package/dist/index.js +0 -0
  6. package/dist/services/rulehost-pipeline-runner.d.ts.map +1 -1
  7. package/dist/services/rulehost-pipeline-runner.js +4 -17
  8. package/dist/services/rulehost-pipeline-runner.js.map +1 -1
  9. package/package.json +13 -7
  10. package/dist/commands/__tests__/intent-flag-wiring.test.d.ts +0 -9
  11. package/dist/commands/__tests__/intent-flag-wiring.test.d.ts.map +0 -1
  12. package/dist/commands/__tests__/intent-flag-wiring.test.js +0 -237
  13. package/dist/commands/__tests__/intent-flag-wiring.test.js.map +0 -1
  14. package/dist/commands/__tests__/legacy-cleanup.test.d.ts +0 -18
  15. package/dist/commands/__tests__/legacy-cleanup.test.d.ts.map +0 -1
  16. package/dist/commands/__tests__/legacy-cleanup.test.js +0 -467
  17. package/dist/commands/__tests__/legacy-cleanup.test.js.map +0 -1
  18. package/dist/commands/__tests__/mvp-smoke.test.d.ts +0 -15
  19. package/dist/commands/__tests__/mvp-smoke.test.d.ts.map +0 -1
  20. package/dist/commands/__tests__/mvp-smoke.test.js +0 -262
  21. package/dist/commands/__tests__/mvp-smoke.test.js.map +0 -1
  22. package/dist/commands/__tests__/pain-retry-maxTokens-flag.test.d.ts +0 -2
  23. package/dist/commands/__tests__/pain-retry-maxTokens-flag.test.d.ts.map +0 -1
  24. package/dist/commands/__tests__/pain-retry-maxTokens-flag.test.js +0 -60
  25. package/dist/commands/__tests__/pain-retry-maxTokens-flag.test.js.map +0 -1
  26. package/dist/commands/__tests__/rulecode-flag-wiring.test.d.ts +0 -21
  27. package/dist/commands/__tests__/rulecode-flag-wiring.test.d.ts.map +0 -1
  28. package/dist/commands/__tests__/rulecode-flag-wiring.test.js +0 -186
  29. package/dist/commands/__tests__/rulecode-flag-wiring.test.js.map +0 -1
  30. package/dist/commands/__tests__/rulecode-handler.test.d.ts +0 -16
  31. package/dist/commands/__tests__/rulecode-handler.test.d.ts.map +0 -1
  32. package/dist/commands/__tests__/rulecode-handler.test.js +0 -285
  33. package/dist/commands/__tests__/rulecode-handler.test.js.map +0 -1
  34. package/dist/commands/__tests__/run-rulehost-flag-wiring.test.d.ts +0 -24
  35. package/dist/commands/__tests__/run-rulehost-flag-wiring.test.d.ts.map +0 -1
  36. package/dist/commands/__tests__/run-rulehost-flag-wiring.test.js +0 -232
  37. package/dist/commands/__tests__/run-rulehost-flag-wiring.test.js.map +0 -1
  38. package/dist/commands/__tests__/runtime-activation-nextaction.test.d.ts +0 -15
  39. package/dist/commands/__tests__/runtime-activation-nextaction.test.d.ts.map +0 -1
  40. package/dist/commands/__tests__/runtime-activation-nextaction.test.js +0 -73
  41. package/dist/commands/__tests__/runtime-activation-nextaction.test.js.map +0 -1
  42. package/dist/commands/__tests__/runtime-probe-config.test.d.ts +0 -20
  43. package/dist/commands/__tests__/runtime-probe-config.test.d.ts.map +0 -1
  44. package/dist/commands/__tests__/runtime-probe-config.test.js +0 -389
  45. package/dist/commands/__tests__/runtime-probe-config.test.js.map +0 -1
  46. package/dist/commands/__tests__/telemetry-flag-wiring.test.d.ts +0 -9
  47. package/dist/commands/__tests__/telemetry-flag-wiring.test.d.ts.map +0 -1
  48. package/dist/commands/__tests__/telemetry-flag-wiring.test.js +0 -76
  49. package/dist/commands/__tests__/telemetry-flag-wiring.test.js.map +0 -1
  50. package/dist/commands/__tests__/version.test.d.ts +0 -2
  51. package/dist/commands/__tests__/version.test.d.ts.map +0 -1
  52. package/dist/commands/__tests__/version.test.js +0 -238
  53. package/dist/commands/__tests__/version.test.js.map +0 -1
  54. package/dist/commands/runtime-uat.guard.test.d.ts +0 -2
  55. package/dist/commands/runtime-uat.guard.test.d.ts.map +0 -1
  56. package/dist/commands/runtime-uat.guard.test.js +0 -153
  57. package/dist/commands/runtime-uat.guard.test.js.map +0 -1
  58. package/dist/services/__tests__/cli-output.test.d.ts +0 -18
  59. package/dist/services/__tests__/cli-output.test.d.ts.map +0 -1
  60. package/dist/services/__tests__/cli-output.test.js +0 -103
  61. package/dist/services/__tests__/cli-output.test.js.map +0 -1
  62. package/dist/services/__tests__/evaluator-runner-deps.test.d.ts +0 -2
  63. package/dist/services/__tests__/evaluator-runner-deps.test.d.ts.map +0 -1
  64. package/dist/services/__tests__/evaluator-runner-deps.test.js +0 -343
  65. package/dist/services/__tests__/evaluator-runner-deps.test.js.map +0 -1
  66. package/dist/services/__tests__/rulehost-readiness.test.d.ts +0 -2
  67. package/dist/services/__tests__/rulehost-readiness.test.d.ts.map +0 -1
  68. package/dist/services/__tests__/rulehost-readiness.test.js +0 -311
  69. package/dist/services/__tests__/rulehost-readiness.test.js.map +0 -1
  70. package/dist/services/__tests__/runtime-adapter-resolver.test.d.ts +0 -18
  71. package/dist/services/__tests__/runtime-adapter-resolver.test.d.ts.map +0 -1
  72. package/dist/services/__tests__/runtime-adapter-resolver.test.js +0 -673
  73. package/dist/services/__tests__/runtime-adapter-resolver.test.js.map +0 -1
  74. package/dist/utils/production-workspace-guard.test.d.ts +0 -2
  75. package/dist/utils/production-workspace-guard.test.d.ts.map +0 -1
  76. package/dist/utils/production-workspace-guard.test.js +0 -137
  77. package/dist/utils/production-workspace-guard.test.js.map +0 -1
  78. package/scripts/llm-dogfood.ts +0 -456
  79. package/scripts/migrate-illegal-expected-decision.ts +0 -252
  80. package/src/commands/__tests__/intent-flag-wiring.test.ts +0 -282
  81. package/src/commands/__tests__/legacy-cleanup.test.ts +0 -602
  82. package/src/commands/__tests__/mvp-smoke.test.ts +0 -300
  83. package/src/commands/__tests__/pain-retry-maxTokens-flag.test.ts +0 -73
  84. package/src/commands/__tests__/rulecode-flag-wiring.test.ts +0 -237
  85. package/src/commands/__tests__/rulecode-handler.test.ts +0 -369
  86. package/src/commands/__tests__/run-rulehost-flag-wiring.test.ts +0 -292
  87. package/src/commands/__tests__/runtime-activation-nextaction.test.ts +0 -81
  88. package/src/commands/__tests__/runtime-probe-config.test.ts +0 -432
  89. package/src/commands/__tests__/telemetry-flag-wiring.test.ts +0 -84
  90. package/src/commands/__tests__/version.test.ts +0 -251
  91. package/src/commands/admission-gate.ts +0 -30
  92. package/src/commands/artifact.ts +0 -82
  93. package/src/commands/build-trajectory-evidence.ts +0 -298
  94. package/src/commands/candidate.ts +0 -1260
  95. package/src/commands/codex-ingest-catchup.ts +0 -114
  96. package/src/commands/codex-ingest-quarantine.ts +0 -127
  97. package/src/commands/codex-reconcile.ts +0 -84
  98. package/src/commands/codex-setup.ts +0 -476
  99. package/src/commands/codex-worker.ts +0 -185
  100. package/src/commands/command-helpers.ts +0 -24
  101. package/src/commands/config-doctor.ts +0 -193
  102. package/src/commands/console.ts +0 -797
  103. package/src/commands/context.ts +0 -72
  104. package/src/commands/demo-story-a.ts +0 -241
  105. package/src/commands/diagnose.ts +0 -756
  106. package/src/commands/errors-list.ts +0 -441
  107. package/src/commands/evolution-tasks-list.ts +0 -48
  108. package/src/commands/evolution-tasks-show.ts +0 -62
  109. package/src/commands/flow.ts +0 -60
  110. package/src/commands/health-codex.ts +0 -576
  111. package/src/commands/health.ts +0 -315
  112. package/src/commands/history.ts +0 -63
  113. package/src/commands/intent.ts +0 -457
  114. package/src/commands/legacy-cleanup.ts +0 -531
  115. package/src/commands/legacy-import.ts +0 -104
  116. package/src/commands/mvp-smoke.ts +0 -160
  117. package/src/commands/pain-evidence.ts +0 -226
  118. package/src/commands/pain-list.ts +0 -239
  119. package/src/commands/pain-record.ts +0 -612
  120. package/src/commands/pain-retry.ts +0 -916
  121. package/src/commands/principles-stats.ts +0 -700
  122. package/src/commands/proven-channel-baseline.ts +0 -115
  123. package/src/commands/quality-scorecard.ts +0 -272
  124. package/src/commands/remediation-output.ts +0 -66
  125. package/src/commands/rulecode.ts +0 -465
  126. package/src/commands/run.ts +0 -89
  127. package/src/commands/runtime-activation.ts +0 -1629
  128. package/src/commands/runtime-artifact-repair.ts +0 -524
  129. package/src/commands/runtime-canary.ts +0 -395
  130. package/src/commands/runtime-compatibility-scan.ts +0 -105
  131. package/src/commands/runtime-diagnostics-export.ts +0 -229
  132. package/src/commands/runtime-features.ts +0 -153
  133. package/src/commands/runtime-gfi-snapshot.ts +0 -135
  134. package/src/commands/runtime-health-snapshot.ts +0 -108
  135. package/src/commands/runtime-init.ts +0 -429
  136. package/src/commands/runtime-internalization-enqueue-successors.ts +0 -530
  137. package/src/commands/runtime-internalization-integrity-repair.ts +0 -79
  138. package/src/commands/runtime-internalization-integrity.ts +0 -107
  139. package/src/commands/runtime-internalization-queue.ts +0 -135
  140. package/src/commands/runtime-internalization-retry.ts +0 -191
  141. package/src/commands/runtime-internalization-run-once.ts +0 -791
  142. package/src/commands/runtime-internalization-run-rulehost.ts +0 -749
  143. package/src/commands/runtime-internalization-wake-once.ts +0 -87
  144. package/src/commands/runtime-pain-flood-simulation.ts +0 -121
  145. package/src/commands/runtime-pruning.ts +0 -438
  146. package/src/commands/runtime-recovery-failed-tasks.ts +0 -258
  147. package/src/commands/runtime-recovery.ts +0 -109
  148. package/src/commands/runtime-synthetic-baseline.ts +0 -70
  149. package/src/commands/runtime-uat.guard.test.ts +0 -175
  150. package/src/commands/runtime-uat.ts +0 -380
  151. package/src/commands/runtime.ts +0 -473
  152. package/src/commands/samples-list.ts +0 -39
  153. package/src/commands/samples-review.ts +0 -36
  154. package/src/commands/task.ts +0 -271
  155. package/src/commands/telemetry.ts +0 -349
  156. package/src/commands/trace.ts +0 -174
  157. package/src/commands/trajectory-db-unavailable.ts +0 -19
  158. package/src/commands/trajectory.ts +0 -64
  159. package/src/commands/version.ts +0 -49
  160. package/src/config-reader.ts +0 -122
  161. package/src/index.ts +0 -1276
  162. package/src/legacy/legacy-import.ts +0 -179
  163. package/src/legacy/session-history-import.ts +0 -203
  164. package/src/resolve-workspace.ts +0 -106
  165. package/src/services/__tests__/cli-output.test.ts +0 -130
  166. package/src/services/__tests__/evaluator-runner-deps.test.ts +0 -382
  167. package/src/services/__tests__/rulehost-readiness.test.ts +0 -363
  168. package/src/services/__tests__/runtime-adapter-resolver.test.ts +0 -793
  169. package/src/services/cli-output.ts +0 -95
  170. package/src/services/config-doctor.ts +0 -697
  171. package/src/services/console-launcher.ts +0 -537
  172. package/src/services/demo-rule-compiler.ts +0 -40
  173. package/src/services/demo-story-a-runner.ts +0 -471
  174. package/src/services/mainline-snapshot-assembler.ts +0 -579
  175. package/src/services/pain-flood-simulation-runner.ts +0 -462
  176. package/src/services/pd-config-loader.ts +0 -433
  177. package/src/services/proven-channel-baseline-runner.ts +0 -157
  178. package/src/services/quality-scorecard/data-extractor.ts +0 -150
  179. package/src/services/quality-scorecard/local-evaluator.ts +0 -142
  180. package/src/services/quality-scorecard/strong-model-gate.ts +0 -202
  181. package/src/services/resolve-runtime-from-pd-config.ts +0 -230
  182. package/src/services/rulehost-pipeline-runner.ts +0 -1216
  183. package/src/services/rulehost-readiness.ts +0 -326
  184. package/src/services/runtime-adapter-resolver.ts +0 -364
  185. package/src/services/synthetic-baseline-runner.ts +0 -400
  186. package/src/services/version-report.ts +0 -253
  187. package/src/services/workspace-tool-semantics.ts +0 -26
  188. package/src/utils/path-security.ts +0 -96
  189. package/src/utils/production-workspace-guard.test.ts +0 -157
  190. package/src/utils/production-workspace-guard.ts +0 -210
  191. package/tests/bdd/cli-contract.steps.ts +0 -346
  192. package/tests/bdd/principles-stats.steps.ts +0 -211
  193. package/tests/bdd/support/gherkin-loader.ts +0 -147
  194. package/tests/bdd/support/repo-root.ts +0 -62
  195. package/tests/bdd/support/vitest-bdd.ts +0 -179
  196. package/tests/commands/admission-gate-coverage.test.ts +0 -79
  197. package/tests/commands/build-trajectory-evidence.test.ts +0 -508
  198. package/tests/commands/candidate-audit-repair.test.ts +0 -421
  199. package/tests/commands/candidate-intake.test.ts +0 -732
  200. package/tests/commands/candidate-internalization-backfill.test.ts +0 -548
  201. package/tests/commands/candidate-internalize-lineage.test.ts +0 -565
  202. package/tests/commands/candidate-internalize.test.ts +0 -299
  203. package/tests/commands/candidate-route.test.ts +0 -329
  204. package/tests/commands/candidate-show.test.ts +0 -95
  205. package/tests/commands/cli-command-tree.test.ts +0 -144
  206. package/tests/commands/cli-help-snapshot.test.ts +0 -155
  207. package/tests/commands/cli-skill-contract.test.ts +0 -121
  208. package/tests/commands/codex-consent-reversibility.steps.test.ts +0 -299
  209. package/tests/commands/codex-ingest-quarantine.test.ts +0 -136
  210. package/tests/commands/codex-setup.test.ts +0 -297
  211. package/tests/commands/codex-worker-daemon.test.ts +0 -95
  212. package/tests/commands/codex-worker-registration.test.ts +0 -207
  213. package/tests/commands/config-doctor.test.ts +0 -336
  214. package/tests/commands/console-launcher-edge-cases.test.ts +0 -388
  215. package/tests/commands/console-open.test.ts +0 -1381
  216. package/tests/commands/context.test.ts +0 -114
  217. package/tests/commands/demo-story-a.test.ts +0 -318
  218. package/tests/commands/diagnose.test.ts +0 -1803
  219. package/tests/commands/errors-list.test.ts +0 -679
  220. package/tests/commands/evolution-tasks-list.test.ts +0 -41
  221. package/tests/commands/evolution-tasks-show.test.ts +0 -46
  222. package/tests/commands/health-codex.test.ts +0 -349
  223. package/tests/commands/health-host-wiring.test.ts +0 -76
  224. package/tests/commands/health-reliability.test.ts +0 -99
  225. package/tests/commands/health.test.ts +0 -413
  226. package/tests/commands/intent.test.ts +0 -321
  227. package/tests/commands/legacy-cleanup.test.ts +0 -148
  228. package/tests/commands/pain-evidence.test.ts +0 -518
  229. package/tests/commands/pain-list.test.ts +0 -219
  230. package/tests/commands/pain-record-async.test.ts +0 -335
  231. package/tests/commands/pain-record-session-parser.test.ts +0 -228
  232. package/tests/commands/pain-record.test.ts +0 -851
  233. package/tests/commands/pain-retry.test.ts +0 -1121
  234. package/tests/commands/plugin-config-resolution-cutover.test.ts +0 -229
  235. package/tests/commands/pri-393-runtime-config-unification.test.ts +0 -443
  236. package/tests/commands/principles-stats-wiring.test.ts +0 -135
  237. package/tests/commands/principles-stats.test.ts +0 -274
  238. package/tests/commands/product-path-regression.test.ts +0 -86
  239. package/tests/commands/proven-channel-baseline.test.ts +0 -441
  240. package/tests/commands/rulecode.test.ts +0 -177
  241. package/tests/commands/run-rulehost-handler.test.ts +0 -908
  242. package/tests/commands/runtime-activation-approve-flag-wiring.test.ts +0 -227
  243. package/tests/commands/runtime-activation-deactivate-flag-wiring.test.ts +0 -167
  244. package/tests/commands/runtime-activation-dispatch-flag-wiring.test.ts +0 -262
  245. package/tests/commands/runtime-activation-governance-audit.test.ts +0 -95
  246. package/tests/commands/runtime-activation-list-flag-wiring.test.ts +0 -193
  247. package/tests/commands/runtime-activation-promote-flag-wiring.test.ts +0 -248
  248. package/tests/commands/runtime-activation-shadow-telemetry.test.ts +0 -130
  249. package/tests/commands/runtime-activation.test.ts +0 -2052
  250. package/tests/commands/runtime-artifact-repair-registration.test.ts +0 -74
  251. package/tests/commands/runtime-artifact-repair.test.ts +0 -404
  252. package/tests/commands/runtime-canary.test.ts +0 -430
  253. package/tests/commands/runtime-compatibility-scan.test.ts +0 -146
  254. package/tests/commands/runtime-diagnostics-export.test.ts +0 -175
  255. package/tests/commands/runtime-features.test.ts +0 -249
  256. package/tests/commands/runtime-health-snapshot.test.ts +0 -358
  257. package/tests/commands/runtime-init-empty-workspace.test.ts +0 -252
  258. package/tests/commands/runtime-init.test.ts +0 -420
  259. package/tests/commands/runtime-internalization-enqueue-successors.test.ts +0 -782
  260. package/tests/commands/runtime-internalization-integrity-repair.test.ts +0 -239
  261. package/tests/commands/runtime-internalization-integrity.test.ts +0 -140
  262. package/tests/commands/runtime-internalization-queue.test.ts +0 -380
  263. package/tests/commands/runtime-internalization-retry-owner-authority.test.ts +0 -431
  264. package/tests/commands/runtime-internalization-run-once-evaluator-parity.test.ts +0 -269
  265. package/tests/commands/runtime-internalization-run-once-language.test.ts +0 -303
  266. package/tests/commands/runtime-internalization-run-once-real-config.test.ts +0 -237
  267. package/tests/commands/runtime-internalization-run-once-rollout-parity.test.ts +0 -706
  268. package/tests/commands/runtime-internalization-run-once.test.ts +0 -1791
  269. package/tests/commands/runtime-internalization-wake-once.test.ts +0 -171
  270. package/tests/commands/runtime-internalization.test.ts +0 -53
  271. package/tests/commands/runtime-pain-flood-simulation.test.ts +0 -418
  272. package/tests/commands/runtime-pruning.test.ts +0 -694
  273. package/tests/commands/runtime-recovery-failed-tasks.test.ts +0 -328
  274. package/tests/commands/runtime-recovery.test.ts +0 -120
  275. package/tests/commands/runtime-synthetic-baseline.test.ts +0 -249
  276. package/tests/commands/runtime-uat.test.ts +0 -397
  277. package/tests/commands/runtime.test.ts +0 -392
  278. package/tests/commands/samples-list.test.ts +0 -43
  279. package/tests/commands/samples-review.test.ts +0 -41
  280. package/tests/commands/task.test.ts +0 -153
  281. package/tests/commands/telemetry.test.ts +0 -190
  282. package/tests/commands/trace.test.ts +0 -316
  283. package/tests/config-reader.test.ts +0 -143
  284. package/tests/e2e/candidate-intake-e2e.test.ts +0 -338
  285. package/tests/e2e/cli-full-flow.test.ts +0 -233
  286. package/tests/e2e/cross-package-acceptance.test.ts +0 -635
  287. package/tests/helpers/pd-cli-path.ts +0 -5
  288. package/tests/pd-cli-smoke.test.ts +0 -13
  289. package/tests/resolve-workspace.test.ts +0 -196
  290. package/tests/services/config-doctor-signal-health.test.ts +0 -109
  291. package/tests/services/console-launcher.test.ts +0 -114
  292. package/tests/services/demo-rule-compiler.test.ts +0 -242
  293. package/tests/services/mainline-snapshot-assembler.test.ts +0 -572
  294. package/tests/services/pd-config-loader.test.ts +0 -505
  295. package/tests/services/proven-channel-baseline-runner.test.ts +0 -30
  296. package/tests/services/quality-scorecard/strong-model-gate.test.ts +0 -133
  297. package/tests/services/resolve-runtime-from-pd-config.test.ts +0 -485
  298. package/tests/services/rulehost-pipeline-e2e.test.ts +0 -538
  299. package/tests/services/rulehost-pipeline-runner.test.ts +0 -1175
  300. package/tests/services/workspace-tool-semantics.test.ts +0 -76
  301. package/tests/utils/path-security.test.ts +0 -180
  302. package/tsconfig.json +0 -26
  303. package/vitest.config.ts +0 -9
@@ -1,524 +0,0 @@
1
- /**
2
- * PRI-555 phase 1 — artifact identity drift repair planner (DRY-RUN ONLY).
3
- *
4
- * Historical scribe artifacts were written under an older task-id naming
5
- * scheme (`artificer-scribe-…-<chan>×4`); re-seeded chains reference scribe
6
- * tasks under the current scheme (`scribe-…-<chan>×3`). The artificer-family
7
- * resolvers do exact source_task_id lookups, so those artifacts are
8
- * unreachable and 63 tasks failed permanently with input_invalid.
9
- *
10
- * This command ONLY builds a repair plan (migration-plan.json). It never
11
- * mutates state.db: the connection is opened readonly with
12
- * bootstrapIfMissing=false (ERR-023 — dry-run must not open writable DBs,
13
- * and must not create an empty state.db as a side effect).
14
- *
15
- * Repair rules (deliberately conservative — no fuzzy matching):
16
- * - Rule 1 (remap): a `principle` artifact exists whose source_task_id carries
17
- * the SAME normalized role chain, the SAME full UUID token, AND the SAME
18
- * trailing channel token as the dependency task id (e.g. a legacy channel
19
- * repetition-count variant of the dependency's own key). Full-token equality
20
- * on all three, not substring/prefix guessing. Exactly one match →
21
- * high-confidence re-key proposal. Downstream-stage artifacts of the same
22
- * chain (extra role prefixes like `artificer-…`/`evaluator-…`) do NOT match —
23
- * re-keying them would feed a later stage's output into an earlier slot.
24
- * - Rule 2 (reconstruct): no artifact found, but the dependency task has a
25
- * succeeded run with non-empty output_payload → medium-confidence artifact
26
- * reconstruction proposal.
27
- * - Anything ambiguous or unconfirmable → needs_human_review. We never guess.
28
- *
29
- * CLI gates: cli-1 (strict JSON), cli-2 (exit + return), cli-4 (dry-run
30
- * default, --confirm refused in this phase), cli-5 (failure path writes
31
- * nothing to the DB), cli-6 (structured reason + nextAction).
32
- */
33
- import * as fs from 'fs';
34
- import * as path from 'path';
35
- import type { Database } from 'better-sqlite3';
36
- import { SqliteConnection } from '@principles/core/runtime-v2';
37
- import { resolveWorkspaceDir } from '../resolve-workspace.js';
38
- import { emitResult, emitError, emitFlagConflict } from '../services/cli-output.js';
39
-
40
- interface ArtifactRepairOptions {
41
- workspace?: string;
42
- dryRun?: boolean;
43
- confirm?: boolean;
44
- out?: string;
45
- json?: boolean;
46
- }
47
-
48
- // ── Plan types (migration-plan.json contract) ────────────────────────────────
49
-
50
- export type ArtifactRepairAction =
51
- | 'remap_source_task_id'
52
- | 'reconstruct_from_run_payload'
53
- | 'needs_human_review';
54
-
55
- export type ArtifactRepairSource =
56
- | 'old_key_uuid_match'
57
- | 'run_output_payload'
58
- | 'direct_key'
59
- | 'none';
60
-
61
- export interface ArtifactRepairPlanEntry {
62
- failed_task_id: string;
63
- failed_task_kind: string;
64
- dependency_task_id: string;
65
- existing_artifact: {
66
- artifact_id: string;
67
- artifact_kind: string;
68
- source_task_id: string;
69
- } | null;
70
- artifact_source: ArtifactRepairSource;
71
- repair_action: ArtifactRepairAction;
72
- confidence: 'high' | 'medium' | null;
73
- reason: string;
74
- proposal: {
75
- action: 'remap_source_task_id' | 'reconstruct_from_run_payload';
76
- artifact_id?: string;
77
- old_source_task_id?: string;
78
- new_source_task_id?: string;
79
- run_id?: string;
80
- artifact_kind?: string;
81
- validation_status?: string;
82
- } | null;
83
- unresolved_dep_count: number;
84
- }
85
-
86
- export interface ArtifactRepairPlanSummary {
87
- scanned_failed_tasks: number;
88
- rule1_remap: number;
89
- rule2_reconstruct: number;
90
- needs_human_review: number;
91
- }
92
-
93
- export interface ArtifactRepairPlan {
94
- generatedAt: string;
95
- workspace: string;
96
- dryRun: true;
97
- summary: ArtifactRepairPlanSummary;
98
- entries: ArtifactRepairPlanEntry[];
99
- }
100
-
101
- // ── Untrusted-row helpers (rc-1/rc-4/rc-5) ───────────────────────────────────
102
-
103
- function isRecord(value: unknown): value is Record<string, unknown> {
104
- return typeof value === 'object' && value !== null && !Array.isArray(value);
105
- }
106
-
107
- function readString(row: unknown, key: string): string | null {
108
- if (!isRecord(row)) return null;
109
- if (!Object.hasOwn(row, key)) return null;
110
- const value = row[key];
111
- return typeof value === 'string' ? value : null;
112
- }
113
-
114
- const BOUNDED_FIELD_MAX = 200;
115
-
116
- function bounded(value: string | null): string | null {
117
- if (value === null) return null;
118
- return value.length <= BOUNDED_FIELD_MAX ? value : value.substring(0, BOUNDED_FIELD_MAX);
119
- }
120
-
121
- const FULL_UUID_RE = /[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/g;
122
-
123
- /** Extract the FIRST full canonical UUID token; null when the id has none. */
124
- function extractFullUuid(id: string): string | null {
125
- for (const match of id.toLowerCase().matchAll(FULL_UUID_RE)) {
126
- return match[0];
127
- }
128
- return null;
129
- }
130
-
131
- /**
132
- * Extract the trailing repeated channel token (e.g. `prompt` from
133
- * `…-prompt-prompt-prompt`). Task ids end with the channel token repeated;
134
- * requiring equality on UUID and channel disambiguates same-chain tasks
135
- * across channels without any fuzzy matching.
136
- */
137
- function extractTrailingChannelToken(id: string): string | null {
138
- const segments = id.split('-');
139
- const last = segments[segments.length - 1];
140
- return last ? last : null;
141
- }
142
-
143
- /**
144
- * Normalize an id to its role chain: strip the UUID token and the trailing
145
- * repeated channel tokens. `scribe-philosopher-dreamer-<uuid>-prompt×3` →
146
- * `scribe-philosopher-dreamer`; `artificer-scribe-philosopher-dreamer-<uuid>-
147
- * prompt×4` → `artificer-scribe-philosopher-dreamer` (a DIFFERENT stage).
148
- * Rule 1 requires this to be equal so downstream-stage artifacts of the same
149
- * chain are never re-keyed into an earlier stage's slot.
150
- */
151
- function normalizeRoleChain(id: string): string {
152
- const withoutUuid = id.replace(FULL_UUID_RE, '');
153
- const segments = withoutUuid.split('-').filter((t) => t.length > 0);
154
- if (segments.length > 1) {
155
- const last = segments[segments.length - 1];
156
- let i = segments.length;
157
- while (i > 1 && segments[i - 1] === last) i -= 1;
158
- segments.length = i;
159
- }
160
- return segments.join('-');
161
- }
162
-
163
- /** Dependency kinds whose pi_artifacts feed downstream runners. */
164
- const PRODUCER_DEP_KINDS: ReadonlySet<string> = new Set(['dreamer', 'philosopher', 'scribe', 'artificer']);
165
-
166
- function extractDependencyTaskIds(diagnosticJson: string | null): { ok: true; ids: string[] } | { ok: false; reason: string } {
167
- if (!diagnosticJson) return { ok: false, reason: 'tasks.diagnostic_json is null' };
168
- let parsed: unknown;
169
- try {
170
- parsed = JSON.parse(diagnosticJson);
171
- } catch (err) {
172
- return { ok: false, reason: `diagnostic_json is not valid JSON: ${err instanceof Error ? err.message : String(err)}` };
173
- }
174
- if (!isRecord(parsed)) return { ok: false, reason: 'diagnostic_json is not an object' };
175
- if (!Object.hasOwn(parsed, 'pi_metadata')) return { ok: false, reason: 'diagnostic_json missing pi_metadata' };
176
- const meta: unknown = parsed.pi_metadata;
177
- if (!isRecord(meta)) return { ok: false, reason: 'pi_metadata is not an object' };
178
- if (!Object.hasOwn(meta, 'dependencyTaskIds')) return { ok: false, reason: 'pi_metadata missing dependencyTaskIds' };
179
- const deps: unknown = meta.dependencyTaskIds;
180
- if (!Array.isArray(deps)) return { ok: false, reason: 'dependencyTaskIds is not an array' };
181
- const ids = deps.filter((d): d is string => typeof d === 'string');
182
- if (ids.length === 0) return { ok: false, reason: 'dependencyTaskIds is empty or contains no string elements' };
183
- return { ok: true, ids };
184
- }
185
-
186
- // ── Plan builder ──────────────────────────────────────────────────────────────
187
-
188
- interface DepTaskRow {
189
- taskId: string;
190
- taskKind: string | null;
191
- status: string | null;
192
- }
193
-
194
- function loadDepTask(db: Database, taskId: string): DepTaskRow | null {
195
- const row: unknown = db
196
- .prepare('SELECT task_id, task_kind, status FROM tasks WHERE task_id = ?')
197
- .get(taskId);
198
- if (!isRecord(row)) return null;
199
- const id = readString(row, 'task_id');
200
- if (!id) return null;
201
- return { taskId: id, taskKind: readString(row, 'task_kind'), status: readString(row, 'status') };
202
- }
203
-
204
- function countDirectArtifacts(db: Database, depTaskId: string): number {
205
- const row: unknown = db
206
- .prepare("SELECT COUNT(*) AS c FROM pi_artifacts WHERE source_task_id = ? AND artifact_kind = 'principle'")
207
- .get(depTaskId);
208
- if (!isRecord(row) || !Object.hasOwn(row, 'c')) return 0;
209
- const { c } = row;
210
- return typeof c === 'number' ? c : 0;
211
- }
212
-
213
- interface CandidateArtifact {
214
- artifactId: string;
215
- sourceTaskId: string;
216
- }
217
-
218
- function findOldKeyCandidates(
219
- db: Database,
220
- depTaskId: string,
221
- ): CandidateArtifact[] {
222
- const depUuid = extractFullUuid(depTaskId);
223
- const depChannel = extractTrailingChannelToken(depTaskId);
224
- const depRoleChain = normalizeRoleChain(depTaskId);
225
- if (!depUuid || !depChannel) return [];
226
-
227
- const rows: unknown[] = db
228
- .prepare("SELECT artifact_id, source_task_id FROM pi_artifacts WHERE artifact_kind = 'principle'")
229
- .all();
230
- const candidates: CandidateArtifact[] = [];
231
- for (const row of rows) {
232
- if (!isRecord(row)) continue;
233
- const artifactId = readString(row, 'artifact_id');
234
- const sourceTaskId = readString(row, 'source_task_id');
235
- if (!artifactId || !sourceTaskId) continue;
236
- if (sourceTaskId === depTaskId) continue; // direct key handled separately
237
- if (extractFullUuid(sourceTaskId) !== depUuid) continue; // exact full-UUID equality
238
- if (extractTrailingChannelToken(sourceTaskId) !== depChannel) continue;
239
- if (normalizeRoleChain(sourceTaskId) !== depRoleChain) continue; // same producer stage only
240
- candidates.push({ artifactId, sourceTaskId });
241
- }
242
- return candidates;
243
- }
244
-
245
- function findSucceededRunPayload(
246
- db: Database,
247
- depTaskId: string,
248
- ): { runId: string } | null {
249
- const row: unknown = db
250
- .prepare(
251
- `SELECT run_id FROM runs
252
- WHERE task_id = ? AND execution_status = 'succeeded'
253
- AND output_payload IS NOT NULL AND TRIM(output_payload) != ''
254
- ORDER BY started_at DESC, attempt_number DESC
255
- LIMIT 1`,
256
- )
257
- .get(depTaskId);
258
- if (!isRecord(row)) return null;
259
- const runId = readString(row, 'run_id');
260
- return runId ? { runId } : null;
261
- }
262
-
263
- function humanReviewEntry(input: {
264
- failedTaskId: string;
265
- failedTaskKind: string;
266
- dependencyTaskId: string;
267
- reason: string;
268
- unresolvedDepCount: number;
269
- }): ArtifactRepairPlanEntry {
270
- return {
271
- failed_task_id: input.failedTaskId,
272
- failed_task_kind: input.failedTaskKind,
273
- dependency_task_id: input.dependencyTaskId,
274
- existing_artifact: null,
275
- artifact_source: 'none',
276
- repair_action: 'needs_human_review',
277
- confidence: null,
278
- reason: bounded(input.reason) ?? input.reason,
279
- proposal: null,
280
- unresolved_dep_count: input.unresolvedDepCount,
281
- };
282
- }
283
-
284
- /**
285
- * Build the dry-run repair plan. `db` must come from a readonly connection —
286
- * this function executes SELECTs only and never mutates state.
287
- */
288
- export function buildArtifactRepairPlan(
289
- db: Database,
290
- opts: { workspaceDir: string; generatedAt: string },
291
- ): ArtifactRepairPlan {
292
- const failedTasks: unknown[] = db
293
- .prepare(
294
- `SELECT task_id, task_kind, last_error, diagnostic_json FROM tasks
295
- WHERE task_kind IN ('dreamer', 'philosopher', 'scribe', 'artificer', 'evaluator')
296
- AND status = 'failed' AND last_error = 'input_invalid'`,
297
- )
298
- .all();
299
-
300
- const entries: ArtifactRepairPlanEntry[] = [];
301
-
302
- for (const failedRow of failedTasks) {
303
- if (!isRecord(failedRow)) continue;
304
- const failedTaskId = readString(failedRow, 'task_id');
305
- const failedTaskKind = readString(failedRow, 'task_kind') ?? 'unknown';
306
- if (!failedTaskId) continue;
307
-
308
- const deps = extractDependencyTaskIds(readString(failedRow, 'diagnostic_json'));
309
- if (!deps.ok) {
310
- entries.push(humanReviewEntry({
311
- failedTaskId,
312
- failedTaskKind,
313
- dependencyTaskId: '',
314
- reason: deps.reason,
315
- unresolvedDepCount: 0,
316
- }));
317
- continue;
318
- }
319
-
320
- // First producer dependency whose artifact cannot be resolved by the
321
- // exact-key lookup is the repair target; count the rest.
322
- let blocker: {
323
- depTaskId: string;
324
- depTask: DepTaskRow | null;
325
- directArtifacts: number;
326
- } | null = null;
327
- let unresolvedDepCount = 0;
328
-
329
- for (const depTaskId of deps.ids) {
330
- const depTask = loadDepTask(db, depTaskId);
331
- const depKind = depTask?.taskKind;
332
- if (!depTask || !depKind || !PRODUCER_DEP_KINDS.has(depKind)) continue; // resolver ignores non-producer deps
333
- const directArtifacts = countDirectArtifacts(db, depTaskId);
334
- if (directArtifacts > 0) continue; // resolvable — not a blocker
335
- unresolvedDepCount++;
336
- if (!blocker) blocker = { depTaskId, depTask, directArtifacts };
337
- }
338
-
339
- if (!blocker) {
340
- entries.push(humanReviewEntry({
341
- failedTaskId,
342
- failedTaskKind,
343
- dependencyTaskId: '',
344
- reason: 'no unresolved producer dependency found — input_invalid has another cause; inspect the task runs',
345
- unresolvedDepCount: 0,
346
- }));
347
- continue;
348
- }
349
-
350
- const { depTaskId, depTask } = blocker;
351
-
352
- if (!depTask || depTask.status !== 'succeeded') {
353
- const status = depTask?.status ?? 'missing';
354
- entries.push(humanReviewEntry({
355
- failedTaskId,
356
- failedTaskKind,
357
- dependencyTaskId: depTaskId,
358
- reason: `producer dependency task is ${status} — repair requires re-running the dependency, not artifact migration`,
359
- unresolvedDepCount,
360
- }));
361
- continue;
362
- }
363
-
364
- // Rule 1: unique old-key artifact with identical full UUID + channel token.
365
- const candidates = findOldKeyCandidates(db, depTaskId);
366
- const [candidate] = candidates;
367
- if (candidates.length === 1 && candidate) {
368
- entries.push({
369
- failed_task_id: failedTaskId,
370
- failed_task_kind: failedTaskKind,
371
- dependency_task_id: depTaskId,
372
- existing_artifact: {
373
- artifact_id: candidate.artifactId,
374
- artifact_kind: 'principle',
375
- source_task_id: candidate.sourceTaskId,
376
- },
377
- artifact_source: 'old_key_uuid_match',
378
- repair_action: 'remap_source_task_id',
379
- confidence: 'high',
380
- reason: `principle artifact exists under a legacy key with identical role-chain+UUID+channel tokens; propose re-keying source_task_id ${candidate.sourceTaskId} → ${depTaskId}`,
381
- proposal: {
382
- action: 'remap_source_task_id',
383
- artifact_id: candidate.artifactId,
384
- old_source_task_id: candidate.sourceTaskId,
385
- new_source_task_id: depTaskId,
386
- },
387
- unresolved_dep_count: unresolvedDepCount,
388
- });
389
- continue;
390
- }
391
- if (candidates.length > 1) {
392
- entries.push(humanReviewEntry({
393
- failedTaskId,
394
- failedTaskKind,
395
- dependencyTaskId: depTaskId,
396
- reason: `ambiguous legacy artifacts: ${candidates.length} principle rows share the dependency's role-chain+UUID+channel tokens (${candidates.map((c) => c.artifactId).join(', ')})`,
397
- unresolvedDepCount,
398
- }));
399
- continue;
400
- }
401
-
402
- // Rule 2: reconstruct from the dependency's succeeded run payload.
403
- const run = findSucceededRunPayload(db, depTaskId);
404
- if (run) {
405
- entries.push({
406
- failed_task_id: failedTaskId,
407
- failed_task_kind: failedTaskKind,
408
- dependency_task_id: depTaskId,
409
- existing_artifact: null,
410
- artifact_source: 'run_output_payload',
411
- repair_action: 'reconstruct_from_run_payload',
412
- confidence: 'medium',
413
- reason: `no principle artifact under any key, but succeeded run ${run.runId} has output_payload; propose reconstructing a principle artifact for ${depTaskId}`,
414
- proposal: {
415
- action: 'reconstruct_from_run_payload',
416
- run_id: run.runId,
417
- new_source_task_id: depTaskId,
418
- artifact_kind: 'principle',
419
- validation_status: 'pending',
420
- },
421
- unresolved_dep_count: unresolvedDepCount,
422
- });
423
- continue;
424
- }
425
-
426
- entries.push(humanReviewEntry({
427
- failedTaskId,
428
- failedTaskKind,
429
- dependencyTaskId: depTaskId,
430
- reason: 'no principle artifact under any resolvable key and no succeeded run output_payload to reconstruct from',
431
- unresolvedDepCount,
432
- }));
433
- }
434
-
435
- const summary: ArtifactRepairPlanSummary = {
436
- scanned_failed_tasks: entries.length,
437
- rule1_remap: entries.filter((e) => e.repair_action === 'remap_source_task_id').length,
438
- rule2_reconstruct: entries.filter((e) => e.repair_action === 'reconstruct_from_run_payload').length,
439
- needs_human_review: entries.filter((e) => e.repair_action === 'needs_human_review').length,
440
- };
441
-
442
- return {
443
- generatedAt: opts.generatedAt,
444
- workspace: opts.workspaceDir,
445
- dryRun: true,
446
- summary,
447
- entries,
448
- };
449
- }
450
-
451
- // ── CLI handler ───────────────────────────────────────────────────────────────
452
-
453
- interface ArtifactRepairCliResult {
454
- ok: true;
455
- dryRun: true;
456
- planFile: string;
457
- summary: ArtifactRepairPlanSummary;
458
- nextAction: string;
459
- }
460
-
461
- function formatTextOutput(output: ArtifactRepairCliResult): string {
462
- const lines: string[] = [];
463
- lines.push(`Artifact Repair (dry-run, PRI-555 phase 1)`);
464
- lines.push(` plan file: ${output.planFile}`);
465
- lines.push(` scanned failed: ${output.summary.scanned_failed_tasks}`);
466
- lines.push(` Rule-1 remap: ${output.summary.rule1_remap}`);
467
- lines.push(` Rule-2 reconstruct: ${output.summary.rule2_reconstruct}`);
468
- lines.push(` needs human review: ${output.summary.needs_human_review}`);
469
- lines.push(` next action: ${output.nextAction}`);
470
- return lines.join('\n');
471
- }
472
-
473
- export async function handleRuntimeArtifactRepair(opts: ArtifactRepairOptions): Promise<void> {
474
- if (opts.dryRun && opts.confirm) {
475
- const exitCode = emitFlagConflict({ json: opts.json ?? false });
476
- process.exit(exitCode);
477
- return;
478
- }
479
- if (opts.confirm) {
480
- // PRI-555 phase 1 is dry-run only: applying a plan mutates production
481
- // state.db and must stay a deliberate, owner-approved follow-up.
482
- const reason = '--confirm is not implemented: artifact repair ships dry-run only in PRI-555 phase 1';
483
- const nextAction = 'Review migration-plan.json with the owner; apply confirmed entries via the runbook in docs/fix/pri-554-556-555-fix-report.md.';
484
- if (opts.json ?? false) {
485
- console.log(JSON.stringify({ ok: false, reason, nextAction }, null, 2));
486
- } else {
487
- console.error(`Error: ${reason}`);
488
- console.error(`Next action: ${nextAction}`);
489
- }
490
- process.exit(1);
491
- return;
492
- }
493
-
494
- const workspaceDir = opts.workspace ? path.resolve(opts.workspace) : resolveWorkspaceDir();
495
- const planPath = opts.out ? path.resolve(opts.out) : path.join(process.cwd(), 'migration-plan.json');
496
-
497
- // ERR-023: dry-run opens the DB readonly, and must not bootstrap an empty
498
- // state.db either — a missing state.db is an error, not a fresh workspace.
499
- let conn: SqliteConnection | null = null;
500
- try {
501
- conn = new SqliteConnection({ workspaceDir, readonly: true, bootstrapIfMissing: false });
502
- const plan = buildArtifactRepairPlan(conn.getDb(), {
503
- workspaceDir,
504
- generatedAt: new Date().toISOString(),
505
- });
506
- fs.writeFileSync(planPath, JSON.stringify(plan, null, 2), 'utf8');
507
-
508
- const result: ArtifactRepairCliResult = {
509
- ok: true,
510
- dryRun: true,
511
- planFile: planPath,
512
- summary: plan.summary,
513
- nextAction: 'Review migration-plan.json (Rule-1 remap proposals first). Nothing has been modified; wait for owner confirmation before applying.',
514
- };
515
- emitResult(result, { json: opts.json ?? false, formatText: formatTextOutput });
516
- } catch (err) {
517
- process.exitCode = emitError(err, {
518
- json: opts.json ?? false,
519
- nextAction: 'Verify --workspace points to a workspace with an initialized .pd/state.db (pd runtime init), then retry.',
520
- });
521
- } finally {
522
- try { conn?.close(); } catch { /* best-effort */ }
523
- }
524
- }