@principles/host-runtime 5.0.0 → 5.2.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
+ }
@@ -48,11 +48,13 @@ export interface PainInboxItem {
48
48
  readonly reason: string | null;
49
49
  readonly createdAt: string;
50
50
  readonly expiresAt: string;
51
+ readonly snoozedUntil?: string | null;
51
52
  }
52
53
  export interface ListPainInboxResult {
53
54
  readonly ok: true;
54
55
  readonly items: readonly PainInboxItem[];
55
56
  readonly total: number;
57
+ readonly snoozedCount: number;
56
58
  readonly byHost: {
57
59
  readonly openclaw: number;
58
60
  readonly codex: number;
@@ -97,6 +99,26 @@ export type DismissInboxCandidateResult = {
97
99
  readonly reason: string;
98
100
  readonly nextAction: string;
99
101
  };
102
+ interface SetSnoozeInput {
103
+ readonly workspaceDir: string;
104
+ readonly itemId: string;
105
+ readonly nowIso?: string;
106
+ readonly databaseFactory?: ObservationDatabaseFactory;
107
+ }
108
+ type SetSnoozeResult = {
109
+ readonly ok: true;
110
+ readonly disposition: 'snoozed';
111
+ readonly itemId: string;
112
+ readonly snoozedUntil: string;
113
+ } | {
114
+ readonly ok: true;
115
+ readonly disposition: 'unsnoozed' | 'not_found' | 'already_resolved';
116
+ readonly itemId: string;
117
+ } | {
118
+ readonly ok: false;
119
+ readonly reason: 'invalid_snooze_time' | 'inbox_snooze_schema_incompatible' | 'inbox_snooze_write_failed';
120
+ readonly nextAction: string;
121
+ };
100
122
  export interface ExpireStalePainInboxResult {
101
123
  readonly ok: boolean;
102
124
  readonly expiredGsa: number;
@@ -110,6 +132,10 @@ export declare function executeQueuedDiagnosisWithInboxRecovery(input: {
110
132
  stateManager: Pick<RuntimeStateManager, 'updateTaskIfDiagnosticJsonUnchanged'>;
111
133
  execute: () => Promise<PainSignalBridgeResult>;
112
134
  }): Promise<PainSignalBridgeResult>;
135
+ export declare function snoozePainInboxCandidate(input: SetSnoozeInput & {
136
+ readonly snoozedUntilIso: string;
137
+ }): SetSnoozeResult;
138
+ export declare function unsnoozePainInboxCandidate(input: SetSnoozeInput): SetSnoozeResult;
113
139
  /**
114
140
  * List unified Pain Inbox candidates across Codex, WorkBuddy, and OpenClaw.
115
141
  * Strictly excludes `source_revoked`, expired (>7d), terminal rows, and
@@ -118,6 +144,7 @@ export declare function executeQueuedDiagnosisWithInboxRecovery(input: {
118
144
  export declare function listPainInboxItems(input: {
119
145
  readonly workspaceDir: string;
120
146
  readonly hostFilter?: PainInboxHostKind;
147
+ readonly includeSnoozed?: boolean;
121
148
  readonly now?: Date;
122
149
  readonly databaseFactory?: ObservationDatabaseFactory;
123
150
  }): ListPainInboxResult;
@@ -143,3 +170,4 @@ export declare function expireStalePainInboxItems(input: {
143
170
  readonly now?: Date;
144
171
  readonly databaseFactory?: ObservationDatabaseFactory;
145
172
  }): ExpireStalePainInboxResult;
173
+ export {};