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/docs/memory-semantics.md
CHANGED
|
@@ -104,13 +104,14 @@
|
|
|
104
104
|
- 触发:`settings.sleepConsolidation` 开着时,每 5 分钟扫一遍(`lib/cycle.js` 的 `runSleepPass`)。候选有三条腿:① 空闲 ≥ `sleepAfterIdleMinutes`(**默认 2 分钟**,`lib/state.js` 的 `DEFAULT_SETTINGS`);② **水位**——账本里 pending 积压 ≥ 200 事件,不依赖空闲;③ 新活动但水位不足时的**探针**(最多每 15 分钟一次,读转录并评估,不 fork)。排序是 backlog → idle → probe,扫描每次最多处理 **2 个**会话。
|
|
105
105
|
- 应用启动后 8 秒补跑一次(`STARTUP_SWEEP_MS`),因为定时器只在应用开着时存在:一段对话如果是在应用关着的时候结束的,它永远等不到那个「空闲窗口」——用户一回来发消息,`lastTurnAt` 就被顶新了。
|
|
106
106
|
- **有新回合 ≠ 该写记忆。** 进 fork 之前先做两道本地评估(只看 `lastSleepSeq` 之后的转录):① `assessConsolidationValue` 的硬门槛——没有任何人类消息(只有插件通知、工具结果、心跳)→ 跳过;只有一条**纯应答**(「谢谢」「好的」「ok」「收到」,且没有任何工具调用)→ 跳过。**这里刻意不按字数判断**:字数少的偏好句(「我不吃香菜」)比一千字的闲聊更该留,长度是坏代理。② 水位优先级高于 `assessWake` 加权分:pending ≥ 200 事件或 ≥10 个真人回合直接整理;水位以下才走 `score = 0.35*min(H/3,2) + 0.45*min(C/4000,2) + 0.20*min(U/20,2)`(`H` 真人回合、`C` 真人文字 + 助手正文 + 去重工具结果、`U` 去重有效工具单元),默认 `activeMemoryMinScore = 0.8`、`activeMemoryStarvationMinutes = 15`。
|
|
107
|
-
- **每次只种一窗。** `requestPrivateConsolidation` 只把 `lastSleepSeq` 之后的增量切成一个 ≤
|
|
107
|
+
- **每次只种一窗。** `requestPrivateConsolidation` 只把 `lastSleepSeq` 之后的增量切成一个 ≤500 事件、尾部对齐完整回合的窗口(`selectConsolidationWindow`);种子经 `compactSeedEvents` 清噪:只留真人消息 / 助手正文 / 工具调用与结果,删 reasoning、`source.replayState`、`data.stream`、插件召回、`runtime-context`、`request/header` 等后台事件;工具结果截 1200 字、重复输出只留一份。窗口开头插一条 `[memory-catalog]` 已有记忆目录(最多 18 条:id + 标题 + layer + status),worker 用它合并/去重,不再为旧库重读历史。剩余事件留到下一次扫描,`lastSleepSeq` 只随对账回执前进。
|
|
108
108
|
- **近期触发过记忆就不 fork。** `runSleepPass` 先看 `suppressionReason`:距上次整理不足 `activeMemoryCooldownMinutes`(默认 0)或距上次**注入过记忆**不足 `activeMemoryRecallCooldownMinutes`(默认 15 分钟)→ 跳过并发 `check` 日志。探针/水位可绕过「刚注入过」这一条(它们先评估、不直接 fork);被抑制或低分跳过的回合返回 `settled: false`,不推进 `lastSleepSeq`/`lastSleepAt`。
|
|
109
109
|
- **寒暄与无新事件是终态。** `small-talk` / `no-human-turn` / `no-new-events` 返回 `settled: true` 并写入 `lastSleepAt`,下一次真人消息到达前不再重扫同一段;政策跳过不计入 `ran`(没有 worker 回执)。
|
|
110
|
-
-
|
|
110
|
+
- **同一快照失败有上限(仅自动触发)。** `failJob` 按窗口 `snapshotHash` 记 `failures`;连续 2 次失败后下一次**自动**请求返回 `skipped: 'snapshot-failed'`(`settled: true`),不再重复付同一段的 fork 成本。手动整理(`force: true`)是明确的一次再决定,不受该上限约束;新事件也会改变哈希,让自动路径重新获得机会。
|
|
111
111
|
- 评估通过但整理写了 0 条 = 正常成功(`lastSleepAt` 前移),不会每小时重来。整理日志额外记录 `scanned/fresh/index +N`(`scanned` 现在是**这一窗**的事件数,`fresh` 是游标后的总增量)和 `remaining`(还余多少事件),`check` 日志记录 `score/reason/parts/空闲分钟/会话事件数/待整理事件数`。
|
|
112
112
|
- 会话被删:host 对 `readSession` 报 `session "…" not found`,这是**不变量**而不是瞬时故障。`runSleepPass` 一旦看到就把 binding 标 `sessionGone: true` 并清掉重试计数,此后直接跳过(以前会按 2 的幂退避、封顶 1 小时,永远重试);同名会话后来真的收到新消息时(`lib/inbound.js`)会清掉这个标记。**"读不出来"不是"被删了"**:转录读失败(例如 `ENOENT`)由快照层显式标成可重试(`lib/consolidation-snapshot.js` 的 `failed()` → `retryable: true`),`runSleepPass` 只按退避重试、不打 `sessionGone`——`isGoneSessionError` 只认宿主那句 `session "…" not found` / `no such session`。
|
|
113
113
|
- 手动「整理这场对话」(RPC `generatePrivate`)带 `force: true`,跳过上面两道评估与抑制:用户已经决定了。若游标已经到末尾,手动整理只重查最后 ≤300 个事件,不再重放整段历史。
|
|
114
|
+
- **必写候选跨窗顺延。** 每窗本地抽 salience ≥3 的轮次(最多 8 条)作为必写清单;本窗没写进库的候选记入账本 `carry`,下一窗优先带 4 条、其余名额留给新候选。核验是纯本地 token 比对(日期命中或 ≥2 个有效 bigram),不额外调模型;最后一窗也会在同一份任务书里看到顺延候选,不需要为补写再开一次整窗 fork。
|
|
114
115
|
|
|
115
116
|
---
|
|
116
117
|
|
package/lib/backup.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import crypto from 'node:crypto'
|
|
2
2
|
import fs from 'node:fs'
|
|
3
3
|
import path from 'node:path'
|
|
4
|
-
import {
|
|
4
|
+
import { spawn } from 'node:child_process'
|
|
5
5
|
import {
|
|
6
6
|
backupsDir, dataDir, ensureDir, indexDir, isSafeId, librariesDir,
|
|
7
7
|
readJson, warn, withFileLock, writeJson,
|
|
@@ -113,14 +113,69 @@ function hasSqliteHeader(file) {
|
|
|
113
113
|
|
|
114
114
|
// ---------------------------------------------------------------- lock & leases
|
|
115
115
|
|
|
116
|
+
// 同进程可重入的锁集合。paths.js 的 withFileLock 是纯同步的(try { return action() }
|
|
117
|
+
// finally 立刻删锁文件):直接把 async action 传进去,锁会在第一个 await 之前
|
|
118
|
+
// 就释放,restore 的 safety backup 与 prune 便失去互斥。这里自己管理同一把
|
|
119
|
+
// .backup.lock,持锁直到 action 的 Promise 完成;同步 action 仍返回同步结果。
|
|
120
|
+
const heldBackupLocks = new Set()
|
|
121
|
+
|
|
122
|
+
function acquireBackupLock() {
|
|
123
|
+
const lock = path.resolve(lockAnchor()) + '.lock'
|
|
124
|
+
if (heldBackupLocks.has(lock)) return () => {}
|
|
125
|
+
ensureDir(backupsDir())
|
|
126
|
+
const until = Date.now() + 500
|
|
127
|
+
let fd
|
|
128
|
+
while (fd === undefined) {
|
|
129
|
+
try {
|
|
130
|
+
fd = fs.openSync(lock, 'wx', 0o600)
|
|
131
|
+
fs.writeFileSync(fd, String(process.pid))
|
|
132
|
+
} catch (error) {
|
|
133
|
+
if (error?.code !== 'EEXIST') throw error
|
|
134
|
+
try {
|
|
135
|
+
const owner = Number(fs.readFileSync(lock, 'utf8'))
|
|
136
|
+
if (Number.isSafeInteger(owner) && owner > 0 && !pidAlive(owner)) { fs.unlinkSync(lock); continue }
|
|
137
|
+
} catch {}
|
|
138
|
+
if (Date.now() >= until) {
|
|
139
|
+
const busy = new Error('memory store is busy: backup; retry the operation')
|
|
140
|
+
busy.code = 'DSH_MEMU_STORE_BUSY'
|
|
141
|
+
throw busy
|
|
142
|
+
}
|
|
143
|
+
pause(10)
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
heldBackupLocks.add(lock)
|
|
147
|
+
return () => {
|
|
148
|
+
heldBackupLocks.delete(lock)
|
|
149
|
+
try { fs.closeSync(fd) } catch {}
|
|
150
|
+
for (let attempt = 0; ; attempt += 1) {
|
|
151
|
+
try { fs.unlinkSync(lock); break } catch (error) {
|
|
152
|
+
if (error?.code === 'ENOENT') break
|
|
153
|
+
if (['EPERM', 'EBUSY', 'EACCES'].includes(error?.code) && attempt < 5) { pause(RETRY_MS * (attempt + 1)); continue }
|
|
154
|
+
warn('backups: could not release backup lock (' + (error?.code || 'io error') + ')')
|
|
155
|
+
break
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
|
|
116
161
|
/**
|
|
117
162
|
* The one lock that coordinates create/delete/restore/prune. It is reentrant
|
|
118
|
-
* inside this process
|
|
119
|
-
*
|
|
163
|
+
* inside this process, so a restore may create its own safety backup and prune
|
|
164
|
+
* while still holding it. A synchronous action returns its value synchronously;
|
|
165
|
+
* an async action returns a Promise and the lock stays held until it settles.
|
|
120
166
|
*/
|
|
121
167
|
export function withBackupLock(action) {
|
|
122
|
-
|
|
123
|
-
|
|
168
|
+
const release = acquireBackupLock()
|
|
169
|
+
let result
|
|
170
|
+
try {
|
|
171
|
+
result = action()
|
|
172
|
+
} catch (error) {
|
|
173
|
+
release()
|
|
174
|
+
throw error
|
|
175
|
+
}
|
|
176
|
+
if (result && typeof result.then === 'function') return Promise.resolve(result).finally(release)
|
|
177
|
+
release()
|
|
178
|
+
return result
|
|
124
179
|
}
|
|
125
180
|
|
|
126
181
|
function pidAlive(pid) {
|
|
@@ -274,14 +329,81 @@ let enginePythonCache = null
|
|
|
274
329
|
/** Forget the cached interpreter probe (tests use this between scenarios). */
|
|
275
330
|
export function resetBackupPythonProbe() { enginePythonCache = null }
|
|
276
331
|
|
|
332
|
+
/**
|
|
333
|
+
* spawn + Promise 版的解释器运行器:不再用 spawnSync 冻结事件循环(S-3)。
|
|
334
|
+
* 超时先软终止,5s 后硬杀并主动 reject,不等 'close';Windows 用
|
|
335
|
+
* taskkill /T /F 连带杀掉子进程树。maxBuffer 超限走同一条终止路径。
|
|
336
|
+
*/
|
|
337
|
+
function spawnPython(cmd, args, { timeout, maxBuffer }) {
|
|
338
|
+
return new Promise((resolve, reject) => {
|
|
339
|
+
let child
|
|
340
|
+
try {
|
|
341
|
+
child = spawn(cmd, args, { windowsHide: true, stdio: ['ignore', 'pipe', 'pipe'] })
|
|
342
|
+
} catch (error) {
|
|
343
|
+
reject(error)
|
|
344
|
+
return
|
|
345
|
+
}
|
|
346
|
+
let settled = false
|
|
347
|
+
let stdout = ''
|
|
348
|
+
let stderr = ''
|
|
349
|
+
let timeoutTimer = null
|
|
350
|
+
let killTimer = null
|
|
351
|
+
const signalChild = force => {
|
|
352
|
+
if (!child || child.exitCode !== null) return
|
|
353
|
+
if (process.platform === 'win32') {
|
|
354
|
+
try { spawn('taskkill', ['/pid', String(child.pid), '/T', '/F'], { windowsHide: true, stdio: 'ignore' }) } catch {}
|
|
355
|
+
} else {
|
|
356
|
+
try { child.kill(force ? 'SIGKILL' : 'SIGTERM') } catch {}
|
|
357
|
+
}
|
|
358
|
+
}
|
|
359
|
+
const finish = (error, value) => {
|
|
360
|
+
if (settled) return
|
|
361
|
+
settled = true
|
|
362
|
+
if (timeoutTimer) clearTimeout(timeoutTimer)
|
|
363
|
+
if (killTimer) clearTimeout(killTimer)
|
|
364
|
+
if (error) reject(error)
|
|
365
|
+
else resolve(value)
|
|
366
|
+
}
|
|
367
|
+
const abort = reason => {
|
|
368
|
+
if (settled || killTimer) return
|
|
369
|
+
if (timeoutTimer) { clearTimeout(timeoutTimer); timeoutTimer = null }
|
|
370
|
+
signalChild(false)
|
|
371
|
+
killTimer = setTimeout(() => {
|
|
372
|
+
signalChild(true)
|
|
373
|
+
finish(reason, null) // 主动结束,不依赖 'close'
|
|
374
|
+
}, 5000)
|
|
375
|
+
killTimer.unref?.()
|
|
376
|
+
}
|
|
377
|
+
if (Number.isFinite(timeout) && timeout > 0) {
|
|
378
|
+
timeoutTimer = setTimeout(() => abort(Object.assign(new Error('python process timed out'), { code: 'ETIMEDOUT' })), timeout)
|
|
379
|
+
timeoutTimer.unref?.()
|
|
380
|
+
}
|
|
381
|
+
try { child.stdout?.setEncoding?.('utf8') } catch {}
|
|
382
|
+
try { child.stderr?.setEncoding?.('utf8') } catch {}
|
|
383
|
+
child.stdout?.on?.('data', chunk => {
|
|
384
|
+
if (settled) return
|
|
385
|
+
stdout += chunk
|
|
386
|
+
if (Buffer.byteLength(stdout) > maxBuffer) abort(Object.assign(new Error('maxBuffer exceeded'), { code: 'ENOBUFS' }))
|
|
387
|
+
})
|
|
388
|
+
child.stderr?.on?.('data', chunk => {
|
|
389
|
+
if (settled) return
|
|
390
|
+
stderr += chunk
|
|
391
|
+
if (Buffer.byteLength(stderr) > maxBuffer) abort(Object.assign(new Error('maxBuffer exceeded'), { code: 'ENOBUFS' }))
|
|
392
|
+
})
|
|
393
|
+
child.on?.('error', error => finish(error, null))
|
|
394
|
+
child.on?.('close', (code, signal) => finish(null, { status: code, signal, stdout, stderr }))
|
|
395
|
+
})
|
|
396
|
+
}
|
|
397
|
+
|
|
277
398
|
/**
|
|
278
399
|
* Runs an interpreter. `exec` is a seam for tests only (a fake interpreter);
|
|
279
400
|
* production always spawns the verified venv binary and nothing else.
|
|
401
|
+
* 兼容同步的测试 seam:await 一个普通返回值也照常拿到结果。
|
|
280
402
|
*/
|
|
281
|
-
function runPython(exec, cmd, args, timeout) {
|
|
282
|
-
const runner = typeof exec === 'function' ? exec :
|
|
403
|
+
async function runPython(exec, cmd, args, timeout) {
|
|
404
|
+
const runner = typeof exec === 'function' ? exec : spawnPython
|
|
283
405
|
try {
|
|
284
|
-
return runner(cmd, args, { timeout, windowsHide: true, encoding: 'utf8', maxBuffer: 4 * 1024 * 1024 })
|
|
406
|
+
return await runner(cmd, args, { timeout, windowsHide: true, encoding: 'utf8', maxBuffer: 4 * 1024 * 1024 })
|
|
285
407
|
} catch (error) {
|
|
286
408
|
return { error, status: null, stdout: '', stderr: '' }
|
|
287
409
|
}
|
|
@@ -298,7 +420,7 @@ function jsonOutcome(result) {
|
|
|
298
420
|
* none. Never falls back to a global interpreter: a missing, foreign or broken
|
|
299
421
|
* venv is a refusal, not a downgrade.
|
|
300
422
|
*/
|
|
301
|
-
function enginePythonForBackup(exec) {
|
|
423
|
+
async function enginePythonForBackup(exec) {
|
|
302
424
|
const disabled = process.env.DSH_MEMU_BACKUP_NO_PYTHON === '1'
|
|
303
425
|
const root = engineRoot()
|
|
304
426
|
const candidates = disabled ? [] : engineVenvCandidates()
|
|
@@ -315,7 +437,7 @@ function enginePythonForBackup(exec) {
|
|
|
315
437
|
value.rejected.push(candidate.source + ': outside ' + root)
|
|
316
438
|
continue
|
|
317
439
|
}
|
|
318
|
-
const probe = runPython(exec, python, ['-c', PYTHON_PROBE_SCRIPT], PROBE_TIMEOUT_MS)
|
|
440
|
+
const probe = await runPython(exec, python, ['-c', PYTHON_PROBE_SCRIPT], PROBE_TIMEOUT_MS)
|
|
319
441
|
const outcome = jsonOutcome(probe)
|
|
320
442
|
if (!outcome || outcome.ok !== true) {
|
|
321
443
|
const reason = outcome?.error || probe?.error?.message || (probe?.status != null ? 'exited ' + probe.status : 'no answer')
|
|
@@ -355,8 +477,8 @@ function removeQuietly(file) {
|
|
|
355
477
|
* snapshot. Anything short of a clean `quick_check` is a failure, never a
|
|
356
478
|
* reason to copy the bytes ourselves.
|
|
357
479
|
*/
|
|
358
|
-
function pythonSnapshot(exec, python, from, to) {
|
|
359
|
-
const result = runPython(exec, python.cmd, ['-c', SQLITE_SNAPSHOT_SCRIPT, from, to], PYTHON_TIMEOUT_MS)
|
|
480
|
+
async function pythonSnapshot(exec, python, from, to) {
|
|
481
|
+
const result = await runPython(exec, python.cmd, ['-c', SQLITE_SNAPSHOT_SCRIPT, from, to], PYTHON_TIMEOUT_MS)
|
|
360
482
|
if (result?.error) return { ok: false, error: String(result.error.message || result.error) }
|
|
361
483
|
if (result?.status !== 0) {
|
|
362
484
|
return { ok: false, error: String(result?.stderr || ('engine interpreter exited ' + result?.status)).trim().slice(0, 400) }
|
|
@@ -379,7 +501,7 @@ function pythonSnapshot(exec, python, from, to) {
|
|
|
379
501
|
* directory. Two outcomes only: a snapshot the engine proved consistent, or a
|
|
380
502
|
* thrown refusal that aborts the whole backup.
|
|
381
503
|
*/
|
|
382
|
-
function snapshotDatabase(from, to, exec) {
|
|
504
|
+
async function snapshotDatabase(from, to, exec) {
|
|
383
505
|
const before = statOrNull(from)
|
|
384
506
|
if (!before) return { mode: 'missing' }
|
|
385
507
|
if (before.isSymbolicLink()) throw new Error('backup refuses symbolic links')
|
|
@@ -397,7 +519,7 @@ function snapshotDatabase(from, to, exec) {
|
|
|
397
519
|
+ ': it is neither an empty placeholder nor a SQLite database, so its contents cannot be verified'
|
|
398
520
|
+ (walContent ? ' (it has a non-empty WAL)' : ''))
|
|
399
521
|
}
|
|
400
|
-
const resolved = enginePythonForBackup(exec)
|
|
522
|
+
const resolved = await enginePythonForBackup(exec)
|
|
401
523
|
const python = resolved.python
|
|
402
524
|
if (!python) {
|
|
403
525
|
const why = resolved.rejected.length ? ' (' + resolved.rejected.join('; ') + ')' : ''
|
|
@@ -406,7 +528,7 @@ function snapshotDatabase(from, to, exec) {
|
|
|
406
528
|
+ engineRoot() + why + '. Install or repair the engine, then retry. '
|
|
407
529
|
+ 'Nothing was copied: a live database copied by hand can restore as silent corruption.')
|
|
408
530
|
}
|
|
409
|
-
const snapshot = pythonSnapshot(exec, python, from, to)
|
|
531
|
+
const snapshot = await pythonSnapshot(exec, python, from, to)
|
|
410
532
|
if (!snapshot.ok) {
|
|
411
533
|
removeQuietly(to)
|
|
412
534
|
removeQuietly(to + '-wal')
|
|
@@ -516,7 +638,7 @@ function engineSummary() {
|
|
|
516
638
|
* `exec` only exists so tests can stand in for the engine interpreter; the
|
|
517
639
|
* default path spawns the verified venv binary and nothing else.
|
|
518
640
|
*/
|
|
519
|
-
function writeStores(staging, exec) {
|
|
641
|
+
async function writeStores(staging, exec) {
|
|
520
642
|
ensureDir(path.join(staging, 'libraries'))
|
|
521
643
|
ensureDir(path.join(staging, 'index'))
|
|
522
644
|
ensureDir(path.join(staging, 'prompts'))
|
|
@@ -525,7 +647,9 @@ function writeStores(staging, exec) {
|
|
|
525
647
|
// backup/restore so a restored install does not re-fork work it already did.
|
|
526
648
|
copyRegular(path.join(dataDir(), 'consolidation.json'), path.join(staging, 'consolidation.json'))
|
|
527
649
|
for (const name of readdirSafe(indexDir())) {
|
|
528
|
-
|
|
650
|
+
// Local deleted-memory stashes are a time-boxed undo buffer, not library
|
|
651
|
+
// data: they must never leak permanently deleted bodies into a backup.
|
|
652
|
+
if (name.endsWith('.json') && !name.endsWith('.deleted.json')) copyRegular(path.join(indexDir(), name), path.join(staging, 'index', name))
|
|
529
653
|
}
|
|
530
654
|
// 词典:data/lexicon/<libraryId>.json 与索引同权进备份清单。只收安全 id
|
|
531
655
|
// 命名的 JSON(restore 侧 allowlist 用同一规则拒绝越界);目录还不存在(这个
|
|
@@ -550,7 +674,7 @@ function writeStores(staging, exec) {
|
|
|
550
674
|
for (const database of databases) {
|
|
551
675
|
const target = path.join(staging, database.rel.split('/').join(path.sep))
|
|
552
676
|
ensureDir(path.dirname(target))
|
|
553
|
-
const result = snapshotDatabase(database.src, target, exec)
|
|
677
|
+
const result = await snapshotDatabase(database.src, target, exec)
|
|
554
678
|
snapshots.push({
|
|
555
679
|
file: database.rel,
|
|
556
680
|
mode: result.mode,
|
|
@@ -607,8 +731,8 @@ function cleanupStaging() {
|
|
|
607
731
|
* throw happens before anything is published, so no partial or torn backup can
|
|
608
732
|
* ever appear in backups/.
|
|
609
733
|
*/
|
|
610
|
-
export function createBackup({ label = 'auto', keep = BACKUP_KEEP, flushState = null, pythonExec = null } = {}) {
|
|
611
|
-
return withBackupLock(() => {
|
|
734
|
+
export async function createBackup({ label = 'auto', keep = BACKUP_KEEP, flushState = null, pythonExec = null } = {}) {
|
|
735
|
+
return withBackupLock(async () => {
|
|
612
736
|
ensureDir(backupsDir())
|
|
613
737
|
cleanupStaging()
|
|
614
738
|
const name = nextBackupName()
|
|
@@ -618,7 +742,7 @@ export function createBackup({ label = 'auto', keep = BACKUP_KEEP, flushState =
|
|
|
618
742
|
// Plugin state is flushed first: a backup must never capture the pending
|
|
619
743
|
// bookkeeping edits that are still only in memory.
|
|
620
744
|
if (typeof flushState === 'function') flushState()
|
|
621
|
-
const snapshots = writeStores(staging, pythonExec)
|
|
745
|
+
const snapshots = await writeStores(staging, pythonExec)
|
|
622
746
|
const files = collectFiles(staging)
|
|
623
747
|
const totals = { files: 0, bytes: 0 }
|
|
624
748
|
for (const rel of Object.keys(files)) {
|
|
@@ -923,6 +1047,7 @@ function liveTargetFor(rel) {
|
|
|
923
1047
|
if (head === 'global.sqlite3-shm') return globalDbFile() + '-shm'
|
|
924
1048
|
}
|
|
925
1049
|
if ((head === 'index' || head === 'libraries') && parts.length === 2) {
|
|
1050
|
+
if (parts[1].endsWith('.deleted.json')) throw new Error('backup contains a deleted-memory stash that must not be restored: ' + rel)
|
|
926
1051
|
return path.join(head === 'index' ? indexDir() : librariesDir(), parts[1])
|
|
927
1052
|
}
|
|
928
1053
|
if (head === 'lexicon' && parts.length === 2) {
|
|
@@ -991,6 +1116,10 @@ function verifyInventory(found) {
|
|
|
991
1116
|
const rels = []
|
|
992
1117
|
for (const rel of Object.keys(manifest.files)) {
|
|
993
1118
|
if (!isSafeRelative(rel)) throw new Error('invalid backup manifest path')
|
|
1119
|
+
// Backups made before stashes were excluded still list them. Skip rather
|
|
1120
|
+
// than fail, so restoring an older backup neither breaks nor resurrects
|
|
1121
|
+
// permanently deleted text.
|
|
1122
|
+
if (/^index\/[^/]+\.deleted\.json$/.test(rel)) continue
|
|
994
1123
|
const full = path.join(found.dir, rel.split('/').join(path.sep))
|
|
995
1124
|
const info = statOrNull(full)
|
|
996
1125
|
if (!info || info.isSymbolicLink() || !info.isFile()) throw new Error('backup is incomplete: ' + rel + ' is missing')
|
|
@@ -1072,17 +1201,17 @@ function retireVectorActive(reason) {
|
|
|
1072
1201
|
* A failure after that point is recoverable: the safety backup holds the state
|
|
1073
1202
|
* that was replaced, and it is protected from this operation's prune.
|
|
1074
1203
|
*/
|
|
1075
|
-
export function restoreFromBackup(name, { beforeRestore = null, flushState = null, clearCaches = null, keep = BACKUP_KEEP } = {}) {
|
|
1076
|
-
return withBackupLock(() => {
|
|
1204
|
+
export async function restoreFromBackup(name, { beforeRestore = null, flushState = null, clearCaches = null, keep = BACKUP_KEEP } = {}) {
|
|
1205
|
+
return withBackupLock(async () => {
|
|
1077
1206
|
const found = findBackup(name)
|
|
1078
1207
|
const plan = verifyInventory(found)
|
|
1079
1208
|
const vector = planVectorActive(found, plan.rels)
|
|
1080
1209
|
writeLease(found.name, { pid: process.pid, at: Date.now(), kind: 'restore' })
|
|
1081
1210
|
let safety = null
|
|
1082
1211
|
try {
|
|
1083
|
-
const created = typeof beforeRestore === 'function'
|
|
1212
|
+
const created = await (typeof beforeRestore === 'function'
|
|
1084
1213
|
? beforeRestore()
|
|
1085
|
-
: createBackup({ label: 'before-restore', flushState })
|
|
1214
|
+
: createBackup({ label: 'before-restore', flushState }))
|
|
1086
1215
|
safety = typeof created === 'string' ? created : (created && created.dir ? created.dir : null)
|
|
1087
1216
|
const rels = restoreOrder(plan.rels.filter(rel => rel !== 'index/vector-active.json' || vector.restore))
|
|
1088
1217
|
for (const rel of rels) {
|
|
@@ -54,9 +54,9 @@ export const RUNTIME_STATE = Object.freeze([
|
|
|
54
54
|
{ layer: 'temporary-map', file: 'lib/inbound.js:13', name: 'calls', keyedBy: 'sessionId', clearedBy: 'tool/result or turn/end' },
|
|
55
55
|
{ layer: 'temporary-map', file: 'lib/inbound.js:14', name: 'sessions', keyedBy: 'sessionId', clearedBy: 'session/disposed (releaseInboundSession)' },
|
|
56
56
|
{ layer: 'temporary-map', file: 'lib/media.js:19', name: 'captures', keyedBy: 'sessionId', clearedBy: 'capture settle' },
|
|
57
|
-
{ layer: 'temporary-map', file: 'lib/private.js:
|
|
57
|
+
{ layer: 'temporary-map', file: 'lib/private.js:742', name: 'inFlight', keyedBy: 'sessionId', clearedBy: 'consolidation settle' },
|
|
58
58
|
{ layer: 'temporary-map', file: 'lib/curator.js:50', name: 'jobs', keyedBy: 'job id', clearedBy: 'curation settle' },
|
|
59
|
-
{ layer: 'cache', file: 'lib/state.js:
|
|
59
|
+
{ layer: 'cache', file: 'lib/state.js:1201', name: 'indexCache', keyedBy: 'libraryId', clearedBy: 'next load / external write' },
|
|
60
60
|
{ layer: 'cache', file: 'lib/paths.js:52', name: 'readFailures', keyedBy: 'absolute file', clearedBy: 'a later successful read' },
|
|
61
61
|
])
|
|
62
62
|
|
|
@@ -75,7 +75,6 @@ const UNKNOWN = Object.freeze({
|
|
|
75
75
|
BINDINGS_NOT_OBJECT: 'bindings-not-an-object',
|
|
76
76
|
UNBOUND_BASIS_UNKNOWN: 'unbound-basis-unknown',
|
|
77
77
|
})
|
|
78
|
-
export const UNKNOWN_CODES = Object.freeze(UNKNOWN)
|
|
79
78
|
|
|
80
79
|
function isObject(value) {
|
|
81
80
|
return Boolean(value) && typeof value === 'object' && !Array.isArray(value)
|
package/lib/budget.js
CHANGED
|
@@ -33,15 +33,6 @@ export function estTokens(text) {
|
|
|
33
33
|
return Math.ceil(wide + narrow / LATIN_CHARS_PER_TOKEN)
|
|
34
34
|
}
|
|
35
35
|
|
|
36
|
-
/** How many characters of a text shaped like `sample` fit in `tokens`. */
|
|
37
|
-
export function charsForTokens(tokens, sample = '') {
|
|
38
|
-
const budget = Number(tokens)
|
|
39
|
-
if (!Number.isFinite(budget) || budget <= 0) return 0
|
|
40
|
-
const ratio = cjkRatio(sample)
|
|
41
|
-
const perChar = ratio + (1 - ratio) / LATIN_CHARS_PER_TOKEN
|
|
42
|
-
return Math.max(1, Math.floor(budget / perChar))
|
|
43
|
-
}
|
|
44
|
-
|
|
45
36
|
/**
|
|
46
37
|
* Cut `text` so its estimate stays within `maxTokens`. Prefers the last newline
|
|
47
38
|
* before the cut so entries are not sliced mid-line.
|