@principles/pd-cli 1.129.0 → 1.131.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 (39) hide show
  1. package/dist/commands/__tests__/intent-flag-wiring.test.d.ts +9 -0
  2. package/dist/commands/__tests__/intent-flag-wiring.test.d.ts.map +1 -0
  3. package/dist/commands/__tests__/intent-flag-wiring.test.js +166 -0
  4. package/dist/commands/__tests__/intent-flag-wiring.test.js.map +1 -0
  5. package/dist/commands/intent.d.ts +59 -0
  6. package/dist/commands/intent.d.ts.map +1 -0
  7. package/dist/commands/intent.js +350 -0
  8. package/dist/commands/intent.js.map +1 -0
  9. package/dist/commands/runtime-canary.d.ts.map +1 -1
  10. package/dist/commands/runtime-canary.js +10 -11
  11. package/dist/commands/runtime-canary.js.map +1 -1
  12. package/dist/commands/runtime-internalization-queue.d.ts.map +1 -1
  13. package/dist/commands/runtime-internalization-queue.js +13 -16
  14. package/dist/commands/runtime-internalization-queue.js.map +1 -1
  15. package/dist/index.js +4 -0
  16. package/dist/index.js.map +1 -1
  17. package/dist/services/__tests__/runtime-adapter-resolver.test.js +20 -12
  18. package/dist/services/__tests__/runtime-adapter-resolver.test.js.map +1 -1
  19. package/dist/services/runtime-adapter-resolver.d.ts +1 -1
  20. package/dist/services/runtime-adapter-resolver.js +3 -3
  21. package/dist/services/runtime-adapter-resolver.js.map +1 -1
  22. package/package.json +1 -1
  23. package/src/commands/__tests__/intent-flag-wiring.test.ts +197 -0
  24. package/src/commands/intent.ts +388 -0
  25. package/src/commands/runtime-canary.ts +11 -13
  26. package/src/commands/runtime-internalization-queue.ts +14 -19
  27. package/src/index.ts +6 -0
  28. package/src/services/__tests__/runtime-adapter-resolver.test.ts +20 -12
  29. package/src/services/runtime-adapter-resolver.ts +3 -3
  30. package/tests/commands/intent.test.ts +321 -0
  31. package/tests/commands/runtime-canary.test.ts +46 -36
  32. package/tests/commands/runtime-internalization-queue.test.ts +11 -24
  33. package/tests/commands/runtime-internalization-run-once.test.ts +14 -6
  34. package/dist/services/feature-flag-loader.d.ts +0 -6
  35. package/dist/services/feature-flag-loader.d.ts.map +0 -1
  36. package/dist/services/feature-flag-loader.js +0 -53
  37. package/dist/services/feature-flag-loader.js.map +0 -1
  38. package/src/services/feature-flag-loader.ts +0 -73
  39. package/tests/services/feature-flag-loader.test.ts +0 -207
@@ -11,7 +11,6 @@ import * as path from 'path';
11
11
  import { createInternalizationQueueReadModel } from '@principles/core/runtime-v2';
12
12
  import type { InternalizationQueueSnapshot } from '@principles/core/runtime-v2';
13
13
  import { resolveWorkspaceDir } from '../resolve-workspace.js';
14
- import { loadEffectiveFeatureFlags } from '../services/feature-flag-loader.js';
15
14
  import { loadPdConfig, computeFlagsFromLoadResult } from '../services/pd-config-loader.js';
16
15
 
