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
package/dist/semantic.js CHANGED
@@ -1,5 +1,4 @@
1
1
  import { skipsAutomaticMemory } from "./automatic.js";
2
- import { literalActionCommand } from "./command-scope.js";
3
2
  import { isDeepStrictEqual } from 'node:util';
4
3
  import { normalizeLabel, semanticSlot, validLabel } from "./personal.js";
5
4
  import { StoreError } from "./store.js";
@@ -35,11 +34,13 @@ export function parseCandidate(row) {
35
34
  throw new StoreError('invalid_input');
36
35
  return {
37
36
  ...(row.subject !== undefined && { subject: row.subject.trim() }),
38
- usage: row.usage === 'proactive' && !row.sensitive ? 'proactive' : 'on_demand',
37
+ usage: row.kind !== 'fact' && row.usage === 'proactive' && !row.sensitive ? 'proactive' : 'on_demand',
39
38
  scope: row.scope, kind: row.kind, topic: row.topic.trim(), user_quote: row.user_quote, action: row.action.trim(),
40
39
  when: row.when ?? '', exceptions: row.exceptions ?? '',
41
- paths: row.paths ?? [], conflicts_with_repo_guidance: row.conflicts_with_repo_guidance === true,
42
- sensitive: row.sensitive === true, correction: row.correction === true,
40
+ paths: row.paths ?? [],
41
+ // Older models included this flag. Repository decisions come from the verified instruction snapshot.
42
+ conflicts_with_repo_guidance: false,
43
+ sensitive: row.sensitive === true,
43
44
  keywords: [...new Set(row.keywords?.map(k => k.trim()) ?? [])],
44
45
  ...(row.replaces ? { replaces: { id: row.replaces.id, rev: Number(row.replaces.rev) } } : {}),
45
46
  };
@@ -62,114 +63,36 @@ export function semanticDraft(row, draft, previous) {
62
63
  ...(row.scope === 'global' && { hard: undefined, guidance: undefined }),
63
64
  };
64
65
  }
65
- const broadCondition = /^(?:始终|总是|一直|默认|平时|一般|通常|每次|任何时候|所有情况|无条件|always|generally|normally|by default|every time|all cases)$/iu;
66
- // Two named occasions or separate subtrees can support independent rules on the same topic.
67
- // An exception, an omitted condition, or a parent path alone cannot establish that distinction.
66
+ // The model supplies the applicable occasion. Only independent, evidenced scopes may
67
+ // coexist under one topic; an omitted qualifier cannot establish a separate context.
68
68
  export function separateContexts(a, b) {
69
- const named = (item) => item.when && !broadCondition.test(item.when) && item.user_quote.includes(item.when);
69
+ const named = (item) => item.when && item.user_quote.includes(item.when);
70
70
  if (a.when !== b.when && named(a) && named(b))
71
71
  return true;
72
72
  return a.paths.length > 0 && b.paths.length > 0 && a.paths.every(p => b.paths.every(q => p !== '.' && q !== '.' && p !== q && !p.startsWith(q + '/') && !q.startsWith(p + '/')));
73
73
  }
