@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
@@ -0,0 +1,712 @@
1
+ /**
2
+ * Learning graph over skills and memory, plus node-level commands
3
+ * (`graph [detail|edit|delete] <nodeId>` — P2-33 (v11): the command is a
4
+ * TOP-LEVEL `graph` command, not `/evolution graph`; README is accurate)
5
+ * aligned with the Hermes
6
+ * journey surface: a skill node is its name, a memory node is
7
+ * `memory:<source>:<index>` (source = memory|user, index = position in that
8
+ * file's entries). Memory node ids carry a trailing snapshot token so
9
+ * edit/delete can reject a stale index (E-21).
10
+ * @module @lmzhen/dsh-evolution-learning-graph
11
+ */
12
+ import { isPresent, isUnknown, authorityFrom, runWriteGates, skillWriteGateContext } from '@lmzhen/dsh-evolution-core';
13
+ import { effectiveSessionPolicy } from '@lmzhen/dsh-evolution-approval';
14
+ import z from '@deepseek-ai/schemastery';
15
+ import { errorText, SKILL_NAME_RE, contentHash, evolutionIoAdapter } from '@lmzhen/dsh-evolution-core';
16
+ import { relatedSkillNames } from '@lmzhen/dsh-evolution-core/skills';
17
+ import { resolveExecOrigins, newSkillLibrary } from '@lmzhen/dsh-evolution-core/skills';
18
+ // N1 (v12), V27 G5.2: the command invocation contract is the platform's own
19
+ // `CommandInvocation` (imported above from `@deepseek-ai/dsh-commands`). It
20
+ // freezes the invoking agent onto the invocation object — evolution-commands
21
+ // `/evolution learn` reads `invocation.agent` the same way — so the graph can
22
+ // pass `agent.session` to the approval service (tool-skill-manage pattern)
23
+ // instead of deriving every approval as foreground. The local structural view
24
+ // this replaces made an upstream shape change invisible to this package.
25
+ /** V27 INS-04: how many skill files one `/graph` batch reads concurrently.
26
+ * Bounded so a large library cannot open every file at once (EMFILE). */
27
+ const SKILL_READ_BATCH = 16;
28
+ export function graphDensity(graph) {
29
+ const linked = new Set();
30
+ let relatedEdges = 0;
31
+ for (const edge of graph.edges) {
32
+ if (edge.type !== 'related')
33
+ continue;
34
+ relatedEdges += 1;
35
+ linked.add(edge.from);
36
+ linked.add(edge.to);
37
+ }
38
+ const skillNodes = graph.nodes.filter(node => node.kind === 'skill').length;
39
+ const isolated = graph.nodes.filter(node => node.kind === 'skill' && !linked.has(node.id)).length;
40
+ return {
41
+ skillNodes,
42
+ relatedEdges,
43
+ edgesPerNode: skillNodes === 0 ? 0 : Math.round((relatedEdges / skillNodes) * 100) / 100,
44
+ isolatedPct: skillNodes === 0 ? 0 : Math.round((isolated / skillNodes) * 100),
45
+ };
46
+ }
47
+ /**
48
+ * Render one node's display line for `/evolution graph`.
49
+ *
50
+ * A skill node's id IS its name, so `● <name>` already addresses it — an
51
+ * isolated skill (no edge) is addressable by name alone. A memory node's id
52
+ * is the `memory:<source>:<index>:<snapshot>` string `buildLearningGraph`
53
+ * emits, so the id is appended in brackets: an isolated memory node (no edge
54
+ * carrying its id) is otherwise unaddressable from the render. The full id is
55
+ * shown (not the bare `memory:<source>:<index>` prefix) so it matches the id
56
+ * form the edge lines render and so the trailing snapshot — the E-21 token the
57
+ * mutation commands use to reject a stale index — survives the copy/paste
58
+ * (F-322). A bare prefix would round-trip through `parseGraphNodeId` but would
59
+ * silently skip the E-21 drift guard in `readMemoryIndex`.
60
+ */
61
+ export function renderNodeLine(node) {
62
+ if (node.kind === 'skill')
63
+ return '● ' + node.label;
64
+ return '◆ ' + node.label + ' [id: ' + node.id + ']';
65
+ }
66
+ /**
67
+ * Build a small deterministic graph from usage records and memory entries.
68
+ * Memory node ids follow `memory:<source>:<index>` (source = memory|user,
69
+ * index = position in that file's entries) — the SAME rule the parser
70
+ * `parseGraphNodeId` accepts, so graph detail/edit/delete round-trips.
71
+ *
72
+ * Skill-skill edges are semantic only (B-line G3): each entry of `related`
73
+ * (skill name -> names its frontmatter references, from
74
+ * `relatedSkillNames`) becomes an edge when BOTH endpoints exist in the
75
+ * usage set, self-edges are dropped and undirected duplicates collapse. An
76
+ * omitted `related` yields no skill-skill edges — the former alphabet-order
77
+ * chain was a placeholder that connected unrelated neighbors.
78
+ */
79
+ export function buildLearningGraph(usage, memoryEntries, userEntries = [], related) {
80
+ const nodes = [...usage.keys()].map(name => ({
81
+ id: name,
82
+ kind: 'skill',
83
+ label: name,
84
+ }));
85
+ const edges = [];
86
+ const sorted = [...usage.keys()].sort();
87
+ const seenPairs = new Set();
88
+ for (const [from, targets] of related ?? []) {
89
+ if (!usage.has(from))
90
+ continue;
91
+ for (const to of targets) {
92
+ if (to === from || !usage.has(to))
93
+ continue;
94
+ const pairKey = [from, to].sort().join('->');
95
+ if (seenPairs.has(pairKey))
96
+ continue;
97
+ seenPairs.add(pairKey);
98
+ edges.push({ from, to, type: 'related' });
99
+ }
100
+ }
101
+ const appendMemory = (source, entries) => {
102
+ entries.forEach((entry, index) => {
103
+ // E-72 (D-9): `split('\n')[0]` is never undefined (a string always
104
+ // splits into at least one element), so the former `?? id` fallback was
105
+ // unreachable and is gone; an empty entry just yields an empty label.
106
+ const label = (entry.split('\n')[0] ?? '').slice(0, 80);
107
+ // E-21: id carries the label snapshot so edit/delete detect index drift.
108
+ const id = `memory:${source}:${index}:${memorySnapshotOf(label)}`;
109
+ nodes.push({ id, kind: 'memory', label });
110
+ // E-72: word-level matching, not substring. Split the entry into word
111
+ // tokens on non-letter/digit/hyphen runs (a hyphenated skill name like
112
+ // `python-testing` stays one token) and require the skill name to be a
113
+ // whole token — so skill `run` no longer links "running"/"grunt".
114
+ const words = new Set(entry.toLowerCase().split(/[^a-z0-9-]+/).filter(Boolean));
115
+ for (const name of sorted) {
116
+ if (name && words.has(name.toLowerCase()))
117
+ edges.push({ from: id, to: name, type: 'memory_skill' });
118
+ }
119
+ });
120
+ };
121
+ appendMemory('memory', memoryEntries);
122
+ appendMemory('user', userEntries);
123
+ return { nodes, edges };
124
+ }
125
+ /**
126
+ * E-21 snapshot token: a deterministic 8-hex-char digest of a memory entry's
127
+ * rendered label (first line, first 80 chars). The graph builder embeds it in
128
+ * the memory node id so a later edit/delete can detect index drift — any
129
+ * memory write between the last render and the command shifts `memory:<source>:<index>`
130
+ * positions, and the token lets the command reject a stale index instead of
131
+ * mutating the wrong entry. FNV-1a (no imports, cross-platform).
132
+ */
133
+ export function memorySnapshotOf(entry) {
134
+ // `[0]` is never undefined (split always yields one element); asserted for
135
+ // noUncheckedIndexedAccess — see buildLearningGraph (E-72 / D-9).
136
+ const label = (entry.split('\n')[0] ?? '').slice(0, 80);
137
+ let hash = 0x811c9dc5;
138
+ for (let i = 0; i < label.length; i += 1) {
139
+ hash ^= label.charCodeAt(i);
140
+ hash = Math.imul(hash, 0x01000193);
141
+ }
142
+ return (hash >>> 0).toString(16).padStart(8, '0').slice(-8);
143
+ }
144
+ /**
145
+ * E-21 TOCTOU guard for a memory node operation. Re-reads the entry at
146
+ * `parsed.index` and, when the id carries a snapshot token, verifies the
147
+ * current entry's label still matches it. A mismatch means a memory write
148
+ * shifted the index between the last `/graph` render and this command, so the
149
+ * operation is refused (the caller surfaces "re-run /graph"). A missing
150
+ * snapshot (a hand-typed bare `memory:<source>:<index>` id) skips the check
151
+ * and falls back to operating on whatever currently sits at the index.
152
+ */
153
+ export function readMemoryIndex(parsed, entries) {
154
+ const entry = entries[parsed.index];
155
+ if (entry === undefined) {
156
+ return { ok: false, message: `记忆 ${parsed.source}[${parsed.index}] 不存在(共 ${entries.length} 条)。` };
157
+ }
158
+ if (parsed.snapshot !== undefined && memorySnapshotOf(entry) !== parsed.snapshot) {
159
+ return { ok: false, message: `记忆 ${parsed.source}[${parsed.index}] 在图渲染之后被改动过:请重新运行 /graph 再重试。` };
160
+ }
161
+ return { ok: true, entry };
162
+ }
163
+ /**
164
+ * Parse a graph node id: skill names pass through; `memory:<source>:<index>`
165
+ * becomes a memory node. An optional trailing `:<snapshot>` (the E-21
166
+ * `memorySnapshotOf` token the builder embeds) is carried so edit/delete can
167
+ * detect index drift; a bare index id (hand-typed) still parses with no
168
+ * snapshot and skips the drift check.
169
+ */
170
+ export function parseGraphNodeId(id) {
171
+ const memory = /^memory:(memory|user):(\d+)(?::([0-9a-f]{8}))?$/.exec(id);
172
+ if (memory) {
173
+ return {
174
+ kind: 'memory',
175
+ source: memory[1],
176
+ index: Number(memory[2]),
177
+ ...(memory[3] !== undefined ? { snapshot: memory[3] } : {}),
178
+ };
179
+ }
180
+ if (SKILL_NAME_RE.test(id))
181
+ return { kind: 'skill', name: id };
182
+ return null;
183
+ }
184
+ /** Resolve a parsed node to its current content (read-only). */
185
+ export async function resolveGraphNode(parsed, repository) {
186
+ if (parsed.kind === 'skill') {
187
+ const content = await repository.readSkill(parsed.name);
188
+ return content === null
189
+ ? { ok: false, message: `技能「${parsed.name}」不存在。` }
190
+ : { ok: true, message: content };
191
+ }
192
+ const entries = await repository.readMemory(parsed.source);
193
+ // E-5 (v18): detail must apply the SAME E-21 snapshot check as edit/delete;
194
+ // an index that shifted since the graph render used to display another entry.
195
+ const check = readMemoryIndex(parsed, entries);
196
+ return check.ok
197
+ ? { ok: true, message: check.entry ?? '' }
198
+ : { ok: false, message: check.message ?? `Memory ${parsed.source}[${parsed.index}] 不可用。` };
199
+ }
200
+ /**
201
+ * E-26 approval seam (soft-probed, mirrors tool-skill-manage): graph skill
202
+ * mutations route through the same `evolutionApproval.request` gate. The
203
+ * staged `args` use the skill_manage runner's shape so the runner tool-skill-
204
+ * manage registers for `kind: 'skill'` replays them on approve.
205
+ */
206
+ // 0.3.19 (W1.2): ApprovalLike is imported from evolution-approval (the one
207
+ // authoritative consumer shape) instead of this local view.
208
+ export const name = 'evolution-learning-graph';
209
+ export const Config = z.object({
210
+ root: z.string().default(''),
211
+ threatExemptLabels: z.array(z.string()).default([]),
212
+ });
213
+ /**
214
+ * F-10: rendered-line cap for the `/graph` directory — nodes span the
215
+ * whole usage set plus every memory entry and the edge list is a full join, so
216
+ * a large library used to produce an unbounded command result. Nodes and edges
217
+ * are each capped at this many lines (the density footer always renders the
218
+ * true totals); overflow shows a `…N more` marker instead.
219
+ */
220
+ export const GRAPH_RENDER_LINE_CAP = 200;
221
+ /** Join lines under the render cap; overflow is summarized, not dropped silently. */
222
+ export function capRenderedLines(lines) {
223
+ if (lines.length <= GRAPH_RENDER_LINE_CAP)
224
+ return lines.join('\n');
225
+ return [...lines.slice(0, GRAPH_RENDER_LINE_CAP), `…${lines.length - GRAPH_RENDER_LINE_CAP} more`].join('\n');
226
+ }
227
+ /**
228
+ * G1/1.2: the graph commands' write-admission call, as a NAMED function.
229
+ *
230
+ * The gates run at the execution point: these commands write at the bytes, exactly like the tool's
231
+ * execution path, so the read-before-write gate does not apply and a missing session read set is not a
232
+ * refusal. `delete` archives (reversible) and is allowed through by the protection gate by design;
233
+ * `update` is what a protected skill is refused for.
234
+ *
235
+ * Named rather than inlined because the wiring it represents - "this command passes the SAME sequence" -
236
+ * has to be provable by a case that fails when the call disappears.
237
+ * @param services - the policy source and the warn sink, both from the command's own context.
238
+ * @param request - the action, the target name, the new body for an update, and the library write origin.
239
+ * @returns the refusal message, or null when the write may proceed.
240
+ */
241
+ export async function graphWriteGate(services, request) {
242
+ // MEASURED: the protection gate only runs at the ADMISSION point. Wiring both actions at `execution`
243
+ // let /graph edit rewrite a protected skill - the policy list was read and then never consulted. The
244
+ // edit branch reads the target first (it stages the old body), so an admission read set naming it is
245
+ // truthful; the archive branch does not read it, and archive is reversible, so it stays at execution.
246
+ const isUpdate = request.action === 'update';
247
+ const args = isUpdate
248
+ ? { action: 'update', name: request.name, content: request.content ?? '' }
249
+ : { action: 'delete', name: request.name };
250
+ return runWriteGates(skillWriteGateContext({
251
+ policy: services.policy,
252
+ confirm: undefined,
253
+ readNames: isUpdate ? new Set([request.name]) : undefined,
254
+ warn: services.warn,
255
+ }, { point: isUpdate ? 'admission' : 'execution', args, origin: request.origin }));
256
+ }
257
+ export function apply(ctx, rawConfig = {}) {
258
+ // V10-11 (P2-7): single root resolution for every graph skill read/edit —
259
+ // empty config falls through to the shared default root inside the resolver.
260
+ // P2-26 (0.3.75): the resolution moved into newSkillLibrary(rawConfig).
261
+ ctx.inject(['commands'], (commandCtx) => {
262
+ // V27 G5.2: the platform's `Context.commands` augmentation and its
263
+ // `CommandDefinition` type are the contract (previously a local cast to
264
+ // `{ register(definition: unknown) }`, which silenced every upstream shape
265
+ // change). `@deepseek-ai/dsh-commands` is a declared peer.
266
+ const commands = commandCtx.commands;
267
+ // M-11 (v3 audit): the register disposer must be bound to the fiber — an
268
+ // unbound registration survives HMR/reload and duplicates the command.
269
+ // v28 G0.3 (CMD-01): the definition is a const so `handler` can delegate
270
+ // to `run` — the wrapper is the ONE net for unexpected throws (an
271
+ // unreadable skill/memory/state file re-thrown out of SkillLibrary.read),
272
+ // the same contract the /evolution wrapper enforces. v27's INS-04 guarded
273
+ // the skill fan-out only; nodeDetail/memory reads/usage.report stayed bare.
274
+ const graphCommand = {
275
+ name: 'graph',
276
+ description: '显示学习图,或对某个节点操作:graph [detail|edit|delete] <nodeId>',
277
+ // F-5 (0.23.0, owner decision): same as `/evolution` — record the input rather than hiding it
278
+ // from the durable record; the platform default is what this surface now gets.
279
+ // input declaration (same fix as /evolution, 2026-08-31): the frontend
280
+ // drops every argument after the first word for commands without it —
281
+ // /graph detail <id> submitted as the bare /graph.
282
+ input: {
283
+ hint: '[detail|edit|delete] <nodeId> [text]',
284
+ },
285
+ run: async (invocation) => {
286
+ const ok = (text) => ({ kind: 'success', text });
287
+ const err = (text) => ({ kind: 'error', text });
288
+ // G1/1.2: the graph commands now pass the SAME write-admission sequence as the tool. The warn sink
289
+ // latches once per process, exactly like the tool's: what it reports (no question service, an
290
+ // unreadable session log) belongs to the deployment, not to one write.
291
+ let writeGateWarned = false;
292
+ const warnWriteGateOnce = (message) => {
293
+ if (writeGateWarned)
294
+ return;
295
+ writeGateWarned = true;
296
+ ctx.logger.warn(message);
297
+ };
298
+ const usageService = ctx.get('skillUsage');
299
+ const memoryService = ctx.get('memory');
300
+ const ioService = ctx.get('evolutionIo');
301
+ if (!usageService || !memoryService || !ioService)
302
+ return err('skill-usage、memory 或 evolution-io 服务未挂载。');
303
+ const usage = usageService;
304
+ const memory = memoryService;
305
+ const io = ioService;
306
+ // A4 (audit P1-5): the platform type declares `invocation.agent`
307
+ // non-optional, but the family's own 0.3.80 record
308
+ // (evolution-commands/src/index.ts) documents real session-less
309
+ // callers (scripts, headless probes). Read-only branches answer
310
+ // without a session; write branches refuse with the SAME E-305 the
311
+ // /evolution command family answers, instead of a raw TypeError.
312
+ const invocationAgent = invocation.agent;
313
+ const session = invocationAgent?.session;
314
+ const sessionMissing = (need) => session === undefined
315
+ ? err(errorText('e-305-this-invocation-carries-no', { a1: need }))
316
+ : undefined;
317
+ const input = invocation.rawInput.trim();
318
+ const detail = /^detail\s+(\S+)$/.exec(input);
319
+ if (detail && detail[1])
320
+ return await nodeDetail(detail[1]);
321
+ const edit = /^edit\s+(\S+)\s+([\s\S]+)$/.exec(input);
322
+ if (edit && edit[1] && edit[2] !== undefined) {
323
+ const gated = sessionMissing('/graph edit');
324
+ if (gated)
325
+ return gated;
326
+ // v30 GRAPH-03: refuse BEFORE staging — a nonexistent (or archived/
327
+ // delisted) SKILL produced an approval record whose replay could
328
+ // never succeed ("Skill not found"), wasting an operator approval.
329
+ // The memory branches already pre-check their index the same way.
330
+ // `memory:*` ids are MEMORY nodes (their own pre-check covers them)
331
+ // and are exempt here.
332
+ // S1-F3: only a clean ENOENT reads as "not found" — the old
333
+ // `.catch(() => null)` folded every read failure (EACCES, EMFILE, a
334
+ // transient win32 hold) into the not-found refusal, misdirecting the
335
+ // operator toward deleting/recreating a skill that actually exists
336
+ // (the E-9 "unreadable ≠ absent" posture the rest of the family
337
+ // already follows).
338
+ if (!edit[1].startsWith('memory:')) {
339
+ const stageRead = await probeSkillForStaging(edit[1]);
340
+ if (stageRead !== null)
341
+ return err(stageRead);
342
+ }
343
+ return await nodeEdit(edit[1], edit[2]);
344
+ }
345
+ const remove = /^delete\s+(\S+)$/.exec(input);
346
+ if (remove && remove[1]) {
347
+ const gated = sessionMissing('/graph delete');
348
+ if (gated)
349
+ return gated;
350
+ if (!remove[1].startsWith('memory:')) {
351
+ const stageRead = await probeSkillForStaging(remove[1]);
352
+ if (stageRead !== null)
353
+ return err(stageRead);
354
+ }
355
+ return await nodeDelete(remove[1]);
356
+ }
357
+ const directory = await renderGraph();
358
+ if (input !== '')
359
+ return err(`未知的 graph 子命令「${input.split(' ')[0]}」。${directory}`);
360
+ return ok(directory);
361
+ /** S1-F3: the pre-staging existence probe shared by edit and delete.
362
+ * @returns null to proceed, or the refusal line to show the operator. */
363
+ async function probeSkillForStaging(name) {
364
+ try {
365
+ const body = await withSkills().read(name);
366
+ if (body !== null)
367
+ return null;
368
+ return `实时技能库里没有技能「${name}」,即该技能不存在。(图里可能显示的是过期节点。)`;
369
+ }
370
+ catch (error) {
371
+ const reason = error instanceof Error ? error.message : String(error);
372
+ return `无法读取技能「${name}」以确认它存在(${reason}):拒绝暂存。该技能可能仍然存在;请解决读取失败后重试。`;
373
+ }
374
+ }
375
+ async function renderGraph() {
376
+ const usageReport = await usage.report();
377
+ // T2-V2/A27: membership comes from the TREE — the same set `graph delete` resolves against —
378
+ // never from the usage sidecar. Deciding it from the sidecar made a skill directory created
379
+ // outside the family INVISIBLE to `/graph` while `graph delete` could still archive it, and
380
+ // rendered a record left behind by a skill deleted outside the family as a node nothing could
381
+ // act on. The sidecar now only supplies metadata for the nodes it knows.
382
+ //
383
+ // The name-only listing is deliberate: the bodies are read once below (for related_skills),
384
+ // so membership must not cost a second whole-tree pass.
385
+ //
386
+ // v29 GRAPH-02 is answered by the same predicate: an archived skill has left the tree (.archive
387
+ // is dot-prefixed and skipped), so no `state==='archived'` filter is needed — and keeping one
388
+ // would put the sidecar back in charge of membership.
389
+ const usageMap = new Map((await withSkills().treeNames()).map(name => [name, usageReport.get(name)]));
390
+ const memoryEntries = await memory.read('memory');
391
+ const userEntries = await memory.read('user');
392
+ // Semantic skill-skill edges (B-line G3): read each usage-known
393
+ // skill and collect its related_skills through the shared parser —
394
+ // the same source the quality references factor uses.
395
+ // P3 (v15): reads run concurrently — the serial loop made `/graph`
396
+ // latency O(N) round-trips on a large library; `skills.read` is
397
+ // safe to fan out (the io seam serializes writes, reads are
398
+ // independent), and the map insertion order stays usage-key order.
399
+ const skills = withSkills();
400
+ const names = [...usageMap.keys()];
401
+ // V27 INS-04: the fan-out is BOUNDED and failure-tolerant. An
402
+ // unbounded `Promise.all` over every usage key opened one read per
403
+ // skill at once (EMFILE on a large library), and `SkillLibrary.read`
404
+ // re-throws everything but EISDIR — so ONE unreadable file or one
405
+ // EMFILE aborted the whole `/graph`. Skills are read in batches, a
406
+ // failed read contributes no references instead of killing the view,
407
+ // and the loss is reported once.
408
+ const contents = [];
409
+ let unreadable = 0;
410
+ for (let offset = 0; offset < names.length; offset += SKILL_READ_BATCH) {
411
+ const batch = names.slice(offset, offset + SKILL_READ_BATCH);
412
+ const batchContents = await Promise.all(batch.map(async (name) => {
413
+ try {
414
+ return await skills.read(name);
415
+ }
416
+ catch {
417
+ unreadable += 1;
418
+ return null;
419
+ }
420
+ }));
421
+ contents.push(...batchContents);
422
+ }
423
+ if (unreadable > 0) {
424
+ ctx.logger.warn(`evolution-learning-graph: ${unreadable} skill file(s) could not be read; their related_skills edges are missing from this graph`);
425
+ }
426
+ const related = new Map();
427
+ names.forEach((name, index) => {
428
+ const content = contents[index];
429
+ if (content === null || content === undefined)
430
+ return;
431
+ related.set(name, relatedSkillNames(content, name));
432
+ });
433
+ const graph = buildLearningGraph(usageMap, memoryEntries, userEntries, related);
434
+ // F-10: bound the rendered output — node lines cover the
435
+ // whole usage set plus every memory entry, and edge lines are the
436
+ // full join; on a large library the command result used to grow
437
+ // unbounded. Each block caps at GRAPH_RENDER_LINE_CAP lines with an
438
+ // explicit …N more marker; the density footer keeps the true totals.
439
+ const nodeBlock = capRenderedLines(graph.nodes.map(node => renderNodeLine(node)));
440
+ const edgeBlock = capRenderedLines(graph.edges.map(edge => edge.from + ' --' + edge.type + '--> ' + edge.to));
441
+ const density = graphDensity(graph);
442
+ const densityLine = `\n\nSkills: ${density.skillNodes} · related edges: ${density.relatedEdges} (${density.edgesPerNode}/node) · isolated: ${density.isolatedPct}%`;
443
+ return nodeBlock + '\n\n' + edgeBlock + densityLine;
444
+ }
445
+ function withSkills() {
446
+ // 0.3.18 (S4.1, E-30): the graph read the COMMON root via undefined —
447
+ // a configured root in other members was silently ignored here,
448
+ // producing graph data from a DIFFERENT skills tree than the one the
449
+ // tools wrote to. Single resolution via resolveSkillsRoot.
450
+ // V10-11 (P2-7): the resolver now reads THIS package's Config.root
451
+ // (empty = the shared default root), so a custom-root deployment no
452
+ // longer has the graph edit/delete write the wrong tree.
453
+ return newSkillLibrary({ authority: authorityFrom({ origin: 'foreground' }),
454
+ config: rawConfig,
455
+ io: evolutionIoAdapter(() => io.provider()),
456
+ ctx,
457
+ threatExemptLabels: rawConfig.threatExemptLabels,
458
+ });
459
+ }
460
+ async function nodeDetail(id) {
461
+ const parsed = parseGraphNodeId(id);
462
+ if (parsed === null)
463
+ return err(`节点 id「${id}」不合法:应为技能名或 memory:<source>:<index>。`);
464
+ const resolved = await resolveGraphNode(parsed, {
465
+ readSkill: (name) => withSkills().read(name),
466
+ readMemory: (target) => memory.read(target),
467
+ });
468
+ return resolved.ok ? ok(resolved.message) : err(resolved.message);
469
+ }
470
+ async function nodeEdit(id, content) {
471
+ const parsed = parseGraphNodeId(id);
472
+ if (parsed === null)
473
+ return err(`节点 id「${id}」不合法:应为技能名或 memory:<source>:<index>。`);
474
+ if (parsed.kind === 'skill') {
475
+ // E-26: the graph edit is a content mutation and must follow the
476
+ // same approval + telemetry path as skill_manage. Approval is a
477
+ // soft dependency (ctx.get); when absent the write executes
478
+ // directly, unchanged.
479
+ const approval = ctx.get('evolutionApproval');
480
+ // P3-38 (v14): the write origin is derived ONCE — the direct path
481
+ // used to hardcode 'foreground' while the staged path sent
482
+ // `origins.library` (which is 'subagent' for a subagent invocation).
483
+ // A4 (audit P1-4): origins resolve through the core SINGLE source
484
+ // (`resolveExecOrigins`), which also reads the v37 review-channel
485
+ // session mark — a one-arg `resolveOrigins(header)` call skipped
486
+ // that mark, so a graph write inside a review-marked window
487
+ // resolved `foreground` and bypassed staging while the same write
488
+ // through skill_manage/memory staged.
489
+ const origins = resolveExecOrigins(invocationAgent && { agent: invocationAgent });
490
+ if (approval) {
491
+ // P2-7 (v15)/P3 (v16): staging pre-check — the skill runner lives
492
+ // in tool-skill-manage, an AGENT-preset row, while this command is
493
+ // a HOST row; in a host-only + approval-enabled assembly the stage
494
+ // below used to create a pending record no approver could ever
495
+ // replay. `hasRunner` is the seam's dedicated pre-check surface.
496
+ // v16: the refusal only fires when staging will ACTUALLY happen
497
+ // (approval enabled, session policy not 'never', and foreground
498
+ // writes stage) — the first cut refused allow-direct combos that
499
+ // never needed a runner.
500
+ const sessionPolicyEdit = effectiveSessionPolicy(ctx, session);
501
+ const stagesForeground = approval.stageForeground !== false;
502
+ const willStage = approval.isEnabled !== false
503
+ && sessionPolicyEdit !== 'never'
504
+ && (origins.approval === 'background_review' || stagesForeground);
505
+ if (willStage && !approval.hasRunner('skill')) {
506
+ return err('无法暂存 graph 技能写入:没有注册技能回放运行器 —— 请挂载 tool-skill-manage 行(evolution-agent 预设),或禁用 evolution-approval。');
507
+ }
508
+ // P2-34 (v11): the graph surface is marked in the summary so the
509
+ // audit record names where the write came from. N1 (v12): the
510
+ // command invocation DOES carry the agent (evolution-commands
511
+ // `/evolution learn` reads `invocation.agent`), so the session
512
+ // rides the request and the approval service derives the platform
513
+ // session policy — a `never`-policy session now stages nothing
514
+ // instead of being treated as foreground.
515
+ const sessionPolicy = sessionPolicyEdit;
516
+ // v23 (AP-3): stage-time staleness hash — the replay refuses a
517
+ // full-content overwrite of a skill that changed between staging
518
+ // and approval (same contract as the tool/review stagings).
519
+ // P1-13 (v37): the catch answers UNDEFINED (unreadable = no anchor),
520
+ // so a missing target still reaches the 'absent' sentinel below.
521
+ // G0/0.7 (S4-01 sweep): the three-state read, not an expression-form swallow. The MEANING is unchanged
522
+ // and deliberate - unreadable answers `undefined` (no anchor), a missing target answers `null` so it
523
+ // still reaches the absent sentinel below - but the distinction is now named by the library instead of
524
+ // re-derived from a thrown error at this call site.
525
+ const stageProbe = await withSkills().readSkillProbe(parsed.name);
526
+ const stageCurrent = isUnknown(stageProbe)
527
+ ? undefined
528
+ : (isPresent(stageProbe) ? stageProbe.value : null);
529
+ const decision = await approval.request({
530
+ kind: 'skill',
531
+ summary: `graph edit ${parsed.name}`,
532
+ args: {
533
+ operation: {
534
+ action: 'update',
535
+ name: parsed.name,
536
+ content,
537
+ // P1-13 (v37): a not-yet-existing target anchors as 'absent' —
538
+ // an unanchored staging let a foreground create between staging
539
+ // and approval be overwritten silently.
540
+ staged_from_sha256: typeof stageCurrent === 'string' ? contentHash(stageCurrent) : 'absent',
541
+ },
542
+ origin: origins.approval,
543
+ libraryOrigin: origins.library,
544
+ },
545
+ origin: origins.approval,
546
+ ...session?.id ? { sessionId: session.id } : {},
547
+ session,
548
+ ...sessionPolicy !== undefined ? { sessionPolicy } : {},
549
+ });
550
+ if (decision.action === 'staged')
551
+ return ok(decision.message);
552
+ }
553
+ // G1/1.2: same admission sequence, same protected list as tool-skill-manage. Before this, the graph
554
+ // commands went through approval and then wrote straight to the library - the write-admission gates
555
+ // (protected names, caps, read-before-write) never ran on this path at all.
556
+ const graphRefusal = await graphWriteGate({ policy: ctx.get('evolutionPolicy'), warn: warnWriteGateOnce }, { action: 'update', name: parsed.name, content, origin: resolveExecOrigins(invocationAgent && { agent: invocationAgent }).library });
557
+ if (graphRefusal !== null)
558
+ return err(graphRefusal);
559
+ const result = await withSkills().update(parsed.name, content, origins.library);
560
+ // E-26: a graph edit is a content patch — bump the patch counter
561
+ // exactly as skill_manage does (previously graph edits never
562
+ // entered the mutation-maturity signal). V4-13: a no-op update
563
+ // (byte-equivalent content, `noop:true`) must NOT count — the
564
+ // skill_manage gate is `result.noop !== true` and the graph branch
565
+ // was only checking `result.ok`, so a redundant re-save inflated
566
+ // the mutation-maturity counter here but not in skill_manage.
567
+ if (result.ok && result.noop !== true) {
568
+ await usageService.record?.(parsed.name, 'patch');
569
+ }
570
+ return result.ok ? ok(result.message) : err(result.message);
571
+ }
572
+ // E-21 memory TOCTOU: re-read the current index and verify the
573
+ // snapshot token still matches before mutating, so a memory write
574
+ // between the last render and this edit cannot shift the target.
575
+ const entries = await memory.read(parsed.source);
576
+ const check = readMemoryIndex(parsed, entries);
577
+ if (!check.ok)
578
+ return err(check.message ?? '记忆索引检查失败。');
579
+ // P2-6 (v15): the SAME approval seam the `memory` tool uses — the
580
+ // skill branch above stages, and an approval-enabled deployment must
581
+ // not have a graph path that lands the same kind of write directly.
582
+ // Staged args mirror the tool-memory runner's replay shape
583
+ // (MemoryWriteArgs), so approve replays byte-for-byte what this
584
+ // branch would have done.
585
+ const memoryApproval = ctx.get('evolutionApproval');
586
+ if (memoryApproval) {
587
+ // P3 (v16): refuse only when staging will actually happen (same
588
+ // refinement as the skill branch) and carry the entry INDEX in the
589
+ // summary — `graph edit memory:user` on index 0 and 3 used to
590
+ // produce identical audit lines.
591
+ const originsM = resolveExecOrigins(invocationAgent && { agent: invocationAgent });
592
+ const sessionPolicyM = effectiveSessionPolicy(ctx, session);
593
+ const willStage = memoryApproval.isEnabled !== false
594
+ && sessionPolicyM !== 'never'
595
+ && (originsM.approval === 'background_review' || memoryApproval.stageForeground !== false);
596
+ if (willStage && !memoryApproval.hasRunner('memory')) {
597
+ // v20 (D-3): the tool-memory row lives in evolution-all and the
598
+ // evolution-preset overlay — the HOST bundle deliberately does
599
+ // not carry it (host patch: "memory seam … no model tool"), so
600
+ // the old "evolution-host/evolution-all" wording sent host-only
601
+ // operators looking for a row that is not there.
602
+ return err('无法暂存 graph 记忆写入:没有注册记忆回放运行器 —— 请挂载 tool-memory 行(evolution-all bundle,或 evolution-preset overlay;宿主 bundle 里不含它),或禁用 evolution-approval。');
603
+ }
604
+ const decision = await memoryApproval.request({
605
+ kind: 'memory',
606
+ summary: `graph edit memory:${parsed.source}:${parsed.index}`,
607
+ args: { target: parsed.source, operations: [{ action: 'replace', old_text: check.entry ?? '', facts: content }] },
608
+ origin: originsM.approval,
609
+ ...session?.id ? { sessionId: session.id } : {},
610
+ session,
611
+ ...sessionPolicyM !== undefined ? { sessionPolicy: sessionPolicyM } : {},
612
+ });
613
+ if (decision.action === 'staged')
614
+ return ok(decision.message);
615
+ }
616
+ const result = await memory.applyBatch(parsed.source, [{ action: 'replace', old_text: check.entry ?? '', facts: content }]);
617
+ return result.ok ? ok(result.message) : err(result.message);
618
+ }
619
+ async function nodeDelete(id) {
620
+ const parsed = parseGraphNodeId(id);
621
+ if (parsed === null)
622
+ return err(`节点 id「${id}」不合法:应为技能名或 memory:<source>:<index>。`);
623
+ if (parsed.kind === 'skill') {
624
+ // E-26: same approval gate as edit/delete via skill_manage; the
625
+ // archived markArchived telemetry below was already written back
626
+ // (the audit's noted gap was approval + the edit patch counter).
627
+ const approval = ctx.get('evolutionApproval');
628
+ if (approval) {
629
+ // P2-7 (v15): staging pre-check (see the edit branch — the skill
630
+ // runner is an agent-preset row, not guaranteed on a host-only
631
+ // assembly).
632
+ // P3 (v16): the refusal fires only when staging will actually
633
+ // happen (approval enabled, session policy not 'never',
634
+ // foreground writes stage).
635
+ const origins = resolveExecOrigins(invocationAgent && { agent: invocationAgent });
636
+ const sessionPolicy = effectiveSessionPolicy(ctx, session);
637
+ const willStage = approval.isEnabled !== false
638
+ && sessionPolicy !== 'never'
639
+ && (origins.approval === 'background_review' || approval.stageForeground !== false);
640
+ if (willStage && !approval.hasRunner('skill')) {
641
+ return err('无法暂存 graph 技能删除:没有注册技能回放运行器 —— 请挂载 tool-skill-manage 行(evolution-agent 预设),或禁用 evolution-approval。');
642
+ }
643
+ const decision = await approval.request({
644
+ kind: 'skill',
645
+ summary: `graph delete ${parsed.name}`,
646
+ args: { operation: { action: 'delete', name: parsed.name }, origin: origins.approval, libraryOrigin: origins.library },
647
+ origin: origins.approval,
648
+ ...session?.id ? { sessionId: session.id } : {},
649
+ session,
650
+ ...sessionPolicy !== undefined ? { sessionPolicy } : {},
651
+ });
652
+ if (decision.action === 'staged')
653
+ return ok(decision.message);
654
+ }
655
+ // G1/1.2: same admission sequence, same protected list as tool-skill-manage. Before this, the graph
656
+ // commands went through approval and then wrote straight to the library - the write-admission gates
657
+ // (protected names, caps, read-before-write) never ran on this path at all.
658
+ const graphRefusal = await graphWriteGate({ policy: ctx.get('evolutionPolicy'), warn: warnWriteGateOnce }, { action: 'delete', name: parsed.name, origin: resolveExecOrigins(invocationAgent && { agent: invocationAgent }).library });
659
+ if (graphRefusal !== null)
660
+ return err(graphRefusal);
661
+ const result = await withSkills().archive(parsed.name);
662
+ if (result.ok) {
663
+ const usageRegistry = usageService;
664
+ await usageRegistry?.markArchived?.(parsed.name);
665
+ }
666
+ return result.ok ? ok(result.message) : err(result.message);
667
+ }
668
+ // E-21 memory TOCTOU guard (same as edit).
669
+ const entries = await memory.read(parsed.source);
670
+ const check = readMemoryIndex(parsed, entries);
671
+ if (!check.ok)
672
+ return err(check.message ?? '记忆索引检查失败。');
673
+ // P2-6 (v15): approval seam for deletes too (see the edit branch).
674
+ const memoryApproval = ctx.get('evolutionApproval');
675
+ if (memoryApproval) {
676
+ // P3 (v16): see the edit branch — stage-only refusal + index in
677
+ // the summary.
678
+ const origins = resolveExecOrigins(invocationAgent && { agent: invocationAgent });
679
+ const sessionPolicy = effectiveSessionPolicy(ctx, session);
680
+ const willStage = memoryApproval.isEnabled !== false
681
+ && sessionPolicy !== 'never'
682
+ && (origins.approval === 'background_review' || memoryApproval.stageForeground !== false);
683
+ if (willStage && !memoryApproval.hasRunner('memory')) {
684
+ // v20 (D-3): see the edit branch — the host bundle does not
685
+ // carry the tool-memory row.
686
+ return err('无法暂存 graph 记忆删除:没有注册记忆回放运行器 —— 请挂载 tool-memory 行(evolution-all bundle,或 evolution-preset overlay;宿主 bundle 里不含它),或禁用 evolution-approval。');
687
+ }
688
+ const decision = await memoryApproval.request({
689
+ kind: 'memory',
690
+ summary: `graph delete memory:${parsed.source}:${parsed.index}`,
691
+ args: { target: parsed.source, operations: [{ action: 'remove', old_text: check.entry ?? '' }] },
692
+ origin: origins.approval,
693
+ ...session?.id ? { sessionId: session.id } : {},
694
+ session,
695
+ ...sessionPolicy !== undefined ? { sessionPolicy } : {},
696
+ });
697
+ if (decision.action === 'staged')
698
+ return ok(decision.message);
699
+ }
700
+ const result = await memory.applyBatch(parsed.source, [{ action: 'remove', old_text: check.entry ?? '' }]);
701
+ return result.ok ? ok(result.message) : err(result.message);
702
+ }
703
+ },
704
+ handler: (invocation) => graphCommand.run(invocation).catch((error) => ({
705
+ kind: 'error',
706
+ text: `graph:命令失败:${error instanceof Error ? error.message : String(error)}\n请检查节点 id 以及 evolution 根目录下的 skills/memory 文件,然后重试。`,
707
+ })),
708
+ };
709
+ commandCtx.effect(() => commands.register(graphCommand), 'evolution-learning-graph.command');
710
+ });
711
+ }
712
+ //# sourceMappingURL=index.js.map