@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,86 @@
1
+ import type { SessionWriteTargets } from '@principles/core/runtime/internalization/rule-context-v2';
2
+ import type { ToolSemanticRegistry } from '@principles/core/runtime';
3
+ export interface SessionWriteRow {
4
+ id: number;
5
+ toolName: string;
6
+ outcome: string;
7
+ paramsJson: string;
8
+ }
9
+ /**
10
+ * Injected read-only row reader. Returns every row of `sessionId` strictly
11
+ * before `beforeKey` whose tool name satisfies `isWriteTool`, oldest first, with
12
+ * NO window limit. Host scoping (project_dir, host attribution, excluding the
13
+ * current call) lives inside the reader. `beforeKey` is host-defined: an ISO
14
+ * created_at cutoff for Codex/WorkBuddy, a tool_calls.id upper bound for OpenClaw.
15
+ */
16
+ export type ReadSessionWriteRows = (sessionId: string, beforeKey: string | number, isWriteTool: (toolName: string) => boolean) => readonly SessionWriteRow[];
17
+ export interface SessionWriteTargetQuery {
18
+ readSessionWriteRows: ReadSessionWriteRows;
19
+ sessionId: string;
20
+ beforeKey: string | number;
21
+ /** Raw targets of the current call (absolute or project-relative, un-sanitized). */
22
+ currentTargets: readonly string[];
23
+ /** Exempt prefixes as policy keys (project-relative, '/' separated). */
24
+ exemptPrefixes: readonly string[];
25
+ toolSemantics: ToolSemanticRegistry;
26
+ /** Absolute project root that history keys are relative to. */
27
+ projectRoot: string;
28
+ /** Path key platform; defaults to `process.platform`. */
29
+ platform?: string;
30
+ }
31
+ /**
32
+ * Policy keys of the write targets of ONE history call whose directory can be
33
+ * proven (same extraction and proof rules as the session lower bound, but with
34
+ * no exemption filtering: the `history` fact shows what was touched). A target
35
+ * that cannot be proven is omitted, never guessed. Non-write tools have none.
36
+ */
37
+ export declare function provableWriteTargetKeys(toolName: string, params: Record<string, unknown>, scope: {
38
+ registry: ToolSemanticRegistry;
39
+ projectRoot: string;
40
+ platform?: string;
41
+ }): readonly string[];
42
+ export declare function computeSessionWriteTargets(query: SessionWriteTargetQuery): SessionWriteTargets;
43
+ export interface WorkspaceSessionWriteRowReaderOptions {
44
+ /** Exact stored `project_dir` scope (Codex cwd / WorkBuddy payload cwd). */
45
+ projectDir: string;
46
+ /** Host stamp the rows must carry (`tool_calls.host_kind`). */
47
+ hostKind: string;
48
+ /** Current call's host-authoritative tool_use_id, excluded even on timestamp ties. */
49
+ excludeToolUseId: string;
50
+ }
51
+ /**
52
+ * Reader for Codex / WorkBuddy: wraps the trajectory database of the governance
53
+ * workspace. `beforeKey` must be the ISO created_at cutoff captured at PreToolUse.
54
+ */
55
+ export declare function createWorkspaceSessionWriteRowReader(workspaceDir: string, options: WorkspaceSessionWriteRowReaderOptions): ReadSessionWriteRows;
56
+ /** Structured unavailable result: whitespace-normalized, capped like every other reason. */
57
+ export declare function unavailableSessionWriteTargets(reason: string): SessionWriteTargets;
58
+ export interface CurrentWriteRequest {
59
+ toolName: string;
60
+ targetPath: string;
61
+ rawPayload: unknown;
62
+ }
63
+ /**
64
+ * Raw targets the CURRENT call will write: none unless it is a write tool, the
65
+ * patch file headers for a `file-header-patch` tool, otherwise the request's
66
+ * target path. Every host feeds this to `computeSessionWriteTargets` so the
67
+ * current call is counted the same way everywhere.
68
+ */
69
+ export declare function currentWriteTargetsOf(request: CurrentWriteRequest, registry: ToolSemanticRegistry): readonly string[];
70
+ export interface WorkspaceSessionWriteTargetsInput {
71
+ workspaceDir: string;
72
+ projectDir: string;
73
+ hostKind: 'codex' | 'workbuddy';
74
+ sessionId: string;
75
+ /** Pre-event cutoff captured at PreToolUse. */
76
+ cutoffAt: Date;
77
+ currentToolUseId: string;
78
+ request: CurrentWriteRequest;
79
+ toolSemantics: ToolSemanticRegistry;
80
+ }
81
+ /**
82
+ * Codex / WorkBuddy entry point: session-wide write-target lower bound from the
83
+ * governance workspace's trajectory database. Never throws; any failure is a
84
+ * structured `unavailable` (the caller keeps its own history verdict).
85
+ */
86
+ export declare function resolveWorkspaceSessionWriteTargets(input: WorkspaceSessionWriteTargetsInput): SessionWriteTargets;
@@ -0,0 +1,216 @@
1
+ /**
2
+ * Session-wide write-target lower bound (Requirements 1.1-1.4, 1.6).
3
+ *
4
+ * `computeSessionWriteTargets` is pure computation over an injected row reader:
5
+ * it holds no database connection. Hosts supply a reader (Codex/WorkBuddy:
6
+ * `createWorkspaceSessionWriteRowReader`; OpenClaw: task 3.8).
7
+ *
8
+ * The result is a LOWER BOUND on distinct non-exempt write targets. Anything
9
+ * whose directory cannot be proven (basename-only `<path:...>` targets,
10
+ * truncated patch headers, out-of-project paths, synthetic labels) is dropped,
11
+ * never counted and never treated as an exemption, so the bound can only be low.
12
+ */
13
+ import fs from 'node:fs';
14
+ import path from 'node:path';
15
+ import { extractFileHeaderPatchTargets, extractFilePathFromParams, } from '@principles/core/runtime/internalization/rule-host-input-builder';
16
+ import { matchesAnyPrefix, toPolicyPathKey } from '@principles/core/runtime/internalization/rule-policy-paths';
17
+ import { defaultExemptPrefixes } from './rule-policy-host-defaults.js';
18
+ import { realPathForPolicyTarget } from './rule-policy-paths-fs.js';
19
+ import { readWorkspaceSessionWriteRowsBefore } from './workspace-behavior-evidence.js';
20
+ const MAX_REASON_LENGTH = 300;
21
+ const TRUNCATION_MARKER = '___TRUNCATED___';
22
+ const VALID_RULE_TOOL_OUTCOMES = new Set(['success', 'failure', 'blocked', 'unknown']);
23
+ function isRecord(value) {
24
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
25
+ }
26
+ function isSessionWriteRow(value) {
27
+ return isRecord(value) && typeof value.id === 'number' && typeof value.toolName === 'string'
28
+ && typeof value.outcome === 'string' && typeof value.paramsJson === 'string';
29
+ }
30
+ function provableKey(target, scope) {
31
+ const { projectRoot, platform, realProjectRoot } = scope;
32
+ if (typeof target !== 'string' || target.length === 0)
33
+ return null;
34
+ if (target.includes(TRUNCATION_MARKER))
35
+ return null;
36
+ // Redaction / synthetic labels: <path:basename>, <tool:name>.
37
+ if (target.startsWith('<') && target.endsWith('>'))
38
+ return null;
39
+ // Drive-relative (`C:foo`) has no provable directory.
40
+ if (/^[A-Za-z]:(?![\\/])/.test(target))
41
+ return null;
42
+ const absolute = /^(?:[A-Za-z]:[\\/]|[\\/])/.test(target);
43
+ const key = toPolicyPathKey(absolute ? target : `${projectRoot}/${target}`, projectRoot, platform);
44
+ // '' is the project root itself, not a file.
45
+ if (key === null || key === '')
46
+ return null;
47
+ if (realProjectRoot === null)
48
+ return key;
49
+ // When the project root exists on this host filesystem, resolve symlinks/junctions
50
+ // so two aliases to one physical file never inflate lowerBound above the real count.
51
+ const realTarget = realPathForPolicyTarget(path.resolve(projectRoot, ...key.split('/')));
52
+ if (!realTarget.ok)
53
+ return null;
54
+ const realKey = toPolicyPathKey(realTarget.path, realProjectRoot, platform);
55
+ return realKey === null || realKey === '' ? null : realKey;
56
+ }
57
+ function normalizeExemptPrefixes(prefixes, platform) {
58
+ return prefixes.map((prefix) => {
59
+ const slashed = prefix.replace(/\\/g, '/');
60
+ return platform === 'win32' ? slashed.toLowerCase() : slashed;
61
+ });
62
+ }
63
+ function writeParamsTargets(toolName, params, registry) {
64
+ if (registry.resolveWritePayloadFormat(toolName) === 'file-header-patch') {
65
+ return extractFileHeaderPatchTargets(params) ?? [];
66
+ }
67
+ const single = extractFilePathFromParams(params, { isWriteTool: true, toolName, canonicalKind: 'write' });
68
+ return single === null ? [] : [single];
69
+ }
70
+ function historyTargets(row, registry) {
71
+ const params = JSON.parse(row.paramsJson);
72
+ if (!isRecord(params))
73
+ throw new Error(`session_write_row_params_not_object:${row.id}`);
74
+ return writeParamsTargets(row.toolName, params, registry);
75
+ }
76
+ /**
77
+ * Policy keys of the write targets of ONE history call whose directory can be
78
+ * proven (same extraction and proof rules as the session lower bound, but with
79
+ * no exemption filtering: the `history` fact shows what was touched). A target
80
+ * that cannot be proven is omitted, never guessed. Non-write tools have none.
81
+ */
82
+ export function provableWriteTargetKeys(toolName, params, scope) {
83
+ const { registry, projectRoot } = scope;
84
+ const platform = scope.platform ?? process.platform;
85
+ if (registry.resolve(toolName) !== 'write')
86
+ return [];
87
+ let realProjectRoot = null;
88
+ if (platform === process.platform && path.isAbsolute(projectRoot) && fs.existsSync(projectRoot)) {
89
+ const resolvedRoot = realPathForPolicyTarget(path.resolve(projectRoot));
90
+ if (resolvedRoot.ok)
91
+ realProjectRoot = resolvedRoot.path;
92
+ }
93
+ const keys = new Set();
94
+ for (const target of writeParamsTargets(toolName, params, registry)) {
95
+ const key = provableKey(target, { projectRoot, platform, realProjectRoot });
96
+ if (key !== null)
97
+ keys.add(key);
98
+ }
99
+ return [...keys];
100
+ }
101
+ function unavailableReason(error) {
102
+ const detail = error instanceof Error ? error.message : String(error);
103
+ return `session_write_targets_failed:${detail}`.slice(0, MAX_REASON_LENGTH);
104
+ }
105
+ export function computeSessionWriteTargets(query) {
106
+ try {
107
+ const platform = query.platform ?? process.platform;
108
+ const registry = query.toolSemantics;
109
+ const exempt = normalizeExemptPrefixes(query.exemptPrefixes, platform);
110
+ let realProjectRoot = null;
111
+ if (platform === process.platform && path.isAbsolute(query.projectRoot) && fs.existsSync(query.projectRoot)) {
112
+ const resolvedRoot = realPathForPolicyTarget(path.resolve(query.projectRoot));
113
+ if (!resolvedRoot.ok)
114
+ throw new Error('session_write_project_root_unresolvable');
115
+ realProjectRoot = resolvedRoot.path;
116
+ }
117
+ const keys = new Set();
118
+ const add = (target) => {
119
+ const key = provableKey(target, { projectRoot: query.projectRoot, platform, realProjectRoot });
120
+ if (key !== null && !matchesAnyPrefix(key, exempt))
121
+ keys.add(key);
122
+ };
123
+ const rows = query.readSessionWriteRows(query.sessionId, query.beforeKey, (toolName) => registry.resolve(toolName) === 'write');
124
+ if (!Array.isArray(rows))
125
+ throw new Error('session_write_rows_not_array');
126
+ const untrustedRows = rows;
127
+ for (const row of untrustedRows) {
128
+ if (!isSessionWriteRow(row))
129
+ throw new Error('session_write_row_malformed');
130
+ if (!VALID_RULE_TOOL_OUTCOMES.has(row.outcome)) {
131
+ throw new Error(`session_write_row_invalid_outcome:${row.id}`);
132
+ }
133
+ if (row.outcome === 'blocked')
134
+ continue;
135
+ if (registry.resolve(row.toolName) !== 'write')
136
+ continue;
137
+ for (const target of historyTargets(row, registry))
138
+ add(target);
139
+ }
140
+ for (const target of query.currentTargets)
141
+ add(target);
142
+ return { status: 'available', lowerBound: keys.size, includesCurrent: true };
143
+ }
144
+ catch (error) {
145
+ return { status: 'unavailable', reason: unavailableReason(error) };
146
+ }
147
+ }
148
+ /**
149
+ * Reader for Codex / WorkBuddy: wraps the trajectory database of the governance
150
+ * workspace. `beforeKey` must be the ISO created_at cutoff captured at PreToolUse.
151
+ */
152
+ export function createWorkspaceSessionWriteRowReader(workspaceDir, options) {
153
+ return (sessionId, beforeKey, isWriteTool) => {
154
+ if (typeof beforeKey !== 'string')
155
+ throw new Error('history_cutoff_invalid');
156
+ return readWorkspaceSessionWriteRowsBefore(workspaceDir, {
157
+ sessionId,
158
+ projectDir: options.projectDir,
159
+ hostKind: options.hostKind,
160
+ beforeCreatedAt: beforeKey,
161
+ excludeToolUseId: options.excludeToolUseId,
162
+ isWriteTool,
163
+ });
164
+ };
165
+ }
166
+ /** Structured unavailable result: whitespace-normalized, capped like every other reason. */
167
+ export function unavailableSessionWriteTargets(reason) {
168
+ return { status: 'unavailable', reason: reason.replace(/\s+/g, ' ').trim().slice(0, MAX_REASON_LENGTH) || 'session_write_targets_unavailable' };
169
+ }
170
+ function rawToolParams(rawPayload) {
171
+ if (!isRecord(rawPayload) || !isRecord(rawPayload.toolInput))
172
+ return null;
173
+ return isRecord(rawPayload.toolInput.params) ? rawPayload.toolInput.params : null;
174
+ }
175
+ /**
176
+ * Raw targets the CURRENT call will write: none unless it is a write tool, the
177
+ * patch file headers for a `file-header-patch` tool, otherwise the request's
178
+ * target path. Every host feeds this to `computeSessionWriteTargets` so the
179
+ * current call is counted the same way everywhere.
180
+ */
181
+ export function currentWriteTargetsOf(request, registry) {
182
+ if (registry.resolve(request.toolName) !== 'write')
183
+ return [];
184
+ if (registry.resolveWritePayloadFormat(request.toolName) === 'file-header-patch') {
185
+ const params = rawToolParams(request.rawPayload);
186
+ const headers = params === null ? undefined : extractFileHeaderPatchTargets(params);
187
+ if (headers !== undefined && headers.length > 0)
188
+ return headers;
189
+ }
190
+ return [request.targetPath];
191
+ }
192
+ /**
193
+ * Codex / WorkBuddy entry point: session-wide write-target lower bound from the
194
+ * governance workspace's trajectory database. Never throws; any failure is a
195
+ * structured `unavailable` (the caller keeps its own history verdict).
196
+ */
197
+ export function resolveWorkspaceSessionWriteTargets(input) {
198
+ try {
199
+ return computeSessionWriteTargets({
200
+ readSessionWriteRows: createWorkspaceSessionWriteRowReader(input.workspaceDir, {
201
+ projectDir: input.projectDir,
202
+ hostKind: input.hostKind,
203
+ excludeToolUseId: input.currentToolUseId,
204
+ }),
205
+ sessionId: input.sessionId,
206
+ beforeKey: input.cutoffAt.toISOString(),
207
+ currentTargets: currentWriteTargetsOf(input.request, input.toolSemantics),
208
+ exemptPrefixes: defaultExemptPrefixes(input.hostKind),
209
+ toolSemantics: input.toolSemantics,
210
+ projectRoot: input.projectDir,
211
+ });
212
+ }
213
+ catch (error) {
214
+ return { status: 'unavailable', reason: unavailableReason(error) };
215
+ }
216
+ }
@@ -29,6 +29,7 @@ export interface SignalClassifierLog {
29
29
  export interface CreateSignalClassifierOptions {
30
30
  readonly log?: SignalClassifierLog;
31
31
  readonly timeoutMs?: number;
32
+ readonly defaultTimeoutMs?: number;
32
33
  }
33
34
  /**
34
35
  * The Stage-2 structured-output contract this classifier requests. It MUST stay
@@ -165,7 +165,7 @@ export function createSignalClassifierForWorkspace(workspaceDir, options = {}) {
165
165
  provider: profile.provider,
166
166
  model: profile.model,
167
167
  apiKeyEnv: profile.apiKeyEnv,
168
- timeoutMs: options.timeoutMs ?? profile.timeoutMs ?? 60_000,
168
+ timeoutMs: options.timeoutMs ?? profile.timeoutMs ?? options.defaultTimeoutMs ?? 60_000,
169
169
  ...(profile.maxTokens !== undefined ? { maxTokens: profile.maxTokens } : {}),
170
170
  ...(profile.baseUrl !== undefined ? { baseUrl: profile.baseUrl } : {}),
171
171
  };
@@ -0,0 +1,34 @@
1
+ export declare const SIGNAL_RATE_LIMIT_WINDOW_MS: number;
2
+ export interface DiscoveryBudgetExhaustedEvent {
3
+ scope: 'session' | 'global';
4
+ sessionId: string;
5
+ sessionDigest: string;
6
+ limit: number;
7
+ windowMs: number;
8
+ }
9
+ export interface SignalRateLimiterOptions {
10
+ strongRateLimitPerHour: number;
11
+ discoveryRateLimitPerHour: number;
12
+ discoveryRateLimitPerSessionPerHour: number;
13
+ windowMs?: number;
14
+ maxSessionBuckets?: number;
15
+ now?: () => number;
16
+ onDiscoveryExhausted?: (event: DiscoveryBudgetExhaustedEvent) => void;
17
+ }
18
+ export declare class SignalRateLimiter {
19
+ private readonly strongRateLimitPerHour;
20
+ private readonly discoveryRateLimitPerHour;
21
+ private readonly discoveryRateLimitPerSessionPerHour;
22
+ private readonly windowMs;
23
+ private readonly maxSessionBuckets;
24
+ private readonly now;
25
+ private readonly onDiscoveryExhausted?;
26
+ private readonly strongBuckets;
27
+ private discoveryBucket;
28
+ private readonly discoverySessionBuckets;
29
+ constructor(options: SignalRateLimiterOptions);
30
+ tryConsumeStrongSignal(sessionId: string): boolean;
31
+ tryConsumeDiscoveryBudget(sessionId: string): boolean;
32
+ private reportDiscoveryExhaustion;
33
+ private pruneDiscoverySessionBuckets;
34
+ }
@@ -0,0 +1,83 @@
1
+ import { createHash } from 'node:crypto';
2
+ export const SIGNAL_RATE_LIMIT_WINDOW_MS = 60 * 60 * 1000;
3
+ export class SignalRateLimiter {
4
+ strongRateLimitPerHour;
5
+ discoveryRateLimitPerHour;
6
+ discoveryRateLimitPerSessionPerHour;
7
+ windowMs;
8
+ maxSessionBuckets;
9
+ now;
10
+ onDiscoveryExhausted;
11
+ strongBuckets = new Map();
12
+ discoveryBucket = { count: 0, windowStart: 0 };
13
+ discoverySessionBuckets = new Map();
14
+ constructor(options) {
15
+ this.strongRateLimitPerHour = options.strongRateLimitPerHour;
16
+ this.discoveryRateLimitPerHour = options.discoveryRateLimitPerHour;
17
+ this.discoveryRateLimitPerSessionPerHour = options.discoveryRateLimitPerSessionPerHour;
18
+ this.windowMs = options.windowMs ?? SIGNAL_RATE_LIMIT_WINDOW_MS;
19
+ this.maxSessionBuckets = options.maxSessionBuckets ?? 64;
20
+ this.now = options.now ?? Date.now;
21
+ this.onDiscoveryExhausted = options.onDiscoveryExhausted;
22
+ }
23
+ tryConsumeStrongSignal(sessionId) {
24
+ const now = this.now();
25
+ let bucket = this.strongBuckets.get(sessionId);
26
+ if (!bucket || now - bucket.windowStart >= this.windowMs) {
27
+ bucket = { count: 0, windowStart: now };
28
+ this.strongBuckets.set(sessionId, bucket);
29
+ }
30
+ if (bucket.count >= this.strongRateLimitPerHour)
31
+ return false;
32
+ bucket.count += 1;
33
+ return true;
34
+ }
35
+ tryConsumeDiscoveryBudget(sessionId) {
36
+ if (this.discoveryRateLimitPerHour <= 0)
37
+ return true;
38
+ const now = this.now();
39
+ if (now - this.discoveryBucket.windowStart >= this.windowMs) {
40
+ this.discoveryBucket = { count: 0, windowStart: now };
41
+ }
42
+ if (this.discoveryRateLimitPerSessionPerHour > 0) {
43
+ const existing = this.discoverySessionBuckets.get(sessionId);
44
+ const bucket = !existing || now - existing.windowStart >= this.windowMs
45
+ ? { count: 0, windowStart: now }
46
+ : existing;
47
+ if (bucket.count >= this.discoveryRateLimitPerSessionPerHour) {
48
+ this.discoverySessionBuckets.set(sessionId, bucket);
49
+ this.reportDiscoveryExhaustion({ scope: 'session', sessionId, limit: this.discoveryRateLimitPerSessionPerHour, bucket });
50
+ return false;
51
+ }
52
+ bucket.count += 1;
53
+ this.discoverySessionBuckets.set(sessionId, bucket);
54
+ this.pruneDiscoverySessionBuckets(now);
55
+ }
56
+ if (this.discoveryBucket.count >= this.discoveryRateLimitPerHour) {
57
+ this.reportDiscoveryExhaustion({ scope: 'global', sessionId, limit: this.discoveryRateLimitPerHour, bucket: this.discoveryBucket });
58
+ return false;
59
+ }
60
+ this.discoveryBucket.count += 1;
61
+ return true;
62
+ }
63
+ reportDiscoveryExhaustion(input) {
64
+ if (input.bucket.exhaustionLogged)
65
+ return;
66
+ input.bucket.exhaustionLogged = true;
67
+ this.onDiscoveryExhausted?.({
68
+ scope: input.scope,
69
+ sessionId: input.sessionId,
70
+ sessionDigest: createHash('sha256').update(input.sessionId, 'utf8').digest('hex').slice(0, 12),
71
+ limit: input.limit,
72
+ windowMs: this.windowMs,
73
+ });
74
+ }
75
+ pruneDiscoverySessionBuckets(now) {
76
+ if (this.discoverySessionBuckets.size <= this.maxSessionBuckets)
77
+ return;
78
+ for (const [key, bucket] of this.discoverySessionBuckets) {
79
+ if (now - bucket.windowStart >= this.windowMs)
80
+ this.discoverySessionBuckets.delete(key);
81
+ }
82
+ }
83
+ }
@@ -48,6 +48,8 @@ export interface TrajectoryRetentionReport {
48
48
  indexesError: string | null;
49
49
  /** Present on refused/failed outcomes (cli-6). */
50
50
  nextAction?: string;
51
+ /** RulePolicy decision-ledger purge sharing this maintenance sweep's cadence and cutoff. */
52
+ policyDecisions?: PolicyDecisionRetentionReport;
51
53
  }
