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,380 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto'
|
|
2
|
+
import { importable, verifyImported } from './maintenance-import.ts'
|
|
3
|
+
import { parseCandidates, skipsCandidate, semanticDraft } from './semantic.ts'
|
|
4
|
+
import { refusesAutomaticMemory, skipsAutomaticMemory } from './automatic.ts'
|
|
5
|
+
import type { AccessDomain } from './domain.ts'
|
|
6
|
+
import type { Agent, Host, HostEvent, Session } from './host.ts'
|
|
7
|
+
import { messageText } from './host.ts'
|
|
8
|
+
import type { HistoryInput } from './maintenance-store.ts'
|
|
9
|
+
import { prepareItems, type UserSource } from './policy.ts'
|
|
10
|
+
import { type ProjectMemory, ruleFields } from './service.ts'
|
|
11
|
+
import { loadedGuidance, sourceStore } from './sources.ts'
|
|
12
|
+
import { isNativeProposalResult } from './proposal-receipts.ts'
|
|
13
|
+
import { verifiedQuestionForm } from './question-answers.ts'
|
|
14
|
+
import { StoreError, type DraftItem, type Source } from './store.ts'
|
|
15
|
+
import { notifyUI } from './ui.ts'
|
|
16
|
+
|
|
17
|
+
export interface StoredHandle {
|
|
18
|
+
id: string
|
|
19
|
+
header: Session['header'] & { id: string }
|
|
20
|
+
inheritedEventCount: number
|
|
21
|
+
read(offset: number, length: number): Promise<{ events: HostEvent[] }>
|
|
22
|
+
close(): Promise<void>
|
|
23
|
+
}
|
|
24
|
+
const marker = 'plugin:project-memory/source'
|
|
25
|
+
function binding(event: HostEvent, id: string, domain: AccessDomain, stream: string, cut: number) {
|
|
26
|
+
const seq = event.data.sourceSeq,
|
|
27
|
+
turn = event.data.turnId
|
|
28
|
+
if (
|
|
29
|
+
event.type !== marker ||
|
|
30
|
+
typeof event.data.memoryGeneration !== 'number' ||
|
|
31
|
+
event.data.domainId !== domain.id ||
|
|
32
|
+
event.data.storeId !== stream ||
|
|
33
|
+
typeof seq !== 'number' ||
|
|
34
|
+
!Number.isSafeInteger(seq) ||
|
|
35
|
+
seq < cut ||
|
|
36
|
+
seq >= event.seq ||
|
|
37
|
+
!turn
|
|
38
|
+
)
|
|
39
|
+
return
|
|
40
|
+
return { storeId: stream, sessionId: id, seq, turnId: turn, origin: 'user' } satisfies Source
|
|
41
|
+
}
|
|
42
|
+
function proof(source: Source, event: HostEvent, tag: HostEvent) {
|
|
43
|
+
return (
|
|
44
|
+
tag.seq +
|
|
45
|
+
':' +
|
|
46
|
+
createHash('sha256')
|
|
47
|
+
.update(JSON.stringify([source, event, tag]))
|
|
48
|
+
.digest('hex')
|
|
49
|
+
)
|
|
50
|
+
}
|
|
51
|
+
async function open(memory: ProjectMemory, id: string) {
|
|
52
|
+
const persistence = memory.ctx.get('sessionPersistence')
|
|
53
|
+
if (!persistence?.open) throw new StoreError('history_unavailable')
|
|
54
|
+
let h: StoredHandle
|
|
55
|
+
try {
|
|
56
|
+
h = await persistence.open(id, 'read')
|
|
57
|
+
} catch {
|
|
58
|
+
throw new StoreError('not_found')
|
|
59
|
+
}
|
|
60
|
+
if (
|
|
61
|
+
h.id !== id ||
|
|
62
|
+
h.header.id !== id ||
|
|
63
|
+
h.header.origin === 'subagent' ||
|
|
64
|
+
!Number.isSafeInteger(h.inheritedEventCount) ||
|
|
65
|
+
h.inheritedEventCount < 0
|
|
66
|
+
) {
|
|
67
|
+
await h.close()
|
|
68
|
+
throw new StoreError('not_found')
|
|
69
|
+
}
|
|
70
|
+
return h
|
|
71
|
+
}
|
|
72
|
+
function assertDomain(memory: ProjectMemory, agent: Agent, domain: AccessDomain, generation: number) {
|
|
73
|
+
if (memory.store.enabledGeneration() !== generation) throw new StoreError('memory_disabled')
|
|
74
|
+
if (memory.rootDomain(agent, true).id !== domain.id) throw new StoreError('unavailable')
|
|
75
|
+
}
|
|
76
|
+
function userMessage(e: HostEvent | undefined, seq: number): e is HostEvent & { type: 'user/message' } {
|
|
77
|
+
return !!e && e.seq === seq && e.type === 'user/message' && e.data.source?.kind === 'user'
|
|
78
|
+
}
|
|
79
|
+
async function enqueue(
|
|
80
|
+
memory: ProjectMemory,
|
|
81
|
+
agent: Agent,
|
|
82
|
+
d: AccessDomain,
|
|
83
|
+
id: string,
|
|
84
|
+
background: boolean,
|
|
85
|
+
generation: number,
|
|
86
|
+
) {
|
|
87
|
+
const m = memory.store.maintenance,
|
|
88
|
+
h = await open(memory, id)
|
|
89
|
+
try {
|
|
90
|
+
const stream = sourceStore(memory.ctx, memory.profile, h.header.createdAt),
|
|
91
|
+
cut = h.inheritedEventCount
|
|
92
|
+
let next = Math.max(cut, m.cursor(d.id, stream, id) + 1),
|
|
93
|
+
added = 0,
|
|
94
|
+
authorized = false
|
|
95
|
+
const available = next > cut
|
|
96
|
+
for (let page = 0; !background || page < 2 || !(available || authorized); page++) {
|
|
97
|
+
const { events } = await h.read(next, 256)
|
|
98
|
+
if (!events.length) break
|
|
99
|
+
const jobs: HistoryInput[] = []
|
|
100
|
+
for (const tag of events) {
|
|
101
|
+
const s = binding(tag, id, d, stream, cut)
|
|
102
|
+
if (!s) continue
|
|
103
|
+
const current = events[s.seq - next] ?? (await h.read(s.seq, 1)).events[0]
|
|
104
|
+
if (!userMessage(current, s.seq)) continue
|
|
105
|
+
const source = { ...s, time: current.time }
|
|
106
|
+
jobs.push({ source, proof: proof(source, current, tag) })
|
|
107
|
+
authorized = true
|
|
108
|
+
}
|
|
109
|
+
assertDomain(memory, agent, d, generation)
|
|
110
|
+
// Advance a domain's persisted cursor only after positive project authority. An
|
|
111
|
+
// arbitrary foreign session ID leaves no observable job, count, or cursor.
|
|
112
|
+
if (available || authorized) added += m.enqueue(d.id, stream, id, jobs, events.at(-1)!.seq, agent.id)
|
|
113
|
+
next = events.at(-1)!.seq + 1
|
|
114
|
+
if (events.length < 256) break
|
|
115
|
+
}
|
|
116
|
+
if (!available && !authorized) throw new StoreError('not_found')
|
|
117
|
+
return { stream, added }
|
|
118
|
+
} finally {
|
|
119
|
+
await h.close()
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
// Read the originating turn, including user steering and form answers before or after the proposal.
|
|
123
|
+
async function historyTurn(handle: StoredHandle, source: Source) {
|
|
124
|
+
let start = source.seq
|
|
125
|
+
while (start > handle.inheritedEventCount) {
|
|
126
|
+
const offset = Math.max(handle.inheritedEventCount, start - 64)
|
|
127
|
+
const page = (await handle.read(offset, start - offset)).events
|
|
128
|
+
const boundary = page.findLast(event => event.type === 'turn/start' || event.type === 'turn/end')
|
|
129
|
+
if (boundary) {
|
|
130
|
+
if (boundary.type !== 'turn/start' || String(boundary.data.turn) !== source.turnId) return []
|
|
131
|
+
start = boundary.seq
|
|
132
|
+
break
|
|
133
|
+
}
|
|
134
|
+
start = offset
|
|
135
|
+
}
|
|
136
|
+
const turn: HostEvent[] = []
|
|
137
|
+
for (let next = start; ; next += 64) {
|
|
138
|
+
const page = (await handle.read(next, 64)).events
|
|
139
|
+
for (const entry of page) {
|
|
140
|
+
if (entry.type === 'turn/end' || (entry.type === 'turn/start' && entry.seq > start)) return turn
|
|
141
|
+
turn.push(entry)
|
|
142
|
+
}
|
|
143
|
+
// The source can still be steered. Release this lease for the next completed checkpoint.
|
|
144
|
+
if (page.length < 64) return undefined
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
// Reconstruct candidates from the model's actual tool call within this user turn.
|
|
149
|
+
async function extract(memory: ProjectMemory, agent: Agent, d: AccessDomain, source: Source, event: HostEvent, h: StoredHandle) {
|
|
150
|
+
if (skipsAutomaticMemory(messageText(event.data))) return []
|
|
151
|
+
const turn = await historyTurn(h, source)
|
|
152
|
+
if (!turn) return undefined
|
|
153
|
+
const cut = Math.max(h.inheritedEventCount, turn[0]?.seq ?? 0)
|
|
154
|
+
if (turn.some(entry => {
|
|
155
|
+
if (userMessage(entry, entry.seq)) return refusesAutomaticMemory(messageText(entry.data))
|
|
156
|
+
const form = entry.type === 'tool/result' ? verifiedQuestionForm(turn, cut, entry) : undefined
|
|
157
|
+
return form?.refusedBy !== undefined || form?.custom.some(answer => refusesAutomaticMemory(answer.text))
|
|
158
|
+
})) return []
|
|
159
|
+
const blocks: UserSource[] = []
|
|
160
|
+
let offset = 0
|
|
161
|
+
for (const [block, part] of (event.data.content ?? []).entries()) {
|
|
162
|
+
if (part.type !== 'text') continue
|
|
163
|
+
const text = part.text ?? ''
|
|
164
|
+
blocks.push({ domainId: d.id, storeId: source.storeId, sessionId: source.sessionId,
|
|
165
|
+
seq: source.seq, text, offset, block })
|
|
166
|
+
offset += text.length + 1
|
|
167
|
+
}
|
|
168
|
+
// A completed write already has an authoritative decision for every proposed
|
|
169
|
+
// item. Its draft labels and wording can differ from the normalized revision.
|
|
170
|
+
// Reconstruct only calls which never received a write decision.
|
|
171
|
+
const calls = new Map(turn.filter(e => e.type === 'tool/call' && e.data.name === 'project_memory_propose')
|
|
172
|
+
.map(e => [e.seq, e]))
|
|
173
|
+
const settled = new Set<string>()
|
|
174
|
+
for (const entry of turn) {
|
|
175
|
+
const message = entry.data.message
|
|
176
|
+
const call = calls.get(entry.sourceEventSeqs?.[0] ?? -1)
|
|
177
|
+
if (!call?.data.callId || !message?.toolCallId || message.isError || entry.data.error !== undefined ||
|
|
178
|
+
call.data.turn !== entry.data.turn || !isNativeProposalResult(entry, call.seq, call.data.callId, call.data.step)) continue
|
|
179
|
+
try {
|
|
180
|
+
const reply = JSON.parse(messageText(message))
|
|
181
|
+
if (['saved', 'partial', 'duplicate', 'skipped'].includes(reply?.status)) settled.add(message.toolCallId)
|
|
182
|
+
} catch { /* An interrupted or unrecognized result is not a completed write. */ }
|
|
183
|
+
}
|
|
184
|
+
const result: DraftItem[] = []
|
|
185
|
+
const guidance = loadedGuidance(agent.session, d, memory.ctx)
|
|
186
|
+
for (const entry of turn) {
|
|
187
|
+
if (entry.seq <= event.seq) continue
|
|
188
|
+
if (entry.type === 'working-directory/change' || userMessage(entry, entry.seq)) break
|
|
189
|
+
if (entry.type !== 'tool/call' || entry.data.name !== 'project_memory_propose' || settled.has(entry.data.callId ?? '') ||
|
|
190
|
+
String(entry.data.turn) !== source.turnId) continue
|
|
191
|
+
try {
|
|
192
|
+
for (const row of parseCandidates(JSON.parse(entry.data.arguments ?? ''))) {
|
|
193
|
+
if (row.scope !== 'project' || row.replaces || skipsCandidate(row) || !row.user_quote.includes(row.action)) continue
|
|
194
|
+
const [draft] = prepareItems(d, { items: [ruleFields(row)] }, blocks, guidance)
|
|
195
|
+
result.push(semanticDraft(row, draft))
|
|
196
|
+
if (result.length === 32) return result
|
|
197
|
+
}
|
|
198
|
+
} catch { /* Malformed proposals and unbound quotes supply no evidence. */ }
|
|
199
|
+
}
|
|
200
|
+
return result
|
|
201
|
+
}
|
|
202
|
+
async function runHistory(
|
|
203
|
+
memory: ProjectMemory,
|
|
204
|
+
agent: Agent,
|
|
205
|
+
d: AccessDomain,
|
|
206
|
+
id: string,
|
|
207
|
+
budget?: number,
|
|
208
|
+
explicitImport = false,
|
|
209
|
+
) {
|
|
210
|
+
if (d.id === memory.personal.id) throw new StoreError('project_required')
|
|
211
|
+
const generation = memory.store.enabledGeneration()
|
|
212
|
+
if (generation === undefined) throw new StoreError('memory_disabled')
|
|
213
|
+
const { ctx } = memory
|
|
214
|
+
const persistence = ctx.get('sessionPersistence')
|
|
215
|
+
if (!persistence?.flush) throw new StoreError('history_unavailable')
|
|
216
|
+
await persistence.flush()
|
|
217
|
+
assertDomain(memory, agent, d, generation)
|
|
218
|
+
let stream: string,
|
|
219
|
+
added = 0
|
|
220
|
+
let importOnly = false
|
|
221
|
+
const task = 'native-import-v1'
|
|
222
|
+
if (explicitImport) {
|
|
223
|
+
const h = await open(memory, id)
|
|
224
|
+
try {
|
|
225
|
+
stream = sourceStore(ctx, memory.profile, h.header.createdAt)
|
|
226
|
+
const rows = await importable(h, d, stream, memory.config.nonGitRoots ?? [], time => memory.store.memoryEnabledAt(time))
|
|
227
|
+
assertDomain(memory, agent, d, generation)
|
|
228
|
+
if (rows.found.size) {
|
|
229
|
+
importOnly = true
|
|
230
|
+
added = memory.store.maintenance.enqueue(
|
|
231
|
+
d.id,
|
|
232
|
+
stream,
|
|
233
|
+
id,
|
|
234
|
+
[...rows.found.values()],
|
|
235
|
+
rows.last,
|
|
236
|
+
agent.id,
|
|
237
|
+
task,
|
|
238
|
+
)
|
|
239
|
+
}
|
|
240
|
+
} finally {
|
|
241
|
+
await h.close()
|
|
242
|
+
}
|
|
243
|
+
}
|
|
244
|
+
// Explicit import also processes authoritative live bindings from a mixed log.
|
|
245
|
+
try {
|
|
246
|
+
const result = await enqueue(memory, agent, d, id, budget !== undefined, generation)
|
|
247
|
+
stream = result.stream
|
|
248
|
+
added += result.added
|
|
249
|
+
} catch (error) {
|
|
250
|
+
if (!importOnly || !(error instanceof StoreError && error.code === 'not_found')) throw error
|
|
251
|
+
}
|
|
252
|
+
let cachedImport: Awaited<ReturnType<typeof importable>> | undefined, cachedRevision: unknown
|
|
253
|
+
let processed = 0
|
|
254
|
+
const proposals: string[] = []
|
|
255
|
+
while (true) {
|
|
256
|
+
assertDomain(memory, agent, d, generation)
|
|
257
|
+
const m = memory.store.maintenance
|
|
258
|
+
const lease =
|
|
259
|
+
m.claim(d.id, stream!, id, agent.id, budget) ??
|
|
260
|
+
(importOnly ? m.claim(d.id, stream!, id, agent.id, undefined, Date.now(), task) : undefined)
|
|
261
|
+
if (!lease) break
|
|
262
|
+
const h = await open(memory, id)
|
|
263
|
+
let verified: string | undefined,
|
|
264
|
+
candidates: DraftItem[] | undefined = []
|
|
265
|
+
try {
|
|
266
|
+
const src = lease.source,
|
|
267
|
+
tagSeq = Number(lease.proof.split(':', 1)[0])
|
|
268
|
+
if (lease.task === task && sourceStore(ctx, memory.profile, h.header.createdAt) === stream!) {
|
|
269
|
+
const revision = (await persistence.stat?.(id))?.revision
|
|
270
|
+
if (!cachedImport || !revision || revision !== cachedRevision) {
|
|
271
|
+
cachedImport = await importable(h, d, stream!, memory.config.nonGitRoots ?? [], time => memory.store.memoryEnabledAt(time))
|
|
272
|
+
cachedRevision = revision
|
|
273
|
+
}
|
|
274
|
+
const result = cachedImport.found.get(src.seq),
|
|
275
|
+
event = (await h.read(src.seq, 1)).events[0]
|
|
276
|
+
if (
|
|
277
|
+
result &&
|
|
278
|
+
userMessage(event, src.seq) &&
|
|
279
|
+
result.proof === lease.proof &&
|
|
280
|
+
verifyImported(result, event, d, memory.config.nonGitRoots ?? [])
|
|
281
|
+
) {
|
|
282
|
+
verified = result.proof
|
|
283
|
+
candidates = (await extract(memory, agent, d, src, event, h))?.map((item) => ({
|
|
284
|
+
...item,
|
|
285
|
+
historyAuthority: 'reconstructed_cwd',
|
|
286
|
+
}))
|
|
287
|
+
}
|
|
288
|
+
} else if (
|
|
289
|
+
sourceStore(ctx, memory.profile, h.header.createdAt) === stream! &&
|
|
290
|
+
src.seq >= h.inheritedEventCount
|
|
291
|
+
) {
|
|
292
|
+
const event = (await h.read(src.seq, 1)).events[0],
|
|
293
|
+
tag = (await h.read(tagSeq, 1)).events[0]
|
|
294
|
+
const bound = tag && binding(tag, id, d, stream!, h.inheritedEventCount)
|
|
295
|
+
if (userMessage(event, src.seq) && bound?.seq === src.seq && bound.turnId === src.turnId) {
|
|
296
|
+
verified = proof({ ...bound, time: event.time }, event, tag)
|
|
297
|
+
if (verified === lease.proof) candidates = await extract(memory, agent, d, src, event, h)
|
|
298
|
+
}
|
|
299
|
+
}
|
|
300
|
+
} finally {
|
|
301
|
+
await h.close()
|
|
302
|
+
}
|
|
303
|
+
if (memory.store.enabledGeneration() !== generation) {
|
|
304
|
+
m.defer(lease)
|
|
305
|
+
throw new StoreError('memory_disabled')
|
|
306
|
+
}
|
|
307
|
+
assertDomain(memory, agent, d, generation)
|
|
308
|
+
if (!candidates) {
|
|
309
|
+
m.defer(lease)
|
|
310
|
+
break
|
|
311
|
+
}
|
|
312
|
+
const result = m.complete(lease, verified, candidates)
|
|
313
|
+
if (result.id) proposals.push(result.id)
|
|
314
|
+
processed++
|
|
315
|
+
}
|
|
316
|
+
if (proposals.length) notifyUI(ctx, agent.id)
|
|
317
|
+
return { queued: added, processed, proposals }
|
|
318
|
+
}
|
|
319
|
+
export function registerMaintenance(ctx: Host, memory: ProjectMemory) {
|
|
320
|
+
const budget = memory.config.historyBudget ?? 0
|
|
321
|
+
if (!Number.isSafeInteger(budget) || budget < 0) throw new StoreError('invalid_history_budget')
|
|
322
|
+
if (!budget) return async () => {}
|
|
323
|
+
const running = new Map<Session, Promise<void>>()
|
|
324
|
+
let closed = false
|
|
325
|
+
function checkpoint(session: Session) {
|
|
326
|
+
const active = running.get(session)
|
|
327
|
+
if (active) return active
|
|
328
|
+
if (closed || !memory.store.memoryEnabled() || session.header.origin === 'subagent' ||
|
|
329
|
+
session.snapshotEvents().findLast(e => e.type === 'turn/start' || e.type === 'turn/end')?.type !== 'turn/end') return
|
|
330
|
+
const agent = ctx.agents.get(session.id)
|
|
331
|
+
if (!agent || agent.session !== session) return
|
|
332
|
+
const work = Promise.resolve().then(async () => {
|
|
333
|
+
if (closed) return
|
|
334
|
+
try {
|
|
335
|
+
const d = memory.rootDomain(agent, true)
|
|
336
|
+
if (d.id !== memory.personal.id) await runHistory(memory, agent, d, session.id, budget)
|
|
337
|
+
} catch (error) {
|
|
338
|
+
if (!closed && !(error instanceof StoreError && ['not_found', 'read_only', 'unavailable', 'project_required', 'memory_disabled'].includes(error.code)))
|
|
339
|
+
ctx.logger.warn('本轮历史整理暂缓;后续持久化检查点可重试。')
|
|
340
|
+
}
|
|
341
|
+
}).finally(() => running.delete(session))
|
|
342
|
+
running.set(session, work)
|
|
343
|
+
return work
|
|
344
|
+
}
|
|
345
|
+
ctx.on('session/event', (session: Session, event: HostEvent) => {
|
|
346
|
+
if (event.type === 'turn/end') void checkpoint(session)
|
|
347
|
+
})
|
|
348
|
+
ctx.on('session/flush', checkpoint)
|
|
349
|
+
return async () => {
|
|
350
|
+
closed = true
|
|
351
|
+
await Promise.all(running.values())
|
|
352
|
+
}
|
|
353
|
+
}
|
|
354
|
+
export async function maintenanceCommand(memory: ProjectMemory, agent: Agent, verb: string, query: string) {
|
|
355
|
+
let d = memory.rootDomain(agent, true)
|
|
356
|
+
if (verb === 'history') {
|
|
357
|
+
const explicitImport = /^import\s+/u.test(query)
|
|
358
|
+
const id = explicitImport ? query.slice(6).trim() : query.trim() || agent.id
|
|
359
|
+
if (!/^[\w.-]{1,160}$/u.test(id)) throw new StoreError('not_found')
|
|
360
|
+
return runHistory(memory, agent, d, id, undefined, explicitImport)
|
|
361
|
+
}
|
|
362
|
+
if ((verb === 'backup' || verb === 'restore') && /^(?:personal)(?:\s|$)/u.test(query)) {
|
|
363
|
+
d = memory.personal
|
|
364
|
+
query = query.slice('personal'.length).trim()
|
|
365
|
+
}
|
|
366
|
+
if (verb === 'backup' && !query.trim()) return memory.store.maintenance.backup(d.id)
|
|
367
|
+
if (verb === 'restore' && /^backup-[a-f0-9-]{36}$/u.test(query)) {
|
|
368
|
+
const result = memory.store.maintenance.restore(d.id, query, agent.id)
|
|
369
|
+
notifyUI(memory.ctx, agent.id)
|
|
370
|
+
return result
|
|
371
|
+
}
|
|
372
|
+
const ref = /^(mem-[a-z0-9-]+)@([1-9]\d*)$/iu.exec(query)
|
|
373
|
+
if (verb === 'clear' && ref) {
|
|
374
|
+
d = memory.owner(agent, d, ref[1]) ?? d
|
|
375
|
+
const result = memory.store.clear(d.id, ref[1], Number(ref[2]), agent.id)
|
|
376
|
+
notifyUI(memory.ctx, agent.id)
|
|
377
|
+
return { state: 'cleared', ...result }
|
|
378
|
+
}
|
|
379
|
+
throw new StoreError('invalid_command')
|
|
380
|
+
}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
interface TextBlock { type: string; text?: string }
|
|
2
|
+
interface Chunk { type: string; reason?: { kind: string } }
|
|
3
|
+
export interface ReviewSdk {
|
|
4
|
+
createUserMessage(value: object): unknown
|
|
5
|
+
BlockAssembler: new () => { push(chunk: Chunk): void; blocks(): TextBlock[] }
|
|
6
|
+
}
|
|
7
|
+
|
|
8
|
+
interface ReviewRequest {
|
|
9
|
+
provider: string; model: string; system: string; messages: unknown[]; maxTokens: number
|
|
10
|
+
signal: AbortSignal; reasoningEffort?: string
|
|
11
|
+
}
|
|
12
|
+
/** A side request through the active DSH route. It has no tools and creates no session turn. */
|
|
13
|
+
export async function reviewText(llm: {stream(request: ReviewRequest): AsyncIterable<Chunk>},
|
|
14
|
+
sdk: ReviewSdk, request: ReviewRequest) {
|
|
15
|
+
request.signal.throwIfAborted()
|
|
16
|
+
const assembler = new sdk.BlockAssembler()
|
|
17
|
+
let stopped = false
|
|
18
|
+
for await (const chunk of llm.stream(request)) {
|
|
19
|
+
request.signal.throwIfAborted()
|
|
20
|
+
assembler.push(chunk)
|
|
21
|
+
if (chunk.type === 'finish') stopped = chunk.reason?.kind === 'stop'
|
|
22
|
+
}
|
|
23
|
+
const blocks = assembler.blocks()
|
|
24
|
+
if (!stopped || blocks.some(block => block.type !== 'text' && block.type !== 'reasoning'))
|
|
25
|
+
throw new Error('incomplete_model_result')
|
|
26
|
+
return blocks.filter(block => block.type === 'text').map(block => block.text ?? '').join('')
|
|
27
|
+
}
|
package/src/personal.ts
ADDED
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto'
|
|
2
|
+
|
|
3
|
+
export type PersonalSlot = `profile.topic.${string}`
|
|
4
|
+
export type MemorySlot = PersonalSlot | `project.topic.${string}`
|
|
5
|
+
|
|
6
|
+
export function normalizeLabel(label: string) {
|
|
7
|
+
return label.normalize('NFKC').trim().replace(/\s+/gu, ' ').toLowerCase()
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
export function validLabel(label: unknown): label is string {
|
|
11
|
+
return typeof label === 'string' && label.length <= 80 && !/[\p{Cc}\p{Cf}]/u.test(label) && !!normalizeLabel(label)
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export const subjectOwners = ['speaker', 'project', 'named', 'unspecified'] as const
|
|
15
|
+
export type SubjectOwner = typeof subjectOwners[number]
|
|
16
|
+
/** Canonical roles are selected by the model from the utterance. They survive a rename. */
|
|
17
|
+
export function subjectForOwner(owner: SubjectOwner, proposed?: string) {
|
|
18
|
+
if (owner === 'speaker') return 'self'
|
|
19
|
+
if (owner === 'project') return 'project'
|
|
20
|
+
return owner === 'named' ? proposed : undefined
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export function reviewedSubject(owner: unknown, proposed?: string, target?: { subject?: string }, explicit = false,
|
|
24
|
+
named?: { subject: unknown; source: string[]; aliasQuote?: unknown }):
|
|
25
|
+
{ subject: string | undefined } | { reason: 'invalid_model_result' | 'subject_mismatch' } {
|
|
26
|
+
const role = owner as SubjectOwner
|
|
27
|
+
if (!subjectOwners.includes(role)) return { reason: 'invalid_model_result' }
|
|
28
|
+
let subject = subjectForOwner(role, proposed)
|
|
29
|
+
if (role === 'named') {
|
|
30
|
+
if (!named || !validLabel(named.subject)) return { reason: 'invalid_model_result' }
|
|
31
|
+
subject = named.subject.trim()
|
|
32
|
+
const label = normalizeLabel(subject)
|
|
33
|
+
if (label === 'self' || label === 'project' || !named.source.some(text => normalizeLabel(text).includes(label)))
|
|
34
|
+
return { reason: 'subject_mismatch' }
|
|
35
|
+
if (target && proposed && normalizeLabel(proposed) !== label) {
|
|
36
|
+
// A candidate's name and the first model's label can differ. The user's own
|
|
37
|
+
// wording must support the alias and the reviewer must cite that wording.
|
|
38
|
+
const quote = named.aliasQuote
|
|
39
|
+
if (explicit || typeof quote !== 'string' || !quote.trim() || !named.source.some(text => text.includes(quote)) ||
|
|
40
|
+
![label, normalizeLabel(proposed)].every(name => normalizeLabel(quote).includes(name)))
|
|
41
|
+
return { reason: 'subject_mismatch' }
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
if (!target) return { subject }
|
|
45
|
+
const retained = normalizeLabel(target.subject ?? '')
|
|
46
|
+
if (normalizeLabel(subject ?? '') === retained) return { subject: target.subject }
|
|
47
|
+
return { reason: 'subject_mismatch' }
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** Subjects and topics are model-provided labels. Hash a tuple to avoid separator collisions. */
|
|
51
|
+
export function semanticSlot(scope: 'global' | 'project', topic: string, subject?: string,
|
|
52
|
+
context?: { when: string; paths: string[] }): MemorySlot | undefined {
|
|
53
|
+
if (!validLabel(topic) || (subject !== undefined && !validLabel(subject))) return
|
|
54
|
+
const identity = JSON.stringify([subject === undefined ? null : normalizeLabel(subject), normalizeLabel(topic),
|
|
55
|
+
...(context && (context.when || context.paths.length) ? [context.when, [...context.paths].sort()] : [])])
|
|
56
|
+
const key = createHash('sha256').update(identity).digest('hex')
|
|
57
|
+
return scope === 'global' ? `profile.topic.${key}` : `project.topic.${key}`
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
export function isSemanticSlot(slot: unknown): slot is MemorySlot {
|
|
61
|
+
return typeof slot === 'string' && /^(?:profile|project)\.topic\.[a-f0-9]{64}$/u.test(slot)
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
export function isPersonalSlot(slot: unknown): slot is PersonalSlot {
|
|
65
|
+
return isSemanticSlot(slot) && slot.startsWith('profile.')
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
export const isMemorySlot = isSemanticSlot
|