dsh-memory-bond 0.3.0-beta.0 → 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 (145) hide show
  1. package/CHANGELOG.md +6 -7
  2. package/README.md +125 -91
  3. package/README.zh-CN.md +122 -92
  4. package/SECURITY.md +29 -0
  5. package/dist/audit.js +155 -80
  6. package/dist/automatic.js +10 -2
  7. package/dist/client.js +2035 -0
  8. package/dist/command-scope.js +4 -4
  9. package/dist/commands.js +15 -9
  10. package/dist/consolidation-store.js +87 -20
  11. package/dist/consolidation.js +2 -6
  12. package/dist/domain.js +8 -4
  13. package/dist/encoder.js +46 -5
  14. package/dist/file-import-store.js +120 -0
  15. package/dist/file-import.js +265 -0
  16. package/dist/foreground-attempts.js +91 -0
  17. package/dist/guidance.js +133 -92
  18. package/dist/host.js +13 -0
  19. package/dist/index-policy.js +91 -48
  20. package/dist/index.js +102 -40
  21. package/dist/knowledge-hooks.js +70 -27
  22. package/dist/knowledge.js +2 -3
  23. package/dist/maintenance-store.js +38 -4
  24. package/dist/maintenance.js +29 -5
  25. package/dist/personal.js +37 -0
  26. package/dist/policy.js +45 -47
  27. package/dist/prompt-copy.js +93 -0
  28. package/dist/proposal-receipts.js +70 -0
  29. package/dist/proposal-review.js +656 -0
  30. package/dist/propose-contract.js +32 -36
  31. package/dist/question-answers.js +86 -29
  32. package/dist/retrieval.js +25 -8
  33. package/dist/scope-narrowing.js +49 -0
  34. package/dist/search-index.js +93 -13
  35. package/dist/semantic.js +69 -207
  36. package/dist/service.js +633 -204
  37. package/dist/sharing.js +7 -13
  38. package/dist/sources.js +28 -3
  39. package/dist/store.js +432 -96
  40. package/dist/tool-experience.js +87 -0
  41. package/dist/turn-review-store.js +83 -16
  42. package/dist/turn-review.js +155 -59
  43. package/dist/ui.js +128 -26
  44. package/dist/vector-index.js +69 -33
  45. package/docs/architecture.zh-CN.md +52 -0
  46. package/docs/benchmark.zh-CN.md +60 -0
  47. package/docs/benchmarks/repository-tasks.json +5355 -0
  48. package/docs/images/bond-memory-principle-en.svg +644 -0
  49. package/docs/images/bond-memory-principle-zh.svg +644 -0
  50. package/docs/images/bond-memory-principle.drawio +644 -0
  51. package/docs/images/memory-settings-en.png +0 -0
  52. package/docs/images/memory-settings-zh.png +0 -0
  53. package/docs/images/memory-turn-recalled-en.png +0 -0
  54. package/docs/images/memory-turn-recalled-zh.png +0 -0
  55. package/docs/images/memory-turn-saved-en.png +0 -0
  56. package/docs/images/memory-turn-saved-zh.png +0 -0
  57. package/docs/media/memory-bond-name-en.gif +0 -0
  58. package/docs/media/memory-bond-name-en.mp4 +0 -0
  59. package/docs/media/memory-bond-name-zh.gif +0 -0
  60. package/docs/media/memory-bond-name-zh.mp4 +0 -0
  61. package/locale/detail.en.md +5 -1
  62. package/locale/detail.zh.md +5 -1
  63. package/locale/en.json +338 -0
  64. package/locale/zh.json +338 -0
  65. package/native/embeddings/NOTICE.md +2 -2
  66. package/package.json +39 -19
  67. package/scripts/benchmark-bond.mjs +72 -0
  68. package/scripts/benchmark-conditions.mjs +144 -0
  69. package/scripts/benchmark-example.mjs +37 -0
  70. package/scripts/benchmark-scale.mjs +119 -0
  71. package/scripts/benchmark-scenarios.mjs +57 -0
  72. package/scripts/benchmark-tasks.mjs +244 -0
  73. package/src/audit.ts +144 -85
  74. package/src/automatic.ts +12 -2
  75. package/src/command-scope.ts +4 -4
  76. package/src/commands.ts +12 -8
  77. package/src/consolidation-store.ts +80 -18
  78. package/src/consolidation.ts +2 -6
  79. package/src/domain.ts +9 -4
  80. package/src/encoder.ts +46 -6
  81. package/src/file-import-store.ts +139 -0
  82. package/src/file-import.ts +256 -0
  83. package/src/foreground-attempts.ts +97 -0
  84. package/src/guidance.ts +138 -102
  85. package/src/host.ts +22 -2
  86. package/src/index-policy.ts +93 -46
  87. package/src/index.ts +87 -43
  88. package/src/knowledge-hooks.ts +71 -29
  89. package/src/knowledge.ts +2 -3
  90. package/src/maintenance-store.ts +37 -4
  91. package/src/maintenance.ts +25 -5
  92. package/src/personal.ts +36 -0
  93. package/src/policy.ts +55 -52
  94. package/src/prompt-copy.ts +99 -0
  95. package/src/proposal-receipts.ts +59 -0
  96. package/src/proposal-review.ts +614 -0
  97. package/src/propose-contract.ts +31 -35
  98. package/src/question-answers.ts +99 -29
  99. package/src/retrieval.ts +26 -9
  100. package/src/scope-narrowing.ts +58 -0
  101. package/src/search-index.ts +94 -14
  102. package/src/semantic.ts +67 -188
  103. package/src/service.ts +595 -210
  104. package/src/sharing.ts +7 -14
  105. package/src/sources.ts +26 -4
  106. package/src/store.ts +434 -97
  107. package/src/tool-experience.ts +93 -0
  108. package/src/turn-review-store.ts +86 -15
  109. package/src/turn-review.ts +142 -60
  110. package/src/ui.ts +122 -27
  111. package/src/vector-index.ts +57 -29
  112. package/client/index.js +0 -1186
  113. package/design/dsh-memory-plugin-design.md +0 -46
  114. package/design/dsh-memory-plugin-evaluation.md +0 -135
  115. package/design/evaluations/locomo-conv-26-2026-12-03.json +0 -252
  116. package/design/evaluations/locomo-conv-26-paired-2026-12-03.json +0 -549
  117. package/design/evaluations/locomo-conv-26-write-replay-2026-12-03.json +0 -289
  118. package/design/evaluations/project-memory-tasks-2026-12-03.json +0 -1059
  119. package/design/memory-lifecycle-consolidation.excalidraw +0 -1212
  120. package/design/memory-lifecycle-consolidation.mobile.excalidraw +0 -1083
  121. package/design/memory-lifecycle-consolidation.mobile.svg +0 -2
  122. package/design/memory-lifecycle-consolidation.mobile.zh-CN.excalidraw +0 -1083
  123. package/design/memory-lifecycle-consolidation.mobile.zh-CN.svg +0 -94
  124. package/design/memory-lifecycle-consolidation.svg +0 -2
  125. package/design/memory-lifecycle-consolidation.zh-CN.excalidraw +0 -1212
  126. package/design/memory-lifecycle-consolidation.zh-CN.svg +0 -94
  127. package/design/memory-lifecycle.excalidraw +0 -2105
  128. package/design/memory-lifecycle.mobile.excalidraw +0 -1896
  129. package/design/memory-lifecycle.mobile.svg +0 -95
  130. package/design/memory-lifecycle.mobile.zh-CN.excalidraw +0 -1896
  131. package/design/memory-lifecycle.mobile.zh-CN.svg +0 -97
  132. package/design/memory-lifecycle.svg +0 -95
  133. package/design/memory-lifecycle.zh-CN.excalidraw +0 -2105
  134. package/design/memory-lifecycle.zh-CN.svg +0 -97
  135. package/native/embeddings/LICENSE +0 -21
  136. package/native/embeddings/en/model.onnx +0 -4
  137. package/native/embeddings/en/vocab.txt +0 -30522
  138. package/native/embeddings/runtime/LICENSE +0 -21
  139. package/native/embeddings/runtime/ThirdPartyNotices.txt +0 -6156
  140. package/native/embeddings/runtime/ort-wasm-simd-threaded.mjs +0 -70
  141. package/native/embeddings/runtime/ort-wasm-simd-threaded.wasm +0 -0
  142. package/native/embeddings/runtime/ort.wasm.min.mjs +0 -7
  143. package/native/embeddings/worker.mjs +0 -97
  144. package/native/embeddings/zh/model.onnx +0 -0
  145. package/native/embeddings/zh/vocab.txt +0 -21128
