@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.
Files changed (47) hide show
  1. package/lib/feedback/index.js +690 -0
  2. package/lib/index.js +23 -18
  3. package/lib/learning-graph/index.js +538 -0
  4. package/lib/replay/index.js +286 -0
  5. package/lib/threat/index.js +70 -0
  6. package/lib/types/feedback/index.d.ts +179 -0
  7. package/lib/types/feedback/index.js +899 -0
  8. package/lib/types/index.js +335 -0
  9. package/lib/types/learning-graph/index.d.ts +178 -0
  10. package/lib/types/learning-graph/index.js +712 -0
  11. package/lib/types/replay/index.d.ts +182 -0
  12. package/lib/types/replay/index.js +404 -0
  13. package/lib/types/threat/index.d.ts +35 -0
  14. package/lib/types/threat/index.js +119 -0
  15. package/locale/feedback/de.json +6 -0
  16. package/locale/feedback/en.json +6 -0
  17. package/locale/feedback/es.json +6 -0
  18. package/locale/feedback/fr.json +6 -0
  19. package/locale/feedback/ja.json +6 -0
  20. package/locale/feedback/pt.json +6 -0
  21. package/locale/feedback/ru.json +6 -0
  22. package/locale/feedback/zh.json +6 -0
  23. package/locale/learning-graph/de.json +6 -0
  24. package/locale/learning-graph/en.json +6 -0
  25. package/locale/learning-graph/es.json +6 -0
  26. package/locale/learning-graph/fr.json +6 -0
  27. package/locale/learning-graph/ja.json +6 -0
  28. package/locale/learning-graph/pt.json +6 -0
  29. package/locale/learning-graph/ru.json +6 -0
  30. package/locale/learning-graph/zh.json +6 -0
  31. package/locale/replay/de.json +6 -0
  32. package/locale/replay/en.json +6 -0
  33. package/locale/replay/es.json +6 -0
  34. package/locale/replay/fr.json +6 -0
  35. package/locale/replay/ja.json +6 -0
  36. package/locale/replay/pt.json +6 -0
  37. package/locale/replay/ru.json +6 -0
  38. package/locale/replay/zh.json +6 -0
  39. package/locale/threat/de.json +6 -0
  40. package/locale/threat/en.json +6 -0
  41. package/locale/threat/es.json +6 -0
  42. package/locale/threat/fr.json +6 -0
  43. package/locale/threat/ja.json +6 -0
  44. package/locale/threat/pt.json +6 -0
  45. package/locale/threat/ru.json +6 -0
  46. package/locale/threat/zh.json +6 -0
  47. package/package.json +30 -8
