@principles/host-runtime 5.1.0 → 5.3.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 (56) hide show
  1. package/dist/advisory-delivery.d.ts +34 -0
  2. package/dist/advisory-delivery.js +69 -0
  3. package/dist/behavior-history.js +1 -1
  4. package/dist/cli-recovery-probe.d.ts +23 -2
  5. package/dist/cli-recovery-probe.js +98 -9
  6. package/dist/codex-ingestion-consent.d.ts +5 -6
  7. package/dist/codex-ingestion-consent.js +5 -6
  8. package/dist/codex-rule-context-provider.js +30 -7
  9. package/dist/conversation-ingestion/consent.d.ts +14 -31
  10. package/dist/conversation-ingestion/consent.js +14 -223
  11. package/dist/fact-assembler.d.ts +91 -0
  12. package/dist/fact-assembler.js +318 -0
  13. package/dist/forward-observation.d.ts +6 -0
  14. package/dist/forward-observation.js +2 -1
  15. package/dist/host-liveness-contract.js +12 -0
  16. package/dist/index.d.ts +11 -1
  17. package/dist/index.js +13 -32
  18. package/dist/internalization-consumer-cycle.js +1 -1
  19. package/dist/mode-state-facts.d.ts +41 -0
  20. package/dist/mode-state-facts.js +224 -0
  21. package/dist/pain-inbox.d.ts +28 -0
  22. package/dist/pain-inbox.js +194 -46
  23. package/dist/product-telemetry/consent-store.d.ts +9 -47
  24. package/dist/product-telemetry/consent-store.js +18 -131
  25. package/dist/production-pain-evidence.d.ts +9 -0
  26. package/dist/production-pain-evidence.js +22 -2
  27. package/dist/production-policy-gate.d.ts +104 -0
  28. package/dist/production-policy-gate.js +379 -0
  29. package/dist/production-rulehost-gate.d.ts +6 -0
  30. package/dist/production-rulehost-gate.js +160 -31
  31. package/dist/prompt-activation-event.d.ts +29 -0
  32. package/dist/prompt-activation-event.js +80 -0
  33. package/dist/prompt-injection-budget-observation.d.ts +0 -11
  34. package/dist/prompt-injection-budget-observation.js +0 -11
  35. package/dist/rule-policy-active.d.ts +80 -0
  36. package/dist/rule-policy-active.js +197 -0
  37. package/dist/rule-policy-host-defaults.d.ts +19 -0
  38. package/dist/rule-policy-host-defaults.js +12 -0
  39. package/dist/rule-policy-paths-fs.d.ts +20 -0
  40. package/dist/rule-policy-paths-fs.js +58 -0
  41. package/dist/rule-policy-replay-evidence.d.ts +52 -0
  42. package/dist/rule-policy-replay-evidence.js +259 -0
  43. package/dist/session-write-targets.d.ts +86 -0
  44. package/dist/session-write-targets.js +216 -0
  45. package/dist/signal-classifier.d.ts +1 -0
  46. package/dist/signal-classifier.js +1 -1
  47. package/dist/signal-rate-limiter.d.ts +34 -0
  48. package/dist/signal-rate-limiter.js +83 -0
  49. package/dist/trajectory-retention.d.ts +8 -0
  50. package/dist/trajectory-retention.js +29 -0
  51. package/dist/trusted-pd-binary.d.ts +10 -0
  52. package/dist/trusted-pd-binary.js +38 -0
  53. package/dist/workbuddy-rule-context-provider.js +31 -10
  54. package/dist/workspace-behavior-evidence.d.ts +55 -0
  55. package/dist/workspace-behavior-evidence.js +93 -0
  56. package/package.json +24 -4
@@ -5,6 +5,8 @@ import { classifyBashRisk } from '@principles/core/runtime/internalization/bash-
5
5
  import { recordDegradedEnforcement } from './degraded-enforcement-marker.js';
6
6
  import { createNodeRuleImplementationRuntime, MAX_ACTIVE_RULES, RULE_BATCH_SOURCE_BYTES, RULE_SOURCE_BYTES, } from './rule-implementation-runtime.js';
7
7
  import { resolveStateDbPath } from '@principles/core/runtime/storage-paths';
8
+ import { createPolicyRuntime, } from './production-policy-gate.js';
9
+ import { isPolicyArtifactContent, parseActivePolicy, policyModeOfAction, } from './rule-policy-active.js';
8
10
  const WARNING_LIMIT = 500;
9
11
  const MAX_WARNINGS = 16;
10
12
  const GATE_DEADLINE_MS = 3_000;
@@ -32,11 +34,23 @@ const ARTIFACT_CONTENT_BYTES = 512 * 1024;
32
34
  const AFFECTED_TOOLS_OBSERVABILITY_ENV = 'PD_AFFECTED_TOOLS_OBSERVABILITY';
33
35
  // Check the actual imported builder, not an installed-package version string:
34
36
  // a mixed host-runtime/core deployment must not claim input-v2 support.
37
+ // Capability self-check only: the arbitrary absolute path is trusted by the
38
+ // test input itself, proving this core/host-runtime pair can mark the mode
39
+ // grammar without ever trusting bare `pd`. It is not environment evidence.
40
+ const RECOVERY_CAPABILITY_PD = '/recovery-capability-probe/pd';
35
41
  const RECOVERY_INPUT_V2_AVAILABLE = RECOVERY_CONTROL_SURFACES
36
42
  .filter(surface => surface.channel === 'cli')
