create-principles-disciple 1.152.0 → 1.152.1

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 (128) hide show
  1. package/_release/product-identity.json +1 -1
  2. package/codex-adapter/dist/tool-semantics.d.ts +11 -1
  3. package/codex-adapter/dist/tool-semantics.js +11 -1
  4. package/codex-adapter/package.json +1 -1
  5. package/console/dist/server/index.js +5 -0
  6. package/console/dist/server/models/EvidenceChainConsoleModel.js +1 -2
  7. package/console/dist/server/models/GovernanceConsoleModel.js +56 -68
  8. package/console/dist/server/models/RuleCandidateBindingConsoleModel.js +31 -31
  9. package/console/dist/server/routes/update.js +45 -30
  10. package/console/dist/server/update-timeout.js +15 -1
  11. package/console/dist/shared/rule-candidate-binding-contract.d.ts +4 -1
  12. package/console/dist/web/assets/app.js +26 -26
  13. package/core/dist/runtime/candidate-audit.d.ts.map +1 -1
  14. package/core/dist/runtime/candidate-audit.js +6 -3
  15. package/core/dist/runtime/candidate-audit.js.map +1 -1
  16. package/core/dist/runtime/golden-trace.d.ts.map +1 -1
  17. package/core/dist/runtime/golden-trace.js +30 -24
  18. package/core/dist/runtime/golden-trace.js.map +1 -1
  19. package/core/dist/runtime/internalization/refiner-sandbox-wrapper.d.ts.map +1 -1
  20. package/core/dist/runtime/internalization/refiner-sandbox-wrapper.js +4 -4
  21. package/core/dist/runtime/internalization/refiner-sandbox-wrapper.js.map +1 -1
  22. package/core/dist/runtime/internalization/rule-host-input-builder.d.ts +21 -1
  23. package/core/dist/runtime/internalization/rule-host-input-builder.d.ts.map +1 -1
  24. package/core/dist/runtime/internalization/rule-host-input-builder.js +13 -0
  25. package/core/dist/runtime/internalization/rule-host-input-builder.js.map +1 -1
  26. package/core/dist/runtime/internalization-chain-integrity-read-model.d.ts +1 -0
  27. package/core/dist/runtime/internalization-chain-integrity-read-model.d.ts.map +1 -1
  28. package/core/dist/runtime/internalization-chain-integrity-read-model.js +8 -5
  29. package/core/dist/runtime/internalization-chain-integrity-read-model.js.map +1 -1
  30. package/core/dist/runtime/pruning-read-model.d.ts.map +1 -1
  31. package/core/dist/runtime/pruning-read-model.js +7 -5
  32. package/core/dist/runtime/pruning-read-model.js.map +1 -1
  33. package/core/dist/runtime/schema-conformance-read-model.d.ts +1 -0
  34. package/core/dist/runtime/schema-conformance-read-model.d.ts.map +1 -1
  35. package/core/dist/runtime/schema-conformance-read-model.js +8 -5
  36. package/core/dist/runtime/schema-conformance-read-model.js.map +1 -1
  37. package/core/dist/trajectory-store.d.ts +17 -1
  38. package/core/dist/trajectory-store.d.ts.map +1 -1
  39. package/core/dist/trajectory-store.js +32 -10
  40. package/core/dist/trajectory-store.js.map +1 -1
  41. package/core/package.json +1 -1
  42. package/dist/installer.d.ts +18 -0
  43. package/dist/installer.d.ts.map +1 -1
  44. package/dist/installer.js +24 -0
  45. package/dist/installer.js.map +1 -1
  46. package/dist/installers/legacy-workbuddy-skill.d.ts +46 -14
  47. package/dist/installers/legacy-workbuddy-skill.d.ts.map +1 -1
  48. package/dist/installers/legacy-workbuddy-skill.js +162 -29
  49. package/dist/installers/legacy-workbuddy-skill.js.map +1 -1
  50. package/dist/installers/workbuddy-host-installer.d.ts.map +1 -1
  51. package/dist/installers/workbuddy-host-installer.js +7 -6
  52. package/dist/installers/workbuddy-host-installer.js.map +1 -1
  53. package/host-runtime/dist/active-principle-prompt.js +2 -2
  54. package/host-runtime/dist/governance-observation-store.js +2 -2
  55. package/host-runtime/dist/governance-signal-admission.js +2 -1
  56. package/host-runtime/dist/host-liveness-contract.js +2 -2
  57. package/host-runtime/dist/product-telemetry/milestone-readers.js +3 -2
  58. package/host-runtime/dist/production-pain-evidence.js +3 -2
  59. package/host-runtime/dist/production-rulehost-gate.d.ts +20 -0
  60. package/host-runtime/dist/production-rulehost-gate.js +110 -35
  61. package/host-runtime/dist/prompt-activation-deliverability.js +3 -3
  62. package/host-runtime/dist/prompt-injection-status.js +2 -2
  63. package/host-runtime/dist/workspace-behavior-evidence.js +4 -3
  64. package/host-runtime/package.json +5 -1
  65. package/package.json +2 -2
  66. package/pd-cli/dist/commands/candidate.d.ts.map +1 -1
  67. package/pd-cli/dist/commands/candidate.js +2 -1
  68. package/pd-cli/dist/commands/candidate.js.map +1 -1
  69. package/pd-cli/dist/commands/demo-story-a.d.ts.map +1 -1
  70. package/pd-cli/dist/commands/demo-story-a.js +2 -1
  71. package/pd-cli/dist/commands/demo-story-a.js.map +1 -1
  72. package/pd-cli/dist/commands/health-mcp.d.ts +21 -0
  73. package/pd-cli/dist/commands/health-mcp.d.ts.map +1 -1
  74. package/pd-cli/dist/commands/health-mcp.js +19 -1
  75. package/pd-cli/dist/commands/health-mcp.js.map +1 -1
  76. package/pd-cli/dist/commands/health.d.ts.map +1 -1
  77. package/pd-cli/dist/commands/health.js +12 -4
  78. package/pd-cli/dist/commands/health.js.map +1 -1
  79. package/pd-cli/dist/commands/legacy-cleanup.d.ts.map +1 -1
  80. package/pd-cli/dist/commands/legacy-cleanup.js +2 -1
  81. package/pd-cli/dist/commands/legacy-cleanup.js.map +1 -1
  82. package/pd-cli/dist/commands/pain-list.d.ts.map +1 -1
  83. package/pd-cli/dist/commands/pain-list.js +2 -1
  84. package/pd-cli/dist/commands/pain-list.js.map +1 -1
  85. package/pd-cli/dist/commands/principles-stats.d.ts.map +1 -1
  86. package/pd-cli/dist/commands/principles-stats.js +2 -1
  87. package/pd-cli/dist/commands/principles-stats.js.map +1 -1
  88. package/pd-cli/dist/commands/quality-scorecard.d.ts.map +1 -1
  89. package/pd-cli/dist/commands/quality-scorecard.js +2 -1
  90. package/pd-cli/dist/commands/quality-scorecard.js.map +1 -1
  91. package/pd-cli/dist/commands/runtime-init.d.ts.map +1 -1
  92. package/pd-cli/dist/commands/runtime-init.js +5 -4
  93. package/pd-cli/dist/commands/runtime-init.js.map +1 -1
  94. package/pd-cli/dist/commands/runtime-internalization-evidence.d.ts.map +1 -1
  95. package/pd-cli/dist/commands/runtime-internalization-evidence.js +2 -1
  96. package/pd-cli/dist/commands/runtime-internalization-evidence.js.map +1 -1
  97. package/pd-cli/dist/commands/runtime-recovery-failed-task.d.ts.map +1 -1
  98. package/pd-cli/dist/commands/runtime-recovery-failed-task.js +2 -1
  99. package/pd-cli/dist/commands/runtime-recovery-failed-task.js.map +1 -1
  100. package/pd-cli/dist/legacy/session-history-import.js +2 -2
  101. package/pd-cli/dist/legacy/session-history-import.js.map +1 -1
  102. package/pd-cli/package.json +1 -1
  103. package/pd-mcp-server/dist/index.js +33 -2
  104. package/pd-mcp-server/dist/server.d.ts +7 -3
  105. package/pd-mcp-server/dist/server.js +6 -1
  106. package/pd-mcp-server/dist/submit-assembly.d.ts +24 -0
  107. package/pd-mcp-server/dist/submit-assembly.js +61 -0
  108. package/pd-mcp-server/dist/version.d.ts +1 -1
  109. package/pd-mcp-server/dist/version.js +1 -1
  110. package/pd-mcp-server/package.json +2 -1
  111. package/plugin/dist/bundle.js +444 -466
  112. package/plugin/dist/constants/tool-semantics.d.ts +13 -0
  113. package/plugin/dist/core/correction-anchor.d.ts +40 -0
  114. package/plugin/dist/core/experiment-workspace-guard.d.ts +10 -0
  115. package/plugin/dist/core/workspace-context.d.ts +0 -4
  116. package/plugin/dist/hooks/gate.d.ts +0 -5
  117. package/plugin/dist/openclaw.plugin.json +1 -1
  118. package/plugin/dist/rulehost-evidence.js +4 -4
  119. package/plugin/openclaw.plugin.json +1 -1
  120. package/plugin/package.json +1 -1
  121. package/release-manager/dist/installer.js +24 -0
  122. package/release-manager/dist/installers/legacy-workbuddy-skill.js +162 -29
  123. package/release-manager/dist/installers/workbuddy-host-installer.js +7 -6
  124. package/release-manager/package.json +1 -1
  125. package/workbuddy-adapter/dist/tool-semantics.d.ts +11 -0
  126. package/workbuddy-adapter/dist/tool-semantics.js +11 -0
  127. package/workbuddy-adapter/package.json +1 -1
  128. package/plugin/dist/core/rule-host.d.ts +0 -203