@@ -0,0 +1,690 @@
1
+ import z from "@deepseek-ai/schemastery";
2
+ import { EVENT_LOG_VERSION, appendEvolutionEvent, clampedNumber, eventsFile, evolutionEventPayloadIssue, evolutionIoAdapter, evolutionRoot, isPresent, isRecord, isUnknown, listEventArchives, parseEvolutionEvents, probeText, readEvolutionTimeline, transactIo } from "@lmzhen/dsh-evolution-core";
3
+ import { join } from "node:path";
4
+ //#region lib/types/feedback/index.js
5
+ /**
6
+ * Feedback-to-quality scoring for self-evolution.
7
+ *
8
+ * Feedback is durable through `ctx.evolutionIo` (when mounted) and skill
9
+ * feedback feeds the FEEDBACK-OWNED `feedback_score` / `feedback_warn` pair on
10
+ * the usage record. P1-1 (v15): this package used to write
11
+ * `quality_score`/`quality_warn` — but the curator's six-factor `scoreTree`
12
+ * overwrote those fields on every run BEFORE the lifecycle engine read them,
13
+ * so the advertised "curator decisions consume feedback deterministically"
14
+ * channel was dead. The lifecycle engine and the scope view now read the
15
+ * union `quality_warn || feedback_warn`, and the curator never writes the
16
+ * feedback pair (field-ownership contract on `UsageRecord` in
17
+ * evolution-core/usage.ts).
18
+ *
19
+ * Persistence (rc.68): the EVENTS LOG (`evolution/events.json`, via
20
+ * `evolution-core/evolution-events.ts`) is the single source of truth —
21
+ * every increment appends one event under the write lock. `feedback.json` is
22
+ * a rebuildable BOOT CACHE (`{ version: 2, lastSeq, skills, sessions }`),
23
+ * never the truth; the in-memory state is the optimistic aggregate.
24
+ * @module @lmzhen/dsh-evolution-feedback
25
+ */
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 reader cannot interpret, e.g. a future version) was dropped, so the folded counts are incomplete; the boot cache was NOT updated (a truncated lastSeq would seal the missing band against every later boot)";
44
+ var EvolutionFeedback = class EvolutionFeedback {
45
+ state = {
46
+ skills: {},
47
+ sessions: {}
48
+ };
49
+ chain = Promise.resolve();
50
+ path;
51
+ eventsPath;
52
+ io;
53
+ warn;
54
+ /** V4-41 (F-324): the last note per target CONFIRMED on the event log. The
55
+ * in-memory `lastNote` is optimistic; a failed append must roll back to this,
56
+ * never to the in-memory `previousNote` (an earlier failed call can leave an
57
+ * unpersisted note there, and reverting to it resurrects a value the log
58
+ * never held). Seeded from the fold truth, updated on successful appends. */
59
+ durableNote = /* @__PURE__ */ new Map();
60
+ /** PLAN S1.4 (2026-09-16): targets with a feedback append still IN FLIGHT,
61
+ * split by table, as a COUNT per target. record() increments before queueing
62
+ * the append and the append task decrements when it settles (landed or rolled
63
+ * back, finally), dropping the entry only at ZERO — the count covers exactly
64
+ * the optimistic window rc.66 meant to protect, including two appends for the
65
+ * same target in flight at once (review C-P2-1: a per-target boolean marker
66
+ * was cleared by the first settle, so a merge between the two appends folded
67
+ * the second append's increment away). restore() lets memory win ONLY for these targets — a settled
68
+ * target folds from the log truth, so another process's feedback for the
69
+ * same target (audit P1-3) is never overwritten by this process's stale
70
+ * record. */
71
+ pendingAppends = {
72
+ skills: /* @__PURE__ */ new Map(),
73
+ sessions: /* @__PURE__ */ new Map()
74
+ };
75
+ /** P2-32 (v11): process-level bound — every feedbacked session would
76
+ * otherwise keep one entry for the whole process lifetime (a name + note
77
+ * string per session); cap this map and drop the earliest-INSERTED entry on
78
+ * overflow (Map iteration order is insertion order, and re-setting an
79
+ * existing key does not refresh its position, so the eviction is FIFO rather
80
+ * than least-recently-used). `warnedMessages` carries the same bound through
81
+ * `WARNED_CAP` below. */
82
+ static NOTE_CAP = 512;
83
+ /** V5-32 (0.3.31): fire-and-forget append failures are warn-once per unique
84
+ * message — a persistent refusal (e.g. a future-version log) must not spam
85
+ * the log on every user feedback entry (family posture: process-level once).
86
+ * Bounded like `durableNote`, with the same FIFO eviction. */
87
+ warnedMessages = /* @__PURE__ */ new Set();
88
+ WARNED_CAP = 512;
89
+ /** V5-29 (0.3.31): invoked after a FAILED append rolled back, so a caller
90
+ * holding derived state (skillUsage quality score) can re-push it instead of
91
+ * keeping an optimistic value that never landed. */
92
+ onRollback;
93
+ fence;
94
+ constructor(io, home = evolutionRoot(), pathOverride, warn = () => {}, fence) {
95
+ this.path = pathOverride ?? join(home, "evolution", "feedback.json");
96
+ this.eventsPath = eventsFile(home);
97
+ this.io = io;
98
+ this.warn = warn;
99
+ this.fence = fence;
100
+ }
101
+ /** Bind the evolution IO backend after construction (S6.4 deferred binding). */
102
+ attachIo(io) {
103
+ this.io = io;
104
+ }
105
+ /** PLAN S4.6 (2026-09-16): whether a durable backend is attached — the
106
+ * plugin's quality push (`apply`) consults this before writing the
107
+ * feedback pair into the skill-usage sidecar. Same no-io posture as
108
+ * `record`/`refold`: without `ctx.evolutionIo` (when mounted) nothing may
109
+ * turn the optimistic in-memory aggregate into a durable side effect. */
110
+ get durable() {
111
+ return this.io !== void 0 && !!this.eventsPath;
112
+ }
113
+ /** V5-32 posture applied to the read side (C-events-dispatch-1, v43): an
114
+ * event a repeated read keeps reporting must not warn on each read —
115
+ * `refold()` calls `restore()` before every quality push. Shares the bounded
116
+ * `warnedMessages` set (and its FIFO eviction) with the append-failure warn.
117
+ * @param message - the warn text; identical text warns once per process.
118
+ */
119
+ warnOnce(message) {
120
+ if (this.warnedMessages.has(message)) return;
121
+ if (this.warnedMessages.size >= this.WARNED_CAP) {
122
+ const oldest = this.warnedMessages.values().next().value;
123
+ if (oldest !== void 0) this.warnedMessages.delete(oldest);
124
+ }
125
+ this.warnedMessages.add(message);
126
+ this.warn(message);
127
+ }
128
+ /** Durable-note map key (V4-41): a target shares one record per mode. */
129
+ noteKey(mode, target) {
130
+ return `${mode}\u0000${target}`;
131
+ }
132
+ mutate(task) {
133
+ const run = this.chain.then(task, task);
134
+ this.chain = run.then(() => void 0, () => void 0);
135
+ return run;
136
+ }
137
+ async restore(io) {
138
+ const path = this.path;
139
+ const eventsPath = this.eventsPath;
140
+ if (!path || !eventsPath) return;
141
+ await this.mutate(async () => {
142
+ const rawEvents = await io.readText(eventsPath);
143
+ const archiveNames = await listEventArchives(io, eventsPath);
144
+ const rawCache = await io.readText(path);
145
+ if ((rawEvents === null || rawEvents.trim() === "") && archiveNames.length === 0) {
146
+ const aggregate = parseAggregate(rawCache, this.warn);
147
+ if (aggregate) try {
148
+ await migrateFeedbackEvents(io, eventsPath, aggregate, this.warn, this.fence);
149
+ } catch {}
150
+ }
151
+ const initial = await readEvolutionTimeline(io, eventsPath, archiveNames);
152
+ const lateArchives = (await listEventArchives(io, eventsPath)).filter((name) => !archiveNames.includes(name));
153
+ const later = lateArchives.length === 0 ? null : await readEvolutionTimeline(io, eventsPath, [...archiveNames, ...lateArchives]);
154
+ const events = later?.events ?? initial.events;
155
+ const truncated = initial.malformed || later?.malformed === true;
156
+ const cache = parseCache(rawCache, this.warn);
157
+ const maxSeq = events.reduce((max, event) => Math.max(max, event.seq), 0);
158
+ const floor = events[0]?.seq ?? 0;
159
+ const usableCache = cache && cache.lastSeq >= floor - 1 && cache.lastSeq <= maxSeq ? cache : null;
160
+ const truth = usableCache ? foldWithDelta(usableCache, events, this.warn) : foldFeedbackState(events, this.warn);
161
+ const pickPending = (mode) => {
162
+ const picked = {};
163
+ for (const [target, inFlight] of this.pendingAppends[mode]) {
164
+ if (inFlight <= 0) continue;
165
+ const record = this.state[mode][target];
166
+ if (record) picked[target] = record;
167
+ }
168
+ return picked;
169
+ };
170
+ this.state = {
171
+ skills: {
172
+ ...truth.skills,
173
+ ...pickPending("skills")
174
+ },
175
+ sessions: {
176
+ ...truth.sessions,
177
+ ...pickPending("sessions")
178
+ }
179
+ };
180
+ const skillEntries = Object.entries(truth.skills);
181
+ const sessionEntries = Object.entries(truth.sessions);
182
+ const seedCount = Math.max(skillEntries.length, sessionEntries.length);
183
+ for (let i = 0; i < seedCount; i += 1) {
184
+ const skillEntry = skillEntries[i];
185
+ if (skillEntry) this.durableNote.set(this.noteKey("skills", skillEntry[0]), skillEntry[1].lastNote);
186
+ const sessionEntry = sessionEntries[i];
187
+ if (sessionEntry) this.durableNote.set(this.noteKey("sessions", sessionEntry[0]), sessionEntry[1].lastNote);
188
+ }
189
+ while (this.durableNote.size > EvolutionFeedback.NOTE_CAP) {
190
+ const oldest = this.durableNote.keys().next().value;
191
+ if (oldest === void 0) break;
192
+ this.durableNote.delete(oldest);
193
+ }
194
+ if (truncated) this.warnOnce(TRUNCATED_TIMELINE_WARN);
195
+ else if (maxSeq > 0 && (!cache || cache.lastSeq !== maxSeq)) try {
196
+ await io.writeText(path, JSON.stringify({
197
+ version: CACHE_VERSION,
198
+ lastSeq: maxSeq,
199
+ ...truth
200
+ }, null, 2));
201
+ } catch {}
202
+ });
203
+ }
204
+ /** External-producer contract (审计 B-4, v18): nothing inside the family
205
+ * calls `record` — the upstream `/feedback` command only appends a
206
+ * `feedback/record` session event carrying free text, which cannot be mapped
207
+ * to a (target, rating) pair without inventing semantics. A host that wants
208
+ * feedback-driven curation wires its own command/event to this method; the
209
+ * curator's union read (`feedback_warn`) then shortens the stale window.
210
+ * `feedback.spec.ts` pins that channel end to end.
211
+ * @param target - skill name or session id the rating belongs to.
212
+ * @param rating - `positive` or `negative`; other values are refused.
213
+ * @param note - optional free-text note carried into the durable event.
214
+ * @param kind - `skill` (default `session`) selects the score table.
215
+ */
216
+ /**
217
+ * v30 FB-01: refold the shared event log into the in-process aggregate.
218
+ * The aggregate only folds at mount, so a long-lived process computed the
219
+ * ABSOLUTE feedback pair from a stale aggregate and overwrote the decision
220
+ * relevant `feedback_warn` another process had recorded. The log is the
221
+ * truth — re-reading it before each quality push shrinks the staleness
222
+ * window to the refold-vs-append race (near-zero, serialized by mutate).
223
+ */
224
+ async refold() {
225
+ if (!this.io) return;
226
+ await this.restore(this.io);
227
+ }
228
+ record(target, rating, note, kind = "session") {
229
+ const mode = kind === "skill" ? "skills" : "sessions";
230
+ const table = this.state[mode];
231
+ const current = table[target] ?? {
232
+ positive: 0,
233
+ negative: 0
234
+ };
235
+ current[rating] += 1;
236
+ if (note !== void 0) current.lastNote = note;
237
+ table[target] = current;
238
+ const recordIo = this.io;
239
+ const eventsPath = this.eventsPath;
240
+ if (!recordIo || !eventsPath) return;
241
+ const pending = this.pendingAppends[mode];
242
+ pending.set(target, (pending.get(target) ?? 0) + 1);
243
+ this.mutate(async () => {
244
+ try {
245
+ const seq = await appendEvolutionEvent(recordIo, eventsPath, {
246
+ type: "feedback",
247
+ target,
248
+ kind,
249
+ rating,
250
+ note
251
+ }, void 0, this.fence);
252
+ if (note !== void 0) {
253
+ if (this.durableNote.size >= EvolutionFeedback.NOTE_CAP) {
254
+ const oldest = this.durableNote.keys().next().value;
255
+ if (oldest !== void 0) this.durableNote.delete(oldest);
256
+ }
257
+ this.durableNote.set(this.noteKey(mode, target), note);
258
+ }
259
+ if (seq % CACHE_SNAP_EVERY === 0) await this.writeCacheNow();
260
+ } catch (error) {
261
+ const rollback = table[target];
262
+ if (rollback) {
263
+ rollback[rating] -= 1;
264
+ if (note !== void 0) {
265
+ if (rollback.lastNote === note) {
266
+ const durable = this.durableNote.get(this.noteKey(mode, target));
267
+ if (durable === void 0) delete rollback.lastNote;
268
+ else rollback.lastNote = durable;
269
+ }
270
+ }
271
+ }
272
+ const message = `evolution-feedback: failed to append feedback event for ${kind} "${target}": ${error instanceof Error ? error.message : String(error)}`;
273
+ const cause = error instanceof Error ? error.message : String(error);
274
+ if (!this.warnedMessages.has(cause)) {
275
+ if (this.warnedMessages.size >= this.WARNED_CAP) {
276
+ const oldest = this.warnedMessages.values().next().value;
277
+ if (oldest !== void 0) this.warnedMessages.delete(oldest);
278
+ }
279
+ this.warnedMessages.add(cause);
280
+ this.warn(message);
281
+ }
282
+ if (rollback) this.onRollback?.(target, kind);
283
+ } finally {
284
+ const remaining = (pending.get(target) ?? 1) - 1;
285
+ if (remaining > 0) pending.set(target, remaining);
286
+ else pending.delete(target);
287
+ }
288
+ });
289
+ }
290
+ score(target, kind = "session") {
291
+ const record = (kind === "skill" ? this.state.skills : this.state.sessions)[target];
292
+ if (!record) return 0;
293
+ const total = record.positive + record.negative;
294
+ if (total === 0) return 0;
295
+ return (record.positive - record.negative) / total;
296
+ }
297
+ /**
298
+ * Deep-copy view of the live aggregate.
299
+ *
300
+ * OPT-26 (2026-09): `@internal` — test-support API, NO production consumer
301
+ * in the family (mirrors the explicit posture of evolution-replay's
302
+ * `plansSnapshot()`). External consumers should read the rendered
303
+ * score/warn surfaces instead of relying on this shape.
304
+ */
305
+ snapshot() {
306
+ const copyRecords = (table) => {
307
+ const out = {};
308
+ for (const [key, record] of Object.entries(table)) out[key] = { ...record };
309
+ return out;
310
+ };
311
+ return {
312
+ skills: copyRecords(this.state.skills),
313
+ sessions: copyRecords(this.state.sessions)
314
+ };
315
+ }
316
+ /** Await the pending record-task chain (unload safety; rc.66). */
317
+ waitIdle() {
318
+ return this.chain;
319
+ }
320
+ /** Snapshot the boot cache from the log truth (rc.68/rc.72); best-effort. */
321
+ async writeCacheNow() {
322
+ const path = this.path;
323
+ const eventsPath = this.eventsPath;
324
+ const recordIo = this.io;
325
+ if (!path || !eventsPath || !recordIo) return;
326
+ try {
327
+ const { events, malformed } = await readEvolutionTimeline(recordIo, eventsPath);
328
+ if (events.length > 0) {
329
+ const activeProbe = await probeText(recordIo, eventsPath);
330
+ if (!isPresent(activeProbe)) {
331
+ if (isUnknown(activeProbe)) this.warnOnce(`evolution-feedback: the active event log ${eventsPath} could not be read (${activeProbe.reason}); withholding the cache write until it can be read`);
332
+ return;
333
+ }
334
+ }
335
+ if (malformed) {
336
+ this.warnOnce(TRUNCATED_TIMELINE_WARN);
337
+ return;
338
+ }
339
+ const maxSeq = events.reduce((max, event) => Math.max(max, event.seq), 0);
340
+ if (maxSeq === 0) return;
341
+ let rawCache;
342
+ try {
343
+ rawCache = await recordIo.readText(path);
344
+ } catch {
345
+ return;
346
+ }
347
+ const cache = parseCache(rawCache, this.warn);
348
+ const floor = events[0]?.seq ?? 0;
349
+ const state = cache && cache.lastSeq >= floor - 1 ? foldWithDelta(cache, events, this.warn) : foldFeedbackState(events, this.warn);
350
+ const body = JSON.stringify({
351
+ version: CACHE_VERSION,
352
+ lastSeq: maxSeq,
353
+ ...state
354
+ }, null, 2);
355
+ await recordIo.writeText(path, body);
356
+ } catch {}
357
+ }
358
+ /** Rebuild the boot cache from the log truth (rc.68); best-effort, queued
359
+ * on the record chain so it runs after the pending appends. */
360
+ persistCache() {
361
+ return this.mutate(async () => {
362
+ await this.writeCacheNow();
363
+ });
364
+ }
365
+ };
366
+ /** Semantic identity of one event: `seq` and `at` are excluded (a merge
367
+ * shifts seqs, a re-synthesis stamps a different `at`), so type/kind/target/
368
+ * rating/note is everything a fold can see. */
369
+ function sameSemantics(a, b) {
370
+ return a.type === b.type && a.kind === b.kind && a.target === b.target && a.rating === b.rating && a.note === b.note;
371
+ }
372
+ /** True when `existing` already carries the WHOLE legacy batch (the skip case).
373
+ * P1-8 (v37): counted as a MULTISET, never as a contiguous run — the
374
+ * synthesizer emits "all positives, then all negatives" per target while the
375
+ * real log is in temporal order, so the run-based gate read an already-migrated
376
+ * log as unmigrated and re-appended the whole history (3 events became 6, and
377
+ * every further boot doubled it again). */
378
+ function containsLegacyMultiset(existing, expected) {
379
+ if (expected.length === 0) return true;
380
+ const pool = [...existing];
381
+ for (const event of expected) {
382
+ const at = pool.findIndex((candidate) => sameSemantics(candidate, event));
383
+ if (at < 0) return false;
384
+ pool.splice(at, 1);
385
+ }
386
+ return true;
387
+ }
388
+ /** True when the body the migration transact just read may be written over:
389
+ * absent or blank (the append path's own "missing" definition), or a v1 body
390
+ * this reader can actually interpret. `parseEvolutionEvents` maps a corrupt or
391
+ * future-version body to an EMPTY timeline, so without this gate a read failure
392
+ * would be folded as "nothing was ever migrated" and the synthesized log would
393
+ * overwrite bytes the append path refuses to touch. */
394
+ function isReadableEventBody(current) {
395
+ if (current === null || current.trim() === "") return true;
396
+ try {
397
+ const parsed = JSON.parse(current);
398
+ if (!isRecord(parsed)) return false;
399
+ if (parsed.version !== void 0 && parsed.version !== EVENT_LOG_VERSION) return false;
400
+ return Array.isArray(parsed.events);
401
+ } catch {
402
+ return false;
403
+ }
404
+ }
405
+ /**
406
+ * Merge a legacy aggregate into the event log (rc.69): the expected synthetic
407
+ * sequence is APPENDED (seq-shifted) when the log does not already contain it
408
+ * — so a concurrent first writer's events AND the legacy history both
409
+ * survive; when the sequence is already present the migration was completed
410
+ * (by a first writer or by this path) and nothing is re-appended. Idempotent
411
+ * and race-safe (the search runs inside the same transact). Exported for the
412
+ * migration-race regression test.
413
+ */
414
+ async function migrateFeedbackEvents(io, eventsPath, aggregate, warn = () => {}, fence) {
415
+ const expected = synthesizeFeedbackEvents(aggregate);
416
+ const refused = expected.filter((event) => evolutionEventPayloadIssue(event) !== null);
417
+ if (refused.length > 0) {
418
+ 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`);
419
+ return;
420
+ }
421
+ const write = async () => {
422
+ await transactIo(io, eventsPath, (current) => {
423
+ if (!isReadableEventBody(current)) {
424
+ warn("evolution-feedback: migration left unreadable event-log bytes untouched (neither migrated nor overwritten)");
425
+ return Promise.resolve(current);
426
+ }
427
+ const existing = parseEvolutionEvents(current);
428
+ if (containsLegacyMultiset(existing, expected)) return Promise.resolve(current);
429
+ const maxSeq = existing.reduce((max, event) => Math.max(max, event.seq), 0);
430
+ const merged = [...existing, ...expected.map((event, index) => ({
431
+ ...event,
432
+ seq: maxSeq + index + 1
433
+ }))];
434
+ return Promise.resolve(JSON.stringify({
435
+ version: EVENT_LOG_VERSION,
436
+ events: merged
437
+ }, null, 2));
438
+ });
439
+ };
440
+ if (fence !== void 0) await fence.run(write);
441
+ else await write();
442
+ }
443
+ /** Parse a legacy aggregate (v1) or a v2 cache into a plain aggregate state.
444
+ * V24-05 (v24): every record passes the shared per-record sanitizer (same
445
+ * validation as `parseCache` — S6.4), and migrated counts are clamped so one
446
+ * corrupted field cannot expand into an unbounded event array at boot. */
447
+ const MAX_MIGRATED_EVENTS_PER_RECORD = 1e4;
448
+ function parseAggregate(raw, warn = () => {}) {
449
+ if (raw === null) return null;
450
+ try {
451
+ const parsed = JSON.parse(raw);
452
+ const clamp = (count, target, field) => {
453
+ if (count > MAX_MIGRATED_EVENTS_PER_RECORD) {
454
+ 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`);
455
+ return MAX_MIGRATED_EVENTS_PER_RECORD;
456
+ }
457
+ return count;
458
+ };
459
+ const sanitizeSection = (section, kind) => {
460
+ if (!isRecord(section)) return void 0;
461
+ const cleaned = sanitizeCacheRecords(section, kind, warn);
462
+ for (const [target, record] of Object.entries(cleaned)) if (record.positive > MAX_MIGRATED_EVENTS_PER_RECORD || record.negative > MAX_MIGRATED_EVENTS_PER_RECORD) cleaned[target] = {
463
+ ...record,
464
+ positive: clamp(record.positive, target, "positive"),
465
+ negative: clamp(record.negative, target, "negative")
466
+ };
467
+ return cleaned;
468
+ };
469
+ const skills = sanitizeSection(parsed.skills, "skill");
470
+ const sessions = sanitizeSection(parsed.sessions, "session");
471
+ if (!skills && !sessions) return null;
472
+ return {
473
+ skills: skills ?? {},
474
+ sessions: sessions ?? {}
475
+ };
476
+ } catch {
477
+ return null;
478
+ }
479
+ }
480
+ function parseCache(raw, warn = () => {}) {
481
+ if (raw === null) return null;
482
+ try {
483
+ const parsed = JSON.parse(raw);
484
+ if (parsed.version !== CACHE_VERSION || typeof parsed.lastSeq !== "number" || !Number.isFinite(parsed.lastSeq)) return null;
485
+ if (!isRecord(parsed.skills) || !isRecord(parsed.sessions)) return null;
486
+ return {
487
+ lastSeq: parsed.lastSeq,
488
+ state: {
489
+ skills: sanitizeCacheRecords(parsed.skills, "skill", warn),
490
+ sessions: sanitizeCacheRecords(parsed.sessions, "session", warn)
491
+ }
492
+ };
493
+ } catch {
494
+ return null;
495
+ }
496
+ }
497
+ /** Per-record numeric-domain validation (S6.4): a record whose `positive` or
498
+ * `negative` is not a finite number >= 0, or whose `lastNote` is not a string,
499
+ * would fold as NaN into the usage aggregate — skip it with a warn instead of
500
+ * corrupting the state. A record with no valid count is dropped entirely.
501
+ * OPT-25 (2026-09): a count ABOVE `MAX_MIGRATED_EVENTS_PER_RECORD` is now
502
+ * CLAMPED here with a warn, symmetric with the migration reader's clamp (same
503
+ * file, same threat model — V24-05 covered the migration side only). Before,
504
+ * a poisoned boot-cache count folded as-is into every downstream decision;
505
+ * the clamp bounds the skew to the same ceiling migration accepts. */
506
+ function sanitizeCacheRecords(input, kind, warn) {
507
+ const out = {};
508
+ for (const [target, value] of Object.entries(input)) {
509
+ const record = sanitizeFeedbackRecord(value, target, kind, warn);
510
+ if (record) {
511
+ let clamped;
512
+ if (record.positive > MAX_MIGRATED_EVENTS_PER_RECORD || record.negative > MAX_MIGRATED_EVENTS_PER_RECORD) {
513
+ warn(`evolution-feedback: cache record for ${kind} "${target}" exceeds the clamp ceiling (${MAX_MIGRATED_EVENTS_PER_RECORD}) — clamping like the migration reader`);
514
+ clamped = {
515
+ positive: Math.min(record.positive, MAX_MIGRATED_EVENTS_PER_RECORD),
516
+ negative: Math.min(record.negative, MAX_MIGRATED_EVENTS_PER_RECORD),
517
+ ...record.lastNote !== void 0 ? { lastNote: record.lastNote } : {}
518
+ };
519
+ }
520
+ out[target] = clamped ?? record;
521
+ }
522
+ }
523
+ return out;
524
+ }
525
+ function sanitizeFeedbackRecord(value, target, kind, warn) {
526
+ if (!isRecord(value)) {
527
+ warn(`evolution-feedback: skipping cache record for ${kind} "${target}": not a record`);
528
+ return null;
529
+ }
530
+ const positive = value.positive;
531
+ const negative = value.negative;
532
+ const note = value.lastNote;
533
+ const validCount = (n) => typeof n === "number" && Number.isFinite(n) && n >= 0;
534
+ if (!validCount(positive) || !validCount(negative)) {
535
+ warn(`evolution-feedback: skipping cache record for ${kind} "${target}": positive/negative must be finite numbers >= 0`);
536
+ return null;
537
+ }
538
+ if (note !== void 0 && typeof note !== "string") {
539
+ warn(`evolution-feedback: skipping cache record for ${kind} "${target}": lastNote must be a string`);
540
+ return null;
541
+ }
542
+ return {
543
+ positive,
544
+ negative,
545
+ ...note !== void 0 ? { lastNote: note } : {}
546
+ };
547
+ }
548
+ /** Fold all feedback events from zero (the truth view). */
549
+ function foldFeedbackState(events, warn = () => {}) {
550
+ const state = {
551
+ skills: {},
552
+ sessions: {}
553
+ };
554
+ for (const event of events) applyFeedbackEvent(state, event, warn);
555
+ return state;
556
+ }
557
+ /** Fold events after the cache's lastSeq onto the cached aggregates. */
558
+ function foldWithDelta(cache, events, warn = () => {}) {
559
+ const state = {
560
+ skills: { ...cache.state.skills },
561
+ sessions: { ...cache.state.sessions }
562
+ };
563
+ for (const event of events) if (event.seq > cache.lastSeq) applyFeedbackEvent(state, event, warn);
564
+ return state;
565
+ }
566
+ function applyFeedbackEvent(state, event, warn = () => {}) {
567
+ if (event.type !== "feedback") return;
568
+ if (event.kind !== "skill" && event.kind !== "session") {
569
+ warn(`evolution-feedback: skipping feedback event with invalid kind: ${String(event.kind)}`);
570
+ return;
571
+ }
572
+ if (event.rating !== "positive" && event.rating !== "negative") {
573
+ warn(`evolution-feedback: skipping feedback event with invalid rating: ${String(event.rating)}`);
574
+ return;
575
+ }
576
+ const target = event.target;
577
+ if (target === void 0) return;
578
+ const table = event.kind === "skill" ? state.skills : state.sessions;
579
+ const record = table[target] ?? {
580
+ positive: 0,
581
+ negative: 0
582
+ };
583
+ record[event.rating] += 1;
584
+ if (event.note !== void 0) record.lastNote = event.note;
585
+ table[target] = record;
586
+ }
587
+ /** Synthesize one event per aggregate count unit, lastNote on the final event
588
+ * (migration). A zero-count record still carrying a lastNote would otherwise
589
+ * drop the note — emit a dedicated note event (S6.4) so it survives. */
590
+ function synthesizeFeedbackEvents(aggregate) {
591
+ const events = [];
592
+ const at = (/* @__PURE__ */ new Date()).toISOString();
593
+ const emitTarget = (kind, target, record) => {
594
+ const first = events.length + 1;
595
+ for (let index = 0; index < record.positive; index += 1) events.push({
596
+ seq: events.length + 1,
597
+ at,
598
+ type: "feedback",
599
+ kind,
600
+ target,
601
+ rating: "positive"
602
+ });
603
+ for (let index = 0; index < record.negative; index += 1) events.push({
604
+ seq: events.length + 1,
605
+ at,
606
+ type: "feedback",
607
+ kind,
608
+ target,
609
+ rating: "negative"
610
+ });
611
+ if (record.lastNote !== void 0) if (events.length >= first) {
612
+ const last = events.length - 1;
613
+ const final = events[last];
614
+ if (final) events[last] = {
615
+ ...final,
616
+ note: record.lastNote
617
+ };
618
+ } else events.push({
619
+ seq: events.length + 1,
620
+ at,
621
+ type: "feedback",
622
+ kind,
623
+ target,
624
+ rating: "positive",
625
+ note: record.lastNote
626
+ });
627
+ };
628
+ for (const [target, record] of Object.entries(aggregate.skills)) emitTarget("skill", target, record);
629
+ for (const [target, record] of Object.entries(aggregate.sessions)) emitTarget("session", target, record);
630
+ return events;
631
+ }
632
+ const name = "evolution-feedback";
633
+ const Config = z.object({
634
+ qualityWarnThreshold: z.number().min(-1).max(1).default(-.25),
635
+ path: z.string().default("")
636
+ });
637
+ /** Resolve the effective quality warn threshold, clamped to its [-1, 1] domain
638
+ * (G3.1). 0 and negative values are legal (a lower threshold is stricter); NaN,
639
+ * ±Infinity and out-of-range values fall back to the default -0.25. Exported so
640
+ * the clamp is directly testable; `apply` warns when a value was corrected. */
641
+ function resolveQualityWarnThreshold(config) {
642
+ return clampedNumber(config.qualityWarnThreshold ?? -.25, -.25, {
643
+ min: -1,
644
+ max: 1
645
+ });
646
+ }
647
+ function apply(ctx, rawConfig = {}) {
648
+ const configuredThreshold = rawConfig.qualityWarnThreshold ?? -.25;
649
+ const qualityWarnThreshold = resolveQualityWarnThreshold(rawConfig);
650
+ if (qualityWarnThreshold !== configuredThreshold) ctx.logger.warn(`evolution-feedback: qualityWarnThreshold=${String(configuredThreshold)} is invalid; falling back to the default -0.25`);
651
+ const feedback = new EvolutionFeedback(void 0, evolutionRoot(), (rawConfig.path ?? "").trim() || void 0, (message) => {
652
+ ctx.logger.warn(message);
653
+ }, ctx.get("evolutionMutationAuthority")?.homeFence);
654
+ ctx.provide("evolutionFeedback", feedback);
655
+ ctx.inject(["evolutionIo"], (ioCtx) => {
656
+ const ioRegistry = ioCtx.evolutionIo;
657
+ const io = evolutionIoAdapter(() => ioRegistry.provider());
658
+ feedback.attachIo(io);
659
+ feedback.restore(io).catch((error) => {
660
+ ioCtx.logger.warn(error);
661
+ });
662
+ });
663
+ const baseRecord = feedback.record.bind(feedback);
664
+ ctx.inject(["skillUsage"], (skillCtx) => {
665
+ const skillUsage = skillCtx.skillUsage;
666
+ const pushQuality = (target, kind) => {
667
+ if (kind !== "skill") return;
668
+ if (!feedback.durable) return;
669
+ feedback.refold().then(() => {
670
+ const score = feedback.score(target, "skill");
671
+ const warn = score < qualityWarnThreshold;
672
+ return skillUsage.setFeedbackQuality(target, score, warn);
673
+ }).catch((error) => {
674
+ skillCtx.logger.warn(error);
675
+ });
676
+ };
677
+ feedback.onRollback = (target, kind) => {
678
+ pushQuality(target, kind);
679
+ };
680
+ feedback.record = (target, rating, note, kind) => {
681
+ baseRecord(target, rating, note, kind ?? "session");
682
+ pushQuality(target, kind ?? "session");
683
+ };
684
+ });
685
+ ctx.effect(() => () => {
686
+ return Promise.all([feedback.persistCache(), feedback.waitIdle()]);
687
+ }, "evolution-feedback.records");
688
+ }
689
+ //#endregion
690
+ export { Config, EvolutionFeedback, apply, migrateFeedbackEvents, name, resolveQualityWarnThreshold };