@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,297 +0,0 @@
1
- /**
2
- * pd codex setup command tests (Slice D consent UX).
3
- *
4
- * Real-filesystem integration style: every test builds a disposable
5
- * workspace (.pd/config.yaml included) and exercises the production config
6
- * editor + consent store — no fs mocks, so round-trip verification, comment
7
- * preservation, and atomic-rename behavior are proven, not assumed.
8
- *
9
- * Config fixtures are built from the production `getDefaultPdConfig()` (same
10
- * source as `pd runtime init`) so they pass the full validator.
11
- *
12
- * Covers:
13
- * - --show-disclosure: frozen text printed (zh + en), zero mutation.
14
- * - --accept: consent recorded granted BEFORE flag flip; config.yaml gains
15
- * features.codex_conversation_ingestion.enabled=true; comments preserved;
16
- * production loader sees the flag enabled.
17
- * - --decline: consent declined; a hand-enabled flag is regularized back off;
18
- * host.codex and other flags untouched.
19
- * - cli-4: --accept --decline mutex refusal.
20
- * - cli-5: refusals (no workspace config, malformed config) mutate nothing.
21
- * - decision_required: --json without explicit decision; non-TTY interactive.
22
- */
23
- import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
24
- import fs from 'node:fs';
25
- import os from 'node:os';
26
- import path from 'node:path';
27
- import * as yaml from 'js-yaml';
28
- import { getDefaultPdConfig } from '@principles/core/runtime-v2';
29
-
30
- let logLines: string[] = [];
31
- let savedExitCode: number | undefined;
32
-
33
- const HEADER_COMMENT = '# PD Runtime Configuration — single source of truth (.pd/config.yaml, ADR-0016)\n# Edited by the Owner. Comments must survive consent-driven flag edits.\n';
34
-
35
- const CORE = getDefaultPdConfig();
36
- // Everything except `features` — features blocks are appended per-test so the
37
- // editor's insert/replace/append paths are all exercised on real content.
38
- // Feature override keys are FLAT flag ids ('host.codex' is a literal key),
39
- // and every override requires category+enabled (validatePdConfig).
40
- const { features: _coreFeatures, ...coreWithoutFeatures } = CORE as unknown as Record<string, unknown>;
41
- const PRELUDE = HEADER_COMMENT + yaml.dump(
42
- { ...coreWithoutFeatures, workspace: { default: '%WS%' } },
43
- { indent: 2, lineWidth: 200, noRefs: true },
44
- );
45
-
46
- function makeWorkspace(configYaml: string | null): string {
47
- const ws = fs.mkdtempSync(path.join(os.tmpdir(), 'pd-codex-setup-'));
48
- if (configYaml !== null) {
49
- fs.mkdirSync(path.join(ws, '.pd'), { recursive: true });
50
- fs.writeFileSync(path.join(ws, '.pd', 'config.yaml'), renderConfig(ws, configYaml), 'utf8');
51
- }
52
- return ws;
53
- }
54
-
55
- function renderConfig(ws: string, template: string): string {
56
- // workspace.default must be an absolute path (validatePdConfig); forward
57
- // slashes keep the YAML plain scalar portable across platforms.
58
- return template.replaceAll('%WS%', ws.replace(/\\/g, '/'));
59
- }
60
-
61
- async function run(options: Record<string, unknown>): Promise<{ reports: string[]; json: unknown[] }> {
62
- const { handleCodexSetup } = await import('../../src/commands/codex-setup.js');
63
- await handleCodexSetup(options as never);
64
- const json: unknown[] = [];
65
- const reports: string[] = [];
66
- for (const line of logLines) {
67
- if (line.startsWith('{')) {
68
- try {
69
- json.push(JSON.parse(line));
70
- } catch {
71
- reports.push(line);
72
- }
73
- } else {
74
- reports.push(line);
75
- }
76
- }
77
- return { reports, json };
78
- }
79
-
80
- function readConsent(ws: string): Record<string, unknown> | null {
81
- const p = path.join(ws, '.pd', 'codex-ingestion-consent.json');
82
- if (!fs.existsSync(p)) return null;
83
- return JSON.parse(fs.readFileSync(p, 'utf8')) as Record<string, unknown>;
84
- }
85
-
86
- function readConfig(ws: string): string {
87
- return fs.readFileSync(path.join(ws, '.pd', 'config.yaml'), 'utf8');
88
- }
89
-
90
- beforeEach(() => {
91
- logLines = [];
92
- savedExitCode = process.exitCode;
93
- process.exitCode = undefined;
94
- vi.spyOn(console, 'log').mockImplementation((...args: unknown[]) => {
95
- logLines.push(args.map(String).join(' '));
96
- });
97
- // --show-disclosure writes via process.stdout.write; capture it too.
98
- vi.spyOn(process.stdout, 'write').mockImplementation(((chunk: unknown) => {
99
- logLines.push(String(chunk));
100
- return true;
101
- }) as typeof process.stdout.write);
102
- });
103
-
104
- afterEach(() => {
105
- vi.restoreAllMocks();
106
- process.exitCode = savedExitCode;
107
- });
108
-
109
- describe('pd codex setup — show-disclosure', () => {
110
- it('prints the frozen Chinese SSoT by default and English with --lang en, mutating nothing', async () => {
111
- const ws = makeWorkspace(PRELUDE + 'features: {}\n');
112
- await run({ workspace: ws, showDisclosure: true });
113
- let all = logLines.join('\n');
114
- expect(all).toContain('对话观察与治理闭环');
115
- expect(all).toContain('默认关闭。只有你在看到本说明后明确选择开启才会生效');
116
- await run({ workspace: ws, showDisclosure: true, lang: 'en' });
117
- all = logLines.join('\n');
118
- expect(all).toContain('Off by default');
119
- expect(readConsent(ws)).toBeNull();
120
- expect(readConfig(ws)).toBe(renderConfig(ws, PRELUDE + 'features: {}\n'));
121
- });
122
- });
123
-
124
- describe('pd codex setup — accept flow', () => {
125
- it('records granted consent, enables the flag, preserves comments, and round-trips', async () => {
126
- const ws = makeWorkspace(PRELUDE + 'features: {}\n');
127
- const { json } = await run({ workspace: ws, accept: true, json: true });
128
- expect(json).toHaveLength(1);
129
- const report = json[0] as Record<string, unknown>;
130
- expect(report.status, JSON.stringify(report)).toBe('ok');
131
- expect(report.decision).toBe('granted');
132
- expect((report.ingestionFlag as Record<string, unknown>).enabled).toBe(true);
133
- expect(report.disclosureVersion).toBe('g2a-2026-08-28');
134
-
135
- const consent = readConsent(ws);
136
- expect(consent?.decision).toBe('granted');
137
- expect(consent?.decidedVia).toBe('pd_codex_setup');
138
-
139
- const configAfter = readConfig(ws);
140
- expect(configAfter).toContain('Comments must survive consent-driven flag edits.');
141
- expect(configAfter).toContain(' codex_conversation_ingestion:');
142
-
143
- // Production loader is the round-trip authority.
144
- const { computeFeatureFlagsFromConfig, isFeatureEnabled } = await import('@principles/core/runtime-v2');
145
- const { loadPdConfigForPlugin } = await import('@principles/host-runtime');
146
- const result = loadPdConfigForPlugin(ws);
147
- expect(result.ok).toBe(true);
148
- expect(isFeatureEnabled(computeFeatureFlagsFromConfig(result.effective), 'codex_conversation_ingestion')).toBe(true);
149
- expect(process.exitCode).toBeUndefined();
150
- });
151
-
152
- it('replaces an empty features mapping with the enabled flag block', async () => {
153
- const ws = makeWorkspace(PRELUDE + 'features: {}\n');
154
- const { json } = await run({ workspace: ws, accept: true, json: true });
155
- expect((json[0] as Record<string, unknown>).status, JSON.stringify(json[0])).toBe('ok');
156
- expect(readConfig(ws)).toMatch(/features:\r?\n {2}codex_conversation_ingestion:\r?\n {4}category: quiet\r?\n {4}enabled: true/);
157
- });
158
-
159
- it('inserts the flag into an existing features block that has other overrides', async () => {
160
- const withOtherFlags = PRELUDE + 'features:\n prompt:\n category: core\n enabled: true\n internalization_auto_consumer:\n category: core\n enabled: true\n';
161
- const ws = makeWorkspace(withOtherFlags);
162
- const { json } = await run({ workspace: ws, accept: true, json: true });
163
- expect((json[0] as Record<string, unknown>).status, JSON.stringify(json[0])).toBe('ok');
164
- const configAfter = readConfig(ws);
165
- expect(configAfter).toMatch(/ {2}codex_conversation_ingestion:\r?\n {4}category: quiet\r?\n {4}enabled: true/);
166
- // Sibling overrides survive byte-for-byte.
167
- expect(configAfter).toContain(' internalization_auto_consumer:');
168
- expect(configAfter).toContain(' prompt:');
169
- });
170
- });
171
-
172
- describe('pd codex setup — decline flow', () => {
173
- it('records revoked consent and regularizes a hand-enabled flag back off', async () => {
174
- const handEnabled = PRELUDE + 'features:\n host.codex:\n category: core\n enabled: true\n codex_conversation_ingestion:\n category: quiet\n enabled: true # hand-edited without consent\n';
175
- const ws = makeWorkspace(handEnabled);
176
- const { json } = await run({ workspace: ws, decline: true, json: true });
177
- const report = json[0] as Record<string, unknown>;
178
- expect(report.status, JSON.stringify(report)).toBe('ok');
179
- expect(report.decision).toBe('revoked');
180
- expect((report.ingestionFlag as Record<string, unknown>).enabled).toBe(false);
181
- expect(report.nextAction).toContain('No transcript');
182
-
183
- expect(readConsent(ws)?.decision).toBe('revoked');
184
- const configAfter = readConfig(ws);
185
- // The inline comment survives; only the value flips.
186
- expect(configAfter).toContain('enabled: false # hand-edited without consent');
187
- // host.codex governance is untouched by the decline.
188
- expect(configAfter).toContain('category: core');
189
- expect(configAfter).toContain('host.codex:');
190
- expect(process.exitCode).toBeUndefined();
191
- });
192
- });
193
-
194
- describe('pd codex setup — consent transition state machine (review round 2)', () => {
195
- it('Case 1: consent write ok + flag enable ok ⇒ state=granted, runtime enabled=true', async () => {
196
- const ws = makeWorkspace(PRELUDE + 'features: {}\n');
197
- const { json } = await run({ workspace: ws, accept: true, json: true });
198
- const report = json[0] as Record<string, unknown>;
199
- expect(report.status, JSON.stringify(report)).toBe('ok');
200
- expect(report.decision).toBe('granted');
201
- expect(report.consentState).toBe('granted');
202
- expect((report.ingestionFlag as Record<string, unknown>).enabled).toBe(true);
203
- expect(readConsent(ws)?.decision).toBe('granted');
204
- });
205
-
206
- it('Case 2: flag enable fails ⇒ state != granted, runtime enabled=false, failure reason recorded and surfaced', async () => {
207
- const ws = makeWorkspace(PRELUDE + 'features: {}\n');
208
- // Break the config AFTER the initial validation so the round-trip
209
- // verification inside the flag editor fails: consent went to 'pending'
210
- // first, then the activation fails ⇒ terminal state 'failed' with the
211
- // reason, and the flag stays off (no granted/disabled mismatch).
212
- const original = await import('../../src/commands/codex-setup.js');
213
- const brokenLoader = await import('@principles/host-runtime');
214
- const realLoad = brokenLoader.loadPdConfigForPlugin;
215
- let loadCalls = 0;
216
- const spy = vi.spyOn(brokenLoader, 'loadPdConfigForPlugin').mockImplementation((dir: string) => {
217
- loadCalls += 1;
218
- // Call 1 is the handler's pre-check (ok); call 2 is the round-trip
219
- // verification INSIDE setCodexConversationIngestionFlag — break it there.
220
- if (loadCalls === 1) return realLoad(dir);
221
- return {
222
- ok: false,
223
- effective: realLoad(dir).effective,
224
- source: 'malformed',
225
- configPath: dir,
226
- warnings: [],
227
- errors: [{ path: 'features', reason: 'injected round-trip failure (test)', nextAction: 'fix yaml' }],
228
- };
229
- });
230
- try {
231
- const { json } = await run({ workspace: ws, accept: true, json: true });
232
- const report = json[0] as Record<string, unknown>;
233
- expect(report.status, JSON.stringify(report)).toBe('degraded');
234
- expect(report.decision).toBe('failed');
235
- expect(report.consentState).toBe('failed');
236
- expect(report.reason).toContain('injected round-trip failure');
237
- expect((report.ingestionFlag as Record<string, unknown>).enabled).toBe(false);
238
- // NOT granted — the whole point of the state machine.
239
- expect(report.consentState).not.toBe('granted');
240
- const consent = readConsent(ws);
241
- expect(consent?.decision).toBe('failed');
242
- expect(String(consent?.failureReason)).toContain('injected round-trip failure');
243
- expect(process.exitCode).toBe(1);
244
- } finally {
245
- spy.mockRestore();
246
- void original;
247
- }
248
- });
249
-
250
- it('re-running accept after a failed attempt reaches granted (state machine recovers)', async () => {
251
- const ws = makeWorkspace(PRELUDE + 'features: {}\n');
252
- // Simulate the failed state on disk, then accept again.
253
- fs.mkdirSync(path.join(ws, '.pd'), { recursive: true });
254
- fs.writeFileSync(path.join(ws, '.pd', 'codex-ingestion-consent.json'), JSON.stringify({
255
- decision: 'failed', disclosureVersion: 'g2a-2026-08-28', decidedAt: new Date().toISOString(),
256
- decidedVia: 'pd_codex_setup', failureReason: 'flag activation failed: prior run', schemaVersion: '2',
257
- }), 'utf8');
258
- const { json } = await run({ workspace: ws, accept: true, json: true });
259
- const report = json[0] as Record<string, unknown>;
260
- expect(report.status, JSON.stringify(report)).toBe('ok');
261
- expect(report.decision).toBe('granted');
262
- expect(readConsent(ws)?.decision).toBe('granted');
263
- });
264
- });
265
-
266
- describe('pd codex setup — refusals mutate nothing (cli-4/cli-5/cli-6)', () => {
267
- it('refuses --accept together with --decline', async () => {
268
- const ws = makeWorkspace(PRELUDE + 'features: {}\n');
269
- const { json } = await run({ workspace: ws, accept: true, decline: true, json: true });
270
- expect((json[0] as Record<string, unknown>).reason).toBe('accept_decline_mutex');
271
- expect(readConsent(ws)).toBeNull();
272
- expect(process.exitCode).toBe(1);
273
- });
274
-
275
- it('refuses when the workspace has no .pd/config.yaml', async () => {
276
- const ws = makeWorkspace(null);
277
- const { json } = await run({ workspace: ws, accept: true, json: true });
278
- expect((json[0] as Record<string, unknown>).reason).toBe('workspace_config_not_found');
279
- expect(fs.existsSync(path.join(ws, '.pd'))).toBe(false);
280
- });
281
-
282
- it('refuses a malformed config without recording consent', async () => {
283
- const ws = makeWorkspace(PRELUDE + 'features: [not, a, mapping]\n');
284
- const { json } = await run({ workspace: ws, accept: true, json: true });
285
- expect((json[0] as Record<string, unknown>).reason).toMatch(/^workspace_config_malformed/);
286
- expect(readConsent(ws)).toBeNull();
287
- });
288
-
289
- it('requires an explicit decision in --json mode and without a TTY', async () => {
290
- const ws = makeWorkspace(PRELUDE + 'features: {}\n');
291
- const viaJson = await run({ workspace: ws, json: true });
292
- expect((viaJson.json[0] as Record<string, unknown>).reason).toBe('decision_required');
293
- const viaNonTty = await run({ workspace: ws });
294
- expect(viaNonTty.reports.join('\n')).toContain('decision_required');
295
- expect(readConsent(ws)).toBeNull();
296
- });
297
- });
@@ -1,95 +0,0 @@
1
- /**
2
- * PRI-655 — `pd codex worker` daemon loop resilience.
3
- *
4
- * Drives the REAL handleCodexWorker with only the cycle boundary mocked
5
- * (importOriginal spread — ERR-115): the first cycle rejects (an exception
6
- * escaping the adapter's internal component catches), the second resolves.
7
- * The daemon must (a) log the failure with a next action, (b) keep looping —
8
- * round two runs, (c) exit cleanly on SIGINT with signal listeners removed.
9
- */
10
- import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
11
- import * as fs from 'node:fs';
12
- import * as os from 'node:os';
13
- import * as path from 'node:path';
14
-
15
- const { mockRunCycle } = vi.hoisted(() => {
16
- const mockRunCycle = vi.fn();
17
- return { mockRunCycle };
18
- });
19
-
20
- vi.mock('@principles/codex-adapter', async (importOriginal) => {
21
- const actual = await importOriginal<typeof import('@principles/codex-adapter')>();
22
- return {
23
- ...actual,
24
- runCodexWorkspaceWorkerCycle: mockRunCycle,
25
- };
26
- });
27
-
28
- const { resolveWorkspaceDir } = vi.hoisted(() => {
29
- const resolveWorkspaceDir = vi.fn();
30
- return { resolveWorkspaceDir };
31
- });
32
- vi.mock('../../src/resolve-workspace.js', () => ({
33
- resolveWorkspaceDir,
34
- }));
35
-
36
- import { handleCodexWorker } from '../../src/commands/codex-worker.js';
37
-
38
- describe('codex worker daemon loop resilience (PRI-655)', () => {
39
- let workspaceDir: string;
40
- let logSpy: ReturnType<typeof vi.spyOn>;
41
- let errorSpy: ReturnType<typeof vi.spyOn>;
42
-
43
- beforeEach(() => {
44
- workspaceDir = fs.mkdtempSync(path.join(os.tmpdir(), 'pd-codex-daemon-'));
45
- resolveWorkspaceDir.mockReturnValue(workspaceDir);
46
- logSpy = vi.spyOn(console, 'log').mockImplementation(() => {});
47
- errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
48
- });
49
-
50
- afterEach(() => {
51
- vi.restoreAllMocks();
52
- vi.clearAllMocks();
53
- fs.rmSync(workspaceDir, { recursive: true, force: true });
54
- });
55
-
56
- async function waitForCalls(count: number, timeoutMs = 8000): Promise<void> {
57
- const deadline = Date.now() + timeoutMs;
58
- while (mockRunCycle.mock.calls.length < count && Date.now() < deadline) {
59
- await new Promise((resolve) => setTimeout(resolve, 50));
60
- }
61
- expect(mockRunCycle.mock.calls.length).toBeGreaterThanOrEqual(count);
62
- }
63
-
64
- it('a rejected cycle logs with a next action and the daemon SURVIVES to the next round', async () => {
65
- mockRunCycle
66
- .mockRejectedValueOnce(new Error('boom: escaping exception'))
67
- .mockResolvedValue({ workspaceDir, mode: 'ready' });
68
-
69
- const handler = handleCodexWorker({ workspace: workspaceDir, intervalMs: 1000 });
70
-
71
- // Review fix (ERR-071 recurrence): the daemon keeps looping with real
72
- // timers and signal listeners — stop it in finally so assertion failures
73
- // cannot leak a live background loop into subsequent tests.
74
- try {
75
- // Round one rejects; the daemon reports it instead of crashing.
76
- await waitForCalls(1);
77
- await vi.waitFor(() => {
78
- expect(errorSpy).toHaveBeenCalledWith(expect.stringContaining('[PD:CodexWorker] cycle failed: boom: escaping exception'));
79
- expect(errorSpy).toHaveBeenCalledWith(expect.stringContaining('Investigate: pd codex worker --status'));
80
- });
81
-
82
- // Round two runs — the loop did not die (the bug: process crash).
83
- await waitForCalls(2);
84
- expect(logSpy).toHaveBeenCalledWith(expect.stringContaining(`Codex workspace worker (${workspaceDir})`));
85
- } finally {
86
- process.emit('SIGINT');
87
- await handler.catch(() => undefined);
88
- }
89
-
90
- // Clean exit: signal listeners removed (only reached after the finally
91
- // stopped the daemon, on the happy path AND on assertion failure).
92
- expect(process.listenerCount('SIGINT')).toBe(0);
93
- expect(process.listenerCount('SIGTERM')).toBe(0);
94
- }, 20_000);
95
- });
@@ -1,207 +0,0 @@
1
- /**
2
- * Command-registration / parser + functional tests for the PRI-624 Slice C
3
- * Codex commands (cli-7): `pd codex ingest catch-up` and `pd codex worker`.
4
- *
5
- * Registration mirrors src/index.ts. Functional tests exercise the real
6
- * handlers against a temp workspace: --json emits exactly one parseable
7
- * JSON object (cli-1), flag-off skips carry reason + nextAction (cli-6), and
8
- * failed paths mutate nothing.
9
- */
10
- import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
11
- import fs from 'node:fs';
12
- import os from 'node:os';
13
- import path from 'node:path';
14
- import { Command } from 'commander';
15
- import { getDefaultPdConfig } from '@principles/core/runtime-v2';
16
-
17
- function buildTestProgram(): Command {
18
- const program = new Command();
19
- const codex = program.command('codex');
20
- codex.command('reconcile');
21
- // PRI-625 Slice D: consent UX command (mirrors src/index.ts registration).
22
- codex
23
- .command('setup')
24
- .option('-w, --workspace <path>', 'Workspace directory')
25
- .option('--accept', 'Explicitly accept after the disclosure has been presented (non-interactive)')
26
- .option('--decline', 'Explicitly decline; the ingestion flag stays off and no transcript is ever read')
27
- .option('--show-disclosure', 'Print the frozen disclosure text (zh default, --lang en) and exit without mutating anything')
28
- .option('--lang <zh|en>', 'Disclosure language for presentation')
29
- .option('--json', 'Output raw JSON (decision must be explicit: --accept or --decline)')
30
- .action(() => {});
31
- const ingest = codex.command('ingest');
32
- ingest
33
- .command('catch-up')
34
- .option('-w, --workspace <path>', 'Workspace directory')
35
- .option('--max-rollouts <n>', 'Maximum rollouts to catch up per pass (1-32, default 8)')
36
- .option('--json', 'Output raw JSON')
37
- .action(() => {});
38
- codex
39
- .command('worker')
40
- .option('-w, --workspace <path>', 'Workspace directory')
41
- .option('--once', 'Run exactly one bounded cycle and exit')
42
- .option('--interval <ms>', 'Cycle interval for continuous mode')
43
- .option('--status', 'Report the SPEC §15 worker mode without executing anything')
44
- .option('--json', 'Output raw JSON')
45
- .action(() => {});
46
- return program;
47
- }
48
-
49
- describe('codex Slice D setup command registration (cli-7)', () => {
50
- it('parses codex setup flags including --accept/--decline/--show-disclosure', () => {
51
- const program = buildTestProgram();
52
- program.parse(['node', 'pd', 'codex', 'setup', '--workspace', '/tmp/ws', '--accept', '--lang', 'en']);
53
- const codex = program.commands.find((c) => c.name() === 'codex');
54
- const setup = codex?.commands.find((c) => c.name() === 'setup');
55
- expect(setup).toBeDefined();
56
- expect(setup?.opts().workspace).toBe('/tmp/ws');
57
- expect(setup?.opts().accept).toBe(true);
58
- expect(setup?.opts().decline).toBeUndefined();
59
- expect(setup?.opts().lang).toBe('en');
60
-
61
- const program2 = buildTestProgram();
62
- program2.parse(['node', 'pd', 'codex', 'setup', '--show-disclosure']);
63
- const setup2 = program2.commands.find((c) => c.name() === 'codex')?.commands.find((c) => c.name() === 'setup');
64
- expect(setup2?.opts().showDisclosure).toBe(true);
65
- });
66
- });
67
-
68
- describe('codex Slice C command registration (cli-7)', () => {
69
- it('parses codex ingest catch-up flags', () => {
70
- const program = buildTestProgram();
71
- program.parse(['node', 'pd', 'codex', 'ingest', 'catch-up', '--workspace', '/tmp/ws', '--max-rollouts', '4', '--json']);
72
- const codex = program.commands.find((c) => c.name() === 'codex');
73
- const ingest = codex?.commands.find((c) => c.name() === 'ingest');
74
- const catchUp = ingest?.commands.find((c) => c.name() === 'catch-up');
75
- expect(catchUp).toBeDefined();
76
- expect(catchUp?.opts().workspace).toBe('/tmp/ws');
77
- expect(catchUp?.opts().maxRollouts).toBe('4');
78
- expect(catchUp?.opts().json).toBe(true);
79
- });
80
-
81
- it('parses codex worker flags including --once and --status', () => {
82
- const program = buildTestProgram();
83
- program.parse(['node', 'pd', 'codex', 'worker', '--workspace', '/tmp/ws', '--once', '--json']);
84
- const codex = program.commands.find((c) => c.name() === 'codex');
85
- const worker = codex?.commands.find((c) => c.name() === 'worker');
86
- expect(worker).toBeDefined();
87
- expect(worker?.opts().workspace).toBe('/tmp/ws');
88
- expect(worker?.opts().once).toBe(true);
89
- expect(worker?.opts().json).toBe(true);
90
-
91
- const program2 = buildTestProgram();
92
- program2.parse(['node', 'pd', 'codex', 'worker', '--status']);
93
- const worker2 = program2.commands.find((c) => c.name() === 'codex')?.commands.find((c) => c.name() === 'worker');
94
- expect(worker2?.opts().status).toBe(true);
95
- // --interval is registered for continuous mode
96
- const intervalOption = worker?.options.find((o) => o.long === '--interval');
97
- expect(intervalOption).toBeDefined();
98
- });
99
- });
100
-
101
- describe('codex ingest catch-up handler (functional)', () => {
102
- let workspaceDir: string;
103
- let logSpy: ReturnType<typeof vi.spyOn>;
104
-
105
- beforeEach(() => {
106
- workspaceDir = fs.mkdtempSync(path.join(os.tmpdir(), 'pd-cli-catchup-'));
107
- fs.mkdirSync(path.join(workspaceDir, '.pd'), { recursive: true });
108
- fs.mkdirSync(path.join(workspaceDir, '.state'), { recursive: true });
109
- fs.writeFileSync(path.join(workspaceDir, '.state', 'trajectory.db'), '');
110
- const config = getDefaultPdConfig();
111
- config.features['host.codex'].enabled = true;
112
- config.features.codex_conversation_ingestion.enabled = false;
113
- fs.writeFileSync(path.join(workspaceDir, '.pd', 'config.yaml'), JSON.stringify(config));
114
- logSpy = vi.spyOn(console, 'log').mockImplementation(() => {});
115
- });
116
-
117
- afterEach(() => {
118
- logSpy.mockRestore();
119
- fs.rmSync(workspaceDir, { recursive: true, force: true });
120
- });
121
-
122
- it('emits exactly one JSON object and skips with reason+nextAction when ingestion is off', { timeout: 20_000 }, async () => {
123
- const { handleCodexIngestCatchUp } = await import('../../src/commands/codex-ingest-catchup.js');
124
- await handleCodexIngestCatchUp({ workspace: workspaceDir, json: true });
125
- expect(logSpy).toHaveBeenCalledTimes(1);
126
- const report = JSON.parse(logSpy.mock.calls[0]?.[0] as string) as { status: string; reason: string; nextAction: string };
127
- expect(report.status).toBe('skipped');
128
- expect(report.reason).toBe('feature_disabled');
129
- expect(report.nextAction).toContain('codex_conversation_ingestion');
130
- expect(process.exitCode ?? 0).toBe(0);
131
- });
132
- });
133
-
134
- describe('codex worker handler (functional)', () => {
135
- let workspaceDir: string;
136
- let logSpy: ReturnType<typeof vi.spyOn>;
137
-
138
- beforeEach(() => {
139
- workspaceDir = fs.mkdtempSync(path.join(os.tmpdir(), 'pd-cli-worker-'));
140
- fs.mkdirSync(path.join(workspaceDir, '.pd'), { recursive: true });
141
- fs.mkdirSync(path.join(workspaceDir, '.state'), { recursive: true });
142
- fs.writeFileSync(path.join(workspaceDir, '.state', 'trajectory.db'), '');
143
- const config = getDefaultPdConfig();
144
- config.features['host.codex'].enabled = true;
145
- config.features.internalization_auto_consumer.enabled = false;
146
- fs.writeFileSync(path.join(workspaceDir, '.pd', 'config.yaml'), JSON.stringify(config));
147
- logSpy = vi.spyOn(console, 'log').mockImplementation(() => {});
148
- });
149
-
150
- afterEach(() => {
151
- logSpy.mockRestore();
152
- process.exitCode = 0;
153
- fs.rmSync(workspaceDir, { recursive: true, force: true });
154
- });
155
-
156
- it('--once reports paused with reason+nextAction when the consumer flag is off', { timeout: 20_000 }, async () => {
157
- const { handleCodexWorker } = await import('../../src/commands/codex-worker.js');
158
- await handleCodexWorker({ workspace: workspaceDir, once: true, json: true });
159
- expect(logSpy).toHaveBeenCalledTimes(1);
160
- const report = JSON.parse(logSpy.mock.calls[0]?.[0] as string) as { mode: string; reason: string; nextAction: string };
161
- expect(report.mode).toBe('paused');
162
- expect(report.reason).toBe('internalization_auto_consumer_disabled');
163
- expect(report.nextAction).toContain('pd diagnose');
164
- expect(process.exitCode ?? 0).toBe(0);
165
- });
166
-
167
- it('--json without --once/--status is refused (continuous mode streams, it is not one JSON document)', async () => {
168
- const { handleCodexWorker } = await import('../../src/commands/codex-worker.js');
169
- await handleCodexWorker({ workspace: workspaceDir, json: true });
170
- expect(logSpy).toHaveBeenCalledTimes(1);
171
- const error = JSON.parse(logSpy.mock.calls[0]?.[0] as string) as { error: string; reason: string; nextAction: string };
172
- expect(error.error).toBe('cli_contract');
173
- expect(error.reason).toBe('json_without_once_or_status');
174
- expect(error.nextAction).toContain('--once');
175
- expect(process.exitCode).toBe(1);
176
- });
177
-
178
- it('--once without --json prints the human-readable cycle report', { timeout: 20_000 }, async () => {
179
- const { handleCodexWorker } = await import('../../src/commands/codex-worker.js');
180
- await handleCodexWorker({ workspace: workspaceDir, once: true, json: false });
181
- // Human-readable form: one multi-line report, no JSON envelope.
182
- const output = logSpy.mock.calls.map((call) => String(call[0])).join('\n');
183
- expect(output).toContain('Codex workspace worker');
184
- expect(output).toContain('mode: paused');
185
- expect(output).toContain('catch-up:');
186
- expect(output).toContain('reconcile:');
187
- expect(output).toContain('next action:');
188
- expect(process.exitCode ?? 0).toBe(0);
189
- });
190
-
191
- it('--status reports manual_action_required for a workspace absent from the install manifest', async () => {
192
- const { handleCodexWorker } = await import('../../src/commands/codex-worker.js');
193
- // Execution enabled — the manifest absence is then the deciding fact.
194
- const config = getDefaultPdConfig();
195
- config.features['host.codex'].enabled = true;
196
- config.features.internalization_auto_consumer.enabled = true;
197
- fs.writeFileSync(path.join(workspaceDir, '.pd', 'config.yaml'), JSON.stringify(config));
198
- await handleCodexWorker({ workspace: workspaceDir, status: true, json: true });
199
- expect(logSpy).toHaveBeenCalledTimes(1);
200
- const report = JSON.parse(logSpy.mock.calls[0]?.[0] as string) as { mode: string; reason: string; registeredInInstallManifest: boolean; nextAction: string };
201
- expect(report.mode).toBe('manual_action_required');
202
- expect(report.reason).toBe('workspace_not_in_install_manifest');
203
- expect(report.registeredInInstallManifest).toBe(false);
204
- expect(report.nextAction).toContain('pd codex ingest catch-up');
205
- expect(process.exitCode ?? 0).toBe(0);
206
- });
207
- });