@principles/pd-cli 1.128.2 → 1.129.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,214 @@
1
+ /**
2
+ * RuleHost Readiness Resolver — PRI-461
3
+ *
4
+ * Checks all preconditions for `run-rulehost` BEFORE constructing adapters,
5
+ * returning one of three user-visible statuses:
6
+ * - `ready`: all agents enabled with pi-ai profiles and API keys; code-rule capability ON
7
+ * - `text_principle_only`: dreamer/philosopher/scribe ready, but code-rule capability OFF
8
+ * (flag disabled, or artificer/evaluator not ready)
9
+ * - `refused`: dreamer/philosopher/scribe chain broken (disabled, wrong profile, missing API key,
10
+ * or config malformed)
11
+ *
12
+ * This module NEVER throws. It always returns a structured result with reason + nextAction,
13
+ * so the CLI handler can emit a clear status instead of an opaque adapter-resolution failure.
14
+ *
15
+ * ERR refs:
16
+ * - EP-02 / ERR-024, ERR-025: wired into the production handler path (runtime-internalization-run-rulehost.ts)
17
+ * - EP-03: refused/text_principle_only include reason + nextAction
18
+ * - EP-07: uses the same config source as the pipeline (resolveRuntimeFromPdConfig)
19
+ * - EP-09: tests cover the default installed config pattern
20
+ */
21
+ import { resolveAgentRuntimeBinding, checkAgentRuntimeReadiness, computeFeatureFlagsFromConfig, isFeatureEnabled, } from '@principles/core/runtime-v2';
22
+ import { resolveRuntimeFromPdConfig } from './resolve-runtime-from-pd-config.js';
23
+ // ── Constants ─────────────────────────────────────────────────────────────────
24
+ /**
25
+ * Agents required for the text-principle path (dreamer → philosopher → scribe).
26
+ * If any of these is not ready, the pipeline cannot produce even text principles.
27
+ */
28
+ const REQUIRED_AGENTS = ['dreamer', 'philosopher', 'scribe'];
29
+ /**
30
+ * Agents required for the code-rule capability (artificer + evaluator).
31
+ * Both must be ready for the adversarial loop to run.
32
+ */
33
+ const CODE_RULE_AGENTS = ['artificer', 'evaluator'];
34
+ // ── Implementation ────────────────────────────────────────────────────────────
35
+ /**
36
+ * Check a single agent's readiness for the RuleHost pipeline.
37
+ *
38
+ * Checks (in order):
39
+ * 1. Agent enabled (via resolveAgentRuntimeBinding)
40
+ * 2. Profile exists (via resolveAgentRuntimeBinding)
41
+ * 3. Profile type is 'pi-ai' (RuleHost needs PiAiRuntimeAdapter)
42
+ * 4. Profile is ready (via checkAgentRuntimeReadiness — provider/model/apiKeyEnv set, env var exists)
43
+ *
44
+ * Returns a structured AgentReadiness result. Never throws.
45
+ */
46
+ function checkAgentReadiness(effective, agentName, getEnvVar) {
47
+ const binding = resolveAgentRuntimeBinding(effective, agentName);
48
+ if (!binding.ok) {
49
+ return {
50
+ status: binding.readiness === 'disabled' ? 'disabled' : binding.readiness === 'needs_setup' ? 'needs_setup' : 'not_ready',
51
+ reason: binding.reason,
52
+ nextAction: binding.nextAction,
53
+ };
54
+ }
55
+ const profile = binding.profile;
56
+ const profileType = profile.type;
57
+ // RuleHost pipeline constructs PiAiRuntimeAdapter instances, so the profile
58
+ // must be pi-ai. OpenClaw profiles delegate to OpenClaw's own runtime, which
59
+ // is not available in the RuleHost pipeline context.
60
+ if (profileType !== 'pi-ai') {
61
+ return {
62
+ status: 'wrong_profile_type',
63
+ reason: `Agent '${agentName}' uses profile '${binding.profileId}' with type '${profileType}', but RuleHost requires pi-ai profile type`,
64
+ nextAction: `Add a pi-ai runtime profile to .pd/config.yaml and assign it to ${agentName} via internalAgents.agents.${agentName}.runtimeProfile`,
65
+ profileId: binding.profileId,
66
+ profileType,
67
+ };
68
+ }
69
+ const readiness = checkAgentRuntimeReadiness(profile, getEnvVar);
70
+ if (readiness.readiness !== 'ready') {
71
+ return {
72
+ status: readiness.readiness === 'needs_setup' ? 'needs_setup' : 'not_ready',
73
+ reason: readiness.reason,
74
+ nextAction: readiness.nextAction,
75
+ profileId: binding.profileId,
76
+ profileType,
77
+ };
78
+ }
79
+ return {
80
+ status: 'ready',
81
+ profileId: binding.profileId,
82
+ profileType,
83
+ };
84
+ }
85
+ function emptyAgentStatuses() {
86
+ const empty = { status: 'not_ready', reason: 'not checked' };
87
+ return {
88
+ dreamer: empty,
89
+ philosopher: empty,
90
+ scribe: empty,
91
+ artificer: empty,
92
+ evaluator: empty,
93
+ };
94
+ }
95
+ function buildRefusedResult(reason, nextAction, parts) {
96
+ return {
97
+ status: 'refused',
98
+ reason,
99
+ nextAction,
100
+ agentStatuses: parts.agentStatuses,
101
+ codeRuleCapability: parts.codeRuleCapability,
102
+ };
103
+ }
104
+ function buildTextPrincipleOnlyResult(reason, nextAction, parts) {
105
+ return {
106
+ status: 'text_principle_only',
107
+ reason,
108
+ nextAction,
109
+ agentStatuses: parts.agentStatuses,
110
+ codeRuleCapability: parts.codeRuleCapability,
111
+ };
112
+ }
113
+ function resolveRuleHostReadinessUnchecked(workspaceDir, getEnvVar) {
114
+ // ── Step 1: Load config ──
115
+ const { configLoadResult } = resolveRuntimeFromPdConfig(workspaceDir, getEnvVar);
116
+ if (!configLoadResult.ok) {
117
+ const [firstError] = configLoadResult.errors;
118
+ const reason = `config_malformed: ${firstError?.reason ?? 'unknown config error'}`;
119
+ const nextAction = firstError?.nextAction ?? 'Fix .pd/config.yaml syntax and retry';
120
+ return buildRefusedResult(reason, nextAction, {
121
+ agentStatuses: emptyAgentStatuses(),
122
+ codeRuleCapability: { enabled: false, disabledReason: 'config_malformed' },
123
+ });
124
+ }
125
+ const { effective } = configLoadResult;
126
+ // ── Step 2: Check required agents (dreamer, philosopher, scribe) ──
127
+ // Start with all 5 keys set to 'not checked'; updated as each agent is checked.
128
+ const agentStatuses = emptyAgentStatuses();
129
+ const requiredFailures = [];
130
+ for (const agentName of REQUIRED_AGENTS) {
131
+ const readiness = checkAgentReadiness(effective, agentName, getEnvVar);
132
+ agentStatuses[agentName] = readiness;
133
+ if (readiness.status !== 'ready') {
134
+ requiredFailures.push(`${agentName}: ${readiness.reason ?? readiness.status}`);
135
+ }
136
+ }
137
+ if (requiredFailures.length > 0) {
138
+ const reason = `required_agents_not_ready: ${requiredFailures.join('; ')}`;
139
+ const nextAction = `Fix the following agent issues in .pd/config.yaml: ${requiredFailures.join('; ')}. RuleHost requires dreamer, philosopher, and scribe agents to be enabled with pi-ai runtime profiles and valid API keys.`;
140
+ return buildRefusedResult(reason, nextAction, {
141
+ agentStatuses,
142
+ codeRuleCapability: { enabled: false, disabledReason: 'required_agents_not_ready' },
143
+ });
144
+ }
145
+ // ── Step 3: Check code_rule_capability feature flag ──
146
+ const featureFlags = computeFeatureFlagsFromConfig(effective);
147
+ if (!isFeatureEnabled(featureFlags, 'code_rule_capability')) {
148
+ const reason = 'code_rule_capability feature flag is disabled';
149
+ const nextAction = "Enable code_rule_capability in .pd/config.yaml features.code_rule_capability.enabled to run the full adversarial pipeline. Text-principle-only mode is available.";
150
+ // Still check artificer/evaluator for reporting, but they don't affect the status
151
+ for (const agentName of CODE_RULE_AGENTS) {
152
+ agentStatuses[agentName] = checkAgentReadiness(effective, agentName, getEnvVar);
153
+ }
154
+ return buildTextPrincipleOnlyResult(reason, nextAction, {
155
+ agentStatuses,
156
+ codeRuleCapability: { enabled: false, disabledReason: reason },
157
+ });
158
+ }
159
+ // ── Step 4: Check code-rule agents (artificer, evaluator) ──
160
+ const codeRuleFailures = [];
161
+ for (const agentName of CODE_RULE_AGENTS) {
162
+ const readiness = checkAgentReadiness(effective, agentName, getEnvVar);
163
+ agentStatuses[agentName] = readiness;
164
+ if (readiness.status !== 'ready') {
165
+ codeRuleFailures.push(`${agentName}: ${readiness.reason ?? readiness.status}`);
166
+ }
167
+ }
168
+ if (codeRuleFailures.length > 0) {
169
+ const reason = `code_rule_agents_not_ready: ${codeRuleFailures.join('; ')}`;
170
+ const nextAction = `Fix the following agent issues to enable code-rule capability: ${codeRuleFailures.join('; ')}. Text-principle-only mode is available with the current configuration.`;
171
+ return buildTextPrincipleOnlyResult(reason, nextAction, {
172
+ agentStatuses,
173
+ codeRuleCapability: { enabled: false, disabledReason: reason },
174
+ });
175
+ }
176
+ // ── Step 5: All checks pass → ready ──
177
+ return {
178
+ status: 'ready',
179
+ reason: 'All agents ready with pi-ai profiles and valid API keys. Code-rule capability is ON.',
180
+ nextAction: 'Pass --confirm to run the full pipeline.',
181
+ agentStatuses,
182
+ codeRuleCapability: { enabled: true },
183
+ };
184
+ }
185
+ /**
186
+ * Resolve RuleHost readiness from the workspace's .pd/config.yaml.
187
+ *
188
+ * This is the production entry point called by the `run-rulehost` handler
189
+ * BEFORE constructing any adapters. It returns a structured result so the
190
+ * handler can emit a clear status instead of an opaque adapter-resolution failure.
191
+ *
192
+ * This function NEVER throws. Any unexpected exception from config loading,
193
+ * feature-flag computation, agent checks, or getEnvVar is caught and converted
194
+ * to a `refused` result with reason + nextAction (Runtime Contract #9).
195
+ *
196
+ * @param workspaceDir - The workspace directory containing .pd/config.yaml
197
+ * @param getEnvVar - Env var accessor, defaults to process.env. Injected for testability.
198
+ * @returns Structured readiness result. Never throws.
199
+ */
200
+ export function resolveRuleHostReadiness(workspaceDir, getEnvVar = (name) => process.env[name]) {
201
+ try {
202
+ return resolveRuleHostReadinessUnchecked(workspaceDir, getEnvVar);
203
+ }
204
+ catch (error) {
205
+ const message = error instanceof Error && error.message.length > 0
206
+ ? error.message
207
+ : 'unknown readiness resolution error';
208
+ return buildRefusedResult(`readiness_resolution_failed: ${message}`, 'Fix the readiness resolution error and retry. Run `pd config doctor` for diagnostics.', {
209
+ agentStatuses: emptyAgentStatuses(),
210
+ codeRuleCapability: { enabled: false, disabledReason: 'readiness_resolution_failed' },
211
+ });
212
+ }
213
+ }
214
+ //# sourceMappingURL=rulehost-readiness.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"rulehost-readiness.js","sourceRoot":"","sources":["../../src/services/rulehost-readiness.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;GAmBG;AAEH,OAAO,EACL,0BAA0B,EAC1B,0BAA0B,EAC1B,6BAA6B,EAC7B,gBAAgB,GACjB,MAAM,6BAA6B,CAAC;AAKrC,OAAO,EAAE,0BAA0B,EAAE,MAAM,qCAAq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AC;QAC5E,MAAM,UAAU,GAAG,kEAAkE,gBAAgB,CAAC,IAAI,CAAC,IAAI,CAAC,yEAAyE,CAAC;QAC1L,OAAO,4BAA4B,CAAC,MAAM,EAAE,UAAU,EAAE;YACtD,aAAa;YACb,kBAAkB,EAAE,EAAE,OAAO,EAAE,KAAK,EAAE,cAAc,EAAE,MAAM,EAAE;SAC/D,CAAC,CAAC;IACL,CAAC;IAED,wCAAwC;IACxC,OAAO;QACL,MAAM,EAAE,OAAO;QACf,MAAM,EAAE,sFAAsF;QAC9F,UAAU,EAAE,0CAA0C;QACtD,aAAa;QACb,kBAAkB,EAAE,EAAE,OAAO,EAAE,IAAI,EAAE;KACtC,CAAC;AACJ,CAAC;AAED;;;;;;;;;;;;;;GAcG;AACH,MAAM,UAAU,wBAAwB,CACtC,YAAoB,EACpB,YAAkD,CAAC,IAAI,EAAE,EAAE,CAAC,OAAO,CAAC,GAAG,CAAC,IAAI,CAAC;IAE7E,IAAI,CAAC;QACH,OAAO,iCAAiC,CAAC,YAAY,EAAE,SAAS,CAAC,CAAC;IACpE,CAAC;IAAC,OAAO,KAAc,EAAE,CAAC;QACxB,MAAM,OAAO,GACX,KAAK,YAAY,KAAK,IAAI,KAAK,CAAC,OAAO,CAAC,MAAM,GAAG,CAAC;YAChD,CAAC,CAAC,KAAK,CAAC,OAAO;YACf,CAAC,CAAC,oCAAoC,CAAC;QAC3C,OAAO,kBAAkB,CACvB,gCAAgC,OAAO,EAAE,EACzC,uFAAuF,EACvF;YACE,aAAa,EAAE,kBAAkB,EAAE;YACnC,kBAAkB,EAAE,EAAE,OAAO,EAAE,KAAK,EAAE,cAAc,EAAE,6BAA6B,EAAE;SACtF,CACF,CAAC;IACJ,CAAC;AACH,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@principles/pd-cli",
3
- "version": "1.128.2",
3
+ "version": "1.129.0",
4
4
  "description": "PD CLI — Pain recording, sample management, and evolution tasks",
