dsh-memory-bond 0.0.0-stage → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (126) hide show
  1. package/CHANGELOG.md +10 -0
  2. package/LICENSE +21 -0
  3. package/README.md +181 -2
  4. package/README.zh-CN.md +180 -0
  5. package/SECURITY.md +29 -0
  6. package/client/memory-icon.svg +21 -0
  7. package/cordis.patch.yml +3 -0
  8. package/dist/audit.js +286 -0
  9. package/dist/automatic.js +16 -0
  10. package/dist/cache.js +40 -0
  11. package/dist/client.js +2035 -0
  12. package/dist/command-scope.js +123 -0
  13. package/dist/commands.js +156 -0
  14. package/dist/consolidation-store.js +357 -0
  15. package/dist/consolidation.js +182 -0
  16. package/dist/domain.js +245 -0
  17. package/dist/encoder.js +138 -0
  18. package/dist/export-files.js +161 -0
  19. package/dist/file-import-store.js +120 -0
  20. package/dist/file-import.js +265 -0
  21. package/dist/foreground-attempts.js +91 -0
  22. package/dist/guidance.js +242 -0
  23. package/dist/host.js +19 -0
  24. package/dist/index-policy.js +191 -0
  25. package/dist/index.js +349 -0
  26. package/dist/knowledge-hooks.js +398 -0
  27. package/dist/knowledge.js +359 -0
  28. package/dist/maintenance-episodes.js +73 -0
  29. package/dist/maintenance-import.js +92 -0
  30. package/dist/maintenance-store.js +738 -0
  31. package/dist/maintenance.js +376 -0
  32. package/dist/model-review.js +16 -0
  33. package/dist/personal.js +60 -0
  34. package/dist/policy.js +382 -0
  35. package/dist/prompt-copy.js +93 -0
  36. package/dist/proposal-receipts.js +70 -0
  37. package/dist/proposal-review.js +656 -0
  38. package/dist/propose-contract.js +38 -0
  39. package/dist/question-answers.js +176 -0
  40. package/dist/retrieval.js +126 -0
  41. package/dist/scope-narrowing.js +49 -0
  42. package/dist/search-index.js +164 -0
  43. package/dist/search-words.js +5 -0
  44. package/dist/semantic.js +157 -0
  45. package/dist/service.js +1473 -0
  46. package/dist/sharing.js +289 -0
  47. package/dist/sources.js +149 -0
  48. package/dist/store.js +1578 -0
  49. package/dist/tool-experience.js +87 -0
  50. package/dist/turn-review-store.js +159 -0
  51. package/dist/turn-review.js +459 -0
  52. package/dist/ui.js +346 -0
  53. package/dist/vector-index.js +232 -0
  54. package/docs/architecture.zh-CN.md +52 -0
  55. package/docs/benchmark.zh-CN.md +60 -0
  56. package/docs/benchmarks/repository-tasks.json +5355 -0
  57. package/docs/images/bond-memory-principle-en.svg +644 -0
  58. package/docs/images/bond-memory-principle-zh.svg +644 -0
  59. package/docs/images/bond-memory-principle.drawio +644 -0
  60. package/docs/images/memory-settings-en.png +0 -0
  61. package/docs/images/memory-settings-zh.png +0 -0
  62. package/docs/images/memory-turn-recalled-en.png +0 -0
  63. package/docs/images/memory-turn-recalled-zh.png +0 -0
  64. package/docs/images/memory-turn-saved-en.png +0 -0
  65. package/docs/images/memory-turn-saved-zh.png +0 -0
  66. package/docs/media/memory-bond-name-en.gif +0 -0
  67. package/docs/media/memory-bond-name-en.mp4 +0 -0
  68. package/docs/media/memory-bond-name-zh.gif +0 -0
  69. package/docs/media/memory-bond-name-zh.mp4 +0 -0
  70. package/locale/detail.en.md +13 -0
  71. package/locale/detail.zh.md +13 -0
  72. package/locale/en.json +345 -0
  73. package/locale/zh.json +345 -0
  74. package/native/embeddings/NOTICE.md +12 -0
  75. package/package.json +117 -4
  76. package/scripts/benchmark-bond.mjs +72 -0
  77. package/scripts/benchmark-conditions.mjs +144 -0
  78. package/scripts/benchmark-example.mjs +37 -0
  79. package/scripts/benchmark-scale.mjs +119 -0
  80. package/scripts/benchmark-scenarios.mjs +57 -0
  81. package/scripts/benchmark-tasks.mjs +244 -0
  82. package/src/audit.ts +286 -0
  83. package/src/automatic.ts +21 -0
  84. package/src/cache.ts +38 -0
  85. package/src/command-scope.ts +125 -0
  86. package/src/commands.ts +159 -0
  87. package/src/consolidation-store.ts +350 -0
  88. package/src/consolidation.ts +176 -0
  89. package/src/domain.ts +254 -0
  90. package/src/encoder.ts +142 -0
  91. package/src/export-files.ts +178 -0
  92. package/src/file-import-store.ts +139 -0
  93. package/src/file-import.ts +256 -0
  94. package/src/foreground-attempts.ts +97 -0
  95. package/src/guidance.ts +265 -0
  96. package/src/host.ts +119 -0
  97. package/src/index-policy.ts +231 -0
  98. package/src/index.ts +333 -0
  99. package/src/knowledge-hooks.ts +456 -0
  100. package/src/knowledge.ts +432 -0
  101. package/src/maintenance-episodes.ts +76 -0
  102. package/src/maintenance-import.ts +107 -0
  103. package/src/maintenance-store.ts +868 -0
  104. package/src/maintenance.ts +380 -0
  105. package/src/model-review.ts +27 -0
  106. package/src/personal.ts +68 -0
  107. package/src/policy.ts +508 -0
  108. package/src/prompt-copy.ts +99 -0
  109. package/src/proposal-receipts.ts +59 -0
  110. package/src/proposal-review.ts +614 -0
  111. package/src/propose-contract.ts +39 -0
  112. package/src/question-answers.ts +181 -0
  113. package/src/retrieval.ts +133 -0
  114. package/src/scope-narrowing.ts +58 -0
  115. package/src/search-index.ts +177 -0
  116. package/src/search-words.ts +6 -0
  117. package/src/semantic.ts +178 -0
  118. package/src/service.ts +1488 -0
  119. package/src/sharing.ts +349 -0
  120. package/src/sources.ts +150 -0
  121. package/src/store.ts +1829 -0
  122. package/src/tool-experience.ts +93 -0
  123. package/src/turn-review-store.ts +158 -0
  124. package/src/turn-review.ts +418 -0
  125. package/src/ui.ts +385 -0
  126. package/src/vector-index.ts +228 -0
