@lmzhen/dsh-evolution-activity 0.44.0 → 0.45.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
package/lib/index.js CHANGED
@@ -191,23 +191,36 @@ function apply(ctx, rawConfig = {}) {
191
191
  const root = evolutionHome();
192
192
  const authority = ioCtx.get("evolutionMutationAuthority");
193
193
  const commit = (path, task) => transactIo(io, path, task);
194
+ /** The ONE cross-process writer: a home fence when the authority provides one, else the seam. */
194
195
  const write = async (path, task) => {
195
196
  if (authority?.homeFence !== void 0) await authority.homeFence.run(async () => {
196
197
  await commit(path, task);
197
198
  });
198
199
  else await commit(path, task);
199
200
  };
200
- let chain = Promise.resolve();
201
- ioCtx.on("evolution/plan-applied", (event) => {
202
- const run = chain.then(() => write(activityFile(root), async (current) => {
201
+ /**
202
+ * One durable fold over the activity file, used by BOTH events.
203
+ *
204
+ * W9/02-P1.3: the review branch used to call transactIo directly while the plan branch went
205
+ * through `write`. Both are read-modify-write over the same file, so the asymmetry meant plan
206
+ * records excluded other processes and review records did not — a review written while another
207
+ * plane appended a plan read a stale snapshot and silently dropped it. One helper, two events.
208
+ */
209
+ const foldActivity = async (task) => {
210
+ await write(activityFile(root), async (current) => {
203
211
  const file = activityFile(root);
204
- if (isCorruptActivity(current)) {
205
- if (!await io.writeText(`${file}.corrupt`, current).then(() => true, () => false)) {
206
- ioCtx.logger.warn(`evolution-activity: ${file} is unreadable; the .corrupt copy could not be written — refusing this write so the original bytes stay recoverable`);
207
- return current;
208
- }
209
- ioCtx.logger.warn(`evolution-activity: ${file} is unreadable (unparsable JSON or wrong top-level shape); the original bytes were copied to ${file}.corrupt and the store restarts from the readable entries`);
212
+ if (!isCorruptActivity(current)) return await task(current);
213
+ if (!await io.writeText(`${file}.corrupt`, current).then(() => true, () => false)) {
214
+ ioCtx.logger.warn(`evolution-activity: ${file} is unreadable; the .corrupt copy could not be written — refusing this write so the original bytes stay recoverable`);
215
+ return current;
210
216
  }
217
+ ioCtx.logger.warn(`evolution-activity: ${file} is unreadable (unparsable JSON or wrong top-level shape); the original bytes were copied to ${file}.corrupt and the store restarts from the readable entries`);
218
+ return await task(current);
219
+ });
220
+ };
221
+ let chain = Promise.resolve();
222
+ ioCtx.on("evolution/plan-applied", (event) => {
223
+ const run = chain.then(() => foldActivity(async (current) => {
211
224
  return serializeActivity(applyActivityEvent(parseActivityContent(current), event, maxItems), parseActivityReviews(current));
212
225
  }));
213
226
  chain = run.then(() => void 0, () => void 0);
@@ -217,15 +230,7 @@ function apply(ctx, rawConfig = {}) {
217
230
  });
218
231
  ioCtx.effect(() => () => chain, "evolution-activity.flush");
219
232
  ioCtx.on("evolution/review-completed", (event) => {
220
- const run = chain.then(() => transactIo(io, activityFile(root), async (current) => {
221
- const file = activityFile(root);
222
- if (isCorruptActivity(current)) {
223
- if (!await io.writeText(`${file}.corrupt`, current).then(() => true, () => false)) {
224
- ioCtx.logger.warn(`evolution-activity: ${file} is unreadable; the .corrupt copy could not be written — refusing this write so the original bytes stay recoverable`);
225
- return current;
226
- }
227
- ioCtx.logger.warn(`evolution-activity: ${file} is unreadable; the original bytes were copied to ${file}.corrupt and the store restarts from the readable entries`);
228
- }
233
+ const run = chain.then(() => foldActivity(async (current) => {
229
234
  const reviews = applyReviewActivityEvent(parseActivityReviews(current), event, maxItems);
230
235
  return serializeActivity(parseActivityContent(current), reviews);
231
236
  }));
@@ -0,0 +1,538 @@
1
+ import z from "@deepseek-ai/schemastery";
2
+ import { SKILL_NAME_RE, authorityFrom, contentHash, errorText, evolutionIoAdapter, isPresent, isUnknown, runWriteGates, skillWriteGateContext } from "@lmzhen/dsh-evolution-core";
3
+ import { effectiveSessionPolicy } from "@lmzhen/dsh-evolution-approval";
4
+ import { newSkillLibrary, relatedSkillNames, resolveExecOrigins } from "@lmzhen/dsh-evolution-core/skills";
5
+ //#region lib/types/learning-graph/index.js
6
+ /**
7
+ * Learning graph over skills and memory, plus node-level commands
8
+ * (`graph [detail|edit|delete] <nodeId>` — P2-33 (v11): the command is a
9
+ * TOP-LEVEL `graph` command, not `/evolution graph`; README is accurate)
10
+ * aligned with the Hermes
11
+ * journey surface: a skill node is its name, a memory node is
12
+ * `memory:<source>:<index>` (source = memory|user, index = position in that
13
+ * file's entries). Memory node ids carry a trailing snapshot token so
14
+ * edit/delete can reject a stale index (E-21).
15
+ * @module @lmzhen/dsh-evolution-learning-graph
16
+ */
17
+ /** V27 INS-04: how many skill files one `/graph` batch reads concurrently.
18
+ * Bounded so a large library cannot open every file at once (EMFILE). */
19
+ const SKILL_READ_BATCH = 16;
20
+ function graphDensity(graph) {
21
+ const linked = /* @__PURE__ */ new Set();
22
+ let relatedEdges = 0;
23
+ for (const edge of graph.edges) {
24
+ if (edge.type !== "related") continue;
25
+ relatedEdges += 1;
26
+ linked.add(edge.from);
27
+ linked.add(edge.to);
28
+ }
29
+ const skillNodes = graph.nodes.filter((node) => node.kind === "skill").length;
30
+ const isolated = graph.nodes.filter((node) => node.kind === "skill" && !linked.has(node.id)).length;
31
+ return {
32
+ skillNodes,
33
+ relatedEdges,
34
+ edgesPerNode: skillNodes === 0 ? 0 : Math.round(relatedEdges / skillNodes * 100) / 100,
35
+ isolatedPct: skillNodes === 0 ? 0 : Math.round(isolated / skillNodes * 100)
36
+ };
37
+ }
38
+ /**
39
+ * Render one node's display line for `/evolution graph`.
40
+ *
41
+ * A skill node's id IS its name, so `● <name>` already addresses it — an
42
+ * isolated skill (no edge) is addressable by name alone. A memory node's id
43
+ * is the `memory:<source>:<index>:<snapshot>` string `buildLearningGraph`
44
+ * emits, so the id is appended in brackets: an isolated memory node (no edge
45
+ * carrying its id) is otherwise unaddressable from the render. The full id is
46
+ * shown (not the bare `memory:<source>:<index>` prefix) so it matches the id
47
+ * form the edge lines render and so the trailing snapshot — the E-21 token the
48
+ * mutation commands use to reject a stale index — survives the copy/paste
49
+ * (F-322). A bare prefix would round-trip through `parseGraphNodeId` but would
50
+ * silently skip the E-21 drift guard in `readMemoryIndex`.
51
+ */
52
+ function renderNodeLine(node) {
53
+ if (node.kind === "skill") return "● " + node.label;
54
+ return "◆ " + node.label + " [id: " + node.id + "]";
55
+ }
56
+ /**
57
+ * Build a small deterministic graph from usage records and memory entries.
58
+ * Memory node ids follow `memory:<source>:<index>` (source = memory|user,
59
+ * index = position in that file's entries) — the SAME rule the parser
60
+ * `parseGraphNodeId` accepts, so graph detail/edit/delete round-trips.
61
+ *
62
+ * Skill-skill edges are semantic only (B-line G3): each entry of `related`
63
+ * (skill name -> names its frontmatter references, from
64
+ * `relatedSkillNames`) becomes an edge when BOTH endpoints exist in the
65
+ * usage set, self-edges are dropped and undirected duplicates collapse. An
66
+ * omitted `related` yields no skill-skill edges — the former alphabet-order
67
+ * chain was a placeholder that connected unrelated neighbors.
68
+ */
69
+ function buildLearningGraph(usage, memoryEntries, userEntries = [], related) {
70
+ const nodes = [...usage.keys()].map((name) => ({
71
+ id: name,
72
+ kind: "skill",
73
+ label: name
74
+ }));
75
+ const edges = [];
76
+ const sorted = [...usage.keys()].sort();
77
+ const seenPairs = /* @__PURE__ */ new Set();
78
+ for (const [from, targets] of related ?? []) {
79
+ if (!usage.has(from)) continue;
80
+ for (const to of targets) {
81
+ if (to === from || !usage.has(to)) continue;
82
+ const pairKey = [from, to].sort().join("->");
83
+ if (seenPairs.has(pairKey)) continue;
84
+ seenPairs.add(pairKey);
85
+ edges.push({
86
+ from,
87
+ to,
88
+ type: "related"
89
+ });
90
+ }
91
+ }
92
+ const appendMemory = (source, entries) => {
93
+ entries.forEach((entry, index) => {
94
+ const label = (entry.split("\n")[0] ?? "").slice(0, 80);
95
+ const id = `memory:${source}:${index}:${memorySnapshotOf(label)}`;
96
+ nodes.push({
97
+ id,
98
+ kind: "memory",
99
+ label
100
+ });
101
+ const words = new Set(entry.toLowerCase().split(/[^a-z0-9-]+/).filter(Boolean));
102
+ for (const name of sorted) if (name && words.has(name.toLowerCase())) edges.push({
103
+ from: id,
104
+ to: name,
105
+ type: "memory_skill"
106
+ });
107
+ });
108
+ };
109
+ appendMemory("memory", memoryEntries);
110
+ appendMemory("user", userEntries);
111
+ return {
112
+ nodes,
113
+ edges
114
+ };
115
+ }
116
+ /**
117
+ * E-21 snapshot token: a deterministic 8-hex-char digest of a memory entry's
118
+ * rendered label (first line, first 80 chars). The graph builder embeds it in
119
+ * the memory node id so a later edit/delete can detect index drift — any
120
+ * memory write between the last render and the command shifts `memory:<source>:<index>`
121
+ * positions, and the token lets the command reject a stale index instead of
122
+ * mutating the wrong entry. FNV-1a (no imports, cross-platform).
123
+ */
124
+ function memorySnapshotOf(entry) {
125
+ const label = (entry.split("\n")[0] ?? "").slice(0, 80);
126
+ let hash = 2166136261;
127
+ for (let i = 0; i < label.length; i += 1) {
128
+ hash ^= label.charCodeAt(i);
129
+ hash = Math.imul(hash, 16777619);
130
+ }
131
+ return (hash >>> 0).toString(16).padStart(8, "0").slice(-8);
132
+ }
133
+ /**
134
+ * E-21 TOCTOU guard for a memory node operation. Re-reads the entry at
135
+ * `parsed.index` and, when the id carries a snapshot token, verifies the
136
+ * current entry's label still matches it. A mismatch means a memory write
137
+ * shifted the index between the last `/graph` render and this command, so the
138
+ * operation is refused (the caller surfaces "re-run /graph"). A missing
139
+ * snapshot (a hand-typed bare `memory:<source>:<index>` id) skips the check
140
+ * and falls back to operating on whatever currently sits at the index.
141
+ */
142
+ function readMemoryIndex(parsed, entries) {
143
+ const entry = entries[parsed.index];
144
+ if (entry === void 0) return {
145
+ ok: false,
146
+ message: `记忆 ${parsed.source}[${parsed.index}] 不存在(共 ${entries.length} 条)。`
147
+ };
148
+ if (parsed.snapshot !== void 0 && memorySnapshotOf(entry) !== parsed.snapshot) return {
149
+ ok: false,
150
+ message: `记忆 ${parsed.source}[${parsed.index}] 在图渲染之后被改动过:请重新运行 /graph 再重试。`
151
+ };
152
+ return {
153
+ ok: true,
154
+ entry
155
+ };
156
+ }
157
+ /**
158
+ * Parse a graph node id: skill names pass through; `memory:<source>:<index>`
159
+ * becomes a memory node. An optional trailing `:<snapshot>` (the E-21
160
+ * `memorySnapshotOf` token the builder embeds) is carried so edit/delete can
161
+ * detect index drift; a bare index id (hand-typed) still parses with no
162
+ * snapshot and skips the drift check.
163
+ */
164
+ function parseGraphNodeId(id) {
165
+ const memory = /^memory:(memory|user):(\d+)(?::([0-9a-f]{8}))?$/.exec(id);
166
+ if (memory) return {
167
+ kind: "memory",
168
+ source: memory[1],
169
+ index: Number(memory[2]),
170
+ ...memory[3] !== void 0 ? { snapshot: memory[3] } : {}
171
+ };
172
+ if (SKILL_NAME_RE.test(id)) return {
173
+ kind: "skill",
174
+ name: id
175
+ };
176
+ return null;
177
+ }
178
+ /** Resolve a parsed node to its current content (read-only). */
179
+ async function resolveGraphNode(parsed, repository) {
180
+ if (parsed.kind === "skill") {
181
+ const content = await repository.readSkill(parsed.name);
182
+ return content === null ? {
183
+ ok: false,
184
+ message: `技能「${parsed.name}」不存在。`
185
+ } : {
186
+ ok: true,
187
+ message: content
188
+ };
189
+ }
190
+ const check = readMemoryIndex(parsed, await repository.readMemory(parsed.source));
191
+ return check.ok ? {
192
+ ok: true,
193
+ message: check.entry ?? ""
194
+ } : {
195
+ ok: false,
196
+ message: check.message ?? `Memory ${parsed.source}[${parsed.index}] 不可用。`
197
+ };
198
+ }
199
+ /**
200
+ * E-26 approval seam (soft-probed, mirrors tool-skill-manage): graph skill
201
+ * mutations route through the same `evolutionApproval.request` gate. The
202
+ * staged `args` use the skill_manage runner's shape so the runner tool-skill-
203
+ * manage registers for `kind: 'skill'` replays them on approve.
204
+ */
205
+ const name = "evolution-learning-graph";
206
+ const Config = z.object({
207
+ root: z.string().default(""),
208
+ threatExemptLabels: z.array(z.string()).default([])
209
+ });
210
+ /**
211
+ * F-10: rendered-line cap for the `/graph` directory — nodes span the
212
+ * whole usage set plus every memory entry and the edge list is a full join, so
213
+ * a large library used to produce an unbounded command result. Nodes and edges
214
+ * are each capped at this many lines (the density footer always renders the
215
+ * true totals); overflow shows a `…N more` marker instead.
216
+ */
217
+ const GRAPH_RENDER_LINE_CAP = 200;
218
+ /** Join lines under the render cap; overflow is summarized, not dropped silently. */
219
+ function capRenderedLines(lines) {
220
+ if (lines.length <= 200) return lines.join("\n");
221
+ return [...lines.slice(0, 200), `…${lines.length - 200} more`].join("\n");
222
+ }
223
+ /**
224
+ * G1/1.2: the graph commands' write-admission call, as a NAMED function.
225
+ *
226
+ * The gates run at the execution point: these commands write at the bytes, exactly like the tool's
227
+ * execution path, so the read-before-write gate does not apply and a missing session read set is not a
228
+ * refusal. `delete` archives (reversible) and is allowed through by the protection gate by design;
229
+ * `update` is what a protected skill is refused for.
230
+ *
231
+ * Named rather than inlined because the wiring it represents - "this command passes the SAME sequence" -
232
+ * has to be provable by a case that fails when the call disappears.
233
+ * @param services - the policy source and the warn sink, both from the command's own context.
234
+ * @param request - the action, the target name, the new body for an update, and the library write origin.
235
+ * @returns the refusal message, or null when the write may proceed.
236
+ */
237
+ async function graphWriteGate(services, request) {
238
+ const isUpdate = request.action === "update";
239
+ const args = isUpdate ? {
240
+ action: "update",
241
+ name: request.name,
242
+ content: request.content ?? ""
243
+ } : {
244
+ action: "delete",
245
+ name: request.name
246
+ };
247
+ return runWriteGates(skillWriteGateContext({
248
+ policy: services.policy,
249
+ confirm: void 0,
250
+ readNames: isUpdate ? new Set([request.name]) : void 0,
251
+ warn: services.warn
252
+ }, {
253
+ point: isUpdate ? "admission" : "execution",
254
+ args,
255
+ origin: request.origin
256
+ }));
257
+ }
258
+ function apply(ctx, rawConfig = {}) {
259
+ ctx.inject(["commands"], (commandCtx) => {
260
+ const commands = commandCtx.commands;
261
+ const graphCommand = {
262
+ name: "graph",
263
+ description: "显示学习图,或对某个节点操作:graph [detail|edit|delete] <nodeId>",
264
+ input: { hint: "[detail|edit|delete] <nodeId> [text]" },
265
+ run: async (invocation) => {
266
+ const ok = (text) => ({
267
+ kind: "success",
268
+ text
269
+ });
270
+ const err = (text) => ({
271
+ kind: "error",
272
+ text
273
+ });
274
+ let writeGateWarned = false;
275
+ const warnWriteGateOnce = (message) => {
276
+ if (writeGateWarned) return;
277
+ writeGateWarned = true;
278
+ ctx.logger.warn(message);
279
+ };
280
+ const usageService = ctx.get("skillUsage");
281
+ const memoryService = ctx.get("memory");
282
+ const ioService = ctx.get("evolutionIo");
283
+ if (!usageService || !memoryService || !ioService) return err("skill-usage、memory 或 evolution-io 服务未挂载。");
284
+ const usage = usageService;
285
+ const memory = memoryService;
286
+ const io = ioService;
287
+ const invocationAgent = invocation.agent;
288
+ const session = invocationAgent?.session;
289
+ const sessionMissing = (need) => session === void 0 ? err(errorText("e-305-this-invocation-carries-no", { a1: need })) : void 0;
290
+ const input = invocation.rawInput.trim();
291
+ const detail = /^detail\s+(\S+)$/.exec(input);
292
+ if (detail && detail[1]) return await nodeDetail(detail[1]);
293
+ const edit = /^edit\s+(\S+)\s+([\s\S]+)$/.exec(input);
294
+ if (edit && edit[1] && edit[2] !== void 0) {
295
+ const gated = sessionMissing("/graph edit");
296
+ if (gated) return gated;
297
+ if (!edit[1].startsWith("memory:")) {
298
+ const stageRead = await probeSkillForStaging(edit[1]);
299
+ if (stageRead !== null) return err(stageRead);
300
+ }
301
+ return await nodeEdit(edit[1], edit[2]);
302
+ }
303
+ const remove = /^delete\s+(\S+)$/.exec(input);
304
+ if (remove && remove[1]) {
305
+ const gated = sessionMissing("/graph delete");
306
+ if (gated) return gated;
307
+ if (!remove[1].startsWith("memory:")) {
308
+ const stageRead = await probeSkillForStaging(remove[1]);
309
+ if (stageRead !== null) return err(stageRead);
310
+ }
311
+ return await nodeDelete(remove[1]);
312
+ }
313
+ const directory = await renderGraph();
314
+ if (input !== "") return err(`未知的 graph 子命令「${input.split(" ")[0]}」。${directory}`);
315
+ return ok(directory);
316
+ /** S1-F3: the pre-staging existence probe shared by edit and delete.
317
+ * @returns null to proceed, or the refusal line to show the operator. */
318
+ async function probeSkillForStaging(name) {
319
+ try {
320
+ if (await withSkills().read(name) !== null) return null;
321
+ return `实时技能库里没有技能「${name}」,即该技能不存在。(图里可能显示的是过期节点。)`;
322
+ } catch (error) {
323
+ return `无法读取技能「${name}」以确认它存在(${error instanceof Error ? error.message : String(error)}):拒绝暂存。该技能可能仍然存在;请解决读取失败后重试。`;
324
+ }
325
+ }
326
+ async function renderGraph() {
327
+ const usageReport = await usage.report();
328
+ const usageMap = new Map((await withSkills().treeNames()).map((name) => [name, usageReport.get(name)]));
329
+ const memoryEntries = await memory.read("memory");
330
+ const userEntries = await memory.read("user");
331
+ const skills = withSkills();
332
+ const names = [...usageMap.keys()];
333
+ const contents = [];
334
+ let unreadable = 0;
335
+ for (let offset = 0; offset < names.length; offset += SKILL_READ_BATCH) {
336
+ const batch = names.slice(offset, offset + SKILL_READ_BATCH);
337
+ const batchContents = await Promise.all(batch.map(async (name) => {
338
+ try {
339
+ return await skills.read(name);
340
+ } catch {
341
+ unreadable += 1;
342
+ return null;
343
+ }
344
+ }));
345
+ contents.push(...batchContents);
346
+ }
347
+ if (unreadable > 0) ctx.logger.warn(`evolution-learning-graph: ${unreadable} skill file(s) could not be read; their related_skills edges are missing from this graph`);
348
+ const related = /* @__PURE__ */ new Map();
349
+ names.forEach((name, index) => {
350
+ const content = contents[index];
351
+ if (content === null || content === void 0) return;
352
+ related.set(name, relatedSkillNames(content, name));
353
+ });
354
+ const graph = buildLearningGraph(usageMap, memoryEntries, userEntries, related);
355
+ const nodeBlock = capRenderedLines(graph.nodes.map((node) => renderNodeLine(node)));
356
+ const edgeBlock = capRenderedLines(graph.edges.map((edge) => edge.from + " --" + edge.type + "--> " + edge.to));
357
+ const density = graphDensity(graph);
358
+ const densityLine = `\n\nSkills: ${density.skillNodes} · related edges: ${density.relatedEdges} (${density.edgesPerNode}/node) · isolated: ${density.isolatedPct}%`;
359
+ return nodeBlock + "\n\n" + edgeBlock + densityLine;
360
+ }
361
+ function withSkills() {
362
+ return newSkillLibrary({
363
+ authority: authorityFrom({ origin: "foreground" }),
364
+ config: rawConfig,
365
+ io: evolutionIoAdapter(() => io.provider()),
366
+ ctx,
367
+ threatExemptLabels: rawConfig.threatExemptLabels
368
+ });
369
+ }
370
+ async function nodeDetail(id) {
371
+ const parsed = parseGraphNodeId(id);
372
+ if (parsed === null) return err(`节点 id「${id}」不合法:应为技能名或 memory:<source>:<index>。`);
373
+ const resolved = await resolveGraphNode(parsed, {
374
+ readSkill: (name) => withSkills().read(name),
375
+ readMemory: (target) => memory.read(target)
376
+ });
377
+ return resolved.ok ? ok(resolved.message) : err(resolved.message);
378
+ }
379
+ async function nodeEdit(id, content) {
380
+ const parsed = parseGraphNodeId(id);
381
+ if (parsed === null) return err(`节点 id「${id}」不合法:应为技能名或 memory:<source>:<index>。`);
382
+ if (parsed.kind === "skill") {
383
+ const approval = ctx.get("evolutionApproval");
384
+ const origins = resolveExecOrigins(invocationAgent && { agent: invocationAgent });
385
+ if (approval) {
386
+ const sessionPolicyEdit = effectiveSessionPolicy(ctx, session);
387
+ const stagesForeground = approval.stageForeground !== false;
388
+ if (approval.isEnabled !== false && sessionPolicyEdit !== "never" && (origins.approval === "background_review" || stagesForeground) && !approval.hasRunner("skill")) return err("无法暂存 graph 技能写入:没有注册技能回放运行器 —— 请挂载 tool-skill-manage 行(evolution-agent 预设),或禁用 evolution-approval。");
389
+ const sessionPolicy = sessionPolicyEdit;
390
+ const stageProbe = await withSkills().readSkillProbe(parsed.name);
391
+ const stageCurrent = isUnknown(stageProbe) ? void 0 : isPresent(stageProbe) ? stageProbe.value : null;
392
+ const decision = await approval.request({
393
+ kind: "skill",
394
+ summary: `graph edit ${parsed.name}`,
395
+ args: {
396
+ operation: {
397
+ action: "update",
398
+ name: parsed.name,
399
+ content,
400
+ staged_from_sha256: typeof stageCurrent === "string" ? contentHash(stageCurrent) : "absent"
401
+ },
402
+ origin: origins.approval,
403
+ libraryOrigin: origins.library
404
+ },
405
+ origin: origins.approval,
406
+ ...session?.id ? { sessionId: session.id } : {},
407
+ session,
408
+ ...sessionPolicy !== void 0 ? { sessionPolicy } : {}
409
+ });
410
+ if (decision.action === "staged") return ok(decision.message);
411
+ }
412
+ const graphRefusal = await graphWriteGate({
413
+ policy: ctx.get("evolutionPolicy"),
414
+ warn: warnWriteGateOnce
415
+ }, {
416
+ action: "update",
417
+ name: parsed.name,
418
+ content,
419
+ origin: resolveExecOrigins(invocationAgent && { agent: invocationAgent }).library
420
+ });
421
+ if (graphRefusal !== null) return err(graphRefusal);
422
+ const result = await withSkills().update(parsed.name, content, origins.library);
423
+ if (result.ok && result.noop !== true) await usageService.record?.(parsed.name, "patch");
424
+ return result.ok ? ok(result.message) : err(result.message);
425
+ }
426
+ const check = readMemoryIndex(parsed, await memory.read(parsed.source));
427
+ if (!check.ok) return err(check.message ?? "记忆索引检查失败。");
428
+ const memoryApproval = ctx.get("evolutionApproval");
429
+ if (memoryApproval) {
430
+ const originsM = resolveExecOrigins(invocationAgent && { agent: invocationAgent });
431
+ const sessionPolicyM = effectiveSessionPolicy(ctx, session);
432
+ if (memoryApproval.isEnabled !== false && sessionPolicyM !== "never" && (originsM.approval === "background_review" || memoryApproval.stageForeground !== false) && !memoryApproval.hasRunner("memory")) return err("无法暂存 graph 记忆写入:没有注册记忆回放运行器 —— 请挂载 tool-memory 行(evolution-all bundle,或 evolution-preset overlay;宿主 bundle 里不含它),或禁用 evolution-approval。");
433
+ const decision = await memoryApproval.request({
434
+ kind: "memory",
435
+ summary: `graph edit memory:${parsed.source}:${parsed.index}`,
436
+ args: {
437
+ target: parsed.source,
438
+ operations: [{
439
+ action: "replace",
440
+ old_text: check.entry ?? "",
441
+ facts: content
442
+ }]
443
+ },
444
+ origin: originsM.approval,
445
+ ...session?.id ? { sessionId: session.id } : {},
446
+ session,
447
+ ...sessionPolicyM !== void 0 ? { sessionPolicy: sessionPolicyM } : {}
448
+ });
449
+ if (decision.action === "staged") return ok(decision.message);
450
+ }
451
+ const result = await memory.applyBatch(parsed.source, [{
452
+ action: "replace",
453
+ old_text: check.entry ?? "",
454
+ facts: content
455
+ }]);
456
+ return result.ok ? ok(result.message) : err(result.message);
457
+ }
458
+ async function nodeDelete(id) {
459
+ const parsed = parseGraphNodeId(id);
460
+ if (parsed === null) return err(`节点 id「${id}」不合法:应为技能名或 memory:<source>:<index>。`);
461
+ if (parsed.kind === "skill") {
462
+ const approval = ctx.get("evolutionApproval");
463
+ if (approval) {
464
+ const origins = resolveExecOrigins(invocationAgent && { agent: invocationAgent });
465
+ const sessionPolicy = effectiveSessionPolicy(ctx, session);
466
+ if (approval.isEnabled !== false && sessionPolicy !== "never" && (origins.approval === "background_review" || approval.stageForeground !== false) && !approval.hasRunner("skill")) return err("无法暂存 graph 技能删除:没有注册技能回放运行器 —— 请挂载 tool-skill-manage 行(evolution-agent 预设),或禁用 evolution-approval。");
467
+ const decision = await approval.request({
468
+ kind: "skill",
469
+ summary: `graph delete ${parsed.name}`,
470
+ args: {
471
+ operation: {
472
+ action: "delete",
473
+ name: parsed.name
474
+ },
475
+ origin: origins.approval,
476
+ libraryOrigin: origins.library
477
+ },
478
+ origin: origins.approval,
479
+ ...session?.id ? { sessionId: session.id } : {},
480
+ session,
481
+ ...sessionPolicy !== void 0 ? { sessionPolicy } : {}
482
+ });
483
+ if (decision.action === "staged") return ok(decision.message);
484
+ }
485
+ const graphRefusal = await graphWriteGate({
486
+ policy: ctx.get("evolutionPolicy"),
487
+ warn: warnWriteGateOnce
488
+ }, {
489
+ action: "delete",
490
+ name: parsed.name,
491
+ origin: resolveExecOrigins(invocationAgent && { agent: invocationAgent }).library
492
+ });
493
+ if (graphRefusal !== null) return err(graphRefusal);
494
+ const result = await withSkills().archive(parsed.name);
495
+ if (result.ok) await usageService?.markArchived?.(parsed.name);
496
+ return result.ok ? ok(result.message) : err(result.message);
497
+ }
498
+ const check = readMemoryIndex(parsed, await memory.read(parsed.source));
499
+ if (!check.ok) return err(check.message ?? "记忆索引检查失败。");
500
+ const memoryApproval = ctx.get("evolutionApproval");
501
+ if (memoryApproval) {
502
+ const origins = resolveExecOrigins(invocationAgent && { agent: invocationAgent });
503
+ const sessionPolicy = effectiveSessionPolicy(ctx, session);
504
+ if (memoryApproval.isEnabled !== false && sessionPolicy !== "never" && (origins.approval === "background_review" || memoryApproval.stageForeground !== false) && !memoryApproval.hasRunner("memory")) return err("无法暂存 graph 记忆删除:没有注册记忆回放运行器 —— 请挂载 tool-memory 行(evolution-all bundle,或 evolution-preset overlay;宿主 bundle 里不含它),或禁用 evolution-approval。");
505
+ const decision = await memoryApproval.request({
506
+ kind: "memory",
507
+ summary: `graph delete memory:${parsed.source}:${parsed.index}`,
508
+ args: {
509
+ target: parsed.source,
510
+ operations: [{
511
+ action: "remove",
512
+ old_text: check.entry ?? ""
513
+ }]
514
+ },
515
+ origin: origins.approval,
516
+ ...session?.id ? { sessionId: session.id } : {},
517
+ session,
518
+ ...sessionPolicy !== void 0 ? { sessionPolicy } : {}
519
+ });
520
+ if (decision.action === "staged") return ok(decision.message);
521
+ }
522
+ const result = await memory.applyBatch(parsed.source, [{
523
+ action: "remove",
524
+ old_text: check.entry ?? ""
525
+ }]);
526
+ return result.ok ? ok(result.message) : err(result.message);
527
+ }
528
+ },
529
+ handler: (invocation) => graphCommand.run(invocation).catch((error) => ({
530
+ kind: "error",
531
+ text: `graph:命令失败:${error instanceof Error ? error.message : String(error)}\n请检查节点 id 以及 evolution 根目录下的 skills/memory 文件,然后重试。`
532
+ }))
533
+ };
534
+ commandCtx.effect(() => commands.register(graphCommand), "evolution-learning-graph.command");
535
+ });
536
+ }
537
+ //#endregion
538
+ export { Config, GRAPH_RENDER_LINE_CAP, apply, buildLearningGraph, capRenderedLines, graphDensity, graphWriteGate, memorySnapshotOf, name, parseGraphNodeId, readMemoryIndex, renderNodeLine, resolveGraphNode };