@principles/pd-cli 1.133.0 → 1.135.0

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 (215) hide show
  1. package/dist/commands/__tests__/intent-flag-wiring.test.js +74 -3
  2. package/dist/commands/__tests__/intent-flag-wiring.test.js.map +1 -1
  3. package/dist/commands/__tests__/pain-retry-maxTokens-flag.test.d.ts +2 -0
  4. package/dist/commands/__tests__/pain-retry-maxTokens-flag.test.d.ts.map +1 -0
  5. package/dist/commands/__tests__/pain-retry-maxTokens-flag.test.js +60 -0
  6. package/dist/commands/__tests__/pain-retry-maxTokens-flag.test.js.map +1 -0
  7. package/dist/commands/__tests__/rulecode-flag-wiring.test.js +11 -4
  8. package/dist/commands/__tests__/rulecode-flag-wiring.test.js.map +1 -1
  9. package/dist/commands/__tests__/run-rulehost-flag-wiring.test.js +9 -0
  10. package/dist/commands/__tests__/run-rulehost-flag-wiring.test.js.map +1 -1
  11. package/dist/commands/admission-gate.d.ts +24 -0
  12. package/dist/commands/admission-gate.d.ts.map +1 -0
  13. package/dist/commands/admission-gate.js +29 -0
  14. package/dist/commands/admission-gate.js.map +1 -0
  15. package/dist/commands/candidate.d.ts.map +1 -1
  16. package/dist/commands/candidate.js +72 -6
  17. package/dist/commands/candidate.js.map +1 -1
  18. package/dist/commands/console.d.ts.map +1 -1
  19. package/dist/commands/console.js +42 -0
  20. package/dist/commands/console.js.map +1 -1
  21. package/dist/commands/demo-story-a.d.ts.map +1 -1
  22. package/dist/commands/demo-story-a.js +4 -2
  23. package/dist/commands/demo-story-a.js.map +1 -1
  24. package/dist/commands/diagnose.d.ts.map +1 -1
  25. package/dist/commands/diagnose.js +155 -8
  26. package/dist/commands/diagnose.js.map +1 -1
  27. package/dist/commands/errors-list.d.ts +25 -0
  28. package/dist/commands/errors-list.d.ts.map +1 -0
  29. package/dist/commands/errors-list.js +368 -0
  30. package/dist/commands/errors-list.js.map +1 -0
  31. package/dist/commands/health-codex.d.ts +7 -0
  32. package/dist/commands/health-codex.d.ts.map +1 -0
  33. package/dist/commands/health-codex.js +209 -0
  34. package/dist/commands/health-codex.js.map +1 -0
  35. package/dist/commands/health.d.ts +24 -0
  36. package/dist/commands/health.d.ts.map +1 -1
  37. package/dist/commands/health.js +48 -0
  38. package/dist/commands/health.js.map +1 -1
  39. package/dist/commands/intent.d.ts +21 -4
  40. package/dist/commands/intent.d.ts.map +1 -1
  41. package/dist/commands/intent.js +88 -27
  42. package/dist/commands/intent.js.map +1 -1
  43. package/dist/commands/pain-evidence.d.ts +6 -0
  44. package/dist/commands/pain-evidence.d.ts.map +1 -1
  45. package/dist/commands/pain-evidence.js +6 -0
  46. package/dist/commands/pain-evidence.js.map +1 -1
  47. package/dist/commands/pain-record.d.ts.map +1 -1
  48. package/dist/commands/pain-record.js +21 -0
  49. package/dist/commands/pain-record.js.map +1 -1
  50. package/dist/commands/pain-retry.d.ts +4 -0
  51. package/dist/commands/pain-retry.d.ts.map +1 -1
  52. package/dist/commands/pain-retry.js +327 -32
  53. package/dist/commands/pain-retry.js.map +1 -1
  54. package/dist/commands/proven-channel-baseline.d.ts.map +1 -1
  55. package/dist/commands/proven-channel-baseline.js +4 -2
  56. package/dist/commands/proven-channel-baseline.js.map +1 -1
  57. package/dist/commands/runtime-activation.d.ts +30 -0
  58. package/dist/commands/runtime-activation.d.ts.map +1 -1
  59. package/dist/commands/runtime-activation.js +567 -11
  60. package/dist/commands/runtime-activation.js.map +1 -1
  61. package/dist/commands/runtime-canary.d.ts.map +1 -1
  62. package/dist/commands/runtime-canary.js +32 -7
  63. package/dist/commands/runtime-canary.js.map +1 -1
  64. package/dist/commands/runtime-health-snapshot.d.ts.map +1 -1
  65. package/dist/commands/runtime-health-snapshot.js +4 -2
  66. package/dist/commands/runtime-health-snapshot.js.map +1 -1
  67. package/dist/commands/runtime-init.d.ts +43 -0
  68. package/dist/commands/runtime-init.d.ts.map +1 -0
  69. package/dist/commands/runtime-init.js +264 -0
  70. package/dist/commands/runtime-init.js.map +1 -0
  71. package/dist/commands/runtime-internalization-context-trace.d.ts +25 -0
  72. package/dist/commands/runtime-internalization-context-trace.d.ts.map +1 -0
  73. package/dist/commands/runtime-internalization-context-trace.js +374 -0
  74. package/dist/commands/runtime-internalization-context-trace.js.map +1 -0
  75. package/dist/commands/runtime-internalization-enqueue-successors.d.ts.map +1 -1
  76. package/dist/commands/runtime-internalization-enqueue-successors.js +3 -1
  77. package/dist/commands/runtime-internalization-enqueue-successors.js.map +1 -1
  78. package/dist/commands/runtime-internalization-integrity.d.ts.map +1 -1
  79. package/dist/commands/runtime-internalization-integrity.js +4 -2
  80. package/dist/commands/runtime-internalization-integrity.js.map +1 -1
  81. package/dist/commands/runtime-internalization-run-once.d.ts.map +1 -1
  82. package/dist/commands/runtime-internalization-run-once.js +20 -5
  83. package/dist/commands/runtime-internalization-run-once.js.map +1 -1
  84. package/dist/commands/runtime-internalization-run-rulehost.d.ts +1 -0
  85. package/dist/commands/runtime-internalization-run-rulehost.d.ts.map +1 -1
  86. package/dist/commands/runtime-internalization-run-rulehost.js +149 -6
  87. package/dist/commands/runtime-internalization-run-rulehost.js.map +1 -1
  88. package/dist/commands/runtime-uat.d.ts.map +1 -1
  89. package/dist/commands/runtime-uat.guard.test.js +13 -15
  90. package/dist/commands/runtime-uat.guard.test.js.map +1 -1
  91. package/dist/commands/runtime-uat.js +4 -3
  92. package/dist/commands/runtime-uat.js.map +1 -1
  93. package/dist/config-reader.js +1 -1
  94. package/dist/config-reader.js.map +1 -1
  95. package/dist/index.js +54 -78
  96. package/dist/index.js.map +1 -1
  97. package/dist/services/__tests__/evaluator-runner-deps.test.d.ts +2 -0
  98. package/dist/services/__tests__/evaluator-runner-deps.test.d.ts.map +1 -0
  99. package/dist/services/__tests__/evaluator-runner-deps.test.js +304 -0
  100. package/dist/services/__tests__/evaluator-runner-deps.test.js.map +1 -0
  101. package/dist/services/__tests__/rulehost-readiness.test.js.map +1 -1
  102. package/dist/services/__tests__/runtime-adapter-resolver.test.js.map +1 -1
  103. package/dist/services/config-doctor.d.ts.map +1 -1
  104. package/dist/services/config-doctor.js +9 -2
  105. package/dist/services/config-doctor.js.map +1 -1
  106. package/dist/services/console-launcher.d.ts +6 -0
  107. package/dist/services/console-launcher.d.ts.map +1 -1
  108. package/dist/services/console-launcher.js.map +1 -1
  109. package/dist/services/pain-flood-simulation-runner.d.ts.map +1 -1
  110. package/dist/services/pain-flood-simulation-runner.js +9 -0
  111. package/dist/services/pain-flood-simulation-runner.js.map +1 -1
  112. package/dist/services/pd-config-loader.js +2 -2
  113. package/dist/services/pd-config-loader.js.map +1 -1
  114. package/dist/services/proven-channel-baseline-runner.d.ts.map +1 -1
  115. package/dist/services/proven-channel-baseline-runner.js +10 -2
  116. package/dist/services/proven-channel-baseline-runner.js.map +1 -1
  117. package/dist/services/quality-scorecard/data-extractor.js.map +1 -1
  118. package/dist/services/resolve-runtime-from-pd-config.js.map +1 -1
  119. package/dist/services/rulehost-pipeline-runner.d.ts +77 -1
  120. package/dist/services/rulehost-pipeline-runner.d.ts.map +1 -1
  121. package/dist/services/rulehost-pipeline-runner.js +111 -7
  122. package/dist/services/rulehost-pipeline-runner.js.map +1 -1
  123. package/dist/services/rulehost-readiness.js.map +1 -1
  124. package/dist/services/runtime-adapter-resolver.d.ts +1 -0
  125. package/dist/services/runtime-adapter-resolver.d.ts.map +1 -1
  126. package/dist/services/runtime-adapter-resolver.js +3 -0
  127. package/dist/services/runtime-adapter-resolver.js.map +1 -1
  128. package/dist/services/synthetic-baseline-runner.d.ts.map +1 -1
  129. package/dist/services/synthetic-baseline-runner.js +11 -0
  130. package/dist/services/synthetic-baseline-runner.js.map +1 -1
  131. package/dist/utils/production-workspace-guard.d.ts +4 -4
  132. package/dist/utils/production-workspace-guard.d.ts.map +1 -1
  133. package/dist/utils/production-workspace-guard.js +19 -16
  134. package/dist/utils/production-workspace-guard.js.map +1 -1
  135. package/dist/utils/production-workspace-guard.test.js +54 -19
  136. package/dist/utils/production-workspace-guard.test.js.map +1 -1
  137. package/package.json +8 -5
  138. package/src/commands/__tests__/intent-flag-wiring.test.ts +88 -3
  139. package/src/commands/__tests__/pain-retry-maxTokens-flag.test.ts +73 -0
  140. package/src/commands/__tests__/rulecode-flag-wiring.test.ts +31 -24
  141. package/src/commands/__tests__/run-rulehost-flag-wiring.test.ts +12 -0
  142. package/src/commands/admission-gate.ts +30 -0
  143. package/src/commands/candidate.ts +74 -6
  144. package/src/commands/console.ts +41 -0
  145. package/src/commands/demo-story-a.ts +4 -2
  146. package/src/commands/diagnose.ts +158 -10
  147. package/src/commands/errors-list.ts +440 -0
  148. package/src/commands/health-codex.ts +249 -0
  149. package/src/commands/health.ts +60 -0
  150. package/src/commands/intent.ts +98 -29
  151. package/src/commands/pain-evidence.ts +6 -0
  152. package/src/commands/pain-record.ts +21 -0
  153. package/src/commands/pain-retry.ts +353 -35
  154. package/src/commands/proven-channel-baseline.ts +4 -2
  155. package/src/commands/runtime-activation.ts +657 -12
  156. package/src/commands/runtime-canary.ts +31 -5
  157. package/src/commands/runtime-health-snapshot.ts +4 -2
  158. package/src/commands/runtime-init.ts +305 -0
  159. package/src/commands/runtime-internalization-context-trace.ts +445 -0
  160. package/src/commands/runtime-internalization-enqueue-successors.ts +3 -1
  161. package/src/commands/runtime-internalization-integrity.ts +4 -2
  162. package/src/commands/runtime-internalization-run-once.ts +20 -5
  163. package/src/commands/runtime-internalization-run-rulehost.ts +159 -6
  164. package/src/commands/runtime-uat.guard.test.ts +14 -16
  165. package/src/commands/runtime-uat.ts +4 -3
  166. package/src/config-reader.ts +1 -1
  167. package/src/index.ts +69 -78
  168. package/src/services/__tests__/evaluator-runner-deps.test.ts +341 -0
  169. package/src/services/config-doctor.ts +9 -2
  170. package/src/services/console-launcher.ts +6 -0
  171. package/src/services/pain-flood-simulation-runner.ts +9 -0
  172. package/src/services/pd-config-loader.ts +2 -2
  173. package/src/services/proven-channel-baseline-runner.ts +10 -3
  174. package/src/services/rulehost-pipeline-runner.ts +157 -6
  175. package/src/services/runtime-adapter-resolver.ts +4 -0
  176. package/src/services/synthetic-baseline-runner.ts +11 -0
  177. package/src/utils/production-workspace-guard.test.ts +62 -20
  178. package/src/utils/production-workspace-guard.ts +19 -16
  179. package/tests/bdd/cli-contract.steps.ts +343 -0
  180. package/tests/bdd/context-trace.steps.ts +229 -0
  181. package/tests/bdd/support/gherkin-loader.ts +147 -0
  182. package/tests/bdd/support/repo-root.ts +62 -0
  183. package/tests/bdd/support/vitest-bdd.ts +179 -0
  184. package/tests/commands/admission-gate-coverage.test.ts +79 -0
  185. package/tests/commands/candidate-audit-repair.test.ts +77 -0
  186. package/tests/commands/candidate-intake.test.ts +155 -10
  187. package/tests/commands/candidate-internalization-backfill.test.ts +30 -0
  188. package/tests/commands/cli-help-snapshot.test.ts +15 -1
  189. package/tests/commands/console-open.test.ts +229 -32
  190. package/tests/commands/diagnose.test.ts +619 -14
  191. package/tests/commands/errors-list.test.ts +678 -0
  192. package/tests/commands/health-codex.test.ts +243 -0
  193. package/tests/commands/health-host-wiring.test.ts +76 -0
  194. package/tests/commands/intent.test.ts +4 -4
  195. package/tests/commands/pain-record.test.ts +80 -0
  196. package/tests/commands/pain-retry.test.ts +94 -3
  197. package/tests/commands/run-rulehost-handler.test.ts +133 -0
  198. package/tests/commands/runtime-activation-approve-flag-wiring.test.ts +227 -0
  199. package/tests/commands/runtime-activation-deactivate-flag-wiring.test.ts +167 -0
  200. package/tests/commands/runtime-activation-dispatch-flag-wiring.test.ts +262 -0
  201. package/tests/commands/runtime-activation-list-flag-wiring.test.ts +193 -0
  202. package/tests/commands/runtime-activation-promote-flag-wiring.test.ts +222 -0
  203. package/tests/commands/runtime-activation.test.ts +1090 -5
  204. package/tests/commands/runtime-canary.test.ts +50 -0
  205. package/tests/commands/runtime-features.test.ts +2 -0
  206. package/tests/commands/runtime-init-empty-workspace.test.ts +234 -0
  207. package/tests/commands/runtime-init.test.ts +346 -0
  208. package/tests/commands/runtime-internalization-context-trace.test.ts +110 -0
  209. package/tests/commands/runtime-internalization.test.ts +2 -2
  210. package/tests/config-reader.test.ts +6 -5
  211. package/tests/e2e/cross-package-acceptance.test.ts +55 -13
  212. package/tests/services/mainline-snapshot-assembler.test.ts +6 -3
  213. package/tests/services/resolve-runtime-from-pd-config.test.ts +2 -0
  214. package/tests/services/rulehost-pipeline-runner.test.ts +1 -1
  215. package/vitest.config.ts +1 -1