package/dist/index.js ADDED
@@ -0,0 +1,349 @@
1
+ import { createRequire } from 'node:module';
2
+ import { isAbsolute } from 'node:path';
3
+ import { ProjectMemory, indexName, publicRule } from "./service.js";
4
+ import { indexLimits } from "./policy.js";
5
+ import { prompts } from "./prompt-copy.js";
6
+ import { proposalContract } from "./propose-contract.js";
7
+ import { reviewProposals } from "./proposal-review.js";
8
+ import { registerMaintenance } from "./maintenance.js";
9
+ import { registerKnowledge } from "./knowledge.js";
10
+ import { newSearchTrace } from "./retrieval.js";
11
+ import { registerAudit, searchContext, searchRowDigest } from "./audit.js";
12
+ import { registerTurnReview } from "./turn-review.js";
13
+ import { registerConsolidation } from "./consolidation.js";
14
+ import { registerCommands, parseRef } from "./commands.js";
15
+ import { registerUI } from "./ui.js";
16
+ import { StoreError } from "./store.js";
17
+ import { registerConditionalTool } from "./host.js";
18
+ export const name = 'dsh-memory-bond';
19
+ export const inject = ['agents', 'workingDirectory', 'tools', 'systemPrompt', 'llm'];
20
+ const output = {
21
+ schema: { type: 'string' },
22
+ render: (_args, value) => [{ type: 'text', text: value }],
23
+ };
24
+ const parameters = (properties, required) => ({
25
+ type: 'object',
26
+ properties,
27
+ required,
28
+ additionalProperties: false,
29
+ });
30
+ const string = { type: 'string' };
31
+ // The assistant uses the same scope names to search, read and write a memory.
32
+ const modelRule = (row) => row.scope === 'profile' ? { ...row, scope: 'global' } : row;
33
+ /**
34
+ * Map a tool execution failure to the short status code sent back to the model. Never send
35
+ * filesystem paths or driver diagnostics in a model result. StoreError's own `.code` is the clean
36
+ * short code; its `.message` is often a separate, human-readable (and sometimes Chinese)
37
+ * explanation, so check it first -- matching ui.ts's dispatch(), which reads the same error type
38
+ * the same way. A plain Error's `.message` is used as-is only when it already looks like a code.
39
+ */
40
+ export function toolErrorStatus(error) {
41
+ const code = error instanceof StoreError ? error.code : error instanceof Error ? error.message : '';
42
+ return /^[a-z_]+$/.test(code) ? code : 'storage_or_validation_error';
43
+ }
44
+ export function apply(ctx, config = {}) {
45
+ function unavailable(missing) {
46
+ ctx.logger.warn('Memory Bond needs ' + missing + '. See /project-memory status.');
47
+ ctx.inject(['commands'], (c) => c.commands.register({
48
+ name: 'project-memory', description: 'Report host compatibility', recordInput: false, input: { hint: 'status' },
49
+ async handler({ rawInput }) {
50
+ return { kind: rawInput.trim() === 'status' ? 'success' : 'error',
51
+ text: JSON.stringify({ status: 'incompatible_host', missing }) };
52
+ },
53
+ }));
54
+ }
55
+ const profileContext = ctx.get('profileContext');
56
+ const profile = profileContext?.dir;
57
+ if (typeof profile !== 'string' || !isAbsolute(profile)) {
58
+ return unavailable('absolute profileContext.dir');
59
+ }
60
+ let isAgentLoopRequest;
61
+ let reviewSdk;
62
+ let appendPluginRecord;
63
+ // installAnchor is the one guarantee that hostRequire() resolves the SAME loaded copy of these
64
+ // host packages the running agent loop/session code uses (module-private state like
65
+ // isAgentLoopRequest's WeakSet only works against that exact instance). Falling back to this
66
+ // plugin's own file when it is absent can silently resolve a different, wrong copy instead of
67
+ // failing loudly - worse than disabling the plugin, so this composition is declined outright.
68
+ if (!profileContext?.installAnchor) {
69
+ return unavailable('profileContext.installAnchor');
70
+ }
71
+ if (typeof ctx.agents.get !== 'function')
72
+ return unavailable('agents.get');
73
+ if (typeof ctx.workingDirectory.get !== 'function')
74
+ return unavailable('workingDirectory.get');
75
+ if (typeof ctx.tools.register !== 'function' || typeof ctx.tools.guard !== 'function')
76
+ return unavailable('tools.register and tools.guard');
77
+ if (typeof ctx.systemPrompt.section !== 'function' || typeof ctx.systemPrompt.context !== 'function')
78
+ return unavailable('systemPrompt.section and systemPrompt.context');
79
+ try {
80
+ const hostRequire = createRequire(profileContext.installAnchor);
81
+ const llm = hostRequire('@deepseek-ai/dsh-llm');
82
+ if (typeof llm?.isAgentLoopRequest !== 'function')
83
+ return unavailable('@deepseek-ai/dsh-llm.isAgentLoopRequest');
84
+ isAgentLoopRequest = llm.isAgentLoopRequest;
85
+ if (typeof llm.createUserMessage === 'function' && typeof llm.BlockAssembler === 'function' &&
86
+ typeof llm.BlockAssembler.prototype?.push === 'function' && typeof llm.BlockAssembler.prototype?.blocks === 'function')
87
+ reviewSdk = llm;
88
+ const sessions = hostRequire('@deepseek-ai/dsh-session');
89
+ if (typeof sessions?.appendPluginRecord !== 'function')
90
+ return unavailable('@deepseek-ai/dsh-session.appendPluginRecord');
91
+ appendPluginRecord = sessions.appendPluginRecord;
92
+ }
93
+ catch {
94
+ return unavailable('@deepseek-ai/dsh-llm and @deepseek-ai/dsh-session at profileContext.installAnchor');
95
+ }
96
+ const hostIssues = reviewSdk ? [] : ['model_review_sdk_unavailable'];
97
+ if (hostIssues.length)
98
+ ctx.logger.warn('Memory Bond automatic writes and background review need the host model SDK. See /project-memory status.');
99
+ const memory = new ProjectMemory(ctx, profile, { ...config, ...indexLimits(config) }, appendPluginRecord);
100
+ ctx.on('agent/inbox/claimed', ({ agent, message, turn }) => {
101
+ try {
102
+ memory.captureTask(agent, message, turn);
103
+ }
104
+ catch { /* A failed scope read leaves the ordinary search hint available. */ }
105
+ });
106
+ memory.retrieval.vectors.start();
107
+ const stopReview = reviewSdk && registerTurnReview(memory, reviewSdk);
108
+ const stopConsolidation = reviewSdk && registerConsolidation(memory, reviewSdk);
109
+ const stopMaintenance = registerMaintenance(ctx, memory);
110
+ ctx.effect(() => async () => {
111
+ stopReview?.();
112
+ await stopConsolidation?.();
113
+ await stopMaintenance();
114
+ memory.retrieval.close();
115
+ memory.store.close();
116
+ });
117
+ // DSH may expose distinct Session proxies for tool execution and emitted events.
118
+ const timings = new Map();
119
+ function timingFor(session, call) {
120
+ let calls = timings.get(session.id);
121
+ if (!calls)
122
+ timings.set(session.id, calls = new Map());
123
+ let timing = calls.get(call);
124
+ if (!timing)
125
+ calls.set(call, timing = {});
126
+ return timing;
127
+ }
128
+ ctx.on('session/event', (session, event) => {
129
+ if (event.type === 'tool/call' && event.data.name === 'project_memory_search' && event.data.callId)
130
+ timingFor(session, event.data.callId).called = performance.now();
131
+ const callId = event.type === 'tool/result' && event.data.message?.toolCallId;
132
+ const timing = callId && timings.get(session.id)?.get(callId);
133
+ if (callId && timing) {
134
+ const calls = timings.get(session.id);
135
+ calls.delete(callId);
136
+ if (!calls.size)
137
+ timings.delete(session.id);
138
+ if (timing.start !== undefined && timing.returned !== undefined) {
139
+ const data = {
140
+ callId, ...timing.trace, executeMs: timing.returned - timing.start,
141
+ hostToExecuteMs: timing.called === undefined ? null : Math.max(0, timing.start - timing.called),
142
+ returnToHostMs: Math.max(0, performance.now() - timing.returned),
143
+ };
144
+ // Publish after the host has finished delivering the tool result to its listeners.
145
+ queueMicrotask(() => {
146
+ try {
147
+ memory.append(session, 'plugin:project-memory/search-timing', data);
148
+ }
149
+ catch {
150
+ ctx.logger.warn('本次记忆查询的耗时记录未能追加。');
151
+ }
152
+ });
153
+ }
154
+ }
155
+ if (event.type === 'turn/end')
156
+ timings.delete(session.id);
157
+ memory.capture(session, event);
158
+ });
159
+ ctx.systemPrompt.section({
160
+ name: 'project-memory:instructions',
161
+ order: 20,
162
+ interpolate: false,
163
+ text: ({ agent } = {}) => {
164
+ const copy = prompts[memory.promptLanguage(agent)];
165
+ return memory.assistantGeneration() === undefined ? copy.disabled : copy.system;
166
+ },
167
+ });
168
+ ctx.systemPrompt.context({
169
+ name: indexName,
170
+ order: 20,
171
+ interpolate: false,
172
+ text: ({ agent }) => {
173
+ // The host does not wrap a context provider's text() in a try/catch (assemble() calls it
174
+ // directly), so a store failure here must degrade to an empty contribution, not fail the
175
+ // whole prompt assembly for every provider in this step.
176
+ try {
177
+ const d = memory.domain(agent);
178
+ return d && agent ? memory.index(agent, d, true).text : '';
179
+ }
180
+ catch (error) {
181
+ ctx.logger.warn('项目记忆索引暂不可用:' + (error instanceof Error ? error.message : String(error)));
182
+ return '';
183
+ }
184
+ },
185
+ });
186
+ const { expanded, shownSearchRows, executed, blocked, wrote } = registerAudit(memory, isAgentLoopRequest);
187
+ registerKnowledge(ctx, memory, expanded, { executed, blocked });
188
+ const emptySearches = new WeakMap();
189
+ function searchAvailable(agent, generation) {
190
+ const previous = emptySearches.get(agent);
191
+ if (!previous)
192
+ return true;
193
+ // DSH asks before every step. Only suppress reformulations while *all* accessible
194
+ // scopes are still empty; another session can add a rule or restore a withdrawal.
195
+ try {
196
+ const domain = memory.domain(agent);
197
+ if (domain && previous === searchContext(agent, domain, generation) &&
198
+ memory.scopes(agent, domain).every(scope => !memory.store.hasCurrent(scope.id)))
199
+ return false;
200
+ }
201
+ catch {
202
+ // Leave ordinary search/error handling available when the probe cannot establish emptiness.
203
+ }
204
+ emptySearches.delete(agent);
205
+ return true;
206
+ }
207
+ function tool(name, contract, run, available, visibleWithoutAgent = true) {
208
+ registerConditionalTool(ctx, {
209
+ name,
210
+ ...contract,
211
+ output,
212
+ async execute(args, exec) {
213
+ if (!exec.agent)
214
+ return JSON.stringify({ status: 'unavailable' });
215
+ try {
216
+ const generation = memory.assistantGeneration();
217
+ if (generation === undefined)
218
+ return JSON.stringify({ status: 'memory_disabled' });
219
+ const result = await run(args, exec.agent, exec.callId, generation, exec.signal);
220
+ return JSON.stringify(memory.assistantGeneration() === generation ? result : { status: 'memory_disabled' });
221
+ }
222
+ catch (error) {
223
+ return JSON.stringify({ status: toolErrorStatus(error) });
224
+ }
225
+ },
226
+ }, agent => {
227
+ const generation = memory.assistantGeneration();
228
+ return generation !== undefined && (!available || (agent ? available(agent, generation) : visibleWithoutAgent));
229
+ });
230
+ }
231
+ const toolLanguage = memory.promptLanguage();
232
+ const toolCopy = prompts[toolLanguage];
233
+ tool('project_memory_propose', proposalContract(toolLanguage), async (args, agent, call, generation, signal) => {
234
+ const initial = memory.domain(agent);
235
+ const receipt = await reviewProposals(memory, agent, args, reviewSdk, signal);
236
+ const current = memory.domain(agent);
237
+ if (memory.assistantGeneration() !== generation)
238
+ return { status: 'memory_disabled' };
239
+ if (!initial || !current || current.id !== initial.id || current.root !== initial.root || current.cwd !== initial.cwd ||
240
+ ctx.agents.get(agent.id) !== agent)
241
+ return { status: 'unavailable' };
242
+ try {
243
+ wrote(agent, current, call, receipt.results);
244
+ }
245
+ catch (error) {
246
+ ctx.logger.warn('未能记录本次记忆回执的投递凭据:' + String(error));
247
+ }
248
+ return receipt;
249
+ });
250
+ tool('project_memory_experience', {
251
+ description: toolCopy.experience,
252
+ parameters: parameters({ callId: string, topic: string, action: string }, ['callId', 'topic', 'action']),
253
+ }, (args, agent, _call, generation) => memory.proposeExperience(agent, args, generation), (agent, generation) => {
254
+ try {
255
+ return !!memory.experienceSource(agent, generation);
256
+ }
257
+ catch {
258
+ return false;
259
+ }
260
+ }, false);
261
+ tool('project_memory_search', {
262
+ description: toolCopy.search,
263
+ parameters: parameters({ query: string, alternateQuery: string, subject: string, topic: string, limit: { type: 'integer', minimum: 1, maximum: 40 },
264
+ scope: { type: 'string', enum: ['global', 'project'] },
265
+ mode: { type: 'string', enum: ['hybrid', 'keyword', 'semantic'] } }, ['query']),
266
+ }, async (args, agent, call, generation) => {
267
+ const timing = timingFor(agent.session, call);
268
+ timing.start = performance.now();
269
+ const trace = timing.trace = newSearchTrace();
270
+ try {
271
+ const d = memory.domain(agent);
272
+ if (!d)
273
+ return { rules: [] };
274
+ const context = searchContext(agent, d, generation);
275
+ const { subject, topic, scope, limit = 6 } = args;
276
+ if (typeof limit !== 'number' || !Number.isInteger(limit) || limit < 1 || limit > 40)
277
+ throw new StoreError('invalid_input');
278
+ if (scope !== undefined && scope !== 'global' && scope !== 'project')
279
+ throw new StoreError('invalid_input');
280
+ const rules = await memory.search(agent, args.query, args.mode, { subject, topic, scope: scope === 'global' ? 'profile' : scope, alternateQuery: args.alternateQuery }, trace);
281
+ if (memory.assistantGeneration() !== generation || memory.domain(agent)?.id !== d.id)
282
+ return { rules: [] };
283
+ const rows = rules.slice(0, limit);
284
+ if (trace.match === 'empty_scope' && context)
285
+ emptySearches.set(agent, context);
286
+ const seen = shownSearchRows(agent, context);
287
+ let noNewEvidence = Boolean(seen);
288
+ const results = rows.map(rule => {
289
+ const full = modelRule(publicRule(rule));
290
+ if (!seen?.has(rule.id) || seen.get(rule.id) !== searchRowDigest(full)) {
291
+ noNewEvidence = false;
292
+ return full;
293
+ }
294
+ return trace.match === 'exact_id' ? full : { id: rule.id, rev: rule.rev, alreadyShown: true };
295
+ });
296
+ expanded(agent, d, call, rows, context);
297
+ memory.store.audit(d.id, agent.id, 'search', { call, agent: agent.id, outcome: rows.length });
298
+ return { rules: results, match: trace.match, coverage: trace.coverage,
299
+ ...(rules.length > limit && { totalMatches: rules.length }),
300
+ ...(trace.match === 'empty_scope' && { guidance: prompts[memory.promptLanguage(agent)].empty }),
301
+ ...(noNewEvidence ? { progress: 'no_new_evidence' } : {}) };
302
+ }
303
+ finally {
304
+ timing.returned = performance.now();
305
+ }
306
+ }, searchAvailable);
307
+ function readTool(name, description) {
308
+ const source = name === 'project_memory_source';
309
+ const contract = { description, parameters: parameters({ id: string, rev: { type: 'integer' } }, ['id']) };
310
+ tool(name, contract, async (args, agent, call, generation) => {
311
+ const ref = typeof args.id === 'string' && parseRef(args.id);
312
+ if (!ref ||
313
+ (args.rev !== undefined &&
314
+ (!Number.isSafeInteger(args.rev) ||
315
+ Number(args.rev) < 1 ||
316
+ (ref.rev !== undefined && ref.rev !== args.rev))))
317
+ return { status: 'not_found' };
318
+ const initial = memory.domain(agent);
319
+ if (!initial)
320
+ return { status: 'not_found' };
321
+ const row = await memory.read(agent, ref.id, ref.rev ?? args.rev, source);
322
+ if (memory.assistantGeneration() !== generation)
323
+ return { status: 'memory_disabled' };
324
+ const d = memory.domain(agent);
325
+ if (!d || d.id !== initial.id)
326
+ return { status: 'not_found' };
327
+ if ('id' in row && row.id !== undefined) {
328
+ const owner = memory.owner(agent, d, row.id);
329
+ const current = owner && memory.current(owner, row.id, row.rev);
330
+ if (!current || !memory.canPublishEvidence(current, row))
331
+ return { status: 'not_found' };
332
+ if (!source && 'action' in row)
333
+ expanded(agent, d, call, [row]);
334
+ memory.store.audit(owner.id, agent.id, source ? 'expand' : 'read', {
335
+ id: row.id,
336
+ rev: row.rev,
337
+ call,
338
+ agent: agent.id,
339
+ });
340
+ }
341
+ return 'scope' in row ? modelRule(row) : row;
342
+ });
343
+ }
344
+ readTool('project_memory_read', toolCopy.read);
345
+ readTool('project_memory_source', toolCopy.source);
346
+ ctx.inject(['commands'], (c) => registerCommands(c, memory, hostIssues));
347
+ registerUI(ctx, memory);
348
+ ctx.provide('projectMemoryReady', true);
349
+ }