@lmzhen/dsh-evolution-feedback 0.1.0-rc.60 → 0.1.0-rc.62

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/index.js CHANGED
@@ -1,6 +1,269 @@
1
1
  import z from "@deepseek-ai/schemastery";
2
- import { homedir } from "node:os";
3
2
  import { join } from "node:path";
3
+ import { createHash } from "node:crypto";
4
+ import { homedir } from "node:os";
5
+ //#region ../evolution-core/src/io.ts
6
+ /**
7
+ * Run `task` inside `io.transact` when the backend provides it; otherwise fall
8
+ * back to a plain read → task → write/remove sequence (no cross-process lock —
9
+ * callers keep their single-process serialize chain as the second layer).
10
+ */
11
+ async function transactIo(io, path, task) {
12
+ if (io.transact) {
13
+ await io.transact(path, task);
14
+ return;
15
+ }
16
+ const next = await task(await io.readText(path));
17
+ if (next === null) await io.remove(path);
18
+ else await io.writeText(path, next);
19
+ }
20
+ /** Lazy adapter over an IO provider registry, shared by every evolution consumer. */
21
+ function evolutionIoAdapter(provider) {
22
+ return {
23
+ readText: (path) => provider().readText(path),
24
+ writeText: (path, content) => provider().writeText(path, content),
25
+ remove: (path) => provider().remove(path),
26
+ list: (path) => provider().list(path),
27
+ exists: (path) => provider().exists(path),
28
+ rename: (path, destination) => provider().rename(path, destination),
29
+ copy: (path, destination) => provider().copy(path, destination),
30
+ size: (path) => {
31
+ const io = provider();
32
+ return io.size ? io.size(path) : Promise.resolve(null);
33
+ },
34
+ transact: (path, task) => {
35
+ const io = provider();
36
+ return io.transact ? io.transact(path, task) : transactIo(io, path, task);
37
+ },
38
+ isSymlink: (path) => {
39
+ const io = provider();
40
+ return io.isSymlink ? io.isSymlink(path) : Promise.resolve(null);
41
+ }
42
+ };
43
+ }
44
+ //#endregion
45
+ //#region ../evolution-core/src/prompts.ts
46
+ /**
47
+ * Review and curation prompts adapted from Hermes Agent
48
+ * `agent/background_review.py`, `agent/curator.py`, and
49
+ * `agent/learn_prompt.py`, with tool names translated to the DSH-native
50
+ * catalog (`memory`, `skill_manage`, `skill`, `bash`, `str_replace_editor`).
51
+ *
52
+ * Alignment policy (2026-08-29): the OPERATIONAL steps and instructions the
53
+ * model follows mirror the Hermes originals structurally (signal list,
54
+ * preference order, support-file taxonomy, curator package integrity,
55
+ * consolidated/pruned reporting block). Tool and platform differences are
56
+ * DSH-adapted (native tool names, pinned-within-review semantics, this
57
+ * platform's index cap), and DSH-only additions are marked as such.
58
+ *
59
+ * Every prompt is pinned in a versioned bundle. Review workers verify the
60
+ * bundle digest before spending a model call, so a partially-patched
61
+ * deployment fails closed instead of silently running a truncated prompt.
62
+ */
63
+ /**
64
+ * Prompt bundle identity. Bump both id and version whenever a prompt's text
65
+ * changes semantically: the bundle digest is the fail-closed signal for
66
+ * review workers, so a stale id across deployments must be distinguishable.
67
+ */
68
+ const PROMPT_BUNDLE_ID = "dsh-evolution@5";
69
+ const MEMORY_REVIEW_PROMPT = `[Auto-review — Memory]
70
+ Review the conversation above and consider saving to memory if appropriate.
71
+
72
+ Focus on:
73
+ 1. Has the user revealed things about themselves — persona, desires, preferences, or personal details worth remembering?
74
+ 2. Has the user expressed expectations about how you should behave, their work style, or ways they want you to operate?
75
+
76
+ If something stands out, save it using the memory tool.
77
+ If nothing is worth saving, just say "Nothing to save." and stop.`;
78
+ const SKILL_REVIEW_PROMPT = `[Auto-review — Skills]
79
+ Review the conversation above and update the skill library. Be ACTIVE — most sessions produce at least one skill update, even if small. A pass that does nothing is a missed learning opportunity, not a neutral outcome.
80
+
81
+ Target shape of the library: CLASS-LEVEL skills, each with a rich SKILL.md and a references/ directory for session-specific detail. Not a long flat list of narrow one-session-one-skill entries. This shapes HOW you update, not WHETHER you update.
82
+
83
+ Signals to look for (any one of these warrants action):
84
+ • User corrected your style, tone, format, legibility, or verbosity. Frustration signals like 'stop doing X', 'this is too verbose', 'don't format like this', 'why are you explaining', 'just give me the answer', 'you always do Y and I hate it', or an explicit 'remember this' are FIRST-CLASS skill signals, not just memory signals. Update the relevant skill(s) to embed the preference so the next session starts already knowing.
85
+ • User corrected your workflow, approach, or sequence of steps. Encode the correction as a pitfall or explicit step in the skill that governs that class of task.
86
+ • Non-trivial technique, fix, workaround, debugging path, or tool-usage pattern emerged that a future session would benefit from. Capture it.
87
+ • A skill that got loaded or consulted this session turned out to be wrong, missing a step, or outdated. Patch it NOW.
88
+
89
+ Preference order — prefer the earliest action that fits, but do pick one when a signal above fired:
90
+ 1. UPDATE A CURRENTLY-LOADED SKILL. Look back through the conversation for skills the user loaded or you read. If any of them covers the territory of the new learning, PATCH that one first. It is the skill that was in play, so it's the right one to extend.
91
+ 2. UPDATE AN EXISTING UMBRELLA. If no loaded skill fits but an existing class-level skill does, patch it. Add a subsection, a pitfall, or broaden a trigger.
92
+ 3. ADD A SUPPORT FILE under an existing umbrella. Skills can be packaged with three kinds of support files — use the right directory per kind:
93
+ • references/<topic>.md — session-specific detail (error transcripts, reproduction recipes, provider quirks) AND condensed knowledge banks: quoted research, API docs, external authoritative excerpts, or domain notes you found while working on the problem. Write it concise and for the value of the task, not as a full mirror of upstream docs.
94
+ • templates/<name>.<ext> — starter files meant to be copied and modified (boilerplate configs, scaffolding, a known-good example the agent can reproduce with modifications).
95
+ • scripts/<name>.<ext> — statically re-runnable actions the skill can invoke directly (verification scripts, fixture generators, deterministic probes, anything the agent should run rather than hand-type each time).
96
+ Add support files via skill_manage action=write_file with file_path starting 'references/', 'templates/', or 'scripts/'. The umbrella's SKILL.md should gain a one-line pointer to any new support file so future agents know it exists.
97
+ 4. CREATE A NEW CLASS-LEVEL UMBRELLA SKILL when no existing skill covers the class. The name MUST be at the class level. The name MUST NOT be a specific PR number, error string, feature codename, library-alone name, or 'fix-X / debug-Y / audit-Z-today' session artifact. If the proposed name only makes sense for today's task, it's wrong — fall back to (1), (2), or (3).
98
+
99
+ User-preference embedding (important): when the user expressed a style/format/workflow preference, the update belongs in the SKILL.md body, not just in memory. Memory captures 'who the user is and what the current situation and state of your operations are'; skills capture 'how to do this class of task for this user'. When they complain about how you handled a task, the skill that governs that task needs to carry the lesson.
100
+
101
+ If you notice two existing skills that overlap, note it in your reply — the background curator handles consolidation at scale.
102
+
103
+ Two-tier deposition discipline (DSH addition, same spirit as the umbrella rule): before writing, classify the knowledge:
104
+ • PATTERN (reusable — symptom → mechanism → fix → verification, still valuable next session) belongs in the SKILL.md body.
105
+ • LOG (one-off — commit SHAs, npm/profile states, what this release changed, this session's process narrative) belongs in a references/ file, never the body. Body density IS reuse rate. Keep new entries tight: a pattern fits in 2-8 physical lines; prefer changing the current-state pointer over appending history.
106
+
107
+ Protected skills (DO NOT edit these):
108
+ • Bundled skills (shipped with the platform).
109
+ • Hub-installed skills (installed from a hub).
110
+ Pinned skills are read-only to THIS background review pass — the pinned write guard refuses background changes, so only the foreground may update or archive them. Foreground and delegated-subagent writes to pinned skills remain allowed.
111
+ If the only skills that need updating are protected, say 'Nothing to save.' and stop.
112
+
113
+ Do NOT capture (these become persistent self-imposed constraints that bite you later when the environment changes):
114
+ • Environment-dependent failures: missing binaries, fresh-install errors, post-migration path mismatches, 'command not found', unconfigured credentials, uninstalled packages. The user can fix these — they are not durable rules.
115
+ • Negative claims about tools or features ('browser tools do not work', 'X tool is broken', 'cannot use Y'). These harden into refusals the agent cites against itself for months after the actual problem was fixed.
116
+ • Session-specific transient errors that resolved before the conversation ended. If retrying worked, the lesson is the retry pattern, not the original failure.
117
+ • One-off task narratives. A user asking 'summarize today's market' or 'analyze this PR' is not a class of work that warrants a skill.
118
+
119
+ If a tool failed because of setup state, capture the FIX (install command, config step, env var to set) under an existing setup or troubleshooting skill — never 'this tool does not work' as a standalone constraint.
120
+
121
+ 'Nothing to save.' is a real option but should NOT be the default. If the session ran smoothly with no corrections and produced no new technique, just say 'Nothing to save.' and stop. Otherwise, act.`;
122
+ const COMBINED_REVIEW_PROMPT = `[Auto-review]
123
+ Review the conversation above and update two things:
124
+
125
+ **Memory**: who the user is. Did the user reveal persona, desires, preferences, personal details, or expectations about how you should behave? Save facts about the user and durable preferences with the memory tool.
126
+
127
+ **Skills**: how to do this class of task. Be ACTIVE — most sessions produce at least one skill update. A pass that does nothing is a missed learning opportunity, not a neutral outcome.
128
+
129
+ Target shape of the skill library: CLASS-LEVEL skills with a rich SKILL.md and a references/ directory for session-specific detail. Not a long flat list of narrow one-session-one-skill entries.
130
+
131
+ Signals that warrant a skill update (any one is enough):
132
+ • User corrected your style, tone, format, legibility, verbosity, or approach. Frustration is a FIRST-CLASS skill signal, not just a memory signal. 'stop doing X', 'don't format like this', 'I hate when you Y' — embed the lesson in the skill that governs that task so the next session starts fixed.
133
+ • Non-trivial technique, fix, workaround, or debugging path emerged.
134
+ • A skill that was loaded or consulted turned out wrong, missing, or outdated — patch it now.
135
+
136
+ Preference order for skills — pick the earliest that fits:
137
+ 1. UPDATE A CURRENTLY-LOADED SKILL. Check what skills were loaded or read in the conversation. If one of them covers the learning, PATCH it first. It was in play; it's the right place.
138
+ 2. UPDATE AN EXISTING UMBRELLA. Patch it.
139
+ 3. ADD A SUPPORT FILE under an existing umbrella via skill_manage action=write_file. Three kinds: references/<topic>.md for session-specific detail OR condensed knowledge banks (quoted research, API docs excerpts, domain notes) written concise and task-focused; templates/<name>.<ext> for starter files meant to be copied and modified; scripts/<name>.<ext> for statically re-runnable actions (verification, fixture generators, probes). Add a one-line pointer in SKILL.md so future agents find them.
140
+ 4. CREATE A NEW CLASS-LEVEL UMBRELLA when nothing exists. Name at the class level — NOT a PR number, error string, codename, library-alone name, or 'fix-X / debug-Y' session artifact. If the name only fits today's task, fall back to (1), (2), or (3).
141
+
142
+ Two-tier deposition discipline (DSH addition): classify before writing — PATTERN (symptom → mechanism → fix → verification) goes in the SKILL.md body; LOG (commit SHAs, npm/profile states, this release's change list, this session's narrative) goes in a references/ file. Body density IS reuse rate; a pattern fits in 2-8 physical lines.
143
+
144
+ User-preference embedding: when the user complains about how you handled a task, update the skill that governs that task — memory alone isn't enough. Memory says 'who the user is and what the current situation and state of your operations are'; skills say 'how to do this class of task for this user'. Both should carry user-preference lessons when relevant.
145
+
146
+ If you notice overlapping existing skills, mention it — the background curator handles consolidation.
147
+
148
+ Protected skills (DO NOT edit these):
149
+ • Bundled skills (shipped with the platform).
150
+ • Hub-installed skills (installed from a hub).
151
+ Pinned skills are read-only to THIS background review pass — the pinned write guard refuses background changes, so only the foreground may update or archive them. Foreground and delegated-subagent writes to pinned skills remain allowed.
152
+ If the only skills that need updating are protected, say 'Nothing to save.' and stop.
153
+
154
+ Do NOT capture as skills (these become persistent self-imposed constraints that bite you later when the environment changes):
155
+ • Environment-dependent failures: missing binaries, fresh-install errors, post-migration path mismatches, 'command not found', unconfigured credentials, uninstalled packages. The user can fix these — they are not durable rules.
156
+ • Negative claims about tools or features ('browser tools do not work', 'X tool is broken', 'cannot use Y'). These harden into refusals the agent cites against itself for months after the actual problem was fixed.
157
+ • Session-specific transient errors that resolved before the conversation ended. If retrying worked, the lesson is the retry pattern, not the original failure.
158
+ • One-off task narratives. A user asking 'summarize today's market' or 'analyze this PR' is not a class of work that warrants a skill.
159
+
160
+ If a tool failed because of setup state, capture the FIX (install command, config step, env var to set) under an existing setup or troubleshooting skill — never 'this tool does not work' as a standalone constraint.
161
+
162
+ Act on whichever of the two dimensions has real signal. If genuinely nothing stands out on either, say 'Nothing to save.' and stop — but don't reach for that conclusion as a default.`;
163
+ const CURATOR_PROMPT = `You are the skill curator. Maintain a healthy, class-level skill library, not a flat pile of narrow one-session skills.
164
+
165
+ This is an UMBRELLA-BUILDING consolidation pass, not a passive audit and not a duplicate-finder.
166
+
167
+ The goal is a LIBRARY OF CLASS-LEVEL INSTRUCTIONS. A skill collection of many narrow skills where each captures one session's specific bug is a FAILURE of the library. An agent searching skills matches on descriptions, not exact names; one broad umbrella with labeled subsections beats five narrow siblings for discoverability.
168
+
169
+ Right target shape: class-level skills with rich SKILL.md + references/, templates/, scripts/ support files for session-specific detail.
170
+
171
+ Hard rules:
172
+ 1. NEVER hard-delete a skill. Archive (moving to .archive/) is the maximum destructive action; archives are recoverable, deletion is not.
173
+ 2. Do not touch bundled, hub-installed, pinned, or scheduled-task-referenced (referenced) skills. Referenced skills MAY be consolidated into an umbrella — but only because the curator rewrites scheduled-task skill references to follow consolidations; never simply prune them.
174
+ 3. Do not archive recently-created or never-used skills without strong evidence. "use=0" is NOT evidence either way — it only means the trigger has not come up yet. Never archive a never-used skill unless it is at least 30 days old AND its content is genuinely obsolete or fully absorbed elsewhere.
175
+ 4. Do NOT reject consolidation on the grounds that "each skill has a distinct trigger". The right bar is: would a human maintainer write this as N separate skills, or one skill with N labeled subsections? When the answer is the latter, merge.
176
+ 5. Judge overlap on CONTENT, not on usage counters.
177
+ 6. Before archiving a merged skill, ensure its unique content was preserved in the umbrella.
178
+
179
+ How to work:
180
+ 1. Scan the candidate list. Identify PREFIX CLUSTERS — skills sharing a first word or domain keyword. Expected cluster count scales with the library: a large collection may show 10-25 prefix clusters, a small one often has none — a clean "nothing to consolidate" summary is the correct small-library outcome, not a shortage of ambition.
181
+ 2. For each cluster with 2+ members, ask "what is the UMBRELLA CLASS these skills serve?" and consolidate:
182
+ a. MERGE INTO AN EXISTING UMBRELLA (patch a labeled section for each sibling's unique insight, then archive the siblings).
183
+ b. CREATE A NEW UMBRELLA SKILL.md covering the shared workflow with short labeled subsections, then archive the absorbed siblings.
184
+ c. DEMOTE session-specific detail to references/, templates/, or scripts/ under the umbrella. Use the right directory per kind:
185
+ • references/<topic>.md — session-specific detail OR condensed knowledge banks (quoted research, API docs excerpts, domain notes, provider quirks, reproduction recipes) written concise and task-focused.
186
+ • templates/<name>.<ext> — starter files meant to be copied and modified.
187
+ • scripts/<name>.<ext> — statically re-runnable actions (verification scripts, fixture generators, probes).
188
+ 3. Package integrity — not optional: inspect each skill as a COMPLETE directory package, not just SKILL.md. A skill root may include references/, templates/, scripts/, and assets/. If the source skill has support files OR its SKILL.md contains relative links to them, DO NOT flatten only SKILL.md into <umbrella>/references/<old>.md. Choose one safe path instead: keep it as a standalone skill, OR fully merge by re-homing every needed support file into the umbrella's canonical directories AND rewriting the destination instructions to the new paths, OR archive the entire original skill package unchanged. Never leave demoted instructions pointing at files left behind under the old skill directory.
189
+ 4. Flag skills whose NAME is too narrow (contains a PR number, a feature codename, a specific error string, an 'audit'/'diagnosis'/'salvage' session artifact) — they almost always belong as a subsection or support file under a class-level umbrella.
190
+ 5. Iterate. After one consolidation round, scan the remaining set and look for the NEXT umbrella opportunity. Don't stop after 3 merges.
191
+
192
+ Your toolset:
193
+ - skill_manage action=list / review — read the current landscape.
194
+ - skill_manage action=patch — add sections to the umbrella.
195
+ - skill_manage action=create — create a new umbrella SKILL.md.
196
+ - skill_manage action=write_file — add a references/, templates/, or scripts/ file under an existing skill (the skill must already exist).
197
+ - skill_manage action=delete — archive a skill. MUST pass absorbed_into=<umbrella> when you've merged its content into another skill, or absorbed_into="" when you're truly pruning with no forwarding target.
198
+ - skill_manage action=consolidate — merge source bodies into a target and archive the sources when patching by hand is error-prone.
199
+ - skill_manage action=restore — bring one archived skill back (recoverability is the archive's contract).
200
+ - For moving support files, keep it inside the skill tree: support files move via reading and writing through skill_manage write_file/remove_file.
201
+
202
+ 'keep' is a legitimate decision ONLY when the skill is already a class-level umbrella and none of the proposed merges would improve discoverability. 'This is narrow but distinct from its siblings' is NOT a reason to keep — it's a reason to move it under an umbrella as a subsection or support file.
203
+
204
+ Expected output: real umbrella-ification. Process every obvious cluster. If you end the pass with obvious clusters still untouched, you stopped too early — go back and look at the clusters you left alone.
205
+
206
+ Keep the umbrella body tight and scannable: exact commands, verbatim paths, ~100-200 lines; never invent flags or APIs.
207
+
208
+ When done, write a human summary AND a structured machine-readable block so downstream tooling can distinguish consolidation from pruning. Format EXACTLY:
209
+
210
+ ## Structured summary (required)
211
+ \`\`\`yaml
212
+ consolidations:
213
+ - from: <old-skill-name>
214
+ into: <umbrella-skill-name>
215
+ reason: <one short sentence — why merged, not just 'similar'>
216
+ prunings:
217
+ - name: <skill-name>
218
+ reason: <one short sentence — why archived with no merge target>
219
+ \`\`\`
220
+
221
+ Every skill you moved to .archive/ MUST appear in exactly one of the two lists. If you consolidated X into umbrella Y (patched Y, wrote a references file to Y, or created Y with X's content absorbed), X goes under consolidations with into: Y. If you archived X with no absorption — truly stale, irrelevant, or obsolete — X goes under prunings. Leave a list empty (consolidations: []) if none. Do not omit the block. The block comes AFTER your human-readable summary of clusters processed, patches made, and decisions left alone.`;
222
+ const COMPLETION_SKILL_REVIEW_PROMPT = `[Auto-review — Skills · task complete]
223
+ Your current task now appears complete. Before wrapping up, review the approach and update the skill library via skill_manage.
224
+
225
+ Follow the skills review policy: be ACTIVE, prefer class-level umbrellas, patch ONLY skills loaded or read this session, and capture non-trivial techniques and user corrections. Do NOT capture environment-dependent failures, negative claims about tools, or one-off task narratives.
226
+
227
+ Do NOT modify output files or re-run the task. If you are still mid-task, ignore this.`;
228
+ /**
229
+ * System-prompt guidance section (Hermes `SKILLS_GUIDANCE`, DSH-adapted).
230
+ * Registered as a system-prompt section by tool-skill-manage (it mounts
231
+ * exactly when `skill_manage` is available — the DSH analogue of Hermes'
232
+ * `if "skill_manage" in agent.valid_tool_names` condition). Instructs the
233
+ * model to save/repair skills on its own initiative.
234
+ */
235
+ const SKILLS_GUIDANCE = `Skills guidance:
236
+ • After completing a complex task (5+ tool calls), fixing a tricky error, or discovering a non-trivial workflow, save the approach as a skill with skill_manage so you can reuse it next time.
237
+ • When using a skill and finding it outdated, incomplete, or wrong, patch it immediately with skill_manage (action='patch') — don't wait to be asked. Skills that aren't maintained become liabilities.`;
238
+ function sha256(text) {
239
+ return createHash("sha256").update(text).digest("hex");
240
+ }
241
+ function createPromptBundle(prompts) {
242
+ const canonical = JSON.stringify({
243
+ id: PROMPT_BUNDLE_ID,
244
+ version: 5,
245
+ prompts: Object.fromEntries(Object.entries(prompts).sort())
246
+ });
247
+ return Object.freeze({
248
+ id: PROMPT_BUNDLE_ID,
249
+ version: 5,
250
+ prompts: Object.freeze({ ...prompts }),
251
+ sha256: sha256(canonical)
252
+ });
253
+ }
254
+ createPromptBundle({
255
+ memory: MEMORY_REVIEW_PROMPT,
256
+ skill: SKILL_REVIEW_PROMPT,
257
+ combined: COMBINED_REVIEW_PROMPT,
258
+ curator: CURATOR_PROMPT,
259
+ completion: COMPLETION_SKILL_REVIEW_PROMPT,
260
+ skillsGuidance: SKILLS_GUIDANCE
261
+ });
262
+ //#endregion
263
+ //#region ../evolution-core/src/threats.ts
264
+ const FILLER = String.raw`(?:\w+\s+){0,8}`;
265
+ new RegExp(String.raw`ignore\s+${FILLER}(?:previous|above|prior|all)\s+${FILLER}instructions`, "i"), new RegExp(String.raw`new\s+${FILLER}system\s+${FILLER}prompt`, "i"), new RegExp(String.raw`forget\s+${FILLER}(?:everything|all)\s+${FILLER}(?:discussed|you\s+know)`, "i"), new RegExp(String.raw`you\s+have\s+been\s+${FILLER}(?:updated|upgraded|patched)\s+to`, "i"), new RegExp(String.raw`do\s+not\s+${FILLER}tell\s+${FILLER}the\s+user`, "i"), new RegExp(String.raw`output\s+${FILLER}(?:system|initial)\s+prompt`, "i");
266
+ //#endregion
4
267
  //#region lib/types/index.js
