@principles/host-runtime 5.2.0 → 5.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (53) 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/mode-state-facts.d.ts +41 -0
  19. package/dist/mode-state-facts.js +224 -0
  20. package/dist/product-telemetry/consent-store.d.ts +9 -47
  21. package/dist/product-telemetry/consent-store.js +18 -131
  22. package/dist/production-pain-evidence.d.ts +9 -0
  23. package/dist/production-pain-evidence.js +22 -2
  24. package/dist/production-policy-gate.d.ts +104 -0
  25. package/dist/production-policy-gate.js +379 -0
  26. package/dist/production-rulehost-gate.d.ts +6 -0
  27. package/dist/production-rulehost-gate.js +160 -31
  28. package/dist/prompt-activation-event.d.ts +29 -0
  29. package/dist/prompt-activation-event.js +80 -0
  30. package/dist/prompt-injection-budget-observation.d.ts +0 -11
  31. package/dist/prompt-injection-budget-observation.js +0 -11
  32. package/dist/rule-policy-active.d.ts +80 -0
  33. package/dist/rule-policy-active.js +197 -0
  34. package/dist/rule-policy-host-defaults.d.ts +19 -0
  35. package/dist/rule-policy-host-defaults.js +12 -0
  36. package/dist/rule-policy-paths-fs.d.ts +20 -0
  37. package/dist/rule-policy-paths-fs.js +58 -0
  38. package/dist/rule-policy-replay-evidence.d.ts +52 -0
  39. package/dist/rule-policy-replay-evidence.js +259 -0
  40. package/dist/session-write-targets.d.ts +86 -0
  41. package/dist/session-write-targets.js +216 -0
  42. package/dist/signal-classifier.d.ts +1 -0
  43. package/dist/signal-classifier.js +1 -1
  44. package/dist/signal-rate-limiter.d.ts +34 -0
  45. package/dist/signal-rate-limiter.js +83 -0
  46. package/dist/trajectory-retention.d.ts +8 -0
  47. package/dist/trajectory-retention.js +29 -0
  48. package/dist/trusted-pd-binary.d.ts +10 -0
  49. package/dist/trusted-pd-binary.js +38 -0
  50. package/dist/workbuddy-rule-context-provider.js +31 -10
  51. package/dist/workspace-behavior-evidence.d.ts +55 -0
  52. package/dist/workspace-behavior-evidence.js +93 -0
  53. package/package.json +24 -4
