@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.
- 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/internalization-consumer-cycle.js +1 -1
- package/dist/mode-state-facts.d.ts +41 -0
- package/dist/mode-state-facts.js +224 -0
- package/dist/pain-inbox.d.ts +28 -0
- package/dist/pain-inbox.js +194 -46
- 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,318 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Fact_Assembler (SPEC-PD-RULE-POLICY-001 Requirement 7.3-7.6; design.md §7).
|
|
3
|
+
*
|
|
4
|
+
* `assembleFacts` is a pure function over injected inputs: it holds no database
|
|
5
|
+
* connection. It computes ONLY the facts in `needed`; every other key is absent.
|
|
6
|
+
* Session-activity facts share one read of the session rows, and that reader is
|
|
7
|
+
* not called at all when no activity fact is needed.
|
|
8
|
+
*
|
|
9
|
+
* Unknown is never a default (Requirement 7.6): a fact whose data is missing,
|
|
10
|
+
* unreadable, cut by the scan limit or not provided by the host is
|
|
11
|
+
* `{ unknown: true, reason }`. "Nothing there" is also reported as unknown with a
|
|
12
|
+
* dedicated reason (`no_write_in_session`, `no_failure_streak`,
|
|
13
|
+
* `no_previous_high_impact`) because the fact has no value to hold.
|
|
14
|
+
*/
|
|
15
|
+
import { classifyBashRisk } from '@principles/core/runtime/internalization/bash-risk';
|
|
16
|
+
import { classifyCommand, } from '@principles/core/runtime/internalization/rule-policy-facts';
|
|
17
|
+
import { provableWriteTargetKeys } from './session-write-targets.js';
|
|
18
|
+
import { readWorkspaceSessionActivityRowsBefore } from './workspace-behavior-evidence.js';
|
|
19
|
+
export const DEFAULT_SCAN_LIMIT = 2000;
|
|
20
|
+
/** `action.targets` above this many entries is unknown, never truncated (bounds anyUnder/allUnder cost). */
|
|
21
|
+
export const MAX_ACTION_TARGETS = 500;
|
|
22
|
+
const MAX_REASON_LENGTH = 300;
|
|
23
|
+
/**
|
|
24
|
+
* design.md ?11 fallback: `action.targetPaths ?? [normalizedPath-derived key]`.
|
|
25
|
+
* `normalizedPath` is already project-relative when it is provably inside the
|
|
26
|
+
* project. Reject absolute, escaping, synthetic and non-structured labels; never
|
|
27
|
+
* turn an unproven or outside target into a policy key.
|
|
28
|
+
*/
|
|
29
|
+
export function normalizedPathTargetKeys(normalizedPath, targetEvidence, platform) {
|
|
30
|
+
if (targetEvidence !== 'structured_path' || typeof normalizedPath !== 'string' || normalizedPath.length === 0)
|
|
31
|
+
return undefined;
|
|
32
|
+
if (normalizedPath.includes('\0') || normalizedPath.startsWith('<'))
|
|
33
|
+
return undefined;
|
|
34
|
+
let text = normalizedPath.replace(/\\/g, '/');
|
|
35
|
+
if (text.startsWith('/') || (/^[A-Za-z]:/.test(text) && text.charAt(2) === '/'))
|
|
36
|
+
return undefined;
|
|
37
|
+
if (platform === 'win32')
|
|
38
|
+
text = text.toLowerCase();
|
|
39
|
+
const segments = [];
|
|
40
|
+
for (const segment of text.split('/')) {
|
|
41
|
+
if (segment === '' || segment === '.')
|
|
42
|
+
continue;
|
|
43
|
+
if (segment === '..')
|
|
44
|
+
return undefined;
|
|
45
|
+
segments.push(segment);
|
|
46
|
+
}
|
|
47
|
+
return segments.length === 0 ? undefined : [segments.join('/')];
|
|
48
|
+
}
|
|
49
|
+
function actionTargets(current, platform) {
|
|
50
|
+
return current.targetPaths ?? normalizedPathTargetKeys(current.normalizedPath, current.targetEvidence, platform);
|
|
51
|
+
}
|
|
52
|
+
function unknownFact(reason) {
|
|
53
|
+
const text = reason.replace(/\s+/g, ' ').trim().slice(0, MAX_REASON_LENGTH);
|
|
54
|
+
return { unknown: true, reason: text.length > 0 ? text : 'unknown' };
|
|
55
|
+
}
|
|
56
|
+
function isRecord(value) {
|
|
57
|
+
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
58
|
+
}
|
|
59
|
+
function errorText(error) {
|
|
60
|
+
return error instanceof Error ? error.message : String(error);
|
|
61
|
+
}
|
|
62
|
+
function toIso(value) {
|
|
63
|
+
const ms = typeof value === 'number' ? value : Date.parse(value);
|
|
64
|
+
if (!Number.isFinite(ms))
|
|
65
|
+
return null;
|
|
66
|
+
const date = new Date(ms);
|
|
67
|
+
return Number.isNaN(date.getTime()) ? null : date.toISOString();
|
|
68
|
+
}
|
|
69
|
+
function timeFact(value) {
|
|
70
|
+
return toIso(value) ?? unknownFact('created_at_unparseable');
|
|
71
|
+
}
|
|
72
|
+
const ACTIVITY_FACT_IDS = [
|
|
73
|
+
'session.hasWrites',
|
|
74
|
+
'session.lastWriteAt',
|
|
75
|
+
'session.toolFailureStreak',
|
|
76
|
+
'session.toolFailureStreakStartAt',
|
|
77
|
+
'session.previousHighImpactAt',
|
|
78
|
+
];
|
|
79
|
+
function allActivityUnknown(reason) {
|
|
80
|
+
const value = unknownFact(reason);
|
|
81
|
+
return {
|
|
82
|
+
'session.hasWrites': value,
|
|
83
|
+
'session.lastWriteAt': value,
|
|
84
|
+
'session.toolFailureStreak': value,
|
|
85
|
+
'session.toolFailureStreakStartAt': value,
|
|
86
|
+
'session.previousHighImpactAt': value,
|
|
87
|
+
};
|
|
88
|
+
}
|
|
89
|
+
function isActivityRow(value) {
|
|
90
|
+
return isRecord(value) && typeof value.id === 'number' && typeof value.toolName === 'string'
|
|
91
|
+
&& typeof value.outcome === 'string' && typeof value.paramsJson === 'string'
|
|
92
|
+
&& (typeof value.createdAt === 'string' || typeof value.createdAt === 'number');
|
|
93
|
+
}
|
|
94
|
+
function isClassified(value) {
|
|
95
|
+
return Object.hasOwn(value, 'classes');
|
|
96
|
+
}
|
|
97
|
+
function commandOf(params) {
|
|
98
|
+
if (typeof params.command === 'string')
|
|
99
|
+
return params.command;
|
|
100
|
+
return typeof params.args === 'string' ? params.args : undefined;
|
|
101
|
+
}
|
|
102
|
+
/** Is this executed command dangerous or a history rewrite? Anything unprovable is unknown, not "no". */
|
|
103
|
+
function highImpactOf(paramsJson) {
|
|
104
|
+
let params;
|
|
105
|
+
try {
|
|
106
|
+
params = JSON.parse(paramsJson);
|
|
107
|
+
}
|
|
108
|
+
catch (error) {
|
|
109
|
+
return { result: 'unknown', reason: `activity_row_params_invalid:${errorText(error)}` };
|
|
110
|
+
}
|
|
111
|
+
if (!isRecord(params))
|
|
112
|
+
return { result: 'unknown', reason: 'activity_row_params_invalid:not_object' };
|
|
113
|
+
if (classifyBashRisk(true, params) === 'dangerous')
|
|
114
|
+
return { result: 'yes' };
|
|
115
|
+
const command = commandOf(params);
|
|
116
|
+
if (command === undefined)
|
|
117
|
+
return { result: 'no' };
|
|
118
|
+
const classification = classifyCommand(command);
|
|
119
|
+
if (!isClassified(classification))
|
|
120
|
+
return { result: 'unknown', reason: 'command_unparsed' };
|
|
121
|
+
return { result: classification.classes.includes('vcs_rewrite') ? 'yes' : 'no' };
|
|
122
|
+
}
|
|
123
|
+
function deriveActivity(q) {
|
|
124
|
+
const scanLimit = q.scanLimit ?? DEFAULT_SCAN_LIMIT;
|
|
125
|
+
if (!Number.isSafeInteger(scanLimit) || scanLimit < 1)
|
|
126
|
+
return allActivityUnknown('scan_limit_invalid');
|
|
127
|
+
if (q.sessionId.trim().length === 0)
|
|
128
|
+
return allActivityUnknown('session_id_unavailable');
|
|
129
|
+
let result;
|
|
130
|
+
try {
|
|
131
|
+
result = q.readActivity(q.sessionId, q.beforeKey, scanLimit);
|
|
132
|
+
}
|
|
133
|
+
catch (error) {
|
|
134
|
+
return allActivityUnknown(`session_activity_read_failed:${errorText(error)}`);
|
|
135
|
+
}
|
|
136
|
+
if (!isRecord(result) || !Array.isArray(result.rows) || typeof result.truncated !== 'boolean') {
|
|
137
|
+
return allActivityUnknown('session_activity_rows_malformed');
|
|
138
|
+
}
|
|
139
|
+
const rows = result.rows;
|
|
140
|
+
if (rows.length > scanLimit)
|
|
141
|
+
return allActivityUnknown('session_activity_rows_exceed_limit');
|
|
142
|
+
const typed = [];
|
|
143
|
+
for (const row of rows) {
|
|
144
|
+
if (!isActivityRow(row))
|
|
145
|
+
return allActivityUnknown('session_activity_rows_malformed');
|
|
146
|
+
typed.push(row);
|
|
147
|
+
}
|
|
148
|
+
const cut = result.truncated;
|
|
149
|
+
const registry = q.toolSemantics;
|
|
150
|
+
// Latest write: a blocked write never happened.
|
|
151
|
+
const write = typed.find((row) => row.outcome !== 'blocked' && registry.resolve(row.toolName) === 'write');
|
|
152
|
+
let hasWrites;
|
|
153
|
+
let lastWriteAt;
|
|
154
|
+
if (write !== undefined) {
|
|
155
|
+
hasWrites = true;
|
|
156
|
+
lastWriteAt = timeFact(write.createdAt);
|
|
157
|
+
}
|
|
158
|
+
else if (cut) {
|
|
159
|
+
hasWrites = unknownFact('scan_limit_reached');
|
|
160
|
+
lastWriteAt = unknownFact('scan_limit_reached');
|
|
161
|
+
}
|
|
162
|
+
else {
|
|
163
|
+
hasWrites = false;
|
|
164
|
+
lastWriteAt = unknownFact('no_write_in_session');
|
|
165
|
+
}
|
|
166
|
+
// Failure streak of the current tool: failure counts, success ends it, unknown/blocked do neither.
|
|
167
|
+
let streak = 0;
|
|
168
|
+
let streakStart;
|
|
169
|
+
let streakEnded = false;
|
|
170
|
+
for (const row of typed) {
|
|
171
|
+
if (row.toolName !== q.current.toolName)
|
|
172
|
+
continue;
|
|
173
|
+
if (row.outcome === 'success') {
|
|
174
|
+
streakEnded = true;
|
|
175
|
+
break;
|
|
176
|
+
}
|
|
177
|
+
if (row.outcome === 'failure') {
|
|
178
|
+
streak += 1;
|
|
179
|
+
streakStart = row.createdAt;
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
let toolFailureStreak;
|
|
183
|
+
let toolFailureStreakStartAt;
|
|
184
|
+
if (!streakEnded && cut) {
|
|
185
|
+
toolFailureStreak = unknownFact('scan_limit_reached');
|
|
186
|
+
toolFailureStreakStartAt = unknownFact('scan_limit_reached');
|
|
187
|
+
}
|
|
188
|
+
else {
|
|
189
|
+
toolFailureStreak = streak;
|
|
190
|
+
toolFailureStreakStartAt = streakStart === undefined ? unknownFact('no_failure_streak') : timeFact(streakStart);
|
|
191
|
+
}
|
|
192
|
+
// Previous high-impact command: first executed (non-blocked) execute row that qualifies.
|
|
193
|
+
let previousHighImpactAt;
|
|
194
|
+
for (const row of typed) {
|
|
195
|
+
if (row.outcome === 'blocked' || registry.resolve(row.toolName) !== 'execute')
|
|
196
|
+
continue;
|
|
197
|
+
const impact = highImpactOf(row.paramsJson);
|
|
198
|
+
if (impact.result === 'unknown') {
|
|
199
|
+
previousHighImpactAt = unknownFact(impact.reason);
|
|
200
|
+
break;
|
|
201
|
+
}
|
|
202
|
+
if (impact.result === 'yes') {
|
|
203
|
+
previousHighImpactAt = timeFact(row.createdAt);
|
|
204
|
+
break;
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
previousHighImpactAt ??= unknownFact(cut ? 'scan_limit_reached' : 'no_previous_high_impact');
|
|
208
|
+
return {
|
|
209
|
+
'session.hasWrites': hasWrites,
|
|
210
|
+
'session.lastWriteAt': lastWriteAt,
|
|
211
|
+
'session.toolFailureStreak': toolFailureStreak,
|
|
212
|
+
'session.toolFailureStreakStartAt': toolFailureStreakStartAt,
|
|
213
|
+
'session.previousHighImpactAt': previousHighImpactAt,
|
|
214
|
+
};
|
|
215
|
+
}
|
|
216
|
+
// ─── history ──────────────────────────────────────────────────────────────────
|
|
217
|
+
function historyRowsOf(q) {
|
|
218
|
+
const { history } = q;
|
|
219
|
+
if (history === undefined)
|
|
220
|
+
return unknownFact('host_did_not_provide');
|
|
221
|
+
if (history.status !== 'available')
|
|
222
|
+
return unknownFact(`history_unavailable:${history.unavailableReason ?? 'unspecified'}`);
|
|
223
|
+
try {
|
|
224
|
+
const rows = [];
|
|
225
|
+
// Window calls are oldest first; the fact is newest first. A blocked call did not happen.
|
|
226
|
+
for (const call of [...history.calls].reverse()) {
|
|
227
|
+
if (call.outcome === 'blocked')
|
|
228
|
+
continue;
|
|
229
|
+
const command = call.canonicalKind === 'execute' ? commandOf(call.paramsSummary) : undefined;
|
|
230
|
+
const classification = command === undefined ? undefined : classifyCommand(command);
|
|
231
|
+
rows.push({
|
|
232
|
+
kind: call.canonicalKind,
|
|
233
|
+
tool: call.toolName,
|
|
234
|
+
outcome: call.outcome,
|
|
235
|
+
commandClasses: classification !== undefined && isClassified(classification) ? classification.classes : [],
|
|
236
|
+
targets: provableWriteTargetKeys(call.toolName, call.paramsSummary, { registry: q.toolSemantics, projectRoot: q.projectRoot, platform: q.platform }),
|
|
237
|
+
});
|
|
238
|
+
}
|
|
239
|
+
return rows;
|
|
240
|
+
}
|
|
241
|
+
catch (error) {
|
|
242
|
+
return unknownFact(`history_conversion_failed:${errorText(error)}`);
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
// ─── entry point ──────────────────────────────────────────────────────────────
|
|
246
|
+
export function assembleFacts(q) {
|
|
247
|
+
const out = {};
|
|
248
|
+
const wants = (id) => q.needed.has(id);
|
|
249
|
+
const { current } = q;
|
|
250
|
+
if (wants('action.kind'))
|
|
251
|
+
out['action.kind'] = current.kind;
|
|
252
|
+
if (wants('action.tool'))
|
|
253
|
+
out['action.tool'] = current.toolName;
|
|
254
|
+
if (wants('action.targets')) {
|
|
255
|
+
const targets = actionTargets(current, q.platform ?? process.platform);
|
|
256
|
+
if (targets === undefined)
|
|
257
|
+
out['action.targets'] = unknownFact('host_did_not_provide');
|
|
258
|
+
else if (targets.length > MAX_ACTION_TARGETS)
|
|
259
|
+
out['action.targets'] = unknownFact('targets_limit_exceeded');
|
|
260
|
+
else
|
|
261
|
+
out['action.targets'] = targets;
|
|
262
|
+
}
|
|
263
|
+
if (wants('action.commandClasses')) {
|
|
264
|
+
out['action.commandClasses'] = current.commandClasses ?? unknownFact('host_did_not_provide');
|
|
265
|
+
}
|
|
266
|
+
if (wants('action.bashRisk'))
|
|
267
|
+
out['action.bashRisk'] = current.bashRisk ?? unknownFact('host_did_not_provide');
|
|
268
|
+
if (wants('action.isSensitivePath')) {
|
|
269
|
+
out['action.isSensitivePath'] = current.isSensitivePath ?? unknownFact('host_did_not_provide');
|
|
270
|
+
}
|
|
271
|
+
if (wants('session.writeTargets')) {
|
|
272
|
+
out['session.writeTargets'] = q.sessionWriteTargets.status === 'available'
|
|
273
|
+
? q.sessionWriteTargets.lowerBound
|
|
274
|
+
: unknownFact(q.sessionWriteTargets.reason);
|
|
275
|
+
}
|
|
276
|
+
if (ACTIVITY_FACT_IDS.some(wants)) {
|
|
277
|
+
const activity = deriveActivity(q);
|
|
278
|
+
for (const id of ACTIVITY_FACT_IDS) {
|
|
279
|
+
if (wants(id))
|
|
280
|
+
out[id] = activity[id];
|
|
281
|
+
}
|
|
282
|
+
}
|
|
283
|
+
if (wants('mode.latestSituationClass')) {
|
|
284
|
+
if (q.modeState === undefined)
|
|
285
|
+
out['mode.latestSituationClass'] = unknownFact('host_did_not_provide');
|
|
286
|
+
else if (q.modeState.status === 'unavailable')
|
|
287
|
+
out['mode.latestSituationClass'] = unknownFact('mode_state_unavailable');
|
|
288
|
+
else if (q.modeState.status === 'absent')
|
|
289
|
+
out['mode.latestSituationClass'] = unknownFact('no_declaration');
|
|
290
|
+
else
|
|
291
|
+
out['mode.latestSituationClass'] = q.modeState.latestSituationClass ?? unknownFact('no_declaration');
|
|
292
|
+
}
|
|
293
|
+
if (wants('designGate.resolution')) {
|
|
294
|
+
out['designGate.resolution'] = q.designGate === undefined ? unknownFact('host_has_no_design_gate') : q.designGate.resolution;
|
|
295
|
+
}
|
|
296
|
+
if (wants('history'))
|
|
297
|
+
out.history = historyRowsOf(q);
|
|
298
|
+
return out;
|
|
299
|
+
}
|
|
300
|
+
// ─── Codex / WorkBuddy reader ─────────────────────────────────────────────────
|
|
301
|
+
/**
|
|
302
|
+
* Reader for Codex / WorkBuddy over the governance workspace's trajectory
|
|
303
|
+
* database. `beforeKey` must be the ISO created_at cutoff captured at PreToolUse.
|
|
304
|
+
*/
|
|
305
|
+
export function createWorkspaceSessionActivityRowReader(workspaceDir, options) {
|
|
306
|
+
return (sessionId, beforeKey, limit) => {
|
|
307
|
+
if (typeof beforeKey !== 'string')
|
|
308
|
+
throw new Error('history_cutoff_invalid');
|
|
309
|
+
return readWorkspaceSessionActivityRowsBefore(workspaceDir, {
|
|
310
|
+
sessionId,
|
|
311
|
+
projectDir: options.projectDir,
|
|
312
|
+
hostKind: options.hostKind,
|
|
313
|
+
beforeCreatedAt: beforeKey,
|
|
314
|
+
excludeToolUseId: options.excludeToolUseId,
|
|
315
|
+
limit,
|
|
316
|
+
});
|
|
317
|
+
};
|
|
318
|
+
}
|
|
@@ -3,6 +3,12 @@ import type { AfterToolCallEnvironmentFacts } from './environment-facts.js';
|
|
|
3
3
|
export interface ForwardObservationOptions {
|
|
4
4
|
hostKind?: string;
|
|
5
5
|
environmentProvider?: (event: HostEvent) => AfterToolCallEnvironmentFacts;
|
|
6
|
+
/**
|
|
7
|
+
* Host project cwd. The opportunity's params are converged against it, the
|
|
8
|
+
* same root the Post row writer uses (K9); otherwise Pre and Post evidence
|
|
9
|
+
* for one call would disagree and quarantine the exact link.
|
|
10
|
+
*/
|
|
11
|
+
projectDir?: string;
|
|
6
12
|
}
|
|
7
13
|
export declare function forwardObservationScopeAuthorized(workspaceDir: string): boolean;
|
|
8
14
|
/**
|
|
@@ -12,6 +12,7 @@ import { recordCoverageDiagnostic, recordObservationOpportunity, recordOpportuni
|
|
|
12
12
|
import { forwardObservationScopeAuthorized as coreForwardObservationScopeAuthorized } from '@principles/core/runtime/forward-observation-scope';
|
|
13
13
|
import { convergeTrajectorySchemaVersion, recordEnvironmentSnapshot } from '@principles/core/runtime/trajectory-schema';
|
|
14
14
|
import { resolveTrajectoryDbPath } from '@principles/core/runtime/storage-paths';
|
|
15
|
+
import { resolveEvidenceProjectRoot } from './production-pain-evidence.js';
|
|
15
16
|
export function forwardObservationScopeAuthorized(workspaceDir) {
|
|
16
17
|
return coreForwardObservationScopeAuthorized(workspaceDir);
|
|
17
18
|
}
|
|
@@ -89,7 +90,7 @@ export function capturePreGateOpportunity(event, options) {
|
|
|
89
90
|
toolCallId: event.context.toolCallId ?? null,
|
|
90
91
|
toolName: event.context.toolName ?? 'unknown',
|
|
91
92
|
params: event.context.toolInput ?? {},
|
|
92
|
-
workspaceDir: event.context.workspaceDir,
|
|
93
|
+
workspaceDir: resolveEvidenceProjectRoot(options.projectDir, event.context.workspaceDir),
|
|
93
94
|
preReceivedAt: capturedAt,
|
|
94
95
|
});
|
|
95
96
|
({ opportunityId } = opportunity);
|
|
@@ -14,6 +14,8 @@ export const OPENCLAW_HOST_LIVENESS_CONTRACT = {
|
|
|
14
14
|
// the real dispatched name or the neutral-probe replay rejects them.
|
|
15
15
|
{ capabilityId: 'pd_status', hostToolAliases: ['exec'] },
|
|
16
16
|
{ capabilityId: 'rulecode_deactivate', hostToolAliases: ['exec'] },
|
|
17
|
+
{ capabilityId: 'mode_declare', hostToolAliases: ['exec'] },
|
|
18
|
+
{ capabilityId: 'mode_waive', hostToolAliases: ['exec'] },
|
|
17
19
|
// Review R1: the global pause has NO pd CLI command — its real surface is
|
|
18
20
|
// the authenticated Owner Console route. Declaring a shell alias here
|
|
19
21
|
// would claim a recovery entry that does not exist.
|
|
@@ -26,6 +28,8 @@ export const OPENCLAW_HOST_LIVENESS_CONTRACT = {
|
|
|
26
28
|
// `pd activation emergency-pause` do not exist and were removed).
|
|
27
29
|
{ probeId: 'probe-pd-status', capabilityId: 'pd_status', toolName: 'exec', params: { command: 'pd activation list --json' }, expectedDecision: 'allow' },
|
|
28
30
|
{ probeId: 'probe-rule-deactivate', capabilityId: 'rulecode_deactivate', toolName: 'exec', params: { command: 'pd activation deactivate --activation-id recovery-probe' }, expectedDecision: 'allow' },
|
|
31
|
+
{ probeId: 'probe-mode-declare', capabilityId: 'mode_declare', toolName: 'exec', params: { command: 'pd mode declare --workspace w --project p --session s --file .principles/modes/probe.json' }, expectedDecision: 'allow' },
|
|
32
|
+
{ probeId: 'probe-mode-waive', capabilityId: 'mode_waive', toolName: 'exec', params: { command: 'pd mode waive --workspace w --project p --session s --rule r --reason "probe reason long enough to pass"' }, expectedDecision: 'allow' },
|
|
29
33
|
// Review R3/P1: console-channel capabilities (global pause, owner review)
|
|
30
34
|
// carry NO probe — their recovery path never passes through the RuleHost
|
|
31
35
|
// gate, so a rule replay would misrepresent their verification. Their
|
|
@@ -52,12 +56,16 @@ export const CODEX_HOST_LIVENESS_CONTRACT = {
|
|
|
52
56
|
protectedCapabilities: [
|
|
53
57
|
{ capabilityId: 'pd_status', hostToolAliases: ['Bash'] },
|
|
54
58
|
{ capabilityId: 'rulecode_deactivate', hostToolAliases: ['Bash'] },
|
|
59
|
+
{ capabilityId: 'mode_declare', hostToolAliases: ['Bash'] },
|
|
60
|
+
{ capabilityId: 'mode_waive', hostToolAliases: ['Bash'] },
|
|
55
61
|
{ capabilityId: 'rulecode_global_pause', hostToolAliases: ['rulecode_global_pause'] },
|
|
56
62
|
{ capabilityId: 'owner_review_access', hostToolAliases: ['owner_review_access'] },
|
|
57
63
|
],
|
|
58
64
|
neutralProbes: [
|
|
59
65
|
{ probeId: 'probe-pd-status', capabilityId: 'pd_status', toolName: 'Bash', params: { command: 'pd activation list --json' }, expectedDecision: 'allow' },
|
|
60
66
|
{ probeId: 'probe-rule-deactivate', capabilityId: 'rulecode_deactivate', toolName: 'Bash', params: { command: 'pd activation deactivate --activation-id recovery-probe' }, expectedDecision: 'allow' },
|
|
67
|
+
{ probeId: 'probe-mode-declare', capabilityId: 'mode_declare', toolName: 'Bash', params: { command: 'pd mode declare --workspace w --project p --session s --file .principles/modes/probe.json' }, expectedDecision: 'allow' },
|
|
68
|
+
{ probeId: 'probe-mode-waive', capabilityId: 'mode_waive', toolName: 'Bash', params: { command: 'pd mode waive --workspace w --project p --session s --rule r --reason "probe reason long enough to pass"' }, expectedDecision: 'allow' },
|
|
61
69
|
// Review R3/P1: console-channel capabilities (global pause, owner review)
|
|
62
70
|
// carry NO probe — their recovery path never passes through the RuleHost
|
|
63
71
|
// gate, so a rule replay would misrepresent their verification. Their
|
|
@@ -81,12 +89,16 @@ export const WORKBUDDY_HOST_LIVENESS_CONTRACT = {
|
|
|
81
89
|
protectedCapabilities: [
|
|
82
90
|
{ capabilityId: 'pd_status', hostToolAliases: ['Bash'] },
|
|
83
91
|
{ capabilityId: 'rulecode_deactivate', hostToolAliases: ['Bash'] },
|
|
92
|
+
{ capabilityId: 'mode_declare', hostToolAliases: ['Bash'] },
|
|
93
|
+
{ capabilityId: 'mode_waive', hostToolAliases: ['Bash'] },
|
|
84
94
|
{ capabilityId: 'rulecode_global_pause', hostToolAliases: ['rulecode_global_pause'] },
|
|
85
95
|
{ capabilityId: 'owner_review_access', hostToolAliases: ['owner_review_access'] },
|
|
86
96
|
],
|
|
87
97
|
neutralProbes: [
|
|
88
98
|
{ probeId: 'probe-pd-status', capabilityId: 'pd_status', toolName: 'Bash', params: { command: 'pd activation list --json' }, expectedDecision: 'allow' },
|
|
89
99
|
{ probeId: 'probe-rule-deactivate', capabilityId: 'rulecode_deactivate', toolName: 'Bash', params: { command: 'pd activation deactivate --activation-id recovery-probe' }, expectedDecision: 'allow' },
|
|
100
|
+
{ probeId: 'probe-mode-declare', capabilityId: 'mode_declare', toolName: 'Bash', params: { command: 'pd mode declare --workspace w --project p --session s --file .principles/modes/probe.json' }, expectedDecision: 'allow' },
|
|
101
|
+
{ probeId: 'probe-mode-waive', capabilityId: 'mode_waive', toolName: 'Bash', params: { command: 'pd mode waive --workspace w --project p --session s --rule r --reason "probe reason long enough to pass"' }, expectedDecision: 'allow' },
|
|
90
102
|
// Review R3/P1: console-channel capabilities (global pause, owner review)
|
|
91
103
|
// carry NO probe — their recovery path never passes through the RuleHost
|
|
92
104
|
// gate, so a rule replay would misrepresent their verification. Their
|
package/dist/index.d.ts
CHANGED
|
@@ -1,12 +1,13 @@
|
|
|
1
1
|
import { type HostEvent, type HostEventResult, type HostEventEmitter } from '@principles/core/host';
|
|
2
2
|
import type { AdaptivePriorityProvider } from './adaptive-priority-provider.js';
|
|
3
3
|
import { buildActivePrinciplePromptContext } from './active-principle-prompt.js';
|
|
4
|
-
import { type RuleContextProvider, type RuleInputEnrichmentProvider } from './production-rulehost-gate.js';
|
|
4
|
+
import { type ProductionRuleHostGateOptions, type RuleContextProvider, type RuleInputEnrichmentProvider } from './production-rulehost-gate.js';
|
|
5
5
|
import type { RuleImplementationRuntime } from './rule-implementation-runtime.js';
|
|
6
6
|
import { type PainDatabaseFactory, type PainEnrichmentProvider } from './production-pain-evidence.js';
|
|
7
7
|
import type { AfterToolCallEnvironmentFacts } from './environment-facts.js';
|
|
8
8
|
import type { GovernanceHostKind, ToolSemanticRegistry } from '@principles/core/runtime';
|
|
9
9
|
export * from './active-principle-prompt.js';
|
|
10
|
+
export * from './prompt-activation-event.js';
|
|
10
11
|
export * from './prompt-activation-authority.js';
|
|
11
12
|
export * from './prompt-injection-projection.js';
|
|
12
13
|
export * from './prompt-activation-deliverability.js';
|
|
@@ -30,6 +31,7 @@ export * from './source-material-authorization.js';
|
|
|
30
31
|
export * from './source-revocation-sweep.js';
|
|
31
32
|
export * from './governance-signal-admission.js';
|
|
32
33
|
export * from './signal-classifier.js';
|
|
34
|
+
export * from './signal-rate-limiter.js';
|
|
33
35
|
export * from './adaptive-selection.js';
|
|
34
36
|
export * from './adaptive-priority-provider.js';
|
|
35
37
|
export * from './adaptive-background-append.js';
|
|
@@ -50,6 +52,7 @@ export * from './diagnostician-auto-run.js';
|
|
|
50
52
|
export * from './workspace-pipeline-host-deps.js';
|
|
51
53
|
export * from './host-tool-declaration.js';
|
|
52
54
|
export * from './host-tool-semantic-resolver.js';
|
|
55
|
+
export * from './rule-policy-replay-evidence.js';
|
|
53
56
|
export * from './evaluator-runtime-context.js';
|
|
54
57
|
export * from './workspace-telemetry-emitter.js';
|
|
55
58
|
export * from './product-telemetry/consent-store.js';
|
|
@@ -64,6 +67,8 @@ export * from './workbuddy-worker-status.js';
|
|
|
64
67
|
export * from './codex-transcript-locate.js';
|
|
65
68
|
export * from './intervention-evidence-ingress.js';
|
|
66
69
|
export * from './degraded-enforcement-marker.js';
|
|
70
|
+
export * from './advisory-delivery.js';
|
|
71
|
+
export { createWorkspaceSessionActivityRowReader } from './fact-assembler.js';
|
|
67
72
|
export declare const HOST_RUNTIME_ROUTES: readonly ['before_prompt_build', 'before_tool_call', 'after_tool_call'];
|
|
68
73
|
export type HostRuntimeRoute = (typeof HOST_RUNTIME_ROUTES)[number];
|
|
69
74
|
export type HostRuntimePort = (event: HostEvent) => HostEventResult | Promise<HostEventResult>;
|
|
@@ -111,6 +116,11 @@ export declare function createProductionHostRuntime(options?: Partial<Pick<HostR
|
|
|
111
116
|
afterToolCallEnvironment?: AfterToolCallEnvironmentFacts | ((event: HostEvent) => AfterToolCallEnvironmentFacts);
|
|
112
117
|
/** PRI-634-F: host-declared tool semantics supplied by the constructing host adapter. */
|
|
113
118
|
toolSemantics?: ToolSemanticRegistry;
|
|
119
|
+
/**
|
|
120
|
+
* SPEC-PD-RULE-POLICY-001: RulePolicyV2 gate wiring supplied by the host adapter: the reader of the
|
|
121
|
+
* session's earlier tool calls (feeds the `session.*` facts) and whether the host can deliver a reminder.
|
|
122
|
+
*/
|
|
123
|
+
rulePolicy?: ProductionRuleHostGateOptions['rulePolicy'];
|
|
114
124
|
/**
|
|
115
125
|
* PRI-1137: optional authoritative session-round key supplied by the host
|
|
116
126
|
* adapter that actually owns an advancing user-turn authority. The
|
package/dist/index.js
CHANGED
|
@@ -1,12 +1,13 @@
|
|
|
1
|
-
import { randomUUID } from 'node:crypto';
|
|
2
1
|
import { isHostEvent, isHostEventResult, } from '@principles/core/host';
|
|
3
2
|
import { getPromptModelCatalog, operatorDeclaredContextWindow, resolvePromptBudget } from '@principles/core/runtime';
|
|
4
3
|
import { loadPdConfigForPlugin } from './pd-config.js';
|
|
5
4
|
import { buildActivePrinciplePromptContext } from './active-principle-prompt.js';
|
|
5
|
+
import { buildRuntimeActivationsInjectedEvent } from './prompt-activation-event.js';
|
|
6
6
|
import { createProductionRuleHostGate } from './production-rulehost-gate.js';
|
|
7
7
|
import { createProductionPainEvidenceHandler } from './production-pain-evidence.js';
|
|
8
8
|
import { capturePreGateOpportunity, recordForwardGateDecision } from './forward-observation.js';
|
|
9
9
|
export * from './active-principle-prompt.js';
|
|
10
|
+
export * from './prompt-activation-event.js';
|
|
10
11
|
export * from './prompt-activation-authority.js';
|
|
11
12
|
export * from './prompt-injection-projection.js';
|
|
12
13
|
// SPEC PD_PROMPT_CAPACITY_V1: route-aware single-artifact deliverability
|
|
@@ -59,6 +60,7 @@ export * from './source-material-authorization.js';
|
|
|
59
60
|
export * from './source-revocation-sweep.js';
|
|
60
61
|
export * from './governance-signal-admission.js';
|
|
61
62
|
export * from './signal-classifier.js';
|
|
63
|
+
export * from './signal-rate-limiter.js';
|
|
62
64
|
export * from './adaptive-selection.js';
|
|
63
65
|
export * from './adaptive-priority-provider.js';
|
|
64
66
|
// PRI-1196: background (async) Adaptive selection for the Codex host. Reuses
|
|
@@ -103,6 +105,9 @@ export * from './workspace-pipeline-host-deps.js';
|
|
|
103
105
|
// neutral consumers (pd-cli/pd-console) resolve through the ONE resolver.
|
|
104
106
|
export * from './host-tool-declaration.js';
|
|
105
107
|
export * from './host-tool-semantic-resolver.js';
|
|
108
|
+
// SPEC-PD-RULE-POLICY-001 Requirement 14: read-only trajectory timelines and
|
|
109
|
+
// production-parity fact reconstruction for offline RulePolicy replay.
|
|
110
|
+
export * from './rule-policy-replay-evidence.js';
|
|
106
111
|
// PRI-661: ONE evaluator replay-context builder for host-neutral CLI entries.
|
|
107
112
|
export * from './evaluator-runtime-context.js';
|
|
108
113
|
// PRI-634 A3: workspace-scoped critical telemetry — canonical implementation
|
|
@@ -139,6 +144,8 @@ export * from './intervention-evidence-ingress.js';
|
|
|
139
144
|
// the SAME three-state fact (healthy / degraded / unknown) instead of each
|
|
140
145
|
// re-deriving the marker path and parse rules.
|
|
141
146
|
export * from './degraded-enforcement-marker.js';
|
|
147
|
+
export * from './advisory-delivery.js';
|
|
148
|
+
export { createWorkspaceSessionActivityRowReader } from './fact-assembler.js';
|
|
142
149
|
export const HOST_RUNTIME_ROUTES = [
|
|
143
150
|
'before_prompt_build',
|
|
144
151
|
'before_tool_call',
|
|
@@ -259,6 +266,7 @@ export function createProductionHostRuntime(options = {}) {
|
|
|
259
266
|
...(options.ruleInputEnrichmentProvider ? { ruleInputEnrichmentProvider: options.ruleInputEnrichmentProvider } : {}),
|
|
260
267
|
...(options.ruleImplementationRuntime ? { implementationRuntime: options.ruleImplementationRuntime } : {}),
|
|
261
268
|
...(options.toolSemantics ? { toolSemantics: options.toolSemantics } : {}),
|
|
269
|
+
...(options.rulePolicy ? { rulePolicy: options.rulePolicy } : {}),
|
|
262
270
|
});
|
|
263
271
|
const { afterToolCallEnvironment } = options;
|
|
264
272
|
return createHostRuntime({
|
|
@@ -280,6 +288,7 @@ export function createProductionHostRuntime(options = {}) {
|
|
|
280
288
|
const capture = capturePreGateOpportunity(event, {
|
|
281
289
|
...(options.hostKind !== undefined ? { hostKind: options.hostKind } : {}),
|
|
282
290
|
...(environmentProvider !== undefined ? { environmentProvider } : {}),
|
|
291
|
+
...(options.projectDir ? { projectDir: options.projectDir } : {}),
|
|
283
292
|
});
|
|
284
293
|
const result = await gate(event);
|
|
285
294
|
const decisionWarnings = capture.opportunityId === null
|
|
@@ -423,41 +432,13 @@ export function createProductionHostRuntime(options = {}) {
|
|
|
423
432
|
emissionWarnings.push(`adaptive_assembly_unavailable:${prompt.adaptivePacking.reason}`);
|
|
424
433
|
}
|
|
425
434
|
try {
|
|
426
|
-
options.events?.recordRuntimeActivationsInjected({
|
|
435
|
+
options.events?.recordRuntimeActivationsInjected(buildRuntimeActivationsInjectedEvent({
|
|
436
|
+
prompt,
|
|
427
437
|
sessionId: event.context.sessionId,
|
|
428
438
|
workspaceDir: event.context.workspaceDir,
|
|
429
|
-
principleIds: prompt.principleIds,
|
|
430
|
-
activationIds: prompt.activationIds,
|
|
431
|
-
artifactIds: prompt.artifactIds,
|
|
432
|
-
injectedCount: prompt.principleIds.length,
|
|
433
|
-
skippedWarnings: prompt.warnings,
|
|
434
|
-
injectedCharCount: prompt.additionalContext.length,
|
|
435
|
-
budget: prompt.budget,
|
|
436
439
|
...(options.hostKind === 'openclaw' || options.hostKind === 'codex' || options.hostKind === 'workbuddy' ? { hostKind: options.hostKind } : {}),
|
|
437
|
-
eventId: randomUUID(),
|
|
438
|
-
...(prompt.truncated !== undefined ? { v2Truncated: prompt.truncated } : {}),
|
|
439
440
|
...(event.context.turnId !== undefined ? { runId: event.context.turnId } : {}),
|
|
440
|
-
|
|
441
|
-
// recorded budget is the one THIS injection actually ran under
|
|
442
|
-
// (prompt.budget), never a constant restated after the fact.
|
|
443
|
-
...(prompt.budgetPolicyVersion !== undefined ? { budgetPolicyVersion: prompt.budgetPolicyVersion } : {}),
|
|
444
|
-
...(prompt.budgetCapacitySource !== undefined ? { budgetCapacitySource: prompt.budgetCapacitySource } : {}),
|
|
445
|
-
...(prompt.budgetCapacityStatus !== undefined ? { budgetCapacityStatus: prompt.budgetCapacityStatus } : {}),
|
|
446
|
-
...(prompt.budgetContextWindowTokens != null ? { budgetContextWindowTokens: prompt.budgetContextWindowTokens } : {}),
|
|
447
|
-
// SPEC §7 v0.2: the bounded fallback reason code rides the event so
|
|
448
|
-
// operators can tell model-identity absence from catalog ambiguity
|
|
449
|
-
// etc. without touching logs. Detail stays out of events.
|
|
450
|
-
...(prompt.budgetFallbackReason !== undefined ? { budgetFallbackReason: prompt.budgetFallbackReason } : {}),
|
|
451
|
-
// PRI-904/PRI-1137: selection diagnostics (bounded, optional).
|
|
452
|
-
// The policy reflects the real selection: `fair_rotation_v1` only
|
|
453
|
-
// when a trusted roundKey was supplied, `legacy_fifo_prefix_v1`
|
|
454
|
-
// otherwise — never a claim the selection did not make.
|
|
455
|
-
...(prompt.selectionPolicy !== undefined ? { selectionPolicy: prompt.selectionPolicy } : {}),
|
|
456
|
-
...(prompt.eligibleCount !== undefined ? { eligibleCount: prompt.eligibleCount } : {}),
|
|
457
|
-
...(prompt.rotationStartIndex !== undefined ? { rotationStartIndex: prompt.rotationStartIndex } : {}),
|
|
458
|
-
...(prompt.droppedActivationIds !== undefined && prompt.droppedActivationIds.length > 0 ? { droppedActivationIds: prompt.droppedActivationIds } : {}),
|
|
459
|
-
...(prompt.oversizedActivationIds !== undefined && prompt.oversizedActivationIds.length > 0 ? { oversizedActivationIds: prompt.oversizedActivationIds } : {}),
|
|
460
|
-
});
|
|
441
|
+
}));
|
|
461
442
|
}
|
|
462
443
|
catch (err) {
|
|
463
444
|
emissionWarnings.push(`receipt_event_write_failed:${err instanceof Error ? err.message.slice(0, 200) : String(err).slice(0, 200)}`);
|
|
@@ -47,7 +47,7 @@ function getNextActionForError(category) {
|
|
|
47
47
|
return 'Retry later or check for concurrent worker processes.';
|
|
48
48
|
}
|
|
49
49
|
if (category === 'timeout') {
|
|
50
|
-
return 'Check model provider service status/latency, or increase timeout settings in
|
|
50
|
+
return 'Check model provider service status/latency, or increase timeout settings in .pd/config.yaml.';
|
|
51
51
|
}
|
|
52
52
|
if (category === 'cancelled') {
|
|
53
53
|
return 'Re-enqueue or restart the task if it was cancelled by mistake.';
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import type { GovernanceHostKind, SqliteConnection } from '@principles/core/runtime';
|
|
2
|
+
import type { ModeStateFact } from '@principles/core/runtime/internalization/rule-context-v2';
|
|
3
|
+
declare const REASON_PLACEHOLDER: {
|
|
4
|
+
readonly 'zh-CN': '<写明为什么这次不适用>';
|
|
5
|
+
readonly en: '<say why this does not apply this time>';
|
|
6
|
+
};
|
|
7
|
+
export type ModeStateLocale = keyof typeof REASON_PLACEHOLDER;
|
|
8
|
+
export interface ModeStateQuery {
|
|
9
|
+
/** The governance workspace connection the gate already holds. */
|
|
10
|
+
governanceDb: SqliteConnection;
|
|
11
|
+
/** Project directory of the session, as the host reports it. */
|
|
12
|
+
projectRoot: string;
|
|
13
|
+
/** Host that produced the session; required because session ids are only unique within a host. */
|
|
14
|
+
hostKind?: GovernanceHostKind;
|
|
15
|
+
/** Host-reported session id (never a tool argument). */
|
|
16
|
+
hostSessionId: string;
|
|
17
|
+
/** Governance workspace directory, printed in the hints. */
|
|
18
|
+
governanceWorkspaceDir: string;
|
|
19
|
+
/** Command word for pd, already resolved and, when it has spaces, quoted; null when no installer-proven shim exists. */
|
|
20
|
+
pdBin: string | null;
|
|
21
|
+
locale?: ModeStateLocale;
|
|
22
|
+
/** Rules relevant to this session; reminders are grouped for these only. */
|
|
23
|
+
ruleIds: readonly string[];
|
|
24
|
+
/** Obligation label used to name the suggested declaration file. */
|
|
25
|
+
labelHint?: string;
|
|
26
|
+
/** Path key platform; defaults to `process.platform`. */
|
|
27
|
+
platform?: string;
|
|
28
|
+
}
|
|
29
|
+
/**
|
|
30
|
+
* Policy keys for the project-relative `inScope` entries of a declaration, or null when
|
|
31
|
+
* ANY entry cannot be converted (or none exist). A partly converted scope would silently
|
|
32
|
+
* shrink the allowed area and flag legitimate writes as drift, so the whole scope is
|
|
33
|
+
* treated as untrusted instead.
|
|
34
|
+
*/
|
|
35
|
+
export declare function toScopeKeys(inScope: readonly string[], projectRoot: string, platform: string): readonly string[] | null;
|
|
36
|
+
/**
|
|
37
|
+
* Mode state of one session. Never throws: a failure to read is `unavailable` with a reason.
|
|
38
|
+
*/
|
|
39
|
+
export declare function loadModeStateFact(q: ModeStateQuery): ModeStateFact;
|
|
40
|
+
export type { TrustedPdBinaryResolution as TrustedPdBinary } from './trusted-pd-binary.js';
|
|
41
|
+
export { resolveTrustedPdBinary } from './trusted-pd-binary.js';
|