@principles/host-runtime 4.12.0 → 5.1.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.
@@ -0,0 +1,265 @@
1
+ /**
2
+ * Keyword Optimization Service
3
+ *
4
+ * Applies LLM optimization results (ADD/UPDATE/REMOVE mutations) to the
5
+ * correction keyword store. Invoked by the correction observer service
6
+ * when optimization results are available.
7
+ */
8
+ import { CorrectionCueLearner } from './correction-cue-learner.js';
9
+ import { openCorrectionTrajectory, } from './correction-trajectory-reader.js';
10
+ /**
11
+ * `updates` is keyed BY term, so a key that is blank or is one of the action
12
+ * words means the model put the action in the key slot (observed in
13
+ * production: REMOVE term="add"). Such an entry carries no term and must never
14
+ * reach the store — rc-1/rc-2: untrusted output is not executed as written.
15
+ */
16
+ const RESERVED_UPDATE_KEYS = new Set(['add', 'update', 'remove']);
17
+ /**
18
+ * Applies CorrectionObserverResult mutations to the keyword store.
19
+ * - ADD: calls learner.add() with new keyword (evicts least-valuable learned
20
+ * terms at/over the cap, with bounded convergence when the store is oversized)
21
+ * - UPDATE: updates weight on an existing keyword
22
+ * - REMOVE: removes keyword from store; Owner-authored seed terms and terms
23
+ * with confirmed TPs are protected
24
+ *
25
+ * Every key is resolved with the store's own identity rule (trim + lowercase),
26
+ * and a key that does not resolve is an observable skip, not a thrown error:
27
+ * the model paraphrases terms constantly, and the old per-op exceptions turned
28
+ * that into ~47 WARN lines a day that hid real failures.
29
+ *
30
+ * Persistence is layered and must not be conflated (P2-3):
31
+ * - the keyword store itself is persisted synchronously and atomically by
32
+ * CorrectionCueLearner.flush() (temp-file-then-rename). That is the only
33
+ * durable mutation of record.
34
+ * - the SYSTEM line emitted by audit() is best-effort, asynchronous and may
35
+ * drop entries. It is an Owner-visible trace, not proof that the store write
36
+ * happened; under disk pressure the two can legitimately disagree.
37
+ */
38
+ export class KeywordOptimizationService {
39
+ stateDir;
40
+ workspaceDir;
41
+ logger;
42
+ ports;
43
+ constructor(stateDir, workspaceDir, ports = {}) {
44
+ this.stateDir = stateDir;
45
+ this.workspaceDir = workspaceDir;
46
+ this.logger = ports.logger;
47
+ this.ports = ports;
48
+ }
49
+ applyResult(result) {
50
+ const learner = CorrectionCueLearner.get(this.stateDir);
51
+ const updates = result.updates ?? {};
52
+ if (result.updated && Object.keys(updates).length > 0) {
53
+ for (const [rawKey, update] of Object.entries(updates)) {
54
+ const term = rawKey.trim().toLowerCase();
55
+ if (term === '' || RESERVED_UPDATE_KEYS.has(term)) {
56
+ this.skip(rawKey, update.action, `"${rawKey}" is not a term (blank or action word)`);
57
+ continue;
58
+ }
59
+ const existing = learner.find(term);
60
+ if (update.action !== 'add' && !existing) {
61
+ this.skip(rawKey, update.action, 'not in store');
62
+ continue;
63
+ }
64
+ if (update.action === 'remove' && existing !== undefined) {
65
+ if (existing.source !== 'llm') {
66
+ this.skip(rawKey, update.action, `${existing.source} term is Owner-authored, not machine-removable`);
67
+ continue;
68
+ }
69
+ // Evidence floor (P1-2): the observer only sees a bounded recent
70
+ // window, so "absent from trajectory/recentMessages" proves nothing
71
+ // about a term the store already credited. Without this guard, a
72
+ // confirmed correction cue (TP>0) could be deleted for silence it was
73
+ // never given a fair chance to break. Owner-authored seed/user
74
+ // authority is preserved above; the automatic cap eviction
75
+ // (learner.add → evictLeastValuable) is a separate, tier-ranked path
76
+ // and is deliberately NOT gated by this rule.
77
+ const truePositives = existing.truePositiveCount ?? 0;
78
+ if (truePositives > 0) {
79
+ this.skip(rawKey, update.action, `term has ${truePositives} confirmed correction(s); recent-window silence is not counter-evidence`);
80
+ continue;
81
+ }
82
+ }
83
+ try {
84
+ switch (update.action) {
85
+ case 'add': {
86
+ if (existing) {
87
+ this.audit('ADD_SKIPPED', `"${term}" already exists as "${existing.term}"`);
88
+ break;
89
+ }
90
+ if (term.includes(',')) {
91
+ this.skip(rawKey, 'add', 'joined cue of several terms, not one learnable term');
92
+ break;
93
+ }
94
+ const weight = update.weight !== undefined
95
+ ? Math.max(0.1, Math.min(0.9, update.weight))
96
+ : 0.5;
97
+ const evicted = learner.add({ term, weight, source: 'llm' });
98
+ // PRI-2053: an oversized store can evict several terms in one ADD
99
+ // (bounded convergence). Every one of them is audited — recording
100
+ // only the last would hide which learned evidence actually left.
101
+ const evictionNote = evicted.length > 0
102
+ ? ` evicted=[${evicted.map((t) => `"${t}"`).join(', ')}] (store at cap)`
103
+ : '';
104
+ this.audit('ADD', `term="${term}" weight=${weight}${evictionNote}`);
105
+ break;
106
+ }
107
+ case 'update': {
108
+ if (update.weight === undefined)
109
+ break;
110
+ // A false return means the term vanished between find() and the
111
+ // write (cap eviction race): audit nothing, report the skip.
112
+ if (!learner.updateWeight(term, update.weight)) {
113
+ this.skip(rawKey, 'update', 'not in store');
114
+ break;
115
+ }
116
+ this.audit('UPDATE', `term="${term}" weight=${update.weight}`);
117
+ break;
118
+ }
119
+ case 'remove': {
120
+ // Same rule for REMOVE: a false return must not be reported as a
121
+ // successful store mutation (rc-9 — no fake success audit).
122
+ if (!learner.remove(term)) {
123
+ this.skip(rawKey, 'remove', 'not in store');
124
+ break;
125
+ }
126
+ this.audit('REMOVE', `term="${term}"`);
127
+ break;
128
+ }
129
+ }
130
+ }
131
+ catch (opErr) {
132
+ // Log and skip individual operation failures — don't fail the whole batch
133
+ this.logger?.warn?.(`[KeywordOptimizationService] ${update.action.toUpperCase()} failed for term="${term}": ${String(opErr)}`);
134
+ }
135
+ }
136
+ }
137
+ else {
138
+ this.logger?.info?.('[KeywordOptimizationService] No store mutations to apply');
139
+ }
140
+ // H-1: Record confirmed false positives — terms where correctionDetected fired
141
+ // but trajectory analysis shows user wasn't actually expressing frustration.
142
+ // PRI-812: recorded INDEPENDENTLY of `updated`/`updates` — the observer
143
+ // contract allows an FP-only verdict (updated=false, fpTerms=[...]), and
144
+ // that verdict is the counter-evidence the earned-high demotion loop
145
+ // consumes (high → FP=1 → precisionFor → ambiguous). Gating it behind
146
+ // store mutations silently discarded the only demotion signal.
147
+ if (result.fpAnalysisStatus === 'completed' && result.fpTerms && result.fpTerms.length > 0) {
148
+ // Normalize: trim, lowercase, dedupe, sanity cap
149
+ const MAX_FP_TERMS = 20;
150
+ const normalizedFpTerms = [...new Set(result.fpTerms
151
+ .map((t) => t.trim().toLowerCase())
152
+ .filter((t) => t.length > 0))].slice(0, MAX_FP_TERMS);
153
+ for (const term of normalizedFpTerms) {
154
+ try {
155
+ if (learner.recordFalsePositive(term)) {
156
+ this.audit('FP_RECORDED', `term="${term}" (weight x0.8)`);
157
+ }
158
+ else {
159
+ this.skip(term, 'fp', 'not in store');
160
+ }
161
+ }
162
+ catch (fpErr) {
163
+ this.logger?.warn?.(`[KeywordOptimizationService] recordFalsePositive failed for term="${term}": ${String(fpErr)}`);
164
+ }
165
+ }
166
+ }
167
+ }
168
+ /**
169
+ * One Owner-visible line per store mutation: plugin log + SYSTEM log.
170
+ *
171
+ * The mutation is durable because the learner flushed the store before this
172
+ * call. The SYSTEM line is a best-effort audit trace (async appendFile that
173
+ * swallows errors): its absence never means the mutation did not happen, and
174
+ * its presence is never by itself evidence that it did.
175
+ */
176
+ audit(action, detail) {
177
+ this.logger?.info?.(`[KeywordOptimizationService] ${action} ${detail}`);
178
+ this.ports.audit?.(`${action} ${detail}`);
179
+ }
180
+ /**
181
+ * A verdict the store cannot act on. Reported, not thrown: the model
182
+ * paraphrases term keys constantly, and each refusal still needs a reason
183
+ * (rc-9 — degradation must be observable).
184
+ */
185
+ skip(term, action, reason) {
186
+ this.logger?.warn?.(`[KeywordOptimizationService] ${action.toUpperCase()} skipped for term="${term}": ${reason}`);
187
+ }
188
+ /**
189
+ * Builds trajectory history for payload:
190
+ * - Calls TrajectoryDatabase.listUserTurnsForSession() for recent sessions
191
+ * - Filters to turns where correctionDetected=true
192
+ * - Returns last 50 correction events
193
+ */
194
+ async buildTrajectoryHistory(sessionIds) {
195
+ const history = [];
196
+ const db = (this.ports.openTrajectory ?? (() => openCorrectionTrajectory(this.workspaceDir)))();
197
+ try {
198
+ for (const sessionId of sessionIds.slice(0, 10)) { // Last 10 sessions
199
+ try {
200
+ const turns = db.listUserTurnsForSession(sessionId);
201
+ for (const turn of turns) {
202
+ if (turn.correctionDetected) {
203
+ const cue = (turn.correctionCue ?? '').trim();
204
+ // A cue persisted as "llm:<reason>" is Stage2 verdict prose, not a
205
+ // keyword. Passing it through as `term` is what taught the
206
+ // optimizer to store whole sentences as terms (52 of the 58
207
+ // detected turns in the live workspace) — an empty term says
208
+ // honestly "this correction had no keyword match", which
209
+ // buildPrompt renders.
210
+ const proseOnly = cue.startsWith('llm:');
211
+ // Stage1 joins every matched term with ", ", so one cue can name
212
+ // several terms. Emit one event per term: the observer judges and
213
+ // proposes per term, and a joined string handed to it as a single
214
+ // "term" is exactly the composite that would come back as an ADD
215
+ // candidate that can never match again.
216
+ const terms = proseOnly ? [''] : (cue.split(',').map((t) => t.trim()).filter((t) => t !== ''));
217
+ for (const term of terms.length > 0 ? terms : ['']) {
218
+ history.push({
219
+ sessionId,
220
+ timestamp: turn.createdAt ?? new Date().toISOString(),
221
+ term,
222
+ // PRI-823: carry the bounded raw excerpt (≤200 chars, persisted
223
+ // per user_turn) so the observer can judge each hit event on its
224
+ // own message text instead of guessing from the term alone. Same
225
+ // data category recentMessages already delivers — no new storage
226
+ // or privacy surface. buildPrompt still caps rendering at 80
227
+ // chars/entry.
228
+ userMessage: turn.rawExcerpt ?? '',
229
+ });
230
+ if (history.length >= 50)
231
+ break; // Cap at 50 events
232
+ }
233
+ }
234
+ if (history.length >= 50)
235
+ break;
236
+ }
237
+ }
238
+ catch (dbErr) {
239
+ // Skip individual session DB errors — try remaining sessions
240
+ this.logger?.warn?.(`[KeywordOptimizationService] Failed to read trajectory for session ${sessionId}: ${String(dbErr)}`);
241
+ }
242
+ if (history.length >= 50)
243
+ break;
244
+ }
245
+ }
246
+ finally {
247
+ db.close?.();
248
+ }
249
+ return history;
250
+ }
251
+ // ── Singleton factory ───────────────────────────────────────────────────
252
+ static _instances = new Map();
253
+ static get(stateDir, workspaceDir, ports) {
254
+ const key = `${stateDir}::${workspaceDir}`;
255
+ const existing = KeywordOptimizationService._instances.get(key);
256
+ if (existing)
257
+ return existing;
258
+ const service = new KeywordOptimizationService(stateDir, workspaceDir, ports);
259
+ KeywordOptimizationService._instances.set(key, service);
260
+ return service;
261
+ }
262
+ static reset() {
263
+ KeywordOptimizationService._instances.clear();
264
+ }
265
+ }
@@ -28,6 +28,7 @@
28
28
  * exclude `source_revoked` rows and re-verify `readSourceMaterialAuthorization()`
