@principles/pd-cli 1.130.0 → 1.132.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.
@@ -0,0 +1,321 @@
1
+ /**
2
+ * PRI-466: pd intent — handler-level tests.
3
+ *
4
+ * Tests real handler behavior using temporary workspaces with .pd/config.yaml
5
+ * to control the intent_engineering flag. No mocks on resolveWorkspaceDir or
6
+ * loadPdConfig — full integration through the real code paths.
7
+ *
8
+ * ERR refs:
9
+ * - ERR-002: all degraded paths include reason + nextAction
10
+ * - ERR-009: missing file / flag-off surfaced explicitly
11
+ */
12
+
13
+ import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
14
+ import * as fs from 'node:fs';
15
+ import * as path from 'node:path';
16
+ import * as os from 'node:os';
17
+ import * as yaml from 'js-yaml';
18
+ import { handleIntentInit, handleIntentShow } from '../../src/commands/intent.js';
19
+
20
+ let workspaceDir: string;
21
+ let tmpDir: string;
22
+
23
+ beforeEach(() => {
24
+ vi.clearAllMocks();
25
+ tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'pd-intent-cli-test-'));
26
+ workspaceDir = path.join(tmpDir, 'workspace');
27
+ fs.mkdirSync(workspaceDir, { recursive: true });
28
+ fs.mkdirSync(path.join(workspaceDir, '.pd'), { recursive: true });
29
+ });
30
+
31
+ afterEach(() => {
32
+ fs.rmSync(tmpDir, { recursive: true, force: true });
33
+ });
34
+
35
+ function writeConfig(intentEnabled: boolean): void {
36
+ const config = {
37
+ version: 1,
38
+ features: {
39
+ intent_engineering: { category: 'quiet', enabled: intentEnabled },
40
+ },
41
+ runtimeProfiles: {
42
+ 'openclaw.default': { type: 'openclaw', source: 'default' },
43
+ },
44
+ internalAgents: {
45
+ defaultRuntime: 'openclaw.default',
46
+ agents: {
47
+ diagnostician: { enabled: true, runtimeProfile: 'openclaw.default' },
48
+ dreamer: { enabled: true },
49
+ scribe: { enabled: true },
50
+ },
51
+ },
52
+ ui: { diagnostics: { mode: 'simple' } },
53
+ };
54
+ fs.writeFileSync(
55
+ path.join(workspaceDir, '.pd', 'config.yaml'),
56
+ yaml.dump(config),
57
+ 'utf8',
58
+ );
59
+ }
60
+
61
+ function getIntentPath(): string {
62
+ return path.join(workspaceDir, '.principles', 'INTENT.md');
63
+ }
64
+
65
+ const VALID_INTENT = `# INTENT.md
66
+
67
+ ## 1. Why
68
+
69
+ This project validates pain from repeatedly correcting Agents.
70
+
71
+ ## 2. Desired Outcome
72
+
73
+ A new user understands PD within five minutes.
74
+
75
+ ## 3. Non-negotiables
76
+
77
+ - Do not make PD a heavy Agent platform.
78
+ - Do not increase Owner attention burden.
79
+
80
+ ## 4. Stop / Escalation
81
+
82
+ If a change expands PD into orchestration, stop and ask Owner.
83
+
84
+ ## 5. Current Strategic Focus
85
+
86
+ Validate the smallest loop: Pain to Principle to Delta.
87
+ `;
88
+
89
+ // ── handleIntentInit ─────────────────────────────────────────────────────────
90
+
91
+ describe('handleIntentInit', () => {
92
+ it('creates INTENT.md from template with --confirm', async () => {
93
+ await handleIntentInit({ workspace: workspaceDir, confirm: true, json: false });
94
+
95
+ const intentPath = getIntentPath();
96
+ expect(fs.existsSync(intentPath)).toBe(true);
97
+ const content = fs.readFileSync(intentPath, 'utf8');
98
+ expect(content).toContain('# INTENT.md');
99
+ expect(content).toContain('## 1. Why');
100
+ expect(content).toContain('## 5. Current Strategic Focus');
101
+ });
102
+
103
+ it('defaults to dry-run (does not write) when no --confirm', async () => {
104
+ const logSpy = vi.spyOn(console, 'log').mockImplementation(() => undefined);
105
+ await handleIntentInit({ workspace: workspaceDir, json: true });
106
+
107
+ expect(logSpy).toHaveBeenCalled();
108
+ const jsonOutput = JSON.parse(logSpy.mock.calls[0][0] as string);
109
+ expect(jsonOutput.status).toBe('dry_run');
110
+ expect(jsonOutput.path).toContain('INTENT.md');
111
+ expect(jsonOutput.reason).toBe('dry_run');
112
+ expect(jsonOutput.nextAction).toContain('--confirm');
113
+
114
+ // File must NOT be created
115
+ expect(fs.existsSync(getIntentPath())).toBe(false);
116
+
117
+ logSpy.mockRestore();
118
+ });
119
+
120
+ it('dry-run with --dry-run flag produces same dry-run output', async () => {
121
+ const logSpy = vi.spyOn(console, 'log').mockImplementation(() => undefined);
122
+ await handleIntentInit({ workspace: workspaceDir, dryRun: true, json: true });
123
+
124
+ const jsonOutput = JSON.parse(logSpy.mock.calls[0][0] as string);
125
+ expect(jsonOutput.status).toBe('dry_run');
126
+
127
+ expect(fs.existsSync(getIntentPath())).toBe(false);
128
+ logSpy.mockRestore();
129
+ });
130
+
131
+ it('rejects --dry-run and --confirm together (CLI Gate rule 4)', async () => {
132
+ const exitSpy = vi.spyOn(process, 'exit').mockImplementation(() => undefined as never);
133
+ await handleIntentInit({ workspace: workspaceDir, dryRun: true, confirm: true, json: true });
134
+
135
+ expect(exitSpy).not.toHaveBeenCalled();
136
+ expect(process.exitCode).toBe(1);
137
+ // File must NOT be created
138
+ expect(fs.existsSync(getIntentPath())).toBe(false);
139
+
140
+ process.exitCode = undefined;
141
+ exitSpy.mockRestore();
142
+ });
143
+
144
+ it('skips when file exists and --force is not set', async () => {
145
+ // Pre-create the file
146
+ fs.mkdirSync(path.dirname(getIntentPath()), { recursive: true });
147
+ fs.writeFileSync(getIntentPath(), 'existing content', 'utf8');
148
+
149
+ const exitSpy = vi.spyOn(process, 'exit').mockImplementation(() => undefined as never);
150
+ await handleIntentInit({ workspace: workspaceDir, force: false, confirm: true, json: false });
151
+ expect(exitSpy).not.toHaveBeenCalled();
152
+ expect(process.exitCode).toBe(1);
153
+
154
+ // File should NOT be overwritten
155
+ const content = fs.readFileSync(getIntentPath(), 'utf8');
156
+ expect(content).toBe('existing content');
157
+
158
+ process.exitCode = undefined;
159
+ exitSpy.mockRestore();
160
+ });
161
+
162
+ it('overwrites when --force and --confirm are set', async () => {
163
+ fs.mkdirSync(path.dirname(getIntentPath()), { recursive: true });
164
+ fs.writeFileSync(getIntentPath(), 'existing content', 'utf8');
165
+
166
+ await handleIntentInit({ workspace: workspaceDir, force: true, confirm: true, json: false });
167
+
168
+ const content = fs.readFileSync(getIntentPath(), 'utf8');
169
+ expect(content).toContain('# INTENT.md');
170
+ expect(content).not.toContain('existing content');
171
+ });
172
+
173
+ it('outputs JSON when --json is set with --confirm', async () => {
174
+ const logSpy = vi.spyOn(console, 'log').mockImplementation(() => undefined);
175
+ await handleIntentInit({ workspace: workspaceDir, confirm: true, json: true });
176
+
177
+ expect(logSpy).toHaveBeenCalled();
178
+ const jsonOutput = JSON.parse(logSpy.mock.calls[0][0] as string);
179
+ expect(jsonOutput.status).toBe('ok');
180
+ expect(jsonOutput.path).toContain('INTENT.md');
181
+ expect(jsonOutput.overwritten).toBe(false);
182
+
183
+ logSpy.mockRestore();
184
+ });
185
+
186
+ it('creates .principles directory if it does not exist', async () => {
187
+ await handleIntentInit({ workspace: workspaceDir, confirm: true, json: false });
188
+
189
+ const dir = path.join(workspaceDir, '.principles');
190
+ expect(fs.existsSync(dir)).toBe(true);
191
+ expect(fs.existsSync(getIntentPath())).toBe(true);
192
+ });
193
+
194
+ it('emits structured read_error JSON when workspace path is invalid (CLI Gate rule 6)', async () => {
195
+ // resolveWorkspaceDir throws on paths with null bytes or other invalid chars.
196
+ // The error must be caught and emitted as a structured IntentInitOutput,
197
+ // not an uncaught stack trace.
198
+ const logSpy = vi.spyOn(console, 'log').mockImplementation(() => undefined);
199
+ process.exitCode = undefined;
200
+ await handleIntentInit({ workspace: 'invalid\0path', confirm: true, json: true });
201
+
202
+ expect(process.exitCode).toBe(1);
203
+ const jsonOutput = JSON.parse(logSpy.mock.calls[0][0] as string) as Record<string, unknown>;
204
+ expect(jsonOutput.status).toBe('read_error');
205
+ expect(jsonOutput.reason).toBeDefined();
206
+ expect(jsonOutput.nextAction).toBeDefined();
207
+ // Must NOT include the ad-hoc `ok` field that the old code emitted
208
+ expect(jsonOutput.ok).toBeUndefined();
209
+
210
+ process.exitCode = undefined;
211
+ logSpy.mockRestore();
212
+ });
213
+ });
214
+
215
+ // ── handleIntentShow ─────────────────────────────────────────────────────────
216
+
217
+ describe('handleIntentShow', () => {
218
+ it('returns flag_disabled when intent_engineering is off', async () => {
219
+ writeConfig(false);
220
+ const logSpy = vi.spyOn(console, 'log').mockImplementation(() => undefined);
221
+
222
+ await handleIntentShow({ workspace: workspaceDir, json: true });
223
+
224
+ const jsonOutput = JSON.parse(logSpy.mock.calls[0][0] as string);
225
+ expect(jsonOutput.status).toBe('flag_disabled');
226
+ expect(jsonOutput.flagEnabled).toBe(false);
227
+ expect(jsonOutput.reason).toBe('flag_disabled');
228
+ expect(jsonOutput.nextAction).toBeDefined();
229
+
230
+ logSpy.mockRestore();
231
+ });
232
+
233
+ it('returns not_found when INTENT.md does not exist', async () => {
234
+ writeConfig(true);
235
+ const logSpy = vi.spyOn(console, 'log').mockImplementation(() => undefined);
236
+
237
+ await handleIntentShow({ workspace: workspaceDir, json: true });
238
+
239
+ const jsonOutput = JSON.parse(logSpy.mock.calls[0][0] as string);
240
+ expect(jsonOutput.status).toBe('not_found');
241
+ expect(jsonOutput.found).toBe(false);
242
+ expect(jsonOutput.nextAction).toContain('pd intent init');
243
+
244
+ logSpy.mockRestore();
245
+ });
246
+
247
+ it('returns ok with sections and hash for valid INTENT.md', async () => {
248
+ writeConfig(true);
249
+ fs.mkdirSync(path.dirname(getIntentPath()), { recursive: true });
250
+ fs.writeFileSync(getIntentPath(), VALID_INTENT, 'utf8');
251
+
252
+ const logSpy = vi.spyOn(console, 'log').mockImplementation(() => undefined);
253
+
254
+ await handleIntentShow({ workspace: workspaceDir, json: true });
255
+
256
+ const jsonOutput = JSON.parse(logSpy.mock.calls[0][0] as string);
257
+ expect(jsonOutput.status).toBe('ok');
258
+ expect(jsonOutput.found).toBe(true);
259
+ expect(jsonOutput.flagEnabled).toBe(true);
260
+ expect(jsonOutput.contentHash).toMatch(/^sha256:/);
261
+ expect(jsonOutput.lastEditedAt).toBeDefined();
262
+ expect(jsonOutput.sections).toBeDefined();
263
+ expect(jsonOutput.sections.why).toContain('correcting Agents');
264
+ expect(jsonOutput.warnings).toEqual([]);
265
+
266
+ logSpy.mockRestore();
267
+ });
268
+
269
+ it('returns oversized for file > 32KB', async () => {
270
+ writeConfig(true);
271
+ fs.mkdirSync(path.dirname(getIntentPath()), { recursive: true });
272
+ const big = '# INTENT.md\n\n## 1. Why\n\n' + 'x'.repeat(33 * 1024) + '\n';
273
+ fs.writeFileSync(getIntentPath(), big, 'utf8');
274
+
275
+ const logSpy = vi.spyOn(console, 'log').mockImplementation(() => undefined);
276
+
277
+ await handleIntentShow({ workspace: workspaceDir, json: true });
278
+
279
+ const jsonOutput = JSON.parse(logSpy.mock.calls[0][0] as string);
280
+ expect(jsonOutput.status).toBe('oversized');
281
+ expect(jsonOutput.found).toBe(true);
282
+ expect(jsonOutput.nextAction).toContain('bytes');
283
+
284
+ logSpy.mockRestore();
285
+ });
286
+
287
+ it('emits warnings for partial INTENT.md', async () => {
288
+ writeConfig(true);
289
+ fs.mkdirSync(path.dirname(getIntentPath()), { recursive: true });
290
+ fs.writeFileSync(getIntentPath(), '# INTENT.md\n\n## 1. Why\n\nJust the why section.\n', 'utf8');
291
+
292
+ const logSpy = vi.spyOn(console, 'log').mockImplementation(() => undefined);
293
+
294
+ await handleIntentShow({ workspace: workspaceDir, json: true });
295
+
296
+ const jsonOutput = JSON.parse(logSpy.mock.calls[0][0] as string);
297
+ expect(jsonOutput.status).toBe('ok');
298
+ expect(jsonOutput.warnings.length).toBe(4);
299
+ expect(jsonOutput.warnings.every((w: { code: string }) => w.code === 'missing_section')).toBe(true);
300
+
301
+ logSpy.mockRestore();
302
+ });
303
+
304
+ it('outputs text when --json is not set', async () => {
305
+ writeConfig(true);
306
+ fs.mkdirSync(path.dirname(getIntentPath()), { recursive: true });
307
+ fs.writeFileSync(getIntentPath(), VALID_INTENT, 'utf8');
308
+
309
+ const logSpy = vi.spyOn(console, 'log').mockImplementation(() => undefined);
310
+
311
+ await handleIntentShow({ workspace: workspaceDir, json: false });
312
+
313
+ const textOutput = logSpy.mock.calls[0][0] as string;
314
+ expect(textOutput).toContain('INTENT.md');
315
+ expect(textOutput).toContain('Content hash:');
316
+ expect(textOutput).toContain('Last edited:');
317
+ expect(textOutput).toContain('## 1. Why');
318
+
319
+ logSpy.mockRestore();
320
+ });
321
+ });