@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
@@ -14,38 +14,17 @@
14
14
  * (HMAC(secret, canonical workspace path); never uploaded). One
15
15
  * workspace succeeding must never suppress another workspace's export.
16
16
  *
17
- * Single-format contract (PRI-1138, 6th dual-track convergence):
18
- * - The ONLY writable/persisted format is the current schema version.
19
- * writeProductTelemetryControlState refuses every state whose
20
- * schemaVersion is not current, so no code path can persist or
21
- * regenerate a legacy v1 file.
22
- * - Legacy v1 files remain readable through migrateLegacyConsentFile — a
23
- * one-way, read-only migrator (legacy reader / one-way migrator, never a
24
- * writer). A read parses a v1 file in memory (identity preserved) but
25
- * NEVER writes; persistence of the migration happens exclusively inside
26
- * withControlStateLock transactions (PRI-1151): the legacy v1→v2
27
- * migration write-back, enable/disable/reset, and workspace export
28
- * bookkeeping merges all serialize on the same cross-process
29
- * `<state>.state-lock`, so no writer can build its write from a stale
30
- * read or overwrite a completed authorization change.
31
- * - Migration from schema v1: consent, consentVersion, and telemetrySecret
32
- * are preserved verbatim; legacy machine-global export bookkeeping
33
- * (lastSucceededAt, retry state, attempt counters) is DISCARDED — it
34
- * cannot be attributed to a workspace, and it is operational state, not a
35
- * governance fact. Dropping it can cause at most one extra same-day
36
- * snapshot per eligible workspace on the machine (each workspace re-exports
37
- * once before its own fresh bookkeeping exists).
17
+ * Single-format contract (PRI-1138 / Clean-Slate Wave 2A):
18
+ * - The ONLY accepted and writable format is schema v2 (`'2'`). Any other
19
+ * `schemaVersion` (including historical `'1'`) fails loud on read and is
20
+ * refused on write.
21
+ * - All read-modify-write callers serialize through `withControlStateLock`
22
+ * (PRI-1151) on `<state>.state-lock`, so no writer can build its write from
23
+ * a stale read or overwrite a completed authorization change.
38
24
  */
39
25
  export declare const PRODUCT_TELEMETRY_STATE_FILENAME = "product-telemetry.json";
40
- /** The ONE writable schema version (single-format contract, PRI-1138). */
26
+ /** The ONE accepted and writable schema version (single-format contract). */
41
27
  export declare const PRODUCT_TELEMETRY_CONTROL_SCHEMA_VERSION = "2";
42
- /**
43
- * Legacy schema v1 — LEGACY-READER SEMANTICS ONLY (PRI-1138): this constant
44
- * exists solely so the one-way migrator can recognize historical files. It
45
- * is never a writable target; writeProductTelemetryControlState refuses
46
- * every state whose schemaVersion is not PRODUCT_TELEMETRY_CONTROL_SCHEMA_VERSION.
47
- */
48
- export declare const PRODUCT_TELEMETRY_LEGACY_CONTROL_SCHEMA_VERSION = "1";
49
28
  /** Hard bound on tracked workspaces so the file cannot grow unboundedly. */
50
29
  export declare const MAX_WORKSPACE_EXPORT_ENTRIES = 200;
51
30
  /**
@@ -109,15 +88,12 @@ export declare function getProductTelemetryStatePath(homeDir: string): string;
109
88
  */
110
89
  export declare function writeProductTelemetryControlState(homeDir: string, state: ProductTelemetryControlState): ControlStateWrite;
111
90
  /**
112
- * Lock-held read result: the parsed CURRENT disk state plus the schema
113
- * version the bytes on disk actually carried (so a transaction can tell a
114
- * migrated-in-memory v1 apart from a genuine v2 and persist the migration).
91
+ * Lock-held read result: the parsed CURRENT disk state.
115
92
  */