29
29
  * live before admitting.
30
30
  */
31
+ import { type RuntimeStateManager, type TaskRecord, type PainSignalBridgeResult } from '@principles/core/runtime';
31
32
  import type { ObservationDatabaseFactory } from './governance-observation-store.js';
32
33
  export declare const PAIN_INBOX_TTL_MS: number;
33
34
  export declare const PAIN_INBOX_APPROVING_TTL_MS: number;
@@ -102,6 +103,13 @@ export interface ExpireStalePainInboxResult {
102
103
  readonly expiredOpenClaw: number;
103
104
  readonly reason?: string;
104
105
  }
106
+ /** All background diagnosis workers share this same narrow recovery boundary. */
107
+ export declare function executeQueuedDiagnosisWithInboxRecovery(input: {
108
+ workspaceDir: string;
109
+ task: TaskRecord;
110
+ stateManager: Pick<RuntimeStateManager, 'updateTaskIfDiagnosticJsonUnchanged'>;
111
+ execute: () => Promise<PainSignalBridgeResult>;
112
+ }): Promise<PainSignalBridgeResult>;
105
113
  /**
106
114
  * List unified Pain Inbox candidates across Codex, WorkBuddy, and OpenClaw.
107
115
  * Strictly excludes `source_revoked`, expired (>7d), terminal rows, and
@@ -31,9 +31,11 @@
31
31
  import { createHash, randomUUID } from 'node:crypto';
32
32
  import fs from 'node:fs';
33
33
  import path from 'node:path';
34
+ import { isDeepStrictEqual } from 'node:util';
34
35
  import Database from 'better-sqlite3';
35
36
  import { resolveTrajectoryDbPath } from '@principles/core/runtime/storage-paths';
36
- import { evaluatePainIngress, } from '@principles/core/runtime';
37
+ import { checkIngressTopLevelConsistency, createDiagnosticianTaskId, evaluatePainIngress, parsePainIngressV1Payload, } from '@principles/core/runtime';
38
+ import { isAutomaticPainSubmissionAuthorized } from './auto-pain-authorization.js';
37
39
  import { readSourceMaterialAuthorization } from './source-material-authorization.js';
38
40
  import { ensureGovernanceDiagnosticianTask } from './governance-signal-admission.js';
39
41
  export const PAIN_INBOX_TTL_MS = 7 * 24 * 60 * 60 * 1000;
@@ -246,6 +248,15 @@ function evaluateInboxCanonicalAdmission(args) {
246
248
  }
247
249
  return { ok: true, decision };
248
250
  }
251
+ function automaticInboxSubmissionRefusal(workspaceDir, provenance) {
252
+ if (provenance !== 'automatic_hook' || isAutomaticPainSubmissionAuthorized(workspaceDir))
253
+ return null;
254
+ return {
255
+ ok: false,
256
+ reason: 'auto_pain_unauthorized',
257
+ nextAction: 'Enable automatic Pain submission in this workspace before approving this item, or dismiss it. No Pain was submitted.',
258
+ };
259
+ }
249
260
  function openTrajectoryDb(workspaceDir, readonly, factory) {
250
261
  const dbPath = resolveTrajectoryDbPath(workspaceDir);
251
262
  if (!factory && !fs.existsSync(dbPath))
@@ -273,6 +284,103 @@ function deriveInboxCanonicalPainId(hostKind, key) {
273
284
  .slice(0, 16);
274
285
  return `pain_${hostKind}_inbox_${digest}`;
275
286
  }
287
+ /**
288
+ * Repair only the historical Inbox writer's contradictory mirror. The
289
+ * independent, Owner-approved marker must match the queued task; this is not
290
+ * a fallback in the general re-entry validator. It neither replays an
291
+ * approval nor reconstructs evidence from conversation material.
292
+ */
293
+ async function repairQueuedLegacyInboxProvenance(input) {
294
+ const { workspaceDir, task, stateManager } = input;
295
+ const painId = task.inputRef;
296
+ if (task.taskKind !== 'diagnostician' || (task.status !== 'pending' && task.status !== 'retry_wait')
297
+ || task.leaseOwner !== undefined
298
+ || painId === undefined || !/^pain_(codex|workbuddy|openclaw)_inbox_[0-9a-f]{16}$/.test(painId)
299
+ || task.taskId !== createDiagnosticianTaskId(painId) || task.diagnosticJson === undefined) {
300
+ return 'not_applicable';
301
+ }
302
+ const record = parseJsonSafe(task.diagnosticJson);
303
+ if (record?.provenance !== 'host_context_bound' || record.sourcePainId !== painId
304
+ || !Array.isArray(record.evidence))
305
+ return 'not_applicable';
306
+ const ingress = parsePainIngressV1Payload(record.painIngress);
307
+ if (!ingress.ok)
308
+ return 'not_applicable';
309
+ const { correlation, origin } = ingress.payload;
310
+ if (correlation.status !== 'bound' || origin.kind !== 'automatic_hook')
311
+ return 'not_applicable';
312
+ const host = correlation.hostKind;
313
+ const sessionId = host === 'codex' ? correlation.rootSessionId : correlation.sessionId;
314
+ if (origin.source !== `${host}:pain_inbox` || record.hostKind !== host || record.sessionIdHint !== sessionId
315
+ || checkIngressTopLevelConsistency({
316
+ payload: ingress.payload, topLevelProvenance: 'automatic_hook',
317
+ topLevelSessionIdHint: sessionId, topLevelEvidenceCount: record.evidence.length,
318
+ }) !== null)
319
+ return 'not_applicable';
320
+ const trajectory = openTrajectoryDb(workspaceDir, true);
321
+ if (trajectory === null)
322
+ return 'not_applicable';
323
+ try {
324
+ if (!tableExists(trajectory.db, 'governance_signal_admissions'))
325
+ return 'not_applicable';
326
+ const marker = trajectory.db.prepare(`SELECT * FROM governance_signal_admissions
327
+ WHERE canonical_pain_id = ? AND diagnostician_task_id = ? AND decision = 'inbox_approved'`).get(painId, task.taskId);
328
+ if (!isGsaAdmissionRow(marker) || marker.host_kind !== host || marker.root_session_id !== sessionId)
329
+ return 'not_applicable';
330
+ const payload = parseJsonSafe(marker.task_payload_json);
331
+ if (payload === null || payload.source !== record.source || payload.sessionId !== sessionId || payload.hostKind !== host
332
+ || payload.reason !== record.reasonSummary
333
+ || !isRecord(payload.ownerApproval) || typeof payload.ownerApproval.approvedAt !== 'string'
334
+ || !isDeepStrictEqual(payload.painIngress, record.painIngress)
335
+ || !Array.isArray(payload.evidence)
336
+ || !isDeepStrictEqual(payload.evidence.map((entry) => (isRecord(entry) ? { kind: 'behavior_trace', sourceRef: entry.sourceRef, note: entry.note } : null)), record.evidence))
337
+ return 'not_applicable';
338
+ let inboxKey = marker.logical_observation_key;
339
+ if (host === 'openclaw' && inboxKey.startsWith('openclaw:confirmation:')) {
340
+ inboxKey = inboxKey.slice('openclaw:confirmation:'.length);
341
+ if (payload.source !== 'mid_confidence_correction' || payload.ownerApproval.confirmationId !== inboxKey)
342
+ return 'not_applicable';
343
+ }
344
+ else if (payload.source !== 'trajectory_stall' && payload.source !== 'idle_audit_deviation') {
345
+ // Governed-host correction tasks were written by another branch.
346
+ return 'not_applicable';
347
+ }
348
+ if (deriveInboxCanonicalPainId(host, inboxKey) !== painId)
349
+ return 'not_applicable';
350
+ const consent = readSourceMaterialAuthorization({ workspaceDir, hostKind: host });
351
+ if (consent.status !== 'authorized' && !(host === 'openclaw' && consent.reason === 'consent_missing')) {
352
+ return 'source_authorization_blocked';
353
+ }
354
+ if (!isAutomaticPainSubmissionAuthorized(workspaceDir))
355
+ return 'auto_pain_unauthorized';
356
+ const updated = await stateManager.updateTaskIfDiagnosticJsonUnchanged(task.taskId, task.diagnosticJson, {
357
+ diagnosticJson: JSON.stringify({
358
+ ...record, provenance: 'automatic_hook', provenanceReason: 'Pain detected by automatic hook (after_tool_call)',
359
+ }),
360
+ }, {
361
+ expectedStatus: task.status, expectedAttemptCount: task.attemptCount,
362
+ expectedLeaseOwner: null, expectedLeaseExpiresAt: task.leaseExpiresAt ?? null, expectedLeaseGeneration: task.leaseGeneration ?? 0,
363
+ });
364
+ return updated === null ? 'conflict' : 'repaired';
365
+ }
366
+ finally {
367
+ trajectory.close();
368
+ }
369
+ }
370
+ /** All background diagnosis workers share this same narrow recovery boundary. */
371
+ export async function executeQueuedDiagnosisWithInboxRecovery(input) {
372
+ const repair = await repairQueuedLegacyInboxProvenance(input);
373
+ if (repair === 'not_applicable' || repair === 'repaired')
374
+ return input.execute();
375
+ return {
376
+ status: 'skipped',
377
+ taskId: input.task.taskId,
378
+ painId: input.task.inputRef ?? input.task.taskId,
379
+ candidateIds: [],
380
+ ledgerEntryIds: [],
381
+ message: repair === 'conflict' ? 'candidate_changed' : repair,
382
+ };
383
+ }
276
384
  function parseItemId(itemId) {
277
385
  if (itemId.startsWith('gsa:') && itemId.length > 4) {
278
386
  return { source: 'gsa', rawKey: itemId.slice(4) };
@@ -576,6 +684,9 @@ export async function admitOwnerApprovedInboxCandidate(input) {
576
684
  };
577
685
  }
578
686
  const canonical = ingress.decision.legacy;
687
+ const refusal = automaticInboxSubmissionRefusal(workspaceDir, canonical.provenance);
688
+ if (refusal)
689
+ return refusal;
579
690
  // W3 Step 1: CAS claim inbox_candidate -> inbox_approving
580
691
  const approvingPayload = {
581
692
  ...payload,
@@ -797,6 +908,9 @@ export async function admitOwnerApprovedInboxCandidate(input) {
797
908
  };
798
909
  }
799
910
  const canonical = ingress.decision.legacy;
911
+ const refusal = automaticInboxSubmissionRefusal(workspaceDir, canonical.provenance);
912
+ if (refusal)
913
+ return refusal;
800
914
  const claimPayload = {
801
915
  signalKind: 'mid_confidence_correction',
802
916
  excerpt: (ocRow.excerpt ?? '').slice(0, 500),
@@ -2,7 +2,6 @@ import fs from 'node:fs';
2
2
  import { buildRuleHostAction, buildToolSemanticRegistry, deriveToolHintsFromCanonicalKind, estimateLineChanges, mergeDecisions, normalizeRuleHostResult, SqliteConnection, UNAVAILABLE_RULE_CONTEXT, validateRuleContextV2, verifyPiArtifactRowDigest, RECOVERY_CONTROL_SURFACES, } from '@principles/core/runtime';
3
3
  import { buildRuleHostInput, isRuleHostEvaluableKind } from '@principles/core/runtime/internalization/rule-host-input-builder';
4
4
  import { classifyBashRisk } from '@principles/core/runtime/internalization/bash-risk';
5
- import { scanRetiredContractSymbols } from './legacy-rule-contract-symbols.js';
6
5
  import { recordDegradedEnforcement } from './degraded-enforcement-marker.js';
7
6
  import { createNodeRuleImplementationRuntime, MAX_ACTIVE_RULES, RULE_BATCH_SOURCE_BYTES, RULE_SOURCE_BYTES, } from './rule-implementation-runtime.js';
8
7
  import { resolveStateDbPath } from '@principles/core/runtime/storage-paths';
@@ -639,24 +638,6 @@ export function createProductionRuleHostGate(options = {}) {
639
638
  }
640
639
  const ruleId = typeof content.ruleId === 'string' ? content.ruleId : typeof row.source_rule_id === 'string' ? row.source_rule_id : artifactId;
641
640
  const principleId = typeof content.principleId === 'string' ? content.principleId : typeof row.source_principle_id === 'string' ? row.source_principle_id : ruleId;
642
- // Retired-contract backstop (2026-08-19; host-liveness correction
643
- // 2026-08-21):
644
- // persisted LIVE RuleCode that references removed RuleHost
645
- // contract symbols can never run safely against the new contract
646
- // — reads silently resolve to undefined and change owner-approved
647
- // behavior. The incompatible activation is therefore skipped and
648
- // surfaced with an actionable warning. It must not turn a runtime
649
- // compatibility defect into a host-wide deny; healthy sibling
650
- // rules continue to evaluate. The scan is a local copy (see
651
- // legacy-rule-contract-symbols.ts) so the published bundle keeps
652
- // working against the currently published core.
653
- const retiredSymbols = scanRetiredContractSymbols(content.implementationCode);
654
- if (retiredSymbols.length > 0) {
655
- const nextAction = 'migrate the RuleCode off the retired contract symbols or deactivate the activation, then re-approve a migrated rule';
656
- addWarning(warnings, `legacy_rule_contract_dependency: ${retiredSymbols.join(', ')} (activation=${activationId})`, nextAction);
657
- addFault(evaluationFaults, 'skipped', { ...faultSource, ruleId }, `legacy_rule_contract_dependency: ${retiredSymbols.join(', ')} (activation=${activationId})`, nextAction);
658
- continue;
659
- }
660
641
  const fallbackMeta = { name: activationId, version: '1', ruleId, coversCondition: 'all' };
661
642
  // PRI-1187: resolved for the observation-only mismatch signal; it
662
643
  // is attached to the candidate but never filters the batch.
@@ -0,0 +1,54 @@
1
+ declare const CORRECTION_OBSERVER_HOSTS: readonly ['openclaw', 'codex', 'workbuddy'];
2
+ export type CorrectionObserverHostKind = typeof CORRECTION_OBSERVER_HOSTS[number];
3
+ type ObserverInputDigests = Partial<Record<CorrectionObserverHostKind, string>>;
4
+ export interface SignalHealthState {
5
+ /** 当日计数:跨日首写归零 */
6
+ stage1Strong: number;
7
+ stage2Confirmed: number;
8
+ stage2Queued: number;
9
+ stage2Dropped: number;
10
+ /**
11
+ * AUDIT-P2-02 (2026-10-21): 当日实际发起的 Stage2 LLM 分类调用次数
12
+ * (realtime detectAsyncAndRoute + 批量确认 confirmPendingSignal 都算——
13
+ * 两者都是花同一个 signal classifier 的钱)。计数时点:真正发起 classifier
14
+ * 调用前;降级/空队列/未配置不计数。跨日归零;旧文件缺失按 0 读。
15
+ */
16
+ stage2Invocations: number;
17
+ /**
18
+ * AUDIT-P2-02 (2026-10-21): 当日因分类器不可用被整批跳过的批量确认次数。
19
+ * 只在「队列非空但 classifier 解析失败」时 +1(空队列不计数——没有工作被
20
+ * 跳过)。让 Owner 能区分「没检测到信号 / 没调用模型 / 队列没被消费」。
21
+ * 跨日归零;旧文件缺失按 0 读。
22
+ */
23
+ stage2BatchSkipped: number;
24
+ /**
25
+ * 零命中「发现」调用被每小时配额挡下的次数(AUDIT-P2-03 性能整改)。
26
+ * 它回答「有多少普通消息本来要送去分类、被预算拦住了」——没有这个计数,
27
+ * 调用量下降就无法与「检测失效」区分。跨日归零;旧文件缺失按 0 读。
28
+ */
29
+ stage2DiscoverySkipped: number;
30
+ /** 最近一次刷新的队列深度(非计数) */
31
+ pendingCount: number;
32
+ lastStage2SuccessAt: string | null;
33
+ /** The shared cooldown clock, not an input watermark. */
34
+ observerLastSuccessAt: string | null;
35
+ /** One digest per host of its last successfully processed, bounded input. No transcript text. */
36
+ observerInputDigests?: ObserverInputDigests;
37
+ /** observer 周期连续失败次数(成功即归零) */
38
+ observerConsecutiveFailures: number;
39
+ /** 归零基准日(YYYY-MM-DD) */
40
+ day: string;
41
+ updatedAt: string;
42
+ }
43
+ /**
44
+ * 读健康状态(doctor 用)。文件缺失/损坏返回 null,由读取方呈现 unknown。
45
+ * 旧格式(无 AUDIT-P2-02 新增计数字段)照常解析,缺省字段读作 0。
46
+ */
47
+ export declare function readSignalHealth(stateDir: string): SignalHealthState | null;
48
+ /**
49
+ * 原子更新健康状态。mutator 收到当前状态(已做跨日归零),就地修改后写回。
50
+ * 任何失败都不抛出——旁路观测不阻塞检测管线。
51
+ */
52
+ export type SignalHealthWriteError = (workspaceDir: string, error: unknown) => void;
53
+ export declare function updateSignalHealth(stateDir: string, mutate: (state: SignalHealthState) => void, onError?: SignalHealthWriteError): void;
54
+ export {};