@principles/pd-cli 1.152.11 → 1.152.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (303) hide show
  1. package/dist/commands/candidate.d.ts +3 -3
  2. package/dist/commands/candidate.d.ts.map +1 -1
  3. package/dist/commands/candidate.js +9 -21
  4. package/dist/commands/candidate.js.map +1 -1
  5. package/dist/index.js +0 -0
  6. package/dist/services/rulehost-pipeline-runner.d.ts.map +1 -1
  7. package/dist/services/rulehost-pipeline-runner.js +4 -17
  8. package/dist/services/rulehost-pipeline-runner.js.map +1 -1
  9. package/package.json +13 -7
  10. package/dist/commands/__tests__/intent-flag-wiring.test.d.ts +0 -9
  11. package/dist/commands/__tests__/intent-flag-wiring.test.d.ts.map +0 -1
  12. package/dist/commands/__tests__/intent-flag-wiring.test.js +0 -237
  13. package/dist/commands/__tests__/intent-flag-wiring.test.js.map +0 -1
  14. package/dist/commands/__tests__/legacy-cleanup.test.d.ts +0 -18
  15. package/dist/commands/__tests__/legacy-cleanup.test.d.ts.map +0 -1
  16. package/dist/commands/__tests__/legacy-cleanup.test.js +0 -467
  17. package/dist/commands/__tests__/legacy-cleanup.test.js.map +0 -1
  18. package/dist/commands/__tests__/mvp-smoke.test.d.ts +0 -15
  19. package/dist/commands/__tests__/mvp-smoke.test.d.ts.map +0 -1
  20. package/dist/commands/__tests__/mvp-smoke.test.js +0 -262
  21. package/dist/commands/__tests__/mvp-smoke.test.js.map +0 -1
  22. package/dist/commands/__tests__/pain-retry-maxTokens-flag.test.d.ts +0 -2
  23. package/dist/commands/__tests__/pain-retry-maxTokens-flag.test.d.ts.map +0 -1
  24. package/dist/commands/__tests__/pain-retry-maxTokens-flag.test.js +0 -60
  25. package/dist/commands/__tests__/pain-retry-maxTokens-flag.test.js.map +0 -1
  26. package/dist/commands/__tests__/rulecode-flag-wiring.test.d.ts +0 -21
  27. package/dist/commands/__tests__/rulecode-flag-wiring.test.d.ts.map +0 -1
  28. package/dist/commands/__tests__/rulecode-flag-wiring.test.js +0 -186
  29. package/dist/commands/__tests__/rulecode-flag-wiring.test.js.map +0 -1
  30. package/dist/commands/__tests__/rulecode-handler.test.d.ts +0 -16
  31. package/dist/commands/__tests__/rulecode-handler.test.d.ts.map +0 -1
  32. package/dist/commands/__tests__/rulecode-handler.test.js +0 -285
  33. package/dist/commands/__tests__/rulecode-handler.test.js.map +0 -1
  34. package/dist/commands/__tests__/run-rulehost-flag-wiring.test.d.ts +0 -24
  35. package/dist/commands/__tests__/run-rulehost-flag-wiring.test.d.ts.map +0 -1
  36. package/dist/commands/__tests__/run-rulehost-flag-wiring.test.js +0 -232
  37. package/dist/commands/__tests__/run-rulehost-flag-wiring.test.js.map +0 -1
  38. package/dist/commands/__tests__/runtime-activation-nextaction.test.d.ts +0 -15
  39. package/dist/commands/__tests__/runtime-activation-nextaction.test.d.ts.map +0 -1
  40. package/dist/commands/__tests__/runtime-activation-nextaction.test.js +0 -73
  41. package/dist/commands/__tests__/runtime-activation-nextaction.test.js.map +0 -1
  42. package/dist/commands/__tests__/runtime-probe-config.test.d.ts +0 -20
  43. package/dist/commands/__tests__/runtime-probe-config.test.d.ts.map +0 -1
  44. package/dist/commands/__tests__/runtime-probe-config.test.js +0 -389
  45. package/dist/commands/__tests__/runtime-probe-config.test.js.map +0 -1
  46. package/dist/commands/__tests__/telemetry-flag-wiring.test.d.ts +0 -9
  47. package/dist/commands/__tests__/telemetry-flag-wiring.test.d.ts.map +0 -1
  48. package/dist/commands/__tests__/telemetry-flag-wiring.test.js +0 -76
  49. package/dist/commands/__tests__/telemetry-flag-wiring.test.js.map +0 -1
  50. package/dist/commands/__tests__/version.test.d.ts +0 -2
  51. package/dist/commands/__tests__/version.test.d.ts.map +0 -1
  52. package/dist/commands/__tests__/version.test.js +0 -238
  53. package/dist/commands/__tests__/version.test.js.map +0 -1
  54. package/dist/commands/runtime-uat.guard.test.d.ts +0 -2
  55. package/dist/commands/runtime-uat.guard.test.d.ts.map +0 -1
  56. package/dist/commands/runtime-uat.guard.test.js +0 -153
  57. package/dist/commands/runtime-uat.guard.test.js.map +0 -1
  58. package/dist/services/__tests__/cli-output.test.d.ts +0 -18
  59. package/dist/services/__tests__/cli-output.test.d.ts.map +0 -1
  60. package/dist/services/__tests__/cli-output.test.js +0 -103
  61. package/dist/services/__tests__/cli-output.test.js.map +0 -1
  62. package/dist/services/__tests__/evaluator-runner-deps.test.d.ts +0 -2
  63. package/dist/services/__tests__/evaluator-runner-deps.test.d.ts.map +0 -1
  64. package/dist/services/__tests__/evaluator-runner-deps.test.js +0 -343
  65. package/dist/services/__tests__/evaluator-runner-deps.test.js.map +0 -1
  66. package/dist/services/__tests__/rulehost-readiness.test.d.ts +0 -2
  67. package/dist/services/__tests__/rulehost-readiness.test.d.ts.map +0 -1
  68. package/dist/services/__tests__/rulehost-readiness.test.js +0 -311
  69. package/dist/services/__tests__/rulehost-readiness.test.js.map +0 -1
  70. package/dist/services/__tests__/runtime-adapter-resolver.test.d.ts +0 -18
  71. package/dist/services/__tests__/runtime-adapter-resolver.test.d.ts.map +0 -1
  72. package/dist/services/__tests__/runtime-adapter-resolver.test.js +0 -673
  73. package/dist/services/__tests__/runtime-adapter-resolver.test.js.map +0 -1
  74. package/dist/utils/production-workspace-guard.test.d.ts +0 -2
  75. package/dist/utils/production-workspace-guard.test.d.ts.map +0 -1
  76. package/dist/utils/production-workspace-guard.test.js +0 -137
  77. package/dist/utils/production-workspace-guard.test.js.map +0 -1
  78. package/scripts/llm-dogfood.ts +0 -456
  79. package/scripts/migrate-illegal-expected-decision.ts +0 -252
  80. package/src/commands/__tests__/intent-flag-wiring.test.ts +0 -282
  81. package/src/commands/__tests__/legacy-cleanup.test.ts +0 -602
  82. package/src/commands/__tests__/mvp-smoke.test.ts +0 -300
  83. package/src/commands/__tests__/pain-retry-maxTokens-flag.test.ts +0 -73
  84. package/src/commands/__tests__/rulecode-flag-wiring.test.ts +0 -237
  85. package/src/commands/__tests__/rulecode-handler.test.ts +0 -369
  86. package/src/commands/__tests__/run-rulehost-flag-wiring.test.ts +0 -292
  87. package/src/commands/__tests__/runtime-activation-nextaction.test.ts +0 -81
  88. package/src/commands/__tests__/runtime-probe-config.test.ts +0 -432
  89. package/src/commands/__tests__/telemetry-flag-wiring.test.ts +0 -84
  90. package/src/commands/__tests__/version.test.ts +0 -251
  91. package/src/commands/admission-gate.ts +0 -30
  92. package/src/commands/artifact.ts +0 -82
  93. package/src/commands/build-trajectory-evidence.ts +0 -298
  94. package/src/commands/candidate.ts +0 -1260
  95. package/src/commands/codex-ingest-catchup.ts +0 -114
  96. package/src/commands/codex-ingest-quarantine.ts +0 -127
  97. package/src/commands/codex-reconcile.ts +0 -84
  98. package/src/commands/codex-setup.ts +0 -476
  99. package/src/commands/codex-worker.ts +0 -185
  100. package/src/commands/command-helpers.ts +0 -24
  101. package/src/commands/config-doctor.ts +0 -193
  102. package/src/commands/console.ts +0 -797
  103. package/src/commands/context.ts +0 -72
  104. package/src/commands/demo-story-a.ts +0 -241
  105. package/src/commands/diagnose.ts +0 -756
  106. package/src/commands/errors-list.ts +0 -441
  107. package/src/commands/evolution-tasks-list.ts +0 -48
  108. package/src/commands/evolution-tasks-show.ts +0 -62
  109. package/src/commands/flow.ts +0 -60
  110. package/src/commands/health-codex.ts +0 -576
  111. package/src/commands/health.ts +0 -315
  112. package/src/commands/history.ts +0 -63
  113. package/src/commands/intent.ts +0 -457
  114. package/src/commands/legacy-cleanup.ts +0 -531
  115. package/src/commands/legacy-import.ts +0 -104
  116. package/src/commands/mvp-smoke.ts +0 -160
  117. package/src/commands/pain-evidence.ts +0 -226
  118. package/src/commands/pain-list.ts +0 -239
  119. package/src/commands/pain-record.ts +0 -612
  120. package/src/commands/pain-retry.ts +0 -916
  121. package/src/commands/principles-stats.ts +0 -700
  122. package/src/commands/proven-channel-baseline.ts +0 -115
  123. package/src/commands/quality-scorecard.ts +0 -272
  124. package/src/commands/remediation-output.ts +0 -66
  125. package/src/commands/rulecode.ts +0 -465
  126. package/src/commands/run.ts +0 -89
  127. package/src/commands/runtime-activation.ts +0 -1629
  128. package/src/commands/runtime-artifact-repair.ts +0 -524
  129. package/src/commands/runtime-canary.ts +0 -395
  130. package/src/commands/runtime-compatibility-scan.ts +0 -105
  131. package/src/commands/runtime-diagnostics-export.ts +0 -229
  132. package/src/commands/runtime-features.ts +0 -153
  133. package/src/commands/runtime-gfi-snapshot.ts +0 -135
  134. package/src/commands/runtime-health-snapshot.ts +0 -108
  135. package/src/commands/runtime-init.ts +0 -429
  136. package/src/commands/runtime-internalization-enqueue-successors.ts +0 -530
  137. package/src/commands/runtime-internalization-integrity-repair.ts +0 -79
  138. package/src/commands/runtime-internalization-integrity.ts +0 -107
  139. package/src/commands/runtime-internalization-queue.ts +0 -135
  140. package/src/commands/runtime-internalization-retry.ts +0 -191
  141. package/src/commands/runtime-internalization-run-once.ts +0 -791
  142. package/src/commands/runtime-internalization-run-rulehost.ts +0 -749
  143. package/src/commands/runtime-internalization-wake-once.ts +0 -87
  144. package/src/commands/runtime-pain-flood-simulation.ts +0 -121
  145. package/src/commands/runtime-pruning.ts +0 -438
  146. package/src/commands/runtime-recovery-failed-tasks.ts +0 -258
  147. package/src/commands/runtime-recovery.ts +0 -109
  148. package/src/commands/runtime-synthetic-baseline.ts +0 -70
  149. package/src/commands/runtime-uat.guard.test.ts +0 -175
  150. package/src/commands/runtime-uat.ts +0 -380
  151. package/src/commands/runtime.ts +0 -473
  152. package/src/commands/samples-list.ts +0 -39
  153. package/src/commands/samples-review.ts +0 -36
  154. package/src/commands/task.ts +0 -271
  155. package/src/commands/telemetry.ts +0 -349
  156. package/src/commands/trace.ts +0 -174
  157. package/src/commands/trajectory-db-unavailable.ts +0 -19
  158. package/src/commands/trajectory.ts +0 -64
  159. package/src/commands/version.ts +0 -49
  160. package/src/config-reader.ts +0 -122
  161. package/src/index.ts +0 -1276
  162. package/src/legacy/legacy-import.ts +0 -179
  163. package/src/legacy/session-history-import.ts +0 -203
  164. package/src/resolve-workspace.ts +0 -106
  165. package/src/services/__tests__/cli-output.test.ts +0 -130
  166. package/src/services/__tests__/evaluator-runner-deps.test.ts +0 -382
  167. package/src/services/__tests__/rulehost-readiness.test.ts +0 -363
  168. package/src/services/__tests__/runtime-adapter-resolver.test.ts +0 -793
  169. package/src/services/cli-output.ts +0 -95
  170. package/src/services/config-doctor.ts +0 -697
  171. package/src/services/console-launcher.ts +0 -537
  172. package/src/services/demo-rule-compiler.ts +0 -40
  173. package/src/services/demo-story-a-runner.ts +0 -471
  174. package/src/services/mainline-snapshot-assembler.ts +0 -579
  175. package/src/services/pain-flood-simulation-runner.ts +0 -462
  176. package/src/services/pd-config-loader.ts +0 -433
  177. package/src/services/proven-channel-baseline-runner.ts +0 -157
  178. package/src/services/quality-scorecard/data-extractor.ts +0 -150
  179. package/src/services/quality-scorecard/local-evaluator.ts +0 -142
  180. package/src/services/quality-scorecard/strong-model-gate.ts +0 -202
  181. package/src/services/resolve-runtime-from-pd-config.ts +0 -230
  182. package/src/services/rulehost-pipeline-runner.ts +0 -1216
  183. package/src/services/rulehost-readiness.ts +0 -326
  184. package/src/services/runtime-adapter-resolver.ts +0 -364
  185. package/src/services/synthetic-baseline-runner.ts +0 -400
  186. package/src/services/version-report.ts +0 -253
  187. package/src/services/workspace-tool-semantics.ts +0 -26
  188. package/src/utils/path-security.ts +0 -96
  189. package/src/utils/production-workspace-guard.test.ts +0 -157
  190. package/src/utils/production-workspace-guard.ts +0 -210
  191. package/tests/bdd/cli-contract.steps.ts +0 -346
  192. package/tests/bdd/principles-stats.steps.ts +0 -211
  193. package/tests/bdd/support/gherkin-loader.ts +0 -147
  194. package/tests/bdd/support/repo-root.ts +0 -62
  195. package/tests/bdd/support/vitest-bdd.ts +0 -179
  196. package/tests/commands/admission-gate-coverage.test.ts +0 -79
  197. package/tests/commands/build-trajectory-evidence.test.ts +0 -508
  198. package/tests/commands/candidate-audit-repair.test.ts +0 -421
  199. package/tests/commands/candidate-intake.test.ts +0 -732
  200. package/tests/commands/candidate-internalization-backfill.test.ts +0 -548
  201. package/tests/commands/candidate-internalize-lineage.test.ts +0 -565
  202. package/tests/commands/candidate-internalize.test.ts +0 -299
  203. package/tests/commands/candidate-route.test.ts +0 -329
  204. package/tests/commands/candidate-show.test.ts +0 -95
  205. package/tests/commands/cli-command-tree.test.ts +0 -144
  206. package/tests/commands/cli-help-snapshot.test.ts +0 -155
  207. package/tests/commands/cli-skill-contract.test.ts +0 -121
  208. package/tests/commands/codex-consent-reversibility.steps.test.ts +0 -299
  209. package/tests/commands/codex-ingest-quarantine.test.ts +0 -136
  210. package/tests/commands/codex-setup.test.ts +0 -297
  211. package/tests/commands/codex-worker-daemon.test.ts +0 -95
  212. package/tests/commands/codex-worker-registration.test.ts +0 -207
  213. package/tests/commands/config-doctor.test.ts +0 -336
  214. package/tests/commands/console-launcher-edge-cases.test.ts +0 -388
  215. package/tests/commands/console-open.test.ts +0 -1381
  216. package/tests/commands/context.test.ts +0 -114
  217. package/tests/commands/demo-story-a.test.ts +0 -318
  218. package/tests/commands/diagnose.test.ts +0 -1803
  219. package/tests/commands/errors-list.test.ts +0 -679
  220. package/tests/commands/evolution-tasks-list.test.ts +0 -41
  221. package/tests/commands/evolution-tasks-show.test.ts +0 -46
  222. package/tests/commands/health-codex.test.ts +0 -349
  223. package/tests/commands/health-host-wiring.test.ts +0 -76
  224. package/tests/commands/health-reliability.test.ts +0 -99
  225. package/tests/commands/health.test.ts +0 -413
  226. package/tests/commands/intent.test.ts +0 -321
  227. package/tests/commands/legacy-cleanup.test.ts +0 -148
  228. package/tests/commands/pain-evidence.test.ts +0 -518
  229. package/tests/commands/pain-list.test.ts +0 -219
  230. package/tests/commands/pain-record-async.test.ts +0 -335
  231. package/tests/commands/pain-record-session-parser.test.ts +0 -228
  232. package/tests/commands/pain-record.test.ts +0 -851
  233. package/tests/commands/pain-retry.test.ts +0 -1121
  234. package/tests/commands/plugin-config-resolution-cutover.test.ts +0 -229
  235. package/tests/commands/pri-393-runtime-config-unification.test.ts +0 -443
  236. package/tests/commands/principles-stats-wiring.test.ts +0 -135
  237. package/tests/commands/principles-stats.test.ts +0 -274
  238. package/tests/commands/product-path-regression.test.ts +0 -86
  239. package/tests/commands/proven-channel-baseline.test.ts +0 -441
  240. package/tests/commands/rulecode.test.ts +0 -177
  241. package/tests/commands/run-rulehost-handler.test.ts +0 -908
  242. package/tests/commands/runtime-activation-approve-flag-wiring.test.ts +0 -227
  243. package/tests/commands/runtime-activation-deactivate-flag-wiring.test.ts +0 -167
  244. package/tests/commands/runtime-activation-dispatch-flag-wiring.test.ts +0 -262
  245. package/tests/commands/runtime-activation-governance-audit.test.ts +0 -95
  246. package/tests/commands/runtime-activation-list-flag-wiring.test.ts +0 -193
  247. package/tests/commands/runtime-activation-promote-flag-wiring.test.ts +0 -248
  248. package/tests/commands/runtime-activation-shadow-telemetry.test.ts +0 -130
  249. package/tests/commands/runtime-activation.test.ts +0 -2052
  250. package/tests/commands/runtime-artifact-repair-registration.test.ts +0 -74
  251. package/tests/commands/runtime-artifact-repair.test.ts +0 -404
  252. package/tests/commands/runtime-canary.test.ts +0 -430
  253. package/tests/commands/runtime-compatibility-scan.test.ts +0 -146
  254. package/tests/commands/runtime-diagnostics-export.test.ts +0 -175
  255. package/tests/commands/runtime-features.test.ts +0 -249
  256. package/tests/commands/runtime-health-snapshot.test.ts +0 -358
  257. package/tests/commands/runtime-init-empty-workspace.test.ts +0 -252
  258. package/tests/commands/runtime-init.test.ts +0 -420
  259. package/tests/commands/runtime-internalization-enqueue-successors.test.ts +0 -782
  260. package/tests/commands/runtime-internalization-integrity-repair.test.ts +0 -239
  261. package/tests/commands/runtime-internalization-integrity.test.ts +0 -140
  262. package/tests/commands/runtime-internalization-queue.test.ts +0 -380
  263. package/tests/commands/runtime-internalization-retry-owner-authority.test.ts +0 -431
  264. package/tests/commands/runtime-internalization-run-once-evaluator-parity.test.ts +0 -269
  265. package/tests/commands/runtime-internalization-run-once-language.test.ts +0 -303
  266. package/tests/commands/runtime-internalization-run-once-real-config.test.ts +0 -237
  267. package/tests/commands/runtime-internalization-run-once-rollout-parity.test.ts +0 -706
  268. package/tests/commands/runtime-internalization-run-once.test.ts +0 -1791
  269. package/tests/commands/runtime-internalization-wake-once.test.ts +0 -171
  270. package/tests/commands/runtime-internalization.test.ts +0 -53
  271. package/tests/commands/runtime-pain-flood-simulation.test.ts +0 -418
  272. package/tests/commands/runtime-pruning.test.ts +0 -694
  273. package/tests/commands/runtime-recovery-failed-tasks.test.ts +0 -328
  274. package/tests/commands/runtime-recovery.test.ts +0 -120
  275. package/tests/commands/runtime-synthetic-baseline.test.ts +0 -249
  276. package/tests/commands/runtime-uat.test.ts +0 -397
  277. package/tests/commands/runtime.test.ts +0 -392
  278. package/tests/commands/samples-list.test.ts +0 -43
  279. package/tests/commands/samples-review.test.ts +0 -41
  280. package/tests/commands/task.test.ts +0 -153
  281. package/tests/commands/telemetry.test.ts +0 -190
  282. package/tests/commands/trace.test.ts +0 -316
  283. package/tests/config-reader.test.ts +0 -143
  284. package/tests/e2e/candidate-intake-e2e.test.ts +0 -338
  285. package/tests/e2e/cli-full-flow.test.ts +0 -233
  286. package/tests/e2e/cross-package-acceptance.test.ts +0 -635
  287. package/tests/helpers/pd-cli-path.ts +0 -5
  288. package/tests/pd-cli-smoke.test.ts +0 -13
  289. package/tests/resolve-workspace.test.ts +0 -196
  290. package/tests/services/config-doctor-signal-health.test.ts +0 -109
  291. package/tests/services/console-launcher.test.ts +0 -114
  292. package/tests/services/demo-rule-compiler.test.ts +0 -242
  293. package/tests/services/mainline-snapshot-assembler.test.ts +0 -572
  294. package/tests/services/pd-config-loader.test.ts +0 -505
  295. package/tests/services/proven-channel-baseline-runner.test.ts +0 -30
  296. package/tests/services/quality-scorecard/strong-model-gate.test.ts +0 -133
  297. package/tests/services/resolve-runtime-from-pd-config.test.ts +0 -485
  298. package/tests/services/rulehost-pipeline-e2e.test.ts +0 -538
  299. package/tests/services/rulehost-pipeline-runner.test.ts +0 -1175
  300. package/tests/services/workspace-tool-semantics.test.ts +0 -76
  301. package/tests/utils/path-security.test.ts +0 -180
  302. package/tsconfig.json +0 -26
  303. package/vitest.config.ts +0 -9
