@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,1260 +0,0 @@
1
- /**
2
- * pd candidate commands — Principle candidate inspection, intake, audit, repair.
3
- *
4
- * Usage:
5
- * pd candidate list --task-id <taskId> --workspace <path> [--json]
6
- * pd candidate show <candidateId> --workspace <path> [--json]
7
- * pd candidate intake --candidate-id <id> [--workspace <path>] [--json] [--dry-run]
8
- * pd candidate audit --workspace <path> [--json]
9
- * pd candidate repair --candidate-id <id> --workspace <path> [--json]
10
- * pd candidate route --candidate-id <id> --workspace <path> [--json]
11
- */
12
- import { randomUUID } from 'crypto';
13
- import * as path from 'path';
14
- import {
15
- RuntimeStateManager,
16
- SqliteConnection,
17
- candidateList,
18
- candidateShow,
19
- CandidateIntakeService,
20
- CandidateIntakeError,
21
- decideInternalizationRoute,
22
- buildDreamerSeedFromCandidate,
23
- findExistingDreamerTask,
24
- PrincipleTreeLedgerAdapter,
25
- type LedgerPrincipleEntry,
26
- } from '@principles/core/runtime-v2';
27
- import { loadLedger, getLedgerFilePathPublic } from '@principles/core/principle-tree-ledger';
28
- import { resolveWorkspaceDir } from '../resolve-workspace.js';
29
- import { resolvePromptFullPipelineSeedMode } from '../services/pd-config-loader.js';
30
- import { createRemediationResult, remediationAction } from './remediation-output.js';
31
- import type { RemediationResult } from './remediation-output.js';
32
- import { checkAdmissionGate } from './admission-gate.js';
33
-
34
- // ── Interfaces ────────────────────────────────────────────────────────────────
35
-
36
- interface CandidateListOptions {
37
- taskId: string;
38
- workspace?: string;
39
- json?: boolean;
40
- }
41
-
42
- interface CandidateShowOptions {
43
- candidateId: string;
44
- workspace?: string;
45
- json?: boolean;
46
- }
47
-
48
- interface CandidateIntakeOptions {
49
- candidateId: string;
50
- workspace?: string;
51
- json?: boolean;
52
- dryRun?: boolean;
53
- }
54
-
55
- interface CandidateAuditOptions {
56
- workspace?: string;
57
- json?: boolean;
58
- }
59
-
60
- interface CandidateRepairOptions {
61
- candidateId: string;
62
- workspace?: string;
63
- json?: boolean;
64
- }
65
-
66
- interface AuditResult {
67
- status: 'ok' | 'degraded';
68
- consumedCount: number;
69
- missingLedgerEntryIds: string[];
70
- checkedLedgerPath: string;
71
- checkedDbPath: string;
72
- }
73
-
74
- // ── Shared helpers ───────────────────────────────────────────────────────────
75
-
76
- /** Update candidate status. Sets consumed_at when status='consumed'. */
77
- interface UpdateCandidateStatusOptions {
78
- stateManager: RuntimeStateManager;
79
- candidateId: string;
80
- targetStatus: string;
81
- expectedCurrentStatus?: string;
82
- }
83
-
84
- async function updateCandidateStatus(opts: UpdateCandidateStatusOptions): Promise<void> {
85
- const { stateManager, candidateId, targetStatus, expectedCurrentStatus } = opts;
86
- const db = stateManager.connection;
87
- const now = new Date().toISOString();
88
- if (targetStatus === 'consumed') {
89
- const result = db.getDb().prepare(
90
- 'UPDATE principle_candidates SET status = ?, consumed_at = ? WHERE candidate_id = ? AND status = ?'
91
- ).run(targetStatus, now, candidateId, expectedCurrentStatus ?? targetStatus);
92
- if (result.changes === 0) {
93
- throw new Error(`Guarded transition failed: candidate ${candidateId} is not in expected status '${expectedCurrentStatus ?? targetStatus}'`);
94
- }
95
- } else {
96
- const result = db.getDb().prepare(
97
- 'UPDATE principle_candidates SET status = ? WHERE candidate_id = ? AND status = ?'
98
- ).run(targetStatus, candidateId, expectedCurrentStatus ?? targetStatus);
99
- if (result.changes === 0) {
100
- throw new Error(`Guarded transition failed: candidate ${candidateId} is not in expected status '${expectedCurrentStatus ?? targetStatus}'`);
101
- }
102
- }
103
- }
104
-
105
- /**
106
- * Ensure consumed_at is set for a consumed candidate.
107
- * Returns the consumed_at value (existing or newly written), or null if candidate not found.
108
- */
109
- async function ensureConsumedAt(stateManager: RuntimeStateManager, candidateId: string): Promise<string | null> {
110
- const db = stateManager.connection;
111
- const row = db.getDb().prepare('SELECT consumed_at FROM principle_candidates WHERE candidate_id = ?').get(candidateId) as { consumed_at: string | null } | undefined;
112
- if (!row) return null;
113
- if (row.consumed_at) return row.consumed_at;
114
- const now = new Date().toISOString();
115
- db.getDb().prepare('UPDATE principle_candidates SET consumed_at = ? WHERE candidate_id = ?').run(now, candidateId);
116
- return now;
117
- }
118
-
119
- interface ResolvedRecommendation {
120
- kind: string;
121
- description: string;
122
- triggerPattern?: string;
123
- action?: string;
124
- abstractedPrinciple?: string;
125
- usedFallback: boolean;
126
- }
127
-
128
- /**
129
- * Resolve `sourcePainId` from the canonical diagnostician task chain.
130
- *
131
- * The `CandidateRecord` does not carry `sourcePainId` — it must be resolved by
132
- * looking up the diagnostician task (`candidate.taskId`) and parsing its
133
- * `diagnosticJson`, which contains `sourcePainId` as a top-level key (set by
134
- * `PainSignalBridge.buildDiagnosticJson`).
135
- *
136
- * Runtime Contract:
137
- * - Rule 1: parsed JSON treated as `unknown`
138
- * - Rule 2: no `as` bypass; type narrowing via `typeof` + `Object.hasOwn`
139
- * - Rule 5: `Object.hasOwn` for untrusted key checks
140
- *
141
- * ERR-004: `sourcePainId` resolved from canonical chain, never invented.
142
- *
143
- * @returns The validated `sourcePainId`, or `null` when it cannot be resolved
144
- * (task missing, JSON malformed, field absent, wrong type, or blank).
145
- * Callers at the production boundary must fail loud on `null`.
146
- */
147
- export async function resolveSourcePainIdFromDiagnostician(
148
- stateManager: RuntimeStateManager,
149
- candidate: { taskId?: string; sourceRunId?: string },
150
- ): Promise<string | null> {
151
- const candidateTaskId = candidate.taskId?.trim();
152
- if (!candidateTaskId) return null;
153
-
154
- let diagTask = await stateManager.getTask(candidateTaskId);
155
- if (!diagTask) return null;
156
-
157
- // Production candidates are emitted by diag_router. Resolve its validated
158
- // diagnosisId from the exact source run, then verify the referenced task is
159
- // a diagnostician task before trusting its lineage.
160
- if (diagTask.taskKind === 'diag_router') {
161
- const sourceRunId = candidate.sourceRunId?.trim();
162
- if (!sourceRunId) return null;
163
- const sourceRun = await stateManager.getRun(sourceRunId);
164
- if (!sourceRun || sourceRun.taskId !== candidateTaskId || typeof sourceRun.outputPayload !== 'string') return null;
165
- let routerOutput: unknown;
166
- try {
167
- routerOutput = JSON.parse(sourceRun.outputPayload);
168
- } catch {
169
- return null;
170
- }
171
- if (routerOutput === null || typeof routerOutput !== 'object' || Array.isArray(routerOutput) ||
172
- !Object.hasOwn(routerOutput, 'diagnosisId')) return null;
173
- const diagnosisId = Reflect.get(routerOutput, 'diagnosisId');
174
- if (typeof diagnosisId !== 'string' || diagnosisId.trim() === '') return null;
175
- diagTask = await stateManager.getTask(diagnosisId.trim());
176
- }
177
-
178
- // Reject every non-canonical task kind to prevent cross-chain lineage
179
- // contamination from arbitrary candidate.taskId values.
180
- if (!diagTask || diagTask.taskKind !== 'diagnostician') return null;
181
-
182
- if (typeof diagTask.diagnosticJson !== 'string') return null;
183
-
184
- let parsed: unknown;
185
- try {
186
- parsed = JSON.parse(diagTask.diagnosticJson);
187
- } catch {
188
- return null;
189
- }
190
-
191
- if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) return null;
192
- if (!Object.hasOwn(parsed, 'sourcePainId')) return null;
193
-
194
- const sourcePainId = Reflect.get(parsed, 'sourcePainId');
195
- if (typeof sourcePainId !== 'string' || sourcePainId.trim() === '') return null;
196
-
197
- return sourcePainId.trim();
198
- }
199
-
200
- function resolveCandidateRecommendation(
201
- candidate: { sourceRecommendationJson?: string; description?: string },
202
- stateManager: RuntimeStateManager,
203
- candidateId: string,
204
- ): ResolvedRecommendation {
205
- if (candidate.sourceRecommendationJson) {
206
- try {
207
- const parsed = JSON.parse(candidate.sourceRecommendationJson);
208
- if (parsed?.kind) {
209
- return {
210
- kind: parsed.kind,
211
- description: parsed.description ?? candidate.description ?? '',
212
- triggerPattern: parsed.triggerPattern,
213
- action: parsed.action,
214
- abstractedPrinciple: parsed.abstractedPrinciple,
215
- usedFallback: false,
216
- };
217
- }
218
- } catch { /* fall through to column fallback */ }
219
- }
220
-
221
- const row = stateManager.connection.getDb().prepare(
222
- 'SELECT recommendation_kind, trigger_pattern, action, abstracted_principle FROM principle_candidates WHERE candidate_id = ?',
223
- ).get(candidateId) as
224
- { recommendation_kind: string; trigger_pattern: string | null; action: string | null; abstracted_principle: string | null } | undefined;
225
-
226
- if (row) {
227
- return {
228
- kind: row.recommendation_kind,
229
- description: candidate.description || '',
230
- triggerPattern: row.trigger_pattern ?? undefined,
231
- action: row.action ?? undefined,
232
- abstractedPrinciple: row.abstracted_principle ?? undefined,
233
- usedFallback: true,
234
- };
235
- }
236
-
237
- return {
238
- kind: 'defer',
239
- description: candidate.description || 'No recommendation data available',
240
- usedFallback: false,
241
- };
242
- }
243
-
244
- // ── List ───────────────────────────────────────────────────────────────────────
245
-
246
- export async function handleCandidateList(opts: CandidateListOptions): Promise<void> {
247
- const workspaceDir = resolveWorkspaceDir(opts.workspace);
248
- const stateManager = new RuntimeStateManager({ workspaceDir });
249
-
250
- try {
251
- await stateManager.initialize();
252
-
253
- const result = await candidateList({
254
- taskId: opts.taskId,
255
- stateManager,
256
- });
257
-
258
- if (opts.json) {
259
- console.log(JSON.stringify(result, null, 2));
260
- return;
261
- }
262
-
263
- if (result.candidates.length === 0) {
264
- console.log(`No candidates found for task: ${opts.taskId}`);
265
- return;
266
- }
267
-
268
- console.log(`\nPrinciple Candidates for Task: ${opts.taskId}\n`);
269
- console.log(` Total: ${result.candidates.length}\n`);
270
-
271
- for (const candidate of result.candidates) {
272
- console.log(` Candidate: ${candidate.candidateId}`);
273
- console.log(` Title: ${candidate.title}`);
274
- console.log(` Artifact: ${candidate.artifactId}`);
275
- console.log(` Source Run: ${candidate.sourceRunId}`);
276
- console.log(` Confidence: ${candidate.confidence ?? 'N/A'}`);
277
- console.log(` Status: ${candidate.status}`);
278
- console.log(` Description: ${candidate.description.substring(0, 100)}${candidate.description.length > 100 ? '...' : ''}`);
279
- console.log('');
280
- }
281
- } finally {
282
- await stateManager.close();
283
- }
284
- }
285
-
286
- // ── Internalize (PRI-89) ──────────────────────────────────────────────────────
287
-
288
- interface CandidateInternalizeOptions {
289
- candidateId: string;
290
- workspace?: string;
291
- json?: boolean;
292
- dryRun?: boolean;
293
- }
294
-
295
- interface CandidateInternalizeResult {
296
- candidateId: string;
297
- route: string;
298
- taskId?: string;
299
- channel?: string;
300
- status: 'created' | 'existing' | 'dry_run' | 'no_task_created';
301
- reason?: string;
302
- /** Required for degraded/refused/failed statuses — tells the operator what to do next. */
303
- nextAction?: string;
304
- }
305
-
306
- export async function handleCandidateInternalize(opts: CandidateInternalizeOptions): Promise<void> {
307
- const workspaceDir = resolveWorkspaceDir(opts.workspace);
308
- const stateManager = new RuntimeStateManager({ workspaceDir });
309
- // PRI-720: resolve the full-chain override once per invocation (seed-time
310
- // application; affects only chains this command seeds).
311
- const seedPipelineMode = resolvePromptFullPipelineSeedMode(workspaceDir);
312
-
313
- try {
314
- await stateManager.initialize();
315
-
316
- const candidate = await stateManager.getCandidate(opts.candidateId);
317
- if (!candidate) {
318
- const result: CandidateInternalizeResult = {
319
- candidateId: opts.candidateId,
320
- route: 'unknown',
321
- status: 'no_task_created',
322
- reason: `Candidate not found: ${opts.candidateId}`,
323
- nextAction: 'Verify candidate ID and run pd candidate show <id> to check existence',
324
- };
325
- if (opts.json) {
326
- console.log(JSON.stringify(result, null, 2));
327
- } else {
328
- console.error(`Candidate not found: ${opts.candidateId}`);
329
- }
330
- process.exit(1);
331
- return;
332
- }
333
-
334
- const recommendation = resolveCandidateRecommendation(candidate, stateManager, opts.candidateId);
335
-
336
- const decision = decideInternalizationRoute(recommendation as Parameters<typeof decideInternalizationRoute>[0]);
337
-
338
- // PRI-435: Resolve sourcePainId from the canonical diagnostician task chain.
339
- // The CandidateRecord does not carry sourcePainId — it must be looked up
340
- // from the diagnostician task's diagnosticJson via candidate.taskId.
341
- // Missing/malformed sourcePainId must fail loud with no side effects.
342
- const sourcePainId = await resolveSourcePainIdFromDiagnostician(stateManager, candidate);
343
- if (sourcePainId === null) {
344
- const result: CandidateInternalizeResult = {
345
- candidateId: opts.candidateId,
346
- route: decision.route,
347
- status: 'no_task_created',
348
- reason: `Cannot resolve sourcePainId from diagnostician task chain for candidate ${opts.candidateId}`,
349
- nextAction: 'Verify the diagnostician task diagnosticJson contains a valid top-level sourcePainId; re-run diagnosis if the pain signal is missing',
350
- };
351
- if (opts.json) {
352
- console.log(JSON.stringify(result, null, 2));
353
- } else {
354
- console.error(`Cannot resolve sourcePainId for candidate ${opts.candidateId}`);
355
- console.error(`Next: ${result.nextAction}`);
356
- }
357
- process.exit(1);
358
- return;
359
- }
360
-
361
- const seed = buildDreamerSeedFromCandidate(candidate, { route: decision.route, ready: decision.ready, sourcePainId, pipelineMode: seedPipelineMode });
362
- // eslint-disable-next-line no-restricted-syntax -- 'in' required for discriminated union narrowing (BridgeTaskSeed | BridgeDecision)
363
- if ('decision' in seed) {
364
- const decisionResult = seed as { decision: string; reason?: string; taskId?: string };
365
- const reason = decisionResult.decision === 'already_exists'
366
- ? `Task ${decisionResult.taskId} already exists`
367
- : decisionResult.reason ?? 'Seed not created';
368
- const result: CandidateInternalizeResult = {
369
- candidateId: opts.candidateId,
370
- route: decision.route,
371
- status: 'no_task_created',
372
- reason,
373
- nextAction: reason.startsWith('Candidate ')
374
- ? 'Check candidate lineage fields (taskId, artifactId, sourceRunId)'
375
- : 'Verify internalization route configuration and candidate readiness',
376
- };
377
- if (opts.json) {
378
- console.log(JSON.stringify(result, null, 2));
379
- } else {
380
- console.log(`\nCandidate Internalize: ${opts.candidateId}\n`);
381
- console.log(` Route: ${decision.route}`);
382
- console.log(` Ready: ${decision.ready}`);
383
- console.log(` Reason: ${reason}`);
384
- console.log(` Next: ${result.nextAction}`);
385
- console.log('');
386
- }
387
- return;
388
- }
389
-
390
- const { channel } = seed;
391
-
392
- if (opts.dryRun) {
393
- const result: CandidateInternalizeResult = {
394
- candidateId: opts.candidateId,
395
- route: decision.route,
396
- channel: seed.channel,
397
- status: 'dry_run',
398
- reason: 'Dry-run mode — no task created',
399
- };
400
- if (opts.json) {
401
- console.log(JSON.stringify(result, null, 2));
402
- } else {
403
- console.log(`\nCandidate Internalize (dry-run): ${opts.candidateId}\n`);
404
- console.log(` Route: ${decision.route}`);
405
- console.log(` Channel: ${channel}`);
406
- console.log(` Would create: dreamer PI task`);
407
- console.log('');
408
- }
409
- return;
410
- }
411
-
412
- // PRI-720 C6: candidate-level dedup (demotion may change the derived
413
- // channel suffix vs a pre-existing chain).
414
- const existingTask = await findExistingDreamerTask((id) => stateManager.getTask(id), opts.candidateId);
415
- if (existingTask) {
416
- const result: CandidateInternalizeResult = {
417
- candidateId: opts.candidateId,
418
- route: decision.route,
419
- taskId: existingTask.taskId,
420
- channel: seed.channel,
421
- status: 'existing',
422
- reason: 'Task already exists for this candidate (any channel variant)',
423
- };
424
- if (opts.json) {
425
- console.log(JSON.stringify(result, null, 2));
426
- } else {
427
- console.log(`\nCandidate Internalize: ${opts.candidateId}\n`);
428
- console.log(` Route: ${decision.route}`);
429
- console.log(` Channel: ${channel}`);
430
- console.log(` Task: ${existingTask.taskId} (existing)`);
431
- console.log('');
432
- }
433
- return;
434
- }
435
-
436
- const task = await stateManager.createTask({
437
- taskId: seed.taskId,
438
- taskKind: seed.taskKind,
439
- status: seed.status,
440
- attemptCount: seed.attemptCount,
441
- maxAttempts: seed.maxAttempts,
442
- diagnosticJson: seed.diagnosticJson,
443
- });
444
-
445
- const result: CandidateInternalizeResult = {
446
- candidateId: opts.candidateId,
447
- route: decision.route,
448
- taskId: task.taskId,
449
- channel: seed.channel,
450
- status: 'created',
451
- };
452
- if (opts.json) {
453
- console.log(JSON.stringify(result, null, 2));
454
- } else {
455
- console.log(`\nCandidate Internalize: ${opts.candidateId}\n`);
456
- console.log(` Route: ${decision.route}`);
457
- console.log(` Channel: ${channel}`);
458
- console.log(` Task: ${task.taskId} (created)`);
459
- console.log('');
460
- }
461
- } finally {
462
- await stateManager.close();
463
- }
464
- }
465
-
466
- // ── Show ───────────────────────────────────────────────────────────────────────
467
-
468
- export async function handleCandidateShow(opts: CandidateShowOptions): Promise<void> {
469
- const workspaceDir = resolveWorkspaceDir(opts.workspace);
470
- const stateManager = new RuntimeStateManager({ workspaceDir });
471
-
472
- try {
473
- await stateManager.initialize();
474
-
475
- const ledgerAdapter = new PrincipleTreeLedgerAdapter({ stateDir: path.join(workspaceDir, '.state') });
476
-
477
- const result = await candidateShow({
478
- candidateId: opts.candidateId,
479
- stateManager,
480
- ledgerAdapter,
481
- });
482
-
483
- if (!result) {
484
- console.error(`Candidate not found: ${opts.candidateId}`);
485
- process.exit(1);
486
- }
487
-
488
- if (opts.json) {
489
- console.log(JSON.stringify(result, null, 2));
490
- return;
491
- }
492
-
493
- console.log(`\nPrinciple Candidate: ${result.candidateId}\n`);
494
- console.log(` Title: ${result.title}`);
495
- console.log(` Description: ${result.description}`);
496
- console.log(` Artifact: ${result.artifactId}`);
497
- console.log(` Task: ${result.taskId}`);
498
- console.log(` Source Run: ${result.sourceRunId}`);
499
- console.log(` Confidence: ${result.confidence ?? 'N/A'}`);
500
- console.log(` Status: ${result.status}`);
501
- console.log(` Created: ${result.createdAt}`);
502
- if (result.ledgerEntryId) {
503
- console.log(` Ledger Entry: ${result.ledgerEntryId}`);
504
- }
505
- // F10-1: surface dangling sourceRunId warning in text mode (rc-9).
506
- if (result.warning) {
507
- console.log(` ⚠ WARNING: ${result.warning}`);
508
- }
509
- if (result.nextAction) {
510
- console.log(` Next Action: ${result.nextAction}`);
511
- }
512
- console.log('');
513
- } finally {
514
- await stateManager.close();
515
- }
516
- }
517
-
518
- // ── Intake ───────────────────────────────────────────────────────────────────
519
-
520
- /**
521
- * pd candidate intake --candidate-id <id> [--workspace <path>] [--json] [--dry-run]
522
- *
523
- * Intakes a principle candidate into the ledger.
524
- * Wires together CandidateIntakeService + PrincipleTreeLedgerAdapter.
525
- * Updates candidate status to 'consumed' (with consumed_at) after successful ledger write.
526
- * If ledger write succeeds but DB update fails, exits non-zero with clear error.
527
- */
528
- export async function handleCandidateIntake(opts: CandidateIntakeOptions): Promise<void> {
529
- const workspaceDir = resolveWorkspaceDir(opts.workspace);
530
- const stateManager = new RuntimeStateManager({ workspaceDir });
531
-
532
- try {
533
- await stateManager.initialize();
534
-
535
- const ledgerAdapter = new PrincipleTreeLedgerAdapter({ stateDir: path.join(workspaceDir, '.state') });
536
- const service = new CandidateIntakeService({ stateManager, ledgerAdapter });
537
-
538
- // Fetch candidate once for admission gate check and downstream paths.
539
- const candidate = await stateManager.getCandidate(opts.candidateId);
540
- if (!candidate) {
541
- console.error(`Candidate not found: ${opts.candidateId}`);
542
- process.exit(1);
543
- return;
544
- }
545
-
546
- // PRI-442 Stage 4: admission gate check — refuse non-admitted candidates
547
- // to prevent CLI from bypassing the production admission gate.
548
- const admissionBlock = checkAdmissionGate(candidate);
549
- if (admissionBlock) {
550
- const result = {
551
- candidateId: opts.candidateId,
552
- status: 'refused',
553
- admissionDecision: admissionBlock.decision,
554
- reason: admissionBlock.reason,
555
- nextAction: admissionBlock.nextAction,
556
- };
557
- if (opts.json) {
558
- console.log(JSON.stringify(result, null, 2));
559
- } else {
560
- console.error(`Admission gate refused candidate ${opts.candidateId}: ${admissionBlock.decision}`);
561
- console.error(` Reason: ${admissionBlock.reason}`);
562
- console.error(` Next Action: ${admissionBlock.nextAction}`);
563
- }
564
- process.exit(1);
565
- return;
566
- }
567
-
568
- if (opts.dryRun) {
569
- const artifact = await stateManager.getArtifact(candidate.artifactId);
570
- if (!artifact) {
571
- console.error(`Artifact not found for candidate: ${opts.candidateId}`);
572
- process.exit(1);
573
- }
574
- let recommendation: { title?: string; text?: string; triggerPattern?: string; action?: string } = {};
575
- try {
576
- const parsed = JSON.parse(artifact.contentJson || '{}');
577
- recommendation = parsed.recommendation || parsed;
578
- } catch (err) {
579
- console.warn(`Warning: could not parse artifact content as JSON — using defaults. ${err instanceof Error ? err.message : String(err)}`);
580
- }
581
- const entry: LedgerPrincipleEntry = {
582
- id: randomUUID(),
583
- title: recommendation.title || candidate.title,
584
- text: recommendation.text || candidate.description || '',
585
- triggerPattern: recommendation.triggerPattern || '',
586
- action: recommendation.action || '',
587
- status: 'probation',
588
- evaluability: 'weak_heuristic',
589
- sourceRef: `candidate://${opts.candidateId}`,
590
- artifactRef: `artifact://${candidate.artifactId}`,
591
- taskRef: candidate.taskId ? `task://${candidate.taskId}` : undefined,
592
- createdAt: new Date().toISOString(),
593
- };
594
- if (opts.json) {
595
- console.log(JSON.stringify(entry, null, 2));
596
- } else {
597
- console.log(`Dry-run: would write entry for candidate ${opts.candidateId}`);
598
- console.log(JSON.stringify(entry, null, 2));
599
- }
600
- return;
601
- }
602
-
603
- // Normal intake: ledger write first
604
- const entry = await service.intake(opts.candidateId);
605
-
606
- // Check if already consumed before this call
607
- if (candidate?.status === 'consumed') {
608
- const infoMessage = `Candidate ${opts.candidateId} was already consumed. Ledger entry: ${entry.id}`;
609
- if (opts.json) {
610
- console.log(JSON.stringify({
611
- candidateId: opts.candidateId,
612
- ledgerEntryId: entry.id,
613
- status: 'already_consumed',
614
- message: infoMessage,
615
- }, null, 2));
616
- } else {
617
- console.log(infoMessage);
618
- }
619
- return;
620
- }
621
-
622
- // Update DB status — this must succeed; if it fails, exit non-zero
623
- try {
624
- await updateCandidateStatus({ stateManager, candidateId: opts.candidateId, targetStatus: 'consumed', expectedCurrentStatus: 'pending' });
625
- } catch (err) {
626
- const msg = `Ledger write succeeded (entry ${entry.id}) but DB status update failed: ${err instanceof Error ? err.message : String(err)}. ` +
627
- `Candidate ${opts.candidateId} may be in inconsistent state.`;
628
- console.error(`ERROR: ${msg}`);
629
- process.exit(1);
630
- }
631
-
632
- const result = {
633
- candidateId: opts.candidateId,
634
- ledgerEntryId: entry.id,
635
- status: 'consumed',
636
- };
637
- if (opts.json) {
638
- console.log(JSON.stringify(result, null, 2));
639
- } else {
640
- console.log(`\nPrinciple Candidate Intake: ${opts.candidateId}\n`);
641
- console.log(` Candidate: ${opts.candidateId}`);
642
- console.log(` Title: ${entry.title}`);
643
- console.log(` Ledger Entry: ${entry.id}`);
644
- console.log(` Status: consumed\n`);
645
- console.log('Intake complete.\n');
646
- }
647
- } catch (err) {
648
- if (err instanceof CandidateIntakeError || (err as { name?: string }).name === 'CandidateIntakeError') {
649
- const e = err as { code?: string; message: string };
650
- console.error(`Intake failed [${e.code ?? 'unknown'}]: ${e.message}`);
651
- } else {
652
- console.error(`Intake failed: ${String(err)}`);
653
- }
654
- process.exit(1);
655
- } finally {
656
- await stateManager.close();
657
- }
658
- }
659
-
660
- // ── Audit ─────────────────────────────────────────────────────────────────────
661
-
662
- /**
663
- * pd candidate audit --workspace <path> [--json]
664
- *
665
- * Reads workspace/.pd/state.db principle_candidates and
666
- * the workspace ledger (same file used by OpenClaw plugin).
667
- * Checks each consumed candidate has a ledger entry.
668
- * Exits non-zero if any consumed candidate is missing from ledger.
669
- */
670
- export async function handleCandidateAudit(opts: CandidateAuditOptions): Promise<void> {
671
- const workspaceDir = resolveWorkspaceDir(opts.workspace);
672
-
673
- let conn: SqliteConnection | undefined;
674
-
675
- try {
676
- const dbPath = path.join(workspaceDir, '.pd', 'state.db');
677
- const ledgerStateDir = path.join(workspaceDir, '.state');
678
- const ledgerPath = getLedgerFilePathPublic(ledgerStateDir);
679
-
680
- conn = new SqliteConnection({ workspaceDir, readonly: true });
681
- const db = conn.getDb();
682
-
683
- const consumedRows = db.prepare(
684
- "SELECT candidate_id FROM principle_candidates WHERE status = 'consumed'"
685
- ).all() as { candidate_id: string }[];
686
-
687
- const consumedIds = consumedRows.map(r => r.candidate_id);
688
-
689
- const ledger = loadLedger(ledgerStateDir);
690
- const ledgerPrinciples = ledger.tree.principles;
691
-
692
- const missingLedgerEntryIds: string[] = [];
693
- for (const candidateId of consumedIds) {
694
- const found = Object.values(ledgerPrinciples).some((p) =>
695
- p.derivedFromPainIds.includes(candidateId),
696
- );
697
- if (!found) {
698
- missingLedgerEntryIds.push(candidateId);
699
- }
700
- }
701
-
702
- const result: AuditResult = {
703
- status: missingLedgerEntryIds.length === 0 ? 'ok' : 'degraded',
704
- consumedCount: consumedIds.length,
705
- missingLedgerEntryIds,
706
- checkedLedgerPath: ledgerPath,
707
- checkedDbPath: dbPath,
708
- };
709
-
710
- if (opts.json) {
711
- console.log(JSON.stringify(result, null, 2));
712
- } else {
713
- console.log(`\nCandidate Audit Results\n`);
714
- console.log(` consumedCount: ${result.consumedCount}`);
715
- console.log(` checkedLedgerPath: ${result.checkedLedgerPath}`);
716
- console.log(` checkedDbPath: ${result.checkedDbPath}`);
717
- console.log(` status: ${result.status}`);
718
- if (result.missingLedgerEntryIds.length > 0) {
719
- console.log(`\n MISSING LEDGER ENTRIES (${result.missingLedgerEntryIds.length}):`);
720
- result.missingLedgerEntryIds.forEach(id => console.log(` - ${id}`));
721
- } else {
722
- console.log(`\n All consumed candidates have ledger entries.`);
723
- }
724
- console.log('');
725
- }
726
-
727
- if (result.status === 'degraded') {
728
- process.exit(1);
729
- }
730
- } catch (err) {
731
- console.error(`Audit failed: ${err instanceof Error ? err.message : String(err)}`);
732
- process.exit(1);
733
- } finally {
734
- try { conn?.close(); } catch { /* best-effort close */ }
735
- }
736
- }
737
-
738
- // ── Repair ─────────────────────────────────────────────────────────────────────
739
-
740
- /**
741
- * pd candidate repair --candidate-id <id> --workspace <path> [--json]
742
- *
743
- * Handles consumed but missing ledger entries.
744
- * Re-calls CandidateIntakeService.intake() to write ledger entry.
745
- * Does not regenerate candidate; does not update status (already consumed).
746
- * Fills consumed_at if empty.
747
- */
748
- export async function handleCandidateRepair(opts: CandidateRepairOptions): Promise<void> {
749
- const workspaceDir = resolveWorkspaceDir(opts.workspace);
750
- const stateManager = new RuntimeStateManager({ workspaceDir });
751
-
752
- try {
753
- await stateManager.initialize();
754
-
755
- // Verify candidate exists and is consumed
756
- const candidate = await stateManager.getCandidate(opts.candidateId);
757
- if (!candidate) {
758
- console.error(`Candidate not found: ${opts.candidateId}`);
759
- process.exit(1);
760
- }
761
- if (candidate.status !== 'consumed') {
762
- console.error(`Candidate ${opts.candidateId} is not consumed (status=${candidate.status}). Repair only handles consumed candidates.`);
763
- process.exit(1);
764
- }
765
-
766
- // PRI-442 Stage 4: admission gate check — even for consumed candidates,
767
- // re-verify admission before re-intaking to prevent bypassing the gate.
768
- // A consumed candidate that would fail the gate indicates data corruption
769
- // or a prior bypass; refuse and surface the reason.
770
- const admissionBlock = checkAdmissionGate(candidate);
771
- if (admissionBlock) {
772
- const result = {
773
- candidateId: opts.candidateId,
774
- status: 'refused',
775
- admissionDecision: admissionBlock.decision,
776
- reason: admissionBlock.reason,
777
- nextAction: admissionBlock.nextAction,
778
- };
779
- if (opts.json) {
780
- console.log(JSON.stringify(result, null, 2));
781
- } else {
782
- console.error(`Admission gate refused candidate ${opts.candidateId}: ${admissionBlock.decision}`);
783
- console.error(` Reason: ${admissionBlock.reason}`);
784
- console.error(` Next Action: ${admissionBlock.nextAction}`);
785
- }
786
- process.exit(1);
787
- return;
788
- }
789
-
790
- const ledgerAdapter = new PrincipleTreeLedgerAdapter({ stateDir: path.join(workspaceDir, '.state') });
791
- const service = new CandidateIntakeService({ stateManager, ledgerAdapter });
792
-
793
- // Check if already in ledger
794
- const existing = ledgerAdapter.existsForCandidate(opts.candidateId);
795
- if (existing) {
796
- const consumedAt = await ensureConsumedAt(stateManager, opts.candidateId);
797
- const result = {
798
- candidateId: opts.candidateId,
799
- status: 'already_consistent',
800
- message: `Candidate ${opts.candidateId} already has ledger entry.`,
801
- ledgerEntryId: existing.id,
802
- consumedAt,
803
- };
804
- if (opts.json) {
805
- console.log(JSON.stringify(result, null, 2));
806
- } else {
807
- console.log(`\nCandidate ${opts.candidateId} already has ledger entry: ${existing.id}\n`);
808
- console.log('No repair needed.\n');
809
- }
810
- return;
811
- }
812
-
813
- // Re-intake to restore ledger entry
814
- const entry = await service.intake(opts.candidateId);
815
- const consumedAt = await ensureConsumedAt(stateManager, opts.candidateId);
816
-
817
- const result = {
818
- candidateId: opts.candidateId,
819
- status: 'repaired',
820
- ledgerEntryId: entry.id,
821
- consumedAt,
822
- message: `Ledger entry restored for consumed candidate ${opts.candidateId}.`,
823
- };
824
- if (opts.json) {
825
- console.log(JSON.stringify(result, null, 2));
826
- } else {
827
- console.log(`\nCandidate Repair: ${opts.candidateId}\n`);
828
- console.log(` Status: repaired`);
829
- console.log(` Ledger Entry: ${entry.id}\n`);
830
- console.log('Repair complete.\n');
831
- }
832
- } catch (err) {
833
- if (err instanceof CandidateIntakeError || (err as { name?: string }).name === 'CandidateIntakeError') {
834
- const e = err as { code?: string; message: string };
835
- console.error(`Repair failed [${e.code ?? 'unknown'}]: ${e.message}`);
836
- } else {
837
- console.error(`Repair failed: ${String(err)}`);
838
- }
839
- process.exit(1);
840
- } finally {
841
- await stateManager.close();
842
- }
843
- }
844
-
845
- // ── Internalization Backfill (consumed candidates missing dreamer tasks) ──────
846
-
847
- interface CandidateBackfillOptions {
848
- workspace?: string;
849
- json?: boolean;
850
- dryRun?: boolean;
851
- confirm?: boolean;
852
- includePending?: boolean;
853
- }
854
-
855
- interface BackfillCandidateResult {
856
- candidateId: string;
857
- route: string;
858
- status: 'would_create' | 'created' | 'existing' | 'deferred' | 'error' | 'would_intake_and_create' | 'intake_failed' | 'intake_succeeded_existing_task';
859
- taskId?: string;
860
- channel?: string;
861
- reason?: string;
862
- statusBefore?: string;
863
- statusAfter?: string;
864
- intakeDecision?: 'would_intake' | 'intake_succeeded' | 'intake_failed' | 'skipped' | 'not_needed';
865
- seedDecision?: 'would_seed' | 'seeded' | 'existing' | 'skipped' | 'not_needed';
866
- nextAction?: string;
867
- }
868
-
869
- interface BackfillOutput {
870
- mode: 'dry-run' | 'confirm';
871
- totalConsumed: number;
872
- totalPending: number;
873
- missingDreamerTask: number;
874
- alreadyHaveTask: number;
875
- deferred: number;
876
- created: number;
877
- intakeSucceeded: number;
878
- intakeFailed: number;
879
- errors: number;
880
- results: BackfillCandidateResult[];
881
- }
882
-
883
- function createBackfillRemediationResult(output: BackfillOutput): RemediationResult {
884
- const actions = output.results
885
- .filter((result) => result.status === 'would_create' || result.status === 'created' || result.status === 'would_intake_and_create' || result.status === 'intake_failed' || result.status === 'intake_succeeded_existing_task')
886
- .map((result) => {
887
- if (result.status === 'would_intake_and_create') {
888
- return remediationAction({
889
- action: 'would_intake_and_create_dreamer_task',
890
- targetId: result.candidateId,
891
- previousState: 'pending_candidate_without_dreamer',
892
- nextState: 'dreamer_task_would_be_created',
893
- reason: result.reason ?? `Backfill would intake pending candidate and create dreamer task${result.taskId ? ` ${result.taskId}` : ''}`,
894
- });
895
- }
896
- if (result.status === 'intake_failed') {
897
- return remediationAction({
898
- action: 'intake_failed',
899
- targetId: result.candidateId,
900
- previousState: 'pending_candidate',
901
- nextState: 'pending_candidate_intake_failed',
902
- reason: result.reason ?? `Backfill intake failed for pending candidate`,
903
- });
904
- }
905
- if (result.status === 'intake_succeeded_existing_task') {
906
- return remediationAction({
907
- action: 'intake_succeeded_existing_task',
908
- targetId: result.candidateId,
909
- previousState: 'pending_candidate',
910
- nextState: 'consumed_candidate_with_existing_dreamer',
911
- reason: result.reason ?? `Backfill intake succeeded but dreamer task already exists`,
912
- });
913
- }
914
- return remediationAction({
915
- action: result.status === 'created' ? 'create_dreamer_task' : 'would_create_dreamer_task',
916
- targetId: result.candidateId,
917
- previousState: 'consumed_candidate_without_dreamer',
918
- nextState: result.status === 'created' ? 'dreamer_task_created' : 'dreamer_task_would_be_created',
919
- reason: result.reason ?? `Backfill ${result.status === 'created' ? 'created' : 'would create'} dreamer task${result.taskId ? ` ${result.taskId}` : ''}`,
920
- });
921
- });
922
-
923
- return createRemediationResult({
924
- mode: output.mode === 'confirm' ? 'confirm' : 'dry_run',
925
- repairedCount: output.created,
926
- skippedCount: output.alreadyHaveTask + output.deferred + output.errors + output.intakeFailed,
927
- actions,
928
- warnings: output.errors > 0 ? [`${output.errors} candidate(s) could not be backfilled.`] : (output.intakeFailed > 0 ? [`${output.intakeFailed} pending candidate(s) intake failed.`] : []),
929
- status: (output.errors > 0 || output.intakeFailed > 0) && output.created === 0 ? 'error' : undefined,
930
- safeToConfirm: output.mode === 'dry-run' && (output.missingDreamerTask > 0 || output.totalPending > 0) && output.errors === 0,
931
- });
932
- }
933
-
934
- export async function handleCandidateInternalizationBackfill(opts: CandidateBackfillOptions): Promise<void> {
935
- if (opts.dryRun && opts.confirm) {
936
- console.error('Error: --dry-run and --confirm are mutually exclusive');
937
- process.exit(1);
938
- return;
939
- }
940
-
941
- const workspaceDir = resolveWorkspaceDir(opts.workspace);
942
- const isConfirm = opts.confirm ?? false;
943
- const stateManager = new RuntimeStateManager({ workspaceDir, readonly: !isConfirm });
944
- // PRI-720: resolve the full-chain override once per invocation.
945
- const seedPipelineMode = resolvePromptFullPipelineSeedMode(workspaceDir);
946
-
947
- try {
948
- await stateManager.initialize();
949
-
950
- const db = stateManager.connection.getDb();
951
-
952
- const consumedRows = db.prepare(
953
- "SELECT candidate_id FROM principle_candidates WHERE status = 'consumed'"
954
- ).all() as { candidate_id: string }[];
955
-
956
- let pendingRows: { candidate_id: string }[] = [];
957
- if (opts.includePending) {
958
- pendingRows = db.prepare(
959
- "SELECT candidate_id FROM principle_candidates WHERE status = 'pending'"
960
- ).all() as { candidate_id: string }[];
961
- }
962
-
963
- const output: BackfillOutput = {
964
- mode: isConfirm ? 'confirm' : 'dry-run',
965
- totalConsumed: consumedRows.length,
966
- totalPending: pendingRows.length,
967
- missingDreamerTask: 0,
968
- alreadyHaveTask: 0,
969
- deferred: 0,
970
- created: 0,
971
- intakeSucceeded: 0,
972
- intakeFailed: 0,
973
- errors: 0,
974
- results: [],
975
- };
976
-
977
- for (const row of consumedRows) {
978
- const candidateId = row.candidate_id;
979
-
980
- const candidate = await stateManager.getCandidate(candidateId);
981
- if (!candidate) {
982
- output.errors++;
983
- output.results.push({ candidateId, route: 'unknown', status: 'error', reason: 'Candidate not found in DB', statusBefore: 'consumed', statusAfter: 'consumed', intakeDecision: 'not_needed', seedDecision: 'skipped', nextAction: 'Investigate why consumed candidate is missing from DB' });
984
- continue;
985
- }
986
-
987
- const recommendation = resolveCandidateRecommendation(candidate, stateManager, candidateId);
988
- const decision = decideInternalizationRoute(recommendation as Parameters<typeof decideInternalizationRoute>[0]);
989
-
990
- // PRI-435: Resolve sourcePainId from the canonical diagnostician task chain.
991
- // Missing/malformed sourcePainId must fail loud per-candidate with no side effects.
992
- const sourcePainId = await resolveSourcePainIdFromDiagnostician(stateManager, candidate);
993
- if (sourcePainId === null) {
994
- output.errors++;
995
- output.results.push({ candidateId, route: decision.route, status: 'error', reason: `Cannot resolve sourcePainId from diagnostician task chain for candidate ${candidateId}`, statusBefore: 'consumed', statusAfter: 'consumed', intakeDecision: 'not_needed', seedDecision: 'skipped', nextAction: 'Verify the diagnostician task diagnosticJson contains a valid top-level sourcePainId; re-run diagnosis if the pain signal is missing' });
996
- continue;
997
- }
998
- const seed = buildDreamerSeedFromCandidate(candidate, { route: decision.route, ready: decision.ready, sourcePainId, pipelineMode: seedPipelineMode });
999
- // eslint-disable-next-line no-restricted-syntax -- 'in' required for discriminated union narrowing (BridgeTaskSeed | BridgeDecision)
1000
- if ('decision' in seed) {
1001
- output.deferred++;
1002
- const decisionResult = seed as { decision: string; reason?: string; taskId?: string };
1003
- const reason = decisionResult.decision === 'already_exists'
1004
- ? `Task ${decisionResult.taskId} already exists`
1005
- : decisionResult.reason ?? 'Seed not created';
1006
- output.results.push({ candidateId, route: decision.route, status: 'deferred', reason, statusBefore: 'consumed', statusAfter: 'consumed', intakeDecision: 'not_needed', seedDecision: 'skipped', nextAction: reason.startsWith('Candidate ') ? 'Check candidate lineage fields (taskId, artifactId, sourceRunId)' : 'Verify internalization route configuration' });
1007
- continue;
1008
- }
1009
-
1010
- const { channel } = seed;
1011
- const { taskId } = seed;
1012
-
1013
- // PRI-720 C6: candidate-level dedup (demotion may change the derived
1014
- // channel suffix vs a pre-existing chain).
1015
- const existingTask = await findExistingDreamerTask((id) => stateManager.getTask(id), candidateId);
1016
- if (existingTask) {
1017
- if (isConfirm && existingTask.diagnosticJson) {
1018
- try {
1019
- const diagObj = JSON.parse(existingTask.diagnosticJson);
1020
- if (!diagObj.candidateId) {
1021
- diagObj.candidateId = candidateId;
1022
- await stateManager.updateTaskDiagnosticJson(taskId, JSON.stringify(diagObj));
1023
- }
1024
- } catch { /* best-effort */ }
1025
- }
1026
- output.alreadyHaveTask++;
1027
- output.results.push({ candidateId, route: decision.route, status: 'existing', taskId: existingTask.taskId, channel, statusBefore: 'consumed', statusAfter: 'consumed', intakeDecision: 'not_needed', seedDecision: 'existing' });
1028
- continue;
1029
- }
1030
-
1031
- output.missingDreamerTask++;
1032
-
1033
- if (!isConfirm) {
1034
- output.results.push({ candidateId, route: decision.route, status: 'would_create', taskId, channel, statusBefore: 'consumed', statusAfter: 'consumed', intakeDecision: 'not_needed', seedDecision: 'would_seed' });
1035
- continue;
1036
- }
1037
-
1038
- try {
1039
- const task = await stateManager.createTask({
1040
- taskId: seed.taskId,
1041
- taskKind: seed.taskKind,
1042
- status: seed.status,
1043
- attemptCount: seed.attemptCount,
1044
- maxAttempts: seed.maxAttempts,
1045
- diagnosticJson: seed.diagnosticJson,
1046
- });
1047
-
1048
- output.created++;
1049
- output.results.push({ candidateId, route: decision.route, status: 'created', taskId: task.taskId, channel, statusBefore: 'consumed', statusAfter: 'consumed', intakeDecision: 'not_needed', seedDecision: 'seeded' });
1050
- } catch (err) {
1051
- output.errors++;
1052
- output.results.push({ candidateId, route: decision.route, status: 'error', reason: err instanceof Error ? err.message : String(err), statusBefore: 'consumed', statusAfter: 'consumed', intakeDecision: 'not_needed', seedDecision: 'skipped', nextAction: 'Investigate dreamer task creation failure' });
1053
- }
1054
- }
1055
-
1056
- const ledgerAdapter = new PrincipleTreeLedgerAdapter({ stateDir: path.join(workspaceDir, '.state') });
1057
- const intakeService = new CandidateIntakeService({ stateManager, ledgerAdapter });
1058
-
1059
- for (const row of pendingRows) {
1060
- const candidateId = row.candidate_id;
1061
-
1062
- const candidate = await stateManager.getCandidate(candidateId);
1063
- if (!candidate) {
1064
- output.errors++;
1065
- output.results.push({ candidateId, route: 'unknown', status: 'error', reason: 'Pending candidate not found in DB', statusBefore: 'pending', statusAfter: 'pending', intakeDecision: 'skipped', seedDecision: 'skipped', nextAction: 'Investigate why pending candidate is missing from DB' });
1066
- continue;
1067
- }
1068
-
1069
- // PRI-442 Stage 4: admission gate check — refuse non-admitted pending
1070
- // candidates to prevent backfill from bypassing the admission gate.
1071
- const admissionBlock = checkAdmissionGate(candidate);
1072
- if (admissionBlock) {
1073
- output.intakeFailed++;
1074
- output.results.push({ candidateId, route: 'unknown', status: 'intake_failed', reason: `Admission gate refused: ${admissionBlock.reason}`, statusBefore: 'pending', statusAfter: 'pending', intakeDecision: 'skipped', seedDecision: 'skipped', nextAction: admissionBlock.nextAction });
1075
- continue;
1076
- }
1077
-
1078
- const recommendation = resolveCandidateRecommendation(candidate, stateManager, candidateId);
1079
- const decision = decideInternalizationRoute(recommendation as Parameters<typeof decideInternalizationRoute>[0]);
1080
-
1081
- // PRI-435: Resolve sourcePainId from the canonical diagnostician task chain.
1082
- // Missing/malformed sourcePainId must fail loud per-candidate with no side effects.
1083
- const sourcePainId = await resolveSourcePainIdFromDiagnostician(stateManager, candidate);
1084
- if (sourcePainId === null) {
1085
- output.errors++;
1086
- output.results.push({ candidateId, route: decision.route, status: 'error', reason: `Cannot resolve sourcePainId from diagnostician task chain for candidate ${candidateId}`, statusBefore: 'pending', statusAfter: 'pending', intakeDecision: 'skipped', seedDecision: 'skipped', nextAction: 'Verify the diagnostician task diagnosticJson contains a valid top-level sourcePainId; re-run diagnosis if the pain signal is missing' });
1087
- continue;
1088
- }
1089
- const seed = buildDreamerSeedFromCandidate(candidate, { route: decision.route, ready: decision.ready, sourcePainId, pipelineMode: seedPipelineMode });
1090
- // eslint-disable-next-line no-restricted-syntax -- 'in' required for discriminated union narrowing (BridgeTaskSeed | BridgeDecision)
1091
- if ('decision' in seed) {
1092
- output.deferred++;
1093
- const decisionResult = seed as { decision: string; reason?: string; taskId?: string };
1094
- const reason = decisionResult.decision === 'already_exists'
1095
- ? `Task ${decisionResult.taskId} already exists`
1096
- : decisionResult.reason ?? 'Seed not created';
1097
- output.results.push({ candidateId, route: decision.route, status: 'deferred', reason, statusBefore: 'pending', statusAfter: 'pending', intakeDecision: 'skipped', seedDecision: 'skipped', nextAction: 'Investigate why bridge decision is not seeded' });
1098
- continue;
1099
- }
1100
-
1101
- const { channel } = seed;
1102
- const { taskId } = seed;
1103
-
1104
- if (!isConfirm) {
1105
- output.missingDreamerTask++;
1106
- output.results.push({ candidateId, route: decision.route, status: 'would_intake_and_create', taskId, channel, statusBefore: 'pending', statusAfter: 'pending', intakeDecision: 'would_intake', seedDecision: 'would_seed', nextAction: 'Run with --confirm to intake and seed' });
1107
- continue;
1108
- }
1109
-
1110
- const intakeEntry = await intakeService.intake(candidateId).catch((intakeErr: unknown) => {
1111
- output.intakeFailed++;
1112
- const intakeReason = intakeErr instanceof CandidateIntakeError
1113
- ? `Intake failed [${(intakeErr as { code?: string }).code ?? 'unknown'}]: ${intakeErr.message}`
1114
- : `Intake failed: ${intakeErr instanceof Error ? intakeErr.message : String(intakeErr)}`;
1115
- output.results.push({ candidateId, route: decision.route, status: 'intake_failed', reason: intakeReason, statusBefore: 'pending', statusAfter: 'pending', intakeDecision: 'intake_failed', seedDecision: 'skipped', nextAction: 'Fix intake issue and re-run backfill' });
1116
- return null;
1117
- });
1118
-
1119
- if (!intakeEntry) {
1120
- continue;
1121
- }
1122
-
1123
- try {
1124
- await updateCandidateStatus({ stateManager, candidateId, targetStatus: 'consumed', expectedCurrentStatus: 'pending' });
1125
- } catch (statusErr) {
1126
- const statusMsg = `Ledger write succeeded (entry ${intakeEntry.id}) but DB status update failed: ${statusErr instanceof Error ? statusErr.message : String(statusErr)}`;
1127
- output.intakeFailed++;
1128
- output.results.push({ candidateId, route: decision.route, status: 'intake_failed', reason: statusMsg, statusBefore: 'pending', statusAfter: 'pending', intakeDecision: 'intake_failed', seedDecision: 'skipped', nextAction: 'Candidate may be in inconsistent state — check ledger and DB manually' });
1129
- continue;
1130
- }
1131
-
1132
- output.intakeSucceeded++;
1133
-
1134
- const existingTask = await stateManager.getTask(taskId);
1135
- if (existingTask) {
1136
- output.alreadyHaveTask++;
1137
- output.results.push({ candidateId, route: decision.route, status: 'intake_succeeded_existing_task', taskId: existingTask.taskId, channel, statusBefore: 'pending', statusAfter: 'consumed', intakeDecision: 'intake_succeeded', seedDecision: 'existing', reason: `Intake succeeded but dreamer task ${existingTask.taskId} already exists` });
1138
- continue;
1139
- }
1140
-
1141
- try {
1142
- const task = await stateManager.createTask({
1143
- taskId: seed.taskId,
1144
- taskKind: seed.taskKind,
1145
- status: seed.status,
1146
- attemptCount: seed.attemptCount,
1147
- maxAttempts: seed.maxAttempts,
1148
- diagnosticJson: seed.diagnosticJson,
1149
- });
1150
-
1151
- output.created++;
1152
- output.results.push({ candidateId, route: decision.route, status: 'created', taskId: task.taskId, channel, statusBefore: 'pending', statusAfter: 'consumed', intakeDecision: 'intake_succeeded', seedDecision: 'seeded' });
1153
- } catch (err) {
1154
- output.errors++;
1155
- output.results.push({ candidateId, route: decision.route, status: 'error', reason: err instanceof Error ? err.message : String(err), statusBefore: 'pending', statusAfter: 'consumed', intakeDecision: 'intake_succeeded', seedDecision: 'skipped', nextAction: 'Intake succeeded but dreamer task creation failed — candidate is consumed, re-run backfill for consumed candidates' });
1156
- }
1157
- }
1158
-
1159
- if (opts.json) {
1160
- console.log(JSON.stringify({ ...createBackfillRemediationResult(output), details: output }, null, 2));
1161
- } else {
1162
- const remediation = createBackfillRemediationResult(output);
1163
- console.log(`\nCandidate Internalization Backfill (${output.mode})\n`);
1164
- console.log(` status: ${remediation.status}`);
1165
- console.log(` safe_to_confirm: ${remediation.safeToConfirm}`);
1166
- console.log(` total_consumed: ${output.totalConsumed}`);
1167
- if (opts.includePending) {
1168
- console.log(` total_pending: ${output.totalPending}`);
1169
- }
1170
- console.log(` missing_dreamer: ${output.missingDreamerTask}`);
1171
- console.log(` already_have_task: ${output.alreadyHaveTask}`);
1172
- console.log(` deferred: ${output.deferred}`);
1173
- if (isConfirm) {
1174
- console.log(` created: ${output.created}`);
1175
- console.log(` errors: ${output.errors}`);
1176
- if (opts.includePending) {
1177
- console.log(` intake_succeeded: ${output.intakeSucceeded}`);
1178
- console.log(` intake_failed: ${output.intakeFailed}`);
1179
- }
1180
- }
1181
- for (const r of output.results) {
1182
- const prefix = r.statusBefore === 'pending' ? '[pending]' : '[consumed]';
1183
- console.log(` ${prefix} ${r.candidateId}: ${r.status} (${r.route})${r.taskId ? ` → ${r.taskId}` : ''}${r.reason ? ` — ${r.reason}` : ''}`);
1184
- }
1185
- if (!isConfirm && (output.missingDreamerTask > 0 || output.totalPending > 0)) {
1186
- console.log(`\n (use --confirm to create missing dreamer tasks${opts.includePending ? ' and intake pending candidates' : ''})`);
1187
- }
1188
- console.log('');
1189
- }
1190
-
1191
- if ((output.missingDreamerTask > 0 || output.totalPending > 0) && !isConfirm) {
1192
- process.exitCode = 1;
1193
- }
1194
- } finally {
1195
- await stateManager.close();
1196
- }
1197
- }
1198
-
1199
- // ── Route (Internalization Inspection) ──────────────────────────────────────
1200
-
1201
- interface CandidateRouteOptions {
1202
- candidateId: string;
1203
- workspace?: string;
1204
- json?: boolean;
1205
- }
1206
-
1207
- /**
1208
- * pd candidate route --candidate-id <id> --workspace <path> [--json]
1209
- *
1210
- * Read-only: shows which internalization pipeline route a candidate will enter,
1211
- * whether it's ready, and what fields are missing.
1212
- */
1213
- export async function handleCandidateRoute(opts: CandidateRouteOptions): Promise<void> {
1214
- const workspaceDir = resolveWorkspaceDir(opts.workspace);
1215
- const stateManager = new RuntimeStateManager({ workspaceDir });
1216
-
1217
- try {
1218
- await stateManager.initialize();
1219
-
1220
- const candidate = await stateManager.getCandidate(opts.candidateId);
1221
- if (!candidate) {
1222
- console.error(`Candidate not found: ${opts.candidateId}`);
1223
- process.exit(1);
1224
- return; // unreachable in production, needed for test mocks
1225
- }
1226
-
1227
- const recommendation = resolveCandidateRecommendation(candidate, stateManager, opts.candidateId);
1228
-
1229
- const decision = decideInternalizationRoute(recommendation as Parameters<typeof decideInternalizationRoute>[0]);
1230
-
1231
- const result = {
1232
- candidateId: opts.candidateId,
1233
- recommendationKind: recommendation.kind,
1234
- route: decision.route,
1235
- ready: decision.ready,
1236
- missingFields: decision.missingFields,
1237
- reason: decision.reason,
1238
- nextAction: decision.nextAction,
1239
- ...(recommendation.usedFallback && { _meta: { source: 'column_fallback' } }),
1240
- };
1241
-
1242
- if (opts.json) {
1243
- console.log(JSON.stringify(result, null, 2));
1244
- } else {
1245
- console.log(`\nCandidate Route: ${result.candidateId}\n`);
1246
- console.log(` Kind: ${result.recommendationKind}`);
1247
- console.log(` Route: ${result.route}`);
1248
- console.log(` Ready: ${result.ready}`);
1249
- console.log(` Missing Fields: ${result.missingFields.length > 0 ? result.missingFields.join(', ') : '(none)'}`);
1250
- console.log(` Reason: ${result.reason}`);
1251
- console.log(` Next Action: ${result.nextAction}`);
1252
- if (recommendation.usedFallback) {
1253
- console.log(` Source: column_fallback (source_recommendation_json unavailable)`);
1254
- }
1255
- console.log('');
1256
- }
1257
- } finally {
1258
- await stateManager.close();
1259
- }
1260
- }