@principles/host-runtime 5.0.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.
- 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/keyword-optimization-service.d.ts +73 -0
- package/dist/keyword-optimization-service.js +265 -0
- 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,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
|
+
}
|
|
@@ -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 {};
|
|
@@ -0,0 +1,194 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* PRI-788 G4: 纠正信号检测健康度产物。
|
|
3
|
+
*
|
|
4
|
+
* 背景:检测器停摆 5 天 409 次失败只进 7 天滚动的 SYSTEM log(ERR-101 家族),
|
|
5
|
+
* Owner 无从发现。本模块把检测链路的关键计数/时间戳原子写入
|
|
6
|
+
* `<workspace>/.state/signal-health.json`,供 `pd config doctor` 呈现。
|
|
7
|
+
*
|
|
8
|
+
* 契约:
|
|
9
|
+
* - 当日计数(stage1Strong/stage2Confirmed/stage2Queued/stage2Dropped/
|
|
10
|
+
* stage2Invocations/stage2BatchSkipped/stage2DiscoverySkipped)在跨日首次写入时归零;
|
|
11
|
+
* 时间戳字段为绝对 ISO 值。
|
|
12
|
+
* - 写失败绝不抛出(健康度是旁路观测,不阻塞检测管线)——通知宿主的可选错误处理(rc-9)。
|
|
13
|
+
* - 文件缺失/损坏按默认值重建,读取方(doctor)自行 unknown 呈现。
|
|
14
|
+
* - AUDIT-P2-02:stage2Invocations/stage2BatchSkipped 为新增字段,升级前的
|
|
15
|
+
* 旧文件缺这两个键仍合法(读作 0);写路径始终写入完整新格式。
|
|
16
|
+
* - 所有 I/O 路径先经 guardWorkspaceLeak:测试里 mock 的 '/fake/state' 在
|
|
17
|
+
* Windows 会被 resolve 成盘根 D:\fake\state,必须和其它 I/O 入口一样重定向
|
|
18
|
+
* 到 os.tmpdir(),否则每次跑测试都在文件系统根重建目录(含 mkdir)。
|
|
19
|
+
*/
|
|
20
|
+
import * as fs from 'fs';
|
|
21
|
+
import * as path from 'path';
|
|
22
|
+
import { atomicWriteFileSync } from './atomic-write-file.js';
|
|
23
|
+
import { guardWorkspaceLeak } from '@principles/core/runtime/store/workspace-leak-guard';
|
|
24
|
+
const SIGNAL_HEALTH_FILE = 'signal-health.json';
|
|
25
|
+
const CORRECTION_OBSERVER_HOSTS = ['openclaw', 'codex', 'workbuddy'];
|
|
26
|
+
function parseObserverInputDigests(value) {
|
|
27
|
+
if (typeof value !== 'object' || value === null || Array.isArray(value))
|
|
28
|
+
return undefined;
|
|
29
|
+
const state = value;
|
|
30
|
+
const digests = {};
|
|
31
|
+
for (const hostKind of CORRECTION_OBSERVER_HOSTS) {
|
|
32
|
+
const digest = Object.hasOwn(state, hostKind) ? state[hostKind] : undefined;
|
|
33
|
+
if (typeof digest === 'string' && /^[a-f0-9]{64}$/.test(digest))
|
|
34
|
+
digests[hostKind] = digest;
|
|
35
|
+
}
|
|
36
|
+
return Object.keys(digests).length > 0 ? digests : undefined;
|
|
37
|
+
}
|
|
38
|
+
function defaultState(now) {
|
|
39
|
+
return {
|
|
40
|
+
stage1Strong: 0,
|
|
41
|
+
stage2Confirmed: 0,
|
|
42
|
+
stage2Queued: 0,
|
|
43
|
+
stage2Dropped: 0,
|
|
44
|
+
stage2Invocations: 0,
|
|
45
|
+
stage2BatchSkipped: 0,
|
|
46
|
+
stage2DiscoverySkipped: 0,
|
|
47
|
+
pendingCount: 0,
|
|
48
|
+
lastStage2SuccessAt: null,
|
|
49
|
+
observerLastSuccessAt: null,
|
|
50
|
+
observerConsecutiveFailures: 0,
|
|
51
|
+
day: now.toISOString().slice(0, 10),
|
|
52
|
+
updatedAt: now.toISOString(),
|
|
53
|
+
};
|
|
54
|
+
}
|
|
55
|
+
function healthFilePath(stateDir) {
|
|
56
|
+
return path.join(stateDir, SIGNAL_HEALTH_FILE);
|
|
57
|
+
}
|
|
58
|
+
/**
|
|
59
|
+
* 结构校验 + 解析:只接受带全部必需数值/字符串字段的对象(ERR-001/ERR-013),
|
|
60
|
+
* 并逐字段构造出完整的 SignalHealthState。
|
|
61
|
+
* 用 Object.hasOwn + typeof 做运行时收窄,避免 `in` 命中原型链、
|
|
62
|
+
* 也避免 `as` 把未校验数据直接断言成领域类型。
|
|
63
|
+
*
|
|
64
|
+
* AUDIT-P2-02 向后兼容规则:stage2Invocations / stage2BatchSkipped 是新增
|
|
65
|
+
* 字段——升级前的旧健康文件没有它们,必须照常解析(缺省读作 0),
|
|
66
|
+
* 否则升级会让 doctor 从「有计数」退化成 unknown。字段存在时仍必须是 number。
|
|
67
|
+
*/
|
|
68
|
+
function parseSignalHealthState(value) {
|
|
69
|
+
if (typeof value !== 'object' || value === null || Array.isArray(value)) {
|
|
70
|
+
return null;
|
|
71
|
+
}
|
|
72
|
+
const obj = value;
|
|
73
|
+
const requiredNum = (key) => {
|
|
74
|
+
if (!Object.hasOwn(obj, key))
|
|
75
|
+
return null;
|
|
76
|
+
const v = obj[key];
|
|
77
|
+
return typeof v === 'number' ? v : null;
|
|
78
|
+
};
|
|
79
|
+
const optionalNum = (key) => {
|
|
80
|
+
const v = obj[key];
|
|
81
|
+
return typeof v === 'number' ? v : 0;
|
|
82
|
+
};
|
|
83
|
+
const optionalStr = (key) => {
|
|
84
|
+
const v = obj[key];
|
|
85
|
+
return typeof v === 'string' ? v : null;
|
|
86
|
+
};
|
|
87
|
+
const stage1Strong = requiredNum('stage1Strong');
|
|
88
|
+
const stage2Confirmed = requiredNum('stage2Confirmed');
|
|
89
|
+
const stage2Queued = requiredNum('stage2Queued');
|
|
90
|
+
const stage2Dropped = requiredNum('stage2Dropped');
|
|
91
|
+
const pendingCount = requiredNum('pendingCount');
|
|
92
|
+
const observerConsecutiveFailures = requiredNum('observerConsecutiveFailures');
|
|
93
|
+
const day = optionalStr('day');
|
|
94
|
+
const updatedAt = optionalStr('updatedAt');
|
|
95
|
+
if (stage1Strong === null || stage2Confirmed === null || stage2Queued === null ||
|
|
96
|
+
stage2Dropped === null || pendingCount === null || observerConsecutiveFailures === null ||
|
|
97
|
+
day === null || updatedAt === null) {
|
|
98
|
+
return null;
|
|
99
|
+
}
|
|
100
|
+
// 新字段存在但非数值 → 视为损坏(与旧必需字段同一纪律)。
|
|
101
|
+
if (Object.hasOwn(obj, 'stage2Invocations') && typeof obj.stage2Invocations !== 'number')
|
|
102
|
+
return null;
|
|
103
|
+
if (Object.hasOwn(obj, 'stage2BatchSkipped') && typeof obj.stage2BatchSkipped !== 'number')
|
|
104
|
+
return null;
|
|
105
|
+
if (Object.hasOwn(obj, 'stage2DiscoverySkipped') && typeof obj.stage2DiscoverySkipped !== 'number')
|
|
106
|
+
return null;
|
|
107
|
+
const digests = parseObserverInputDigests(obj.observerInputDigests);
|
|
108
|
+
return {
|
|
109
|
+
stage1Strong,
|
|
110
|
+
stage2Confirmed,
|
|
111
|
+
stage2Queued,
|
|
112
|
+
stage2Dropped,
|
|
113
|
+
stage2Invocations: optionalNum('stage2Invocations'),
|
|
114
|
+
stage2BatchSkipped: optionalNum('stage2BatchSkipped'),
|
|
115
|
+
stage2DiscoverySkipped: optionalNum('stage2DiscoverySkipped'),
|
|
116
|
+
pendingCount,
|
|
117
|
+
lastStage2SuccessAt: optionalStr('lastStage2SuccessAt'),
|
|
118
|
+
observerLastSuccessAt: optionalStr('observerLastSuccessAt'),
|
|
119
|
+
...(digests === undefined ? {} : { observerInputDigests: digests }),
|
|
120
|
+
observerConsecutiveFailures,
|
|
121
|
+
day,
|
|
122
|
+
updatedAt,
|
|
123
|
+
};
|
|
124
|
+
}
|
|
125
|
+
function loadState(stateDir, now) {
|
|
126
|
+
try {
|
|
127
|
+
const raw = fs.readFileSync(healthFilePath(stateDir), 'utf-8');
|
|
128
|
+
const parsed = JSON.parse(raw);
|
|
129
|
+
const state = parseSignalHealthState(parsed);
|
|
130
|
+
if (state) {
|
|
131
|
+
const today = now.toISOString().slice(0, 10);
|
|
132
|
+
if (state.day !== today) {
|
|
133
|
+
// 跨日:当日计数归零(含 AUDIT-P2-02 新增计数),时间戳与失败计数保留
|
|
134
|
+
return {
|
|
135
|
+
...state,
|
|
136
|
+
stage1Strong: 0,
|
|
137
|
+
stage2Confirmed: 0,
|
|
138
|
+
stage2Queued: 0,
|
|
139
|
+
stage2Dropped: 0,
|
|
140
|
+
stage2Invocations: 0,
|
|
141
|
+
stage2BatchSkipped: 0,
|
|
142
|
+
stage2DiscoverySkipped: 0,
|
|
143
|
+
day: today,
|
|
144
|
+
};
|
|
145
|
+
}
|
|
146
|
+
return state;
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
catch {
|
|
150
|
+
// 缺失/损坏 → 重建默认值(doctor 侧以 updatedAt/字段存在性呈现 unknown)
|
|
151
|
+
}
|
|
152
|
+
return defaultState(now);
|
|
153
|
+
}
|
|
154
|
+
/**
|
|
155
|
+
* 读健康状态(doctor 用)。文件缺失/损坏返回 null,由读取方呈现 unknown。
|
|
156
|
+
* 旧格式(无 AUDIT-P2-02 新增计数字段)照常解析,缺省字段读作 0。
|
|
157
|
+
*/
|
|
158
|
+
export function readSignalHealth(stateDir) {
|
|
159
|
+
try {
|
|
160
|
+
const raw = fs.readFileSync(healthFilePath(guardWorkspaceLeak(stateDir)), 'utf-8');
|
|
161
|
+
const parsed = JSON.parse(raw);
|
|
162
|
+
return parseSignalHealthState(parsed);
|
|
163
|
+
}
|
|
164
|
+
catch {
|
|
165
|
+
return null;
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
export function updateSignalHealth(stateDir, mutate, onError) {
|
|
169
|
+
// Guard BEFORE the mkdir — a leaked '/fake/state' must not recreate
|
|
170
|
+
// D:\fake\state on Windows. loadState / healthFilePath receive the same
|
|
171
|
+
// guarded dir, so read and write always agree on one location.
|
|
172
|
+
const safeStateDir = guardWorkspaceLeak(stateDir);
|
|
173
|
+
try {
|
|
174
|
+
const now = new Date();
|
|
175
|
+
const state = loadState(safeStateDir, now);
|
|
176
|
+
mutate(state);
|
|
177
|
+
state.updatedAt = now.toISOString();
|
|
178
|
+
state.day = now.toISOString().slice(0, 10);
|
|
179
|
+
fs.mkdirSync(safeStateDir, { recursive: true });
|
|
180
|
+
atomicWriteFileSync(healthFilePath(safeStateDir), JSON.stringify(state, null, 2));
|
|
181
|
+
}
|
|
182
|
+
catch (err) {
|
|
183
|
+
// Without a concrete workspace, do not write an audit line to cwd.
|
|
184
|
+
// Reporting is best-effort too: an optional host callback cannot block detection.
|
|
185
|
+
if (safeStateDir) {
|
|
186
|
+
try {
|
|
187
|
+
onError?.(path.dirname(safeStateDir), err);
|
|
188
|
+
}
|
|
189
|
+
catch {
|
|
190
|
+
// The health write has already failed; keep the side channel non-blocking.
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
}
|
|
@@ -45,6 +45,8 @@ export interface ResolveWorkspacePipelineHostDepsInput {
|
|
|
45
45
|
readonly workspaceDir: string;
|
|
46
46
|
/** The CURRENT entry's effective config — the intent reader's flag authority (SPEC §13.1). */
|
|
47
47
|
readonly effectiveConfig: EffectivePdConfig;
|
|
48
|
+
/** Reuse the worker cycle's workspace-scoped, live consent port. */
|
|
49
|
+
readonly sourceMaterialAuthorization?: SourceMaterialAuthorizationPort;
|
|
48
50
|
/**
|
|
49
51
|
* OpenClaw Gateway hook / command processes already hold
|
|
50
52
|
* `WorkspaceContext.trajectory`; pass it here to replace the default
|
|
@@ -57,7 +57,7 @@ export function resolveWorkspacePipelineHostDeps(input) {
|
|
|
57
57
|
// trajectory reader and every gate consumer returned to the caller observe
|
|
58
58
|
// the SAME latest-consent state (the double-instance defect this module
|
|
59
59
|
// exists to remove).
|
|
60
|
-
const sourceMaterialAuthorization = createConsentLedgerSourceMaterialAuthorization(input.workspaceDir);
|
|
60
|
+
const sourceMaterialAuthorization = input.sourceMaterialAuthorization ?? createConsentLedgerSourceMaterialAuthorization(input.workspaceDir);
|
|
61
61
|
const overrideHostKind = input.trajectoryTurnReaderOverrideHostKind;
|
|
62
62
|
if (input.trajectoryTurnReaderOverride !== undefined && overrideHostKind === undefined) {
|
|
63
63
|
throw new Error('trajectoryTurnReaderOverrideHostKind is required when trajectoryTurnReaderOverride is provided');
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@principles/host-runtime",
|
|
3
|
-
"version": "5.
|
|
3
|
+
"version": "5.1.0",
|
|
4
4
|
"description": "Shared host-neutral orchestration for Principles Disciple MVP-Core hook paths.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.js",
|
|
@@ -11,6 +11,10 @@
|
|
|
11
11
|
"default": "./dist/index.js"
|
|
12
12
|
},
|
|
13
13
|
"./package.json": "./package.json",
|
|
14
|
+
"./atomic-write-file": {
|
|
15
|
+
"types": "./dist/atomic-write-file.d.ts",
|
|
16
|
+
"default": "./dist/atomic-write-file.js"
|
|
17
|
+
},
|
|
14
18
|
"./behavior-example-pack-assembler": {
|
|
15
19
|
"types": "./dist/behavior-example-pack-assembler.d.ts",
|
|
16
20
|
"default": "./dist/behavior-example-pack-assembler.js"
|
|
@@ -39,7 +43,7 @@
|
|
|
39
43
|
"lint": "eslint \"src/**/*.ts\""
|
|
40
44
|
},
|
|
41
45
|
"dependencies": {
|
|
42
|
-
"@principles/core": "^10.0.
|
|
46
|
+
"@principles/core": "^10.0.1",
|
|
43
47
|
"@principles/install-layout": "^0.12.0",
|
|
44
48
|
"better-sqlite3": "^13.0.3",
|
|
45
49
|
"js-yaml": "^5.4.3"
|
|
@@ -57,5 +61,5 @@
|
|
|
57
61
|
"url": "git+https://github.com/csuzngjh/principles.git"
|
|
58
62
|
},
|
|
59
63
|
"license": "Apache-2.0",
|
|
60
|
-
"gitHead": "
|
|
64
|
+
"gitHead": "a6798ad286b1584b8d6e2da6fd9b81e9b99609cf"
|
|
61
65
|
}
|