@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
@@ -0,0 +1,197 @@
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 { verifyPiArtifactRowDigest, } from '@principles/core/runtime';
21
+ import { COGNITIVE_ACT_REGISTRY_VERSION, FACT_CATALOG_VERSION, validatePolicyEnforcement, validateRulePolicyV2, } from '@principles/core/runtime/internalization/rule-policy-gate';
22
+ /** `activations.action` values that arm a rule policy, and the mode each one stands for. */
23
+ export const POLICY_ACTIVATION_ACTIONS = Object.freeze({
24
+ code_tool_hook_live_activate: 'live',
25
+ code_tool_hook_shadow_activate: 'shadow',
26
+ code_tool_hook_challenger_activate: 'challenger',
27
+ });
28
+ export function policyModeOfAction(action) {
29
+ if (typeof action !== 'string' || !Object.hasOwn(POLICY_ACTIVATION_ACTIONS, action))
30
+ return null;
31
+ const mode = Reflect.get(POLICY_ACTIVATION_ACTIONS, action);
32
+ return mode ?? null;
33
+ }
34
+ const MAX_ERRORS_IN_REASON = 3;
35
+ const MAX_FAULT_TEXT = 300;
36
+ function isRecord(value) {
37
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
38
+ }
39
+ function ownValue(record, key) {
40
+ return Object.hasOwn(record, key) ? record[key] : undefined;
41
+ }
42
+ function bounded(text) {
43
+ return text.replace(/\s+/g, ' ').slice(0, MAX_FAULT_TEXT);
44
+ }
45
+ function fault(reason, nextAction) {
46
+ return { ok: false, fault: { reason: bounded(reason), nextAction: bounded(nextAction) } };
47
+ }
48
+ /** An artifact is a policy candidate when `content_json.rulePolicy` is an object with `version === 2`. */
49
+ export function isPolicyArtifactContent(content) {
50
+ if (!isRecord(content))
51
+ return false;
52
+ const policy = ownValue(content, 'rulePolicy');
53
+ return isRecord(policy) && ownValue(policy, 'version') === 2;
54
+ }
55
+ function readVersion(content, key) {
56
+ const value = ownValue(content, key);
57
+ return typeof value === 'number' && Number.isSafeInteger(value) && value >= 1 ? value : null;
58
+ }
59
+ function nonEmptyString(value) {
60
+ return typeof value === 'string' && value.trim().length > 0 ? value : null;
61
+ }
62
+ function readEnforcement(enforcementJson) {
63
+ if (enforcementJson === null || enforcementJson === undefined) {
64
+ return fault('enforcement_missing: the activation has no Owner enforcement decision', 'record the Owner enforcement decision for this activation (observe, remind or block) and reactivate; the policy was not evaluated');
65
+ }
66
+ if (typeof enforcementJson !== 'string') {
67
+ return fault('enforcement_invalid: enforcement_json is not text', 'repair the activation decision record; the policy was not evaluated');
68
+ }
69
+ let parsed;
70
+ try {
71
+ parsed = JSON.parse(enforcementJson);
72
+ }
73
+ catch (error) {
74
+ return fault(`enforcement_invalid: enforcement_json is not valid JSON (${error instanceof Error ? error.message : String(error)})`, 'repair the activation decision record; the policy was not evaluated');
75
+ }
76
+ const checked = validatePolicyEnforcement(parsed);
77
+ if (!checked.ok) {
78
+ const detail = checked.errors.slice(0, MAX_ERRORS_IN_REASON).map((error) => `${error.path}: ${error.message}`).join('; ');
79
+ return fault(`enforcement_invalid: ${detail}`, 'record a valid Owner enforcement decision for this activation; the policy was not evaluated');
80
+ }
81
+ return { ok: true, enforcement: checked.enforcement };
82
+ }
83
+ /**
84
+ * Judge one policy artifact. `content` must already satisfy `isPolicyArtifactContent` and have
85
+ * passed the digest check. A catalog or act registry version above this build's is refused
86
+ * (`catalog_version_unsupported`); a lower one is accepted because facts and acts only grow.
87
+ */
88
+ export function parseActivePolicy(ref, content, enforcementJson) {
89
+ const validated = validateRulePolicyV2(ownValue(content, 'rulePolicy'));
90
+ if (!validated.ok) {
91
+ const detail = validated.errors.slice(0, MAX_ERRORS_IN_REASON).map((error) => `${error.path}: ${error.message}`).join('; ');
92
+ return fault(`policy_artifact_invalid: ${detail}`, 'regenerate the rule policy artifact and approve it again; the policy was not evaluated');
93
+ }
94
+ const factCatalogVersion = readVersion(content, 'factCatalogVersion');
95
+ const actRegistryVersion = readVersion(content, 'actRegistryVersion');
96
+ if (factCatalogVersion === null || actRegistryVersion === null) {
97
+ return fault('policy_artifact_invalid: factCatalogVersion and actRegistryVersion must be positive integers', 'regenerate the rule policy artifact and approve it again; the policy was not evaluated');
98
+ }
99
+ if (factCatalogVersion > FACT_CATALOG_VERSION || actRegistryVersion > COGNITIVE_ACT_REGISTRY_VERSION) {
100
+ return fault(`catalog_version_unsupported: artifact uses fact catalog ${factCatalogVersion} and act registry ${actRegistryVersion}; this build supports ${FACT_CATALOG_VERSION} and ${COGNITIVE_ACT_REGISTRY_VERSION}`, 'update PD to a build that supports this artifact, or regenerate the rule with this build; the policy was not evaluated');
101
+ }
102
+ const enforcement = readEnforcement(enforcementJson);
103
+ if (!enforcement.ok)
104
+ return enforcement;
105
+ return {
106
+ ok: true,
107
+ active: {
108
+ activationId: ref.activationId,
109
+ artifactId: ref.artifactId,
110
+ ruleId: nonEmptyString(ownValue(content, 'ruleId')) ?? ref.sourceRuleId ?? ref.artifactId,
111
+ ruleLineageId: nonEmptyString(ownValue(content, 'ruleLineageId')) ?? ref.artifactId,
112
+ mode: ref.mode,
113
+ policy: validated.policy,
114
+ enforcement: enforcement.enforcement,
115
+ },
116
+ };
117
+ }
118
+ const ACTIVE_POLICY_ROWS_SQL = `
119
+ SELECT a.activation_id, a.artifact_id, a.action,
120
+ c.enforcement AS control_enforcement,
121
+ d.artifact_digest AS approved_artifact_digest,
122
+ d.enforcement_json AS enforcement_json
123
+ FROM activations a
124
+ LEFT JOIN activation_control_states c ON a.activation_id = c.activation_id
125
+ LEFT JOIN activation_decisions d ON d.rowid = (
126
+ SELECT d2.rowid FROM activation_decisions d2
127
+ WHERE d2.subject_kind = 'activation'
128
+ AND d2.activation_id = a.activation_id
129
+ AND d2.principal_kind = 'configured_owner'
130
+ AND d2.decision IN ('promote_live', 'continue_observing', 'recover_to_shadow')
131
+ ORDER BY d2.decided_at DESC, d2.rowid DESC LIMIT 1
132
+ )
133
+ WHERE a.channel = 'code_tool_hook' AND a.deactivated_at IS NULL
134
+ ORDER BY a.activated_at ASC
135
+ `;
136
+ const ARTIFACT_ROW_SQL = `
137
+ SELECT artifact_id, artifact_kind, source_task_id, source_principle_id, source_rule_id,
138
+ lineage_artifact_ids, validation_status, content_json, created_at, updated_at
139
+ FROM pi_artifacts WHERE artifact_id = ?
140
+ `;
141
+ function parseContent(contentJson) {
142
+ try {
143
+ return JSON.parse(contentJson);
144
+ }
145
+ catch {
146
+ // Not JSON: not a policy artifact. The code branch of the gate reports it as invalid.
147
+ return null;
148
+ }
149
+ }
150
+ /**
151
+ * Active rule policies (live, shadow and challenger) of the governance workspace behind
152
+ * `connection`. Throws when the activation tables cannot be read: the caller must treat that as
153
+ * "unknown", never as "no policies".
154
+ */
155
+ export function loadActivePolicies(connection) {
156
+ const db = connection.getDb();
157
+ const rows = db.prepare(ACTIVE_POLICY_ROWS_SQL).all();
158
+ if (!Array.isArray(rows))
159
+ throw new Error('active_policy_rows_invalid: activation query did not return rows');
160
+ const active = [];
161
+ const faults = [];
162
+ for (const row of rows) {
163
+ if (!isRecord(row))
164
+ throw new Error('active_policy_rows_invalid: activation row is not an object');
165
+ const mode = policyModeOfAction(row.action);
166
+ const activationId = nonEmptyString(row.activation_id);
167
+ const artifactId = nonEmptyString(row.artifact_id);
168
+ if (mode === null || activationId === null || artifactId === null)
169
+ continue;
170
+ const artifact = db.prepare(ARTIFACT_ROW_SQL).get(artifactId);
171
+ if (!isRecord(artifact) || typeof artifact.content_json !== 'string')
172
+ continue;
173
+ const content = parseContent(artifact.content_json);
174
+ if (!isPolicyArtifactContent(content))
175
+ continue;
176
+ const refuse = (result) => {
177
+ faults.push({ ...result.fault, activationId });
178
+ };
179
+ if (row.control_enforcement !== 'eligible') {
180
+ refuse(fault(`activation_not_eligible: ${activationId}`, 'review the activation control state; the policy is not enforced'));
181
+ continue;
182
+ }
183
+ const approvedDigest = typeof row.approved_artifact_digest === 'string' ? row.approved_artifact_digest : null;
184
+ const digest = verifyPiArtifactRowDigest(artifact, artifact.content_json, approvedDigest);
185
+ if (digest.outcome !== 'verified') {
186
+ refuse(fault(`policy_digest_${digest.outcome}: ${activationId}`, 'the artifact does not match its Owner-approved digest; re-approve the rule; the policy is not enforced'));
187
+ continue;
188
+ }
189
+ const sourceRuleId = nonEmptyString(artifact.source_rule_id);
190
+ const parsed = parseActivePolicy({ activationId, artifactId, sourceRuleId, mode }, content, row.enforcement_json);
191
+ if (parsed.ok)
192
+ active.push(parsed.active);
193
+ else
194
+ refuse(parsed);
195
+ }
196
+ return { active, faults };
197
+ }
@@ -0,0 +1,19 @@
1
+ /**
2
+ * Single declaration point for the host-default exempt prefixes used by the
3
+ * RulePolicy feature (SPEC-PD-RULE-POLICY-001 D7).
4
+ *
5
+ * Exempt prefixes are project-relative policy keys. A trailing `/` marks a
6
+ * directory; no trailing `/` marks one file (`MEMORY.md`). Matching is done by
7
+ * `matchesAnyPrefix` from `@principles/core/runtime/internalization/rule-policy-paths`,
8
+ * which ignores the trailing `/`.
9
+ *
10
+ * Consumers: `session-write-targets` (what counts toward the session write
11
+ * lower bound) today, the policy compiler / card renderer in later phases.
12
+ * They must read these defaults here instead of repeating literals, so the
13
+ * counted set and the enforced set cannot drift apart.
14
+ */
15
+ import type { GovernanceHostKind } from '@principles/core/runtime';
16
+ /** Exempt on every host: mode registration must never itself be gated. */
17
+ export declare const BUILTIN_EXEMPT_PREFIXES: readonly string[];
18
+ /** Built-in plus host-specific exempt prefixes. Returns a fresh array each call. */
19
+ export declare function defaultExemptPrefixes(hostKind: GovernanceHostKind): string[];
@@ -0,0 +1,12 @@
1
+ /** Exempt on every host: mode registration must never itself be gated. */
2
+ export const BUILTIN_EXEMPT_PREFIXES = Object.freeze(['.principles/modes/']);
3
+ const HOST_EXEMPT_PREFIXES = Object.freeze({
4
+ // OpenClaw keeps its own agent memory and PD state inside the project root.
5
+ openclaw: Object.freeze(['memory/', 'MEMORY.md', '.state/', '.principles/']),
6
+ codex: Object.freeze([]),
7
+ workbuddy: Object.freeze([]),
8
+ });
9
+ /** Built-in plus host-specific exempt prefixes. Returns a fresh array each call. */
10
+ export function defaultExemptPrefixes(hostKind) {
11
+ return [...BUILTIN_EXEMPT_PREFIXES, ...HOST_EXEMPT_PREFIXES[hostKind]];
12
+ }
@@ -0,0 +1,20 @@
1
+ export type PolicyRealPathResult = {
2
+ ok: true;
3
+ path: string;
4
+ } | {
5
+ ok: false;
6
+ reason: 'target_path_not_absolute' | 'target_path_unresolvable';
7
+ };
8
+ /**
9
+ * realpath for a path that may not exist yet: resolve the nearest existing
10
+ * ancestor, then re-append the remaining segments. Callers feed the result to
11
+ * `toPolicyPathKey` from `@principles/core` (pure; no I/O there).
12
+ */
13
+ export declare function realPathForPolicyTarget(candidate: string): PolicyRealPathResult;
14
+ /**
15
+ * Re-derive already extracted policy target keys through realpath. The complete
16
+ * set stays all-or-nothing: one symlink escape or unresolvable target makes the
17
+ * set unproven (`undefined`), never a partial list. Shared by the production
18
+ * gate and offline replay so both keep exactly one unproven-target semantic.
19
+ */
20
+ export declare function canonicalPolicyTargetPaths(targetPaths: readonly string[] | undefined, projectRoot: string, platform: string): readonly string[] | undefined;
@@ -0,0 +1,58 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { toPolicyPathKey } from '@principles/core/runtime/internalization/rule-policy-paths';
4
+ /**
5
+ * realpath for a path that may not exist yet: resolve the nearest existing
6
+ * ancestor, then re-append the remaining segments. Callers feed the result to
7
+ * `toPolicyPathKey` from `@principles/core` (pure; no I/O there).
8
+ */
9
+ export function realPathForPolicyTarget(candidate) {
10
+ if (!path.isAbsolute(candidate))
11
+ return { ok: false, reason: 'target_path_not_absolute' };
12
+ let current = path.resolve(candidate);
13
+ const suffix = [];
14
+ for (;;) {
15
+ try {
16
+ const realCurrent = fs.realpathSync.native(current);
17
+ return { ok: true, path: path.join(realCurrent, ...suffix.reverse()) };
18
+ }
19
+ catch (error) {
20
+ // Only a missing path (or a non-directory ancestor) means "walk up to the
21
+ // nearest existing ancestor". Any other failure (EACCES, ELOOP, invalid
22
+ // argument) must not be canonicalized from a partially resolved prefix.
23
+ const code = typeof error === 'object' && error !== null && Object.hasOwn(error, 'code') ? Reflect.get(error, 'code') : undefined;
24
+ if (code !== 'ENOENT' && code !== 'ENOTDIR')
25
+ return { ok: false, reason: 'target_path_unresolvable' };
26
+ const parent = path.dirname(current);
27
+ if (parent === current)
28
+ return { ok: false, reason: 'target_path_unresolvable' };
29
+ suffix.push(path.basename(current));
30
+ current = parent;
31
+ }
32
+ }
33
+ }
34
+ /**
35
+ * Re-derive already extracted policy target keys through realpath. The complete
36
+ * set stays all-or-nothing: one symlink escape or unresolvable target makes the
37
+ * set unproven (`undefined`), never a partial list. Shared by the production
38
+ * gate and offline replay so both keep exactly one unproven-target semantic.
39
+ */
40
+ export function canonicalPolicyTargetPaths(targetPaths, projectRoot, platform) {
41
+ if (targetPaths === undefined)
42
+ return undefined;
43
+ const root = realPathForPolicyTarget(path.resolve(projectRoot));
44
+ if (!root.ok)
45
+ return undefined;
46
+ const keys = [];
47
+ for (const key of targetPaths) {
48
+ const real = realPathForPolicyTarget(path.resolve(projectRoot, ...key.split('/')));
49
+ if (!real.ok)
50
+ return undefined;
51
+ const realKey = toPolicyPathKey(real.path, root.path, platform);
52
+ if (realKey === null || realKey === '')
53
+ return undefined;
54
+ if (!keys.includes(realKey))
55
+ keys.push(realKey);
56
+ }
57
+ return keys;
58
+ }
@@ -0,0 +1,52 @@
1
+ import { reconstructSourcePolicyTestCase, type RulePolicyV2, type SessionTimeline } from '@principles/core/runtime/internalization/rule-policy-gate';
2
+ import type { ToolSemanticRegistry } from '@principles/core/runtime';
3
+ export interface PolicyReplayTrajectoryRow {
4
+ readonly id: number;
5
+ readonly sessionId: string;
6
+ readonly toolName: string;
7
+ readonly outcome: string;
8
+ readonly paramsJson: string;
9
+ readonly createdAt: string;
10
+ readonly projectDir: string;
11
+ readonly hostKind: string;
12
+ readonly toolUseId?: string;
13
+ }
14
+ export interface PolicyReplayRowsResult {
15
+ readonly rows: readonly PolicyReplayTrajectoryRow[];
16
+ /** Rows that cannot be scoped to a proven project/host/session and are therefore never replayed. */
17
+ readonly skippedUnscopedRows: number;
18
+ }
19
+ /**
20
+ * Read candidate rows in ascending time order. The DB is opened with
21
+ * `readonly: true, fileMustExist: true`; no write transaction, migration,
22
+ * checkpoint or state mutation is performed here.
23
+ */
24
+ export declare function readPolicyReplayTrajectoryRows(workspaceDir: string, options?: {
25
+ readonly since?: string;
26
+ }): PolicyReplayRowsResult;
27
+ /** Group rows by the composite session identity and reconstruct every call in ascending order. */
28
+ export declare function buildPolicyReplaySessionTimelines(rows: readonly PolicyReplayTrajectoryRow[], policy: RulePolicyV2, options: {
29
+ readonly toolSemantics: ToolSemanticRegistry;
30
+ readonly platform?: string;
31
+ }): readonly SessionTimeline[];
32
+ /** One-call convenience composition used by the CLI; the DB close happens before evaluation. */
33
+ export declare function readPolicyReplaySessionTimelines(workspaceDir: string, policy: RulePolicyV2, options?: {
34
+ readonly since?: string;
35
+ readonly platform?: string;
36
+ }): {
37
+ readonly timelines: readonly SessionTimeline[];
38
+ readonly skippedUnscopedRows: number;
39
+ };
40
+ /**
41
+ * Reconstruct a source-case decision point from already-read rows (V15). Facts that
42
+ * cannot be proven remain unknown inside the returned case; no field is inferred.
43
+ */
44
+ export declare function reconstructPolicySourceCaseFromRows(args: {
45
+ readonly rows: readonly PolicyReplayTrajectoryRow[];
46
+ readonly toolCallId: number;
47
+ readonly policy: RulePolicyV2;
48
+ readonly options: {
49
+ readonly toolSemantics: ToolSemanticRegistry;
50
+ readonly platform?: string;
51
+ };
52
+ }): ReturnType<typeof reconstructSourcePolicyTestCase> | null;
@@ -0,0 +1,259 @@
1
+ /**
2
+ * Read-only RulePolicy replay evidence assembly.
3
+ *
4
+ * This module is the I/O boundary for Requirement 14: it opens the canonical
5
+ * trajectory database read-only, reads complete session timelines once, closes it,
6
+ * and reconstructs each decision point through the same production computation
7
+ * pieces used by the live gate (`buildRuleHostAction`, `assembleBehaviorHistory`,
8
+ * `computeSessionWriteTargets`, `assembleFacts`, and the shared realpath target
9
+ * canonicalizer). The pure replay engine in core consumes only the in-memory result.
10
+ */
11
+ import Database from 'better-sqlite3';
12
+ import { classifyBashRisk } from '@principles/core/runtime/internalization/bash-risk';
13
+ import { buildRuleHostAction } from '@principles/core/runtime/internalization/rule-host-input-builder';
14
+ import { effectiveExemptPrefixes, referencedFactIds, reconstructSourcePolicyTestCase, } from '@principles/core/runtime/internalization/rule-policy-gate';
15
+ import { resolveTrajectoryDbPath } from '@principles/core/runtime/storage-paths';
16
+ import { assembleBehaviorHistory } from './behavior-history.js';
17
+ import { assembleFacts, normalizedPathTargetKeys } from './fact-assembler.js';
18
+ import { resolveWorkspaceHostToolSemantics } from './host-tool-semantic-resolver.js';
19
+ import { BUILTIN_EXEMPT_PREFIXES, defaultExemptPrefixes } from './rule-policy-host-defaults.js';
20
+ import { canonicalPolicyTargetPaths } from './rule-policy-paths-fs.js';
21
+ import { computeSessionWriteTargets } from './session-write-targets.js';
22
+ const HISTORY_LIMIT = 100;
23
+ const VALID_HOSTS = new Set(['openclaw', 'codex', 'workbuddy']);
24
+ function isRecord(value) {
25
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
26
+ }
27
+ function hasUnsafeKey(value) {
28
+ return Object.keys(value).some((key) => key === '__proto__' || key === 'constructor' || key === 'prototype');
29
+ }
30
+ function parseParams(row) {
31
+ let parsed;
32
+ try {
33
+ parsed = JSON.parse(row.paramsJson);
34
+ }
35
+ catch (error) {
36
+ throw new Error(`replay_row_params_invalid:${row.id}:${error instanceof Error ? error.message : String(error)}`, { cause: error });
37
+ }
38
+ if (!isRecord(parsed))
39
+ throw new Error(`replay_row_params_not_object:${row.id}`);
40
+ if (hasUnsafeKey(parsed))
41
+ throw new Error(`replay_row_params_unsafe_key:${row.id}`);
42
+ return parsed;
43
+ }
44
+ function validHost(value) {
45
+ return VALID_HOSTS.has(value);
46
+ }
47
+ /**
48
+ * Read candidate rows in ascending time order. The DB is opened with
49
+ * `readonly: true, fileMustExist: true`; no write transaction, migration,
50
+ * checkpoint or state mutation is performed here.
51
+ */
52
+ export function readPolicyReplayTrajectoryRows(workspaceDir, options = {}) {
53
+ const { since } = options;
54
+ if (since !== undefined && !Number.isFinite(Date.parse(since)))
55
+ throw new Error('replay_since_invalid');
56
+ const db = new Database(resolveTrajectoryDbPath(workspaceDir), { readonly: true, fileMustExist: true });
57
+ try {
58
+ db.pragma('busy_timeout = 100');
59
+ const sql = `
60
+ SELECT id, session_id, tool_name, outcome, params_json, created_at, project_dir, host_kind, tool_use_id
61
+ FROM tool_calls
62
+ ${since === undefined ? '' : 'WHERE created_at >= ?'}
63
+ ORDER BY created_at ASC, id ASC
64
+ `;
65
+ const rows = since === undefined ? db.prepare(sql).all() : db.prepare(sql).all(since);
66
+ const valid = [];
67
+ let skipped = 0;
68
+ for (const value of rows) {
69
+ if (!isRecord(value) || typeof value.id !== 'number' || !Number.isSafeInteger(value.id)
70
+ || typeof value.session_id !== 'string' || typeof value.tool_name !== 'string'
71
+ || typeof value.outcome !== 'string' || typeof value.params_json !== 'string'
72
+ || typeof value.created_at !== 'string') {
73
+ throw new Error('replay_trajectory_row_malformed');
74
+ }
75
+ if (typeof value.project_dir !== 'string' || typeof value.host_kind !== 'string') {
76
+ skipped += 1;
77
+ continue;
78
+ }
79
+ valid.push({
80
+ id: value.id,
81
+ sessionId: value.session_id,
82
+ toolName: value.tool_name,
83
+ outcome: value.outcome,
84
+ paramsJson: value.params_json,
85
+ createdAt: value.created_at,
86
+ projectDir: value.project_dir,
87
+ hostKind: value.host_kind,
88
+ ...(typeof value.tool_use_id === 'string' && value.tool_use_id.length > 0 ? { toolUseId: value.tool_use_id } : {}),
89
+ });
90
+ }
91
+ return { rows: valid, skippedUnscopedRows: skipped };
92
+ }
93
+ finally {
94
+ db.close();
95
+ }
96
+ }
97
+ function absentModeState() {
98
+ return {
99
+ version: 1,
100
+ status: 'absent',
101
+ acts: {},
102
+ scopePaths: null,
103
+ scopeRevision: null,
104
+ latestSituationClass: null,
105
+ waiversByRule: {},
106
+ remindersByRule: {},
107
+ declareHint: null,
108
+ waiveHint: null,
109
+ suggestedFile: null,
110
+ };
111
+ }
112
+ function priorRowsFor(rows, row) {
113
+ return rows.filter((candidate) => candidate.createdAt < row.createdAt
114
+ && !(row.toolUseId !== undefined && candidate.toolUseId === row.toolUseId));
115
+ }
116
+ function activityRow(row) {
117
+ return { id: row.id, toolName: row.toolName, outcome: row.outcome, paramsJson: row.paramsJson, createdAt: row.createdAt };
118
+ }
119
+ function writeRow(row) {
120
+ return { id: row.id, toolName: row.toolName, outcome: row.outcome, paramsJson: row.paramsJson };
121
+ }
122
+ function replayCall(context) {
123
+ const { rows, row, sequence, policy, toolSemantics, platform } = context;
124
+ const params = parseParams(row);
125
+ const canonicalKind = toolSemantics.resolve(row.toolName);
126
+ const action = buildRuleHostAction(row.toolName, params, row.projectDir, {
127
+ canonicalKind,
128
+ writePayloadFormat: toolSemantics.resolveWritePayloadFormat(row.toolName),
129
+ platform,
130
+ });
131
+ const inputTargetPaths = action.targetPaths ?? normalizedPathTargetKeys(action.normalizedPath, action.targetEvidence, platform);
132
+ const targetPaths = canonicalKind === 'write' ? canonicalPolicyTargetPaths(inputTargetPaths, row.projectDir, platform) : inputTargetPaths;
133
+ const input = {
134
+ action: {
135
+ toolName: row.toolName,
136
+ normalizedPath: action.normalizedPath,
137
+ paramsSummary: params,
138
+ canonicalKind,
139
+ targetEvidence: action.targetEvidence,
140
+ ...(targetPaths === undefined ? {} : { targetPaths }),
141
+ ...(action.commandClasses === undefined ? {} : { commandClasses: action.commandClasses }),
142
+ },
143
+ workspace: { isRiskPath: false },
144
+ session: { sessionId: row.sessionId },
145
+ evolution: { epTier: 0 },
146
+ derived: { estimatedLineChanges: 0, bashRisk: classifyBashRisk(canonicalKind === 'execute', params) },
147
+ };
148
+ const prior = priorRowsFor(rows, row);
149
+ const historyWindow = prior.slice(-HISTORY_LIMIT);
150
+ const history = assembleBehaviorHistory(historyWindow.map((entry) => ({
151
+ id: entry.id,
152
+ toolName: entry.toolName,
153
+ outcome: entry.outcome,
154
+ paramsJson: entry.paramsJson,
155
+ ...(entry.toolUseId === undefined ? {} : { toolUseId: entry.toolUseId }),
156
+ })), prior.length > HISTORY_LIMIT, { projectDir: row.projectDir, toolSemantics, currentToolUseId: row.toolUseId ?? '' });
157
+ if (!validHost(row.hostKind))
158
+ throw new Error(`replay_host_kind_invalid:${row.id}`);
159
+ const { hostKind } = row;
160
+ const callExemptPrefixes = effectiveExemptPrefixes(policy, {
161
+ builtin: BUILTIN_EXEMPT_PREFIXES,
162
+ hostDefault: defaultExemptPrefixes(hostKind),
163
+ });
164
+ const sessionWriteTargets = computeSessionWriteTargets({
165
+ readSessionWriteRows: (_sessionId, beforeKey, isWriteTool) => {
166
+ if (typeof beforeKey !== 'string')
167
+ throw new Error('replay_before_key_invalid');
168
+ return prior.filter((entry) => entry.createdAt < beforeKey && isWriteTool(entry.toolName)).map(writeRow);
169
+ },
170
+ sessionId: row.sessionId,
171
+ beforeKey: row.createdAt,
172
+ currentTargets: inputTargetPaths ?? [],
173
+ exemptPrefixes: defaultExemptPrefixes(hostKind),
174
+ toolSemantics,
175
+ projectRoot: row.projectDir,
176
+ platform,
177
+ });
178
+ const facts = assembleFacts({
179
+ needed: referencedFactIds(policy),
180
+ current: {
181
+ kind: canonicalKind,
182
+ toolName: row.toolName,
183
+ normalizedPath: action.normalizedPath,
184
+ targetEvidence: action.targetEvidence,
185
+ ...(targetPaths === undefined ? {} : { targetPaths }),
186
+ ...(action.commandClasses === undefined ? {} : { commandClasses: action.commandClasses }),
187
+ bashRisk: classifyBashRisk(canonicalKind === 'execute', params),
188
+ },
189
+ sessionWriteTargets,
190
+ readActivity: (_sessionId, beforeKey, limit) => {
191
+ if (typeof beforeKey !== 'string')
192
+ throw new Error('replay_before_key_invalid');
193
+ const before = prior.filter((entry) => entry.createdAt < beforeKey).map(activityRow);
194
+ return { rows: [...before].reverse().slice(0, limit), truncated: before.length > limit };
195
+ },
196
+ history,
197
+ modeState: absentModeState(),
198
+ designGate: undefined,
199
+ toolSemantics,
200
+ sessionId: row.sessionId,
201
+ beforeKey: row.createdAt,
202
+ projectRoot: row.projectDir,
203
+ platform,
204
+ });
205
+ return { sequence, toolCallId: row.id, input, facts, effectiveExemptPrefixes: callExemptPrefixes };
206
+ }
207
+ /** Group rows by the composite session identity and reconstruct every call in ascending order. */
208
+ export function buildPolicyReplaySessionTimelines(rows, policy, options) {
209
+ const platform = options.platform ?? process.platform;
210
+ const groups = new Map();
211
+ for (const row of rows) {
212
+ const key = `${row.hostKind}\0${row.projectDir}\0${row.sessionId}`;
213
+ const group = groups.get(key) ?? [];
214
+ group.push(row);
215
+ groups.set(key, group);
216
+ }
217
+ const timelines = [];
218
+ for (const group of groups.values()) {
219
+ const ordered = [...group].sort((left, right) => left.createdAt === right.createdAt ? left.id - right.id : left.createdAt.localeCompare(right.createdAt));
220
+ const [first] = ordered;
221
+ if (first === undefined)
222
+ continue;
223
+ timelines.push({
224
+ sessionId: first.sessionId,
225
+ calls: ordered.map((row, index) => replayCall({ rows: ordered, row, sequence: index + 1, policy, toolSemantics: options.toolSemantics, platform })),
226
+ });
227
+ }
228
+ return timelines.sort((left, right) => left.sessionId.localeCompare(right.sessionId));
229
+ }
230
+ /** One-call convenience composition used by the CLI; the DB close happens before evaluation. */
231
+ export function readPolicyReplaySessionTimelines(workspaceDir, policy, options = {}) {
232
+ const semantics = resolveWorkspaceHostToolSemantics(workspaceDir);
233
+ if (!semantics.ok)
234
+ throw new Error(`replay_tool_semantics_unavailable:${semantics.reason}`);
235
+ const rows = readPolicyReplayTrajectoryRows(workspaceDir, options);
236
+ return {
237
+ timelines: buildPolicyReplaySessionTimelines(rows.rows, policy, { toolSemantics: semantics.registry, ...(options.platform === undefined ? {} : { platform: options.platform }) }),
238
+ skippedUnscopedRows: rows.skippedUnscopedRows,
239
+ };
240
+ }
241
+ /**
242
+ * Reconstruct a source-case decision point from already-read rows (V15). Facts that
243
+ * cannot be proven remain unknown inside the returned case; no field is inferred.
244
+ */
245
+ export function reconstructPolicySourceCaseFromRows(args) {
246
+ const { rows, toolCallId, policy, options } = args;
247
+ const row = rows.find((candidate) => candidate.id === toolCallId);
248
+ if (row === undefined)
249
+ return null;
250
+ const sessionRows = rows.filter((candidate) => candidate.sessionId === row.sessionId && candidate.projectDir === row.projectDir && candidate.hostKind === row.hostKind);
251
+ const ordered = [...sessionRows].sort((left, right) => left.createdAt === right.createdAt ? left.id - right.id : left.createdAt.localeCompare(right.createdAt));
252
+ const sequence = ordered.findIndex((candidate) => candidate.id === row.id) + 1;
253
+ const call = replayCall({ rows: ordered, row, sequence, policy, toolSemantics: options.toolSemantics, platform: options.platform ?? process.platform });
254
+ return reconstructSourcePolicyTestCase({
255
+ id: `source-${toolCallId}`,
256
+ description: `Reconstructed decision point from trajectory tool call ${toolCallId}`,
257
+ facts: call.facts,
258
+ });
259
+ }