@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,388 @@
1
+ /**
2
+ * pd intent — Owner-authored INTENT.md management (PRI-466).
3
+ *
4
+ * Subcommands:
5
+ * - init : create .principles/INTENT.md from the canonical template
6
+ * - show : display a read-only summary of INTENT.md (sections, hash, warnings)
7
+ *
8
+ * `init` is not gated by the intent_engineering flag — the Owner can
9
+ * initialise the intent doc at any time. `show` IS gated: flag-off returns
10
+ * a structured `flag_disabled` result without touching the filesystem,
11
+ * matching the Console backend contract.
12
+ *
13
+ * JSON mode is strict: --json outputs exactly one parseable JSON object on
14
+ * stdout (CLI Operator Gate rule 1). Failure paths include structured
15
+ * reason + nextAction (rule 6).
16
+ *
17
+ * ERR refs:
18
+ * - ERR-001 (no any): all types explicit
19
+ * - ERR-005 (no as bypass): no type casts on untrusted data
20
+ * - ERR-002 (graceful degradation with reason): all failure paths include
21
+ * reason + nextAction
22
+ * - ERR-009 (fail loud): missing file / flag-off surfaced explicitly
23
+ */
24
+
25
+ import * as fs from 'node:fs';
26
+ import * as path from 'node:path';
27
+ import type { Command } from 'commander';
28
+ import {
29
+ INTENT_MAX_BYTES,
30
+ INTENT_DOC_TEMPLATE,
31
+ parseIntentDocSections,
32
+ computeIntentContentHash,
33
+ validateIntentDocSections,
34
+ isFeatureEnabled,
35
+ } from '@principles/core/runtime-v2';
36
+ import type { IntentDocSections, IntentDocWarning } from '@principles/core/runtime-v2';
37
+ import { resolveWorkspaceDir } from '../resolve-workspace.js';
38
+ import { loadPdConfig, computeFlagsFromLoadResult } from '../services/pd-config-loader.js';
39
+ import { emitResult } from '../services/cli-output.js';
40
+
41
+ // ── Constants ────────────────────────────────────────────────────────────────
42
+
43
+ const INTENT_DIR = '.principles';
44
+ const INTENT_FILENAME = 'INTENT.md';
45
+
46
+ // ── Output types ─────────────────────────────────────────────────────────────
47
+
48
+ export interface IntentInitOutput {
49
+ status: 'ok' | 'skipped' | 'dry_run' | 'read_error';
50
+ path: string;
51
+ overwritten: boolean;
52
+ reason?: string;
53
+ nextAction?: string;
54
+ }
55
+
56
+ export interface IntentShowOutput {
57
+ status: 'ok' | 'flag_disabled' | 'not_found' | 'oversized' | 'read_error';
58
+ flagEnabled: boolean;
59
+ found: boolean;
60
+ path?: string;
61
+ contentHash?: string;
62
+ lastEditedAt?: string;
63
+ sections?: Record<string, string>;
64
+ warnings: IntentDocWarning[];
65
+ reason?: string;
66
+ nextAction?: string;
67
+ }
68
+
69
+ // ── Helpers ──────────────────────────────────────────────────────────────────
70
+
71
+ function getIntentFilePath(workspaceDir: string): string {
72
+ return path.join(workspaceDir, INTENT_DIR, INTENT_FILENAME);
73
+ }
74
+
75
+ function sectionsToRecord(sections: IntentDocSections): Record<string, string> {
76
+ const record: Record<string, string> = {};
77
+ if (sections.why !== undefined) { record.why = sections.why; }
78
+ if (sections.desiredOutcome !== undefined) { record.desiredOutcome = sections.desiredOutcome; }
79
+ if (sections.nonNegotiables !== undefined) { record.nonNegotiables = sections.nonNegotiables; }
80
+ if (sections.stopEscalation !== undefined) { record.stopEscalation = sections.stopEscalation; }
81
+ if (sections.currentStrategicFocus !== undefined) { record.currentStrategicFocus = sections.currentStrategicFocus; }
82
+ return record;
83
+ }
84
+
85
+ function formatIntentShowText(o: IntentShowOutput): string {
86
+ const lines: string[] = [];
87
+ lines.push(`INTENT.md — ${o.path}`);
88
+ lines.push(`Content hash: ${o.contentHash}`);
89
+ lines.push(`Last edited: ${o.lastEditedAt}`);
90
+ lines.push('');
91
+ if (o.sections) {
92
+ if (o.sections.why) { lines.push('## 1. Why'); lines.push(o.sections.why); lines.push(''); }
93
+ if (o.sections.desiredOutcome) { lines.push('## 2. Desired Outcome'); lines.push(o.sections.desiredOutcome); lines.push(''); }
94
+ if (o.sections.nonNegotiables) { lines.push('## 3. Non-negotiables'); lines.push(o.sections.nonNegotiables); lines.push(''); }
95
+ if (o.sections.stopEscalation) { lines.push('## 4. Stop / Escalation'); lines.push(o.sections.stopEscalation); lines.push(''); }
96
+ if (o.sections.currentStrategicFocus) { lines.push('## 5. Current Strategic Focus'); lines.push(o.sections.currentStrategicFocus); lines.push(''); }
97
+ }
98
+ if (o.warnings.length > 0) {
99
+ lines.push('Warnings:');
100
+ for (const w of o.warnings) {
101
+ lines.push(` [${w.code}] ${w.message}`);
102
+ }
103
+ } else {
104
+ lines.push('No warnings.');
105
+ }
106
+ return lines.join('\n');
107
+ }
108
+
109
+ // ── Handlers ─────────────────────────────────────────────────────────────────
110
+
111
+ export interface IntentInitOptions {
112
+ workspace?: string;
113
+ force?: boolean;
114
+ json?: boolean;
115
+ dryRun?: boolean;
116
+ confirm?: boolean;
117
+ }
118
+
119
+ export async function handleIntentInit(opts: IntentInitOptions): Promise<void> {
120
+ // CLI Gate rule 4: --dry-run and --confirm must be mutually exclusive.
121
+ if (opts.dryRun && opts.confirm) {
122
+ const output: IntentInitOutput = {
123
+ status: 'skipped',
124
+ path: '',
125
+ overwritten: false,
126
+ reason: 'flag_conflict',
127
+ nextAction: 'Use either --dry-run or --confirm, not both.',
128
+ };
129
+ emitResult(output, {
130
+ json: opts.json ?? false,
131
+ formatText: (o) => `Error: ${o.reason}\n→ ${o.nextAction}`,
132
+ });
133
+ process.exitCode = 1;
134
+ return;
135
+ }
136
+
137
+ // CLI Gate rule 6: workspace resolution inside try/catch so failures emit
138
+ // structured JSON with reason + nextAction instead of an uncaught stack trace.
139
+ let workspaceDir: string;
140
+ let filePath: string;
141
+ let dir: string;
142
+ try {
143
+ workspaceDir = resolveWorkspaceDir(opts.workspace);
144
+ filePath = getIntentFilePath(workspaceDir);
145
+ dir = path.dirname(filePath);
146
+ } catch (err) {
147
+ const reason = err instanceof Error ? err.message : String(err);
148
+ const output: IntentInitOutput = {
149
+ status: 'read_error',
150
+ path: '',
151
+ overwritten: false,
152
+ reason,
153
+ nextAction: 'Provide a valid --workspace <path> argument.',
154
+ };
155
+ emitResult(output, {
156
+ json: opts.json ?? false,
157
+ formatText: (o) => `Error: ${o.reason}\n→ ${o.nextAction}`,
158
+ });
159
+ process.exitCode = 1;
160
+ return;
161
+ }
162
+
163
+ // CLI Gate rule 4: state-mutating command defaults to dry-run unless --confirm.
164
+ const isDryRun = opts.dryRun === true || opts.confirm !== true;
165
+
166
+ try {
167
+ if (fs.existsSync(filePath) && !opts.force) {
168
+ const output: IntentInitOutput = {
169
+ status: 'skipped',
170
+ path: filePath,
171
+ overwritten: false,
172
+ reason: 'file_exists',
173
+ nextAction: `Use --force to overwrite: pd intent init --force --confirm --workspace "${workspaceDir}"`,
174
+ };
175
+ emitResult(output, {
176
+ json: opts.json ?? false,
177
+ formatText: (o) => `INTENT.md already exists at ${o.path}\n→ ${o.nextAction}`,
178
+ });
179
+ process.exitCode = 1;
180
+ return;
181
+ }
182
+
183
+ if (isDryRun) {
184
+ const output: IntentInitOutput = {
185
+ status: 'dry_run',
186
+ path: filePath,
187
+ overwritten: opts.force === true,
188
+ reason: 'dry_run',
189
+ nextAction: `Confirm write: pd intent init --confirm${opts.force ? ' --force' : ''} --workspace "${workspaceDir}"`,
190
+ };
191
+ emitResult(output, {
192
+ json: opts.json ?? false,
193
+ formatText: (o) => `[dry-run] Would create INTENT.md at ${o.path}${o.overwritten ? ' (overwritten)' : ''}\n→ ${o.nextAction}`,
194
+ });
195
+ return;
196
+ }
197
+
198
+ fs.mkdirSync(dir, { recursive: true });
199
+ fs.writeFileSync(filePath, INTENT_DOC_TEMPLATE, 'utf8');
200
+
201
+ const output: IntentInitOutput = {
202
+ status: 'ok',
203
+ path: filePath,
204
+ overwritten: opts.force === true,
205
+ };
206
+ emitResult(output, {
207
+ json: opts.json ?? false,
208
+ formatText: (o) => `Created INTENT.md at ${o.path}${o.overwritten ? ' (overwritten)' : ''}\nNext: edit the file to declare your project intent, then run "pd intent show".`,
209
+ });
210
+ } catch (err) {
211
+ const reason = err instanceof Error ? err.message : String(err);
212
+ // CLI Gate rule 1: route through emitResult for consistent IntentInitOutput shape.
213
+ const output: IntentInitOutput = {
214
+ status: 'read_error',
215
+ path: filePath,
216
+ overwritten: false,
217
+ reason,
218
+ nextAction: `Check filesystem permissions for ${filePath}`,
219
+ };
220
+ emitResult(output, {
221
+ json: opts.json ?? false,
222
+ formatText: (o) => `Error: ${o.reason}\n→ ${o.nextAction}`,
223
+ });
224
+ process.exitCode = 1;
225
+ }
226
+ }
227
+
228
+ export interface IntentShowOptions {
229
+ workspace?: string;
230
+ json?: boolean;
231
+ }
232
+
233
+ export async function handleIntentShow(opts: IntentShowOptions): Promise<void> {
234
+ // CLI Gate rule 6: workspace resolution inside try/catch for structured errors.
235
+ let workspaceDir: string;
236
+ try {
237
+ workspaceDir = resolveWorkspaceDir(opts.workspace);
238
+ } catch (err) {
239
+ const reason = err instanceof Error ? err.message : String(err);
240
+ const output: IntentShowOutput = {
241
+ status: 'read_error',
242
+ flagEnabled: false,
243
+ found: false,
244
+ warnings: [],
245
+ reason,
246
+ nextAction: 'Provide a valid --workspace <path> argument.',
247
+ };
248
+ emitResult(output, {
249
+ json: opts.json ?? false,
250
+ formatText: (o) => `Error: ${o.reason}\n→ ${o.nextAction}`,
251
+ });
252
+ process.exitCode = 1;
253
+ return;
254
+ }
255
+
256
+ // Flag check — flag-off short-circuits without fs access
257
+ const configResult = loadPdConfig(workspaceDir);
258
+ const flagsResult = computeFlagsFromLoadResult(configResult);
259
+ const flagEnabled = isFeatureEnabled(flagsResult, 'intent_engineering');
260
+
261
+ if (!flagEnabled) {
262
+ const output: IntentShowOutput = {
263
+ status: 'flag_disabled',
264
+ flagEnabled: false,
265
+ found: false,
266
+ warnings: [],
267
+ reason: 'flag_disabled',
268
+ nextAction: 'Enable the intent_engineering feature flag in .pd/config.yaml to read INTENT.md.',
269
+ };
270
+ emitResult(output, {
271
+ json: opts.json ?? false,
272
+ formatText: (o) => `Intent Engineering is disabled (flag off).\n→ ${o.nextAction}`,
273
+ });
274
+ return;
275
+ }
276
+
277
+ const filePath = getIntentFilePath(workspaceDir);
278
+
279
+ try {
280
+ if (!fs.existsSync(filePath)) {
281
+ const output: IntentShowOutput = {
282
+ status: 'not_found',
283
+ flagEnabled: true,
284
+ found: false,
285
+ warnings: [],
286
+ reason: 'not_found',
287
+ nextAction: `Create INTENT.md: pd intent init --workspace "${workspaceDir}"`,
288
+ };
289
+ emitResult(output, {
290
+ json: opts.json ?? false,
291
+ formatText: (o) => `INTENT.md not found.\n→ ${o.nextAction}`,
292
+ });
293
+ return;
294
+ }
295
+
296
+ const stat = fs.statSync(filePath);
297
+ if (stat.size > INTENT_MAX_BYTES) {
298
+ const output: IntentShowOutput = {
299
+ status: 'oversized',
300
+ flagEnabled: true,
301
+ found: true,
302
+ warnings: [],
303
+ reason: 'oversized',
304
+ nextAction: `INTENT.md exceeds ${INTENT_MAX_BYTES} bytes (${stat.size} bytes). Reduce content.`,
305
+ };
306
+ emitResult(output, {
307
+ json: opts.json ?? false,
308
+ formatText: (o) => `INTENT.md is too large.\n→ ${o.nextAction}`,
309
+ });
310
+ return;
311
+ }
312
+
313
+ const raw = fs.readFileSync(filePath, 'utf8');
314
+ const sections = parseIntentDocSections(raw);
315
+ const warnings = validateIntentDocSections(sections);
316
+ const contentHash = computeIntentContentHash(raw);
317
+
318
+ const output: IntentShowOutput = {
319
+ status: 'ok',
320
+ flagEnabled: true,
321
+ found: true,
322
+ path: filePath,
323
+ contentHash,
324
+ lastEditedAt: stat.mtime.toISOString(),
325
+ sections: sectionsToRecord(sections),
326
+ warnings,
327
+ };
328
+ emitResult(output, {
329
+ json: opts.json ?? false,
330
+ formatText: (o) => formatIntentShowText(o),
331
+ });
332
+ } catch (err) {
333
+ const reason = err instanceof Error ? err.message : String(err);
334
+ const output: IntentShowOutput = {
335
+ status: 'read_error',
336
+ flagEnabled: true,
337
+ found: false,
338
+ warnings: [],
339
+ reason,
340
+ nextAction: `Check filesystem permissions for ${filePath}`,
341
+ };
342
+ emitResult(output, {
343
+ json: opts.json ?? false,
344
+ formatText: (o) => `Error reading INTENT.md: ${o.reason}\n→ ${o.nextAction}`,
345
+ });
346
+ process.exitCode = 1;
347
+ }
348
+ }
349
+
350
+ // ── Command registration ─────────────────────────────────────────────────────
351
+
352
+ export function registerIntentCommand(parentCmd: Command): Command {
353
+ const intentCmd = parentCmd
354
+ .command('intent')
355
+ .description('Owner-authored INTENT.md management (init, show)');
356
+
357
+ intentCmd
358
+ .command('init')
359
+ .description('Create .principles/INTENT.md from the canonical template')
360
+ .option('-w, --workspace <path>', 'Workspace directory')
361
+ .option('--force', 'Overwrite existing INTENT.md')
362
+ .option('--dry-run', 'Show what would happen without writing (default)')
363
+ .option('--confirm', 'Actually write the file (required to create INTENT.md)')
364
+ .option('--json', 'Output raw JSON')
365
+ .action(async (opts) => {
366
+ await handleIntentInit({
367
+ workspace: opts.workspace,
368
+ force: opts.force === true,
369
+ json: opts.json === true,
370
+ dryRun: opts.dryRun === true,
371
+ confirm: opts.confirm === true,
372
+ });
373
+ });
374
+
375
+ intentCmd
376
+ .command('show')
377
+ .description('Display a read-only summary of INTENT.md (sections, hash, warnings)')
378
+ .option('-w, --workspace <path>', 'Workspace directory')
379
+ .option('--json', 'Output raw JSON')
380
+ .action(async (opts) => {
381
+ await handleIntentShow({
382
+ workspace: opts.workspace,
383
+ json: opts.json === true,
384
+ });
385
+ });
386
+
387
+ return intentCmd;
388
+ }
package/src/index.ts CHANGED
@@ -53,6 +53,7 @@ import { handleRuntimeFeaturesStatus } from './commands/runtime-features.js';
53
53
  import { handleConfigDoctor } from './commands/config-doctor.js';
