@principles/pd-cli 1.138.0 → 1.139.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,404 @@
1
+ /**
2
+ * PRI-555 phase 1 — artifact-repair dry-run planner tests.
3
+ *
4
+ * Coverage:
5
+ * - Rule 1 (unique legacy-key artifact with identical UUID+channel → remap, high)
6
+ * - UUID match but DIFFERENT channel is NOT a Rule-1 candidate (no fuzzy match)
7
+ * - Rule 2 (succeeded run output_payload → reconstruct, medium)
8
+ * - Ambiguous legacy artifacts → needs_human_review
9
+ * - No artifact + no run payload → needs_human_review
10
+ * - Dependency not succeeded → needs_human_review
11
+ * - Malformed diagnostic_json → needs_human_review (fail loud, rc-3)
12
+ * - Already-resolvable dependency → needs_human_review (input_invalid has another cause)
13
+ * - Dry-run never mutates state.db (byte-identical before/after) and writes
14
+ * migration-plan.json (cli-5)
15
+ * - --json stdout is exactly one parseable JSON object (cli-1)
16
+ * - --confirm is refused with structured reason + nextAction (cli-4/cli-6)
17
+ * - --dry-run + --confirm conflict → exit 1
18
+ */
19
+ import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
20
+ import * as fs from 'fs';
21
+ import * as path from 'path';
22
+ import * as os from 'os';
23
+ import * as crypto from 'crypto';
24
+ import Database from 'better-sqlite3';
25
+ import { handleRuntimeArtifactRepair } from '../../src/commands/runtime-artifact-repair.js';
26
+
27
+ const UUID = '9e9081a2-3b4c-4d5e-8f90-aabbccddeeff';
28
+ // Current scribe naming: scribe- prefix, channel ×3
29
+ const DEP_SCRIBE_ID = `scribe-philosopher-dreamer-${UUID}-prompt-prompt-prompt`;
30
+ // Legacy variant of the SAME scribe task's key: identical role chain, channel repeated ×4
31
+ const LEGACY_SAME_ROLE_X4 = `scribe-philosopher-dreamer-${UUID}-prompt-prompt-prompt-prompt`;
32
+ // Downstream-stage artifact of the same chain (extra role prefix) — must NOT
33
+ // be re-keyed into the scribe slot (live-data trap found in the 2026-08-21 dry-run)
34
+ const DOWNSTREAM_ARTIFICER_KEY = `artificer-scribe-philosopher-dreamer-${UUID}-prompt-prompt-prompt-prompt`;
35
+ // Same role chain + UUID but a different channel — must NOT match
36
+ const LEGACY_OTHER_CHANNEL = `scribe-philosopher-dreamer-${UUID}-code_tool_hook-code_tool_hook-code_tool_hook-code_tool_hook`;
37
+ const FAILED_ARTIFICER_ID = `artificer-scribe-philosopher-dreamer-${UUID}-prompt-prompt-prompt`;
38
+
39
+ let workspaceDir: string;
40
+ let dbPath: string;
41
+ let outDir: string;
42
+ let planPath: string;
43
+
44
+ function diagJson(deps: string[]): string {
45
+ return JSON.stringify({
46
+ pi_metadata: {
47
+ dependencyTaskIds: deps,
48
+ channel: 'prompt',
49
+ timeoutMs: 300000,
50
+ inputArtifactRefs: [],
51
+ outputArtifactRefs: [],
52
+ },
53
+ });
54
+ }
55
+
56
+ interface TaskFixture {
57
+ taskId: string;
58
+ kind?: string;
59
+ status?: string;
60
+ lastError?: string | null;
61
+ diagnosticJson?: string | null;
62
+ }
63
+
64
+ function insertTasks(db: Database.Database, tasks: TaskFixture[]): void {
65
+ const now = new Date().toISOString();
66
+ const stmt = db.prepare(`
67
+ INSERT INTO tasks (task_id, task_kind, status, created_at, updated_at, last_error, diagnostic_json)
68
+ VALUES (?, ?, ?, ?, ?, ?, ?)
69
+ `);
70
+ for (const t of tasks) {
71
+ stmt.run(t.taskId, t.kind ?? 'artificer', t.status ?? 'failed', now, now, t.lastError ?? 'input_invalid', t.diagnosticJson ?? null);
72
+ }
73
+ }
74
+
75
+ function insertArtifact(db: Database.Database, artifactId: string, sourceTaskId: string): void {
76
+ const now = new Date().toISOString();
77
+ db.prepare(`
78
+ INSERT INTO pi_artifacts (artifact_id, artifact_kind, source_task_id, content_json, validation_status, created_at, updated_at)
79
+ VALUES (?, 'principle', ?, '{}', 'validated', ?, ?)
80
+ `).run(artifactId, sourceTaskId, now, now);
81
+ }
82
+
83
+ function insertSucceededRun(db: Database.Database, taskId: string, runId: string): void {
84
+ const now = new Date().toISOString();
85
+ const payload = JSON.stringify({ draftPrinciple: 'p' });
86
+ db.prepare(`
87
+ INSERT INTO runs (run_id, task_id, runtime_kind, execution_status, started_at, attempt_number, output_payload, created_at, updated_at)
88
+ VALUES (?, ?, ?, 'succeeded', ?, 1, ?, ?, ?)
89
+ `).run(runId, taskId, 'pi-ai', now, payload, now, now);
90
+ }
91
+
92
+ const DDL_STATEMENTS = [
93
+ `CREATE TABLE tasks (
94
+ task_id TEXT PRIMARY KEY, task_kind TEXT NOT NULL, status TEXT NOT NULL DEFAULT 'pending',
95
+ created_at TEXT NOT NULL, updated_at TEXT NOT NULL, lease_owner TEXT, lease_expires_at TEXT,
96
+ attempt_count INTEGER NOT NULL DEFAULT 0, max_attempts INTEGER NOT NULL DEFAULT 3,
97
+ last_error TEXT, input_ref TEXT, result_ref TEXT, diagnostic_json TEXT
98
+ )`,
99
+ `CREATE TABLE runs (
100
+ run_id TEXT PRIMARY KEY, task_id TEXT NOT NULL, runtime_kind TEXT NOT NULL,
101
+ execution_status TEXT NOT NULL DEFAULT 'queued', started_at TEXT NOT NULL, ended_at TEXT,
102
+ reason TEXT, output_ref TEXT, input_payload TEXT, output_payload TEXT, error_category TEXT,
103
+ attempt_number INTEGER NOT NULL DEFAULT 0, created_at TEXT NOT NULL, updated_at TEXT NOT NULL
104
+ )`,
105
+ `CREATE TABLE pi_artifacts (
106
+ artifact_id TEXT PRIMARY KEY, artifact_kind TEXT NOT NULL, source_task_id TEXT NOT NULL,
107
+ source_principle_id TEXT, source_rule_id TEXT, lineage_artifact_ids TEXT NOT NULL DEFAULT '[]',
108
+ validation_status TEXT NOT NULL DEFAULT 'pending', content_json TEXT NOT NULL,
109
+ created_at TEXT NOT NULL, updated_at TEXT NOT NULL
110
+ )`,
111
+ ];
112
+
113
+ function createWorkspaceDb(withSchema: (db: Database.Database) => void): void {
114
+ fs.mkdirSync(path.join(workspaceDir, '.pd'), { recursive: true });
115
+ const db = new Database(dbPath);
116
+ for (const ddl of DDL_STATEMENTS) {
117
+ db.prepare(ddl).run();
118
+ }
119
+ withSchema(db);
120
+ db.close();
121
+ }
122
+
123
+ function fileHash(p: string): string {
124
+ return crypto.createHash('sha256').update(fs.readFileSync(p)).digest('hex');
125
+ }
126
+
127
+ beforeEach(() => {
128
+ workspaceDir = fs.mkdtempSync(path.join(os.tmpdir(), 'pd-artifact-repair-'));
129
+ dbPath = path.join(workspaceDir, '.pd', 'state.db');
130
+ outDir = fs.mkdtempSync(path.join(os.tmpdir(), 'pd-artifact-repair-out-'));
131
+ planPath = path.join(outDir, 'migration-plan.json');
132
+ });
133
+
134
+ afterEach(() => {
135
+ vi.restoreAllMocks();
136
+ if (process.exitCode === 1) process.exitCode = 0;
137
+ for (const dir of [workspaceDir, outDir]) {
138
+ try { fs.rmSync(dir, { recursive: true, force: true }); } catch { /* best-effort */ }
139
+ }
140
+ });
141
+
142
+ function mockConsole(): { logs: string[]; errors: string[] } {
143
+ const logs: string[] = [];
144
+ const errors: string[] = [];
145
+ vi.spyOn(console, 'log').mockImplementation((...args: unknown[]) => {
146
+ logs.push(args.map(String).join(' '));
147
+ });
148
+ vi.spyOn(console, 'error').mockImplementation((...args: unknown[]) => {
149
+ errors.push(args.map(String).join(' '));
150
+ });
151
+ return { logs, errors };
152
+ }
153
+
154
+ /** Standard fixture: one failed artificer task + its June scribe dependency. */
155
+ function standardFixture(): void {
156
+ createWorkspaceDb((db) => {
157
+ insertTasks(db, [
158
+ { taskId: FAILED_ARTIFICER_ID, kind: 'artificer', status: 'failed', lastError: 'input_invalid', diagnosticJson: diagJson([DEP_SCRIBE_ID]) },
159
+ { taskId: DEP_SCRIBE_ID, kind: 'scribe', status: 'succeeded', lastError: null, diagnosticJson: diagJson([]) },
160
+ ]);
161
+ });
162
+ }
163
+
164
+ describe('artifact-repair dry-run — repair rules', () => {
165
+ it('Rule 1: unique legacy key with identical role-chain+UUID+channel → remap proposal (high confidence)', async () => {
166
+ standardFixture();
167
+ {
168
+ const db = new Database(dbPath);
169
+ insertArtifact(db, 'pi-art-old-1', LEGACY_SAME_ROLE_X4);
170
+ db.close();
171
+ }
172
+
173
+ const { logs } = mockConsole();
174
+ const before = fileHash(dbPath);
175
+ await handleRuntimeArtifactRepair({ workspace: workspaceDir, dryRun: true, out: planPath, json: true });
176
+ const after = fileHash(dbPath);
177
+
178
+ // cli-5 evidence: state.db byte-identical after a dry-run
179
+ expect(after).toBe(before);
180
+ // migration-plan.json written with the spec fields
181
+ expect(fs.existsSync(planPath)).toBe(true);
182
+ const plan = JSON.parse(fs.readFileSync(planPath, 'utf8'));
183
+ expect(plan.dryRun).toBe(true);
184
+ expect(plan.summary.rule1_remap).toBe(1);
185
+ expect(plan.entries).toHaveLength(1);
186
+ const entry = plan.entries[0];
187
+ expect(entry.failed_task_id).toBe(FAILED_ARTIFICER_ID);
188
+ expect(entry.dependency_task_id).toBe(DEP_SCRIBE_ID);
189
+ expect(entry.existing_artifact.source_task_id).toBe(LEGACY_SAME_ROLE_X4);
190
+ expect(entry.artifact_source).toBe('old_key_uuid_match');
191
+ expect(entry.repair_action).toBe('remap_source_task_id');
192
+ expect(entry.confidence).toBe('high');
193
+ expect(entry.proposal.old_source_task_id).toBe(LEGACY_SAME_ROLE_X4);
194
+ expect(entry.proposal.new_source_task_id).toBe(DEP_SCRIBE_ID);
195
+ // cli-1: stdout is exactly one parseable JSON object
196
+ expect(logs).toHaveLength(1);
197
+ const stdout = JSON.parse(logs[0]);
198
+ expect(stdout.ok).toBe(true);
199
+ expect(stdout.dryRun).toBe(true);
200
+ expect(stdout.summary.rule1_remap).toBe(1);
201
+ });
202
+
203
+ it('downstream-stage artifact (extra role prefix, same UUID+channel) is NOT a Rule-1 match', async () => {
204
+ // Live-data trap found in the 2026-08-21 production dry-run: the ×4
205
+ // `artificer-…` key is the June artificer task's OWN output, not the
206
+ // scribe's draft. Re-keying it into the scribe slot would feed a later
207
+ // stage's output backwards into an earlier slot.
208
+ standardFixture();
209
+ {
210
+ const db = new Database(dbPath);
211
+ insertArtifact(db, 'pi-art-downstream', DOWNSTREAM_ARTIFICER_KEY);
212
+ insertSucceededRun(db, DEP_SCRIBE_ID, 'run-scribe-1');
213
+ db.close();
214
+ }
215
+
216
+ mockConsole();
217
+ await handleRuntimeArtifactRepair({ workspace: workspaceDir, dryRun: true, out: planPath, json: true });
218
+ const plan = JSON.parse(fs.readFileSync(planPath, 'utf8'));
219
+
220
+ expect(plan.summary.rule1_remap).toBe(0);
221
+ expect(plan.summary.rule2_reconstruct).toBe(1);
222
+ expect(plan.entries[0].artifact_source).toBe('run_output_payload');
223
+ });
224
+
225
+ it('same role chain + UUID but different channel is NOT a Rule-1 match (no fuzzy matching)', async () => {
226
+ standardFixture();
227
+ {
228
+ const db = new Database(dbPath);
229
+ insertArtifact(db, 'pi-art-other-channel', LEGACY_OTHER_CHANNEL);
230
+ insertSucceededRun(db, DEP_SCRIBE_ID, 'run-scribe-1');
231
+ db.close();
232
+ }
233
+
234
+ mockConsole();
235
+ await handleRuntimeArtifactRepair({ workspace: workspaceDir, dryRun: true, out: planPath, json: true });
236
+ const plan = JSON.parse(fs.readFileSync(planPath, 'utf8'));
237
+
238
+ // Role chain matched but channel differs → falls through to Rule 2, never a remap
239
+ expect(plan.summary.rule1_remap).toBe(0);
240
+ expect(plan.summary.rule2_reconstruct).toBe(1);
241
+ expect(plan.entries[0].artifact_source).toBe('run_output_payload');
242
+ });
243
+
244
+ it('Rule 2: no artifact anywhere + succeeded run payload → reconstruct proposal (medium confidence)', async () => {
245
+ standardFixture();
246
+ {
247
+ const db = new Database(dbPath);
248
+ insertSucceededRun(db, DEP_SCRIBE_ID, 'run-scribe-1');
249
+ db.close();
250
+ }
251
+
252
+ mockConsole();
253
+ await handleRuntimeArtifactRepair({ workspace: workspaceDir, dryRun: true, out: planPath, json: true });
254
+ const plan = JSON.parse(fs.readFileSync(planPath, 'utf8'));
255
+
256
+ expect(plan.summary.rule2_reconstruct).toBe(1);
257
+ const entry = plan.entries[0];
258
+ expect(entry.repair_action).toBe('reconstruct_from_run_payload');
259
+ expect(entry.confidence).toBe('medium');
260
+ expect(entry.existing_artifact).toBeNull();
261
+ expect(entry.proposal.run_id).toBe('run-scribe-1');
262
+ expect(entry.proposal.new_source_task_id).toBe(DEP_SCRIBE_ID);
263
+ expect(entry.proposal.artifact_kind).toBe('principle');
264
+ expect(entry.proposal.validation_status).toBe('pending');
265
+ });
266
+
267
+ it('ambiguous legacy artifacts (2 candidates, same UUID+channel) → needs_human_review', async () => {
268
+ standardFixture();
269
+ {
270
+ const db = new Database(dbPath);
271
+ insertArtifact(db, 'pi-art-old-a', LEGACY_SAME_ROLE_X4);
272
+ insertArtifact(db, 'pi-art-old-b', `scribe-philosopher-dreamer-${UUID}-prompt-prompt`);
273
+ db.close();
274
+ }
275
+
276
+ mockConsole();
277
+ await handleRuntimeArtifactRepair({ workspace: workspaceDir, dryRun: true, out: planPath, json: true });
278
+ const plan = JSON.parse(fs.readFileSync(planPath, 'utf8'));
279
+
280
+ expect(plan.summary.needs_human_review).toBe(1);
281
+ expect(plan.entries[0].repair_action).toBe('needs_human_review');
282
+ expect(plan.entries[0].reason).toContain('ambiguous');
283
+ expect(plan.entries[0].confidence).toBeNull();
284
+ });
285
+
286
+ it('no artifact + no succeeded run payload → needs_human_review', async () => {
287
+ standardFixture();
288
+
289
+ mockConsole();
290
+ await handleRuntimeArtifactRepair({ workspace: workspaceDir, dryRun: true, out: planPath, json: true });
291
+ const plan = JSON.parse(fs.readFileSync(planPath, 'utf8'));
292
+
293
+ expect(plan.summary.needs_human_review).toBe(1);
294
+ expect(plan.entries[0].reason).toContain('no succeeded run output_payload');
295
+ });
296
+
297
+ it('dependency task exists but is not succeeded → needs_human_review (re-run dependency)', async () => {
298
+ createWorkspaceDb((db) => {
299
+ insertTasks(db, [
300
+ { taskId: FAILED_ARTIFICER_ID, status: 'failed', lastError: 'input_invalid', diagnosticJson: diagJson([DEP_SCRIBE_ID]) },
301
+ { taskId: DEP_SCRIBE_ID, kind: 'scribe', status: 'retry_wait', lastError: 'timeout', diagnosticJson: diagJson([]) },
302
+ ]);
303
+ });
304
+
305
+ mockConsole();
306
+ await handleRuntimeArtifactRepair({ workspace: workspaceDir, dryRun: true, out: planPath, json: true });
307
+ const plan = JSON.parse(fs.readFileSync(planPath, 'utf8'));
308
+
309
+ expect(plan.entries[0].repair_action).toBe('needs_human_review');
310
+ expect(plan.entries[0].reason).toContain('retry_wait');
311
+ });
312
+
313
+ it('malformed diagnostic_json → needs_human_review with explicit reason (rc-3)', async () => {
314
+ createWorkspaceDb((db) => {
315
+ insertTasks(db, [
316
+ { taskId: 'artificer-broken-diag', status: 'failed', lastError: 'input_invalid', diagnosticJson: '{not json' },
317
+ ]);
318
+ });
319
+
320
+ mockConsole();
321
+ await handleRuntimeArtifactRepair({ workspace: workspaceDir, dryRun: true, out: planPath, json: true });
322
+ const plan = JSON.parse(fs.readFileSync(planPath, 'utf8'));
323
+
324
+ expect(plan.entries[0].repair_action).toBe('needs_human_review');
325
+ expect(plan.entries[0].reason).toContain('not valid JSON');
326
+ });
327
+
328
+ it('dependency resolves directly → needs_human_review (input_invalid cause is elsewhere)', async () => {
329
+ createWorkspaceDb((db) => {
330
+ insertTasks(db, [
331
+ { taskId: FAILED_ARTIFICER_ID, status: 'failed', lastError: 'input_invalid', diagnosticJson: diagJson([DEP_SCRIBE_ID]) },
332
+ { taskId: DEP_SCRIBE_ID, kind: 'scribe', status: 'succeeded', lastError: null, diagnosticJson: diagJson([]) },
333
+ ]);
334
+ insertArtifact(db, 'pi-art-direct', DEP_SCRIBE_ID);
335
+ });
336
+
337
+ mockConsole();
338
+ await handleRuntimeArtifactRepair({ workspace: workspaceDir, dryRun: true, out: planPath, json: true });
339
+ const plan = JSON.parse(fs.readFileSync(planPath, 'utf8'));
340
+
341
+ expect(plan.entries[0].repair_action).toBe('needs_human_review');
342
+ expect(plan.entries[0].reason).toContain('no unresolved producer dependency');
343
+ expect(plan.entries[0].artifact_source).toBe('none');
344
+ });
345
+ });
346
+
347
+ describe('artifact-repair — CLI contract', () => {
348
+ it('--confirm is refused: exit 1, structured reason + nextAction, no plan file (cli-4/cli-6)', async () => {
349
+ standardFixture();
350
+ const { logs } = mockConsole();
351
+ const exitCalls: number[] = [];
352
+ vi.spyOn(process, 'exit').mockImplementation(((code?: number) => {
353
+ exitCalls.push(code ?? 0);
354
+ throw new Error('exit-called');
355
+ }) as never);
356
+
357
+ await expect(
358
+ handleRuntimeArtifactRepair({ workspace: workspaceDir, confirm: true, out: planPath, json: true }),
359
+ ).rejects.toThrow('exit-called');
360
+
361
+ expect(exitCalls).toEqual([1]);
362
+ expect(JSON.parse(logs[0])).toMatchObject({ ok: false });
363
+ expect(JSON.parse(logs[0]).reason).toContain('--confirm is not implemented');
364
+ expect(JSON.parse(logs[0]).nextAction).toContain('migration-plan.json');
365
+ expect(fs.existsSync(planPath)).toBe(false);
366
+ });
367
+
368
+ it('--dry-run + --confirm conflict → exit 1 (mutually exclusive)', async () => {
369
+ standardFixture();
370
+ const { logs } = mockConsole();
371
+ const exitCalls: number[] = [];
372
+ vi.spyOn(process, 'exit').mockImplementation(((code?: number) => {
373
+ exitCalls.push(code ?? 0);
374
+ throw new Error('exit-called');
375
+ }) as never);
376
+
377
+ await expect(
378
+ handleRuntimeArtifactRepair({ workspace: workspaceDir, dryRun: true, confirm: true, out: planPath, json: true }),
379
+ ).rejects.toThrow('exit-called');
380
+
381
+ expect(exitCalls).toEqual([1]);
382
+ expect(JSON.parse(logs[0]).reason).toContain('mutually exclusive');
383
+ });
384
+
385
+ it('missing state.db → structured error + nextAction, exitCode 1, no DB bootstrapped (rc-9/cli-5)', async () => {
386
+ // Workspace has a .pd directory but state.db was never initialized.
387
+ fs.mkdirSync(path.join(workspaceDir, '.pd'), { recursive: true });
388
+ const { logs } = mockConsole();
389
+
390
+ await handleRuntimeArtifactRepair({ workspace: workspaceDir, dryRun: true, out: planPath, json: true });
391
+
392
+ expect(process.exitCode).toBe(1);
393
+ // cli-1/cli-6: exactly one JSON object with ok:false, reason, nextAction
394
+ expect(logs).toHaveLength(1);
395
+ const stdout = JSON.parse(logs[0]);
396
+ expect(stdout.ok).toBe(false);
397
+ expect(typeof stdout.reason).toBe('string');
398
+ expect(stdout.reason.length).toBeGreaterThan(0);
399
+ expect(stdout.nextAction).toContain('state.db');
400
+ // dry-run must not create an empty state.db as a side effect
401
+ expect(fs.existsSync(dbPath)).toBe(false);
402
+ expect(fs.existsSync(planPath)).toBe(false);
403
+ });
404
+ });