@@ -1,15 +1,17 @@
1
+ import { prompts } from "./prompt-copy.js";
1
2
  import { normalizeLabel } from "./personal.js";
2
3
  import { searchWords } from "./search-words.js";
3
4
  // UTF-8 byte length upper-bounds byte-BPE token count without a model tokenizer.
4
5
  export const provisionalLimits = { maxRows: 16, maxTokens: 2048 };
5
- const searchHint = '所需细节未列出时先查 project_memory_search。';
6
- const invalidation = '旧索引失效,以当前列出的条目或重新读取的结果为准。';
7
6
  const oneline = (s) => s.replace(/[\p{Cc}\p{Zl}\p{Zp}]+/gu, ' ').trim();
8
7
  // Common task framing (e.g. "run this in the repository") supplies no topic.
9
8
  const generic = new Set('这个 本仓 本项目 仓库 项目 如何 怎么 什么 哪个 一下 帮我 请问 需要 改动 运行 执行 检查 当前 使用 repo repository project run use this that please should when which changes check'.split(' '));
9
+ export function taskTerms(task) {
10
+ return [...new Set(searchWords(normalizeLabel(task.slice(0, 2048))))]
11
+ .filter(word => !generic.has(word) && (word.length > 1 || /^\p{Script=Latin}$/u.test(word))).slice(0, 48);
12
+ }
10
13
  export function taskMatcher(task) {
11
- const terms = [...new Set(searchWords(normalizeLabel(task.slice(0, 2048))))]
12
- .filter(word => word.length > 1 && !generic.has(word)).slice(0, 48);
14
+ const terms = typeof task === 'string' ? taskTerms(task) : task;
13
15
  if (!terms.length)
14
16
  return;
15
17
  const patterns = terms.sort((a, b) => b.length - a.length).map(word => {
@@ -19,39 +21,41 @@ export function taskMatcher(task) {
19
21
  return new RegExp(patterns.join('|'), 'gu');
20
22
  }
21
23
  function taskHints(candidates, matcher, keepUnmatched) {
22
- if (!matcher)
23
- return keepUnmatched ? candidates : [];
24
- // Match bounded task terms against eligible triggers. Segmenting every saved
25
- // agreement here would add a full ICU tokenization pass to each prompt assembly.
26
- return candidates.map(row => {
27
- const text = normalizeLabel([row.when, row.semanticTopic, ...(row.keywords ?? [])].filter(Boolean).join(' '));
28
- return { row, score: new Set(text.match(matcher)).size };
29
- }).filter(entry => entry.score || keepUnmatched)
30
- .sort((a, b) => b.score - a.score)
31
- .map(entry => entry.row);
24
+ const ranked = candidates.map(row => {
25
+ const lazy = row.usage !== 'proactive';
26
+ const labels = [row.semanticTopic, ...(row.keywords ?? []), ...(lazy ? [] : [row.when])];
27
+ const text = normalizeLabel(labels.filter(Boolean).join(' '));
28
+ const matches = [...new Set(matcher ? text.match(matcher) : [])];
29
+ // On-demand metadata may itself contain a value. Only echo terms already in the user's message.
30
+ const trigger = lazy ? matches.join(' ') : oneline([row.subject, row.when].filter(Boolean).join(' '));
31
+ return { row, score: matches.length, trigger };
32
+ }).filter(({ row, score, trigger }) => trigger && (score || (keepUnmatched && row.usage === 'proactive')))
33
+ .sort((a, b) => b.score - a.score || a.row.id.localeCompare(b.row.id));
34
+ const threshold = (ranked[0]?.score ?? 0) * 0.6;
35
+ return ranked.filter(entry => entry.row.usage === 'proactive' || entry.score >= threshold);
32
36
  }
33
- function render(row) {
34
- const scopes = [...row.paths, ...(row.hard?.branch ? ['分支 ' + row.hard.branch] : [])];
37
+ function render(row, language) {
38
+ const copy = prompts[language];
39
+ const scopes = [...row.paths, ...(row.hard?.branch ? [copy.branch + row.hard.branch] : [])];
40
+ const topic = oneline(row.semanticTopic ?? '');
41
+ const applicability = oneline(row.when);
35
42
  const when = [
36
- scopes.map(oneline).join('、'),
37
- oneline(row.subject ?? ''), oneline(row.when),
43
+ scopes.map(oneline).join(copy.separator),
44
+ oneline(row.subject ?? ''),
45
+ topic && !normalizeLabel(applicability).includes(normalizeLabel(topic)) ? topic : '',
46
+ applicability,
38
47
  ]
39
48
  .filter(Boolean)
40
49
  .join(' ');
41
50
  const exception = row.localException;
42
- const local = exception
43
- ? ';本机覆盖 ' +
44
- oneline(row.guidance?.path ?? '仓库指令') +
45
- ' 的默认项(' +
46
- oneline(exception.environment) +
47
- ';' +
48
- oneline(exception.scope) +
49
- ')'
50
- : '';
51
- return ((when || '长期约定') +
51
+ const path = oneline(row.guidance?.path ?? copy.repo);
52
+ const local = !exception ? '' : language === 'zh'
53
+ ? `;本机覆盖 ${path} 的默认项(${oneline(exception.environment)};${oneline(exception.scope)})`
54
+ : ` · local override of ${path} (${oneline(exception.environment)}, ${oneline(exception.scope)})`;
55
+ return ((when || copy.standing) +
52
56
  ' → ' +
53
57
  oneline(row.action) +
54
- (row.exceptions ? ';例外:' + oneline(row.exceptions) : '') +
58
+ (row.exceptions ? copy.except + oneline(row.exceptions) : '') +
55
59
  local +
56
60
  ' [' +
57
61
  row.id +
@@ -66,31 +70,44 @@ export function indexLimits(limits = {}) {
66
70
  if (!Number.isSafeInteger(maxRows) ||
67
71
  maxRows < 2 ||
68
72
  !Number.isSafeInteger(maxTokens) ||
69
- maxTokens < Buffer.byteLength(invalidation + '\n' + searchHint))
73
+ maxTokens < Math.max(...Object.values(prompts).map(copy => Buffer.byteLength(copy.invalid + '\n' + copy.lookup))))
70
74
  throw new Error('invalid_index_budget');
71
75
  if (limits.overflowHints !== undefined && typeof limits.overflowHints !== 'boolean')
72
76
  throw new Error('invalid_index_budget');
73
77
  return { maxRows, maxTokens, overflowHints: limits.overflowHints };
74
78
  }
75
- export function buildIndex(rows, revokedIds, limits = {}, currentTask) {
79
+ export function buildIndex(rows, revokedIds, limits = {}, currentTask, language = 'zh',
80
+ // Rows whose eligibility can change this prompt when other rows are omitted.
81
+ recheck) {
82
+ const copy = prompts[language];
83
+ const searchHint = copy.lookup;
76
84
  const { maxRows, maxTokens, overflowHints } = indexLimits(limits);
77
85
  const fits = (lines) => lines.length <= maxRows && Buffer.byteLength(lines.join('\n')) <= maxTokens;
78
86
  const included = [], overflow = [];
79
87
  const onDemand = rows.filter(row => row.usage !== 'proactive' || row.sensitive);
80
88
  const lazy = new Set(onDemand);
81
89
  overflow.push(...onDemand);
82
- let lines = [...new Set(revokedIds)].sort().map((id) => '[' + id + '] 已撤回');
90
+ let lines = [...new Set(revokedIds)].sort().map((id) => '[' + id + '] ' + copy.withdrawn);
83
91
  if (!fits([...lines, ...(rows.length ? [searchHint] : [])]) && lines.length)
84
- lines = [invalidation];
92
+ lines = [copy.invalid];
85
93
  if (!fits(lines))
86
94
  return { text: '', included, overflow: [...rows] };
87
95
  const groups = new Map();
96
+ let proactiveCount = 0;
88
97
  for (const row of rows) {
89
98
  if (lazy.has(row))
90
99
  continue;
100
+ // One more than the row budget proves the complete index cannot fit, even
101
+ // if all remaining unexamined rules have become inapplicable.
102
+ if (++proactiveCount <= maxRows + 1)
103
+ recheck?.add(row);
91
104
  const group = groups.get(row.familyId);
92
- if (group)
105
+ if (group) {
106
+ // Removing a variant can change its family's priority or make it fit.
107
+ recheck?.add(group[0]);
108
+ recheck?.add(row);
93
109
  group.push(row);
110
+ }
94
111
  else
95
112
  groups.set(row.familyId, [row]);
96
113
  }
@@ -100,19 +117,37 @@ export function buildIndex(rows, revokedIds, limits = {}, currentTask) {
100
117
  group: group.sort((a, b) => a.id.localeCompare(b.id)),
101
118
  pinned: group.some((rule) => rule.pinned),
102
119
  confirmed: group.reduce((latest, rule) => Math.max(latest, rule.confirmedAt), 0),
120
+ relevance: 0,
103
121
  }))
104
122
  .sort((a, b) => Number(b.pinned) - Number(a.pinned) ||
105
123
  b.confirmed - a.confirmed ||
106
124
  a.family.localeCompare(b.family));
107
- const all = ordered.flatMap((entry) => entry.group);
108
- const complete = [...lines, ...all.map(render), ...(onDemand.length ? [searchHint] : [])];
109
- if (fits(complete)) {
110
- return { text: complete.join('\n'), included: all, overflow };
125
+ if (!onDemand.length && lines.length + proactiveCount <= maxRows) {
126
+ const all = ordered.flatMap(entry => entry.group);
127
+ const complete = [...lines, ...all.map(row => render(row, language))];
128
+ if (fits(complete))
129
+ return { text: complete.join('\n'), included: all, overflow };
130
+ }
131
+ const matcher = currentTask?.();
132
+ // When all full agreements fit, keep the stable prompt order across requests.
133
+ // Under pressure, reserve the remaining room for the current task before recency.
134
+ if (matcher && (lines.length + proactiveCount + 1 > maxRows ||
135
+ !fits([...lines, ...ordered.flatMap(({ group }) => group.map(row => render(row, language))), searchHint]))) {
136
+ for (const entry of ordered) {
137
+ for (const row of entry.group) {
138
+ const labels = [row.subject, row.semanticTopic, ...(row.keywords ?? []), row.when, ...row.paths];
139
+ const matched = new Set(normalizeLabel(labels.filter(Boolean).join(' ')).match(matcher) ?? []);
140
+ entry.relevance = Math.max(entry.relevance, matched.size);
141
+ }
142
+ }
143
+ ordered.sort((a, b) => Number(b.pinned) - Number(a.pinned) || b.relevance - a.relevance ||
144
+ b.confirmed - a.confirmed || a.family.localeCompare(b.family));
111
145
  }
112
- const hintCandidates = [];
146
+ const hintCandidates = overflowHints === false ? [] :
147
+ onDemand.filter(row => !row.sensitive && !row.localException && row.semanticTopic);
113
148
  for (const { group } of ordered) {
114
- const candidates = group.map(render);
115
- if (fits([...lines, ...candidates, searchHint])) {
149
+ const candidates = lines.length + group.length + 1 <= maxRows ? group.map(row => render(row, language)) : undefined;
150
+ if (candidates && fits([...lines, ...candidates, searchHint])) {
116
151
  included.push(...group);
117
152
  lines.push(...candidates);
118
153
  }
@@ -128,13 +163,14 @@ export function buildIndex(rows, revokedIds, limits = {}, currentTask) {
128
163
  const hints = [];
129
164
  let lookup = searchHint;
130
165
  const candidates = hintCandidates.length
131
- ? taskHints(hintCandidates, currentTask?.(), overflowHints === true) : [];
132
- for (const row of candidates) {
133
- const trigger = oneline([row.subject, row.when].filter(Boolean).join(' '));
134
- if (!trigger)
135
- continue;
136
- const hint = trigger + ' [' + row.id + '@' + row.rev + ']';
137
- const withHint = '按场景用 project_memory_read 查阅 ' + [...hints, hint].join('、') + '。' + searchHint;
166
+ ? taskHints(hintCandidates, matcher, overflowHints === true) : [];
167
+ for (const { row, trigger } of candidates) {
168
+ // Even a skipped, oversized hint may set the relevance cutoff for later hints.
169
+ recheck?.add(row);
170
+ // A user-authored trigger can itself quote a revision. Reserve bracketed
171
+ // references on this line for the pointers actually selected by Bond.
172
+ const hint = trigger.replace(/\[(?=mem-[\da-f-]+@\d+\])/giu, '[') + ' [' + row.id + '@' + row.rev + ']';
173
+ const withHint = copy.lookupPrefix + [...hints, hint].join(copy.separator) + copy.lookupEnd + searchHint;
138
174
  if (!fits([...lines, withHint]))
139
175
  continue;
140
176
  hints.push(hint);
@@ -146,3 +182,10 @@ export function buildIndex(rows, revokedIds, limits = {}, currentTask) {
146
182
  }
147
183
  return { text: lines.join('\n'), included, overflow };
148
184
  }
185
+ /** Recognize only Bond's own localized lookup line in an admitted runtime context. */
186
+ export function indexHintRefs(line) {
187
+ const copy = Object.values(prompts).find(copy => line.startsWith(copy.lookupPrefix) && line.endsWith(copy.lookupEnd + copy.lookup));
188
+ if (!copy)
189
+ return [];
190
+ return Array.from(line.matchAll(/\[(mem-[\da-f-]+)@(\d+)\]/giu), m => ({ id: m[1], rev: Number(m[2]) }));
191
+ }
package/dist/index.js CHANGED
@@ -1,7 +1,10 @@
1
1
  import { createRequire } from 'node:module';
2
2
  import { isAbsolute } from 'node:path';
3
3
  import { ProjectMemory, indexName, publicRule } from "./service.js";
4
- import { indexLimits, proposeTool, systemSection } from "./policy.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";
5
8
  import { registerMaintenance } from "./maintenance.js";
6
9
  import { registerKnowledge } from "./knowledge.js";
7
10
  import { newSearchTrace } from "./retrieval.js";
@@ -11,6 +14,7 @@ import { registerConsolidation } from "./consolidation.js";
11
14
  import { registerCommands, parseRef } from "./commands.js";
12
15
  import { registerUI } from "./ui.js";
13
16
  import { StoreError } from "./store.js";
17
+ import { registerConditionalTool } from "./host.js";
14
18
  export const name = 'dsh-memory-bond';
15
19
  export const inject = ['agents', 'workingDirectory', 'tools', 'systemPrompt', 'llm'];
16
20
  const output = {
@@ -38,11 +42,20 @@ export function toolErrorStatus(error) {
38
42
  return /^[a-z_]+$/.test(code) ? code : 'storage_or_validation_error';
39
43
  }
40
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
+ }
41
55
  const profileContext = ctx.get('profileContext');
42
56
  const profile = profileContext?.dir;
43
57
  if (typeof profile !== 'string' || !isAbsolute(profile)) {
44
- ctx.logger.warn('无法定位当前 DSH profile,记忆插件需要绝对路径 profileContext.dir。');
45
- return;
58
+ return unavailable('absolute profileContext.dir');
46
59
  }
47
60
  let isAgentLoopRequest;
48
61
  let reviewSdk;
@@ -53,21 +66,36 @@ export function apply(ctx, config = {}) {
53
66
  // plugin's own file when it is absent can silently resolve a different, wrong copy instead of
54
67
  // failing loudly - worse than disabling the plugin, so this composition is declined outright.
55
68
  if (!profileContext?.installAnchor) {
56
- ctx.logger.warn('project-memory 需要 profileContext.installAnchor 才能定位宿主模块,当前已停用。');
57
- return;
69
+ return unavailable('profileContext.installAnchor');
58
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');
59
79
  try {
60
80
  const hostRequire = createRequire(profileContext.installAnchor);
61
81
  const llm = hostRequire('@deepseek-ai/dsh-llm');
82
+ if (typeof llm?.isAgentLoopRequest !== 'function')
83
+ return unavailable('@deepseek-ai/dsh-llm.isAgentLoopRequest');
62
84
  isAgentLoopRequest = llm.isAgentLoopRequest;
63
- reviewSdk = llm;
64
- ({ appendPluginRecord } = hostRequire('@deepseek-ai/dsh-session'));
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;
65
92
  }
66
- catch (error) {
67
- ctx.logger.warn('project-memory 无法解析宿主模块 @deepseek-ai/dsh-llm 或 @deepseek-ai/dsh-session,当前已停用:' +
68
- (error instanceof Error ? error.message : String(error)));
69
- return;
93
+ catch {
94
+ return unavailable('@deepseek-ai/dsh-llm and @deepseek-ai/dsh-session at profileContext.installAnchor');
70
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.');
71
99
  const memory = new ProjectMemory(ctx, profile, { ...config, ...indexLimits(config) }, appendPluginRecord);
72
100
  ctx.on('agent/inbox/claimed', ({ agent, message, turn }) => {
73
101
  try {
@@ -76,12 +104,12 @@ export function apply(ctx, config = {}) {
76
104
  catch { /* A failed scope read leaves the ordinary search hint available. */ }
77
105
  });
78
106
  memory.retrieval.vectors.start();
79
- const stopReview = registerTurnReview(memory, reviewSdk);
80
- const stopConsolidation = registerConsolidation(memory, reviewSdk);
107
+ const stopReview = reviewSdk && registerTurnReview(memory, reviewSdk);
108
+ const stopConsolidation = reviewSdk && registerConsolidation(memory, reviewSdk);
81
109
  const stopMaintenance = registerMaintenance(ctx, memory);
82
110
  ctx.effect(() => async () => {
83
- stopReview();
84
- await stopConsolidation();
111
+ stopReview?.();
112
+ await stopConsolidation?.();
85
113
  await stopMaintenance();
86
114
  memory.retrieval.close();
87
115
  memory.store.close();
@@ -132,9 +160,10 @@ export function apply(ctx, config = {}) {
132
160
  name: 'project-memory:instructions',
133
161
  order: 20,
134
162
  interpolate: false,
135
- text: () => memory.assistantGeneration() === undefined
136
- ? '记忆已停用。忽略先前由记忆索引、记忆工具和项目知识提示提供的信息。'
137
- : systemSection,
163
+ text: ({ agent } = {}) => {
164
+ const copy = prompts[memory.promptLanguage(agent)];
165
+ return memory.assistantGeneration() === undefined ? copy.disabled : copy.system;
166
+ },
138
167
  });
139
168
  ctx.systemPrompt.context({
140
169
  name: indexName,
@@ -154,8 +183,8 @@ export function apply(ctx, config = {}) {
154
183
  }
155
184
  },
156
185
  });
157
- const { expanded, shownSearchRows } = registerAudit(memory, isAgentLoopRequest);
158
- registerKnowledge(ctx, memory, expanded);
186
+ const { expanded, shownSearchRows, executed, blocked, wrote } = registerAudit(memory, isAgentLoopRequest);
187
+ registerKnowledge(ctx, memory, expanded, { executed, blocked });
159
188
  const emptySearches = new WeakMap();
160
189
  function searchAvailable(agent, generation) {
161
190
  const previous = emptySearches.get(agent);
@@ -175,8 +204,8 @@ export function apply(ctx, config = {}) {
175
204
  emptySearches.delete(agent);
176
205
  return true;
177
206
  }
178
- function tool(name, contract, run, available) {
179
- ctx.tools.register({
207
+ function tool(name, contract, run, available, visibleWithoutAgent = true) {
208
+ registerConditionalTool(ctx, {
180
209
  name,
181
210
  ...contract,
182
211
  output,
@@ -187,22 +216,52 @@ export function apply(ctx, config = {}) {
187
216
  const generation = memory.assistantGeneration();
188
217
  if (generation === undefined)
189
218
  return JSON.stringify({ status: 'memory_disabled' });
190
- const result = await run(args, exec.agent, exec.callId, generation);
219
+ const result = await run(args, exec.agent, exec.callId, generation, exec.signal);
191
220
  return JSON.stringify(memory.assistantGeneration() === generation ? result : { status: 'memory_disabled' });
192
221
  }
193
222
  catch (error) {
194
223
  return JSON.stringify({ status: toolErrorStatus(error) });
195
224
  }
196
225
  },
197
- }, { when: step => {
198
- const generation = memory.assistantGeneration();
199
- return generation !== undefined && (!available || !step || available(step.agent, generation));
200
- } });
226
+ }, agent => {
227
+ const generation = memory.assistantGeneration();
228
+ return generation !== undefined && (!available || (agent ? available(agent, generation) : visibleWithoutAgent));
229
+ });
201
230
  }
202
- tool('project_memory_propose', proposeTool, (args, agent) => memory.propose(agent, args));
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);
203
261
  tool('project_memory_search', {
204
- description: '搜索全局与本项目的记忆。知道对象和主题时传 subject 和 topic,否则用自然语言 query。查项目约定且记录语言可能不同时,同时传另一语言的等义短语 alternateQuery(中英各一),保留命令和专名。命中按相关性排序,alreadyShown 表示当前对话步骤已收到该版本的完整条目。no_new_evidence 表示本次没有补充证据,同一细节停止改写搜索词,依据已有信息回答或说明未知;独立线索可另查。empty_scope 表示所查范围没有可用记忆,直接按当前任务或用户给出的备用方式继续。ambiguous 表示需要核对多个候选。coverage 为 partial/missing/unavailable 时语义覆盖不完整。',
205
- parameters: parameters({ query: string, alternateQuery: string, subject: string, topic: string, scope: { type: 'string', enum: ['global', 'project'] },
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'] },
206
265
  mode: { type: 'string', enum: ['hybrid', 'keyword', 'semantic'] } }, ['query']),
207
266
  }, async (args, agent, call, generation) => {
208
267
  const timing = timingFor(agent.session, call);
@@ -213,13 +272,15 @@ export function apply(ctx, config = {}) {
213
272
  if (!d)
214
273
  return { rules: [] };
215
274
  const context = searchContext(agent, d, generation);
216
- const { subject, topic, scope } = args;
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');
217
278
  if (scope !== undefined && scope !== 'global' && scope !== 'project')
218
279
  throw new StoreError('invalid_input');
219
280
  const rules = await memory.search(agent, args.query, args.mode, { subject, topic, scope: scope === 'global' ? 'profile' : scope, alternateQuery: args.alternateQuery }, trace);
220
281
  if (memory.assistantGeneration() !== generation || memory.domain(agent)?.id !== d.id)
221
282
  return { rules: [] };
222
- const rows = rules.slice(0, 40);
283
+ const rows = rules.slice(0, limit);
223
284
  if (trace.match === 'empty_scope' && context)
224
285
  emptySearches.set(agent, context);
225
286
  const seen = shownSearchRows(agent, context);
@@ -232,10 +293,11 @@ export function apply(ctx, config = {}) {
232
293
  }
233
294
  return trace.match === 'exact_id' ? full : { id: rule.id, rev: rule.rev, alreadyShown: true };
234
295
  });
235
- expanded(agent, d, call, rows.map(({ id, rev }) => ({ id, rev })), context);
296
+ expanded(agent, d, call, rows, context);
236
297
  memory.store.audit(d.id, agent.id, 'search', { call, agent: agent.id, outcome: rows.length });
237
298
  return { rules: results, match: trace.match, coverage: trace.coverage,
238
- ...(trace.match === 'empty_scope' && { guidance: '所查范围没有可用约定。按用户当前要求或给出的备用方式继续;已有成功执行结果时直接报告结果。' }),
299
+ ...(rules.length > limit && { totalMatches: rules.length }),
300
+ ...(trace.match === 'empty_scope' && { guidance: prompts[memory.promptLanguage(agent)].empty }),
239
301
  ...(noNewEvidence ? { progress: 'no_new_evidence' } : {}) };
240
302
  }
241
303
  finally {
@@ -265,10 +327,10 @@ export function apply(ctx, config = {}) {
265
327
  if ('id' in row && row.id !== undefined) {
266
328
  const owner = memory.owner(agent, d, row.id);
267
329
  const current = owner && memory.current(owner, row.id, row.rev);
268
- if (!current || ('quote' in row && current.user_quote !== row.quote))
330
+ if (!current || !memory.canPublishEvidence(current, row))
269
331
  return { status: 'not_found' };
270
- if (!source)
271
- expanded(agent, d, call, [{ id: row.id, rev: row.rev }]);
332
+ if (!source && 'action' in row)
333
+ expanded(agent, d, call, [row]);
272
334
  memory.store.audit(owner.id, agent.id, source ? 'expand' : 'read', {
273
335
  id: row.id,
274
336
  rev: row.rev,
@@ -279,9 +341,9 @@ export function apply(ctx, config = {}) {
279
341
  return 'scope' in row ? modelRule(row) : row;
280
342
  });
281
343
  }
282
- readTool('project_memory_read', '按 ID 或 ID@版本读取现行结论、适用条件和例外。执行任务时用此工具展开索引中的记忆。');
283
- readTool('project_memory_source', '仅在用户询问出处或要求核对原话时,用 ID 或 ID@版本查询来源。返回短引和核验状态。verified_user_quote 表示已核验,retained_quote 表示仅有留存引文,confirmed_wording 表示用户确认的表述,receipt 表示未保留引文。');
284
- ctx.inject(['commands'], (c) => registerCommands(c, memory));
344
+ readTool('project_memory_read', toolCopy.read);
345
+ readTool('project_memory_source', toolCopy.source);
346
+ ctx.inject(['commands'], (c) => registerCommands(c, memory, hostIssues));
285
347
  registerUI(ctx, memory);
286
348
  ctx.provide('projectMemoryReady', true);
287
349
  }