sage-mem 2.17.1 → 2.19.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/README.en.md +33 -2
- package/README.md +33 -2
- package/lib/autodream/llm-loop.js +19 -0
- package/lib/autodream/prompt.js +42 -3
- package/lib/autodream/reconcile.js +145 -0
- package/lib/autodream/session-search-policy.js +388 -0
- package/lib/autodream/session-search.js +406 -0
- package/lib/autodream/tools.js +15 -173
- package/lib/client.js +2 -2
- package/package.json +1 -1
package/README.en.md
CHANGED
|
@@ -12,7 +12,7 @@
|
|
|
12
12
|
|
|
13
13
|
**Cross-session memory for DeepSeek Harness — plain markdown files, no database, no worker.**
|
|
14
14
|
|
|
15
|
-
**Current release: `2.
|
|
15
|
+
**Current release: `2.19.0`** — the npm badge above is the dynamic source of truth. **Contract baseline: `1.0.0`** — the first stable release, whose public commitments, the capability boundaries and the list of things it explicitly cannot do are frozen in the
|
|
16
16
|
[frozen contract](https://github.com/gezi-wen/sage-mem/blob/main/docs/1.0.0-contract.md).
|
|
17
17
|
|
|
18
18
|
If it is useful to you, a Star is the most direct feedback.
|
|
@@ -405,10 +405,41 @@ The optional memory-consolidation feature (identifier `autodream`): it reads thr
|
|
|
405
405
|
|---|---|---|
|
|
406
406
|
| Trigger | Manual only / run automatically when conditions are met | Automatic mode goes through three levels of gating, **checking the cheapest first**: time gate (≥ N hours since last time, one read/write) → session gate (≥ M sessions with updates in between, one directory scan) → lock (against concurrency). A 10-minute scan throttle is sandwiched in between, so that while "the time gate passed but the session gate did not" it does not rescan for nothing every turn |
|
|
407
407
|
| Mode of change | Report only / rewrite directly | In "report only" mode **the write tools are simply not attached for the model at all** — it is not constrained by a sentence saying "please do not write", it has no hands |
|
|
408
|
-
| Input source | Memory directory only / memory + session records | The latter decompresses session records (zstd) for targeted keyword search; the cost is that private conversations enter the model context, and the token cost is higher too |
|
|
408
|
+
| Input source | Memory directory only / memory + session records | The latter decompresses session records (zstd) for a targeted keyword search (not a full index: at most the **40** most recent v4 sessions enter the queue, and the first line of every result states how much was actually covered); the cost is that private conversations enter the model context, and the token cost is higher too |
|
|
409
409
|
|
|
410
410
|
Automatic triggering runs on the plugin's own timer (checks the gates every 30 minutes by default). Consolidation **deliberately does not run through your session** — the tool set is given by the plugin, the step count is capped, and it is not written into your session records.
|
|
411
411
|
|
|
412
|
+
### Reconciliation: checking old memories against sessions (2.18.0)
|
|
413
|
+
|
|
414
|
+
When the input source is "memory + session records", consolidation first picks at most 5 memories **most likely to disagree with the present**. Two criteria must both hold:
|
|
415
|
+
|
|
416
|
+
- **Still being injected recently** (it appeared in your context within the last 7 days) — so it is in service, not a dead file;
|
|
417
|
+
- **But the content has not changed for a long time** (the file has not been written for 14+ days) — so the wording may be stale.
|
|
418
|
+
|
|
419
|
+
"Still in use + long unchanged" is the dangerous combination: new facts cannot get in, while the old statement keeps showing up in every injection. For those 5, the model uses session records to check whether what they say still lines up:
|
|
420
|
+
|
|
421
|
+
- **It lines up** → do nothing. **All five passing with not a single edit is a normal outcome of that run.**
|
|
422
|
+
- **It does not line up** → fix the old wording at its source (not by appending "actually it is not like that")
|
|
423
|
+
- **The whole entry is obsolete** → archiving is an option, but a reason is required
|
|
424
|
+
- **It is merely missing new progress** → merge into the existing file, do not open a new one
|
|
425
|
+
|
|
426
|
+
So it may occasionally touch an entry you never asked it to change — **that is reconciliation, not random editing**. This is also the first time the feature can notice "this was recorded wrong / has gone stale"; before this it could only notice "something is missing".
|
|
427
|
+
|
|
428
|
+
**With "memory directory only" this whole stage disappears** (there are no sessions to check against, and a list without sessions would only make it guess). The list itself carries only file names and day counts, never the body text.
|
|
429
|
+
|
|
430
|
+
### Session search now states how much it looked at (2.19.0)
|
|
431
|
+
|
|
432
|
+
The `search_sessions` tool that consolidation holds is a **targeted keyword search**, not a full index. **The first line of every result is the coverage**:
|
|
433
|
+
|
|
434
|
+
- **How much is reachable**: how many session transcripts it recognises, how many actually entered the queue (**40 is the queue cap**, not "always exactly 40"; nor does entering the queue guarantee being fully read — the first line is the authoritative number), and how many were fully searched / only partly readable / unreadable / not looked at because of the cap / never started because the output budget ran out.
|
|
435
|
+
- **Each snippet is at most 500 characters and is centred on the keyword**: for an ordinary hit (the keyword itself no longer than the snippet cap) the match point is always inside the snippet; if the keyword is close to or longer than 500 characters, the window starts at the keyword. The old version cut 500 characters from the start of the line, so a keyword past the window produced a snippet that did not contain it at all.
|
|
436
|
+
- **8000 is the character budget for the matching snippets** — not a hard cap on the whole output including that first line.
|
|
437
|
+
- **Two axes are reported separately**: *input coverage* (did it look everywhere) and *output truncation* (were the snippets clipped). "Everything was read but each snippet was cut" and "only a few sessions were read" are different things, and `complete` / `truncated` each say one of them.
|
|
438
|
+
- **A zero result has two phrasings**: only with complete coverage may it say "searched all N sessions, found nothing"; with incomplete coverage it must say "found nothing among the M sessions it actually read, with … remaining", and state plainly that **this does not mean the sessions do not mention it**.
|
|
439
|
+
- **Old formats are reported, not read**: v3 and unversioned session transcripts are counted and appear in the coverage, but this version does not read them (that is left to a separate release).
|
|
440
|
+
|
|
441
|
+
So reconciliation has one discipline: **with incomplete coverage, "found nothing" must not be used as counter-evidence that a memory is stale or should be archived**; explicit contrary evidence (a session stating another address or another conclusion) is still acted on as before.
|
|
442
|
+
|
|
412
443
|
### The Consolidation Model Can Be Specified Separately
|
|
413
444
|
|
|
414
445
|
Consolidation is a background batch job and need not be the same model as the one used for chatting. The settings page under 「高级设置 → 模型」(Advanced settings → Model) lets you pick one from **the model routes currently configured** (the options come from the same catalog as in 「模型选择」/ model selection).
|
package/README.md
CHANGED
|
@@ -14,7 +14,7 @@
|
|
|
14
14
|
|
|
15
15
|
> File-based cross-session memory for DeepSeek Harness — every memory is a plain markdown file you can open, edit and delete. No database, no worker, no port.
|
|
16
16
|
|
|
17
|
-
**当前发布版本:`2.
|
|
17
|
+
**当前发布版本:`2.19.0`** —— 顶部 npm 徽章是动态权威。**契约基线:`1.0.0`** —— 第一个稳定版,公开承诺、能力边界与「明确做不到」的清单冻结在
|
|
18
18
|
[契约冻结](https://github.com/gezi-wen/sage-mem/blob/main/docs/1.0.0-contract.md)。
|
|
19
19
|
|
|
20
20
|
如果它对你有用,给个 Star 是最直接的反馈。
|
|
@@ -407,10 +407,41 @@ sage-mem 给记忆目录的写入加了**版本守卫**:写入前记下当前
|
|
|
407
407
|
|---|---|---|
|
|
408
408
|
| 触发 | 只手动 / 满足条件自动跑 | 自动模式走三级门控,**最便宜的先查**:时间门(距上次 ≥ N 小时,一次读写)→ 会话门(期间 ≥ M 个会话有更新,一次目录扫描)→ 锁(防并发)。中间夹一层 10 分钟扫描节流,免得「时间门过了、会话门没过」时每轮白扫 |
|
|
409
409
|
| 改动方式 | 只出报告 / 直接改写 | 「只出报告」模式下**写工具根本不会挂给模型** —— 不是靠一句「请不要写」约束,是它没有手 |
|
|
410
|
-
| 输入源 | 仅记忆目录 / 记忆 + 会话记录 | 后者会解压会话记录(zstd
|
|
410
|
+
| 输入源 | 仅记忆目录 / 记忆 + 会话记录 | 后者会解压会话记录(zstd)做定向关键词搜索(不是全量索引:最近最多 **40 个** v4 会话,结果首行会写明实际覆盖了多少);代价是私密对话会进入模型上下文,token 成本也更高 |
|
|
411
411
|
|
|
412
412
|
自动触发走插件自己的定时器(默认 30 分钟查一次门控)。整理**刻意不走会话** —— 工具集由插件给、步数有上限、不写进你的会话记录。
|
|
413
413
|
|
|
414
|
+
### 对账:拿会话核对旧记忆(2.18.0)
|
|
415
|
+
|
|
416
|
+
输入源选了「记忆 + 会话记录」时,整理前会先挑出最多 5 条**最可能与现状不符**的记忆。判据是两条同时成立:
|
|
417
|
+
|
|
418
|
+
- **最近还被注入过**(最近 7 天里出现过在你的上下文里)—— 说明它仍在服役,不是死文件;
|
|
419
|
+
- **但内容很久没动**(文件 14 天以上没写过)—— 说明这段话可能就是旧的。
|
|
420
|
+
|
|
421
|
+
「还在用 + 很久没改」才是最危险的组合:新事实进不来,旧说法还在每次注入里出现。对这 5 条,模型拿会话记录去核对「它写的还对不对得上」:
|
|
422
|
+
|
|
423
|
+
- **对得上** → 什么都不做。**全部通过、一个字都不改,是这一趟的正常结果。**
|
|
424
|
+
- **对不上** → 在源头改掉旧说法(不是后面追加一句「其实不是这样」)
|
|
425
|
+
- **整条过时** → 可以考虑归档,必须带缘由
|
|
426
|
+
- **只是缺了新进展** → 合并进已有文件,不新开一条
|
|
427
|
+
|
|
428
|
+
所以它偶尔会动到你没明说要改的条目 —— **那是对账,不是乱动**。这也是本功能第一次具备「发现记错了 / 过时了」的能力;在此之前它只能发现「漏了什么」。
|
|
429
|
+
|
|
430
|
+
**选「仅记忆目录」时这一段完全不出现**(没有会话可核对,名单给出来只会让它硬猜)。名单本身只有文件名与天数,不含正文。
|
|
431
|
+
|
|
432
|
+
### 搜会话时它会说清「看了多少」(2.19.0)
|
|
433
|
+
|
|
434
|
+
整理时手上那个 `search_sessions` 是**定向关键词搜索**,不是全量索引。它的结果**首行就是覆盖率**:
|
|
435
|
+
|
|
436
|
+
- **看得到多少**:认得的会话正文有多少份、实际进队多少份(**40 是进队上限**,不是「每次必扫 40」;也不保证进队的那几份都能读完 —— 实际数字以首行为准)、完整搜索 / 只读到一部分 / 读不动 / 因上限没看 / 因输出预算没开始各多少份。
|
|
437
|
+
- **每段最多 500 字,以关键词为中心取**:常规命中(关键词本身不超过片段上限)时命中点一定在片段里;关键词长到接近或超过 500 字时,窗口从关键词开头取满。旧版从行首硬切,关键词落在窗口之后就等于返回了一段看不见它的文字。
|
|
438
|
+
- **8000 是命中片段的字符总预算** —— 不是整份输出(含首行)的硬上限。
|
|
439
|
+
- **两条轴分开报**:*输入覆盖*(有没有看完)与*输出截断*(片段有没有被裁)。「全都看了、每段被裁短」与「只看了几份」是两件不同的事,`complete` 与 `truncated` 各说一件。
|
|
440
|
+
- **零命中分两种说法**:覆盖完整才说「完整搜索了全部 N 个会话,没找到」;覆盖不完整只能说「在真正读到的 M 个会话里没找到,另有 …」,并明说**这不等于会话里没有**。
|
|
441
|
+
- **旧格式只报不读**:v3 与无版本号的会话正文会被数出来写进覆盖率,本版不读它们(读的行为留给单独一版)。
|
|
442
|
+
|
|
443
|
+
所以对账有一条纪律:**覆盖率不完整时的「没搜到」不能当成「这条记忆过时 / 该归档」的反证**;而拿到明确相反的证据(会话里写着另一个地址、另一套结论)时照常改。
|
|
444
|
+
|
|
414
445
|
### 整理用的模型可以单独指定
|
|
415
446
|
|
|
416
447
|
整理是后台批量任务,跟聊天用的不一定是同一个模型。设置页「高级设置 → 模型」可以从**当前已配置的模型路线**里挑一条(选项与「模型选择」里的目录同源)。
|
|
@@ -9,6 +9,9 @@
|
|
|
9
9
|
*/
|
|
10
10
|
|
|
11
11
|
import { buildAutodreamSystemPrompt, buildAutodreamUserPrompt } from './prompt.js'
|
|
12
|
+
import { buildReconcileList } from './reconcile.js'
|
|
13
|
+
import { readAccessLedger, ledgerFileFor } from '../memory/access.js'
|
|
14
|
+
import { scanMemoryDir } from '../memory/scan.js'
|
|
12
15
|
import { randomUUID } from 'node:crypto'
|
|
13
16
|
|
|
14
17
|
export class BlockAssembler {
|
|
@@ -214,12 +217,28 @@ export async function agentLoop(cfg, runOpts) {
|
|
|
214
217
|
withSessions: cfg.source === 'memory+sessions',
|
|
215
218
|
reservedFiles: this.reservedFiles,
|
|
216
219
|
})
|
|
220
|
+
/**
|
|
221
|
+
* 2.18.0「对账」:只在**会话记录也在输入源里**时,挑几条「还在被注入、内容却很久没动」
|
|
222
|
+
* 的记忆,让模型拿会话去核对它们。这是「查字典」之外的新切口 —— 字典补漏,对账纠错。
|
|
223
|
+
*
|
|
224
|
+
* 「什么时候算、算不出来怎么办」都在 `buildReconcileList` 里(含静默降级),
|
|
225
|
+
* 这里只负责把真实 IO 递进去:扫目录拿 mtime,读 access 台账拿「最近被注入过没有」。
|
|
226
|
+
*/
|
|
227
|
+
const reconcileList = await buildReconcileList({
|
|
228
|
+
source: cfg.source,
|
|
229
|
+
// 粗细刚好:这里只需要 mtime 做粗筛,正文一个字都不读(扫描层有目录缓存)。
|
|
230
|
+
listEntries: async () =>
|
|
231
|
+
(await scanMemoryDir(this.ctx, '', this.memoryDir)).map((f) => ({ file: f.file, mtime: f.mtimeMs })),
|
|
232
|
+
readLedger: readAccessLedger,
|
|
233
|
+
ledgerFile: ledgerFileFor(this.memoryDir),
|
|
234
|
+
})
|
|
217
235
|
const userText = buildAutodreamUserPrompt({
|
|
218
236
|
memoryDir: this.memoryDir,
|
|
219
237
|
apply: cfg.apply,
|
|
220
238
|
hoursSince: runOpts.hoursSince ?? 0,
|
|
221
239
|
sessionCount: runOpts.sessionCount ?? 0,
|
|
222
240
|
now: Date.now(),
|
|
241
|
+
reconcileList,
|
|
223
242
|
})
|
|
224
243
|
const messages = [userMessage(userText)]
|
|
225
244
|
|
package/lib/autodream/prompt.js
CHANGED
|
@@ -79,7 +79,46 @@ ${reservedNote}
|
|
|
79
79
|
* @returns {string}
|
|
80
80
|
*/
|
|
81
81
|
export function buildAutodreamUserPrompt(opts) {
|
|
82
|
-
const { memoryDir, apply, hoursSince, sessionCount, now } = opts
|
|
82
|
+
const { memoryDir, apply, hoursSince, sessionCount, now, reconcileList } = opts
|
|
83
|
+
|
|
84
|
+
/**
|
|
85
|
+
* 阶段 2.5(2.18.0「对账」)。只在**有会话输入源且确实挑出了候选**时出现。
|
|
86
|
+
*
|
|
87
|
+
* 为什么单开一段而不是塞进阶段 2:阶段 2 说的是「收集新东西」,这一段说的是
|
|
88
|
+
* 「核对旧东西还对不对」。两者目标相反 —— 前者要多记,后者要少错。混在一起,
|
|
89
|
+
* 模型会把它读成「又一轮收集」,于是对着每条候选硬凑一句改动。
|
|
90
|
+
*
|
|
91
|
+
* ⚠️ 末句「一条都没问题也可以」是必需的:不给退路,模型会为了有产出而去改
|
|
92
|
+
* 本来没错的记忆,那就是把「对账」做成了「制造 Git 噪音」。
|
|
93
|
+
*/
|
|
94
|
+
const stage25 = reconcileList
|
|
95
|
+
? `
|
|
96
|
+
## 阶段 2.5 — 对账(只核对下面这几条)
|
|
97
|
+
|
|
98
|
+
下面这些条目**最近还在被注入,但内容很久没动过**。它们不代表写错了,只是最可能与现状不符:
|
|
99
|
+
|
|
100
|
+
${reconcileList}
|
|
101
|
+
|
|
102
|
+
对每一条,用 \`search_sessions\` 搜一两个来自它的关键词,看最近实际发生的事跟它写的**还对不对得上**:
|
|
103
|
+
|
|
104
|
+
- **对得上** → 什么都不要做(通过,别为了「有产出」去改它)
|
|
105
|
+
- **对不上** → 在**源头**改掉旧说法(阶段 3 的规则同样适用:改在源头,不在后面追加一句「其实不是这样」)
|
|
106
|
+
- **整条过时** → 可以考虑归档,但必须带 \`reason\`
|
|
107
|
+
- **只是缺了新进展** → 合并进已有文件,不要新开一条
|
|
108
|
+
|
|
109
|
+
⚠️ **先读搜索结果的覆盖率那一行,再决定怎么解释「没搜到」。** \`search_sessions\` **可能只覆盖得到
|
|
110
|
+
一部分会话**(最近若干个、读得动的、认得的格式),首行会写明看了多少、漏了多少。所以:
|
|
111
|
+
|
|
112
|
+
- 覆盖率**不完整**时的零命中 = **没有看见**,不是**没有**。**它不能当成「这条记忆过时 / 该归档」的反证**,
|
|
113
|
+
也不足以支撑「对不上」这个判断 —— 那就当这一条没核对成,放着别动。
|
|
114
|
+
- 覆盖率**完整**时的零命中,才可以说「会话里确实没有提到它」。
|
|
115
|
+
- 反过来,如果你拿到的是**明确相反的证据**(会话里写着另一个地址、另一套结论、已经推翻了它),
|
|
116
|
+
那和覆盖率无关,照上面的规则改。
|
|
117
|
+
|
|
118
|
+
⚠️ 这一段的目标是**减少错记忆**,不是增加记忆条数。全部核对通过、一个字都不改,也是这一趟的正常结果。
|
|
119
|
+
`
|
|
120
|
+
: ''
|
|
121
|
+
|
|
83
122
|
const stage4 = apply
|
|
84
123
|
? `- 更新 \`MEMORY.md\` 索引,让它保持是索引而不是内容堆:
|
|
85
124
|
- 每条一行 \`- [标题](文件.md) — 一句话\`
|
|
@@ -124,8 +163,8 @@ export function buildAutodreamUserPrompt(opts) {
|
|
|
124
163
|
|
|
125
164
|
1. **结构性毛病** —— 直接跑 \`audit_memory\`,它会把索引悬空、漏索引、type 与前缀不一致、双链断链、YAML 陷阱都列出来。这些是确定要做的事。
|
|
126
165
|
2. **漂移的旧记忆** —— 描述与内容已经对不上的、日期还是相对写法的、被后续进展推翻的。
|
|
127
|
-
3. **(仅在需要具体细节时)** 用 \`search_sessions\`
|
|
128
|
-
|
|
166
|
+
3. **(仅在需要具体细节时)** 用 \`search_sessions\` 定向搜一个具体词。它首行会写明这次覆盖了多少会话 —— 覆盖不完整时的「没搜到」只是没看见,不是证据。不要通读会话记录。
|
|
167
|
+
${stage25}
|
|
129
168
|
## 阶段 3 — 整合
|
|
130
169
|
|
|
131
170
|
对每件值得记住的事,改写或新建一条记忆。**合并新信息进已有文件**,不要为一点新东西新开一个文件。被推翻的事实改在源头,而不是在后面追加一句「其实不是这样」。
|
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 「对账候选」的挑选(2.18.0)。
|
|
3
|
+
*
|
|
4
|
+
* ## 为什么要有它
|
|
5
|
+
*
|
|
6
|
+
* 自动做梦原先拿会话记录的方式是**查字典**(`prompt.js` 里那句「用 `search_sessions`
|
|
7
|
+
* 定向搜一个具体词,不要通读会话记录」)。查字典能补漏,但发现不了「记错了 / 过时了」——
|
|
8
|
+
* 而那恰恰是 Anthropic 的 Dreams 在做的事(把 session transcripts 当输入,跟记忆逐条对)。
|
|
9
|
+
*
|
|
10
|
+
* 我们不通读会话是有意的取舍(token 与隐私)。所以这里换个更省的切口:
|
|
11
|
+
* **不让模型通读,而是先给它一张「最可能与现状不符」的短名单**,让它只对这几条去核对。
|
|
12
|
+
*
|
|
13
|
+
* ## 候选判据(两个条件同时成立)
|
|
14
|
+
*
|
|
15
|
+
* 1. **最近还被注入过**(`injected` 在 N 天内)—— 说明它仍在服役,不是死文件;
|
|
16
|
+
* 2. **但内容很久没动过**(文件 mtime 早于 M 天)—— 说明这段话很可能是旧的。
|
|
17
|
+
*
|
|
18
|
+
* 「还在用 + 很久没改」= 最危险的组合:新的事实进不来,旧的说法还在每次注入里出现。
|
|
19
|
+
*
|
|
20
|
+
* 为什么用 mtime 而不读 frontmatter 的 `updated`:这里只需要粗筛,读 129 个文件的
|
|
21
|
+
* frontmatter 要解析 YAML,而 mtime 一次 stat 就够。**粗筛宁宽勿严** —— 名单是给模型
|
|
22
|
+
* 参考的,它自己会判断要不要真去改。
|
|
23
|
+
*
|
|
24
|
+
* ## 为什么不用语义
|
|
25
|
+
*
|
|
26
|
+
* 与整个插件一致:这一层只做「哪几条值得看一眼」的排序,不做「哪条错了」的判断。
|
|
27
|
+
* 判断留给模型(它在做梦时本来就有 tool 和上下文)。
|
|
28
|
+
*/
|
|
29
|
+
|
|
30
|
+
/** 候选条数的默认上限。给多了模型读不完,给少了覆盖不到。 */
|
|
31
|
+
export const DEFAULT_RECONCILE_LIMIT = 5
|
|
32
|
+
|
|
33
|
+
/** 「最近还被注入过」的窗口(天)。 */
|
|
34
|
+
export const DEFAULT_FRESH_DAYS = 7
|
|
35
|
+
|
|
36
|
+
/** 「内容很久没动」的门槛(天)。 */
|
|
37
|
+
export const DEFAULT_STALE_DAYS = 14
|
|
38
|
+
|
|
39
|
+
const day = 86400000
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* 纯函数:从「文件 × 台账」里挑对账候选。
|
|
43
|
+
*
|
|
44
|
+
* @param {object} input
|
|
45
|
+
* @param {Array<{file: string, mtime: number, bytes?: number}>} input.entries — 记忆目录里的条目
|
|
46
|
+
* @param {Record<string, {injected?: number, read?: number}>} input.ledger — access 台账
|
|
47
|
+
* @param {number} [input.limit]
|
|
48
|
+
* @param {number} [input.freshDays]
|
|
49
|
+
* @param {number} [input.staleDays]
|
|
50
|
+
* @param {number} [input.now]
|
|
51
|
+
* @returns {Array<{file: string, idleDays: number, injectedDays: number}>} 按「最久没改」优先
|
|
52
|
+
*/
|
|
53
|
+
export function pickReconcileCandidates({
|
|
54
|
+
entries,
|
|
55
|
+
ledger,
|
|
56
|
+
limit = DEFAULT_RECONCILE_LIMIT,
|
|
57
|
+
freshDays = DEFAULT_FRESH_DAYS,
|
|
58
|
+
staleDays = DEFAULT_STALE_DAYS,
|
|
59
|
+
now = Date.now(),
|
|
60
|
+
}) {
|
|
61
|
+
if (!Array.isArray(entries) || entries.length === 0) return []
|
|
62
|
+
const rows = []
|
|
63
|
+
for (const e of entries) {
|
|
64
|
+
if (!e || typeof e.file !== 'string') continue
|
|
65
|
+
const rec = ledger?.[e.file] ?? ledger?.[e.file.toLowerCase()]
|
|
66
|
+
const injected = typeof rec?.injected === 'number' ? rec.injected : 0
|
|
67
|
+
// 条件一:最近还被注入过(0 = 从没注入过,不算候选 —— 那种不叫「过时」,叫「没用上」)
|
|
68
|
+
if (injected <= 0) continue
|
|
69
|
+
const injectedDays = (now - injected) / day
|
|
70
|
+
if (injectedDays > freshDays) continue
|
|
71
|
+
// 条件二:内容很久没动
|
|
72
|
+
const mtime = typeof e.mtime === 'number' ? e.mtime : 0
|
|
73
|
+
if (mtime <= 0) continue
|
|
74
|
+
const idleDays = (now - mtime) / day
|
|
75
|
+
if (idleDays < staleDays) continue
|
|
76
|
+
rows.push({ file: e.file, idleDays: Math.floor(idleDays), injectedDays: Math.floor(injectedDays) })
|
|
77
|
+
}
|
|
78
|
+
// 「还在服役」这一点越强(注入越近)、「内容越旧」,越该先对账。
|
|
79
|
+
rows.sort((a, b) => (a.injectedDays - b.injectedDays) || (b.idleDays - a.idleDays))
|
|
80
|
+
return rows.slice(0, Math.max(0, limit))
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/**
|
|
84
|
+
* 带上 IO 的那层:读目录 + 读台账,交给纯函数挑。
|
|
85
|
+
*
|
|
86
|
+
* @param {object} input
|
|
87
|
+
* @param {string} input.memoryDir
|
|
88
|
+
* @param {(dir: string) => Promise<Array<{file: string, mtime: number, bytes?: number}>>} input.listEntries — 由调用方注入,避免本文件依赖 scan
|
|
89
|
+
* @param {(ledgerFile: string) => Promise<object>} input.readLedger
|
|
90
|
+
* @param {string} input.ledgerFile
|
|
91
|
+
* @param {number} [input.now]
|
|
92
|
+
* @param {number} [input.limit]
|
|
93
|
+
* @returns {Promise<Array<{file: string, idleDays: number, injectedDays: number}>>}
|
|
94
|
+
*/
|
|
95
|
+
export async function collectReconcileCandidates({ listEntries, readLedger, ledgerFile, now = Date.now(), limit }) {
|
|
96
|
+
const [entries, ledger] = await Promise.all([listEntries(), readLedger(ledgerFile)])
|
|
97
|
+
return pickReconcileCandidates({ entries, ledger, limit, now })
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/**
|
|
101
|
+
* 把候选渲染成 prompt 里那一段。
|
|
102
|
+
*
|
|
103
|
+
* 为什么渲染在 prompt 侧而不是这里拼好整段:这一段要跟「阶段 2.5」的标题与指令一起出现,
|
|
104
|
+
* 分开写会让两处措辞漂移。这里只负责**列表本身**,措辞归 `prompt.js`。
|
|
105
|
+
*
|
|
106
|
+
* @param {Array<{file: string, idleDays: number, injectedDays: number}>} rows
|
|
107
|
+
* @returns {string} 每行一条;空数组返回空串(调用方据此整段不出现)
|
|
108
|
+
*/
|
|
109
|
+
export function renderReconcileList(rows) {
|
|
110
|
+
if (!Array.isArray(rows) || rows.length === 0) return ''
|
|
111
|
+
return rows
|
|
112
|
+
.map((r) => `- \`${r.file}\` —— 最近 ${r.injectedDays} 天内还在被注入,但内容已经 ${r.idleDays} 天没动过`)
|
|
113
|
+
.join('\n')
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/** 只有会话记录也在输入源里时才有「拿会话去核对」这回事。 */
|
|
117
|
+
export const RECONCILE_SOURCE = 'memory+sessions'
|
|
118
|
+
|
|
119
|
+
/**
|
|
120
|
+
* 引擎实际调用的那一层:**按输入源开关 + 失败降级**都收在这里,好被测试直接钉住。
|
|
121
|
+
*
|
|
122
|
+
* 为什么把「什么时候算、算不出来怎么办」也放本文件:这两条是这一版唯一有行为风险的
|
|
123
|
+
* 决定(错了要么拖垮整趟做梦,要么在「仅记忆目录」时凭空多出一段)。留在引擎的方法体里
|
|
124
|
+
* 就只能靠读源码断言,放到这里可以直接喂假 IO 跑。
|
|
125
|
+
*
|
|
126
|
+
* ⚠️ 降级是**静默**的:对账是附加价值,它挂了不该让整趟做梦失败,也不该往报告里塞错误。
|
|
127
|
+
*
|
|
128
|
+
* @param {object} input
|
|
129
|
+
* @param {string} input.source — 本次输入源
|
|
130
|
+
* @param {() => Promise<Array<{file: string, mtime: number}>>} input.listEntries
|
|
131
|
+
* @param {(file: string) => Promise<object>} input.readLedger
|
|
132
|
+
* @param {string} input.ledgerFile
|
|
133
|
+
* @param {number} [input.limit]
|
|
134
|
+
* @param {number} [input.now]
|
|
135
|
+
* @returns {Promise<string>} 列表文本;不该有或算不出来时是空串
|
|
136
|
+
*/
|
|
137
|
+
export async function buildReconcileList({ source, listEntries, readLedger, ledgerFile, limit, now = Date.now() }) {
|
|
138
|
+
if (source !== RECONCILE_SOURCE) return ''
|
|
139
|
+
try {
|
|
140
|
+
const rows = await collectReconcileCandidates({ listEntries, readLedger, ledgerFile, limit, now })
|
|
141
|
+
return renderReconcileList(rows)
|
|
142
|
+
} catch {
|
|
143
|
+
return ''
|
|
144
|
+
}
|
|
145
|
+
}
|