@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,531 @@
1
+ import { createRequire } from "node:module";
2
+ import { realpathSync } from "node:fs";
3
+ import { resolve } from "node:path";
4
+ import { pathToFileURL } from "node:url";
5
+ // src/host.ts
6
+ /**
7
+ * Host-anchored module loading.
8
+ *
9
+ * `@deepseek-ai/dsh-*` packages are NOT resolvable from a plugin's own package
10
+ * scope (the profile's node_modules only hoists non-dsh runtime deps). The
11
+ * proven third-party pattern (dsh-vscode-mode) resolves the specifier against
12
+ * the running DSH entry (`process.argv[1]`) and imports the resolved file URL,
13
+ * which lands on the host's bundled copy. Import failures after successful
14
+ * resolution are preserved, not hidden by an older copy.
15
+ * @module supermemory/host
16
+ */
17
+ const cache = /* @__PURE__ */ new Map();
18
+ /**
19
+ * Import a host package, preferring the copy the running DSH entry resolves.
20
+ * @param specifier - host package name, e.g. `@deepseek-ai/dsh-tools`.
21
+ * @returns the evaluated module namespace (cached per specifier).
22
+ */
23
+ async function loadHostModule(specifier) {
24
+ let pending = cache.get(specifier);
25
+ if (!pending) {
26
+ pending = (async () => {
27
+ const anchor = process.argv[1];
28
+ let resolved;
29
+ if (anchor) try {
30
+ resolved = createRequire(anchor).resolve(specifier);
31
+ } catch {}
32
+ return resolved ? import(pathToFileURL(resolved).href) : import(specifier);
33
+ })();
34
+ cache.set(specifier, pending);
35
+ }
36
+ return pending;
37
+ }
38
+ // src/schema.ts
39
+ let zodPending;
40
+ /** The host's zod module (v4), shared with the storage-domain layer. */
41
+ function getZod() {
42
+ return zodPending ??= loadHostModule("zod");
43
+ }
44
+ /** Builds every table schema of the domain. Called once, inside apply(). */
45
+ async function buildSchemas() {
46
+ const z = await getZod();
47
+ const member = z.object({
48
+ sessionId: z.string(),
49
+ kind: z.enum(["root", "fork"]).default("root"),
50
+ title: z.string().default(""),
51
+ summary: z.string().default(""),
52
+ status: z.enum(["live", "idle"]).default("live"),
53
+ model: z.string().optional(),
54
+ modelOverridden: z.boolean().default(false),
55
+ lastActiveAt: z.number().int().default(0)
56
+ });
57
+ const topicsets = z.object({
58
+ workspaceKey: z.string(),
59
+ title: z.string(),
60
+ summary: z.string().default(""),
61
+ keywords: z.array(z.string()).default([]),
62
+ status: z.enum(["active", "archived"]).default("active"),
63
+ defaultModel: z.object({
64
+ provider: z.string(),
65
+ model: z.string(),
66
+ reasoningEffort: z.string().optional()
67
+ }).optional(),
68
+ members: z.array(member).default([]),
69
+ shapeFingerprint: z.string().default(""),
70
+ shapeGeneratedAt: z.number().int().default(0),
71
+ createdAt: z.number().int(),
72
+ updatedAt: z.number().int(),
73
+ lastActiveAt: z.number().int().default(0)
74
+ });
75
+ const memories = z.object({
76
+ workspaceKey: z.string(),
77
+ title: z.string().default(""),
78
+ text: z.string(),
79
+ key: z.string().optional(),
80
+ keywords: z.array(z.string()).default([]),
81
+ collectionId: z.string().optional(),
82
+ sourceSessionId: z.string(),
83
+ sourceSeq: z.number().int().nonnegative(),
84
+ status: z.enum(["active", "superseded"]).default("active"),
85
+ supersededBy: z.string().optional(),
86
+ version: z.number().int().default(1),
87
+ createdAt: z.number().int(),
88
+ updatedAt: z.number().int()
89
+ });
90
+ const memoryCollections = z.object({
91
+ workspaceKey: z.string(),
92
+ title: z.string(),
93
+ keywords: z.array(z.string()).default([]),
94
+ summary: z.string().default(""),
95
+ status: z.enum(["active", "archived"]).default("active"),
96
+ createdAt: z.number().int(),
97
+ updatedAt: z.number().int()
98
+ });
99
+ const memoryVersions = z.object({
100
+ workspaceKey: z.string(),
101
+ memoryId: z.string(),
102
+ version: z.number().int(),
103
+ title: z.string().default(""),
104
+ text: z.string(),
105
+ /** 该版本的标签(与 memories.keywords 同语义,历史行用 tags 命名)。 */
106
+ tags: z.array(z.string()).default([]),
107
+ collectionId: z.string().optional(),
108
+ /** 该版本生效的时间(创建/更新时刻;迁移行沿用记忆自身的 updatedAt)。 */
109
+ updatedAt: z.number().int(),
110
+ /** create=新建 v1;update=就地更新升版;migrate=旧记忆惰性迁移补的 v1。 */
111
+ changeType: z.enum([
112
+ "create",
113
+ "update",
114
+ "migrate"
115
+ ])
116
+ });
117
+ const hubPolicies = z.object({
118
+ workspaceKey: z.string(),
119
+ tools: z.array(z.string()).default([]),
120
+ prefixes: z.array(z.string()).default([]),
121
+ updatedAt: z.number().int()
122
+ });
123
+ const modelDefaults = z.object({
124
+ workspaceKey: z.string(),
125
+ /** 新建中枢会话的默认模型;缺省=跟随宿主默认。 */
126
+ hub: z.object({
127
+ provider: z.string(),
128
+ model: z.string(),
129
+ reasoningEffort: z.string().optional()
130
+ }).optional(),
131
+ /** 新派发分支会话的默认模型;缺省=跟随话题集/中枢/宿主默认。 */
132
+ branch: z.object({
133
+ provider: z.string(),
134
+ model: z.string(),
135
+ reasoningEffort: z.string().optional()
136
+ }).optional(),
137
+ updatedAt: z.number().int()
138
+ });
139
+ const episodes = z.object({
140
+ topicSetId: z.string().optional(),
141
+ branchSessionId: z.string().optional(),
142
+ timeStart: z.number().int(),
143
+ timeEnd: z.number().int(),
144
+ /** Short form for recall cards / topic-shape fingerprints / exports. */
145
+ summary: z.string().default(""),
146
+ /**
147
+ * The branch's FULL final answer. `summary` is deliberately short (recall
148
+ * cards, topic-shape fingerprints and exports read it), but the hub-facing
149
+ * relay must carry the whole result: clipping it there silently destroyed
150
+ * most of a branch's work. Episodes written before this field read as ''
151
+ * and fall back to `summary` (the domain stays v1).
152
+ */
153
+ result: z.string().default(""),
154
+ decisions: z.array(z.string()).default([]),
155
+ files: z.array(z.string()).default([]),
156
+ nextSteps: z.array(z.string()).default([]),
157
+ reqIds: z.array(z.string()).default([]),
158
+ sourceSessionId: z.string(),
159
+ sourceSeqStart: z.number().int().nonnegative(),
160
+ sourceSeqEnd: z.number().int().nonnegative()
161
+ });
162
+ const requirements = z.object({
163
+ topicSetId: z.string().optional(),
164
+ workspaceKey: z.string(),
165
+ text: z.string(),
166
+ constraints: z.array(z.string()).default([]),
167
+ status: z.enum(["open", "closed"]).default("open"),
168
+ sourceSessionId: z.string(),
169
+ sourceSeq: z.number().int().nonnegative(),
170
+ createdAt: z.number().int(),
171
+ closedAt: z.number().int().optional()
172
+ });
173
+ const filemap = z.object({
174
+ workspaceKey: z.string(),
175
+ path: z.string(),
176
+ role: z.string().default(""),
177
+ summary: z.string().default(""),
178
+ keywords: z.array(z.string()).default([]),
179
+ hash: z.string().optional(),
180
+ mtime: z.number().int().optional(),
181
+ annotatedAt: z.number().int()
182
+ });
183
+ const toolMemory = z.object({
184
+ workspaceKey: z.string().optional(),
185
+ createdAt: z.number().int().optional(),
186
+ /**
187
+ * R50 统一能力记录:capability = 可执行能力(知识面 + 执行面),knowledge =
188
+ * 仅知识能力(知识面文件,无入口命令),proposal = 待接受的自动知识草稿。
189
+ * composite / skill / workflow 是 R50 之前的历史 kind,只由惰性迁移读取:
190
+ * 旧 capability(kind='composite' + spec.kind='capability')迁为 capability,
191
+ * 旧 skill 行迁为 knowledge,旧的工具序列行退役(status='retired')。
192
+ */
193
+ kind: z.enum([
194
+ "composite",
195
+ "skill",
196
+ "workflow",
197
+ "capability",
198
+ "knowledge",
199
+ "proposal"
200
+ ]).default("composite"),
201
+ title: z.string().default(""),
202
+ tags: z.array(z.string()).default([]),
203
+ trigger: z.string().default(""),
204
+ description: z.string().default(""),
205
+ /**
206
+ * R50:新行为能力记录的 JSON 定义(CapabilityRecord);旧行仍是旧的
207
+ * CompositeSpec / skill 路径。读取统一走 capability.ts readCapabilityRow,
208
+ * 迁移后旧行改写为新定义。域版本保持 v1。
209
+ */
210
+ entry: z.string().default(""),
211
+ useCount: z.number().int().nonnegative().default(0),
212
+ status: z.enum(["active", "retired"]).default("active"),
213
+ /** 知识面文件绝对路径(R52:.dsh/capabilities/<name>.md;旧 kind='skill' 行迁移时从 entry 取出)。 */
214
+ skillPath: z.string().optional(),
215
+ /** 启用/停用同时作用于知识面(disable-model-invocation)与执行面(工具注册)。 */
216
+ enabled: z.boolean().default(true),
217
+ /** 模型经 sm_cap_doc 加载本能力知识面的次数(转化率分母)。 */
218
+ loadCount: z.number().int().nonnegative().default(0),
219
+ /** 执行面(sm_cap_* 工具 / 面板 / memory_toolize)实际执行次数(转化率分子)。 */
220
+ runCount: z.number().int().nonnegative().default(0),
221
+ /** 来源:builtin / manual / auto / migrated(面板徽标与上限判定)。 */
222
+ source: z.string().default("manual"),
223
+ /** 任务签名(自动知识草稿/能力聚合同一类任务)。 */
224
+ taskKey: z.string().optional(),
225
+ /** 高置信自动起草的入口命令(未验证;人工「启用执行」前不得执行)。 */
226
+ entryDraft: z.string().default(""),
227
+ /** entryDraft 是否经人工确认(true 才允许 runnable=true)。 */
228
+ entryVerified: z.boolean().default(false),
229
+ /** 知识面正文(事实块之外)的哈希:检测人工编辑。 */
230
+ bodyHash: z.string().optional(),
231
+ /** 事实块哈希:判断自动事实是否过期。 */
232
+ factsHash: z.string().optional()
233
+ });
234
+ const signals = z.object({
235
+ workspaceKey: z.string(),
236
+ pattern: z.string(),
237
+ count: z.number().int().nonnegative().default(0),
238
+ lastSeen: z.number().int(),
239
+ examples: z.array(z.string()).default([]),
240
+ proposedAt: z.number().int().optional(),
241
+ proposalStatus: z.enum([
242
+ "pending",
243
+ "accepted",
244
+ "declined"
245
+ ]).optional(),
246
+ sequence: z.array(z.string()).default([]),
247
+ samples: z.array(z.string()).default([]),
248
+ sessions: z.array(z.string()).optional(),
249
+ dispatches: z.array(z.string()).optional()
250
+ });
251
+ const dispatches = z.object({
252
+ topicSetId: z.string().optional(),
253
+ groupId: z.string().optional(),
254
+ branchSessionId: z.string(),
255
+ task: z.string(),
256
+ hubSessionId: z.string(),
257
+ startSeq: z.number().int().nonnegative(),
258
+ turnEndReason: z.string().optional(),
259
+ status: z.enum([
260
+ "queued",
261
+ "dispatched",
262
+ "observed",
263
+ "summarized",
264
+ "delivered",
265
+ "failed",
266
+ "interrupted"
267
+ ]).default("queued"),
268
+ lastActivityAt: z.number().int().optional(),
269
+ title: z.string().default(""),
270
+ tags: z.array(z.string()).default([]),
271
+ capability: z.string().default(""),
272
+ resumeOf: z.string().optional(),
273
+ resumedBy: z.string().optional(),
274
+ interruptNoticedAt: z.number().int().optional(),
275
+ createdAt: z.number().int(),
276
+ updatedAt: z.number().int()
277
+ });
278
+ const questions = z.object({
279
+ dispatchId: z.string().optional(),
280
+ groupId: z.string().optional(),
281
+ topicSetId: z.string().optional(),
282
+ branchSessionId: z.string(),
283
+ hubSessionId: z.string().optional(),
284
+ /** The dispatched task label, so a hub aggregate is readable without a join. */
285
+ branchTask: z.string().default(""),
286
+ title: z.string(),
287
+ question: z.string(),
288
+ options: z.array(z.string()).default([]),
289
+ severity: z.enum([
290
+ "low",
291
+ "medium",
292
+ "high"
293
+ ]).default("medium"),
294
+ /** false = the branch keeps working under its best interpretation. */
295
+ blocking: z.boolean().default(false),
296
+ /** What the branch already finished (required for blocking=true by contract). */
297
+ progress: z.string().default(""),
298
+ /** The branch's default fallback if the user never answers. */
299
+ defaultPlan: z.string().default(""),
300
+ status: z.enum(["open", "resolved"]).default("open"),
301
+ /** The user's answer, filled by the hub's memory_questions resolve step. */
302
+ answer: z.string().optional(),
303
+ createdAt: z.number().int(),
304
+ updatedAt: z.number().int()
305
+ });
306
+ const outbox = z.object({
307
+ dispatchId: z.string().optional(),
308
+ groupId: z.string().optional(),
309
+ kind: z.enum(["single", "group"]).default("single"),
310
+ payload: z.string(),
311
+ status: z.enum([
312
+ "pending",
313
+ "relayed",
314
+ "confirmed",
315
+ "failed"
316
+ ]).default("pending"),
317
+ enqueuedAt: z.number().int(),
318
+ relayedAt: z.number().int().optional(),
319
+ fromSessionId: z.string().optional(),
320
+ fromTitle: z.string().optional(),
321
+ fromKind: z.enum([
322
+ "hub",
323
+ "branch",
324
+ "group",
325
+ "system"
326
+ ]).optional(),
327
+ task: z.string().default(""),
328
+ topicSetTitle: z.string().default(""),
329
+ capability: z.string().default(""),
330
+ suppressedOf: z.string().optional()
331
+ });
332
+ const hubSessions = z.object({
333
+ workspaceKey: z.string(),
334
+ sessionId: z.string(),
335
+ title: z.string().default(""),
336
+ /** How the hub was marked (audit only; resolution trusts every source). */
337
+ source: z.enum([
338
+ "panel",
339
+ "topicset-root",
340
+ "dispatch",
341
+ "migration",
342
+ "title-migration"
343
+ ]).default("panel"),
344
+ createdAt: z.number().int(),
345
+ updatedAt: z.number().int()
346
+ });
347
+ return {
348
+ topicsets,
349
+ memories,
350
+ memory_collections: memoryCollections,
351
+ memory_versions: memoryVersions,
352
+ episodes,
353
+ requirements,
354
+ filemap,
355
+ tool_memory: toolMemory,
356
+ signals,
357
+ dispatches,
358
+ questions,
359
+ outbox,
360
+ routing: z.object({
361
+ activeTopicSetId: z.string().optional(),
362
+ driftCount: z.number().int().nonnegative().default(0),
363
+ updatedAt: z.number().int()
364
+ }),
365
+ hotcache: z.object({
366
+ recentRelevant: z.object({
367
+ episodes: z.array(z.string()).default([]),
368
+ reqIds: z.array(z.string()).default([]),
369
+ memoryIds: z.array(z.string()).default([]),
370
+ toolNames: z.array(z.string()).default([])
371
+ }).default({
372
+ episodes: [],
373
+ reqIds: [],
374
+ memoryIds: [],
375
+ toolNames: []
376
+ }),
377
+ lastMaintainedSeq: z.number().int().nonnegative().optional(),
378
+ updatedAt: z.number().int()
379
+ }),
380
+ meta: z.object({
381
+ titlesMigratedAt: z.number().int().optional(),
382
+ titlesMigrationVersion: z.number().int().optional(),
383
+ mergesVersion: z.number().int().optional(),
384
+ mergeSignatures: z.array(z.string()).optional(),
385
+ lastMergeAt: z.number().int().optional(),
386
+ organizeVersion: z.number().int().optional(),
387
+ organizeAppliedAt: z.number().int().optional(),
388
+ organizeWorkspace: z.string().optional(),
389
+ organizeBackup: z.string().optional(),
390
+ organizeSummary: z.string().optional(),
391
+ hubTitlesMigrationVersion: z.number().int().optional(),
392
+ hubTitlesMigratedAt: z.number().int().optional(),
393
+ hubTitlesProcessedIds: z.array(z.string()).optional(),
394
+ hubTitlesPendingIds: z.array(z.string()).optional(),
395
+ hubRecordsMigrationVersion: z.number().int().optional(),
396
+ hubRecordsMigratedAt: z.number().int().optional(),
397
+ roleGuardInstalledAt: z.number().int().optional(),
398
+ roleGuardFailedAt: z.number().int().optional(),
399
+ roleGuardVersion: z.number().int().optional(),
400
+ roleGuardError: z.string().optional(),
401
+ hubPolicyLockedVersion: z.number().int().optional(),
402
+ hubPolicyLockedMergedAt: z.number().int().optional(),
403
+ hubPolicyLockedRows: z.number().int().optional(),
404
+ hubPolicyLockedUpdated: z.number().int().optional()
405
+ }),
406
+ hub_sessions: hubSessions,
407
+ hub_policies: hubPolicies,
408
+ model_defaults: modelDefaults
409
+ };
410
+ }
411
+ // src/store.ts
412
+ /**
413
+ * Domain store: opens the `supermemory` storage domain and exposes typed table
414
+ * accessors plus workspace-key resolution.
415
+ * @module supermemory/store
416
+ */
417
+ /**
418
+ * Canonical workspace key: the realpath of a session cwd (decision D4).
419
+ * Falls back to the resolved path when the directory vanished.
420
+ */
421
+ function workspaceKeyOf(cwd) {
422
+ if (!cwd) return "unknown";
423
+ try {
424
+ return realpathSync(resolve(cwd));
425
+ } catch {
426
+ return resolve(cwd);
427
+ }
428
+ }
429
+ /** Monotonic-ish id helper (no host import needed). */
430
+ function newId(prefix) {
431
+ return `${prefix}-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`;
432
+ }
433
+ /** Backoff used while a disposing instance still owns the domain (plugin reload race). */
434
+ const STORE_OPEN_RETRY_MS = Object.freeze([
435
+ 100,
436
+ 250,
437
+ 750,
438
+ 2e3
439
+ ]);
440
+ /**
441
+ * Retry an async open while the domain name is still reserved by an instance
442
+ * that is unloading.
443
+ *
444
+ * `storageDomain.open()` rejects `already-open` when the name is reserved by
445
+ * an in-flight or completed open, and a plugin reload can start the new fiber
446
+ * before the old fiber's domain disposer ran. Only that code is retried; every
447
+ * other failure (version mismatch, malformed medium, backend route, …) is the
448
+ * caller's to degrade on, immediately.
449
+ */
450
+ async function retryDomainOpen(open, logger, delays = STORE_OPEN_RETRY_MS) {
451
+ for (let attempt = 0;; attempt += 1) try {
452
+ return await open();
453
+ } catch (error) {
454
+ if (error?.code !== "already-open" || attempt >= delays.length) throw error;
455
+ logger.warn(`supermemory: storage domain still owned by a disposing instance; retrying in ${delays[attempt]}ms`);
456
+ await new Promise((resolve) => setTimeout(resolve, delays[attempt]));
457
+ }
458
+ }
459
+ /** Open the storage domain, riding out a reload's domain-handover window. */
460
+ async function openStoreWithRetry(storageDomain, logger) {
461
+ return retryDomainOpen(() => openStore(storageDomain, logger), logger);
462
+ }
463
+ /**
464
+ * The supermemory domain declaration. Exported (besides openStore) so the
465
+ * offline maintenance script (scripts/cleanup-legacy-titles.mjs) can open the
466
+ * SAME domain through the real domain layer — schema-validated reads and the
467
+ * domain write chain — instead of hand-editing the JSON medium.
468
+ *
469
+ * @param sd - one storage-domain module (the host copy in the plugin; the
470
+ * _dsh_src copy in the script — same 0.2.2-rc.3 version).
471
+ * @param schemas - record schemas from buildSchemas.
472
+ */
473
+ function supermemorySpec(sd, schemas) {
474
+ return sd.defineDomain({
475
+ name: "supermemory",
476
+ version: 1,
477
+ tables: {
478
+ topicsets: sd.domainTable(schemas.topicsets),
479
+ memories: sd.domainTable(schemas.memories),
480
+ memory_collections: sd.domainTable(schemas.memory_collections),
481
+ memory_versions: sd.domainTable(schemas.memory_versions),
482
+ episodes: sd.domainTable(schemas.episodes),
483
+ requirements: sd.domainTable(schemas.requirements),
484
+ filemap: sd.domainTable(schemas.filemap),
485
+ tool_memory: sd.domainTable(schemas.tool_memory),
486
+ signals: sd.domainTable(schemas.signals),
487
+ dispatches: sd.domainTable(schemas.dispatches),
488
+ questions: sd.domainTable(schemas.questions),
489
+ outbox: sd.domainTable(schemas.outbox),
490
+ routing: sd.domainTable(schemas.routing),
491
+ hotcache: sd.domainTable(schemas.hotcache),
492
+ meta: sd.domainTable(schemas.meta),
493
+ hub_sessions: sd.domainTable(schemas.hub_sessions),
494
+ hub_policies: sd.domainTable(schemas.hub_policies),
495
+ model_defaults: sd.domainTable(schemas.model_defaults)
496
+ }
497
+ });
498
+ }
499
+ /**
500
+ * Open the storage domain. A failure is logged and rethrown — the caller
501
+ * decides whether to degrade (P0: degrade to a disabled store).
502
+ */
503
+ async function openStore(storageDomain, logger) {
504
+ const spec = supermemorySpec(await loadHostModule("@deepseek-ai/dsh-storage-domain"), await buildSchemas());
505
+ const domain = await storageDomain.open(spec);
506
+ logger.info("supermemory: storage domain opened");
507
+ const table = (name) => domain.table(name);
508
+ return {
509
+ domain,
510
+ topicsets: table("topicsets"),
511
+ memories: table("memories"),
512
+ memoryCollections: table("memory_collections"),
513
+ memoryVersions: table("memory_versions"),
514
+ episodes: table("episodes"),
515
+ requirements: table("requirements"),
516
+ filemap: table("filemap"),
517
+ toolMemory: table("tool_memory"),
518
+ signals: table("signals"),
519
+ routing: table("routing"),
520
+ hotcache: table("hotcache"),
521
+ dispatches: table("dispatches"),
522
+ questions: table("questions"),
523
+ outbox: table("outbox"),
524
+ meta: table("meta"),
525
+ hubs: table("hub_sessions"),
526
+ hubPolicies: table("hub_policies"),
527
+ modelDefaults: table("model_defaults"),
528
+ close: () => domain.close()
529
+ };
530
+ }
531
+ export { loadHostModule as i, openStoreWithRetry as n, workspaceKeyOf as r, newId as t };