37
- .every(surface => typeof surface.cliCommand === 'string'
38
- && buildRuleHostAction('recovery-contract-probe', { command: surface.cliCommand }, '/', { canonicalKind: 'execute' })
39
- .recoveryControl === surface.capabilityId);
43
+ .every(surface => {
44
+ if (typeof surface.cliCommand !== 'string')
45
+ return false;
46
+ const command = surface.cliCommand.startsWith('pd mode ')
47
+ ? `${RECOVERY_CAPABILITY_PD}${surface.cliCommand.slice(2)}`
48
+ : surface.cliCommand;
49
+ return buildRuleHostAction('recovery-contract-probe', { command }, '/', {
50
+ canonicalKind: 'execute',
51
+ trustedPdBinaries: [RECOVERY_CAPABILITY_PD],
52
+ }).recoveryControl === surface.capabilityId;
53
+ });
40
54
  function boundedWarning(reason, nextAction) {
41
55
  return `${reason}; nextAction=${nextAction}`.replace(/\s+/g, ' ').slice(0, WARNING_LIMIT);
42
56
  }
@@ -149,6 +163,7 @@ export function createProductionRuleHostGate(options = {}) {
149
163
  const observabilityEnabled = options.affectedToolsObservability?.enabled
150
164
  ?? !affectedToolsObservabilityDisabledByEnv();
151
165
  const observabilitySink = options.affectedToolsObservability?.sink ?? defaultAffectedToolsSink;
166
+ const policyRuntime = createPolicyRuntime(options.rulePolicy, options.hostKind);
152
167
  /**
153
168
  * PRI-1187 observation-only: record that a declared scope did not cover the
154
169
  * action while the rule was still evaluated. MUST NOT skip, reorder, or
@@ -196,7 +211,15 @@ export function createProductionRuleHostGate(options = {}) {
196
211
  return { decision: 'allow', source: event.source, metadata: withFaults({ evaluatedLiveRules: 0 }, evaluationFaults) };
197
212
  }
198
213
  const { isBashTool: isBash, isWriteTool: isWrite } = deriveToolHintsFromCanonicalKind(canonicalKind);
199
- const action = buildRuleHostAction(input.toolName, input.params, options.projectDir ?? event.context.workspaceDir, { isBashTool: isBash, isWriteTool: isWrite, canonicalKind });
214
+ const writePayloadFormat = toolSemantics.resolveWritePayloadFormat(input.toolName);
215
+ const trustedPdBinaries = policyRuntime.trustedPdBinaries();
216
+ const action = buildRuleHostAction(input.toolName, input.params, options.projectDir ?? event.context.workspaceDir, {
217
+ isBashTool: isBash,
218
+ isWriteTool: isWrite,
219
+ canonicalKind,
220
+ ...(writePayloadFormat !== undefined ? { writePayloadFormat } : {}),
221
+ ...(trustedPdBinaries.length > 0 ? { trustedPdBinaries } : {}),
222
+ });
200
223
  // F3': normalizePathPure returns '' when no path could be extracted, so the
201
224
  // old `=== null` guard never fired. Both null and '' mean "no action
202
225
  // target": a pathless tool is not evaluated rather than treating an empty
@@ -286,6 +309,8 @@ export function createProductionRuleHostGate(options = {}) {
286
309
  }
287
310
  const connection = new SqliteConnection({ workspaceDir: event.context.workspaceDir, readonly: true, bootstrapIfMissing: false });
288
311
  const candidates = [];
312
+ // RulePolicyV2 candidates (live, shadow, challenger). Judged in-process; never sent to the RuleCode runtime.
313
+ const policyCandidates = [];
289
314
  try {
290
315
  const globalPause = connection.getDb().prepare(`
291
316
  SELECT pause_id FROM global_rulecode_pauses WHERE status = 'paused' LIMIT 1
@@ -338,12 +363,19 @@ export function createProductionRuleHostGate(options = {}) {
338
363
  EXISTS (SELECT 1 FROM approvals ap WHERE ap.artifact_id = a.artifact_id
339
364
  AND ap.channel = 'code_tool_hook' AND ap.status = 'approved') AS owner_approved,
340
365
  length(CAST(p.content_json AS BLOB)) AS content_bytes,
341
- (SELECT d.artifact_digest FROM activation_decisions d
342
- WHERE d.subject_kind = 'activation' AND d.activation_id = a.activation_id
343
- ORDER BY d.decided_at DESC, d.rowid DESC LIMIT 1) AS approved_artifact_digest
366
+ d.artifact_digest AS approved_artifact_digest,
367
+ d.enforcement_json AS enforcement_json
344
368
  FROM activations a
345
369
  JOIN pi_artifacts p ON a.artifact_id = p.artifact_id
346
370
  LEFT JOIN activation_control_states c ON a.activation_id = c.activation_id
371
+ LEFT JOIN activation_decisions d ON d.rowid = (
372
+ SELECT d2.rowid FROM activation_decisions d2
373
+ WHERE d2.subject_kind = 'activation'
374
+ AND d2.activation_id = a.activation_id
375
+ AND d2.principal_kind = 'configured_owner'
376
+ AND d2.decision IN ('promote_live', 'continue_observing', 'recover_to_shadow')
377
+ ORDER BY d2.decided_at DESC, d2.rowid DESC LIMIT 1
378
+ )
347
379
  WHERE a.channel = 'code_tool_hook' AND a.deactivated_at IS NULL
348
380
  ORDER BY a.activated_at ASC
349
381
  LIMIT ?
@@ -418,9 +450,8 @@ export function createProductionRuleHostGate(options = {}) {
418
450
  // collected as observations only and never join mergeDecisions
419
451
  // (shadow observes, never enforces). The v2 qualification and context
420
452
  // checks below remain ahead of evaluation for both activation modes.
421
- const activationMode = row.action === 'code_tool_hook_live_activate'
422
- ? 'live'
423
- : row.action === 'code_tool_hook_shadow_activate' ? 'shadow' : null;
453
+ // 'challenger' (RulePolicyV2 only) is judged and recorded like shadow but never joins a decision.
454
+ const activationMode = policyModeOfAction(row.action);
424
455
  if (activationMode === null)
425
456
  continue;
426
457
  const activationId = row.activation_id;
@@ -434,7 +465,7 @@ export function createProductionRuleHostGate(options = {}) {
434
465
  activationId,
435
466
  artifactId,
436
467
  ruleId: typeof row.source_rule_id === 'string' && row.source_rule_id.length > 0 ? row.source_rule_id : artifactId,
437
- mode: activationMode,
468
+ ...(activationMode === 'challenger' ? {} : { mode: activationMode }),
438
469
  };
439
470
  const contentRow = connection.getDb().prepare(`
440
471
  SELECT artifact_id, artifact_kind, source_task_id, source_principle_id, source_rule_id,
@@ -456,7 +487,7 @@ export function createProductionRuleHostGate(options = {}) {
456
487
  // the shadow observation — pre-PRI-813 this return was unreachable
457
488
  // for shadow rows, and letting it fire now would suppress live
458
489
  // enforcement (shadow may never influence the live outcome).
459
- if (activationMode === 'shadow') {
490
+ if (activationMode !== 'live') {
460
491
  addWarning(warnings, `artifact_content_budget_exceeded: activation=${activationId} bytes=${Math.max(contentRow.content_bytes, returnedContentBytes)} maximum=${ARTIFACT_CONTENT_BYTES}`, 'reduce the active shadow artifact envelope and reactivate the rule; live enforcement is unaffected');
461
492
  addFault(evaluationFaults, 'skipped', faultSource, `artifact_content_budget_exceeded: activation=${activationId}`, 'reduce the active shadow artifact envelope and reactivate the rule');
462
493
  continue;
@@ -464,7 +495,7 @@ export function createProductionRuleHostGate(options = {}) {
464
495
  return { decision: 'allow', source: event.source, warnings: [boundedWarning(`artifact_content_budget_exceeded: activation=${activationId} bytes=${Math.max(contentRow.content_bytes, returnedContentBytes)} maximum=${ARTIFACT_CONTENT_BYTES}`, 'reduce the active artifact envelope and reactivate the rule')], metadata: withFaults({ evaluatedLiveRules: 0 }, evaluationFaults) };
465
496
  }
466
497
  if (contentRow.content_bytes !== expectedContentBytes || returnedContentBytes !== contentRow.content_bytes) {
467
- if (activationMode === 'shadow') {
498
+ if (activationMode !== 'live') {
468
499
  addWarning(warnings, `artifact_content_size_changed: activation=${activationId}`, 'retry after the active shadow artifact update completes; live enforcement is unaffected');
469
500
  addFault(evaluationFaults, 'skipped', faultSource, `artifact_content_size_changed: activation=${activationId}`, 'retry after the active shadow artifact update completes');
470
501
  continue;
@@ -493,7 +524,7 @@ export function createProductionRuleHostGate(options = {}) {
493
524
  }
494
525
  if (digestCheck.outcome === 'tampered') {
495
526
  const digestNextAction = 'the artifact content no longer matches the Owner-approved digest — deactivate and re-approve the rule; execution was skipped';
496
- if (activationMode === 'shadow') {
527
+ if (activationMode !== 'live') {
497
528
  addWarning(warnings, `artifact_digest_mismatch (shadow): activation=${activationId}`, `${digestNextAction}; live enforcement is unaffected`);
498
529
  addFault(evaluationFaults, 'skipped', faultSource, `artifact_digest_mismatch (shadow): activation=${activationId}`, digestNextAction);
499
530
  continue;
@@ -504,6 +535,30 @@ export function createProductionRuleHostGate(options = {}) {
504
535
  }
505
536
  try {
506
537
  const content = JSON.parse(contentJson);
538
+ // RulePolicyV2 (SPEC-PD-RULE-POLICY-001 design §13): validated here, judged in-process below.
539
+ // A policy artifact is only ever enforced when its Owner-approved digest binding verified.
540
+ if (isPolicyArtifactContent(content)) {
541
+ if (digestCheck.outcome !== 'verified') {
542
+ const reason = `policy_digest_unbound: activation=${activationId}`;
543
+ const nextAction = 'the rule policy has no Owner-approved digest binding; approve the rule through the Owner decision flow; the policy was not evaluated';
544
+ addWarning(warnings, reason, nextAction);
545
+ addFault(evaluationFaults, 'skipped', faultSource, reason, nextAction);
546
+ continue;
547
+ }
548
+ const parsedPolicy = parseActivePolicy({ activationId, artifactId, sourceRuleId: typeof row.source_rule_id === 'string' && row.source_rule_id.length > 0 ? row.source_rule_id : null, mode: activationMode }, content, row.enforcement_json);
549
+ if (!parsedPolicy.ok) {
550
+ addWarning(warnings, `${parsedPolicy.fault.reason} (activation=${activationId})`, parsedPolicy.fault.nextAction);
551
+ addFault(evaluationFaults, 'skipped', faultSource, parsedPolicy.fault.reason, parsedPolicy.fault.nextAction);
552
+ continue;
553
+ }
554
+ policyCandidates.push(parsedPolicy.active);
555
+ continue;
556
+ }
557
+ if (activationMode === 'challenger') {
558
+ addWarning(warnings, `challenger_requires_rule_policy: ${activationId}`, 'only a RulePolicyV2 can be armed as a challenger; deactivate this activation');
559
+ addFault(evaluationFaults, 'skipped', faultSource, `challenger_requires_rule_policy: ${activationId}`, 'only a RulePolicyV2 can be armed as a challenger; deactivate this activation');
560
+ continue;
561
+ }
507
562
  if (!isRecord(content) || typeof content.implementationCode !== 'string' || content.implementationCode.length === 0) {
508
563
  addWarning(warnings, `activation_artifact_invalid: ${activationId}`, 'regenerate the rule artifact with implementationCode');
509
564
  addFault(evaluationFaults, 'skipped', faultSource, `activation_artifact_invalid: ${activationId}`, 'regenerate the rule artifact with implementationCode');
@@ -671,22 +726,38 @@ export function createProductionRuleHostGate(options = {}) {
671
726
  const liveCandidates = candidates.filter((candidate) => candidate.activationMode === 'live');
672
727
  const shadowCandidates = candidates.filter((candidate) => candidate.activationMode === 'shadow');
673
728
  const liveBatchBytes = liveCandidates.reduce((sum, candidate) => sum + Buffer.byteLength(candidate.source, 'utf8'), 0);
729
+ let liveRuleCodeSkipped = false;
730
+ let liveBatch = { ok: true, results: [] };
731
+ let remaining = remainingGateMs(startedAt);
674
732
  if (liveBatchBytes > RULE_BATCH_SOURCE_BYTES) {
675
- return { decision: 'allow', source: event.source, warnings: [boundedWarning(`rule_source_budget_exceeded: batchBytes=${liveBatchBytes}`, `reduce total active RuleCode below ${RULE_BATCH_SOURCE_BYTES} bytes`)], metadata: withFaults({ evaluatedLiveRules: 0, evaluationStatus: 'failed' }, evaluationFaults) };
733
+ if (policyCandidates.length === 0) {
734
+ return { decision: 'allow', source: event.source, warnings: [boundedWarning(`rule_source_budget_exceeded: batchBytes=${liveBatchBytes}`, `reduce total active RuleCode below ${RULE_BATCH_SOURCE_BYTES} bytes`)], metadata: withFaults({ evaluatedLiveRules: 0, evaluationStatus: 'failed' }, evaluationFaults) };
735
+ }
736
+ addWarning(warnings, `rule_source_budget_exceeded: batchBytes=${liveBatchBytes}`, `reduce total active RuleCode below ${RULE_BATCH_SOURCE_BYTES} bytes; live RuleCode was skipped while RulePolicyV2 still evaluated`);
737
+ liveRuleCodeSkipped = true;
676
738
  }
677
- let remaining = remainingGateMs(startedAt);
678
- if (remaining <= 0) {
739
+ else if (remaining <= 0) {
679
740
  return { decision: 'allow', source: event.source, warnings: [boundedWarning('gate_deadline_exceeded', 'reduce active RuleCode count or source size and retry')], metadata: withFaults({ evaluatedLiveRules: 0, evaluationStatus: 'failed' }, evaluationFaults) };
680
741
  }
681
- const liveBatch = liveCandidates.length === 0
682
- ? { ok: true, results: [] }
683
- : implementationRuntime.evaluateBatch(liveCandidates.map((candidate) => ({ source: candidate.source, filename: `activation-${candidate.implId}` })), hostInput, remaining);
684
- if (!liveBatch.ok || !liveBatch.results) {
685
- return { decision: 'allow', source: event.source, warnings: [boundedWarning(`${liveBatch.reason ?? 'rule_batch_failed'}: ${liveBatch.detail ?? 'unknown failure'}`, 'inspect active RuleCode resource use and repair or deactivate the unhealthy rule')], metadata: withFaults({ evaluatedLiveRules: 0, evaluationStatus: 'failed' }, evaluationFaults) };
686
- }
687
- const timedOutChild = liveBatch.results.find((candidate) => !candidate.ok && candidate.error?.includes('timed out'));
688
- if (timedOutChild) {
689
- return { decision: 'allow', source: event.source, warnings: [boundedWarning(`rule_batch_timeout: ${timedOutChild.error ?? 'unknown child timeout'}`, 'fix or deactivate the unhealthy RuleCode and retry')], metadata: withFaults({ evaluatedLiveRules: 0, evaluationStatus: 'failed' }, evaluationFaults) };
742
+ else if (liveCandidates.length > 0) {
743
+ liveBatch = implementationRuntime.evaluateBatch(liveCandidates.map((candidate) => ({ source: candidate.source, filename: `activation-${candidate.implId}` })), hostInput, remaining);
744
+ if (!liveBatch.ok || !liveBatch.results) {
745
+ if (policyCandidates.length === 0) {
746
+ return { decision: 'allow', source: event.source, warnings: [boundedWarning(`${liveBatch.reason ?? 'rule_batch_failed'}: ${liveBatch.detail ?? 'unknown failure'}`, 'inspect active RuleCode resource use and repair or deactivate the unhealthy rule')], metadata: withFaults({ evaluatedLiveRules: 0, evaluationStatus: 'failed' }, evaluationFaults) };
747
+ }
748
+ addWarning(warnings, `${liveBatch.reason ?? 'rule_batch_failed'}: ${liveBatch.detail ?? 'unknown failure'}`, 'inspect active RuleCode resource use and repair or deactivate the unhealthy rule; live RuleCode was skipped while RulePolicyV2 still evaluated');
749
+ liveRuleCodeSkipped = true;
750
+ }
751
+ else {
752
+ const timedOutChild = liveBatch.results.find((candidate) => !candidate.ok && candidate.error?.includes('timed out'));
753
+ if (timedOutChild) {
754
+ if (policyCandidates.length === 0) {
755
+ return { decision: 'allow', source: event.source, warnings: [boundedWarning(`rule_batch_timeout: ${timedOutChild.error ?? 'unknown child timeout'}`, 'fix or deactivate the unhealthy RuleCode and retry')], metadata: withFaults({ evaluatedLiveRules: 0, evaluationStatus: 'failed' }, evaluationFaults) };
756
+ }
757
+ addWarning(warnings, `rule_batch_timeout: ${timedOutChild.error ?? 'unknown child timeout'}`, 'fix or deactivate the unhealthy RuleCode and retry; live RuleCode was skipped while RulePolicyV2 still evaluated');
758
+ liveRuleCodeSkipped = true;
759
+ }
760
+ }
690
761
  }
691
762
  // PRI-813: one canonical evaluation fact per shadow activation —
692
763
  // observations only. Shadow results never join mergeDecisions, never
@@ -756,11 +827,50 @@ export function createProductionRuleHostGate(options = {}) {
756
827
  }
757
828
  }
758
829
  }
830
+ // RulePolicyV2: judged in-process with ONE fact assembly for all candidates. Live verdicts join
831
+ // the merge below; shadow verdicts are telemetry only; challenger verdicts are ledger-only.
832
+ // A policy problem is a warning and an observation, never a thrown error: it must not take the
833
+ // RuleCode path down with it.
834
+ let policyRun;
835
+ if (policyCandidates.length > 0) {
836
+ policyRun = policyRuntime.evaluate({
837
+ candidates: policyCandidates,
838
+ hostInput,
839
+ context,
840
+ governanceDb: connection,
841
+ workspaceDir: event.context.workspaceDir,
842
+ sessionId: event.context.sessionId,
843
+ ...(event.context.toolCallId !== undefined ? { toolCallId: event.context.toolCallId } : {}),
844
+ projectRoot: options.projectDir ?? event.context.workspaceDir,
845
+ toolName: input.toolName,
846
+ canonicalKind,
847
+ bashRisk: enrichment.bashRisk,
848
+ toolSemantics,
849
+ startedAt,
850
+ });
851
+ for (const warning of policyRun.warnings)
852
+ addWarning(warnings, warning.reason, warning.nextAction);
853
+ for (const outcome of policyRun.outcomes) {
854
+ if (outcome.active.mode !== 'shadow')
855
+ continue;
856
+ shadowEvaluations.push({
857
+ toolName: input.toolName,
858
+ filePath: action.normalizedPath,
859
+ matched: outcome.result.matched,
860
+ decision: outcome.result.decision,
861
+ ruleId: outcome.active.ruleId,
862
+ activationId: outcome.active.activationId,
863
+ activationMode: 'shadow',
864
+ ...(options.hostKind !== undefined ? { hostKind: options.hostKind } : {}),
865
+ });
866
+ }
867
+ }
868
+ const livePolicyOutcomes = (policyRun?.outcomes ?? []).filter((outcome) => outcome.active.mode === 'live');
759
869
  const implementations = [];
760
870
  const liveEvaluatedResults = [];
761
- for (let index = 0; index < liveCandidates.length; index += 1) {
871
+ for (let index = 0; !liveRuleCodeSkipped && index < liveCandidates.length; index += 1) {
762
872
  const candidate = liveCandidates[index];
763
- const batchResult = liveBatch.results[index];
873
+ const batchResult = liveBatch.results?.[index];
764
874
  if (!candidate || !batchResult) {
765
875
  addWarning(warnings, 'rule_batch_result_missing', 'inspect the RuleCode runtime result contract');
766
876
  continue;
@@ -793,6 +903,15 @@ export function createProductionRuleHostGate(options = {}) {
793
903
  liveEvaluatedResults.push(validatedResult);
794
904
  emitAffectedToolsMismatch(candidate, { decision: validatedResult.decision, actionFamily: canonicalKind, toolName: input.toolName });
795
905
  }
906
+ for (const { active, result: policyResult } of livePolicyOutcomes) {
907
+ implementations.push({
908
+ implId: active.activationId,
909
+ ruleId: active.ruleId,
910
+ meta: { name: active.activationId, version: '2', ruleId: active.ruleId, coversCondition: 'all' },
911
+ evaluate: () => policyResult,
912
+ });
913
+ liveEvaluatedResults.push(policyResult);
914
+ }
796
915
  const result = mergeDecisions(implementations, hostInput, {
797
916
  warn(message) { addWarning(warnings, message, 'inspect the unhealthy activation and RuleCode output'); },
798
917
  });
@@ -817,7 +936,7 @@ export function createProductionRuleHostGate(options = {}) {
817
936
  // not a live 'allow' — enforcement statistics must not read as if a
818
937
  // live rule evaluated (the legacy writer already distinguishes
819
938
  // this; the shared path now aligns).
820
- decision: liveCandidates.length === 0 ? 'no_rules_armed' : result?.decision ?? 'allow',
939
+ decision: liveCandidates.length + livePolicyOutcomes.length === 0 ? 'no_rules_armed' : result?.decision ?? 'allow',
821
940
  ...(result?.ruleId !== undefined ? { ruleId: result.ruleId } : {}),
822
941
  ...(liveActivationId !== undefined ? { activationId: liveActivationId } : {}),
823
942
  activationMode: 'live',
@@ -825,12 +944,19 @@ export function createProductionRuleHostGate(options = {}) {
825
944
  },
826
945
  ...shadowEvaluations,
827
946
  ];
947
+ // Policy facts for host adapters: policyEvaluated marks a verdict that came from a RulePolicyV2 (a block whose
948
+ // winner is a policy, or an allow while at least one live policy was judged); observations are bounded and host-neutral.
949
+ const policyWon = result !== undefined && isRecord(result.diagnostics) && result.diagnostics.policyEvaluated === true;
950
+ const policyMetadata = {
951
+ ...((result?.decision === 'block' ? policyWon : livePolicyOutcomes.length > 0) ? { policyEvaluated: true } : {}),
952
+ ...(policyRun !== undefined && policyRun.observations.length > 0 ? { policyObservations: policyRun.observations } : {}),
953
+ };
828
954
  if (result?.decision === 'block') {
829
955
  if (result.reason.trim().length === 0) {
830
956
  addWarning(warnings, 'deny_reason_missing', 'fix the RuleCode to return a non-empty block reason');
831
- return { decision: 'allow', source: event.source, warnings, metadata: withFaults({ evaluatedLiveRules: implementations.length, evaluations }, evaluationFaults) };
957
+ return { decision: 'allow', source: event.source, warnings, metadata: withFaults({ evaluatedLiveRules: implementations.length, evaluations, ...policyMetadata }, evaluationFaults) };
832
958
  }
833
- return { decision: 'deny', reason: result.reason, source: event.source, ...(warnings.length ? { warnings } : {}), metadata: withFaults({ evaluatedLiveRules: implementations.length, ruleId: result.ruleId, principleId: result.principleId, evaluations }, evaluationFaults) };
959
+ return { decision: 'deny', reason: result.reason, source: event.source, ...(warnings.length ? { warnings } : {}), metadata: withFaults({ evaluatedLiveRules: implementations.length, ruleId: result.ruleId, principleId: result.principleId, evaluations, ...policyMetadata }, evaluationFaults) };
834
960
  }
835
961
  // Task 1 (legacy fallback convergence): a non-block verdict now carries
836
962
  // the facts the OpenClaw adapter needs to record/apply it WITHOUT a
@@ -851,6 +977,9 @@ export function createProductionRuleHostGate(options = {}) {
851
977
  ...(result?.reason !== undefined ? { ruleReason: result.reason } : {}),
852
978
  ...(result !== undefined && result.correctionProposal !== undefined ? { correctionProposal: result.correctionProposal } : {}),
853
979
  evaluations,
980
+ ...policyMetadata,
981
+ // Reminder text of the LIVE policies only (shadow and challenger never reach here; v1 code rules' advisory is not collected).
982
+ ...(policyRun?.advisory !== undefined ? { advisory: policyRun.advisory, advisoryRuleIds: [...policyRun.advisoryRuleIds] } : {}),
854
983
  }, evaluationFaults),
855
984
  };
856
985
  }
@@ -0,0 +1,29 @@
1
+ import type { HostEventEmitter } from '@principles/core/host';
2
+ import type { ActivePrinciplePromptResult } from './active-principle-prompt.js';
3
+ type RuntimePromptActivationsInjectedEventData = Parameters<HostEventEmitter['recordRuntimeActivationsInjected']>[0];
4
+ export interface BuildRuntimeActivationsInjectedEventInput {
5
+ prompt: ActivePrinciplePromptResult;
6
+ workspaceDir: string;
7
+ sessionId: string;
8
+ hostKind?: 'openclaw' | 'codex' | 'workbuddy';
9
+ runId?: string;
10
+ hookInvocationId?: string;
11
+ eventId?: string;
12
+ injectedCount?: number;
13
+ injectedCharCount?: number;
14
+ skippedWarnings?: string[];
15
+ /** Round provenance is opt-in; the shared emitter did not record it. */
16
+ selectionRoundOrdinal?: number;
17
+ selectionRoundSource?: 'session_user_turn_ordinal';
18
+ selectionOverrides?: {
19
+ selectionPolicy?: ActivePrinciplePromptResult['selectionPolicy'];
20
+ eligibleCount?: number;
21
+ rotationStartIndex?: number;
22
+ selectionRoundOrdinal?: number;
23
+ droppedActivationIds?: string[];
24
+ oversizedActivationIds?: string[];
25
+ };
26
+ includeEmptySkipReason?: boolean;
27
+ }
28
+ export declare function buildRuntimeActivationsInjectedEvent(input: BuildRuntimeActivationsInjectedEventInput): RuntimePromptActivationsInjectedEventData;
29
+ export {};
@@ -0,0 +1,80 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ export function buildRuntimeActivationsInjectedEvent(input) {
3
+ const { prompt } = input;
4
+ const injectedCount = input.injectedCount ?? prompt.principleIds.length;
5
+ const selection = {
6
+ selectionPolicy: prompt.selectionPolicy,
7
+ eligibleCount: prompt.eligibleCount,
8
+ rotationStartIndex: prompt.rotationStartIndex,
9
+ selectionRoundOrdinal: input.selectionRoundOrdinal,
10
+ droppedActivationIds: prompt.droppedActivationIds,
11
+ oversizedActivationIds: prompt.oversizedActivationIds,
12
+ };
13
+ if (input.selectionOverrides) {
14
+ const overrides = input.selectionOverrides;
15
+ if (Object.hasOwn(overrides, 'selectionPolicy'))
16
+ selection.selectionPolicy = overrides.selectionPolicy;
17
+ if (Object.hasOwn(overrides, 'eligibleCount'))
18
+ selection.eligibleCount = overrides.eligibleCount;
19
+ if (Object.hasOwn(overrides, 'rotationStartIndex'))
20
+ selection.rotationStartIndex = overrides.rotationStartIndex;
21
+ if (Object.hasOwn(overrides, 'selectionRoundOrdinal'))
22
+ selection.selectionRoundOrdinal = overrides.selectionRoundOrdinal;
23
+ if (Object.hasOwn(overrides, 'droppedActivationIds'))
24
+ selection.droppedActivationIds = overrides.droppedActivationIds;
25
+ if (Object.hasOwn(overrides, 'oversizedActivationIds'))
26
+ selection.oversizedActivationIds = overrides.oversizedActivationIds;
27
+ }
28
+ const event = {
29
+ eventId: input.eventId ?? randomUUID(),
30
+ sessionId: input.sessionId,
31
+ workspaceDir: input.workspaceDir,
32
+ principleIds: prompt.principleIds,
33
+ activationIds: prompt.activationIds,
34
+ artifactIds: prompt.artifactIds,
35
+ injectedCount,
36
+ skippedWarnings: input.skippedWarnings ?? prompt.warnings,
37
+ injectedCharCount: input.injectedCharCount ?? prompt.additionalContext.length,
38
+ budget: prompt.budget,
39
+ };
40
+ if (input.hostKind !== undefined)
41
+ event.hostKind = input.hostKind;
42
+ if (input.runId !== undefined)
43
+ event.runId = input.runId;
44
+ if (input.hookInvocationId !== undefined)
45
+ event.hookInvocationId = input.hookInvocationId;
46
+ if (prompt.truncated !== undefined)
47
+ event.v2Truncated = prompt.truncated;
48
+ if (selection.selectionPolicy !== undefined)
49
+ event.selectionPolicy = selection.selectionPolicy;
50
+ if (selection.eligibleCount !== undefined)
51
+ event.eligibleCount = selection.eligibleCount;
52
+ if (selection.rotationStartIndex !== undefined)
53
+ event.rotationStartIndex = selection.rotationStartIndex;
54
+ if (selection.selectionRoundOrdinal !== undefined) {
55
+ event.selectionRoundOrdinal = selection.selectionRoundOrdinal;
56
+ if (input.selectionRoundSource !== undefined)
57
+ event.selectionRoundSource = input.selectionRoundSource;
58
+ }
59
+ if (selection.droppedActivationIds !== undefined && selection.droppedActivationIds.length > 0) {
60
+ event.droppedActivationIds = selection.droppedActivationIds;
61
+ }
62
+ if (selection.oversizedActivationIds !== undefined && selection.oversizedActivationIds.length > 0) {
63
+ event.oversizedActivationIds = selection.oversizedActivationIds;
64
+ }
65
+ if (prompt.budgetPolicyVersion !== undefined)
66
+ event.budgetPolicyVersion = prompt.budgetPolicyVersion;
67
+ if (prompt.budgetCapacitySource !== undefined)
68
+ event.budgetCapacitySource = prompt.budgetCapacitySource;
69
+ if (prompt.budgetCapacityStatus !== undefined)
70
+ event.budgetCapacityStatus = prompt.budgetCapacityStatus;
71
+ if (prompt.budgetContextWindowTokens != null)
72
+ event.budgetContextWindowTokens = prompt.budgetContextWindowTokens;
73
+ if (prompt.budgetFallbackReason !== undefined)
74
+ event.budgetFallbackReason = prompt.budgetFallbackReason;
75
+ if (input.includeEmptySkipReason === true && injectedCount === 0) {
76
+ event.skipReason = 'no_validated_activations';
77
+ event.nextAction = 'check activations table for prompt channel rows with validated artifacts';
78
+ }
79
+ return event;
80
+ }
@@ -43,17 +43,6 @@ import { type PromptInjectionTargetHost } from './prompt-injection-projection.js
43
43
  * code ever created `.pd/logs`).