52
54
  export interface RunTrajectoryRetentionOptions {
53
55
  workspaceDir: string;
@@ -62,6 +64,12 @@ export declare function trajectoryRetentionPaths(workspaceDir: string): {
62
64
  lockPath: string;
63
65
  exportsDir: string;
64
66
  };
67
+ export interface PolicyDecisionRetentionReport {
68
+ status: 'purged' | 'skipped' | 'degraded';
69
+ purged: number;
70
+ reason?: string;
71
+ nextAction?: string;
72
+ }
65
73
  /**
66
74
  * One retention attempt for one workspace.
67
75
  *
@@ -21,6 +21,9 @@ import fs from 'node:fs';
21
21
  import path from 'node:path';
22
22
  import Database from 'better-sqlite3';
23
23
  import { EMPTY_RETENTION_MARKER, computeRetentionCutoff, ensureTrajectoryRetentionIndexes, isRetentionCutoffInWindow, missingTrajectoryRetentionIndexes, normalizeRetentionMarker, nextBackoffUntil, resolveTrajectoryRetentionPolicy, runTrajectoryRetentionBatches, TRAJECTORY_RETENTION_TABLES, } from '@principles/core/runtime';
24
+ import { SqliteConnection } from '@principles/core/runtime';
25
+ import { SqliteDecisionLedgerStore } from '@principles/core/runtime/internalization/rule-policy-modes';
26
+ import { resolveStateDbPath } from '@principles/core/runtime/storage-paths';
24
27
  import { loadPdConfigForPlugin } from './pd-config.js';
25
28
  import { releaseExclusiveLock, tryAcquireExclusiveLockSync, } from './product-telemetry/control-state-lock.js';
26
29
  export const TRAJECTORY_RETENTION_MARKER_FILENAME = 'trajectory-retention.json';
@@ -273,6 +276,28 @@ function skipReport(args) {
273
276
  ...(args.nextAction === undefined ? {} : { nextAction: args.nextAction }),
274
277
  };
275
278
  }
279
+ function purgePolicyDecisions(workspaceDir, cutoff) {
280
+ const stateDbPath = resolveStateDbPath(workspaceDir);
281
+ if (!fs.existsSync(stateDbPath)) {
282
+ return { status: 'skipped', purged: 0, reason: 'state_db_missing', nextAction: 'Initialize the governance workspace before expecting policy-decision retention' };
283
+ }
284
+ let connection;
285
+ try {
286
+ connection = new SqliteConnection({ workspaceDir, readonly: false, bootstrapIfMissing: false, busyTimeoutMs: TRAJECTORY_RETENTION_WRITE_LOCK_WAIT_MS });
287
+ const purged = new SqliteDecisionLedgerStore(connection).purgeDecisionsOlderThan(new Date(cutoff));
288
+ return { status: 'purged', purged };
289
+ }
290
+ catch (error) {
291
+ const message = error instanceof Error ? error.message : String(error);
292
+ return { status: 'degraded', purged: 0, reason: `policy_decisions_retention_failed:${message}`, nextAction: 'Inspect the governance state.db policy_decisions ledger; trajectory retention continued and this purge can be retried on the next sweep' };
293
+ }
294
+ finally {
295
+ try {
296
+ connection?.close();
297
+ }
298
+ catch { /* closing must not mask the retention report */ }
299
+ }
300
+ }
276
301
  /**
277
302
  * One retention attempt for one workspace.
278
303
  *
@@ -487,6 +512,9 @@ export function runTrajectoryRetention(options) {
487
512
  },
488
513
  },
489
514
  });
515
+ const policyDecisions = run.outcome === 'invariant_violation'
516
+ ? { status: 'skipped', purged: 0, reason: 'trajectory_retention_invariant_violation', nextAction: 'Resolve the trajectory retention invariant violation; policy-decision cleanup was not attempted in the same sweep' }
517
+ : purgePolicyDecisions(workspaceDir, decision.cutoff);
490
518
  const totalDurationMs = now() - startedAt;
491
519
  // Fill in tables the engine reached even when no batch committed, so a
492
520
  // stopped run reports `{ tool_calls: 0 }` rather than an empty object.
@@ -542,6 +570,7 @@ export function runTrajectoryRetention(options) {
542
570
  policy,
543
571
  indexes,
544
572
  indexesError,
573
+ policyDecisions,
545
574
  ...(run.outcome === 'invariant_violation'
546
575
  ? {
547
576
  nextAction: 'Row counts did not reconcile; sweeping stopped without deleting further. Inspect trajectory.db and the marker before retrying',
@@ -0,0 +1,10 @@
1
+ export interface TrustedPdBinaryResolution {
2
+ /** Command word a host may print in a recovery hint: absolute path, quoted when it has spaces, or bare `pd` when unproven. */
3
+ readonly bin: string;
4
+ /** Absolute shim paths that may be trusted by `identifyRecoveryControl`. Empty when the shim is unproven. */
5
+ readonly trusted: readonly string[];
6
+ readonly source: 'installed_runtime' | 'path_lookup';
7
+ readonly reason?: string;
8
+ }
9
+ /** Resolve the installer-owned pd shim read-only; never create or modify anything under the install directory. */
10
+ export declare function resolveTrustedPdBinary(env?: Readonly<Record<string, string | undefined>>, platform?: string): TrustedPdBinaryResolution;
@@ -0,0 +1,38 @@
1
+ /**
2
+ * Installer-owned pd shim resolution for recovery-control recognition.
3
+ *
4
+ * The shell command text is untrusted agent input. A bare `pd` word can be
5
+ * redirected by the agent's own filesystem/PATH manipulation, so it is never
6
+ * treated as the recovery entry. Only the exact absolute shim owned by the
7
+ * installer may be marked as trusted; when that shim cannot be proven to
8
+ * exist, no trusted binary is returned and mode commands fail closed.
9
+ */
10
+ import * as fs from 'node:fs';
11
+ import * as path from 'node:path';
12
+ import { resolvePdHome } from '@principles/install-layout';
13
+ function isRecord(value) {
14
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
15
+ }
16
+ function unavailable(reason) {
17
+ return { bin: 'pd', trusted: [], source: 'path_lookup', reason };
18
+ }
19
+ /** Resolve the installer-owned pd shim read-only; never create or modify anything under the install directory. */
20
+ export function resolveTrustedPdBinary(env = process.env, platform = process.platform) {
21
+ const home = resolvePdHome({ env });
22
+ if (!home.ok)
23
+ return unavailable(`pd_home_unresolved: ${home.reason}`);
24
+ const shim = path.resolve(home.runtimeDir, 'bin', platform === 'win32' ? 'pd.cmd' : 'pd');
25
+ try {
26
+ if (!fs.statSync(shim).isFile())
27
+ return unavailable(`shim_not_found: ${shim} is not a file`);
28
+ }
29
+ catch (error) {
30
+ const code = isRecord(error) && typeof error.code === 'string' ? error.code : 'unreadable';
31
+ return unavailable(`shim_not_found: ${shim} (${code})`);
32
+ }
33
+ return {
34
+ bin: /\s/.test(shim) ? `"${shim}"` : shim,
35
+ trusted: [shim],
36
+ source: 'installed_runtime',
37
+ };
38
+ }
@@ -2,22 +2,29 @@ import path from 'node:path';
2
2
  import { computeBehaviorFacts, } from '@principles/core/runtime';
