@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.
- package/dist/atomic-write-file.d.ts +1 -0
- package/dist/atomic-write-file.js +100 -0
- package/dist/correction-cue-learner.d.ts +69 -0
- package/dist/correction-cue-learner.js +366 -0
- package/dist/correction-observer-config.d.ts +21 -0
- package/dist/correction-observer-config.js +55 -0
- package/dist/correction-observer-cycle.d.ts +33 -0
- package/dist/correction-observer-cycle.js +255 -0
- package/dist/correction-trajectory-reader.d.ts +35 -0
- package/dist/correction-trajectory-reader.js +113 -0
- package/dist/index.d.ts +6 -0
- package/dist/index.js +7 -0
- package/dist/internalization-consumer-cycle.js +1 -1
- package/dist/keyword-optimization-service.d.ts +73 -0
- package/dist/keyword-optimization-service.js +265 -0
- package/dist/pain-inbox.d.ts +28 -0
- package/dist/pain-inbox.js +194 -46
- package/dist/signal-health.d.ts +54 -0
- package/dist/signal-health.js +194 -0
- package/dist/workspace-pipeline-host-deps.d.ts +2 -0
- package/dist/workspace-pipeline-host-deps.js +1 -1
- package/package.json +7 -3
|
@@ -0,0 +1,255 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
import { PiAiRuntimeAdapter, CorrectionObserver, AgentScheduler } from '@principles/core/runtime';
|
|
3
|
+
import { CorrectionCueLearner } from './correction-cue-learner.js';
|
|
4
|
+
import { resolveObserverConfig } from './correction-observer-config.js';
|
|
5
|
+
import { openCorrectionTrajectory } from './correction-trajectory-reader.js';
|
|
6
|
+
import { KeywordOptimizationService, } from './keyword-optimization-service.js';
|
|
7
|
+
import { readSignalHealth, updateSignalHealth } from './signal-health.js';
|
|
8
|
+
const CORRECTION_OBSERVER_MAX_RECENT_SESSIONS = 20;
|
|
9
|
+
// PRI-823: aligned with buildTrajectoryHistory's 10-session window — the FP
|
|
10
|
+
// counter-evidence surface (recentMessages excerpts) must cover the same
|
|
11
|
+
// sessions the correction-hit history (trajectoryHistory) reports on,
|
|
12
|
+
// otherwise hits outside the text window are unjudgeable for the observer.
|
|
13
|
+
const CORRECTION_OBSERVER_MAX_PAYLOAD_SESSIONS = 10;
|
|
14
|
+
/**
|
|
15
|
+
* payload 体积上限:recentMessages 是"反证素材",不是全量审计。观测到的真实
|
|
16
|
+
* 语料里 10 个会话可拼出 25KB(最坏 48KB)的 user 回合正文;这些文本全部塞进
|
|
17
|
+
* prompt 只换来更强的上下文,代价是每次调用都变慢。封顶保留最近的 40 条,每条
|
|
18
|
+
* 截断到 400 字符(足够判断是否同一主题)。
|
|
19
|
+
*/
|
|
20
|
+
const CORRECTION_OBSERVER_MAX_PAYLOAD_MESSAGES = 40;
|
|
21
|
+
const CORRECTION_OBSERVER_MAX_MESSAGE_CHARS = 400;
|
|
22
|
+
/**
|
|
23
|
+
* PRI-307: Resolve CorrectionObserver from .pd/config.yaml.
|
|
24
|
+
*
|
|
25
|
+
* States:
|
|
26
|
+
* - disabled: feature flag off → return null, no noisy logs
|
|
27
|
+
* - needs_setup: enabled but missing API key or profile → return null with structured reason
|
|
28
|
+
* - ready/not_ready: enabled and configured → return observer instance
|
|
29
|
+
*/
|
|
30
|
+
export function resolveCorrectionObserver(workspaceDir, logger, resolveConfig = resolveObserverConfig) {
|
|
31
|
+
try {
|
|
32
|
+
const observerConfig = resolveConfig(workspaceDir, 'correction_observer', 'correctionObserver');
|
|
33
|
+
if (!observerConfig.enabled) {
|
|
34
|
+
if (observerConfig.readiness === 'config_malformed') {
|
|
35
|
+
logger?.warn?.(`[PD:CorrectionObserver] Config malformed: ${observerConfig.reason}. ${observerConfig.nextAction}`);
|
|
36
|
+
}
|
|
37
|
+
else {
|
|
38
|
+
logger?.debug?.(`[PD:CorrectionObserver] ${observerConfig.reason}`);
|
|
39
|
+
}
|
|
40
|
+
return null;
|
|
41
|
+
}
|
|
42
|
+
if (observerConfig.readiness === 'needs_setup') {
|
|
43
|
+
logger?.info?.(`[PD:CorrectionObserver] ${observerConfig.reason}. ${observerConfig.nextAction}`);
|
|
44
|
+
return null;
|
|
45
|
+
}
|
|
46
|
+
// ADR-0029: pi-ai is the only internal-agent backend. The loader already
|
|
47
|
+
// reports needs_setup for a retired profile; fail closed here too so no
|
|
48
|
+
// future loader change can silently route an observer through anything else.
|
|
49
|
+
if (observerConfig.runtimeProfileType !== 'pi-ai') {
|
|
50
|
+
logger?.warn?.(`[PD:CorrectionObserver] Runtime profile type '${String(observerConfig.runtimeProfileType)}' is not supported (ADR-0029: pi-ai only). Skipping.`);
|
|
51
|
+
return null;
|
|
52
|
+
}
|
|
53
|
+
const adapter = new PiAiRuntimeAdapter({
|
|
54
|
+
provider: observerConfig.provider ?? 'anthropic',
|
|
55
|
+
model: observerConfig.model ?? 'anthropic/claude-3-5-sonnet',
|
|
56
|
+
apiKeyEnv: observerConfig.apiKeyEnv ?? 'ANTHROPIC_API_KEY',
|
|
57
|
+
timeoutMs: observerConfig.timeoutMs ?? undefined,
|
|
58
|
+
// PRI-788 G3: profile 的 maxTokens 透传(思考型本地模型小 token 预算会返回空)
|
|
59
|
+
maxTokens: observerConfig.maxTokens ?? undefined,
|
|
60
|
+
baseUrl: observerConfig.baseUrl ?? undefined,
|
|
61
|
+
workspace: workspaceDir,
|
|
62
|
+
});
|
|
63
|
+
return new CorrectionObserver({ runtimeAdapter: adapter }, { timeoutMs: observerConfig.timeoutMs ?? undefined });
|
|
64
|
+
}
|
|
65
|
+
catch {
|
|
66
|
+
logger?.warn?.('[PD:CorrectionObserver] Failed to resolve CorrectionObserver: configuration_error');
|
|
67
|
+
return null;
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
/** Store the cooldown clock and host-specific consumed input atomically. */
|
|
71
|
+
function recordObserverCycleSuccess(input, digest) {
|
|
72
|
+
updateSignalHealth(input.stateDir, (state) => {
|
|
73
|
+
state.observerLastSuccessAt = (input.now?.() ?? new Date()).toISOString();
|
|
74
|
+
state.observerInputDigests = { ...state.observerInputDigests, [input.hostKind ?? 'openclaw']: digest };
|
|
75
|
+
state.observerConsecutiveFailures = 0;
|
|
76
|
+
}, input.onHealthWriteError);
|
|
77
|
+
}
|
|
78
|
+
class CorrectionObserverDispatchTimeout extends Error {
|
|
79
|
+
}
|
|
80
|
+
/** Real adapter timeout uses the same cap as this tail's independent deadline.
|
|
81
|
+
* A late resolution is observed by Promise.race but cannot commit any state. */
|
|
82
|
+
async function withDispatchDeadline(operation, timeoutMs) {
|
|
83
|
+
if (timeoutMs === undefined)
|
|
84
|
+
return operation();
|
|
85
|
+
let timer;
|
|
86
|
+
try {
|
|
87
|
+
const deadline = new Promise((_resolve, reject) => {
|
|
88
|
+
timer = setTimeout(() => reject(new CorrectionObserverDispatchTimeout()), timeoutMs);
|
|
89
|
+
});
|
|
90
|
+
return await Promise.race([operation(), deadline]);
|
|
91
|
+
}
|
|
92
|
+
finally {
|
|
93
|
+
clearTimeout(timer);
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
/** Run one optimization cycle. Hosts own scheduling and any confirmation queue. */
|
|
97
|
+
export async function runCorrectionObserverOptimizationCycle(input) {
|
|
98
|
+
const { workspaceDir, stateDir, logger, confirmedCount = 0, isStale, minIntervalMs = 0 } = input;
|
|
99
|
+
if (isStale?.())
|
|
100
|
+
return;
|
|
101
|
+
const openTrajectory = input.openTrajectory ?? (() => openCorrectionTrajectory(workspaceDir));
|
|
102
|
+
let isSourceAuthorized;
|
|
103
|
+
// Stable, safe diagnostic categories; never stringify exception messages.
|
|
104
|
+
let phase = 'configuration_error';
|
|
105
|
+
try {
|
|
106
|
+
if (minIntervalMs > 0 && confirmedCount === 0) {
|
|
107
|
+
const last = readSignalHealth(stateDir)?.observerLastSuccessAt;
|
|
108
|
+
const elapsed = last ? (input.now?.() ?? new Date()).getTime() - Date.parse(last) : NaN;
|
|
109
|
+
if (elapsed >= 0 && elapsed < minIntervalMs)
|
|
110
|
+
return;
|
|
111
|
+
}
|
|
112
|
+
const timeoutMs = input.timeoutMs !== undefined && Number.isFinite(input.timeoutMs) && input.timeoutMs > 0
|
|
113
|
+
? Math.max(1, Math.min(Math.trunc(input.timeoutMs), 2_147_483_647))
|
|
114
|
+
: undefined;
|
|
115
|
+
const resolveConfig = input.resolveConfig ?? resolveObserverConfig;
|
|
116
|
+
const observer = resolveCorrectionObserver(workspaceDir, logger, timeoutMs === undefined ? resolveConfig : (...args) => {
|
|
117
|
+
const config = resolveConfig(...args);
|
|
118
|
+
return { ...config, timeoutMs: Math.min(config.timeoutMs ?? timeoutMs, timeoutMs) };
|
|
119
|
+
});
|
|
120
|
+
if (!observer) {
|
|
121
|
+
// PRI-307: No noisy "no API key" cycling. Only log at debug level.
|
|
122
|
+
logger?.debug?.(`[PD:CorrectionObserver] Observer not resolved. Skipping cycle.`);
|
|
123
|
+
return;
|
|
124
|
+
}
|
|
125
|
+
logger?.info?.('[PD:CorrectionObserver] Observer resolved. Initiating periodic optimization...');
|
|
126
|
+
phase = 'trajectory_read_failed';
|
|
127
|
+
let recentSessionIds;
|
|
128
|
+
const recentTurns = [];
|
|
129
|
+
const db = openTrajectory();
|
|
130
|
+
const governanceSource = db.sourceKind === 'governance-observations';
|
|
131
|
+
isSourceAuthorized = db.isSourceAuthorized?.bind(db);
|
|
132
|
+
try {
|
|
133
|
+
const recentSessions = db.listRecentSessions({ limit: CORRECTION_OBSERVER_MAX_RECENT_SESSIONS });
|
|
134
|
+
recentSessionIds = recentSessions.map(s => s.sessionId);
|
|
135
|
+
if (recentSessionIds.length === 0) {
|
|
136
|
+
logger?.info?.('[PD:CorrectionObserver] No recent sessions found. Skipping correction optimization.');
|
|
137
|
+
return;
|
|
138
|
+
}
|
|
139
|
+
for (const sId of recentSessionIds.slice(0, CORRECTION_OBSERVER_MAX_PAYLOAD_SESSIONS)) {
|
|
140
|
+
try {
|
|
141
|
+
const turns = db.listUserTurnsForSession(sId);
|
|
142
|
+
for (const t of turns) {
|
|
143
|
+
if (t.rawExcerpt) {
|
|
144
|
+
recentTurns.push({
|
|
145
|
+
sessionId: sId,
|
|
146
|
+
observedAt: t.createdAt,
|
|
147
|
+
excerpt: t.rawExcerpt.length > CORRECTION_OBSERVER_MAX_MESSAGE_CHARS
|
|
148
|
+
? `${t.rawExcerpt.slice(0, CORRECTION_OBSERVER_MAX_MESSAGE_CHARS)}…`
|
|
149
|
+
: t.rawExcerpt,
|
|
150
|
+
});
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
catch (turnErr) {
|
|
155
|
+
// A partial authorized window is not evidence of silence.
|
|
156
|
+
// OpenClaw keeps its existing per-session tolerance.
|
|
157
|
+
if (governanceSource)
|
|
158
|
+
throw turnErr;
|
|
159
|
+
logger?.warn?.('[PD:CorrectionObserver] Failed to load user turns: trajectory_read_failed');
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
if (recentTurns.length > CORRECTION_OBSERVER_MAX_PAYLOAD_MESSAGES) {
|
|
163
|
+
recentTurns.splice(0, recentTurns.length - CORRECTION_OBSERVER_MAX_PAYLOAD_MESSAGES);
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
finally {
|
|
167
|
+
db.close?.();
|
|
168
|
+
}
|
|
169
|
+
const recentMessages = recentTurns.map((turn) => turn.excerpt);
|
|
170
|
+
// A retention sweep can remove the rows between the session list and
|
|
171
|
+
// the per-session read. Do not send a governed store-only prompt.
|
|
172
|
+
if (isSourceAuthorized !== undefined && (!isSourceAuthorized() || recentMessages.length === 0))
|
|
173
|
+
return;
|
|
174
|
+
phase = 'keyword_store_failed';
|
|
175
|
+
const learner = CorrectionCueLearner.get(stateDir);
|
|
176
|
+
const { keywords } = learner.getStore();
|
|
177
|
+
// PRI-812: hitCount 不再投影——recordHits 已删除(死写者),该字段在
|
|
178
|
+
// payload 里结构性恒 0,只会喂养 prompt 里失真的 REMOVE 判据。
|
|
179
|
+
const keywordStoreSummary = {
|
|
180
|
+
totalKeywords: keywords.length,
|
|
181
|
+
terms: keywords.map(k => ({
|
|
182
|
+
term: k.term,
|
|
183
|
+
weight: k.weight,
|
|
184
|
+
truePositiveCount: k.truePositiveCount ?? 0,
|
|
185
|
+
falsePositiveCount: k.falsePositiveCount ?? 0,
|
|
186
|
+
})),
|
|
187
|
+
};
|
|
188
|
+
const ports = { logger, openTrajectory, audit: input.audit };
|
|
189
|
+
// A singleton captures its reader. Sharing a captured Codex reader
|
|
190
|
+
// with WorkBuddy in the same process would defeat exact-host consent.
|
|
191
|
+
const optimizationService = governanceSource
|
|
192
|
+
? new KeywordOptimizationService(stateDir, workspaceDir, ports)
|
|
193
|
+
: KeywordOptimizationService.get(stateDir, workspaceDir, ports);
|
|
194
|
+
phase = 'trajectory_read_failed';
|
|
195
|
+
const trajectoryHistory = await optimizationService.buildTrajectoryHistory(recentSessionIds);
|
|
196
|
+
// Use the actual bounded input, not a completion time. This includes
|
|
197
|
+
// rows arriving during dispatch and late/same-timestamp backfills on
|
|
198
|
+
// the next cycle, but never repeats a successful unchanged snapshot.
|
|
199
|
+
const digest = createHash('sha256').update(JSON.stringify([recentTurns, trajectoryHistory])).digest('hex');
|
|
200
|
+
if (confirmedCount === 0 && readSignalHealth(stateDir)?.observerInputDigests?.[input.hostKind ?? 'openclaw'] === digest) {
|
|
201
|
+
logger?.debug?.('[PD:CorrectionObserver] No new turns: input snapshot unchanged.');
|
|
202
|
+
return;
|
|
203
|
+
}
|
|
204
|
+
const payload = {
|
|
205
|
+
parentSessionId: 'correction-observer-service',
|
|
206
|
+
workspaceDir,
|
|
207
|
+
keywordStoreSummary,
|
|
208
|
+
recentMessages,
|
|
209
|
+
trajectoryHistory,
|
|
210
|
+
};
|
|
211
|
+
const scheduler = new AgentScheduler();
|
|
212
|
+
scheduler.register({
|
|
213
|
+
agentId: 'correction-observer',
|
|
214
|
+
mode: 'realtime',
|
|
215
|
+
runner: observer,
|
|
216
|
+
});
|
|
217
|
+
logger?.info?.(`[PD:CorrectionObserver] Dispatching with ${trajectoryHistory.length} trajectory events, ${recentMessages.length} recent messages.`);
|
|
218
|
+
if (isSourceAuthorized?.() === false)
|
|
219
|
+
return;
|
|
220
|
+
phase = 'model_dispatch_failed';
|
|
221
|
+
const result = await withDispatchDeadline(() => scheduler.dispatch('correction-observer', payload), timeoutMs);
|
|
222
|
+
if (isSourceAuthorized?.() === false)
|
|
223
|
+
return;
|
|
224
|
+
// A model summary can quote Owner text. Only report the outcome flag.
|
|
225
|
+
logger?.info?.(`[PD:CorrectionObserver] Completed: updated=${result.updated}`);
|
|
226
|
+
// dispatch 期间可能被 stop/重启 ⇒ 不再写 keyword store / 健康度。
|
|
227
|
+
if (isStale?.() || isSourceAuthorized?.() === false)
|
|
228
|
+
return;
|
|
229
|
+
// PRI-812: 无条件投递——FP-only 裁决(updated=false 但 fpTerms 非空)
|
|
230
|
+
// 是 earned-high 降级闭环的唯一自动反证来源,applyResult 内部把
|
|
231
|
+
// store mutations 与 FP 记录分开处理,空结果只记 info 不产生变更。
|
|
232
|
+
// A governed reader does not supply attested correction hits. A
|
|
233
|
+
// hallucinated FP verdict must not demote one of the shared terms.
|
|
234
|
+
// Preserve OpenClaw's existing FP-only feedback path.
|
|
235
|
+
const verdict = governanceSource && trajectoryHistory.length === 0
|
|
236
|
+
? { ...result, fpTerms: [], fpAnalysisStatus: 'skipped' }
|
|
237
|
+
: result;
|
|
238
|
+
phase = 'keyword_store_failed';
|
|
239
|
+
optimizationService.applyResult(verdict);
|
|
240
|
+
recordObserverCycleSuccess(input, digest);
|
|
241
|
+
}
|
|
242
|
+
catch (err) {
|
|
243
|
+
if (isSourceAuthorized?.() === false)
|
|
244
|
+
return;
|
|
245
|
+
const category = err instanceof CorrectionObserverDispatchTimeout ? 'model_timeout' : phase;
|
|
246
|
+
const errMsg = `Correction observer cycle failed: ${category}`;
|
|
247
|
+
logger?.warn?.(`[PD:CorrectionObserver] ${errMsg}`);
|
|
248
|
+
input.onCycleError?.(errMsg);
|
|
249
|
+
// PRI-788 G4: 失败计数上浮到健康产物(doctor 呈现 degraded)。
|
|
250
|
+
// 若本轮已因 stop/重启失效,则不再把失败记到新一代的计数上。
|
|
251
|
+
if (!isStale?.()) {
|
|
252
|
+
updateSignalHealth(stateDir, (state) => { state.observerConsecutiveFailures += 1; }, input.onHealthWriteError);
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
}
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import { type SourceMaterialAuthorizationPort } from './source-material-authorization.js';
|
|
2
|
+
export interface CorrectionTrajectoryReader {
|
|
3
|
+
/** Governance turn rows do not carry attested OpenClaw correction hits. */
|
|
4
|
+
sourceKind?: 'governance-observations';
|
|
5
|
+
listRecentSessions(options: {
|
|
6
|
+
limit: number;
|
|
7
|
+
}): readonly {
|
|
8
|
+
sessionId: string;
|
|
9
|
+
updatedAt: string;
|
|
10
|
+
}[];
|
|
11
|
+
listUserTurnsForSession(sessionId: string): readonly {
|
|
12
|
+
rawExcerpt: string;
|
|
13
|
+
correctionDetected: boolean;
|
|
14
|
+
correctionCue: string | null;
|
|
15
|
+
createdAt: string;
|
|
16
|
+
}[];
|
|
17
|
+
/** Optional live authorization gate; the cycle also checks it on both sides of dispatch. */
|
|
18
|
+
isSourceAuthorized?(): boolean;
|
|
19
|
+
/** Omit for a connection owned by the calling host. */
|
|
20
|
+
close?(): void;
|
|
21
|
+
}
|
|
22
|
+
/**
|
|
23
|
+
* Default observer source for the canonical shared trajectory.db. Keep the
|
|
24
|
+
* existing excerpts and correction flags (not full text or blobs). Read-only:
|
|
25
|
+
* opening a missing database is an error, never an initialization or migration.
|
|
26
|
+
*/
|
|
27
|
+
export declare function openCorrectionTrajectory(workspaceDir: string): CorrectionTrajectoryReader;
|
|
28
|
+
export interface GovernanceCorrectionTrajectoryInput {
|
|
29
|
+
workspaceDir: string;
|
|
30
|
+
hostKind: 'codex' | 'workbuddy';
|
|
31
|
+
sourceMaterialAuthorization?: SourceMaterialAuthorizationPort;
|
|
32
|
+
}
|
|
33
|
+
/** Exact-host, exact-rollout reads. Every call checks current consent BEFORE
|
|
34
|
+
* opening SQLite; no fallback to the plugin tables or a parent rollout. */
|
|
35
|
+
export declare function openGovernanceCorrectionTrajectory(input: GovernanceCorrectionTrajectoryInput): CorrectionTrajectoryReader;
|
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import Database from 'better-sqlite3';
|
|
3
|
+
import { resolveTrajectoryDbPath } from '@principles/core/runtime/storage-paths';
|
|
4
|
+
import { createConsentLedgerSourceMaterialAuthorization, } from './source-material-authorization.js';
|
|
5
|
+
import { openTrajectoryDbReadonly } from '@principles/core/trajectory-store';
|
|
6
|
+
/**
|
|
7
|
+
* Default observer source for the canonical shared trajectory.db. Keep the
|
|
8
|
+
* existing excerpts and correction flags (not full text or blobs). Read-only:
|
|
9
|
+
* opening a missing database is an error, never an initialization or migration.
|
|
10
|
+
*/
|
|
11
|
+
export function openCorrectionTrajectory(workspaceDir) {
|
|
12
|
+
const db = openTrajectoryDbReadonly(workspaceDir);
|
|
13
|
+
return {
|
|
14
|
+
listRecentSessions({ limit }) {
|
|
15
|
+
return db.prepare(`
|
|
16
|
+
SELECT session_id, updated_at FROM sessions ORDER BY updated_at DESC LIMIT ?
|
|
17
|
+
`).all(limit).map((value) => {
|
|
18
|
+
const row = value;
|
|
19
|
+
return { sessionId: String(row.session_id), updatedAt: String(row.updated_at) };
|
|
20
|
+
});
|
|
21
|
+
},
|
|
22
|
+
listUserTurnsForSession(sessionId) {
|
|
23
|
+
return db.prepare(`
|
|
24
|
+
SELECT raw_excerpt, correction_detected, correction_cue, created_at FROM user_turns
|
|
25
|
+
WHERE session_id = ? ORDER BY turn_index ASC
|
|
26
|
+
`).all(sessionId).map((value) => {
|
|
27
|
+
const row = value;
|
|
28
|
+
return {
|
|
29
|
+
rawExcerpt: String(row.raw_excerpt ?? ''),
|
|
30
|
+
correctionDetected: Boolean(row.correction_detected),
|
|
31
|
+
correctionCue: row.correction_cue ? String(row.correction_cue) : null,
|
|
32
|
+
createdAt: String(row.created_at),
|
|
33
|
+
};
|
|
34
|
+
});
|
|
35
|
+
},
|
|
36
|
+
close: () => { db.close(); },
|
|
37
|
+
};
|
|
38
|
+
}
|
|
39
|
+
const ELIGIBLE_GOVERNANCE_TURNS = `
|
|
40
|
+
host_kind = ?
|
|
41
|
+
AND kind = 'user_turn'
|
|
42
|
+
AND completeness = 'complete'
|
|
43
|
+
AND retention_class IN ('operational', 'promoted')
|
|
44
|
+
AND visible_text IS NOT NULL AND TRIM(visible_text) <> ''
|
|
45
|
+
`;
|
|
46
|
+
const MAX_GOVERNANCE_SESSIONS = 20;
|
|
47
|
+
const MAX_GOVERNANCE_TURNS_PER_SESSION = 40;
|
|
48
|
+
const MAX_GOVERNANCE_EXCERPT_CHARS = 401;
|
|
49
|
+
const READER_BUSY_TIMEOUT_MS = 250;
|
|
50
|
+
/** Exact-host, exact-rollout reads. Every call checks current consent BEFORE
|
|
51
|
+
* opening SQLite; no fallback to the plugin tables or a parent rollout. */
|
|
52
|
+
export function openGovernanceCorrectionTrajectory(input) {
|
|
53
|
+
const { workspaceDir, hostKind } = input;
|
|
54
|
+
const auth = input.sourceMaterialAuthorization ?? createConsentLedgerSourceMaterialAuthorization(workspaceDir);
|
|
55
|
+
const isSourceAuthorized = () => auth.isHostSourceMaterialAuthorized(hostKind).authorized;
|
|
56
|
+
function readRows(query) {
|
|
57
|
+
if (!isSourceAuthorized())
|
|
58
|
+
return [];
|
|
59
|
+
const dbPath = resolveTrajectoryDbPath(workspaceDir);
|
|
60
|
+
if (!fs.existsSync(dbPath))
|
|
61
|
+
return [];
|
|
62
|
+
let db;
|
|
63
|
+
try {
|
|
64
|
+
db = new Database(dbPath, { readonly: true, fileMustExist: true, timeout: READER_BUSY_TIMEOUT_MS });
|
|
65
|
+
// A separate process could have withdrawn consent during open/lock wait.
|
|
66
|
+
return isSourceAuthorized() ? query(db) : [];
|
|
67
|
+
}
|
|
68
|
+
catch (error) {
|
|
69
|
+
if ((!db && !fs.existsSync(dbPath))
|
|
70
|
+
|| (error instanceof Error && /no such table: (?:main\.)?governance_observations\b/.test(error.message))) {
|
|
71
|
+
return [];
|
|
72
|
+
}
|
|
73
|
+
throw error;
|
|
74
|
+
}
|
|
75
|
+
finally {
|
|
76
|
+
db?.close();
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
return {
|
|
80
|
+
sourceKind: 'governance-observations',
|
|
81
|
+
isSourceAuthorized,
|
|
82
|
+
listRecentSessions({ limit }) {
|
|
83
|
+
if (!Number.isFinite(limit) || limit < 1)
|
|
84
|
+
return [];
|
|
85
|
+
return readRows((db) => db.prepare(`
|
|
86
|
+
SELECT rollout_identity, MAX(observed_at) AS updated_at
|
|
87
|
+
FROM governance_observations WHERE ${ELIGIBLE_GOVERNANCE_TURNS}
|
|
88
|
+
GROUP BY rollout_identity ORDER BY updated_at DESC, rollout_identity ASC LIMIT ?
|
|
89
|
+
`).all(hostKind, Math.min(Math.trunc(limit), MAX_GOVERNANCE_SESSIONS)).flatMap((value) => {
|
|
90
|
+
const row = value;
|
|
91
|
+
return typeof row.rollout_identity === 'string' && typeof row.updated_at === 'string'
|
|
92
|
+
? [{ sessionId: row.rollout_identity, updatedAt: row.updated_at }]
|
|
93
|
+
: [];
|
|
94
|
+
}));
|
|
95
|
+
},
|
|
96
|
+
listUserTurnsForSession(sessionId) {
|
|
97
|
+
return readRows((db) => db.prepare(`
|
|
98
|
+
SELECT excerpt, observed_at FROM (
|
|
99
|
+
SELECT substr(visible_text, 1, ?) AS excerpt, observed_at, source_order, id
|
|
100
|
+
FROM governance_observations WHERE ${ELIGIBLE_GOVERNANCE_TURNS} AND rollout_identity = ?
|
|
101
|
+
ORDER BY source_order DESC, id DESC LIMIT ?
|
|
102
|
+
) ORDER BY source_order ASC, id ASC
|
|
103
|
+
`).all(MAX_GOVERNANCE_EXCERPT_CHARS, hostKind, sessionId, MAX_GOVERNANCE_TURNS_PER_SESSION).flatMap((value) => {
|
|
104
|
+
const row = value;
|
|
105
|
+
// Ingestion does not attest a plugin-style correction hit. Never
|
|
106
|
+
// give the model a fabricated hit, cue or FP evidence to learn from.
|
|
107
|
+
return typeof row.excerpt === 'string' && typeof row.observed_at === 'string'
|
|
108
|
+
? [{ rawExcerpt: row.excerpt, createdAt: row.observed_at, correctionDetected: false, correctionCue: null }]
|
|
109
|
+
: [];
|
|
110
|
+
}));
|
|
111
|
+
},
|
|
112
|
+
};
|
|
113
|
+
}
|
package/dist/index.d.ts
CHANGED
|
@@ -172,3 +172,9 @@ export * from './adaptive-journal-reconciliation.js';
|
|
|
172
172
|
export * from './adaptive-behavior-linkage.js';
|
|
173
173
|
export * from './intent-doc-reader.js';
|
|
174
174
|
export * from './auto-pain-authorization.js';
|
|
175
|
+
export { CorrectionCueLearner, loadCorrectionKeywordStore, saveCorrectionKeywordStore, _resetCorrectionCueCache, _resetCorrectionCueLearnerInstance, } from './correction-cue-learner.js';
|
|
176
|
+
export { readSignalHealth, updateSignalHealth, type SignalHealthState, type SignalHealthWriteError } from './signal-health.js';
|
|
177
|
+
export { KeywordOptimizationService, type CorrectionObserverLogger, type KeywordOptimizationPorts, type TrajectoryHistoryEntry, type CorrectionObserverPayload, } from './keyword-optimization-service.js';
|
|
178
|
+
export { resolveObserverConfig, type ObserverConfigResult, type ObserverReadiness } from './correction-observer-config.js';
|
|
179
|
+
export { resolveCorrectionObserver, runCorrectionObserverOptimizationCycle, type CorrectionObserverCycleInput, } from './correction-observer-cycle.js';
|
|
180
|
+
export { openGovernanceCorrectionTrajectory, type CorrectionTrajectoryReader, type GovernanceCorrectionTrajectoryInput, } from './correction-trajectory-reader.js';
|
package/dist/index.js
CHANGED
|
@@ -499,3 +499,10 @@ export * from './adaptive-behavior-linkage.js';
|
|
|
499
499
|
// admission. Business semantics stay in Core; this is the I/O adapter only.
|
|
500
500
|
export * from './intent-doc-reader.js';
|
|
501
501
|
export * from './auto-pain-authorization.js';
|
|
502
|
+
// Host-neutral correction learning; adapters own timers and their confirmation queues.
|
|
503
|
+
export { CorrectionCueLearner, loadCorrectionKeywordStore, saveCorrectionKeywordStore, _resetCorrectionCueCache, _resetCorrectionCueLearnerInstance, } from './correction-cue-learner.js';
|
|
504
|
+
export { readSignalHealth, updateSignalHealth } from './signal-health.js';
|
|
505
|
+
export { KeywordOptimizationService, } from './keyword-optimization-service.js';
|
|
506
|
+
export { resolveObserverConfig } from './correction-observer-config.js';
|
|
507
|
+
export { resolveCorrectionObserver, runCorrectionObserverOptimizationCycle, } from './correction-observer-cycle.js';
|
|
508
|
+
export { openGovernanceCorrectionTrajectory, } from './correction-trajectory-reader.js';
|
|
@@ -47,7 +47,7 @@ function getNextActionForError(category) {
|
|
|
47
47
|
return 'Retry later or check for concurrent worker processes.';
|
|
48
48
|
}
|
|
49
49
|
if (category === 'timeout') {
|
|
50
|
-
return 'Check model provider service status/latency, or increase timeout settings in
|
|
50
|
+
return 'Check model provider service status/latency, or increase timeout settings in .pd/config.yaml.';
|
|
51
51
|
}
|
|
52
52
|
if (category === 'cancelled') {
|
|
53
53
|
return 'Re-enqueue or restart the task if it was cancelled by mistake.';
|
|
@@ -0,0 +1,73 @@
|
|
|
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 { type CorrectionObserverOutputV1 as CorrectionObserverResult, type CorrectionObserverPayload } from '@principles/core/runtime';
|
|
9
|
+
import { type CorrectionTrajectoryReader } from './correction-trajectory-reader.js';
|
|
10
|
+
export type CorrectionObserverLogger = Partial<Pick<Console, 'info' | 'warn' | 'debug' | 'error'>>;
|
|
11
|
+
export interface KeywordOptimizationPorts {
|
|
12
|
+
logger?: CorrectionObserverLogger;
|
|
13
|
+
/** Optional Owner-visible trace, not a durable mutation receipt. */
|
|
14
|
+
audit?: (detail: string) => void;
|
|
15
|
+
/** Open a reader for this workspace; hosts can lend their existing connection. */
|
|
16
|
+
openTrajectory?: () => CorrectionTrajectoryReader;
|
|
17
|
+
}
|
|
18
|
+
/**
|
|
19
|
+
* Applies CorrectionObserverResult mutations to the keyword store.
|
|
20
|
+
* - ADD: calls learner.add() with new keyword (evicts least-valuable learned
|
|
21
|
+
* terms at/over the cap, with bounded convergence when the store is oversized)
|
|
22
|
+
* - UPDATE: updates weight on an existing keyword
|
|
23
|
+
* - REMOVE: removes keyword from store; Owner-authored seed terms and terms
|
|
24
|
+
* with confirmed TPs are protected
|
|
25
|
+
*
|
|
26
|
+
* Every key is resolved with the store's own identity rule (trim + lowercase),
|
|
27
|
+
* and a key that does not resolve is an observable skip, not a thrown error:
|
|
28
|
+
* the model paraphrases terms constantly, and the old per-op exceptions turned
|
|
29
|
+
* that into ~47 WARN lines a day that hid real failures.
|
|
30
|
+
*
|
|
31
|
+
* Persistence is layered and must not be conflated (P2-3):
|
|
32
|
+
* - the keyword store itself is persisted synchronously and atomically by
|
|
33
|
+
* CorrectionCueLearner.flush() (temp-file-then-rename). That is the only
|
|
34
|
+
* durable mutation of record.
|
|
35
|
+
* - the SYSTEM line emitted by audit() is best-effort, asynchronous and may
|
|
36
|
+
* drop entries. It is an Owner-visible trace, not proof that the store write
|
|
37
|
+
* happened; under disk pressure the two can legitimately disagree.
|
|
38
|
+
*/
|
|
39
|
+
export declare class KeywordOptimizationService {
|
|
40
|
+
private readonly stateDir;
|
|
41
|
+
private readonly workspaceDir;
|
|
42
|
+
private readonly logger?;
|
|
43
|
+
private readonly ports;
|
|
44
|
+
constructor(stateDir: string, workspaceDir: string, ports?: KeywordOptimizationPorts);
|
|
45
|
+
applyResult(result: CorrectionObserverResult): void;
|
|
46
|
+
/**
|
|
47
|
+
* One Owner-visible line per store mutation: plugin log + SYSTEM log.
|
|
48
|
+
*
|
|
49
|
+
* The mutation is durable because the learner flushed the store before this
|
|
50
|
+
* call. The SYSTEM line is a best-effort audit trace (async appendFile that
|
|
51
|
+
* swallows errors): its absence never means the mutation did not happen, and
|
|
52
|
+
* its presence is never by itself evidence that it did.
|
|
53
|
+
*/
|
|
54
|
+
private audit;
|
|
55
|
+
/**
|
|
56
|
+
* A verdict the store cannot act on. Reported, not thrown: the model
|
|
57
|
+
* paraphrases term keys constantly, and each refusal still needs a reason
|
|
58
|
+
* (rc-9 — degradation must be observable).
|
|
59
|
+
*/
|
|
60
|
+
private skip;
|
|
61
|
+
/**
|
|
62
|
+
* Builds trajectory history for payload:
|
|
63
|
+
* - Calls TrajectoryDatabase.listUserTurnsForSession() for recent sessions
|
|
64
|
+
* - Filters to turns where correctionDetected=true
|
|
65
|
+
* - Returns last 50 correction events
|
|
66
|
+
*/
|
|
67
|
+
buildTrajectoryHistory(sessionIds: string[]): Promise<TrajectoryHistoryEntry[]>;
|
|
68
|
+
private static readonly _instances;
|
|
69
|
+
static get(stateDir: string, workspaceDir: string, ports?: KeywordOptimizationPorts): KeywordOptimizationService;
|
|
70
|
+
static reset(): void;
|
|
71
|
+
}
|
|
72
|
+
export type TrajectoryHistoryEntry = CorrectionObserverPayload['trajectoryHistory'][number];
|
|
73
|
+
export type { CorrectionObserverPayload } from '@principles/core/runtime';
|