@principles/host-runtime 5.2.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.
- package/dist/advisory-delivery.d.ts +34 -0
- package/dist/advisory-delivery.js +69 -0
- package/dist/behavior-history.js +1 -1
- package/dist/cli-recovery-probe.d.ts +23 -2
- package/dist/cli-recovery-probe.js +98 -9
- package/dist/codex-ingestion-consent.d.ts +5 -6
- package/dist/codex-ingestion-consent.js +5 -6
- package/dist/codex-rule-context-provider.js +30 -7
- package/dist/conversation-ingestion/consent.d.ts +14 -31
- package/dist/conversation-ingestion/consent.js +14 -223
- package/dist/fact-assembler.d.ts +91 -0
- package/dist/fact-assembler.js +318 -0
- package/dist/forward-observation.d.ts +6 -0
- package/dist/forward-observation.js +2 -1
- package/dist/host-liveness-contract.js +12 -0
- package/dist/index.d.ts +11 -1
- package/dist/index.js +13 -32
- package/dist/mode-state-facts.d.ts +41 -0
- package/dist/mode-state-facts.js +224 -0
- package/dist/product-telemetry/consent-store.d.ts +9 -47
- package/dist/product-telemetry/consent-store.js +18 -131
- package/dist/production-pain-evidence.d.ts +9 -0
- package/dist/production-pain-evidence.js +22 -2
- package/dist/production-policy-gate.d.ts +104 -0
- package/dist/production-policy-gate.js +379 -0
- package/dist/production-rulehost-gate.d.ts +6 -0
- package/dist/production-rulehost-gate.js +160 -31
- package/dist/prompt-activation-event.d.ts +29 -0
- package/dist/prompt-activation-event.js +80 -0
- package/dist/prompt-injection-budget-observation.d.ts +0 -11
- package/dist/prompt-injection-budget-observation.js +0 -11
- package/dist/rule-policy-active.d.ts +80 -0
- package/dist/rule-policy-active.js +197 -0
- package/dist/rule-policy-host-defaults.d.ts +19 -0
- package/dist/rule-policy-host-defaults.js +12 -0
- package/dist/rule-policy-paths-fs.d.ts +20 -0
- package/dist/rule-policy-paths-fs.js +58 -0
- package/dist/rule-policy-replay-evidence.d.ts +52 -0
- package/dist/rule-policy-replay-evidence.js +259 -0
- package/dist/session-write-targets.d.ts +86 -0
- package/dist/session-write-targets.js +216 -0
- package/dist/signal-classifier.d.ts +1 -0
- package/dist/signal-classifier.js +1 -1
- package/dist/signal-rate-limiter.d.ts +34 -0
- package/dist/signal-rate-limiter.js +83 -0
- package/dist/trajectory-retention.d.ts +8 -0
- package/dist/trajectory-retention.js +29 -0
- package/dist/trusted-pd-binary.d.ts +10 -0
- package/dist/trusted-pd-binary.js +38 -0
- package/dist/workbuddy-rule-context-provider.js +31 -10
- package/dist/workspace-behavior-evidence.d.ts +55 -0
- package/dist/workspace-behavior-evidence.js +93 -0
- package/package.json +24 -4
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* In-process judgement of active RulePolicyV2 rules for the RuleHost gate
|
|
3
|
+
* (SPEC-PD-RULE-POLICY-001 Requirement 10.13, 10.14, 13.1, 13.2, 13.6; design.md §13).
|
|
4
|
+
*
|
|
5
|
+
* `production-rulehost-gate.ts` finds the policy candidates (digest, validation, catalog
|
|
6
|
+
* version, Owner enforcement: `rule-policy-active.ts`) and hands them here with the call's
|
|
7
|
+
* `RuleHostInput`. This module:
|
|
8
|
+
* 1. loads the session's `modeState` and assembles the facts ONCE for all candidates;
|
|
9
|
+
* 2. judges each candidate with core's `evaluatePolicy` and converts the verdict with the
|
|
10
|
+
* real message renderer (`createPolicyMessageRenderer`, never the minimal default);
|
|
11
|
+
* 3. writes one Decision_Ledger row per verdict that is not `not_triggered` and bumps the
|
|
12
|
+
* session counter of every applicable judgement. A failed write never changes a verdict
|
|
13
|
+
* (Requirement 13.6): it becomes a warning and an observation;
|
|
14
|
+
* 4. reports observations, degradations and the live reminder text.
|
|
15
|
+
*
|
|
16
|
+
* Only `live` verdicts reach the gate's merge. `shadow` and `challenger` verdicts are written to
|
|
17
|
+
* the ledger and returned for telemetry but never contribute a decision or advisory text.
|
|
18
|
+
* Nothing here starts a child process or executes artifact-supplied code.
|
|
19
|
+
*/
|
|
20
|
+
import { SqliteConnection, type GovernanceHostKind, type RuleContextV2, type RuleHostInput, type RuleHostResult, type ToolSemanticRegistry } from '@principles/core/runtime';
|
|
21
|
+
import type { BashRiskLevel } from '@principles/core/runtime/internalization/bash-risk';
|
|
22
|
+
import type { CanonicalKind } from '@principles/core/runtime/internalization/rule-context-v2';
|
|
23
|
+
import { type PdLocale, type PolicyEvaluation } from '@principles/core/runtime/internalization/rule-policy-gate';
|
|
24
|
+
import { type ReadSessionActivityRows } from './fact-assembler.js';
|
|
25
|
+
import { type TrustedPdBinary } from './mode-state-facts.js';
|
|
26
|
+
import type { ActivePolicy, PolicyMode } from './rule-policy-active.js';
|
|
27
|
+
export interface PolicyReaderRequest {
|
|
28
|
+
workspaceDir: string;
|
|
29
|
+
sessionId: string;
|
|
30
|
+
toolName: string;
|
|
31
|
+
}
|
|
32
|
+
export interface RulePolicyGateOptions {
|
|
33
|
+
/** Language of the texts shown to the host agent; defaults to `zh-CN`. */
|
|
34
|
+
locale?: PdLocale;
|
|
35
|
+
/** The installed pd binary used in recovery hints and recognised as a recovery control. Defaults to `resolveTrustedPdBinary()`. */
|
|
36
|
+
pdBinary?: TrustedPdBinary;
|
|
37
|
+
/**
|
|
38
|
+
* Per-call reader of the session's earlier tool calls, feeding the `session.*` facts. Absent
|
|
39
|
+
* means those facts are unknown (`session_activity_read_failed`), never zero.
|
|
40
|
+
*/
|
|
41
|
+
createSessionActivityReader?: (request: PolicyReaderRequest) => ReadSessionActivityRows;
|
|
42
|
+
/**
|
|
43
|
+
* Whether the host has a channel that hands a reminder to the model without blocking the call
|
|
44
|
+
* (Requirement 12.5). Defaults to true. When false, a live rule that starts at `remind` is
|
|
45
|
+
* judged as `observe` (it never reminds, never counts a reminder and never escalates) and each
|
|
46
|
+
* judgement that would have reminded leaves a `policy_degraded` observation with its next action.
|
|
47
|
+
*/
|
|
48
|
+
advisoryChannelAvailable?: boolean;
|
|
49
|
+
now?: () => Date;
|
|
50
|
+
/** Path key platform; defaults to `process.platform`. */
|
|
51
|
+
platform?: string;
|
|
52
|
+
}
|
|
53
|
+
/** One bounded, host-neutral signal about a judgement that did not simply allow or enforce. */
|
|
54
|
+
export interface PolicyObservation {
|
|
55
|
+
kind: 'policy_unknown' | 'policy_target_unproven' | 'mode_self_assessment_mismatch' | 'policy_render_fault' | 'policy_ledger_write_failed' | 'policy_degraded';
|
|
56
|
+
ruleId: string;
|
|
57
|
+
activationId: string;
|
|
58
|
+
mode: PolicyMode;
|
|
59
|
+
reason: string;
|
|
60
|
+
nextAction: string;
|
|
61
|
+
}
|
|
62
|
+
export interface PolicyRuleOutcome {
|
|
63
|
+
active: ActivePolicy;
|
|
64
|
+
evaluation: PolicyEvaluation;
|
|
65
|
+
/** The verdict in host-contract form. Only `live` outcomes may join the gate's merge. */
|
|
66
|
+
result: RuleHostResult;
|
|
67
|
+
}
|
|
68
|
+
export interface PolicyRun {
|
|
69
|
+
outcomes: readonly PolicyRuleOutcome[];
|
|
70
|
+
observations: readonly PolicyObservation[];
|
|
71
|
+
/** Human-readable problems for the host logger, with their next action. */
|
|
72
|
+
warnings: readonly {
|
|
73
|
+
reason: string;
|
|
74
|
+
nextAction: string;
|
|
75
|
+
}[];
|
|
76
|
+
/** Reminder text of the LIVE policies that reminded, ordered by rule id; undefined when none. */
|
|
77
|
+
advisory: string | undefined;
|
|
78
|
+
/** Exactly the rules whose complete reminder text is represented in `advisory`. */
|
|
79
|
+
advisoryRuleIds: readonly string[];
|
|
80
|
+
}
|
|
81
|
+
export interface PolicyEvaluationArgs {
|
|
82
|
+
candidates: readonly ActivePolicy[];
|
|
83
|
+
hostInput: RuleHostInput;
|
|
84
|
+
context: RuleContextV2 | undefined;
|
|
85
|
+
/** Read-only governance connection the gate already holds. */
|
|
86
|
+
governanceDb: SqliteConnection;
|
|
87
|
+
workspaceDir: string;
|
|
88
|
+
sessionId: string;
|
|
89
|
+
/** Native physical tool-call id of this exact invocation, when the host provides one. */
|
|
90
|
+
toolCallId?: string;
|
|
91
|
+
projectRoot: string;
|
|
92
|
+
toolName: string;
|
|
93
|
+
canonicalKind: CanonicalKind;
|
|
94
|
+
bashRisk: BashRiskLevel;
|
|
95
|
+
toolSemantics: ToolSemanticRegistry;
|
|
96
|
+
/** Gate start time; the cutoff for earlier-call facts. */
|
|
97
|
+
startedAt: number;
|
|
98
|
+
}
|
|
99
|
+
export interface PolicyRuntime {
|
|
100
|
+
/** Absolute pd binary paths recognised as a recovery control by the shared action builder. */
|
|
101
|
+
trustedPdBinaries(): readonly string[];
|
|
102
|
+
evaluate(args: PolicyEvaluationArgs): PolicyRun;
|
|
103
|
+
}
|
|
104
|
+
export declare function createPolicyRuntime(options: RulePolicyGateOptions | undefined, hostKind: GovernanceHostKind | undefined): PolicyRuntime;
|
|
@@ -0,0 +1,379 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* In-process judgement of active RulePolicyV2 rules for the RuleHost gate
|
|
3
|
+
* (SPEC-PD-RULE-POLICY-001 Requirement 10.13, 10.14, 13.1, 13.2, 13.6; design.md §13).
|
|
4
|
+
*
|
|
5
|
+
* `production-rulehost-gate.ts` finds the policy candidates (digest, validation, catalog
|
|
6
|
+
* version, Owner enforcement: `rule-policy-active.ts`) and hands them here with the call's
|
|
7
|
+
* `RuleHostInput`. This module:
|
|
8
|
+
* 1. loads the session's `modeState` and assembles the facts ONCE for all candidates;
|
|
9
|
+
* 2. judges each candidate with core's `evaluatePolicy` and converts the verdict with the
|
|
10
|
+
* real message renderer (`createPolicyMessageRenderer`, never the minimal default);
|
|
11
|
+
* 3. writes one Decision_Ledger row per verdict that is not `not_triggered` and bumps the
|
|
12
|
+
* session counter of every applicable judgement. A failed write never changes a verdict
|
|
13
|
+
* (Requirement 13.6): it becomes a warning and an observation;
|
|
14
|
+
* 4. reports observations, degradations and the live reminder text.
|
|
15
|
+
*
|
|
16
|
+
* Only `live` verdicts reach the gate's merge. `shadow` and `challenger` verdicts are written to
|
|
17
|
+
* the ledger and returned for telemetry but never contribute a decision or advisory text.
|
|
18
|
+
* Nothing here starts a child process or executes artifact-supplied code.
|
|
19
|
+
*/
|
|
20
|
+
import { SqliteConnection, } from '@principles/core/runtime';
|
|
21
|
+
import { RULE_HOST_ADVISORY_MAX, createPolicyMessageRenderer, effectiveExemptPrefixes, evaluatePolicy, referencedFactIds, toRuleHostResult, } from '@principles/core/runtime/internalization/rule-policy-gate';
|
|
22
|
+
import { SqliteDecisionLedgerStore } from '@principles/core/runtime/internalization/rule-policy-modes';
|
|
23
|
+
import { recordDegradedEnforcement } from './degraded-enforcement-marker.js';
|
|
24
|
+
import { assembleFacts, normalizedPathTargetKeys, } from './fact-assembler.js';
|
|
25
|
+
import { loadModeStateFact, resolveTrustedPdBinary } from './mode-state-facts.js';
|
|
26
|
+
import { BUILTIN_EXEMPT_PREFIXES, defaultExemptPrefixes } from './rule-policy-host-defaults.js';
|
|
27
|
+
import { canonicalPolicyTargetPaths } from './rule-policy-paths-fs.js';
|
|
28
|
+
import { unavailableSessionWriteTargets } from './session-write-targets.js';
|
|
29
|
+
const MAX_OBSERVATIONS = 16;
|
|
30
|
+
const MAX_REASON = 300;
|
|
31
|
+
const ADVISORY_SEPARATOR = '\n\n';
|
|
32
|
+
/** Why a judged rule counts as "applicable" is the negation of these `not_triggered` reasons. */
|
|
33
|
+
const NOT_APPLICABLE_REASONS = new Set(['recovery_control', 'action_kind_not_applicable', 'no_targets', 'exempt']);
|
|
34
|
+
/** Unknown-fact reasons that mean "the data could not be had", as opposed to "nothing happened". */
|
|
35
|
+
const AVAILABILITY_FAILURE_PREFIXES = [
|
|
36
|
+
'host_did_not_provide',
|
|
37
|
+
'session_activity_',
|
|
38
|
+
'history_unavailable',
|
|
39
|
+
'history_conversion_failed',
|
|
40
|
+
'session_write_targets_failed',
|
|
41
|
+
'mode_state_unavailable',
|
|
42
|
+
'scan_limit_reached',
|
|
43
|
+
'created_at_unparseable',
|
|
44
|
+
];
|
|
45
|
+
function isRecord(value) {
|
|
46
|
+
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
47
|
+
}
|
|
48
|
+
function errorText(error) {
|
|
49
|
+
return (error instanceof Error ? error.message : String(error)).replace(/\s+/g, ' ').slice(0, MAX_REASON);
|
|
50
|
+
}
|
|
51
|
+
/**
|
|
52
|
+
* Write-target canonicalization lives in rule-policy-paths-fs.ts and is shared
|
|
53
|
+
* with offline replay: one realpath/unproven semantic, no second implementation.
|
|
54
|
+
*/
|
|
55
|
+
function withTargetPaths(input, targetPaths) {
|
|
56
|
+
const { targetPaths: _discarded, ...action } = input.action;
|
|
57
|
+
return { ...input, action: targetPaths === undefined ? action : { ...action, targetPaths } };
|
|
58
|
+
}
|
|
59
|
+
function isApplicable(evaluation) {
|
|
60
|
+
return evaluation.conclusion !== 'not_triggered' || !NOT_APPLICABLE_REASONS.has(evaluation.reason);
|
|
61
|
+
}
|
|
62
|
+
function isAvailabilityFailure(reason) {
|
|
63
|
+
return AVAILABILITY_FAILURE_PREFIXES.some((prefix) => reason.startsWith(prefix));
|
|
64
|
+
}
|
|
65
|
+
/** The first reason a LIVE rule could not judge because data was unavailable, or null. */
|
|
66
|
+
function degradationOf(live, modeState) {
|
|
67
|
+
if (live.length === 0)
|
|
68
|
+
return null;
|
|
69
|
+
if (modeState.status === 'unavailable')
|
|
70
|
+
return `policy_mode_state_unavailable: ${modeState.unavailableReason ?? 'unknown'}`;
|
|
71
|
+
for (const { active, evaluation } of live) {
|
|
72
|
+
if (evaluation.conclusion !== 'unknown')
|
|
73
|
+
continue;
|
|
74
|
+
if (evaluation.reason === 'evaluator_internal_error')
|
|
75
|
+
return `policy_evaluator_internal_error: rule ${active.ruleId}`;
|
|
76
|
+
const lost = evaluation.trace.unknownFacts.find((fact) => isAvailabilityFailure(fact.reason));
|
|
77
|
+
if (lost !== undefined)
|
|
78
|
+
return `policy_fact_unavailable: rule ${active.ruleId} fact ${lost.id} (${lost.reason})`;
|
|
79
|
+
}
|
|
80
|
+
return null;
|
|
81
|
+
}
|
|
82
|
+
function observationsOf(outcomes) {
|
|
83
|
+
const found = [];
|
|
84
|
+
for (const { active, evaluation, result } of outcomes) {
|
|
85
|
+
const base = { ruleId: active.ruleId, activationId: active.activationId, mode: active.mode };
|
|
86
|
+
if (evaluation.conclusion === 'unknown') {
|
|
87
|
+
const unproven = evaluation.reason === 'target_unproven';
|
|
88
|
+
found.push({
|
|
89
|
+
...base,
|
|
90
|
+
kind: unproven ? 'policy_target_unproven' : 'policy_unknown',
|
|
91
|
+
reason: evaluation.reason,
|
|
92
|
+
nextAction: unproven
|
|
93
|
+
? 'the write target could not be proven inside the project, so the rule did not judge this call; no action is needed unless it keeps happening'
|
|
94
|
+
: 'the rule could not decide because a fact was unknown; inspect the facts in the decision ledger if this repeats',
|
|
95
|
+
});
|
|
96
|
+
}
|
|
97
|
+
if (evaluation.selfAssessmentMismatch) {
|
|
98
|
+
found.push({
|
|
99
|
+
...base,
|
|
100
|
+
kind: 'mode_self_assessment_mismatch',
|
|
101
|
+
reason: 'the host declared a routine situation but the rule still reminded or blocked',
|
|
102
|
+
nextAction: 'review the rule trigger and the situation guidance shown to the host agent',
|
|
103
|
+
});
|
|
104
|
+
}
|
|
105
|
+
const renderFault = isRecord(result.diagnostics) ? result.diagnostics.renderFault : undefined;
|
|
106
|
+
if (typeof renderFault === 'string') {
|
|
107
|
+
found.push({
|
|
108
|
+
...base,
|
|
109
|
+
kind: 'policy_render_fault',
|
|
110
|
+
reason: renderFault.slice(0, MAX_REASON),
|
|
111
|
+
nextAction: 'the verdict was kept with a plain message; report the message renderer fault',
|
|
112
|
+
});
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
return found;
|
|
116
|
+
}
|
|
117
|
+
function collectAdvisory(live) {
|
|
118
|
+
const entries = live
|
|
119
|
+
.filter(({ result }) => result.decision === 'allow' && typeof result.advisory === 'string' && result.advisory.length > 0)
|
|
120
|
+
.sort((left, right) => (left.active.ruleId < right.active.ruleId ? -1 : left.active.ruleId > right.active.ruleId ? 1 : 0));
|
|
121
|
+
let text = '';
|
|
122
|
+
const ruleIds = [];
|
|
123
|
+
for (const entry of entries) {
|
|
124
|
+
const part = entry.result.advisory ?? '';
|
|
125
|
+
const candidate = text.length === 0 ? part : `${text}${ADVISORY_SEPARATOR}${part}`;
|
|
126
|
+
// A partially clipped rule message is not that rule's delivered reminder. Only a
|
|
127
|
+
// complete entry joins the aggregate and may later count toward that rule's escalation.
|
|
128
|
+
if (candidate.length > RULE_HOST_ADVISORY_MAX)
|
|
129
|
+
continue;
|
|
130
|
+
text = candidate;
|
|
131
|
+
ruleIds.push(entry.active.ruleId);
|
|
132
|
+
}
|
|
133
|
+
return text.length === 0 ? undefined : { text, ruleIds };
|
|
134
|
+
}
|
|
135
|
+
function factsSnapshot(active, facts) {
|
|
136
|
+
const snapshot = {};
|
|
137
|
+
for (const id of referencedFactIds(active.policy)) {
|
|
138
|
+
if (Object.hasOwn(facts, id))
|
|
139
|
+
snapshot[id] = facts[id];
|
|
140
|
+
}
|
|
141
|
+
return snapshot;
|
|
142
|
+
}
|
|
143
|
+
function ledgerRecordOf(outcome, hostKind, ctx) {
|
|
144
|
+
const { active, evaluation } = outcome;
|
|
145
|
+
if (evaluation.conclusion === 'not_triggered')
|
|
146
|
+
return null;
|
|
147
|
+
const unknown = evaluation.conclusion === 'unknown';
|
|
148
|
+
return {
|
|
149
|
+
ruleId: active.ruleId,
|
|
150
|
+
ruleLineageId: active.ruleLineageId,
|
|
151
|
+
artifactId: active.artifactId,
|
|
152
|
+
activationId: active.activationId,
|
|
153
|
+
mode: active.mode,
|
|
154
|
+
hostKind,
|
|
155
|
+
projectWorkspacePath: ctx.projectRoot,
|
|
156
|
+
hostSessionId: ctx.sessionId,
|
|
157
|
+
toolCallId: ctx.toolCallId ?? '',
|
|
158
|
+
// The store keeps `unknown` conclusions with exprResult `unknown`; the real value stays in the trace notes.
|
|
159
|
+
exprResult: unknown ? 'unknown' : evaluation.exprResult,
|
|
160
|
+
conclusion: evaluation.conclusion,
|
|
161
|
+
missing: { acts: [...evaluation.missing.acts], customChecks: [...evaluation.missing.customChecks] },
|
|
162
|
+
trace: {
|
|
163
|
+
...evaluation.trace,
|
|
164
|
+
notes: [...evaluation.trace.notes, `policy_reason:${evaluation.reason}`, ...(unknown ? [`policy_expr_result:${evaluation.exprResult}`] : [])],
|
|
165
|
+
},
|
|
166
|
+
facts: factsSnapshot(active, ctx.facts),
|
|
167
|
+
// Delivery is a later host fact. The gate has only produced reminder text at this point,
|
|
168
|
+
// so every row starts unconfirmed; the host receipt path flips the one-way bit.
|
|
169
|
+
advisoryDelivered: false,
|
|
170
|
+
};
|
|
171
|
+
}
|
|
172
|
+
/** Writes ledger rows and counters. Returns one bounded message per failure; never throws. */
|
|
173
|
+
function writeLedger(outcomes, ctx) {
|
|
174
|
+
const recordable = outcomes.filter((outcome) => isApplicable(outcome.evaluation));
|
|
175
|
+
if (recordable.length === 0)
|
|
176
|
+
return [];
|
|
177
|
+
const { hostKind } = ctx;
|
|
178
|
+
if (hostKind === undefined)
|
|
179
|
+
return ['policy_ledger_skipped: the gate was created without a host kind, so decisions cannot be attributed'];
|
|
180
|
+
if (ctx.toolCallId === undefined || ctx.toolCallId.trim().length === 0) {
|
|
181
|
+
return ['policy_ledger_skipped: the host did not provide a physical toolCallId, so decisions cannot be made idempotent or delivery-confirmed'];
|
|
182
|
+
}
|
|
183
|
+
const failures = [];
|
|
184
|
+
let connection = null;
|
|
185
|
+
try {
|
|
186
|
+
connection = new SqliteConnection({ workspaceDir: ctx.workspaceDir, readonly: false, bootstrapIfMissing: false });
|
|
187
|
+
const ledger = new SqliteDecisionLedgerStore(connection);
|
|
188
|
+
for (const outcome of recordable) {
|
|
189
|
+
const { active } = outcome;
|
|
190
|
+
try {
|
|
191
|
+
const record = ledgerRecordOf(outcome, hostKind, ctx);
|
|
192
|
+
if (record !== null)
|
|
193
|
+
ledger.recordDecision(record, ctx.now);
|
|
194
|
+
ledger.bumpApplicable({ ruleId: active.ruleId, mode: active.mode, hostSessionId: ctx.sessionId }, ctx.now);
|
|
195
|
+
}
|
|
196
|
+
catch (error) {
|
|
197
|
+
failures.push(`rule ${active.ruleId} (${active.mode}): ${errorText(error)}`);
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
catch (error) {
|
|
202
|
+
failures.push(`ledger unavailable: ${errorText(error)}`);
|
|
203
|
+
}
|
|
204
|
+
finally {
|
|
205
|
+
try {
|
|
206
|
+
connection?.close();
|
|
207
|
+
}
|
|
208
|
+
catch (error) {
|
|
209
|
+
failures.push(`ledger connection close failed: ${errorText(error)}`);
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
return failures;
|
|
213
|
+
}
|
|
214
|
+
// ── evaluation ───────────────────────────────────────────────────────────────
|
|
215
|
+
function envOf(active, args, settings) {
|
|
216
|
+
return {
|
|
217
|
+
locale: settings.locale,
|
|
218
|
+
platform: settings.platform,
|
|
219
|
+
ruleId: active.ruleId,
|
|
220
|
+
effectiveExemptPrefixes: effectiveExemptPrefixes(active.policy, {
|
|
221
|
+
builtin: BUILTIN_EXEMPT_PREFIXES,
|
|
222
|
+
hostDefault: settings.hostKind === undefined ? [] : defaultExemptPrefixes(settings.hostKind),
|
|
223
|
+
}),
|
|
224
|
+
designGateResolution: args.context?.facts.designGate?.resolution,
|
|
225
|
+
};
|
|
226
|
+
}
|
|
227
|
+
function currentFacts(args, targetPaths) {
|
|
228
|
+
const { commandClasses } = args.hostInput.action;
|
|
229
|
+
return {
|
|
230
|
+
kind: args.canonicalKind,
|
|
231
|
+
toolName: args.toolName,
|
|
232
|
+
normalizedPath: args.hostInput.action.normalizedPath,
|
|
233
|
+
targetEvidence: args.hostInput.action.targetEvidence,
|
|
234
|
+
...(targetPaths !== undefined ? { targetPaths } : {}),
|
|
235
|
+
...(commandClasses !== undefined ? { commandClasses } : {}),
|
|
236
|
+
bashRisk: args.bashRisk,
|
|
237
|
+
isSensitivePath: args.hostInput.workspace.isRiskPath,
|
|
238
|
+
};
|
|
239
|
+
}
|
|
240
|
+
function missingActivityReader() {
|
|
241
|
+
return () => {
|
|
242
|
+
throw new Error('session_activity_reader_not_provided');
|
|
243
|
+
};
|
|
244
|
+
}
|
|
245
|
+
export function createPolicyRuntime(options, hostKind) {
|
|
246
|
+
const locale = options?.locale ?? 'zh-CN';
|
|
247
|
+
const platform = options?.platform ?? process.platform;
|
|
248
|
+
const renderer = createPolicyMessageRenderer();
|
|
249
|
+
let pdBinary = options?.pdBinary;
|
|
250
|
+
const resolvePdBinary = () => {
|
|
251
|
+
pdBinary ??= resolveTrustedPdBinary();
|
|
252
|
+
return pdBinary;
|
|
253
|
+
};
|
|
254
|
+
const evaluate = (args) => {
|
|
255
|
+
const warnings = [];
|
|
256
|
+
const needed = new Set(args.candidates.flatMap((candidate) => [...referencedFactIds(candidate.policy)]));
|
|
257
|
+
const firstLive = args.candidates.find((candidate) => candidate.mode === 'live');
|
|
258
|
+
const modeState = loadModeStateFact({
|
|
259
|
+
governanceDb: args.governanceDb,
|
|
260
|
+
projectRoot: args.projectRoot,
|
|
261
|
+
hostKind,
|
|
262
|
+
hostSessionId: args.sessionId,
|
|
263
|
+
governanceWorkspaceDir: args.workspaceDir,
|
|
264
|
+
pdBin: resolvePdBinary().trusted.length > 0 ? resolvePdBinary().bin : null,
|
|
265
|
+
locale,
|
|
266
|
+
ruleIds: args.candidates.map((candidate) => candidate.ruleId),
|
|
267
|
+
// Only a live rule may name the suggested file: a shadow or challenger label must never reach the live message.
|
|
268
|
+
...(firstLive !== undefined ? { labelHint: firstLive.policy.obligation.label } : {}),
|
|
269
|
+
platform,
|
|
270
|
+
});
|
|
271
|
+
const inputTargetPaths = args.hostInput.action.targetPaths
|
|
272
|
+
?? normalizedPathTargetKeys(args.hostInput.action.normalizedPath, args.hostInput.action.targetEvidence, platform);
|
|
273
|
+
const targetPaths = args.canonicalKind === 'write'
|
|
274
|
+
? canonicalPolicyTargetPaths(inputTargetPaths, args.projectRoot, platform)
|
|
275
|
+
: inputTargetPaths;
|
|
276
|
+
const policyInput = args.canonicalKind === 'write' ? withTargetPaths(args.hostInput, targetPaths) : args.hostInput;
|
|
277
|
+
let facts = {};
|
|
278
|
+
try {
|
|
279
|
+
facts = assembleFacts({
|
|
280
|
+
needed,
|
|
281
|
+
current: currentFacts(args, targetPaths),
|
|
282
|
+
sessionWriteTargets: args.context?.facts.sessionWriteTargets ?? unavailableSessionWriteTargets('host_did_not_provide'),
|
|
283
|
+
readActivity: options?.createSessionActivityReader?.({ workspaceDir: args.workspaceDir, sessionId: args.sessionId, toolName: args.toolName }) ?? missingActivityReader(),
|
|
284
|
+
history: args.context?.history,
|
|
285
|
+
modeState,
|
|
286
|
+
designGate: args.context?.facts.designGate,
|
|
287
|
+
toolSemantics: args.toolSemantics,
|
|
288
|
+
sessionId: args.sessionId,
|
|
289
|
+
beforeKey: new Date(args.startedAt).toISOString(),
|
|
290
|
+
projectRoot: args.projectRoot,
|
|
291
|
+
platform,
|
|
292
|
+
});
|
|
293
|
+
}
|
|
294
|
+
catch (error) {
|
|
295
|
+
warnings.push({
|
|
296
|
+
reason: `policy_fact_assembly_failed: ${errorText(error)}`,
|
|
297
|
+
nextAction: 'every fact is unknown for this call, so rule policies could not judge it; inspect the fact assembler inputs',
|
|
298
|
+
});
|
|
299
|
+
}
|
|
300
|
+
const outcomes = [];
|
|
301
|
+
const unreminded = [];
|
|
302
|
+
for (const active of args.candidates) {
|
|
303
|
+
try {
|
|
304
|
+
const withoutChannel = options?.advisoryChannelAvailable === false && active.mode === 'live' && active.enforcement.start === 'remind';
|
|
305
|
+
const enforcement = withoutChannel
|
|
306
|
+
? { ...active.enforcement, start: 'observe', escalateAfterReminders: null }
|
|
307
|
+
: active.enforcement;
|
|
308
|
+
const request = {
|
|
309
|
+
policy: active.policy,
|
|
310
|
+
enforcement,
|
|
311
|
+
input: policyInput,
|
|
312
|
+
facts,
|
|
313
|
+
modeState,
|
|
314
|
+
env: envOf(active, args, { locale, platform, hostKind }),
|
|
315
|
+
};
|
|
316
|
+
const evaluation = evaluatePolicy(request);
|
|
317
|
+
outcomes.push({ active, evaluation, result: toRuleHostResult(evaluation, request, renderer) });
|
|
318
|
+
if (withoutChannel && evaluation.conclusion === 'observe')
|
|
319
|
+
unreminded.push(active);
|
|
320
|
+
}
|
|
321
|
+
catch (error) {
|
|
322
|
+
warnings.push({
|
|
323
|
+
reason: `policy_evaluation_failed: rule ${active.ruleId} (${active.mode}): ${errorText(error)}`,
|
|
324
|
+
nextAction: 'the rule was not judged for this call; report the evaluator fault',
|
|
325
|
+
});
|
|
326
|
+
}
|
|
327
|
+
}
|
|
328
|
+
const live = outcomes.filter((outcome) => outcome.active.mode === 'live');
|
|
329
|
+
const collectedAdvisory = collectAdvisory(live);
|
|
330
|
+
const advisory = collectedAdvisory?.text;
|
|
331
|
+
const advisoryRuleIds = collectedAdvisory?.ruleIds ?? [];
|
|
332
|
+
const observations = observationsOf(outcomes);
|
|
333
|
+
const degraded = degradationOf(live, modeState);
|
|
334
|
+
if (degraded !== null) {
|
|
335
|
+
warnings.push({ reason: degraded, nextAction: 'the affected live rule could not judge this call; the call was allowed. Check the host context wiring and the governance workspace' });
|
|
336
|
+
recordDegradedEnforcement(args.workspaceDir, degraded.slice(0, MAX_REASON));
|
|
337
|
+
const [first] = live;
|
|
338
|
+
if (first !== undefined) {
|
|
339
|
+
observations.push({
|
|
340
|
+
kind: 'policy_degraded',
|
|
341
|
+
ruleId: first.active.ruleId,
|
|
342
|
+
activationId: first.active.activationId,
|
|
343
|
+
mode: 'live',
|
|
344
|
+
reason: degraded.slice(0, MAX_REASON),
|
|
345
|
+
nextAction: 'check the host context wiring and the governance workspace',
|
|
346
|
+
});
|
|
347
|
+
}
|
|
348
|
+
}
|
|
349
|
+
for (const active of unreminded) {
|
|
350
|
+
const reason = `advisory_channel_unavailable: host ${hostKind ?? 'unknown'} has no way to hand a reminder to the model without blocking, so rule ${active.ruleId} was judged as observe`;
|
|
351
|
+
const nextAction = 'the reminder was not delivered and no reminder was counted; set the rule to block if it must be enforced on this host, or keep it as observe';
|
|
352
|
+
warnings.push({ reason, nextAction });
|
|
353
|
+
recordDegradedEnforcement(args.workspaceDir, reason.slice(0, MAX_REASON));
|
|
354
|
+
observations.push({ kind: 'policy_degraded', ruleId: active.ruleId, activationId: active.activationId, mode: active.mode, reason: reason.slice(0, MAX_REASON), nextAction });
|
|
355
|
+
}
|
|
356
|
+
const ledgerFailures = writeLedger(outcomes, {
|
|
357
|
+
workspaceDir: args.workspaceDir,
|
|
358
|
+
projectRoot: args.projectRoot,
|
|
359
|
+
sessionId: args.sessionId,
|
|
360
|
+
toolCallId: args.toolCallId,
|
|
361
|
+
hostKind,
|
|
362
|
+
facts,
|
|
363
|
+
now: options?.now?.() ?? new Date(),
|
|
364
|
+
});
|
|
365
|
+
for (const failure of ledgerFailures) {
|
|
366
|
+
const nextAction = 'the verdict was applied without a ledger row; check that state.db of the governance workspace is writable';
|
|
367
|
+
warnings.push({ reason: `policy_ledger_write_failed: ${failure}`, nextAction });
|
|
368
|
+
const [subject] = outcomes;
|
|
369
|
+
if (subject !== undefined) {
|
|
370
|
+
observations.push({ kind: 'policy_ledger_write_failed', ruleId: subject.active.ruleId, activationId: subject.active.activationId, mode: subject.active.mode, reason: failure.slice(0, MAX_REASON), nextAction });
|
|
371
|
+
}
|
|
372
|
+
}
|
|
373
|
+
return { outcomes, observations: observations.slice(0, MAX_OBSERVATIONS), warnings, advisory, advisoryRuleIds };
|
|
374
|
+
};
|
|
375
|
+
return {
|
|
376
|
+
trustedPdBinaries: () => resolvePdBinary().trusted,
|
|
377
|
+
evaluate,
|
|
378
|
+
};
|
|
379
|
+
}
|
|
@@ -2,6 +2,7 @@ import { type RuleHostResult, type ToolSemanticRegistry, type GovernanceHostKind
|
|
|
2
2
|
import type { RuleTargetEvidence } from '@principles/core/runtime/internalization/rule-context-v2';
|
|
3
3
|
import type { HostEvent, HostEventResult } from '@principles/core/host';
|
|
4
4
|
import { type RuleImplementationRuntime } from './rule-implementation-runtime.js';
|
|
5
|
+
import { type RulePolicyGateOptions } from './production-policy-gate.js';
|
|
5
6
|
/**
|
|
6
7
|
* PRI-1208 Stage 3: structured, bounded evaluation faults.
|
|
7
8
|
*
|
|
@@ -65,6 +66,11 @@ export interface ProductionRuleHostGateOptions {
|
|
|
65
66
|
* try/catch and can never alter the decision.
|
|
66
67
|
*/
|
|
67
68
|
affectedToolsObservability?: AffectedToolsObservabilityOptions;
|
|
69
|
+
/**
|
|
70
|
+
* RulePolicyV2 evaluation (SPEC-PD-RULE-POLICY-001 design §13). Policies are judged in-process
|
|
71
|
+
* by core's `evaluatePolicy`; nothing here starts a child process. Every field has a default.
|
|
72
|
+
*/
|
|
73
|
+
rulePolicy?: RulePolicyGateOptions;
|
|
68
74
|
}
|
|
69
75
|
/** One observation-only "declared scope does not cover the action" record. */
|
|
70
76
|
export interface AffectedToolsMismatchEvent {
|