44
44
  */
45
45
  export declare const RUNTIME_EVENT_LOG_CANDIDATE_DIRS: readonly string[];
46
- /**
47
- * @deprecated Use `RUNTIME_EVENT_LOG_CANDIDATE_DIRS`.
48
- *
49
- * PRI-1136 renamed this exported constant, and `src/index.ts` re-exports it
50
- * through `export *`, so it is part of the package's public root API. Removing
51
- * the old name in a patch release would break external consumers that
52
- * `import { RUNTIME_V2_EVENT_LOG_CANDIDATE_DIRS } from '@principles/host-runtime'`.
53
- * The alias is the exact same frozen array (not a copy) and will be removed in
54
- * the next major release.
55
- */
56
- export declare const RUNTIME_V2_EVENT_LOG_CANDIDATE_DIRS: readonly string[];
57
46
  /**
58
47
  * Bounded I/O: only the most recent daily files are scanned — PER candidate
59
48
  * log directory (`RUNTIME_EVENT_LOG_CANDIDATE_DIRS`), not globally. The
@@ -76,17 +76,6 @@ function isAcceptedBudgetPolicyVersion(value) {
76
76
  * code ever created `.pd/logs`).
77
77
  */
78
78
  export const RUNTIME_EVENT_LOG_CANDIDATE_DIRS = ['.pd/logs', '.state/logs'];
