@principles/pd-cli 1.152.12 → 1.152.14

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