cortico-world-memory-core 0.3.2 → 0.4.1
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 +23 -0
- package/ENV_PROMPT.md +1 -1
- package/README.md +15 -3
- package/describe.json +2 -2
- package/package.json +3 -3
- package/src/config.ts +12 -1
- package/src/recall.ts +10 -1
- package/src/site.ts +45 -4
- package/src/store.ts +165 -14
- package/src/tools.ts +1 -1
- package/src/world.ts +143 -4
- package/webui/app.js +235 -12
- package/webui/index.html +2 -0
- package/webui/style.css +701 -665
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,28 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.4.1
|
|
4
|
+
|
|
5
|
+
0.4.0 没发到 npm,这里补上它漏掉的两件事——都是「承诺闭环」那一处。
|
|
6
|
+
|
|
7
|
+
- **补齐「无截止」出口**:0.4.0 只做了「不带 `dueAt` 就拒绝」,结果是一个真没时间的承诺(「下次见面给她带那本书」)根本存不进去,模型要么编一个日期,要么降级写成 `note`。现在 `dueAt: "none"` 会被接受,存成「无截止」的承诺:不参与提醒,但在体检测出来,可以补时间。
|
|
8
|
+
- **周期提醒改成默认开**:`promiseRepeatDays` 默认从 `0` 改成 `1`。0.4.0 的默认值等于「提醒一次就永久沉默」,那个 bug 实际还在。现在过期没做的承诺每天最多提一次,直到做完(传 `closes`)或退休;想退回旧行为就设 `0`。
|
|
9
|
+
- 修一处恢复失真:走导入接口撤销删除时,原本会把 `source` 一律改成 `import:backup`,现在能带就带。
|
|
10
|
+
|
|
11
|
+
## 0.4.0
|
|
12
|
+
|
|
13
|
+
这一版先把「会丢的东西别丢、答应的别忘」,再加一个能看见自己状态的体检页。默认行为基本不变,两处有意的变化单独标出。
|
|
14
|
+
|
|
15
|
+
- **写盘改成原子操作**:`cards.jsonl` / `turns.jsonl` / `state.json` 都先写 `.tmp` 再改名。原来每次全量 `writeFileSync` 覆盖,写到一半断电或被杀,文件会截断成空,`load()` 静默返回 0 条——整个库就这么没了,页面上一点异常都看不出来。rename 被杀软锁住时退回直接写。
|
|
16
|
+
- **每天自动备份**:当天第一次写入前把 `cards.jsonl` 复制到 `backups/cards-YYYY-MM-DD.jsonl`,只留 7 份。备份先于覆盖,所以备份里总是「改动前」的完整文件。
|
|
17
|
+
- **导入**:`POST /api/import` 接受自己导出的 JSON(整包:卡片 + 原文 + 日程 + 状态)。只加不覆盖——同 id 或「同类型 + 同文本」跳过,所以重复导同一个文件是幂等的。`state` 只接 `rawWatermark` 而且只往前推,防止旧备份把水位倒回去重录原文。原来只有导出没有导入,备份是单向的。
|
|
18
|
+
- **承诺必须带 `dueAt`**:`mcore_write` 写 `promise` 不给 `dueAt` 会直接被拒,并提示先问对方。之前 6 条承诺里 4 条没有截止时间,提醒管线对它们完全无效。
|
|
19
|
+
- **可选的周期提醒**:新增 `promiseRepeatDays`(默认 `0`)。`0` 时和旧版完全一致(提醒一次就永久沉默);大于 `0` 时按上次提醒时间算,够天数就再提一次,给「每天发一条」这类周期承诺用。
|
|
20
|
+
- **排序参考「上次被想起的时间」**:`lastUsedAt` 进打分(权重上限 0.15,压不倒一个关键词命中)。新增 `recallUseAging`(默认开),关掉退回旧公式。
|
|
21
|
+
- **体检页**:在用 / 从没被召回 / 召回次数 / 原文规模、近 14 天新增柱状、承诺与备份状态。从没被召回的卡可一键退休(不删除)。
|
|
22
|
+
- **维护面板加「承诺」页**:列出没写截止时间的(带时间输入框直接补)和已过时间还没做的(可标记做完)。
|
|
23
|
+
- **彻底删除加预览与撤销**:删前列出将删的条目,删后 10 秒内可整包还原(走新的导入接口)。
|
|
24
|
+
- 提示词 720 → 732 字:补一句「承诺必须写 dueAt,不知道就先问」。
|
|
25
|
+
|
|
3
26
|
## 0.3.2
|
|
4
27
|
|
|
5
28
|
- 简介统一格式:群号单独成段「QQ 交流群:745879632」,不再跟着正文尾巴;英文版同步。
|
package/ENV_PROMPT.md
CHANGED
|
@@ -6,7 +6,7 @@
|
|
|
6
6
|
- `fact` 关于对方的稳定事实(名字、作息、忌讳、正在忙的事)。
|
|
7
7
|
- `self` 关于你自己的(喜欢什么、怕什么、决定过什么)。
|
|
8
8
|
- `episode` 发生过的一件事,带上当时的感觉。
|
|
9
|
-
- `promise`
|
|
9
|
+
- `promise` 答应过的事,必须写 `dueAt`(不知道就先问一句;确实没有截止时间就写 `none`);做完或改了传 `closes`(查出来的行首 8 位就是 id)。
|
|
10
10
|
- `note` 过几天就没用的临时信息。
|
|
11
11
|
|
|
12
12
|
写法:一条一件事,40–80 字,写清楚谁、什么时候、怎么了;不要写「对方说了一些事」这种空话。同一件事不要写两遍,记不清就先查。`weight` 是这事在你心里的分量,0.3 琐事 / 0.5 一般 / 0.8 重要。
|
package/README.md
CHANGED
|
@@ -29,7 +29,7 @@ pnpm add cortico-world-memory-core
|
|
|
29
29
|
|
|
30
30
|
| 工具 | 作用 |
|
|
31
31
|
|---|---|
|
|
32
|
-
| `mcore_write` | 写一条记忆。`kind` 五选一,可带 `weight` / `tags` / `dueAt`;传 `closes` 表示「这条替代了某条旧的」 |
|
|
32
|
+
| `mcore_write` | 写一条记忆。`kind` 五选一,可带 `weight` / `tags` / `dueAt`;**`promise` 必须带 `dueAt`**,不知道时间会被拒绝并提示先问,确实没有截止时间就写 `dueAt: "none"`;传 `closes` 表示「这条替代了某条旧的」 |
|
|
33
33
|
| `mcore_recall` | 查记忆。不传 `query` 就是最近几条;传了就按内容搜,同时搜最近 7 天的对话原文和工作区笔记;`mode=open` 看没做完的承诺和今天的安排;`mode=archive` 翻更早的归档原文 |
|
|
34
34
|
| `mcore_state` | 角色自己的精力 / 心情 / 正在做什么 / 在哪 / 睡没睡 |
|
|
35
35
|
| `mcore_plan` | 今天的日程(增、勾、清空) |
|
|
@@ -55,13 +55,16 @@ pnpm add cortico-world-memory-core
|
|
|
55
55
|
| 列表 | 可排序表格(类型 / 内容 / 权重 / 来源 / 标签 / 记于 / 使用次数),权重带微条 |
|
|
56
56
|
| 原文 | 最近 7 天的对话原文,搜索高亮;更早的进 `archive/`,模型可用 `mode=archive` 翻回去 |
|
|
57
57
|
| 文件 | 工作区里被检索的 md / txt(只读) |
|
|
58
|
-
| 维护 | 重复 / 疑似作废 / 垃圾 /
|
|
58
|
+
| 维护 | 重复 / 疑似作废 / 垃圾 / **承诺** / 回收站;承诺页能补截止时间、标记做完;彻底的删除会先列出要删的东西,10 秒内可撤销 |
|
|
59
|
+
| 体检 | 在用 / 从没被召回 / 召回次数 / 原文规模、近 14 天新增、承诺与备份状态;从没被召回的卡能一键退休 |
|
|
59
60
|
|
|
60
61
|
右栏是详情:可改文本、类型、权重、标签、截止时间,能复制、看相关记忆与版本链;没有选中时收成一条 46px 的窄条,把宽度还给舞台。
|
|
61
62
|
|
|
62
|
-
快捷键:`/` 搜索 · `1–
|
|
63
|
+
快捷键:`/` 搜索 · `1–6` 切视图 · `J/K` 移动 · `Enter` 打开 · `E` 改 · `N` 新建 · `I` 右栏 · `R` 刷新 · `?` 帮助。
|
|
63
64
|
深链接:`/?view=timeline`、`/?card=<id>`。
|
|
64
65
|
|
|
66
|
+
导出与导入:`⋯` 菜单里能导出 Markdown / JSON。JSON 是整包(卡片 + 原文 + 日程 + 状态),可以原样 `POST /api/import` 导回来——**只加不覆盖**,同 id 或同类型同文本会跳过,所以重复导同一个文件是安全的。水位只往前推,不会被旧备份倒回去。
|
|
67
|
+
|
|
65
68
|
四条实现约束(改的时候别破坏):
|
|
66
69
|
|
|
67
70
|
1. 只绑 `127.0.0.1` —— 站点没有身份认证,不能对局域网露面;
|
|
@@ -89,6 +92,8 @@ pnpm add cortico-world-memory-core
|
|
|
89
92
|
| `captureBackfill` | `false` | 打开后重启一次:把水位倒回开头重扫历史消息,补录完自动停用 |
|
|
90
93
|
| `recallLimit` | `5` | 一次召回给几条 |
|
|
91
94
|
| `recallMaxChars` | `600` | 召回结果总字数上限 |
|
|
95
|
+
| `recallUseAging` | `true` | 排序参考「上次被想起的时间」:久不用的旧卡让位;关掉退回只看关键词、标签、权重 |
|
|
96
|
+
| `promiseRepeatDays` | `1` | 到期还没做的承诺隔几天再提一次,直到做完或退休;`0` = 只提醒一次 |
|
|
92
97
|
| `proactiveEnabled` | `true` | 主动开口 |
|
|
93
98
|
| `proactiveMinGapMin` / `proactiveDailyCap` | `100` / `3` | 主动间隔与每日上限 |
|
|
94
99
|
| `nightlyConsolidate` | `false` | 夜间整理(会多一次完整请求,默认关) |
|
|
@@ -101,6 +106,7 @@ pnpm add cortico-world-memory-core
|
|
|
101
106
|
```
|
|
102
107
|
data/memory-core/
|
|
103
108
|
├─ cards.jsonl 卡片(一行一张,可以直接看)
|
|
109
|
+
├─ backups/ 每天第一笔写入前自动存的副本(cards-YYYY-MM-DD.jsonl,留 7 份)
|
|
104
110
|
├─ turns.jsonl 对方最近的对话原文(按 captureSenders 过滤)
|
|
105
111
|
├─ archive/ 过期的原文按天归档(YYYY-MM-DD.jsonl),可搜可删
|
|
106
112
|
├─ plans.json 今天的日程
|
|
@@ -124,6 +130,12 @@ data/memory-core/
|
|
|
124
130
|
# 数据层:退休 / 恢复 / 改版血缘 / 重复合并 / 作废与垃圾识别
|
|
125
131
|
node --experimental-transform-types tools/test-store.ts
|
|
126
132
|
|
|
133
|
+
# 0.4.0 新增:原子写与备份轮转 / 导入去重 / 承诺提醒周期 / 体检与导入
|
|
134
|
+
node --experimental-transform-types tools/test-upgrade.ts
|
|
135
|
+
|
|
136
|
+
# 原文捕获:白名单、旧默认迁移、回放、按天归档
|
|
137
|
+
node --experimental-transform-types tools/test-capture.ts
|
|
138
|
+
|
|
127
139
|
# World 层:用假宿主真启动一次,跑写、查、closes 取代
|
|
128
140
|
node --experimental-transform-types tools/test-world.ts
|
|
129
141
|
|
package/describe.json
CHANGED
|
@@ -37,7 +37,7 @@
|
|
|
37
37
|
},
|
|
38
38
|
"dueAt": {
|
|
39
39
|
"type": "string",
|
|
40
|
-
"description": "仅 promise 用:什么时候该做,ISO
|
|
40
|
+
"description": "仅 promise 用:什么时候该做,ISO 或 YYYY-MM-DD HH:MM;确实没有截止时间就写 none"
|
|
41
41
|
},
|
|
42
42
|
"closes": {
|
|
43
43
|
"type": "string",
|
|
@@ -258,7 +258,7 @@
|
|
|
258
258
|
"key": "worlds.memory-core.envPrompt",
|
|
259
259
|
"title": "记忆核心 · 环境提示词",
|
|
260
260
|
"role": "envPrompt",
|
|
261
|
-
"content": "【记忆核心】\n\n你现在只有一套记忆:`mcore_write` 写进去,`mcore_recall` 查出来。旧的几套记忆已经并进这里,不要再提「另一个记忆系统」,也不要问对方「要记在哪」。\n\n写什么:\n- `fact` 关于对方的稳定事实(名字、作息、忌讳、正在忙的事)。\n- `self` 关于你自己的(喜欢什么、怕什么、决定过什么)。\n- `episode` 发生过的一件事,带上当时的感觉。\n- `promise`
|
|
261
|
+
"content": "【记忆核心】\n\n你现在只有一套记忆:`mcore_write` 写进去,`mcore_recall` 查出来。旧的几套记忆已经并进这里,不要再提「另一个记忆系统」,也不要问对方「要记在哪」。\n\n写什么:\n- `fact` 关于对方的稳定事实(名字、作息、忌讳、正在忙的事)。\n- `self` 关于你自己的(喜欢什么、怕什么、决定过什么)。\n- `episode` 发生过的一件事,带上当时的感觉。\n- `promise` 答应过的事,必须写 `dueAt`(不知道就先问一句;确实没有截止时间就写 `none`);做完或改了传 `closes`(查出来的行首 8 位就是 id)。\n- `note` 过几天就没用的临时信息。\n\n写法:一条一件事,40–80 字,写清楚谁、什么时候、怎么了;不要写「对方说了一些事」这种空话。同一件事不要写两遍,记不清就先查。`weight` 是这事在你心里的分量,0.3 琐事 / 0.5 一般 / 0.8 重要。\n\n查法:`mcore_recall` 不传 `query` 就是最近几条;传 `query` 搜内容,最近 7 天的对话原文和工作区里的笔记文件也会一起搜,更早的加 `mode=archive` 翻归档;`mode=open` 看没做完的承诺和今天的安排。\n什么时候查:对方提到某个人、某件事、某个日期、旧约定,或者问「你还记得吗」——先查再答,不要硬猜。\n\n你自己也有状态:`mcore_state` 管精力、心情、正在做什么、在哪、睡没睡;`mcore_plan` 管今天的安排。这两样和记忆分开放,不要写进 `mcore_write`。\n\n分寸:记忆是你记得的东西,不是拿来念的清单。可以自然地说「我记得你说过……」;不确定的就直接问,别编。"
|
|
262
262
|
}
|
|
263
263
|
]
|
|
264
264
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "cortico-world-memory-core",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.4.1",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"description": "Cortico World 长期记忆:一张卡片表 + 4 个工具 + 一段静态提示词,附状态、日程、主动开口与本地记忆地图。\n\nQQ 交流群:745879632",
|
|
6
6
|
"keywords": [
|
|
@@ -31,11 +31,11 @@
|
|
|
31
31
|
"locales": {
|
|
32
32
|
"zh": {
|
|
33
33
|
"displayName": "记忆核心",
|
|
34
|
-
"description": "一张卡片表、四个工具、一段
|
|
34
|
+
"description": "一张卡片表、四个工具、一段 750 字的静态提示词。改口不覆盖:旧卡退休、新卡记下接替了谁,召回时不会再同时看到作废的和改后的那条。附带状态、日程、主动开口,以及一个本地记忆地图(图谱 / 时间线 / 维护面板)。\n\nQQ 交流群:745879632"
|
|
35
35
|
},
|
|
36
36
|
"en": {
|
|
37
37
|
"displayName": "Memory Core",
|
|
38
|
-
"description": "One card table, four tools and a
|
|
38
|
+
"description": "One card table, four tools and a 750-character static prompt. Corrections don't overwrite: the old card is retired and the new one records what it supersedes, so a retracted plan never comes back alongside the revised one. Ships mood/energy state, today's plan, speaking first, and a local memory map with graph, timeline and a maintenance panel.\n\nQQ group: 745879632"
|
|
39
39
|
}
|
|
40
40
|
},
|
|
41
41
|
"tags": [
|
package/src/config.ts
CHANGED
|
@@ -18,7 +18,8 @@ export interface MemoryCoreConfig {
|
|
|
18
18
|
idleGateMin: number;
|
|
19
19
|
/** 只有最近这么多小时内对方说过话才主动(0 = 不限制)。 */
|
|
20
20
|
requireRecentUserHours: number;
|
|
21
|
-
/**
|
|
21
|
+
/** 承诺到期后,隔多少天可以再提醒一次(0 = 只提醒一次)。 */
|
|
22
|
+
promiseRepeatDays: number; /** 免打扰开始(含)。 */
|
|
22
23
|
quietStart: string;
|
|
23
24
|
/** 免打扰结束(不含)。 */
|
|
24
25
|
quietEnd: string;
|
|
@@ -44,6 +45,8 @@ export interface MemoryCoreConfig {
|
|
|
44
45
|
recallLimit: number;
|
|
45
46
|
/** 召回结果的总字数上限。 */
|
|
46
47
|
recallMaxChars: number;
|
|
48
|
+
/** 排序时是否参考「上次被想起的时间」:久不用的旧卡不抢新卡的位。 */
|
|
49
|
+
recallUseAging: boolean;
|
|
47
50
|
/** 每隔多少分钟把状态作为一条事件投递一次(0 = 不投递,最省)。 */
|
|
48
51
|
contextEveryMin: number;
|
|
49
52
|
/** 夜间是否唤醒一轮让角色整理记忆(会多一次完整请求)。 */
|
|
@@ -76,6 +79,7 @@ export const MEMORY_CORE_DEFAULTS: MemoryCoreConfig = {
|
|
|
76
79
|
proactiveDailyCap: 3,
|
|
77
80
|
idleGateMin: 20,
|
|
78
81
|
requireRecentUserHours: 8,
|
|
82
|
+
promiseRepeatDays: 1,
|
|
79
83
|
quietStart: '23:30',
|
|
80
84
|
quietEnd: '08:00',
|
|
81
85
|
sleepStart: '01:00',
|
|
@@ -91,6 +95,7 @@ export const MEMORY_CORE_DEFAULTS: MemoryCoreConfig = {
|
|
|
91
95
|
captureBackfill: false,
|
|
92
96
|
recallLimit: 5,
|
|
93
97
|
recallMaxChars: 600,
|
|
98
|
+
recallUseAging: true,
|
|
94
99
|
contextEveryMin: 0,
|
|
95
100
|
nightlyConsolidate: false,
|
|
96
101
|
nightlyHour: 3,
|
|
@@ -140,6 +145,7 @@ export const MEMORY_CORE_CONFIG_GROUP: ConfigGroup = {
|
|
|
140
145
|
'worlds.memory-core.proactiveDailyCap': num('每天主动上限', '每次主动都是一次完整请求,3 次约等于 30 万 token。0 = 不限。', 0, 12, '次'),
|
|
141
146
|
'worlds.memory-core.idleGateMin': num('对方刚说话后的静默', '窗口内不主动,免得打断。', 0, 240, '分钟'),
|
|
142
147
|
'worlds.memory-core.requireRecentUserHours': num('对方多久没说话就不主动', '超过这个时长就当没人在,主动会对着空房间说话、白花钱。0 = 不限制。', 0, 72, '小时'),
|
|
148
|
+
'worlds.memory-core.promiseRepeatDays': num('承诺隔几天再提一次', '到期还没做的承诺,隔这么多天再提一次,直到做完或退休。默认 1(每天最多一次);0 = 只提醒一次。', 0, 30, '天'),
|
|
143
149
|
'worlds.memory-core.quietStart': {
|
|
144
150
|
type: 'string',
|
|
145
151
|
title: '免打扰开始',
|
|
@@ -192,6 +198,11 @@ export const MEMORY_CORE_CONFIG_GROUP: ConfigGroup = {
|
|
|
192
198
|
},
|
|
193
199
|
'worlds.memory-core.recallLimit': num('一次召回给几条', '默认 5 条。给多了挤占上下文。', 1, 12, '条'),
|
|
194
200
|
'worlds.memory-core.recallMaxChars': num('召回结果字数上限', '超过就截断,默认 600 字。', 120, 2000, '字'),
|
|
201
|
+
'worlds.memory-core.recallUseAging': {
|
|
202
|
+
type: 'boolean',
|
|
203
|
+
title: '久不用的记忆让位',
|
|
204
|
+
description: '排序时参考「上次被想起的时间」:长期没被召回、权重又低的卡排到后面。关掉就退回只看关键词、标签和权重。',
|
|
205
|
+
},
|
|
195
206
|
'worlds.memory-core.contextEveryMin': num('状态投递间隔', '每隔这么多分钟把「我在做什么」推到上下文里。0 = 不推(默认,最省);推一次约 60 token,但每轮都在历史里。', 0, 240, '分钟'),
|
|
196
207
|
'worlds.memory-core.nightlyConsolidate': {
|
|
197
208
|
type: 'boolean',
|
package/src/recall.ts
CHANGED
|
@@ -59,6 +59,8 @@ export interface RankOptions {
|
|
|
59
59
|
days?: number;
|
|
60
60
|
limit: number;
|
|
61
61
|
now?: number;
|
|
62
|
+
/** 是否参考「上次被想起的时间」。关掉就退回只看关键词、标签、权重和新鲜度。 */
|
|
63
|
+
useAging?: boolean;
|
|
62
64
|
}
|
|
63
65
|
|
|
64
66
|
export function rankCards(cards: readonly Card[], opts: RankOptions): Card[] {
|
|
@@ -86,7 +88,14 @@ export function rankCards(cards: readonly Card[], opts: RankOptions): Card[] {
|
|
|
86
88
|
const tagHit = card.tags.length ? overlap(queryTokens, card.tags.join(' ')) : 0;
|
|
87
89
|
// 同一张卡被反复召回只做有限的边际压制(封顶 8 次),别让常用的重要记忆越用越沉
|
|
88
90
|
const used = Math.min(card.uses || 0, 8) * 0.03;
|
|
89
|
-
|
|
91
|
+
// 最近被想起过的卡给一点小加成:三个月没动过的旧卡不该把上周刚聊过的挤下去。
|
|
92
|
+
// 权重刻意压得很小(0.15 上限),压不倒一个关键词命中(2 分)。
|
|
93
|
+
const lastUsed = Date.parse(card.lastUsedAt ?? '');
|
|
94
|
+
const glow =
|
|
95
|
+
opts.useAging && Number.isFinite(lastUsed)
|
|
96
|
+
? 0.15 * Math.exp(-(now - lastUsed) / (30 * 86_400_000))
|
|
97
|
+
: 0;
|
|
98
|
+
const score = lexical * 2 + tagHit * 1.2 + card.weight * 0.5 + freshness(card.createdAt, now) + glow - used;
|
|
90
99
|
return { card, score };
|
|
91
100
|
});
|
|
92
101
|
scored.sort((a, b) => b.score - a.score);
|
package/src/site.ts
CHANGED
|
@@ -27,6 +27,8 @@ const MIME: Record<string, string> = {
|
|
|
27
27
|
|
|
28
28
|
const MAX_PORT_TRIES = 10;
|
|
29
29
|
const MAX_BODY = 512 * 1024;
|
|
30
|
+
/** 导入的是整包备份,比日常请求大得多。 */
|
|
31
|
+
const MAX_IMPORT = 32 * 1024 * 1024;
|
|
30
32
|
|
|
31
33
|
export interface Snapshot {
|
|
32
34
|
now: string;
|
|
@@ -58,6 +60,27 @@ export interface MaintenanceReport {
|
|
|
58
60
|
stale: string[];
|
|
59
61
|
junk: string[];
|
|
60
62
|
retired: string[];
|
|
63
|
+
/** 承诺:没写截止时间的提醒管线管不到;overdue 是已过期还没做的。 */
|
|
64
|
+
promises: { noDue: string[]; overdue: string[] };
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
export interface HealthReport {
|
|
68
|
+
generatedAt: string;
|
|
69
|
+
cards: { total: number; active: number; retired: number; dead: number };
|
|
70
|
+
recall: { calls: number; cardsTouched: number };
|
|
71
|
+
perDay: Array<{ day: string; n: number }>;
|
|
72
|
+
promises: { open: number; overdue: number; noDue: number; repeating: number };
|
|
73
|
+
raw: { lines: number; archivedDays: number; archivedLines: number };
|
|
74
|
+
backup: { count: number; latest: string | null; dir: string };
|
|
75
|
+
deadIds: string[];
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
export interface ImportReport {
|
|
79
|
+
cards: { added: number; skipped: number };
|
|
80
|
+
turns: { added: number; skipped: number };
|
|
81
|
+
plans: { added: number; skipped: number };
|
|
82
|
+
state: { watermark: number };
|
|
83
|
+
warnings: string[];
|
|
61
84
|
}
|
|
62
85
|
|
|
63
86
|
export interface SiteHooks {
|
|
@@ -73,6 +96,8 @@ export interface SiteHooks {
|
|
|
73
96
|
maintenance(): MaintenanceReport;
|
|
74
97
|
mergeCards(keepId: string, dropIds: string[]): { kept: Card | null; merged: number };
|
|
75
98
|
purgeCards(ids: string[]): number;
|
|
99
|
+
health(): HealthReport;
|
|
100
|
+
importData(payload: Record<string, unknown>): ImportReport;
|
|
76
101
|
patchState(input: Record<string, unknown>): CoreState;
|
|
77
102
|
planAction(input: Record<string, unknown>): unknown;
|
|
78
103
|
exportAll(fmt: string): { body: string; mime: string; filename: string };
|
|
@@ -197,6 +222,22 @@ export class MemorySite {
|
|
|
197
222
|
const ids = Array.isArray(body.ids) ? (body.ids as unknown[]).map((x) => String(x)) : [];
|
|
198
223
|
return this.json(rsp, 200, { removed: this.hooks.purgeCards(ids) });
|
|
199
224
|
}
|
|
225
|
+
if (path === '/api/health' && req.method === 'GET') {
|
|
226
|
+
return this.json(rsp, 200, this.hooks.health());
|
|
227
|
+
}
|
|
228
|
+
if (path === '/api/import' && req.method === 'POST') {
|
|
229
|
+
let body: Record<string, unknown>;
|
|
230
|
+
try {
|
|
231
|
+
body = await this.body(req, MAX_IMPORT);
|
|
232
|
+
} catch (err) {
|
|
233
|
+
return this.json(rsp, 400, { error: err instanceof Error ? err.message : '读不了请求体' });
|
|
234
|
+
}
|
|
235
|
+
try {
|
|
236
|
+
return this.json(rsp, 200, this.hooks.importData(body));
|
|
237
|
+
} catch (err) {
|
|
238
|
+
return this.json(rsp, 400, { error: err instanceof Error ? err.message : '导入失败' });
|
|
239
|
+
}
|
|
240
|
+
}
|
|
200
241
|
const actionMatch = /^\/api\/cards\/([\w-]{1,60})\/(retire|restore|lineage)$/.exec(path);
|
|
201
242
|
if (actionMatch) {
|
|
202
243
|
const [, id, action] = actionMatch;
|
|
@@ -274,13 +315,13 @@ export class MemorySite {
|
|
|
274
315
|
}
|
|
275
316
|
}
|
|
276
317
|
|
|
277
|
-
private readBody(req: IncomingMessage): Promise<string> {
|
|
318
|
+
private readBody(req: IncomingMessage, limit = MAX_BODY): Promise<string> {
|
|
278
319
|
return new Promise((res, rej) => {
|
|
279
320
|
let size = 0;
|
|
280
321
|
const chunks: Buffer[] = [];
|
|
281
322
|
req.on('data', (chunk: Buffer) => {
|
|
282
323
|
size += chunk.length;
|
|
283
|
-
if (size >
|
|
324
|
+
if (size > limit) {
|
|
284
325
|
rej(new Error('请求体太大'));
|
|
285
326
|
req.destroy();
|
|
286
327
|
return;
|
|
@@ -292,8 +333,8 @@ export class MemorySite {
|
|
|
292
333
|
});
|
|
293
334
|
}
|
|
294
335
|
|
|
295
|
-
private async body(req: IncomingMessage): Promise<Record<string, unknown>> {
|
|
296
|
-
const raw = await this.readBody(req);
|
|
336
|
+
private async body(req: IncomingMessage, limit = MAX_BODY): Promise<Record<string, unknown>> {
|
|
337
|
+
const raw = await this.readBody(req, limit);
|
|
297
338
|
if (!raw.trim()) return {};
|
|
298
339
|
try {
|
|
299
340
|
const parsed = JSON.parse(raw) as unknown;
|
package/src/store.ts
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
* 卡片表、对话原文、日程与状态的文件层。
|
|
3
3
|
* 只碰本插件自己的数据目录;四套旧记忆由 importer.ts 只读导入,不改原文件。
|
|
4
4
|
*/
|
|
5
|
-
import { existsSync, mkdirSync, readdirSync, readFileSync, statSync, unlinkSync, writeFileSync, appendFileSync } from 'node:fs';
|
|
5
|
+
import { copyFileSync, existsSync, mkdirSync, readdirSync, readFileSync, renameSync, statSync, unlinkSync, writeFileSync, appendFileSync } from 'node:fs';
|
|
6
6
|
import { randomUUID } from 'node:crypto';
|
|
7
7
|
import { join } from 'node:path';
|
|
8
8
|
|
|
@@ -101,14 +101,38 @@ export function readJson<T>(file: string, fallback: T): T {
|
|
|
101
101
|
}
|
|
102
102
|
}
|
|
103
103
|
|
|
104
|
-
|
|
104
|
+
/**
|
|
105
|
+
* 先写同目录的 `.tmp` 再改名覆盖。
|
|
106
|
+
* 直接 writeFileSync 覆盖的窗口里断电/被杀,原文件会变成半截或空文件——整个记忆库就这么没了。
|
|
107
|
+
* rename 在 Windows 上偶尔被杀软或索引服务锁住,失败时退回直接写,至少不丢这一次。
|
|
108
|
+
* @returns 是否落盘成功
|
|
109
|
+
*/
|
|
110
|
+
export function writeAtomic(file: string, body: string): boolean {
|
|
111
|
+
const tmp = `${file}.tmp`;
|
|
105
112
|
try {
|
|
106
|
-
writeFileSync(
|
|
113
|
+
writeFileSync(tmp, body, 'utf8');
|
|
114
|
+
renameSync(tmp, file);
|
|
115
|
+
return true;
|
|
107
116
|
} catch {
|
|
108
|
-
|
|
117
|
+
try {
|
|
118
|
+
writeFileSync(file, body, 'utf8');
|
|
119
|
+
return true;
|
|
120
|
+
} catch {
|
|
121
|
+
return false;
|
|
122
|
+
} finally {
|
|
123
|
+
try {
|
|
124
|
+
unlinkSync(tmp);
|
|
125
|
+
} catch {
|
|
126
|
+
// 没有残留就算了
|
|
127
|
+
}
|
|
128
|
+
}
|
|
109
129
|
}
|
|
110
130
|
}
|
|
111
131
|
|
|
132
|
+
export function writeJson(file: string, value: unknown): void {
|
|
133
|
+
writeAtomic(file, JSON.stringify(value, null, 2));
|
|
134
|
+
}
|
|
135
|
+
|
|
112
136
|
/** 规范化文本,用于判重:去掉标点空白与日期,只留内容。 */
|
|
113
137
|
export function normalizeText(text: string): string {
|
|
114
138
|
return String(text ?? '')
|
|
@@ -124,11 +148,15 @@ function clamp01(n: number): number {
|
|
|
124
148
|
export class CardStore {
|
|
125
149
|
private cards: Card[] = [];
|
|
126
150
|
private readonly file: string;
|
|
151
|
+
private readonly backupDir: string;
|
|
152
|
+
/** 今天是否已经备过份。同一天只备一次,避免每次 save 都复制。 */
|
|
153
|
+
private backupDay = '';
|
|
127
154
|
private dirty = false;
|
|
128
155
|
|
|
129
156
|
constructor(dir: string) {
|
|
130
157
|
ensureDir(dir);
|
|
131
158
|
this.file = join(dir, 'cards.jsonl');
|
|
159
|
+
this.backupDir = join(dir, 'backups');
|
|
132
160
|
this.load();
|
|
133
161
|
}
|
|
134
162
|
|
|
@@ -500,15 +528,90 @@ export class CardStore {
|
|
|
500
528
|
.slice(0, Math.max(0, limit));
|
|
501
529
|
}
|
|
502
530
|
|
|
503
|
-
|
|
531
|
+
/**
|
|
532
|
+
* 到点该提的承诺。
|
|
533
|
+
* repeatDays = 0 时和旧版一致:提醒过一次就永久沉默。
|
|
534
|
+
* repeatDays > 0 时,距上次提醒够这么多天就再提一次(「每天发一条」这种周期承诺靠它)。
|
|
535
|
+
*/
|
|
536
|
+
duePromises(now = Date.now(), repeatDays = 0): Card[] {
|
|
504
537
|
const at = now;
|
|
538
|
+
const gap = Math.max(0, Number(repeatDays) || 0) * 86_400_000;
|
|
505
539
|
return this.cards.filter((c) => {
|
|
506
540
|
if (c.kind !== 'promise' || c.done || c.status === 'retired' || !c.dueAt) return false;
|
|
507
541
|
const due = Date.parse(c.dueAt);
|
|
508
|
-
|
|
542
|
+
if (!Number.isFinite(due) || due > at) return false;
|
|
543
|
+
if (!c.remindedAt) return true;
|
|
544
|
+
if (gap <= 0) return false;
|
|
545
|
+
const last = Date.parse(c.remindedAt);
|
|
546
|
+
return !Number.isFinite(last) || at - last >= gap;
|
|
509
547
|
});
|
|
510
548
|
}
|
|
511
549
|
|
|
550
|
+
/** 没有截止时间的承诺:提醒管线对它们完全无效,界面上要单独列出来让人补。 */
|
|
551
|
+
promisesWithoutDue(): Card[] {
|
|
552
|
+
return this.cards
|
|
553
|
+
.filter((c) => c.kind === 'promise' && !c.done && c.status !== 'retired' && !c.dueAt)
|
|
554
|
+
.sort((a, b) => b.createdAt.localeCompare(a.createdAt));
|
|
555
|
+
}
|
|
556
|
+
|
|
557
|
+
/**
|
|
558
|
+
* 从备份里灌卡片。同 id 或「同类型 + 同文本」已经存在就跳过,绝不覆盖现有内容——
|
|
559
|
+
* 导入是恢复,不是覆盖。返回加了几条、跳了几条。
|
|
560
|
+
*/
|
|
561
|
+
importCards(input: readonly unknown[]): { added: number; skipped: number } {
|
|
562
|
+
let added = 0;
|
|
563
|
+
let skipped = 0;
|
|
564
|
+
const byId = new Set(this.cards.map((c) => c.id));
|
|
565
|
+
const byKey = new Set(this.cards.map((c) => `${c.kind}\u0000${normalizeText(c.text)}`));
|
|
566
|
+
for (const raw of input) {
|
|
567
|
+
const c = (raw ?? {}) as Partial<Card>;
|
|
568
|
+
if (typeof c.text !== 'string' || !c.text.trim()) {
|
|
569
|
+
skipped += 1;
|
|
570
|
+
continue;
|
|
571
|
+
}
|
|
572
|
+
const kind = CARD_KINDS.includes(c.kind as CardKind) ? (c.kind as CardKind) : 'fact';
|
|
573
|
+
const text = c.text.replace(/\s+/g, ' ').trim().slice(0, 500);
|
|
574
|
+
const key = `${kind}\u0000${normalizeText(text)}`;
|
|
575
|
+
const id = typeof c.id === 'string' && /^[\w-]{1,60}$/.test(c.id) ? c.id : randomUUID();
|
|
576
|
+
if (byId.has(id) || byKey.has(key)) {
|
|
577
|
+
skipped += 1;
|
|
578
|
+
continue;
|
|
579
|
+
}
|
|
580
|
+
const now = new Date().toISOString();
|
|
581
|
+
const card: Card = {
|
|
582
|
+
id,
|
|
583
|
+
kind,
|
|
584
|
+
text,
|
|
585
|
+
weight: clamp01(Number(c.weight ?? 0.5)),
|
|
586
|
+
tags: Array.isArray(c.tags) ? (c.tags as unknown[]).map((t) => String(t).slice(0, 20)).slice(0, 6) : [],
|
|
587
|
+
createdAt: typeof c.createdAt === 'string' && c.createdAt ? c.createdAt : now,
|
|
588
|
+
updatedAt: typeof c.updatedAt === 'string' && c.updatedAt ? c.updatedAt : now,
|
|
589
|
+
// 恢复要尽量还原原样:来源、作用域能带就带,别一律改成 import:backup
|
|
590
|
+
source: typeof c.source === 'string' && c.source ? c.source.slice(0, 40) : 'import:backup',
|
|
591
|
+
origin: 'import',
|
|
592
|
+
uses: Math.max(0, Math.floor(Number(c.uses ?? 0)) || 0),
|
|
593
|
+
lastUsedAt: typeof c.lastUsedAt === 'string' ? c.lastUsedAt : undefined,
|
|
594
|
+
dueAt: typeof c.dueAt === 'string' ? c.dueAt : undefined,
|
|
595
|
+
done: c.done === true ? true : undefined,
|
|
596
|
+
remindedAt: typeof c.remindedAt === 'string' ? c.remindedAt : undefined,
|
|
597
|
+
status: c.status === 'retired' ? 'retired' : 'active',
|
|
598
|
+
retiredAt: typeof c.retiredAt === 'string' ? c.retiredAt : undefined,
|
|
599
|
+
retiredBy: typeof c.retiredBy === 'string' ? c.retiredBy : undefined,
|
|
600
|
+
supersedes: Array.isArray(c.supersedes) ? (c.supersedes as unknown[]).map((x) => String(x)).slice(0, 20) : undefined,
|
|
601
|
+
scope: typeof c.scope === 'string' && c.scope ? c.scope.slice(0, 20) : 'import',
|
|
602
|
+
};
|
|
603
|
+
this.cards.push(card);
|
|
604
|
+
byId.add(id);
|
|
605
|
+
byKey.add(key);
|
|
606
|
+
added += 1;
|
|
607
|
+
}
|
|
608
|
+
if (added) {
|
|
609
|
+
this.dirty = true;
|
|
610
|
+
this.save(true);
|
|
611
|
+
}
|
|
612
|
+
return { added, skipped };
|
|
613
|
+
}
|
|
614
|
+
|
|
512
615
|
reset(): void {
|
|
513
616
|
this.cards = [];
|
|
514
617
|
this.dirty = true;
|
|
@@ -518,13 +621,52 @@ export class CardStore {
|
|
|
518
621
|
save(force = false): void {
|
|
519
622
|
if (!this.dirty && !force) return;
|
|
520
623
|
this.dirty = false;
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
} catch {
|
|
624
|
+
this.backupOnceADay();
|
|
625
|
+
if (!writeAtomic(this.file, this.cards.map((c) => JSON.stringify(c)).join('\n') + '\n')) {
|
|
524
626
|
// 落盘失败下一拍再来
|
|
525
627
|
this.dirty = true;
|
|
526
628
|
}
|
|
527
629
|
}
|
|
630
|
+
|
|
631
|
+
/**
|
|
632
|
+
* 每天第一次写之前,把当前文件复制一份到 backups/cards-YYYY-MM-DD.jsonl,只留最近 7 份。
|
|
633
|
+
* 顺序很重要:先备份、再覆盖,这样备份里至少有一份「改动前」的完整文件。
|
|
634
|
+
*/
|
|
635
|
+
private backupOnceADay(): void {
|
|
636
|
+
try {
|
|
637
|
+
const d = new Date();
|
|
638
|
+
const day = `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`;
|
|
639
|
+
if (this.backupDay === day) return;
|
|
640
|
+
// 文件还不存在时先不标记,等第一次写出来之后再补备份
|
|
641
|
+
if (!existsSync(this.file)) return;
|
|
642
|
+
ensureDir(this.backupDir);
|
|
643
|
+
copyFileSync(this.file, join(this.backupDir, `cards-${day}.jsonl`));
|
|
644
|
+
this.backupDay = day;
|
|
645
|
+
const old = readdirSync(this.backupDir)
|
|
646
|
+
.filter((f) => /^cards-\d{4}-\d{2}-\d{2}\.jsonl$/.test(f))
|
|
647
|
+
.sort();
|
|
648
|
+
for (const f of old.slice(0, Math.max(0, old.length - 7))) {
|
|
649
|
+
try {
|
|
650
|
+
unlinkSync(join(this.backupDir, f));
|
|
651
|
+
} catch {
|
|
652
|
+
// 删不掉就留着,不影响
|
|
653
|
+
}
|
|
654
|
+
}
|
|
655
|
+
} catch {
|
|
656
|
+
// 备份失败不阻断写入
|
|
657
|
+
}
|
|
658
|
+
}
|
|
659
|
+
|
|
660
|
+
/** 备份现状,健康面板用。 */
|
|
661
|
+
backupInfo(): { dir: string; count: number; latest: string | null } {
|
|
662
|
+
try {
|
|
663
|
+
if (!existsSync(this.backupDir)) return { dir: this.backupDir, count: 0, latest: null };
|
|
664
|
+
const files = readdirSync(this.backupDir).filter((f) => /^cards-\d{4}-\d{2}-\d{2}\.jsonl$/.test(f)).sort();
|
|
665
|
+
return { dir: this.backupDir, count: files.length, latest: files.at(-1) ?? null };
|
|
666
|
+
} catch {
|
|
667
|
+
return { dir: this.backupDir, count: 0, latest: null };
|
|
668
|
+
}
|
|
669
|
+
}
|
|
528
670
|
}
|
|
529
671
|
|
|
530
672
|
const DAY_FMT = new Intl.DateTimeFormat('sv-SE', { year: 'numeric', month: '2-digit', day: '2-digit' });
|
|
@@ -667,6 +809,19 @@ export class RawLog {
|
|
|
667
809
|
return { days: files.length, bytes, oldest: files[0]?.day ?? '' };
|
|
668
810
|
}
|
|
669
811
|
|
|
812
|
+
/** 归档总行数。健康面板按需调用,不进热路径。 */
|
|
813
|
+
archiveLines(): number {
|
|
814
|
+
let n = 0;
|
|
815
|
+
for (const f of this.archiveFiles()) {
|
|
816
|
+
try {
|
|
817
|
+
n += readFileSync(f.file, 'utf8').split('\n').filter((line) => line.trim()).length;
|
|
818
|
+
} catch {
|
|
819
|
+
// 读不了就跳过
|
|
820
|
+
}
|
|
821
|
+
}
|
|
822
|
+
return n;
|
|
823
|
+
}
|
|
824
|
+
|
|
670
825
|
/** 翻归档:默认最近 30 天,最多 8000 行。只给 mode=archive 用,不进常规召回。 */
|
|
671
826
|
readArchive(days = 30, maxEntries = 8000): RawEntry[] {
|
|
672
827
|
const span = Math.max(1, Math.min(365, Number(days) || 30));
|
|
@@ -694,11 +849,7 @@ export class RawLog {
|
|
|
694
849
|
}
|
|
695
850
|
|
|
696
851
|
private rewrite(): void {
|
|
697
|
-
|
|
698
|
-
writeFileSync(this.file, this.entries.map((e) => JSON.stringify(e)).join('\n') + '\n', 'utf8');
|
|
699
|
-
} catch {
|
|
700
|
-
// ignore
|
|
701
|
-
}
|
|
852
|
+
writeAtomic(this.file, this.entries.map((e) => JSON.stringify(e)).join('\n') + '\n');
|
|
702
853
|
}
|
|
703
854
|
|
|
704
855
|
get size(): number {
|
package/src/tools.ts
CHANGED
|
@@ -35,7 +35,7 @@ export const TOOL_SPECS: ToolSpec[] = [
|
|
|
35
35
|
tags: { type: 'array', items: { type: 'string' }, description: '关键词,最多 6 个' },
|
|
36
36
|
dueAt: {
|
|
37
37
|
type: 'string',
|
|
38
|
-
description: '仅 promise 用:什么时候该做,ISO
|
|
38
|
+
description: '仅 promise 用:什么时候该做,ISO 或 YYYY-MM-DD HH:MM;确实没有截止时间就写 none',
|
|
39
39
|
},
|
|
40
40
|
closes: { type: 'string', description: '要关掉的旧记录 id(已完成/已失效)' },
|
|
41
41
|
},
|