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.
- package/CHANGELOG.md +10 -0
- package/LICENSE +21 -0
- package/README.md +181 -2
- package/README.zh-CN.md +180 -0
- package/SECURITY.md +29 -0
- package/client/memory-icon.svg +21 -0
- package/cordis.patch.yml +3 -0
- package/dist/audit.js +286 -0
- package/dist/automatic.js +16 -0
- package/dist/cache.js +40 -0
- package/dist/client.js +2035 -0
- package/dist/command-scope.js +123 -0
- package/dist/commands.js +156 -0
- package/dist/consolidation-store.js +357 -0
- package/dist/consolidation.js +182 -0
- package/dist/domain.js +245 -0
- package/dist/encoder.js +138 -0
- package/dist/export-files.js +161 -0
- package/dist/file-import-store.js +120 -0
- package/dist/file-import.js +265 -0
- package/dist/foreground-attempts.js +91 -0
- package/dist/guidance.js +242 -0
- package/dist/host.js +19 -0
- package/dist/index-policy.js +191 -0
- package/dist/index.js +349 -0
- package/dist/knowledge-hooks.js +398 -0
- package/dist/knowledge.js +359 -0
- package/dist/maintenance-episodes.js +73 -0
- package/dist/maintenance-import.js +92 -0
- package/dist/maintenance-store.js +738 -0
- package/dist/maintenance.js +376 -0
- package/dist/model-review.js +16 -0
- package/dist/personal.js +60 -0
- package/dist/policy.js +382 -0
- package/dist/prompt-copy.js +93 -0
- package/dist/proposal-receipts.js +70 -0
- package/dist/proposal-review.js +656 -0
- package/dist/propose-contract.js +38 -0
- package/dist/question-answers.js +176 -0
- package/dist/retrieval.js +126 -0
- package/dist/scope-narrowing.js +49 -0
- package/dist/search-index.js +164 -0
- package/dist/search-words.js +5 -0
- package/dist/semantic.js +157 -0
- package/dist/service.js +1473 -0
- package/dist/sharing.js +289 -0
- package/dist/sources.js +149 -0
- package/dist/store.js +1578 -0
- package/dist/tool-experience.js +87 -0
- package/dist/turn-review-store.js +159 -0
- package/dist/turn-review.js +459 -0
- package/dist/ui.js +346 -0
- package/dist/vector-index.js +232 -0
- package/docs/architecture.zh-CN.md +52 -0
- package/docs/benchmark.zh-CN.md +60 -0
- package/docs/benchmarks/repository-tasks.json +5355 -0
- package/docs/images/bond-memory-principle-en.svg +644 -0
- package/docs/images/bond-memory-principle-zh.svg +644 -0
- package/docs/images/bond-memory-principle.drawio +644 -0
- package/docs/images/memory-settings-en.png +0 -0
- package/docs/images/memory-settings-zh.png +0 -0
- package/docs/images/memory-turn-recalled-en.png +0 -0
- package/docs/images/memory-turn-recalled-zh.png +0 -0
- package/docs/images/memory-turn-saved-en.png +0 -0
- package/docs/images/memory-turn-saved-zh.png +0 -0
- package/docs/media/memory-bond-name-en.gif +0 -0
- package/docs/media/memory-bond-name-en.mp4 +0 -0
- package/docs/media/memory-bond-name-zh.gif +0 -0
- package/docs/media/memory-bond-name-zh.mp4 +0 -0
- package/locale/detail.en.md +13 -0
- package/locale/detail.zh.md +13 -0
- package/locale/en.json +345 -0
- package/locale/zh.json +345 -0
- package/native/embeddings/NOTICE.md +12 -0
- package/package.json +117 -4
- package/scripts/benchmark-bond.mjs +72 -0
- package/scripts/benchmark-conditions.mjs +144 -0
- package/scripts/benchmark-example.mjs +37 -0
- package/scripts/benchmark-scale.mjs +119 -0
- package/scripts/benchmark-scenarios.mjs +57 -0
- package/scripts/benchmark-tasks.mjs +244 -0
- package/src/audit.ts +286 -0
- package/src/automatic.ts +21 -0
- package/src/cache.ts +38 -0
- package/src/command-scope.ts +125 -0
- package/src/commands.ts +159 -0
- package/src/consolidation-store.ts +350 -0
- package/src/consolidation.ts +176 -0
- package/src/domain.ts +254 -0
- package/src/encoder.ts +142 -0
- package/src/export-files.ts +178 -0
- package/src/file-import-store.ts +139 -0
- package/src/file-import.ts +256 -0
- package/src/foreground-attempts.ts +97 -0
- package/src/guidance.ts +265 -0
- package/src/host.ts +119 -0
- package/src/index-policy.ts +231 -0
- package/src/index.ts +333 -0
- package/src/knowledge-hooks.ts +456 -0
- package/src/knowledge.ts +432 -0
- package/src/maintenance-episodes.ts +76 -0
- package/src/maintenance-import.ts +107 -0
- package/src/maintenance-store.ts +868 -0
- package/src/maintenance.ts +380 -0
- package/src/model-review.ts +27 -0
- package/src/personal.ts +68 -0
- package/src/policy.ts +508 -0
- package/src/prompt-copy.ts +99 -0
- package/src/proposal-receipts.ts +59 -0
- package/src/proposal-review.ts +614 -0
- package/src/propose-contract.ts +39 -0
- package/src/question-answers.ts +181 -0
- package/src/retrieval.ts +133 -0
- package/src/scope-narrowing.ts +58 -0
- package/src/search-index.ts +177 -0
- package/src/search-words.ts +6 -0
- package/src/semantic.ts +178 -0
- package/src/service.ts +1488 -0
- package/src/sharing.ts +349 -0
- package/src/sources.ts +150 -0
- package/src/store.ts +1829 -0
- package/src/tool-experience.ts +93 -0
- package/src/turn-review-store.ts +158 -0
- package/src/turn-review.ts +418 -0
- package/src/ui.ts +385 -0
- package/src/vector-index.ts +228 -0
|
@@ -0,0 +1,350 @@
|
|
|
1
|
+
import { randomUUID } from 'node:crypto'
|
|
2
|
+
import type { DatabaseSync, SQLOutputValue } from 'node:sqlite'
|
|
3
|
+
import { skipsAutomaticMemory } from './automatic.ts'
|
|
4
|
+
import { normalizeLabel } from './personal.ts'
|
|
5
|
+
import { indexWords } from './search-index.ts'
|
|
6
|
+
import { encoderId, modelLanguages } from './encoder.ts'
|
|
7
|
+
import { StoreError, storedVector, type Ref } from './store.ts'
|
|
8
|
+
|
|
9
|
+
export interface ConsolidationItem extends Ref {
|
|
10
|
+
topic: string
|
|
11
|
+
subject?: string
|
|
12
|
+
kind: 'fact' | 'rule' | 'preference'
|
|
13
|
+
usage: 'proactive' | 'on_demand'
|
|
14
|
+
action: string
|
|
15
|
+
when: string
|
|
16
|
+
exceptions: string
|
|
17
|
+
paths: string[]
|
|
18
|
+
}
|
|
19
|
+
export interface ConsolidationPair { left: ConsolidationItem; right: ConsolidationItem }
|
|
20
|
+
export interface ConsolidationLease { domain: string; token: string }
|
|
21
|
+
export type ConsolidationOutcome = 'duplicate' | 'distinct' | 'failed' | 'stale'
|
|
22
|
+
|
|
23
|
+
const dayMs = 86_400_000
|
|
24
|
+
const intervalMs = 3_600_000
|
|
25
|
+
const leaseMs = 300_000
|
|
26
|
+
const pageSize = 24
|
|
27
|
+
type Row = Record<string, SQLOutputValue>
|
|
28
|
+
interface Candidate {
|
|
29
|
+
rid: number; session: string; item: ConsolidationItem; labels: string[]; words: Set<string>; constraints: string
|
|
30
|
+
}
|
|
31
|
+
interface Operations {
|
|
32
|
+
transaction<T>(fn: () => T): T
|
|
33
|
+
generation(): number | undefined
|
|
34
|
+
revoke(domain: string, ref: Ref, session: string): void
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
// Session IDs are used only to compare origins locally. The model projection below has no
|
|
38
|
+
// source coordinates, raw quote, or general-purpose revision payload.
|
|
39
|
+
const columns = `r.rid,r.id,r.rev,r.action,r.condition,r.paths,
|
|
40
|
+
json_extract(r.payload,'$.semanticTopic') topic,json_extract(r.payload,'$.subject') subject,
|
|
41
|
+
json_extract(r.payload,'$.exceptions') exceptions,json_extract(r.payload,'$.keywords') keywords,
|
|
42
|
+
json_extract(r.payload,'$.kind') kind,json_extract(r.payload,'$.usage') usage,
|
|
43
|
+
json_extract(r.payload,'$.hard','$.guidance') constraints,json_extract(e.source,'$.sessionId') session`
|
|
44
|
+
const joins = `JOIN heads h USING(domain,id,rev) JOIN evidence e USING(domain,id,rev)`
|
|
45
|
+
const eligible = `r.state='confirmed' AND r.slot GLOB 'project.topic.*' AND h.pinned=0
|
|
46
|
+
AND json_extract(r.payload,'$.channel')='automatic'
|
|
47
|
+
AND json_extract(r.payload,'$.kind') IN ('fact','preference','rule')
|
|
48
|
+
AND json_extract(r.payload,'$.sensitive') IS NOT 1 AND json_extract(r.payload,'$.usageOverride') IS NOT 1
|
|
49
|
+
AND json_extract(r.payload,'$.localException') IS NULL AND json_extract(r.payload,'$.semanticTopic') IS NOT NULL
|
|
50
|
+
AND e.type='user_quote' AND json_extract(e.source,'$.sessionId')<>''`
|
|
51
|
+
function candidate(row: Row | undefined): Candidate | undefined {
|
|
52
|
+
if (!row) return
|
|
53
|
+
const item: ConsolidationItem = {
|
|
54
|
+
id: String(row.id), rev: Number(row.rev), topic: String(row.topic),
|
|
55
|
+
...(row.subject != null && { subject: String(row.subject) }),
|
|
56
|
+
kind: row.kind as ConsolidationItem['kind'], usage: row.usage === 'proactive' ? 'proactive' : 'on_demand',
|
|
57
|
+
action: String(row.action), when: String(row.condition), exceptions: String(row.exceptions ?? ''),
|
|
58
|
+
paths: JSON.parse(String(row.paths)),
|
|
59
|
+
}
|
|
60
|
+
const labels: string[] = [item.topic, ...JSON.parse(String(row.keywords ?? '[]'))].map(normalizeLabel)
|
|
61
|
+
if (skipsAutomaticMemory([item.subject, ...labels, item.action, item.when, item.exceptions, ...item.paths].join(' '))) return
|
|
62
|
+
return { rid: Number(row.rid), session: String(row.session), constraints: String(row.constraints), labels, item,
|
|
63
|
+
words: new Set(indexWords(normalizeLabel([item.topic, item.action].join(' ')))) }
|
|
64
|
+
}
|
|
65
|
+
function comparable(a: Candidate, b: Candidate) {
|
|
66
|
+
// The model sees both subjects, kinds and usage policies. Repository guards
|
|
67
|
+
// are not in that projection; differing guards cannot be safely compared.
|
|
68
|
+
return a.session !== b.session && a.constraints === b.constraints
|
|
69
|
+
}
|
|
70
|
+
function lexicalSimilarity(a: Candidate, b: Candidate) {
|
|
71
|
+
if (normalizeLabel(a.item.action) === normalizeLabel(b.item.action) || a.labels.some(l => b.labels.includes(l))) return 1
|
|
72
|
+
const common = [...a.words].filter(w => b.words.has(w)).length
|
|
73
|
+
return common / Math.sqrt(Math.max(1, a.words.size * b.words.size))
|
|
74
|
+
}
|
|
75
|
+
const schema = `
|
|
76
|
+
CREATE TABLE IF NOT EXISTS consolidation_settings (
|
|
77
|
+
singleton INTEGER PRIMARY KEY CHECK(singleton=1), enabled INTEGER NOT NULL, generation INTEGER NOT NULL
|
|
78
|
+
);
|
|
79
|
+
INSERT OR IGNORE INTO consolidation_settings(singleton,enabled,generation) VALUES(1,0,0);
|
|
80
|
+
CREATE TABLE IF NOT EXISTS consolidation_scans(domain TEXT PRIMARY KEY,cursor INTEGER NOT NULL,checked INTEGER NOT NULL);
|
|
81
|
+
CREATE TABLE IF NOT EXISTS consolidation_unpin_scans(domain TEXT PRIMARY KEY,cursor INTEGER NOT NULL);
|
|
82
|
+
CREATE TABLE IF NOT EXISTS consolidation_vector_jobs(domain TEXT NOT NULL,rid INTEGER NOT NULL,
|
|
83
|
+
PRIMARY KEY(domain,rid));
|
|
84
|
+
CREATE INDEX IF NOT EXISTS consolidation_vector_lookup ON memory_vectors(domain,model) WHERE model GLOB '*/passage-0';
|
|
85
|
+
CREATE TRIGGER IF NOT EXISTS queue_consolidation_vector AFTER INSERT ON memory_vectors
|
|
86
|
+
WHEN NEW.model GLOB '*/passage-0' BEGIN
|
|
87
|
+
INSERT OR IGNORE INTO consolidation_vector_jobs SELECT r.domain,r.rid FROM revisions r
|
|
88
|
+
WHERE r.domain=NEW.domain AND r.id=NEW.id AND r.rev=NEW.rev AND r.slot GLOB 'project.topic.*';
|
|
89
|
+
END;
|
|
90
|
+
CREATE TRIGGER IF NOT EXISTS discard_retired_vector_job AFTER UPDATE OF state ON revisions
|
|
91
|
+
WHEN OLD.state='confirmed' AND NEW.state<>'confirmed' BEGIN
|
|
92
|
+
DELETE FROM consolidation_vector_jobs WHERE domain=NEW.domain AND rid=NEW.rid;
|
|
93
|
+
END;
|
|
94
|
+
CREATE INDEX IF NOT EXISTS consolidation_unpin_events ON audit(domain,seq) WHERE event='unpin';
|
|
95
|
+
CREATE TABLE IF NOT EXISTS consolidation_pairs(
|
|
96
|
+
domain TEXT NOT NULL, a INTEGER NOT NULL REFERENCES revisions(rid), b INTEGER NOT NULL REFERENCES revisions(rid),
|
|
97
|
+
state TEXT NOT NULL DEFAULT 'queued', run TEXT, decided INTEGER, kept INTEGER, priority REAL NOT NULL DEFAULT 0,
|
|
98
|
+
PRIMARY KEY(domain,a,b), CHECK(a<b), CHECK(kept IS NULL OR kept IN (a,b))
|
|
99
|
+
);
|
|
100
|
+
CREATE INDEX IF NOT EXISTS consolidation_pending ON consolidation_pairs(domain,state,b,a);
|
|
101
|
+
CREATE INDEX IF NOT EXISTS consolidation_pair_run ON consolidation_pairs(run) WHERE run IS NOT NULL;
|
|
102
|
+
CREATE TABLE IF NOT EXISTS consolidation_runs(
|
|
103
|
+
token TEXT PRIMARY KEY, domain TEXT NOT NULL, day INTEGER NOT NULL, started INTEGER NOT NULL,
|
|
104
|
+
generation INTEGER NOT NULL, memory_generation INTEGER NOT NULL, finished INTEGER, outcome TEXT
|
|
105
|
+
);
|
|
106
|
+
CREATE INDEX IF NOT EXISTS consolidation_day ON consolidation_runs(day);
|
|
107
|
+
CREATE INDEX IF NOT EXISTS consolidation_domain_start ON consolidation_runs(domain,started);
|
|
108
|
+
CREATE INDEX IF NOT EXISTS consolidation_changes ON revisions(domain,rid) WHERE state='confirmed' AND slot GLOB 'project.topic.*';
|
|
109
|
+
CREATE TRIGGER IF NOT EXISTS remove_retired_consolidation AFTER UPDATE OF state ON revisions
|
|
110
|
+
WHEN OLD.state='confirmed' AND NEW.state<>'confirmed' BEGIN
|
|
111
|
+
DELETE FROM consolidation_pairs WHERE domain=NEW.domain AND (a=NEW.rid OR b=NEW.rid) AND state NOT IN ('accepted','dismissed');
|
|
112
|
+
END;
|
|
113
|
+
CREATE TRIGGER IF NOT EXISTS remove_redacted_consolidation AFTER UPDATE OF type ON evidence
|
|
114
|
+
WHEN OLD.type='user_quote' AND NEW.type<>'user_quote' BEGIN
|
|
115
|
+
DELETE FROM consolidation_pairs WHERE domain=NEW.domain AND state NOT IN ('accepted','dismissed')
|
|
116
|
+
AND (SELECT rid FROM revisions WHERE domain=NEW.domain AND id=NEW.id AND rev=NEW.rev) IN (a,b);
|
|
117
|
+
END;
|
|
118
|
+
`
|
|
119
|
+
export class ConsolidationStore {
|
|
120
|
+
private db: DatabaseSync
|
|
121
|
+
private ops: Operations
|
|
122
|
+
constructor(db: DatabaseSync, ops: Operations) {
|
|
123
|
+
this.db = db
|
|
124
|
+
this.ops = ops
|
|
125
|
+
this.ops.transaction(() => {
|
|
126
|
+
if (db.prepare("SELECT 1 FROM pragma_table_info('consolidation_settings') WHERE name='budget'").get()) {
|
|
127
|
+
db.exec(`ALTER TABLE consolidation_settings DROP COLUMN budget;
|
|
128
|
+
ALTER TABLE consolidation_runs DROP COLUMN reserved;
|
|
129
|
+
ALTER TABLE consolidation_runs DROP COLUMN actual;`)
|
|
130
|
+
}
|
|
131
|
+
db.exec(schema)
|
|
132
|
+
if (!db.prepare("SELECT 1 FROM pragma_table_info('consolidation_pairs') WHERE name='priority'").get()) {
|
|
133
|
+
db.exec(`ALTER TABLE consolidation_pairs ADD COLUMN priority REAL NOT NULL DEFAULT 0;
|
|
134
|
+
UPDATE consolidation_scans SET cursor=-1;`)
|
|
135
|
+
}
|
|
136
|
+
})
|
|
137
|
+
}
|
|
138
|
+
private settings() {
|
|
139
|
+
return this.db.prepare('SELECT enabled,generation FROM consolidation_settings WHERE singleton=1').get()!
|
|
140
|
+
}
|
|
141
|
+
status() {
|
|
142
|
+
const now = Date.now()
|
|
143
|
+
const settings = this.settings()
|
|
144
|
+
const last = this.db.prepare(`SELECT COALESCE(finished,started+?) AS at,COALESCE(outcome,'failed') AS outcome
|
|
145
|
+
FROM consolidation_runs WHERE finished IS NOT NULL OR started<=? ORDER BY at DESC,rowid DESC LIMIT 1`).get(leaseMs, now - leaseMs)
|
|
146
|
+
const checked = this.db.prepare('SELECT max(checked) AS at FROM consolidation_scans').get()?.at
|
|
147
|
+
return { enabled: Boolean(settings.enabled),
|
|
148
|
+
lastScanAt: checked == null ? null : Number(checked),
|
|
149
|
+
lastRun: last ? { at: Number(last.at), outcome: last.outcome as ConsolidationOutcome } : null }
|
|
150
|
+
}
|
|
151
|
+
configure(change: { enabled: boolean }) {
|
|
152
|
+
if (typeof change?.enabled !== 'boolean') throw new StoreError('invalid_input')
|
|
153
|
+
return this.ops.transaction(() => {
|
|
154
|
+
if (this.ops.generation() === undefined) throw new StoreError('memory_disabled')
|
|
155
|
+
const enabled = Number(change.enabled)
|
|
156
|
+
this.db.prepare('UPDATE consolidation_settings SET enabled=?,generation=generation+1 WHERE singleton=1 AND enabled<>?')
|
|
157
|
+
.run(enabled, enabled)
|
|
158
|
+
return this.status()
|
|
159
|
+
})
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
private byRid(domain: string, rid: number) {
|
|
163
|
+
return candidate(this.db.prepare(`SELECT ${columns} FROM revisions r ${joins}
|
|
164
|
+
WHERE r.domain=? AND r.rid=? AND ${eligible}`).get(domain, rid))
|
|
165
|
+
}
|
|
166
|
+
private byRef(domain: string, ref: Ref) {
|
|
167
|
+
return candidate(this.db.prepare(`SELECT ${columns} FROM revisions r ${joins}
|
|
168
|
+
WHERE r.domain=? AND r.id=? AND r.rev=? AND ${eligible}`).get(domain, ref.id, ref.rev))
|
|
169
|
+
}
|
|
170
|
+
private available(domain: string, now: number) {
|
|
171
|
+
const settings = this.settings()
|
|
172
|
+
if (!settings.enabled || this.ops.generation() === undefined || domain === 'profile:personal') return false
|
|
173
|
+
return !this.db.prepare('SELECT 1 FROM consolidation_runs WHERE domain=? AND started>? LIMIT 1').get(domain, now - intervalMs)
|
|
174
|
+
}
|
|
175
|
+
private scan(domain: string, now: number) {
|
|
176
|
+
const cursor = Number(this.db.prepare('SELECT cursor FROM consolidation_scans WHERE domain=?').get(domain)?.cursor ?? -1)
|
|
177
|
+
const high = Number(this.db.prepare(`SELECT max(rid) AS rid FROM revisions
|
|
178
|
+
WHERE domain=? AND state='confirmed' AND slot GLOB 'project.topic.*'`).get(domain)?.rid ?? 0)
|
|
179
|
+
// Unpinning keeps the revision number. Its durable audit receipt also covers heads
|
|
180
|
+
// unpinned before this cursor existed or by another process using the same profile.
|
|
181
|
+
const unpins = this.db.prepare(`SELECT seq,memory,rev FROM audit WHERE domain=? AND event='unpin'
|
|
182
|
+
AND seq>COALESCE((SELECT cursor FROM consolidation_unpin_scans WHERE domain=?),0)
|
|
183
|
+
ORDER BY seq LIMIT ?`).all(domain, domain, pageSize)
|
|
184
|
+
if (high <= cursor && !unpins.length) return
|
|
185
|
+
const changes = this.db.prepare(`SELECT ${columns} FROM revisions r ${joins}
|
|
186
|
+
WHERE r.domain=? AND r.rid>? AND r.rid<=? AND ${eligible} ORDER BY r.rid LIMIT ?`).all(domain, cursor, high, pageSize)
|
|
187
|
+
const partners = this.db.prepare(`SELECT ${columns} FROM memory_fts CROSS JOIN revisions r ON r.rid=memory_fts.rowid ${joins}
|
|
188
|
+
WHERE memory_fts MATCH ? AND r.domain=? AND r.rid<=? AND json_extract(e.source,'$.sessionId')<>?
|
|
189
|
+
AND ${eligible} ORDER BY rank,r.rid LIMIT 32`)
|
|
190
|
+
const vectorJob = this.db.prepare(`INSERT OR IGNORE INTO consolidation_vector_jobs
|
|
191
|
+
SELECT r.domain,r.rid FROM revisions r JOIN memory_vectors v USING(domain,id,rev)
|
|
192
|
+
WHERE r.domain=? AND r.rid=? AND v.model GLOB '*/passage-0'`)
|
|
193
|
+
const queuePartners = (head: Candidate, throughRid: number) => {
|
|
194
|
+
vectorJob.run(domain, head.rid)
|
|
195
|
+
const terms = [...new Set([...head.words, ...head.labels.flatMap(indexWords)])]
|
|
196
|
+
if (!terms.length) return
|
|
197
|
+
let added = 0
|
|
198
|
+
for (const hit of partners.iterate('words:(' + terms.join(' OR ') + ')', domain, throughRid, head.session)) {
|
|
199
|
+
const other = candidate(hit)
|
|
200
|
+
if (!other || !comparable(head, other)) continue
|
|
201
|
+
this.queuePair(domain, head.rid, other.rid, lexicalSimilarity(head, other))
|
|
202
|
+
// Bound noisy common aliases. SQLite orders partners by lexical relevance.
|
|
203
|
+
if (++added === 8) break
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
for (const row of changes) {
|
|
207
|
+
const head = candidate(row)
|
|
208
|
+
if (head) queuePartners(head, head.rid - 1)
|
|
209
|
+
}
|
|
210
|
+
const rechecked = new Set<number>()
|
|
211
|
+
for (const event of unpins) {
|
|
212
|
+
const head = this.byRef(domain, { id: String(event.memory), rev: Number(event.rev) })
|
|
213
|
+
// Newer heads will visit this one in their ordinary scan. Recheck older and
|
|
214
|
+
// newer partners which the revision cursor has already passed.
|
|
215
|
+
if (!head || head.rid > cursor || rechecked.has(head.rid)) continue
|
|
216
|
+
rechecked.add(head.rid)
|
|
217
|
+
queuePartners(head, cursor)
|
|
218
|
+
}
|
|
219
|
+
if (unpins.length) this.db.prepare(`INSERT INTO consolidation_unpin_scans(domain,cursor) VALUES(?,?)
|
|
220
|
+
ON CONFLICT(domain) DO UPDATE SET cursor=excluded.cursor`).run(domain, unpins.at(-1)!.seq)
|
|
221
|
+
const watermark = changes.length < pageSize ? high : Number(changes.at(-1)!.rid)
|
|
222
|
+
this.db.prepare(`INSERT INTO consolidation_scans VALUES(?,?,?) ON CONFLICT(domain) DO UPDATE
|
|
223
|
+
SET cursor=max(cursor,excluded.cursor),checked=excluded.checked`).run(domain, watermark, now)
|
|
224
|
+
}
|
|
225
|
+
private queuePair(domain: string, a: number, b: number, priority: number) {
|
|
226
|
+
this.db.prepare(`INSERT INTO consolidation_pairs(domain,a,b,priority) VALUES(?,?,?,?)
|
|
227
|
+
ON CONFLICT(domain,a,b) DO UPDATE SET priority=max(priority,excluded.priority) WHERE state='queued'`)
|
|
228
|
+
.run(domain, Math.min(a, b), Math.max(a, b), priority)
|
|
229
|
+
}
|
|
230
|
+
private scanVectors(domain: string) {
|
|
231
|
+
const jobs = this.db.prepare('SELECT rid FROM consolidation_vector_jobs WHERE domain=? ORDER BY rid LIMIT 4').all(domain)
|
|
232
|
+
if (!jobs.length) return
|
|
233
|
+
const models = modelLanguages.map(lang => encoderId(lang) + '/passage-0')
|
|
234
|
+
const vectors = this.db.prepare(`SELECT r.rid,v.dimensions,v.vector FROM memory_vectors v
|
|
235
|
+
JOIN revisions r USING(domain,id,rev) ${joins}
|
|
236
|
+
WHERE v.domain=? AND v.model=? AND v.model GLOB '*/passage-0' AND r.rid<>? AND ${eligible}
|
|
237
|
+
AND json_extract(e.source,'$.sessionId')<>?
|
|
238
|
+
AND json_extract(r.payload,'$.hard','$.guidance')=?`)
|
|
239
|
+
for (const {rid} of jobs) {
|
|
240
|
+
const head = this.byRid(domain, Number(rid))
|
|
241
|
+
if (head) {
|
|
242
|
+
const passages = this.db.prepare(`SELECT model,dimensions,vector FROM memory_vectors
|
|
243
|
+
WHERE domain=? AND id=? AND rev=? AND model IN (?,?)`).all(domain, head.item.id, head.item.rev, ...models)
|
|
244
|
+
for (const passage of passages) {
|
|
245
|
+
const q = storedVector(passage)
|
|
246
|
+
if (!q) continue
|
|
247
|
+
const best: {rid: number; score: number}[] = []
|
|
248
|
+
for (const other of vectors.iterate(domain, passage.model, rid, head.session, head.constraints)) {
|
|
249
|
+
const v = storedVector(other)
|
|
250
|
+
if (!v || v.length !== q.length) continue
|
|
251
|
+
const score = v.reduce((sum, value, i) => sum + value * q[i], 0)
|
|
252
|
+
if (score < 0.65 || (best.length === 8 && score <= best[7].score)) continue
|
|
253
|
+
best.push({ rid: Number(other.rid), score })
|
|
254
|
+
best.sort((a, b) => b.score - a.score || a.rid - b.rid)
|
|
255
|
+
if (best.length > 8) best.pop()
|
|
256
|
+
}
|
|
257
|
+
for (const hit of best) this.queuePair(domain, Number(rid), hit.rid, hit.score)
|
|
258
|
+
}
|
|
259
|
+
}
|
|
260
|
+
this.db.prepare('DELETE FROM consolidation_vector_jobs WHERE domain=? AND rid=?').run(domain, rid)
|
|
261
|
+
}
|
|
262
|
+
}
|
|
263
|
+
next(domain: string, visible: (ref: Ref) => boolean = () => true): ConsolidationPair | undefined {
|
|
264
|
+
const now = Date.now()
|
|
265
|
+
if (!this.available(domain, now)) return
|
|
266
|
+
const scanned = this.ops.transaction(() => {
|
|
267
|
+
if (!this.available(domain, now)) return false
|
|
268
|
+
const cutoff = Math.floor(now / dayMs) - 30
|
|
269
|
+
// Decisions belong to immutable revisions. Keep the latest run for the settings screen.
|
|
270
|
+
this.db.prepare(`UPDATE consolidation_pairs SET state='queued',run=NULL
|
|
271
|
+
WHERE state IN ('failed','stale','running') AND run IN (SELECT token FROM consolidation_runs WHERE day<?)`).run(cutoff)
|
|
272
|
+
this.db.prepare(`DELETE FROM consolidation_runs WHERE day<? AND token<>(
|
|
273
|
+
SELECT token FROM consolidation_runs ORDER BY started DESC LIMIT 1)`).run(cutoff)
|
|
274
|
+
this.scan(domain, now)
|
|
275
|
+
this.scanVectors(domain)
|
|
276
|
+
return true
|
|
277
|
+
})
|
|
278
|
+
if (!scanned) return
|
|
279
|
+
const pending = this.db.prepare(`SELECT p.a,p.b FROM consolidation_pairs p LEFT JOIN consolidation_runs t ON p.run=t.token
|
|
280
|
+
WHERE p.domain=? AND (p.state='queued' OR (p.state IN ('failed','stale','running') AND t.day<?))
|
|
281
|
+
ORDER BY p.state='queued' DESC,p.priority DESC,p.b,p.a`)
|
|
282
|
+
for (const row of pending.iterate(domain, Math.floor(now / dayMs))) {
|
|
283
|
+
const left = this.byRid(domain, Number(row.a)), right = this.byRid(domain, Number(row.b))
|
|
284
|
+
if (!left || !right || !comparable(left, right) || !visible(left.item) || !visible(right.item)) continue
|
|
285
|
+
return { left: left.item, right: right.item }
|
|
286
|
+
}
|
|
287
|
+
}
|
|
288
|
+
reserve(domain: string, pair: ConsolidationPair): ConsolidationLease | undefined {
|
|
289
|
+
return this.ops.transaction(() => {
|
|
290
|
+
const now = Date.now()
|
|
291
|
+
if (!this.available(domain, now)) return
|
|
292
|
+
const left = this.byRef(domain, pair.left), right = this.byRef(domain, pair.right)
|
|
293
|
+
if (!left || !right || !comparable(left, right)) return
|
|
294
|
+
const day = Math.floor(now / dayMs)
|
|
295
|
+
const token = randomUUID()
|
|
296
|
+
const changed = this.db.prepare(`UPDATE consolidation_pairs SET state='running',run=?
|
|
297
|
+
WHERE domain=? AND a=? AND b=? AND (state='queued' OR (state IN ('failed','stale','running') AND
|
|
298
|
+
run IN (SELECT token FROM consolidation_runs WHERE day<?)))`).run(token, domain, left.rid, right.rid, day)
|
|
299
|
+
if (!changed.changes) return
|
|
300
|
+
this.db.prepare(`INSERT INTO consolidation_runs(token,domain,day,started,generation,memory_generation)
|
|
301
|
+
VALUES(?,?,?,?,?,?)`).run(token, domain, day, now, this.settings().generation, this.ops.generation()!)
|
|
302
|
+
return { domain, token }
|
|
303
|
+
})
|
|
304
|
+
}
|
|
305
|
+
current(lease: ConsolidationLease): boolean {
|
|
306
|
+
const now = Date.now(), settings = this.settings(), generation = this.ops.generation()
|
|
307
|
+
if (!settings.enabled || generation === undefined) return false
|
|
308
|
+
const p = this.db.prepare(`SELECT p.a,p.b FROM consolidation_pairs p JOIN consolidation_runs t ON t.token=p.run
|
|
309
|
+
WHERE p.domain=? AND p.run=? AND p.state='running' AND t.finished IS NULL AND t.started>?
|
|
310
|
+
AND t.generation=? AND t.memory_generation=?`).get(lease.domain, lease.token, now - leaseMs, settings.generation, generation)
|
|
311
|
+
if (!p) return false
|
|
312
|
+
const left = this.byRid(lease.domain, Number(p.a)), right = this.byRid(lease.domain, Number(p.b))
|
|
313
|
+
return Boolean(left && right && comparable(left, right))
|
|
314
|
+
}
|
|
315
|
+
finish(lease: ConsolidationLease, outcome: ConsolidationOutcome) {
|
|
316
|
+
if (!['duplicate','distinct','failed','stale'].includes(outcome)) throw new StoreError('invalid_input')
|
|
317
|
+
return this.ops.transaction(() => {
|
|
318
|
+
if (!this.current(lease)) outcome = 'stale'
|
|
319
|
+
const settled = this.db.prepare(`UPDATE consolidation_runs SET finished=?,outcome=?
|
|
320
|
+
WHERE token=? AND domain=? AND finished IS NULL`).run(Date.now(), outcome, lease.token, lease.domain)
|
|
321
|
+
if (!settled.changes) return false
|
|
322
|
+
this.db.prepare(`UPDATE consolidation_pairs SET state=? WHERE run=? AND domain=? AND state='running'`)
|
|
323
|
+
.run(outcome, lease.token, lease.domain)
|
|
324
|
+
return true
|
|
325
|
+
})
|
|
326
|
+
}
|
|
327
|
+
suggestions(domain: string): { left: Ref; right: Ref }[] {
|
|
328
|
+
const result: { left: Ref; right: Ref }[] = []
|
|
329
|
+
for (const row of this.db.prepare("SELECT a,b FROM consolidation_pairs WHERE domain=? AND state='duplicate' ORDER BY b,a").iterate(domain)) {
|
|
330
|
+
const left = this.byRid(domain, Number(row.a)), right = this.byRid(domain, Number(row.b))
|
|
331
|
+
if (left && right && comparable(left, right))
|
|
332
|
+
result.push({ left: { id: left.item.id, rev: left.item.rev }, right: { id: right.item.id, rev: right.item.rev } })
|
|
333
|
+
}
|
|
334
|
+
return result
|
|
335
|
+
}
|
|
336
|
+
decide(domain: string, a: Ref, b: Ref, keep: Ref | null, sessionId: string) {
|
|
337
|
+
return this.ops.transaction(() => {
|
|
338
|
+
const left = this.byRef(domain, a), right = this.byRef(domain, b)
|
|
339
|
+
if (!left || !right || !comparable(left, right)) throw new StoreError('conflict')
|
|
340
|
+
if (keep && ![a,b].some(r => r.id === keep.id && r.rev === keep.rev)) throw new StoreError('invalid_input')
|
|
341
|
+
const kept = keep ? (keep.id === a.id ? left.rid : right.rid) : null
|
|
342
|
+
const decision = this.db.prepare(`UPDATE consolidation_pairs SET state=?,decided=?,kept=?
|
|
343
|
+
WHERE domain=? AND a=? AND b=? AND state='duplicate'`).run(keep ? 'accepted' : 'dismissed',
|
|
344
|
+
Date.now(), kept, domain, Math.min(left.rid, right.rid), Math.max(left.rid, right.rid))
|
|
345
|
+
if (!decision.changes) throw new StoreError('conflict')
|
|
346
|
+
if (keep) this.ops.revoke(domain, keep.id === a.id ? b : a, sessionId)
|
|
347
|
+
return { status: keep ? 'accepted' : 'dismissed' }
|
|
348
|
+
})
|
|
349
|
+
}
|
|
350
|
+
}
|
|
@@ -0,0 +1,176 @@
|
|
|
1
|
+
import { prompts } from './prompt-copy.ts'
|
|
2
|
+
import type { ConsolidationOutcome, ConsolidationPair } from './consolidation-store.ts'
|
|
3
|
+
import type { HostEvent, Session } from './host.ts'
|
|
4
|
+
import { reviewText, type ReviewSdk } from './model-review.ts'
|
|
5
|
+
import type { ProjectMemory } from './service.ts'
|
|
6
|
+
|
|
7
|
+
interface Job {
|
|
8
|
+
sessionId: string
|
|
9
|
+
session: WeakRef<Session>
|
|
10
|
+
domain: string
|
|
11
|
+
cwd: string
|
|
12
|
+
route: { provider: string; model: string }
|
|
13
|
+
idle: boolean
|
|
14
|
+
nextAt: number
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
const maxOutput = 64
|
|
18
|
+
const hour = 60 * 60 * 1000
|
|
19
|
+
|
|
20
|
+
function describe({ topic, subject, kind, usage, action, when, exceptions, paths }: ConsolidationPair['left']) {
|
|
21
|
+
return { topic, subject, kind, usage, action, when, exceptions, paths }
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
const modelInput = (pair: ConsolidationPair) => JSON.stringify({ left: describe(pair.left), right: describe(pair.right) })
|
|
25
|
+
|
|
26
|
+
function decision(text: string): 'duplicate' | 'distinct' {
|
|
27
|
+
const clean = text.trim().replace(/^\x60\x60\x60(?:json)?\s*\n([\s\S]*)\n\x60\x60\x60$/iu, '$1')
|
|
28
|
+
const answer = JSON.parse(clean)
|
|
29
|
+
if (answer && Object.keys(answer).length === 1 && ['duplicate', 'distinct'].includes(answer.decision))
|
|
30
|
+
return answer.decision
|
|
31
|
+
throw new Error('invalid_consolidation_result')
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** Keep only a bounded set of completed root sessions. Their live project and route authorize each call. */
|
|
35
|
+
export function registerConsolidation(memory: ProjectMemory, sdk: ReviewSdk,
|
|
36
|
+
{ idleMs = 1500, intervalMs = hour, timeoutMs = 30_000, checkMs = 1000 } = {}) {
|
|
37
|
+
const host = memory.ctx
|
|
38
|
+
const store = memory.store.consolidation
|
|
39
|
+
const projects = new Map<string, Job>()
|
|
40
|
+
let timer: NodeJS.Timeout | undefined
|
|
41
|
+
let active: { job: Job; controller: AbortController; done: Promise<void> } | undefined
|
|
42
|
+
let closed = false
|
|
43
|
+
|
|
44
|
+
function live(job: Job) {
|
|
45
|
+
const agent = host.agents.get(job.sessionId)
|
|
46
|
+
if (!agent || !job.idle || agent.session !== job.session.deref()) return
|
|
47
|
+
const route = agent.model?.current()
|
|
48
|
+
if (route?.provider !== job.route.provider || route.model !== job.route.model) return
|
|
49
|
+
const domain = memory.rootDomain(agent, true)
|
|
50
|
+
return domain.id === job.domain && domain.cwd === job.cwd ? domain : undefined
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
async function run(job: Job, controller: AbortController) {
|
|
54
|
+
if (closed || controller.signal.aborted) return
|
|
55
|
+
const domain = live(job)
|
|
56
|
+
if (!domain) {
|
|
57
|
+
if (projects.get(job.domain) === job) projects.delete(job.domain)
|
|
58
|
+
return
|
|
59
|
+
}
|
|
60
|
+
const llm = host.get('llm')
|
|
61
|
+
if (!memory.store.memoryEnabled() || !store.status().enabled || !llm?.stream) return
|
|
62
|
+
const pair = store.next(job.domain, ref => !!memory.current(domain, ref.id, ref.rev))
|
|
63
|
+
host.emit('project-memory/consolidation-updated')
|
|
64
|
+
if (!pair) return
|
|
65
|
+
const request = {
|
|
66
|
+
...job.route, system: prompts[memory.promptLanguage(host.agents.get(job.sessionId))].consolidate, maxTokens: maxOutput,
|
|
67
|
+
signal: controller.signal, messages: [sdk.createUserMessage({
|
|
68
|
+
source: { kind: 'project-memory-consolidation' }, content: [{ type: 'text', text: modelInput(pair) }],
|
|
69
|
+
})],
|
|
70
|
+
}
|
|
71
|
+
const lease = store.reserve(job.domain, pair)
|
|
72
|
+
if (!lease) return
|
|
73
|
+
let outcome: ConsolidationOutcome = 'failed'
|
|
74
|
+
let timeout: NodeJS.Timeout | undefined
|
|
75
|
+
let guard: NodeJS.Timeout | undefined
|
|
76
|
+
let timedOut = false
|
|
77
|
+
let onAbort: (() => void) | undefined
|
|
78
|
+
const eligible = () => {
|
|
79
|
+
const now = live(job)
|
|
80
|
+
return now && store.current(lease) && memory.current(now, pair.left.id, pair.left.rev) &&
|
|
81
|
+
memory.current(now, pair.right.id, pair.right.rev)
|
|
82
|
+
}
|
|
83
|
+
try {
|
|
84
|
+
host.emit('project-memory/consolidation-updated')
|
|
85
|
+
if (controller.signal.aborted || !eligible()) {
|
|
86
|
+
outcome = 'stale'
|
|
87
|
+
return
|
|
88
|
+
}
|
|
89
|
+
const aborted = new Promise<never>((_, reject) => {
|
|
90
|
+
onAbort = () => reject(new Error('cancelled'))
|
|
91
|
+
controller.signal.addEventListener('abort', onAbort, { once: true })
|
|
92
|
+
})
|
|
93
|
+
timeout = setTimeout(() => { timedOut = true; controller.abort() }, timeoutMs)
|
|
94
|
+
timeout.unref()
|
|
95
|
+
// Other DSH processes may change settings/revisions without notifying this host.
|
|
96
|
+
guard = setInterval(() => {
|
|
97
|
+
try { if (eligible()) return } catch { /* access may have been revoked */ }
|
|
98
|
+
controller.abort()
|
|
99
|
+
}, checkMs)
|
|
100
|
+
guard.unref()
|
|
101
|
+
const classify = async () => {
|
|
102
|
+
// DSH rejects reasoningEffort even as "off" on models which do not advertise it.
|
|
103
|
+
// Preparation checks controls without sending memory to the provider.
|
|
104
|
+
const prepared = await llm.prepareCall?.({ ...job.route, maxTokens: maxOutput }, controller.signal,
|
|
105
|
+
(controls: object, info: { reasoning?: { efforts: {id: string}[] } }) =>
|
|
106
|
+
info.reasoning?.efforts.some(e => e.id === 'off') ? { ...controls, reasoningEffort: 'off' } : controls)
|
|
107
|
+
controller.signal.throwIfAborted()
|
|
108
|
+
if (!eligible()) { controller.abort(); throw new Error('cancelled') }
|
|
109
|
+
return reviewText(prepared ?? llm, sdk, { ...request, ...prepared?.config })
|
|
110
|
+
}
|
|
111
|
+
const reply = await Promise.race([aborted, classify()])
|
|
112
|
+
outcome = !controller.signal.aborted && eligible() ? decision(reply) : 'stale'
|
|
113
|
+
} catch {
|
|
114
|
+
outcome = controller.signal.aborted && !timedOut ? 'stale' : 'failed'
|
|
115
|
+
} finally {
|
|
116
|
+
clearInterval(guard)
|
|
117
|
+
clearTimeout(timeout)
|
|
118
|
+
if (onAbort) controller.signal.removeEventListener('abort', onAbort)
|
|
119
|
+
store.finish(lease, outcome)
|
|
120
|
+
host.emit('project-memory/consolidation-updated')
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
function schedule() {
|
|
125
|
+
clearTimeout(timer)
|
|
126
|
+
if (closed || active) return
|
|
127
|
+
const next = [...projects.values()].filter(job => job.idle).sort((a, b) => a.nextAt - b.nextAt)[0]
|
|
128
|
+
if (!next) return
|
|
129
|
+
timer = setTimeout(() => {
|
|
130
|
+
next.nextAt = Date.now() + intervalMs
|
|
131
|
+
const controller = new AbortController()
|
|
132
|
+
const done = Promise.resolve().then(() => run(next, controller)).catch(() => {
|
|
133
|
+
if (!controller.signal.aborted) host.logger.warn('跨会话记忆整理暂缓,待下次空闲检查。')
|
|
134
|
+
}).finally(() => { active = undefined; schedule() })
|
|
135
|
+
active = { job: next, controller, done }
|
|
136
|
+
}, Math.max(0, next.nextAt - Date.now()))
|
|
137
|
+
timer.unref()
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
host.on('session/event', (session: Session, event: HostEvent) => {
|
|
141
|
+
if (closed || session.header.origin === 'subagent' || event.seq < session.inheritedEventCount) return
|
|
142
|
+
if (event.type === 'turn/start') {
|
|
143
|
+
for (const job of projects.values()) if (job.session.deref() === session) job.idle = false
|
|
144
|
+
if (active?.job.session.deref() === session) active.controller.abort()
|
|
145
|
+
schedule()
|
|
146
|
+
return
|
|
147
|
+
}
|
|
148
|
+
if (event.type !== 'turn/end' || event.data.reason?.kind !== 'completed') return
|
|
149
|
+
try {
|
|
150
|
+
const agent = host.agents.get(session.id)
|
|
151
|
+
const route = agent?.model?.current()
|
|
152
|
+
if (!agent || agent.session !== session || !route?.provider || !route.model) return
|
|
153
|
+
const d = memory.rootDomain(agent, true)
|
|
154
|
+
if (d.id === memory.personal.id) return
|
|
155
|
+
const previous = projects.get(d.id)
|
|
156
|
+
const nextAt = Math.max(previous?.nextAt ?? 0, Date.now() + idleMs)
|
|
157
|
+
if (!previous && projects.size >= 64) projects.delete(projects.keys().next().value!)
|
|
158
|
+
projects.set(d.id, { sessionId: session.id, session: new WeakRef(session), domain: d.id,
|
|
159
|
+
cwd: d.cwd, route: { provider: route.provider, model: route.model }, idle: true, nextAt })
|
|
160
|
+
schedule()
|
|
161
|
+
} catch { /* a read-only or inaccessible project cannot authorize a background call */ }
|
|
162
|
+
})
|
|
163
|
+
host.on('project-memory/consolidation-settings-changed', () => {
|
|
164
|
+
if (closed) return
|
|
165
|
+
active?.controller.abort()
|
|
166
|
+
for (const job of projects.values()) job.nextAt = Date.now() + idleMs
|
|
167
|
+
schedule()
|
|
168
|
+
})
|
|
169
|
+
return async () => {
|
|
170
|
+
closed = true
|
|
171
|
+
clearTimeout(timer)
|
|
172
|
+
projects.clear()
|
|
173
|
+
active?.controller.abort()
|
|
174
|
+
await active?.done
|
|
175
|
+
}
|
|
176
|
+
}
|