@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,1381 +0,0 @@
1
- /**
2
- * pd console open tests (PRI-300).
3
- *
4
- * Covers:
5
- * - isLoopbackHost() returns true for loopback, false for LAN/public
6
- * - isPortInUse() / findAvailablePort() detect busy ports
7
- * - planConsoleLaunch() classifies reused / started / refused / failed
8
- * - non-loopback host is refused before any port work
9
- * - port-in-use-by-non-console case (reused but unhealthy) is structured
10
- * - console runtime not installed is structured failure
11
- * - workspace missing is structured failure
12
- * - CLI command wiring: pd console open --help, --workspace, --port, --json, --host
13
- */
14
-
15
- import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
16
- import * as net from 'node:net';
17
- import * as http from 'node:http';
18
- import * as fs from 'node:fs';
19
- import * as os from 'node:os';
20
- import * as path from 'node:path';
21
- import { execFileSync } from 'node:child_process';
22
- import * as childProcessModule from 'node:child_process';
23
- import { EventEmitter } from 'node:events';
24
- import { getBuiltPdCliPath } from '../helpers/pd-cli-path.js';
25
- import {
26
- isLoopbackHost,
27
- normalizeLoopbackHost,
28
- buildConsoleUrl,
29
- isPortInUse,
30
- findAvailablePort,
31
- planConsoleLaunch,
32
- probeConsoleHealth,
33
- openBrowser,
34
- } from '../../src/services/console-launcher.js';
35
-
36
- vi.mock('child_process', async (importOriginal) => {
37
- const original = await importOriginal<typeof import('child_process')>();
38
- return {
39
- ...original,
40
- spawn: (...args: any[]) => {
41
- if ((globalThis as any).__mockSpawn) {
42
- return (globalThis as any).__mockSpawn(...args);
43
- }
44
- return original.spawn(...args as [any, any]);
45
- },
46
- };
47
- });
48
-
49
- // ─── Loopback safety ─────────────────────────────────────────────────────────
50
-
51
- describe('isLoopbackHost', () => {
52
- it('returns true for 127.0.0.1, localhost, ::1, 127.x.x.x', () => {
53
- expect(isLoopbackHost('127.0.0.1')).toBe(true);
54
- expect(isLoopbackHost('localhost')).toBe(true);
55
- expect(isLoopbackHost('::1')).toBe(true);
56
- expect(isLoopbackHost('[::1]')).toBe(true);
57
- expect(isLoopbackHost('127.0.0.42')).toBe(true);
58
- });
59
-
60
- it('returns false for non-loopback hosts (LAN, public, 0.0.0.0)', () => {
61
- expect(isLoopbackHost('0.0.0.0')).toBe(false);
62
- expect(isLoopbackHost('192.168.1.5')).toBe(false);
63
- expect(isLoopbackHost('10.0.0.1')).toBe(false);
64
- expect(isLoopbackHost('172.16.0.1')).toBe(false);
65
- expect(isLoopbackHost('8.8.8.8')).toBe(false);
66
- expect(isLoopbackHost('myhost.example.com')).toBe(false);
67
- });
68
- });
69
-
70
- // ─── IPv6 loopback normalization ─────────────────────────────────────────────
71
-
72
- describe('normalizeLoopbackHost', () => {
73
- it('strips brackets from [::1] → ::1', () => {
74
- expect(normalizeLoopbackHost('[::1]')).toBe('::1');
75
- });
76
-
77
- it('passes through 127.0.0.1 unchanged', () => {
78
- expect(normalizeLoopbackHost('127.0.0.1')).toBe('127.0.0.1');
79
- });
80
-
81
- it('passes through localhost unchanged', () => {
82
- expect(normalizeLoopbackHost('localhost')).toBe('localhost');
83
- });
84
-
85
- it('passes through ::1 unchanged (already normalized)', () => {
86
- expect(normalizeLoopbackHost('::1')).toBe('::1');
87
- });
88
-
89
- it('passes through non-loopback as-is (caller must reject)', () => {
90
- expect(normalizeLoopbackHost('0.0.0.0')).toBe('0.0.0.0');
91
- });
92
- });
93
-
94
- // ─── URL formatting for IPv6 ─────────────────────────────────────────────────
95
-
96
- describe('buildConsoleUrl', () => {
97
- it('wraps ::1 in brackets for valid URL', () => {
98
- expect(buildConsoleUrl('::1', 3100)).toBe('http://[::1]:3100');
99
- });
100
-
101
- it('keeps 127.0.0.1 unchanged', () => {
102
- expect(buildConsoleUrl('127.0.0.1', 3100)).toBe('http://127.0.0.1:3100');
103
- });
104
-
105
- it('keeps localhost unchanged', () => {
106
- expect(buildConsoleUrl('localhost', 3100)).toBe('http://localhost:3100');
107
- });
108
-
109
- it('keeps 127.x.x.x unchanged', () => {
110
- expect(buildConsoleUrl('127.0.0.42', 3119)).toBe('http://127.0.0.42:3119');
111
- });
112
- });
113
-
114
- // ─── Port detection ──────────────────────────────────────────────────────────
115
-
116
- describe('isPortInUse', () => {
117
- let server: net.Server;
118
-
119
- beforeEach(async () => {
120
- server = net.createServer();
121
- await new Promise<void>((resolve) => {
122
- server.listen(0, '127.0.0.1', () => resolve());
123
- });
124
- });
125
-
126
- afterEach(async () => {
127
- await new Promise<void>((resolve) => {
128
- server.close(() => resolve());
129
- });
130
- });
131
-
132
- it('returns true for a port that accepts a TCP connection', async () => {
133
- const addr = server.address();
134
- if (typeof addr === 'object' && addr) {
135
- const inUse = await isPortInUse(addr.address, addr.port, 1000);
136
- expect(inUse).toBe(true);
137
- }
138
- });
139
-
140
- it('returns false for a port that is closed', async () => {
141
- const addr = server.address();
142
- if (typeof addr === 'object' && addr) {
143
- // Close the server, then probe
144
- await new Promise<void>((resolve) => server.close(() => resolve()));
145
- const inUse = await isPortInUse(addr.address, addr.port, 800);
146
- expect(inUse).toBe(false);
147
- }
148
- });
149
- });
150
-
151
- describe('findAvailablePort', () => {
152
- it('returns the first port in the range that is not in use', async () => {
153
- // Pick a very high port to avoid colliding with running services
154
- const port = await findAvailablePort('127.0.0.1', 49000, 5);
155
- expect(port).not.toBeNull();
156
- expect(port).toBeGreaterThanOrEqual(49000);
157
- });
158
-
159
- it('skips occupied ports and returns the next free one', async () => {
160
- const server = net.createServer();
161
- await new Promise<void>((resolve) => {
162
- server.listen(49100, '127.0.0.1', () => resolve());
163
- });
164
- try {
165
- // Should skip 49100 and return 49101
166
- const port = await findAvailablePort('127.0.0.1', 49100, 5);
167
- expect(port).toBe(49101);
168
- } finally {
169
- await new Promise<void>((resolve) => server.close(() => resolve()));
170
- }
171
- });
172
-
173
- it('returns null when all ports in the range are occupied', async () => {
174
- // Open 3 ports and check that findAvailablePort with limit=2 returns null
175
- const servers: net.Server[] = [];
176
- const ports: number[] = [];
177
- for (let i = 0; i < 3; i++) {
178
- const s = net.createServer();
179
- await new Promise<void>((resolve) => {
180
- s.listen(0, '127.0.0.1', () => {
181
- const a = s.address();
182
- if (typeof a === 'object' && a) ports.push(a.port);
183
- resolve();
184
- });
185
- });
186
- servers.push(s);
187
- }
188
- try {
189
- const port = await findAvailablePort('127.0.0.1', ports[0], 1);
190
- expect(port).toBeNull();
191
- } finally {
192
- for (const s of servers) {
193
- await new Promise<void>((resolve) => s.close(() => resolve()));
194
- }
195
- }
196
- });
197
-
198
- it('does not return ports above 65535 when fallback goes out of range', async () => {
199
- (globalThis as any).__mockIsPortInUse = async (host: string, port: number) => {
200
- if (port === 65535) return true;
201
- return false;
202
- };
203
- try {
204
- const port = await findAvailablePort('127.0.0.1', 65535, 2);
205
- expect(port).toBeNull();
206
- } finally {
207
- delete (globalThis as any).__mockIsPortInUse;
208
- }
209
- });
210
- });
211
-
212
- // ─── planConsoleLaunch: refused (non-loopback) ──────────────────────────────
213
-
214
- describe('planConsoleLaunch — refused (non-loopback host)', () => {
215
- it('refuses 0.0.0.0', async () => {
216
- const result = await planConsoleLaunch({
217
- workspaceDir: '/tmp/anywhere',
218
- preferredPort: 3100,
219
- host: '0.0.0.0',
220
- });
221
- expect(result.status).toBe('refused');
222
- expect(result.reason).toMatch(/non-loopback/i);
223
- expect(result.nextAction).toBeDefined();
224
- });
225
-
226
- it('refuses LAN host 192.168.1.5', async () => {
227
- const result = await planConsoleLaunch({
228
- workspaceDir: '/tmp/anywhere',
229
- preferredPort: 3100,
230
- host: '192.168.1.5',
231
- });
232
- expect(result.status).toBe('refused');
233
- expect(result.reason).toMatch(/192\.168\.1\.5/);
234
- });
235
-
236
- it('normalizes [::1] to ::1 and uses it for port probing', async () => {
237
- // [::1] should be normalized to ::1 and NOT refused
238
- const preferred = 49250;
239
- expect(await isPortInUse('::1', preferred)).toBe(false);
240
- const result = await planConsoleLaunch({
241
- workspaceDir: '/tmp/anywhere',
242
- preferredPort: preferred,
243
- host: '[::1]',
244
- });
245
- expect(result.status).toBe('started');
246
- expect(result.host).toBe('::1');
247
- // URL must have brackets for valid IPv6 URL format
248
- expect(result.url).toBe(`http://[::1]:${preferred}`);
249
- });
250
-
251
- it('formats ::1 URL with brackets (no raw IPv6 in URL)', async () => {
252
- const preferred = 49251;
253
- expect(await isPortInUse('::1', preferred)).toBe(false);
254
- const result = await planConsoleLaunch({
255
- workspaceDir: '/tmp/anywhere',
256
- preferredPort: preferred,
257
- host: '::1',
258
- });
259
- expect(result.status).toBe('started');
260
- expect(result.host).toBe('::1');
261
- expect(result.url).toBe(`http://[::1]:${preferred}`);
262
- });
263
- });
264
-
265
- // ─── planConsoleLaunch: started (port free) ─────────────────────────────────
266
-
267
- describe('planConsoleLaunch — started (preferred port free)', () => {
268
- it('returns started on the preferred port when no service is running', async () => {
269
- const preferred = 49200;
270
- // Verify the port is free first
271
- expect(await isPortInUse('127.0.0.1', preferred)).toBe(false);
272
- const result = await planConsoleLaunch({
273
- workspaceDir: '/tmp/anywhere',
274
- preferredPort: preferred,
275
- host: '127.0.0.1',
276
- });
277
- expect(result.status).toBe('started');
278
- expect(result.reused).toBe(false);
279
- expect(result.port).toBe(preferred);
280
- expect(result.url).toBe(`http://127.0.0.1:${preferred}`);
281
- });
282
- });
283
-
284
- // ─── planConsoleLaunch: reused (existing healthy console) ──────────────────
285
-
286
- describe('planConsoleLaunch — reused (healthy console on preferred port)', () => {
287
- it('returns reused when /api/health returns 200 on the preferred port', async () => {
288
- const server = http.createServer((req, res) => {
289
- if (req.url === '/api/health') {
290
- res.statusCode = 200;
291
- res.end(JSON.stringify({ success: true }));
292
- return;
293
- }
294
- res.statusCode = 404;
295
- res.end('not found');
296
- });
297
- await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', () => resolve()));
298
- const addr = server.address();
299
- if (typeof addr !== 'object' || !addr) throw new Error('no addr');
300
- try {
301
- const result = await planConsoleLaunch({
302
- workspaceDir: '/tmp/anywhere',
303
- preferredPort: addr.port,
304
- host: '127.0.0.1',
305
- });
306
- expect(result.status).toBe('reused');
307
- expect(result.reused).toBe(true);
308
- expect(result.url).toBe(`http://127.0.0.1:${addr.port}`);
309
- } finally {
310
- await new Promise<void>((resolve) => server.close(() => resolve()));
311
- }
312
- });
313
-
314
- it('does not reuse a verified no-auth Console when a token is configured', async () => {
315
- const server = http.createServer((_req, res) => {
316
- res.statusCode = 200;
317
- res.end(JSON.stringify({ success: true, data: { authenticationMode: 'no_auth' } }));
318
- });
319
- await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve));
320
- const addr = server.address();
321
- if (typeof addr !== 'object' || !addr) throw new Error('no addr');
322
- try {
323
- const result = await planConsoleLaunch({
324
- workspaceDir: '/tmp/anywhere', preferredPort: addr.port,
325
- host: '127.0.0.1', token: 'configured-token',
326
- });
327
- expect(result.status).toBe('refused');
328
- expect(result.reason).toBe('console_authentication_mode_mismatch');
329
- // PRI-695: the guidance names the actual running state and both ways
330
- // out — it no longer references "Companion" (meaningless to CLI users)
331
- // or PD_CONSOLE_TOKEN (never set by the default install). PRI-784: the
332
- // no-source form stays source-neutral; the env/flag variants have
333
- // their own cases below.
334
- expect(result.nextAction).toContain('without authentication');
335
- expect(result.nextAction).toContain(`port ${addr.port}`);
336
- expect(result.nextAction).not.toContain('Companion');
337
- expect(result.nextAction).not.toContain('PD_CONSOLE_TOKEN');
338
- } finally {
339
- await new Promise<void>((resolve) => server.close(resolve));
340
- }
341
- });
342
-
343
- it('auth-mismatch guidance names PD_CONSOLE_TOKEN and its durable removal when the token came from the env (PRI-784)', async () => {
344
- const server = http.createServer((_req, res) => {
345
- res.statusCode = 200;
346
- res.end(JSON.stringify({ success: true, data: { authenticationMode: 'no_auth' } }));
347
- });
348
- await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve));
349
- const addr = server.address();
350
- if (typeof addr !== 'object' || !addr) throw new Error('no addr');
351
- try {
352
- const result = await planConsoleLaunch({
353
- workspaceDir: '/tmp/anywhere', preferredPort: addr.port,
354
- host: '127.0.0.1', token: 'configured-token', tokenSource: 'env',
355
- });
356
- expect(result.status).toBe('refused');
357
- expect(result.reason).toBe('console_authentication_mode_mismatch');
358
- // The env source is the recurring real-world trap: a persistently set
359
- // variable makes "reopen without a token" impossible to follow, so the
360
- // guidance must name the variable and how to remove it at its source.
361
- expect(result.nextAction).toContain('PD_CONSOLE_TOKEN');
362
- expect(result.nextAction).toContain("SetEnvironmentVariable('PD_CONSOLE_TOKEN', $null, 'User')");
363
- expect(result.nextAction).toContain('--no-auth');
364
- expect(result.nextAction).toContain('--token');
365
- } finally {
366
- await new Promise<void>((resolve) => server.close(resolve));
367
- }
368
- });
369
-
370
- it('auth-mismatch guidance names --token, never the env var, when the token came from the flag (PRI-784)', async () => {
371
- const server = http.createServer((_req, res) => {
372
- res.statusCode = 200;
373
- res.end(JSON.stringify({ success: true, data: { authenticationMode: 'no_auth' } }));
374
- });
375
- await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve));
376
- const addr = server.address();
377
- if (typeof addr !== 'object' || !addr) throw new Error('no addr');
378
- try {
379
- const result = await planConsoleLaunch({
380
- workspaceDir: '/tmp/anywhere', preferredPort: addr.port,
381
- host: '127.0.0.1', token: 'configured-token', tokenSource: 'flag',
382
- });
383
- expect(result.status).toBe('refused');
384
- expect(result.reason).toBe('console_authentication_mode_mismatch');
385
- expect(result.nextAction).toContain('--token');
386
- expect(result.nextAction).toContain('--no-auth');
387
- expect(result.nextAction).not.toContain('PD_CONSOLE_TOKEN');
388
- } finally {
389
- await new Promise<void>((resolve) => server.close(resolve));
390
- }
391
- });
392
-
393
- it('reuses a no-auth Console for a tokenless caller (PRI-695 default post-install state)', async () => {
394
- // The installer auto-launches the Console with --no-auth; the documented
395
- // reopen command carries no flags and no token. That combination must
396
- // REUSE the running console, not refuse it.
397
- const server = http.createServer((_req, res) => {
398
- res.statusCode = 200;
399
- res.end(JSON.stringify({ success: true, data: { authenticationMode: 'no_auth' } }));
400
- });
401
- await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve));
402
- const addr = server.address();
403
- if (typeof addr !== 'object' || !addr) throw new Error('no addr');
404
- try {
405
- const result = await planConsoleLaunch({
406
- workspaceDir: '/tmp/anywhere', preferredPort: addr.port,
407
- host: '127.0.0.1',
408
- });
409
- expect(result.status).toBe('reused');
410
- expect(result.reused).toBe(true);
411
- expect(result.url).toBe(`http://127.0.0.1:${addr.port}`);
412
- } finally {
413
- await new Promise<void>((resolve) => server.close(resolve));
414
- }
415
- });
416
-
417
- it('fails loud when the configured token is rejected by an existing Console', async () => {
418
- const server = http.createServer((_req, res) => {
419
- res.statusCode = 401;
420
- res.end('unauthorized');
421
- });
422
- await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve));
423
- const addr = server.address();
424
- if (typeof addr !== 'object' || !addr) throw new Error('no addr');
425
- try {
426
- const result = await planConsoleLaunch({
427
- workspaceDir: '/tmp/anywhere', preferredPort: addr.port,
428
- host: '127.0.0.1', token: 'wrong-token',
429
- });
430
- expect(result.status).toBe('refused');
431
- expect(result.reason).toBe('console_authentication_failed');
432
- } finally {
433
- await new Promise<void>((resolve) => server.close(resolve));
434
- }
435
- });
436
-
437
- it('does NOT classify a non-console responder as reused', async () => {
438
- // Server returns 200 on any path but with a non-OK status code from /api/health
439
- const server = http.createServer((req, res) => {
440
- res.statusCode = 500;
441
- res.end('error');
442
- });
443
- await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', () => resolve()));
444
- const addr = server.address();
445
- if (typeof addr !== 'object' || !addr) throw new Error('no addr');
446
- try {
447
- const result = await planConsoleLaunch({
448
- workspaceDir: '/tmp/anywhere',
449
- preferredPort: addr.port,
450
- host: '127.0.0.1',
451
- });
452
- // health 500 → not healthy → falls through to "started" (port is occupied by non-console → next port)
453
- // but it may also stay in "started" if no fallback is found
454
- expect(result.status === 'started' || result.status === 'failed').toBe(true);
455
- if (result.status === 'started') {
456
- // It should have moved to a different port (not addr.port)
457
- expect(result.port).not.toBe(addr.port);
458
- }
459
- } finally {
460
- await new Promise<void>((resolve) => server.close(() => resolve()));
461
- }
462
- });
463
- });
464
-
465
- // ─── planConsoleLaunch: started with port fallback ──────────────────────────
466
-
467
- describe('planConsoleLaunch — port fallback', () => {
468
- it('moves to next free port when preferred is occupied by a non-console', async () => {
469
- const server = http.createServer((req, res) => {
470
- res.statusCode = 500; // not a healthy console
471
- res.end('error');
472
- });
473
- await new Promise<void>((resolve) => server.listen(49300, '127.0.0.1', () => resolve()));
474
- try {
475
- const result = await planConsoleLaunch({
476
- workspaceDir: '/tmp/anywhere',
477
- preferredPort: 49300,
478
- host: '127.0.0.1',
479
- });
480
- expect(result.status).toBe('started');
481
- expect(result.port).toBe(49301);
482
- expect(result.reason).toMatch(/busy|49300/i);
483
- } finally {
484
- await new Promise<void>((resolve) => server.close(() => resolve()));
485
- }
486
- });
487
- });
488
-
489
- // ─── probeConsoleHealth ─────────────────────────────────────────────────────
490
-
491
- describe('probeConsoleHealth', () => {
492
- it('returns healthy=true for a server that returns 200 on /api/health', async () => {
493
- const server = http.createServer((req, res) => {
494
- if (req.url === '/api/health') {
495
- res.statusCode = 200;
496
- res.end(JSON.stringify({ success: true }));
497
- return;
498
- }
499
- res.statusCode = 404;
500
- res.end();
501
- });
502
- await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', () => resolve()));
503
- const addr = server.address();
504
- if (typeof addr !== 'object' || !addr) throw new Error('no addr');
505
- try {
506
- const h = await probeConsoleHealth({ host: '127.0.0.1', port: addr.port });
507
- expect(h.healthy).toBe(true);
508
- } finally {
509
- await new Promise<void>((resolve) => server.close(() => resolve()));
510
- }
511
- });
512
-
513
- it('returns the verified authentication mode from the health contract', async () => {
514
- const server = http.createServer((_req, res) => {
515
- res.statusCode = 200;
516
- res.end(JSON.stringify({ success: true, data: { authenticationMode: 'authenticated' } }));
517
- });
518
- await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve));
519
- const addr = server.address();
520
- if (typeof addr !== 'object' || !addr) throw new Error('no addr');
521
- try {
522
- const h = await probeConsoleHealth({ host: '127.0.0.1', port: addr.port, token: 'token' });
523
- expect(h).toMatchObject({ healthy: true, authenticationMode: 'authenticated' });
524
- } finally {
525
- await new Promise<void>((resolve) => server.close(resolve));
526
- }
527
- });
528
-
529
- it('returns healthy=false with reason for a server that returns 500', async () => {
530
- const server = http.createServer((req, res) => {
531
- res.statusCode = 500;
532
- res.end('boom');
533
- });
534
- await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', () => resolve()));
535
- const addr = server.address();
536
- if (typeof addr !== 'object' || !addr) throw new Error('no addr');
537
- try {
538
- const h = await probeConsoleHealth({ host: '127.0.0.1', port: addr.port });
539
- expect(h.healthy).toBe(false);
540
- expect(h.reason).toBeDefined();
541
- } finally {
542
- await new Promise<void>((resolve) => server.close(() => resolve()));
543
- }
544
- });
545
-
546
- it('sends Authorization header when token is provided', async () => {
547
- let receivedAuth: string | undefined;
548
- const server = http.createServer((req, res) => {
549
- receivedAuth = req.headers.authorization;
550
- res.statusCode = 200;
551
- res.end(JSON.stringify({ success: true }));
552
- });
553
- await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', () => resolve()));
554
- const addr = server.address();
555
- if (typeof addr !== 'object' || !addr) throw new Error('no addr');
556
- try {
557
- const h = await probeConsoleHealth({ host: '127.0.0.1', port: addr.port, token: 'test-token-123' });
558
- expect(h.healthy).toBe(true);
559
- expect(receivedAuth).toBe('Bearer test-token-123');
560
- } finally {
561
- await new Promise<void>((resolve) => server.close(() => resolve()));
562
- }
563
- });
564
-
565
- it('does NOT send Authorization header when token is undefined', async () => {
566
- let receivedAuth: string | undefined;
567
- const server = http.createServer((req, res) => {
568
- receivedAuth = req.headers.authorization;
569
- res.statusCode = 200;
570
- res.end(JSON.stringify({ success: true }));
571
- });
572
- await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', () => resolve()));
573
- const addr = server.address();
574
- if (typeof addr !== 'object' || !addr) throw new Error('no addr');
575
- try {
576
- const h = await probeConsoleHealth({ host: '127.0.0.1', port: addr.port });
577
- expect(h.healthy).toBe(true);
578
- expect(receivedAuth).toBeUndefined();
579
- } finally {
580
- await new Promise<void>((resolve) => server.close(() => resolve()));
581
- }
582
- });
583
-
584
- it('returns healthy=false with reason when server returns 401 (unauthorized)', async () => {
585
- const server = http.createServer((req, res) => {
586
- res.statusCode = 401;
587
- res.end('unauthorized');
588
- });
589
- await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', () => resolve()));
590
- const addr = server.address();
591
- if (typeof addr !== 'object' || !addr) throw new Error('no addr');
592
- try {
593
- const h = await probeConsoleHealth({ host: '127.0.0.1', port: addr.port });
594
- expect(h.healthy).toBe(false);
595
- expect(h.reason).toMatch(/401/);
596
- expect(h.reason).not.toMatch(/non-console/i);
597
- } finally {
598
- await new Promise<void>((resolve) => server.close(() => resolve()));
599
- }
600
- });
601
-
602
- it('401 is NOT misclassified as healthy even with a valid token', async () => {
603
- const server = http.createServer((req, res) => {
604
- // Simulate a console that requires auth and rejects bad tokens
605
- if (req.headers.authorization !== 'Bearer correct-token') {
606
- res.statusCode = 401;
607
- res.end('unauthorized');
608
- return;
609
- }
610
- res.statusCode = 200;
611
- res.end(JSON.stringify({ success: true }));
612
- });
613
- await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', () => resolve()));
614
- const addr = server.address();
615
- if (typeof addr !== 'object' || !addr) throw new Error('no addr');
616
- try {
617
- // Wrong token → 401 → should NOT be healthy
618
- const h = await probeConsoleHealth({ host: '127.0.0.1', port: addr.port, token: 'wrong-token' });
619
- expect(h.healthy).toBe(false);
620
- expect(h.reason).toMatch(/401/);
621
- } finally {
622
- await new Promise<void>((resolve) => server.close(() => resolve()));
623
- }
624
- });
625
- });
626
-
627
- // ─── CLI command wiring ──────────────────────────────────────────────────────
628
-
629
- describe('CLI command wiring (pd console open)', () => {
630
- let cliPath: string;
631
- let workspaceRoot: string;
632
- let tmp: string;
633
- let originalConsoleToken: string | undefined;
634
-
635
- beforeEach(() => {
636
- originalConsoleToken = process.env.PD_CONSOLE_TOKEN;
637
- delete process.env.PD_CONSOLE_TOKEN;
638
- workspaceRoot = path.resolve(__dirname, '../../../..');
639
- cliPath = path.join(workspaceRoot, 'packages', 'pd-cli', 'dist', 'index.js');
640
- tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'pd-console-open-test-'));
641
- // Isolated fake HOME so the tests never read from — or rmSync-destroy — a
642
- // real ~/.openclaw install on developer machines. runPd() points the CLI
643
- // child at this home via __PD_CONSOLE_TEST_FAKE_HOME.
644
- const fakeHome = path.join(tmp, 'home');
645
- process.env.__PD_CONSOLE_TEST_FAKE_HOME = fakeHome;
646
- // Fake a console install: dir + ESM package.json + dist/server.js with a
647
- // minimal HTTP server. The package.json "type": "module" makes the fake
648
- // server's module system deterministic regardless of whether a real
649
- // extension-root package.json exists above the console dir.
650
- const consoleDir = path.join(fakeHome, '.openclaw', 'extensions', 'principles-disciple', 'console');
651
- fs.mkdirSync(path.join(consoleDir, 'dist', 'web'), { recursive: true });
652
- fs.writeFileSync(path.join(consoleDir, 'package.json'), JSON.stringify({ name: 'fake-pd-console', version: '0.0.0', type: 'module' }, null, 2));
653
- // EP-06 regression guard: dist/web/index.html must exist (PR #1169 fix)
654
- fs.writeFileSync(path.join(consoleDir, 'dist', 'web', 'index.html'), '<!DOCTYPE html><html></html>');
655
- // Runtime dependency integrity check: fake console needs minimal node_modules
656
- // slots so the launcher passes the integrity gate and reaches spawn/health logic.
657
- const nm = path.join(consoleDir, 'node_modules');
658
- // principles-disciple: server imports principles-disciple/governance-audit
659
- fs.mkdirSync(path.join(nm, 'principles-disciple', 'dist'), { recursive: true });
660
- fs.writeFileSync(path.join(nm, 'principles-disciple', 'package.json'), JSON.stringify({ name: 'x', version: '0.0.0' }, null, 2));
661
- fs.writeFileSync(path.join(nm, 'principles-disciple', 'dist', 'governance-audit.js'), 'export {};\n');
662
- // @principles/core: server imports TWO subpaths
663
- // @principles/core/principle-tree-ledger → dist/principle-tree-ledger.js
664
- // @principles/core/runtime-v2 → dist/runtime-v2/index.js
665
- fs.mkdirSync(path.join(nm, '@principles', 'core', 'dist', 'runtime-v2'), { recursive: true });
666
- fs.writeFileSync(path.join(nm, '@principles', 'core', 'package.json'), JSON.stringify({ name: 'x', version: '0.0.0' }, null, 2));
667
- fs.writeFileSync(path.join(nm, '@principles', 'core', 'dist', 'principle-tree-ledger.js'), 'export {};\n');
668
- fs.writeFileSync(path.join(nm, '@principles', 'core', 'dist', 'runtime-v2', 'index.js'), 'export {};\n');
669
- // @principles/host-runtime: uses root entry dist/index.js
670
- fs.mkdirSync(path.join(nm, '@principles', 'host-runtime', 'dist'), { recursive: true });
671
- fs.writeFileSync(path.join(nm, '@principles', 'host-runtime', 'package.json'), JSON.stringify({ name: 'x', version: '0.0.0' }, null, 2));
672
- fs.writeFileSync(path.join(nm, '@principles', 'host-runtime', 'dist', 'index.js'), 'export {};\n');
673
- // @principles/install-layout: uses root entry dist/index.js
674
- fs.mkdirSync(path.join(nm, '@principles', 'install-layout', 'dist'), { recursive: true });
675
- fs.writeFileSync(path.join(nm, '@principles', 'install-layout', 'package.json'), JSON.stringify({ name: 'x', version: '0.0.0' }, null, 2));
676
- fs.writeFileSync(path.join(nm, '@principles', 'install-layout', 'dist', 'index.js'), 'export {};\n');
677
- fs.writeFileSync(path.join(consoleDir, 'dist', 'server.js'), `
678
- import http from 'node:http';
679
- const args = process.argv.slice(2);
680
- const portIdx = args.indexOf('--port');
681
- const port = portIdx >= 0 ? parseInt(args[portIdx + 1]) : 3100;
682
- const hostIdx = args.indexOf('--host');
683
- const host = hostIdx >= 0 ? args[hostIdx + 1] : '127.0.0.1';
684
- const server = http.createServer((req, res) => {
685
- if (req.url === '/api/health') {
686
- res.writeHead(200, {'Content-Type': 'application/json'});
687
- res.end(JSON.stringify({success: true, data: {authenticationMode: 'no_auth'}}));
688
- } else {
689
- res.writeHead(404);
690
- res.end();
691
- }
692
- });
693
- server.listen(port, host, () => {
694
- console.log(JSON.stringify({status: 'running', port, host}));
695
- });
696
- `);
697
- });
698
-
699
- afterEach(() => {
700
- if (originalConsoleToken === undefined) delete process.env.PD_CONSOLE_TOKEN;
701
- else process.env.PD_CONSOLE_TOKEN = originalConsoleToken;
702
- delete process.env.__PD_CONSOLE_TEST_FAKE_HOME;
703
- try { fs.rmSync(tmp, { recursive: true, force: true }); } catch { /* ignore */ }
704
- });
705
-
706
- it('console open subcommand is registered (pd console open --help)', () => {
707
- const out = runPd(['console', 'open', '--help'], workspaceRoot);
708
- expect(out).toContain('--workspace');
709
- expect(out).toContain('--port');
710
- expect(out).toContain('--host');
711
- expect(out).toContain('--json');
712
- expect(out).toContain('--no-browser');
713
- });
714
-
715
- it('console subcommand list shows "open" subcommand', () => {
716
- const out = runPd(['console', '--help'], workspaceRoot);
717
- expect(out).toMatch(/\bopen\b/);
718
- });
719
-
720
- it('pd console open --host 0.0.0.0 --json returns a refused JSON object', () => {
721
- const out = runPd(['console', 'open', '--workspace', tmp, '--host', '0.0.0.0', '--json', '--no-browser'], workspaceRoot);
722
- const parsed = JSON.parse(out);
723
- expect(parsed.status).toBe('refused');
724
- expect(parsed.reason).toMatch(/non-loopback/i);
725
- expect(parsed.nextAction).toBeDefined();
726
- });
727
-
728
- it('pd console open --json (port free) returns a structured JSON object with required fields', () => {
729
- // The real CLI spawns a long-lived Console server process and then prints
730
- // JSON *without exiting* (the child keeps running). execFileSync would
731
- // block forever waiting for the child to exit. Use a short timeout so the
732
- // test reads stdout before the process is killed.
733
- // Vitest timeout (10s) must exceed execFileSync timeout (8s) so the child
734
- // is killed by execFileSync first, allowing stdout to be read.
735
- const out = runPd(['console', 'open', '--workspace', tmp, '--json', '--no-browser'], workspaceRoot, 8_000);
736
- const parsed = JSON.parse(out);
737
- expect(parsed).toHaveProperty('status');
738
- expect(['started', 'reused', 'failed', 'refused']).toContain(parsed.status);
739
- expect(parsed).toHaveProperty('port');
740
- expect(parsed).toHaveProperty('host');
741
- expect(parsed).toHaveProperty('workspaceDir');
742
- expect(parsed).toHaveProperty('reused');
743
- expect(parsed).toHaveProperty('browserOpened');
744
- }, 10_000);
745
-
746
- it('pd console open --json fresh spawn includes a positive integer serverPid (PRI-526)', async () => {
747
- // Async stream-parse + guaranteed teardown. execFileSync patterns are
748
- // unreliable here on Windows: the CLI keeps running after printing JSON
749
- // (fresh spawn) or may unexpectedly take another branch, and killing via
750
- // timeout can leave the grandchild server holding pipe handles.
751
- let run: CliJsonRun | undefined;
752
- try {
753
- run = await runPdUntilJson(
754
- ['console', 'open', '--workspace', tmp, '--port', '49390', '--json', '--no-browser'],
755
- workspaceRoot,
756
- );
757
- if (!isRecord(run.parsed)) throw new Error('CLI JSON output was not an object');
758
- expect(run.parsed.status).toBe('started');
759
- expect(run.parsed.reused).toBe(false);
760
- const serverPid = run.parsed.serverPid;
761
- expect(typeof serverPid === 'number' && Number.isInteger(serverPid) && serverPid > 0).toBe(true);
762
- } finally {
763
- await teardownCliTree(run);
764
- }
765
- }, 20_000);
766
-
767
- it('kills and refuses a fresh Console whose reported authentication mode mismatches the configured token', async () => {
768
- process.env.PD_CONSOLE_TOKEN = 'configured-token';
769
- let run: CliJsonRun | undefined;
770
- try {
771
- run = await runPdUntilJson(
772
- ['console', 'open', '--workspace', tmp, '--port', '49391', '--json', '--no-browser'],
773
- workspaceRoot,
774
- );
775
- if (!isRecord(run.parsed)) throw new Error('CLI JSON output was not an object');
776
- expect(run.parsed.status).toBe('refused');
777
- expect(run.parsed.reason).toBe('console_authentication_mode_mismatch');
778
- expect(run.parsed).not.toHaveProperty('serverPid');
779
- // PRI-784 review fix (PR #1670): the fresh-start env guidance is part of
780
- // the user contract — assert its content, not just the refusal shell.
781
- expect(run.parsed.nextAction).toContain('PD_CONSOLE_TOKEN');
782
- expect(run.parsed.nextAction).toContain('not forwarded');
783
- expect(run.parsed.nextAction).toContain('--token "$PD_CONSOLE_TOKEN"');
784
- expect(run.parsed.nextAction).toContain('--no-auth');
785
- await new Promise((resolve) => setTimeout(resolve, 100));
786
- expect(await isPortInUse('127.0.0.1', 49391)).toBe(false);
787
- } finally {
788
- await teardownCliTree(run);
789
- }
790
- }, 20_000);
791
-
792
- it('pd console open --json reused path does NOT include serverPid (PRI-526)', async () => {
793
- // Stand up a fake healthy console in-process, then point the CLI at its
794
- // port: planConsoleLaunch probes /api/health → 200 → reused, no spawn.
795
- const server = http.createServer((req, res) => {
796
- if (req.url === '/api/health') {
797
- res.statusCode = 200;
798
- res.end(JSON.stringify({ success: true, data: { authenticationMode: 'no_auth' } }));
799
- return;
800
- }
801
- res.statusCode = 404;
802
- res.end();
803
- });
804
- await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', () => resolve()));
805
- const addr = server.address();
806
- if (typeof addr !== 'object' || !addr) throw new Error('no addr');
807
- let run: CliJsonRun | undefined;
808
- try {
809
- run = await runPdUntilJson(
810
- ['console', 'open', '--workspace', tmp, '--port', String(addr.port), '--json', '--no-browser'],
811
- workspaceRoot,
812
- );
813
- if (!isRecord(run.parsed)) throw new Error('CLI JSON output was not an object');
814
- expect(run.parsed.status).toBe('reused');
815
- expect(run.parsed.reused).toBe(true);
816
- expect(run.parsed.authenticationMode).toBe('no_auth');
817
- expect(run.parsed).not.toHaveProperty('serverPid');
818
- } finally {
819
- await teardownCliTree(run);
820
- server.close();
821
- }
822
- }, 20_000);
823
-
824
- it('reuses a healthy running Console even when local dependency slots are broken (reuse-before-integrity contract)', async () => {
825
- // Regression for the control-flow contract: the integrity gate must only
826
- // run on the fresh-spawn branch. If a healthy Console is already running,
827
- // broken on-disk node_modules (dangling junction / empty shell left by an
828
- // interrupted update) must NOT prevent reusing it — its modules are loaded
829
- // in memory. This test breaks the @principles/core slot on disk, then
830
- // verifies the CLI still returns status "reused" (never hits the gate).
831
- const nm = path.join(
832
- process.env.__PD_CONSOLE_TEST_FAKE_HOME ?? '',
833
- '.openclaw', 'extensions', 'principles-disciple', 'console', 'node_modules',
834
- );
835
- // Simulate a broken install: remove the @principles/core dist entry entirely.
836
- const coreDist = path.join(nm, '@principles', 'core', 'dist');
837
- if (fs.existsSync(coreDist)) fs.rmSync(coreDist, { recursive: true, force: true });
838
-
839
- const server = http.createServer((req, res) => {
840
- if (req.url === '/api/health') {
841
- res.statusCode = 200;
842
- res.end(JSON.stringify({ success: true, data: { authenticationMode: 'no_auth' } }));
843
- return;
844
- }
845
- res.statusCode = 404;
846
- res.end();
847
- });
848
- await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', () => resolve()));
849
- const addr = server.address();
850
- if (typeof addr !== 'object' || !addr) throw new Error('no addr');
851
- let run: CliJsonRun | undefined;
852
- try {
853
- run = await runPdUntilJson(
854
- ['console', 'open', '--workspace', tmp, '--port', String(addr.port), '--json', '--no-browser'],
855
- workspaceRoot,
856
- );
857
- if (!isRecord(run.parsed)) throw new Error('CLI JSON output was not an object');
858
- expect(run.parsed.status).toBe('reused');
859
- expect(run.parsed.reused).toBe(true);
860
- } finally {
861
- await teardownCliTree(run);
862
- server.close();
863
- }
864
- }, 20_000);
865
-
866
- it('pd console open --port 99999 --json returns a structured failure (invalid port)', () => {
867
- const out = runPd(['console', 'open', '--workspace', tmp, '--port', '99999', '--json', '--no-browser'], workspaceRoot);
868
- const parsed = JSON.parse(out);
869
- expect(parsed.status).toBe('failed');
870
- expect(parsed.reason).toMatch(/Invalid --port/);
871
- });
872
-
873
- it('pd console open without --workspace and no env var returns a structured workspace_missing failure', () => {
874
- const previous = process.env.PD_WORKSPACE_DIR;
875
- delete process.env.PD_WORKSPACE_DIR;
876
- try {
877
- const out = runPd(['console', 'open', '--json', '--no-browser'], workspaceRoot);
878
- const parsed = JSON.parse(out);
879
- expect(parsed.status).toBe('failed');
880
- expect(parsed.reason).toBe('workspace_missing');
881
- expect(parsed.nextAction).toBeDefined();
882
- } finally {
883
- if (previous !== undefined) process.env.PD_WORKSPACE_DIR = previous;
884
- }
885
- });
886
-
887
- it('pd console open --json with --no-auth and --no-browser parses options correctly', () => {
888
- // Same as port-free test: CLI spawns a long-lived server, use timeout.
889
- const out = runPd(['console', 'open', '--workspace', tmp, '--json', '--no-auth', '--no-browser'], workspaceRoot, 8_000);
890
- const parsed = JSON.parse(out);
891
- expect(parsed).toHaveProperty('status');
892
- expect(parsed.browserOpened).toBe(false);
893
- }, 10_000);
894
-
895
- it('pd console --no-auth --json legacy path parses --no-auth correctly', () => {
896
- // Same: may spawn a long-lived server, use timeout.
897
- const out = runPd(['console', '--workspace', tmp, '--json', '--no-auth'], workspaceRoot, 8_000);
898
- expect(out.trim()).not.toBe('');
899
- const parsed = JSON.parse(out);
900
- expect(parsed).toBeDefined();
901
- }, 10_000);
902
-
903
- describe('openBrowser', () => {
904
- afterEach(() => {
905
- delete (globalThis as any).__mockSpawn;
906
- });
907
-
908
- it('returns opened: true when spawn does not emit error in the short window', async () => {
909
- const mockChild = new EventEmitter() as any;
910
- mockChild.unref = vi.fn();
911
- let spawnCalled = false;
912
- (globalThis as any).__mockSpawn = () => {
913
- spawnCalled = true;
914
- return mockChild;
915
- };
916
-
917
- const result = await openBrowser('http://127.0.0.1:3100');
918
- expect(result.opened).toBe(true);
919
- expect(spawnCalled).toBe(true);
920
- });
921
-
922
- it('returns opened: false when spawn emits an error within the short window', async () => {
923
- const mockChild = new EventEmitter() as any;
924
- mockChild.unref = vi.fn();
925
- let spawnCalled = false;
926
- (globalThis as any).__mockSpawn = () => {
927
- spawnCalled = true;
928
- process.nextTick(() => {
929
- mockChild.emit('error', new Error('spawn ENOENT'));
930
- });
931
- return mockChild;
932
- };
933
-
934
- const result = await openBrowser('http://127.0.0.1:3100');
935
- expect(result.opened).toBe(false);
936
- expect(result.reason).toContain('Failed to spawn browser process: spawn ENOENT');
937
- expect(spawnCalled).toBe(true);
938
- });
939
-
940
- it('returns opened: false when spawn throws synchronously', async () => {
941
- let spawnCalled = false;
942
- (globalThis as any).__mockSpawn = () => {
943
- spawnCalled = true;
944
- throw new Error('Sync spawn failure');
945
- };
946
-
947
- const result = await openBrowser('http://127.0.0.1:3100');
948
- expect(result.opened).toBe(false);
949
- expect(result.reason).toContain('Sync spawn failure');
950
- expect(spawnCalled).toBe(true);
951
- });
952
- });
953
-
954
- describe('handleConsoleOpen browser failure reporting', () => {
955
- afterEach(() => {
956
- delete (globalThis as any).__mockSpawn;
957
- delete (globalThis as any).__mockPlanConsoleLaunch;
958
- delete (globalThis as any).__mockProbeConsoleHealth;
959
- });
960
-
961
- it('sets browserOpened: false when browser fails to open', async () => {
962
- const { handleConsoleOpen } = await import('../../src/commands/console.js');
963
-
964
- const exitSpy = vi.spyOn(process, 'exit').mockImplementation((() => {}) as any);
965
- const logSpy = vi.spyOn(console, 'log').mockImplementation(() => {});
966
- const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
967
-
968
- // The in-process handler resolves the console dir via getConsoleDir(),
969
- // which reads HOME/USERPROFILE directly. Point them at the isolated
970
- // fake home — a clean CI runner has no real ~/.openclaw console, and
971
- // relying on one (as this test implicitly did before) makes the result
972
- // machine-dependent.
973
- const fakeHome = process.env.__PD_CONSOLE_TEST_FAKE_HOME ?? '';
974
- const savedHome = process.env.HOME;
975
- const savedUserProfile = process.env.USERPROFILE;
976
- process.env.HOME = fakeHome;
977
- process.env.USERPROFILE = fakeHome;
978
-
979
- const mockChild = new EventEmitter() as any;
980
- mockChild.unref = vi.fn();
981
- let spawnCalled = false;
982
- (globalThis as any).__mockSpawn = () => {
983
- spawnCalled = true;
984
- process.nextTick(() => {
985
- mockChild.emit('error', new Error('mock spawn error'));
986
- });
987
- return mockChild;
988
- };
989
-
990
- (globalThis as any).__mockPlanConsoleLaunch = async () => {
991
- return {
992
- status: 'reused',
993
- url: 'http://127.0.0.1:3100',
994
- port: 3100,
995
- host: '127.0.0.1',
996
- reused: true
997
- };
998
- };
999
-
1000
- (globalThis as any).__mockProbeConsoleHealth = async () => {
1001
- return {
1002
- healthy: true
1003
- };
1004
- };
1005
-
1006
- try {
1007
- await handleConsoleOpen({
1008
- workspace: tmp,
1009
- json: false,
1010
- });
1011
-
1012
- await new Promise(resolve => setTimeout(resolve, 150));
1013
-
1014
- const loggedOutput = logSpy.mock.calls.map(c => c.join(' ')).join('\n');
1015
- expect(exitSpy).not.toHaveBeenCalled();
1016
- expect(spawnCalled).toBe(true);
1017
-
1018
- expect(loggedOutput).not.toContain('Browser opened');
1019
- expect(loggedOutput).toContain('Open http://127.0.0.1:3100 in your browser');
1020
- } finally {
1021
- if (savedHome === undefined) delete process.env.HOME;
1022
- else process.env.HOME = savedHome;
1023
- if (savedUserProfile === undefined) delete process.env.USERPROFILE;
1024
- else process.env.USERPROFILE = savedUserProfile;
1025
- exitSpy.mockRestore();
1026
- logSpy.mockRestore();
1027
- errorSpy.mockRestore();
1028
- }
1029
- });
1030
- });
1031
-
1032
- describe('Strict port parsing and boundary validation', () => {
1033
- it('rejects partial numeric strings like 3100abc', () => {
1034
- const out = runPd(['console', 'open', '--workspace', tmp, '--port', '3100abc', '--json', '--no-browser'], workspaceRoot);
1035
- const parsed = JSON.parse(out);
1036
- expect(parsed.status).toBe('failed');
1037
- expect(parsed.reason).toMatch(/Invalid --port/);
1038
- });
1039
-
1040
- it('rejects port 0', () => {
1041
- const out = runPd(['console', 'open', '--workspace', tmp, '--port', '0', '--json', '--no-browser'], workspaceRoot);
1042
- const parsed = JSON.parse(out);
1043
- expect(parsed.status).toBe('failed');
1044
- expect(parsed.reason).toMatch(/Invalid --port/);
1045
- });
1046
- });
1047
-
1048
- describe('Non-loopback host checks before workspace resolution', () => {
1049
- it('refuses non-loopback hosts even when workspace is missing', () => {
1050
- const previous = process.env.PD_WORKSPACE_DIR;
1051
- delete process.env.PD_WORKSPACE_DIR;
1052
- try {
1053
- const out = runPd(['console', 'open', '--host', '192.168.1.100', '--json', '--no-browser'], workspaceRoot);
1054
- const parsed = JSON.parse(out);
1055
- expect(parsed.status).toBe('refused');
1056
- expect(parsed.reason).toMatch(/non-loopback/i);
1057
- expect(parsed.workspaceDir).toBe('');
1058
- } finally {
1059
- if (previous !== undefined) process.env.PD_WORKSPACE_DIR = previous;
1060
- }
1061
- });
1062
-
1063
- it('[::1] is accepted and normalized to ::1 (not refused)', async (ctx) => {
1064
- // PRI-581 / ERR-111: IPv6 loopback is an optional host capability — a
1065
- // global TUN VPN / WFP filter driver can silently block ::1 connections
1066
- // (bind succeeds, connect returns EACCES) while the IPv6 stack itself is
1067
- // healthy. Probe-and-skip instead of hard-failing for 8s on such hosts.
1068
- if (!(await isIpv6LoopbackUsable())) {
1069
- ctx.skip({ reason: 'IPv6 loopback (::1) is filtered on this machine (VPN/WFP filter driver? — see ERR-111 / PRI-581)' });
1070
- return;
1071
- }
1072
- // May spawn a long-lived server, use timeout.
1073
- const out = runPd(['console', 'open', '--workspace', tmp, '--host', '[::1]', '--json', '--no-browser'], workspaceRoot, 8_000);
1074
- if (out.trim() === '') {
1075
- // The CLI was still in its 15s ready-poll when execFileSync timed out.
1076
- // The capability probe above passed, so this is a genuine failure —
1077
- // the health probe on ::1 never succeeded despite ::1 being reachable.
1078
- throw new Error('CLI produced no JSON within 8s — ::1 health probe never succeeded (IPv6 loopback probe passed; this is a real failure)');
1079
- }
1080
- const parsed = JSON.parse(out);
1081
- // Should NOT be refused — [::1] is loopback
1082
- expect(parsed.status).not.toBe('refused');
1083
- // Host should be normalized to ::1 (without brackets)
1084
- expect(parsed.host).toBe('::1');
1085
- }, 10_000);
1086
- });
1087
-
1088
- describe('EP-06 regression guard: dist/web/index.html check (PR #1169)', () => {
1089
- it('returns console_web_ui_missing when dist/web/index.html does not exist', () => {
1090
- // beforeEach creates the fake console dir WITH dist/web/index.html.
1091
- // Remove it to simulate a corrupted install (the PR #1169 regression).
1092
- const fakeHome = process.env.__PD_CONSOLE_TEST_FAKE_HOME ?? '';
1093
- const webIndex = path.join(fakeHome, '.openclaw', 'extensions', 'principles-disciple', 'console', 'dist', 'web', 'index.html');
1094
- fs.rmSync(webIndex, { force: true });
1095
-
1096
- const out = runPd(['console', 'open', '--workspace', tmp, '--json', '--no-browser'], workspaceRoot, 5_000);
1097
- const parsed = JSON.parse(out);
1098
- expect(parsed.status).toBe('failed');
1099
- expect(parsed.reason).toBe('console_web_ui_missing');
1100
- expect(parsed.nextAction).toMatch(/create-principles-disciple/);
1101
- }, 10_000);
1102
- });
1103
- });
1104
-
1105
- /**
1106
- * Probe whether IPv6 loopback (::1) is actually usable on this machine.
1107
- * Mirrors the production path (TCP connect), not ICMP ping: on hosts where a
1108
- * VPN/WFP filter driver intercepts ::1 (bind OK + connect EACCES — ERR-111 /
1109
- * PRI-581), the console health probe on ::1 can never succeed, so the CLI
1110
- * test above must skip rather than hard-fail for environmental reasons.
1111
- */
1112
- function isIpv6LoopbackUsable(): Promise<boolean> {
1113
- return new Promise((resolve) => {
1114
- const server = net.createServer();
1115
- let settled = false;
1116
- const finish = (ok: boolean) => {
1117
- if (settled) return;
1118
- settled = true;
1119
- server.close();
1120
- resolve(ok);
1121
- };
1122
- const timer = setTimeout(() => finish(false), 1_500);
1123
- server.once('error', () => {
1124
- clearTimeout(timer);
1125
- finish(false);
1126
- });
1127
- server.listen(0, '::1', () => {
1128
- const addr = server.address();
1129
- const port = addr !== null && typeof addr === 'object' ? addr.port : 0;
1130
- if (port === 0) {
1131
- clearTimeout(timer);
1132
- finish(false);
1133
- return;
1134
- }
1135
- const socket = net.connect({ port, host: '::1' }, () => {
1136
- socket.destroy();
1137
- clearTimeout(timer);
1138
- finish(true);
1139
- });
1140
- socket.once('error', () => {
1141
- clearTimeout(timer);
1142
- finish(false);
1143
- });
1144
- });
1145
- });
1146
- }
1147
-
1148
- function runPd(args: string[], cwd: string, timeoutMs?: number): string {
1149
- try {
1150
- return execFileSync('node', [getBuiltPdCliPath(), ...args], {
1151
- encoding: 'utf8',
1152
- cwd,
1153
- env: buildChildEnv(),
1154
- timeout: timeoutMs,
1155
- });
1156
- } catch (err: unknown) {
1157
- if (err && typeof err === 'object' && Object.hasOwn(err, 'stdout')) {
1158
- const stdoutVal = Reflect.get(err, 'stdout');
1159
- if (typeof stdoutVal === 'string' || stdoutVal instanceof Buffer) {
1160
- return String(stdoutVal);
1161
- }
1162
- }
1163
- throw err;
1164
- }
1165
- }
1166
-
1167
- /** Env for spawned CLI processes: isolated fake HOME, no workspace env leaks. */
1168
- function buildChildEnv(): Record<string, string> {
1169
- const env = { ...process.env } as Record<string, string>;
1170
- const fakeHome = process.env.__PD_CONSOLE_TEST_FAKE_HOME;
1171
- if (fakeHome) {
1172
- env.USERPROFILE = fakeHome;
1173
- env.HOME = fakeHome;
1174
- delete env.HOMEPATH;
1175
- delete env.HOMEDRIVE;
1176
- delete env.PD_WORKSPACE_DIR;
1177
- }
1178
- return env;
1179
- }
1180
-
1181
- /** Runtime type guard for unknown CLI JSON output (rc-1/rc-2). */
1182
- function isRecord(value: unknown): value is Record<string, unknown> {
1183
- return typeof value === 'object' && value !== null;
1184
- }
1185
-
1186
- // ─── Async CLI runner with guaranteed teardown (PRI-526 tests) ───────────────
1187
-
1188
- interface CliJsonRun {
1189
- parsed: unknown;
1190
- child: childProcessModule.ChildProcess;
1191
- }
1192
-
1193
- /**
1194
- * Spawn the CLI and resolve as soon as stdout contains one parseable JSON
1195
- * object. Fails fast (bounded timeout / early exit) with the collected
1196
- * stdout in the error message. The caller MUST call teardownCliTree(run)
1197
- * in a finally block — the CLI process may still be alive after the JSON
1198
- * is emitted (fresh-spawn mode keeps the console server attached).
1199
- */
1200
- async function runPdUntilJson(args: string[], cwd: string, timeoutMs = 12_000): Promise<CliJsonRun> {
1201
- const child = childProcessModule.spawn('node', [getBuiltPdCliPath(), ...args], {
1202
- cwd,
1203
- env: buildChildEnv(),
1204
- });
1205
- let stdout = '';
1206
- child.stdout?.on('data', (d: Buffer) => { stdout += d.toString('utf8'); });
1207
-
1208
- const parsed: unknown = await new Promise<unknown>((resolve, reject) => {
1209
- let done = false;
1210
- const fail = (msg: string): void => {
1211
- if (done) return;
1212
- done = true;
1213
- reject(new Error(`${msg}; stdout so far: ${stdout.slice(0, 400)}`));
1214
- };
1215
- const timer = setTimeout(() => fail('timed out waiting for CLI JSON'), timeoutMs);
1216
- const tryParse = (): boolean => {
1217
- const trimmed = stdout.trim();
1218
- if (!trimmed.startsWith('{')) return false;
1219
- try {
1220
- const value = JSON.parse(trimmed) as unknown;
1221
- done = true;
1222
- clearTimeout(timer);
1223
- resolve(value);
1224
- return true;
1225
- } catch {
1226
- return false; // partial pretty-printed JSON — wait for more chunks
1227
- }
1228
- };
1229
- if (tryParse()) return;
1230
- const onData = (): void => {
1231
- if (tryParse()) child.stdout?.off('data', onData);
1232
- };
1233
- child.stdout?.on('data', onData);
1234
- child.on('error', (err: Error) => fail(`CLI spawn error: ${err.message}`));
1235
- child.on('exit', (code: number | null) => fail(`CLI exited with code ${code} before emitting JSON`));
1236
- });
1237
-
1238
- return { parsed, child };
1239
- }
1240
-
1241
- /**
1242
- * Deterministic teardown of a runPdUntilJson run: kill the reported console
1243
- * server PID (grandchild) first so the CLI can exit on its own, then wait a
1244
- * bounded time, then force-kill the whole CLI tree. Safe to call multiple
1245
- * times and with undefined.
1246
- */
1247
- async function teardownCliTree(run: CliJsonRun | undefined): Promise<void> {
1248
- if (!run) return;
1249
- const record = isRecord(run.parsed) ? run.parsed : undefined;
1250
- const serverPid = record !== undefined && typeof record.serverPid === 'number' ? record.serverPid : undefined;
1251
- if (serverPid !== undefined) {
1252
- try { process.kill(serverPid); } catch { /* already gone */ }
1253
- }
1254
- await new Promise<void>((resolve) => {
1255
- const t = setTimeout(() => { killTreeForce(run.child); resolve(); }, 4_000);
1256
- run.child.once('exit', () => { clearTimeout(t); resolve(); });
1257
- });
1258
- killTreeForce(run.child);
1259
- }
1260
-
1261
- /**
1262
- * Last-resort kill of the CLI child process. The console server grandchild is
1263
- * reaped separately via its reported serverPid (see teardownCliTree), so a
1264
- * plain signal kill suffices — no shell/argv command wrapper needed.
1265
- */
1266
- function killTreeForce(child: childProcessModule.ChildProcess): void {
1267
- try {
1268
- child.kill('SIGKILL');
1269
- } catch { /* already gone */ }
1270
- }
1271
-
1272
- import { checkConsoleRuntimeDependencies } from '../../src/commands/console.js';
1273
-
1274
- describe('checkConsoleRuntimeDependencies', () => {
1275
- it('returns undefined when all deps are intact', () => {
1276
- const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'console-integ-'));
1277
- try {
1278
- // @principles/core: entries are dist/principle-tree-ledger.js + dist/runtime-v2/index.js
1279
- fs.mkdirSync(path.join(tmp, 'node_modules', '@principles', 'core', 'dist', 'runtime-v2'), { recursive: true });
1280
- fs.writeFileSync(path.join(tmp, 'node_modules', '@principles', 'core', 'package.json'), '{}');
1281
- fs.writeFileSync(path.join(tmp, 'node_modules', '@principles', 'core', 'dist', 'principle-tree-ledger.js'), '');
1282
- fs.writeFileSync(path.join(tmp, 'node_modules', '@principles', 'core', 'dist', 'runtime-v2', 'index.js'), '');
1283
- // @principles/host-runtime: entry is dist/index.js
1284
- fs.mkdirSync(path.join(tmp, 'node_modules', '@principles', 'host-runtime', 'dist'), { recursive: true });
1285
- fs.writeFileSync(path.join(tmp, 'node_modules', '@principles', 'host-runtime', 'package.json'), '{}');
1286
- fs.writeFileSync(path.join(tmp, 'node_modules', '@principles', 'host-runtime', 'dist', 'index.js'), '');
1287
- // @principles/install-layout: entry is dist/index.js
1288
- fs.mkdirSync(path.join(tmp, 'node_modules', '@principles', 'install-layout', 'dist'), { recursive: true });
1289
- fs.writeFileSync(path.join(tmp, 'node_modules', '@principles', 'install-layout', 'package.json'), '{}');
1290
- fs.writeFileSync(path.join(tmp, 'node_modules', '@principles', 'install-layout', 'dist', 'index.js'), '');
1291
- // principles-disciple: entry is dist/governance-audit.js
1292
- fs.mkdirSync(path.join(tmp, 'node_modules', 'principles-disciple', 'dist'), { recursive: true });
1293
- fs.writeFileSync(path.join(tmp, 'node_modules', 'principles-disciple', 'package.json'), '{}');
1294
- fs.writeFileSync(path.join(tmp, 'node_modules', 'principles-disciple', 'dist', 'governance-audit.js'), '');
1295
-
1296
- expect(checkConsoleRuntimeDependencies(tmp)).toBeUndefined();
1297
- } finally {
1298
- fs.rmSync(tmp, { recursive: true, force: true });
1299
- }
1300
- });
1301
-
1302
- it('returns error when a dep is missing package.json', () => {
1303
- const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'console-integ-'));
1304
- try {
1305
- // Create all deps intact except host-runtime (no package.json)
1306
- // core
1307
- fs.mkdirSync(path.join(tmp, 'node_modules', '@principles', 'core', 'dist', 'runtime-v2'), { recursive: true });
1308
- fs.writeFileSync(path.join(tmp, 'node_modules', '@principles', 'core', 'package.json'), '{}');
1309
- fs.writeFileSync(path.join(tmp, 'node_modules', '@principles', 'core', 'dist', 'principle-tree-ledger.js'), '');
1310
- fs.writeFileSync(path.join(tmp, 'node_modules', '@principles', 'core', 'dist', 'runtime-v2', 'index.js'), '');
1311
- // install-layout
1312
- fs.mkdirSync(path.join(tmp, 'node_modules', '@principles', 'install-layout', 'dist'), { recursive: true });
1313
- fs.writeFileSync(path.join(tmp, 'node_modules', '@principles', 'install-layout', 'package.json'), '{}');
1314
- fs.writeFileSync(path.join(tmp, 'node_modules', '@principles', 'install-layout', 'dist', 'index.js'), '');
1315
- // principles-disciple
1316
- fs.mkdirSync(path.join(tmp, 'node_modules', 'principles-disciple', 'dist'), { recursive: true });
1317
- fs.writeFileSync(path.join(tmp, 'node_modules', 'principles-disciple', 'package.json'), '{}');
1318
- fs.writeFileSync(path.join(tmp, 'node_modules', 'principles-disciple', 'dist', 'governance-audit.js'), '');
1319
- // @principles/host-runtime without package.json — the broken-shell case
1320
- fs.mkdirSync(path.join(tmp, 'node_modules', '@principles', 'host-runtime', 'dist'), { recursive: true });
1321
- fs.writeFileSync(path.join(tmp, 'node_modules', '@principles', 'host-runtime', 'dist', 'index.js'), '');
1322
-
1323
- const err = checkConsoleRuntimeDependencies(tmp);
1324
- expect(err).toContain('host-runtime');
1325
- expect(err).toContain('package.json');
1326
- } finally {
1327
- fs.rmSync(tmp, { recursive: true, force: true });
1328
- }
1329
- });
1330
-
1331
- it('returns error when a dep has package.json but no dist entry (empty shell)', () => {
1332
- const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'console-integ-'));
1333
- try {
1334
- // core intact
1335
- fs.mkdirSync(path.join(tmp, 'node_modules', '@principles', 'core', 'dist', 'runtime-v2'), { recursive: true });
1336
- fs.writeFileSync(path.join(tmp, 'node_modules', '@principles', 'core', 'package.json'), '{}');
1337
- fs.writeFileSync(path.join(tmp, 'node_modules', '@principles', 'core', 'dist', 'principle-tree-ledger.js'), '');
1338
- fs.writeFileSync(path.join(tmp, 'node_modules', '@principles', 'core', 'dist', 'runtime-v2', 'index.js'), '');
1339
- // install-layout intact
1340
- fs.mkdirSync(path.join(tmp, 'node_modules', '@principles', 'install-layout', 'dist'), { recursive: true });
1341
- fs.writeFileSync(path.join(tmp, 'node_modules', '@principles', 'install-layout', 'package.json'), '{}');
1342
- fs.writeFileSync(path.join(tmp, 'node_modules', '@principles', 'install-layout', 'dist', 'index.js'), '');
1343
- // principles-disciple intact
1344
- fs.mkdirSync(path.join(tmp, 'node_modules', 'principles-disciple', 'dist'), { recursive: true });
1345
- fs.writeFileSync(path.join(tmp, 'node_modules', 'principles-disciple', 'package.json'), '{}');
1346
- fs.writeFileSync(path.join(tmp, 'node_modules', 'principles-disciple', 'dist', 'governance-audit.js'), '');
1347
- // host-runtime exists but has no dist/index.js (root entry missing)
1348
- fs.mkdirSync(path.join(tmp, 'node_modules', '@principles', 'host-runtime'));
1349
- fs.writeFileSync(path.join(tmp, 'node_modules', '@principles', 'host-runtime', 'package.json'), '{}');
1350
-
1351
- const err = checkConsoleRuntimeDependencies(tmp);
1352
- expect(err).toContain('host-runtime');
1353
- expect(err).toContain('dist/index.js');
1354
- } finally {
1355
- fs.rmSync(tmp, { recursive: true, force: true });
1356
- }
1357
- });
1358
-
1359
- it('returns error when a dep junction is dangling (directory missing)', () => {
1360
- const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'console-integ-'));
1361
- try {
1362
- // Create core, install-layout, principles-disciple; leave host-runtime missing
1363
- fs.mkdirSync(path.join(tmp, 'node_modules', '@principles', 'core', 'dist', 'runtime-v2'), { recursive: true });
1364
- fs.writeFileSync(path.join(tmp, 'node_modules', '@principles', 'core', 'package.json'), '{}');
1365
- fs.writeFileSync(path.join(tmp, 'node_modules', '@principles', 'core', 'dist', 'principle-tree-ledger.js'), '');
1366
- fs.writeFileSync(path.join(tmp, 'node_modules', '@principles', 'core', 'dist', 'runtime-v2', 'index.js'), '');
1367
- fs.mkdirSync(path.join(tmp, 'node_modules', '@principles', 'install-layout', 'dist'), { recursive: true });
1368
- fs.writeFileSync(path.join(tmp, 'node_modules', '@principles', 'install-layout', 'package.json'), '{}');
1369
- fs.writeFileSync(path.join(tmp, 'node_modules', '@principles', 'install-layout', 'dist', 'index.js'), '');
1370
- fs.mkdirSync(path.join(tmp, 'node_modules', 'principles-disciple', 'dist'), { recursive: true });
1371
- fs.writeFileSync(path.join(tmp, 'node_modules', 'principles-disciple', 'package.json'), '{}');
1372
- fs.writeFileSync(path.join(tmp, 'node_modules', 'principles-disciple', 'dist', 'governance-audit.js'), '');
1373
-
1374
- const err = checkConsoleRuntimeDependencies(tmp);
1375
- expect(err).toContain('host-runtime');
1376
- expect(err).toContain('package.json');
1377
- } finally {
1378
- fs.rmSync(tmp, { recursive: true, force: true });
1379
- }
1380
- });
1381
- });