5
5
  "type": "module",
6
6
  "bin": {
@@ -38,6 +38,8 @@ import {
38
38
  } from '@principles/core/runtime-v2';
39
39
  import type { EffectivePdConfig, InternalAgentName, PDRuntimeAdapter } from '@principles/core/runtime-v2';
40
40
  import { resolveRuntimeFromPdConfig } from '../services/resolve-runtime-from-pd-config.js';
41
+ import { resolveRuleHostReadiness } from '../services/rulehost-readiness.js';
42
+ import type { RuleHostReadinessResult } from '../services/rulehost-readiness.js';
41
43
 
42
44
  export interface RunRuleHostOptions {
43
45
  workspace?: string;
@@ -109,6 +111,7 @@ function resolvePiAiAgentAdapter(
109
111
  function resolveRunRuleHostRuntime(
110
112
  workspaceDir: string,
111
113
  timeoutMs: number | undefined,
114
+ readiness: RuleHostReadinessResult,
112
115
  ): ResolvedRunRuleHostRuntime {
113
116
  const { configLoadResult } = resolveRuntimeFromPdConfig(workspaceDir);
114
117
 
@@ -126,6 +129,14 @@ function resolveRunRuleHostRuntime(
126
129
  philosopher: philosopher.profileId,
127
130
  scribe: scribe.profileId,
128
131
  };
132
+ if (readiness.status === 'text_principle_only') {
133
+ return {
134
+ agentAdapters: { dreamer: dreamer.adapter, philosopher: philosopher.adapter, scribe: scribe.adapter, evaluator: scribe.adapter },
135
+ agentRuntimeProfiles,
136
+ capability: { enabled: false, disabledReason: readiness.reason },
137
+ capabilityStatus: `code_rule_capability: OFF (${readiness.reason})`,
138
+ };
139
+ }
129
140
  const featureFlags = computeFeatureFlagsFromConfig(effective);
130
141
  if (!isFeatureEnabled(featureFlags, 'code_rule_capability')) {
131
142
  return {
@@ -234,16 +245,35 @@ function formatTextOutput(result: RuleHostPipelineResult): string {
234
245
  return lines.join('\n');
235
246
  }
236
247
 
237
- function formatDryRunOutput(opts: RunRuleHostOptions, capabilityStatus: string, workspaceDir: string): string {
248
+ interface DryRunFormatInput {
249
+ readonly opts: RunRuleHostOptions;
250
+ readonly capabilityStatus: string;
251
+ readonly workspaceDir: string;
252
+ readonly readiness: RuleHostReadinessResult;
253
+ }
254
+
255
+ function formatDryRunOutput(input: DryRunFormatInput): string {
256
+ const { opts, capabilityStatus, workspaceDir, readiness } = input;
238
257
  const lines: string[] = [];
239
258
  lines.push('RuleHost Pipeline (PRI-429) — DRY RUN');
240
259
  lines.push(`pain: ${opts.painId}`);
241
260
  lines.push(`workspace: ${workspaceDir}`);
242
261
  lines.push(`channel: ${opts.channel ?? 'code_tool_hook'}`);
262
+ lines.push(`readiness: ${readiness.status.toUpperCase()}`);
263
+ if (readiness.status !== 'ready') {
264
+ lines.push(` reason: ${readiness.reason}`);
265
+ lines.push(` nextAction: ${readiness.nextAction}`);
266
+ }
243
267
  lines.push(capabilityStatus);
244
268
  lines.push('');
245
269
  lines.push('No tasks created, no LLM calls made, no artifacts written.');
246
- lines.push('Next: pass --confirm to actually run the pipeline.');
270
+ if (readiness.status === 'ready') {
271
+ lines.push('Next: pass --confirm to actually run the pipeline.');
272
+ } else if (readiness.status === 'text_principle_only') {
273
+ lines.push('Next: pass --confirm to run in text-principle-only mode, or fix the issues above to enable full pipeline.');
274
+ } else {
275
+ lines.push('Next: fix the readiness issues above before running the pipeline.');
276
+ }
247
277
  return lines.join('\n');
248
278
  }
249
279
 
@@ -303,14 +333,40 @@ export async function handleRunRuleHost(opts: RunRuleHostOptions): Promise<void>
303
333
 
304
334
  const workspaceDir = resolveWorkspace(opts);
305
335
 
336
+ // ── Readiness check (PRI-461) ──
337
+ // Check all preconditions BEFORE constructing adapters. This produces a
338
+ // structured ready/text_principle_only/refused status instead of an opaque
339
+ // agent_runtime_resolution_failed error.
340
+ const readiness = resolveRuleHostReadiness(workspaceDir);
341
+
342
+ // If refused, emit structured error and exit (CLI gate rule 2 + rule 5).
343
+ // Refused means the pipeline cannot run at all — do NOT attempt adapter
344
+ // construction or pipeline execution.
345
+ if (readiness.status === 'refused') {
346
+ if (opts.json) {
347
+ process.stdout.write(JSON.stringify({
348
+ status: 'refused',
349
+ reason: readiness.reason,
350
+ nextAction: readiness.nextAction,
351
+ readiness,
352
+ }) + '\n');
353
+ } else {
354
+ console.error(`RuleHost readiness: REFUSED`);
355
+ console.error(` reason: ${readiness.reason}`);
356
+ console.error(` nextAction: ${readiness.nextAction}`);
357
+ }
358
+ process.exitCode = 1;
359
+ return;
360
+ }
361
+
306
362
  // ── Resolve each executed agent from canonical config ──
307
363
  let resolvedRuntime: ResolvedRunRuleHostRuntime;
308
364
  try {
309
- resolvedRuntime = resolveRunRuleHostRuntime(workspaceDir, opts.timeoutMs);
365
+ resolvedRuntime = resolveRunRuleHostRuntime(workspaceDir, opts.timeoutMs, readiness);
310
366
  } catch (err) {
311
367
  const message = err instanceof Error ? err.message : String(err);
312
368
  if (opts.json) {
313
- process.stdout.write(JSON.stringify({ status: 'failed', reason: 'agent_runtime_resolution_failed', message, nextAction: 'check internalAgents and runtimeProfiles in .pd/config.yaml; run pd config doctor' }) + '\n');
369
+ process.stdout.write(JSON.stringify({ status: 'failed', reason: 'agent_runtime_resolution_failed', message, nextAction: 'check internalAgents and runtimeProfiles in .pd/config.yaml; run pd config doctor', readiness }) + '\n');
314
370
  } else {
315
371
  console.error(`Error: ${message}`);
316
372
  }
@@ -328,13 +384,19 @@ export async function handleRunRuleHost(opts: RunRuleHostOptions): Promise<void>
328
384
  painId: opts.painId,
329
385
  workspace: workspaceDir,
330
386
  channel,
387
+ readiness,
388
+ readinessStatus: readiness.status,
331
389
  capabilityStatus: resolvedRuntime.capabilityStatus,
332
390
  agentRuntimeProfiles: resolvedRuntime.agentRuntimeProfiles,
333
391
  codeRuleCapability: { enabled: resolvedRuntime.capability.enabled, disabledReason: resolvedRuntime.capability.disabledReason },
334
- nextAction: 'pass --confirm to actually run the pipeline',
392
+ nextAction: readiness.status === 'ready'
393
+ ? 'pass --confirm to run the full pipeline'
394
+ : readiness.status === 'text_principle_only'
395
+ ? 'pass --confirm to run in text-principle-only mode (code-rule capability OFF), or fix the issues above to enable full pipeline'
396
+ : 'fix the readiness issues above before running the pipeline',
335
397
  }) + '\n');
336
398
  } else {
337
- process.stdout.write(formatDryRunOutput(opts, resolvedRuntime.capabilityStatus, workspaceDir) + '\n');
399
+ process.stdout.write(formatDryRunOutput({ opts, capabilityStatus: resolvedRuntime.capabilityStatus, workspaceDir, readiness }) + '\n');
338
400
  }
339
401
  return;
340
402
  }