@@ -0,0 +1,678 @@
1
+ /**
2
+ * Task 14: pd errors list — CLI unit + parser-wiring tests.
3
+ *
4
+ * Coverage:
5
+ * - cli-7-test-wiring: command registration + option parsing via the real
6
+ * Commander tree (registerErrorsListCommand).
7
+ * - cli-1-strict-json: --json stdout is exactly one parseable JSON object.
8
+ * - cli-2-exit-stops: failure paths set process.exitCode=1 and return.
9
+ * - cli-6-output-next-action: empty result includes `nextAction` field.
10
+ * - rc-1/rc-2/rc-4/rc-5: worker-status.json parsed as unknown, validated
11
+ * with type guards (no `as` casts in test code either).
12
+ *
13
+ * SqliteConnection / SqliteTaskStore are mocked — their contracts are tested
14
+ * in principles-core. fs is mocked for state.db / worker-status.json checks.
15
+ */
16
+ import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
17
+ import { Command } from 'commander';
18
+ import * as path from 'path';
19
+
20
+ // ── Mocks ────────────────────────────────────────────────────────────────────
21
+
22
+ const mockListFailedTasks = vi.fn();
23
+ const mockClose = vi.fn();
24
+
25
+ vi.mock('../../src/resolve-workspace.js', () => ({
26
+ resolveWorkspaceDir: vi.fn().mockReturnValue('/fake/workspace'),
27
+ }));
28
+
29
+ vi.mock('@principles/core', () => ({
30
+ SqliteConnection: vi.fn().mockImplementation(function () {
31
+ return { close: mockClose };
32
+ }),
33
+ SqliteTaskStore: vi.fn().mockImplementation(function () {
34
+ return { listFailedTasks: mockListFailedTasks };
35
+ }),
36
+ }));
37
+
38
+ // In-memory mock fs: tests configure which paths "exist" and what content
39
+ // each file returns from readFileSync. existsSync falls back to false.
40
+ const mockFiles = new Map<string, string>();
41
+ vi.mock('fs', () => ({
42
+ existsSync: vi.fn((p: unknown) => {
43
+ const key = typeof p === 'string' ? path.normalize(p) : '';
44
+ return mockFiles.has(key);
45
+ }),
46
+ readFileSync: vi.fn((p: unknown) => {
47
+ const key = typeof p === 'string' ? path.normalize(p) : '';
48
+ if (!mockFiles.has(key)) {
49
+ // rc-2: no `as` cast — use Object.assign to attach `code` to the Error.
50
+ throw Object.assign(new Error(`ENOENT: no such file or directory, open '${key}'`), {
51
+ code: 'ENOENT',
52
+ });
53
+ }
54
+ return mockFiles.get(key);
55
+ }),
56
+ mkdirSync: vi.fn(),
57
+ }));
58
+
59
+ import { handleErrorsList, registerErrorsListCommand } from '../../src/commands/errors-list.js';
60
+
61
+ // ── Helpers ──────────────────────────────────────────────────────────────────
62
+
63
+ const WS = '/fake/workspace';
64
+ // Mirror the handler's path resolution so mock fs paths match exactly.
65
+ // `path.resolve('/fake/workspace')` on Windows yields `D:\fake\workspace`,
66
+ // so the test must use the same resolved path when seeding mockFiles.
67
+ const WS_RESOLVED = path.resolve(WS);
68
+ const STATE_DIR = path.join(WS_RESOLVED, '.pd');
69
+ const STATE_DB = path.join(STATE_DIR, 'state.db');
70
+ const WORKER_STATUS = path.join(STATE_DIR, 'worker-status.json');
71
+
72
+ function setFile(p: string, content: string): void {
73
+ mockFiles.set(path.normalize(p), content);
74
+ }
75
+
76
+ function clearFiles(): void {
77
+ mockFiles.clear();
78
+ }
79
+
80
+ function setStateDbExists(): void {
81
+ // Touch state.db with empty content — existsSync only checks key presence.
82
+ setFile(STATE_DB, '');
83
+ }
84
+
85
+ function setWorkerStatus(content: string): void {
86
+ setFile(WORKER_STATUS, content);
87
+ }
88
+
89
+ function failedTaskSummary(overrides: Partial<Record<string, unknown>> = {}): Record<string, unknown> {
90
+ return {
91
+ taskId: 'task_001',
92
+ taskKind: 'diagnostician',
93
+ painId: 'pain_001',
94
+ status: 'failed',
95
+ lastError: 'runtime_unavailable',
96
+ attemptCount: 3,
97
+ createdAt: '2026-07-01T00:00:00.000Z',
98
+ lastAttemptAt: '2026-07-04T12:00:00.000Z',
99
+ ...overrides,
100
+ };
101
+ }
102
+
103
+ function workerErrorObject(overrides: Partial<Record<string, unknown>> = {}): Record<string, unknown> {
104
+ return {
105
+ at: '2026-07-04T12:00:00.000Z',
106
+ kind: 'principle_update_failed',
107
+ principleId: 'principle_001',
108
+ error: 'SQLite UNIQUE constraint failed',
109
+ ...overrides,
110
+ };
111
+ }
112
+
113
+ // ── Parser-level tests (cli-7-test-wiring) ─────────────────────────────────
114
+
115
+ type ActionOptions = Record<string, unknown>;
116
+ interface CapturedAction {
117
+ opts: ActionOptions | null;
118
+ }
119
+
120
+ function freshProgram(): Command {
121
+ const program = new Command();
122
+ program.name('pd').exitOverride();
123
+ return program;
124
+ }
125
+
126
+ /**
127
+ * rc-2: type guard instead of `as` cast. Narrows `unknown` to a plain
128
+ * options record after Commander dispatch, excluding Commander instances.
129
+ */
130
+ function isPlainOptions(value: unknown): value is ActionOptions {
131
+ return value !== null && typeof value === 'object' && !(value instanceof Command);
132
+ }
133
+
134
+ function captureActionInto(state: CapturedAction): (...args: unknown[]) => void {
135
+ return function (...args: unknown[]): void {
136
+ let optsArg: unknown = null;
137
+ for (let i = args.length - 1; i >= 0; i--) {
138
+ const arg = args[i];
139
+ if (isPlainOptions(arg)) {
140
+ optsArg = arg;
141
+ break;
142
+ }
143
+ }
144
+ state.opts = isPlainOptions(optsArg) ? optsArg : {};
145
+ };
146
+ }
147
+
148
+ function requireCmd(cmd: Command | undefined, name: string): Command {
149
+ if (cmd === undefined) {
150
+ throw new Error(`Command '${name}' not found in tree`);
151
+ }
152
+ return cmd;
153
+ }
154
+
155
+ describe('pd errors list — command registration (cli-7-test-wiring)', () => {
156
+ it('registers "errors" command group with "list" subcommand', () => {
157
+ const program = freshProgram();
158
+ registerErrorsListCommand(program);
159
+ const errorsCmd = requireCmd(program.commands.find((c) => c.name() === 'errors'), 'errors');
160
+ const subNames = errorsCmd.commands.map((c) => c.name());
161
+ expect(subNames).toContain('list');
162
+ });
163
+
164
+ it('errors command group is hidden from --help (operator diagnostic)', () => {
165
+ const program = freshProgram();
166
+ registerErrorsListCommand(program);
167
+ const errorsCmd = requireCmd(program.commands.find((c) => c.name() === 'errors'), 'errors');
168
+ // Commander v12: hidden commands have `_hidden === true` (internal field,
169
+ // but stable across v12.x). Equivalent to `errorsCmd.hidden()` in some
170
+ // Commander versions — using the field directly avoids API drift.
171
+ expect((errorsCmd as unknown as { _hidden: boolean })._hidden).toBe(true);
172
+ });
173
+
174
+ it('list subcommand has --workspace, --json, --kind, --since, --limit options', () => {
175
+ const program = freshProgram();
176
+ registerErrorsListCommand(program);
177
+ const errorsCmd = requireCmd(program.commands.find((c) => c.name() === 'errors'), 'errors');
178
+ const listCmd = requireCmd(errorsCmd.commands.find((c) => c.name() === 'list'), 'list');
179
+
180
+ expect(listCmd.options.find((o) => o.long === '--workspace')).toBeDefined();
181
+ expect(listCmd.options.find((o) => o.long === '--workspace')?.short).toBe('-w');
182
+ expect(listCmd.options.find((o) => o.long === '--json')).toBeDefined();
183
+ expect(listCmd.options.find((o) => o.long === '--kind')).toBeDefined();
184
+ expect(listCmd.options.find((o) => o.long === '--since')).toBeDefined();
185
+ expect(listCmd.options.find((o) => o.long === '--limit')).toBeDefined();
186
+ });
187
+
188
+ it('parses --json --kind --since --limit flags correctly (cli-7)', async () => {
189
+ const program = freshProgram();
190
+ registerErrorsListCommand(program);
191
+ const errorsCmd = requireCmd(program.commands.find((c) => c.name() === 'errors'), 'errors');
192
+ const listCmd = requireCmd(errorsCmd.commands.find((c) => c.name() === 'list'), 'list');
193
+
194
+ const captured: CapturedAction = { opts: null };
195
+ // Replace the production action with a capture so we can assert parser output
196
+ // without invoking the real handler (which would touch mocked fs/core).
197
+ listCmd.action(captureActionInto(captured));
198
+
199
+ await program.parseAsync([
200
+ 'node',
201
+ 'pd',
202
+ 'errors',
203
+ 'list',
204
+ '--json',
205
+ '--kind',
206
+ 'diag_router',
207
+ '--since',
208
+ '24',
209
+ '--limit',
210
+ '10',
211
+ '--workspace',
212
+ WS,
213
+ ]);
214
+
215
+ expect(captured.opts).not.toBeNull();
216
+ expect(captured.opts?.json).toBe(true);
217
+ expect(captured.opts?.kind).toBe('diag_router');
218
+ expect(captured.opts?.since).toBe(24);
219
+ expect(captured.opts?.limit).toBe(10);
220
+ expect(captured.opts?.workspace).toBe(WS);
221
+ });
222
+
223
+ it('--since and --limit are parsed as integers (not strings)', async () => {
224
+ const program = freshProgram();
225
+ registerErrorsListCommand(program);
226
+ const errorsCmd = requireCmd(program.commands.find((c) => c.name() === 'errors'), 'errors');
227
+ const listCmd = requireCmd(errorsCmd.commands.find((c) => c.name() === 'list'), 'list');
228
+
229
+ const captured: CapturedAction = { opts: null };
230
+ listCmd.action(captureActionInto(captured));
231
+
232
+ await program.parseAsync([
233
+ 'node',
234
+ 'pd',
235
+ 'errors',
236
+ 'list',
237
+ '--since',
238
+ '48',
239
+ '--limit',
240
+ '100',
241
+ ]);
242
+
243
+ expect(typeof captured.opts?.since).toBe('number');
244
+ expect(captured.opts?.since).toBe(48);
245
+ expect(typeof captured.opts?.limit).toBe('number');
246
+ expect(captured.opts?.limit).toBe(100);
247
+ });
248
+ });
249
+
250
+ // ── Handler tests ───────────────────────────────────────────────────────────
251
+
252
+ describe('handleErrorsList — handler behavior', () => {
253
+ let consoleLogSpy: ReturnType<typeof vi.spyOn>;
254
+ let stderrWriteSpy: ReturnType<typeof vi.spyOn>;
255
+
256
+ beforeEach(() => {
257
+ vi.clearAllMocks();
258
+ consoleLogSpy = vi.spyOn(console, 'log').mockImplementation(() => {});
259
+ stderrWriteSpy = vi.spyOn(process.stderr, 'write').mockImplementation(() => true);
260
+ clearFiles();
261
+ mockListFailedTasks.mockReset();
262
+ mockClose.mockReset();
263
+ });
264
+
265
+ afterEach(() => {
266
+ consoleLogSpy.mockRestore();
267
+ stderrWriteSpy.mockRestore();
268
+ process.exitCode = 0;
269
+ });
270
+
271
+ // ── Empty result (cli-6-output-next-action) ──────────────────────────────
272
+
273
+ it('empty result --json: outputs single JSON object with nextAction (cli-1, cli-6)', async () => {
274
+ setStateDbExists();
275
+ mockListFailedTasks.mockResolvedValue([]);
276
+
277
+ await handleErrorsList({ workspace: WS, json: true });
278
+
279
+ expect(consoleLogSpy).toHaveBeenCalledTimes(1);
280
+ const parsed = JSON.parse(consoleLogSpy.mock.calls[0][0]);
281
+ expect(parsed.tasks).toEqual([]);
282
+ expect(parsed.workerErrors).toEqual([]);
283
+ expect(parsed.total).toBe(0);
284
+ expect(parsed.nextAction).toBe('No errors found. PD pipeline is healthy.');
285
+ // worker-status.json missing → workerStatusMissing=true
286
+ expect(parsed.workerStatusMissing).toBe(true);
287
+ expect(parsed.workerStatusPath).toContain('worker-status.json');
288
+ // cli-2-exit-stops: success path does NOT set exitCode to failure (1).
289
+ // We assert "not 1" rather than "toBe(0)" because vitest may reset
290
+ // process.exitCode to undefined between tests; the contract under test
291
+ // is "handler must not mark failure", not "handler must set 0".
292
+ expect(process.exitCode).not.toBe(1);
293
+ });
294
+
295
+ it('empty result text: human-readable output contains health message', async () => {
296
+ setStateDbExists();
297
+ mockListFailedTasks.mockResolvedValue([]);
298
+
299
+ await handleErrorsList({ workspace: WS, json: false });
300
+
301
+ const text = consoleLogSpy.mock.calls.map((c) => c.join(' ')).join('\n');
302
+ expect(text).toContain('No errors found. PD pipeline is healthy.');
303
+ expect(text).toContain('total: 0');
304
+ });
305
+
306
+ // ── With failed tasks ────────────────────────────────────────────────────
307
+
308
+ it('--json with failed tasks: outputs tasks array (cli-1-strict-json single object)', async () => {
309
+ setStateDbExists();
310
+ const task = failedTaskSummary();
311
+ mockListFailedTasks.mockResolvedValue([task]);
312
+
313
+ await handleErrorsList({ workspace: WS, json: true });
314
+
315
+ expect(mockListFailedTasks).toHaveBeenCalledWith({
316
+ kind: undefined,
317
+ since: undefined,
318
+ limit: 50, // default
319
+ });
320
+ const parsed = JSON.parse(consoleLogSpy.mock.calls[0][0]);
321
+ expect(parsed.tasks).toHaveLength(1);
322
+ expect(parsed.tasks[0].taskId).toBe('task_001');
323
+ expect(parsed.tasks[0].taskKind).toBe('diagnostician');
324
+ expect(parsed.tasks[0].status).toBe('failed');
325
+ expect(parsed.total).toBe(1);
326
+ // nextAction should NOT be present when there are errors
327
+ expect(parsed.nextAction).toBeUndefined();
328
+ });
329
+
330
+ it('--kind filter is passed through to listFailedTasks', async () => {
331
+ setStateDbExists();
332
+ mockListFailedTasks.mockResolvedValue([]);
333
+
334
+ await handleErrorsList({ workspace: WS, json: true, kind: 'dreamer' });
335
+
336
+ expect(mockListFailedTasks).toHaveBeenCalledWith({
337
+ kind: 'dreamer',
338
+ since: undefined,
339
+ limit: 50,
340
+ });
341
+ });
342
+
343
+ it('--since filter is converted from hours to Unix-ms timestamp', async () => {
344
+ setStateDbExists();
345
+ mockListFailedTasks.mockResolvedValue([]);
346
+ const before = Date.now();
347
+
348
+ await handleErrorsList({ workspace: WS, json: true, since: 24 });
349
+
350
+ const after = Date.now();
351
+ expect(mockListFailedTasks).toHaveBeenCalledTimes(1);
352
+ const call = mockListFailedTasks.mock.calls[0][0];
353
+ expect(typeof call.since).toBe('number');
354
+ // 24 hours ago, ±a few ms of slack for test execution time
355
+ const expectedSince = before - 24 * 3600 * 1000;
356
+ expect(call.since).toBeGreaterThanOrEqual(expectedSince - 1000);
357
+ expect(call.since).toBeLessThanOrEqual(after - 24 * 3600 * 1000 + 1000);
358
+ });
359
+
360
+ it('--limit is clamped to MAX_LIMIT (200)', async () => {
361
+ setStateDbExists();
362
+ mockListFailedTasks.mockResolvedValue([]);
363
+
364
+ await handleErrorsList({ workspace: WS, json: true, limit: 500 });
365
+
366
+ expect(mockListFailedTasks).toHaveBeenCalledWith({
367
+ kind: undefined,
368
+ since: undefined,
369
+ limit: 200,
370
+ });
371
+ });
372
+
373
+ it('--limit default is 50 when not specified', async () => {
374
+ setStateDbExists();
375
+ mockListFailedTasks.mockResolvedValue([]);
376
+
377
+ await handleErrorsList({ workspace: WS, json: true });
378
+
379
+ expect(mockListFailedTasks).toHaveBeenCalledWith({
380
+ kind: undefined,
381
+ since: undefined,
382
+ limit: 50,
383
+ });
384
+ });
385
+
386
+ // ── worker-status.json parsing (rc-1, rc-4, rc-5) ───────────────────────
387
+
388
+ it('worker-status.json with object-form errors: parsed and normalized', async () => {
389
+ setStateDbExists();
390
+ setWorkerStatus(
391
+ JSON.stringify({
392
+ timestamp: '2026-07-04T12:00:00.000Z',
393
+ errors: [workerErrorObject()],
394
+ }),
395
+ );
396
+ mockListFailedTasks.mockResolvedValue([]);
397
+
398
+ await handleErrorsList({ workspace: WS, json: true });
399
+
400
+ const parsed = JSON.parse(consoleLogSpy.mock.calls[0][0]);
401
+ expect(parsed.workerErrors).toHaveLength(1);
402
+ expect(parsed.workerErrors[0].at).toBe('2026-07-04T12:00:00.000Z');
403
+ expect(parsed.workerErrors[0].kind).toBe('principle_update_failed');
404
+ expect(parsed.workerErrors[0].principleId).toBe('principle_001');
405
+ expect(parsed.workerErrors[0].error).toBe('SQLite UNIQUE constraint failed');
406
+ expect(parsed.workerErrors[0].rawForm).toBe('object');
407
+ expect(parsed.workerStatusMissing).toBeUndefined();
408
+ expect(parsed.total).toBe(1); // 0 tasks + 1 workerError
409
+ });
410
+
411
+ it('worker-status.json with string-form errors: normalized with rawForm=string', async () => {
412
+ setStateDbExists();
413
+ setWorkerStatus(
414
+ JSON.stringify({
415
+ errors: ['legacy error string'],
416
+ }),
417
+ );
418
+ mockListFailedTasks.mockResolvedValue([]);
419
+
420
+ await handleErrorsList({ workspace: WS, json: true });
421
+
422
+ const parsed = JSON.parse(consoleLogSpy.mock.calls[0][0]);
423
+ expect(parsed.workerErrors).toHaveLength(1);
424
+ expect(parsed.workerErrors[0].error).toBe('legacy error string');
425
+ expect(parsed.workerErrors[0].rawForm).toBe('string');
426
+ expect(parsed.workerErrors[0].at).toBeNull();
427
+ expect(parsed.workerErrors[0].kind).toBeNull();
428
+ expect(parsed.workerErrors[0].principleId).toBeNull();
429
+ });
430
+
431
+ it('worker-status.json with mixed object + string errors: both normalized', async () => {
432
+ setStateDbExists();
433
+ setWorkerStatus(
434
+ JSON.stringify({
435
+ errors: [
436
+ workerErrorObject({ error: 'first error' }),
437
+ 'second error string',
438
+ workerErrorObject({ kind: 'retry_count_update_failed', error: 'third error' }),
439
+ ],
440
+ }),
441
+ );
442
+ mockListFailedTasks.mockResolvedValue([]);
443
+
444
+ await handleErrorsList({ workspace: WS, json: true });
445
+
446
+ const parsed = JSON.parse(consoleLogSpy.mock.calls[0][0]);
447
+ expect(parsed.workerErrors).toHaveLength(3);
448
+ expect(parsed.workerErrors[0].rawForm).toBe('object');
449
+ expect(parsed.workerErrors[1].rawForm).toBe('string');
450
+ expect(parsed.workerErrors[2].rawForm).toBe('object');
451
+ expect(parsed.workerErrors[2].kind).toBe('retry_count_update_failed');
452
+ });
453
+
454
+ it('worker-status.json with malformed entries: skipped with workerStatusWarning (rc-9)', async () => {
455
+ setStateDbExists();
456
+ setWorkerStatus(
457
+ JSON.stringify({
458
+ errors: [
459
+ workerErrorObject({ error: 'good entry' }),
460
+ 42, // malformed — number, not string or object
461
+ null, // malformed — null
462
+ 'string entry',
463
+ ],
464
+ }),
465
+ );
466
+ mockListFailedTasks.mockResolvedValue([]);
467
+
468
+ await handleErrorsList({ workspace: WS, json: true });
469
+
470
+ const parsed = JSON.parse(consoleLogSpy.mock.calls[0][0]);
471
+ expect(parsed.workerErrors).toHaveLength(2); // only good + string
472
+ expect(parsed.workerStatusWarning).toContain('Skipped 2 malformed');
473
+ expect(parsed.workerErrors[0].error).toBe('good entry');
474
+ expect(parsed.workerErrors[1].error).toBe('string entry');
475
+ });
476
+
477
+ it('worker-status.json missing errors field: treated as empty, no warning', async () => {
478
+ setStateDbExists();
479
+ setWorkerStatus(JSON.stringify({ timestamp: '2026-07-04T12:00:00.000Z' }));
480
+ mockListFailedTasks.mockResolvedValue([]);
481
+
482
+ await handleErrorsList({ workspace: WS, json: true });
483
+
484
+ const parsed = JSON.parse(consoleLogSpy.mock.calls[0][0]);
485
+ expect(parsed.workerErrors).toEqual([]);
486
+ expect(parsed.workerStatusWarning).toBeUndefined();
487
+ expect(parsed.workerStatusMissing).toBeUndefined();
488
+ });
489
+
490
+ it('worker-status.json with non-array errors field: warning surfaced (rc-9)', async () => {
491
+ setStateDbExists();
492
+ setWorkerStatus(JSON.stringify({ errors: 'not an array' }));
493
+ mockListFailedTasks.mockResolvedValue([]);
494
+
495
+ await handleErrorsList({ workspace: WS, json: true });
496
+
497
+ const parsed = JSON.parse(consoleLogSpy.mock.calls[0][0]);
498
+ expect(parsed.workerErrors).toEqual([]);
499
+ expect(parsed.workerStatusWarning).toContain('not an array');
500
+ });
501
+
502
+ it('worker-status.json unparseable JSON: warning surfaced (rc-9)', async () => {
503
+ setStateDbExists();
504
+ setWorkerStatus('{ this is not valid json');
505
+ mockListFailedTasks.mockResolvedValue([]);
506
+
507
+ await handleErrorsList({ workspace: WS, json: true });
508
+
509
+ const parsed = JSON.parse(consoleLogSpy.mock.calls[0][0]);
510
+ expect(parsed.workerErrors).toEqual([]);
511
+ expect(parsed.workerStatusWarning).toContain('Failed to parse');
512
+ });
513
+
514
+ it('worker-status.json root is array (not object): warning surfaced', async () => {
515
+ setStateDbExists();
516
+ setWorkerStatus(JSON.stringify(['not', 'an', 'object']));
517
+ mockListFailedTasks.mockResolvedValue([]);
518
+
519
+ await handleErrorsList({ workspace: WS, json: true });
520
+
521
+ const parsed = JSON.parse(consoleLogSpy.mock.calls[0][0]);
522
+ expect(parsed.workerErrors).toEqual([]);
523
+ expect(parsed.workerStatusWarning).toContain('not a JSON object');
524
+ });
525
+
526
+ // ── Failure paths (cli-2-exit-stops) ────────────────────────────────────
527
+
528
+ it('state.db missing: stderr error + exitCode=1 + return (cli-2)', async () => {
529
+ // Do NOT call setStateDbExists — state.db missing
530
+ mockListFailedTasks.mockResolvedValue([]);
531
+
532
+ await handleErrorsList({ workspace: WS, json: false });
533
+
534
+ // listFailedTasks should NOT be called (early return)
535
+ expect(mockListFailedTasks).not.toHaveBeenCalled();
536
+ expect(process.exitCode).toBe(1);
537
+ const stderrText = stderrWriteSpy.mock.calls.map((c) => String(c[0])).join('');
538
+ expect(stderrText).toContain('state.db not found');
539
+ });
540
+
541
+ it('state.db missing --json: JSON error envelope on stderr (cli-1 + cli-2)', async () => {
542
+ // state.db missing
543
+ mockListFailedTasks.mockResolvedValue([]);
544
+
545
+ await handleErrorsList({ workspace: WS, json: true });
546
+
547
+ expect(process.exitCode).toBe(1);
548
+ // cli-1: stdout must stay clean (no console.log calls)
549
+ expect(consoleLogSpy).not.toHaveBeenCalled();
550
+ // stderr carries the JSON error envelope
551
+ const stderrText = stderrWriteSpy.mock.calls.map((c) => String(c[0])).join('');
552
+ const errEnvelope = JSON.parse(stderrText.trim());
553
+ expect(errEnvelope.ok).toBe(false);
554
+ expect(errEnvelope.reason).toContain('state.db not found');
555
+ expect(errEnvelope.nextAction).toBeDefined();
556
+ });
557
+
558
+ it('invalid --limit (negative): stderr error + exitCode=1 (cli-2)', async () => {
559
+ setStateDbExists();
560
+ mockListFailedTasks.mockResolvedValue([]);
561
+
562
+ await handleErrorsList({ workspace: WS, json: false, limit: -5 });
563
+
564
+ expect(mockListFailedTasks).not.toHaveBeenCalled();
565
+ expect(process.exitCode).toBe(1);
566
+ const stderrText = stderrWriteSpy.mock.calls.map((c) => String(c[0])).join('');
567
+ expect(stderrText).toContain('--limit must be a positive integer');
568
+ });
569
+
570
+ it('invalid --since (negative): stderr error + exitCode=1 (cli-2)', async () => {
571
+ setStateDbExists();
572
+ mockListFailedTasks.mockResolvedValue([]);
573
+
574
+ await handleErrorsList({ workspace: WS, json: false, since: -1 });
575
+
576
+ expect(mockListFailedTasks).not.toHaveBeenCalled();
577
+ expect(process.exitCode).toBe(1);
578
+ const stderrText = stderrWriteSpy.mock.calls.map((c) => String(c[0])).join('');
579
+ expect(stderrText).toContain('--since must be a non-negative number');
580
+ });
581
+
582
+ it('listFailedTasks throws: stderr error + exitCode=1 + connection closed (cli-2)', async () => {
583
+ setStateDbExists();
584
+ mockListFailedTasks.mockRejectedValue(new Error('database is locked'));
585
+
586
+ await handleErrorsList({ workspace: WS, json: false });
587
+
588
+ expect(process.exitCode).toBe(1);
589
+ const stderrText = stderrWriteSpy.mock.calls.map((c) => String(c[0])).join('');
590
+ expect(stderrText).toContain('database is locked');
591
+ // connection.close() called in finally block
592
+ expect(mockClose).toHaveBeenCalled();
593
+ });
594
+
595
+ it('listFailedTasks throws --json: JSON error envelope on stderr (cli-1 + cli-2)', async () => {
596
+ setStateDbExists();
597
+ mockListFailedTasks.mockRejectedValue(new Error('database is locked'));
598
+
599
+ await handleErrorsList({ workspace: WS, json: true });
600
+
601
+ expect(process.exitCode).toBe(1);
602
+ expect(consoleLogSpy).not.toHaveBeenCalled();
603
+ const stderrText = stderrWriteSpy.mock.calls.map((c) => String(c[0])).join('');
604
+ const errEnvelope = JSON.parse(stderrText.trim());
605
+ expect(errEnvelope.ok).toBe(false);
606
+ expect(errEnvelope.reason).toContain('database is locked');
607
+ expect(errEnvelope.nextAction).toBeDefined();
608
+ expect(mockClose).toHaveBeenCalled();
609
+ });
610
+
611
+ // ── cli-1-strict-json: stdout is exactly one parseable JSON object ───────
612
+
613
+ it('--json stdout is exactly one parseable JSON object (cli-1-strict-json)', async () => {
614
+ setStateDbExists();
615
+ setWorkerStatus(
616
+ JSON.stringify({
617
+ errors: [workerErrorObject()],
618
+ }),
619
+ );
620
+ mockListFailedTasks.mockResolvedValue([failedTaskSummary()]);
621
+
622
+ await handleErrorsList({ workspace: WS, json: true });
623
+
624
+ // console.log called exactly once with a single string
625
+ expect(consoleLogSpy).toHaveBeenCalledTimes(1);
626
+ const raw = consoleLogSpy.mock.calls[0][0];
627
+ expect(typeof raw).toBe('string');
628
+ // Must parse without error (already asserted above, but be explicit)
629
+ expect(() => JSON.parse(raw)).not.toThrow();
630
+ // No trailing or leading non-JSON text
631
+ const parsed = JSON.parse(raw);
632
+ expect(parsed).toBeTypeOf('object');
633
+ expect(parsed).not.toBeNull();
634
+ expect(Array.isArray(parsed)).toBe(false);
635
+ });
636
+
637
+ // ── Text output smoke tests ──────────────────────────────────────────────
638
+
639
+ it('text output with errors: includes task and worker error sections', async () => {
640
+ setStateDbExists();
641
+ setWorkerStatus(
642
+ JSON.stringify({
643
+ errors: [workerErrorObject({ error: 'worker boom' })],
644
+ }),
645
+ );
646
+ mockListFailedTasks.mockResolvedValue([failedTaskSummary({ lastError: 'runtime_unavailable' })]);
647
+
648
+ await handleErrorsList({ workspace: WS, json: false });
649
+
650
+ const text = consoleLogSpy.mock.calls.map((c) => c.join(' ')).join('\n');
651
+ expect(text).toContain('Failed tasks:');
652
+ expect(text).toContain('task_001');
653
+ expect(text).toContain('runtime_unavailable');
654
+ expect(text).toContain('Worker errors:');
655
+ expect(text).toContain('worker boom');
656
+ expect(text).toContain('principle_update_failed');
657
+ expect(text).toContain('total: 2');
658
+ });
659
+
660
+ it('text output: worker-status.json missing is reported in workerStatus line', async () => {
661
+ setStateDbExists();
662
+ mockListFailedTasks.mockResolvedValue([]);
663
+
664
+ await handleErrorsList({ workspace: WS, json: false });
665
+
666
+ const text = consoleLogSpy.mock.calls.map((c) => c.join(' ')).join('\n');
667
+ expect(text).toContain('workerStatus: (missing');
668
+ });
669
+
670
+ it('connection.close() called on success path (resource cleanup)', async () => {
671
+ setStateDbExists();
672
+ mockListFailedTasks.mockResolvedValue([]);
673
+
674
+ await handleErrorsList({ workspace: WS, json: true });
675
+
676
+ expect(mockClose).toHaveBeenCalledTimes(1);
677
+ });
678
+ });