17
16
  interface QueueOptions {
@@ -95,29 +94,25 @@ function formatTextOutput(snap: InternalizationQueueSnapshot, workspaceDir: stri
95
94
  export async function handleRuntimeInternalizationQueue(opts: QueueOptions): Promise<void> {
96
95
  const workspaceDir = opts.workspace ? path.resolve(opts.workspace) : resolveWorkspaceDir();
97
96
 
98
- const featureFlags = loadEffectiveFeatureFlags(workspaceDir);
99
- const enabledChannels = new Set(
100
- Object.values(featureFlags.flags)
101
- .filter(f => f.enabled)
102
- .map(f => f.id),
103
- );
97
+ // Single canonical config load — replaces split-brain legacy + canonical reads (PRI-460).
98
+ const pdConfigResult = loadPdConfig(workspaceDir);
99
+ if (!pdConfigResult.ok) {
100
+ const configWarning = JSON.stringify({
101
+ level: 'warning',
102
+ source: 'pd_config',
103
+ errors: pdConfigResult.errors.map(e => ({ reason: e.reason, nextAction: e.nextAction })),
104
+ });
105
+ process.stderr.write(`${configWarning}\n`);
106
+ }
107
+ const pdFlags = computeFlagsFromLoadResult(pdConfigResult);
108
+ const enabledChannels = new Set(pdFlags.enabledChannels);
109
+ const autoConsumerEnabled = pdFlags.flags.internalization_auto_consumer?.enabled ?? false;
110
+
104
111
  const { readModel, close } = await createInternalizationQueueReadModel({ workspaceDir, enabledChannels });
105
112
 
106
113
  try {
107
114
  const snapshot = await readModel.getSnapshot();
108
115
 
109
- const pdConfigResult = loadPdConfig(workspaceDir);
110
- if (!pdConfigResult.ok) {
111
- const configWarning = JSON.stringify({
112
- level: 'warning',
113
- source: 'pd_config',
114
- errors: pdConfigResult.errors.map(e => ({ reason: e.reason, nextAction: e.nextAction })),
115
- });
116
- process.stderr.write(`${configWarning}\n`);
117
- }
118
- const pdFlags = computeFlagsFromLoadResult(pdConfigResult);
119
- const autoConsumerEnabled = pdFlags.flags.internalization_auto_consumer?.enabled ?? false;
120
-
121
116
  if (opts.json) {
122
117
  const output: Record<string, unknown> = { ...snapshot };
123
118
 
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)')
@@ -62,9 +62,11 @@ vi.mock('@principles/core/principle-tree-ledger', () => ({
62
62
  loadLedger: vi.fn().mockReturnValue({ tree: { principles: {} } }),
63
63
  }));
64
64
 
65
- const mockLoadEffectiveFeatureFlags = vi.fn();
66
- vi.mock('../feature-flag-loader.js', () => ({
67
- loadEffectiveFeatureFlags: mockLoadEffectiveFeatureFlags,
65
+ const mockLoadPdConfig = vi.fn();
66
+ const mockComputeFlagsFromLoadResult = vi.fn();
67
+ vi.mock('../pd-config-loader.js', () => ({
68
+ loadPdConfig: mockLoadPdConfig,
69
+ computeFlagsFromLoadResult: mockComputeFlagsFromLoadResult,
68
70
  }));
69
71
 
70
72
  const mockResolveRuntimeFromPdConfig = vi.fn();
@@ -136,8 +138,10 @@ describe('resolveRuntimeAdapterFromConfig (PRI-431)', () => {
136
138
  // no-op: valid config
137
139
  });
138
140
  // Default: feature flags have l2_dreamer disabled
139
- mockLoadEffectiveFeatureFlags.mockReturnValue({
141
+ mockLoadPdConfig.mockReturnValue({ ok: true, effective: {}, source: 'defaults' });
142
+ mockComputeFlagsFromLoadResult.mockReturnValue({
140
143
  flags: {},
144
+ enabledChannels: [],
141
145
  warnings: [],
142
146
  });
143
147
  });
@@ -288,8 +292,9 @@ describe('resolveRuntimeAdapterFromConfig (PRI-431)', () => {
288
292
  it('returns L2AgentLoopAdapter when runnerKind=dreamer + l2ArtifactReader + l2StateDir + flag enabled', () => {
289
293
  const config = makeValidPiAiConfig();
290
294
  mockResolveRuntimeFromPdConfig.mockReturnValue(makeResolvedConfig(config));
291
- mockLoadEffectiveFeatureFlags.mockReturnValue({
292
- flags: { l2_dreamer: { enabled: true } },
295
+ mockComputeFlagsFromLoadResult.mockReturnValue({
296
+ flags: { l2_dreamer: { id: 'l2_dreamer', enabled: true, category: 'quiet' } },
297
+ enabledChannels: [],
293
298
  warnings: [],
294
299
  });
295
300
  const fakeArtifactReader = { readArtifact: vi.fn() };
@@ -310,8 +315,9 @@ describe('resolveRuntimeAdapterFromConfig (PRI-431)', () => {
310
315
  it('falls back to PiAiRuntimeAdapter when l2_dreamer flag is disabled', () => {
311
316
  const config = makeValidPiAiConfig();
312
317
  mockResolveRuntimeFromPdConfig.mockReturnValue(makeResolvedConfig(config));
313
- mockLoadEffectiveFeatureFlags.mockReturnValue({
314
- flags: { l2_dreamer: { enabled: false } },
318
+ mockComputeFlagsFromLoadResult.mockReturnValue({
319
+ flags: { l2_dreamer: { id: 'l2_dreamer', enabled: false, category: 'quiet' } },
320
+ enabledChannels: [],
315
321
  warnings: [],
316
322
  });
317
323
 
@@ -330,8 +336,9 @@ describe('resolveRuntimeAdapterFromConfig (PRI-431)', () => {
330
336
  it('falls back to PiAiRuntimeAdapter when l2ArtifactReader is missing', () => {
331
337
  const config = makeValidPiAiConfig();
332
338
  mockResolveRuntimeFromPdConfig.mockReturnValue(makeResolvedConfig(config));
333
- mockLoadEffectiveFeatureFlags.mockReturnValue({
334
- flags: { l2_dreamer: { enabled: true } },
339
+ mockComputeFlagsFromLoadResult.mockReturnValue({
340
+ flags: { l2_dreamer: { id: 'l2_dreamer', enabled: true, category: 'quiet' } },
341
+ enabledChannels: [],
335
342
  warnings: [],
336
343
  });
337
344
 
@@ -349,8 +356,9 @@ describe('resolveRuntimeAdapterFromConfig (PRI-431)', () => {
349
356
  it('falls back to PiAiRuntimeAdapter when runnerKind is not dreamer', () => {
350
357
  const config = makeValidPiAiConfig();
351
358
  mockResolveRuntimeFromPdConfig.mockReturnValue(makeResolvedConfig(config));
352
- mockLoadEffectiveFeatureFlags.mockReturnValue({
353
- flags: { l2_dreamer: { enabled: true } },
359
+ mockComputeFlagsFromLoadResult.mockReturnValue({
360
+ flags: { l2_dreamer: { id: 'l2_dreamer', enabled: true, category: 'quiet' } },
361
+ enabledChannels: [],
354
362
  warnings: [],
355
363
  });
356
364
 
@@ -13,7 +13,7 @@
13
13
  * - CLI-gate concerns (process.exit, telemetry, help text) stay at call sites.
14
14
  * This resolver throws structured `ConfigResolutionError` that handlers translate.
15
15
  * - Lives in pd-cli/services (NOT core) because it constructs adapters and reads
16
- * CLI feature flags via `loadEffectiveFeatureFlags`, which is a pd-cli service.
16
+ * PD config via `loadPdConfig` + `computeFlagsFromLoadResult`, which are pd-cli services.
17
17
  *
18
18
  * ERR refs:
19
19
  * - ERR-001 (no any): all types explicit
@@ -34,7 +34,7 @@ import {
34
34
  } from '@principles/core/runtime-v2';
35
35
  import type { PDRuntimeAdapter, PdL2ArtifactReader, RuntimeConfig, RuntimeConfigResult } from '@principles/core/runtime-v2';
36
36
  import { loadLedger } from '@principles/core/principle-tree-ledger';
37
- import { loadEffectiveFeatureFlags } from './feature-flag-loader.js';
37
+ import { loadPdConfig, computeFlagsFromLoadResult } from './pd-config-loader.js';
38
38
  import { resolveRuntimeFromPdConfig } from './resolve-runtime-from-pd-config.js';
39
39
  import type { ResolvedRuntimeFromPdConfig } from './resolve-runtime-from-pd-config.js';
40
40
 
@@ -255,7 +255,7 @@ export function resolveRuntimeAdapterFromConfig(opts: ResolveAdapterOptions): PD
255
255
  // dreamer runner, route through the L2 multi-turn agent loop adapter.
256
256
  // Other runners (philosopher/scribe/...) stay on L1.
257
257
  if (opts.runnerKind === 'dreamer' && opts.l2ArtifactReader && opts.l2StateDir) {
258
- const effectiveFlags = loadEffectiveFeatureFlags(opts.workspaceDir);
258
+ const effectiveFlags = computeFlagsFromLoadResult(loadPdConfig(opts.workspaceDir));
259
259
  const l2FlagDef = Object.hasOwn(effectiveFlags.flags, 'l2_dreamer')
260
260
  ? effectiveFlags.flags.l2_dreamer
261
261
  : undefined;
@@ -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
+ });
@@ -46,22 +46,17 @@ vi.mock('@principles/core/runtime-v2', () => ({
46
46
  resolveOutputLanguage: vi.fn().mockReturnValue({ outputLanguage: 'zh-CN' }),
47
47
  }));
48
48
 
49
- vi.mock('../../src/services/feature-flag-loader.js', () => ({
50
- loadEffectiveFeatureFlags: vi.fn().mockReturnValue({
51
- source: 'defaults',
52
- configPath: '/fake/workspace/.pd/feature-flags.yaml',
53
- flags: {
54
- prompt: { id: 'prompt', category: 'core', enabled: true, since: '2026-05-24' },
55
- code_tool_hook: { id: 'code_tool_hook', category: 'core', enabled: true, since: '2026-05-24' },
56
- defer_archive: { id: 'defer_archive', category: 'core', enabled: true, since: '2026-05-24' },
57
- gfi: { id: 'gfi', category: 'quiet', enabled: true, since: '2026-05-24' },
58
- },
59
- warnings: [],
60
- }),
49
+ const { mockLoadPdConfig, mockComputeFlagsFromLoadResult } = vi.hoisted(() => ({
50
+ mockLoadPdConfig: vi.fn(),
51
+ mockComputeFlagsFromLoadResult: vi.fn(),
52
+ }));
53
+
54
+ vi.mock('../../src/services/pd-config-loader.js', () => ({
55
+ loadPdConfig: mockLoadPdConfig,
56
+ computeFlagsFromLoadResult: mockComputeFlagsFromLoadResult,
61
57
  }));
62
58
 
63
59
  import { runCanaryChecks } from '../../src/commands/runtime-canary.js';
64
- import { loadEffectiveFeatureFlags } from '../../src/services/feature-flag-loader.js';
65
60
 
66
61
  const WS = '/fake/workspace';
67
62
 
@@ -126,6 +121,26 @@ describe('runCanaryChecks', () => {
126
121
  mockAuditConsistency.mockResolvedValue({ status: 'ok', consumedCount: 0, orphanCandidateCount: 0, missingLedgerCount: 0 });
127
122
  mockBuildGfiSnapshot.mockReturnValue(healthyGfiSnapshot());
128
123
  mockClassifyGfiHealth.mockReturnValue({ status: 'healthy', reason: '0 active, 0 stale sessions', staleGfiDegradedThreshold: 40 });
124
+ // Default: GFI enabled, no warnings (canonical config loader)
125
+ mockLoadPdConfig.mockReturnValue({
126
+ ok: true,
127
+ effective: {},
128
+ source: 'defaults',
129
+ configPath: `${WS}/.pd/config.yaml`,
130
+ warnings: [],
131
+ legacyFilesDetected: [],
132
+ legacyFileNextActions: [],
133
+ });
134
+ mockComputeFlagsFromLoadResult.mockReturnValue({
135
+ flags: {
136
+ prompt: { id: 'prompt', category: 'core', enabled: true },
137
+ code_tool_hook: { id: 'code_tool_hook', category: 'core', enabled: true },
138
+ defer_archive: { id: 'defer_archive', category: 'core', enabled: true },
139
+ gfi: { id: 'gfi', category: 'quiet', enabled: true },
140
+ },
141
+ enabledChannels: ['prompt', 'code_tool_hook', 'defer_archive'],
142
+ warnings: [],
143
+ });
129
144
  });
130
145
 
131
146
  it('returns healthy when all checks are healthy', async () => {
@@ -275,12 +290,11 @@ describe('runCanaryChecks', () => {
275
290
 
276
291
  describe('GFI config warning degraded status', () => {
277
292
  it('returns healthy when GFI disabled with no warnings', async () => {
278
- vi.mocked(loadEffectiveFeatureFlags).mockReturnValue({
279
- source: 'defaults',
280
- configPath: `${WS}/.pd/feature-flags.yaml`,
293
+ mockComputeFlagsFromLoadResult.mockReturnValue({
281
294
  flags: {
282
- gfi: { id: 'gfi', category: 'quiet', enabled: false, since: '2026-05-24' },
295
+ gfi: { id: 'gfi', category: 'quiet', enabled: false },
283
296
  },
297
+ enabledChannels: [],
284
298
  warnings: [],
285
299
  });
286
300
 
@@ -292,13 +306,12 @@ describe('runCanaryChecks', () => {
292
306
  });
293
307
 
294
308
  it('returns degraded when GFI disabled but config has warnings (malformed YAML)', async () => {
295
- vi.mocked(loadEffectiveFeatureFlags).mockReturnValue({
296
- source: 'defaults',
297
- configPath: `${WS}/.pd/feature-flags.yaml`,
309
+ mockComputeFlagsFromLoadResult.mockReturnValue({
298
310
  flags: {
299
- gfi: { id: 'gfi', category: 'quiet', enabled: false, since: '2026-05-24' },
311
+ gfi: { id: 'gfi', category: 'quiet', enabled: false },
300
312
  },
301
- warnings: ['feature-flags.yaml: YAML parse error, using defaults'],
313
+ enabledChannels: [],
314
+ warnings: ['.pd/config.yaml: YAML parse error, using defaults'],
302
315
  });
303
316
 
304
317
  const result = await runCanaryChecks(WS);
@@ -307,16 +320,15 @@ describe('runCanaryChecks', () => {
307
320
  expect(gfiCheck?.status).toBe('degraded');
308
321
  expect(gfiCheck?.summary).toContain('warnings');
309
322
  expect(gfiCheck?.details).toBeDefined();
310
- expect(result.recommendedNextActions.some(a => a.includes('feature-flags.yaml'))).toBe(true);
323
+ expect(result.recommendedNextActions.some(a => a.includes('config.yaml'))).toBe(true);
311
324
  });
312
325
 
313
326
  it('returns degraded when GFI disabled but config has malformed override warning', async () => {
314
- vi.mocked(loadEffectiveFeatureFlags).mockReturnValue({
315
- source: 'workspace_file',
316
- configPath: `${WS}/.pd/feature-flags.yaml`,
327
+ mockComputeFlagsFromLoadResult.mockReturnValue({
317
328
  flags: {
318
- gfi: { id: 'gfi', category: 'quiet', enabled: false, since: '2026-05-24' },
329
+ gfi: { id: 'gfi', category: 'quiet', enabled: false },
319
330
  },
331
+ enabledChannels: [],
320
332
  warnings: ["flag 'gfi': malformed override kept default (enabled must be boolean)"],
321
333
  });
322
334
 
@@ -324,16 +336,15 @@ describe('runCanaryChecks', () => {
324
336
  const gfiCheck = result.checks.find(c => c.name === 'gfi_snapshot');
325
337
 
326
338
  expect(gfiCheck?.status).toBe('degraded');
327
- expect(result.recommendedNextActions.some(a => a.includes('feature-flags.yaml') || a.includes('pd runtime features'))).toBe(true);
339
+ expect(result.recommendedNextActions.some(a => a.includes('config.yaml') || a.includes('pd runtime features'))).toBe(true);
328
340
  });
329
341
 
330
342
  it('runs GFI snapshot when flag enabled with no warnings', async () => {
331
- vi.mocked(loadEffectiveFeatureFlags).mockReturnValue({
332
- source: 'workspace_file',
333
- configPath: `${WS}/.pd/feature-flags.yaml`,
343
+ mockComputeFlagsFromLoadResult.mockReturnValue({
334
344
  flags: {
335
- gfi: { id: 'gfi', category: 'quiet', enabled: true, since: '2026-05-24' },
345
+ gfi: { id: 'gfi', category: 'quiet', enabled: true },
336
346
  },
347
+ enabledChannels: [],
337
348
  warnings: [],
338
349
  });
339
350
 
@@ -346,12 +357,11 @@ describe('runCanaryChecks', () => {
346
357
  });
347
358
 
348
359
  it('recommends session lifecycle review for GFI session issues (not config)', async () => {
349
- vi.mocked(loadEffectiveFeatureFlags).mockReturnValue({
350
- source: 'defaults',
351
- configPath: `${WS}/.pd/feature-flags.yaml`,
360
+ mockComputeFlagsFromLoadResult.mockReturnValue({
352
361
  flags: {
353
- gfi: { id: 'gfi', category: 'quiet', enabled: true, since: '2026-05-24' },
362
+ gfi: { id: 'gfi', category: 'quiet', enabled: true },
354
363
  },
364
+ enabledChannels: [],
355
365
  warnings: [],
356
366
  });
357
367
  mockClassifyGfiHealth.mockReturnValue({