@frogmoo/dsh-supermemory 0.0.0-stage → 1.4.1

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.
@@ -0,0 +1,2971 @@
1
+ import { t as __exportAll } from "./rolldown-runtime-BJohB4LM.js";
2
+ import { i as loadHostModule, r as workspaceKeyOf, t as newId } from "./store-DD2L3GDr.js";
3
+ import { _ as updateTopicSetShape, c as getRouting, f as setRouting, h as touchTopicSet, i as clipWithNote, l as getTopicSet, n as clipAtBoundary, t as charCount, u as listTopicSets } from "./clip-kqqR05NC.js";
4
+ import { b as injectionTitle, h as normalizeTags, i as hubSelection, r as enumerateModels, u as tokenize, y as INJECTION_TITLES } from "./model-Z4_-9sAj.js";
5
+ import { S as upsertCapabilitySkill, _ as resolveSkillRoot, a as archivedCapabilityDocFiles, b as splitFactsBlock, c as capabilitySkillNames, d as isShellIdentity, f as parseSkillMarkdown, g as resolveCapabilityRoot, i as archiveShellSkills, m as readSkillVersionAt, n as archiveCapabilityDoc, o as bodyHashOf, r as archiveCapabilitySkill, s as capabilityDocPath, t as adoptCapabilityDocVersion } from "./skill-forge-DHxPo_w6.js";
6
+ import { copyFileSync, existsSync, mkdirSync, readFileSync } from "node:fs";
7
+ import { basename, dirname, isAbsolute, join, resolve, sep } from "node:path";
8
+ import { fileURLToPath } from "node:url";
9
+ import { homedir } from "node:os";
10
+ import { spawnSync } from "node:child_process";
11
+ // src/source.ts
12
+ /**
13
+ * Build one injection card's source. The label comes from the registry — never
14
+ * hand-write `kind: 'supermemory'` for a card (that would collapse every card
15
+ * back to the same 「上下文注入 supermemory」 title).
16
+ * @param kind - Registered card kind.
17
+ * @param formed - Host presentation form (and its required fields), if any.
18
+ * @returns The message source whose `kind` is the card label.
19
+ */
20
+ function injectionSource(kind, formed = {}) {
21
+ return {
22
+ kind: INJECTION_TITLES[kind],
23
+ ...formed
24
+ };
25
+ }
26
+ // src/role.ts
27
+ /** The id a role decision should use for an Agent. */
28
+ function agentSessionId(agent) {
29
+ const shaped = agent;
30
+ return String(shaped?.id ?? shaped?.session?.id ?? "");
31
+ }
32
+ /** Canonical workspace key of an Agent's session cwd (undefined when absent). */
33
+ function agentWorkspaceKey(agent) {
34
+ const cwd = agent?.session?.header?.cwd;
35
+ return typeof cwd === "string" && cwd.trim() ? workspaceKeyOf(cwd) : void 0;
36
+ }
37
+ /**
38
+ * A marker's workspace agrees with the agent's. Unknown on either side is not a
39
+ * mismatch (an old record may predate workspace fields); a known disagreement
40
+ * IS one — the hub role is deliberately workspace-scoped.
41
+ */
42
+ function workspaceAgrees(markerKey, agentKey) {
43
+ if (!markerKey || !agentKey) return true;
44
+ return markerKey === agentKey;
45
+ }
46
+ /** Safe iterable view of a table (missing table in a fixture/host-free run). */
47
+ function entriesOf(table) {
48
+ if (!table) return [];
49
+ try {
50
+ return [...table.entries()];
51
+ } catch {
52
+ return [];
53
+ }
54
+ }
55
+ /**
56
+ * Resolve one agent's role. Never throws: a store read failure answers
57
+ * `other / resolution-error` so the caller's guard can stay total.
58
+ */
59
+ function resolveRole(store, agent) {
60
+ const sessionId = agentSessionId(agent);
61
+ const header = agent?.session?.header;
62
+ const workspaceKey = agentWorkspaceKey(agent);
63
+ const base = (role, reason) => ({
64
+ role,
65
+ reason,
66
+ sessionId,
67
+ ...workspaceKey ? { workspaceKey } : {}
68
+ });
69
+ if (!store) return base("other", "no-session-id");
70
+ if (!sessionId) return base("other", "no-session-id");
71
+ try {
72
+ if (sessionId.startsWith("branch-") || sessionId.startsWith("fork-")) return base("branch", "plugin-branch-id");
73
+ let sawFork = false;
74
+ for (const [, topicSet] of entriesOf(store.topicsets)) {
75
+ const member = (topicSet.members ?? []).find((row) => row.sessionId === sessionId);
76
+ if (!member) continue;
77
+ if (member.kind === "fork") {
78
+ sawFork = true;
79
+ break;
80
+ }
81
+ }
82
+ if (sawFork) return base("branch", "fork-member");
83
+ for (const [, dispatch] of entriesOf(store.dispatches)) if (dispatch.branchSessionId === sessionId) return base("branch", "dispatch-branch");
84
+ if (header?.origin === "subagent") return base("other", "subagent-child");
85
+ let sawForeignHub = false;
86
+ const hubs = store.hubs;
87
+ try {
88
+ const record = hubs?.get?.(sessionId);
89
+ if (record) {
90
+ if (workspaceAgrees(record.workspaceKey, workspaceKey)) return base("hub", "hub-record");
91
+ sawForeignHub = true;
92
+ }
93
+ } catch {}
94
+ for (const [, topicSet] of entriesOf(store.topicsets)) {
95
+ if (!(topicSet.members ?? []).find((row) => row.sessionId === sessionId && row.kind === "root")) continue;
96
+ if (workspaceAgrees(String(topicSet.workspaceKey ?? ""), workspaceKey)) return base("hub", "topic-set-root");
97
+ sawForeignHub = true;
98
+ }
99
+ for (const [, dispatch] of entriesOf(store.dispatches)) {
100
+ if (dispatch.hubSessionId !== sessionId) continue;
101
+ let markerWorkspace;
102
+ if (dispatch.topicSetId) try {
103
+ markerWorkspace = store.topicsets?.get?.(dispatch.topicSetId)?.workspaceKey;
104
+ } catch {}
105
+ if (workspaceAgrees(markerWorkspace, workspaceKey)) return base("hub", "dispatch-hub");
106
+ sawForeignHub = true;
107
+ }
108
+ return base("other", sawForeignHub ? "workspace-mismatch" : "no-positive-marker");
109
+ } catch {
110
+ return base("other", "resolution-error");
111
+ }
112
+ }
113
+ /**
114
+ * Write (or refresh) one positive hub record. Best-effort: a missing table or a
115
+ * closing store loses only the audit row — resolution still sees root members
116
+ * and dispatch references.
117
+ */
118
+ async function recordHubSession(store, input) {
119
+ const sessionId = String(input.sessionId ?? "").trim();
120
+ if (!store || !sessionId) return;
121
+ try {
122
+ const table = store.hubs;
123
+ if (!table || typeof table.put !== "function") return;
124
+ const existing = typeof table.get === "function" ? table.get(sessionId) : void 0;
125
+ const now = Date.now();
126
+ await table.put(sessionId, {
127
+ workspaceKey: String(input.workspaceKey || existing?.workspaceKey || "unknown"),
128
+ sessionId,
129
+ title: String(input.title ?? existing?.title ?? ""),
130
+ source: input.source ?? existing?.source ?? "panel",
131
+ createdAt: Number(existing?.createdAt) || now,
132
+ updatedAt: now
133
+ });
134
+ } catch {}
135
+ }
136
+ /**
137
+ * Seed hub records from durable positive evidence (root members + dispatch hub
138
+ * references) so the R33 table is populated for media written by earlier
139
+ * rounds. Idempotent; returns the number of rows written.
140
+ */
141
+ async function backfillHubRecords(store, logger) {
142
+ if (!store) return 0;
143
+ let written = 0;
144
+ try {
145
+ const existing = /* @__PURE__ */ new Set();
146
+ try {
147
+ for (const [id] of store.hubs.entries()) existing.add(id);
148
+ } catch {}
149
+ for (const [, topicSet] of entriesOf(store.topicsets)) for (const member of topicSet.members ?? []) {
150
+ if (member.kind !== "root" || existing.has(member.sessionId)) continue;
151
+ if (resolveRole(store, { id: member.sessionId }).role === "branch") continue;
152
+ await recordHubSession(store, {
153
+ sessionId: member.sessionId,
154
+ workspaceKey: String(topicSet.workspaceKey ?? "unknown"),
155
+ title: member.title,
156
+ source: "topicset-root"
157
+ });
158
+ existing.add(member.sessionId);
159
+ written += 1;
160
+ }
161
+ for (const [, dispatch] of entriesOf(store.dispatches)) {
162
+ const id = String(dispatch.hubSessionId ?? "");
163
+ if (!id || existing.has(id)) continue;
164
+ let workspaceKey = "unknown";
165
+ try {
166
+ workspaceKey = String(store.topicsets?.get?.(dispatch.topicSetId ?? "")?.workspaceKey ?? "unknown");
167
+ } catch {}
168
+ await recordHubSession(store, {
169
+ sessionId: id,
170
+ workspaceKey,
171
+ source: "dispatch"
172
+ });
173
+ existing.add(id);
174
+ written += 1;
175
+ }
176
+ } catch (error) {
177
+ logger?.warn("supermemory: hub record backfill failed: " + String(error).slice(0, 160));
178
+ }
179
+ return written;
180
+ }
181
+ /** Last attempt per set id (throttle, including failures). */
182
+ const lastAttemptAt = /* @__PURE__ */ new Map();
183
+ /** In-flight regenerations, so two activations do not call twice. */
184
+ const inflight = /* @__PURE__ */ new Map();
185
+ /** FNV-1a 32-bit, hex — a cheap stable digest for the content snapshot. */
186
+ function fnv1a(text) {
187
+ let hash = 2166136261;
188
+ for (let i = 0; i < text.length; i += 1) {
189
+ hash ^= text.charCodeAt(i);
190
+ hash = Math.imul(hash, 16777619);
191
+ }
192
+ return (hash >>> 0).toString(16);
193
+ }
194
+ /**
195
+ * Content snapshot of one set: everything a regeneration would read. The
196
+ * persisted row's own title/tags/body participate, so a manual edit also marks
197
+ * the set stale (the next activation refines it once).
198
+ */
199
+ function topicSetFingerprint(store, topicSetId, overrides = {}) {
200
+ const record = store.topicsets.get(topicSetId);
201
+ if (!record) return "";
202
+ const topicSet = {
203
+ ...record,
204
+ ...overrides
205
+ };
206
+ const parts = [
207
+ topicSet.title,
208
+ topicSet.summary,
209
+ topicSet.keywords.join(",")
210
+ ];
211
+ for (const member of topicSet.members) parts.push(`m:${member.sessionId}:${member.kind}:${member.title}:${member.summary}:${member.status}:${member.lastActiveAt}`);
212
+ for (const [id, episode] of store.episodes.entries()) {
213
+ if (episode.topicSetId !== topicSetId) continue;
214
+ parts.push(`e:${id}:${episode.timeEnd}:${episode.summary}:${episode.decisions.join("|")}`);
215
+ }
216
+ for (const [id, requirement] of store.requirements.entries()) {
217
+ if (requirement.topicSetId !== topicSetId) continue;
218
+ parts.push(`r:${id}:${requirement.status}:${requirement.text}`);
219
+ }
220
+ for (const [id, dispatch] of store.dispatches.entries()) {
221
+ if (dispatch.topicSetId !== topicSetId) continue;
222
+ parts.push(`d:${id}:${dispatch.status}:${dispatch.updatedAt ?? dispatch.createdAt}:${dispatch.task}`);
223
+ }
224
+ const joined = parts.join("\n");
225
+ return `${fnv1a(joined)}-${joined.length}`;
226
+ }
227
+ /**
228
+ * Bounded textual corpus of one set's current content. Recent episodes and
229
+ * open requirements come first (they are the durable conclusions), then member
230
+ * titles and recent dispatch tasks.
231
+ */
232
+ function buildTopicCorpus(store, topicSetId, maxChars = 4e3) {
233
+ const topicSet = store.topicsets.get(topicSetId);
234
+ if (!topicSet) return "";
235
+ const lines = [
236
+ `话题集:${topicSet.title}`,
237
+ ...topicSet.keywords.length ? [`现有标签:${topicSet.keywords.join("、")}`] : [],
238
+ ...topicSet.summary ? [`现有正文:${topicSet.summary}`] : []
239
+ ];
240
+ const episodes = [...store.episodes.entries()].filter(([, episode]) => episode.topicSetId === topicSetId).sort((a, b) => b[1].timeEnd - a[1].timeEnd).slice(0, 5);
241
+ if (episodes.length > 0) {
242
+ lines.push("最近归档结论:");
243
+ for (const [, episode] of episodes) lines.push(`- ${episode.summary || "(无梗概)"}${episode.decisions.length ? `;决策:${episode.decisions.join(";")}` : ""}`);
244
+ }
245
+ const requirements = [...store.requirements.entries()].filter(([, requirement]) => requirement.topicSetId === topicSetId).sort((a, b) => b[1].createdAt - a[1].createdAt).slice(0, 5);
246
+ if (requirements.length > 0) {
247
+ lines.push("需求:");
248
+ for (const [, requirement] of requirements) lines.push(`- [${requirement.status}] ${requirement.text}`);
249
+ }
250
+ const members = topicSet.members.slice(0, 10);
251
+ if (members.length > 0) {
252
+ lines.push("会话:");
253
+ for (const member of members) lines.push(`- ${member.kind === "fork" ? "分支" : "中枢"} ${member.title || member.sessionId}${member.summary ? `:${member.summary}` : ""}`);
254
+ }
255
+ const dispatches = [...store.dispatches.entries()].filter(([, dispatch]) => dispatch.topicSetId === topicSetId).sort((a, b) => (b[1].updatedAt ?? b[1].createdAt) - (a[1].updatedAt ?? a[1].createdAt)).slice(0, 6);
256
+ if (dispatches.length > 0) {
257
+ lines.push("最近派发:");
258
+ for (const [, dispatch] of dispatches) lines.push(`- [${dispatch.status}] ${dispatch.task.slice(0, 160)}`);
259
+ }
260
+ return lines.join("\n").slice(0, maxChars);
261
+ }
262
+ /**
263
+ * Resolve the route used for generation: the set's own default model, the hub
264
+ * model of the acting session, then the first enumerated route. `undefined`
265
+ * means "no model available" — callers then keep the old shape.
266
+ */
267
+ async function resolveTopicShapeModel(ctx, store, topicSetId, sessionId) {
268
+ if (!ctx) return void 0;
269
+ const topicSet = store.topicsets.get(topicSetId);
270
+ if (topicSet?.defaultModel?.provider && topicSet.defaultModel.model) return { ...topicSet.defaultModel };
271
+ if (sessionId) try {
272
+ const agent = ctx.agents?.get?.(sessionId);
273
+ const hub = hubSelection(agent);
274
+ if (hub) return hub;
275
+ } catch {}
276
+ try {
277
+ const { models } = await enumerateModels(ctx);
278
+ const first = models[0];
279
+ if (first) return {
280
+ provider: first.provider,
281
+ model: first.id
282
+ };
283
+ } catch {}
284
+ }
285
+ /** Strip code fences/quotes and collapse the title to one line. */
286
+ function cleanTitle(value, fallback) {
287
+ let text = String(value ?? "").trim();
288
+ text = text.replace(/^```[a-z]*\s*|```$/gi, "").replace(/^["'「『]+|["'」』]+$/g, "").trim();
289
+ text = text.split(/\r?\n/)[0]?.trim() || "";
290
+ if (!text) return fallback.slice(0, 48);
291
+ return Array.from(text).slice(0, 48).join("");
292
+ }
293
+ /** Validate one parsed answer; an unusable answer yields undefined. */
294
+ function normalizeTopicShape(raw, fallbackTitle) {
295
+ if (!raw || typeof raw !== "object") return void 0;
296
+ const record = raw;
297
+ const title = cleanTitle(String(record.title ?? ""), fallbackTitle);
298
+ const tags = normalizeTags(record.tags).slice(0, 8);
299
+ const summary = String(record.summary ?? "").replace(/\s+/g, " ").trim().slice(0, 500);
300
+ if (!title && tags.length === 0 && !summary) return void 0;
301
+ return {
302
+ title,
303
+ tags,
304
+ summary
305
+ };
306
+ }
307
+ /** Extract the first JSON object from a model answer (fences tolerated). */
308
+ function parseTopicShapeText(text, fallbackTitle) {
309
+ const clean = String(text ?? "").replace(/```[a-z]*/gi, "").replace(/```/g, "").trim();
310
+ const start = clean.indexOf("{");
311
+ const end = clean.lastIndexOf("}");
312
+ if (start < 0 || end <= start) return void 0;
313
+ try {
314
+ return normalizeTopicShape(JSON.parse(clean.slice(start, end + 1)), fallbackTitle);
315
+ } catch {
316
+ return;
317
+ }
318
+ }
319
+ /**
320
+ * One model call. Returns undefined when there is no model, the call fails, it
321
+ * times out (20 s), or the answer does not contain a usable JSON object — the
322
+ * caller keeps the old shape in every one of those cases.
323
+ */
324
+ async function generateTopicShape(deps, input, route) {
325
+ const { ctx, store } = deps;
326
+ if (!ctx) return void 0;
327
+ let llm;
328
+ try {
329
+ llm = ctx.get?.("llm");
330
+ } catch {
331
+ llm = void 0;
332
+ }
333
+ if (!llm || typeof llm.stream !== "function") return void 0;
334
+ const selected = route ?? (input.topicSetId ? await resolveTopicShapeModel(ctx, store, input.topicSetId) : void 0);
335
+ if (!selected) return void 0;
336
+ const context = [
337
+ input.topicSetId ? buildTopicCorpus(store, input.topicSetId) : "",
338
+ input.seedText ? `补充说明:${input.seedText}` : "",
339
+ `当前标题:${input.title}`,
340
+ input.tags && input.tags.length ? `当前标签:${input.tags.join("、")}` : "当前标签:(无)",
341
+ `当前正文:${input.summary || "(无)"}`
342
+ ].filter(Boolean).join("\n").slice(0, 6e3);
343
+ const system = [
344
+ "你在维护 SuperMemory 话题集的检索索引。只输出一个 JSON 对象,不要代码围栏、不要解释。",
345
+ "字段:{\"title\":\"一句话可扫读的标题(≤40字)\",\"tags\":[\"3–8个短词\"],\"summary\":\"这个话题集要做什么、已经形成的结论与决策(≤300字)\"}",
346
+ "内容必须是结论性、可复用的事实或决策;禁止过程流水账(谁先做了什么、执行了哪些命令、第几步、工具调用日志)。",
347
+ "标题要稳定:除非旧标题明显跑题,否则沿用它的措辞。"
348
+ ].join("\n");
349
+ const user = `请根据以下材料重新生成话题集索引:\n\n${context}\n\n只返回 JSON。`;
350
+ const controller = new AbortController();
351
+ const timer = setTimeout(() => controller.abort(), 2e4);
352
+ let text = "";
353
+ try {
354
+ const stream = llm.stream({
355
+ provider: selected.provider,
356
+ model: selected.model,
357
+ ...selected.reasoningEffort ? { reasoningEffort: selected.reasoningEffort } : {},
358
+ system,
359
+ messages: [{
360
+ role: "user",
361
+ content: [{
362
+ type: "text",
363
+ text: user
364
+ }]
365
+ }],
366
+ maxTokens: 600,
367
+ temperature: .2,
368
+ signal: controller.signal
369
+ });
370
+ for await (const chunk of stream) if (chunk?.type === "text-delta" && typeof chunk.text === "string") text += chunk.text;
371
+ } catch (error) {
372
+ deps.logger?.warn(`supermemory: topic-shape generation failed: ${String(error).slice(0, 160)}`);
373
+ return;
374
+ } finally {
375
+ clearTimeout(timer);
376
+ }
377
+ const shape = parseTopicShapeText(text, input.title);
378
+ if (!shape) deps.logger?.warn("supermemory: topic-shape answer did not contain usable JSON; keeping the old shape");
379
+ return shape;
380
+ }
381
+ /**
382
+ * Fill a freshly created set. The creator-supplied title is authoritative; only
383
+ * empty tags/body are filled, so an explicit seeding is never overwritten.
384
+ * Both layers already present = no model call at all.
385
+ */
386
+ async function fillTopicShapeOnCreate(deps, topicSetId, seedText = "", fill = {}) {
387
+ const { store } = deps;
388
+ const topicSet = store.topicsets.get(topicSetId);
389
+ if (!topicSet) return void 0;
390
+ const needTags = fill.tags ?? topicSet.keywords.length === 0;
391
+ const needSummary = fill.summary ?? !topicSet.summary.trim();
392
+ if (!needTags && !needSummary) return void 0;
393
+ const shape = await generateTopicShape(deps, {
394
+ title: topicSet.title,
395
+ tags: topicSet.keywords,
396
+ summary: topicSet.summary,
397
+ seedText,
398
+ topicSetId
399
+ });
400
+ if (!shape) return void 0;
401
+ const summary = needSummary ? shape.summary || topicSet.summary : topicSet.summary;
402
+ const keywords = needTags ? shape.tags.length ? shape.tags : topicSet.keywords : topicSet.keywords;
403
+ const fingerprint = topicSetFingerprint(store, topicSetId, {
404
+ title: topicSet.title,
405
+ summary,
406
+ keywords
407
+ });
408
+ await updateTopicSetShape(store, topicSetId, {
409
+ title: topicSet.title,
410
+ summary,
411
+ keywords,
412
+ fingerprint,
413
+ generatedAt: Date.now()
414
+ });
415
+ return shape;
416
+ }
417
+ /**
418
+ * Regenerate one set after an activation **only when its content changed**.
419
+ *
420
+ * Guards: archived sets are skipped; an unchanged fingerprint is skipped; a
421
+ * changed set is regenerated at most once per {@link TOPIC_SHAPE_MIN_INTERVAL_MS};
422
+ * concurrent callers share one in-flight promise. Failure keeps the old
423
+ * title/tags/body and the old fingerprint (the next activation retries, still
424
+ * under the throttle).
425
+ */
426
+ function maybeRefreshTopicShape(deps, topicSetId, reason = "activation") {
427
+ const { store } = deps;
428
+ const topicSet = store.topicsets.get(topicSetId);
429
+ if (!topicSet || topicSet.status !== "active") return Promise.resolve();
430
+ const fingerprint = topicSetFingerprint(store, topicSetId);
431
+ if (topicSet.shapeFingerprint && topicSet.shapeFingerprint === fingerprint) return Promise.resolve();
432
+ const now = Date.now();
433
+ if (now - (lastAttemptAt.get(topicSetId) ?? 0) < 18e4) return Promise.resolve();
434
+ const running = inflight.get(topicSetId);
435
+ if (running) return running;
436
+ lastAttemptAt.set(topicSetId, now);
437
+ const run = (async () => {
438
+ try {
439
+ const shape = await generateTopicShape(deps, {
440
+ title: topicSet.title,
441
+ tags: topicSet.keywords,
442
+ summary: topicSet.summary,
443
+ seedText: "",
444
+ topicSetId
445
+ });
446
+ if (!shape) return;
447
+ const latest = store.topicsets.get(topicSetId);
448
+ if (!latest) return;
449
+ const title = shape.title || latest.title;
450
+ const summary = shape.summary || latest.summary;
451
+ const keywords = shape.tags.length ? shape.tags : latest.keywords;
452
+ const fingerprint = topicSetFingerprint(store, topicSetId, {
453
+ title,
454
+ summary,
455
+ keywords
456
+ });
457
+ await updateTopicSetShape(store, topicSetId, {
458
+ title,
459
+ summary,
460
+ keywords,
461
+ fingerprint,
462
+ generatedAt: Date.now()
463
+ });
464
+ deps.logger?.info?.(`supermemory: refreshed topic shape for ${latest.title} (${reason})`);
465
+ } catch (error) {
466
+ deps.logger?.warn(`supermemory: topic-shape refresh skipped: ${String(error).slice(0, 160)}`);
467
+ } finally {
468
+ inflight.delete(topicSetId);
469
+ }
470
+ })();
471
+ inflight.set(topicSetId, run);
472
+ return run;
473
+ }
474
+ /** Activation hook: fire-and-forget, never blocks or fails the routing write. */
475
+ function noteTopicSetActivated(deps, topicSetId) {
476
+ maybeRefreshTopicShape(deps, topicSetId, "activation").catch(() => {});
477
+ }
478
+ // src/route.ts
479
+ /**
480
+ * 固化能力(capability)的路由规则——模型可见文案的单一事实来源:
481
+ * memory_toolize 的工具描述与每个能力工具的描述都引用它(src/tools.ts /
482
+ * src/composite.ts)。规则要点:scope 内高频事务优先固化/更新能力,不要每次
483
+ * 现敲命令;能力连续失败或文档与现状不符时必须更新能力,而不是绕过它。
484
+ */
485
+ const CAPABILITY_ROUTING_RULES = "固化能力(capability)路由规则:① 在能力适用范围(scope)内遇到高频事务(git 同步/提交/推送、构建、验证、测试、发布等)时,优先调用已固化能力(sm_cap_*,默认预演、写操作 confirm=true 确认真实执行),不要每次现敲命令;② 重复工作先沉淀经验:判断型、易变的流程用 memory_toolize register 产出/更新能力知识面(描述写「何时用」,正文写触发条件/步骤/关键坑/验证;模型用 sm_cap_doc 按需读取,不要用宿主 skill 工具加载能力),不要满足于一次性工作;确实需要固定入口命令时才固化能力(入口命令 + 文档 + 适用范围);③ 能力执行连续失败、或文档与现状不符时,必须用 memory_toolize register 同名更新能力(version+1、changelog 记录原因),不要绕过它手敲命令;④ 用 memory_toolize refresh-builtin 刷新内置能力并查看差异报告与健康度(使用次数、成败分列、连续失败、文档/适用范围缺失、零使用),按信号决定更新还是停用;⑤ 职责边界(R55):中枢只能只读检查——用 sm_cap_doc 读知识面判断是否适用,执行必须 memory_dispatch 派发到分支(sm_cap_* 在中枢被 HUB_CAPABILITY_EXEC_DENIED 拒绝);分支才是执行者(默认预演,写操作 confirm=true)。";
486
+ function textOf(message) {
487
+ return (message.content ?? []).map((block) => block.type === "text" ? String(block.text ?? "") : "").filter(Boolean).join("\n");
488
+ }
489
+ /** Score one topic set against the query tokens (title + summary + keywords). */
490
+ function scoreTopicSet(topicSet, tokens) {
491
+ if (tokens.size === 0) return 0;
492
+ const bag = new Set(tokenize(`${topicSet.title} ${topicSet.summary} ${topicSet.keywords.join(" ")}`));
493
+ let hits = 0;
494
+ for (const token of tokens) if (bag.has(token)) hits++;
495
+ return hits / Math.sqrt(bag.size || 1);
496
+ }
497
+ /**
498
+ * Run routing for one user batch. Returns the outcome (possibly empty when
499
+ * routing declines); never throws — a routing failure must not block the hub.
500
+ *
501
+ * Only hub sessions route: branches (plugin-created topicset members) and
502
+ * delegated sessions (subagents, `delegationDepth > 0`) are skipped, so a
503
+ * worker is never parked on a routing confirmation.
504
+ */
505
+ async function routeBatch(ctx, deps, agent, sessionId, text, signal) {
506
+ const { store, config, logger } = deps;
507
+ if (!config.enabled || !text.trim()) return {};
508
+ const header = agent?.session?.header;
509
+ const workspaceKey = workspaceKeyOf(header?.cwd);
510
+ if ((header?.delegationDepth ?? 0) > 0) return {};
511
+ if (isBranchSession(store, sessionId)) return {};
512
+ const tokens = new Set(tokenize(text));
513
+ const mention = text.match(/(?:^|[^\w@])@([^\s@,,。;;]{1,30})/);
514
+ if (mention) {
515
+ const name = mention[1];
516
+ for (const [id, topicSet] of listTopicSets(store, workspaceKey)) {
517
+ const title = topicSet.title.trim();
518
+ if (title.length < 2) continue;
519
+ if (title === name || title.includes(name) || name.includes(title)) {
520
+ await setRouting(store, sessionId, {
521
+ activeTopicSetId: id,
522
+ driftCount: 0
523
+ });
524
+ await touchTopicSet(store, id);
525
+ if (deps.ctx) noteTopicSetActivated({
526
+ ctx: deps.ctx,
527
+ store,
528
+ logger: deps.logger
529
+ }, id);
530
+ return {
531
+ topicSetId: id,
532
+ card: renderCard(getTopicSet(store, id)),
533
+ cardKind: "topic"
534
+ };
535
+ }
536
+ }
537
+ }
538
+ const routing = getRouting(store, sessionId);
539
+ if (routing?.activeTopicSetId) {
540
+ const active = getTopicSet(store, routing.activeTopicSetId);
541
+ if (active && active.status === "active") {
542
+ if (scoreTopicSet(active, tokens) >= config.driftThreshold) {
543
+ await setRouting(store, sessionId, { driftCount: 0 });
544
+ await touchTopicSet(store, routing.activeTopicSetId);
545
+ return {
546
+ topicSetId: routing.activeTopicSetId,
547
+ card: renderCard(active),
548
+ cardKind: "topic"
549
+ };
550
+ }
551
+ const drift = routing.driftCount + 1;
552
+ if (drift < config.driftTurns) {
553
+ await setRouting(store, sessionId, { driftCount: drift });
554
+ return {
555
+ topicSetId: routing.activeTopicSetId,
556
+ card: renderCard(active),
557
+ cardKind: "topic"
558
+ };
559
+ }
560
+ await setRouting(store, sessionId, { driftCount: 0 });
561
+ }
562
+ }
563
+ if (!config.hint) return {};
564
+ const candidates = listTopicSets(store, workspaceKey).map(([id, topicSet]) => ({
565
+ id,
566
+ topicSet,
567
+ score: scoreTopicSet(topicSet, tokens)
568
+ })).filter((c) => c.score > 0).sort((a, b) => b.score - a.score).slice(0, 3);
569
+ if (candidates.length === 0) return {};
570
+ const lines = candidates.map((c) => `- 『${c.topicSet.title}』${c.topicSet.summary ? `:${clipWithNote(c.topicSet.summary, 80)}` : ""}`);
571
+ return {
572
+ cardKind: "topicCandidate",
573
+ card: [
574
+ injectionTitle("topicCandidate"),
575
+ "检测到可能与当前对话相关的历史话题(未切换,当前对话继续):",
576
+ ...lines,
577
+ "需要切换时:在消息里 @话题集名,或在 SuperMemory 面板中点击激活。"
578
+ ].join("\n")
579
+ };
580
+ }
581
+ /**
582
+ * True when the session is one of this plugin's branch sessions.
583
+ *
584
+ * R35: the local R19 rule (prefix + fork member) was a SECOND branch authority —
585
+ * it missed `dispatches.branchSessionId`, so a dispatch branch reached through
586
+ * `mode: continue` on a non-`branch-*` id could be routed as a hub. Resolution
587
+ * now goes through {@link resolveRole}, the single authority (branch facts win,
588
+ * then positive hub marks, otherwise other).
589
+ */
590
+ function isBranchSession(store, sessionId) {
591
+ return resolveRole(store, { id: sessionId }).role === "branch";
592
+ }
593
+ /** The model-facing topicset context card (§1.2 final step). */
594
+ function renderCard(topicSet) {
595
+ if (!topicSet) return "";
596
+ const lines = [`${injectionTitle("topic")} ${topicSet.title}`, topicSet.summary ? `梗概:${topicSet.summary}` : "梗概:(暂无,随对话滚动更新)"];
597
+ if (topicSet.defaultModel) lines.push(`默认模型:${topicSet.defaultModel.provider}/${topicSet.defaultModel.model}`);
598
+ if (topicSet.members.length > 0) {
599
+ lines.push("分支:");
600
+ for (const m of topicSet.members) lines.push(`- ${m.title || m.sessionId}(${m.status}${m.model ? " · " + m.model : ""})`);
601
+ }
602
+ lines.push("如需把实质工作分派到分支,调用 memory_dispatch;本会话是中枢,只做判断与整合;派发回执后立即结束本轮回复,分支完成后 relay 会自动开启新一轮对话。");
603
+ return lines.join("\n");
604
+ }
605
+ /**
606
+ * Attach routing to the pre-step waterfall. `next()` is always called and the
607
+ * full decision passed through; only the context message is appended.
608
+ */
609
+ function attachRoute(ctx, deps) {
610
+ if (!deps.config.enabled) return () => {};
611
+ let createMessage;
612
+ const ensureFactory = async () => {
613
+ if (!createMessage) createMessage = (await loadHostModule("@deepseek-ai/dsh-llm")).createUserMessage;
614
+ return createMessage;
615
+ };
616
+ return ctx.on("agent/pre-step", async (payload, next) => {
617
+ let decision;
618
+ try {
619
+ decision = await next();
620
+ } catch (error) {
621
+ deps.logger.warn(`supermemory: route next() failed: ${String(error)}`);
622
+ throw error;
623
+ }
624
+ if (decision.kind !== "enter") return decision;
625
+ const messages = decision.messages ?? [];
626
+ if (!messages.some((m) => m.source?.kind === "user")) return decision;
627
+ try {
628
+ const sessionId = String(payload.agent?.id ?? "");
629
+ const text = messages.map(textOf).filter(Boolean).join("\n");
630
+ const outcome = await routeBatch(ctx, deps, payload.agent, sessionId, text, payload.signal);
631
+ if (!outcome.card) return decision;
632
+ const factory = await ensureFactory();
633
+ const cardSource = outcome.cardKind === "topicCandidate" ? injectionSource("topicCandidate", { form: "recall" }) : injectionSource("topic", { form: "recall" });
634
+ const card = factory({
635
+ content: [{
636
+ type: "text",
637
+ text: outcome.card
638
+ }],
639
+ source: cardSource
640
+ });
641
+ return {
642
+ ...decision,
643
+ messages: [...decision.messages, card]
644
+ };
645
+ } catch (error) {
646
+ deps.logger.warn(`supermemory: routing skipped: ${String(error).slice(0, 200)}`);
647
+ return decision;
648
+ }
649
+ });
650
+ }
651
+ // src/builtin-capabilities.ts
652
+ /**
653
+ * 内置能力(builtin capabilities):随插件源码一起分发的固化能力定义。
654
+ *
655
+ * 背景(2026-11-18):git-sync 能力原先由中枢在插件重载后经 memory_toolize
656
+ * register 手工录入——清库或全新安装后插件不带这个能力,定义也只存在于
657
+ * store 里、不随代码维护。内置能力把定义收进源码:rebuildCapabilities 启动
658
+ * 重建时与 store 合并(缺失→播种、旧版→升级、现场更新→保留),能力定义从此
659
+ * 随插件代码一起被维护(改入口/文档/路由描述 = 改这个文件 + version+1)。
660
+ *
661
+ * 合并/升级策略(mergeBuiltinCapabilities,src/capability.ts):
662
+ * - store 缺失 → 播种(落库 + 注册),版本 = 内置版本;
663
+ * - store 版本 < 内置 → 升级:用内置定义覆盖 entry/doc/scope/routeNote/
664
+ * dryRunArg/writeConfirm/runnable/title/description/tags,
665
+ * 保留 useCount/usage 与 workspaceKey。理由:内置定义随
666
+ * 插件代码和文档一起发布,旧版本定义本身就是「文档与现状
667
+ * 不符」的故障形态;唯一有意的本地修改路径是
668
+ * memory_toolize register,它会 version+1 超过内置版本,
669
+ * 因此版本旧于内置的行不可能是认真的本地编辑——覆盖可恢复
670
+ * 受管行为,且不丢任何使用数据;
671
+ * - store 版本 >= 内置 → 保留现场(本地维护中的版本,或更新版插件已播种)。
672
+ *
673
+ * 维护方式:新增内置能力 = 往 BUILTIN_CAPABILITIES 加一条(version: 1);
674
+ * 修改现有能力 = 改定义 + version+1 + changelog 追加一行(最新在前)。
675
+ * @module supermemory/builtin-capabilities
676
+ */
677
+ /** Package names this plugin is installed under: the published scoped name and the pre-1.4.0 dev name. */
678
+ const PLUGIN_PACKAGE_NAMES = /* @__PURE__ */ new Set(["@frogmoo/dsh-supermemory", "dsh-supermemory"]);
679
+ /**
680
+ * 从插件自身位置推导出**本仓库根目录**。
681
+ *
682
+ * 为什么需要它:内置能力的 scope 原先写成绝对路径('G:\09 - dsh\SuperMemory'),
683
+ * 换机器/换克隆目录后该目录不存在——能力对当前工作区不生效、健康报告持续报
684
+ * 「适用范围目录不存在」。scope 的正确含义是「入口命令的执行目录」,也就是本插件
685
+ * 所在的源码仓库,它应当随插件位置自动跟随。
686
+ *
687
+ * 推导链(宿主产物是 ESM,见 tsdown.config.ts format:'esm',所以 import.meta.url
688
+ * 在 lib/supermemory.js 与各 chunk 里都可用;DSH profile 里的
689
+ * node_modules/@frogmoo/dsh-supermemory(1.4.0 起的 scoped 名;更早的草稿名是
690
+ * node_modules/dsh-supermemory)是指向源码仓库的符号链接,Node 默认解析 realpath):
691
+ * import.meta.url → lib/<file>.js → 逐级向上找到含 package.json(name 为本包的
692
+ * scoped 名或旧名)的目录即仓库根;找不到时退回「模块目录的上一级」(lib/ 的父目录)。
693
+ *
694
+ * 兜底说明:安装成副本(非符号链接)时推导值是副本包根——此时该能力本就不适用
695
+ * (入口脚本与 docs 在副本里,不是 git 仓库),能力描述已要求调用前先确认是本仓库。
696
+ */
697
+ function resolvePluginRepoRoot(moduleUrl = import.meta.url) {
698
+ const moduleDir = dirname(fileURLToPath(moduleUrl));
699
+ let dir = moduleDir;
700
+ for (let depth = 0; depth < 4; depth += 1) {
701
+ try {
702
+ const pkg = JSON.parse(readFileSync(join(dir, "package.json"), "utf8"));
703
+ if (typeof pkg?.name === "string" && PLUGIN_PACKAGE_NAMES.has(pkg.name)) return dir;
704
+ } catch {}
705
+ const parent = dirname(dir);
706
+ if (parent === dir) break;
707
+ dir = parent;
708
+ }
709
+ return resolve(moduleDir, "..");
710
+ }
711
+ /** 本插件源码仓库根目录(scope 的推导来源,模块加载时求值一次)。 */
712
+ const PLUGIN_REPO_ROOT = resolvePluginRepoRoot();
713
+ /**
714
+ * The built-in capability catalogue (stable order = seed order).
715
+ *
716
+ * scope 由 PLUGIN_REPO_ROOT 运行时推导,跟随插件的安装/克隆位置(v2 起):
717
+ * 不再需要在换机器后手工 memory_toolize register 修正。合并升级时若某行的
718
+ * 行级归属恰好等于「旧 scope 推导值」(即由内置定义自己播种/继承而来),
719
+ * 该行归属会随之迁移到新 scope 的工作区键;现场显式指定别的工作区的行保持不动
720
+ * (见 mergeBuiltinCapabilities)。
721
+ */
722
+ const BUILTIN_CAPABILITIES = Object.freeze([{
723
+ name: "git-sync-supermemory",
724
+ version: 7,
725
+ title: "git 同步/提交/推送(SuperMemory 仓库)",
726
+ description: "SuperMemory 仓库 git 同步/提交/推送固化流程。先确认工作区是本仓库(有 scripts/git-sync-push.sh),否则不触发。优先 pnpm git:sync,不要手敲 fetch/rebase/push。凭据走仓库本地 GCM(helper=manager);GIT_TERMINAL_PROMPT=0,失败找用户,勿改全局 config/remote。推送(2026-11-23 起双远程):origin push = GitHub(FrogMoo/SuperMemory,首位)+ 内网 Gitee 镜像,fetch/pull 只走 Gitee;首个 push URL 失败即中止后续推送,故远程排位即韧性。Gitea 2026-11-22 晚曾重置、已恢复(帐号改名为 Zry)。日常=跑入口;预演=加 --dry-run;提交前闸门 pnpm typecheck + pnpm smoke,提交信息写文件后 commit -F。凭据键坑与恢复流程见 docs/git-sync.md。",
727
+ entry: "pnpm git:sync",
728
+ doc: "docs/git-sync.md",
729
+ scope: PLUGIN_REPO_ROOT,
730
+ runnable: true,
731
+ dryRunArg: "--dry-run",
732
+ writeConfirm: true,
733
+ tags: [
734
+ "git",
735
+ "同步",
736
+ "推送",
737
+ "流程固化"
738
+ ],
739
+ routeNote: "在本仓库范围内遇到 git 同步/提交/推送类事务时优先用本能力:先默认预演(--dry-run)看计划,确认后 confirm=true 真实执行;不要手敲 git fetch/rebase/push。",
740
+ changelog: [
741
+ "v6: 清理能力定义中的平台旧帐号身份信息(描述与 changelog 不再出现旧帐号名与邮箱);路由与操作内容不变。",
742
+ "v5: 描述压回 500 字上限内并更新为现状。根因:v4 描述 725 字超过 buildCapabilitySpec 的 500 字上限,mergeBuiltinCapabilities 静默跳过播种(report.seeded=[]),capability-smoke C3 与 workspace-scope W5 因此失败、内置能力计数差 1。内容更新:Gitea 2026-11-22 晚重置后已恢复(帐号改名为 Zry,非重建)、origin push = GitHub(首位)+ Gitee Zry/SuperMemory、fetch/pull 只走 Gitee、凭据走仓库本地 GCM(git http 传输的凭据键 host 带端口,换帐号时该键与 host+port 分开写法都要 approve、旧键要 reject)。",
743
+ "v4: 双远程同时推送(origin push URL = GitHub 优先 + Gitee,fetch 仍只走 Gitee;git 2.55 首个 push URL 失败即中止后续推送,故 GitHub 排首位保障 Gitee 故障期推送不落空);记录 Gitee 服务器 2026-11-22 重置、旧帐号名仓库 404 的现状与恢复后 URL 更新方法。",
744
+ "v3: 凭据改为走仓库本地 GCM(manager + Windows 凭据存储);旧 store 方案(~/.git-credentials)已失效(文件不存在,fetch 必报 could not read Username),脚本与 docs 同步更新。",
745
+ "v2: scope 改为从插件位置自动推导(原硬编码 G:\\09 - dsh\\SuperMemory),修复仓库迁移后「适用范围目录不存在」导致能力对当前工作区失效;升级时由旧 scope 继承的行级归属一并迁移。",
746
+ "v1: 能力内置化(原由 memory_toolize register 手工录入):随插件分发,清库/全新安装后自动播种;附带使用统计(成败分列/连续失败/最近一次结果)与刷新入口 memory_toolize refresh-builtin。"
747
+ ]
748
+ }]);
749
+ // src/capability.ts
750
+ /**
751
+ * Unified capability (R50): ONE record, TWO faces — knowledge (SKILL.md) and
752
+ * execution (sm_cap_<name>).
753
+ *
754
+ * R50 (2026-11-26) replaced the old split between "composite tools" (tool
755
+ * sequences compiled into one call), "capabilities" (entry command + doc +
756
+ * scope) and the separate auto-generated skill list. A capability is now a
757
+ * single durable record:
758
+ *
759
+ * kind='capability' executable + knowledge face (entry command);
760
+ * kind='knowledge' knowledge face only (SKILL.md, no entry);
761
+ * kind='proposal' pending auto knowledge draft (accept -> capability).
762
+ *
763
+ * The old sequence pipeline is GONE: no compile/register/rebuild path exists
764
+ * for sm_composite_* tools. Legacy rows are migrated lazily and idempotently:
765
+ * - old capability rows (kind='composite' + spec.kind='capability') become
766
+ * capabilities, renamed sm_composite_<x> -> sm_cap_<x>, with a SKILL.md;
767
+ * - old kind='skill' rows become knowledge (no entry);
768
+ * - old tool-sequence rows become status='retired' (audit only, never registered).
769
+ *
770
+ * Execution semantics are unchanged: scope/workspace gate, default dry-run
771
+ * (dryRunArg), writeConfirm requires confirm=true, output clipped and
772
+ * time-limited. One tool per capability, named sm_cap_<name>, with a fixed
773
+ * entry (no arbitrary argument passthrough); it only accepts dry_run/confirm.
774
+ *
775
+ * @module supermemory/capability
776
+ */
777
+ var capability_exports = /* @__PURE__ */ __exportAll({
778
+ acceptProposal: () => acceptProposal,
779
+ bumpCapabilityLoad: () => bumpCapabilityLoad,
780
+ capabilityHealthOf: () => capabilityHealthOf,
781
+ capabilityLogicalName: () => capabilityLogicalName,
782
+ capabilityRows: () => capabilityRows,
783
+ capabilityToolName: () => capabilityToolName,
784
+ declineProposal: () => declineProposal,
785
+ isShellUnit: () => isShellUnit,
786
+ liveCapabilityNames: () => liveCapabilityNames,
787
+ loadCapabilityDoc: () => loadCapabilityDoc,
788
+ mergeBuiltinCapabilities: () => mergeBuiltinCapabilities,
789
+ pendingProposalsOf: () => pendingProposalsOf,
790
+ rebuildCapabilities: () => rebuildCapabilities,
791
+ registerCapability: () => registerCapability,
792
+ registerCapabilityTool: () => registerCapabilityTool,
793
+ setCapabilityEnabled: () => setCapabilityEnabled
794
+ });
795
+ /** Serialized record marker (distinguishes new JSON from legacy CompositeSpec). */
796
+ const CAPABILITY_SCHEMA = "sm.capability/1";
797
+ /** Tool prefix of the execution face. sm_composite_* is retired for good. */
798
+ const CAPABILITY_PREFIX = "sm_cap_";
799
+ /** Logical name -> registered tool name (git-sync-supermemory -> sm_cap_git_sync_supermemory). */
800
+ function capabilityToolName(name) {
801
+ const slug = String(name ?? "").replace(/^sm_cap_|^sm_composite_|^sm-/, "").trim().replace(/[^a-zA-Z0-9]+/g, "_").replace(/^_+|_+$/g, "").slice(0, 41);
802
+ return CAPABILITY_PREFIX + (slug || "capability");
803
+ }
804
+ /** Logical name -> skill name (git-sync-supermemory -> sm-git-sync-supermemory). */
805
+ function capabilitySkillName(name) {
806
+ return capabilitySkillNames(name).skillName;
807
+ }
808
+ /** Normalise any historical name form to the logical kebab slug. */
809
+ function capabilityLogicalName(name) {
810
+ return String(name ?? "").trim().replace(/^sm_cap_|^sm_composite_|^sm-/, "").replace(/_/g, "-").replace(/[^a-zA-Z0-9-]+/g, "-").replace(/^-+|-+$/g, "").toLowerCase() || "capability";
811
+ }
812
+ const CHANGELOG_MAX = 20;
813
+ const PROPOSAL_TTL_MS = 2592e6;
814
+ const PROPOSAL_MAX = 20;
815
+ function num(value, fallback = 0) {
816
+ const parsed = Number(value);
817
+ return Number.isFinite(parsed) ? parsed : fallback;
818
+ }
819
+ function str(value, fallback = "") {
820
+ return typeof value === "string" ? value : fallback;
821
+ }
822
+ /** Normalise a record read from any historical shape (never throws). */
823
+ function normalizeCapabilityRecord(raw, row) {
824
+ const isNew = raw.schema === CAPABILITY_SCHEMA;
825
+ const kind = raw.kind === "proposal" || raw.kind === "knowledge" || row?.kind === "knowledge" || row?.kind === "proposal" ? raw.kind === "proposal" || row?.kind === "proposal" ? "proposal" : "knowledge" : "capability";
826
+ const name = isNew ? capabilityLogicalName(str(raw.name)) : capabilityLogicalName(str(raw.name) || str(row?.trigger) || "capability");
827
+ const usage = raw.usage && typeof raw.usage === "object" ? raw.usage : {};
828
+ const facts = raw.facts && typeof raw.facts === "object" ? raw.facts : {};
829
+ const entryDraft = str(raw.entryDraft ?? row?.entryDraft);
830
+ const entry = kind === "capability" || raw.kind === "capability" ? str(raw.entry) : str(raw.entry);
831
+ const enabled = raw.enabled === void 0 ? row?.enabled === false ? false : row?.status !== "retired" : Boolean(raw.enabled);
832
+ return {
833
+ schema: CAPABILITY_SCHEMA,
834
+ name,
835
+ kind,
836
+ title: str(raw.title) || name,
837
+ description: str(raw.description) || str(row?.description),
838
+ tags: Array.isArray(raw.tags) ? raw.tags.map((tag) => String(tag)).slice(0, 8) : row?.tags ?? [],
839
+ entry,
840
+ entryDraft,
841
+ entryVerified: Boolean(raw.entryVerified ?? row?.entryVerified ?? (entry && !entryDraft)),
842
+ doc: str(raw.doc),
843
+ scope: str(raw.scope),
844
+ runnable: raw.runnable === void 0 ? Boolean(entry) : Boolean(raw.runnable),
845
+ enabled,
846
+ dryRunArg: str(raw.dryRunArg),
847
+ writeConfirm: Boolean(raw.writeConfirm),
848
+ routeNote: str(raw.routeNote),
849
+ source: str(raw.source) || str(row?.source) || "manual",
850
+ taskKey: str(raw.taskKey ?? row?.taskKey),
851
+ version: Math.max(1, num(raw.version, 1)),
852
+ updatedAt: num(raw.updatedAt ?? row?.createdAt, Date.now()),
853
+ changelog: Array.isArray(raw.changelog) ? raw.changelog.map((line) => String(line)).slice(0, CHANGELOG_MAX) : [],
854
+ skillPath: str(raw.skillPath ?? row?.skillPath),
855
+ bodyHash: str(raw.bodyHash ?? row?.bodyHash),
856
+ factsHash: str(raw.factsHash ?? row?.factsHash),
857
+ facts,
858
+ loadCount: Math.max(0, num(raw.loadCount, num(row?.loadCount))),
859
+ runCount: Math.max(0, num(raw.runCount, num(row?.runCount, num(row?.useCount)))),
860
+ successCount: Math.max(0, num(raw.successCount, num(usage.successCount))),
861
+ failCount: Math.max(0, num(raw.failCount, num(usage.failCount))),
862
+ consecutiveFailures: Math.max(0, num(raw.consecutiveFailures, num(usage.consecutiveFailures))),
863
+ ...num(raw.lastUsedAt ?? usage.lastUsedAt) > 0 ? { lastUsedAt: num(raw.lastUsedAt ?? usage.lastUsedAt) } : {},
864
+ ...raw.lastStatus ?? usage.lastStatus ? { lastStatus: raw.lastStatus ?? usage.lastStatus } : {},
865
+ ...raw.lastDryRun !== void 0 ? { lastDryRun: Boolean(raw.lastDryRun) } : usage.lastDryRun !== void 0 ? { lastDryRun: Boolean(usage.lastDryRun) } : {},
866
+ ...raw.lastExitCode !== void 0 ? { lastExitCode: num(raw.lastExitCode) } : usage.lastExitCode !== void 0 ? { lastExitCode: num(usage.lastExitCode) } : {},
867
+ ...typeof (raw.lastSummary ?? usage.lastSummary) === "string" ? { lastSummary: String(raw.lastSummary ?? usage.lastSummary).slice(0, 200) } : {},
868
+ builtin: Boolean(raw.builtin),
869
+ ...raw.builtinVersion !== void 0 ? { builtinVersion: num(raw.builtinVersion) } : {},
870
+ ...raw.proposalStatus ? { proposalStatus: raw.proposalStatus } : {},
871
+ ...raw.expiresAt !== void 0 ? { expiresAt: num(raw.expiresAt) } : {},
872
+ ...typeof raw.draftBody === "string" ? { draftBody: raw.draftBody } : {},
873
+ ...typeof raw.acceptedId === "string" ? { acceptedId: raw.acceptedId } : {}
874
+ };
875
+ }
876
+ /** Convert one legacy CompositeSpec capability definition (pre-R50). */
877
+ function legacyCapabilityRecord(spec, row) {
878
+ return normalizeCapabilityRecord({
879
+ ...spec,
880
+ schema: CAPABILITY_SCHEMA,
881
+ kind: "capability",
882
+ entry: spec.entry,
883
+ entryVerified: true,
884
+ source: "migrated"
885
+ }, row);
886
+ }
887
+ function skillPathOfLegacyRow(row) {
888
+ const entry = str(row.entry);
889
+ if (!entry) return "";
890
+ if (entry.startsWith("{")) try {
891
+ const parsed = JSON.parse(entry);
892
+ return str(parsed.skillPath) || str(parsed.entryPath);
893
+ } catch {
894
+ return "";
895
+ }
896
+ return entry;
897
+ }
898
+ function skillNameOfLegacyRow(row) {
899
+ const trigger = str(row.trigger);
900
+ const fromTrigger = /skill\/(.+)$/.exec(trigger)?.[1];
901
+ if (fromTrigger) return fromTrigger;
902
+ const path = skillPathOfLegacyRow(row);
903
+ const match = /[\\/]([^\\/]+)[\\/]SKILL\.md$/.exec(path);
904
+ return match ? match[1] : str(row.title) || "skill";
905
+ }
906
+ /** Parse one row into a unified record; undefined for legacy sequence/unknown rows. */
907
+ function readCapabilityRow(row, id = "") {
908
+ if (!row) return void 0;
909
+ if (row.kind === "proposal") {
910
+ let raw;
911
+ try {
912
+ raw = JSON.parse(row.entry);
913
+ } catch {
914
+ return;
915
+ }
916
+ const record = normalizeCapabilityRecord(raw, row);
917
+ record.kind = "proposal";
918
+ record.proposalStatus = raw.proposalStatus ?? "pending";
919
+ return {
920
+ id,
921
+ row,
922
+ record
923
+ };
924
+ }
925
+ if (row.kind === "knowledge" || row.kind === "skill") {
926
+ const path = row.kind === "skill" ? skillPathOfLegacyRow(row) : row.skillPath ?? "";
927
+ if (row.entry.startsWith("{")) try {
928
+ const raw = JSON.parse(row.entry);
929
+ if (raw.schema === "sm.capability/1") {
930
+ const record = normalizeCapabilityRecord(raw, row);
931
+ record.kind = "knowledge";
932
+ if (!record.skillPath && path) record.skillPath = path;
933
+ return {
934
+ id,
935
+ row,
936
+ record
937
+ };
938
+ }
939
+ } catch {}
940
+ let file;
941
+ if (path) try {
942
+ file = parseSkillMarkdown(readFileSync(path, "utf8"), "");
943
+ } catch {
944
+ file = void 0;
945
+ }
946
+ const name = file?.name || skillNameOfLegacyRow(row);
947
+ return {
948
+ id,
949
+ row,
950
+ record: normalizeCapabilityRecord({
951
+ schema: CAPABILITY_SCHEMA,
952
+ name,
953
+ kind: "knowledge",
954
+ title: row.title || name,
955
+ description: file?.description || row.description,
956
+ entry: "",
957
+ entryVerified: false,
958
+ runnable: false,
959
+ source: str(row.source) || "migrated",
960
+ taskKey: file?.taskKey ?? row.taskKey,
961
+ version: file?.version ?? 1,
962
+ changelog: file?.changelog ?? [],
963
+ bodyHash: file?.bodyHash ?? row.bodyHash,
964
+ factsHash: file?.factsHash ?? row.factsHash,
965
+ skillPath: path
966
+ }, row)
967
+ };
968
+ }
969
+ if (row.kind !== "capability" && row.kind !== "composite" && row.kind !== "workflow") return void 0;
970
+ let raw;
971
+ try {
972
+ raw = JSON.parse(row.entry);
973
+ } catch {
974
+ return;
975
+ }
976
+ if (!raw || typeof raw !== "object") return void 0;
977
+ if (raw.schema === "sm.capability/1") return {
978
+ id,
979
+ row,
980
+ record: normalizeCapabilityRecord(raw, row)
981
+ };
982
+ if (raw.kind !== "capability" || !str(raw.entry)) return void 0;
983
+ return {
984
+ id,
985
+ row,
986
+ record: legacyCapabilityRecord(raw, row)
987
+ };
988
+ }
989
+ /** Build the durable row projection for one record. */
990
+ function rowOfRecord(record, workspaceKey, createdAt) {
991
+ return {
992
+ ...workspaceKey ? { workspaceKey } : {},
993
+ ...createdAt !== void 0 ? { createdAt } : {},
994
+ kind: record.kind,
995
+ title: record.title,
996
+ tags: record.tags.slice(0, 8),
997
+ trigger: record.kind === "proposal" ? "proposal/" + record.name : "capability/" + record.name,
998
+ description: record.description,
999
+ entry: JSON.stringify(record),
1000
+ useCount: record.runCount,
1001
+ status: record.kind === "proposal" ? record.proposalStatus === "pending" ? "active" : "retired" : record.enabled === false ? "retired" : "active",
1002
+ ...record.skillPath ? { skillPath: record.skillPath } : {},
1003
+ enabled: record.enabled !== false,
1004
+ loadCount: record.loadCount,
1005
+ runCount: record.runCount,
1006
+ source: record.source,
1007
+ ...record.taskKey ? { taskKey: record.taskKey } : {},
1008
+ entryDraft: record.entryDraft,
1009
+ entryVerified: record.entryVerified,
1010
+ ...record.bodyHash ? { bodyHash: record.bodyHash } : {},
1011
+ ...record.factsHash ? { factsHash: record.factsHash } : {}
1012
+ };
1013
+ }
1014
+ /** True when the record has a usable execution face. */
1015
+ function isExecutable(record) {
1016
+ return record.kind === "capability" && Boolean(record.entry) && record.runnable !== false && record.enabled !== false;
1017
+ }
1018
+ /** Every unified record (capability/knowledge/proposal), broken rows skipped. */
1019
+ function capabilityRows(store, workspaceKey) {
1020
+ const out = [];
1021
+ for (const [id, row] of store.toolMemory.entries()) {
1022
+ if (!row || ![
1023
+ "capability",
1024
+ "knowledge",
1025
+ "proposal",
1026
+ "composite",
1027
+ "skill",
1028
+ "workflow"
1029
+ ].includes(row.kind)) continue;
1030
+ const parsed = readCapabilityRow(row, id);
1031
+ if (!parsed) continue;
1032
+ if (workspaceKey !== void 0 && !capabilityAppliesToWorkspace(parsed.record, workspaceKey, row.workspaceKey)) continue;
1033
+ out.push(parsed);
1034
+ }
1035
+ return out.sort((left, right) => left.record.name.localeCompare(right.record.name));
1036
+ }
1037
+ /** A capability belongs to a workspace via row ownership or scope. */
1038
+ function capabilityAppliesToWorkspace(record, callerWorkspace, rowWorkspaceKey) {
1039
+ if (!callerWorkspace) return true;
1040
+ const own = rowWorkspaceKey || (record.scope ? workspaceKeyOf(record.scope) : void 0);
1041
+ if (!own) return true;
1042
+ return own === callerWorkspace;
1043
+ }
1044
+ /** A caller cwd is inside the capability scope (equal or descendant). */
1045
+ function scopeContains(scope, cwd) {
1046
+ if (!scope || !cwd) return true;
1047
+ try {
1048
+ const base = resolve(scope).replace(/[\\/]+$/, "").toLowerCase();
1049
+ const target = resolve(cwd).replace(/[\\/]+$/, "").toLowerCase();
1050
+ return target === base || target.startsWith(base + sep);
1051
+ } catch {
1052
+ return false;
1053
+ }
1054
+ }
1055
+ function findCapabilityRow(store, options) {
1056
+ if (options.id) return readCapabilityRow(store.toolMemory.get(options.id), options.id);
1057
+ if (!options.name) return void 0;
1058
+ const target = capabilityLogicalName(options.name);
1059
+ for (const candidate of capabilityRows(store)) {
1060
+ if (candidate.record.name !== target) continue;
1061
+ if (options.workspaceKey && candidate.row.workspaceKey && candidate.row.workspaceKey !== options.workspaceKey) continue;
1062
+ return candidate;
1063
+ }
1064
+ }
1065
+ async function saveCapabilityRecord(store, record, options = {}) {
1066
+ if (options.id) {
1067
+ await store.toolMemory.update(options.id, (row) => ({
1068
+ ...row,
1069
+ ...rowOfRecord(record, options.workspaceKey ?? row.workspaceKey, row.createdAt ?? options.createdAt)
1070
+ }));
1071
+ return options.id;
1072
+ }
1073
+ const id = newId("tm");
1074
+ await store.toolMemory.put(id, rowOfRecord(record, options.workspaceKey ?? (record.scope ? workspaceKeyOf(record.scope) : void 0), options.createdAt ?? Date.now()));
1075
+ return id;
1076
+ }
1077
+ /**
1078
+ * R51: a unit that is really a legacy tool-order shell, even after R50 rewrote
1079
+ * its SKILL.md face from `sm-source: sequence` to `sm-source: capability`.
1080
+ * Executable capabilities are never shells — only knowledge-only units qualify.
1081
+ */
1082
+ function isShellUnit(record) {
1083
+ if (record.kind === "capability" && String(record.entry ?? "").trim()) return false;
1084
+ return isShellIdentity({
1085
+ name: record.name,
1086
+ description: record.description,
1087
+ source: record.source,
1088
+ body: record.draftBody
1089
+ });
1090
+ }
1091
+ /** Retire one unit row without deleting it (audit + rollback stay possible). */
1092
+ async function retireUnitRow(store, id) {
1093
+ await store.toolMemory.update(id, (row) => ({
1094
+ ...row,
1095
+ status: "retired",
1096
+ enabled: false
1097
+ }));
1098
+ }
1099
+ /**
1100
+ * R51: idempotently retire every adopted tool-order shell unit.
1101
+ * Used by migration, boot cleanup and `memory_toolize cleanup`; never deletes.
1102
+ */
1103
+ async function retireShellUnits(store, options = {}) {
1104
+ const retired = [];
1105
+ for (const entry of capabilityRows(store)) {
1106
+ if (entry.record.kind === "proposal") continue;
1107
+ if (entry.row.status === "retired") continue;
1108
+ if (!isShellUnit(entry.record)) continue;
1109
+ retired.push({
1110
+ id: entry.id,
1111
+ name: entry.record.name
1112
+ });
1113
+ if (!options.dryRun) try {
1114
+ await retireUnitRow(store, entry.id);
1115
+ } catch {}
1116
+ }
1117
+ return retired;
1118
+ }
1119
+ function normalizePathKey(path) {
1120
+ try {
1121
+ return resolve(path).replace(/\\/g, "/").toLowerCase();
1122
+ } catch {
1123
+ return String(path ?? "").replace(/\\/g, "/").toLowerCase();
1124
+ }
1125
+ }
1126
+ function skillRootOf(file) {
1127
+ try {
1128
+ const normalized = resolve(file).replace(/\\/g, "/");
1129
+ const lower = normalized.toLowerCase();
1130
+ const index = lower.lastIndexOf("/.dsh/skills/");
1131
+ if (index >= 0) return resolve(normalized.slice(0, index + 13 - 1));
1132
+ const homeSkills = resolve(process.env.DSH_HOME ?? join(homedir(), ".dsh"), "skills").replace(/\\/g, "/");
1133
+ if (lower.startsWith(homeSkills.toLowerCase() + "/")) return resolve(homeSkills);
1134
+ } catch {}
1135
+ }
1136
+ async function migrateCapabilityDocs(store, options = {}) {
1137
+ const now = options.now ?? Date.now();
1138
+ const report = {
1139
+ moved: 0,
1140
+ archivedDirs: 0,
1141
+ skippedManual: 0,
1142
+ skippedShells: 0,
1143
+ changed: false,
1144
+ entries: []
1145
+ };
1146
+ for (const entry of capabilityRows(store)) {
1147
+ const record = entry.record;
1148
+ if (record.kind === "proposal" || entry.row.status === "retired") continue;
1149
+ const oldPath = String(record.skillPath ?? "").trim();
1150
+ if (!oldPath) continue;
1151
+ if (!skillRootOf(oldPath)) continue;
1152
+ const owned = entry.row.workspaceKey ?? (record.scope ? workspaceKeyOf(record.scope) : void 0);
1153
+ if (!owned || owned === "unknown" || !isAbsolute(owned) || !existsSync(owned)) continue;
1154
+ const newRoot = options.capabilityRoot ?? resolveCapabilityRoot(owned).root;
1155
+ const newPath = capabilityDocPath(newRoot, record.name);
1156
+ const oldExists = existsSync(oldPath);
1157
+ const newExists = existsSync(newPath);
1158
+ if (oldExists) {
1159
+ let parsed;
1160
+ try {
1161
+ parsed = parseSkillMarkdown(readFileSync(oldPath, "utf8"), capabilitySkillName(record.name));
1162
+ } catch {
1163
+ parsed = void 0;
1164
+ }
1165
+ if (!parsed) continue;
1166
+ if (parsed.source === "sequence" || isShellIdentity({
1167
+ name: parsed.name,
1168
+ description: parsed.description,
1169
+ source: parsed.source,
1170
+ body: parsed.body
1171
+ })) {
1172
+ report.skippedShells += 1;
1173
+ continue;
1174
+ }
1175
+ if (parsed.source !== "capability") {
1176
+ report.skippedManual += 1;
1177
+ continue;
1178
+ }
1179
+ if (!newExists) try {
1180
+ mkdirSync(newRoot, { recursive: true });
1181
+ copyFileSync(oldPath, newPath);
1182
+ } catch (error) {
1183
+ options.logger?.info("supermemory: capability doc copy failed " + oldPath + ": " + String(error).slice(0, 120));
1184
+ continue;
1185
+ }
1186
+ const oldSkillRoot = dirname(dirname(oldPath));
1187
+ const oldSkillName = basename(dirname(oldPath));
1188
+ let archivePath;
1189
+ try {
1190
+ const archived = await archiveCapabilitySkill(oldSkillRoot, oldSkillName, {
1191
+ now,
1192
+ reason: "R52 能力知识面迁移:从宿主 skill 目录移出到 .dsh/capabilities(可回滚)"
1193
+ });
1194
+ archivePath = archived?.archivePath;
1195
+ if (archived) report.archivedDirs += 1;
1196
+ } catch {}
1197
+ if (!archivePath) continue;
1198
+ await saveCapabilityRecord(store, {
1199
+ ...record,
1200
+ skillPath: newPath
1201
+ }, {
1202
+ id: entry.id,
1203
+ workspaceKey: entry.row.workspaceKey,
1204
+ createdAt: entry.row.createdAt
1205
+ });
1206
+ report.moved += 1;
1207
+ report.changed = true;
1208
+ report.entries.push({
1209
+ name: record.name,
1210
+ from: oldPath,
1211
+ to: newPath,
1212
+ archivePath
1213
+ });
1214
+ options.logger?.info("supermemory: capability doc moved " + record.name + " -> " + newPath);
1215
+ continue;
1216
+ }
1217
+ if (newExists) {
1218
+ await saveCapabilityRecord(store, {
1219
+ ...record,
1220
+ skillPath: newPath
1221
+ }, {
1222
+ id: entry.id,
1223
+ workspaceKey: entry.row.workspaceKey,
1224
+ createdAt: entry.row.createdAt
1225
+ });
1226
+ report.moved += 1;
1227
+ report.changed = true;
1228
+ report.entries.push({
1229
+ name: record.name,
1230
+ from: oldPath,
1231
+ to: newPath
1232
+ });
1233
+ }
1234
+ }
1235
+ return report;
1236
+ }
1237
+ /** R54: one-line explanation written into the knowledge face when a version is restored. */
1238
+ function versionRestoreLine(version, restoredFrom) {
1239
+ if (!restoredFrom) return "v" + version + ": 知识面版本与能力记录对齐(R54 单调化)";
1240
+ let source = "";
1241
+ try {
1242
+ source = basename(dirname(restoredFrom));
1243
+ } catch {
1244
+ source = "";
1245
+ }
1246
+ return "v" + version + ": R52 迁移到 .dsh/capabilities,保留归档版本" + (source ? "(源自归档 " + source + ")" : "");
1247
+ }
1248
+ /**
1249
+ * R54: enforce the monotonic knowledge-face version ledger.
1250
+ *
1251
+ * R52's migration could regenerate `.dsh/capabilities/<name>.md` from a stale
1252
+ * record version (6) while the pre-R52 archive still carried the newer file
1253
+ * (8) — the live document then regressed two versions. The rule is now
1254
+ * max(record.version, live file version, every archived version); when the max
1255
+ * comes from somewhere else, the live file is rewritten AT that version (prose
1256
+ * untouched) and the restoration is recorded in both the file and the record.
1257
+ * Idempotent: a second pass finds every ledger aligned and reports changed=false.
1258
+ */
1259
+ async function reconcileCapabilityVersions(store, options = {}) {
1260
+ const now = options.now ?? Date.now();
1261
+ const report = {
1262
+ reconciled: 0,
1263
+ changed: false,
1264
+ entries: []
1265
+ };
1266
+ for (const entry of capabilityRows(store)) {
1267
+ const record = entry.record;
1268
+ if (record.kind === "proposal" || entry.row.status === "retired") continue;
1269
+ const owned = entry.row.workspaceKey ?? (record.scope ? workspaceKeyOf(record.scope) : void 0);
1270
+ let root = options.capabilityRoot;
1271
+ let skillsRoot = options.skillsRoot;
1272
+ const usable = owned && owned !== "unknown" && isAbsolute(owned) && existsSync(owned);
1273
+ if (!root && usable) try {
1274
+ root = resolveCapabilityRoot(owned).root;
1275
+ } catch {
1276
+ root = void 0;
1277
+ }
1278
+ if (!skillsRoot && usable) try {
1279
+ skillsRoot = resolveSkillRoot(owned).root;
1280
+ } catch {
1281
+ skillsRoot = void 0;
1282
+ }
1283
+ if (!root) continue;
1284
+ const livePath = String(record.skillPath ?? "").trim();
1285
+ const docPath = livePath && existsSync(livePath) ? livePath : capabilityDocPath(root, record.name);
1286
+ const archived = archivedCapabilityDocFiles(root, record.name, skillsRoot).map((file) => ({
1287
+ file,
1288
+ version: readSkillVersionAt(file)
1289
+ })).filter((row) => row.version > 0).sort((left, right) => right.version - left.version);
1290
+ if (!existsSync(docPath)) {
1291
+ if (archived.length === 0) continue;
1292
+ try {
1293
+ mkdirSync(dirname(docPath), { recursive: true });
1294
+ copyFileSync(archived[0].file, docPath);
1295
+ } catch {
1296
+ continue;
1297
+ }
1298
+ }
1299
+ const fileVersion = readSkillVersionAt(docPath);
1300
+ const preserved = Math.max(record.version, fileVersion, archived[0]?.version ?? 0);
1301
+ if (preserved <= record.version && preserved <= fileVersion) continue;
1302
+ const restoredFrom = archived[0] && archived[0].version > Math.max(record.version, fileVersion) ? archived[0].file : void 0;
1303
+ const line = versionRestoreLine(preserved, restoredFrom);
1304
+ let restoredHistory = [];
1305
+ if (restoredFrom) try {
1306
+ restoredHistory = parseSkillMarkdown(readFileSync(restoredFrom, "utf8"), capabilitySkillNames(record.name).skillName)?.changelog ?? [];
1307
+ } catch {
1308
+ restoredHistory = [];
1309
+ }
1310
+ const adopted = adoptCapabilityDocVersion({
1311
+ path: docPath,
1312
+ name: record.name,
1313
+ title: record.title,
1314
+ tags: record.tags,
1315
+ version: preserved,
1316
+ changelogLine: line,
1317
+ ...restoredHistory.length > 0 ? { extraChangelog: restoredHistory } : {},
1318
+ now
1319
+ });
1320
+ if (adopted.status === "error") {
1321
+ options.logger?.info("supermemory: capability version reconcile failed " + record.name + ": " + adopted.message);
1322
+ continue;
1323
+ }
1324
+ const next = {
1325
+ ...record,
1326
+ version: adopted.version,
1327
+ updatedAt: now,
1328
+ changelog: (record.changelog[0] === line ? record.changelog : [line, ...record.changelog]).slice(0, CHANGELOG_MAX),
1329
+ skillPath: docPath,
1330
+ ...adopted.bodyHash ? { bodyHash: adopted.bodyHash } : {},
1331
+ ...adopted.factsHash ? { factsHash: adopted.factsHash } : {}
1332
+ };
1333
+ const builtin = BUILTIN_CAPABILITIES.find((candidate) => capabilityLogicalName(candidate.name) === record.name);
1334
+ if (builtin) {
1335
+ next.builtin = true;
1336
+ next.builtinVersion = builtin.version;
1337
+ }
1338
+ await saveCapabilityRecord(store, next, {
1339
+ id: entry.id,
1340
+ workspaceKey: entry.row.workspaceKey,
1341
+ createdAt: entry.row.createdAt
1342
+ });
1343
+ report.reconciled += 1;
1344
+ report.changed = true;
1345
+ report.entries.push({
1346
+ name: record.name,
1347
+ version: adopted.version,
1348
+ path: docPath,
1349
+ ...restoredFrom ? { restoredFrom } : {}
1350
+ });
1351
+ options.logger?.info("supermemory: capability version reconciled " + record.name + " -> v" + adopted.version + (restoredFrom ? "(恢复归档版本)" : ""));
1352
+ }
1353
+ return report;
1354
+ }
1355
+ /**
1356
+ * R54: make the health counters tell ONE story.
1357
+ *
1358
+ * Legacy rows can carry successCount=13 / failCount=9 / consecutiveFailures=2 /
1359
+ * lastStatus='failed' while runCount stayed 0 (the old `usage` object was
1360
+ * carried into the record without its denominator). The panel then renders
1361
+ * "0 runs, 0 loads→runs, 13 successes, 9 failures", which reads as a bug.
1362
+ *
1363
+ * Chosen rule (documented in CHANGELOG/DEV-NOTES): PRESERVE the history instead
1364
+ * of discarding it — runCount = max(runCount, successCount + failCount), the
1365
+ * success rate keeps its real denominator, and lastStatus is forced to agree
1366
+ * with the most recent outcome (a non-zero consecutive-failure streak means the
1367
+ * last run failed). Everything is derived, so the pass is idempotent.
1368
+ */
1369
+ function reconcileCapabilityHealth(record) {
1370
+ const successCount = Math.max(0, Number(record.successCount) || 0);
1371
+ const failCount = Math.max(0, Number(record.failCount) || 0);
1372
+ const runs = successCount + failCount;
1373
+ const previousRuns = Math.max(0, Number(record.runCount) || 0);
1374
+ const runCount = Math.max(previousRuns, runs);
1375
+ const legacyFolded = runs > previousRuns;
1376
+ const consecutiveFailures = failCount === 0 ? 0 : Math.min(Math.max(0, Number(record.consecutiveFailures) || 0), failCount);
1377
+ let lastStatus = record.lastStatus;
1378
+ if (consecutiveFailures > 0) lastStatus = "failed";
1379
+ else if (lastStatus === "failed" && successCount > 0) lastStatus = "completed";
1380
+ else if (!lastStatus && runCount > 0) lastStatus = successCount > 0 ? "completed" : "failed";
1381
+ if (!(runCount !== record.runCount || consecutiveFailures !== record.consecutiveFailures || lastStatus !== record.lastStatus)) return {
1382
+ record,
1383
+ changed: false,
1384
+ legacyFolded: false
1385
+ };
1386
+ return {
1387
+ record: {
1388
+ ...record,
1389
+ runCount,
1390
+ consecutiveFailures,
1391
+ ...lastStatus ? { lastStatus } : {}
1392
+ },
1393
+ changed: true,
1394
+ legacyFolded
1395
+ };
1396
+ }
1397
+ /**
1398
+ * Lazy, idempotent migration: convert every legacy row exactly once.
1399
+ *
1400
+ * R51 order is load-bearing: shell skills are ARCHIVED (and their mirror rows
1401
+ * retired) before any row is turned into a unit. R50 refreshed every row's
1402
+ * knowledge face, which re-created archived shells under their canonical path
1403
+ * with `sm-source: capability` — the next scan then saw a brand-new unit.
1404
+ * Old sequence rows are retired (never registered); old capability rows become
1405
+ * executable capabilities; old skill rows become knowledge capabilities; skill
1406
+ * files without a row become knowledge capabilities — unless they are shells.
1407
+ */
1408
+ async function migrateCapabilities(store, options = {}) {
1409
+ const now = options.now ?? Date.now();
1410
+ const report = {
1411
+ migratedCapabilities: 0,
1412
+ migratedKnowledge: 0,
1413
+ retiredComposites: 0,
1414
+ linkedSkills: 0,
1415
+ generatedSkills: 0,
1416
+ expiredProposals: 0,
1417
+ archivedShells: 0,
1418
+ retiredShellUnits: 0,
1419
+ dedupedKnowledge: 0,
1420
+ movedDocs: 0,
1421
+ archivedDocDirs: 0,
1422
+ skippedManualDocs: 0,
1423
+ versionsReconciled: 0,
1424
+ healthReconciled: 0,
1425
+ changed: false
1426
+ };
1427
+ const roots = /* @__PURE__ */ new Set();
1428
+ if (options.root) roots.add(options.root);
1429
+ for (const [, row] of store.toolMemory.entries()) {
1430
+ if (!row.workspaceKey || row.workspaceKey === "unknown" || !isAbsolute(row.workspaceKey) || !existsSync(row.workspaceKey)) continue;
1431
+ try {
1432
+ roots.add(resolveSkillRoot(row.workspaceKey).root);
1433
+ } catch {}
1434
+ }
1435
+ try {
1436
+ const archived = await archiveShellSkills({
1437
+ roots: [...roots],
1438
+ store,
1439
+ now
1440
+ });
1441
+ report.archivedShells = archived.totalArchived;
1442
+ if (archived.totalArchived > 0) report.changed = true;
1443
+ } catch {}
1444
+ const seen = /* @__PURE__ */ new Map();
1445
+ for (const [id, row] of [...store.toolMemory.entries()]) {
1446
+ if (row.status === "retired" && (row.kind === "skill" || row.kind === "knowledge")) continue;
1447
+ if (row.kind === "composite" || row.kind === "workflow") {
1448
+ let raw;
1449
+ try {
1450
+ raw = JSON.parse(row.entry);
1451
+ } catch {
1452
+ raw = void 0;
1453
+ }
1454
+ if (!raw || raw.kind !== "capability" || !str(raw.entry)) {
1455
+ if (row.status !== "retired") {
1456
+ await store.toolMemory.update(id, (record) => ({
1457
+ ...record,
1458
+ status: "retired"
1459
+ }));
1460
+ report.retiredComposites += 1;
1461
+ report.changed = true;
1462
+ }
1463
+ continue;
1464
+ }
1465
+ const record = legacyCapabilityRecord(raw, row);
1466
+ const key = (row.workspaceKey ?? "global") + "|" + record.name;
1467
+ if (seen.has(key)) {
1468
+ await store.toolMemory.update(id, (r) => ({
1469
+ ...r,
1470
+ status: "retired"
1471
+ }));
1472
+ report.retiredComposites += 1;
1473
+ continue;
1474
+ }
1475
+ seen.set(key, id);
1476
+ await saveCapabilityRecord(store, record, {
1477
+ id,
1478
+ workspaceKey: row.workspaceKey,
1479
+ createdAt: row.createdAt ?? now
1480
+ });
1481
+ report.migratedCapabilities += 1;
1482
+ report.changed = true;
1483
+ options.logger?.info("supermemory: migrated capability " + record.name + " -> " + capabilityToolName(record.name));
1484
+ continue;
1485
+ }
1486
+ if (row.kind === "proposal") {
1487
+ const parsed = readCapabilityRow(row, id);
1488
+ if (parsed && parsed.record.expiresAt !== void 0 && parsed.record.expiresAt < now && parsed.record.proposalStatus === "pending") {
1489
+ parsed.record.proposalStatus = "declined";
1490
+ await saveCapabilityRecord(store, parsed.record, {
1491
+ id,
1492
+ workspaceKey: row.workspaceKey,
1493
+ createdAt: row.createdAt
1494
+ });
1495
+ report.expiredProposals += 1;
1496
+ }
1497
+ continue;
1498
+ }
1499
+ if (row.kind === "skill") {
1500
+ const parsed = readCapabilityRow(row, id);
1501
+ if (!parsed) continue;
1502
+ const record = parsed.record;
1503
+ if (isShellUnit(record)) {
1504
+ await retireUnitRow(store, id);
1505
+ report.retiredShellUnits += 1;
1506
+ report.changed = true;
1507
+ continue;
1508
+ }
1509
+ record.kind = "knowledge";
1510
+ record.entry = "";
1511
+ record.runnable = false;
1512
+ record.source = record.source === "manual" ? "manual" : "migrated";
1513
+ const key = (row.workspaceKey ?? "global") + "|" + record.name;
1514
+ if (seen.has(key)) continue;
1515
+ seen.set(key, id);
1516
+ await saveCapabilityRecord(store, record, {
1517
+ id,
1518
+ workspaceKey: row.workspaceKey,
1519
+ createdAt: row.createdAt
1520
+ });
1521
+ report.migratedKnowledge += 1;
1522
+ report.changed = true;
1523
+ continue;
1524
+ }
1525
+ if (row.kind === "knowledge" || row.kind === "capability") {
1526
+ const parsed = readCapabilityRow(row, id);
1527
+ if (!parsed) continue;
1528
+ if (isShellUnit(parsed.record)) {
1529
+ await retireUnitRow(store, id);
1530
+ report.retiredShellUnits += 1;
1531
+ report.changed = true;
1532
+ continue;
1533
+ }
1534
+ const key = (row.workspaceKey ?? "global") + "|" + parsed.record.name;
1535
+ if (seen.has(key)) continue;
1536
+ seen.set(key, id);
1537
+ let legacy = false;
1538
+ try {
1539
+ legacy = JSON.parse(row.entry).schema !== CAPABILITY_SCHEMA;
1540
+ } catch {
1541
+ legacy = true;
1542
+ }
1543
+ if (legacy) {
1544
+ await saveCapabilityRecord(store, parsed.record, {
1545
+ id,
1546
+ workspaceKey: row.workspaceKey,
1547
+ createdAt: row.createdAt
1548
+ });
1549
+ report.changed = true;
1550
+ }
1551
+ continue;
1552
+ }
1553
+ }
1554
+ try {
1555
+ const docs = await migrateCapabilityDocs(store, {
1556
+ now,
1557
+ ...options.capabilityRoot ? { capabilityRoot: options.capabilityRoot } : {},
1558
+ ...options.logger ? { logger: options.logger } : {}
1559
+ });
1560
+ report.movedDocs = docs.moved;
1561
+ report.archivedDocDirs = docs.archivedDirs;
1562
+ report.skippedManualDocs = docs.skippedManual;
1563
+ if (docs.changed) report.changed = true;
1564
+ } catch (error) {
1565
+ options.logger?.info("supermemory: capability doc migration failed: " + String(error).slice(0, 160));
1566
+ }
1567
+ try {
1568
+ const versions = await reconcileCapabilityVersions(store, {
1569
+ now,
1570
+ ...options.capabilityRoot ? { capabilityRoot: options.capabilityRoot } : {},
1571
+ ...options.root ? { skillsRoot: options.root } : {},
1572
+ ...options.logger ? { logger: options.logger } : {}
1573
+ });
1574
+ report.versionsReconciled = versions.reconciled;
1575
+ if (versions.changed) report.changed = true;
1576
+ } catch (error) {
1577
+ options.logger?.info("supermemory: capability version reconcile failed: " + String(error).slice(0, 160));
1578
+ }
1579
+ for (const entry of capabilityRows(store)) {
1580
+ if (entry.record.kind === "proposal" || entry.row.status === "retired") continue;
1581
+ const health = reconcileCapabilityHealth(entry.record);
1582
+ if (!health.changed) continue;
1583
+ await saveCapabilityRecord(store, health.record, {
1584
+ id: entry.id,
1585
+ workspaceKey: entry.row.workspaceKey,
1586
+ createdAt: entry.row.createdAt
1587
+ });
1588
+ report.healthReconciled += 1;
1589
+ report.changed = true;
1590
+ }
1591
+ const capabilityPaths = /* @__PURE__ */ new Map();
1592
+ for (const entry of capabilityRows(store)) {
1593
+ if (entry.record.kind !== "capability" || !entry.record.skillPath) continue;
1594
+ capabilityPaths.set(normalizePathKey(entry.record.skillPath), entry.record.name);
1595
+ }
1596
+ for (const entry of capabilityRows(store)) {
1597
+ if (entry.record.kind !== "knowledge" || entry.row.status === "retired" || !entry.record.skillPath) continue;
1598
+ if (!capabilityPaths.has(normalizePathKey(entry.record.skillPath))) continue;
1599
+ await retireUnitRow(store, entry.id);
1600
+ report.dedupedKnowledge += 1;
1601
+ report.changed = true;
1602
+ }
1603
+ for (const entry of capabilityRows(store)) {
1604
+ if (entry.record.kind === "proposal") continue;
1605
+ if (entry.row.status === "retired") continue;
1606
+ if (isShellUnit(entry.record)) {
1607
+ await retireUnitRow(store, entry.id);
1608
+ report.retiredShellUnits += 1;
1609
+ report.changed = true;
1610
+ continue;
1611
+ }
1612
+ let root = options.capabilityRoot;
1613
+ const owned = entry.row.workspaceKey;
1614
+ if (!root && owned && owned !== "unknown" && isAbsolute(owned) && existsSync(owned)) try {
1615
+ root = resolveCapabilityRoot(owned).root;
1616
+ } catch {
1617
+ root = void 0;
1618
+ }
1619
+ if (!root) continue;
1620
+ try {
1621
+ const result = await syncCapabilitySkill(store, entry, root, { now });
1622
+ if (result && result.status === "created") report.generatedSkills += 1;
1623
+ if (result && result.status !== "unchanged") report.changed = true;
1624
+ } catch {}
1625
+ }
1626
+ return report;
1627
+ }
1628
+ /** Synchronise one capability's SKILL.md (knowledge face). */
1629
+ async function syncCapabilitySkill(store, entry, root, options = {}) {
1630
+ const record = entry.record;
1631
+ if (record.kind === "proposal") return void 0;
1632
+ if (isShellUnit(record)) return void 0;
1633
+ const input = {
1634
+ name: record.name,
1635
+ title: record.title,
1636
+ description: record.description,
1637
+ ...record.entry ? { entry: record.entry } : {},
1638
+ ...!record.entry && record.entryDraft ? { entryDraft: record.entryDraft } : {},
1639
+ ...record.scope ? { scope: record.scope } : {},
1640
+ ...record.doc ? { doc: record.doc } : {},
1641
+ ...record.dryRunArg ? { dryRunArg: record.dryRunArg } : {},
1642
+ writeConfirm: record.writeConfirm,
1643
+ runnable: record.runnable,
1644
+ ...record.taskKey ? { taskKey: record.taskKey } : {},
1645
+ tags: record.tags,
1646
+ source: record.source,
1647
+ version: record.version,
1648
+ ...record.routeNote ? { routeNote: record.routeNote } : {},
1649
+ facts: record.facts
1650
+ };
1651
+ const result = await upsertCapabilitySkill({
1652
+ store,
1653
+ workspaceKey: entry.row.workspaceKey ?? (record.scope ? workspaceKeyOf(record.scope) : "unknown"),
1654
+ root,
1655
+ input,
1656
+ ...options.draftBody ?? record.draftBody ? { draftBody: options.draftBody ?? record.draftBody } : {},
1657
+ ...options.now !== void 0 ? { now: options.now } : {},
1658
+ ...options.changelog ? { changelog: options.changelog } : {},
1659
+ ...record.bodyHash ? { previousBodyHash: record.bodyHash } : {}
1660
+ });
1661
+ const next = {
1662
+ ...record,
1663
+ skillPath: result.path ?? record.skillPath,
1664
+ bodyHash: result.bodyHash ?? record.bodyHash,
1665
+ factsHash: result.factsHash ?? record.factsHash,
1666
+ version: Math.max(record.version, Math.floor(Number(result.version) || 0))
1667
+ };
1668
+ if (result.status !== "error") await saveCapabilityRecord(store, next, {
1669
+ id: entry.id,
1670
+ workspaceKey: entry.row.workspaceKey,
1671
+ createdAt: entry.row.createdAt
1672
+ });
1673
+ return result;
1674
+ }
1675
+ function isValidCapabilityName(name) {
1676
+ return /^[a-zA-Z0-9][a-zA-Z0-9_-]{0,40}$/.test(String(name ?? ""));
1677
+ }
1678
+ /** Build + validate one capability record (pure). */
1679
+ function buildCapabilityRecord(input) {
1680
+ const rawName = String(input.name ?? "").trim();
1681
+ if (!isValidCapabilityName(rawName)) return {
1682
+ status: "error",
1683
+ message: "能力名称只能包含字母/数字/-/_(≤41 字符)且以字母或数字开头。"
1684
+ };
1685
+ const logical = capabilityLogicalName(rawName);
1686
+ const description = String(input.description ?? "").trim();
1687
+ if (!description) return {
1688
+ status: "error",
1689
+ message: "描述不能为空(模型靠它路由到本能力)。"
1690
+ };
1691
+ if (description.length > 500) return {
1692
+ status: "error",
1693
+ message: "描述过长(≤500 字符)。"
1694
+ };
1695
+ const entry = String(input.entry ?? "").trim();
1696
+ const entryDraft = String(input.entryDraft ?? "").trim();
1697
+ if (entry.length > 300 || entryDraft.length > 300) return {
1698
+ status: "error",
1699
+ message: "入口命令过长(≤300 字符)。"
1700
+ };
1701
+ const kind = entry || entryDraft ? "capability" : "knowledge";
1702
+ const record = {
1703
+ schema: CAPABILITY_SCHEMA,
1704
+ name: logical,
1705
+ kind,
1706
+ title: String(input.title ?? "").trim().slice(0, 80) || logical,
1707
+ description,
1708
+ tags: (input.tags && input.tags.length > 0 ? input.tags : [logical]).map((tag) => String(tag).slice(0, 24)).slice(0, 8),
1709
+ entry,
1710
+ entryDraft,
1711
+ entryVerified: Boolean(entry) && !entryDraft,
1712
+ doc: String(input.doc ?? "").trim().slice(0, 300),
1713
+ scope: String(input.scope ?? "").trim().slice(0, 300),
1714
+ runnable: Boolean(entry) && (input.runnable === void 0 ? true : Boolean(input.runnable)),
1715
+ enabled: true,
1716
+ dryRunArg: String(input.dryRunArg ?? "").trim().slice(0, 80),
1717
+ writeConfirm: Boolean(input.writeConfirm),
1718
+ routeNote: String(input.routeNote ?? "").trim().slice(0, 500),
1719
+ source: input.source ?? "manual",
1720
+ taskKey: String(input.taskKey ?? "").trim().slice(0, 120),
1721
+ version: 1,
1722
+ updatedAt: Date.now(),
1723
+ changelog: [],
1724
+ skillPath: "",
1725
+ bodyHash: "",
1726
+ factsHash: "",
1727
+ facts: {},
1728
+ loadCount: 0,
1729
+ runCount: 0,
1730
+ successCount: 0,
1731
+ failCount: 0,
1732
+ consecutiveFailures: 0,
1733
+ builtin: false
1734
+ };
1735
+ if (kind === "capability" && entryDraft && !entry) {
1736
+ record.entryVerified = false;
1737
+ record.runnable = false;
1738
+ }
1739
+ return {
1740
+ status: "ok",
1741
+ record
1742
+ };
1743
+ }
1744
+ /** Live registrations of the execution face (tool name -> disposer). */
1745
+ const liveCapabilities = /* @__PURE__ */ new Map();
1746
+ const liveCapabilityToolNames = /* @__PURE__ */ new Set();
1747
+ function liveCapabilityNames() {
1748
+ return [...liveCapabilityToolNames];
1749
+ }
1750
+ function disposeCapabilityTool(toolName) {
1751
+ const dispose = liveCapabilities.get(toolName);
1752
+ if (dispose) try {
1753
+ dispose();
1754
+ } catch {}
1755
+ liveCapabilities.delete(toolName);
1756
+ liveCapabilityToolNames.delete(toolName);
1757
+ }
1758
+ const OUTPUT_CLIP = 8e3;
1759
+ const TIMEOUT_MS = 12e4;
1760
+ const PATH_SEP = process.platform === "win32" ? ";" : ":";
1761
+ function clipOutput(text) {
1762
+ return text.length > OUTPUT_CLIP ? text.slice(0, OUTPUT_CLIP) + "\n…(输出过长已截断,原 " + text.length + " 字符)" : text;
1763
+ }
1764
+ /** PATH fallback so node/pnpm resolve even when the host inherited a stripped PATH. */
1765
+ function capabilityExecEnv(base = process.env) {
1766
+ const env = { ...base };
1767
+ const variants = Object.keys(env).filter((name) => name.toLowerCase() === "path");
1768
+ const key = variants[0] ?? "PATH";
1769
+ for (const variant of variants.slice(1)) delete env[variant];
1770
+ const parts = String(env[key] ?? "").split(PATH_SEP).map((part) => part.trim()).filter(Boolean);
1771
+ const seen = new Set(parts.map((part) => process.platform === "win32" ? part.toLowerCase() : part));
1772
+ const candidates = [];
1773
+ const add = (dir) => {
1774
+ if (dir && isAbsolute(dir)) candidates.push(dir);
1775
+ };
1776
+ add(dirname(process.execPath));
1777
+ add(env.PNPM_HOME);
1778
+ if (process.platform === "win32") {
1779
+ if (env.APPDATA) add(join(env.APPDATA, "npm"));
1780
+ if (env.LOCALAPPDATA) add(join(env.LOCALAPPDATA, "pnpm"));
1781
+ if (env.ProgramFiles) add(join(env.ProgramFiles, "nodejs"));
1782
+ if (env["ProgramFiles(x86)"]) add(join(env["ProgramFiles(x86)"], "nodejs"));
1783
+ }
1784
+ for (const dir of candidates) {
1785
+ const dedupe = process.platform === "win32" ? dir.toLowerCase() : dir;
1786
+ if (seen.has(dedupe) || !existsSync(dir)) continue;
1787
+ seen.add(dedupe);
1788
+ parts.push(dir);
1789
+ }
1790
+ env[key] = parts.join(PATH_SEP);
1791
+ return env;
1792
+ }
1793
+ /** Execute one capability entry inside its scope (default dry-run; writeConfirm gate). */
1794
+ function runCapability(record, options = {}) {
1795
+ if (record.kind !== "capability" || !record.entry) return {
1796
+ status: "failed",
1797
+ stdout: "",
1798
+ stderr: "",
1799
+ durationMs: 0,
1800
+ dryRun: Boolean(options.dryRun),
1801
+ command: "",
1802
+ summary: "不是可执行的能力(缺少入口命令)。"
1803
+ };
1804
+ if (record.runnable === false || record.enabled === false) return {
1805
+ status: "failed",
1806
+ stdout: "",
1807
+ stderr: "",
1808
+ durationMs: 0,
1809
+ dryRun: Boolean(options.dryRun),
1810
+ command: record.entry,
1811
+ summary: "该能力未开放执行(runnable/enabled=false)。"
1812
+ };
1813
+ const dryRun = options.dryRun !== void 0 ? Boolean(options.dryRun) : options.confirm === true ? false : Boolean(record.dryRunArg);
1814
+ const command = dryRun && record.dryRunArg ? record.entry + " " + record.dryRunArg : record.entry;
1815
+ if (dryRun && record.writeConfirm && !record.dryRunArg) return {
1816
+ status: "failed",
1817
+ stdout: "",
1818
+ stderr: "",
1819
+ durationMs: 0,
1820
+ dryRun,
1821
+ command,
1822
+ summary: "该能力标记了写操作确认但未定义预演参数,无法预演;确认执行请显式传 confirm=true。"
1823
+ };
1824
+ if (!dryRun && record.writeConfirm && options.confirm !== true) return {
1825
+ status: "needs-confirm",
1826
+ stdout: "",
1827
+ stderr: "",
1828
+ durationMs: 0,
1829
+ dryRun,
1830
+ command,
1831
+ summary: "该能力真实执行可能写远端/改状态:确认执行请显式传 confirm=true;只要预演可保持缺省。"
1832
+ };
1833
+ const started = Date.now();
1834
+ const child = spawnSync(command, {
1835
+ shell: true,
1836
+ cwd: record.scope && record.scope.trim() ? record.scope : process.cwd(),
1837
+ encoding: "utf8",
1838
+ timeout: TIMEOUT_MS,
1839
+ maxBuffer: 16777216,
1840
+ env: capabilityExecEnv()
1841
+ });
1842
+ const durationMs = Date.now() - started;
1843
+ const exitCode = typeof child.status === "number" ? child.status : void 0;
1844
+ return {
1845
+ status: Boolean(child.error) || exitCode === void 0 ? "failed" : exitCode === 0 ? "completed" : "failed",
1846
+ exitCode,
1847
+ stdout: clipOutput(String(child.stdout ?? "")),
1848
+ stderr: clipOutput(String(child.stderr ?? "")),
1849
+ durationMs,
1850
+ dryRun,
1851
+ command,
1852
+ summary: command + " → " + (child.error ? "启动失败:" + String(child.error).slice(0, 120) : "exit " + exitCode) + "(" + (dryRun ? "预演" : "实跑") + "," + durationMs + "ms)"
1853
+ };
1854
+ }
1855
+ /**
1856
+ * R54: the index line's「何时用」sentence prefers the human TITLE.
1857
+ *
1858
+ * R52 rendered whatever `whenToUse` the caller passed, so a hint that named the
1859
+ * MACHINE name (git-sync-supermemory) contradicted the human title shown by the
1860
+ * panel (「git 同步/提交/推送(SuperMemory 仓库)」). The card now derives the
1861
+ * subject from `title`; a supplied sentence is kept only when it already names
1862
+ * that title (it usually also carries the scope), and rows without a title fall
1863
+ * back to description/whenToUse exactly as before.
1864
+ */
1865
+ function capabilityIndexHint(row) {
1866
+ const title = String(row.title ?? "").trim();
1867
+ const name = String(row.name ?? "").trim();
1868
+ const supplied = String(row.whenToUse ?? "").replace(/\s+/g, " ").trim();
1869
+ if (title && title !== name) {
1870
+ if (supplied && supplied.includes(title)) return supplied;
1871
+ const scope = String(row.scope ?? "").trim();
1872
+ return scope ? "在 " + scope + " 内遇到「" + title + "」类任务时加载。" : "遇到「" + title + "」类任务时加载。";
1873
+ }
1874
+ return supplied || String(row.description ?? "").replace(/\s+/g, " ").trim();
1875
+ }
1876
+ /** 徽标:可执行 / 仅知识 / 入口待验证。 */
1877
+ function capabilityIndexBadge(row) {
1878
+ if (row.entryDraft && !row.entryVerified) return "入口待验证";
1879
+ if (row.entry && row.runnable !== false) return "可执行";
1880
+ return "仅知识";
1881
+ }
1882
+ /**
1883
+ * R52: the compact capability index injected into hub/branch sessions. The body
1884
+ * is NOT here — the model calls `sm_cap_doc` for it. Budget-aware (R47): rows
1885
+ * degrade with an explicit omission note instead of being hard-sliced.
1886
+ */
1887
+ function renderCapabilityIndex(rows, options = {}) {
1888
+ const maxItems = Math.max(1, Math.min(options.maxItems ?? 8, 8));
1889
+ const budget = Math.max(160, options.budget ?? 1600);
1890
+ const eligible = rows.filter((row) => row.enabled !== false && row.status !== "retired" && row.kind !== "proposal").sort((left, right) => left.name.localeCompare(right.name));
1891
+ if (eligible.length === 0) return {
1892
+ text: "",
1893
+ included: 0,
1894
+ omitted: 0,
1895
+ truncated: false
1896
+ };
1897
+ const header = injectionTitle("capability") + "(仅中枢/分支会话注入;正文按需读取)";
1898
+ const footer = "正文用 sm_cap_doc 加载:sm_cap_doc { name: \"<能力名>\" };中枢只读,执行需派发分支;第三方 skill 仍走宿主 skill 目录。";
1899
+ const lines = eligible.map((row) => {
1900
+ const hint = capabilityIndexHint(row);
1901
+ const clipped = clipAtBoundary(hint, 80) || hint.slice(0, 80);
1902
+ return "- " + row.name + " [" + capabilityIndexBadge(row) + "]:" + clipped;
1903
+ });
1904
+ let kept = lines.slice(0, maxItems);
1905
+ let omitted = lines.length - kept.length;
1906
+ const build = () => [
1907
+ header,
1908
+ ...kept,
1909
+ ...omitted > 0 ? ["… 省略 " + omitted + " 条(sm_cap_doc 可逐个读取)"] : [],
1910
+ footer
1911
+ ].join("\n");
1912
+ while (kept.length > 0 && charCount(build()) > budget) {
1913
+ kept = kept.slice(0, -1);
1914
+ omitted += 1;
1915
+ }
1916
+ const text = build();
1917
+ if (kept.length === 0 && charCount(text) > budget) return {
1918
+ text: clipAtBoundary(header + "…(预算不足,正文用 sm_cap_doc 读取)", budget),
1919
+ included: 0,
1920
+ omitted: lines.length,
1921
+ truncated: true
1922
+ };
1923
+ return {
1924
+ text,
1925
+ included: kept.length,
1926
+ omitted,
1927
+ truncated: omitted > 0
1928
+ };
1929
+ }
1930
+ /** Derive the "when to use" sentence for one capability. */
1931
+ function capabilityWhenToUse(record) {
1932
+ if (record.scope) return "在 " + record.scope + " 内遇到「" + record.title + "」类任务时加载。";
1933
+ return record.description;
1934
+ }
1935
+ /** Extract one `## <section>` block from a capability body. */
1936
+ function extractCapabilitySection(body, section) {
1937
+ const wanted = String(section ?? "").trim().replace(/^#+\s*/, "").toLowerCase();
1938
+ if (!wanted) return void 0;
1939
+ const lines = String(body ?? "").split(/\r?\n/);
1940
+ const headings = [];
1941
+ let start = -1;
1942
+ for (let index = 0; index < lines.length; index += 1) {
1943
+ const match = /^##\s+(.+?)\s*$/.exec(lines[index] ?? "");
1944
+ if (!match) continue;
1945
+ headings.push(match[1]);
1946
+ if (start < 0 && match[1].toLowerCase() === wanted) start = index;
1947
+ }
1948
+ if (start < 0) return {
1949
+ text: "",
1950
+ headings
1951
+ };
1952
+ let end = lines.length;
1953
+ for (let index = start + 1; index < lines.length; index += 1) if (/^##\s+/.test(lines[index] ?? "")) {
1954
+ end = index;
1955
+ break;
1956
+ }
1957
+ return {
1958
+ text: lines.slice(start, end).join("\n").trim(),
1959
+ headings
1960
+ };
1961
+ }
1962
+ /**
1963
+ * R52: load one capability knowledge body on demand (the `sm_cap_doc` tool's
1964
+ * single source of truth). Only enabled, non-retired units whose file exists are
1965
+ * readable; a successful load increments loadCount (conversion-rate denominator).
1966
+ */
1967
+ async function loadCapabilityDoc(store, workspaceKey, rawName, section) {
1968
+ const raw = String(rawName ?? "").trim();
1969
+ if (!raw) return {
1970
+ status: "error",
1971
+ message: "缺少能力名。"
1972
+ };
1973
+ const logical = capabilityLogicalName(raw);
1974
+ const rows = capabilityRows(store, workspaceKey);
1975
+ const entry = rows.find((row) => row.record.name === logical) ?? rows.find((row) => capabilityToolName(row.record.name) === raw) ?? rows.find((row) => capabilitySkillName(row.record.name) === raw);
1976
+ if (!entry) return {
1977
+ status: "error",
1978
+ message: "能力不存在:" + raw + "(可在「固化能力」面板查看可用能力)。"
1979
+ };
1980
+ const record = entry.record;
1981
+ if (record.kind === "proposal") return {
1982
+ status: "error",
1983
+ message: "能力「" + record.name + "」还是待接受提案,尚未生成知识面。"
1984
+ };
1985
+ if (record.enabled === false || entry.row.status === "retired") return {
1986
+ status: "error",
1987
+ message: "能力「" + record.name + "」已停用:不加载知识面。"
1988
+ };
1989
+ if (record.kind === "capability" && record.runnable === false) return {
1990
+ status: "error",
1991
+ message: "能力「" + record.name + "」的执行面尚未启用(入口待验证):先人工启用执行。"
1992
+ };
1993
+ const path = String(record.skillPath ?? "").trim();
1994
+ if (!path || !existsSync(path)) return {
1995
+ status: "error",
1996
+ message: "能力「" + record.name + "」的知识面文件缺失:" + (path || "(未生成)") + ";在面板保存正文可重建。"
1997
+ };
1998
+ let parsed;
1999
+ try {
2000
+ parsed = parseSkillMarkdown(readFileSync(path, "utf8"), capabilitySkillName(record.name));
2001
+ } catch {
2002
+ parsed = void 0;
2003
+ }
2004
+ if (!parsed) return {
2005
+ status: "error",
2006
+ message: "能力「" + record.name + "」的知识面文件解析失败:" + path
2007
+ };
2008
+ const fullBody = parsed.body;
2009
+ let body = fullBody;
2010
+ let headings;
2011
+ if (section !== void 0 && String(section).trim() !== "") {
2012
+ const found = extractCapabilitySection(fullBody, section);
2013
+ if (!found) {
2014
+ headings = extractCapabilitySection(fullBody, "__none__")?.headings ?? [];
2015
+ return {
2016
+ status: "error",
2017
+ message: "知识面没有小节「" + String(section).trim() + "」;可用小节:" + (headings.join("、") || "(无二级标题)"),
2018
+ headings
2019
+ };
2020
+ }
2021
+ if (!found.text) {
2022
+ headings = found.headings;
2023
+ return {
2024
+ status: "error",
2025
+ message: "知识面没有小节「" + String(section).trim() + "」;可用小节:" + (found.headings.join("、") || "(无二级标题)"),
2026
+ headings: found.headings
2027
+ };
2028
+ }
2029
+ body = found.text;
2030
+ headings = found.headings;
2031
+ }
2032
+ const next = {
2033
+ ...record,
2034
+ loadCount: record.loadCount + 1
2035
+ };
2036
+ try {
2037
+ await saveCapabilityRecord(store, next, {
2038
+ id: entry.id,
2039
+ workspaceKey: entry.row.workspaceKey,
2040
+ createdAt: entry.row.createdAt
2041
+ });
2042
+ } catch {}
2043
+ return {
2044
+ status: "ok",
2045
+ message: "已加载能力「" + record.name + "」的知识面(sm_cap_doc)。",
2046
+ name: record.name,
2047
+ title: record.title,
2048
+ body,
2049
+ factsBlock: splitFactsBlock(fullBody).facts,
2050
+ entry: record.entry,
2051
+ scope: record.scope,
2052
+ dryRunArg: record.dryRunArg,
2053
+ writeConfirm: Boolean(record.writeConfirm),
2054
+ whenToUse: capabilityWhenToUse(record),
2055
+ ...headings ? { headings } : {},
2056
+ loadCount: next.loadCount
2057
+ };
2058
+ }
2059
+ /** R52: current knowledge-face body (frontmatter stripped) for the panel editor. */
2060
+ function capabilityBodyOf(record) {
2061
+ const path = String(record.skillPath ?? "").trim();
2062
+ if (!path || !existsSync(path)) return "";
2063
+ try {
2064
+ return parseSkillMarkdown(readFileSync(path, "utf8"), capabilitySkillName(record.name))?.body ?? "";
2065
+ } catch {
2066
+ return "";
2067
+ }
2068
+ }
2069
+ /** Model-visible description of one capability (routing note + semantics + rules). */
2070
+ function capabilityToolDescription(record) {
2071
+ const semantics = "(能力:在适用范围 " + (record.scope || "当前目录") + " 内执行入口命令 " + record.entry + " 的固定入口;" + (record.dryRunArg ? "默认追加预演参数 " + record.dryRunArg + "(只读不改);" : "") + (record.writeConfirm ? "真实执行可能写远端/改状态:confirm=true 表示确认真实执行;" : "") + (record.doc ? "详细流程见 " + record.doc + ";" : "") + "返回 exitCode/stdout/stderr/durationMs。)";
2072
+ return record.description + (record.routeNote ? "。" + record.routeNote : "") + semantics + "\n固化能力(capability)路由规则:① 在能力适用范围(scope)内遇到高频事务(git 同步/提交/推送、构建、验证、测试、发布等)时,优先调用已固化能力(sm_cap_*,默认预演、写操作 confirm=true 确认真实执行),不要每次现敲命令;② 重复工作先沉淀经验:判断型、易变的流程用 memory_toolize register 产出/更新能力知识面(描述写「何时用」,正文写触发条件/步骤/关键坑/验证;模型用 sm_cap_doc 按需读取,不要用宿主 skill 工具加载能力),不要满足于一次性工作;确实需要固定入口命令时才固化能力(入口命令 + 文档 + 适用范围);③ 能力执行连续失败、或文档与现状不符时,必须用 memory_toolize register 同名更新能力(version+1、changelog 记录原因),不要绕过它手敲命令;④ 用 memory_toolize refresh-builtin 刷新内置能力并查看差异报告与健康度(使用次数、成败分列、连续失败、文档/适用范围缺失、零使用),按信号决定更新还是停用;⑤ 职责边界(R55):中枢只能只读检查——用 sm_cap_doc 读知识面判断是否适用,执行必须 memory_dispatch 派发到分支(sm_cap_* 在中枢被 HUB_CAPABILITY_EXEC_DENIED 拒绝);分支才是执行者(默认预演,写操作 confirm=true)。";
2073
+ }
2074
+ function callerCwd(exec) {
2075
+ const cwd = exec.agent?.session?.header?.cwd;
2076
+ return typeof cwd === "string" && cwd.length > 0 ? cwd : void 0;
2077
+ }
2078
+ /** The single model-visible tool of one capability (fixed entry, dry_run/confirm only). */
2079
+ function capabilityToolDef(store, record, rowId, workspaceKey) {
2080
+ return {
2081
+ name: capabilityToolName(record.name),
2082
+ description: capabilityToolDescription(record),
2083
+ parameters: {
2084
+ dry_run: {
2085
+ type: "boolean",
2086
+ description: "true=强制预演;缺省时若能力定义了预演参数则自动预演"
2087
+ },
2088
+ confirm: {
2089
+ type: "boolean",
2090
+ description: "真实执行写操作能力(writeConfirm)时的二次确认,必须为 true"
2091
+ }
2092
+ },
2093
+ output: {
2094
+ schema: {
2095
+ type: "object",
2096
+ properties: {
2097
+ status: {
2098
+ type: "string",
2099
+ enum: [
2100
+ "completed",
2101
+ "failed",
2102
+ "needs-confirm"
2103
+ ],
2104
+ required: true
2105
+ },
2106
+ exitCode: { type: "integer" },
2107
+ stdout: { type: "string" },
2108
+ stderr: { type: "string" },
2109
+ durationMs: { type: "integer" },
2110
+ dryRun: { type: "boolean" },
2111
+ command: { type: "string" },
2112
+ summary: {
2113
+ type: "string",
2114
+ required: true
2115
+ }
2116
+ },
2117
+ additionalProperties: false
2118
+ },
2119
+ render: (_args, value) => {
2120
+ const v = value;
2121
+ return [{
2122
+ type: "text",
2123
+ text: (v.status === "needs-confirm" ? "需要确认:" : "") + String(v.summary ?? "")
2124
+ }];
2125
+ }
2126
+ },
2127
+ async execute(args, exec) {
2128
+ const parsed = readCapabilityRow(store.toolMemory.get(rowId), rowId);
2129
+ if (!parsed || !isExecutable(parsed.record)) return {
2130
+ status: "failed",
2131
+ stdout: "",
2132
+ stderr: "",
2133
+ durationMs: 0,
2134
+ dryRun: false,
2135
+ command: "",
2136
+ summary: "能力不存在或已停用。"
2137
+ };
2138
+ const recordNow = parsed.record;
2139
+ const cwd = callerCwd(exec);
2140
+ if (cwd && recordNow.scope && !scopeContains(recordNow.scope, cwd)) return {
2141
+ status: "failed",
2142
+ stdout: "",
2143
+ stderr: "",
2144
+ durationMs: 0,
2145
+ dryRun: false,
2146
+ command: recordNow.entry,
2147
+ summary: "当前目录不在能力适用范围 " + recordNow.scope + " 内:不执行(scope 外拒绝)。"
2148
+ };
2149
+ if (cwd && workspaceKey && !capabilityAppliesToWorkspace(recordNow, workspaceKeyOf(cwd), workspaceKey)) return {
2150
+ status: "failed",
2151
+ stdout: "",
2152
+ stderr: "",
2153
+ durationMs: 0,
2154
+ dryRun: false,
2155
+ command: recordNow.entry,
2156
+ summary: "该能力适用于其他工作区:不执行(工作区隔离)。"
2157
+ };
2158
+ const result = runCapability(recordNow, {
2159
+ ...typeof args.dry_run === "boolean" ? { dryRun: args.dry_run } : {},
2160
+ ...typeof args.dryRun === "boolean" ? { dryRun: args.dryRun } : {},
2161
+ ...typeof args.confirm === "boolean" ? { confirm: args.confirm } : {}
2162
+ });
2163
+ if (result.status !== "needs-confirm") await bumpCapabilityRun(store, rowId, result);
2164
+ if (result.status === "failed") {
2165
+ const failures = readCapabilityRow(store.toolMemory.get(rowId), rowId)?.record.consecutiveFailures ?? 0;
2166
+ if (failures >= 2) return {
2167
+ ...result,
2168
+ summary: result.summary + "\n连续失败 " + failures + " 次:请更新本能力的事实块/文档(version+1、changelog 记录原因),不要绕过闸门。"
2169
+ };
2170
+ }
2171
+ return result;
2172
+ }
2173
+ };
2174
+ }
2175
+ /** Register one capability tool; returns its disposer. Replaces a previous handle. */
2176
+ async function registerCapabilityTool(ctx, store, entry, workspaceKey) {
2177
+ const toolName = capabilityToolName(entry.record.name);
2178
+ disposeCapabilityTool(toolName);
2179
+ const tools = await loadHostModule("@deepseek-ai/dsh-tools");
2180
+ const workspaceGate = capabilityWhenGate(entry.record, workspaceKey);
2181
+ const gate = (context) => capabilityVisibleToCaller(store, context) && workspaceGate(context);
2182
+ const disposer = ctx.tools.register(tools.defineTool(capabilityToolDef(store, entry.record, entry.id, workspaceKey)), { when: gate });
2183
+ liveCapabilities.set(toolName, disposer);
2184
+ liveCapabilityToolNames.add(toolName);
2185
+ return disposer;
2186
+ }
2187
+ /**
2188
+ * R55: a hub never SEES the execution surface (`sm_cap_*`) in its tool list.
2189
+ * Hiding is the first layer (tool declarations), the role guard is the second
2190
+ * (dispatch): a stale/foreign call is still refused with
2191
+ * `HUB_CAPABILITY_EXEC_DENIED`. `sm_cap_doc` is registered unconditionally, so
2192
+ * the hub keeps its read-only capability check. An unknown/absent agent or a
2193
+ * resolution failure stays visible (fail-open on VISIBILITY only — the guard
2194
+ * still decides execution); branch/ordinary sessions are untouched.
2195
+ */
2196
+ function capabilityVisibleToCaller(store, context) {
2197
+ const agent = context?.agent;
2198
+ if (!agent) return true;
2199
+ try {
2200
+ return resolveRole(store, agent).role !== "hub";
2201
+ } catch {
2202
+ return true;
2203
+ }
2204
+ }
2205
+ /** Registration-side visibility gate (same semantics as execute). */
2206
+ function capabilityWhenGate(record, rowWorkspaceKey) {
2207
+ return (context) => {
2208
+ try {
2209
+ const cwd = context?.agent?.session?.header?.cwd;
2210
+ if (!cwd || typeof cwd !== "string") return true;
2211
+ return capabilityAppliesToWorkspace(record, workspaceKeyOf(cwd), rowWorkspaceKey);
2212
+ } catch {
2213
+ return true;
2214
+ }
2215
+ };
2216
+ }
2217
+ /** Record one actual execution (needs-confirm does not count). */
2218
+ async function bumpCapabilityRun(store, id, result) {
2219
+ const parsed = readCapabilityRow(store.toolMemory.get(id), id);
2220
+ if (!parsed) return;
2221
+ const record = parsed.record;
2222
+ const succeeded = result.status === "completed";
2223
+ const next = {
2224
+ ...record,
2225
+ runCount: record.runCount + 1,
2226
+ successCount: succeeded ? record.successCount + 1 : record.successCount,
2227
+ failCount: succeeded ? record.failCount : record.failCount + 1,
2228
+ consecutiveFailures: succeeded ? 0 : record.consecutiveFailures + 1,
2229
+ lastUsedAt: Date.now(),
2230
+ lastStatus: succeeded ? "completed" : "failed",
2231
+ lastDryRun: result.dryRun,
2232
+ ...typeof result.exitCode === "number" ? { lastExitCode: result.exitCode } : {},
2233
+ ...result.summary ? { lastSummary: result.summary.slice(0, 200) } : {}
2234
+ };
2235
+ try {
2236
+ await saveCapabilityRecord(store, next, {
2237
+ id,
2238
+ workspaceKey: parsed.row.workspaceKey,
2239
+ createdAt: parsed.row.createdAt
2240
+ });
2241
+ } catch {}
2242
+ }
2243
+ /** Record one model-side skill load (knowledge face). */
2244
+ async function bumpCapabilityLoad(store, callerWorkspaceKey, skillName) {
2245
+ for (const entry of capabilityRows(store)) {
2246
+ if (entry.record.kind === "proposal") continue;
2247
+ if (capabilitySkillName(entry.record.name) !== skillName) continue;
2248
+ if (callerWorkspaceKey && entry.row.workspaceKey && callerWorkspaceKey !== entry.row.workspaceKey) continue;
2249
+ const next = {
2250
+ ...entry.record,
2251
+ loadCount: entry.record.loadCount + 1
2252
+ };
2253
+ try {
2254
+ await saveCapabilityRecord(store, next, {
2255
+ id: entry.id,
2256
+ workspaceKey: entry.row.workspaceKey,
2257
+ createdAt: entry.row.createdAt
2258
+ });
2259
+ return true;
2260
+ } catch {
2261
+ return false;
2262
+ }
2263
+ }
2264
+ return false;
2265
+ }
2266
+ function defaultCapabilityDeps() {
2267
+ return { register: registerCapabilityTool };
2268
+ }
2269
+ async function ensureSkillFor(store, entry, workspaceKey, options = {}) {
2270
+ if (!workspaceKey || workspaceKey === "unknown" || !isAbsolute(workspaceKey) || !existsSync(workspaceKey)) return entry;
2271
+ let root;
2272
+ try {
2273
+ root = resolveCapabilityRoot(workspaceKey).root;
2274
+ } catch {
2275
+ return entry;
2276
+ }
2277
+ try {
2278
+ await syncCapabilitySkill(store, entry, root, options);
2279
+ } catch {}
2280
+ return readCapabilityRow(store.toolMemory.get(entry.id), entry.id) ?? entry;
2281
+ }
2282
+ async function registerIfExecutable(ctx, store, entry, workspaceKey, deps) {
2283
+ if (!ctx) return;
2284
+ if (!isExecutable(entry.record)) {
2285
+ disposeCapabilityTool(capabilityToolName(entry.record.name));
2286
+ return;
2287
+ }
2288
+ if (!(typeof ctx.tools?.register === "function")) return;
2289
+ try {
2290
+ await (deps ?? defaultCapabilityDeps()).register(ctx, store, entry, workspaceKey);
2291
+ } catch {}
2292
+ }
2293
+ /**
2294
+ * Register one capability (manual path and builtin seed). Same logical name =
2295
+ * update in place: version+1, changelog, statistics and knowledge face kept.
2296
+ */
2297
+ async function registerCapability(ctx, store, input, workspaceKey, deps) {
2298
+ const built = buildCapabilityRecord(input);
2299
+ if (built.status === "error") return {
2300
+ status: "error",
2301
+ message: built.message
2302
+ };
2303
+ const record = built.record;
2304
+ const own = workspaceKey ?? (record.scope ? workspaceKeyOf(record.scope) : void 0);
2305
+ const existing = findCapabilityRow(store, {
2306
+ name: record.name,
2307
+ ...own ? { workspaceKey: own } : {}
2308
+ });
2309
+ let id;
2310
+ let next;
2311
+ if (existing) {
2312
+ const changeLine = String(input.changelog ?? "").trim().slice(0, 200) || "更新能力定义(入口 " + (record.entry || "无") + (record.doc ? ",文档 " + record.doc : "") + ")";
2313
+ next = {
2314
+ ...record,
2315
+ loadCount: existing.record.loadCount,
2316
+ runCount: existing.record.runCount,
2317
+ successCount: existing.record.successCount,
2318
+ failCount: existing.record.failCount,
2319
+ consecutiveFailures: existing.record.consecutiveFailures,
2320
+ ...existing.record.lastUsedAt !== void 0 ? { lastUsedAt: existing.record.lastUsedAt } : {},
2321
+ ...existing.record.lastStatus ? { lastStatus: existing.record.lastStatus } : {},
2322
+ ...existing.record.lastDryRun !== void 0 ? { lastDryRun: existing.record.lastDryRun } : {},
2323
+ ...existing.record.lastExitCode !== void 0 ? { lastExitCode: existing.record.lastExitCode } : {},
2324
+ ...existing.record.lastSummary ? { lastSummary: existing.record.lastSummary } : {},
2325
+ version: existing.record.version + 1,
2326
+ updatedAt: Date.now(),
2327
+ changelog: [changeLine, ...existing.record.changelog].slice(0, CHANGELOG_MAX)
2328
+ };
2329
+ id = await saveCapabilityRecord(store, next, {
2330
+ id: existing.id,
2331
+ workspaceKey: own ?? existing.row.workspaceKey,
2332
+ createdAt: existing.row.createdAt
2333
+ });
2334
+ } else {
2335
+ next = {
2336
+ ...record,
2337
+ version: 1,
2338
+ updatedAt: Date.now(),
2339
+ changelog: [String(input.changelog ?? "").trim().slice(0, 200) || "注册能力(入口 " + (record.entry || "仅知识") + ")"]
2340
+ };
2341
+ id = await saveCapabilityRecord(store, next, { workspaceKey: own });
2342
+ }
2343
+ let entry = readCapabilityRow(store.toolMemory.get(id), id);
2344
+ entry = await ensureSkillFor(store, entry, own ?? entry.row.workspaceKey, {
2345
+ ...input.body ? { draftBody: input.body } : {},
2346
+ ...input.changelog ? { changelog: input.changelog } : {}
2347
+ });
2348
+ await registerIfExecutable(ctx, store, entry, own ?? entry.row.workspaceKey, deps);
2349
+ const toolName = capabilityToolName(entry.record.name);
2350
+ return {
2351
+ status: "ok",
2352
+ id,
2353
+ name: entry.record.name,
2354
+ tool: entry.record.kind === "capability" ? toolName : capabilitySkillName(entry.record.name),
2355
+ message: (existing ? "已更新能力 " : "已注册能力 ") + entry.record.name + "(v" + entry.record.version + "," + (entry.record.entry ? "入口 " + entry.record.entry : "仅知识") + ";" + (entry.record.kind === "capability" ? "执行面工具 " + toolName : "无执行面") + ";知识面 " + (entry.record.skillPath || "待生成") + ")。"
2356
+ };
2357
+ }
2358
+ /** Enable/disable BOTH faces of one capability. */
2359
+ async function setCapabilityEnabled(ctx, store, id, enabled) {
2360
+ const entry = readCapabilityRow(store.toolMemory.get(id), id);
2361
+ if (!entry) return {
2362
+ status: "error",
2363
+ message: "能力不存在。"
2364
+ };
2365
+ const next = {
2366
+ ...entry.record,
2367
+ enabled,
2368
+ updatedAt: Date.now(),
2369
+ version: entry.record.version + 1,
2370
+ changelog: [(enabled ? "启用" : "停用") + "(知识面与执行面同时生效)", ...entry.record.changelog].slice(0, CHANGELOG_MAX)
2371
+ };
2372
+ const row = rowOfRecord(next, entry.row.workspaceKey, entry.row.createdAt);
2373
+ row.status = enabled ? "active" : "retired";
2374
+ await store.toolMemory.update(id, () => row);
2375
+ if (next.skillPath) try {
2376
+ const { writeFileSync } = await import("node:fs");
2377
+ const text = readFileSync(next.skillPath, "utf8").replace(/disable-model-invocation: (true|false)/, "disable-model-invocation: " + String(!enabled));
2378
+ writeFileSync(next.skillPath, text, "utf8");
2379
+ } catch {}
2380
+ if (enabled) await registerIfExecutable(ctx, store, entry, entry.row.workspaceKey);
2381
+ else disposeCapabilityTool(capabilityToolName(entry.record.name));
2382
+ return {
2383
+ status: "ok",
2384
+ message: (enabled ? "已启用 " : "已停用 ") + entry.record.name + "(知识面与执行面已同步)。",
2385
+ name: entry.record.name
2386
+ };
2387
+ }
2388
+ /** Human gate for an auto-drafted entry: draft becomes the verified entry. */
2389
+ async function enableCapabilityEntryDraft(ctx, store, id) {
2390
+ const entry = readCapabilityRow(store.toolMemory.get(id), id);
2391
+ if (!entry) return {
2392
+ status: "error",
2393
+ message: "能力不存在。"
2394
+ };
2395
+ if (!entry.record.entryDraft) return {
2396
+ status: "error",
2397
+ message: "该能力没有待启用的入口草稿。"
2398
+ };
2399
+ const row = rowOfRecord({
2400
+ ...entry.record,
2401
+ kind: "capability",
2402
+ entry: entry.record.entryDraft,
2403
+ entryDraft: "",
2404
+ entryVerified: true,
2405
+ runnable: true,
2406
+ version: entry.record.version + 1,
2407
+ updatedAt: Date.now(),
2408
+ changelog: ["人工启用执行:入口草稿已确认为入口命令(entryVerified=true)", ...entry.record.changelog].slice(0, CHANGELOG_MAX)
2409
+ }, entry.row.workspaceKey, entry.row.createdAt);
2410
+ await store.toolMemory.update(id, () => row);
2411
+ let updated = readCapabilityRow(store.toolMemory.get(id), id);
2412
+ updated = await ensureSkillFor(store, updated, entry.row.workspaceKey, { changelog: "人工启用执行(入口草稿已验证)" });
2413
+ await registerIfExecutable(ctx, store, updated, entry.row.workspaceKey);
2414
+ return {
2415
+ status: "ok",
2416
+ message: "已启用执行:" + updated.record.name + " → " + updated.record.entry + "。",
2417
+ name: updated.record.name
2418
+ };
2419
+ }
2420
+ /** Edit one capability definition (panel / memory_toolize). */
2421
+ async function editCapability(ctx, store, id, patch) {
2422
+ const entry = readCapabilityRow(store.toolMemory.get(id), id);
2423
+ if (!entry) return {
2424
+ status: "error",
2425
+ message: "能力不存在。"
2426
+ };
2427
+ const record = { ...entry.record };
2428
+ if (patch.title !== void 0) record.title = String(patch.title).slice(0, 80);
2429
+ if (patch.tags !== void 0) record.tags = patch.tags.map((tag) => String(tag)).slice(0, 8);
2430
+ if (patch.description !== void 0) record.description = String(patch.description).slice(0, 500);
2431
+ if (patch.entry !== void 0) {
2432
+ record.entry = String(patch.entry).slice(0, 300);
2433
+ if (record.entry) {
2434
+ record.entryVerified = true;
2435
+ record.kind = "capability";
2436
+ }
2437
+ record.runnable = Boolean(record.entry);
2438
+ }
2439
+ if (patch.doc !== void 0) record.doc = String(patch.doc).slice(0, 300);
2440
+ if (patch.scope !== void 0) record.scope = String(patch.scope).slice(0, 300);
2441
+ if (patch.runnable !== void 0) record.runnable = Boolean(patch.runnable) && Boolean(record.entry);
2442
+ if (patch.dryRunArg !== void 0) record.dryRunArg = String(patch.dryRunArg).slice(0, 80);
2443
+ if (patch.writeConfirm !== void 0) record.writeConfirm = Boolean(patch.writeConfirm);
2444
+ if (patch.routeNote !== void 0) record.routeNote = String(patch.routeNote).slice(0, 500);
2445
+ if (patch.status !== void 0 && patch.status !== "active" && patch.status !== "retired") return {
2446
+ status: "error",
2447
+ message: "status 仅支持 active / retired。"
2448
+ };
2449
+ if (patch.enabled !== void 0) record.enabled = Boolean(patch.enabled);
2450
+ if (patch.status !== void 0) record.enabled = patch.status === "active";
2451
+ record.version = record.version + 1;
2452
+ record.updatedAt = Date.now();
2453
+ record.changelog = [String(patch.changelog ?? "").trim().slice(0, 200) || "更新能力定义", ...record.changelog].slice(0, CHANGELOG_MAX);
2454
+ const row = rowOfRecord(record, entry.row.workspaceKey, entry.row.createdAt);
2455
+ await store.toolMemory.update(id, () => row);
2456
+ let updated = readCapabilityRow(store.toolMemory.get(id), id);
2457
+ updated = await ensureSkillFor(store, updated, entry.row.workspaceKey, {
2458
+ ...patch.changelog ? { changelog: patch.changelog } : {},
2459
+ ...patch.body ? { draftBody: patch.body } : {}
2460
+ });
2461
+ if (updated.record.enabled === false || !isExecutable(updated.record)) disposeCapabilityTool(capabilityToolName(updated.record.name));
2462
+ else await registerIfExecutable(ctx, store, updated, entry.row.workspaceKey);
2463
+ return {
2464
+ status: "ok",
2465
+ message: "已更新能力 " + updated.record.name + "(v" + updated.record.version + ")。",
2466
+ id
2467
+ };
2468
+ }
2469
+ /** Edit the human prose of one capability's knowledge face (facts block preserved). */
2470
+ async function updateCapabilitySkillBody(store, id, body) {
2471
+ const entry = readCapabilityRow(store.toolMemory.get(id), id);
2472
+ if (!entry) return {
2473
+ status: "error",
2474
+ message: "能力不存在。"
2475
+ };
2476
+ if (!entry.record.skillPath) return {
2477
+ status: "error",
2478
+ message: "该能力还没有知识面文件。"
2479
+ };
2480
+ try {
2481
+ const { writeFileSync } = await import("node:fs");
2482
+ const text = readFileSync(entry.record.skillPath, "utf8");
2483
+ const parsed = parseSkillMarkdown(text, capabilitySkillName(entry.record.name));
2484
+ if (!parsed) return {
2485
+ status: "error",
2486
+ message: "知识面文件解析失败,未修改。"
2487
+ };
2488
+ const endOfFrontmatter = text.indexOf(parsed.body);
2489
+ const frontmatter = endOfFrontmatter >= 0 ? text.slice(0, endOfFrontmatter) : "";
2490
+ const split = splitFactsBlock(parsed.body);
2491
+ const nextBody = (String(body).trim() + (split.hasBlock ? "\n\n" + split.facts : "")).trim();
2492
+ writeFileSync(entry.record.skillPath, frontmatter + nextBody + "\n", "utf8");
2493
+ await saveCapabilityRecord(store, {
2494
+ ...entry.record,
2495
+ bodyHash: bodyHashOf(nextBody),
2496
+ version: entry.record.version + 1,
2497
+ updatedAt: Date.now(),
2498
+ changelog: ["人工编辑知识面正文(事实块保留)", ...entry.record.changelog].slice(0, CHANGELOG_MAX)
2499
+ }, {
2500
+ id,
2501
+ workspaceKey: entry.row.workspaceKey,
2502
+ createdAt: entry.row.createdAt
2503
+ });
2504
+ return {
2505
+ status: "ok",
2506
+ message: "正文已保存(事实块保留)。"
2507
+ };
2508
+ } catch (error) {
2509
+ return {
2510
+ status: "error",
2511
+ message: "保存正文失败:" + String(error).slice(0, 160)
2512
+ };
2513
+ }
2514
+ }
2515
+ /** Delete one capability: archive its knowledge file (never hard-delete), unregister, drop row. */
2516
+ async function deleteCapability(ctx, store, id) {
2517
+ const entry = readCapabilityRow(store.toolMemory.get(id), id);
2518
+ if (!entry) return {
2519
+ status: "error",
2520
+ message: "能力不存在。"
2521
+ };
2522
+ disposeCapabilityTool(capabilityToolName(entry.record.name));
2523
+ let archivePath;
2524
+ if (entry.record.skillPath) {
2525
+ if (/\.md$/i.test(entry.record.skillPath)) archivePath = (await archiveCapabilityDoc(dirname(entry.record.skillPath), entry.record.name, { reason: "能力删除:知识面归档" }))?.archivePath;
2526
+ else {
2527
+ const root = dirname(dirname(entry.record.skillPath));
2528
+ archivePath = (await archiveCapabilitySkill(root, capabilitySkillName(entry.record.name), { reason: "能力删除:知识面归档" }))?.archivePath;
2529
+ }
2530
+ }
2531
+ await store.toolMemory.delete(id);
2532
+ return {
2533
+ status: "ok",
2534
+ message: "已删除能力 " + entry.record.name + (archivePath ? "(知识面已归档到 " + archivePath + ",可回滚)" : "") + "。",
2535
+ ...archivePath ? { archivePath } : {}
2536
+ };
2537
+ }
2538
+ async function mergeBuiltinCapabilities(store, options = {}) {
2539
+ const report = {
2540
+ seeded: [],
2541
+ upgraded: [],
2542
+ current: [],
2543
+ localNewer: [],
2544
+ changed: []
2545
+ };
2546
+ for (const builtin of BUILTIN_CAPABILITIES) {
2547
+ const target = capabilityLogicalName(builtin.name);
2548
+ const existing = capabilityRows(store).find((entry) => entry.record.name === target);
2549
+ if (!existing) {
2550
+ const { changelog: builtinChangelog, ...builtinBase } = builtin;
2551
+ const built = buildCapabilityRecord({
2552
+ ...builtinBase,
2553
+ source: "builtin",
2554
+ ...builtinChangelog?.[0] ? { changelog: builtinChangelog[0] } : {}
2555
+ });
2556
+ if (built.status === "error") continue;
2557
+ built.record.version = builtin.version;
2558
+ built.record.changelog = [...builtin.changelog ?? []];
2559
+ built.record.builtin = true;
2560
+ built.record.builtinVersion = builtin.version;
2561
+ built.record.entryVerified = true;
2562
+ built.record.source = "builtin";
2563
+ const id = await saveCapabilityRecord(store, built.record, { workspaceKey: builtin.scope ? workspaceKeyOf(builtin.scope) : void 0 });
2564
+ const entry = readCapabilityRow(store.toolMemory.get(id), id);
2565
+ const synced = await ensureSkillFor(store, entry, entry.row.workspaceKey, { changelog: "内置能力播种:生成知识面" });
2566
+ report.seeded.push(synced.record.name);
2567
+ report.changed.push(synced);
2568
+ continue;
2569
+ }
2570
+ const builtinSeen = existing.record.builtinVersion;
2571
+ if (!(existing.record.version < builtin.version || builtinSeen !== void 0 && builtinSeen < builtin.version)) {
2572
+ if (builtinSeen === void 0 && existing.record.version > builtin.version) report.localNewer.push(existing.record.name);
2573
+ else report.current.push(existing.record.name);
2574
+ continue;
2575
+ }
2576
+ const { changelog: upgradeChangelog, ...upgradeBase } = builtin;
2577
+ const built = buildCapabilityRecord({
2578
+ ...upgradeBase,
2579
+ source: "builtin",
2580
+ ...upgradeChangelog?.[0] ? { changelog: upgradeChangelog[0] } : {}
2581
+ });
2582
+ if (built.status === "error") continue;
2583
+ const next = {
2584
+ ...existing.record,
2585
+ ...built.record,
2586
+ loadCount: existing.record.loadCount,
2587
+ runCount: existing.record.runCount,
2588
+ successCount: existing.record.successCount,
2589
+ failCount: existing.record.failCount,
2590
+ consecutiveFailures: existing.record.consecutiveFailures,
2591
+ ...existing.record.lastUsedAt !== void 0 ? { lastUsedAt: existing.record.lastUsedAt } : {},
2592
+ ...existing.record.lastStatus ? { lastStatus: existing.record.lastStatus } : {},
2593
+ version: Math.max(existing.record.version, builtin.version),
2594
+ updatedAt: Date.now(),
2595
+ changelog: [...builtin.changelog ?? [], ...existing.record.changelog].slice(0, CHANGELOG_MAX),
2596
+ builtin: true,
2597
+ builtinVersion: builtin.version,
2598
+ entryVerified: true
2599
+ };
2600
+ const previousScopeKey = existing.record.scope ? workspaceKeyOf(existing.record.scope) : void 0;
2601
+ const nextScopeKey = next.scope ? workspaceKeyOf(next.scope) : void 0;
2602
+ const workspaceKey = Boolean(existing.row.workspaceKey && previousScopeKey && existing.row.workspaceKey === previousScopeKey) && nextScopeKey ? nextScopeKey : existing.row.workspaceKey;
2603
+ await saveCapabilityRecord(store, next, {
2604
+ id: existing.id,
2605
+ workspaceKey,
2606
+ createdAt: existing.row.createdAt
2607
+ });
2608
+ const synced = await ensureSkillFor(store, readCapabilityRow(store.toolMemory.get(existing.id), existing.id), workspaceKey, { changelog: "内置能力升级:刷新知识面事实块" });
2609
+ report.upgraded.push(synced.record.name);
2610
+ report.changed.push(synced);
2611
+ }
2612
+ return report;
2613
+ }
2614
+ /** Boot/refresh rebuild: migrate, merge builtins, register every executable face. */
2615
+ async function rebuildCapabilities(ctx, store, deps) {
2616
+ try {
2617
+ const migration = await migrateCapabilities(store, { ...deps?.logger ? { logger: deps.logger } : {} });
2618
+ if (migration.changed) deps?.logger?.info("supermemory: capability migration — caps " + migration.migratedCapabilities + ", knowledge " + migration.migratedKnowledge + ", retired sequences " + migration.retiredComposites + ", linked skills " + migration.linkedSkills + ", archived shells " + migration.archivedShells + ", retired shell units " + migration.retiredShellUnits + ", deduped knowledge " + migration.dedupedKnowledge);
2619
+ } catch (error) {
2620
+ deps?.logger?.warn?.("supermemory: capability migration failed: " + String(error).slice(0, 160));
2621
+ }
2622
+ try {
2623
+ const merged = await mergeBuiltinCapabilities(store, { ...deps?.logger ? { logger: deps.logger } : {} });
2624
+ if (merged.seeded.length > 0 || merged.upgraded.length > 0) deps?.logger?.info("supermemory: builtin capabilities — seeded " + merged.seeded.join(",") + "; upgraded " + merged.upgraded.join(","));
2625
+ } catch {}
2626
+ const seam = deps?.register ?? registerCapabilityTool;
2627
+ let registered = 0;
2628
+ for (const entry of capabilityRows(store)) {
2629
+ if (!isExecutable(entry.record)) {
2630
+ disposeCapabilityTool(capabilityToolName(entry.record.name));
2631
+ continue;
2632
+ }
2633
+ try {
2634
+ await seam(ctx, store, entry, entry.row.workspaceKey);
2635
+ registered += 1;
2636
+ } catch {}
2637
+ }
2638
+ return registered;
2639
+ }
2640
+ function capabilityHealthOf(store, workspaceKey) {
2641
+ const out = [];
2642
+ for (const entry of capabilityRows(store, workspaceKey)) {
2643
+ if (entry.record.kind === "proposal") continue;
2644
+ const health = reconcileCapabilityHealth(entry.record);
2645
+ const record = health.record;
2646
+ if (record.kind === "proposal") continue;
2647
+ const builtin = BUILTIN_CAPABILITIES.find((candidate) => capabilityLogicalName(candidate.name) === record.name);
2648
+ const scopeMissing = Boolean(record.scope && !existsSync(record.scope));
2649
+ const docMissing = Boolean(record.doc && record.scope && !scopeMissing && !existsSync(join(record.scope, record.doc)));
2650
+ const notes = [];
2651
+ if (record.consecutiveFailures >= 2) notes.push("连续失败 " + record.consecutiveFailures + " 次:更新能力定义/事实块/文档(version+1、changelog 记录原因),不要绕过");
2652
+ if (record.runCount > 0 && record.successCount === 0 && record.failCount > 0) notes.push("从未成功执行过:入口命令或适用范围需要修订");
2653
+ if (scopeMissing) notes.push("适用范围目录不存在:" + record.scope);
2654
+ if (docMissing) notes.push("文档缺失:" + record.doc);
2655
+ if (record.runCount === 0 && record.loadCount === 0) notes.push("零使用/零加载:确认路由描述是否说清何时用它");
2656
+ if (record.loadCount > 0 && record.runCount === 0) notes.push("有加载无执行:检查知识面是否说清执行面入口");
2657
+ if (record.kind === "capability" && !liveCapabilityToolNames.has(capabilityToolName(record.name))) notes.push("执行面未注册(重启或 refresh-builtin 后生效)");
2658
+ if (record.entryDraft && !record.entryVerified) notes.push("入口草稿未验证:人工在面板点「启用执行」后才会 runnable=true");
2659
+ if (health.changed) notes.push("历史统计已校正(R54:runCount=success+fail,lastStatus 与最近结果一致)");
2660
+ const builtinSeen = record.builtinVersion;
2661
+ if (builtin && (builtinSeen !== void 0 ? builtinSeen < builtin.version : record.version < builtin.version)) notes.push("现场版本旧于内置 v" + builtin.version + ":memory_toolize refresh-builtin 可升级");
2662
+ if (builtin && builtinSeen === void 0 && record.version > builtin.version) notes.push("现场版本新于内置 v" + builtin.version + "(本地维护中)");
2663
+ const successRate = record.runCount > 0 ? record.successCount / record.runCount : 0;
2664
+ const loadsToRuns = record.loadCount > 0 ? record.runCount / record.loadCount : 0;
2665
+ out.push({
2666
+ id: entry.id,
2667
+ name: record.name,
2668
+ ...record.title ? { title: record.title } : {},
2669
+ kind: record.kind,
2670
+ entry: record.entry,
2671
+ ...record.entryDraft ? { entryDraft: record.entryDraft } : {},
2672
+ entryVerified: record.entryVerified,
2673
+ ...record.doc ? { doc: record.doc } : {},
2674
+ ...record.scope ? { scope: record.scope } : {},
2675
+ status: entry.row.status,
2676
+ enabled: record.enabled !== false,
2677
+ live: liveCapabilityToolNames.has(capabilityToolName(record.name)),
2678
+ builtin: Boolean(builtin),
2679
+ ...builtin ? { builtinVersion: builtin.version } : {},
2680
+ version: record.version,
2681
+ loadCount: record.loadCount,
2682
+ runCount: record.runCount,
2683
+ loadsToRuns,
2684
+ successRate,
2685
+ successCount: record.successCount,
2686
+ failCount: record.failCount,
2687
+ consecutiveFailures: record.consecutiveFailures,
2688
+ ...record.lastUsedAt !== void 0 ? { lastUsedAt: record.lastUsedAt } : {},
2689
+ ...record.lastStatus ? { lastStatus: record.lastStatus } : {},
2690
+ ...record.lastDryRun !== void 0 ? { lastDryRun: record.lastDryRun } : {},
2691
+ ...record.lastSummary ? { lastSummary: record.lastSummary } : {},
2692
+ ...record.skillPath ? { skillPath: record.skillPath } : {},
2693
+ ...record.bodyHash ? { bodyHash: record.bodyHash } : {},
2694
+ ...record.factsHash ? { factsHash: record.factsHash } : {},
2695
+ docMissing,
2696
+ scopeMissing,
2697
+ notes
2698
+ });
2699
+ }
2700
+ return out;
2701
+ }
2702
+ function pendingProposalsOf(store, workspaceKey) {
2703
+ return capabilityRows(store).filter((entry) => entry.record.kind === "proposal" && entry.record.proposalStatus === "pending" && (!workspaceKey || !entry.row.workspaceKey || entry.row.workspaceKey === workspaceKey));
2704
+ }
2705
+ /** Create/update one pending proposal. Pending proposals never consume the 8-skill cap. */
2706
+ async function createProposal(store, input) {
2707
+ const now = input.now ?? Date.now();
2708
+ const logical = capabilityLogicalName(input.name);
2709
+ if (!isValidCapabilityName(logical)) return {
2710
+ status: "rejected",
2711
+ name: logical,
2712
+ message: "提案名称不合法:" + logical
2713
+ };
2714
+ const existing = capabilityRows(store).find((entry) => entry.record.kind === "proposal" && entry.record.name === logical && (entry.row.workspaceKey ?? "") === (input.workspaceKey ?? ""));
2715
+ const record = normalizeCapabilityRecord({
2716
+ schema: CAPABILITY_SCHEMA,
2717
+ name: logical,
2718
+ kind: "proposal",
2719
+ title: input.title,
2720
+ description: input.description,
2721
+ entry: "",
2722
+ entryDraft: input.entryDraft ?? "",
2723
+ entryVerified: false,
2724
+ runnable: false,
2725
+ scope: input.scope ?? "",
2726
+ source: input.source ?? "auto",
2727
+ taskKey: input.taskKey ?? "",
2728
+ version: 1,
2729
+ updatedAt: now,
2730
+ changelog: ["自动知识草稿(待接受)"],
2731
+ draftBody: input.body,
2732
+ facts: input.facts ?? {},
2733
+ proposalStatus: "pending",
2734
+ expiresAt: now + PROPOSAL_TTL_MS
2735
+ });
2736
+ record.kind = "proposal";
2737
+ if (existing) {
2738
+ await saveCapabilityRecord(store, {
2739
+ ...record,
2740
+ version: existing.record.version,
2741
+ changelog: existing.record.changelog
2742
+ }, {
2743
+ id: existing.id,
2744
+ workspaceKey: input.workspaceKey,
2745
+ createdAt: existing.row.createdAt
2746
+ });
2747
+ return {
2748
+ status: "updated",
2749
+ id: existing.id,
2750
+ name: logical,
2751
+ message: "已刷新待接受的知识草稿。"
2752
+ };
2753
+ }
2754
+ if (pendingProposalsOf(store, input.workspaceKey).length >= PROPOSAL_MAX) return {
2755
+ status: "rejected",
2756
+ name: logical,
2757
+ message: "待处理提案已达上限 20 条:先接受/拒绝或清空。"
2758
+ };
2759
+ return {
2760
+ status: "created",
2761
+ id: await saveCapabilityRecord(store, record, { workspaceKey: input.workspaceKey }),
2762
+ name: logical,
2763
+ message: "已写入待接受提案(知识草稿,无执行面)。"
2764
+ };
2765
+ }
2766
+ /** Accept a pending proposal -> a real capability (knowledge only, or entryDraft pending verification). */
2767
+ async function acceptProposal(ctx, store, id, options = {}) {
2768
+ const proposal = readCapabilityRow(store.toolMemory.get(id), id);
2769
+ if (!proposal || proposal.record.kind !== "proposal") return {
2770
+ status: "error",
2771
+ message: "提案不存在。"
2772
+ };
2773
+ if (proposal.record.proposalStatus !== "pending") return {
2774
+ status: "error",
2775
+ message: "提案已处理(不是待接受状态)。"
2776
+ };
2777
+ const workspaceKey = proposal.row.workspaceKey ?? "unknown";
2778
+ let root = options.root;
2779
+ if (!root && workspaceKey !== "unknown") try {
2780
+ root = resolveCapabilityRoot(workspaceKey).root;
2781
+ } catch {
2782
+ root = void 0;
2783
+ }
2784
+ if (root) {
2785
+ if (capabilityRows(store).filter((entry) => entry.record.source === "auto" && entry.record.kind !== "proposal" && Boolean(entry.record.skillPath) && resolve(entry.record.skillPath).toLowerCase().startsWith(resolve(root).toLowerCase())).length >= 8) return {
2786
+ status: "error",
2787
+ message: "该 skills 根自动生成上限 8 个已满:先停用/删除一个再接受。"
2788
+ };
2789
+ }
2790
+ const now = options.now ?? Date.now();
2791
+ const record = proposal.record;
2792
+ const kind = record.entryDraft ? "capability" : "knowledge";
2793
+ const capId = await saveCapabilityRecord(store, {
2794
+ ...record,
2795
+ kind,
2796
+ version: 1,
2797
+ updatedAt: now,
2798
+ changelog: ["接受自动提案(" + (record.entryDraft ? "入口草稿待人工验证" : "仅知识") + ")", ...record.changelog].slice(0, CHANGELOG_MAX),
2799
+ proposalStatus: "accepted",
2800
+ entry: "",
2801
+ entryVerified: false,
2802
+ runnable: false,
2803
+ enabled: true,
2804
+ source: record.source === "manual" ? "manual" : "auto"
2805
+ }, { workspaceKey });
2806
+ const entry = readCapabilityRow(store.toolMemory.get(capId), capId);
2807
+ let synced = entry;
2808
+ if (root) {
2809
+ try {
2810
+ await syncCapabilitySkill(store, entry, root, {
2811
+ draftBody: record.draftBody,
2812
+ now,
2813
+ changelog: "接受自动提案:生成知识面"
2814
+ });
2815
+ } catch {}
2816
+ synced = readCapabilityRow(store.toolMemory.get(capId), capId);
2817
+ }
2818
+ await saveCapabilityRecord(store, {
2819
+ ...record,
2820
+ proposalStatus: "accepted",
2821
+ acceptedId: capId
2822
+ }, {
2823
+ id,
2824
+ workspaceKey,
2825
+ createdAt: proposal.row.createdAt
2826
+ });
2827
+ return {
2828
+ status: "ok",
2829
+ message: "已接受提案:创建" + (kind === "capability" ? "可执行能力(入口草稿待人工「启用执行」)" : "仅知识能力") + " " + synced.record.name + "。",
2830
+ id: capId,
2831
+ name: synced.record.name,
2832
+ entryDraft: kind === "capability"
2833
+ };
2834
+ }
2835
+ async function declineProposal(store, id) {
2836
+ const proposal = readCapabilityRow(store.toolMemory.get(id), id);
2837
+ if (!proposal || proposal.record.kind !== "proposal") return {
2838
+ status: "error",
2839
+ message: "提案不存在。"
2840
+ };
2841
+ const record = {
2842
+ ...proposal.record,
2843
+ proposalStatus: "declined",
2844
+ updatedAt: Date.now()
2845
+ };
2846
+ await saveCapabilityRecord(store, record, {
2847
+ id,
2848
+ workspaceKey: proposal.row.workspaceKey,
2849
+ createdAt: proposal.row.createdAt
2850
+ });
2851
+ return {
2852
+ status: "ok",
2853
+ message: "已拒绝提案 " + record.name + "。"
2854
+ };
2855
+ }
2856
+ /** Expire stale pending proposals (30 days). Idempotent. */
2857
+ async function expireProposals(store, now = Date.now()) {
2858
+ let expired = 0;
2859
+ for (const entry of capabilityRows(store)) {
2860
+ if (entry.record.kind !== "proposal" || entry.record.proposalStatus !== "pending") continue;
2861
+ if (entry.record.expiresAt !== void 0 && entry.record.expiresAt >= now) continue;
2862
+ await saveCapabilityRecord(store, {
2863
+ ...entry.record,
2864
+ proposalStatus: "declined",
2865
+ updatedAt: now,
2866
+ changelog: ["提案超 30 天未处理:自动过期", ...entry.record.changelog].slice(0, CHANGELOG_MAX)
2867
+ }, {
2868
+ id: entry.id,
2869
+ workspaceKey: entry.row.workspaceKey,
2870
+ createdAt: entry.row.createdAt
2871
+ });
2872
+ expired += 1;
2873
+ }
2874
+ return expired;
2875
+ }
2876
+ /** Collapse whitespace and strip the dry-run suffix so samples group together. */
2877
+ function normalizeCommand(command) {
2878
+ let value = String(command ?? "").replace(/\s+/g, " ").trim();
2879
+ let dryRunArg;
2880
+ const match = /\s(--dry-run|--preview|-n)$/.exec(value);
2881
+ if (match) {
2882
+ dryRunArg = match[1];
2883
+ value = value.slice(0, match.index).trim();
2884
+ }
2885
+ value = value.replace(/^pnpm\s+run\s+/, "pnpm ").replace(/^npm\s+run\s+/, "npm run ");
2886
+ return {
2887
+ command: value,
2888
+ ...dryRunArg ? { dryRunArg } : {}
2889
+ };
2890
+ }
2891
+ function isInteractive(command) {
2892
+ if (/(^|\s)-[a-z]*i[a-z]*(\s|$)/.test(command)) return true;
2893
+ if (/\b(vim?|nvim|nano|notepad|code|emacs)\b/.test(command)) return true;
2894
+ if (/(^|\s)(read|select|pause)(\s|$)/.test(command)) return true;
2895
+ if (/set\s+\/p/i.test(command)) return true;
2896
+ if (/[<>]/.test(command)) return true;
2897
+ return false;
2898
+ }
2899
+ function hasPlaceholderOrTemp(command) {
2900
+ if (/[{}]/.test(command)) return true;
2901
+ if (/\$\{/.test(command)) return true;
2902
+ if (/(^|[\s/"'])(\/tmp|%temp%|\$tmp|c:\\users\\[^\\]+\\appdata\\local\\temp)/i.test(command)) return true;
2903
+ if (/\.tmp\b|\.temp\b|mkdtemp/i.test(command)) return true;
2904
+ return false;
2905
+ }
2906
+ function allowedCommandFamily(command, scriptNames) {
2907
+ if (/^pnpm\s+git:sync(\s|$)/.test(command)) return true;
2908
+ const script = /^(?:pnpm|npm)(?:\s+run)?\s+([a-zA-Z0-9:_.-]+)(?:\s|$)/.exec(command);
2909
+ if (script) return scriptNames.includes(script[1]);
2910
+ if (/^(?:node\s+)?(?:\.\/)?scripts\/[A-Za-z0-9._-]+\.(?:mjs|cjs|js|sh)(?:\s|$)/.test(command)) return true;
2911
+ if (/^bash\s+(?:\.\/)?scripts\/[A-Za-z0-9._-]+\.sh(?:\s|$)/.test(command)) return true;
2912
+ return false;
2913
+ }
2914
+ function readScriptNames(scope) {
2915
+ if (!scope) return [];
2916
+ try {
2917
+ const pkg = JSON.parse(readFileSync(join(scope, "package.json"), "utf8"));
2918
+ return Object.keys(pkg.scripts ?? {});
2919
+ } catch {
2920
+ return [];
2921
+ }
2922
+ }
2923
+ /**
2924
+ * Decide whether the samples justify one auto-drafted entry command. Pure over
2925
+ * the recorded samples plus an optional scope/workspace root (filesystem read of
2926
+ * package.json only to validate the script family).
2927
+ */
2928
+ function highConfidenceEntryDraft(samples, options = {}) {
2929
+ const scope = options.scope ? resolve(options.scope) : void 0;
2930
+ if (scope && options.workspaceRoot && resolve(options.workspaceRoot).toLowerCase() !== scope.toLowerCase()) return {
2931
+ status: "none",
2932
+ reason: "scope 不是仓库根(" + scope + " ≠ " + resolve(options.workspaceRoot) + ")"
2933
+ };
2934
+ const scriptNames = options.scriptNames ?? readScriptNames(scope);
2935
+ const stats = /* @__PURE__ */ new Map();
2936
+ for (const [index, sample] of samples.entries()) {
2937
+ if (sample.ok !== true) continue;
2938
+ const session = sample.sessionId ?? "sample-" + index;
2939
+ for (const arg of sample.args) {
2940
+ const raw = typeof arg.command === "string" ? arg.command : "";
2941
+ if (!raw) continue;
2942
+ const normalized = normalizeCommand(raw);
2943
+ const bucket = stats.get(normalized.command) ?? {
2944
+ samples: 0,
2945
+ sessions: /* @__PURE__ */ new Set(),
2946
+ ...normalized.dryRunArg ? { dryRunArg: normalized.dryRunArg } : {}
2947
+ };
2948
+ bucket.samples += 1;
2949
+ bucket.sessions.add(session);
2950
+ if (normalized.dryRunArg && !bucket.dryRunArg) bucket.dryRunArg = normalized.dryRunArg;
2951
+ stats.set(normalized.command, bucket);
2952
+ }
2953
+ }
2954
+ const candidates = [...stats.entries()].filter(([command, bucket]) => bucket.samples >= 3 && bucket.sessions.size >= 2 && allowedCommandFamily(command, scriptNames) && !isInteractive(command) && !hasPlaceholderOrTemp(command)).sort((left, right) => right[1].samples - left[1].samples);
2955
+ if (candidates.length === 0) return {
2956
+ status: "none",
2957
+ reason: "没有满足高置信条件的命令(≥3 样本、≥2 会话、全部 exit 0、非交互、允许的命令家族、无占位符/临时路径)"
2958
+ };
2959
+ const [command, bucket] = candidates[0];
2960
+ const readOnly = /(?:^|\s)(typecheck|smoke|test|lint|check|status|log|diff|verify)(?:\s|$)/.test(command);
2961
+ return {
2962
+ status: "ok",
2963
+ reason: "高置信候选:" + bucket.samples + " 个样本、" + bucket.sessions.size + " 个会话、全部 exit 0;命令家族在允许列表",
2964
+ entry: command,
2965
+ ...bucket.dryRunArg ? { dryRunArg: bucket.dryRunArg } : {},
2966
+ writeConfirm: !readOnly,
2967
+ samples: bucket.samples,
2968
+ sessions: bucket.sessions.size
2969
+ };
2970
+ }
2971
+ export { attachRoute as A, runCapability as C, updateCapabilitySkillBody as D, syncCapabilitySkill as E, backfillHubRecords as F, recordHubSession as I, resolveRole as L, fillTopicShapeOnCreate as M, noteTopicSetActivated as N, PLUGIN_REPO_ROOT as O, agentWorkspaceKey as P, injectionSource as R, retireShellUnits as S, setCapabilityEnabled as T, isShellUnit as _, capabilityHealthOf as a, registerCapability as b, capabilityToolName as c, declineProposal as d, deleteCapability as f, highConfidenceEntryDraft as g, expireProposals as h, capabilityBodyOf as i, renderCard as j, CAPABILITY_ROUTING_RULES as k, capability_exports as l, enableCapabilityEntryDraft as m, bumpCapabilityRun as n, capabilityRows as o, editCapability as p, capabilityAppliesToWorkspace as r, capabilitySkillName as s, acceptProposal as t, createProposal as u, liveCapabilityToolNames as v, saveCapabilityRecord as w, renderCapabilityIndex as x, readCapabilityRow as y };