dsh-memvault 0.10.1 → 0.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,490 @@
1
+ /**
2
+ * The domain half of the plugin: activation state, the second context segment,
3
+ * and the three tools the model uses to ask about a pack.
4
+ *
5
+ * Kept out of `index.js` on purpose. `index.js` is already the wiring for four
6
+ * other halves; a domain plane that decides what to inject every ten seconds
7
+ * deserves its own file with its own tests, and `domain.js` stays pure.
8
+ */
9
+ import { draftDomain, DRAFT_LIMITS } from './domain.js'
10
+ import {
11
+ DOMAIN_THRESHOLD,
12
+ getDomain,
13
+ listDomains,
14
+ logDomainEvent,
15
+ probeWorkspace,
16
+ rankDomains,
17
+ renderDomainIndex,
18
+ renderShadow,
19
+ selectDomains,
20
+ touchDomain,
21
+ } from './domain.js'
22
+ import {
23
+ DEFAULT_GATED_TOOLS,
24
+ evaluateEvidence,
25
+ gateKey,
26
+ openGates,
27
+ renderGateNotice,
28
+ } from './gate.js'
29
+
30
+ /**
31
+ * Process-local activation state.
32
+ *
33
+ * `active` is sticky for the lifetime of the host, not per session: the injected
34
+ * segment is a KV-cache prefix, and a pack appearing and disappearing mid-task is
35
+ * worse than a pack that lingers. Deactivating is explicit (`domain_deactivate`).
36
+ */
37
+ export function createDomainState() {
38
+ return {
39
+ active: new Set(),
40
+ shadow: [],
41
+ reasons: new Map(),
42
+ lastProbeAt: 0,
43
+ probe: { dir: '', files: [], deps: '' },
44
+ lastText: '',
45
+ lastScoreAt: 0,
46
+ // Gates the guard must refuse on, refreshed with the segment. `passed` is
47
+ // keyed by pack version, so editing a pack voids the evidence gathered for the
48
+ // old version — the rule changed, so the research has to be redone.
49
+ openGates: [],
50
+ passed: new Set(),
51
+ }
52
+ }
53
+
54
+ /**
55
+ * Recent signals, kept as a tiny ring because scoring only needs the tail.
56
+ *
57
+ * The alternative — rescanning the event buffer — costs more as a session grows,
58
+ * and the useful evidence is always "what has been said or touched lately".
59
+ */
60
+ export function createSignalRing({ maxChars = 2000 } = {}) {
61
+ let text = ''
62
+ let tools = ''
63
+ return {
64
+ pushUser(value) {
65
+ text = `${text}\n${String(value ?? '')}`.slice(-maxChars)
66
+ },
67
+ pushTool(value) {
68
+ tools = `${tools}\n${String(value ?? '')}`.slice(-maxChars)
69
+ },
70
+ snapshot() {
71
+ return { text, tools }
72
+ },
73
+ }
74
+ }
75
+
76
+ /**
77
+ * Decide the segment text for this step.
78
+ *
79
+ * Order: probe (cached), rank the human-approved packs, keep the sticky ones,
80
+ * render. A pack that is not `active` is never injected: automatic generation may
81
+ * only create a `draft`, because an unapproved pack is a guess wearing the clothes
82
+ * of a rule.
83
+ *
84
+ * @returns `{ text, active, shadow, reasons, probe, ranked }`.
85
+ */
86
+ export function computeDomainSegment({
87
+ store,
88
+ state,
89
+ settings,
90
+ signals,
91
+ now = Date.now(),
92
+ probe = probeWorkspace,
93
+ } = {}) {
94
+ const config = settings ?? {}
95
+ const empty = { text: '', active: [], shadow: [], reasons: [], probe: state?.probe ?? { dir: '', files: [], deps: '' }, ranked: [] }
96
+ if (!store) return empty
97
+
98
+ const packs = listDomains(store, { status: 'active' })
99
+ if (packs.length === 0) {
100
+ state.active.clear()
101
+ state.shadow = []
102
+ return empty
103
+ }
104
+
105
+ if (now - (state.lastProbeAt ?? 0) >= (config.refreshMs ?? 10_000) || state.probe.dir !== (config.probeDir ?? '')) {
106
+ state.probe = probe({ dir: config.probeDir ?? '', domains: packs })
107
+ state.lastProbeAt = now
108
+ }
109
+
110
+ const ranked = rankDomains(packs, {
111
+ dir: state.probe.dir,
112
+ files: state.probe.files,
113
+ deps: state.probe.deps,
114
+ text: signals?.text ?? '',
115
+ tools: signals?.tools ?? '',
116
+ seen: false,
117
+ })
118
+ const picked = selectDomains({
119
+ ranked,
120
+ sticky: state.active,
121
+ maxDomains: config.maxDomains ?? 2,
122
+ threshold: config.threshold ?? DOMAIN_THRESHOLD,
123
+ })
124
+
125
+ // Sticky entries stay even when the probe no longer matches; freshly scored ones
126
+ // are recorded so the panel can say why this pack is in the prompt.
127
+ const activeIds = new Set(picked.active.map((entry) => entry.domainId))
128
+ for (const id of [...state.active]) if (!activeIds.has(id)) state.active.delete(id)
129
+ for (const entry of picked.active) {
130
+ if (!state.active.has(entry.domainId)) {
131
+ state.active.add(entry.domainId)
132
+ state.reasons.set(entry.domainId, entry.reasons)
133
+ logDomainEvent(store, entry.domainId, 'activate', { reasons: entry.reasons, score: entry.score })
134
+
135
+ try { touchDomain(store, entry.domainId) } catch { /* usage counting is advisory */ }
136
+ } else if (!state.reasons.has(entry.domainId)) {
137
+ state.reasons.set(entry.domainId, entry.reasons)
138
+ }
139
+ }
140
+ state.shadow = picked.shadow
141
+
142
+ const active = picked.active
143
+ .map((entry) => getDomain(store, entry.domainId))
144
+ .filter(Boolean)
145
+
146
+ // Gates are computed here, with the same active set, so the guard and the
147
+ // injected notice can never disagree about what is open.
148
+ const gateConfig = config.gate ?? {}
149
+ const gates = gateConfig.enabled === false
150
+ ? []
151
+ : openGates(active, state.passed)
152
+ state.openGates = gates
153
+
154
+ const parts = [
155
+ renderDomainIndex(active, {
156
+ maxChars: config.maxChars ?? 1000,
157
+ indexChars: config.indexChars ?? 480,
158
+ }),
159
+ renderShadow(picked.shadow),
160
+ renderGateNotice(gates, { maxChars: gateConfig.noticeChars ?? 240 }),
161
+ ].filter(Boolean)
162
+
163
+ // The drafting hint deliberately rides the domain segment rather than the core
164
+ // block: it is about a capability of this plane, it must disappear when the plane
165
+ // is empty (an install with no packs keeps a byte-identical injection), and it
166
+ // would be a lie once the shelf is full.
167
+ if (parts.length > 0 && config.draftHint !== false) {
168
+ const totalPacks = store.db.prepare('SELECT COUNT(*) AS n FROM domains').get()?.n ?? 0
169
+ if (totalPacks < (config.maxPacks ?? 20)) {
170
+ parts.push('若发现可复用的新领域,可用 domain_draft 起草(草稿不会注入,需人工批准)。')
171
+ }
172
+ }
173
+
174
+ const text = parts.join('\n')
175
+
176
+ return {
177
+ text,
178
+ active: picked.active,
179
+ shadow: picked.shadow,
180
+ reasons: picked.active.map((entry) => ({ domainId: entry.domainId, score: entry.score, reasons: entry.reasons })),
181
+ probe: state.probe,
182
+ ranked,
183
+ }
184
+ }
185
+
186
+ /** Model-facing JSON: one text block carrying the result object. */
187
+ const jsonOutput = (schema) => ({
188
+ schema,
189
+ render: (_args, value) => [{ type: 'text', text: JSON.stringify(value) }],
190
+ })
191
+
192
+ const ACTIVATE_PARAMETERS = {
193
+ type: 'object',
194
+ properties: {
195
+ domain_id: { type: 'string', description: 'Pack id, e.g. "game". Must already exist and be approved (status active).' },
196
+ reason: { type: 'string', description: 'Why this pack applies to the current task.' },
197
+ },
198
+ required: ['domain_id'],
199
+ additionalProperties: false,
200
+ }
201
+
202
+ const DEACTIVATE_PARAMETERS = {
203
+ type: 'object',
204
+ properties: {
205
+ domain_id: { type: 'string', description: 'Pack id to stop injecting.' },
206
+ },
207
+ required: ['domain_id'],
208
+ additionalProperties: false,
209
+ }
210
+
211
+ const DETAIL_PARAMETERS = {
212
+ type: 'object',
213
+ properties: {
214
+ domain_id: { type: 'string', description: 'Pack id whose detail to read.' },
215
+ },
216
+ required: ['domain_id'],
217
+ additionalProperties: false,
218
+ }
219
+
220
+ /**
221
+ * Build the three domain tools.
222
+ *
223
+ * `domain_detail` is the only way detail reaches the model: injecting it would
224
+ * make every active pack pay its full length on every step, and the point of the
225
+ * split is that most steps do not need it.
226
+ */
227
+ export function buildDomainTools({ store, state, detailChars = 2500, config = {} } = {}) {
228
+ if (!store) throw new Error('a store is required for the domain tools')
229
+
230
+ const activate = {
231
+ name: 'domain_activate',
232
+ description: 'Load a vertical domain pack (background rules for a kind of work: games, study, modelling, …) '
233
+ + 'into the current context. Use it when the user starts work in a domain that was hinted at but not loaded. '
234
+ + 'Only approved packs can be activated.',
235
+ parameters: ACTIVATE_PARAMETERS,
236
+ output: jsonOutput({
237
+ type: 'object',
238
+ properties: {
239
+ active: { type: 'array', items: { type: 'string' } },
240
+ index: { type: 'string' },
241
+ },
242
+ additionalProperties: false,
243
+ }),
244
+ async execute(args) {
245
+ const domain = getDomain(store, args.domain_id)
246
+ if (!domain) throw new Error(`domain_activate: no domain ${JSON.stringify(args.domain_id)}`)
247
+ if (domain.status !== 'active') {
248
+ throw new Error(`domain_activate: ${domain.domainId} is ${domain.status}; only an approved (active) pack can be injected`)
249
+ }
250
+ state.active.add(domain.domainId)
251
+ state.reasons.set(domain.domainId, ['explicit'])
252
+ logDomainEvent(store, domain.domainId, 'activate', { reasons: ['explicit'], note: String(args.reason ?? '') })
253
+ try { touchDomain(store, domain.domainId) } catch { /* advisory */ }
254
+ return {
255
+ active: [...state.active],
256
+ index: String(domain.indexText ?? '').slice(0, 600),
257
+ }
258
+ },
259
+ }
260
+
261
+ const deactivate = {
262
+ name: 'domain_deactivate',
263
+ description: 'Stop injecting a domain pack. Use it when the task has moved out of that domain.',
264
+ parameters: DEACTIVATE_PARAMETERS,
265
+ output: jsonOutput({
266
+ type: 'object',
267
+ properties: { active: { type: 'array', items: { type: 'string' } } },
268
+ additionalProperties: false,
269
+ }),
270
+ async execute(args) {
271
+ const id = String(args.domain_id ?? '').trim()
272
+ const existed = state.active.delete(id)
273
+ state.reasons.delete(id)
274
+ logDomainEvent(store, id, 'deactivate', { existed })
275
+ return { active: [...state.active] }
276
+ },
277
+ }
278
+
279
+ const detail = {
280
+ name: 'domain_detail',
281
+ description: 'Read the detail of a domain pack: terminology, architecture notes, pitfalls and the full checklist. '
282
+ + 'The detail is not injected, so call this when the index line says it applies and you need the specifics.',
283
+ parameters: DETAIL_PARAMETERS,
284
+ output: jsonOutput({
285
+ type: 'object',
286
+ properties: {
287
+ domain_id: { type: 'string' },
288
+ status: { type: 'string' },
289
+ detail: { type: 'string' },
290
+ gates: { type: 'array', items: { type: 'object', additionalProperties: true } },
291
+ redlines: { type: 'array', items: { type: 'string' } },
292
+ truncated: { type: 'boolean' },
293
+ },
294
+ additionalProperties: false,
295
+ }),
296
+ async execute(args) {
297
+ const domain = getDomain(store, args.domain_id)
298
+ if (!domain) throw new Error(`domain_detail: no domain ${JSON.stringify(args.domain_id)}`)
299
+ const full = String(domain.detailText ?? '')
300
+ const detailText = full.slice(0, detailChars)
301
+ return {
302
+ domain_id: domain.domainId,
303
+ status: domain.status,
304
+ detail: detailText,
305
+ gates: domain.gates.slice(0, 10),
306
+ redlines: domain.redlines.slice(0, 20),
307
+ truncated: full.length > detailText.length,
308
+ }
309
+ },
310
+ }
311
+
312
+ return [activate, deactivate, detail, buildGateTool({ store, state, config }), buildDomainDraftTool({ store, config })]
313
+ }
314
+
315
+ /**
316
+ * `domain_draft`: the model may write a pack, but only as a draft.
317
+ *
318
+ * Exposed because the six-class channel can notice a vertical ("this workspace is a
319
+ * 2D game engine project") that nobody has a pack for, and handing that observation
320
+ * to a human as a reviewable draft is more useful than dropping it. The tool cannot
321
+ * make anything injected: `draftDomain` forces `draft`, refuses to overwrite an
322
+ * approved pack, and requires a source a person can check.
323
+ */
324
+ export function buildDomainDraftTool({ store, config = {} } = {}) {
325
+ return {
326
+ name: 'domain_draft',
327
+ description: 'Save a DRAFT for a vertical domain pack (background rules for a kind of work: games, study, '
328
+ + 'modelling, …). Use it when you notice a repeatable domain whose knowledge nobody has written down. '
329
+ + 'A draft is NEVER injected: a human must review and approve it. Every draft needs at least one source '
330
+ + '(session id, url, or document title) so the claims can be checked.',
331
+ parameters: {
332
+ type: 'object',
333
+ properties: {
334
+ domain_id: { type: 'string', description: 'Short lowercase id, e.g. "godot-2d". 2-32 chars of [a-z0-9_-].' },
335
+ name: { type: 'string', description: 'Human-readable name.' },
336
+ index_text: { type: 'string', description: 'The ≤600-character index that would be injected once approved: what it is, when it applies, the red lines.' },
337
+ detail_text: { type: 'string', description: 'Longer detail read on demand through domain_detail. Not injected.' },
338
+ keywords: { type: 'array', items: { type: 'string' }, description: 'Words that suggest this domain.' },
339
+ path_globs: { type: 'array', items: { type: 'string' }, description: 'Path fragments that suggest this domain (e.g. "godot", "games").' },
340
+ file_markers: { type: 'array', items: { type: 'string' }, description: 'Literal relative marker files (e.g. "project.godot"). They are checked for existence, not globbed.' },
341
+ redlines: { type: 'array', items: { type: 'string' }, description: 'What must not be done in this domain.' },
342
+ sources: {
343
+ type: 'array',
344
+ description: 'At least one. The session id or document each rule came from.',
345
+ items: {
346
+ type: 'object',
347
+ properties: {
348
+ title: { type: 'string' },
349
+ url: { type: 'string' },
350
+ quote: { type: 'string', description: 'The sentence this rule came from, if you have it.' },
351
+ },
352
+ additionalProperties: false,
353
+ },
354
+ },
355
+ },
356
+ required: ['domain_id', 'index_text', 'sources'],
357
+ additionalProperties: false,
358
+ },
359
+ output: jsonOutput({
360
+ type: 'object',
361
+ properties: {
362
+ ok: { type: 'boolean' },
363
+ domain_id: { type: 'string' },
364
+ status: { type: 'string' },
365
+ version: { type: 'number' },
366
+ note: { type: 'string' },
367
+ },
368
+ additionalProperties: false,
369
+ }),
370
+ async execute(args) {
371
+ const result = draftDomain(store, {
372
+ domain_id: args.domain_id,
373
+ name: args.name,
374
+ index_text: args.index_text,
375
+ detail_text: args.detail_text,
376
+ keywords: args.keywords,
377
+ pathGlobs: args.path_globs,
378
+ fileMarkers: args.file_markers,
379
+ redlines: args.redlines,
380
+ sources: args.sources,
381
+ }, { maxPacks: config.maxPacks ?? DRAFT_LIMITS.maxPacks })
382
+ if (!result.ok) {
383
+ // A refusal is information, not a crash: 409 (already approved) and 429
384
+ // (shelf full) both tell the model what a human has to do next.
385
+ const error = new Error(`domain_draft: ${result.error}`)
386
+ error.code = result.status
387
+ throw error
388
+ }
389
+ return {
390
+ ok: true,
391
+ domain_id: result.domain.domainId,
392
+ status: result.domain.status,
393
+ version: result.domain.version,
394
+ note: result.note,
395
+ }
396
+ },
397
+ }
398
+ }
399
+
400
+ /**
401
+ * `domain_gate`: the only way to satisfy a gate.
402
+ *
403
+ * Deliberately takes evidence rather than a boolean: `{ satisfied: true }` would be
404
+ * a promise the model makes to itself, while a quote of 40+ characters from a page
405
+ * is a claim a human can check in the panel later. No network request is made — the
406
+ * plugin validates shape, and records what was claimed.
407
+ */
408
+ export function buildGateTool({ store, state, config = {} } = {}) {
409
+ return {
410
+ name: 'domain_gate',
411
+ description: 'Satisfy a domain gate: record that you checked a source before doing the work. '
412
+ + 'Pass the url you read and a verbatim quote (>=40 characters) from it. '
413
+ + 'Action tools stay refused until this succeeds.',
414
+ parameters: {
415
+ type: 'object',
416
+ properties: {
417
+ domain_id: { type: 'string', description: 'Pack id, e.g. "game".' },
418
+ gate_id: { type: 'string', description: 'Gate id from the pack, e.g. "engine-docs".' },
419
+ url: { type: 'string', description: 'The document you read.' },
420
+ quote: { type: 'string', description: 'At least 40 characters copied verbatim from that document.' },
421
+ verified_at: { type: 'number', description: 'Epoch ms when you checked it; defaults to now.' },
422
+ },
423
+ required: ['domain_id', 'gate_id', 'url', 'quote'],
424
+ additionalProperties: false,
425
+ },
426
+ output: jsonOutput({
427
+ type: 'object',
428
+ properties: {
429
+ passed: { type: 'array', items: { type: 'string' } },
430
+ remaining: { type: 'array', items: { type: 'string' } },
431
+ note: { type: 'string' },
432
+ },
433
+ additionalProperties: false,
434
+ }),
435
+ async execute(args) {
436
+ const domain = getDomain(store, args.domain_id)
437
+ if (!domain) throw new Error(`domain_gate: no domain ${JSON.stringify(args.domain_id)}`)
438
+ if (domain.status !== 'active') {
439
+ throw new Error(`domain_gate: ${domain.domainId} is ${domain.status}; only an approved pack can have gates`)
440
+ }
441
+ const gateId = String(args.gate_id ?? '').trim()
442
+ const gate = (domain.gates ?? []).find((entry) => String(entry?.id ?? '') === gateId)
443
+ if (!gate) throw new Error(`domain_gate: ${domain.domainId} has no gate ${JSON.stringify(gateId)}`)
444
+
445
+ const evidence = {
446
+ url: String(args.url ?? ''),
447
+ quote: String(args.quote ?? ''),
448
+ verifiedAt: Number.isFinite(Number(args.verified_at)) ? Number(args.verified_at) : Date.now(),
449
+ }
450
+ const verdict = evaluateEvidence(gate, evidence, {
451
+ now: Date.now(),
452
+ maxAgeHours: config.maxAgeHours,
453
+ minQuote: config.minQuote,
454
+ })
455
+ if (!verdict.ok) throw new Error(`domain_gate: ${verdict.reason}`)
456
+
457
+ state.passed.add(gateKey(domain.domainId, gateId, domain.version))
458
+ // Recompute what is still open so the guard and the notice agree immediately.
459
+ const stillOpen = (state.openGates ?? []).filter((entry) => !(entry.domainId === domain.domainId && entry.gateId === gateId))
460
+ state.openGates = stillOpen
461
+ logDomainEvent(store, domain.domainId, 'gate_pass', {
462
+ gateId,
463
+ quoteLength: evidence.quote.length,
464
+ // The URL is kept short and the quote is not stored: the point is the
465
+ // claim's shape and its auditability, not a copy of someone's browsing.
466
+ url: evidence.url.slice(0, 200),
467
+ })
468
+ try { touchDomain(store, domain.domainId) } catch { /* advisory */ }
469
+
470
+ return {
471
+ passed: [`${domain.domainId}/${gateId}`],
472
+ remaining: stillOpen.map((entry) => `${entry.domainId}/${entry.gateId}`),
473
+ note: stillOpen.length === 0
474
+ ? 'all gates satisfied; you can retry the action tool now'
475
+ : 'more gates are still open; satisfy them before the action tool',
476
+ }
477
+ },
478
+ }
479
+ }
480
+
481
+ /** Register on a tools service; returns one disposer for all four. */
482
+ export function registerDomainTools(tools, options) {
483
+ if (!tools || typeof tools.register !== 'function') throw new Error('tools service is not available')
484
+ const disposers = buildDomainTools(options).map((tool) => tools.register(tool))
485
+ return () => {
486
+ for (const dispose of disposers) {
487
+ try { dispose() } catch { /* already gone */ }
488
+ }
489
+ }
490
+ }