@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 @@
1
+ export declare function atomicWriteFileSync(filePath: string, data: string | Buffer): void;
@@ -0,0 +1,100 @@
1
+ import * as path from 'path';
2
+ import * as fs from 'fs';
3
+ /**
4
+ * Atomic file write — write to a private staging file, then rename to the
5
+ * target to prevent partial writes on crash.
6
+ *
7
+ * Temp-file safety (P2-3 + CodeQL js/insecure-temporary-file remediation):
8
+ * the staging file lives in a PRIVATE staging directory created with
9
+ * `mkdtempSync` (mode 0700 on POSIX, user-private ACL on Windows) inside the
10
+ * TARGET's own directory — same volume, so the rename stays atomic. mkdtemp
11
+ * guarantees a unique, unpredictable directory name (an attacker cannot
12
+ * pre-create or follow it), and the 0700 directory means even a same-user
13
+ * peer process cannot touch the staging file mid-write. The staging file
14
+ * itself is created exclusively (`wx`). This replaces both the historical
15
+ * fixed `<target>.tmp` name and the flat same-directory temp file.
16
+ *
17
+ * On Windows, renameSync can fail with EPERM/EBUSY if the file is temporarily
18
+ * locked by antivirus software or another process. Retries with exponential
19
+ * backoff to handle transient locks.
20
+ */
21
+ const RENAME_MAX_RETRIES = 3;
22
+ const RENAME_BASE_DELAY_MS = 50;
23
+ export function atomicWriteFileSync(filePath, data) {
24
+ const dir = path.dirname(filePath);
25
+ const base = path.basename(filePath);
26
+ // Private staging directory (unique + unpredictable + owner-only). A
27
+ // missing target directory surfaces as mkdtemp's own ENOENT — no
28
+ // existsSync pre-check, so mocked-filesystem flows stay honest too.
29
+ const stagingDir = fs.mkdtempSync(path.join(dir, `${base}.staging.`));
30
+ const tmpPath = path.join(stagingDir, `${base}.tmp`);
31
+ try {
32
+ // 'wx' = exclusive create inside the private staging dir.
33
+ const fd = fs.openSync(tmpPath, fs.constants.O_WRONLY | fs.constants.O_CREAT | fs.constants.O_EXCL);
34
+ try {
35
+ if (typeof data === 'string') {
36
+ fs.writeFileSync(fd, data, 'utf8');
37
+ }
38
+ else {
39
+ fs.writeFileSync(fd, data);
40
+ }
41
+ }
42
+ finally {
43
+ fs.closeSync(fd);
44
+ }
45
+ }
46
+ catch (err) {
47
+ // A partially written staging file is OURS — never leave residue.
48
+ try {
49
+ fs.rmSync(stagingDir, { recursive: true, force: true });
50
+ }
51
+ catch { /* best effort */ }
52
+ throw err;
53
+ }
54
+ let lastError = new Error('Atomic rename did not run');
55
+ for (let attempt = 0; attempt < RENAME_MAX_RETRIES; attempt++) {
56
+ try {
57
+ fs.renameSync(tmpPath, filePath);
58
+ // Rename succeeded: remove the (now empty) staging directory.
59
+ try {
60
+ fs.rmdirSync(stagingDir);
61
+ }
62
+ catch { /* best effort */ }
63
+ return;
64
+ }
65
+ catch (err) {
66
+ lastError = err;
67
+ const { code } = err;
68
+ // Only retry on Windows transient lock errors
69
+ if (code === 'EPERM' || code === 'EBUSY' || code === 'EACCES') {
70
+ if (attempt < RENAME_MAX_RETRIES - 1) {
71
+ const delay = RENAME_BASE_DELAY_MS * Math.pow(2, attempt);
72
+ // Bounded spin-wait with CPU yield — materially different from
73
+ // tight infinite spin; only 50-200ms total across retries.
74
+ const waitUntil = Date.now() + delay;
75
+ let yielded = false;
76
+ while (Date.now() < waitUntil) {
77
+ if (!yielded && Date.now() >= waitUntil - 10) {
78
+ // Last few ms: yield to give other sync code a chance to run
79
+ try {
80
+ fs.accessSync?.(tmpPath);
81
+ }
82
+ catch { /* ignore */ }
83
+ yielded = true;
84
+ }
85
+ }
86
+ }
87
+ continue;
88
+ }
89
+ // Non-retryable error — throw immediately
90
+ break;
91
+ }
92
+ }
93
+ // Rename failed after retries: remove OUR staging dir (with the staging
94
+ // file inside); the original target file was never touched.
95
+ try {
96
+ fs.rmSync(stagingDir, { recursive: true, force: true });
97
+ }
98
+ catch { /* best effort */ }
99
+ throw lastError;
100
+ }
@@ -0,0 +1,69 @@
1
+ /**
2
+ * Correction Cue Learner
3
+ *
4
+ * Persistent, learnable keyword store for correction cue detection.
5
+ * Replaces the hardcoded cue list in detectCorrectionCue() with a
6
+ * crash-safe JSON store that can grow over time.
7
+ *
8
+ * Persistence contract:
9
+ * - Atomic write: temp-file-then-rename (T-38-02)
10
+ * - Cache invalidated after every write (D-05), keyed by stateDir (EP-07)
11
+ * - MAX_CORRECTION_KEYWORDS is a budget, not a freeze: at the cap the least
12
+ * valuable llm-learned term is evicted so learning never stops (T-38-01).
13
+ * seed/user terms are never evicted — they are Owner-authored authority.
14
+ */
15
+ import type { CorrectionKeyword, CorrectionKeywordStore } from '@principles/core/runtime';
16
+ export declare function _resetCorrectionCueCache(): void;
17
+ export declare function saveCorrectionKeywordStore(stateDir: string, store: CorrectionKeywordStore): void;
18
+ export declare function loadCorrectionKeywordStore(stateDir: string): CorrectionKeywordStore;
19
+ export declare function _resetCorrectionCueLearnerInstance(): void;
20
+ export declare class CorrectionCueLearner {
21
+ private readonly store;
22
+ private readonly stateDir;
23
+ constructor(stateDir: string);
24
+ recordTruePositive(term: string): boolean;
25
+ recordFalsePositive(term: string): boolean;
26
+ /**
27
+ * Insert a term, keeping the store inside MAX_CORRECTION_KEYWORDS.
28
+ *
29
+ * At/over the cap the least valuable `llm` terms leave first (see
30
+ * evictionTier), because throwing instead froze the learning channel
31
+ * permanently once the store filled up. The store may already be OVERSIZED
32
+ * from an older build; in that case each ADD also evicts up to
33
+ * MAX_EVICTIONS_PER_ADD terms, so the count converges downwards instead of
34
+ * being replaced one-for-one forever.
35
+ *
36
+ * @returns the evicted terms (empty when the store had room).
37
+ * @throws when there are too few evictable learned terms to preserve the cap
38
+ * (at 200) or to reduce the count (above 200), without touching Owner
39
+ * seed/user authority. A failed ADD leaves the store unchanged.
40
+ */
41
+ add(keyword: Omit<CorrectionKeyword, 'addedAt'>): string[];
42
+ /**
43
+ * Rank learned terms by what the store itself proves about them, worst first:
44
+ * proven noise (FP without any TP) leaves before never-confirmed terms, which
45
+ * leave before confirmed-useful ones. Within a tier, low weight then old
46
+ * addition loses. seed/user entries are Owner authority and never compete.
47
+ *
48
+ * @param count maximum number of terms to evict (bounded by the caller).
49
+ * @returns evicted terms in eviction order (fewer than `count` when the store
50
+ * holds fewer learned terms).
51
+ */
52
+ private evictLeastValuable;
53
+ /** @returns false when the term is not in the store (caller logs the skip). */
54
+ updateWeight(term: string, weight: number): boolean;
55
+ /** @returns false when the term is not in the store (caller logs the skip). */
56
+ remove(term: string): boolean;
57
+ /** Look a term up with the store's own identity rule (trim + lowercase). */
58
+ find(term: string): CorrectionKeyword | undefined;
59
+ getStore(): CorrectionKeywordStore;
60
+ getLastOptimizedAt(): string;
61
+ /**
62
+ * The store's only durable write: an atomic temp-file-then-rename of
63
+ * correction_keywords.json (T-38-02). A successful flush — not a SYSTEM log
64
+ * line — is what makes a mutation real; the audit trail emitted by
65
+ * KeywordOptimizationService is best-effort and may be missing.
66
+ */
67
+ flush(): void;
68
+ static get(stateDir: string): CorrectionCueLearner;
69
+ }
@@ -0,0 +1,366 @@
1
+ /**
2
+ * Correction Cue Learner
3
+ *
4
+ * Persistent, learnable keyword store for correction cue detection.
5
+ * Replaces the hardcoded cue list in detectCorrectionCue() with a
6
+ * crash-safe JSON store that can grow over time.
7
+ *
8
+ * Persistence contract:
9
+ * - Atomic write: temp-file-then-rename (T-38-02)
10
+ * - Cache invalidated after every write (D-05), keyed by stateDir (EP-07)
11
+ * - MAX_CORRECTION_KEYWORDS is a budget, not a freeze: at the cap the least
12
+ * valuable llm-learned term is evicted so learning never stops (T-38-01).
13
+ * seed/user terms are never evicted — they are Owner-authored authority.
14
+ */
15
+ import * as fs from 'fs';
16
+ import * as path from 'path';
17
+ import { CORRECTION_SEED_KEYWORDS, MAX_CORRECTION_KEYWORDS, } from '@principles/core/runtime';
18
+ import { atomicWriteFileSync } from './atomic-write-file.js';
19
+ const KEYWORD_STORE_FILE = 'correction_keywords.json';
20
+ const MIN_KEYWORD_WEIGHT = 0.1;
21
+ const MAX_KEYWORD_WEIGHT = 0.9;
22
+ /**
23
+ * PRI-2053: bounded convergence rate for a historically oversized store.
24
+ *
25
+ * A store can carry more than MAX_CORRECTION_KEYWORDS terms from an older
26
+ * build. Freeing exactly one slot per ADD then replaced one learned term with
27
+ * another forever — the count never moved (372 → 372). Clearing the whole
28
+ * backlog in one shot would instead bulk-delete learned evidence on no
29
+ * per-term grounds. So every successful ADD beyond the cap additionally evicts
30
+ * up to this many least-valuable `llm` terms, each through the same tier-ranked
31
+ * ordering and audit path as the normal single eviction. seed/user terms never
32
+ * participate, and a store with no evictable term still refuses to grow.
33
+ */
34
+ const MAX_EVICTIONS_PER_ADD = 5;
35
+ /**
36
+ * EP-07 / ERR-092: the store is per-stateDir, so the cache is a Map keyed by
37
+ * the resolved directory. A single-valued slot made one workspace's store
38
+ * flush into another workspace's file.
39
+ */
40
+ const _correctionCueCache = new Map();
41
+ function cacheKey(stateDir) {
42
+ return path.resolve(stateDir);
43
+ }
44
+ export function _resetCorrectionCueCache() {
45
+ _correctionCueCache.clear();
46
+ }
47
+ /**
48
+ * The one term-identity rule for this store. Detection compares lowercased
49
+ * substrings, so a learned term is the same term when it matches after
50
+ * trim + lowercase — writers and readers must not disagree (the observer
51
+ * echoes LLM text with surrounding whitespace).
52
+ */
53
+ function normalizeTerm(term) {
54
+ return term.trim().toLowerCase();
55
+ }
56
+ function indexOfTerm(keywords, term) {
57
+ const needle = normalizeTerm(term);
58
+ return keywords.findIndex((k) => normalizeTerm(k.term) === needle);
59
+ }
60
+ /** Lower tier = evicted first. See CorrectionCueLearner.evictLeastValuable(). */
61
+ function evictionTier(keyword) {
62
+ const tp = keyword.truePositiveCount ?? 0;
63
+ const fp = keyword.falsePositiveCount ?? 0;
64
+ if (tp > 0)
65
+ return 2;
66
+ if (fp > 0)
67
+ return 0;
68
+ return 1;
69
+ }
70
+ /**
71
+ * Validate the decision-bearing fields and rebuild the row (unknown extras are
72
+ * dropped). Lenient where nothing reads the field: a missing addedAt becomes ''
73
+ * (it only breaks an eviction tie-break) rather than costing a whole term.
74
+ */
75
+ function normalizeStoredKeyword(raw) {
76
+ if (typeof raw !== 'object' || raw === null)
77
+ return null;
78
+ const { term, weight, source, addedAt, truePositiveCount, falsePositiveCount, hitCount, lastHitAt } = raw;
79
+ if (typeof term !== 'string' || term.trim() === '')
80
+ return null;
81
+ // weight feeds precisionFor(): an out-of-range value would hand a term the
82
+ // high-certainty path, so the bound is part of the contract, not presentation.
83
+ if (typeof weight !== 'number' || !Number.isFinite(weight) || weight < 0 || weight > 1)
84
+ return null;
85
+ if (source !== 'seed' && source !== 'llm' && source !== 'user')
86
+ return null;
87
+ // Earned precision counts gate host-runtime's high-certainty path: a corrupt
88
+ // 3.1 or a negative must not be trusted (same stance as its strict reader).
89
+ const isCount = (value) => value === undefined ||
90
+ (typeof value === 'number' && Number.isSafeInteger(value) && value >= 0);
91
+ if (!isCount(truePositiveCount) || !isCount(falsePositiveCount))
92
+ return null;
93
+ const keyword = {
94
+ term,
95
+ weight,
96
+ source,
97
+ addedAt: typeof addedAt === 'string' ? addedAt : '',
98
+ };
99
+ if (typeof hitCount === 'number')
100
+ keyword.hitCount = hitCount;
101
+ if (typeof truePositiveCount === 'number')
102
+ keyword.truePositiveCount = truePositiveCount;
103
+ if (typeof falsePositiveCount === 'number')
104
+ keyword.falsePositiveCount = falsePositiveCount;
105
+ if (typeof lastHitAt === 'string')
106
+ keyword.lastHitAt = lastHitAt;
107
+ return keyword;
108
+ }
109
+ /** Bounded, safe one-line identity for a rejected row (rc-8). */
110
+ function previewRow(raw) {
111
+ if (typeof raw !== 'object' || raw === null)
112
+ return `<${typeof raw}>`;
113
+ const { term } = raw;
114
+ const label = typeof term === 'string' ? term.slice(0, 40) : `<${typeof term}>`;
115
+ return `"${label}"`;
116
+ }
117
+ /**
118
+ * Read-side guard for the persisted store (rc-1/rc-2). The file is written by
119
+ * this module but read back as untrusted JSON, and its weight/TP/FP values gate
120
+ * the earned-high precision path in host-runtime, so decision-bearing fields
121
+ * are validated per row — the same contract as governance-signal-admission's
122
+ * reader, not a weaker second schema beside it (EP-07).
123
+ */
124
+ function parseStoredKeywordStore(input) {
125
+ if (typeof input !== 'object' || input === null)
126
+ return null;
127
+ const { keywords: rawKeywords, version, lastOptimizedAt } = input;
128
+ if (!Array.isArray(rawKeywords))
129
+ return null;
130
+ const keywords = [];
131
+ const dropped = [];
132
+ for (const raw of rawKeywords) {
133
+ const keyword = normalizeStoredKeyword(raw);
134
+ if (keyword) {
135
+ keywords.push(keyword);
136
+ }
137
+ else {
138
+ dropped.push(previewRow(raw));
139
+ }
140
+ }
141
+ if (dropped.length > 0) {
142
+ // A row that fails the guard is already inert to detection — host-runtime
143
+ // refuses the same fields on its read — so dropping it aligns the two
144
+ // readers instead of discarding usable data. Names stay in the log because
145
+ // this is the only trace of what the store no longer holds.
146
+ console.warn(`[PD:CorrectionCue] ${KEYWORD_STORE_FILE}: ${dropped.length} unusable keyword row(s) ignored: ${dropped.slice(0, 3).join(' | ')}`);
147
+ }
148
+ // version/lastOptimizedAt are bookkeeping, not decisions: rejecting a store
149
+ // for a missing one would reset learned terms, so tolerate and re-stamp.
150
+ return {
151
+ keywords,
152
+ version: typeof version === 'number' && Number.isSafeInteger(version) && version >= 0 ? version : 1,
153
+ lastOptimizedAt: typeof lastOptimizedAt === 'string' ? lastOptimizedAt : new Date().toISOString(),
154
+ };
155
+ }
156
+ function createDefaultStore() {
157
+ const now = new Date().toISOString();
158
+ const keywords = CORRECTION_SEED_KEYWORDS.map((k) => ({
159
+ ...k,
160
+ source: 'seed',
161
+ addedAt: now,
162
+ }));
163
+ return { keywords, version: 1, lastOptimizedAt: now };
164
+ }
165
+ export function saveCorrectionKeywordStore(stateDir, store) {
166
+ const filePath = path.join(stateDir, KEYWORD_STORE_FILE);
167
+ fs.mkdirSync(stateDir, { recursive: true });
168
+ atomicWriteFileSync(filePath, JSON.stringify(store, null, 2));
169
+ _correctionCueCache.delete(cacheKey(stateDir));
170
+ }
171
+ export function loadCorrectionKeywordStore(stateDir) {
172
+ const key = cacheKey(stateDir);
173
+ const cached = _correctionCueCache.get(key);
174
+ if (cached)
175
+ return cached;
176
+ const filePath = path.join(stateDir, KEYWORD_STORE_FILE);
177
+ if (fs.existsSync(filePath)) {
178
+ try {
179
+ const raw = fs.readFileSync(filePath, 'utf-8');
180
+ const loaded = parseStoredKeywordStore(JSON.parse(raw));
181
+ if (loaded) {
182
+ _correctionCueCache.set(key, loaded);
183
+ return loaded;
184
+ }
185
+ console.warn(`[PD:CorrectionCue] ${KEYWORD_STORE_FILE} is not a valid store; replacing it with the seed store`);
186
+ }
187
+ catch (err) {
188
+ console.warn(`[PD:CorrectionCue] cannot parse ${KEYWORD_STORE_FILE} (${String(err)}); replacing it with the seed store`);
189
+ }
190
+ }
191
+ const defaultStore = createDefaultStore();
192
+ saveCorrectionKeywordStore(stateDir, defaultStore);
193
+ _correctionCueCache.set(key, defaultStore);
194
+ return defaultStore;
195
+ }
196
+ // EP-07: keyed by stateDir like the store cache — one process hosts several
197
+ // workspaces (getSignalCollectorHost does the same for its hosts).
198
+ const _instances = new Map();
199
+ export function _resetCorrectionCueLearnerInstance() {
200
+ _instances.clear();
201
+ }
202
+ export class CorrectionCueLearner {
203
+ store;
204
+ stateDir;
205
+ constructor(stateDir) {
206
+ this.stateDir = stateDir;
207
+ this.store = loadCorrectionKeywordStore(stateDir);
208
+ }
209
+ // PRI-812: CorrectionCueLearner.match() 与 recordHits() 已删除。
210
+ // match() 是 canonical detector(createSharedCorrectionKeywordStore →
211
+ // collectSync)之外的幽灵第二检测算法,生产调用者为 0;recordHits() 同样
212
+ // 无生产调用者,其维护的 hitCount 在观测面结构性恒 0。检测权威与 TP/FP
213
+ // 反馈(recordTruePositive / recordFalsePositive)保持不变。
214
+ recordTruePositive(term) {
215
+ const idx = indexOfTerm(this.store.keywords, term);
216
+ const keyword = idx < 0 ? undefined : this.store.keywords[idx];
217
+ if (!keyword)
218
+ return false;
219
+ this.store.keywords[idx] = {
220
+ ...keyword,
221
+ truePositiveCount: (keyword.truePositiveCount ?? 0) + 1,
222
+ };
223
+ this.flush();
224
+ return true;
225
+ }
226
+ recordFalsePositive(term) {
227
+ const idx = indexOfTerm(this.store.keywords, term);
228
+ const keyword = idx < 0 ? undefined : this.store.keywords[idx];
229
+ if (!keyword)
230
+ return false;
231
+ this.store.keywords[idx] = {
232
+ ...keyword,
233
+ falsePositiveCount: (keyword.falsePositiveCount ?? 0) + 1,
234
+ weight: Math.max(MIN_KEYWORD_WEIGHT, keyword.weight * 0.8),
235
+ lastHitAt: new Date().toISOString(),
236
+ };
237
+ this.flush();
238
+ return true;
239
+ }
240
+ /**
241
+ * Insert a term, keeping the store inside MAX_CORRECTION_KEYWORDS.
242
+ *
243
+ * At/over the cap the least valuable `llm` terms leave first (see
244
+ * evictionTier), because throwing instead froze the learning channel
245
+ * permanently once the store filled up. The store may already be OVERSIZED
246
+ * from an older build; in that case each ADD also evicts up to
247
+ * MAX_EVICTIONS_PER_ADD terms, so the count converges downwards instead of
248
+ * being replaced one-for-one forever.
249
+ *
250
+ * @returns the evicted terms (empty when the store had room).
251
+ * @throws when there are too few evictable learned terms to preserve the cap
252
+ * (at 200) or to reduce the count (above 200), without touching Owner
253
+ * seed/user authority. A failed ADD leaves the store unchanged.
254
+ */
255
+ add(keyword) {
256
+ const evicted = [];
257
+ const over = this.store.keywords.length - MAX_CORRECTION_KEYWORDS;
258
+ if (over >= 0) {
259
+ // over = 0 (exactly at cap) → free exactly one slot: the historical
260
+ // behaviour. over > 0 → also take a bounded convergence step.
261
+ const budget = Math.min(over + 1, MAX_EVICTIONS_PER_ADD);
262
+ // Above the cap, evicting only one learned term and inserting one new
263
+ // term cannot converge (e.g. 200 Owner terms + 1 llm: 201 -> 201).
264
+ // Preflight BEFORE any splice so a rejected ADD cannot destroy evidence.
265
+ // At exactly the cap, a one-for-one learned replacement is still valid.
266
+ const minimumToEvict = over > 0 ? 2 : 1;
267
+ const available = this.store.keywords.filter(k => k.source === 'llm').length;
268
+ if (available < minimumToEvict) {
269
+ throw new Error(`Correction keyword store limit reached (${MAX_CORRECTION_KEYWORDS} terms): only ${available} learned term(s) are evictable, need ${minimumToEvict} to ${over > 0 ? 'converge' : 'add'} without touching Owner terms`);
270
+ }
271
+ evicted.push(...this.evictLeastValuable(budget));
272
+ if (evicted.length === 0) {
273
+ throw new Error(`Correction keyword store limit reached (${MAX_CORRECTION_KEYWORDS} terms) and no learned term is evictable`);
274
+ }
275
+ }
276
+ const entry = {
277
+ ...keyword,
278
+ addedAt: new Date().toISOString(),
279
+ };
280
+ this.store.keywords.push(entry);
281
+ this.flush();
282
+ return evicted;
283
+ }
284
+ /**
285
+ * Rank learned terms by what the store itself proves about them, worst first:
286
+ * proven noise (FP without any TP) leaves before never-confirmed terms, which
287
+ * leave before confirmed-useful ones. Within a tier, low weight then old
288
+ * addition loses. seed/user entries are Owner authority and never compete.
289
+ *
290
+ * @param count maximum number of terms to evict (bounded by the caller).
291
+ * @returns evicted terms in eviction order (fewer than `count` when the store
292
+ * holds fewer learned terms).
293
+ */
294
+ evictLeastValuable(count) {
295
+ const evicted = [];
296
+ for (let i = 0; i < count; i++) {
297
+ const candidates = [];
298
+ this.store.keywords.forEach((keyword, index) => {
299
+ if (keyword.source === 'llm')
300
+ candidates.push({ keyword, index });
301
+ });
302
+ if (candidates.length === 0)
303
+ break;
304
+ candidates.sort((a, b) => evictionTier(a.keyword) - evictionTier(b.keyword)
305
+ || a.keyword.weight - b.keyword.weight
306
+ || a.keyword.addedAt.localeCompare(b.keyword.addedAt));
307
+ const [loser] = candidates;
308
+ if (!loser)
309
+ break;
310
+ this.store.keywords.splice(loser.index, 1);
311
+ evicted.push(loser.keyword.term);
312
+ }
313
+ return evicted;
314
+ }
315
+ /** @returns false when the term is not in the store (caller logs the skip). */
316
+ updateWeight(term, weight) {
317
+ const idx = indexOfTerm(this.store.keywords, term);
318
+ const keyword = idx < 0 ? undefined : this.store.keywords[idx];
319
+ if (!keyword)
320
+ return false;
321
+ this.store.keywords[idx] = {
322
+ ...keyword,
323
+ weight: Math.max(MIN_KEYWORD_WEIGHT, Math.min(MAX_KEYWORD_WEIGHT, weight)),
324
+ };
325
+ this.flush();
326
+ return true;
327
+ }
328
+ /** @returns false when the term is not in the store (caller logs the skip). */
329
+ remove(term) {
330
+ const idx = indexOfTerm(this.store.keywords, term);
331
+ if (idx < 0)
332
+ return false;
333
+ this.store.keywords.splice(idx, 1);
334
+ this.flush();
335
+ return true;
336
+ }
337
+ /** Look a term up with the store's own identity rule (trim + lowercase). */
338
+ find(term) {
339
+ const idx = indexOfTerm(this.store.keywords, term);
340
+ return idx < 0 ? undefined : this.store.keywords[idx];
341
+ }
342
+ getStore() {
343
+ return this.store;
344
+ }
345
+ getLastOptimizedAt() {
346
+ return this.store.lastOptimizedAt;
347
+ }
348
+ /**
349
+ * The store's only durable write: an atomic temp-file-then-rename of
350
+ * correction_keywords.json (T-38-02). A successful flush — not a SYSTEM log
351
+ * line — is what makes a mutation real; the audit trail emitted by
352
+ * KeywordOptimizationService is best-effort and may be missing.
353
+ */
354
+ flush() {
355
+ saveCorrectionKeywordStore(this.stateDir, this.store);
356
+ }
357
+ static get(stateDir) {
358
+ const key = cacheKey(stateDir);
359
+ let instance = _instances.get(key);
360
+ if (!instance) {
361
+ instance = new CorrectionCueLearner(stateDir);
362
+ _instances.set(key, instance);
363
+ }
364
+ return instance;
365
+ }
366
+ }
@@ -0,0 +1,21 @@
1
+ import { type PluginConfigLoadResult } from './pd-config.js';
2
+ export type ObserverReadiness = 'disabled' | 'needs_setup' | 'ready' | 'not_ready' | 'config_malformed';
3
+ export interface ObserverConfigResult {
4
+ enabled: boolean;
5
+ readiness: ObserverReadiness;
6
+ source: string;
7
+ reason: string;
8
+ nextAction: string;
9
+ runtimeProfileId: string | null;
10
+ runtimeProfileType: string | null;
11
+ apiKeyEnv: string | null;
12
+ apiKeyPresent: boolean;
13
+ provider: string | null;
14
+ model: string | null;
15
+ timeoutMs: number | null;
16
+ /** PRI-788 G3: profile 的 maxTokens(思考型本地模型需要显式大 token 预算) */
17
+ maxTokens: number | null;
18
+ baseUrl: string | null;
19
+ configErrors?: PluginConfigLoadResult['errors'];
20
+ }
21
+ export declare function resolveObserverConfig(workspaceDir: string, observerFlagId: string, observerAgentName: string): ObserverConfigResult;
@@ -0,0 +1,55 @@
1
+ import { INTERNAL_AGENT_NAMES, } from '@principles/core/runtime';
2
+ import { loadPdConfigForPlugin, } from './pd-config.js';
3
+ function base(result) {
4
+ return { source: result.source };
5
+ }
6
+ function emptyRuntime() {
7
+ return { runtimeProfileId: null, runtimeProfileType: null, apiKeyEnv: null, apiKeyPresent: false, provider: null, model: null, timeoutMs: null, maxTokens: null, baseUrl: null };
8
+ }
9
+ function isInternalAgentName(value) {
10
+ return INTERNAL_AGENT_NAMES.some((name) => name === value);
11
+ }
12
+ export function resolveObserverConfig(workspaceDir, observerFlagId, observerAgentName) {
13
+ const result = loadPdConfigForPlugin(workspaceDir);
14
+ if (!result.ok) {
15
+ return {
16
+ enabled: false, readiness: 'config_malformed', ...base(result), ...emptyRuntime(),
17
+ reason: `Config validation failed: ${result.errors.map((error) => error.reason).join('; ')}`,
18
+ nextAction: result.errors[0]?.nextAction ?? 'Fix .pd/config.yaml and retry', configErrors: result.errors,
19
+ };
20
+ }
21
+ const { config } = result.effective;
22
+ const feature = config.features[observerFlagId];
23
+ if (!feature?.enabled) {
24
+ // PRI-1063 (review fix): flow mapping, single line. Feature ids are flat
25
+ // keys inside the EXISTING `features:` block — a standalone block would
26
+ // duplicate that key and fail YAML parsing.
27
+ return { enabled: false, readiness: 'disabled', ...base(result), ...emptyRuntime(), reason: `${observerFlagId} is disabled in .pd/config.yaml`, nextAction: `Enable it in .pd/config.yaml — in the existing "features:" block set ${observerFlagId}: {enabled: true} (one flat key, not nested)` };
28
+ }
29
+ if (!isInternalAgentName(observerAgentName)) {
30
+ return { enabled: false, readiness: 'needs_setup', ...base(result), ...emptyRuntime(), reason: `Unknown agent name '${observerAgentName}'`, nextAction: `Use one of the known agent names: ${INTERNAL_AGENT_NAMES.join(', ')}` };
31
+ }
32
+ const agent = config.internalAgents.agents[observerAgentName];
33
+ if (!agent?.enabled) {
34
+ // PRI-1063 (review fix): internalAgents IS a genuinely nested path, so it
35
+ // is described as one; the feature id is flat. Both stay single-line.
36
+ return { enabled: false, readiness: 'disabled', ...base(result), ...emptyRuntime(), reason: `${observerFlagId} feature flag is enabled but internalAgents.agents.${observerAgentName}.enabled is false`, nextAction: `Enable the agent in .pd/config.yaml — this path IS nested: internalAgents > agents > ${observerAgentName} > enabled: true; or disable the flag instead (flat key): in the existing "features:" block set ${observerFlagId}: {enabled: false}` };
37
+ }
38
+ const runtimeProfileId = agent.runtimeProfile ?? config.internalAgents.defaultRuntime;
39
+ const profile = config.runtimeProfiles[runtimeProfileId];
40
+ if (!profile) {
41
+ return { enabled: true, readiness: 'needs_setup', ...base(result), ...emptyRuntime(), runtimeProfileId, reason: `Runtime profile '${runtimeProfileId}' not found in .pd/config.yaml`, nextAction: `Add runtime profile '${runtimeProfileId}' to .pd/config.yaml runtimeProfiles` };
42
+ }
43
+ if (profile.type !== 'pi-ai') {
44
+ return { enabled: true, readiness: 'needs_setup', ...base(result), ...emptyRuntime(), runtimeProfileId, runtimeProfileType: profile.type, provider: profile.provider ?? null, model: profile.model ?? null, reason: `Runtime profile '${runtimeProfileId}' has retired type '${profile.type}' (ADR-0029: pi-ai only). Observers require a pi-ai profile with an API key.`, nextAction: `Configure a pi-ai runtime profile for ${observerAgentName} in .pd/config.yaml (e.g., add a pi-ai profile with provider, model, and apiKeyEnv)` };
45
+ }
46
+ const apiKeyEnv = profile.apiKeyEnv ?? null;
47
+ if (!apiKeyEnv) {
48
+ return { enabled: true, readiness: 'needs_setup', ...base(result), ...emptyRuntime(), runtimeProfileId, runtimeProfileType: profile.type, provider: profile.provider ?? null, model: profile.model ?? null, timeoutMs: profile.timeoutMs ?? null, maxTokens: profile.maxTokens ?? null, baseUrl: profile.baseUrl ?? null, reason: `pi-ai profile '${runtimeProfileId}' missing apiKeyEnv`, nextAction: `Add apiKeyEnv to runtime profile '${runtimeProfileId}' in .pd/config.yaml` };
49
+ }
50
+ const apiKeyPresent = Object.hasOwn(process.env, apiKeyEnv) && Boolean(process.env[apiKeyEnv]);
51
+ if (!apiKeyPresent) {
52
+ return { enabled: true, readiness: 'needs_setup', ...base(result), runtimeProfileId, runtimeProfileType: profile.type, apiKeyEnv, apiKeyPresent: false, provider: profile.provider ?? null, model: profile.model ?? null, timeoutMs: profile.timeoutMs ?? null, maxTokens: profile.maxTokens ?? null, baseUrl: profile.baseUrl ?? null, reason: `Environment variable '${apiKeyEnv}' is not set or empty`, nextAction: `Set the environment variable '${apiKeyEnv}' with a valid API key` };
53
+ }
54
+ return { enabled: true, readiness: 'not_ready', ...base(result), runtimeProfileId, runtimeProfileType: profile.type, apiKeyEnv, apiKeyPresent: true, provider: profile.provider ?? null, model: profile.model ?? null, timeoutMs: profile.timeoutMs ?? null, maxTokens: profile.maxTokens ?? null, baseUrl: profile.baseUrl ?? null, reason: `pi-ai profile configured with apiKeyEnv='${apiKeyEnv}' (key present); runtime availability unknown`, nextAction: 'Run pd runtime probe to verify end-to-end connectivity' };
55
+ }
@@ -0,0 +1,33 @@
1
+ import { CorrectionObserver } from '@principles/core/runtime';
2
+ import { resolveObserverConfig } from './correction-observer-config.js';
3
+ import { type CorrectionObserverLogger, type KeywordOptimizationPorts } from './keyword-optimization-service.js';
4
+ import { type CorrectionObserverHostKind, type SignalHealthWriteError } from './signal-health.js';
5
+ /**
6
+ * PRI-307: Resolve CorrectionObserver from .pd/config.yaml.
7
+ *
8
+ * States:
9
+ * - disabled: feature flag off → return null, no noisy logs
10
+ * - needs_setup: enabled but missing API key or profile → return null with structured reason
11
+ * - ready/not_ready: enabled and configured → return observer instance
12
+ */
13
+ export declare function resolveCorrectionObserver(workspaceDir: string, logger?: CorrectionObserverLogger, resolveConfig?: typeof resolveObserverConfig): CorrectionObserver | null;
14
+ export interface CorrectionObserverCycleInput extends KeywordOptimizationPorts {
15
+ workspaceDir: string;
16
+ stateDir: string;
17
+ /** Identity for the input snapshot; independent from the shared workspace cooldown. */
18
+ hostKind?: CorrectionObserverHostKind;
19
+ /** New evidence from a host-owned confirmation queue bypasses the no-new-turn gate. */
20
+ confirmedCount?: number;
21
+ /** Stop/restart invalidates writes after the model await. */
22
+ isStale?: () => boolean;
23
+ onHealthWriteError?: SignalHealthWriteError;
24
+ minIntervalMs?: number;
25
+ now?: () => Date;
26
+ /** Optional bound on model dispatch. Omit to preserve OpenClaw's profile-only budget. */
27
+ timeoutMs?: number;
28
+ onCycleError?: (message: string) => void;
29
+ /** Same shared loader by default; adapters may supply their config-resolution facade. */
30
+ resolveConfig?: typeof resolveObserverConfig;
31
+ }
32
+ /** Run one optimization cycle. Hosts own scheduling and any confirmation queue. */
33
+ export declare function runCorrectionObserverOptimizationCycle(input: CorrectionObserverCycleInput): Promise<void>;