@principles/pd-cli 1.152.12 → 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 (296) hide show
  1. package/package.json +13 -7
  2. package/CHANGELOG.md +0 -23
  3. package/dist/commands/__tests__/intent-flag-wiring.test.d.ts +0 -9
  4. package/dist/commands/__tests__/intent-flag-wiring.test.d.ts.map +0 -1
  5. package/dist/commands/__tests__/intent-flag-wiring.test.js +0 -237
  6. package/dist/commands/__tests__/intent-flag-wiring.test.js.map +0 -1
  7. package/dist/commands/__tests__/legacy-cleanup.test.d.ts +0 -18
  8. package/dist/commands/__tests__/legacy-cleanup.test.d.ts.map +0 -1
  9. package/dist/commands/__tests__/legacy-cleanup.test.js +0 -467
  10. package/dist/commands/__tests__/legacy-cleanup.test.js.map +0 -1
  11. package/dist/commands/__tests__/mvp-smoke.test.d.ts +0 -15
  12. package/dist/commands/__tests__/mvp-smoke.test.d.ts.map +0 -1
  13. package/dist/commands/__tests__/mvp-smoke.test.js +0 -262
  14. package/dist/commands/__tests__/mvp-smoke.test.js.map +0 -1
  15. package/dist/commands/__tests__/pain-retry-maxTokens-flag.test.d.ts +0 -2
  16. package/dist/commands/__tests__/pain-retry-maxTokens-flag.test.d.ts.map +0 -1
  17. package/dist/commands/__tests__/pain-retry-maxTokens-flag.test.js +0 -60
  18. package/dist/commands/__tests__/pain-retry-maxTokens-flag.test.js.map +0 -1
  19. package/dist/commands/__tests__/rulecode-flag-wiring.test.d.ts +0 -21
  20. package/dist/commands/__tests__/rulecode-flag-wiring.test.d.ts.map +0 -1
  21. package/dist/commands/__tests__/rulecode-flag-wiring.test.js +0 -186
  22. package/dist/commands/__tests__/rulecode-flag-wiring.test.js.map +0 -1
  23. package/dist/commands/__tests__/rulecode-handler.test.d.ts +0 -16
  24. package/dist/commands/__tests__/rulecode-handler.test.d.ts.map +0 -1
  25. package/dist/commands/__tests__/rulecode-handler.test.js +0 -285
  26. package/dist/commands/__tests__/rulecode-handler.test.js.map +0 -1
  27. package/dist/commands/__tests__/run-rulehost-flag-wiring.test.d.ts +0 -24
  28. package/dist/commands/__tests__/run-rulehost-flag-wiring.test.d.ts.map +0 -1
  29. package/dist/commands/__tests__/run-rulehost-flag-wiring.test.js +0 -232
  30. package/dist/commands/__tests__/run-rulehost-flag-wiring.test.js.map +0 -1
  31. package/dist/commands/__tests__/runtime-activation-nextaction.test.d.ts +0 -15
  32. package/dist/commands/__tests__/runtime-activation-nextaction.test.d.ts.map +0 -1
  33. package/dist/commands/__tests__/runtime-activation-nextaction.test.js +0 -73
  34. package/dist/commands/__tests__/runtime-activation-nextaction.test.js.map +0 -1
  35. package/dist/commands/__tests__/runtime-probe-config.test.d.ts +0 -20
  36. package/dist/commands/__tests__/runtime-probe-config.test.d.ts.map +0 -1
  37. package/dist/commands/__tests__/runtime-probe-config.test.js +0 -389
  38. package/dist/commands/__tests__/runtime-probe-config.test.js.map +0 -1
  39. package/dist/commands/__tests__/telemetry-flag-wiring.test.d.ts +0 -9
  40. package/dist/commands/__tests__/telemetry-flag-wiring.test.d.ts.map +0 -1
  41. package/dist/commands/__tests__/telemetry-flag-wiring.test.js +0 -76
  42. package/dist/commands/__tests__/telemetry-flag-wiring.test.js.map +0 -1
  43. package/dist/commands/__tests__/version.test.d.ts +0 -2
  44. package/dist/commands/__tests__/version.test.d.ts.map +0 -1
  45. package/dist/commands/__tests__/version.test.js +0 -238
  46. package/dist/commands/__tests__/version.test.js.map +0 -1
  47. package/dist/commands/runtime-uat.guard.test.d.ts +0 -2
  48. package/dist/commands/runtime-uat.guard.test.d.ts.map +0 -1
  49. package/dist/commands/runtime-uat.guard.test.js +0 -153
  50. package/dist/commands/runtime-uat.guard.test.js.map +0 -1
  51. package/dist/services/__tests__/cli-output.test.d.ts +0 -18
  52. package/dist/services/__tests__/cli-output.test.d.ts.map +0 -1
  53. package/dist/services/__tests__/cli-output.test.js +0 -103
  54. package/dist/services/__tests__/cli-output.test.js.map +0 -1
  55. package/dist/services/__tests__/evaluator-runner-deps.test.d.ts +0 -2
  56. package/dist/services/__tests__/evaluator-runner-deps.test.d.ts.map +0 -1
  57. package/dist/services/__tests__/evaluator-runner-deps.test.js +0 -343
  58. package/dist/services/__tests__/evaluator-runner-deps.test.js.map +0 -1
  59. package/dist/services/__tests__/rulehost-readiness.test.d.ts +0 -2
  60. package/dist/services/__tests__/rulehost-readiness.test.d.ts.map +0 -1
  61. package/dist/services/__tests__/rulehost-readiness.test.js +0 -311
  62. package/dist/services/__tests__/rulehost-readiness.test.js.map +0 -1
  63. package/dist/services/__tests__/runtime-adapter-resolver.test.d.ts +0 -18
  64. package/dist/services/__tests__/runtime-adapter-resolver.test.d.ts.map +0 -1
  65. package/dist/services/__tests__/runtime-adapter-resolver.test.js +0 -673
  66. package/dist/services/__tests__/runtime-adapter-resolver.test.js.map +0 -1
  67. package/dist/utils/production-workspace-guard.test.d.ts +0 -2
  68. package/dist/utils/production-workspace-guard.test.d.ts.map +0 -1
  69. package/dist/utils/production-workspace-guard.test.js +0 -137
  70. package/dist/utils/production-workspace-guard.test.js.map +0 -1
  71. package/scripts/llm-dogfood.ts +0 -456
  72. package/scripts/migrate-illegal-expected-decision.ts +0 -252
  73. package/src/commands/__tests__/intent-flag-wiring.test.ts +0 -282
  74. package/src/commands/__tests__/legacy-cleanup.test.ts +0 -602
  75. package/src/commands/__tests__/mvp-smoke.test.ts +0 -300
  76. package/src/commands/__tests__/pain-retry-maxTokens-flag.test.ts +0 -73
  77. package/src/commands/__tests__/rulecode-flag-wiring.test.ts +0 -237
  78. package/src/commands/__tests__/rulecode-handler.test.ts +0 -369
  79. package/src/commands/__tests__/run-rulehost-flag-wiring.test.ts +0 -292
  80. package/src/commands/__tests__/runtime-activation-nextaction.test.ts +0 -81
  81. package/src/commands/__tests__/runtime-probe-config.test.ts +0 -432
  82. package/src/commands/__tests__/telemetry-flag-wiring.test.ts +0 -84
  83. package/src/commands/__tests__/version.test.ts +0 -251
  84. package/src/commands/admission-gate.ts +0 -30
  85. package/src/commands/artifact.ts +0 -82
  86. package/src/commands/build-trajectory-evidence.ts +0 -298
  87. package/src/commands/candidate.ts +0 -1250
  88. package/src/commands/codex-ingest-catchup.ts +0 -114
  89. package/src/commands/codex-ingest-quarantine.ts +0 -127
  90. package/src/commands/codex-reconcile.ts +0 -84
  91. package/src/commands/codex-setup.ts +0 -476
  92. package/src/commands/codex-worker.ts +0 -185
  93. package/src/commands/command-helpers.ts +0 -24
  94. package/src/commands/config-doctor.ts +0 -193
  95. package/src/commands/console.ts +0 -797
  96. package/src/commands/context.ts +0 -72
  97. package/src/commands/demo-story-a.ts +0 -241
  98. package/src/commands/diagnose.ts +0 -756
  99. package/src/commands/errors-list.ts +0 -441
  100. package/src/commands/evolution-tasks-list.ts +0 -48
  101. package/src/commands/evolution-tasks-show.ts +0 -62
  102. package/src/commands/flow.ts +0 -60
  103. package/src/commands/health-codex.ts +0 -576
  104. package/src/commands/health.ts +0 -315
  105. package/src/commands/history.ts +0 -63
  106. package/src/commands/intent.ts +0 -457
  107. package/src/commands/legacy-cleanup.ts +0 -531
  108. package/src/commands/legacy-import.ts +0 -104
  109. package/src/commands/mvp-smoke.ts +0 -160
  110. package/src/commands/pain-evidence.ts +0 -226
  111. package/src/commands/pain-list.ts +0 -239
  112. package/src/commands/pain-record.ts +0 -612
  113. package/src/commands/pain-retry.ts +0 -916
  114. package/src/commands/principles-stats.ts +0 -700
  115. package/src/commands/proven-channel-baseline.ts +0 -115
  116. package/src/commands/quality-scorecard.ts +0 -272
  117. package/src/commands/remediation-output.ts +0 -66
  118. package/src/commands/rulecode.ts +0 -465
  119. package/src/commands/run.ts +0 -89
  120. package/src/commands/runtime-activation.ts +0 -1629
  121. package/src/commands/runtime-artifact-repair.ts +0 -524
  122. package/src/commands/runtime-canary.ts +0 -395
  123. package/src/commands/runtime-compatibility-scan.ts +0 -105
  124. package/src/commands/runtime-diagnostics-export.ts +0 -229
  125. package/src/commands/runtime-features.ts +0 -153
  126. package/src/commands/runtime-gfi-snapshot.ts +0 -135
  127. package/src/commands/runtime-health-snapshot.ts +0 -108
  128. package/src/commands/runtime-init.ts +0 -429
  129. package/src/commands/runtime-internalization-enqueue-successors.ts +0 -530
  130. package/src/commands/runtime-internalization-integrity-repair.ts +0 -79
  131. package/src/commands/runtime-internalization-integrity.ts +0 -107
  132. package/src/commands/runtime-internalization-queue.ts +0 -135
  133. package/src/commands/runtime-internalization-retry.ts +0 -191
  134. package/src/commands/runtime-internalization-run-once.ts +0 -791
  135. package/src/commands/runtime-internalization-run-rulehost.ts +0 -749
  136. package/src/commands/runtime-internalization-wake-once.ts +0 -87
  137. package/src/commands/runtime-pain-flood-simulation.ts +0 -121
  138. package/src/commands/runtime-pruning.ts +0 -438
  139. package/src/commands/runtime-recovery-failed-tasks.ts +0 -258
  140. package/src/commands/runtime-recovery.ts +0 -109
  141. package/src/commands/runtime-synthetic-baseline.ts +0 -70
  142. package/src/commands/runtime-uat.guard.test.ts +0 -175
  143. package/src/commands/runtime-uat.ts +0 -380
  144. package/src/commands/runtime.ts +0 -473
  145. package/src/commands/samples-list.ts +0 -39
  146. package/src/commands/samples-review.ts +0 -36
  147. package/src/commands/task.ts +0 -271
  148. package/src/commands/telemetry.ts +0 -349
  149. package/src/commands/trace.ts +0 -174
  150. package/src/commands/trajectory-db-unavailable.ts +0 -19
  151. package/src/commands/trajectory.ts +0 -64
  152. package/src/commands/version.ts +0 -49
  153. package/src/config-reader.ts +0 -122
  154. package/src/index.ts +0 -1276
  155. package/src/legacy/legacy-import.ts +0 -179
  156. package/src/legacy/session-history-import.ts +0 -203
  157. package/src/resolve-workspace.ts +0 -106
  158. package/src/services/__tests__/cli-output.test.ts +0 -130
  159. package/src/services/__tests__/evaluator-runner-deps.test.ts +0 -382
  160. package/src/services/__tests__/rulehost-readiness.test.ts +0 -363
  161. package/src/services/__tests__/runtime-adapter-resolver.test.ts +0 -793
  162. package/src/services/cli-output.ts +0 -95
  163. package/src/services/config-doctor.ts +0 -697
  164. package/src/services/console-launcher.ts +0 -537
  165. package/src/services/demo-rule-compiler.ts +0 -40
  166. package/src/services/demo-story-a-runner.ts +0 -471
  167. package/src/services/mainline-snapshot-assembler.ts +0 -579
  168. package/src/services/pain-flood-simulation-runner.ts +0 -462
  169. package/src/services/pd-config-loader.ts +0 -433
  170. package/src/services/proven-channel-baseline-runner.ts +0 -157
  171. package/src/services/quality-scorecard/data-extractor.ts +0 -150
  172. package/src/services/quality-scorecard/local-evaluator.ts +0 -142
  173. package/src/services/quality-scorecard/strong-model-gate.ts +0 -202
  174. package/src/services/resolve-runtime-from-pd-config.ts +0 -230
  175. package/src/services/rulehost-pipeline-runner.ts +0 -1214
  176. package/src/services/rulehost-readiness.ts +0 -326
  177. package/src/services/runtime-adapter-resolver.ts +0 -364
  178. package/src/services/synthetic-baseline-runner.ts +0 -400
  179. package/src/services/version-report.ts +0 -253
  180. package/src/services/workspace-tool-semantics.ts +0 -26
  181. package/src/utils/path-security.ts +0 -96
  182. package/src/utils/production-workspace-guard.test.ts +0 -157
  183. package/src/utils/production-workspace-guard.ts +0 -210
  184. package/tests/bdd/cli-contract.steps.ts +0 -346
  185. package/tests/bdd/principles-stats.steps.ts +0 -211
  186. package/tests/bdd/support/gherkin-loader.ts +0 -147
  187. package/tests/bdd/support/repo-root.ts +0 -62
  188. package/tests/bdd/support/vitest-bdd.ts +0 -179
  189. package/tests/commands/admission-gate-coverage.test.ts +0 -79
  190. package/tests/commands/build-trajectory-evidence.test.ts +0 -508
  191. package/tests/commands/candidate-audit-repair.test.ts +0 -421
  192. package/tests/commands/candidate-intake.test.ts +0 -732
  193. package/tests/commands/candidate-internalization-backfill.test.ts +0 -548
  194. package/tests/commands/candidate-internalize-lineage.test.ts +0 -628
  195. package/tests/commands/candidate-internalize.test.ts +0 -299
  196. package/tests/commands/candidate-route.test.ts +0 -329
  197. package/tests/commands/candidate-show.test.ts +0 -95
  198. package/tests/commands/cli-command-tree.test.ts +0 -144
  199. package/tests/commands/cli-help-snapshot.test.ts +0 -155
  200. package/tests/commands/cli-skill-contract.test.ts +0 -121
  201. package/tests/commands/codex-consent-reversibility.steps.test.ts +0 -299
  202. package/tests/commands/codex-ingest-quarantine.test.ts +0 -136
  203. package/tests/commands/codex-setup.test.ts +0 -297
  204. package/tests/commands/codex-worker-daemon.test.ts +0 -95
  205. package/tests/commands/codex-worker-registration.test.ts +0 -207
  206. package/tests/commands/config-doctor.test.ts +0 -336
  207. package/tests/commands/console-launcher-edge-cases.test.ts +0 -388
  208. package/tests/commands/console-open.test.ts +0 -1381
  209. package/tests/commands/context.test.ts +0 -114
  210. package/tests/commands/demo-story-a.test.ts +0 -318
  211. package/tests/commands/diagnose.test.ts +0 -1803
  212. package/tests/commands/errors-list.test.ts +0 -679
  213. package/tests/commands/evolution-tasks-list.test.ts +0 -41
  214. package/tests/commands/evolution-tasks-show.test.ts +0 -46
  215. package/tests/commands/health-codex.test.ts +0 -349
  216. package/tests/commands/health-host-wiring.test.ts +0 -76
  217. package/tests/commands/health-reliability.test.ts +0 -99
  218. package/tests/commands/health.test.ts +0 -413
  219. package/tests/commands/intent.test.ts +0 -321
  220. package/tests/commands/legacy-cleanup.test.ts +0 -148
  221. package/tests/commands/pain-evidence.test.ts +0 -518
  222. package/tests/commands/pain-list.test.ts +0 -219
  223. package/tests/commands/pain-record-async.test.ts +0 -335
  224. package/tests/commands/pain-record-session-parser.test.ts +0 -228
  225. package/tests/commands/pain-record.test.ts +0 -851
  226. package/tests/commands/pain-retry.test.ts +0 -1121
  227. package/tests/commands/plugin-config-resolution-cutover.test.ts +0 -229
  228. package/tests/commands/pri-393-runtime-config-unification.test.ts +0 -443
  229. package/tests/commands/principles-stats-wiring.test.ts +0 -135
  230. package/tests/commands/principles-stats.test.ts +0 -274
  231. package/tests/commands/product-path-regression.test.ts +0 -86
  232. package/tests/commands/proven-channel-baseline.test.ts +0 -441
  233. package/tests/commands/rulecode.test.ts +0 -177
  234. package/tests/commands/run-rulehost-handler.test.ts +0 -908
  235. package/tests/commands/runtime-activation-approve-flag-wiring.test.ts +0 -227
  236. package/tests/commands/runtime-activation-deactivate-flag-wiring.test.ts +0 -167
  237. package/tests/commands/runtime-activation-dispatch-flag-wiring.test.ts +0 -262
  238. package/tests/commands/runtime-activation-governance-audit.test.ts +0 -95
  239. package/tests/commands/runtime-activation-list-flag-wiring.test.ts +0 -193
  240. package/tests/commands/runtime-activation-promote-flag-wiring.test.ts +0 -248
  241. package/tests/commands/runtime-activation-shadow-telemetry.test.ts +0 -130
  242. package/tests/commands/runtime-activation.test.ts +0 -2052
  243. package/tests/commands/runtime-artifact-repair-registration.test.ts +0 -74
  244. package/tests/commands/runtime-artifact-repair.test.ts +0 -404
  245. package/tests/commands/runtime-canary.test.ts +0 -430
  246. package/tests/commands/runtime-compatibility-scan.test.ts +0 -146
  247. package/tests/commands/runtime-diagnostics-export.test.ts +0 -175
  248. package/tests/commands/runtime-features.test.ts +0 -249
  249. package/tests/commands/runtime-health-snapshot.test.ts +0 -358
  250. package/tests/commands/runtime-init-empty-workspace.test.ts +0 -252
  251. package/tests/commands/runtime-init.test.ts +0 -420
  252. package/tests/commands/runtime-internalization-enqueue-successors.test.ts +0 -782
  253. package/tests/commands/runtime-internalization-integrity-repair.test.ts +0 -239
  254. package/tests/commands/runtime-internalization-integrity.test.ts +0 -140
  255. package/tests/commands/runtime-internalization-queue.test.ts +0 -380
  256. package/tests/commands/runtime-internalization-retry-owner-authority.test.ts +0 -431
  257. package/tests/commands/runtime-internalization-run-once-evaluator-parity.test.ts +0 -269
  258. package/tests/commands/runtime-internalization-run-once-language.test.ts +0 -303
  259. package/tests/commands/runtime-internalization-run-once-real-config.test.ts +0 -237
  260. package/tests/commands/runtime-internalization-run-once-rollout-parity.test.ts +0 -706
  261. package/tests/commands/runtime-internalization-run-once.test.ts +0 -1791
  262. package/tests/commands/runtime-internalization-wake-once.test.ts +0 -171
  263. package/tests/commands/runtime-internalization.test.ts +0 -53
  264. package/tests/commands/runtime-pain-flood-simulation.test.ts +0 -418
  265. package/tests/commands/runtime-pruning.test.ts +0 -694
  266. package/tests/commands/runtime-recovery-failed-tasks.test.ts +0 -328
  267. package/tests/commands/runtime-recovery.test.ts +0 -120
  268. package/tests/commands/runtime-synthetic-baseline.test.ts +0 -249
  269. package/tests/commands/runtime-uat.test.ts +0 -397
  270. package/tests/commands/runtime.test.ts +0 -392
  271. package/tests/commands/samples-list.test.ts +0 -43
  272. package/tests/commands/samples-review.test.ts +0 -41
  273. package/tests/commands/task.test.ts +0 -153
  274. package/tests/commands/telemetry.test.ts +0 -190
  275. package/tests/commands/trace.test.ts +0 -316
  276. package/tests/config-reader.test.ts +0 -143
  277. package/tests/e2e/candidate-intake-e2e.test.ts +0 -338
  278. package/tests/e2e/cli-full-flow.test.ts +0 -233
  279. package/tests/e2e/cross-package-acceptance.test.ts +0 -635
  280. package/tests/helpers/pd-cli-path.ts +0 -5
  281. package/tests/pd-cli-smoke.test.ts +0 -13
  282. package/tests/resolve-workspace.test.ts +0 -196
  283. package/tests/services/config-doctor-signal-health.test.ts +0 -109
  284. package/tests/services/console-launcher.test.ts +0 -114
  285. package/tests/services/demo-rule-compiler.test.ts +0 -242
  286. package/tests/services/mainline-snapshot-assembler.test.ts +0 -572
  287. package/tests/services/pd-config-loader.test.ts +0 -505
  288. package/tests/services/proven-channel-baseline-runner.test.ts +0 -30
  289. package/tests/services/quality-scorecard/strong-model-gate.test.ts +0 -133
  290. package/tests/services/resolve-runtime-from-pd-config.test.ts +0 -485
  291. package/tests/services/rulehost-pipeline-e2e.test.ts +0 -538
  292. package/tests/services/rulehost-pipeline-runner.test.ts +0 -1242
  293. package/tests/services/workspace-tool-semantics.test.ts +0 -76
  294. package/tests/utils/path-security.test.ts +0 -180
  295. package/tsconfig.json +0 -26
  296. package/vitest.config.ts +0 -10
