@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,426 @@
1
+ import { E as syncCapabilitySkill, S as retireShellUnits, T as setCapabilityEnabled, g as highConfidenceEntryDraft, h as expireProposals, o as capabilityRows, s as capabilitySkillName, u as createProposal, w as saveCapabilityRecord } from "./capability-T5x_17iK.js";
2
+ import { _ as resolveSkillRoot, h as recordTaskObservation, i as archiveShellSkills, l as draftSkillFromTaskSignal, p as parseTaskSamples, u as extractWorkflowFacts, v as signalSessionCount, x as taskSignalKey } from "./skill-forge-DHxPo_w6.js";
3
+ // src/toolize.ts
4
+ const GENERIC_TOOL_NAMES = /* @__PURE__ */ new Set([
5
+ "run_code",
6
+ "bash",
7
+ "read",
8
+ "edit",
9
+ "write",
10
+ "glob",
11
+ "grep",
12
+ "todo_write",
13
+ "present",
14
+ "skill",
15
+ "read_image",
16
+ "working_directory",
17
+ "wait_agent",
18
+ "send_message",
19
+ "list_agents",
20
+ "subagent",
21
+ "subagent_fork",
22
+ "ask_user_question",
23
+ "web_search",
24
+ "web_fetch",
25
+ "schedule_create",
26
+ "schedule_edit",
27
+ "schedule_list",
28
+ "schedule_view",
29
+ "job_list",
30
+ "job_output",
31
+ "job_kill",
32
+ "list_mcp_resources",
33
+ "list_mcp_resource_templates",
34
+ "read_mcp_resource"
35
+ ]);
36
+ const GENERIC_TOOL_PREFIXES = [
37
+ "memory_",
38
+ "sm_cap_",
39
+ "job_",
40
+ "schedule_",
41
+ "session_",
42
+ "cordis_",
43
+ "plugin_"
44
+ ];
45
+ function isGenericToolName(name) {
46
+ const tool = String(name ?? "").trim();
47
+ if (!tool) return true;
48
+ if (GENERIC_TOOL_NAMES.has(tool)) return true;
49
+ return GENERIC_TOOL_PREFIXES.some((prefix) => tool.startsWith(prefix));
50
+ }
51
+ function proposalVerdict(tools) {
52
+ const steps = tools.map((tool) => String(tool ?? "").trim()).filter(Boolean);
53
+ if (steps.length < 2) return {
54
+ valuable: false,
55
+ reason: "步数不足(至少 2 步)"
56
+ };
57
+ if (new Set(steps).size < 2) return {
58
+ valuable: false,
59
+ reason: "同一工具重复不构成流程"
60
+ };
61
+ const generic = steps.find((tool) => isGenericToolName(tool));
62
+ if (generic) return {
63
+ valuable: false,
64
+ reason: "宽泛工具序列:" + generic + " 是通用工具,没有业务对象/命令/文件/入口"
65
+ };
66
+ return {
67
+ valuable: true,
68
+ reason: "ok"
69
+ };
70
+ }
71
+ function dispatchOf(store, sessionId) {
72
+ if (!sessionId) return void 0;
73
+ const table = store.dispatches;
74
+ if (!table || typeof table.entries !== "function") return void 0;
75
+ try {
76
+ for (const [id, row] of table.entries()) {
77
+ if (row?.branchSessionId !== sessionId) continue;
78
+ return {
79
+ id,
80
+ task: String(row.task ?? ""),
81
+ ...row.topicSetId ? { topicSetId: row.topicSetId } : {}
82
+ };
83
+ }
84
+ } catch {}
85
+ }
86
+ function factsOf(samples) {
87
+ const facts = extractWorkflowFacts(samples);
88
+ const verify = facts.commands.filter((command) => /typecheck|build|smoke|test|lint|check/i.test(command));
89
+ return {
90
+ commands: facts.commands,
91
+ files: facts.files,
92
+ ...verify.length > 0 ? { verify } : {},
93
+ pitfalls: facts.patterns.slice(0, 5)
94
+ };
95
+ }
96
+ /**
97
+ * Write/refresh the pending knowledge proposal for one crossed TASK signature.
98
+ * If a capability with the same taskKey already exists, refresh its facts
99
+ * instead (facts-block merge; human prose is preserved by skill-forge).
100
+ */
101
+ async function proposeTaskCapability(store, workspaceKey, signatureKey, options = { threshold: 3 }) {
102
+ if (!workspaceKey || workspaceKey === "unknown") return {
103
+ status: "skipped",
104
+ message: "没有工作区事实,不生成提案。"
105
+ };
106
+ const signalKey = taskSignalKey(workspaceKey, signatureKey);
107
+ const signal = store.signals.get(signalKey);
108
+ if (!signal) return {
109
+ status: "skipped",
110
+ message: "任务信号不存在。"
111
+ };
112
+ const samples = parseTaskSamples(signal.samples ?? []);
113
+ const sessions = signalSessionCount(signal, samples);
114
+ const draft = draftSkillFromTaskSignal(signal, samples, { sessions });
115
+ if (!draft) return {
116
+ status: "skipped",
117
+ message: "任务样本不足,不生成提案。"
118
+ };
119
+ const now = options.now ?? Date.now();
120
+ const facts = factsOf(samples);
121
+ const existing = capabilityRows(store).find((entry) => entry.record.kind !== "proposal" && entry.record.taskKey === signatureKey && (!entry.row.workspaceKey || entry.row.workspaceKey === workspaceKey));
122
+ if (existing) {
123
+ const next = {
124
+ ...existing.record,
125
+ description: draft.description,
126
+ facts,
127
+ version: existing.record.version + 1,
128
+ updatedAt: now,
129
+ changelog: ["重复任务有新样本:刷新能力事实块(正文散文保留)", ...existing.record.changelog].slice(0, 20)
130
+ };
131
+ await saveCapabilityRecord(store, next, {
132
+ id: existing.id,
133
+ workspaceKey: existing.row.workspaceKey,
134
+ createdAt: existing.row.createdAt
135
+ });
136
+ let root = options.root;
137
+ if (!root) try {
138
+ root = resolveSkillRoot(workspaceKey).root;
139
+ } catch {
140
+ root = void 0;
141
+ }
142
+ if (root) {
143
+ const updated = capabilityRows(store).find((entry) => entry.id === existing.id);
144
+ if (updated) try {
145
+ await syncCapabilitySkill(store, updated, root, {
146
+ now,
147
+ changelog: "重复任务有新样本:刷新事实块"
148
+ });
149
+ } catch {}
150
+ }
151
+ return {
152
+ status: "refreshed",
153
+ name: existing.record.name,
154
+ message: "已有能力,已刷新事实块。"
155
+ };
156
+ }
157
+ const entryDraft = highConfidenceEntryDraft(samples, {
158
+ scope: workspaceKey,
159
+ workspaceRoot: workspaceKey
160
+ });
161
+ const result = await createProposal(store, {
162
+ workspaceKey,
163
+ name: capabilitySkillName(draft.name).replace(/^sm-/, ""),
164
+ title: draft.title,
165
+ description: draft.description,
166
+ body: draft.body,
167
+ facts,
168
+ taskKey: signatureKey,
169
+ ...entryDraft.status === "ok" ? {
170
+ scope: workspaceKey,
171
+ entryDraft: entryDraft.entry,
172
+ dryRunArg: entryDraft.dryRunArg,
173
+ writeConfirm: entryDraft.writeConfirm
174
+ } : {},
175
+ source: "auto",
176
+ now
177
+ });
178
+ return {
179
+ status: result.status === "created" ? "created" : result.status === "updated" ? "updated" : "unchanged",
180
+ ...result.name ? { name: result.name } : {},
181
+ message: result.message
182
+ };
183
+ }
184
+ /**
185
+ * Durable per-turn recording (R50): one TASK observation per turn, no sliding
186
+ * tool-sequence windows, no registration. config.enabled is accepted for
187
+ * compatibility and ignored.
188
+ */
189
+ async function recordTurnSequences(ctx, store, workspaceKey, tools, args, config, logger, _deps, context = {}) {
190
+ if (tools.length < 2) return void 0;
191
+ if (!config.autoSkill) return void 0;
192
+ try {
193
+ const dispatch = dispatchOf(store, context.sessionId);
194
+ const task = [dispatch?.task, context.task].filter((part) => typeof part === "string" && part.trim().length > 0).join("\n").trim();
195
+ if (!task) return void 0;
196
+ const ok = Array.isArray(context.successes) && context.successes.length === tools.length ? context.successes.every(Boolean) : void 0;
197
+ const observation = await recordTaskObservation(store, workspaceKey, {
198
+ tools,
199
+ args,
200
+ task,
201
+ ...context.sessionId ? { sessionId: context.sessionId } : {},
202
+ ...context.dispatchId ?? dispatch?.id ? { dispatchId: context.dispatchId ?? dispatch?.id } : {},
203
+ ...context.topicSetId ?? dispatch?.topicSetId ? { topicSetId: context.topicSetId ?? dispatch?.topicSetId } : {},
204
+ ...context.now !== void 0 ? { at: context.now } : {},
205
+ ...ok !== void 0 ? { ok } : {}
206
+ }, {
207
+ threshold: config.threshold,
208
+ ...config.skillMinSessions !== void 0 ? { minSessions: config.skillMinSessions } : {},
209
+ ...context.now !== void 0 ? { now: context.now } : {}
210
+ });
211
+ if (!observation) return void 0;
212
+ const report = {
213
+ signature: observation.key,
214
+ count: observation.count,
215
+ sessions: observation.sessions,
216
+ crossed: observation.crossed
217
+ };
218
+ if (!observation.crossed) return report;
219
+ const written = await proposeTaskCapability(store, workspaceKey, observation.key, {
220
+ threshold: config.threshold,
221
+ ...config.skillMinSessions !== void 0 ? { minSessions: config.skillMinSessions } : {},
222
+ ...config.skillRecencyDays !== void 0 ? { recencyDays: config.skillRecencyDays } : {},
223
+ ...context.now !== void 0 ? { now: context.now } : {}
224
+ });
225
+ if (written.status !== "unchanged" && written.status !== "skipped") logger.info("supermemory: task proposal " + (written.name ?? observation.key) + " " + written.status);
226
+ return report;
227
+ } catch (error) {
228
+ logger.warn("supermemory: task proposal recording failed: " + String(error).slice(0, 160));
229
+ return;
230
+ }
231
+ }
232
+ /** Boot sweep: durable task signals that already crossed become pending proposals. */
233
+ async function sweepTaskProposals(store, config, logger) {
234
+ if (!config.autoSkill) return 0;
235
+ const threshold = Math.max(1, config.threshold);
236
+ let created = 0;
237
+ for (const [key, signal] of [...store.signals.entries()]) {
238
+ if (!signal.pattern.startsWith("task:")) continue;
239
+ if (signal.count < threshold) continue;
240
+ if ((signal.sessions ?? []).length < Math.max(1, config.skillMinSessions ?? 2)) continue;
241
+ if (!signal.workspaceKey || signal.workspaceKey === "unknown") continue;
242
+ const signatureKey = signal.pattern.slice(5);
243
+ try {
244
+ const result = await proposeTaskCapability(store, signal.workspaceKey, signatureKey, {
245
+ threshold,
246
+ ...config.skillMinSessions !== void 0 ? { minSessions: config.skillMinSessions } : {},
247
+ ...config.skillRecencyDays !== void 0 ? { recencyDays: config.skillRecencyDays } : {}
248
+ });
249
+ if (result.status === "created" || result.status === "updated") created += 1;
250
+ } catch (error) {
251
+ logger.warn("supermemory: task proposal sweep failed for " + key + ": " + String(error).slice(0, 160));
252
+ }
253
+ }
254
+ if (created > 0) logger.info("supermemory: task proposal sweep created " + created + " proposal(s)");
255
+ return created;
256
+ }
257
+ function sequenceOf(signal, key) {
258
+ if (Array.isArray(signal.sequence) && signal.sequence.length > 0) return signal.sequence.map((tool) => String(tool));
259
+ const match = /\/seq\/([^/]+)$/.exec(key);
260
+ return match ? match[1].split(">").filter(Boolean) : [];
261
+ }
262
+ function isSequenceSignal(key) {
263
+ return /\/seq\//.test(key);
264
+ }
265
+ /** Clear legacy tool-sequence signals (idempotent; no tool is created). */
266
+ async function clearSequenceSignals(store, options = {}) {
267
+ const dryRun = Boolean(options.dryRun);
268
+ let pendingBefore = 0;
269
+ for (const [, signal] of store.signals.entries()) if (signal.proposalStatus === "pending") pendingBefore += 1;
270
+ let clearedProposals = 0;
271
+ let prunedSignals = 0;
272
+ for (const [key, signal] of [...store.signals.entries()]) {
273
+ if (!isSequenceSignal(key)) continue;
274
+ const pending = signal.proposalStatus === "pending";
275
+ if (!!proposalVerdict(sequenceOf(signal, key)).valuable && !(pending && options.dropAllPending === true)) continue;
276
+ if (!dryRun) try {
277
+ await store.signals.delete(key);
278
+ } catch {
279
+ continue;
280
+ }
281
+ if (pending) clearedProposals += 1;
282
+ else prunedSignals += 1;
283
+ }
284
+ let pendingAfter = 0;
285
+ for (const [, signal] of store.signals.entries()) if (signal.proposalStatus === "pending") pendingAfter += 1;
286
+ return {
287
+ pendingBefore,
288
+ clearedProposals,
289
+ prunedSignals,
290
+ pendingAfter,
291
+ dryRun
292
+ };
293
+ }
294
+ /** Every ACTIVE legacy sequence row (kind=composite/workflow, no capability entry). */
295
+ function legacySequenceRows(store) {
296
+ const out = [];
297
+ for (const [id, row] of store.toolMemory.entries()) {
298
+ if (row.kind !== "composite" && row.kind !== "workflow") continue;
299
+ if (row.status !== "active") continue;
300
+ let raw;
301
+ try {
302
+ raw = JSON.parse(row.entry);
303
+ } catch {
304
+ continue;
305
+ }
306
+ if (!raw || raw.kind === "capability" || raw.schema === "sm.capability/1") continue;
307
+ const steps = Array.isArray(raw.steps) ? raw.steps.map((step) => String(step.tool ?? "")).filter(Boolean) : [];
308
+ out.push({
309
+ id,
310
+ name: String(raw.name ?? id),
311
+ steps,
312
+ reason: "历史工具序列行:R50 已删除组合工具机制,仅保留退役记录"
313
+ });
314
+ }
315
+ return out;
316
+ }
317
+ /** Retire every legacy sequence row (idempotent). */
318
+ async function retireLegacySequenceRows(store, logger, options = {}) {
319
+ const candidates = legacySequenceRows(store);
320
+ if (options.dryRun) return candidates;
321
+ const retired = [];
322
+ for (const item of candidates) try {
323
+ await store.toolMemory.update(item.id, (row) => ({
324
+ ...row,
325
+ status: "retired"
326
+ }));
327
+ retired.push(item);
328
+ logger?.info("supermemory: retired legacy sequence row " + item.name);
329
+ } catch {}
330
+ return retired;
331
+ }
332
+ /** Decline every pending proposal (idempotent; never deletes the audit row). */
333
+ async function clearPendingProposals(store, options = {}) {
334
+ const pending = capabilityRows(store).filter((entry) => entry.record.kind === "proposal" && entry.record.proposalStatus === "pending");
335
+ if (options.dryRun) return {
336
+ before: pending.length,
337
+ cleared: pending.length
338
+ };
339
+ let cleared = 0;
340
+ for (const entry of pending) {
341
+ const next = {
342
+ ...entry.record,
343
+ proposalStatus: "declined",
344
+ updatedAt: Date.now(),
345
+ changelog: ["清理:待处理提案已清空", ...entry.record.changelog].slice(0, 20)
346
+ };
347
+ try {
348
+ await saveCapabilityRecord(store, next, {
349
+ id: entry.id,
350
+ workspaceKey: entry.row.workspaceKey,
351
+ createdAt: entry.row.createdAt
352
+ });
353
+ cleared += 1;
354
+ } catch {}
355
+ }
356
+ return {
357
+ before: pending.length,
358
+ cleared
359
+ };
360
+ }
361
+ /** One idempotent cleanup pass (boot + memory_toolize cleanup). */
362
+ async function cleanupToolize(options) {
363
+ const now = options.now ?? Date.now();
364
+ const dryRun = Boolean(options.dryRun);
365
+ const dropPending = options.dropPending !== false;
366
+ const expiredProposals = dryRun ? 0 : await expireProposals(options.store, now);
367
+ const retired = await retireLegacySequenceRows(options.store, options.logger, { dryRun });
368
+ const proposals = dropPending ? await clearPendingProposals(options.store, { dryRun }) : {
369
+ before: capabilityRows(options.store).filter((entry) => entry.record.kind === "proposal" && entry.record.proposalStatus === "pending").length,
370
+ cleared: 0
371
+ };
372
+ const signals = await clearSequenceSignals(options.store, {
373
+ dropAllPending: dropPending,
374
+ dryRun
375
+ });
376
+ let archived = [];
377
+ let archiveRoots = [];
378
+ let scannedSkills = 0;
379
+ if (options.roots !== void 0 && options.roots.length > 0) {
380
+ const result = await archiveShellSkills({
381
+ roots: options.roots,
382
+ store: options.store,
383
+ now,
384
+ dryRun
385
+ });
386
+ archived = result.archived;
387
+ archiveRoots = result.roots;
388
+ scannedSkills = result.totalScanned;
389
+ }
390
+ const shellUnits = await retireShellUnits(options.store, { dryRun });
391
+ return {
392
+ retired,
393
+ retiredCount: retired.length,
394
+ clearedProposals: Math.max(proposals.cleared, signals.clearedProposals),
395
+ prunedSignals: signals.prunedSignals,
396
+ pendingBefore: Math.max(proposals.before, signals.pendingBefore),
397
+ pendingAfter: signals.pendingAfter,
398
+ archived,
399
+ archiveRoots,
400
+ archivedCount: archived.length,
401
+ scannedSkills,
402
+ expiredProposals,
403
+ retiredShellUnits: shellUnits.length,
404
+ retiredShellNames: shellUnits.map((item) => item.name),
405
+ dryRun
406
+ };
407
+ }
408
+ /** Idle capability recycle (default OFF via recycleIdleDays 0). */
409
+ let lastRecycleAt = 0;
410
+ async function recycleIdleCapabilities(ctx, store, config, logger, now = Date.now()) {
411
+ if (config.recycleIdleDays <= 0) return 0;
412
+ if (now - lastRecycleAt < 36e5) return 0;
413
+ lastRecycleAt = now;
414
+ let retired = 0;
415
+ for (const entry of capabilityRows(store)) {
416
+ if (entry.record.kind !== "capability" || entry.record.loadCount > 0 || entry.record.runCount > 0) continue;
417
+ if (now - entry.record.updatedAt < config.recycleIdleDays * 864e5) continue;
418
+ try {
419
+ await setCapabilityEnabled(ctx, store, entry.id, false);
420
+ retired += 1;
421
+ logger.info("supermemory: recycled idle capability " + entry.record.name);
422
+ } catch {}
423
+ }
424
+ return retired;
425
+ }
426
+ export { cleanupToolize, recordTurnSequences, recycleIdleCapabilities, sweepTaskProposals };
package/package.json CHANGED
@@ -1,6 +1,69 @@
1
1
  {
2
2
  "name": "@frogmoo/dsh-supermemory",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "1.4.1",
4
+ "description": "SuperMemory — DSH 跨会话记忆插件:话题集记忆、派发归档、过程内再召回与统一能力(知识面 SKILL.md + 执行面 sm_cap_*)。",
5
+ "license": "MIT",
6
+ "publishConfig": {
7
+ "access": "public",
8
+ "registry": "https://registry.npmjs.org/"
9
+ },
10
+ "type": "module",
11
+ "main": "lib/supermemory.js",
12
+ "exports": {
13
+ ".": "./lib/supermemory.js",
14
+ "./client": "./lib/client.js",
15
+ "./package.json": "./package.json"
16
+ },
17
+ "files": [
18
+ "lib",
19
+ "cordis.patch.yml",
20
+ "CHANGELOG.md",
21
+ "INSTALL.md"
22
+ ],
23
+ "dependencies": {
24
+ "@deepseek-ai/schemastery": "~3.18.4",
25
+ "zod": "4.6.6"
26
+ },
27
+ "peerDependencies": {
28
+ "@deepseek-ai/cordis": "*",
29
+ "@deepseek-ai/dsh-agent": "*",
30
+ "@deepseek-ai/dsh-llm": "*",
31
+ "@deepseek-ai/dsh-storage-domain": "*",
32
+ "@deepseek-ai/dsh-tools": "*",
33
+ "@deepseek-ai/dsh-user-questions": "*",
34
+ "@deepseek-ai/dsh-workspace": "*",
35
+ "cordis": ">=4.0.0-rc <5"
36
+ },
37
+ "devDependencies": {
38
+ "@types/node": "^22.10.0",
39
+ "tsdown": "^0.22.14",
40
+ "typescript": "^5.9.0"
41
+ },
42
+ "engines": {
43
+ "dsh": ">=0.2.0 <0.3.0"
44
+ },
45
+ "scripts": {
46
+ "git:sync": "node scripts/git-sync-push.mjs",
47
+ "install:dsh": "node scripts/install-into-dsh.mjs",
48
+ "build": "tsdown && tsdown -c tsdown.client.config.ts && node scripts/wrap-client.mjs",
49
+ "package-release": "node scripts/package-release.mjs",
50
+ "prepublishOnly": "pnpm run build",
51
+ "publish:npm": "npm publish --access public",
52
+ "typecheck": "tsc -p tsconfig.json && tsc -p tsconfig.client.json",
53
+ "build:host": "tsdown",
54
+ "build:client": "tsdown -c tsdown.client.config.ts && node scripts/wrap-client.mjs",
55
+ "smoke:webui": "node scripts/webui-smoke.mjs",
56
+ "smoke:core": "node scripts/core-smoke.mjs",
57
+ "smoke:skill": "node scripts/skill-smoke.mjs",
58
+ "skill:cleanup": "node --experimental-transform-types scripts/skill-cleanup.mjs",
59
+ "smoke": "node scripts/core-smoke.mjs && node scripts/mechanism-smoke.mjs && node scripts/webui-smoke.mjs && node scripts/client-sim-smoke.mjs && node scripts/capability-smoke.mjs && node scripts/workspace-scope-smoke.mjs && node scripts/skill-smoke.mjs"
60
+ },
61
+ "dsh": {
62
+ "bundle": {
63
+ "patch": "./cordis.patch.yml"
64
+ },
65
+ "client": {
66
+ "platform": "web"
67
+ }
68
+ }
69
+ }