54
54
  import { registerMvpCommands } from './commands/mvp-smoke.js';
55
55
  import { registerRulecodeCommand } from './commands/rulecode.js';
56
+ import { registerIntentCommand } from './commands/intent.js';
56
57
 
57
58
  import { createRequire } from 'module';
58
59
  const require = createRequire(import.meta.url);
@@ -971,6 +972,11 @@ registerMvpCommands(program);
971
972
 
972
973
  registerRulecodeCommand(program);
973
974
 
975
+ // ─── Intent Engineering (PRI-466) ───────────────────────────────────────────
976
+ // Owner-authored INTENT.md management: init (create), show (read-only summary).
977
+
978
+ registerIntentCommand(program);
979
+
974
980
  const consoleCmd = program
975
981
  .command('console')
976
982
  .description('Start the pd-console web UI for principle review (default: fallback launcher)')
@@ -326,6 +326,14 @@ export async function runStoryADemo(opts: DemoStoryARunnerOptions): Promise<Stor
326
326
  // Persist artifacts to real workspace DB
327
327
  const principleRecord = makePrincipleArtifactRecord(runId);
328
328
  const ruleRecord = makeRuleArtifactRecord(runId, principleRecord);
329
+ // P1-3: Seed parent task record for FK validation. Both demo artifacts share
330
+ // sourceTaskId = `task-demo-${runId}`; createArtifact rejects it unless the
331
+ // task exists in the tasks table (ERR-009/ERR-010/ERR-002).
332
+ const demoTaskId = principleRecord.sourceTaskId;
333
+ stateManager.connection.getDb().prepare(
334
+ "INSERT OR IGNORE INTO tasks (task_id, task_kind, status, created_at, updated_at)" +
335
+ " VALUES (?, 'diagnosis', 'pending', ?, ?)",
336
+ ).run(demoTaskId, principleRecord.createdAt, principleRecord.createdAt);
329
337
  await stateManager.piArtifactStore.createArtifact(principleRecord);
330
338
  await stateManager.piArtifactStore.createArtifact(ruleRecord);
331
339