dsh-memu-memory 1.2.8 → 1.3.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 +494 -0
- package/README.md +1 -1
- package/README.zh.md +1 -1
- package/docs/memory-semantics.md +3 -2
- package/lib/backup.js +154 -25
- package/lib/binding-diagnostics.js +2 -3
- package/lib/budget.js +0 -9
- package/lib/client.js +221 -128
- package/lib/commitment.js +3 -3
- package/lib/consolidation-ledger.js +46 -3
- package/lib/consolidation-receipt.js +41 -16
- package/lib/consolidation-worker.js +34 -10
- package/lib/curator-policy.js +23 -0
- package/lib/cycle.js +8 -4
- package/lib/embedding-download.js +168 -28
- package/lib/embedding-runtime.js +76 -17
- package/lib/engine.js +0 -6
- package/lib/freshness.js +2 -2
- package/lib/graph.js +139 -11
- package/lib/index.js +71 -20
- package/lib/inject.js +50 -7
- package/lib/lexicon.js +61 -16
- package/lib/local-vector-service.js +21 -1
- package/lib/media.js +49 -12
- package/lib/memory.js +662 -116
- package/lib/paths.js +0 -7
- package/lib/preset-scope.js +6 -1
- package/lib/private.js +281 -18
- package/lib/prompts/private-consolidation.md +2 -2
- package/lib/prompts/private-consolidation.rp.md +3 -2
- package/lib/prompts.js +0 -7
- package/lib/rpc.js +95 -17
- package/lib/snippet.js +18 -2
- package/lib/state.js +109 -30
- package/lib/stats.js +2 -2
- package/lib/temporal.js +19 -0
- package/lib/text-retrieval.js +120 -44
- package/lib/text-similarity.js +205 -24
- package/lib/tokenizer-v2.js +0 -24
- package/lib/tools.js +62 -62
- package/lib/vector-migration.js +15 -0
- package/lib/vector-profile.js +81 -8
- package/lib/visibility.js +0 -4
- package/lib/webui/standalone.css +17 -22
- package/lib/webui/standalone.js +27 -9
- package/lib/webui.js +4 -4
- package/package.json +3 -2
- package/scripts/acceptance-local.mjs +2 -2
- package/scripts/check-all.mjs +3 -1
- package/scripts/check-i18n.mjs +35 -1
- package/scripts/migrate-visibility.mjs +3 -3
- package/scripts/prune-sessions.mjs +34 -0
- package/scripts/prune-vectors.mjs +24 -0
- package/tests/appendix-b.test.mjs +5 -4
- package/tests/audit-batch3.test.mjs +247 -0
- package/tests/audit-regression.test.mjs +2 -2
- package/tests/backup.test.mjs +83 -83
- package/tests/browser.test.mjs +6 -1
- package/tests/client-render.test.mjs +2 -2
- package/tests/consolidation-fork.test.mjs +61 -15
- package/tests/consolidation-ledger.test.mjs +64 -3
- package/tests/consolidation-snapshot.test.mjs +25 -9
- package/tests/curator-clusters.test.mjs +18 -0
- package/tests/curator-pairing.test.mjs +59 -16
- package/tests/dynamic-rrf.test.mjs +22 -19
- package/tests/dynamic-threshold.test.mjs +52 -0
- package/tests/fact-version.test.mjs +18 -0
- package/tests/fixtures/tokenizer-cases.mjs +27 -0
- package/tests/graph-cascade.test.mjs +29 -0
- package/tests/graph.test.mjs +45 -0
- package/tests/inject-conflict.test.mjs +18 -0
- package/tests/injection-chain.test.mjs +2 -2
- package/tests/lexical-bm25.test.mjs +171 -0
- package/tests/lexicon-frequency.test.mjs +16 -0
- package/tests/lexicon-inject.test.mjs +21 -0
- package/tests/lexicon-perf.test.mjs +37 -9
- package/tests/lexicon-scope.test.mjs +2 -2
- package/tests/lexicon-ui.test.mjs +1 -1
- package/tests/managed-memory.test.mjs +19 -0
- package/tests/ops-hardening.test.mjs +209 -0
- package/tests/package-shipping.test.mjs +4 -0
- package/tests/prompt-semantics.test.mjs +1 -1
- package/tests/prompts.test.mjs +1 -1
- package/tests/recall-intent.test.mjs +23 -0
- package/tests/slot-similarity.test.mjs +153 -0
- package/tests/state-gc.test.mjs +34 -0
- package/tests/state.test.mjs +2 -2
- package/tests/tokenizer-v2.test.mjs +1 -1
- package/tests/vector-gc.test.mjs +37 -0
- package/tests/webui.test.mjs +27 -0
package/lib/paths.js
CHANGED
|
@@ -267,13 +267,6 @@ export function windowsSystemEnv(platform = process.platform, env = process.env)
|
|
|
267
267
|
return overlay
|
|
268
268
|
}
|
|
269
269
|
|
|
270
|
-
export function safeSegment(value, fallback = 'unknown') {
|
|
271
|
-
const text = String(value ?? '').trim()
|
|
272
|
-
if (!text) return fallback
|
|
273
|
-
const cleaned = text.replace(/[^A-Za-z0-9._-]+/g, '-').replace(/^-+|-+$/g, '')
|
|
274
|
-
return cleaned || fallback
|
|
275
|
-
}
|
|
276
|
-
|
|
277
270
|
export function isSafeId(value) {
|
|
278
271
|
return typeof value === 'string' && /^[A-Za-z0-9._-]{1,128}$/.test(value) && value !== '.' && value !== '..'
|
|
279
272
|
}
|
package/lib/preset-scope.js
CHANGED
|
@@ -114,8 +114,13 @@ export function registerPresetAttachment(ctx, { log = () => {}, intervalMs = ATT
|
|
|
114
114
|
timer.unref?.()
|
|
115
115
|
return () => {
|
|
116
116
|
clearInterval(timer)
|
|
117
|
-
for (const [, dispose] of attached.entries()) {
|
|
117
|
+
for (const [agentCtx, dispose] of attached.entries()) {
|
|
118
118
|
try { dispose?.() } catch {}
|
|
119
|
+
// S-5: this Map is a strong reference. Detaching without deleting left every
|
|
120
|
+
// disposed agent context reachable for the life of the process, and a context
|
|
121
|
+
// that ever came back through the same key would still read as "attached" and
|
|
122
|
+
// never be registered again.
|
|
123
|
+
attached.delete(agentCtx)
|
|
119
124
|
}
|
|
120
125
|
}
|
|
121
126
|
}
|
package/lib/private.js
CHANGED
|
@@ -8,6 +8,25 @@ import { condenseEvents, readSessionSnapshot } from './curator.js'
|
|
|
8
8
|
import { record } from './activity-log.js'
|
|
9
9
|
import { ACTIVE_MEMORY_POLICY, assessWake, collectEvidence } from './active-memory.js'
|
|
10
10
|
import { entryFingerprint } from './consolidation-receipt.js'
|
|
11
|
+
import { DEFAULT_TIME_ZONE } from './temporal.js'
|
|
12
|
+
|
|
13
|
+
// The consolidation worker only sees the transcript as text. Without a visible
|
|
14
|
+
// per-turn clock it falls back to the wall clock (or a single batch sceneTime),
|
|
15
|
+
// which is exactly how "前天" gets written months away from the scene. The seed
|
|
16
|
+
// event keeps the replayed logical time; surface it as a leading text block so
|
|
17
|
+
// the worker can pass that turn's observed_at to the write tools.
|
|
18
|
+
function eventTimeLabel(event) {
|
|
19
|
+
const explicit = event?.data?.sceneTime
|
|
20
|
+
const at = explicit ? new Date(explicit) : (Number.isFinite(event?.time) ? new Date(event.time) : null)
|
|
21
|
+
if (!at || !Number.isFinite(at.getTime())) return null
|
|
22
|
+
const parts = new Intl.DateTimeFormat('en-CA', {
|
|
23
|
+
timeZone: DEFAULT_TIME_ZONE,
|
|
24
|
+
year: 'numeric', month: '2-digit', day: '2-digit',
|
|
25
|
+
hour: '2-digit', minute: '2-digit', hour12: false,
|
|
26
|
+
}).formatToParts(at)
|
|
27
|
+
const pick = (type) => parts.find((part) => part.type === type)?.value || ''
|
|
28
|
+
return `${pick('year')}-${pick('month')}-${pick('day')} ${pick('hour')}:${pick('minute')}`
|
|
29
|
+
}
|
|
11
30
|
|
|
12
31
|
// Short-term entries expire on a clock, so the idle pass is the last moment anyone
|
|
13
32
|
// can decide what they were worth. The list is generated in code rather than added
|
|
@@ -148,13 +167,16 @@ export function assessConsolidationValue(events) {
|
|
|
148
167
|
// tail, compact the noise, and leave the rest for the next window.
|
|
149
168
|
export const CONSOLIDATION_BACKLOG_EVENTS = 200
|
|
150
169
|
export const CONSOLIDATION_BACKLOG_TURNS = 10
|
|
151
|
-
|
|
170
|
+
// A checkpoint is measured in session events, and six of them are pure turn/step
|
|
171
|
+
// wrappers. 300 events therefore bought only ~50 turns of transcript. 500 keeps
|
|
172
|
+
// the same seed size in practice but cuts one fork for a 200-turn catch-up.
|
|
173
|
+
export const CONSOLIDATION_WINDOW_EVENTS = 500
|
|
152
174
|
export const CONSOLIDATION_PROBE_MINUTES = 15
|
|
153
175
|
export const CONSOLIDATION_SNAPSHOT_FAILURE_LIMIT = 2
|
|
154
|
-
const SEED_TOOL_RESULT_CHARS =
|
|
155
|
-
const SEED_TOOL_CALL_CHARS =
|
|
156
|
-
const SEED_TEXT_CHARS =
|
|
157
|
-
const SEED_CATALOG_ENTRIES =
|
|
176
|
+
const SEED_TOOL_RESULT_CHARS = 1_200
|
|
177
|
+
const SEED_TOOL_CALL_CHARS = 600
|
|
178
|
+
const SEED_TEXT_CHARS = 12_000
|
|
179
|
+
const SEED_CATALOG_ENTRIES = 18
|
|
158
180
|
|
|
159
181
|
// Types that carry conversation, plus the structural events a seeded Session
|
|
160
182
|
// replays. Everything else is host bookkeeping: request headers, permissions,
|
|
@@ -237,6 +259,8 @@ export function compactSeedEvents(events, catalogEvent = null) {
|
|
|
237
259
|
clone.data.arguments = capSeedText(event.data?.arguments, SEED_TOOL_CALL_CHARS)
|
|
238
260
|
} else if (event.type === 'user/message') {
|
|
239
261
|
clone.data.content = cloneSeedBlocks(event.data?.content, { text: SEED_TEXT_CHARS })
|
|
262
|
+
const timeLabel = eventTimeLabel(event)
|
|
263
|
+
if (timeLabel) clone.data.content.unshift({ type: 'text', text: `[事件时间 ${timeLabel}]` })
|
|
240
264
|
}
|
|
241
265
|
kept.push(clone)
|
|
242
266
|
}
|
|
@@ -263,6 +287,158 @@ export function compactSeedEvents(events, catalogEvent = null) {
|
|
|
263
287
|
return out
|
|
264
288
|
}
|
|
265
289
|
|
|
290
|
+
// P3: spend the worker's context on turns that can produce a durable memory.
|
|
291
|
+
// Zero-token local filter: strong signals (dates, promises, corrections,
|
|
292
|
+
// identities) count double; generic preference/social words count once. Whole
|
|
293
|
+
// turns are kept, plus the turn before/after for context. If nothing looks
|
|
294
|
+
// salient, keep everything rather than silently dropping the window.
|
|
295
|
+
const SALIENCE_STRONG = /今天|明天|昨天|前天|后天|大后天|下周|上周|这周|月底|月初|年初|年底|生日|纪念日|周年|星期[一二三四五六日天]|周[一二三四五六日天]|\d{1,2}\s*[月日号]|\d{4}\s*[-/年]|\d{1,2}\s*[点时]|答应|约定|说好|提醒|帮我|帮忙|欠|借|还|截止|到期|记得|别忘|改口|说错|更正|其实|矛盾|两版|之前说/g
|
|
296
|
+
const SALIENCE_WEAK = /喜欢|讨厌|不吃|不要|不能|不想|边界|秘密|别说|打算|计划|准备|要去|想去|叫|称呼|名字|岁|住|工作|职业|负责|接手|登记|换|孩子|父亲|母亲|老公|老婆|朋友|同事|邻居/g
|
|
297
|
+
|
|
298
|
+
function turnText(events) {
|
|
299
|
+
const parts = []
|
|
300
|
+
for (const event of events) {
|
|
301
|
+
if (event.type === 'user/message') {
|
|
302
|
+
for (const block of event.data?.content || []) if (block?.type === 'text' && typeof block.text === 'string') parts.push(block.text)
|
|
303
|
+
} else if (event.type === 'assistant/message') {
|
|
304
|
+
for (const block of event.data?.message?.content || []) if (block?.type === 'text' && typeof block.text === 'string') parts.push(block.text)
|
|
305
|
+
}
|
|
306
|
+
}
|
|
307
|
+
return parts.join('\n')
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
function salienceScore(text) {
|
|
311
|
+
const strong = (String(text).match(SALIENCE_STRONG) || []).length
|
|
312
|
+
const weak = (String(text).match(SALIENCE_WEAK) || []).length
|
|
313
|
+
return strong * 2 + weak
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
/** Keep salient complete turns and one neighbour on each side. */
|
|
317
|
+
export function candidateSeedEvents(events, { maxTurns = 60 } = {}) {
|
|
318
|
+
const groups = []
|
|
319
|
+
let current = null
|
|
320
|
+
for (const event of Array.isArray(events) ? events : []) {
|
|
321
|
+
if (event?.type === 'turn/start' || current === null) {
|
|
322
|
+
current = []
|
|
323
|
+
groups.push(current)
|
|
324
|
+
}
|
|
325
|
+
current.push(event)
|
|
326
|
+
if (event?.type === 'turn/end') current = null
|
|
327
|
+
}
|
|
328
|
+
const kept = new Set()
|
|
329
|
+
groups.forEach((group, index) => {
|
|
330
|
+
if (salienceScore(turnText(group)) >= 2) kept.add(index)
|
|
331
|
+
})
|
|
332
|
+
if (kept.size === 0) return Array.isArray(events) ? [...events] : []
|
|
333
|
+
const expanded = new Set(kept)
|
|
334
|
+
for (const index of kept) {
|
|
335
|
+
if (index > 0) expanded.add(index - 1)
|
|
336
|
+
if (index + 1 < groups.length) expanded.add(index + 1)
|
|
337
|
+
}
|
|
338
|
+
const selected = [...expanded].sort((a, b) => a - b).slice(0, maxTurns)
|
|
339
|
+
const covered = selected.reduce((sum, index) => sum + groups[index].length, 0)
|
|
340
|
+
if (covered >= events.length * 0.8) return [...events]
|
|
341
|
+
return selected.flatMap((index) => groups[index])
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
// P4:本地零 Token 抽「本窗必写候选」。worker 的任务选择常常只覆盖带日期/数字的
|
|
345
|
+
// 几条,新人物、换人接手、只有一句约定的轮次会被漏掉;这些轮次在 salience 里分数
|
|
346
|
+
// 不低,却在模型的 topic selection 里没有位置。给它就是一份带 seq 的短清单:要么
|
|
347
|
+
// 写,要么在回执里说明为什么不写,不能静默跳过。
|
|
348
|
+
const MUST_COVER_PERSON = /叫|自称|称呼|换|接手|改成|换成|新来|同事|师傅|阿姨|房东|店长|老板|邻居|朋友|家人/
|
|
349
|
+
export function mustCoverCandidates(events, { max = 8, minScore = 3 } = {}) {
|
|
350
|
+
const groups = []
|
|
351
|
+
let current = null
|
|
352
|
+
for (const event of Array.isArray(events) ? events : []) {
|
|
353
|
+
if (event?.type === 'turn/start' || current === null) {
|
|
354
|
+
current = []
|
|
355
|
+
groups.push(current)
|
|
356
|
+
}
|
|
357
|
+
current.push(event)
|
|
358
|
+
if (event?.type === 'turn/end') current = null
|
|
359
|
+
}
|
|
360
|
+
const rows = []
|
|
361
|
+
const seen = new Set()
|
|
362
|
+
groups.forEach((group) => {
|
|
363
|
+
const text = turnText(group)
|
|
364
|
+
const score = salienceScore(text)
|
|
365
|
+
if (score < minScore) return
|
|
366
|
+
const userText = group
|
|
367
|
+
.filter((event) => event?.type === 'user/message' && event.data?.source?.kind === 'user')
|
|
368
|
+
.flatMap((event) => (event.data?.content || []).filter((block) => block?.type === 'text').map((block) => String(block.text || '')))
|
|
369
|
+
.join(' ')
|
|
370
|
+
const source = (userText || text).replace(/\s+/g, ' ').trim().slice(0, 90)
|
|
371
|
+
if (!source || seen.has(source)) return
|
|
372
|
+
seen.add(source)
|
|
373
|
+
const observedAt = group
|
|
374
|
+
.filter((event) => event?.type === 'user/message' && event.data?.source?.kind === 'user')
|
|
375
|
+
.map((event) => event.data?.sceneTime)
|
|
376
|
+
.find((value) => typeof value === 'string' && value) || null
|
|
377
|
+
rows.push({
|
|
378
|
+
fromSeq: Number(group[0]?.seq),
|
|
379
|
+
throughSeq: Number(group[group.length - 1]?.seq),
|
|
380
|
+
score,
|
|
381
|
+
tag: MUST_COVER_PERSON.test(text) ? '人物/关系' : '事实',
|
|
382
|
+
text: source,
|
|
383
|
+
observedAt,
|
|
384
|
+
})
|
|
385
|
+
})
|
|
386
|
+
return rows
|
|
387
|
+
.sort((a, b) => b.score - a.score)
|
|
388
|
+
.slice(0, Math.max(1, Number(max) || 8))
|
|
389
|
+
.sort((a, b) => a.fromSeq - b.fromSeq)
|
|
390
|
+
}
|
|
391
|
+
|
|
392
|
+
/** 顺延候选优先占位,但最多 4 条;其余名额留给本窗新候选。 */
|
|
393
|
+
export function mergeMustCover(carry, fresh, { max = 8, carryMax = 4 } = {}) {
|
|
394
|
+
const rows = []
|
|
395
|
+
const seen = new Set()
|
|
396
|
+
const add = (row) => {
|
|
397
|
+
if (!row || typeof row.text !== 'string') return
|
|
398
|
+
const key = row.text.replace(/\s+/g, '').slice(0, 60)
|
|
399
|
+
if (!key || seen.has(key)) return
|
|
400
|
+
seen.add(key)
|
|
401
|
+
rows.push(row)
|
|
402
|
+
}
|
|
403
|
+
for (const row of (Array.isArray(carry) ? carry : []).slice(0, Math.max(0, Number(carryMax) || 0))) {
|
|
404
|
+
add({ ...row, carried: true })
|
|
405
|
+
}
|
|
406
|
+
for (const row of Array.isArray(fresh) ? fresh : []) add(row)
|
|
407
|
+
return rows.slice(0, Math.max(1, Number(max) || 8))
|
|
408
|
+
}
|
|
409
|
+
|
|
410
|
+
const COVER_DATE_RE = /\d{4}-\d{2}-\d{2}|\d{1,2}\s*[月日号]/
|
|
411
|
+
// 这些 bigram 到处出现,不能证明候选被写进库;命中两个以上才算覆盖。
|
|
412
|
+
const COVER_STOP = new Set([
|
|
413
|
+
'我们', '他们', '你们', '现在', '已经', '可以', '什么', '这个', '那个',
|
|
414
|
+
'时候', '今天', '明天', '昨天', '一下', '一个', '还是', '不是', '就是',
|
|
415
|
+
])
|
|
416
|
+
function coverTokens(text) {
|
|
417
|
+
return new Set(tokenize(String(text || ''))
|
|
418
|
+
.filter((token) => typeof token === 'string' && token.length >= 2 && !COVER_STOP.has(token)))
|
|
419
|
+
}
|
|
420
|
+
/** 本地零 Token 核验:候选里的关键事实是否真的出现在本窗新增/更新的条目里。 */
|
|
421
|
+
export function candidateCovered(candidate, writtenIds, index) {
|
|
422
|
+
const entries = index?.entries || {}
|
|
423
|
+
const text = String(candidate?.text || '')
|
|
424
|
+
if (!text) return true
|
|
425
|
+
const date = (text.match(COVER_DATE_RE) || [])[0] || null
|
|
426
|
+
const wanted = coverTokens(text)
|
|
427
|
+
if (wanted.size === 0 && !date) return true
|
|
428
|
+
for (const id of Array.isArray(writtenIds) ? writtenIds : []) {
|
|
429
|
+
const entry = entries[id]
|
|
430
|
+
if (!entry) continue
|
|
431
|
+
const body = String(entry.title || '') + ' ' + String(entry.content || '')
|
|
432
|
+
if (date && body.includes(date)) return true
|
|
433
|
+
const have = coverTokens(body)
|
|
434
|
+
let shared = 0
|
|
435
|
+
for (const token of wanted) {
|
|
436
|
+
if (have.has(token) && (shared += 1) >= 2) return true
|
|
437
|
+
}
|
|
438
|
+
}
|
|
439
|
+
return false
|
|
440
|
+
}
|
|
441
|
+
|
|
266
442
|
/** Existing entries, compact, for dedupe/update instead of duplicate writes. */
|
|
267
443
|
export function memoryCatalogEvent(binding, now = Date.now()) {
|
|
268
444
|
if (!binding?.libraryId) return null
|
|
@@ -520,6 +696,37 @@ async function attachWorkerTools(agents, childId, parentId) {
|
|
|
520
696
|
// workerToolsPartial true = 未证明 worker 拿到完整 wanted 集(子集、空集、或挂载
|
|
521
697
|
// 整体失败)。刻意把"一件都没挂上"也标 true:若失败标 false,
|
|
522
698
|
// false 会被一眼读成"全量挂载",元数据又不准了。
|
|
699
|
+
// A fork inherits the parent preset's plugin tools. `tools.restrict()` is scoped
|
|
700
|
+
// to the child agent, so this removes every plugin tool the worker never uses
|
|
701
|
+
// without touching the parent session. Restrict before followup: the host
|
|
702
|
+
// resolves the admitted set at step start.
|
|
703
|
+
async function restrictWorkerTools(agents, childId, parentId) {
|
|
704
|
+
for (let attempt = 0; attempt < 6; attempt += 1) {
|
|
705
|
+
let record = null
|
|
706
|
+
try { record = agents.get?.(childId) || null } catch { record = null }
|
|
707
|
+
const actx = record?.ctx || record?.agent?.ctx || null
|
|
708
|
+
if (actx && actx.tools && typeof actx.tools.restrict === 'function') {
|
|
709
|
+
try {
|
|
710
|
+
const dispose = actx.tools.restrict({ allow: WORKER_TOOL_ALLOW })
|
|
711
|
+
return { dispose, allowed: [...WORKER_TOOL_ALLOW] }
|
|
712
|
+
} catch (error) {
|
|
713
|
+
// A host missing one of the optional tools must not lose consolidation;
|
|
714
|
+
// retry with the write/read core and let the brief tell the truth.
|
|
715
|
+
const core = ['memu_private_remember', 'memu_private_update', 'memu_private_list', 'memu_status']
|
|
716
|
+
try {
|
|
717
|
+
return { dispose: actx.tools.restrict({ allow: core }), allowed: core }
|
|
718
|
+
} catch (inner) {
|
|
719
|
+
warn('consolidation worker tool restriction failed: ' + String(inner?.message || inner))
|
|
720
|
+
return null
|
|
721
|
+
}
|
|
722
|
+
}
|
|
723
|
+
}
|
|
724
|
+
if (record || !(agents.get?.(parentId))) return null
|
|
725
|
+
await new Promise(resolve => setTimeout(resolve, 100))
|
|
726
|
+
}
|
|
727
|
+
return null
|
|
728
|
+
}
|
|
729
|
+
|
|
523
730
|
function workerToolsMeta(workerTools) {
|
|
524
731
|
const wanted = [...WORKER_WRITE_TOOLS, ...WORKER_READ_TOOLS]
|
|
525
732
|
if (!workerTools) {
|
|
@@ -533,18 +740,25 @@ function workerToolsMeta(workerTools) {
|
|
|
533
740
|
}
|
|
534
741
|
|
|
535
742
|
const inFlight = new Map()
|
|
743
|
+
// How long a cancelled fork gets to finish the tool call it was in the middle of.
|
|
744
|
+
// Bounded on purpose: a child that ignores the cancel must not hang the sweep, and
|
|
745
|
+
// the alternative — disposing immediately — is what let a write land after the range
|
|
746
|
+
// was already handed back to pending.
|
|
747
|
+
const WORKER_STOP_GRACE_MS = 5_000
|
|
536
748
|
|
|
537
749
|
// 这里的 import 刻意写在语句之后:lib/binding-diagnostics.js 的 RUNTIME_STATE 把 `inFlight`
|
|
538
|
-
// 的 file:line 当成诊断契约(当前 lib/private.js:
|
|
750
|
+
// 的 file:line 当成诊断契约(当前 lib/private.js:742),修改位置时同步更新该诊断映射,
|
|
539
751
|
// 而那是别人的文件、本包不改。ESM 的 import 声明是提升的,写在语句之后合法。
|
|
540
752
|
import { warn } from './paths.js'
|
|
541
753
|
import { captureSessionSnapshot, eventSeq, safePrefix, snapshotHash } from './consolidation-snapshot.js'
|
|
542
754
|
import {
|
|
543
755
|
beginJob, completeJob, failJob, findOperation, noteEvidence, operationKey,
|
|
544
756
|
recoverStaleJobs, recordOperation, scopeGenerationOf, clearSessionState, skipRange,
|
|
757
|
+
readCarryCandidates, setCarryCandidates,
|
|
545
758
|
} from './consolidation-ledger.js'
|
|
546
759
|
import { decideCompletion, receiptContractText } from './consolidation-receipt.js'
|
|
547
|
-
import { buildWorkerBrief, probeToolSurface, WORKER_READ_TOOLS, WORKER_WRITE_TOOLS } from './consolidation-worker.js'
|
|
760
|
+
import { buildWorkerBrief, probeToolSurface, WORKER_READ_TOOLS, WORKER_WRITE_TOOLS, WORKER_TOOL_ALLOW } from './consolidation-worker.js'
|
|
761
|
+
import { tokenize } from './text-retrieval.js'
|
|
548
762
|
import { isGoneSessionError } from './cycle.js'
|
|
549
763
|
import { autoLinkPrivateMemories } from './private-links.js'
|
|
550
764
|
import { registerTools } from './tools.js'
|
|
@@ -615,10 +829,39 @@ export async function requestHistoricalConsolidation(ctx, sessionId, options = {
|
|
|
615
829
|
inFlight.set(sessionId, abort)
|
|
616
830
|
let handle = null
|
|
617
831
|
let offSession = null
|
|
832
|
+
let idle = null
|
|
833
|
+
// Stopped once, callable twice: the timeout path and `finally` both need it.
|
|
834
|
+
let stopped = false
|
|
835
|
+
// The host's own order is cancel -> whenIdle -> dispose. dispose() alone does not
|
|
836
|
+
// wait for a tool call in flight, and this fork writes memories *through tools*, so
|
|
837
|
+
// "the fork was stopped" was not true when the timeout path returned: failJob had
|
|
838
|
+
// already handed the range back and the next pass could fork the same window while
|
|
839
|
+
// the old child was still writing. Bounded, because a child that ignores the cancel
|
|
840
|
+
// must not hang the sweep.
|
|
841
|
+
const stopWorker = async () => {
|
|
842
|
+
if (stopped) return
|
|
843
|
+
stopped = true
|
|
844
|
+
try { abort.abort() } catch {}
|
|
845
|
+
try { offSession?.() } catch {}
|
|
846
|
+
if (idle) {
|
|
847
|
+
try {
|
|
848
|
+
await Promise.race([
|
|
849
|
+
idle.then(() => {}, () => {}),
|
|
850
|
+
// Deliberately NOT unref'd: this promise is what we are awaiting, so an
|
|
851
|
+
// unref'd timer lets the event loop drain while the await is still pending
|
|
852
|
+
// and the caller (or the test runner) is left holding a promise that can
|
|
853
|
+
// never settle. A <=5s hold on the loop is the correct trade.
|
|
854
|
+
new Promise((resolve) => setTimeout(resolve, WORKER_STOP_GRACE_MS)),
|
|
855
|
+
])
|
|
856
|
+
} catch {}
|
|
857
|
+
}
|
|
858
|
+
try { await handle?.dispose?.() } catch {}
|
|
859
|
+
}
|
|
618
860
|
let turnEnd = null
|
|
619
861
|
let jobId = null
|
|
620
862
|
let scopeChanged = null
|
|
621
863
|
let workerTools = null
|
|
864
|
+
let workerRestriction = null
|
|
622
865
|
const assistantTexts = []
|
|
623
866
|
let childId = null
|
|
624
867
|
// 每次整理都要在活动日志里留一条:谁触发(手动/空闲)、fork 有没有建、结果是完成、
|
|
@@ -796,7 +1039,7 @@ export async function requestHistoricalConsolidation(ctx, sessionId, options = {
|
|
|
796
1039
|
const snapshotMeta = snapshotMetaOf(windowSnapshot)
|
|
797
1040
|
// 范围大小决定等多久:显式给了就听调用方的,没给按这一窗的事件数推。
|
|
798
1041
|
const budgetMs = Number.isInteger(maxWaitMs) && maxWaitMs > 0 ? maxWaitMs : consolidationWaitBudget(window.events.length)
|
|
799
|
-
const seedEvents = compactSeedEvents(window.events, memoryCatalogEvent({ ...binding, sessionId }))
|
|
1042
|
+
const seedEvents = compactSeedEvents(candidateSeedEvents(window.events), memoryCatalogEvent({ ...binding, sessionId }))
|
|
800
1043
|
if (seedEvents.length === 0) {
|
|
801
1044
|
return finish({ ok: true, sessionId, skipped: 'empty-seed', settled: true, snapshot: snapshotMeta })
|
|
802
1045
|
}
|
|
@@ -808,9 +1051,11 @@ export async function requestHistoricalConsolidation(ctx, sessionId, options = {
|
|
|
808
1051
|
if (previous && (previous.outcome === 'completed' || previous.outcome === 'skipped')) {
|
|
809
1052
|
return finish({ ok: true, sessionId, skipped: 'already-consolidated', settled: true, snapshot: snapshotMeta, credential: previous })
|
|
810
1053
|
}
|
|
811
|
-
//
|
|
812
|
-
//
|
|
813
|
-
|
|
1054
|
+
// 同一份快照连续失败到上限就不再「自动」重跑:窗口已经很小,重试成本可控,但
|
|
1055
|
+
// 没有新事件的同一段转录不值得无限重试。手动整理(force)是明确的一次再决定,
|
|
1056
|
+
// 不受上限约束——否则冻结回放/用户重试都会被永久卡在同一个窗口。新消息会改变
|
|
1057
|
+
// 快照哈希,自动路径也重新获得机会。
|
|
1058
|
+
if (!force && previous?.outcome === 'failed' && Number(previous.failures) >= CONSOLIDATION_SNAPSHOT_FAILURE_LIMIT) {
|
|
814
1059
|
return finish({
|
|
815
1060
|
ok: true, sessionId, skipped: 'snapshot-failed', settled: true, reasonCode: 'snapshot-failed-too-many',
|
|
816
1061
|
snapshot: snapshotMeta, failures: Number(previous.failures) || 0,
|
|
@@ -918,6 +1163,7 @@ export async function requestHistoricalConsolidation(ctx, sessionId, options = {
|
|
|
918
1163
|
if (probe.hasWrite !== true) {
|
|
919
1164
|
workerTools = await attachWorkerTools(agents, childId, sessionId)
|
|
920
1165
|
}
|
|
1166
|
+
workerRestriction = await restrictWorkerTools(agents, childId, sessionId)
|
|
921
1167
|
|
|
922
1168
|
// 先记"已开始"再等结果:一个大会话的 fork 可能跑好几分钟,没有这条记录,
|
|
923
1169
|
// 侧边栏和日志页在等待期间只会显示上一次的结果,用户会以为按钮没生效。
|
|
@@ -993,6 +1239,10 @@ export async function requestHistoricalConsolidation(ctx, sessionId, options = {
|
|
|
993
1239
|
// 不继承 mood。显式写 null 而不是留空:缺字段和「这一刻是中性」在写入时都走
|
|
994
1240
|
// 同一条兜底,但只有 null 能把「后台 worker 没有当下心境」说清楚。
|
|
995
1241
|
mood: null,
|
|
1242
|
+
// The fork writes memories on the same logical clock as its parent. Without
|
|
1243
|
+
// this the worker falls back to the wall clock at fork time; the per-turn
|
|
1244
|
+
// [事件时间] markers in the seed remain the authoritative override.
|
|
1245
|
+
sceneTime: binding.sceneTime || null,
|
|
996
1246
|
parentSessionId: sessionId,
|
|
997
1247
|
parentScopeGeneration: generationAtStart,
|
|
998
1248
|
snapshotHash: snapshot.hash,
|
|
@@ -1020,11 +1270,13 @@ export async function requestHistoricalConsolidation(ctx, sessionId, options = {
|
|
|
1020
1270
|
})
|
|
1021
1271
|
}
|
|
1022
1272
|
|
|
1023
|
-
const
|
|
1273
|
+
const carry = safeLedger(() => readCarryCandidates(sessionId), [])
|
|
1274
|
+
const mustCover = mergeMustCover(carry, mustCoverCandidates(window.events))
|
|
1275
|
+
const brief = buildWorkerBrief({ snapshot, probe, contract: receiptContractText({ jobId, snapshotHash: snapshot.hash }), reason: force ? 'manual' : 'auto', jobId, mustCover })
|
|
1024
1276
|
handle.agent.followup(noticeMessage([buildPrivateConsolidationPrompt(sessionId), '', brief].join('\n'), '整理这场对话的私有记忆'))
|
|
1025
1277
|
// followup only queues. whenIdle says the driver stopped; turn/end says
|
|
1026
1278
|
// whether that turn actually succeeded, so both are checked below.
|
|
1027
|
-
|
|
1279
|
+
idle = typeof handle.agent.whenIdle === 'function' ? handle.agent.whenIdle() : Promise.resolve()
|
|
1028
1280
|
let timer = null
|
|
1029
1281
|
let outcome
|
|
1030
1282
|
try {
|
|
@@ -1092,6 +1344,11 @@ export async function requestHistoricalConsolidation(ctx, sessionId, options = {
|
|
|
1092
1344
|
error: 'the consolidation ledger could not verify the covered snapshot range' })
|
|
1093
1345
|
}
|
|
1094
1346
|
setSessionBinding(sessionId, { lastSleepSeq: snapshot.throughSeq })
|
|
1347
|
+
// 候选跨窗顺延:本窗没写进库的候选留给下一窗的必写清单;最后一窗也在同一份
|
|
1348
|
+
// brief 里见到它们,不需要为了补写再开一次整窗 fork。核验纯本地,0 Token。
|
|
1349
|
+
const writtenIds = [...(decision.createdIds || []), ...(decision.updatedIds || []), ...(decision.heldIds || [])]
|
|
1350
|
+
const missed = mustCover.filter((candidate) => !candidateCovered(candidate, writtenIds, index))
|
|
1351
|
+
safeLedger(() => setCarryCandidates(sessionId, missed))
|
|
1095
1352
|
safeLedger(() => recordOperation({ sessionId, key: opKey, outcome: decision.status, ids: decision.createdIds || [] }))
|
|
1096
1353
|
// 私有自动关联(§5.6 兜底):只在整理真的对账并推进边界之后跑,纯算法,
|
|
1097
1354
|
// 0 token。worker 若已调用 memu_private_link_suggest,这一遍是幂等的(已有的
|
|
@@ -1113,7 +1370,11 @@ export async function requestHistoricalConsolidation(ctx, sessionId, options = {
|
|
|
1113
1370
|
// `result.error` and an empty string there is indistinguishable from a click
|
|
1114
1371
|
// that did nothing at all (observed: two clicks, no feedback, no memories).
|
|
1115
1372
|
if (outcome === 'timeout') {
|
|
1116
|
-
|
|
1373
|
+
// Stop the writer before releasing the range, not after. Waiting matters here
|
|
1374
|
+
// because a tool call already in flight can still land a memory on disk, and the
|
|
1375
|
+
// range going back to pending is what lets the next pass redo this window.
|
|
1376
|
+
await stopWorker()
|
|
1377
|
+
safeLedger(() => failJob({ sessionId, jobId, reasonCode: 'timeout', error: 'timed out before a receipt; the worker was stopped first, but a tool call already in flight may have written' }))
|
|
1117
1378
|
return finish({
|
|
1118
1379
|
ok: false,
|
|
1119
1380
|
sessionId,
|
|
@@ -1121,7 +1382,10 @@ export async function requestHistoricalConsolidation(ctx, sessionId, options = {
|
|
|
1121
1382
|
settled: false,
|
|
1122
1383
|
timedOut: true,
|
|
1123
1384
|
reasonCode: 'timeout',
|
|
1124
|
-
|
|
1385
|
+
// The next pass must not assume this window left nothing behind: the range is
|
|
1386
|
+
// pending again and some writes may already have landed.
|
|
1387
|
+
partialWritesPossible: true,
|
|
1388
|
+
error: 'consolidation timed out after ' + Math.round(budgetMs / 1000) + 's over ' + window.events.length + ' events; the fork was stopped before the range was released (memories written before the timeout are kept). Retry, or consolidate a shorter conversation.',
|
|
1125
1389
|
})
|
|
1126
1390
|
}
|
|
1127
1391
|
return finish({
|
|
@@ -1153,10 +1417,9 @@ export async function requestHistoricalConsolidation(ctx, sessionId, options = {
|
|
|
1153
1417
|
return finish({ ok: false, sessionId, settled: false, reasonCode: 'exception', error: String(error?.message || error) })
|
|
1154
1418
|
} finally {
|
|
1155
1419
|
inFlight.delete(sessionId)
|
|
1156
|
-
|
|
1157
|
-
try { offSession?.() } catch {}
|
|
1420
|
+
try { await stopWorker() } catch {}
|
|
1158
1421
|
try { workerTools?.dispose?.() } catch {}
|
|
1159
|
-
try {
|
|
1422
|
+
try { workerRestriction?.dispose?.() } catch {}
|
|
1160
1423
|
try { if (childId) deleteSessionBinding(childId) } catch {}
|
|
1161
1424
|
}
|
|
1162
1425
|
}
|
|
@@ -11,12 +11,12 @@
|
|
|
11
11
|
- 一条只写一件事,并且自包含:以后看不到这段对话,要写清背景。
|
|
12
12
|
- 优先写具体的东西:一句原话、一个决定和它的理由、一次踩过的坑。
|
|
13
13
|
- 可以写有后续影响的关系、感受或限制,但要有具体事件与来源;一次礼貌或情绪不推导稳定人格,不按轮数增加亲密度。只有明确的叙事内容才用角色口吻。
|
|
14
|
-
-
|
|
14
|
+
- 只与实际提供或成功检索到的旧记忆去重:兼容可合并,矛盾保留来源、时间与条件供复核,不抹旧正文或自行宣布取代。**最多新增 8 条,按价值排序**:约定/承诺 > 日期/改口/冲突 > 身份/称呼/边界/第三方人物与变化 > 偏好/计划 > 其他明确事实;普通日常流水、打招呼、重复对话不写,没有值得留的就不写。
|
|
15
15
|
|
|
16
16
|
字段:
|
|
17
17
|
- title:8–40 字,写具体事实(人名、物名、事件、结论的关键词)。锚点与召回只显示标题、不显示正文,所以标题就是目录项;
|
|
18
18
|
不要「一些事」「那段对话」「关于……的记录」这类空标签,细节全部放进 content。合并/吸收后的标题要覆盖来源的关键词。
|
|
19
|
-
- content
|
|
19
|
+
- content:自包含的具体内容、对象/条件及后续意义,**50–170 字,尽量小但精准**;只保留人物、地点、时间、事情、原话/说话人,不复述整段对话,不写成行为日志。
|
|
20
20
|
- tags:可选,便于以后检索。
|
|
21
21
|
- salient_date:只在确有日期时填,且要落成绝对日期。每年复发的那一天(生日、周年)用 `MM-DD`;
|
|
22
22
|
一次性的约定或安排用 `YYYY-MM-DD`。说「明天」「后天」「下周」的约定必须按今天算出具体年月日——
|
|
@@ -16,7 +16,8 @@
|
|
|
16
16
|
- 同一件事有两种说法:各写一条,`conflicts_with` 互指;不要合并成一条,也不要自行裁决。
|
|
17
17
|
- 承诺/约定写 `commitment`(对谁/做什么/`due_at`/`status`);梦、假设、转述标 `source_kind`。
|
|
18
18
|
- 助手说过的承诺和计划同样要写;不要只收用户消息。
|
|
19
|
-
-
|
|
19
|
+
- 每窗最多新增 8 条。按价值排序:约定/承诺 = 新人物首次出现/换人接手/称呼变化 > 日期/改口/冲突 > 身份/边界/第三方人物 > 偏好/计划 > 其他明确事实。前两类必须写,不得因为已经写了几条就省略。明确说过的日常事实(颜色、物品、口味、作息、行程、称呼变更)也要各自成条;同一件事的两种说法各写一条,保留时间和来源,不要自行裁决。条数不能靠少写省掉;「少写」只指单条正文精准。
|
|
20
|
+
- 人物首次出现、换人接手或称呼变化必须单独成一条,写清先后(谁先、谁后来接手)与发生轮次;这类事实不并入生活流水,也不因为主体是第三方就不写。
|
|
20
21
|
|
|
21
22
|
写什么(活人感):
|
|
22
23
|
- 用角色的口吻、第一人称写,像在回想,不像在归档。
|
|
@@ -29,7 +30,7 @@
|
|
|
29
30
|
字段:
|
|
30
31
|
- title:8–40 字,写清这件事是什么——具体的人名、称谓、物件、事件或结论关键词。锚点/召回只显示标题、不显示正文,
|
|
31
32
|
所以标题就是目录项;不要「关于……的回忆」「一些对话」这类空标签,细节留在 content。合并/吸收后的标题要覆盖来源的关键词。
|
|
32
|
-
- content:一个瞬间 + 它对之后的影响,通常
|
|
33
|
+
- content:一个瞬间 + 它对之后的影响,通常 50–170 字,不硬凑长度;最多引一句有出处的原话。能让下次称呼、选择或分寸自然接续,比抒情更重要。
|
|
33
34
|
- tags:可选。
|
|
34
35
|
- salient_date:只在确有日期时填,且要落成绝对日期。每年复发的那一天(生日、周年)用 `MM-DD`;
|
|
35
36
|
一次性的约定或安排用 `YYYY-MM-DD`。说「明天」「后天」「下周」的约定必须按今天算出具体年月日——
|
package/lib/prompts.js
CHANGED
|
@@ -302,11 +302,4 @@ export function syncPromptDefaults() {
|
|
|
302
302
|
return getPromptStates()
|
|
303
303
|
}
|
|
304
304
|
|
|
305
|
-
export function promptDefaultsVersion() {
|
|
306
|
-
return allDefs().map((def) => {
|
|
307
|
-
const text = readText(defaultPath(def)) || ''
|
|
308
|
-
return `${def.key}:${hash(text)}`
|
|
309
|
-
}).join(',')
|
|
310
|
-
}
|
|
311
|
-
|
|
312
305
|
export { DEFAULT_DIR }
|