@@ -1,429 +0,0 @@
1
- /**
2
- * pd runtime init — Initialize all PD SQLite databases for a workspace.
3
- *
4
- * Creates state.db and trajectory.db with full schema
5
- * (tables + indexes + views + migrations). Idempotent: safe to run on existing
6
- * workspaces (all CREATE statements use IF NOT EXISTS).
7
- * (subagent_workflows.db initialization removed in PRI-737 with the legacy
8
- * evolution worker chain — the workflow store had no remaining producers.)
9
- *
10
- * Output contract (cli-1 strict-json, cli-4 dry-run/confirm mutex, cli-6 nextAction):
11
- * - Default mode is --dry-run (no writes); use --confirm to actually initialize.
12
- * - --json emits a single parseable JSON object on stdout.
13
- * - Failures emit { ok: false, reason, nextAction } with exit code 1.
14
- *
15
- * ERR refs:
16
- * - ERR-001/ERR-005: no `as` casts; DB rows typed via type guards
17
- * - ERR-002: degraded paths include reason + nextAction
18
- * - ERR-009/ERR-010: missing required fields fail loud
19
- * - ERR-014: safe JSON.stringify on known output shapes
20
- */
21
-
22
- import * as path from 'path';
23
- import * as fs from 'fs';
24
- import * as yaml from 'js-yaml';
25
- import { SqliteConnection, SchemaConformanceReadModel } from '@principles/core/runtime-v2';
26
- import { getDefaultPdConfig, validatePdConfig } from '@principles/core/runtime-v2';
27
- import { initTrajectorySchema } from 'principles-disciple';
28
- import { TRAJECTORY_TABLES } from '@principles/core/runtime-v2';
29
- import { resolveWorkspaceDir } from '../resolve-workspace.js';
30
- import { emitResult, emitFlagConflict, emitError } from '../services/cli-output.js';
31
-
32
- // ── Constants ─────────────────────────────────────────────────────────────────
33
-
34
- const CONFIG_DIR = '.pd';
35
- const CONFIG_FILENAME = 'config.yaml';
36
- const CONFIG_HEADER =
37
- `# PD Runtime Configuration — single source of truth (.pd/config.yaml, ADR-0016)\n` +
38
- `# Auto-generated by 'pd runtime init'. Existing config files are never overwritten.\n` +
39
- `# Edit to configure feature flags, runtime profiles, internal agents, and UI.\n`;
40
-
41
- /**
42
- * Type guard for Node.js errno errors (rc-2: no `as` on caught unknown).
43
- * Mirrors principle-tree-ledger.ts — uses Object.hasOwn, not `in`.
44
- * Structural type (not NodeJS.ErrnoException) to avoid the NodeJS global,
45
- * which is not defined in this package's eslint config.
46
- * Needed to detect EEXIST from the atomic exclusive write below.
47
- */
48
- interface ErrnoExceptionLike {
49
- code?: string;
50
- }
51
-
52
- function isErrnoException(value: unknown): value is ErrnoExceptionLike {
53
- return typeof value === 'object' && value !== null && Object.hasOwn(value, 'code');
54
- }
55
-
56
- // ── Output types ─────────────────────────────────────────────────────────────
57
-
58
- export interface DatabaseInitResult {
59
- name: string;
60
- path: string;
61
- tables: string[];
62
- status: 'initialized' | 'verified' | 'skipped' | 'failed';
63
- warnings: string[];
64
- }
65
-
66
- export interface ConfigInitResult {
67
- path: string;
68
- status: 'initialized' | 'skipped' | 'failed' | 'verified';
69
- warnings: string[];
70
- }
71
-
72
- export interface RuntimeInitOutput {
73
- ok: boolean;
74
- mode: 'dry-run' | 'confirm';
75
- workspace: string;
76
- databases: DatabaseInitResult[];
77
- config?: ConfigInitResult;
78
- warnings: string[];
79
- reason?: string;
80
- nextAction?: string;
81
- }
82
-
83
- // ── Build output ─────────────────────────────────────────────────────────────
84
-
85
- const DB_NAMES = {
86
- state: 'state.db',
87
- trajectory: 'trajectory.db',
88
- } as const;
89
-
90
- // ── Config file generation ─────────────────────────────────────────────────────
91
-
92
- /**
93
- * Build a clean YAML representation of the default PD config, injecting the
94
- * workspace.default path so that discoverWorkspaceDefault() can find it.
95
- *
96
- * PRI-645: `features` is a sparse map — the registry (DEFAULT_FEATURE_FLAGS)
97
- * owns every default value and computeEffectivePdConfig() fills missing flags
98
- * at read time. Materializing the full registry snapshot here would freeze
99
- * today's defaults against future graduation flips. An empty map is fully
100
- * valid (validatePdConfig only requires the section to be an object) and
101
- * means "every flag follows its registry default".
102
- *
103
- * Returns the YAML string (with header comment) for writing to disk.
104
- */
105
- function buildConfigYaml(workspaceDir: string): string {
106
- const config = getDefaultPdConfig();
107
- const yamlObj: Record<string, unknown> = {
108
- version: config.version,
109
- workspace: {
110
- default: workspaceDir,
111
- },
112
- features: {},
113
- runtimeProfiles: config.runtimeProfiles,
114
- internalAgents: config.internalAgents,
115
- ui: config.ui,
116
- };
117
- return CONFIG_HEADER + yaml.dump(yamlObj, {
118
- indent: 2,
119
- lineWidth: 120,
120
- noRefs: true,
121
- sortKeys: false,
122
- // js-yaml 5 renamed quotingType ('"' | "'") to quoteStyle.
123
- quoteStyle: 'double',
124
- forceQuotes: false,
125
- });
126
- }
127
-
128
- /**
129
- * Generate and write .pd/config.yaml if it does not already exist.
130
- * Validates the generated file with a round-trip parse+validate check.
131
- */
132
- function buildConfigInitResult(workspaceDir: string, confirm: boolean): ConfigInitResult {
133
- const configPath = path.join(workspaceDir, CONFIG_DIR, CONFIG_FILENAME);
134
- const warnings: string[] = [];
135
-
136
- if (!confirm) {
137
- return { path: configPath, status: 'skipped', warnings: [] };
138
- }
139
-
140
- // Ensure .pd directory exists
141
- const configDir = path.dirname(configPath);
142
- try {
143
- fs.mkdirSync(configDir, { recursive: true });
144
- } catch (err) {
145
- const reason = err instanceof Error ? err.message : String(err);
146
- return { path: configPath, status: 'failed', warnings: [`Failed to create ${configDir}: ${reason}`] };
147
- }
148
-
149
- // Build and write YAML
150
- let yamlContent: string;
151
- try {
152
- yamlContent = buildConfigYaml(workspaceDir);
153
- } catch (err) {
154
- const reason = err instanceof Error ? err.message : String(err);
155
- return { path: configPath, status: 'failed', warnings: [`Failed to build config YAML: ${reason}`] };
156
- }
157
-
158
- try {
159
- // Atomic exclusive create ('wx'): the write itself is the authoritative
160
- // existence check — fails with EEXIST if the file already exists (from a
161
- // previous run or a concurrent process). No existsSync pre-check, so there
162
- // is no TOCTOU window and the "never overwrite existing config" contract
163
- // is race-free (CodeQL js/race-condition).
164
- fs.writeFileSync(configPath, yamlContent, { encoding: 'utf8', flag: 'wx' });
165
- } catch (err) {
166
- if (isErrnoException(err) && err.code === 'EEXIST') {
167
- return { path: configPath, status: 'skipped', warnings: ['config.yaml already exists, skipped'] };
168
- }
169
- const reason = err instanceof Error ? err.message : String(err);
170
- return { path: configPath, status: 'failed', warnings: [`Failed to write ${configPath}: ${reason}`] };
171
- }
172
-
173
- // Round-trip validation: read back, parse, validate
174
- try {
175
- const raw = fs.readFileSync(configPath, 'utf8');
176
- const parsed: unknown = yaml.load(raw, { schema: yaml.JSON_SCHEMA });
177
- const validationResult = validatePdConfig(parsed);
178
- if (!validationResult.ok) {
179
- warnings.push(`config.yaml round-trip validation produced ${validationResult.errors.length} warnings`);
180
- for (const ve of validationResult.errors) {
181
- warnings.push(` [${ve.path}] ${ve.reason} — ${ve.nextAction}`);
182
- }
183
- }
184
- } catch (err) {
185
- // Non-fatal: proceed even if round-trip check fails
186
- warnings.push(`config.yaml round-trip check skipped: ${err instanceof Error ? err.message : String(err)}`);
187
- }
188
-
189
- return { path: configPath, status: 'initialized', warnings };
190
- }
191
-
192
- export function buildRuntimeInitOutput(workspaceDir: string, confirm: boolean): RuntimeInitOutput {
193
- const resolvedWorkspace = path.resolve(workspaceDir);
194
- const warnings: string[] = [];
195
- const databases: DatabaseInitResult[] = [];
196
-
197
- // 1. state.db (via SqliteConnection, which triggers initSchema + migrateSchema)
198
- const stateDbPath = path.join(resolvedWorkspace, '.pd', 'state.db');
199
- if (!confirm) {
200
- // dry-run: report what would be initialized without touching disk
201
- databases.push({
202
- name: DB_NAMES.state,
203
- path: stateDbPath,
204
- tables: ['tasks', 'runs', 'artifacts', 'commits', 'principle_candidates',
205
- 'pi_artifacts', 'approvals', 'activations', 'intent_decisions', 'schema_version'],
206
- status: 'skipped',
207
- warnings: [],
208
- });
209
- } else {
210
- try {
211
- const conn = new SqliteConnection({ workspaceDir: resolvedWorkspace, readonly: false });
212
- try {
213
- conn.getDb(); // triggers initSchema + migrateSchema
214
- const connWarnings = conn.getSchemaInitWarnings();
215
- if (connWarnings.length > 0) {
216
- warnings.push(...connWarnings.map(w => `${DB_NAMES.state}: ${w}`));
217
- }
218
- databases.push({
219
- name: DB_NAMES.state,
220
- path: stateDbPath,
221
- tables: ['tasks', 'runs', 'artifacts', 'commits', 'principle_candidates',
222
- 'pi_artifacts', 'approvals', 'activations', 'intent_decisions', 'schema_version'],
223
- status: 'initialized',
224
- warnings: connWarnings,
225
- });
226
- } finally {
227
- conn.close();
228
- }
229
- } catch (err) {
230
- const reason = err instanceof Error ? err.message : String(err);
231
- databases.push({
232
- name: DB_NAMES.state,
233
- path: stateDbPath,
234
- tables: [],
235
- status: 'failed',
236
- warnings: [reason],
237
- });
238
- return {
239
- ok: false,
240
- mode: 'confirm',
241
- workspace: resolvedWorkspace,
242
- databases,
243
- warnings,
244
- reason: `state.db initialization failed: ${reason}`,
245
- nextAction: 'Check workspace directory permissions and disk space, then retry.',
246
- };
247
- }
248
- }
249
-
250
- // 2. trajectory.db (via initTrajectorySchema)
251
- if (!confirm) {
252
- databases.push({
253
- name: DB_NAMES.trajectory,
254
- path: path.join(resolvedWorkspace, '.state', 'trajectory.db'),
255
- // PRI-774: derived from TRAJECTORY_TABLES — same canonical source as
256
- // the real init, so the dry-run report can never drift.
257
- tables: [...TRAJECTORY_TABLES],
258
- status: 'skipped',
259
- warnings: [],
260
- });
261
- } else {
262
- try {
263
- const result = initTrajectorySchema(resolvedWorkspace);
264
- if (result.warnings.length > 0) {
265
- warnings.push(...result.warnings.map((w: string) => `${DB_NAMES.trajectory}: ${w}`));
266
- }
267
- databases.push({
268
- name: DB_NAMES.trajectory,
269
- path: path.join(resolvedWorkspace, '.state', 'trajectory.db'),
270
- tables: result.tables,
271
- status: 'initialized',
272
- warnings: result.warnings,
273
- });
274
- } catch (err) {
275
- const reason = err instanceof Error ? err.message : String(err);
276
- databases.push({
277
- name: DB_NAMES.trajectory,
278
- path: path.join(resolvedWorkspace, '.state', 'trajectory.db'),
279
- tables: [],
280
- status: 'failed',
281
- warnings: [reason],
282
- });
283
- return {
284
- ok: false,
285
- mode: 'confirm',
286
- workspace: resolvedWorkspace,
287
- databases,
288
- warnings,
289
- reason: `trajectory.db initialization failed: ${reason}`,
290
- nextAction: 'Check workspace directory permissions and disk space, then retry.',
291
- };
292
- }
293
- }
294
-
295
- // 3. subagent_workflows.db — no longer initialized (PRI-737): the legacy
296
- // workflow store had zero producers and the worker chain is retired.
297
- // Existing legacy databases in old workspaces are left untouched.
298
-
299
- // Verify state.db schema conformance after initialization (confirm mode only)
300
- if (confirm) {
301
- try {
302
- const conformance = new SchemaConformanceReadModel({ workspaceDir: resolvedWorkspace });
303
- const result = conformance.check();
304
- if (result.overallStatus === 'error') {
305
- warnings.push(`state.db schema conformance check returned 'error' — some tables or indexes may be missing`);
306
- }
307
- } catch (err) {
308
- // Non-fatal: schema conformance check is a post-verification step
309
- warnings.push(`schema conformance verification skipped: ${err instanceof Error ? err.message : String(err)}`);
310
- }
311
- }
312
-
313
- // 4. config.yaml — scaffold the single source of truth (P0: runtime discovery)
314
- const config = buildConfigInitResult(resolvedWorkspace, confirm);
315
- if (config.status === 'failed') {
316
- return {
317
- ok: false,
318
- mode: 'confirm',
319
- workspace: resolvedWorkspace,
320
- databases,
321
- config,
322
- warnings,
323
- reason: config.warnings[0] ?? 'config.yaml initialization failed',
324
- nextAction: 'Check .pd directory permissions and disk space, then re-run `pd runtime init --confirm`.',
325
- };
326
- }
327
-
328
- return {
329
- ok: true,
330
- mode: confirm ? 'confirm' : 'dry-run',
331
- workspace: resolvedWorkspace,
332
- databases,
333
- config,
334
- warnings,
335
- };
336
- }
337
-
338
- // ── Text formatting ──────────────────────────────────────────────────────────
339
-
340
- function formatTextOutput(output: RuntimeInitOutput): string {
341
- const lines: string[] = [];
342
-
343
- lines.push('PD Runtime Init');
344
- lines.push(`mode: ${output.mode}`);
345
- lines.push(`workspace: ${output.workspace}`);
346
- lines.push('');
347
-
348
- for (const db of output.databases) {
349
- const icon = db.status === 'initialized' ? '[+]' :
350
- db.status === 'verified' ? '[v]' :
351
- db.status === 'skipped' ? '[ ]' : '[x]';
352
- lines.push(`${icon} ${db.name} (${db.status})`);
353
- lines.push(` path: ${db.path}`);
354
- if (db.tables.length > 0) {
355
- lines.push(` tables: ${db.tables.length} (${db.tables.slice(0, 5).join(', ')}${db.tables.length > 5 ? ', ...' : ''})`);
356
- }
357
- for (const w of db.warnings) {
358
- lines.push(` warning: ${w}`);
359
- }
360
- }
361
-
362
- if (output.config) {
363
- const icon = output.config.status === 'initialized' ? '[+]' :
364
- output.config.status === 'verified' ? '[v]' :
365
- output.config.status === 'skipped' ? '[ ]' : '[x]';
366
- lines.push(`${icon} config.yaml (${output.config.status})`);
367
- lines.push(` path: ${output.config.path}`);
368
- for (const w of output.config.warnings) {
369
- lines.push(` warning: ${w}`);
370
- }
371
- }
372
-
373
- if (output.warnings.length > 0) {
374
- lines.push('');
375
- lines.push('Warnings:');
376
- for (const w of output.warnings) {
377
- lines.push(` [!] ${w}`);
378
- }
379
- }
380
-
381
- if (!output.ok && output.reason) {
382
- lines.push('');
383
- lines.push(`Error: ${output.reason}`);
384
- if (output.nextAction) {
385
- lines.push(`→ ${output.nextAction}`);
386
- }
387
- }
388
-
389
- return lines.join('\n');
390
- }
391
-
392
- // ── CLI handler ──────────────────────────────────────────────────────────────
393
-
394
- export interface RuntimeInitOptions {
395
- workspace?: string;
396
- dryRun?: boolean;
397
- confirm?: boolean;
398
- json?: boolean;
399
- }
400
-
401
- export async function handleRuntimeInit(opts: RuntimeInitOptions): Promise<void> {
402
- // cli-4: --dry-run and --confirm are mutually exclusive
403
- if (opts.dryRun && opts.confirm) {
404
- process.exitCode = emitFlagConflict({ json: opts.json ?? false });
405
- return;
406
- }
407
-
408
- const workspaceDir = opts.workspace
409
- ? path.resolve(opts.workspace)
410
- : resolveWorkspaceDir();
411
-
412
- // Default is dry-run; --confirm opts in to actual initialization
413
- const confirm = opts.confirm === true;
414
-
415
- try {
416
- const output = buildRuntimeInitOutput(workspaceDir, confirm);
417
- emitResult(output, { json: opts.json ?? false, formatText: formatTextOutput });
418
-
419
- if (!output.ok) {
420
- process.exitCode = 1; // cli-2: set exit code, no process.exit()
421
- }
422
- } catch (err) {
423
- process.exitCode = emitError(err, {
424
- json: opts.json ?? false,
425
- nextAction: 'Check workspace directory and permissions, then retry.',
426
- });
427
- }
428
- }
429
-