@@ -1,797 +0,0 @@
1
- import * as path from 'path';
2
- import * as fs from 'fs';
3
- import { spawn, type ChildProcess } from 'child_process';
4
- import { resolveWorkspaceDir } from '../resolve-workspace.js';
5
- import {
6
- getConsoleServerEntry,
7
- getConsoleWebIndex,
8
- getInstallLayoutPaths,
9
- resolveInstallLayout,
10
- type InstallLayoutMode,
11
- } from '@principles/install-layout';
12
- import {
13
- planConsoleLaunch,
14
- openBrowser,
15
- isLoopbackHost,
16
- normalizeLoopbackHost,
17
- probeConsoleHealth,
18
- type ConsoleLaunchResult,
19
- } from '../services/console-launcher.js';
20
-
21
- function sleep(ms: number): Promise<void> {
22
- return new Promise((res) => setTimeout(res, ms));
23
- }
24
-
25
- interface ConsoleOpenOptions {
26
- workspace?: string;
27
- port?: string;
28
- host?: string;
29
- json?: boolean;
30
- noAuth?: boolean;
31
- /** Auth token for the Console. */
32
- token?: string;
33
- /** Skip browser opening even in non-JSON mode. */
34
- noBrowser?: boolean;
35
- }
36
-
37
- // ─── Backward-compatible top-level launcher (pd console) ─────────────────────
38
-
39
- interface ConsoleOptions {
40
- workspace?: string;
41
- port?: string;
42
- noAuth?: boolean;
43
- json?: boolean;
44
- }
45
-
46
- function getConsoleDir(): { dir: string; mode: InstallLayoutMode } | null {
47
- const homeDir = process.env.HOME || process.env.USERPROFILE;
48
- if (!homeDir) return null;
49
- const paths = getInstallLayoutPaths(homeDir);
50
- let manifest: unknown;
51
- try {
52
- manifest = JSON.parse(fs.readFileSync(paths.manifest, 'utf8')) as unknown;
53
- } catch {
54
- manifest = undefined;
55
- }
56
- const resolved = resolveInstallLayout({
57
- homeDir,
58
- manifest,
59
- canonicalRuntimeExists: fs.existsSync(paths.runtimeDir),
60
- legacyExtensionExists: fs.existsSync(paths.openClawExtensionDir),
61
- });
62
- if (resolved.mode === 'missing') return null;
63
- const dir = resolved.mode === 'canonical' ? paths.consoleDir : path.join(paths.openClawExtensionDir, 'console');
64
- return { dir, mode: resolved.mode };
65
- }
66
-
67
- /**
68
- * Verify the console server's runtime dependency slots are resolvable.
69
- *
70
- * The console's dist statically imports `@principles/core/runtime-v2` and
71
- * `@principles/host-runtime`, and reads plugin governance exports from
72
- * `principles-disciple`. Each slot must be a real package (package.json present
73
- * AND dist/index.js present) — a dangling junction or an empty shell (package.json
74
- * without dist) makes the server crash with ERR_MODULE_NOT_FOUND at startup.
75
- *
76
- * Returns a human-readable description of the first broken slot, or undefined
77
- * when everything is resolvable.
78
- */
79
- export function checkConsoleRuntimeDependencies(consoleDir: string): string | undefined {
80
- // These are the exact entry files the console server resolves at startup,
81
- // derived from each package's real `exports` map (not assumed dist/index.js):
82
- // @principles/core/principle-tree-ledger → dist/principle-tree-ledger.js
83
- // @principles/core/runtime-v2 → dist/runtime-v2/index.js
84
- // @principles/host-runtime → dist/index.js
85
- // @principles/install-layout → dist/index.js
86
- // principles-disciple/governance-audit → dist/governance-audit.js
87
- // Checking the real resolved entries (not just dist/index.js) catches broken
88
- // shells where package.json exists but the actual import target is missing.
89
- // One package can have multiple required entries (@principles/core).
90
- const slots: { pkg: string; entries: string[] }[] = [
91
- {
92
- pkg: '@principles/core',
93
- entries: [
94
- path.join('dist', 'principle-tree-ledger.js'),
95
- path.join('dist', 'runtime-v2', 'index.js'),
96
- ],
97
- },
98
- { pkg: '@principles/host-runtime', entries: [path.join('dist', 'index.js')] },
99
- { pkg: '@principles/install-layout', entries: [path.join('dist', 'index.js')] },
100
- { pkg: 'principles-disciple', entries: [path.join('dist', 'governance-audit.js')] },
101
- ];
102
- for (const slot of slots) {
103
- const base = path.join(consoleDir, 'node_modules', slot.pkg);
104
- const pkgJson = path.join(base, 'package.json');
105
- if (!fs.existsSync(pkgJson)) {
106
- return `console/node_modules/${slot.pkg}/package.json is missing`;
107
- }
108
- for (const entry of slot.entries) {
109
- const entryFile = path.join(base, entry);
110
- if (!fs.existsSync(entryFile)) {
111
- return `console/node_modules/${slot.pkg}/${entry.replaceAll('\\', '/')} is missing (incomplete package)`;
112
- }
113
- }
114
- }
115
- return undefined;
116
- }
117
-
118
- export async function handleConsole(opts: ConsoleOptions = {}): Promise<void> {
119
- const workspaceDir = opts.workspace
120
- ? path.resolve(opts.workspace)
121
- : resolveWorkspaceDir();
122
-
123
- const consoleLocation = getConsoleDir();
124
- if (!consoleLocation) {
125
- const msg = 'pd-console is not installed. Run: npx create-principles-disciple to install.';
126
- if (opts.json) {
127
- console.log(JSON.stringify({ success: false, reason: msg, nextAction: 'npx create-principles-disciple' }));
128
- } else {
129
- console.error(msg);
130
- }
131
- process.exit(1);
132
- return;
133
- }
134
-
135
- const paths = getInstallLayoutPaths(process.env.HOME || process.env.USERPROFILE || '.');
136
- const serverEntry = getConsoleServerEntry(paths, consoleLocation.mode);
137
- if (!fs.existsSync(serverEntry)) {
138
- const msg = `Console server entry not found at ${serverEntry}. Re-run installer.`;
139
- if (opts.json) {
140
- console.log(JSON.stringify({ success: false, reason: msg, nextAction: 'npx create-principles-disciple' }));
141
- } else {
142
- console.error(msg);
143
- }
144
- process.exit(1);
145
- return;
146
- }
147
-
148
- // EP-06 regression guard (PR #1169): verify web UI bundle exists before launch.
149
- // Without dist/web/index.html the server returns 404 "Run npm run build:ui first".
150
- const webIndex = getConsoleWebIndex(paths, consoleLocation.mode);
151
- if (!fs.existsSync(webIndex)) {
152
- const msg = `Console web UI not found at ${webIndex}. The console bundle is corrupted. Re-run installer.`;
153
- if (opts.json) {
154
- console.log(JSON.stringify({ success: false, reason: msg, nextAction: 'npx create-principles-disciple' }));
155
- } else {
156
- console.error(msg);
157
- }
158
- process.exit(1);
159
- return;
160
- }
161
-
162
- // Runtime dependency integrity check: the console server statically imports
163
- // @principles/core/runtime-v2 and @principles/host-runtime, and the console
164
- // reads plugin governance exports from principles-disciple. When the OpenClaw
165
- // upgrade path refreshes the plugin bundle without re-running the PD installer
166
- // (2026-09: console_cli_exited_before_result), these node_modules slots can be
167
- // left as an empty shell (package.json without dist) or a dangling junction.
168
- // The server then crashes with ERR_MODULE_NOT_FOUND at startup, which the
169
- // Companion reports as the opaque console_cli_exited_before_result. Fail loud
170
- // here with the actionable repair command instead.
171
- const integrityError = checkConsoleRuntimeDependencies(consoleLocation.dir);
172
- if (integrityError) {
173
- const msg = `Console runtime dependency broken: ${integrityError}. Re-run installer to repair.`;
174
- if (opts.json) {
175
- console.log(JSON.stringify({ success: false, reason: msg, nextAction: 'npx create-principles-disciple' }));
176
- } else {
177
- console.error(msg);
178
- }
179
- process.exit(1);
180
- return;
181
- }
182
-
183
- const port = opts.port || '3100';
184
- const host = '127.0.0.1';
185
- const args = [serverEntry, '--workspace', workspaceDir, '--port', port, '--host', host];
186
- if (opts.noAuth) args.push('--no-auth');
187
-
188
- const child = spawn(process.execPath, args, {
189
- stdio: opts.json ? 'pipe' : 'inherit',
190
- env: { ...process.env },
191
- });
192
-
193
- let startupConfirmed = false;
194
-
195
- child.on('error', (err) => {
196
- if (opts.json) {
197
- if (!startupConfirmed) {
198
- console.log(JSON.stringify({
199
- success: false,
200
- reason: `Console spawn failed: ${err.message}`,
201
- nextAction: 'Check Node.js installation and console server entry. Re-run: npx create-principles-disciple',
202
- }));
203
- }
204
- } else {
205
- console.error(`Console spawn failed: ${err.message}`);
206
- }
207
- process.exit(1);
208
- return;
209
- });
210
-
211
- child.on('exit', (code) => {
212
- if (code !== 0 && code !== null) {
213
- if (opts.json) {
214
- if (!startupConfirmed) {
215
- console.log(JSON.stringify({
216
- success: false,
217
- reason: `Console exited with code ${code}`,
218
- nextAction: 'Check console logs above. Re-run: npx create-principles-disciple',
219
- }));
220
- }
221
- } else {
222
- console.error(`Console exited with code ${code}`);
223
- }
224
- process.exit(typeof code === 'number' ? code : 1);
225
- return;
226
- }
227
- process.exit(0);
228
- });
229
-
230
- setTimeout(() => {
231
- if (child.exitCode === null) {
232
- startupConfirmed = true;
233
- if (opts.json) {
234
- console.log(JSON.stringify({
235
- success: true,
236
- status: 'running',
237
- url: `http://${host}:${port}`,
238
- workspace: workspaceDir,
239
- nextAction: `Open http://${host}:${port} in your browser`,
240
- }));
241
- } else {
242
- console.log(`Starting pd-console on http://${host}:${port}`);
243
- console.log(`Workspace: ${workspaceDir}`);
244
- console.log('Press Ctrl+C to stop');
245
- }
246
- }
247
- }, 2000);
248
-
249
- const cleanup = () => {
250
- try { child.kill('SIGTERM'); } catch { /* ignore */ }
251
- process.exit(0);
252
- };
253
- process.on('SIGINT', cleanup);
254
- process.on('SIGTERM', cleanup);
255
- }
256
-
257
- // ─── Seed-friendly launcher (pd console open) — PRI-300 ─────────────────────
258
-
259
- /**
260
- * Launch (or reuse) the PD Console with seed-friendly defaults:
261
- * - Default port 3100; auto-falls back to next free port
262
- * - Reuses an existing healthy Console if one is already running
263
- * - Opens the system browser on success (skipped in --json)
264
- * - Refuses non-loopback hosts
265
- * - Emits structured reason+nextAction on every failure path
266
- */
267
- export async function handleConsoleOpen(opts: ConsoleOpenOptions = {}): Promise<void> {
268
- // 1) Loopback safety (ERR-049: refuse non-loopback) — check FIRST so we
269
- // never reveal runtime information about non-loopback hosts and refuse before workspace resolution.
270
- const rawHost = opts.host ?? '127.0.0.1';
271
- // Normalize IPv6 bracket notation: [::1] → ::1 (ERR-049)
272
- const host = normalizeLoopbackHost(rawHost);
273
- if (!isLoopbackHost(host)) {
274
- const result: ConsoleLaunchResult = {
275
- status: 'refused',
276
- url: '',
277
- port: 0,
278
- host,
279
- workspaceDir: '',
280
- reused: false,
281
- browserOpened: false,
282
- reason: `Non-loopback host refused: '${host}'. Console binds to loopback only.`,
283
- nextAction: 'Use the default (127.0.0.1) or "localhost". Do not pass --host 0.0.0.0 or a LAN address.',
284
- };
285
- if (opts.json) {
286
- console.log(JSON.stringify(result, null, 2));
287
- } else {
288
- console.error(`error: ${result.reason}`);
289
- console.error(`next: ${result.nextAction}`);
290
- }
291
- process.exit(1);
292
- return;
293
- }
294
-
295
- // 2) Resolve workspace (ERR-040: fail loud if missing)
296
- let workspaceDir: string;
297
- try {
298
- workspaceDir = opts.workspace ? path.resolve(opts.workspace) : resolveWorkspaceDir();
299
- } catch (err) {
300
- const message = err instanceof Error ? err.message : String(err);
301
- const result: ConsoleLaunchResult = {
302
- status: 'failed',
303
- url: '',
304
- port: 0,
305
- host,
306
- workspaceDir: '',
307
- reused: false,
308
- browserOpened: false,
309
- reason: 'workspace_missing',
310
- nextAction: 'Pass --workspace <path>, set PD_WORKSPACE_DIR, or run from within an initialized workspace.',
311
- };
312
- if (opts.json) {
313
- console.log(JSON.stringify({ ...result, message }, null, 2));
314
- } else {
315
- console.error(`error: ${message}`);
316
- console.error(`next: ${result.nextAction}`);
317
- }
318
- process.exit(1);
319
- return;
320
- }
321
-
322
- // 3) Strict port parsing
323
- let preferredPort = 3100;
324
- if (opts.port !== undefined) {
325
- if (!/^\d+$/.test(opts.port)) {
326
- const result: ConsoleLaunchResult = {
327
- status: 'failed',
328
- url: '',
329
- port: 0,
330
- host,
331
- workspaceDir,
332
- reused: false,
333
- browserOpened: false,
334
- reason: `Invalid --port: '${opts.port}'. Must be an integer 1..65535.`,
335
- nextAction: 'Use --port 3100 (default) or another valid port number.',
336
- };
337
- if (opts.json) {
338
- console.log(JSON.stringify(result, null, 2));
339
- } else {
340
- console.error(`error: ${result.reason}`);
341
- console.error(`next: ${result.nextAction}`);
342
- }
343
- process.exit(1);
344
- return;
345
- }
346
- preferredPort = Number(opts.port);
347
- if (preferredPort < 1 || preferredPort > 65535) {
348
- const result: ConsoleLaunchResult = {
349
- status: 'failed',
350
- url: '',
351
- port: 0,
352
- host,
353
- workspaceDir,
354
- reused: false,
355
- browserOpened: false,
356
- reason: `Invalid --port: '${opts.port}'. Must be an integer 1..65535.`,
357
- nextAction: 'Use --port 3100 (default) or another valid port number.',
358
- };
359
- if (opts.json) {
360
- console.log(JSON.stringify(result, null, 2));
361
- } else {
362
- console.error(`error: ${result.reason}`);
363
- console.error(`next: ${result.nextAction}`);
364
- }
365
- process.exit(1);
366
- return;
367
- }
368
- }
369
-
370
- // 3) Check that the console runtime is installed (ERR-040: fail loud if missing)
371
- const consoleLocation = getConsoleDir();
372
- if (!consoleLocation) {
373
- const result: ConsoleLaunchResult = {
374
- status: 'failed',
375
- url: '',
376
- port: 0,
377
- host: '127.0.0.1',
378
- workspaceDir,
379
- reused: false,
380
- browserOpened: false,
381
- reason: 'console_runtime_not_installed',
382
- nextAction: 'Run: npx create-principles-disciple',
383
- };
384
- if (opts.json) {
385
- console.log(JSON.stringify(result, null, 2));
386
- } else {
387
- console.error(`error: ${result.reason}`);
388
- console.error(`next: ${result.nextAction}`);
389
- }
390
- process.exit(1);
391
- return;
392
- }
393
- const paths = getInstallLayoutPaths(process.env.HOME || process.env.USERPROFILE || '.');
394
- const serverEntry = getConsoleServerEntry(paths, consoleLocation.mode);
395
- if (!fs.existsSync(serverEntry)) {
396
- const result: ConsoleLaunchResult = {
397
- status: 'failed',
398
- url: '',
399
- port: 0,
400
- host: '127.0.0.1',
401
- workspaceDir,
402
- reused: false,
403
- browserOpened: false,
404
- reason: 'console_server_entry_missing',
405
- nextAction: `Re-run installer: npx create-principles-disciple (expected ${serverEntry})`,
406
- };
407
- if (opts.json) {
408
- console.log(JSON.stringify(result, null, 2));
409
- } else {
410
- console.error(`error: ${result.reason}`);
411
- console.error(`next: ${result.nextAction}`);
412
- }
413
- process.exit(1);
414
- return;
415
- }
416
-
417
- // EP-06 regression guard (PR #1169): verify web UI bundle exists before launch.
418
- // Without dist/web/index.html the server returns 404 "Run npm run build:ui first"
419
- // — a fatal first-impression bug for new users.
420
- const webIndex = getConsoleWebIndex(paths, consoleLocation.mode);
421
- if (!fs.existsSync(webIndex)) {
422
- const result: ConsoleLaunchResult = {
423
- status: 'failed',
424
- url: '',
425
- port: 0,
426
- host: '127.0.0.1',
427
- workspaceDir,
428
- reused: false,
429
- browserOpened: false,
430
- reason: 'console_web_ui_missing',
431
- nextAction: `Re-run installer: npx create-principles-disciple (expected ${webIndex})`,
432
- };
433
- if (opts.json) {
434
- console.log(JSON.stringify(result, null, 2));
435
- } else {
436
- console.error(`error: ${result.reason}`);
437
- console.error(`next: ${result.nextAction}`);
438
- }
439
- process.exit(1);
440
- return;
441
- }
442
-
443
- // 4) Read auth token for health probes (PD_CONSOLE_TOKEN)
444
- const rawToken = opts.token ?? process.env.PD_CONSOLE_TOKEN;
445
- const token = !opts.noAuth && rawToken?.trim() ? rawToken.trim() : undefined;
446
- // PRI-784: mismatch guidance must name where the token came from — a
447
- // persistently set env var survives "reopen without a token", so the
448
- // actionable advice differs fundamentally between flag and env sources.
449
- const tokenSource: 'flag' | 'env' = opts.token ? 'flag' : 'env';
450
-
451
- // 5) Plan the launch (reuse or fresh bind)
452
- let plan;
453
- try {
454
- plan = await planConsoleLaunch({ workspaceDir, preferredPort, host, token, ...(token ? { tokenSource } : {}) });
455
- } catch (err) {
456
- const message = err instanceof Error ? err.message : String(err);
457
- const result: ConsoleLaunchResult = {
458
- status: 'failed',
459
- url: '',
460
- port: preferredPort,
461
- host,
462
- workspaceDir,
463
- reused: false,
464
- browserOpened: false,
465
- reason: 'launch_plan_error',
466
- nextAction: 'Inspect logs and retry.',
467
- };
468
- if (opts.json) {
469
- console.log(JSON.stringify({ ...result, message }, null, 2));
470
- } else {
471
- console.error(`error: launch plan failed: ${message}`);
472
- }
473
- process.exit(1);
474
- return;
475
- }
476
-
477
- if (plan.status === 'refused') {
478
- const result: ConsoleLaunchResult = {
479
- status: 'refused',
480
- url: '',
481
- port: plan.port,
482
- host: plan.host,
483
- workspaceDir,
484
- reused: false,
485
- browserOpened: false,
486
- reason: plan.reason,
487
- nextAction: plan.nextAction,
488
- };
489
- if (opts.json) {
490
- console.log(JSON.stringify(result, null, 2));
491
- } else {
492
- console.error(`error: ${result.reason}`);
493
- console.error(`next: ${result.nextAction}`);
494
- }
495
- process.exit(1);
496
- return;
497
- }
498
-
499
- if (plan.status === 'reused') {
500
- // Existing console — verify health one more time (already healthy from plan, but be safe)
501
- const health = await probeConsoleHealth({ host: plan.host, port: plan.port, token });
502
- if (!health.healthy) {
503
- const result: ConsoleLaunchResult = {
504
- status: 'failed',
505
- url: '',
506
- port: plan.port,
507
- host: plan.host,
508
- workspaceDir,
509
- reused: false,
510
- browserOpened: false,
511
- reason: `port_in_use_by_non_console: ${health.reason ?? 'health probe failed'}`,
512
- nextAction: 'Stop the conflicting process, or use --port <free> to bind a different port.',
513
- };
514
- if (opts.json) {
515
- console.log(JSON.stringify(result, null, 2));
516
- } else {
517
- console.error(`error: ${result.reason}`);
518
- console.error(`next: ${result.nextAction}`);
519
- }
520
- process.exit(1);
521
- return;
522
- }
523
- // Reused path — do not spawn. Optionally open browser.
524
- let browserOpened = false;
525
- let browserWarning: string | undefined;
526
- if (!opts.json && !opts.noBrowser) {
527
- const result = await openBrowser(plan.url);
528
- browserOpened = result.opened;
529
- if (!result.opened) {
530
- browserWarning = result.reason;
531
- }
532
- }
533
- const out: ConsoleLaunchResult = {
534
- status: 'reused',
535
- url: plan.url,
536
- port: plan.port,
537
- host: plan.host,
538
- workspaceDir,
539
- reused: true,
540
- browserOpened,
541
- ...(health.authenticationMode ? { authenticationMode: health.authenticationMode } : {}),
542
- nextAction: browserOpened
543
- ? 'Browser opened to the running Console.'
544
- : `Open ${plan.url} in your browser to access the Console.`,
545
- };
546
- if (browserWarning) out.reason = `browser_open_failed: ${browserWarning}`;
547
- if (opts.json) {
548
- console.log(JSON.stringify(out, null, 2));
549
- } else {
550
- console.log(`Reusing existing Console at ${plan.url}`);
551
- if (browserOpened) {
552
- console.log('Browser opened.');
553
- } else if (browserWarning) {
554
- console.log(`Browser not opened: ${browserWarning}`);
555
- console.log(out.nextAction);
556
- } else {
557
- console.log(out.nextAction);
558
- }
559
- }
560
- return;
561
- }
562
-
563
- // 5) Fresh spawn path
564
- // Runtime dependency integrity check — only here, NOT before the reuse
565
- // probe above. A healthy console already running (reused) has its modules
566
- // loaded in memory; broken disk slots (dangling junction / empty shell left
567
- // by an interrupted update) must not prevent reusing it. Only when we are
568
- // about to execute the local console bytes do the local bytes need to be
569
- // resolvable. The server statically imports @principles/core/runtime-v2 and
570
- // @principles/host-runtime, and reads plugin governance exports from
571
- // principles-disciple; without this check a broken install crashes with
572
- // ERR_MODULE_NOT_FOUND which the Companion reports as the opaque
573
- // console_cli_exited_before_result.
574
- const integrityError = checkConsoleRuntimeDependencies(consoleLocation.dir);
575
- if (integrityError) {
576
- const result: ConsoleLaunchResult = {
577
- status: 'failed',
578
- url: '',
579
- port: plan.port,
580
- host: plan.host,
581
- workspaceDir,
582
- reused: false,
583
- browserOpened: false,
584
- reason: 'console_runtime_dependency_broken',
585
- nextAction: `Re-run installer: npx create-principles-disciple (${integrityError})`,
586
- };
587
- if (opts.json) {
588
- console.log(JSON.stringify(result, null, 2));
589
- } else {
590
- console.error(`error: ${result.reason}`);
591
- console.error(`next: ${result.nextAction}`);
592
- }
593
- process.exit(1);
594
- return;
595
- }
596
-
597
- const args = [serverEntry, '--workspace', workspaceDir, '--port', String(plan.port), '--host', plan.host];
598
- if (opts.noAuth) args.push('--no-auth');
599
- if (opts.token) args.push('--token', opts.token);
600
-
601
- const child: ChildProcess = spawn(process.execPath, args, {
602
- stdio: opts.json ? 'pipe' : 'inherit',
603
- env: { ...process.env },
604
- });
605
-
606
- let resolved = false;
607
- const resolveOnce = (fn: () => void) => {
608
- if (resolved) return;
609
- resolved = true;
610
- fn();
611
- };
612
-
613
- const cleanup = () => {
614
- resolveOnce(() => {
615
- try { child.kill('SIGTERM'); } catch { /* ignore */ }
616
- process.exit(0);
617
- });
618
- };
619
-
620
- child.on('error', (err) => {
621
- resolveOnce(() => {
622
- const result: ConsoleLaunchResult = {
623
- status: 'failed',
624
- url: '',
625
- port: plan.port,
626
- host: plan.host,
627
- workspaceDir,
628
- reused: false,
629
- browserOpened: false,
630
- reason: `console_spawn_failed: ${err.message}`,
631
- nextAction: 'Check Node.js and package path configuration.',
632
- };
633
- if (opts.json) {
634
- console.log(JSON.stringify(result, null, 2));
635
- } else {
636
- console.error(`error: ${result.reason}`);
637
- }
638
- try { child.kill('SIGTERM'); } catch { /* ignore */ }
639
- process.exit(1);
640
- });
641
- });
642
-
643
- process.on('SIGINT', cleanup);
644
- process.on('SIGTERM', cleanup);
645
-
646
- // 7) Wait for console ready (bounded poll)
647
- const readyDeadline = Date.now() + 15_000;
648
- let ready = false;
649
- let readyAuthenticationMode: 'authenticated' | 'no_auth' | undefined;
650
- while (Date.now() < readyDeadline) {
651
- if (child.exitCode !== null) break;
652
- const h = await probeConsoleHealth({ host: plan.host, port: plan.port, timeoutMs: 1000, token });
653
- if (h.healthy) {
654
- ready = true;
655
- readyAuthenticationMode = h.authenticationMode;
656
- break;
657
- }
658
- await sleep(250);
659
- }
660
-
661
- if (child.exitCode !== null && child.exitCode !== 0) {
662
- const result: ConsoleLaunchResult = {
663
- status: 'failed',
664
- url: '',
665
- port: plan.port,
666
- host: plan.host,
667
- workspaceDir,
668
- reused: false,
669
- browserOpened: false,
670
- reason: `console_exited_with_code_${child.exitCode}`,
671
- nextAction: 'Check console logs above. Re-run: npx create-principles-disciple',
672
- };
673
- if (opts.json) {
674
- console.log(JSON.stringify(result, null, 2));
675
- } else {
676
- console.error(`error: ${result.reason}`);
677
- }
678
- process.exit(typeof child.exitCode === 'number' ? child.exitCode : 1);
679
- return;
680
- }
681
-
682
- if (!ready) {
683
- // Clean up: kill the orphan child
684
- try { child.kill('SIGTERM'); } catch { /* ignore */ }
685
- const result: ConsoleLaunchResult = {
686
- status: 'failed',
687
- url: '',
688
- port: plan.port,
689
- host: plan.host,
690
- workspaceDir,
691
- reused: false,
692
- browserOpened: false,
693
- reason: 'console_health_check_timeout',
694
- nextAction: 'Increase timeout, free system resources, or re-run: npx create-principles-disciple',
695
- };
696
- if (opts.json) {
697
- console.log(JSON.stringify(result, null, 2));
698
- } else {
699
- console.error(`error: ${result.reason}`);
700
- console.error(`next: ${result.nextAction}`);
701
- }
702
- process.exit(1);
703
- return;
704
- }
705
-
706
- // PRI-695: the caller's token presence decides the REQUIRED mode, but a
707
- // tokenless caller must not refuse a no_auth console — that combination is
708
- // the default post-install state (the installer auto-launches with
709
- // --no-auth) and the documented reopen command has no flags. Refusal is
710
- // reserved for the genuinely incompatible combination: a caller that
711
- // expects authenticated access against a no_auth server (governance writes
712
- // would be unauthenticated without the user realizing it).
713
- const expectedAuthenticationMode = token?.trim() ? 'authenticated' : 'no_auth';
714
- const authMismatch = readyAuthenticationMode !== expectedAuthenticationMode;
715
- const tokenlessCallerOnNoAuthServer = !token?.trim() && readyAuthenticationMode === 'no_auth';
716
- if (authMismatch && !tokenlessCallerOnNoAuthServer) {
717
- try { child.kill('SIGTERM'); } catch { /* child may already have exited */ }
718
- // PRI-784: name the token source. A freshly spawned server only receives
719
- // --token (never the env var), so an env-sourced token ALWAYS lands here;
720
- // without that fact the user cannot form a working command.
721
- const tokenConfiguredVia =
722
- tokenSource === 'env' ? 'the PD_CONSOLE_TOKEN environment variable' : '--token';
723
- const result: ConsoleLaunchResult = {
724
- status: 'refused',
725
- url: '',
726
- port: plan.port,
727
- host: plan.host,
728
- workspaceDir,
729
- reused: false,
730
- browserOpened: false,
731
- authenticationMode: readyAuthenticationMode,
732
- reason: 'console_authentication_mode_mismatch',
733
- nextAction:
734
- `The freshly started Console came up without authentication even though a token was configured via ${tokenConfiguredVia}. ` +
735
- (tokenSource === 'env'
736
- ? 'A token in that variable is not forwarded to a freshly started Console — pass it explicitly instead:\n' +
737
- ' pd console open --token "$PD_CONSOLE_TOKEN" (PowerShell: --token $env:PD_CONSOLE_TOKEN)\n' +
738
- 'or run it without authentication: pd console open --no-auth'
739
- : 'Verify the token value, update the installed runtime (npx create-principles-disciple), or run pd console open --no-auth to use it without authentication.'),
740
- };
741
- if (opts.json) {
742
- console.log(JSON.stringify(result, null, 2));
743
- } else {
744
- console.error(`error: ${result.reason}`);
745
- console.error(`next: ${result.nextAction}`);
746
- }
747
- process.exit(1);
748
- return;
749
- }
750
-
751
- // 7) Console is ready → optionally open browser, emit result, then keep child running
752
- let browserOpened = false;
753
- let browserWarning: string | undefined;
754
- if (!opts.json && !opts.noBrowser) {
755
- const r = await openBrowser(plan.url);
756
- browserOpened = r.opened;
757
- if (!r.opened) browserWarning = r.reason;
758
- }
759
-
760
- const out: ConsoleLaunchResult = {
761
- status: 'started',
762
- url: plan.url,
763
- port: plan.port,
764
- host: plan.host,
765
- workspaceDir,
766
- reused: false,
767
- browserOpened,
768
- ...(readyAuthenticationMode ? { authenticationMode: readyAuthenticationMode } : {}),
769
- nextAction: browserOpened
770
- ? 'Browser opened to the Console. Press Ctrl+C to stop.'
771
- : `Open ${plan.url} in your browser. Press Ctrl+C to stop.`,
772
- };
773
- if (typeof child.pid === 'number') out.serverPid = child.pid;
774
- if (plan.reason) out.reason = plan.reason;
775
- if (browserWarning) {
776
- out.reason = out.reason ? `${out.reason}; browser_open_failed: ${browserWarning}` : `browser_open_failed: ${browserWarning}`;
777
- }
778
-
779
- if (opts.json) {
780
- // Single JSON object on stdout, then keep child attached.
781
- console.log(JSON.stringify(out, null, 2));
782
- } else {
783
- console.log(`\nConsole ready: ${plan.url}`);
784
- console.log(`Workspace: ${workspaceDir}`);
785
- if (plan.reason) console.log(`Note: ${plan.reason}`);
786
- if (browserOpened) {
787
- console.log('Browser opened. Press Ctrl+C to stop.');
788
- } else {
789
- if (browserWarning) {
790
- console.log(`Browser not opened: ${browserWarning}`);
791
- }
792
- console.log(`Open ${plan.url} in your browser. Press Ctrl+C to stop.`);
793
- }
794
- }
795
-
796
-
797
- }