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
@@ -0,0 +1,181 @@
1
+ import { refusesAutomaticMemory, skipsAutomaticMemory } from './automatic.ts'
2
+ import { messageText, type HostEvent, type Session } from './host.ts'
3
+
4
+ interface QuestionAnswer {
5
+ question: string
6
+ text: string
7
+ block: number
8
+ offset: number
9
+ userSeq: number
10
+ }
11
+
12
+ export interface SubmittedOption {
13
+ userSeq: number
14
+ callSeq: number
15
+ resultSeq: number
16
+ questionId: string
17
+ question: string
18
+ label: string
19
+ }
20
+ export interface SelectionEvidence { option: SubmittedOption; directive: string }
21
+
22
+ /** Keep the user's directive and the submitted format intact. Strip only the
23
+ * recommendation marker that DSH forms display as part of an option label. */
24
+ export function selectedAction(directive: string, label: string) {
25
+ return directive + '\n' + label.replace(/\s*(?:\((?:recommended|推荐)\)|((?:recommended|推荐)))\s*$/iu, '').trim()
26
+ }
27
+
28
+ interface QuestionForm { custom: QuestionAnswer[]; selected: SubmittedOption[]; refusedBy?: number }
29
+
30
+ // A submitted choice can supply the implementation of a standing request. The
31
+ // user must express its continuing applicability in their own cited words.
32
+ export function standingRequest(text: string) {
33
+ return /以后|今后|往后|后续|每次|每当|一律|始终|总是|长期|默认|记住|记下|之[后後]都|\b(?:always|each|every|whenever|henceforth|remember|by default|from now on|in future|in the future|going forward)\b/iu.test(text)
34
+ }
35
+
36
+ const sentences = new Intl.Segmenter(undefined, { granularity: 'sentence' })
37
+
38
+ /** Include submitted formats only for claims in a standing-request sentence.
39
+ * A cropped quote must not turn that same instruction back into a bare rule. */
40
+ export function choicesForQuote(text: string, quote: string, choices?: SubmittedOption[]) {
41
+ if (!choices?.length) return
42
+ const start = text.indexOf(quote)
43
+ if (start < 0) return
44
+ const end = start + quote.length
45
+ for (const sentence of sentences.segment(text)) {
46
+ if (sentence.index < end && sentence.index + sentence.segment.length > start && standingRequest(sentence.segment))
47
+ return choices
48
+ }
49
+ }
50
+
51
+ /** Both reviewers use the same reference into the native form. Unrelated
52
+ * options require an explicit null decision before saving a standing rule. */
53
+ export function resolveSelectedDirective(action: string, index: unknown, choices: SubmittedOption[] | undefined,
54
+ canSelect: boolean): {action: string; selection?: SelectionEvidence} | undefined {
55
+ if (index == null) {
56
+ if (choices?.length && canSelect && index !== null) return
57
+ return { action }
58
+ }
59
+ if (!canSelect || !Number.isSafeInteger(index) || !standingRequest(action)) return
60
+ const option = choices?.[Number(index)]
61
+ if (!option) return
62
+ const combined = selectedAction(action, option.label)
63
+ if (combined.length > 480) return
64
+ return { action: combined, selection: { directive: action, option } }
65
+ }
66
+
67
+ const record = (value: unknown): value is Record<string, unknown> =>
68
+ typeof value === 'object' && value !== null && !Array.isArray(value)
69
+
70
+ function eligiblePrompt(text: string) {
71
+ // Unlabelled answers like "123456" cannot identify an OTP by themselves.
72
+ return !skipsAutomaticMemory(text) && !/\b(?:otp|pin|one[- ]time (?:code|password)|token)\b|令牌|密码/iu.test(text)
73
+ }
74
+
75
+ /** Keep user-typed text and submitted option labels distinct. */
76
+ function submittedForm(args: unknown, result: unknown, userSeq: number, callSeq: number, resultSeq: number): QuestionForm | undefined {
77
+ if (!record(args) || !Array.isArray(args.questions) || !record(result) ||
78
+ Object.keys(result).some(key => key !== 'answers') || !Array.isArray(result.answers) ||
79
+ !args.questions.length || result.answers.length !== args.questions.length) return undefined
80
+ const questions = new Map<string, { text: string; eligible: boolean; options: unknown }>()
81
+ for (const field of args.questions) {
82
+ if (!record(field) || typeof field.id !== 'string' || !field.id.trim() || questions.has(field.id) ||
83
+ typeof field.question !== 'string' || !field.question.trim() ||
84
+ (field.header !== undefined && typeof field.header !== 'string')) return undefined
85
+ const fieldName = field.id.replace(/([a-z])([A-Z])/gu, '$1 $2').replace(/[_-]/gu, ' ')
86
+ questions.set(field.id, {
87
+ text: field.question, options: field.options,
88
+ eligible: field.question.length <= 1024 && eligiblePrompt([fieldName, field.header, field.question].join(' ')),
89
+ })
90
+ }
91
+ let offset = 0
92
+ const answers: QuestionAnswer[] = []
93
+ const selected: SubmittedOption[] = []
94
+ let refusedBy: number | undefined
95
+ for (const [block, answer] of result.answers.entries()) {
96
+ if (!record(answer) || typeof answer.id !== 'string' || !Array.isArray(answer.selected) ||
97
+ !answer.selected.every(label => typeof label === 'string') ||
98
+ (answer.custom !== undefined && typeof answer.custom !== 'string') ||
99
+ Object.keys(answer).some(key => !['id', 'selected', 'custom'].includes(key))) return undefined
100
+ const question = questions.get(answer.id)
101
+ if (!question) return undefined
102
+ questions.delete(answer.id)
103
+ if (typeof answer.custom !== 'string' || !answer.custom.trim()) {
104
+ const label = answer.selected.length === 1 ? answer.selected[0] : undefined
105
+ if (typeof label === 'string' && label.trim() && label.length <= 480 && Array.isArray(question.options) &&
106
+ question.options.filter(option => record(option) && option.label === label).length === 1) {
107
+ if (refusesAutomaticMemory(label)) refusedBy = userSeq
108
+ else if (question.eligible && !skipsAutomaticMemory(label))
109
+ selected.push({ userSeq, callSeq, resultSeq, questionId: answer.id, question: question.text, label })
110
+ }
111
+ continue
112
+ }
113
+ // Offsets refer to the decoded custom answers joined by newlines, so escaped
114
+ // characters and surrogate pairs have the same UTF-16 positions during rechecking.
115
+ if (question.eligible || refusesAutomaticMemory(answer.custom))
116
+ answers.push({ question: question.text, text: answer.custom, block, offset, userSeq })
117
+ offset += answer.custom.length + 1
118
+ }
119
+ return { custom: answers, selected, refusedBy }
120
+ }
121
+
122
+ /** Only a native submitted result can supply a custom answer or an option selection. */
123
+ export function questionForm(session: Session, published: HostEvent) {
124
+ if (session.header.origin === 'subagent') return
125
+ return verifiedQuestionForm(session.snapshotEvents(), session.inheritedEventCount, published)
126
+ }
127
+
128
+ export function questionAnswers(session: Session, published: HostEvent): QuestionAnswer[] {
129
+ return questionForm(session, published)?.custom ?? []
130
+ }
131
+
132
+ /** Accepts a full session snapshot or a contiguous slice of its original event sequence. */
133
+ export function verifiedQuestionForm(events: readonly HostEvent[], cut: number, published: HostEvent): QuestionForm | undefined {
134
+ if (published.type !== 'tool/result') return undefined
135
+ const offset = events[0]?.seq ?? 0
136
+ const at = (seq: number) => events[seq - offset]
137
+ const event = at(published.seq)
138
+ if (event?.type !== 'tool/result' || event.surfaceOp !== 'append' ||
139
+ event.sourceEventSeqs?.length !== 1 || event.data.error !== undefined) return undefined
140
+ const { message, step, turn } = event.data
141
+ const callId = message?.toolCallId
142
+ if (!callId || message.role !== 'tool' || message.isError || message.source?.kind !== 'tool' ||
143
+ message.source.callId !== callId || !Number.isSafeInteger(step) || !Number.isSafeInteger(turn)) return undefined
144
+ const [callSeq] = event.sourceEventSeqs
145
+ const call = at(callSeq)
146
+ if (callSeq < cut || callSeq >= event.seq || call?.seq !== callSeq ||
147
+ call.type !== 'tool/call' || call.data.name !== 'ask_user_question' || call.data.callId !== callId ||
148
+ call.data.turn !== turn || call.data.step !== step) return undefined
149
+
150
+ // Replay only the local turn. A call or an opening user prompt inherited at
151
+ // a fork, or a change of project between prompt, question and answer, breaks attribution.
152
+ let start = callSeq
153
+ while (start >= cut && at(start).type !== 'turn/start') start--
154
+ if (start < cut || at(start).data.turn !== turn) return undefined
155
+ let userSeq: number | undefined
156
+ let calls = 0, results = 0
157
+ for (let index = start + 1; index < offset + events.length; index++) {
158
+ const e = at(index)
159
+ if (e.type === 'turn/start' || e.type === 'turn/end') {
160
+ if (e.seq < event.seq) return undefined
161
+ break
162
+ }
163
+ if (e.seq <= event.seq && e.type === 'working-directory/change' && userSeq !== undefined) return undefined
164
+ if (e.seq > callSeq && e.seq < event.seq && (e.type === 'step/start' || e.type === 'step/end')) return undefined
165
+ if (e.seq < event.seq && e.type === 'user/message' && e.data.source?.kind === 'user') {
166
+ if ((e.surfaceOp && e.surfaceOp !== 'append') || !eligiblePrompt(messageText(e.data))) return undefined
167
+ if (e.seq < callSeq) userSeq = e.seq
168
+ }
169
+ if (e.data.turn !== turn || e.data.step !== step) continue
170
+ if (e.type === 'tool/call' && e.data.callId === callId) calls++
171
+ if (e.type === 'tool/result' && e.surfaceOp === 'append' && e.data.message?.toolCallId === callId) results++
172
+ }
173
+ if (userSeq === undefined || calls !== 1 || results !== 1 || message.content?.length !== 1) return undefined
174
+ const [part] = message.content
175
+ if (part.type !== 'text' || typeof part.text !== 'string' || typeof call.data.arguments !== 'string') return undefined
176
+ try {
177
+ return submittedForm(JSON.parse(call.data.arguments), JSON.parse(part.text), userSeq, callSeq, event.seq)
178
+ } catch {
179
+ return undefined
180
+ }
181
+ }
@@ -0,0 +1,133 @@
1
+ // Rank only the heads that have already passed the caller's scope and validity checks.
2
+ import { normalizeLabel } from './personal.ts'
3
+ import type { KeywordHit } from './search-index.ts'
4
+ import { encoderId, queryLanguages, type Encoder } from './encoder.ts'
5
+ import type { MemoryStore, Rule } from './store.ts'
6
+ import { document, language, newSearchTrace, VectorIndex, type SearchRow, type SearchTrace } from './vector-index.ts'
7
+ export { newSearchTrace, type SearchTrace } from './vector-index.ts'
8
+
9
+ export type SearchMode = 'hybrid' | 'keyword' | 'semantic'
10
+ export interface SearchOptions { subject?: string; topic?: string; scope?: 'project' | 'profile'; alternateQuery?: string }
11
+
12
+ // Rank each distinct wording in its own language and retain the strongest
13
+ // match per revision. This also admits paraphrases in a single language.
14
+ function queryVariants(query: string, options: SearchOptions) {
15
+ const primary = normalizeLabel(query || options.topic || '')
16
+ const alternate = normalizeLabel(options.alternateQuery ?? '')
17
+ return primary && alternate && primary !== alternate ? [primary, alternate] : [primary]
18
+ }
19
+ export function matchingTopics(rows: SearchRow[], options: SearchOptions) {
20
+ const subject = normalizeLabel(options.subject ?? '')
21
+ const topic = normalizeLabel(options.topic ?? '')
22
+ if (!topic) return []
23
+ return rows.filter(({ rule }) =>
24
+ (!subject || normalizeLabel(rule.subject ?? '') === subject) &&
25
+ [rule.semanticTopic, ...(rule.keywords ?? [])].some(key => key && normalizeLabel(key) === topic))
26
+ }
27
+
28
+ export class Retrieval {
29
+ private readonly store: MemoryStore
30
+ readonly vectors: VectorIndex
31
+ constructor(store: MemoryStore, encoder?: Encoder) {
32
+ this.store = store
33
+ this.vectors = new VectorIndex(store, encoder)
34
+ }
35
+ close() {
36
+ this.vectors.close()
37
+ }
38
+
39
+ keywordHits(domains: string[], query: string, options: SearchOptions) {
40
+ const primary = this.store.keywordMatches(domains, query, options.topic)
41
+ const [, alternate] = queryVariants(query, options)
42
+ if (!alternate) return primary
43
+ const hits = new Map<string, KeywordHit>()
44
+ for (const hit of [...primary, ...this.store.keywordMatches(domains, alternate)]) {
45
+ const key = JSON.stringify([hit.domain, hit.id, hit.rev])
46
+ if (hit.score > (hits.get(key)?.score ?? -Infinity)) hits.set(key, hit)
47
+ }
48
+ return [...hits.values()]
49
+ }
50
+
51
+ // A foreground save only consumes matched candidates, not corpus coverage statistics.
52
+ // A revision with neither a lexical hit nor any passage of a requested model cannot
53
+ // score. Include every indexed passage, even when it shares no words with the proposal.
54
+ reviewRefs(domains: string[], query: string, options: SearchOptions, lexical: KeywordHit[]) {
55
+ const langs = new Set(queryVariants(query, options).flatMap(queryLanguages))
56
+ const models = this.vectors.languages.filter(lang => langs.has(lang)).flatMap(lang =>
57
+ Array.from({length: 8}, (_, i) => encoderId(lang) + '/passage-' + i))
58
+ const refs = domains.flatMap(domain => this.store.vectorRefs(domain, models))
59
+ return [...new Map([...refs, ...lexical].map(row => [JSON.stringify([row.domain,row.id,row.rev]), row])).values()]
60
+ }
61
+
62
+ async search(
63
+ rows: SearchRow[], query: string, mode?: SearchMode,
64
+ options: SearchOptions = {}, trace: SearchTrace = newSearchTrace(), keywordHits?: KeywordHit[],
65
+ ): Promise<Rule[] & { degraded?: boolean }> {
66
+ const q = normalizeLabel(query)
67
+ const subject = normalizeLabel(options.subject ?? '')
68
+ const topic = normalizeLabel(options.topic ?? '')
69
+ if (subject) rows = rows.filter(({ rule }) => !rule.subject || normalizeLabel(rule.subject) === subject)
70
+ if (/^mem-[\da-f-]+(?:@\d+)?$/iu.test(q)) {
71
+ trace.match = 'exact_id'
72
+ return rows.filter(({rule}) => rule.id === q || rule.id + '@' + rule.rev === q).map(d => d.rule)
73
+ }
74
+ if (topic && !mode) {
75
+ const exact = matchingTopics(rows, options)
76
+ if (subject && exact.length === 1) {
77
+ trace.match = 'exact_topic'
78
+ return [exact[0].rule]
79
+ }
80
+ if (exact.length > 1) {
81
+ trace.match = 'ambiguous'
82
+ rows = exact
83
+ }
84
+ }
85
+ if (!rows.length || (!q && !topic)) return rows.map(d => d.rule)
86
+ const started = performance.now()
87
+ const hits = mode === 'semantic' ? [] : keywordHits ?? this.keywordHits(
88
+ [...new Set(rows.map(row => row.domain))], q, options,
89
+ )
90
+ const key = (domain: string, id: string, rev: number) => JSON.stringify([domain, id, rev])
91
+ const lexical = new Map(hits.map(hit => [key(hit.domain, hit.id, hit.rev), hit.score]))
92
+ trace.sqliteMs += performance.now() - started
93
+ const semantic = new Map<string, number>()
94
+ if (mode !== 'keyword') {
95
+ const languages = this.vectors.languages
96
+ const docs = languages.length ? rows.map(row => ({ ...row, text: document(row.rule) })) : []
97
+ const coverage = new Set<SearchTrace['coverage']>()
98
+ const queries = queryVariants(q, options).flatMap(wording => queryLanguages(wording).map(lang => ({ wording, lang })))
99
+ if (!queries.length) coverage.add('unavailable')
100
+ for (const { wording, lang } of queries) {
101
+ if (!languages.includes(lang)) {
102
+ coverage.add('unavailable')
103
+ continue
104
+ }
105
+ if (!docs.some(doc => language(doc.text) === lang)) continue
106
+ try {
107
+ const scores = await this.vectors.scores(wording, docs, trace, lang)
108
+ for (const [id, score] of scores) semantic.set(id, Math.max(score, semantic.get(id) ?? -Infinity))
109
+ coverage.add(trace.coverage)
110
+ } catch {
111
+ coverage.add('unavailable')
112
+ }
113
+ }
114
+ trace.coverage = coverage.size > 1 ? 'partial' : coverage.values().next().value ?? 'complete'
115
+ if (coverage.has('unavailable') && !semantic.size) {
116
+ trace.coverage = 'unavailable'
117
+ if (mode === 'semantic') throw Error('embedding_unavailable')
118
+ }
119
+ }
120
+ const ranked = rows.map(d => {
121
+ const keywordScore = lexical.get(key(d.domain, d.rule.id, d.rule.rev)) ?? 0
122
+ const cos = semantic.get(d.rule.id) ?? 0
123
+ const semanticScore = cos >= 0.45 ? cos : 0
124
+ const score = mode === 'semantic' ? semanticScore : keywordScore + 0.9 * semanticScore
125
+ return { rule: d.rule, score }
126
+ })
127
+ const result = ranked
128
+ .filter(d => d.score > 0 || trace.match === 'ambiguous')
129
+ .sort((a, b) => b.score - a.score || a.rule.id.localeCompare(b.rule.id))
130
+ .map(d => d.rule)
131
+ return trace.coverage && trace.coverage !== 'complete' ? Object.assign(result, { degraded: true }) : result
132
+ }
133
+ }
@@ -0,0 +1,58 @@
1
+ import { isDeepStrictEqual } from 'node:util'
2
+ import { skipsAutomaticMemory } from './automatic.ts'
3
+ import type { AccessDomain } from './domain.ts'
4
+ import type { Agent } from './host.ts'
5
+ import { isPersonalSlot } from './personal.ts'
6
+ import type { SemanticCandidate } from './semantic.ts'
7
+ import type { ProjectMemory } from './service.ts'
8
+ import { StoreError, type Ref, type Rule } from './store.ts'
9
+
10
+ type Agreement = Rule & { kind: 'rule' | 'preference'; semanticTopic: string }
11
+
12
+ function isAgreement(rule: Rule): rule is Agreement {
13
+ return Boolean(rule.semanticTopic) && (rule.kind === 'rule' || rule.kind === 'preference')
14
+ }
15
+
16
+ /** Bind a follow-up such as "I meant this project" to the actual agreement from
17
+ * the preceding turn. An assistant-supplied ID alone cannot authorize moving it. */
18
+ export function previousScopeAgreement(memory: ProjectMemory, agent: Agent, project: AccessDomain,
19
+ ref: Ref, generation: number, turn: string): Agreement {
20
+ const old = memory.current(memory.personal, ref.id)
21
+ if (!old || old.source.sessionId !== agent.id || old.source.storeId !== memory.storeId(agent.session))
22
+ throw new StoreError('target_not_found')
23
+ if (old.rev !== ref.rev) throw new StoreError('stale_revision')
24
+ if (!isPersonalSlot(old.slot) || !isAgreement(old) ||
25
+ old.channel !== 'automatic' || old.pinned || old.usageOverride || old.sensitive || old.localException ||
26
+ old.quoteType !== 'user_quote' || !old.evidence ||
27
+ skipsAutomaticMemory([old.action, old.user_quote, old.when, old.exceptions, old.semanticTopic,
28
+ old.subject, ...(old.keywords ?? [])].join('\n')))
29
+ throw new StoreError('protected_revision')
30
+
31
+ const starts = agent.session.snapshotEvents().slice(agent.session.inheritedEventCount)
32
+ .filter(event => event.type === 'turn/start').slice(-2)
33
+ if (starts.length !== 2 || String(starts[1].data.turn) !== turn || String(starts[0].data.turn) !== old.source.turnId)
34
+ throw new StoreError('invalid_source')
35
+ const prior = memory.proposalSources(agent, agent, project, old.source.turnId, generation)
36
+ const span = old.evidence
37
+ const block = prior.events.find(event => {
38
+ const start = span.start - (event.offset ?? 0)
39
+ return event.seq === old.source.seq && event.seq === span.seq && start >= 0 &&
40
+ event.text.slice(start, start + span.end - span.start) === old.user_quote &&
41
+ (!old.source.formSelection || event.formSelections?.some(option => isDeepStrictEqual(option, old.source.formSelection)))
42
+ })
43
+ if (prior.reason || !block) throw new StoreError(prior.reason ?? 'invalid_source')
44
+ if (!memory.store.soleTurnAgreement([project.id, memory.personal.id], old.source, ref))
45
+ throw new StoreError('ambiguous_topic')
46
+ return old
47
+ }
48
+
49
+ /** Project the saved agreement. The second proposal supplies only a clarification,
50
+ * never a new body, a new subject, or model-invented path restrictions. */
51
+ export function projectAgreement(old: Agreement): SemanticCandidate {
52
+ return {
53
+ scope: 'project', kind: old.kind, topic: old.semanticTopic,
54
+ action: old.action, user_quote: old.user_quote, subject: old.subject, when: old.when,
55
+ exceptions: old.exceptions, paths: old.paths, keywords: old.keywords ?? [],
56
+ usage: old.usage ?? 'on_demand', sensitive: false, conflicts_with_repo_guidance: false,
57
+ }
58
+ }
@@ -0,0 +1,177 @@
1
+ import type { DatabaseSync } from 'node:sqlite'
2
+ import { encoderId, language } from './encoder.ts'
3
+ import { isKnowledge } from './knowledge.ts'
4
+ import { normalizeLabel } from './personal.ts'
5
+ import type { DraftItem, Ref } from './store.ts'
6
+
7
+ import { searchWords } from './search-words.ts'
8
+
9
+ export function document(rule: DraftItem) {
10
+ const detail = rule.knowledge as {
11
+ anchors?: { path: string; symbol?: string }[]
12
+ steps?: { diagnose: string; repair: string; verify: string }
13
+ trigger?: { text?: string }
14
+ } | undefined
15
+ return [rule.action, rule.when, rule.exceptions, ...rule.paths, rule.subject, rule.semanticTopic,
16
+ ...(rule.keywords ?? []), ...(detail?.anchors ?? []).map(a => a.path + ' ' + (a.symbol ?? '')),
17
+ detail?.steps?.diagnose, detail?.steps?.repair, detail?.steps?.verify, detail?.trigger?.text,
18
+ ].filter(Boolean).join(' ').slice(0, 8192)
19
+ }
20
+
21
+ // Encode complete ICU words as single FTS tokens, including punctuation inside word-like tokens.
22
+ // The second column indexes codepoint positions and supports literal substring phrases of any length.
23
+ export const indexWords = (text: string) => searchWords(text).map(word => Buffer.from(word).toString('hex'))
24
+ const characters = (text: string) => Array.from(text, char => char.codePointAt(0)!.toString(16)).join(' ')
25
+
26
+ function indexLabels(db: DatabaseSync, domain: string, rid: number | bigint, rule: DraftItem) {
27
+ const canonical = normalizeLabel(rule.semanticTopic ?? '')
28
+ const aliases = new Set([canonical, ...(rule.keywords ?? []).map(normalizeLabel)])
29
+ aliases.delete('')
30
+ if (!aliases.size) return
31
+ const subject = normalizeLabel(rule.subject ?? '')
32
+ const insert = db.prepare('INSERT INTO memory_topic_labels(domain,label,subject,rid,canonical) VALUES(?,?,?,?,?)')
33
+ for (const label of aliases)
34
+ insert.run(domain, label, subject, rid, Number(label === canonical))
35
+ }
36
+
37
+ // Each derived row belongs to the stable primary key of its source revision.
38
+ export function indexRevision(db: DatabaseSync, domain: string, rid: number | bigint, rule: DraftItem) {
39
+ indexLabels(db, domain, rid, rule)
40
+ const content = document(rule)
41
+ const text = normalizeLabel(content)
42
+ const labels = rule.sensitive || rule.usage !== 'on_demand' ? '' :
43
+ normalizeLabel([rule.semanticTopic, ...(rule.keywords ?? [])].filter(Boolean).join(' '))
44
+ db.prepare('INSERT INTO memory_fts(rowid,words,chars,labels) VALUES(?,?,?,?)')
45
+ .run(rid, indexWords(text).join(' '), characters(text), indexWords(labels).join(' '))
46
+ db.prepare('INSERT INTO memory_vector_jobs(rid,language) VALUES(?,?)').run(rid, language(content))
47
+ }
48
+
49
+ export function promptRole(rule: DraftItem) {
50
+ return isKnowledge(rule) ? null : Number(rule.usage === 'proactive' && !rule.sensitive)
51
+ }
52
+
53
+ export interface KeywordHit extends Ref { domain: string; score: number }
54
+ export class SearchIndex {
55
+ private db: DatabaseSync
56
+ constructor(db: DatabaseSync) {
57
+ this.db = db
58
+ }
59
+
60
+ create() {
61
+ this.db.exec(`
62
+ CREATE INDEX revision_current_slot ON revisions(domain,slot)
63
+ WHERE state='confirmed' AND slot IS NOT NULL;
64
+ CREATE INDEX revision_prompt_role ON revisions(domain,proactive) WHERE state='confirmed';
65
+ CREATE VIRTUAL TABLE memory_fts USING fts5(words,chars,labels,content='',contentless_delete=1);
66
+ INSERT INTO memory_fts(memory_fts,rank) VALUES('secure-delete',1);
67
+ CREATE TABLE memory_vector_jobs (rid INTEGER PRIMARY KEY, available INTEGER NOT NULL DEFAULT 0, language TEXT NOT NULL);
68
+ CREATE INDEX memory_vector_ready ON memory_vector_jobs(available,rid);
69
+ CREATE INDEX memory_vector_language_ready ON memory_vector_jobs(language,available,rid);
70
+ CREATE TABLE memory_vector_format (version TEXT PRIMARY KEY);
71
+ CREATE TRIGGER remove_retired_search AFTER UPDATE OF state ON revisions WHEN OLD.state='confirmed' AND NEW.state<>'confirmed' BEGIN
72
+ DELETE FROM memory_fts WHERE rowid=NEW.rid;
73
+ DELETE FROM memory_vector_jobs WHERE rid=NEW.rid;
74
+ END;
75
+ `)
76
+ }
77
+
78
+ ensureTopicLabels() {
79
+ if (this.db.prepare("SELECT 1 FROM sqlite_schema WHERE type='table' AND name='memory_topic_labels'").get()) {
80
+ const pending = this.db.prepare(`SELECT r.rid,r.domain,r.payload FROM memory_unindexed_topics u
81
+ CROSS JOIN revisions r ON u.rid=r.rid AND r.state='confirmed'`)
82
+ for (const row of pending.iterate())
83
+ indexLabels(this.db, String(row.domain), Number(row.rid), JSON.parse(String(row.payload)))
84
+ this.db.exec('DELETE FROM memory_unindexed_topics')
85
+ return
86
+ }
87
+ // Backfill once, under the same write transaction as initialization. Retired revisions
88
+ // never contribute aliases and consent cleanup removes their derived labels atomically.
89
+ // An older CLI sharing the same database can write FTS without knowing this index.
90
+ // The heads trigger marks just those revisions. New writers have already indexed
91
+ // their labels before they publish a head. A reader includes pending rows immediately.
92
+ const queueUnindexed = `INSERT OR IGNORE INTO memory_unindexed_topics(domain,rid)
93
+ SELECT r.domain,r.rid FROM revisions r WHERE r.domain=NEW.domain AND r.id=NEW.id AND r.rev=NEW.rev AND r.state='confirmed'
94
+ AND (json_type(r.payload,'$.semanticTopic')='text' OR json_array_length(r.payload,'$.keywords')>0)
95
+ AND NOT EXISTS(SELECT 1 FROM memory_topic_labels l WHERE l.rid=r.rid);`
96
+ this.db.exec(`CREATE TABLE memory_topic_labels (
97
+ domain TEXT NOT NULL, label TEXT NOT NULL, subject TEXT NOT NULL, rid INTEGER NOT NULL,
98
+ canonical INTEGER NOT NULL, PRIMARY KEY(domain,label,subject,rid)
99
+ ) WITHOUT ROWID;
100
+ CREATE INDEX memory_topic_revision ON memory_topic_labels(rid);
101
+ CREATE TABLE memory_unindexed_topics(domain TEXT NOT NULL,rid INTEGER NOT NULL,PRIMARY KEY(domain,rid)) WITHOUT ROWID;
102
+ CREATE TRIGGER queue_legacy_topic_insert AFTER INSERT ON heads BEGIN ${queueUnindexed} END;
103
+ CREATE TRIGGER queue_legacy_topic_update AFTER UPDATE OF rev ON heads BEGIN ${queueUnindexed} END;
104
+ CREATE INDEX memory_scope_vector_models ON memory_vectors(domain,model,id,rev);
105
+ CREATE TRIGGER retire_topic_labels AFTER UPDATE OF state ON revisions
106
+ WHEN OLD.state='confirmed' AND NEW.state<>'confirmed'
107
+ BEGIN DELETE FROM memory_topic_labels WHERE rid=OLD.rid;
108
+ DELETE FROM memory_unindexed_topics WHERE domain=OLD.domain AND rid=OLD.rid; END;`)
109
+ const heads = this.db.prepare(`SELECT r.domain,r.rid,r.payload FROM heads h
110
+ CROSS JOIN revisions r USING(domain,id,rev) WHERE r.state='confirmed'`)
111
+ for (const row of heads.iterate())
112
+ indexLabels(this.db, String(row.domain), Number(row.rid), JSON.parse(String(row.payload)))
113
+ }
114
+
115
+ topicRefs(domain: string, topic: string, subject?: string, canonicalScope?: 'global' | 'project') {
116
+ const hasSubject = canonicalScope !== undefined || subject !== undefined
117
+ const slot = canonicalScope === 'global' ? " AND r.slot GLOB 'profile.topic.*'" :
118
+ canonicalScope === 'project' ? " AND r.slot GLOB 'project.topic.*'" : ''
119
+ const normalized = normalizeLabel(topic)
120
+ const owner = normalizeLabel(subject ?? '')
121
+ const rows = this.db.prepare(`SELECT r.id,r.rev,r.confirmed,NULL AS pending FROM memory_topic_labels l
122
+ CROSS JOIN revisions r ON r.rid=l.rid CROSS JOIN heads h ON h.domain=r.domain AND h.id=r.id AND h.rev=r.rev
123
+ WHERE l.domain=? AND l.label=? ${hasSubject ? 'AND l.subject=?' : ''}${canonicalScope ? ' AND l.canonical=1' : ''}${slot}
124
+ AND r.state='confirmed'
125
+ UNION ALL SELECT r.id,r.rev,r.confirmed,r.payload AS pending FROM memory_unindexed_topics u
126
+ CROSS JOIN revisions r ON r.rid=u.rid CROSS JOIN heads h ON h.domain=r.domain AND h.id=r.id AND h.rev=r.rev
127
+ WHERE u.domain=? AND r.state='confirmed'${slot} ORDER BY 3 DESC,1`)
128
+ .all(domain, normalized, ...(hasSubject ? [owner] : []), domain)
129
+ return rows.flatMap(row => {
130
+ if (row.pending) {
131
+ const rule: DraftItem = JSON.parse(String(row.pending))
132
+ if (hasSubject && normalizeLabel(rule.subject ?? '') !== owner) return []
133
+ const labels = canonicalScope ? [rule.semanticTopic] : [rule.semanticTopic, ...(rule.keywords ?? [])]
134
+ if (!labels.some(label => label && normalizeLabel(label) === normalized)) return []
135
+ }
136
+ return [{domain, id: String(row.id), rev: Number(row.rev)}]
137
+ })
138
+ }
139
+
140
+ syncVectorFormat() {
141
+ // Changing the encoder or passage layout requeues current revisions, including completed jobs.
142
+ const version = [encoderId('en'), encoderId('zh'), 'passages-v1'].join('|')
143
+ if (!this.db.prepare('SELECT 1 FROM memory_vector_format WHERE version=?').get(version)) {
144
+ this.db.exec('DELETE FROM memory_vector_format')
145
+ const heads = this.db.prepare("SELECT r.rid,r.payload FROM heads h JOIN revisions r USING(domain,id,rev) WHERE r.state='confirmed'")
146
+ const enqueue = this.db.prepare('INSERT OR IGNORE INTO memory_vector_jobs(rid,language) VALUES(?,?)')
147
+ for (const row of heads.iterate())
148
+ enqueue.run(row.rid, language(document(JSON.parse(String(row.payload)))))
149
+ this.db.prepare('INSERT INTO memory_vector_format VALUES(?)').run(version)
150
+ }
151
+ }
152
+
153
+ matches(domains: string[], query: string, topic: string, filter?: 'review_topics'): KeywordHit[] {
154
+ if (!domains.length) return []
155
+ const q = normalizeLabel(query)
156
+ const terms = [...new Set(indexWords(normalizeLabel([query, topic].join(' '))))]
157
+ const hits = new Map<number, KeywordHit>()
158
+ const where = domains.map(() => '?').join(',')
159
+ const reviewable = filter === 'review_topics'
160
+ ? " AND r.slot IS NOT NULL AND json_extract(r.payload,'$.sensitive') IS NOT 1"
161
+ : ''
162
+ const collect = (expression: string, weight: '3' | '-bm25(memory_fts,1,0,0)') => {
163
+ const find = this.db.prepare(`SELECT r.rid,r.domain,r.id,r.rev,${weight} AS weight
164
+ FROM memory_fts CROSS JOIN revisions r ON r.rid=memory_fts.rowid
165
+ WHERE memory_fts MATCH ? AND r.domain IN (${where})${reviewable}`)
166
+ for (const row of find.iterate(expression, ...domains)) {
167
+ const rid = Number(row.rid)
168
+ const hit = hits.get(rid) ?? { domain: String(row.domain), id: String(row.id), rev: Number(row.rev), score: 0 }
169
+ hit.score += Number(row.weight)
170
+ hits.set(rid, hit)
171
+ }
172
+ }
173
+ if (terms.length) collect('words:(' + terms.join(' OR ') + ')', '-bm25(memory_fts,1,0,0)')
174
+ if (q) collect('chars:"' + characters(q) + '"', '3')
175
+ return [...hits.values()]
176
+ }
177
+ }
@@ -0,0 +1,6 @@
1
+ const segmenter = new Intl.Segmenter('zh', { granularity: 'word' })
2
+ const stop = new Set('的 了 和 是 时 在 我 你 该 请 或 a an the of at to in for and is what how'.split(' '))
3
+
4
+ export const searchWords = (text: string) => Array.from(segmenter.segment(text))
5
+ .filter(token => token.isWordLike && !stop.has(token.segment))
6
+ .map(token => token.segment)