5
268
  /**
6
269
  * Feedback-to-quality scoring for self-evolution.
@@ -74,10 +337,46 @@ var EvolutionFeedback = class {
74
337
  const path = this.path;
75
338
  if (!path || !io) return;
76
339
  await this.mutate(async () => {
77
- await io.writeText(path, JSON.stringify(this.state, null, 2));
340
+ await transactIo(io, path, (current) => {
341
+ const merged = mergeStates(parseState(current), this.state);
342
+ this.state = merged;
343
+ return Promise.resolve(JSON.stringify(merged, null, 2));
344
+ });
78
345
  });
79
346
  }
80
347
  };
348
+ /** Parse a raw feedback sidecar; malformed reads as empty (best-effort). */
349
+ function parseState(raw) {
350
+ if (raw === null) return {
351
+ skills: {},
352
+ sessions: {}
353
+ };
354
+ try {
355
+ const parsed = JSON.parse(raw);
356
+ return {
357
+ skills: typeof parsed.skills === "object" ? parsed.skills : {},
358
+ sessions: typeof parsed.sessions === "object" ? parsed.sessions : {}
359
+ };
360
+ } catch {
361
+ return {
362
+ skills: {},
363
+ sessions: {}
364
+ };
365
+ }
366
+ }
367
+ /** Deep-merge two feedback states: union by target, in-memory values win on conflict. */
368
+ function mergeStates(disk, memory) {
369
+ return {
370
+ skills: {
371
+ ...disk.skills,
372
+ ...memory.skills
373
+ },
374
+ sessions: {
375
+ ...disk.sessions,
376
+ ...memory.sessions
377
+ }
378
+ };
379
+ }
81
380
  const name = "evolution-feedback";