@@ -1,7 +1,7 @@
1
1
  import fs from 'node:fs';
2
- import path from 'node:path';
3
2
  import Database from 'better-sqlite3';
4
3
  import { loadHostToolDeclarations } from './host-tool-declaration.js';
4
+ import { resolveTrajectoryDbPath } from '@principles/core/runtime/storage-paths';
5
5
  /** Adapter-owned facts consumed by the non-bypassable RuleCode promotion gate. */
6
6
  export const OPENCLAW_HOST_LIVENESS_CONTRACT = {
7
7
  version: 'openclaw-legacy@1',
@@ -113,7 +113,7 @@ const HOST_LIVENESS_CONTRACTS = {
113
113
  * — equivalent to empty, not unreadable. Read-only, never mutates state.
114
114
  */
115
115
  function readWorkspaceHostProvenance(workspaceDir) {
116
- const dbPath = path.join(workspaceDir, '.state', 'trajectory.db');
116
+ const dbPath = resolveTrajectoryDbPath(workspaceDir);
117
117
  if (!fs.existsSync(dbPath))
118
118
  return { ok: true, kinds: [] };
119
119
  let db;
@@ -51,6 +51,7 @@ import path from 'node:path';
51
51
  import Database from 'better-sqlite3';
52
52
  import { loadLedger } from '@principles/core/principle-tree-ledger';
53
53
  import { loadFeatureFlagFromConfig } from '../pd-config.js';
54
+ import { resolveStateDbPath, resolveTrajectoryDbPath } from '@principles/core/runtime/storage-paths';
54
55
  /** Feature flag whose absence of writes makes receipt absence unprovable. */
55
56
  const RECEIPT_LEDGER_FLAG = 'principle_receipt_ledger';
56
57
  /**
@@ -138,7 +139,7 @@ export function readMilestoneFacts(workspaceDir) {
138
139
  initializationFailed: false,
139
140
  };
140
141
  const workspace = path.resolve(workspaceDir);
141
- const stateDbPath = path.join(workspace, '.pd', 'state.db');
142
+ const stateDbPath = resolveStateDbPath(workspace);
142
143
  // existsSync never throws (errors render as false) — safe inside the
143
144
  // never-throws contract; the single lookup is shared by the note and the
144
145
  // initializationFailed derivation below.
@@ -185,7 +186,7 @@ export function readMilestoneFacts(workspaceDir) {
185
186
  facts.presenceReceiptObserved = stateResults.presenceReceipts ?? null;
186
187
  facts.effectReceiptObserved = stateResults.effectReceipts ?? null;
187
188
  }
188
- const trajectoryResults = existsQueries(path.join(workspace, '.state', 'trajectory.db'), { painEvents: 'SELECT EXISTS(SELECT 1 FROM pain_events)' }, { notes, unavailableNote: 'trajectory_db_unreadable' });
189
+ const trajectoryResults = existsQueries(resolveTrajectoryDbPath(workspace), { painEvents: 'SELECT EXISTS(SELECT 1 FROM pain_events)' }, { notes, unavailableNote: 'trajectory_db_unreadable' });
189
190
  facts.painObserved = trajectoryResults.painEvents ?? null;
190
191
  // Ledger fallback. loadLedger is fail-soft by contract (returns an empty
191
192
  // tree for anything it cannot read), which would silently render a
@@ -6,6 +6,7 @@ import { applyTrajectorySchemaBase, migrateLegacyGfiSchema, sanitizeToolParams,
6
6
  // PRI-1135: the canonical column declaration lives with the DDL owner. Import
7
7
  // the subpath directly so the public runtime barrel surface stays unchanged.
8
8
  import { TRAJECTORY_REQUIRED_COLUMNS } from '@principles/core/runtime/trajectory-schema';
9
+ import { resolveTrajectoryDbPath } from '@principles/core/runtime/storage-paths';
9
10
  const MAX_PREVIEW = 500;
10
11
  function isRecord(value) {
11
12
  return typeof value === 'object' && value !== null && !Array.isArray(value);
@@ -277,7 +278,7 @@ export function recordVerifiedToolOutcomes(args) {
277
278
  const results = [];
278
279
  if (args.outcomes.length === 0)
279
280
  return results;
280
- const dbPath = path.join(args.workspaceDir, '.state', 'trajectory.db');
281
+ const dbPath = resolveTrajectoryDbPath(args.workspaceDir);
281
282
  if (!fs.existsSync(dbPath)) {
282
283
  return args.outcomes.map(() => ({ status: 'unavailable', reason: 'trajectory_db_not_found' }));
283
284
  }
@@ -402,7 +403,7 @@ export function createProductionPainEvidenceHandler(options = {}) {
402
403
  catch (err) {
403
404
  emissionWarning = `receipt_event_write_failed:${err instanceof Error ? err.message.slice(0, 200) : String(err).slice(0, 200)}`;
404
405
  }
405
- const dbPath = path.join(event.context.workspaceDir, '.state', 'trajectory.db');
406
+ const dbPath = resolveTrajectoryDbPath(event.context.workspaceDir);
406
407
  if (!fs.existsSync(dbPath)) {
407
408
  return { decision: 'observe', source: event.source, warnings: [...(emissionWarning ? [emissionWarning] : []), 'trajectory_db_not_found'], metadata: { outcome: 'unavailable', duplicate: false, nextAction: 'initialize the selected PD workspace before retrying the hook' } };
408
409
  }
@@ -1,6 +1,26 @@
1
1
  import { type RuleHostResult, type ToolSemanticRegistry, type GovernanceHostKind } from '@principles/core/runtime';
2
2
  import type { HostEvent, HostEventResult } from '@principles/core/host';
3
3
  import { type RuleImplementationRuntime } from './rule-implementation-runtime.js';
4
+ /**
5
+ * PRI-1208 Stage 3: structured, bounded evaluation faults.
6
+ *
7
+ * Warnings are human text for the host logger. The legacy `RuleHost` also
8
+ * persisted two kinds of evidence that the shared gate did not carry:
9
+ * `rulehost_unhealthy` (a rule defect) and `rulehost_skipped` (a governance /
10
+ * configuration skip). Deleting the legacy path would silently drop that
11
+ * evidence. These facts are host-neutral: the gate returns them; the OpenClaw
12
+ * adapter maps them onto its existing EventLog schema. Other hosts are free to
13
+ * ignore them — this file never writes host state.
14
+ */
15
+ export interface RuleHostEvaluationFault {
16
+ kind: 'unhealthy' | 'skipped';
17
+ activationId: string;
18
+ artifactId: string;
19
+ ruleId: string;
20
+ mode?: 'live' | 'shadow';
21
+ reason: string;
22
+ nextAction: string;
23
+ }
4
24
  export interface ProductionRuleContextRequest {
5
25
  workspaceDir: string;
6
26
  sessionId: string;
@@ -1,11 +1,11 @@
1
1
  import fs from 'node:fs';
2
- import path from 'node:path';
3
2
  import { buildRuleHostAction, buildToolSemanticRegistry, deriveToolHintsFromCanonicalKind, estimateLineChanges, mergeDecisions, normalizeRuleHostResult, SqliteConnection, UNAVAILABLE_RULE_CONTEXT, validateRuleContextV2, verifyPiArtifactRowDigest, RECOVERY_CONTROL_SURFACES, } from '@principles/core/runtime';
4
- import { isRuleHostEvaluableKind, isSensitiveSystemPath } from '@principles/core/runtime/internalization/rule-host-input-builder';
3
+ import { buildRuleHostInput, isRuleHostEvaluableKind } from '@principles/core/runtime/internalization/rule-host-input-builder';
5
4
  import { classifyBashRisk } from '@principles/core/runtime/internalization/bash-risk';
6
5
  import { scanRetiredContractSymbols } from './legacy-rule-contract-symbols.js';
7
6
  import { recordDegradedEnforcement } from './degraded-enforcement-marker.js';
8
7
  import { createNodeRuleImplementationRuntime, MAX_ACTIVE_RULES, RULE_BATCH_SOURCE_BYTES, RULE_SOURCE_BYTES, } from './rule-implementation-runtime.js';
8
+ import { resolveStateDbPath } from '@principles/core/runtime/storage-paths';
9
9
  const WARNING_LIMIT = 500;
10
10
  const MAX_WARNINGS = 16;
11
11
  const GATE_DEADLINE_MS = 3_000;
@@ -45,6 +45,15 @@ function addWarning(warnings, reason, nextAction) {
45
45
  if (warnings.length < MAX_WARNINGS)
46
46
  warnings.push(boundedWarning(reason, nextAction));
47
47
  }
48
+ // eslint-disable-next-line @typescript-eslint/max-params -- internal accumulator; positional args keep every call site one line
49
+ function addFault(faults, kind, source, reason, nextAction) {
50
+ if (faults.length >= MAX_WARNINGS)
51
+ return;
52
+ faults.push({ kind, ...source, reason: reason.slice(0, 300), nextAction: nextAction.slice(0, 300) });
53
+ }
54
+ function withFaults(metadata, faults) {
55
+ return faults.length > 0 ? { ...metadata, evaluationFaults: faults } : metadata;
56
+ }
48
57
  function remainingGateMs(startedAt) {
49
58
  return GATE_DEADLINE_MS - (Date.now() - startedAt);
50
59
  }
@@ -173,6 +182,7 @@ export function createProductionRuleHostGate(options = {}) {
173
182
  return async (event) => {
174
183
  const startedAt = Date.now();
175
184
  const warnings = [];
185
+ const evaluationFaults = [];
176
186
  const input = readToolInput(event.rawPayload);
177
187
  if (!input || input.toolName !== event.context.toolName) {
178
188
  return { decision: 'allow', source: event.source, warnings: [boundedWarning('tool_input_invalid', 'decode and validate toolName and params before dispatch')] };
@@ -184,7 +194,7 @@ export function createProductionRuleHostGate(options = {}) {
184
194
  // The kind comes from the same ToolSemanticRegistry that supplies the
185
195
  // extraction hints below — never a tool-name allowlist.
186
196
  if (!isRuleHostEvaluableKind(canonicalKind)) {
187
- return { decision: 'allow', source: event.source, metadata: { evaluatedLiveRules: 0 } };
197
+ return { decision: 'allow', source: event.source, metadata: withFaults({ evaluatedLiveRules: 0 }, evaluationFaults) };
188
198
  }
189
199
  const { isBashTool: isBash, isWriteTool: isWrite } = deriveToolHintsFromCanonicalKind(canonicalKind);
190
200
  const action = buildRuleHostAction(input.toolName, input.params, options.projectDir ?? event.context.workspaceDir, { isBashTool: isBash, isWriteTool: isWrite, canonicalKind });
@@ -193,7 +203,7 @@ export function createProductionRuleHostGate(options = {}) {
193
203
  // target": a pathless tool is not evaluated rather than treating an empty
194
204
  // string as a path.
195
205
  if (action.normalizedPath === null || action.normalizedPath === '')
196
- return { decision: 'allow', source: event.source, metadata: { evaluatedLiveRules: 0 } };
206
+ return { decision: 'allow', source: event.source, metadata: withFaults({ evaluatedLiveRules: 0 }, evaluationFaults) };
197
207
  let context;
198
208
  /**
199
209
  * SPEC-RULECODE-QUALITY-001 A3 (Q10): the precise reason a v2 rule is
@@ -257,13 +267,13 @@ export function createProductionRuleHostGate(options = {}) {
257
267
  else {
258
268
  contextFault = 'provider_absent';
259
269
  }
260
- const dbPath = path.join(event.context.workspaceDir, '.pd', 'state.db');
270
+ const dbPath = resolveStateDbPath(event.context.workspaceDir);
261
271
  if (remainingGateMs(startedAt) <= 0) {
262
272
  // SPEC-RULECODE-QUALITY-001 Q24: a deadline-exhausted allow must be
263
273
  // observable as "no rule executed" (evaluatedLiveRules=0), never read
264
274
  // as successful governance — isolated probe finding (the early return
265
275
  // previously carried no evaluation facts at all).
266
- return { decision: 'allow', source: event.source, warnings: [boundedWarning('gate_deadline_exceeded', 'inspect host context providers and active RuleCode resource use')], metadata: { evaluatedLiveRules: 0 } };
276
+ return { decision: 'allow', source: event.source, warnings: [boundedWarning('gate_deadline_exceeded', 'inspect host context providers and active RuleCode resource use')], metadata: withFaults({ evaluatedLiveRules: 0 }, evaluationFaults) };
267
277
  }
268
278
  if (!fs.existsSync(dbPath)) {
269
279
  // Security audit run-1 (gate-failopen-allow-on-state-corruption):
@@ -285,7 +295,7 @@ export function createProductionRuleHostGate(options = {}) {
285
295
  decision: 'allow',
286
296
  source: event.source,
287
297
  warnings: [boundedWarning('global_rulecode_pause_active', 'review the incident in the Owner Console before releasing the global pause')],
288
- metadata: { evaluatedLiveRules: 0 },
298
+ metadata: withFaults({ evaluatedLiveRules: 0 }, evaluationFaults),
289
299
  };
290
300
  }
291
301
  // PRI-1044 step 3-1: an ACTIVE activation whose pi_artifacts row is gone
@@ -342,16 +352,16 @@ export function createProductionRuleHostGate(options = {}) {
342
352
  addWarning(warnings, 'activation_query_invalid', 'inspect state.db schema and integrity');
343
353
  }
344
354
  else if (rows.length > MAX_ACTIVE_RULES) {
345
- return { decision: 'allow', source: event.source, warnings: [boundedWarning(`active_rule_limit_exceeded: maximum ${MAX_ACTIVE_RULES}`, 'deactivate excess active RuleHost rules and retry')], metadata: { evaluatedLiveRules: 0 } };
355
+ return { decision: 'allow', source: event.source, warnings: [boundedWarning(`active_rule_limit_exceeded: maximum ${MAX_ACTIVE_RULES}`, 'deactivate excess active RuleHost rules and retry')], metadata: withFaults({ evaluatedLiveRules: 0 }, evaluationFaults) };
346
356
  }
347
357
  else {
348
358
  for (const row of rows) {
349
359
  if (!isRecord(row) || typeof row.content_bytes !== 'number' || !Number.isSafeInteger(row.content_bytes) || row.content_bytes < 0) {
350
- return { decision: 'allow', source: event.source, warnings: [boundedWarning('artifact_content_size_invalid', 'inspect state.db artifact content integrity')], metadata: { evaluatedLiveRules: 0 } };
360
+ return { decision: 'allow', source: event.source, warnings: [boundedWarning('artifact_content_size_invalid', 'inspect state.db artifact content integrity')], metadata: withFaults({ evaluatedLiveRules: 0 }, evaluationFaults) };
351
361
  }
352
362
  if (row.content_bytes > ARTIFACT_CONTENT_BYTES) {
353
363
  const activation = typeof row.activation_id === 'string' ? row.activation_id : 'unknown';
354
- return { decision: 'allow', source: event.source, warnings: [boundedWarning(`artifact_content_budget_exceeded: activation=${activation} bytes=${row.content_bytes} maximum=${ARTIFACT_CONTENT_BYTES}`, 'reduce the active artifact envelope and reactivate the rule')], metadata: { evaluatedLiveRules: 0 } };
364
+ return { decision: 'allow', source: event.source, warnings: [boundedWarning(`artifact_content_budget_exceeded: activation=${activation} bytes=${row.content_bytes} maximum=${ARTIFACT_CONTENT_BYTES}`, 'reduce the active artifact envelope and reactivate the rule')], metadata: withFaults({ evaluatedLiveRules: 0 }, evaluationFaults) };
355
365
  }
356
366
  }
357
367
  const groups = new Map();
@@ -361,12 +371,24 @@ export function createProductionRuleHostGate(options = {}) {
361
371
  continue;
362
372
  }
363
373
  const activationId = typeof row.activation_id === 'string' ? row.activation_id : 'unknown';
374
+ const controlFaultSource = {
375
+ activationId,
376
+ artifactId: typeof row.artifact_id === 'string' ? row.artifact_id : 'unknown',
377
+ // Same identity rule everywhere: the rule's own id, else its
378
+ // artifact. Never activationId / targetRef — consumers group by
379
+ // ruleId and a fallback would invent a fake rule.
380
+ ruleId: typeof row.source_rule_id === 'string' && row.source_rule_id.length > 0
381
+ ? row.source_rule_id
382
+ : (typeof row.artifact_id === 'string' && row.artifact_id.length > 0 ? row.artifact_id : activationId),
383
+ };
364
384
  if (row.enforcement === 'safety_isolated') {
365
385
  addWarning(warnings, `activation_safety_isolated: ${activationId}`, 'recover the activation to shadow after reviewing safety evidence');
386
+ addFault(evaluationFaults, 'skipped', controlFaultSource, `activation_safety_isolated: ${activationId}`, 'recover the activation to shadow after reviewing safety evidence');
366
387
  continue;
367
388
  }
368
389
  if (row.enforcement !== 'eligible') {
369
390
  addWarning(warnings, `activation_control_state_invalid: ${activationId}`, 'repair the activation control state before RuleCode enforcement');
391
+ addFault(evaluationFaults, 'skipped', controlFaultSource, `activation_control_state_invalid: ${activationId}`, 'repair the activation control state before RuleCode enforcement');
370
392
  continue;
371
393
  }
372
394
  const group = groups.get(row.target_ref) ?? [];
@@ -376,6 +398,15 @@ export function createProductionRuleHostGate(options = {}) {
376
398
  for (const [targetRef, group] of groups) {
377
399
  if (group.length !== 1) {
378
400
  addWarning(warnings, `duplicate_active_activation: ${targetRef}`, 'deactivate all but one activation for this target_ref');
401
+ for (const duplicate of group) {
402
+ addFault(evaluationFaults, 'unhealthy', {
403
+ activationId: typeof duplicate.activation_id === 'string' ? duplicate.activation_id : 'unknown',
404
+ artifactId: typeof duplicate.artifact_id === 'string' ? duplicate.artifact_id : 'unknown',
405
+ ruleId: typeof duplicate.source_rule_id === 'string' && duplicate.source_rule_id.length > 0
406
+ ? duplicate.source_rule_id
407
+ : (typeof duplicate.artifact_id === 'string' ? duplicate.artifact_id : 'unknown'),
408
+ }, `duplicate active activation for target_ref ${targetRef}`, 'Deactivate all but one activation for this target_ref');
409
+ }
379
410
  continue;
380
411
  }
381
412
  const [row] = group;
@@ -399,6 +430,12 @@ export function createProductionRuleHostGate(options = {}) {
399
430
  addWarning(warnings, 'activation_required_fields_invalid', 'deactivate and recreate the activation');
400
431
  continue;
401
432
  }
433
+ const faultSource = {
434
+ activationId,
435
+ artifactId,
436
+ ruleId: typeof row.source_rule_id === 'string' && row.source_rule_id.length > 0 ? row.source_rule_id : artifactId,
437
+ mode: activationMode,
438
+ };
402
439
  const contentRow = connection.getDb().prepare(`
403
440
  SELECT artifact_id, artifact_kind, source_task_id, source_principle_id, source_rule_id,
404
441
  lineage_artifact_ids, validation_status, content_json,
@@ -409,6 +446,7 @@ export function createProductionRuleHostGate(options = {}) {
409
446
  if (!isRecord(contentRow) || typeof contentRow.content_json !== 'string'
410
447
  || typeof contentRow.content_bytes !== 'number' || !Number.isSafeInteger(contentRow.content_bytes)) {
411
448
  addWarning(warnings, `activation_artifact_invalid: ${activationId}`, 'inspect state.db artifact content integrity');
449
+ addFault(evaluationFaults, 'skipped', faultSource, `activation_artifact_invalid: ${activationId}`, 'inspect state.db artifact content integrity');
412
450
  continue;
413
451
  }
414
452
  const contentJson = contentRow.content_json;
@@ -420,16 +458,18 @@ export function createProductionRuleHostGate(options = {}) {
420
458
  // enforcement (shadow may never influence the live outcome).
421
459
  if (activationMode === 'shadow') {
422
460
  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
+ addFault(evaluationFaults, 'skipped', faultSource, `artifact_content_budget_exceeded: activation=${activationId}`, 'reduce the active shadow artifact envelope and reactivate the rule');
423
462
  continue;
424
463
  }
425
- 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: { evaluatedLiveRules: 0 } };
464
+ 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) };
426
465
  }
427
466
  if (contentRow.content_bytes !== expectedContentBytes || returnedContentBytes !== contentRow.content_bytes) {
428
467
  if (activationMode === 'shadow') {
429
468
  addWarning(warnings, `artifact_content_size_changed: activation=${activationId}`, 'retry after the active shadow artifact update completes; live enforcement is unaffected');
469
+ addFault(evaluationFaults, 'skipped', faultSource, `artifact_content_size_changed: activation=${activationId}`, 'retry after the active shadow artifact update completes');
430
470
  continue;
431
471
  }
432
- return { decision: 'allow', source: event.source, warnings: [boundedWarning(`artifact_content_size_changed: activation=${activationId}`, 'retry after the active artifact update completes')], metadata: { evaluatedLiveRules: 0 } };
472
+ return { decision: 'allow', source: event.source, warnings: [boundedWarning(`artifact_content_size_changed: activation=${activationId}`, 'retry after the active artifact update completes')], metadata: withFaults({ evaluatedLiveRules: 0 }, evaluationFaults) };
433
473
  }
434
474
  // Enforcement-time content binding (security audit run-1,
435
475
  // rulecode-approval-content-unbound): the Owner decision recorded
@@ -448,34 +488,40 @@ export function createProductionRuleHostGate(options = {}) {
448
488
  const digestCheck = verifyPiArtifactRowDigest(contentRow, contentJson, approvedArtifactDigest);
449
489
  if (digestCheck.outcome === 'unverifiable') {
450
490
  addWarning(warnings, `activation_artifact_invalid: ${activationId} (${digestCheck.error})`, 'inspect state.db artifact row integrity; the approved digest could not be re-verified');
491
+ addFault(evaluationFaults, 'skipped', faultSource, `activation_artifact_invalid: ${activationId}`, 'inspect state.db artifact row integrity');
451
492
  continue;
452
493
  }
453
494
  if (digestCheck.outcome === 'tampered') {
454
495
  const digestNextAction = 'the artifact content no longer matches the Owner-approved digest — deactivate and re-approve the rule; execution was skipped';
455
496
  if (activationMode === 'shadow') {
456
497
  addWarning(warnings, `artifact_digest_mismatch (shadow): activation=${activationId}`, `${digestNextAction}; live enforcement is unaffected`);
498
+ addFault(evaluationFaults, 'skipped', faultSource, `artifact_digest_mismatch (shadow): activation=${activationId}`, digestNextAction);
457
499
  continue;
458
500
  }
459
501
  addWarning(warnings, `artifact_content_tampered: activation=${activationId} approved=${approvedArtifactDigest} actual=${digestCheck.actualDigest}`, digestNextAction);
502
+ addFault(evaluationFaults, 'skipped', faultSource, `artifact_content_tampered: activation=${activationId}`, digestNextAction);
460
503
  continue;
461
504
  }
462
505
  try {
463
506
  const content = JSON.parse(contentJson);
464
507
  if (!isRecord(content) || typeof content.implementationCode !== 'string' || content.implementationCode.length === 0) {
465
508
  addWarning(warnings, `activation_artifact_invalid: ${activationId}`, 'regenerate the rule artifact with implementationCode');
509
+ addFault(evaluationFaults, 'skipped', faultSource, `activation_artifact_invalid: ${activationId}`, 'regenerate the rule artifact with implementationCode');
466
510
  continue;
467
511
  }
468
512
  const sourceBytes = Buffer.byteLength(content.implementationCode, 'utf8');
469
513
  if (sourceBytes > RULE_SOURCE_BYTES) {
470
514
  if (activationMode === 'shadow') {
471
515
  addWarning(warnings, `rule_source_budget_exceeded: activation=${activationId} bytes=${sourceBytes}`, `reduce the shadow RuleCode source below ${RULE_SOURCE_BYTES} bytes; live enforcement is unaffected`);
516
+ addFault(evaluationFaults, 'skipped', faultSource, `rule_source_budget_exceeded: activation=${activationId}`, `reduce the shadow RuleCode source below ${RULE_SOURCE_BYTES} bytes`);
472
517
  continue;
473
518
  }
474
- return { decision: 'allow', source: event.source, warnings: [boundedWarning(`rule_source_budget_exceeded: activation=${activationId} bytes=${sourceBytes}`, `reduce each RuleCode source below ${RULE_SOURCE_BYTES} bytes`)], metadata: { evaluatedLiveRules: 0 } };
519
+ return { decision: 'allow', source: event.source, warnings: [boundedWarning(`rule_source_budget_exceeded: activation=${activationId} bytes=${sourceBytes}`, `reduce each RuleCode source below ${RULE_SOURCE_BYTES} bytes`)], metadata: withFaults({ evaluatedLiveRules: 0 }, evaluationFaults) };
475
520
  }
476
521
  if (Object.hasOwn(content, 'requiresContextVersion')) {
477
522
  if (content.requiresContextVersion !== 2) {
478
523
  addWarning(warnings, `unsupported_context_version: ${String(content.requiresContextVersion)}`, 'regenerate the rule artifact for context version 2');
524
+ addFault(evaluationFaults, 'skipped', faultSource, `unsupported_context_version: ${String(content.requiresContextVersion)}`, 'regenerate the rule artifact for context version 2');
479
525
  continue;
480
526
  }
481
527
  // Codex V2 is opt-in per regenerated, Owner-approved artifact.
@@ -518,6 +564,7 @@ export function createProductionRuleHostGate(options = {}) {
518
564
  || !hosts.includes(options.hostKind) || row.owner_approved !== 1
519
565
  || !contentBindingVerified) {
520
566
  addWarning(warnings, `${options.hostKind}_rule_context_v2_unqualified: activation=${activationId}`, `regenerate and replay this artifact for ${options.hostKind}, approve it for shadow observation, and use the existing Owner promotion flow for live execution`);
567
+ addFault(evaluationFaults, 'skipped', faultSource, `${options.hostKind}_rule_context_v2_unqualified: activation=${activationId}`, `regenerate and replay this artifact for ${options.hostKind}, approve it for shadow observation, and use the existing Owner promotion flow for live execution`);
521
568
  continue;
522
569
  }
523
570
  }
@@ -571,6 +618,7 @@ export function createProductionRuleHostGate(options = {}) {
571
618
  ? `:${context.history.unavailableReason}`
572
619
  : '';
573
620
  addWarning(warnings, `rule_context_v2_unavailable: ${fault}${preciseReason} (activation=${activationId})`, 'enable and wire the host rule context provider, or regenerate the rule without context dependence');
621
+ addFault(evaluationFaults, 'skipped', faultSource, `rule_context_v2_unavailable: ${fault}${preciseReason} (activation=${activationId})`, 'enable and wire the host rule context provider, or regenerate the rule without context dependence');
574
622
  continue;
575
623
  }
576
624
  const inputContract = content.ruleHostInputContract;
@@ -578,10 +626,12 @@ export function createProductionRuleHostGate(options = {}) {
578
626
  if (!Array.isArray(inputContract.requiredFactKinds)
579
627
  || !inputContract.requiredFactKinds.every((kind) => typeof kind === 'string')) {
580
628
  addWarning(warnings, `rule_required_fact_contract_invalid: activation=${activationId}`, 'regenerate the rule artifact from validated Scribe execution conditions');
629
+ addFault(evaluationFaults, 'skipped', faultSource, `rule_required_fact_contract_invalid: activation=${activationId}`, 'regenerate the rule artifact from validated Scribe execution conditions');
581
630
  continue;
582
631
  }
583
632
  if (requiresDesignGateFact(inputContract) && designGateActionable === undefined) {
584
633
  addWarning(warnings, `rule_required_fact_unavailable: design_approval (activation=${activationId})`, 'verify the current Owner design declaration and scope before retrying');
634
+ addFault(evaluationFaults, 'skipped', faultSource, `rule_required_fact_unavailable: design_approval (activation=${activationId})`, 'verify the current Owner design declaration and scope before retrying');
585
635
  continue;
586
636
  }
587
637
  }
@@ -603,27 +653,33 @@ export function createProductionRuleHostGate(options = {}) {
603
653
  if (retiredSymbols.length > 0) {
604
654
  const nextAction = 'migrate the RuleCode off the retired contract symbols or deactivate the activation, then re-approve a migrated rule';
605
655
  addWarning(warnings, `legacy_rule_contract_dependency: ${retiredSymbols.join(', ')} (activation=${activationId})`, nextAction);
656
+ addFault(evaluationFaults, 'skipped', { ...faultSource, ruleId }, `legacy_rule_contract_dependency: ${retiredSymbols.join(', ')} (activation=${activationId})`, nextAction);
606
657
  continue;
607
658
  }
608
659
  const fallbackMeta = { name: activationId, version: '1', ruleId, coversCondition: 'all' };
609
660
  // PRI-1187: resolved for the observation-only mismatch signal; it
610
661
  // is attached to the candidate but never filters the batch.
611
662
  const declaredScope = resolveDeclaredFamilies(content.affectedTools, toolSemantics);
612
- candidates.push({ implId: activationId, ruleId, principleId, meta: isRuleMeta(content.meta) ? content.meta : fallbackMeta, source: content.implementationCode, activationMode, declaredTools: declaredScope?.tools ?? null, declaredFamilies: declaredScope?.families ?? null });
663
+ candidates.push({ implId: activationId, artifactId, ruleId, principleId, meta: isRuleMeta(content.meta) ? content.meta : fallbackMeta, source: content.implementationCode, activationMode, declaredTools: declaredScope?.tools ?? null, declaredFamilies: declaredScope?.families ?? null });
613
664
  }
614
665
  catch (error) {
615
- addWarning(warnings, `implementation_unhealthy: ${error instanceof Error ? error.message : String(error)}`, 'fix the RuleCode and reactivate the rule');
666
+ const reason = `implementation_unhealthy: ${error instanceof Error ? error.message : String(error)}`;
667
+ addWarning(warnings, reason, 'fix the RuleCode and reactivate the rule');
668
+ addFault(evaluationFaults, 'unhealthy', faultSource, reason, 'fix the RuleCode and reactivate the rule');
616
669
  }
617
670
  }
618
671
  }
619
- const hostInput = {
672
+ // PRI-1208 Stage 2: the single input-assembly contract shared with
673
+ // Golden Trace replay. `isRiskPath` is derived there, never re-derived
674
+ // (or hard-coded) by a host.
675
+ const hostInput = buildRuleHostInput({
620
676
  action,
621
- workspace: { isRiskPath: isSensitiveSystemPath(action.normalizedPath) },
622
- session: { sessionId: event.context.sessionId },
623
- evolution: { epTier: enrichment.epTier },
624
- derived: { estimatedLineChanges: estimateLineChanges({ toolName: input.toolName, params: input.params }, toolSemantics), bashRisk: enrichment.bashRisk },
625
- ...(context ? { context } : {}),
626
- };
677
+ sessionId: event.context.sessionId,
678
+ epTier: enrichment.epTier,
679
+ bashRisk: enrichment.bashRisk,
680
+ estimatedLineChanges: estimateLineChanges({ toolName: input.toolName, params: input.params }, toolSemantics),
681
+ ...(context !== undefined ? { context } : {}),
682
+ });
627
683
  // CodeRabbit CR-3: live and shadow evaluate in SEPARATE batches so a
628
684
  // shadow rule's timeout/budget failure can never suppress live
629
685
  // enforcement (shadow observes; it must not influence the live
@@ -634,21 +690,21 @@ export function createProductionRuleHostGate(options = {}) {
634
690
  const shadowCandidates = candidates.filter((candidate) => candidate.activationMode === 'shadow');
635
691
  const liveBatchBytes = liveCandidates.reduce((sum, candidate) => sum + Buffer.byteLength(candidate.source, 'utf8'), 0);
636
692
  if (liveBatchBytes > RULE_BATCH_SOURCE_BYTES) {
637
- 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: { evaluatedLiveRules: 0 } };
693
+ 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) };
638
694
  }
639
695
  let remaining = remainingGateMs(startedAt);
640
696
  if (remaining <= 0) {
641
- return { decision: 'allow', source: event.source, warnings: [boundedWarning('gate_deadline_exceeded', 'reduce active RuleCode count or source size and retry')], metadata: { evaluatedLiveRules: 0 } };
697
+ 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) };
642
698
  }
643
699
  const liveBatch = liveCandidates.length === 0
644
700
  ? { ok: true, results: [] }
645
701
  : implementationRuntime.evaluateBatch(liveCandidates.map((candidate) => ({ source: candidate.source, filename: `activation-${candidate.implId}` })), hostInput, remaining);
646
702
  if (!liveBatch.ok || !liveBatch.results) {
647
- 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: { evaluatedLiveRules: 0 } };
703
+ 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) };
648
704
  }
649
705
  const timedOutChild = liveBatch.results.find((candidate) => !candidate.ok && candidate.error?.includes('timed out'));
650
706
  if (timedOutChild) {
651
- 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: { evaluatedLiveRules: 0 } };
707
+ 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) };
652
708
  }
653
709
  // PRI-813: one canonical evaluation fact per shadow activation —
654
710
  // observations only. Shadow results never join mergeDecisions, never
@@ -682,12 +738,22 @@ export function createProductionRuleHostGate(options = {}) {
682
738
  const candidate = shadowCandidates[index];
683
739
  const batchResult = shadowBatch.results[index];
684
740
  if (!candidate || !batchResult || !batchResult.ok) {
685
- addWarning(warnings, `implementation_unhealthy: ${batchResult && !batchResult.ok ? batchResult.error ?? 'unknown child error' : 'rule_batch_result_missing'}`, 'fix the shadow RuleCode and reactivate the rule; live enforcement is unaffected');
741
+ const reason = `implementation_unhealthy: ${batchResult && !batchResult.ok ? batchResult.error ?? 'unknown child error' : 'rule_batch_result_missing'}`;
742
+ addWarning(warnings, reason, 'fix the shadow RuleCode and reactivate the rule; live enforcement is unaffected');
743
+ if (candidate) {
744
+ addFault(evaluationFaults, 'unhealthy', {
745
+ activationId: candidate.implId, artifactId: candidate.artifactId, ruleId: candidate.ruleId, mode: 'shadow',
746
+ }, reason, 'fix the shadow RuleCode and reactivate the rule');
747
+ }
686
748
  continue;
687
749
  }
688
750
  const normalized = normalizeRuleHostResult(batchResult.result);
689
751
  if (normalized.degraded !== undefined) {
690
- addWarning(warnings, `invalid RuleHostResult: ${normalized.degraded.notes ?? 'unknown invalid result'}`, 'fix the shadow RuleCode result and reactivate the rule; live enforcement is unaffected');
752
+ const reason = `invalid RuleHostResult: ${normalized.degraded.notes ?? 'unknown invalid result'}`;
753
+ addWarning(warnings, reason, 'fix the shadow RuleCode result and reactivate the rule; live enforcement is unaffected');
754
+ addFault(evaluationFaults, 'unhealthy', {
755
+ activationId: candidate.implId, artifactId: candidate.artifactId, ruleId: candidate.ruleId, mode: 'shadow',
756
+ }, reason, 'fix the shadow RuleCode result and reactivate the rule');
691
757
  continue;
692
758
  }
693
759
  const shadowResult = normalized.matched
@@ -718,7 +784,11 @@ export function createProductionRuleHostGate(options = {}) {
718
784
  continue;
719
785
  }
720
786
  if (!batchResult.ok) {
721
- addWarning(warnings, `implementation_unhealthy: ${batchResult.error ?? 'unknown child error'}`, 'fix the RuleCode and reactivate the rule');
787
+ const reason = `implementation_unhealthy: ${batchResult.error ?? 'unknown child error'}`;
788
+ addWarning(warnings, reason, 'fix the RuleCode and reactivate the rule');
789
+ addFault(evaluationFaults, 'unhealthy', {
790
+ activationId: candidate.implId, artifactId: candidate.artifactId, ruleId: candidate.ruleId, mode: 'live',
791
+ }, reason, 'fix the RuleCode and reactivate the rule');
722
792
  continue;
723
793
  }
724
794
  // B1: one reading of unusable output. Previously this branch warned and
@@ -727,7 +797,12 @@ export function createProductionRuleHostGate(options = {}) {
727
797
  // as a contract-level fail-closed requireApproval marked `degraded`.
728
798
  const normalized = normalizeRuleHostResult(batchResult.result);
729
799
  if (normalized.degraded !== undefined) {
730
- addWarning(warnings, `invalid RuleHostResult: ${normalized.degraded.notes ?? 'unknown invalid result'}`, 'fix the RuleCode result and reactivate the rule; invalid output is normalized to requireApproval (fail-closed in the contract, not enforced as a block by this gate)');
800
+ const reason = `invalid RuleHostResult: ${normalized.degraded.notes ?? 'unknown invalid result'}`;
801
+ const nextAction = 'fix the RuleCode result and reactivate the rule; invalid output is normalized to requireApproval (fail-closed in the contract, not enforced as a block by this gate)';
802
+ addWarning(warnings, reason, nextAction);
803
+ addFault(evaluationFaults, 'unhealthy', {
804
+ activationId: candidate.implId, artifactId: candidate.artifactId, ruleId: candidate.ruleId, mode: 'live',
805
+ }, reason, nextAction);
731
806
  }
732
807
  const validatedResult = normalized.matched
733
808
  ? { ...normalized, ruleId: candidate.ruleId, principleId: candidate.principleId }
@@ -771,9 +846,9 @@ export function createProductionRuleHostGate(options = {}) {
771
846
  if (result?.decision === 'block') {
772
847
  if (result.reason.trim().length === 0) {
773
848
  addWarning(warnings, 'deny_reason_missing', 'fix the RuleCode to return a non-empty block reason');
774
- return { decision: 'allow', source: event.source, warnings, metadata: { evaluatedLiveRules: implementations.length, evaluations } };
849
+ return { decision: 'allow', source: event.source, warnings, metadata: withFaults({ evaluatedLiveRules: implementations.length, evaluations }, evaluationFaults) };
775
850
  }
776
- return { decision: 'deny', reason: result.reason, source: event.source, ...(warnings.length ? { warnings } : {}), metadata: { evaluatedLiveRules: implementations.length, ruleId: result.ruleId, principleId: result.principleId, evaluations } };
851
+ 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) };
777
852
  }
778
853
  // Task 1 (legacy fallback convergence): a non-block verdict now carries
779
854
  // the facts the OpenClaw adapter needs to record/apply it WITHOUT a
@@ -785,7 +860,7 @@ export function createProductionRuleHostGate(options = {}) {
785
860
  decision: 'allow',
786
861
  source: event.source,
787
862
  ...(warnings.length ? { warnings } : {}),
788
- metadata: {
863
+ metadata: withFaults({
789
864
  evaluatedLiveRules: implementations.length,
790
865
  ruleDecision: result?.decision ?? 'allow',
791
866
  matched: result?.matched ?? false,
@@ -794,7 +869,7 @@ export function createProductionRuleHostGate(options = {}) {
794
869
  ...(result?.reason !== undefined ? { ruleReason: result.reason } : {}),
795
870
  ...(result !== undefined && result.correctionProposal !== undefined ? { correctionProposal: result.correctionProposal } : {}),
796
871
  evaluations,
797
- },
872
+ }, evaluationFaults),
798
873
  };
799
874
  }
800
875
  catch (error) {
@@ -807,7 +882,7 @@ export function createProductionRuleHostGate(options = {}) {
807
882
  recordDegradedEnforcement(event.context.workspaceDir, `activation_read_failed: ${error instanceof Error ? error.message : String(error)}`.slice(0, 300));
808
883
  }
809
884
  catch { /* observability only */ }
810
- return { decision: 'allow', source: event.source, warnings, metadata: { evaluatedLiveRules: 0 } };
885
+ return { decision: 'allow', source: event.source, warnings, metadata: withFaults({ evaluatedLiveRules: 0, evaluationStatus: 'failed' }, evaluationFaults) };
811
886
  }
812
887
  finally {
813
888
  connection.close();
@@ -1,10 +1,10 @@
1
1
  import fs from 'node:fs';
2
- import path from 'node:path';
3
2
  import { PROMPT_BUDGET_FALLBACK_CHARS, PROMPT_BUDGET_MAX_CHARS, PROMPT_BUDGET_MIN_CHARS, SqliteConnection, SqlitePIArtifactStore, classifySingleItemBudgetTier, computeFeatureFlagsFromConfig, renderPrinciplesToDirectives, resolvePrincipleFromArtifact, } from '@principles/core/runtime';
4
3
  import { escapeXml } from '@principles/core/prompt-builder';
5
4
  import { loadPdConfigForPlugin } from './pd-config.js';
6
5
  import { readPromptActivationAuthority } from './prompt-activation-authority.js';
7
6
  import { PROMPT_INJECTION_TARGET_HOSTS, PROMPT_INJECTION_UNIT, resolvePromptInjectionRouteDecision, } from './prompt-injection-projection.js';
7
+ import { resolveStateDbPath } from '@principles/core/runtime/storage-paths';
8
8
  function syntheticPendingActivation(artifactId) {
9
9
  return {
10
10
  activationId: `pending:${artifactId}`,
@@ -61,7 +61,7 @@ const MODEL_DEPENDENT_NEXT_ACTION = 'this principle fits the injection budget on
61
61
  * billing an unannotated (cheaper) entry (rc-3/rc-9).
62
62
  */
63
63
  function readAuthorityForArtifact(workspaceDir, artifactId) {
64
- const stateDbPath = path.join(workspaceDir, '.pd', 'state.db');
64
+ const stateDbPath = resolveStateDbPath(workspaceDir);
65
65
  if (!fs.existsSync(stateDbPath))
66
66
  return { ok: true, authority: undefined };
67
67
  let connection;
@@ -180,7 +180,7 @@ export async function checkPromptArtifactDeliverability(input) {
180
180
  }
181
181
  /** Load one artifact read-only from `<workspace>/.pd/state.db`. Failures carry a reason (rc-9). */
182
182
  export async function loadPromptArtifactById(workspaceDir, artifactId) {
183
- const stateDbPath = path.join(workspaceDir, '.pd', 'state.db');
183
+ const stateDbPath = resolveStateDbPath(workspaceDir);
184
184
  if (!fs.existsSync(stateDbPath)) {
185
185
  return { ok: false, reason: `activation_db_not_found: ${stateDbPath}; nextAction=initialize_workspace_runtime_state` };
186
186
  }
@@ -1,10 +1,10 @@
1
1
  import fs from 'node:fs';
2
- import path from 'node:path';
3
2
  import { PROMPT_BUDGET_MAX_CHARS, PROMPT_BUDGET_MIN_CHARS, SqliteActivationStateStore, SqliteConnection, SqlitePIArtifactStore, classifySingleItemBudgetTier, computeFeatureFlagsFromConfig, filterPromptActivations, resolvePrincipleFromArtifact, } from '@principles/core/runtime';
4
3
  import { loadPdConfigForPlugin } from './pd-config.js';
5
4
  import { computePromptSingleItemFit } from './prompt-activation-deliverability.js';
6
5
  import { readPromptActivationAuthority } from './prompt-activation-authority.js';
7
6
  import { PROMPT_INJECTION_TARGET_HOSTS, buildLivePromptInjectionProjection, resolvePromptInjectionRouteDecision, } from './prompt-injection-projection.js';
7
+ import { resolveStateDbPath } from '@principles/core/runtime/storage-paths';
8
8
  export async function readPromptActivationInjectionStatuses(input) {
9
9
  const config = loadPdConfigForPlugin(input.workspaceDir);
10
10
  const warnings = [];
@@ -22,7 +22,7 @@ export async function readPromptActivationInjectionStatuses(input) {
22
22
  globalReason: 'prompt_feature_disabled: the prompt injection surface is off, so no activation can be injected; nextAction=set features.prompt.enabled=true in .pd/config.yaml',
23
23
  };
24
24
  }
25
- const stateDbPath = path.join(input.workspaceDir, '.pd', 'state.db');
25
+ const stateDbPath = resolveStateDbPath(input.workspaceDir);
26
26
  if (!fs.existsSync(stateDbPath)) {
27
27
  return {
28
28
  route,
@@ -6,6 +6,7 @@ import { SqliteConnection } from '@principles/core/runtime';
6
6
  import { createOwnerEvidenceScopeError } from '@principles/core/runtime/internalization/evidence-readiness';
7
7
  import { BehaviorExamplePackAssembler } from './behavior-example-pack-assembler.js';
8
8
  import { resolveWorkspaceHostToolSemantics } from './host-tool-semantic-resolver.js';
9
+ import { resolveTrajectoryDbPath } from '@principles/core/runtime/storage-paths';
9
10
  function record(value) {
10
11
  return typeof value === 'object' && value !== null && !Array.isArray(value);
11
12
  }
@@ -58,7 +59,7 @@ export function createWorkspaceBehaviorEvidencePort(workspaceDir, toolSemantics)
58
59
  throw createOwnerEvidenceScopeError('evidence_source_error', 'Host tool semantics unavailable');
59
60
  let db;
60
61
  try {
61
- db = new Database(path.join(workspaceDir, '.state', 'trajectory.db'), { readonly: true, fileMustExist: true });
62
+ db = new Database(resolveTrajectoryDbPath(workspaceDir), { readonly: true, fileMustExist: true });
62
63
  }
63
64
  catch (error) {
64
65
  throw createOwnerEvidenceScopeError('evidence_source_error', `Trajectory evidence unavailable: ${error instanceof Error ? error.message : String(error)}`);
@@ -86,7 +87,7 @@ export function readWorkspaceRuleContextRowsBefore(workspaceDir, input) {
86
87
  throw new Error('history_limit_invalid');
87
88
  if (!Number.isFinite(Date.parse(beforeCreatedAt)))
88
89
  throw new Error('history_cutoff_invalid');
89
- const db = new Database(path.join(workspaceDir, '.state', 'trajectory.db'), { readonly: true, fileMustExist: true });
90
+ const db = new Database(resolveTrajectoryDbPath(workspaceDir), { readonly: true, fileMustExist: true });
90
91
  try {
91
92
  db.pragma('busy_timeout = 100');
92
93
  const attributionAware = input.hostKind !== undefined;
@@ -191,7 +192,7 @@ export function listObservedDesignGateSessions(workspaceDir) {
191
192
  finally {
192
193
  connection.close();
193
194
  }
194
- const trajectoryPath = path.join(workspaceDir, '.state', 'trajectory.db');
195
+ const trajectoryPath = resolveTrajectoryDbPath(workspaceDir);
195
196
  const trajectory = new Database(trajectoryPath, { readonly: true, fileMustExist: true });
196
197
  try {
197
198
  const selectProject = trajectory.prepare(`