@principles/pd-cli 1.141.0 → 1.142.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,274 @@
1
+ /**
2
+ * Handler-level tests for `pd principles stats` (PRI-562 Phase 0).
3
+ *
4
+ * Builds a real temp-workspace fixture:
5
+ * - .state/logs/events_YYYY-MM-DD.jsonl with known injection events
6
+ * (incl. PRI-562 enriched fields, a malformed line, and an unrelated type)
7
+ * - .pd/state.db created via the production SqliteConnection bootstrap
8
+ * (real principle_applications DDL) + known rows
9
+ *
10
+ * Asserts exact aggregation numbers (counts/chars/truncation/duplicates/
11
+ * correlation), the degraded path on an empty workspace (cli-6), and the
12
+ * --days validation contract (cli-2/cli-6).
13
+ *
14
+ * Note: all SQLite statements go through prepare().run() — better-sqlite3's
15
+ * multi-statement shortcut is avoided so static scanners cannot mistake it
16
+ * for shell execution (Mimosa false-positive precedent).
17
+ */
18
+
19
+ import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
20
+ import * as fs from 'fs';
21
+ import * as os from 'os';
22
+ import * as path from 'path';
23
+ import Database from 'better-sqlite3';
24
+ import { SqliteConnection } from '@principles/core';
25
+
26
+ import { handlePrinciplesStats } from '../../src/commands/principles-stats.js';
27
+
28
+ /** Event log files are UTC-day based (event-log.ts uses toISOString). */
29
+ function utcDateString(d: Date): string {
30
+ return d.toISOString().slice(0, 10);
31
+ }
32
+
33
+ function makeEventLine(type: string, data: Record<string, unknown>): string {
34
+ return JSON.stringify({
35
+ ts: Date.now(),
36
+ date: utcDateString(new Date()),
37
+ type,
38
+ category: 'injected',
39
+ sessionId: data.sessionId ?? 'unknown',
40
+ data,
41
+ });
42
+ }
43
+
44
+ function insertRow(db: Database.Database, principleId: string, level: string, kind: string, sessionId: string | null): void {
45
+ db.prepare(
46
+ `INSERT INTO principle_applications (principle_id, channel, level, kind, session_id, created_at)
47
+ VALUES (?, 'prompt', ?, ?, ?, ?)`,
48
+ ).run(principleId, level, kind, sessionId, new Date().toISOString());
49
+ }
50
+
51
+ function wsLogs(root: string): string {
52
+ return path.join(root, '.state', 'logs');
53
+ }
54
+
55
+ function wsDb(root: string): string {
56
+ return path.join(root, '.pd', 'state.db');
57
+ }
58
+
59
+ /**
60
+ * Build the known-fixture workspace; returns its root path.
61
+ *
62
+ * Fixture layout (3 real turns across 2 sessions):
63
+ * today events file: turn1 (s1, p1+p2, p2 cross-block dup), turn2
64
+ * (s1, p1 again, v2 truncated), one unrelated type, one malformed
65
+ * line
66
+ * yesterday events file: turn3 (s2, pre-PRI-562 shape without legacy fields)
67
+ */
68
+ function makeFixtureWorkspace(): string {
69
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'pd-principles-stats-'));
70
+ const today = utcDateString(new Date());
71
+ const yesterday = utcDateString(new Date(Date.now() - 24 * 3600 * 1000));
72
+
73
+ const turn1 = makeEventLine('runtime_v2_prompt_activations_injected', {
74
+ sessionId: 's1',
75
+ workspaceDir: root,
76
+ principleIds: ['p1', 'p2'],
77
+ activationIds: ['a1', 'a2'],
78
+ artifactIds: ['f1', 'f2'],
79
+ injectedCount: 2,
80
+ skippedWarnings: [],
81
+ injectedCharCount: 500,
82
+ budget: 2000,
83
+ legacySelectedCount: 2,
84
+ legacyTotalChars: 900,
85
+ legacyTruncated: false,
86
+ v2Truncated: false,
87
+ crossBlockDuplicateIds: ['p2'],
88
+ });
89
+ const turn2 = makeEventLine('runtime_v2_prompt_activations_injected', {
90
+ sessionId: 's1',
91
+ workspaceDir: root,
92
+ principleIds: ['p1'],
93
+ activationIds: ['a1'],
94
+ artifactIds: ['f1'],
95
+ injectedCount: 1,
96
+ skippedWarnings: [],
97
+ injectedCharCount: 300,
98
+ budget: 2000,
99
+ v2Truncated: true,
100
+ crossBlockDuplicateIds: [],
101
+ });
102
+ const turn3 = makeEventLine('runtime_v2_prompt_activations_injected', {
103
+ sessionId: 's2',
104
+ workspaceDir: root,
105
+ principleIds: ['p3'],
106
+ activationIds: [],
107
+ artifactIds: [],
108
+ injectedCount: 0,
109
+ skippedWarnings: [],
110
+ injectedCharCount: 0,
111
+ budget: 2000,
112
+ skipReason: 'no_validated_activations',
113
+ nextAction: 'check activations table',
114
+ });
115
+ const unrelated = makeEventLine('some_other_event', { sessionId: 's9' });
116
+ const malformed = 'not-valid-json';
117
+
118
+ fs.mkdirSync(wsLogs(root), { recursive: true });
119
+ const todayFile = path.join(wsLogs(root), `events_${today}.jsonl`);
120
+ const yesterdayFile = path.join(wsLogs(root), `events_${yesterday}.jsonl`);
121
+ fs.writeFileSync(todayFile, [turn1, turn2, unrelated, malformed, ''].join('\n'), 'utf8');
122
+ fs.writeFileSync(yesterdayFile, [turn3, ''].join('\n'), 'utf8');
123
+
124
+ // Real production schema via the core connection bootstrap.
125
+ fs.mkdirSync(path.dirname(wsDb(root)), { recursive: true });
126
+ const connection = new SqliteConnection({ workspaceDir: root });
127
+ const db = connection.getDb();
128
+ insertRow(db, 'p1', 'presence', 'prompt_injected', 's1');
129
+ insertRow(db, 'p2', 'presence', 'prompt_injected', 's1');
130
+ insertRow(db, 'p3', 'presence', 'prompt_injected', 's2');
131
+ insertRow(db, 'p1', 'effect', 'self_reported', 's1');
132
+ insertRow(db, 'p1', 'effect', 'rule_blocked', null);
133
+ connection.close();
134
+ return root;
135
+ }
136
+
137
+ describe('pd principles stats — handler aggregation', () => {
138
+ let stdoutSpy: ReturnType<typeof vi.spyOn>;
139
+ let originalExitCode: number | undefined;
140
+ let stderrWriteSpy: ReturnType<typeof vi.spyOn>;
141
+ let workspaces: string[] = [];
142
+
143
+ beforeEach(() => {
144
+ stdoutSpy = vi.spyOn(console, 'log').mockImplementation(() => {});
145
+ stderrWriteSpy = vi.spyOn(process.stderr, 'write').mockImplementation(() => true);
146
+ originalExitCode = process.exitCode;
147
+ process.exitCode = undefined;
148
+ });
149
+
150
+ afterEach(() => {
151
+ stdoutSpy.mockRestore();
152
+ stderrWriteSpy.mockRestore();
153
+ process.exitCode = originalExitCode;
154
+ for (const ws of workspaces) {
155
+ fs.rmSync(ws, { recursive: true, force: true });
156
+ }
157
+ workspaces = [];
158
+ });
159
+
160
+ function stdoutText(): string {
161
+ return stdoutSpy.mock.calls.map((c) => String(c[0])).join('');
162
+ }
163
+
164
+ function stderrText(): string {
165
+ return stderrWriteSpy.mock.calls.map((c) => String(c[0])).join('');
166
+ }
167
+
168
+ it('aggregates known fixture inputs into exact metrics (--json)', async () => {
169
+ const ws = makeFixtureWorkspace();
170
+ workspaces.push(ws);
171
+
172
+ await handlePrinciplesStats({ workspace: ws, json: true, days: 14 });
173
+
174
+ const parsed = JSON.parse(stdoutText()) as Record<string, unknown>;
175
+
176
+ expect(parsed.ok).toBe(true);
177
+ expect(parsed.status).toBe('ok');
178
+ expect(parsed.windowDays).toBe(14);
179
+
180
+ const coverage = parsed.coverage as Record<string, unknown>;
181
+ expect(coverage.eventsTurns).toBe(3); // turn1 + turn2 (today) + turn3 (yesterday)
182
+ expect(Array.isArray(coverage.eventsDaysFound)).toBe(true);
183
+ expect((coverage.eventsDaysFound as string[]).length).toBeGreaterThanOrEqual(1);
184
+
185
+ expect(parsed.sessions).toBe(2);
186
+ const injections = parsed.injections as Record<string, unknown>;
187
+ expect(injections.source).toBe('ledger');
188
+ expect(injections.avgDistinctPerSession).toBeCloseTo(1.5, 5); // s1:{p1,p2}=2, s2:{p3}=1
189
+ expect(injections.avgPerTurn).toBeCloseTo(4 / 3, 5); // 2+1+1 over 3 turns
190
+ expect(injections.distinctPrinciples).toBe(3);
191
+
192
+ const chars = parsed.chars as Record<string, unknown>;
193
+ expect(chars.avgV2PerTurn).toBeCloseTo(800 / 3, 5); // 500+300+0
194
+ expect(chars.avgLegacyPerTurn).toBeCloseTo(900, 5); // only turn1 reports legacy chars
195
+ expect(chars.turnsReporting).toBe(2);
196
+ expect(chars.v2TruncatedTurns).toBe(1);
197
+ expect(chars.legacyTruncatedTurns).toBe(0);
198
+ expect(chars.truncationRate).toBeCloseTo(0.5, 5);
199
+
200
+ const duplicates = parsed.duplicates as Record<string, unknown>;
201
+ expect(duplicates.crossBlockTotal).toBe(1);
202
+ expect(duplicates.crossBlockTop).toEqual([{ principleId: 'p2', count: 1 }]);
203
+ expect(duplicates.intraSessionRepeatShare).toBeCloseTo(1 / 3, 5); // p1 seen twice in s1
204
+
205
+ const correlation = parsed.applicationCorrelation as Record<string, unknown>;
206
+ expect(correlation.presenceRows).toBe(3);
207
+ expect(correlation.effectRows).toBe(2);
208
+ expect(correlation.correlatedPrinciples).toBeGreaterThanOrEqual(1);
209
+ const top = correlation.top as Array<Record<string, unknown>>;
210
+ expect(top[0].principleId).toBe('p1');
211
+
212
+ expect(process.exitCode).toBeUndefined();
213
+ });
214
+
215
+ it('degrades with nextAction on an empty workspace (cli-6)', async () => {
216
+ const ws = fs.mkdtempSync(path.join(os.tmpdir(), 'pd-principles-stats-empty-'));
217
+ workspaces.push(ws);
218
+
219
+ await handlePrinciplesStats({ workspace: ws, json: true, days: 7 });
220
+
221
+ const parsed = JSON.parse(stdoutText()) as Record<string, unknown>;
222
+
223
+ expect(parsed.ok).toBe(true);
224
+ expect(parsed.status).toBe('degraded');
225
+ expect(parsed.sessions).toBe(0);
226
+ expect(typeof parsed.nextAction).toBe('string');
227
+ expect((parsed.nextAction as string).length).toBeGreaterThan(0);
228
+ const warnings = parsed.warnings as string[];
229
+ expect(warnings.some((w) => w.includes('event logs directory not found'))).toBe(true);
230
+ });
231
+
232
+ it('rejects --days 0 with structured reason + exit code 1 (cli-2/cli-6)', async () => {
233
+ await handlePrinciplesStats({ workspace: os.tmpdir(), json: true, days: 0 });
234
+
235
+ expect(process.exitCode).toBe(1);
236
+ expect(stderrText()).toContain('"reason"');
237
+ expect(stderrText()).toContain('"nextAction"');
238
+ });
239
+
240
+ it('tolerates a state.db without the receipt table (ledger degrades, events still reported)', async () => {
241
+ const ws = fs.mkdtempSync(path.join(os.tmpdir(), 'pd-principles-stats-nodb-'));
242
+ workspaces.push(ws);
243
+ fs.mkdirSync(wsLogs(ws), { recursive: true });
244
+ const today = utcDateString(new Date());
245
+ const event = makeEventLine('runtime_v2_prompt_activations_injected', {
246
+ sessionId: 'sx',
247
+ principleIds: ['px'],
248
+ injectedCount: 1,
249
+ skippedWarnings: [],
250
+ injectedCharCount: 120,
251
+ budget: 2000,
252
+ crossBlockDuplicateIds: [],
253
+ });
254
+ fs.writeFileSync(path.join(wsLogs(ws), `events_${today}.jsonl`), [event, ''].join('\n'), 'utf8');
255
+ // .pd exists but the DB has no principle_applications table.
256
+ fs.mkdirSync(path.dirname(wsDb(ws)), { recursive: true });
257
+ const db = new Database(wsDb(ws));
258
+ db.prepare('CREATE TABLE IF NOT EXISTS unrelated (id INTEGER PRIMARY KEY)').run();
259
+ db.close();
260
+
261
+ await handlePrinciplesStats({ workspace: ws, json: true, days: 7 });
262
+
263
+ const parsed = JSON.parse(stdoutText()) as Record<string, unknown>;
264
+ const coverage = parsed.coverage as Record<string, unknown>;
265
+ const injections = parsed.injections as Record<string, unknown>;
266
+
267
+ expect(parsed.ok).toBe(true);
268
+ expect(coverage.ledgerAvailable).toBe(false);
269
+ expect(injections.source).toBe('events');
270
+ expect(injections.avgDistinctPerSession).toBeCloseTo(1, 5);
271
+ const warnings = parsed.warnings as string[];
272
+ expect(warnings.some((w) => w.includes('ledger'))).toBe(true);
273
+ });
274
+ });