@lmzhen/dsh-evolution-activity 0.44.0 → 0.46.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/lib/feedback/index.js +690 -0
- package/lib/index.js +23 -18
- package/lib/learning-graph/index.js +538 -0
- package/lib/replay/index.js +286 -0
- package/lib/threat/index.js +70 -0
- package/lib/types/feedback/index.d.ts +179 -0
- package/lib/types/feedback/index.js +899 -0
- package/lib/types/index.js +335 -0
- package/lib/types/learning-graph/index.d.ts +178 -0
- package/lib/types/learning-graph/index.js +712 -0
- package/lib/types/replay/index.d.ts +182 -0
- package/lib/types/replay/index.js +404 -0
- package/lib/types/threat/index.d.ts +35 -0
- package/lib/types/threat/index.js +119 -0
- package/locale/feedback/de.json +6 -0
- package/locale/feedback/en.json +6 -0
- package/locale/feedback/es.json +6 -0
- package/locale/feedback/fr.json +6 -0
- package/locale/feedback/ja.json +6 -0
- package/locale/feedback/pt.json +6 -0
- package/locale/feedback/ru.json +6 -0
- package/locale/feedback/zh.json +6 -0
- package/locale/learning-graph/de.json +6 -0
- package/locale/learning-graph/en.json +6 -0
- package/locale/learning-graph/es.json +6 -0
- package/locale/learning-graph/fr.json +6 -0
- package/locale/learning-graph/ja.json +6 -0
- package/locale/learning-graph/pt.json +6 -0
- package/locale/learning-graph/ru.json +6 -0
- package/locale/learning-graph/zh.json +6 -0
- package/locale/replay/de.json +6 -0
- package/locale/replay/en.json +6 -0
- package/locale/replay/es.json +6 -0
- package/locale/replay/fr.json +6 -0
- package/locale/replay/ja.json +6 -0
- package/locale/replay/pt.json +6 -0
- package/locale/replay/ru.json +6 -0
- package/locale/replay/zh.json +6 -0
- package/locale/threat/de.json +6 -0
- package/locale/threat/en.json +6 -0
- package/locale/threat/es.json +6 -0
- package/locale/threat/fr.json +6 -0
- package/locale/threat/ja.json +6 -0
- package/locale/threat/pt.json +6 -0
- package/locale/threat/ru.json +6 -0
- package/locale/threat/zh.json +6 -0
- package/package.json +30 -8
|
@@ -0,0 +1,899 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Feedback-to-quality scoring for self-evolution.
|
|
3
|
+
*
|
|
4
|
+
* Feedback is durable through `ctx.evolutionIo` (when mounted) and skill
|
|
5
|
+
* feedback feeds the FEEDBACK-OWNED `feedback_score` / `feedback_warn` pair on
|
|
6
|
+
* the usage record. P1-1 (v15): this package used to write
|
|
7
|
+
* `quality_score`/`quality_warn` — but the curator's six-factor `scoreTree`
|
|
8
|
+
* overwrote those fields on every run BEFORE the lifecycle engine read them,
|
|
9
|
+
* so the advertised "curator decisions consume feedback deterministically"
|
|
10
|
+
* channel was dead. The lifecycle engine and the scope view now read the
|
|
11
|
+
* union `quality_warn || feedback_warn`, and the curator never writes the
|
|
12
|
+
* feedback pair (field-ownership contract on `UsageRecord` in
|
|
13
|
+
* evolution-core/usage.ts).
|
|
14
|
+
*
|
|
15
|
+
* Persistence (rc.68): the EVENTS LOG (`evolution/events.json`, via
|
|
16
|
+
* `evolution-core/evolution-events.ts`) is the single source of truth —
|
|
17
|
+
* every increment appends one event under the write lock. `feedback.json` is
|
|
18
|
+
* a rebuildable BOOT CACHE (`{ version: 2, lastSeq, skills, sessions }`),
|
|
19
|
+
* never the truth; the in-memory state is the optimistic aggregate.
|
|
20
|
+
* @module @lmzhen/dsh-evolution-feedback
|
|
21
|
+
*/
|
|
22
|
+
import { isRecord } from '@lmzhen/dsh-evolution-core';
|
|
23
|
+
import z from '@deepseek-ai/schemastery';
|
|
24
|
+
import { appendEvolutionEvent, eventsFile, evolutionEventPayloadIssue, evolutionIoAdapter, evolutionRoot, isPresent, isUnknown, listEventArchives, parseEvolutionEvents, probeText, readEvolutionTimeline, transactIo, clampedNumber, EVENT_LOG_VERSION } from '@lmzhen/dsh-evolution-core';
|
|
25
|
+
import { join } from 'node:path';
|
|
26
|
+
const CACHE_VERSION = 2;
|
|
27
|
+
/** Cache snapshot cadence (rc.72 G-3): every N-th appended event refreshes the
|
|
28
|
+
* boot cache, so `cache.lastSeq` always stays inside the retention window —
|
|
29
|
+
* a hard crash between snapshots loses at most N events, all of which still
|
|
30
|
+
* live in the ACTIVE log (bounded by `EVENT_LOG_ROTATE_AT`), so the next fold
|
|
31
|
+
* is complete. Package-private tunable, not a config surface. */
|
|
32
|
+
const CACHE_SNAP_EVERY = 1024;
|
|
33
|
+
/** C-events-dispatch-1 (v43 audit): the timeline read flags a DROPPED band — an
|
|
34
|
+
* unreadable archive (EISDIR/EACCES) or a body this v1 reader cannot interpret
|
|
35
|
+
* (damaged, or a future version). The boot cache stores the fold BASELINE
|
|
36
|
+
* (`lastSeq`), and `foldWithDelta` only folds `seq > lastSeq`, so folding a
|
|
37
|
+
* truncated read back into it would seal the dropped band against every later
|
|
38
|
+
* boot — the loss becomes unrecoverable without deleting the cache by hand.
|
|
39
|
+
* Both cache writers withhold the refresh when that flag is set (the cache is
|
|
40
|
+
* disposable by contract, so the last COMPLETE fold simply stays) and say so
|
|
41
|
+
* through this ONE message, deduped to a single warn per process (V5-32) because
|
|
42
|
+
* `refold()` re-runs `restore()` before every quality push. */
|
|
43
|
+
const TRUNCATED_TIMELINE_WARN = 'evolution-feedback: the evolution event timeline is TRUNCATED - at least one segment (an unreadable archive, or a body this v1'
|
|
44
|
+
+ ' reader cannot interpret, e.g. a future version) was dropped, so the folded counts are incomplete; the boot cache was NOT updated'
|
|
45
|
+
+ ' (a truncated lastSeq would seal the missing band against every later boot)';
|
|
46
|
+
export class EvolutionFeedback {
|
|
47
|
+
state = { skills: {}, sessions: {} };
|
|
48
|
+
chain = Promise.resolve();
|
|
49
|
+
path;
|
|
50
|
+
eventsPath;
|
|
51
|
+
io;
|
|
52
|
+
warn;
|
|
53
|
+
/** V4-41 (F-324): the last note per target CONFIRMED on the event log. The
|
|
54
|
+
* in-memory `lastNote` is optimistic; a failed append must roll back to this,
|
|
55
|
+
* never to the in-memory `previousNote` (an earlier failed call can leave an
|
|
56
|
+
* unpersisted note there, and reverting to it resurrects a value the log
|
|
57
|
+
* never held). Seeded from the fold truth, updated on successful appends. */
|
|
58
|
+
durableNote = new Map;
|
|
59
|
+
/** PLAN S1.4 (2026-09-16): targets with a feedback append still IN FLIGHT,
|
|
60
|
+
* split by table, as a COUNT per target. record() increments before queueing
|
|
61
|
+
* the append and the append task decrements when it settles (landed or rolled
|
|
62
|
+
* back, finally), dropping the entry only at ZERO — the count covers exactly
|
|
63
|
+
* the optimistic window rc.66 meant to protect, including two appends for the
|
|
64
|
+
* same target in flight at once (review C-P2-1: a per-target boolean marker
|
|
65
|
+
* was cleared by the first settle, so a merge between the two appends folded
|
|
66
|
+
* the second append's increment away). restore() lets memory win ONLY for these targets — a settled
|
|
67
|
+
* target folds from the log truth, so another process's feedback for the
|
|
68
|
+
* same target (audit P1-3) is never overwritten by this process's stale
|
|
69
|
+
* record. */
|
|
70
|
+
pendingAppends = {
|
|
71
|
+
skills: new Map(),
|
|
72
|
+
sessions: new Map(),
|
|
73
|
+
};
|
|
74
|
+
/** P2-32 (v11): process-level bound — every feedbacked session would
|
|
75
|
+
* otherwise keep one entry for the whole process lifetime (a name + note
|
|
76
|
+
* string per session); cap this map and drop the earliest-INSERTED entry on
|
|
77
|
+
* overflow (Map iteration order is insertion order, and re-setting an
|
|
78
|
+
* existing key does not refresh its position, so the eviction is FIFO rather
|
|
79
|
+
* than least-recently-used). `warnedMessages` carries the same bound through
|
|
80
|
+
* `WARNED_CAP` below. */
|
|
81
|
+
static NOTE_CAP = 512;
|
|
82
|
+
/** V5-32 (0.3.31): fire-and-forget append failures are warn-once per unique
|
|
83
|
+
* message — a persistent refusal (e.g. a future-version log) must not spam
|
|
84
|
+
* the log on every user feedback entry (family posture: process-level once).
|
|
85
|
+
* Bounded like `durableNote`, with the same FIFO eviction. */
|
|
86
|
+
warnedMessages = new Set();
|
|
87
|
+
WARNED_CAP = 512;
|
|
88
|
+
/** V5-29 (0.3.31): invoked after a FAILED append rolled back, so a caller
|
|
89
|
+
* holding derived state (skillUsage quality score) can re-push it instead of
|
|
90
|
+
* keeping an optimistic value that never landed. */
|
|
91
|
+
onRollback;
|
|
92
|
+
fence;
|
|
93
|
+
constructor(io, home = evolutionRoot(), pathOverride, warn = () => { }, fence) {
|
|
94
|
+
// rc.68 + K-6: BOTH paths derive from the constructor surface only —
|
|
95
|
+
// record() takes no backend io, so path and io backend can never disagree.
|
|
96
|
+
// They derive unconditionally so a late `attachIo` (S6.4) does not need to
|
|
97
|
+
// repopulate them; methods no-op on `this.io` being absent.
|
|
98
|
+
this.path = pathOverride ?? join(home, 'evolution', 'feedback.json');
|
|
99
|
+
this.eventsPath = eventsFile(home);
|
|
100
|
+
this.io = io;
|
|
101
|
+
this.warn = warn;
|
|
102
|
+
this.fence = fence;
|
|
103
|
+
}
|
|
104
|
+
/** Bind the evolution IO backend after construction (S6.4 deferred binding). */
|
|
105
|
+
attachIo(io) {
|
|
106
|
+
this.io = io;
|
|
107
|
+
}
|
|
108
|
+
/** PLAN S4.6 (2026-09-16): whether a durable backend is attached — the
|
|
109
|
+
* plugin's quality push (`apply`) consults this before writing the
|
|
110
|
+
* feedback pair into the skill-usage sidecar. Same no-io posture as
|
|
111
|
+
* `record`/`refold`: without `ctx.evolutionIo` (when mounted) nothing may
|
|
112
|
+
* turn the optimistic in-memory aggregate into a durable side effect. */
|
|
113
|
+
get durable() {
|
|
114
|
+
return this.io !== undefined && !!this.eventsPath;
|
|
115
|
+
}
|
|
116
|
+
/** V5-32 posture applied to the read side (C-events-dispatch-1, v43): an
|
|
117
|
+
* event a repeated read keeps reporting must not warn on each read —
|
|
118
|
+
* `refold()` calls `restore()` before every quality push. Shares the bounded
|
|
119
|
+
* `warnedMessages` set (and its FIFO eviction) with the append-failure warn.
|
|
120
|
+
* @param message - the warn text; identical text warns once per process.
|
|
121
|
+
*/
|
|
122
|
+
warnOnce(message) {
|
|
123
|
+
if (this.warnedMessages.has(message))
|
|
124
|
+
return;
|
|
125
|
+
if (this.warnedMessages.size >= this.WARNED_CAP) {
|
|
126
|
+
const oldest = this.warnedMessages.values().next().value;
|
|
127
|
+
if (oldest !== undefined)
|
|
128
|
+
this.warnedMessages.delete(oldest);
|
|
129
|
+
}
|
|
130
|
+
this.warnedMessages.add(message);
|
|
131
|
+
this.warn(message);
|
|
132
|
+
}
|
|
133
|
+
/** Durable-note map key (V4-41): a target shares one record per mode. */
|
|
134
|
+
noteKey(mode, target) {
|
|
135
|
+
return `${mode}\u0000${target}`;
|
|
136
|
+
}
|
|
137
|
+
mutate(task) {
|
|
138
|
+
const run = this.chain.then(task, task);
|
|
139
|
+
this.chain = run.then(() => undefined, () => undefined);
|
|
140
|
+
return run;
|
|
141
|
+
}
|
|
142
|
+
async restore(io) {
|
|
143
|
+
const path = this.path;
|
|
144
|
+
const eventsPath = this.eventsPath;
|
|
145
|
+
if (!path || !eventsPath)
|
|
146
|
+
return;
|
|
147
|
+
await this.mutate(async () => {
|
|
148
|
+
const rawEvents = await io.readText(eventsPath);
|
|
149
|
+
// Migration (rc.68/rc.69, idempotent + race-safe): no event log AND no
|
|
150
|
+
// archive yet — fold whatever aggregate exists (legacy v1 or v2 cache)
|
|
151
|
+
// into synthetic events. rc.71: with archives present the truth lives in
|
|
152
|
+
// the archive timeline, so a manually deleted active file must never be
|
|
153
|
+
// re-synthesized from the cache. rc.69: a concurrent first writer that
|
|
154
|
+
// created the log in the race window is handled by the merge in
|
|
155
|
+
// migrateFeedbackEvents (append, never drop).
|
|
156
|
+
const archiveNames = await listEventArchives(io, eventsPath);
|
|
157
|
+
// C2 (v35): the cache file is read ONCE for both consumers below — the
|
|
158
|
+
// migration branch's parseAggregate and the boot cache's parseCache (both
|
|
159
|
+
// are pure; the migration writes only the event log, never this file).
|
|
160
|
+
const rawCache = await io.readText(path);
|
|
161
|
+
const noLog = rawEvents === null || rawEvents.trim() === '';
|
|
162
|
+
if (noLog && archiveNames.length === 0) {
|
|
163
|
+
// V24-05 (v24): the migration path now consumes the SAME per-record
|
|
164
|
+
// sanitizer as the boot cache reader (S6.4) — parseAggregate used to
|
|
165
|
+
// cast `{skills,sessions}` unchecked, so a single corrupted
|
|
166
|
+
// `positive: 1e9` count in a hand-edited/damaged feedback.json was
|
|
167
|
+
// expanded by synthesizeFeedbackEvents into a billion-element event
|
|
168
|
+
// array at boot (OOM / wedged event loop), and a non-string lastNote
|
|
169
|
+
// flowed into the folded record as a type lie. Bad records are
|
|
170
|
+
// dropped with a warn; surviving counts are clamped to the migration
|
|
171
|
+
// budget below.
|
|
172
|
+
const aggregate = parseAggregate(rawCache, this.warn);
|
|
173
|
+
if (aggregate) {
|
|
174
|
+
try {
|
|
175
|
+
await migrateFeedbackEvents(io, eventsPath, aggregate, this.warn, this.fence);
|
|
176
|
+
}
|
|
177
|
+
catch {
|
|
178
|
+
// Best-effort: a failed migration means the log stays absent and
|
|
179
|
+
// history starts empty — the old aggregate is not re-booted.
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
// The archives listed above ride along (one directory scan). P2-1 (v37):
|
|
184
|
+
// that list is a snapshot taken BEFORE the read, so a rotate landing in
|
|
185
|
+
// between archives a band this read never sees — re-list and fold the union.
|
|
186
|
+
const initial = await readEvolutionTimeline(io, eventsPath, archiveNames);
|
|
187
|
+
// A repeated full read is idempotent: the merge dedupes by seq.
|
|
188
|
+
const lateArchives = (await listEventArchives(io, eventsPath)).filter(name => !archiveNames.includes(name));
|
|
189
|
+
const later = lateArchives.length === 0
|
|
190
|
+
? null
|
|
191
|
+
: await readEvolutionTimeline(io, eventsPath, [...archiveNames, ...lateArchives]);
|
|
192
|
+
const events = later?.events ?? initial.events;
|
|
193
|
+
// C-events-dispatch-1 (v43): EITHER read can drop a seq band (an unreadable
|
|
194
|
+
// archive, or a body this v1 reader cannot interpret) and the union is the
|
|
195
|
+
// honest answer — a dropped band is missing from `events` while `malformed`
|
|
196
|
+
// is the only signal that it ever existed.
|
|
197
|
+
const truncated = initial.malformed || later?.malformed === true;
|
|
198
|
+
const cache = parseCache(rawCache, this.warn);
|
|
199
|
+
const maxSeq = events.reduce((max, event) => Math.max(max, event.seq), 0);
|
|
200
|
+
const floor = events[0]?.seq ?? 0;
|
|
201
|
+
// rc.72 G-3: a cache whose lastSeq fell below the timeline floor is out
|
|
202
|
+
// of the retained window — using it would silently fabricate a partial
|
|
203
|
+
// fold; fall back to the full fold (an unrecoverable band stays lost,
|
|
204
|
+
// but the result is never WRONG).
|
|
205
|
+
// P2-25: a cache AHEAD of the retained timeline (the log was cleared) is not
|
|
206
|
+
// usable: its stale lastSeq would skip every new event <= that value.
|
|
207
|
+
const usableCache = cache && cache.lastSeq >= floor - 1 && cache.lastSeq <= maxSeq ? cache : null;
|
|
208
|
+
const truth = usableCache ? foldWithDelta(usableCache, events, this.warn) : foldFeedbackState(events, this.warn);
|
|
209
|
+
// PLAN S1.4 (2026-09-16), narrowing the rc.66 "memory wins per record"
|
|
210
|
+
// rule: memory wins ONLY for targets whose append is still in flight —
|
|
211
|
+
// the rc.66 intent ("a record() that landed optimistically before this
|
|
212
|
+
// restore settled must survive") covers that window, not the target
|
|
213
|
+
// forever. A settled target folds from the log truth, so another
|
|
214
|
+
// process's feedback for the same target survives this refold instead of
|
|
215
|
+
// being replaced by this process's stale record (audit P1-3: the stale
|
|
216
|
+
// absolute pair used to be pushed into the usage sidecar by
|
|
217
|
+
// setFeedbackQuality and read back by the curator).
|
|
218
|
+
const pickPending = (mode) => {
|
|
219
|
+
const picked = {};
|
|
220
|
+
for (const [target, inFlight] of this.pendingAppends[mode]) {
|
|
221
|
+
if (inFlight <= 0)
|
|
222
|
+
continue;
|
|
223
|
+
const record = this.state[mode][target];
|
|
224
|
+
if (record)
|
|
225
|
+
picked[target] = record;
|
|
226
|
+
}
|
|
227
|
+
return picked;
|
|
228
|
+
};
|
|
229
|
+
this.state = {
|
|
230
|
+
skills: { ...truth.skills, ...pickPending('skills') },
|
|
231
|
+
sessions: { ...truth.sessions, ...pickPending('sessions') },
|
|
232
|
+
};
|
|
233
|
+
// V4-41: seed the durable-note map from the persisted fold (the TRUTH),
|
|
234
|
+
// so a later failed append rolls back to what the log actually holds.
|
|
235
|
+
// P3-3 (v13): interleave skills/sessions by kind — the old order seeded
|
|
236
|
+
// all skills first, so the N7 oldest-dropped eviction beyond the cap
|
|
237
|
+
// (insertion order) systematically evicted skill notes (the V5-29
|
|
238
|
+
// quality-rollback channel) over session notes.
|
|
239
|
+
const skillEntries = Object.entries(truth.skills);
|
|
240
|
+
const sessionEntries = Object.entries(truth.sessions);
|
|
241
|
+
const seedCount = Math.max(skillEntries.length, sessionEntries.length);
|
|
242
|
+
for (let i = 0; i < seedCount; i += 1) {
|
|
243
|
+
const skillEntry = skillEntries[i];
|
|
244
|
+
if (skillEntry)
|
|
245
|
+
this.durableNote.set(this.noteKey('skills', skillEntry[0]), skillEntry[1].lastNote);
|
|
246
|
+
const sessionEntry = sessionEntries[i];
|
|
247
|
+
if (sessionEntry)
|
|
248
|
+
this.durableNote.set(this.noteKey('sessions', sessionEntry[0]), sessionEntry[1].lastNote);
|
|
249
|
+
}
|
|
250
|
+
// N7 (v12): the seed path had no cap — a >512 feedbacked-target
|
|
251
|
+
// deployment stayed over the bound after every restore (the record
|
|
252
|
+
// path's insert-time eviction cannot lower it). Same oldest-dropped
|
|
253
|
+
// order as record().
|
|
254
|
+
while (this.durableNote.size > EvolutionFeedback.NOTE_CAP) {
|
|
255
|
+
const oldest = this.durableNote.keys().next().value;
|
|
256
|
+
if (oldest === undefined)
|
|
257
|
+
break;
|
|
258
|
+
this.durableNote.delete(oldest);
|
|
259
|
+
}
|
|
260
|
+
// Refresh the boot cache from the TRUTH, never from the memory-merged
|
|
261
|
+
// state — an optimistic record whose event is not yet on disk must not
|
|
262
|
+
// double-count at the next boot.
|
|
263
|
+
if (truncated) {
|
|
264
|
+
// C-events-dispatch-1 (v43): the folded view is incomplete, and `lastSeq`
|
|
265
|
+
// is the fold BASELINE for every later boot — writing it from a truncated
|
|
266
|
+
// read would stamp the dropped band as already folded and `foldWithDelta`
|
|
267
|
+
// would never revisit it (P1-3's unrecoverable loss). Withhold the write:
|
|
268
|
+
// the cache is disposable, so the last COMPLETE fold stays in place and a
|
|
269
|
+
// later boot with the archive repaired still folds the band it dropped.
|
|
270
|
+
this.warnOnce(TRUNCATED_TIMELINE_WARN);
|
|
271
|
+
}
|
|
272
|
+
else if (maxSeq > 0 && (!cache || cache.lastSeq !== maxSeq)) {
|
|
273
|
+
try {
|
|
274
|
+
await io.writeText(path, JSON.stringify({ version: CACHE_VERSION, lastSeq: maxSeq, ...truth }, null, 2));
|
|
275
|
+
}
|
|
276
|
+
catch {
|
|
277
|
+
// Best-effort: the cache is disposable.
|
|
278
|
+
}
|
|
279
|
+
}
|
|
280
|
+
});
|
|
281
|
+
}
|
|
282
|
+
/** External-producer contract (审计 B-4, v18): nothing inside the family
|
|
283
|
+
* calls `record` — the upstream `/feedback` command only appends a
|
|
284
|
+
* `feedback/record` session event carrying free text, which cannot be mapped
|
|
285
|
+
* to a (target, rating) pair without inventing semantics. A host that wants
|
|
286
|
+
* feedback-driven curation wires its own command/event to this method; the
|
|
287
|
+
* curator's union read (`feedback_warn`) then shortens the stale window.
|
|
288
|
+
* `feedback.spec.ts` pins that channel end to end.
|
|
289
|
+
* @param target - skill name or session id the rating belongs to.
|
|
290
|
+
* @param rating - `positive` or `negative`; other values are refused.
|
|
291
|
+
* @param note - optional free-text note carried into the durable event.
|
|
292
|
+
* @param kind - `skill` (default `session`) selects the score table.
|
|
293
|
+
*/
|
|
294
|
+
/**
|
|
295
|
+
* v30 FB-01: refold the shared event log into the in-process aggregate.
|
|
296
|
+
* The aggregate only folds at mount, so a long-lived process computed the
|
|
297
|
+
* ABSOLUTE feedback pair from a stale aggregate and overwrote the decision
|
|
298
|
+
* relevant `feedback_warn` another process had recorded. The log is the
|
|
299
|
+
* truth — re-reading it before each quality push shrinks the staleness
|
|
300
|
+
* window to the refold-vs-append race (near-zero, serialized by mutate).
|
|
301
|
+
*/
|
|
302
|
+
async refold() {
|
|
303
|
+
if (!this.io)
|
|
304
|
+
return;
|
|
305
|
+
await this.restore(this.io);
|
|
306
|
+
}
|
|
307
|
+
record(target, rating, note, kind = 'session') {
|
|
308
|
+
const mode = kind === 'skill' ? 'skills' : 'sessions';
|
|
309
|
+
// Optimistic in-memory update: score()/quality read it synchronously.
|
|
310
|
+
const table = this.state[mode];
|
|
311
|
+
const current = table[target] ?? { positive: 0, negative: 0 };
|
|
312
|
+
current[rating] += 1;
|
|
313
|
+
if (note !== undefined)
|
|
314
|
+
current.lastNote = note;
|
|
315
|
+
table[target] = current;
|
|
316
|
+
const recordIo = this.io;
|
|
317
|
+
const eventsPath = this.eventsPath;
|
|
318
|
+
if (!recordIo || !eventsPath)
|
|
319
|
+
return;
|
|
320
|
+
// PLAN S1.4: mark the target in flight BEFORE queueing the append — a
|
|
321
|
+
// restore merging before the append settles must keep this optimistic
|
|
322
|
+
// record (the rc.66 window). The early return above is the no-io path:
|
|
323
|
+
// no append is ever queued, so nothing stays pending.
|
|
324
|
+
const pending = this.pendingAppends[mode];
|
|
325
|
+
pending.set(target, (pending.get(target) ?? 0) + 1);
|
|
326
|
+
// rc.68: the increment is an EVENT APPEND under the write lock — the log
|
|
327
|
+
// is the truth, the aggregate is derived. A malformed log refuses the
|
|
328
|
+
// append (rc.65 posture). S6.4 E-8: a failed append reclaims the optimistic
|
|
329
|
+
// count — the log is the truth, so a count that never landed must not
|
|
330
|
+
// linger in memory (it would silently diverge and be dropped next boot).
|
|
331
|
+
void this.mutate(async () => {
|
|
332
|
+
try {
|
|
333
|
+
const seq = await appendEvolutionEvent(recordIo, eventsPath, { type: 'feedback', target, kind, rating, note }, undefined, this.fence);
|
|
334
|
+
// A successfully persisted note becomes the durable truth for a later
|
|
335
|
+
// failed append's rollback (V4-41).
|
|
336
|
+
if (note !== undefined) {
|
|
337
|
+
if (this.durableNote.size >= EvolutionFeedback.NOTE_CAP) {
|
|
338
|
+
const oldest = this.durableNote.keys().next().value;
|
|
339
|
+
if (oldest !== undefined)
|
|
340
|
+
this.durableNote.delete(oldest);
|
|
341
|
+
}
|
|
342
|
+
this.durableNote.set(this.noteKey(mode, target), note);
|
|
343
|
+
}
|
|
344
|
+
// rc.72 G-3: cadence snapshot keeps the boot cache inside the retention
|
|
345
|
+
// window (see CACHE_SNAP_EVERY); best-effort inside the same task.
|
|
346
|
+
// writeCacheNow swallows its own errors and never throws, so this catch
|
|
347
|
+
// is reached only when the append itself failed.
|
|
348
|
+
if (seq % CACHE_SNAP_EVERY === 0)
|
|
349
|
+
await this.writeCacheNow();
|
|
350
|
+
}
|
|
351
|
+
catch (error) {
|
|
352
|
+
const rollback = table[target];
|
|
353
|
+
if (rollback) {
|
|
354
|
+
rollback[rating] -= 1;
|
|
355
|
+
if (note !== undefined) {
|
|
356
|
+
// F-324 / V4-41: revert the note only when THIS call's note is still
|
|
357
|
+
// the current one — a concurrent record() that landed a newer note
|
|
358
|
+
// must not be clobbered by this failed append's rollback. Revert to
|
|
359
|
+
// the last CONFIRMED note (`durableNote`), never to the in-memory
|
|
360
|
+
// `previousNote`: the old code captured the pre-call in-memory note,
|
|
361
|
+
// and after an A/B double failure that value was itself an
|
|
362
|
+
// unpersisted optimistic note ('A'), so it resurrected a note the
|
|
363
|
+
// log never held. The log is the truth; since PLAN S1.4 a later
|
|
364
|
+
// restore folds a settled target from the truth, so a stale
|
|
365
|
+
// optimistic note self-heals there — but the rollback must still be
|
|
366
|
+
// correct on its own (score()/quality read the live state before
|
|
367
|
+
// any restore runs).
|
|
368
|
+
if (rollback.lastNote === note) {
|
|
369
|
+
const durable = this.durableNote.get(this.noteKey(mode, target));
|
|
370
|
+
if (durable === undefined)
|
|
371
|
+
delete rollback.lastNote;
|
|
372
|
+
else
|
|
373
|
+
rollback.lastNote = durable;
|
|
374
|
+
}
|
|
375
|
+
}
|
|
376
|
+
}
|
|
377
|
+
// Best-effort (V4-50): the rollback keeps memory aligned with the log
|
|
378
|
+
// truth; a persistence failure must not throw, but the reject is no
|
|
379
|
+
// longer SILENT — the injected warn channel observes it (V5-32: once
|
|
380
|
+
// per unique message).
|
|
381
|
+
const message = `evolution-feedback: failed to append feedback event for ${kind} "${target}": ${error instanceof Error ? error.message : String(error)}`;
|
|
382
|
+
// V5-32: dedupe by the FAILURE CAUSE (not the target-bearing message) —
|
|
383
|
+
// a persistent refusal like a version mismatch must not spam on every
|
|
384
|
+
// user entry, regardless of which target triggered it.
|
|
385
|
+
const cause = error instanceof Error ? error.message : String(error);
|
|
386
|
+
if (!this.warnedMessages.has(cause)) {
|
|
387
|
+
if (this.warnedMessages.size >= this.WARNED_CAP) {
|
|
388
|
+
const oldest = this.warnedMessages.values().next().value;
|
|
389
|
+
if (oldest !== undefined)
|
|
390
|
+
this.warnedMessages.delete(oldest);
|
|
391
|
+
}
|
|
392
|
+
this.warnedMessages.add(cause);
|
|
393
|
+
this.warn(message);
|
|
394
|
+
}
|
|
395
|
+
// V5-29: the rollback changed the score / note — derived state (the
|
|
396
|
+
// skill-usage quality channel) must be re-pushed, else it keeps the
|
|
397
|
+
// optimistic value indefinitely.
|
|
398
|
+
if (rollback)
|
|
399
|
+
this.onRollback?.(target, kind);
|
|
400
|
+
}
|
|
401
|
+
finally {
|
|
402
|
+
// PLAN S1.4: THIS append has settled (landed, or rolled back to the
|
|
403
|
+
// durable values). The protection ends only when the LAST in-flight
|
|
404
|
+
// append for the target settles (review C-P2-1) — a merge between two
|
|
405
|
+
// appends must still see the target pending. Later merges fold a settled
|
|
406
|
+
// target from the truth, which is consistent with either outcome.
|
|
407
|
+
const remaining = (pending.get(target) ?? 1) - 1;
|
|
408
|
+
if (remaining > 0)
|
|
409
|
+
pending.set(target, remaining);
|
|
410
|
+
else
|
|
411
|
+
pending.delete(target);
|
|
412
|
+
}
|
|
413
|
+
});
|
|
414
|
+
}
|
|
415
|
+
score(target, kind = 'session') {
|
|
416
|
+
const table = kind === 'skill' ? this.state.skills : this.state.sessions;
|
|
417
|
+
const record = table[target];
|
|
418
|
+
if (!record)
|
|
419
|
+
return 0;
|
|
420
|
+
const total = record.positive + record.negative;
|
|
421
|
+
if (total === 0)
|
|
422
|
+
return 0;
|
|
423
|
+
return (record.positive - record.negative) / total;
|
|
424
|
+
}
|
|
425
|
+
/**
|
|
426
|
+
* Deep-copy view of the live aggregate.
|
|
427
|
+
*
|
|
428
|
+
* OPT-26 (2026-09): `@internal` — test-support API, NO production consumer
|
|
429
|
+
* in the family (mirrors the explicit posture of evolution-replay's
|
|
430
|
+
* `plansSnapshot()`). External consumers should read the rendered
|
|
431
|
+
* score/warn surfaces instead of relying on this shape.
|
|
432
|
+
*/
|
|
433
|
+
snapshot() {
|
|
434
|
+
// P3 (v15): deep-enough copy — the records themselves are copied too, so
|
|
435
|
+
// a consumer mutating a snapshot record can no longer poison the live
|
|
436
|
+
// state (the old shape shared record objects with the live aggregate).
|
|
437
|
+
const copyRecords = (table) => {
|
|
438
|
+
const out = {};
|
|
439
|
+
for (const [key, record] of Object.entries(table))
|
|
440
|
+
out[key] = { ...record };
|
|
441
|
+
return out;
|
|
442
|
+
};
|
|
443
|
+
return { skills: copyRecords(this.state.skills), sessions: copyRecords(this.state.sessions) };
|
|
444
|
+
}
|
|
445
|
+
/** Await the pending record-task chain (unload safety; rc.66). */
|
|
446
|
+
waitIdle() {
|
|
447
|
+
return this.chain;
|
|
448
|
+
}
|
|
449
|
+
/** Snapshot the boot cache from the log truth (rc.68/rc.72); best-effort. */
|
|
450
|
+
async writeCacheNow() {
|
|
451
|
+
const path = this.path;
|
|
452
|
+
const eventsPath = this.eventsPath;
|
|
453
|
+
const recordIo = this.io;
|
|
454
|
+
if (!path || !eventsPath || !recordIo)
|
|
455
|
+
return;
|
|
456
|
+
try {
|
|
457
|
+
const { events, malformed } = await readEvolutionTimeline(recordIo, eventsPath);
|
|
458
|
+
// P2-13 (audit): with archives present but the ACTIVE log transiently
|
|
459
|
+
// absent (another process is inside its commitTmp rename on Windows),
|
|
460
|
+
// the fold above answered clean-empty for the active band and `maxSeq`
|
|
461
|
+
// below would advance past records this read never saw — the cache
|
|
462
|
+
// then seals the loss until the next full refold. Withhold the write
|
|
463
|
+
// for that window; the next tick refolds with the band back in place.
|
|
464
|
+
// N36: three-state. Withholding the write is the SAFE answer for an unreadable ACTIVE log too
|
|
465
|
+
// (the next tick refolds), so both non-present states withhold — and the unknown one says why
|
|
466
|
+
// instead of reporting as the transient-absence window this guard exists for.
|
|
467
|
+
if (events.length > 0) {
|
|
468
|
+
const activeProbe = await probeText(recordIo, eventsPath);
|
|
469
|
+
if (!isPresent(activeProbe)) {
|
|
470
|
+
if (isUnknown(activeProbe))
|
|
471
|
+
this.warnOnce(`evolution-feedback: the active event log ${eventsPath} could not be read (${activeProbe.reason}); withholding the cache write until it can be read`);
|
|
472
|
+
return;
|
|
473
|
+
}
|
|
474
|
+
}
|
|
475
|
+
// C-events-dispatch-1 (v43): this is the SECOND cache writer (cadence
|
|
476
|
+
// snapshot + the unload `persistCache`), and a truncated read here advanced
|
|
477
|
+
// `lastSeq` to the surviving max exactly like the restore write did — the
|
|
478
|
+
// same withhold applies, with the same warn.
|
|
479
|
+
if (malformed) {
|
|
480
|
+
this.warnOnce(TRUNCATED_TIMELINE_WARN);
|
|
481
|
+
return;
|
|
482
|
+
}
|
|
483
|
+
const maxSeq = events.reduce((max, event) => Math.max(max, event.seq), 0);
|
|
484
|
+
if (maxSeq === 0)
|
|
485
|
+
return;
|
|
486
|
+
// P1-7 (v37): the read side accepts `lastSeq >= floor - 1` as "this cache
|
|
487
|
+
// carries the band the log no longer holds", so a window-only fold stamped
|
|
488
|
+
// with `maxSeq` would erase that band and seal the loss. Fold the delta.
|
|
489
|
+
let rawCache;
|
|
490
|
+
try {
|
|
491
|
+
rawCache = await recordIo.readText(path);
|
|
492
|
+
}
|
|
493
|
+
catch {
|
|
494
|
+
// A failed cache read is NOT an absent cache — folding from zero would
|
|
495
|
+
// erase the band it carries. Skip the refresh (fail-closed).
|
|
496
|
+
return;
|
|
497
|
+
}
|
|
498
|
+
const cache = parseCache(rawCache, this.warn);
|
|
499
|
+
const floor = events[0]?.seq ?? 0;
|
|
500
|
+
const state = cache && cache.lastSeq >= floor - 1 ? foldWithDelta(cache, events, this.warn) : foldFeedbackState(events, this.warn);
|
|
501
|
+
const body = JSON.stringify({ version: CACHE_VERSION, lastSeq: maxSeq, ...state }, null, 2);
|
|
502
|
+
await recordIo.writeText(path, body);
|
|
503
|
+
}
|
|
504
|
+
catch {
|
|
505
|
+
// Best-effort: the cache is disposable.
|
|
506
|
+
}
|
|
507
|
+
}
|
|
508
|
+
/** Rebuild the boot cache from the log truth (rc.68); best-effort, queued
|
|
509
|
+
* on the record chain so it runs after the pending appends. */
|
|
510
|
+
persistCache() {
|
|
511
|
+
return this.mutate(async () => {
|
|
512
|
+
await this.writeCacheNow();
|
|
513
|
+
});
|
|
514
|
+
}
|
|
515
|
+
}
|
|
516
|
+
/** Semantic identity of one event: `seq` and `at` are excluded (a merge
|
|
517
|
+
* shifts seqs, a re-synthesis stamps a different `at`), so type/kind/target/
|
|
518
|
+
* rating/note is everything a fold can see. */
|
|
519
|
+
function sameSemantics(a, b) {
|
|
520
|
+
return a.type === b.type && a.kind === b.kind && a.target === b.target && a.rating === b.rating && a.note === b.note;
|
|
521
|
+
}
|
|
522
|
+
/** True when `existing` already carries the WHOLE legacy batch (the skip case).
|
|
523
|
+
* P1-8 (v37): counted as a MULTISET, never as a contiguous run — the
|
|
524
|
+
* synthesizer emits "all positives, then all negatives" per target while the
|
|
525
|
+
* real log is in temporal order, so the run-based gate read an already-migrated
|
|
526
|
+
* log as unmigrated and re-appended the whole history (3 events became 6, and
|
|
527
|
+
* every further boot doubled it again). */
|
|
528
|
+
function containsLegacyMultiset(existing, expected) {
|
|
529
|
+
if (expected.length === 0)
|
|
530
|
+
return true;
|
|
531
|
+
const pool = [...existing];
|
|
532
|
+
for (const event of expected) {
|
|
533
|
+
const at = pool.findIndex(candidate => sameSemantics(candidate, event));
|
|
534
|
+
if (at < 0)
|
|
535
|
+
return false;
|
|
536
|
+
pool.splice(at, 1);
|
|
537
|
+
}
|
|
538
|
+
return true;
|
|
539
|
+
}
|
|
540
|
+
/** True when the body the migration transact just read may be written over:
|
|
541
|
+
* absent or blank (the append path's own "missing" definition), or a v1 body
|
|
542
|
+
* this reader can actually interpret. `parseEvolutionEvents` maps a corrupt or
|
|
543
|
+
* future-version body to an EMPTY timeline, so without this gate a read failure
|
|
544
|
+
* would be folded as "nothing was ever migrated" and the synthesized log would
|
|
545
|
+
* overwrite bytes the append path refuses to touch. */
|
|
546
|
+
function isReadableEventBody(current) {
|
|
547
|
+
if (current === null || current.trim() === '')
|
|
548
|
+
return true;
|
|
549
|
+
try {
|
|
550
|
+
const parsed = JSON.parse(current);
|
|
551
|
+
if (!isRecord(parsed))
|
|
552
|
+
return false;
|
|
553
|
+
if (parsed.version !== undefined && parsed.version !== EVENT_LOG_VERSION)
|
|
554
|
+
return false;
|
|
555
|
+
return Array.isArray(parsed.events);
|
|
556
|
+
}
|
|
557
|
+
catch {
|
|
558
|
+
return false;
|
|
559
|
+
}
|
|
560
|
+
}
|
|
561
|
+
/**
|
|
562
|
+
* Merge a legacy aggregate into the event log (rc.69): the expected synthetic
|
|
563
|
+
* sequence is APPENDED (seq-shifted) when the log does not already contain it
|
|
564
|
+
* — so a concurrent first writer's events AND the legacy history both
|
|
565
|
+
* survive; when the sequence is already present the migration was completed
|
|
566
|
+
* (by a first writer or by this path) and nothing is re-appended. Idempotent
|
|
567
|
+
* and race-safe (the search runs inside the same transact). Exported for the
|
|
568
|
+
* migration-race regression test.
|
|
569
|
+
*/
|
|
570
|
+
export async function migrateFeedbackEvents(io, eventsPath, aggregate, warn = () => { }, fence) {
|
|
571
|
+
const expected = synthesizeFeedbackEvents(aggregate);
|
|
572
|
+
// v35 R5: this is the event log's SECOND writer, and it used to serialize the
|
|
573
|
+
// synthesized batch straight to disk — bypassing the durable-boundary payload
|
|
574
|
+
// gate every live append runs (evolution-events: appendEvolutionEvent). The
|
|
575
|
+
// synthesizer feeds off a sanitized aggregate, so a violation means the two
|
|
576
|
+
// halves drifted apart; refuse the WHOLE batch (never a half-written log) and
|
|
577
|
+
// say so, so the drift is visible instead of silently durable.
|
|
578
|
+
const refused = expected.filter(event => evolutionEventPayloadIssue(event) !== null);
|
|
579
|
+
if (refused.length > 0) {
|
|
580
|
+
warn(`evolution-feedback: migration refused ${refused.length} synthesized event(s) that the event log's payload gate rejects (types: ${[...new Set(refused.map(event => event.type))].join(', ')}) — history starts empty instead of writing an unreadable log`);
|
|
581
|
+
return;
|
|
582
|
+
}
|
|
583
|
+
const write = async () => {
|
|
584
|
+
await transactIo(io, eventsPath, (current) => {
|
|
585
|
+
// P1-8 (v37): the gate reads the content INSIDE the transact — a lockless
|
|
586
|
+
// read outside it can report a just-committed log as missing, and the
|
|
587
|
+
// migration must never translate that read into a write.
|
|
588
|
+
if (!isReadableEventBody(current)) {
|
|
589
|
+
warn('evolution-feedback: migration left unreadable event-log bytes untouched (neither migrated nor overwritten)');
|
|
590
|
+
return Promise.resolve(current);
|
|
591
|
+
}
|
|
592
|
+
const existing = parseEvolutionEvents(current);
|
|
593
|
+
// Skip = hand back `current` untouched: null means "no file" in the
|
|
594
|
+
// transact contract, so an empty legacy aggregate never creates one
|
|
595
|
+
// (rc.70 F-4).
|
|
596
|
+
if (containsLegacyMultiset(existing, expected))
|
|
597
|
+
return Promise.resolve(current);
|
|
598
|
+
const maxSeq = existing.reduce((max, event) => Math.max(max, event.seq), 0);
|
|
599
|
+
const merged = [...existing, ...expected.map((event, index) => ({ ...event, seq: maxSeq + index + 1 }))];
|
|
600
|
+
return Promise.resolve(JSON.stringify({ version: EVENT_LOG_VERSION, events: merged }, null, 2));
|
|
601
|
+
});
|
|
602
|
+
};
|
|
603
|
+
if (fence !== undefined)
|
|
604
|
+
await fence.run(write);
|
|
605
|
+
else
|
|
606
|
+
await write();
|
|
607
|
+
}
|
|
608
|
+
/** Parse a legacy aggregate (v1) or a v2 cache into a plain aggregate state.
|
|
609
|
+
* V24-05 (v24): every record passes the shared per-record sanitizer (same
|
|
610
|
+
* validation as `parseCache` — S6.4), and migrated counts are clamped so one
|
|
611
|
+
* corrupted field cannot expand into an unbounded event array at boot. */
|
|
612
|
+
const MAX_MIGRATED_EVENTS_PER_RECORD = 10_000;
|
|
613
|
+
function parseAggregate(raw, warn = () => { }) {
|
|
614
|
+
if (raw === null)
|
|
615
|
+
return null;
|
|
616
|
+
try {
|
|
617
|
+
const parsed = JSON.parse(raw);
|
|
618
|
+
const clamp = (count, target, field) => {
|
|
619
|
+
if (count > MAX_MIGRATED_EVENTS_PER_RECORD) {
|
|
620
|
+
warn(`evolution-feedback: migration clamps ${field}=${count} for "${target}" to ${MAX_MIGRATED_EVENTS_PER_RECORD} — the on-disk aggregate is not trustworthy at that scale`);
|
|
621
|
+
return MAX_MIGRATED_EVENTS_PER_RECORD;
|
|
622
|
+
}
|
|
623
|
+
return count;
|
|
624
|
+
};
|
|
625
|
+
const sanitizeSection = (section, kind) => {
|
|
626
|
+
if (!isRecord(section))
|
|
627
|
+
return undefined;
|
|
628
|
+
const cleaned = sanitizeCacheRecords(section, kind, warn);
|
|
629
|
+
for (const [target, record] of Object.entries(cleaned)) {
|
|
630
|
+
if (record.positive > MAX_MIGRATED_EVENTS_PER_RECORD || record.negative > MAX_MIGRATED_EVENTS_PER_RECORD) {
|
|
631
|
+
cleaned[target] = {
|
|
632
|
+
...record,
|
|
633
|
+
positive: clamp(record.positive, target, 'positive'),
|
|
634
|
+
negative: clamp(record.negative, target, 'negative'),
|
|
635
|
+
};
|
|
636
|
+
}
|
|
637
|
+
}
|
|
638
|
+
return cleaned;
|
|
639
|
+
};
|
|
640
|
+
const skills = sanitizeSection(parsed.skills, 'skill');
|
|
641
|
+
const sessions = sanitizeSection(parsed.sessions, 'session');
|
|
642
|
+
if (!skills && !sessions)
|
|
643
|
+
return null;
|
|
644
|
+
return { skills: skills ?? {}, sessions: sessions ?? {} };
|
|
645
|
+
}
|
|
646
|
+
catch {
|
|
647
|
+
return null;
|
|
648
|
+
}
|
|
649
|
+
}
|
|
650
|
+
function parseCache(raw, warn = () => { }) {
|
|
651
|
+
if (raw === null)
|
|
652
|
+
return null;
|
|
653
|
+
try {
|
|
654
|
+
const parsed = JSON.parse(raw);
|
|
655
|
+
if (parsed.version !== CACHE_VERSION || typeof parsed.lastSeq !== 'number' || !Number.isFinite(parsed.lastSeq))
|
|
656
|
+
return null;
|
|
657
|
+
if (!isRecord(parsed.skills) || !isRecord(parsed.sessions))
|
|
658
|
+
return null;
|
|
659
|
+
return {
|
|
660
|
+
lastSeq: parsed.lastSeq,
|
|
661
|
+
state: {
|
|
662
|
+
skills: sanitizeCacheRecords(parsed.skills, 'skill', warn),
|
|
663
|
+
sessions: sanitizeCacheRecords(parsed.sessions, 'session', warn),
|
|
664
|
+
},
|
|
665
|
+
};
|
|
666
|
+
}
|
|
667
|
+
catch {
|
|
668
|
+
return null;
|
|
669
|
+
}
|
|
670
|
+
}
|
|
671
|
+
/** Per-record numeric-domain validation (S6.4): a record whose `positive` or
|
|
672
|
+
* `negative` is not a finite number >= 0, or whose `lastNote` is not a string,
|
|
673
|
+
* would fold as NaN into the usage aggregate — skip it with a warn instead of
|
|
674
|
+
* corrupting the state. A record with no valid count is dropped entirely.
|
|
675
|
+
* OPT-25 (2026-09): a count ABOVE `MAX_MIGRATED_EVENTS_PER_RECORD` is now
|
|
676
|
+
* CLAMPED here with a warn, symmetric with the migration reader's clamp (same
|
|
677
|
+
* file, same threat model — V24-05 covered the migration side only). Before,
|
|
678
|
+
* a poisoned boot-cache count folded as-is into every downstream decision;
|
|
679
|
+
* the clamp bounds the skew to the same ceiling migration accepts. */
|
|
680
|
+
function sanitizeCacheRecords(input, kind, warn) {
|
|
681
|
+
const out = {};
|
|
682
|
+
for (const [target, value] of Object.entries(input)) {
|
|
683
|
+
const record = sanitizeFeedbackRecord(value, target, kind, warn);
|
|
684
|
+
if (record) {
|
|
685
|
+
let clamped;
|
|
686
|
+
if (record.positive > MAX_MIGRATED_EVENTS_PER_RECORD || record.negative > MAX_MIGRATED_EVENTS_PER_RECORD) {
|
|
687
|
+
warn(`evolution-feedback: cache record for ${kind} "${target}" exceeds the clamp ceiling (${MAX_MIGRATED_EVENTS_PER_RECORD}) — clamping like the migration reader`);
|
|
688
|
+
clamped = {
|
|
689
|
+
positive: Math.min(record.positive, MAX_MIGRATED_EVENTS_PER_RECORD),
|
|
690
|
+
negative: Math.min(record.negative, MAX_MIGRATED_EVENTS_PER_RECORD),
|
|
691
|
+
...(record.lastNote !== undefined ? { lastNote: record.lastNote } : {}),
|
|
692
|
+
};
|
|
693
|
+
}
|
|
694
|
+
out[target] = clamped ?? record;
|
|
695
|
+
}
|
|
696
|
+
}
|
|
697
|
+
return out;
|
|
698
|
+
}
|
|
699
|
+
function sanitizeFeedbackRecord(value, target, kind, warn) {
|
|
700
|
+
if (!isRecord(value)) {
|
|
701
|
+
warn(`evolution-feedback: skipping cache record for ${kind} "${target}": not a record`);
|
|
702
|
+
return null;
|
|
703
|
+
}
|
|
704
|
+
const positive = value.positive;
|
|
705
|
+
const negative = value.negative;
|
|
706
|
+
const note = value.lastNote;
|
|
707
|
+
const validCount = (n) => typeof n === 'number' && Number.isFinite(n) && n >= 0;
|
|
708
|
+
if (!validCount(positive) || !validCount(negative)) {
|
|
709
|
+
warn(`evolution-feedback: skipping cache record for ${kind} "${target}": positive/negative must be finite numbers >= 0`);
|
|
710
|
+
return null;
|
|
711
|
+
}
|
|
712
|
+
if (note !== undefined && typeof note !== 'string') {
|
|
713
|
+
warn(`evolution-feedback: skipping cache record for ${kind} "${target}": lastNote must be a string`);
|
|
714
|
+
return null;
|
|
715
|
+
}
|
|
716
|
+
return { positive, negative, ...(note !== undefined ? { lastNote: note } : {}) };
|
|
717
|
+
}
|
|
718
|
+
/** Fold all feedback events from zero (the truth view). */
|
|
719
|
+
function foldFeedbackState(events, warn = () => { }) {
|
|
720
|
+
const state = { skills: {}, sessions: {} };
|
|
721
|
+
for (const event of events)
|
|
722
|
+
applyFeedbackEvent(state, event, warn);
|
|
723
|
+
return state;
|
|
724
|
+
}
|
|
725
|
+
/** Fold events after the cache's lastSeq onto the cached aggregates. */
|
|
726
|
+
function foldWithDelta(cache, events, warn = () => { }) {
|
|
727
|
+
const state = {
|
|
728
|
+
skills: { ...cache.state.skills },
|
|
729
|
+
sessions: { ...cache.state.sessions },
|
|
730
|
+
};
|
|
731
|
+
for (const event of events) {
|
|
732
|
+
if (event.seq > cache.lastSeq)
|
|
733
|
+
applyFeedbackEvent(state, event, warn);
|
|
734
|
+
}
|
|
735
|
+
return state;
|
|
736
|
+
}
|
|
737
|
+
function applyFeedbackEvent(state, event, warn = () => { }) {
|
|
738
|
+
if (event.type !== 'feedback')
|
|
739
|
+
return;
|
|
740
|
+
// B-5 (v18): an invalid/missing kind used to fold into sessions. Skip it
|
|
741
|
+
// with a warn so a malformed log cannot silently mis-attribute feedback.
|
|
742
|
+
if (event.kind !== 'skill' && event.kind !== 'session') {
|
|
743
|
+
warn(`evolution-feedback: skipping feedback event with invalid kind: ${String(event.kind)}`);
|
|
744
|
+
return;
|
|
745
|
+
}
|
|
746
|
+
// S6.4: only 'positive'/'negative' are valid ratings. Any other value
|
|
747
|
+
// (NaN or an arbitrary string from a malformed log) would fold
|
|
748
|
+
// `record[value] += 1` as NaN into the usage aggregate, so skip with a warn.
|
|
749
|
+
if (event.rating !== 'positive' && event.rating !== 'negative') {
|
|
750
|
+
warn(`evolution-feedback: skipping feedback event with invalid rating: ${String(event.rating)}`);
|
|
751
|
+
return;
|
|
752
|
+
}
|
|
753
|
+
const target = event.target;
|
|
754
|
+
if (target === undefined)
|
|
755
|
+
return;
|
|
756
|
+
const table = event.kind === 'skill' ? state.skills : state.sessions;
|
|
757
|
+
const record = table[target] ?? { positive: 0, negative: 0 };
|
|
758
|
+
record[event.rating] += 1;
|
|
759
|
+
if (event.note !== undefined)
|
|
760
|
+
record.lastNote = event.note;
|
|
761
|
+
table[target] = record;
|
|
762
|
+
}
|
|
763
|
+
/** Synthesize one event per aggregate count unit, lastNote on the final event
|
|
764
|
+
* (migration). A zero-count record still carrying a lastNote would otherwise
|
|
765
|
+
* drop the note — emit a dedicated note event (S6.4) so it survives. */
|
|
766
|
+
function synthesizeFeedbackEvents(aggregate) {
|
|
767
|
+
const events = [];
|
|
768
|
+
const at = new Date().toISOString();
|
|
769
|
+
const emitTarget = (kind, target, record) => {
|
|
770
|
+
const first = events.length + 1;
|
|
771
|
+
for (let index = 0; index < record.positive; index += 1) {
|
|
772
|
+
events.push({ seq: events.length + 1, at, type: 'feedback', kind, target, rating: 'positive' });
|
|
773
|
+
}
|
|
774
|
+
for (let index = 0; index < record.negative; index += 1) {
|
|
775
|
+
events.push({ seq: events.length + 1, at, type: 'feedback', kind, target, rating: 'negative' });
|
|
776
|
+
}
|
|
777
|
+
if (record.lastNote !== undefined) {
|
|
778
|
+
if (events.length >= first) {
|
|
779
|
+
const last = events.length - 1;
|
|
780
|
+
const final = events[last];
|
|
781
|
+
if (final)
|
|
782
|
+
events[last] = { ...final, note: record.lastNote };
|
|
783
|
+
}
|
|
784
|
+
else {
|
|
785
|
+
// Zero-count record with a note (legacy migration, F-325). The event
|
|
786
|
+
// model only folds a note via a rated feedback event, so the note is
|
|
787
|
+
// preserved as a single `positive` event. DELIBERATE side effect: this
|
|
788
|
+
// bumps the skill's positive count by one even though the record had no
|
|
789
|
+
// count — the note is kept at the price of a synthetic positive. A
|
|
790
|
+
// bare `note` event type has no aggregation semantics, so this is the
|
|
791
|
+
// chosen tradeoff (the old changelog wording "independent note event"
|
|
792
|
+
// understated that it changes count; the count change is intended).
|
|
793
|
+
events.push({ seq: events.length + 1, at, type: 'feedback', kind, target, rating: 'positive', note: record.lastNote });
|
|
794
|
+
}
|
|
795
|
+
}
|
|
796
|
+
};
|
|
797
|
+
for (const [target, record] of Object.entries(aggregate.skills))
|
|
798
|
+
emitTarget('skill', target, record);
|
|
799
|
+
for (const [target, record] of Object.entries(aggregate.sessions))
|
|
800
|
+
emitTarget('session', target, record);
|
|
801
|
+
return events;
|
|
802
|
+
}
|
|
803
|
+
export const name = 'evolution-feedback';
|
|
804
|
+
export const Config = z.object({
|
|
805
|
+
qualityWarnThreshold: z.number().min(-1).max(1).default(-0.25),
|
|
806
|
+
path: z.string().default(''),
|
|
807
|
+
});
|
|
808
|
+
/** Resolve the effective quality warn threshold, clamped to its [-1, 1] domain
|
|
809
|
+
* (G3.1). 0 and negative values are legal (a lower threshold is stricter); NaN,
|
|
810
|
+
* ±Infinity and out-of-range values fall back to the default -0.25. Exported so
|
|
811
|
+
* the clamp is directly testable; `apply` warns when a value was corrected. */
|
|
812
|
+
export function resolveQualityWarnThreshold(config) {
|
|
813
|
+
return clampedNumber(config.qualityWarnThreshold ?? -0.25, -0.25, { min: -1, max: 1 });
|
|
814
|
+
}
|
|
815
|
+
export function apply(ctx, rawConfig = {}) {
|
|
816
|
+
// G3.1 (0.3.23): clamp the quality threshold to its [-1, 1] domain. A NaN or
|
|
817
|
+
// ±Infinity (which `z.number()` lets through) would make every `warn`
|
|
818
|
+
// comparison wrong; a value outside [-1, 1] is out of domain. 0 is valid
|
|
819
|
+
// (a neutral/lenient threshold) — only out-of-range/non-finite falls back.
|
|
820
|
+
const configuredThreshold = rawConfig.qualityWarnThreshold ?? -0.25;
|
|
821
|
+
const qualityWarnThreshold = resolveQualityWarnThreshold(rawConfig);
|
|
822
|
+
if (qualityWarnThreshold !== configuredThreshold) {
|
|
823
|
+
ctx.logger.warn(`evolution-feedback: qualityWarnThreshold=${String(configuredThreshold)} is invalid; falling back to the default -0.25`);
|
|
824
|
+
}
|
|
825
|
+
// Deferred binding (S6.4, tool-* pattern): the feedback service is provided
|
|
826
|
+
// with no backend first; evolutionIo/skillUsage wire themselves once the
|
|
827
|
+
// providers mount. Apply-time `ctx.get` probes were startup-order sensitive —
|
|
828
|
+
// a provider registered after this plugin was skipped entirely.
|
|
829
|
+
const feedback = new EvolutionFeedback(undefined, evolutionRoot(),
|
|
830
|
+
// V6-39 (0.3.35): a whitespace-only `path` was truthy and resolved to a
|
|
831
|
+
// CWD-relative file — trim like resolveSkillsRoot/state-json (V5-11);
|
|
832
|
+
// empty/whitespace both fall through to the default path.
|
|
833
|
+
(rawConfig.path ?? '').trim() || undefined, (message) => {
|
|
834
|
+
ctx.logger.warn(message);
|
|
835
|
+
}, ctx.get('evolutionMutationAuthority')?.homeFence);
|
|
836
|
+
// Make the service available first; restoration settles in the background.
|
|
837
|
+
ctx.provide('evolutionFeedback', feedback);
|
|
838
|
+
ctx.inject(['evolutionIo'], (ioCtx) => {
|
|
839
|
+
// G2 S3 migration: prefer the platform backend when the deployment mounts one (this consumer both
|
|
840
|
+
// reads on restore and writes through transact), else the default backend.
|
|
841
|
+
const ioRegistry = ioCtx.evolutionIo;
|
|
842
|
+
const io = evolutionIoAdapter(() => ioRegistry.provider());
|
|
843
|
+
feedback.attachIo(io);
|
|
844
|
+
void feedback.restore(io).catch((error) => {
|
|
845
|
+
ioCtx.logger.warn(error);
|
|
846
|
+
});
|
|
847
|
+
});
|
|
848
|
+
const baseRecord = feedback.record.bind(feedback);
|
|
849
|
+
// V6-40 (0.3.35): no one-time flag. `ctx.inject` re-runs this callback
|
|
850
|
+
// whenever the skillUsage dependency is REPLACED (its provider fiber id
|
|
851
|
+
// changes — e.g. an unload/re-mount), so a stale pushQuality bound to an
|
|
852
|
+
// unloaded instance must re-wire to the new one. Re-wrapping
|
|
853
|
+
// `feedback.record` over `baseRecord` (and reassigning `onRollback`) is
|
|
854
|
+
// idempotent — assignments replace, never stack.
|
|
855
|
+
ctx.inject(['skillUsage'], (skillCtx) => {
|
|
856
|
+
const skillUsage = skillCtx.skillUsage;
|
|
857
|
+
const pushQuality = (target, kind) => {
|
|
858
|
+
if (kind !== 'skill')
|
|
859
|
+
return;
|
|
860
|
+
// PLAN S4.6 (2026-09-16, audit P2-20): no mounted io → no durable push.
|
|
861
|
+
// Without this gate the optimistic in-memory score flowed into the
|
|
862
|
+
// PERSISTENT usage sidecar (`setFeedbackQuality`) even though no event
|
|
863
|
+
// append could ever confirm it, and nothing reconciled the sidecar
|
|
864
|
+
// field after a restart — against the file-header contract "Feedback is
|
|
865
|
+
// durable through ctx.evolutionIo (when mounted)". The onRollback
|
|
866
|
+
// re-push below rides the same gate harmlessly: without io no append
|
|
867
|
+
// can happen, so a rollback never fires.
|
|
868
|
+
if (!feedback.durable)
|
|
869
|
+
return;
|
|
870
|
+
// v30 FB-01: refold the shared log first so the absolute pair is
|
|
871
|
+
// computed from the CURRENT truth, not this process's mount-time
|
|
872
|
+
// aggregate (multi-process DSH_HOME overwrote a live warn with a stale
|
|
873
|
+
// value). Failures degrade to the previous behavior with a warn.
|
|
874
|
+
void feedback.refold()
|
|
875
|
+
.then(() => {
|
|
876
|
+
const score = feedback.score(target, 'skill');
|
|
877
|
+
const warn = score < qualityWarnThreshold;
|
|
878
|
+
return skillUsage.setFeedbackQuality(target, score, warn);
|
|
879
|
+
})
|
|
880
|
+
.catch((error) => {
|
|
881
|
+
skillCtx.logger.warn(error);
|
|
882
|
+
});
|
|
883
|
+
};
|
|
884
|
+
// V5-29: a failed append rolls the memory count/note back — re-push the
|
|
885
|
+
// derived quality so the usage side never keeps an unpersisted score.
|
|
886
|
+
feedback.onRollback = (target, kind) => { pushQuality(target, kind); };
|
|
887
|
+
feedback.record = (target, rating, note, kind) => {
|
|
888
|
+
baseRecord(target, rating, note, kind ?? 'session');
|
|
889
|
+
pushQuality(target, kind ?? 'session');
|
|
890
|
+
};
|
|
891
|
+
});
|
|
892
|
+
ctx.effect(() => () => {
|
|
893
|
+
// rc.68: the event log is the only durable write, but the boot cache is
|
|
894
|
+
// refreshed from the log truth at unload — plus the rc.66 waitIdle for
|
|
895
|
+
// pending appends so a slow CI cannot remove a file mid-write.
|
|
896
|
+
return Promise.all([feedback.persistCache(), feedback.waitIdle()]);
|
|
897
|
+
}, 'evolution-feedback.records');
|
|
898
|
+
}
|
|
899
|
+
//# sourceMappingURL=index.js.map
|