116
93
  export type LatestControlStateRead = {
117
94
  ok: true;
118
95
  state: ProductTelemetryControlState;
119
96
  existed: boolean;
120
- diskSchemaVersion: '1' | '2';
121
97
  } | {
122
98
  ok: false;
123
99
  reason: string;
@@ -125,11 +101,6 @@ export type LatestControlStateRead = {
125
101
  };
126
102
  /**
127
103
  * Read and validate the control state — PURE READ, never writes (PRI-1151).
128
- * A legacy v1 file is parsed in memory (identity preserved, bookkeeping
129
- * dropped) so callers observe the migrated semantics, but persisting the
130
- * migration happens exclusively inside withControlStateLock transactions;
131
- * a read-only caller (status/preview) can therefore never race a concurrent
132
- * authorization change.
133
104
  */
134
105
  export declare function readProductTelemetryControlState(homeDir: string): ControlStateRead;
135
106
  /** Transactional read/write surface handed to withControlStateLock bodies. */
@@ -172,15 +143,6 @@ export declare function withControlStateLock<T>(homeDir: string, body: (tx: Cont
172
143
  reason: string;
173
144
  nextAction: string;
174
145
  }>;
175
- /**
176
- * One-way legacy v1→v2 migration as a locked transaction (PRI-1151): read
177
- * the CURRENT disk state under the lock; if it is still v1, persist the
178
- * migrated state (identity preserved) through the normal atomic write; if it
179
- * is already the current format, do nothing (idempotent — no rewrite). A
180
- * concurrent disable/reset/enable serializes on the same lock, so this can
181
- * never overwrite a completed authorization change.
182
- */
183
- export declare function migrateLegacyControlState(homeDir: string): Promise<ControlStateWrite>;
184
146
  /**
185
147
  * Drop `workspaceExports` entries whose most recent activity (attempt or
186
148
  * success) is older than WORKSPACE_EXPORT_STATE_MAX_AGE_DAYS. Bounded local
@@ -14,42 +14,21 @@
14
14
  * (HMAC(secret, canonical workspace path); never uploaded). One
15
15
  * workspace succeeding must never suppress another workspace's export.
16
16
  *
17
- * Single-format contract (PRI-1138, 6th dual-track convergence):
18
- * - The ONLY writable/persisted format is the current schema version.
19
- * writeProductTelemetryControlState refuses every state whose
20
- * schemaVersion is not current, so no code path can persist or
21
- * regenerate a legacy v1 file.
22
- * - Legacy v1 files remain readable through migrateLegacyConsentFile — a
23
- * one-way, read-only migrator (legacy reader / one-way migrator, never a
24
- * writer). A read parses a v1 file in memory (identity preserved) but
25
- * NEVER writes; persistence of the migration happens exclusively inside
26
- * withControlStateLock transactions (PRI-1151): the legacy v1→v2
27
- * migration write-back, enable/disable/reset, and workspace export
28
- * bookkeeping merges all serialize on the same cross-process
29
- * `<state>.state-lock`, so no writer can build its write from a stale
30
- * read or overwrite a completed authorization change.
31
- * - Migration from schema v1: consent, consentVersion, and telemetrySecret
32
- * are preserved verbatim; legacy machine-global export bookkeeping
33
- * (lastSucceededAt, retry state, attempt counters) is DISCARDED — it
34
- * cannot be attributed to a workspace, and it is operational state, not a
35
- * governance fact. Dropping it can cause at most one extra same-day
36
- * snapshot per eligible workspace on the machine (each workspace re-exports
37
- * once before its own fresh bookkeeping exists).
17
+ * Single-format contract (PRI-1138 / Clean-Slate Wave 2A):
18
+ * - The ONLY accepted and writable format is schema v2 (`'2'`). Any other
19
+ * `schemaVersion` (including historical `'1'`) fails loud on read and is
20
+ * refused on write.
21
+ * - All read-modify-write callers serialize through `withControlStateLock`
22
+ * (PRI-1151) on `<state>.state-lock`, so no writer can build its write from
23
+ * a stale read or overwrite a completed authorization change.
38
24
  */
39
25
  import fs from 'node:fs';
40
26
  import path from 'node:path';
41
27
  import { generateTelemetrySecretHex, isValidBucketDate, isValidTelemetrySecretHex, PRODUCT_TELEMETRY_CONSENT_VERSION, } from '@principles/core/runtime';
42
28
  import { acquireExclusiveLock, ownsExclusiveLock, releaseExclusiveLock } from './control-state-lock.js';
43
29
  export const PRODUCT_TELEMETRY_STATE_FILENAME = 'product-telemetry.json';
44
- /** The ONE writable schema version (single-format contract, PRI-1138). */
30
+ /** The ONE accepted and writable schema version (single-format contract). */
45
31
  export const PRODUCT_TELEMETRY_CONTROL_SCHEMA_VERSION = '2';
46
- /**
47
- * Legacy schema v1 — LEGACY-READER SEMANTICS ONLY (PRI-1138): this constant
48
- * exists solely so the one-way migrator can recognize historical files. It
49
- * is never a writable target; writeProductTelemetryControlState refuses
50
- * every state whose schemaVersion is not PRODUCT_TELEMETRY_CONTROL_SCHEMA_VERSION.
51
- */
52
- export const PRODUCT_TELEMETRY_LEGACY_CONTROL_SCHEMA_VERSION = '1';
53
32
  /** Hard bound on tracked workspaces so the file cannot grow unboundedly. */
54
33
  export const MAX_WORKSPACE_EXPORT_ENTRIES = 200;
55
34
  /**
@@ -117,50 +96,6 @@ function isPlainRecord(value) {
117
96
  }
118
97
  /** The single field whitelist of the current persisted format. */
119
98
  const CURRENT_ALLOWED_KEYS = ['consent', 'consentVersion', 'telemetrySecret', 'workspaceExports', 'schemaVersion'];
120
- /**
121
- * Field whitelist of the LEGACY v1 reader only: identity fields plus the
122
- * retired machine-global export bookkeeping names. Used exclusively inside
123
- * the legacy branch of parseConsentState to recognize historical files —
124
- * never for the current format, and never a write shape (those top-level
125
- * bookkeeping fields are discarded by migrateLegacyConsentFile; no
126
- * production logic reads them).
127
- */
128
- const LEGACY_V1_ALLOWED_KEYS = [
129
- 'consent',
130
- 'consentVersion',
131
- 'telemetrySecret',
132
- 'lastAttemptedAt',
133
- 'lastSucceededAt',
134
- 'lastFailureCode',
135
- 'nextRetryAt',
136
- 'dailyAttemptCount',
137
- 'attemptBucketDate',
138
- 'schemaVersion',
139
- ];
140
- /**
141
- * One-way migrator for legacy schema-v1 control files — legacy reader /
142
- * one-way migrator, never a writer (PRI-1138). Accepts only objects already
143
- * validated against LEGACY_V1_ALLOWED_KEYS by parseConsentState. The
144
- * historical authorization identity is carried over VERBATIM — consent,
145
- * consentVersion, and telemetrySecret are never reset, regenerated, or
146
- * fabricated — while the retired machine-global export bookkeeping is
147
- * dropped (it cannot be attributed to a workspace; operational state, not a
148
- * governance fact). This function never touches the filesystem and never
149
- * logs the secret; persisting its result happens exclusively through
150
- * writeProductTelemetryControlState (the normal atomic write).
151
- */
152
- function migrateLegacyConsentFile(parsed) {
153
- // Post-validation reconstruction from guard-narrowed fields — no `as` on
154
- // the untrusted parsed object (rc-2). The ternary fallbacks are
155
- // unreachable after parseConsentState's validation and mirror the
156
- // defensive reconstruction style of the current-format path.
157
- return {
158
- consent: isConsent(parsed.consent) ? parsed.consent : 'unset',
159
- consentVersion: typeof parsed.consentVersion === 'string' ? parsed.consentVersion : PRODUCT_TELEMETRY_CONSENT_VERSION,
160
- ...(isValidTelemetrySecretHex(parsed.telemetrySecret) ? { telemetrySecret: parsed.telemetrySecret } : {}),
161
- schemaVersion: PRODUCT_TELEMETRY_CONTROL_SCHEMA_VERSION,
162
- };
163
- }
164
99
  /**
165
100
  * Reconstruct the current-format state from guard-narrowed fields — no `as`
166
101
  * on the untrusted parsed object (rc-2). isConsent is a type guard; the
@@ -200,10 +135,8 @@ function reconstructCurrentState(obj) {
200
135
  }
201
136
  /**
202
137
  * parseConsentState — the ONE parse entry for the persisted control state
203
- * (PRI-1138). Current-format files validate against the single current
204
- * whitelist; legacy v1 files go through the one-way migrator path and are
205
- * flagged migratedFromLegacy so the caller persists the migration exactly
206
- * once. Every other shape — missing, malformed, or future schemaVersion —
138
+ * (PRI-1138). Validates strictly against the current v2 schema whitelist.
139
+ * Every other shape — missing, malformed, or any non-current schemaVersion —
207
140
  * fails loud: versions are never guessed and invalid data is never silently
208
141
  * treated as an empty/default consent state.
209
142
  */
@@ -212,21 +145,15 @@ function parseConsentState(parsed) {
212
145
  return { ok: false, errors: ['state must be a JSON object'] };
213
146
  }
214
147
  const obj = parsed;
215
- const { schemaVersion } = obj;
216
- const isLegacyV1 = schemaVersion === PRODUCT_TELEMETRY_LEGACY_CONTROL_SCHEMA_VERSION;
217
- const isCurrent = schemaVersion === PRODUCT_TELEMETRY_CONTROL_SCHEMA_VERSION;
218
- if (!isLegacyV1 && !isCurrent) {
148
+ if (obj.schemaVersion !== PRODUCT_TELEMETRY_CONTROL_SCHEMA_VERSION) {
219
149
  return {
220
150
  ok: false,
221
- errors: [
222
- `schemaVersion must be '${PRODUCT_TELEMETRY_CONTROL_SCHEMA_VERSION}' or legacy '${PRODUCT_TELEMETRY_LEGACY_CONTROL_SCHEMA_VERSION}'`,
223
- ],
151
+ errors: [`schemaVersion must be '${PRODUCT_TELEMETRY_CONTROL_SCHEMA_VERSION}'`],
224
152
  };
225
153
  }
226
- const allowedKeys = isLegacyV1 ? LEGACY_V1_ALLOWED_KEYS : CURRENT_ALLOWED_KEYS;
227
154
  const errors = [];
228
155
  for (const key of Object.keys(obj)) {
229
- if (!allowedKeys.includes(key)) {
156
+ if (!CURRENT_ALLOWED_KEYS.includes(key)) {
230
157
  errors.push(`unknown field '${key}'`);
231
158
  }
232
159
  }
@@ -236,16 +163,6 @@ function parseConsentState(parsed) {
236
163
  errors.push('consentVersion must be a short non-empty string');
237
164
  if (!isValidTelemetrySecretHex(obj.telemetrySecret) && obj.telemetrySecret !== undefined)
238
165
  errors.push('telemetrySecret must be 64 hex chars when present');
239
- if (isLegacyV1) {
240
- // Legacy machine-global export fields are migrated by DISCARDING them —
241
- // validating values that are about to be dropped would only turn a
242
- // smooth migration into a hard failure (the identity fields carry the
243
- // user's decision). Only the field-NAME allowlist above still applies to
244
- // legacy files.
245
- if (errors.length > 0)
246
- return { ok: false, errors };
247
- return { ok: true, state: migrateLegacyConsentFile(obj), migratedFromLegacy: true };
248
- }
249
166
  if (obj.workspaceExports !== undefined) {
250
167
  if (typeof obj.workspaceExports !== 'object' || obj.workspaceExports === null || Array.isArray(obj.workspaceExports)) {
251
168
  errors.push('workspaceExports must be an object');
@@ -272,7 +189,7 @@ function parseConsentState(parsed) {
272
189
  }
273
190
  if (errors.length > 0)
274
191
  return { ok: false, errors };
275
- return { ok: true, state: reconstructCurrentState(obj), migratedFromLegacy: false };
192
+ return { ok: true, state: reconstructCurrentState(obj) };
276
193
  }
277
194
  /**
278
195
  * Atomic write (temp file + rename) so a crash never truncates the state.
@@ -323,9 +240,9 @@ export function writeProductTelemetryControlState(homeDir, state) {
323
240
  /**
324
241
  * Read the raw bytes from disk and parse them — pure, no write, no lock.
325
242
  * A missing file is the normal never-configured case (defaults,
326
- * existed=false, diskSchemaVersion '2'). A malformed file is a loud failure
327
- * — silently treating it as "unset" could re-prompt or re-export against the
328
- * user's recorded decision (rc-3/rc-9).
243
+ * existed=false). A malformed file is a loud failure — silently treating
244
+ * it as "unset" could re-prompt or re-export against the user's recorded
245
+ * decision (rc-3/rc-9).
329
246
  */
330
247
  function loadControlStateFromDisk(filePath) {
331
248
  let raw;
@@ -340,7 +257,7 @@ function loadControlStateFromDisk(filePath) {
340
257
  : undefined;
341
258
  const code = typeof codeValue === 'string' ? codeValue : undefined;
342
259
  if (code === 'ENOENT') {
343
- return { ok: true, state: defaultProductTelemetryControlState(), existed: false, diskSchemaVersion: PRODUCT_TELEMETRY_CONTROL_SCHEMA_VERSION };
260
+ return { ok: true, state: defaultProductTelemetryControlState(), existed: false };
344
261
  }
345
262
  return {
346
263
  ok: false,
@@ -371,18 +288,10 @@ function loadControlStateFromDisk(filePath) {
371
288
  ok: true,
372
289
  state: result.state,
373
290
  existed: true,
374
- diskSchemaVersion: result.migratedFromLegacy
375
- ? PRODUCT_TELEMETRY_LEGACY_CONTROL_SCHEMA_VERSION
376
- : PRODUCT_TELEMETRY_CONTROL_SCHEMA_VERSION,
377
291
  };
378
292
  }
379
293
  /**
380
294
  * Read and validate the control state — PURE READ, never writes (PRI-1151).
381
- * A legacy v1 file is parsed in memory (identity preserved, bookkeeping
382
- * dropped) so callers observe the migrated semantics, but persisting the
383
- * migration happens exclusively inside withControlStateLock transactions;
384
- * a read-only caller (status/preview) can therefore never race a concurrent
385
- * authorization change.
386
295
  */
387
296
  export function readProductTelemetryControlState(homeDir) {
388
297
  const loaded = loadControlStateFromDisk(getProductTelemetryStatePath(homeDir));
@@ -458,28 +367,6 @@ export async function withControlStateLock(homeDir, body, options) {
458
367
  releaseExclusiveLock(lock);
459
368
  }
460
369
  }
461
- /**
462
- * One-way legacy v1→v2 migration as a locked transaction (PRI-1151): read
463
- * the CURRENT disk state under the lock; if it is still v1, persist the
464
- * migrated state (identity preserved) through the normal atomic write; if it
465
- * is already the current format, do nothing (idempotent — no rewrite). A
466
- * concurrent disable/reset/enable serializes on the same lock, so this can
467
- * never overwrite a completed authorization change.
468
- */
469
- export async function migrateLegacyControlState(homeDir) {
470
- const outcome = await withControlStateLock(homeDir, (tx) => {
471
- const latest = tx.readLatest();
472
- if (!latest.ok)
473
- return latest;
474
- if (latest.diskSchemaVersion !== PRODUCT_TELEMETRY_LEGACY_CONTROL_SCHEMA_VERSION) {
475
- return { ok: true };
476
- }
477
- return tx.write(latest.state);
478
- });
479
- if (!outcome.ok)
480
- return outcome;
481
- return outcome.value;
482
- }
483
370
  /**
484
371
  * Drop `workspaceExports` entries whose most recent activity (attempt or
485
372
  * success) is older than WORKSPACE_EXPORT_STATE_MAX_AGE_DAYS. Bounded local
@@ -84,6 +84,15 @@ export declare function recordVerifiedToolOutcomes(args: {
84
84
  * this shared handler (OpenClaw / Codex adapters) — never guessed inside the
85
85
  * writer. Omitted -> NULL (unknown).
86
86
  */
87
+ /**
88
+ * K9: the single project-root authority for evidence writes. Shared by the
89
+ * after-tool row writer (`project_dir` + `params_json` convergence) and the
90
+ * pre-gate opportunity writer so both sanitize against the same root; a
91
+ * mismatch would make Pre/Post evidence look contradictory. An empty
92
+ * projectDir counts as absent (`path.resolve('')` would silently pick the hook
93
+ * process cwd).
94
+ */
95
+ export declare function resolveEvidenceProjectRoot(projectDir: string | undefined, workspaceDir: string): string;
87
96
  export declare function createProductionPainEvidenceHandler(options?: {
88
97
  painEnrichmentProvider?: PainEnrichmentProvider;
89
98
  painDatabaseFactory?: PainDatabaseFactory;
@@ -453,6 +453,17 @@ export function recordVerifiedToolOutcomes(args) {
453
453
  * this shared handler (OpenClaw / Codex adapters) — never guessed inside the
454
454
  * writer. Omitted -> NULL (unknown).
455
455
  */
456
+ /**
457
+ * K9: the single project-root authority for evidence writes. Shared by the
458
+ * after-tool row writer (`project_dir` + `params_json` convergence) and the
459
+ * pre-gate opportunity writer so both sanitize against the same root; a
460
+ * mismatch would make Pre/Post evidence look contradictory. An empty
461
+ * projectDir counts as absent (`path.resolve('')` would silently pick the hook
462
+ * process cwd).
463
+ */
464
+ export function resolveEvidenceProjectRoot(projectDir, workspaceDir) {
465
+ return path.resolve(projectDir !== undefined && projectDir.trim().length > 0 ? projectDir : workspaceDir);
466
+ }
456
467
  export function createProductionPainEvidenceHandler(options = {}) {
457
468
  return async (event) => {
458
469
  // PRI-750: shared-path tool event with the host's natural turn/tool ids
@@ -530,7 +541,16 @@ export function createProductionPainEvidenceHandler(options = {}) {
530
541
  return { decision: 'observe', source: event.source, warnings: [...(emissionWarning ? [emissionWarning] : []), ...(warnings.length > 0 ? warnings : ['pain_enrichment_invalid'])], metadata: { outcome: 'unavailable', duplicate: false, nextAction: 'inspect host tool-call enrichment input' } };
531
542
  }
532
543
  const outcome = normalizeOutcome(event);
533
- const sanitizedParams = sanitizeToolParams(outcome.params, event.context.workspaceDir);
544
+ // K9: params are converged against the PROJECT directory (the value stored
545
+ // in tool_calls.project_dir) so project-internal targets survive as
546
+ // project-relative paths. Hosts whose governance workspace differs from the
547
+ // project (Codex, WorkBuddy) must supply projectDir; without it the root
548
+ // degrades to the governance workspace observably (rc-9), never silently.
549
+ const projectRoot = resolveEvidenceProjectRoot(options.projectDir, event.context.workspaceDir);
550
+ if ((options.hostKind === 'codex' || options.hostKind === 'workbuddy') && (options.projectDir === undefined || options.projectDir.trim().length === 0)) {
551
+ warnings.push('project_dir_unavailable:host adapter supplied no projectDir; project_dir and path convergence fell back to the governance workspace, so project-internal paths are stored as <path:basename>. nextAction: pass the host cwd as projectDir when constructing the host runtime');
552
+ }
553
+ const sanitizedParams = sanitizeToolParams(outcome.params, projectRoot);
534
554
  const toolName = event.context.toolName ?? '';
535
555
  const { eventId } = ids({
536
556
  workspaceDir: event.context.workspaceDir,
@@ -708,7 +728,7 @@ export function createProductionPainEvidenceHandler(options = {}) {
708
728
  }
709
729
  db.prepare(`INSERT INTO sessions (session_id, started_at, updated_at) VALUES (?, ?, ?) ON CONFLICT(session_id) DO UPDATE SET updated_at = excluded.updated_at`).run(event.context.sessionId, createdAt, createdAt);
710
730
  const insertedToolCall = db.prepare(`INSERT INTO tool_calls (session_id, tool_name, outcome, duration_ms, exit_code, error_type, error_message, params_json, result_preview, created_at, tool_use_id, project_dir, host_kind, turn_id) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`)
711
- .run(event.context.sessionId, toolName, outcome.outcome, outcome.durationMs ?? null, outcome.exitCode, outcome.error ? outcome.error.split(/[\s:]/, 1)[0] : null, outcome.error ?? null, paramsJson, resultPreview, createdAt, event.context.toolCallId ?? null, path.resolve(options.projectDir ?? event.context.workspaceDir), options.hostKind ?? null, event.context.turnId ?? null);
731
+ .run(event.context.sessionId, toolName, outcome.outcome, outcome.durationMs ?? null, outcome.exitCode, outcome.error ? outcome.error.split(/[\s:]/, 1)[0] : null, outcome.error ?? null, paramsJson, resultPreview, createdAt, event.context.toolCallId ?? null, projectRoot, options.hostKind ?? null, event.context.turnId ?? null);
712
732
  const toolCallRowid = Number(insertedToolCall.lastInsertRowid);
713
733
  if (options.hostKind !== undefined && forwardAuthorizedAtWrite && event.context.sessionId !== 'openclaw:session-unavailable') {
714
734
  claimFirstWriterProvenance(db, {
@@ -0,0 +1,104 @@
1
+ /**
2
+ * In-process judgement of active RulePolicyV2 rules for the RuleHost gate
3
+ * (SPEC-PD-RULE-POLICY-001 Requirement 10.13, 10.14, 13.1, 13.2, 13.6; design.md §13).
4
+ *
5
+ * `production-rulehost-gate.ts` finds the policy candidates (digest, validation, catalog
6
+ * version, Owner enforcement: `rule-policy-active.ts`) and hands them here with the call's
7
+ * `RuleHostInput`. This module:
8
+ * 1. loads the session's `modeState` and assembles the facts ONCE for all candidates;
9
+ * 2. judges each candidate with core's `evaluatePolicy` and converts the verdict with the
10
+ * real message renderer (`createPolicyMessageRenderer`, never the minimal default);
11
+ * 3. writes one Decision_Ledger row per verdict that is not `not_triggered` and bumps the
12
+ * session counter of every applicable judgement. A failed write never changes a verdict
13
+ * (Requirement 13.6): it becomes a warning and an observation;
14
+ * 4. reports observations, degradations and the live reminder text.
15
+ *
16
+ * Only `live` verdicts reach the gate's merge. `shadow` and `challenger` verdicts are written to
17
+ * the ledger and returned for telemetry but never contribute a decision or advisory text.
18
+ * Nothing here starts a child process or executes artifact-supplied code.
19
+ */
20
+ import { SqliteConnection, type GovernanceHostKind, type RuleContextV2, type RuleHostInput, type RuleHostResult, type ToolSemanticRegistry } from '@principles/core/runtime';
21
+ import type { BashRiskLevel } from '@principles/core/runtime/internalization/bash-risk';
22
+ import type { CanonicalKind } from '@principles/core/runtime/internalization/rule-context-v2';
23
+ import { type PdLocale, type PolicyEvaluation } from '@principles/core/runtime/internalization/rule-policy-gate';
24
+ import { type ReadSessionActivityRows } from './fact-assembler.js';
25
+ import { type TrustedPdBinary } from './mode-state-facts.js';
26
+ import type { ActivePolicy, PolicyMode } from './rule-policy-active.js';
27
+ export interface PolicyReaderRequest {
28
+ workspaceDir: string;
29
+ sessionId: string;
30
+ toolName: string;
31
+ }
32
+ export interface RulePolicyGateOptions {
33
+ /** Language of the texts shown to the host agent; defaults to `zh-CN`. */
34
+ locale?: PdLocale;
35
+ /** The installed pd binary used in recovery hints and recognised as a recovery control. Defaults to `resolveTrustedPdBinary()`. */
36
+ pdBinary?: TrustedPdBinary;
37
+ /**
38
+ * Per-call reader of the session's earlier tool calls, feeding the `session.*` facts. Absent
39
+ * means those facts are unknown (`session_activity_read_failed`), never zero.
40
+ */
41
+ createSessionActivityReader?: (request: PolicyReaderRequest) => ReadSessionActivityRows;
42
+ /**
43
+ * Whether the host has a channel that hands a reminder to the model without blocking the call
44
+ * (Requirement 12.5). Defaults to true. When false, a live rule that starts at `remind` is
45
+ * judged as `observe` (it never reminds, never counts a reminder and never escalates) and each
46
+ * judgement that would have reminded leaves a `policy_degraded` observation with its next action.
47
+ */
48
+ advisoryChannelAvailable?: boolean;
49
+ now?: () => Date;
50
+ /** Path key platform; defaults to `process.platform`. */
51
+ platform?: string;
52
+ }
53
+ /** One bounded, host-neutral signal about a judgement that did not simply allow or enforce. */
54
+ export interface PolicyObservation {
55
+ kind: 'policy_unknown' | 'policy_target_unproven' | 'mode_self_assessment_mismatch' | 'policy_render_fault' | 'policy_ledger_write_failed' | 'policy_degraded';
56
+ ruleId: string;
57
+ activationId: string;
58
+ mode: PolicyMode;
59
+ reason: string;
60
+ nextAction: string;
61
+ }
62
+ export interface PolicyRuleOutcome {
63
+ active: ActivePolicy;
64
+ evaluation: PolicyEvaluation;
65
+ /** The verdict in host-contract form. Only `live` outcomes may join the gate's merge. */
66
+ result: RuleHostResult;
67
+ }
68
+ export interface PolicyRun {
69
+ outcomes: readonly PolicyRuleOutcome[];
70
+ observations: readonly PolicyObservation[];
71
+ /** Human-readable problems for the host logger, with their next action. */
72
+ warnings: readonly {
73
+ reason: string;
74
+ nextAction: string;
75
+ }[];
76
+ /** Reminder text of the LIVE policies that reminded, ordered by rule id; undefined when none. */
77
+ advisory: string | undefined;
78
+ /** Exactly the rules whose complete reminder text is represented in `advisory`. */
79
+ advisoryRuleIds: readonly string[];
80
+ }
81
+ export interface PolicyEvaluationArgs {
82
+ candidates: readonly ActivePolicy[];
83
+ hostInput: RuleHostInput;
84
+ context: RuleContextV2 | undefined;
85
+ /** Read-only governance connection the gate already holds. */
86
+ governanceDb: SqliteConnection;
87
+ workspaceDir: string;
88
+ sessionId: string;
89
+ /** Native physical tool-call id of this exact invocation, when the host provides one. */
90
+ toolCallId?: string;
91
+ projectRoot: string;
92
+ toolName: string;
93
+ canonicalKind: CanonicalKind;
94
+ bashRisk: BashRiskLevel;
95
+ toolSemantics: ToolSemanticRegistry;
96
+ /** Gate start time; the cutoff for earlier-call facts. */
97
+ startedAt: number;
98
+ }
99
+ export interface PolicyRuntime {
100
+ /** Absolute pd binary paths recognised as a recovery control by the shared action builder. */
101
+ trustedPdBinaries(): readonly string[];
102
+ evaluate(args: PolicyEvaluationArgs): PolicyRun;
103
+ }
104
+ export declare function createPolicyRuntime(options: RulePolicyGateOptions | undefined, hostKind: GovernanceHostKind | undefined): PolicyRuntime;