82
381
  const Config = z.object({
83
382
  qualityWarnThreshold: z.number().default(-.25),
@@ -85,10 +384,7 @@ const Config = z.object({
85
384
  });
86
385
  function apply(ctx, rawConfig = {}) {
87
386
  const ioRegistry = ctx.get("evolutionIo");
88
- const io = ioRegistry ? {
89
- readText: (path) => ioRegistry.provider().readText(path),
90
- writeText: (path, content) => ioRegistry.provider().writeText(path, content)
91
- } : void 0;
387
+ const io = ioRegistry ? evolutionIoAdapter(() => ioRegistry.provider()) : void 0;
92
388
  const feedback = new EvolutionFeedback(io, process.env.DSH_HOME ?? join(homedir(), ".dsh"), rawConfig.path || void 0);
93
389
  if (io) feedback.restore(io).catch((error) => {
94
390
  ctx.logger.warn(error);
@@ -8,6 +8,7 @@
8
8
  */
9
9
  import type { Context } from '@deepseek-ai/cordis';
10
10
  import z from '@deepseek-ai/schemastery';
11
+ import { type EvolutionIoLike } from '@deepseek-ai/dsh-evolution-core';
11
12
  declare module '@deepseek-ai/cordis' {
12
13
  interface Context {
13
14
  evolutionFeedback: EvolutionFeedback;
@@ -22,10 +23,7 @@ export interface FeedbackState {
22
23
  skills: Record<string, FeedbackRecord>;
23
24
  sessions: Record<string, FeedbackRecord>;
24
25
  }
25
- interface IoLike {
26
- readText(path: string): Promise<string | null>;
27
- writeText(path: string, content: string): Promise<void>;
28
- }
26
+ type IoLike = EvolutionIoLike;
29
27
  export declare class EvolutionFeedback {
30
28
  private state;
31
29
  private chain;
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@lmzhen/dsh-evolution-feedback",
3
3
  "description": "Feedback-to-quality scoring for self-evolution (community build)",
4
- "version": "0.1.0-rc.60",
4
+ "version": "0.1.0-rc.62",
5
5
  "publishConfig": {
6
6
  "access": "public"
7
7
  },
@@ -37,13 +37,13 @@
37
37
  "peerDependencies": {
38
38
  "@deepseek-ai/dsh-invariants": "^0.1.1-rc.2",
39
39
  "@deepseek-ai/cordis": "^4.0.1",
40
- "@lmzhen/dsh-evolution-io": "^0.1.0-rc.60",
41
- "@lmzhen/dsh-skill-usage": "^0.1.0-rc.60"
40
+ "@lmzhen/dsh-evolution-io": "^0.1.0-rc.62",
41
+ "@lmzhen/dsh-skill-usage": "^0.1.0-rc.62"
42
42
  },
43
43
  "devDependencies": {
44
44
  "@deepseek-ai/dsh-invariants": "^0.1.1-rc.2",
45
- "@lmzhen/dsh-evolution-io": "^0.1.0-rc.60",
46
- "@lmzhen/dsh-evolution-io-node": "^0.1.0-rc.60",
47
- "@lmzhen/dsh-skill-usage": "^0.1.0-rc.60"
45
+ "@lmzhen/dsh-evolution-io": "^0.1.0-rc.62",
46
+ "@lmzhen/dsh-evolution-io-node": "^0.1.0-rc.62",
47
+ "@lmzhen/dsh-skill-usage": "^0.1.0-rc.62"
48
48
  }
49
49
  }