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