@@ -0,0 +1,224 @@
1
+ /**
2
+ * Mode-state fact loader (SPEC-PD-RULE-POLICY-001 Requirement 8; design.md §8).
3
+ *
4
+ * Reads one session's Mode_Store records and live Decision_Ledger reminders from the
5
+ * governance workspace connection the gate already holds, and returns the
6
+ * `ModeStateFact` the policy evaluator consumes.
7
+ *
8
+ * Trust boundary: every input of `loadModeStateFact` comes from the host event or from
9
+ * the host's own configuration. There is deliberately NO parameter that carries tool
10
+ * arguments, because the values below are rendered into commands the agent is told to
11
+ * run; a path or id taken from a tool call would let the agent steer that command.
12
+ *
13
+ * Failure is never silent (rc-9): any read error becomes `status: 'unavailable'` with a
14
+ * bounded reason, which the evaluator turns into `unknown` (never into a reminder or block).
15
+ */
16
+ import * as fs from 'node:fs';
17
+ import * as path from 'node:path';
18
+ import { SqliteDecisionLedgerStore, SqliteModeDeclarationStore, checkHostSessionId, } from '@principles/core/runtime/internalization/rule-policy-modes';
19
+ import { toPolicyPathKey } from '@principles/core/runtime/internalization/rule-policy-paths';
20
+ import { realPathForPolicyTarget } from './rule-policy-paths-fs.js';
21
+ const REASON_MAX = 300;
22
+ const LABEL_SLUG_MAX = 40;
23
+ const SESSION_PREFIX_LENGTH = 8;
24
+ const MODES_DIR = '.principles/modes';
25
+ const RULE_ID_PLACEHOLDER = '{ruleId}';
26
+ const REASON_PLACEHOLDER = {
27
+ 'zh-CN': '<写明为什么这次不适用>',
28
+ en: '<say why this does not apply this time>',
29
+ };
30
+ function emptyFact() {
31
+ return {
32
+ version: 1,
33
+ acts: {},
34
+ scopePaths: null,
35
+ scopeRevision: null,
36
+ latestSituationClass: null,
37
+ waiversByRule: {},
38
+ remindersByRule: {},
39
+ declareHint: null,
40
+ waiveHint: null,
41
+ suggestedFile: null,
42
+ };
43
+ }
44
+ function unavailable(reason) {
45
+ const text = reason.replace(/\s+/g, ' ').trim().slice(0, REASON_MAX);
46
+ return { ...emptyFact(), status: 'unavailable', unavailableReason: text.length > 0 ? text : 'unknown' };
47
+ }
48
+ function isRecord(value) {
49
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
50
+ }
51
+ // ── hint values ────────────────────────────────────────────────────────────
52
+ function hasControlCharacter(value) {
53
+ for (let i = 0; i < value.length; i += 1) {
54
+ const code = value.charCodeAt(i);
55
+ if (code < 0x20 || code === 0x7f)
56
+ return true;
57
+ }
58
+ return false;
59
+ }
60
+ /**
61
+ * Values inside double quotes must not be able to end the quote, expand, or span lines:
62
+ * the agent is told to run these commands, and the Recovery_Marker recogniser refuses any
63
+ * command with expansion anyway.
64
+ */
65
+ function isSafeQuotedValue(value) {
66
+ return value.length > 0 && !/["`$]/.test(value) && !hasControlCharacter(value);
67
+ }
68
+ /**
69
+ * A bare word or path without spaces or shell syntax, or one pair of double quotes around
70
+ * a safe value (a path with spaces). Backslashes are allowed so `C:\Users\x\pd.cmd` works.
71
+ */
72
+ function isSafePdBin(value) {
73
+ if (value.length >= 2 && value.startsWith('"') && value.endsWith('"'))
74
+ return isSafeQuotedValue(value.slice(1, -1));
75
+ return value.length > 0 && !/[\s"'`$;&|<>(){}*?[\]#~!]/.test(value) && !hasControlCharacter(value);
76
+ }
77
+ function slug(text) {
78
+ const cleaned = (text ?? '').toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '').slice(0, LABEL_SLUG_MAX).replace(/-+$/g, '');
79
+ return cleaned.length > 0 ? cleaned : 'mode';
80
+ }
81
+ function sessionPrefix(sessionId) {
82
+ const cleaned = sessionId.slice(0, SESSION_PREFIX_LENGTH).replace(/[^A-Za-z0-9_-]/g, '-');
83
+ return cleaned.length > 0 ? cleaned : 'session';
84
+ }
85
+ function buildHints(q, sessionId) {
86
+ const values = [q.governanceWorkspaceDir, q.projectRoot, sessionId];
87
+ if (q.pdBin === null || !isSafePdBin(q.pdBin) || !values.every(isSafeQuotedValue))
88
+ return null;
89
+ const suggestedFile = `${MODES_DIR}/${slug(q.labelHint)}-${sessionPrefix(sessionId)}.json`;
90
+ const common = `--workspace "${q.governanceWorkspaceDir}" --project "${q.projectRoot}" --session "${sessionId}"`;
91
+ const reason = REASON_PLACEHOLDER[q.locale ?? 'zh-CN'];
92
+ return {
93
+ declareHint: `${q.pdBin} mode declare ${common} --file "${suggestedFile}"`,
94
+ // `{ruleId}` stays literal: the message renderer substitutes the rule being blocked.
95
+ waiveHint: `${q.pdBin} mode waive ${common} --rule "${RULE_ID_PLACEHOLDER}" --reason "${reason}"`,
96
+ suggestedFile,
97
+ };
98
+ }
99
+ // ── scope ──────────────────────────────────────────────────────────────────
100
+ /**
101
+ * Policy keys for the project-relative `inScope` entries of a declaration, or null when
102
+ * ANY entry cannot be converted (or none exist). A partly converted scope would silently
103
+ * shrink the allowed area and flag legitimate writes as drift, so the whole scope is
104
+ * treated as untrusted instead.
105
+ */
106
+ export function toScopeKeys(inScope, projectRoot, platform) {
107
+ if (inScope.length === 0)
108
+ return null;
109
+ const root = projectRoot.replace(/[\\/]+$/, '');
110
+ let realRoot = null;
111
+ if (platform === process.platform && path.isAbsolute(projectRoot) && fs.existsSync(projectRoot)) {
112
+ const resolvedRoot = realPathForPolicyTarget(path.resolve(projectRoot));
113
+ if (!resolvedRoot.ok)
114
+ return null;
115
+ realRoot = resolvedRoot.path;
116
+ }
117
+ const keys = [];
118
+ for (const entry of inScope) {
119
+ const kept = entry.split(/[\\/]/).filter((segment) => segment !== '' && segment !== '.');
120
+ if (kept.length === 0 || kept.includes('..'))
121
+ return null;
122
+ const key = toPolicyPathKey(`${root}/${kept.join('/')}`, projectRoot, platform);
123
+ if (key === null || key === '')
124
+ return null;
125
+ if (realRoot !== null) {
126
+ const resolvedEntry = realPathForPolicyTarget(path.resolve(projectRoot, ...kept));
127
+ if (!resolvedEntry.ok)
128
+ return null;
129
+ const realKey = toPolicyPathKey(resolvedEntry.path, realRoot, platform);
130
+ if (realKey === null || realKey === '')
131
+ return null;
132
+ keys.push(realKey);
133
+ }
134
+ else {
135
+ keys.push(key);
136
+ }
137
+ }
138
+ return keys;
139
+ }
140
+ // ── load ───────────────────────────────────────────────────────────────────
141
+ function customAnswerIdsOf(declarationActs, actId) {
142
+ const output = Object.hasOwn(declarationActs, actId) ? declarationActs[actId] : undefined;
143
+ if (!isRecord(output) || !Object.hasOwn(output, 'customAnswers'))
144
+ return [];
145
+ const answers = output.customAnswers;
146
+ return isRecord(answers) ? Object.keys(answers) : [];
147
+ }
148
+ function groupAscending(entries) {
149
+ const grouped = new Map();
150
+ for (const [ruleId, at] of entries) {
151
+ const times = grouped.get(ruleId) ?? [];
152
+ times.push(at);
153
+ grouped.set(ruleId, times);
154
+ }
155
+ // ISO timestamps from the stores share one format, so lexicographic order is chronological.
156
+ return Object.fromEntries([...grouped].map(([ruleId, times]) => [ruleId, [...times].sort()]));
157
+ }
158
+ function describeError(error) {
159
+ const code = isRecord(error) && typeof error.code === 'string' ? `${error.code}: ` : '';
160
+ const message = error instanceof Error ? error.message : String(error);
161
+ return `mode_state_read_failed: ${code}${message}`;
162
+ }
163
+ /**
164
+ * Mode state of one session. Never throws: a failure to read is `unavailable` with a reason.
165
+ */
166
+ export function loadModeStateFact(q) {
167
+ const session = checkHostSessionId(q.hostSessionId);
168
+ if (!session.ok)
169
+ return unavailable(`session_id_invalid: ${session.reason}`);
170
+ const hints = q.pdBin === null
171
+ ? { declareHint: null, waiveHint: null, suggestedFile: null }
172
+ : buildHints(q, session.sessionId);
173
+ if (hints === null) {
174
+ return unavailable('hint_unsafe_value: a workspace, project, session id or pd binary contains a quote, expansion or control character, so no recovery command can be rendered safely');
175
+ }
176
+ try {
177
+ if (q.hostKind === undefined)
178
+ return unavailable('host_kind_unavailable: the gate did not identify the host, so mode state cannot be attributed');
179
+ const platform = q.platform ?? process.platform;
180
+ const records = new SqliteModeDeclarationStore(q.governanceDb, { platform }).listForSession(q.hostKind, q.projectRoot, session.sessionId);
181
+ const allReminders = new SqliteDecisionLedgerStore(q.governanceDb).listRemindersForSession(q.hostKind, q.projectRoot, session.sessionId);
182
+ const acts = {};
183
+ let latestSituationClass = null;
184
+ let scopeSource = null;
185
+ const waivers = [];
186
+ for (const record of records) {
187
+ if (record.recordKind === 'waiver') {
188
+ waivers.push([record.ruleId, record.recordedAt]);
189
+ continue;
190
+ }
191
+ latestSituationClass = record.situationClass;
192
+ for (const actId of record.actIds) {
193
+ const crossCheck = record.crossCheck?.[actId];
194
+ acts[actId] = {
195
+ recordedAt: record.recordedAt,
196
+ revision: record.revision,
197
+ customAnswerIds: customAnswerIdsOf(record.declaration.acts, actId),
198
+ ...(crossCheck === undefined ? {} : { crossCheck: { kind: crossCheck.kind, score: crossCheck.score } }),
199
+ };
200
+ }
201
+ if (record.scopePaths !== null)
202
+ scopeSource = { inScope: record.scopePaths, revision: record.revision };
203
+ }
204
+ const scopePaths = scopeSource === null ? null : toScopeKeys(scopeSource.inScope, q.projectRoot, platform);
205
+ const wanted = new Set(q.ruleIds);
206
+ const remindersByRule = groupAscending(Object.entries(allReminders).filter(([ruleId]) => wanted.has(ruleId)).flatMap(([ruleId, times]) => times.map((at) => [ruleId, at])));
207
+ const declared = latestSituationClass !== null;
208
+ return {
209
+ ...emptyFact(),
210
+ status: declared ? 'declared' : 'absent',
211
+ acts: declared ? acts : {},
212
+ scopePaths: declared ? scopePaths : null,
213
+ scopeRevision: declared && scopePaths !== null && scopeSource !== null ? scopeSource.revision : null,
214
+ latestSituationClass,
215
+ waiversByRule: groupAscending(waivers),
216
+ remindersByRule,
217
+ ...hints,
218
+ };
219
+ }
220
+ catch (error) {
221
+ return unavailable(describeError(error));
222
+ }
223
+ }
224
+ export { resolveTrustedPdBinary } from './trusted-pd-binary.js';
@@ -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, {