79
- /**
80
- * @deprecated Use `RUNTIME_EVENT_LOG_CANDIDATE_DIRS`.
81
- *
82
- * PRI-1136 renamed this exported constant, and `src/index.ts` re-exports it
83
- * through `export *`, so it is part of the package's public root API. Removing
84
- * the old name in a patch release would break external consumers that
85
- * `import { RUNTIME_V2_EVENT_LOG_CANDIDATE_DIRS } from '@principles/host-runtime'`.
86
- * The alias is the exact same frozen array (not a copy) and will be removed in
87
- * the next major release.
88
- */
89
- export const RUNTIME_V2_EVENT_LOG_CANDIDATE_DIRS = RUNTIME_EVENT_LOG_CANDIDATE_DIRS;
90
79
  /**
91
80
  * Bounded I/O: only the most recent daily files are scanned — PER candidate
92
81
  * log directory (`RUNTIME_EVENT_LOG_CANDIDATE_DIRS`), not globally. The
@@ -0,0 +1,80 @@
1
+ /**
2
+ * Active RulePolicyV2 rules of a governance workspace (SPEC-PD-RULE-POLICY-001
3
+ * Requirement 10.13, 10.14; design.md §13).
4
+ *
5
+ * Two consumers share one reading of "what is an active policy":
6
+ * - the RuleHost gate (`production-rulehost-gate.ts`) decides each tool call with them;
7
+ * - `pd mode declare | waive` (pd-cli) asks which follow-up questions the rules attach to
8
+ * each act and which rule accepts a waiver.
9
+ *
10
+ * `parseActivePolicy` is the single judgement of one artifact: untrusted `content_json`
11
+ * (rc-1, rc-2) is validated by core's `validateRulePolicyV2`, the artifact's catalog versions
12
+ * are checked against this build, and the Owner's `PolicyEnforcement` is read from the
13
+ * activation decision, never from the artifact (design D7). A rejected artifact returns a
14
+ * structured fault (reason + nextAction); nothing is silently skipped (rc-9).
15
+ *
16
+ * `loadActivePolicies` reads read-only. It applies the same enforcement-time conditions the
17
+ * gate applies to a policy row (eligible control state, approved digest still matching);
18
+ * rows the gate would not enforce are returned as faults, not as active policies.
19
+ */
20
+ import { type SqliteConnection } from '@principles/core/runtime';
21
+ import { type PolicyEnforcement, type RulePolicyV2 } from '@principles/core/runtime/internalization/rule-policy-gate';
22
+ export type PolicyMode = 'live' | 'shadow' | 'challenger';
23
+ /** `activations.action` values that arm a rule policy, and the mode each one stands for. */
24
+ export declare const POLICY_ACTIVATION_ACTIONS: Readonly<{
25
+ readonly code_tool_hook_live_activate: 'live';
26
+ readonly code_tool_hook_shadow_activate: 'shadow';
27
+ readonly code_tool_hook_challenger_activate: 'challenger';
28
+ }>;
29
+ export declare function policyModeOfAction(action: unknown): PolicyMode | null;
30
+ export interface ActivePolicy {
31
+ readonly activationId: string;
32
+ readonly artifactId: string;
33
+ /** The id waivers, reminders and the ledger use for this rule. */
34
+ readonly ruleId: string;
35
+ /** First artifact id of the rule's version chain; the artifact id itself when the artifact names none. */
36
+ readonly ruleLineageId: string;
37
+ readonly mode: PolicyMode;
38
+ readonly policy: RulePolicyV2;
39
+ /** The Owner's decision, from the activation decision record. */
40
+ readonly enforcement: PolicyEnforcement;
41
+ }
42
+ export interface PolicyLoadFault {
43
+ readonly reason: string;
44
+ readonly nextAction: string;
45
+ }
46
+ export type PolicyParseResult = {
47
+ readonly ok: true;
48
+ readonly active: ActivePolicy;
49
+ } | {
50
+ readonly ok: false;
51
+ readonly fault: PolicyLoadFault;
52
+ };
53
+ export interface PolicyArtifactRef {
54
+ readonly activationId: string;
55
+ readonly artifactId: string;
56
+ /** `pi_artifacts.source_rule_id`, when set. */
57
+ readonly sourceRuleId: string | null;
58
+ readonly mode: PolicyMode;
59
+ }
60
+ /** An artifact is a policy candidate when `content_json.rulePolicy` is an object with `version === 2`. */
61
+ export declare function isPolicyArtifactContent(content: unknown): content is Record<string, unknown>;
62
+ /**
63
+ * Judge one policy artifact. `content` must already satisfy `isPolicyArtifactContent` and have
64
+ * passed the digest check. A catalog or act registry version above this build's is refused
65
+ * (`catalog_version_unsupported`); a lower one is accepted because facts and acts only grow.
66
+ */
67
+ export declare function parseActivePolicy(ref: PolicyArtifactRef, content: Record<string, unknown>, enforcementJson: unknown): PolicyParseResult;
68
+ export interface ActivePolicyLoad {
69
+ readonly active: readonly ActivePolicy[];
70
+ /** Rows that look like policies but would not be enforced, with the reason. */
71
+ readonly faults: readonly (PolicyLoadFault & {
72
+ readonly activationId: string;
73
+ })[];
74
+ }
75
+ /**
76
+ * Active rule policies (live, shadow and challenger) of the governance workspace behind
77
+ * `connection`. Throws when the activation tables cannot be read: the caller must treat that as
78
+ * "unknown", never as "no policies".
79
+ */
80
+ export declare function loadActivePolicies(connection: SqliteConnection): ActivePolicyLoad;