74
- const correctionWording = /更正|纠正|修正|改为|改成|改用|改写|改到|换成|换为|改回|不再.{1,60}(?:而是|改)|(?:记错|说错|写错|搞错|有误)[\s\S]{0,80}(?:应该[是为]|应[是为]|实际[是为]|正确的?是)|\b(?:correction|correcting|switch(?:ed)? to|changed? (?:from|to)|replace .{1,60} with|use .{1,60} instead|(?:was wrong|misremembered|misspoke|mistyped|was mistaken).{0,80}(?:should be|actually is))\b/iu;
75
- const uncertainWording = /[??]|如果|假设|假如|例如|比如|示例|据说|转述|引用|引文|不要|不想|不用|不必|不能|无需|并未|没有|(?:不|没|未|别|勿)(?:会|要|想|需|应|曾|让你)?(?:改|换|更正|修正|纠正)|是否|考虑|可能|\b(?:if|suppose|example|quoted?|maybe|might|perhaps|never|not|don['’]t|didn['’]t|should we)\b/iu;
76
- const wording = (text) => text.trim().replace(/[。!!]+$|(?<=[`”"」])\.$/u, '').trim().replace(/^[`“"「](.+)[`”"」]$/u, '$1');
77
- const selfSubject = /^(?:本人|自己|我自己|我|用户本人|用户|me|myself|self|user|the user)$/u;
78
- export function isExplicitCorrection(source) {
79
- return correctionWording.test(source) && !uncertainWording.test(source);
80
- }
81
- function supportsCorrectionValue(row, previous) {
82
- const quote = wording(row.user_quote);
83
- const action = wording(row.action);
84
- const replacement = /(?:改为|改成|改用|改到|换成|换为|改回|修正为|而是|应该[是为]|应[为是]|实际[是为]|其实是|正确的?是|\b(?:should be|actually is|switch(?:ed)? to|changed? (?:from .+? to|to)|replace .+? with))\s*([^,。;;!?\n]+)$/iu.exec(quote);
85
- const value = wording(replacement?.[1] ?? quote);
86
- if (action === quote)
87
- return !replacement;
88
- const command = literalActionCommand(action);
89
- if (command)
90
- return literalActionCommand(value) === command;
91
- if (!replacement)
92
- return quote.endsWith(action);
93
- if (!action.endsWith(value))
94
- return false;
95
- const prefix = action.slice(0, -value.length);
96
- if (/[,,;;。()()]|原来|原先|上次|此前|过去|previously|used to/iu.test(prefix) ||
97
- prefix.includes(wording(previous.action)))
98
- return false;
99
- if (!prefix || quote.includes(action) || previous.action.startsWith(prefix))
100
- return true;
101
- // For a versioned fact, the model may spell out the subject/topic around the exact new
102
- // value. Accept a single grounded label; keep extra values, qualifiers and clauses out.
103
- if (!row.replaces || row.kind !== 'fact')
104
- return false;
105
- const subject = row.subject ? normalizeLabel(row.subject) : '';
106
- const labels = [row.topic, previous.semanticTopic, ...(previous.keywords ?? [])];
107
- return labels.some(label => {
108
- if (!label || !normalizeLabel(quote).includes(normalizeLabel(label)))
109
- return false;
110
- const head = normalizeLabel(prefix);
111
- const start = head.indexOf(normalizeLabel(label));
112
- if (start === -1)
113
- return false;
114
- const owner = head.slice(0, start).trim().replace(/的$/u, '');
115
- const predicate = head.slice(start + normalizeLabel(label).length).trim();
116
- const self = (selfSubject.test(subject) || (!subject && /我|\b(?:my|i)\b/iu.test(quote))) &&
117
- /^(?:我|本人|用户|my|the user's)$/u.test(owner);
118
- return (!owner || owner === subject || self) &&
119
- /^(?:是|为|[::]|is|is now|=)?$/u.test(predicate);
120
- });
74
+ // Normalize semantically equivalent wording only after the reviewer saw both
75
+ // sets of qualifiers. Adding or dropping a condition still reaches the store as
76
+ // a scope change. Paths keep their filesystem-based validation in prepareItems.
77
+ export function reviewedQualifiers(row, target, equivalent) {
78
+ const { when, exceptions } = row;
79
+ if (!target || equivalent !== true)
80
+ return { when, exceptions };
81
+ return {
82
+ when: when && target.when ? target.when : when,
83
+ exceptions: exceptions && target.exceptions ? target.exceptions : exceptions,
84
+ };
121
85
  }
122
86
  const sameContext = (a, b) => a.when === b.when && a.exceptions === b.exceptions && isDeepStrictEqual(a.paths, b.paths);
123
- function namesSubject(subject, quote, scope, implicitProject = false) {
124
- if (!subject)
125
- return true;
126
- if (selfSubject.test(subject) && /我(?!们)|本人|\b(?:i|my|me|myself)\b/u.test(quote))
127
- return true;
128
- if (scope === 'project' && /^(?:本仓库|本项目|当前仓库|当前项目|this (?:repo|project))$/u.test(subject) &&
129
- (implicitProject || /(?:本|这个|当前)(?:仓库|项目)|\bthis (?:repo(?:sitory)?|project)\b/u.test(quote)))
87
+ // A newly assessed action can revise a confirmed action under the same repository authority.
88
+ function sameGuidanceForRevision(previous, next) {
89
+ if (isDeepStrictEqual(previous, next))
130
90
  return true;
131
- const escaped = subject.replace(/[.*+?^${}()|[\]\\]/gu, '\\$&');
132
- // A label such as Ann must not match the subject Anna.
133
- const left = /^[a-z0-9]/u.test(subject) ? '(?<![a-z0-9_])' : '';
134
- const right = /[a-z0-9]$/u.test(subject) ? '(?![a-z0-9_])' : '';
135
- return new RegExp(left + escaped + right, 'u').test(quote);
136
- }
137
- export function correctReviewSubject(row, source, known) {
138
- const subject = normalizeLabel(row.subject ?? '');
139
- const quote = normalizeLabel(row.user_quote);
140
- if (!namesSubject(subject, quote, row.scope, true))
91
+ if (!object(previous) || !object(next) || previous.status !== 'clear' || next.status !== 'clear')
141
92
  return false;
142
- // Even an unqualified entry cannot absorb a named sibling's correction. Consult
143
- // all local same-topic subjects, including ones outside the offered shortlist.
144
- const full = normalizeLabel(source);
145
- for (const other of known)
146
- if (other !== subject && namesSubject(other, full, row.scope))
147
- return false;
148
- return true;
149
- }
150
- function namesTarget(row, previous, uniquePrefix) {
151
- const quote = normalizeLabel(row.user_quote);
152
- if (!namesSubject(normalizeLabel(row.subject ?? ''), quote, row.scope))
153
- return false;
154
- const labels = [row.topic, previous.semanticTopic, ...(previous.keywords ?? []),
155
- previous.action, previous.when, ...previous.paths.filter(path => path !== '.')];
156
- if (labels.some(label => label && quote.includes(normalizeLabel(label))))
157
- return true;
158
- // The utterance may say “集成测试改用 …” for “集成测试入口” / “集成测试命令”.
159
- // Only accept their common name if both sources use it and no sibling shares it.
160
- const topic = normalizeLabel(previous.semanticTopic);
161
- return previous.keywords?.some(alias => {
162
- const keyword = normalizeLabel(alias);
163
- let length = 0;
164
- while (length < topic.length && topic[length] === keyword[length])
165
- length++;
166
- const shared = topic.slice(0, length).trim();
167
- if (shared.length < 4 || !normalizeLabel(previous.user_quote).includes(shared))
168
- return false;
169
- const at = quote.indexOf(shared);
170
- return at >= 0 && /^(?:\s*(?:改为|改用|改成|换成|换为|应该是|应为|changed? to|switch(?:ed)? to))/u
171
- .test(quote.slice(at + shared.length)) && uniquePrefix(shared);
172
- }) ?? false;
93
+ const { assessmentKey: oldActionKey, ...oldAuthority } = previous;
94
+ const { assessmentKey: newActionKey, ...newAuthority } = next;
95
+ return typeof newActionKey === 'string' && isDeepStrictEqual(oldAuthority, newAuthority);
173
96
  }
174
97
  export function sameSemanticContent(a, b) {
175
98
  return sameContext(a, b) && a.action === b.action && a.kind === b.kind &&
@@ -177,119 +100,58 @@ export function sameSemanticContent(a, b) {
177
100
  isDeepStrictEqual(a.hard, b.hard) && isDeepStrictEqual(a.guidance, b.guidance) &&
178
101
  isDeepStrictEqual(a.localException, b.localException);
179
102
  }
180
- const oneTime = /仅限本次|仅(?:此|这)一次|只限这次|仅这次|这次(?:先|临时|暂时)|本次(?:临时|暂时)|\b(?:just this once|this time only|for this (?:run|task) only)\b/iu;
181
- const prohibition = /不要|禁止|切勿|请勿|不得|别用|不用|不(?:再)?(?:默认)?(?:使用|运行|执行)|\b(?:do not|don't|don’t|never|avoid|forbid|skip|without)\b/iu;
182
- const negativeDirective = /(?:不要|禁止|切勿|请勿|不得|别用|不用|不(?:再)?(?:默认)?(?:使用|运行|执行))|^\s*(?:please\s+)?(?:do not|don['’]t|never|avoid)\s+/iu;
183
- const conditionLabel = /(?:仅|只)在\s*([\w-]+|[^\s,。;]{1,24}?(?:环境|分支|阶段))|\bonly (?:in|on|during) (?:the )?([\w-]+)/iu;
184
- const conditionClause = /^(?:(?:仅|只)在.{1,30}?(?:环境|分支|阶段|中|时|下|[\w-])|only (?:in|on|during) (?:the )?[\w-]+(?: (?:environment|branch|stage|pipeline))?)$/iu;
185
- // Preserve explicit safeguards in and immediately around the cited clause. The
186
- // source locator has already established that this quotation occurs exactly once.
187
- function firstDirectiveIssue(row, source) {
188
- const at = source.indexOf(row.user_quote);
189
- if (at < 0)
190
- return;
191
- const stop = /[。!?!?;;\n]|\.(?=\s|$)/u;
192
- const prefix = source.slice(0, at).split(stop).at(-1) ?? '';
193
- const suffix = source.slice(at + row.user_quote.length).split(stop)[0];
194
- const sentence = prefix + row.user_quote + suffix;
195
- const candidates = Array.from(sentence.matchAll(/[^,,。!?!?;;\n]+/gu));
196
- const cited = candidates.filter(part => part.index < prefix.length + row.user_quote.length &&
197
- part.index + part[0].length > prefix.length);
198
- const exactAction = cited.filter(part => part[0].includes(row.action));
199
- for (const part of exactAction.length === 1 ? exactAction : cited) {
200
- const clause = part[0];
201
- const owner = /我(?:的)?同事(?=\s*(?:个人|平时|通常|一般)?(?:习惯|偏好|喜欢|使用|用))|\bmy (?:colleague|coworker|co-worker)(?=\s+(?:(?:personally|usually)\s+)?(?:uses|likes|prefers)\b)/iu.exec(clause);
202
- if (owner && (row.subject ? !normalizeLabel(clause).includes(normalizeLabel(row.subject)) || selfSubject.test(normalizeLabel(row.subject)) :
203
- !row.action.toLowerCase().includes(owner[0].toLowerCase())))
204
- return 'unsupported_subject';
205
- if (row.kind === 'fact' && row.usage !== 'proactive')
206
- continue;
207
- if (row.scope === 'global' && /^\s*(?:以后|今后)?(?:这个|本|当前)(?:仓库|项目)|^\s*(?:only )?(?:in|for) this (?:repo(?:sitory)?|project)\b/iu.test(clause))
208
- return 'project_only';
209
- const index = candidates.indexOf(part);
210
- const previous = candidates[index - 1]?.[0].trim() ?? '';
211
- const next = candidates[index + 1]?.[0].trim() ?? '';
212
- const qualifiers = [previous, next].filter(text => conditionClause.test(text) || oneTime.exec(text)?.[0] === text);
213
- const context = [clause, ...qualifiers].join(' ');
214
- if (oneTime.test(context))
215
- return 'one_time_request';
216
- if (negativeDirective.test(clause) && !prohibition.test(row.action))
217
- return 'missing_negation';
218
- const condition = conditionLabel.exec(context);
219
- if (condition) {
220
- const label = normalizeLabel(condition[1] ?? condition[2]);
221
- const retains = [row.when, row.action].some(text => /^[\w-]+$/u.test(label) ? normalizeLabel(text).split(/[^\w-]+/u).includes(label) : normalizeLabel(text).includes(label));
222
- if (!retains)
223
- return 'missing_condition';
224
- }
225
- }
103
+ /** An ID selects an existing entry inside its authorized domain. Supplied labels
104
+ * can confirm its identity but cannot redirect the reference to a different topic. */
105
+ export function targetMismatch(row, target) {
106
+ if (!target.semanticTopic || ![target.semanticTopic, ...(target.keywords ?? [])]
107
+ .some(label => normalizeLabel(label) === normalizeLabel(row.topic)))
108
+ return 'topic_mismatch';
109
+ if (row.subject !== undefined && normalizeLabel(row.subject) !== normalizeLabel(target.subject ?? ''))
110
+ return 'subject_mismatch';
111
+ if (target.kind !== row.kind)
112
+ return 'kind_mismatch';
226
113
  }
227
- export function planSemantic(row, prepared, matches, sourceText, background, uniquePrefix) {
228
- // A shared search alias can name entirely different facts about the same subject.
229
- if (new Set(matches.map(head => normalizeLabel(head.semanticTopic))).size > 1)
230
- return { reason: 'ambiguous_topic' };
114
+ export function planSemantic(row, prepared, matches, target, background, hasVerifiedSelection = false) {
231
115
  const applicable = matches.filter(head => sameContext(head, prepared));
232
- let previous;
233
- if (row.replaces) {
234
- previous = matches.find(head => head.id === row.replaces.id && head.rev === row.replaces.rev);
235
- if (!previous)
236
- return { reason: 'stale_revision' };
237
- if (applicable.some(head => head.id !== previous.id))
238
- return { reason: 'ambiguous_topic' };
239
- }
240
- else {
241
- if (applicable.length > 1)
242
- return { reason: 'ambiguous_topic' };
243
- previous = applicable[0];
244
- if (!previous && (row.correction || matches.some(head => !separateContexts(head, prepared))))
245
- return { reason: 'replacement_required' };
246
- }
116
+ if (target && !sameContext(target, prepared))
117
+ return { reason: 'context_mismatch' };
118
+ if (applicable.length > 1)
119
+ return { reason: 'ambiguous_topic' };
120
+ const previous = target ?? applicable[0];
121
+ if (!previous && matches.some(head => !separateContexts(head, prepared)))
122
+ return { reason: 'replacement_required' };
247
123
  const canonical = previous ?? matches[0];
248
124
  const item = semanticDraft(canonical ? { ...row, topic: canonical.semanticTopic, subject: canonical.subject } : row, prepared, previous);
249
- if (!previous) {
250
- const issue = firstDirectiveIssue(row, sourceText);
251
- if (issue)
252
- return { reason: issue };
253
- if (canonical) {
254
- item.keywords = [...new Set([...(canonical.keywords ?? []), ...row.keywords])].slice(0, 8);
255
- if (matches.some(head => head.sensitive)) {
256
- item.sensitive = true;
257
- item.usage = 'on_demand';
258
- }
259
- }
260
- return { item };
261
- }
262
- if (!row.replaces && !item.sensitive)
125
+ if (previous && !row.replaces && !item.sensitive)
263
126
  item.usage = previous.usage;
264
- if (sameSemanticContent(previous, item)) {
265
- // Alias vocabulary is retrieval metadata. A restatement retains the current fingerprint
266
- // and records its own event against the existing revision in the automatic-source ledger.
127
+ if (previous && sameSemanticContent(previous, item)) {
128
+ // Identical observations preserve both the existing revision and its evidence.
267
129
  item.keywords = previous.keywords;
268
- item.hard = previous.hard;
269
- item.guidance = previous.guidance;
270
- item.localException = previous.localException;
271
130
  return { item, previous };
272
131
  }
273
- if (row.correction || background) {
274
- if (!correctionWording.test(row.user_quote) || uncertainWording.test(sourceText))
275
- return { reason: 'replacement_required' };
276
- if (!supportsCorrectionValue(row, previous))
277
- return { reason: 'unsupported_correction' };
132
+ if (previous && !target)
133
+ return { reason: 'replacement_required' };
134
+ // This is source integrity, not an entailment test. The semantic extractor
135
+ // selects the asserted current value, speaker and qualifiers from the full input.
136
+ if (!row.user_quote.includes(row.action) && !hasVerifiedSelection)
137
+ return { reason: 'insufficient_evidence' };
138
+ if (previous && background && (previous.channel !== 'automatic' || previous.pinned ||
139
+ previous.quoteType !== 'user_quote' || previous.usageOverride || previous.localException ||
140
+ (previous.usage ?? 'on_demand') !== (item.usage ?? 'on_demand') ||
141
+ !sameGuidanceForRevision(previous.guidance, item.guidance) ||
142
+ !isDeepStrictEqual(item.hard?.branch, previous.hard?.branch)))
143
+ return { reason: 'protected_revision' };
144
+ if (previous) {
145
+ // Retain the topic's aliases across updates. Avoid indexing the obsolete value.
146
+ item.keywords = [...new Set([...(previous.keywords ?? []).filter(k => !previous.action.includes(k) || item.action.includes(k)),
147
+ ...row.keywords])].slice(0, 8);
278
148
  }
279
- if (matches.length > 1 && (!sameContext(previous, prepared) ||
280
- (previous.when && !row.user_quote.includes(previous.when)) ||
281
- (previous.paths.length && !previous.paths.some(path => row.user_quote.includes(path)))))
282
- return { reason: 'ambiguous_topic' };
283
- if (!row.replaces || background) {
284
- if ((!row.replaces && (!row.correction || !namesTarget(row, previous, uniquePrefix))) ||
285
- !sameContext(previous, item) || previous.channel !== 'automatic' || previous.pinned ||
286
- previous.quoteType !== 'user_quote' || previous.usageOverride || previous.kind !== item.kind ||
287
- (previous.usage ?? 'on_demand') !== (item.usage ?? 'on_demand') || previous.localException || !isDeepStrictEqual(item.guidance, previous.guidance) ||
288
- !isDeepStrictEqual(item.hard?.branch, previous.hard?.branch))
289
- return { reason: 'replacement_required' };
149
+ else if (canonical) {
150
+ item.keywords = [...new Set([...(canonical.keywords ?? []), ...row.keywords])].slice(0, 8);
151
+ if (matches.some(head => head.sensitive)) {
152
+ item.sensitive = true;
153
+ item.usage = 'on_demand';
154
+ }
290
155
  }
291
- // Keep stable topic aliases on corrections; remove keywords drawn only from the obsolete value.
292
- item.keywords = [...new Set([...(previous.keywords ?? []).filter(k => !previous.action.includes(k) || item.action.includes(k)),
293
- ...row.keywords])].slice(0, 8);
294
156
  return { item, previous };
295
157
  }