3
3
  import { assembleBehaviorHistory, computeConservativeBehaviorFacts } from './behavior-history.js';
4
4
  import { readWorkspaceRuleContextRowsBefore } from './workspace-behavior-evidence.js';
5
+ import { resolveWorkspaceSessionWriteTargets, unavailableSessionWriteTargets } from './session-write-targets.js';
5
6
  const HISTORY_LIMIT = 100;
6
7
  const MAX_REASON_LENGTH = 240;
7
8
  function isRecord(value) {
8
9
  return typeof value === 'object' && value !== null && !Array.isArray(value);
9
10
  }
10
- function unavailable(reason) {
11
+ function unavailable(reason, sessionWriteTargets) {
12
+ const normalizedReason = reason.replace(/\s+/g, ' ').slice(0, MAX_REASON_LENGTH);
11
13
  const history = {
12
14
  status: 'unavailable',
13
- unavailableReason: reason.replace(/\s+/g, ' ').slice(0, MAX_REASON_LENGTH),
15
+ unavailableReason: normalizedReason,
14
16
  truncated: false,
15
17
  calls: [],
16
18
  };
17
19
  return {
18
20
  version: 2,
19
21
  history,
20
- facts: computeBehaviorFacts(history, null, null),
22
+ facts: {
23
+ ...computeBehaviorFacts(history, null, null),
24
+ // Early exits could not locate session/project scope: unavailable for the same
25
+ // structured reason. Only branches that DID locate scope pass a computed value.
26
+ sessionWriteTargets: sessionWriteTargets ?? unavailableSessionWriteTargets(normalizedReason),
27
+ },
21
28
  };
22
29
  }
23
30
  /**
@@ -62,6 +69,20 @@ export function createWorkbuddyRuleContextProvider(options) {
62
69
  const cutoff = options.cutoffAt;
63
70
  if (!(cutoff instanceof Date) || !Number.isFinite(cutoff.getTime()))
64
71
  return unavailable('history_cutoff_invalid');
72
+ // Session/project scope is proven here, so the session-wide lower bound is computed
73
+ // independently of the 100-row window and rides on every later history verdict.
74
+ // Only rows proven to be WorkBuddy's (host_kind stamp) are read, so a foreign or
75
+ // unattributed row can only lower the bound.
76
+ const sessionWriteTargets = resolveWorkspaceSessionWriteTargets({
77
+ workspaceDir,
78
+ projectDir,
79
+ hostKind: 'workbuddy',
80
+ sessionId: request.sessionId,
81
+ cutoffAt: cutoff,
82
+ currentToolUseId: options.currentToolCallId,
83
+ request,
84
+ toolSemantics: options.toolSemantics,
85
+ });
65
86
  try {
66
87
  const historyRows = readWorkspaceRuleContextRowsBefore(workspaceDir, {
67
88
  sessionId: request.sessionId,
@@ -76,22 +97,22 @@ export function createWorkbuddyRuleContextProvider(options) {
76
97
  hostKind: 'workbuddy',
77
98
  });
78
99
  if (historyRows.unscopedPriorRows)
79
- return unavailable('trajectory_project_scope_incomplete');
100
+ return unavailable('trajectory_project_scope_incomplete', sessionWriteTargets);
80
101
  if ((historyRows.otherHostRows ?? 0) > 0) {
81
- return unavailable('workbuddy_history_attribution_conflict');
102
+ return unavailable('workbuddy_history_attribution_conflict', sessionWriteTargets);
82
103
  }
83
104
  if (historyRows.rows.length === 0) {
84
105
  // Fail closed with the precise reason: legacy rows exist but cannot
85
106
  // be PROVEN WorkBuddy's (never back-filled, never assumed).
86
107
  if ((historyRows.unattributedRows ?? 0) > 0)
87
- return unavailable('workbuddy_history_attribution_unprovable');
88
- return unavailable('no_prior_session_history');
108
+ return unavailable('workbuddy_history_attribution_unprovable', sessionWriteTargets);
109
+ return unavailable('no_prior_session_history', sessionWriteTargets);
89
110
  }
90
111
  if ((historyRows.unattributedRows ?? 0) > 0) {
91
112
  // Mixed window: consuming only the proven subset could UNDERCOUNT
92
113
  // prior reads (a hidden foreign read would flip priorReadOfTarget),
93
114
  // so the window is unprovable as a whole — suspend precisely.
94
- return unavailable('workbuddy_history_attribution_unprovable');
115
+ return unavailable('workbuddy_history_attribution_unprovable', sessionWriteTargets);
95
116
  }
96
117
  const history = assembleBehaviorHistory(historyRows.rows, historyRows.truncated, {
97
118
  projectDir,
@@ -107,11 +128,11 @@ export function createWorkbuddyRuleContextProvider(options) {
107
128
  return {
108
129
  version: 2,
109
130
  history,
110
- facts,
131
+ facts: { ...facts, sessionWriteTargets },
111
132
  };
112
133
  }
113
134
  catch (error) {
114
- return unavailable(`trajectory_history_unavailable:${error instanceof Error ? error.message : String(error)}`);
135
+ return unavailable(`trajectory_history_unavailable:${error instanceof Error ? error.message : String(error)}`, sessionWriteTargets);
115
136
  }
116
137
  };
117
138
  }