cortico-world-memory-core 0.4.3 → 0.12.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 +118 -0
- package/ENV_PROMPT.md +15 -19
- package/README.md +181 -157
- package/describe.json +30 -53
- package/package.json +7 -4
- package/src/config.ts +266 -258
- package/src/recall.ts +215 -114
- package/src/site.ts +65 -7
- package/src/store.ts +115 -0
- package/src/tools.ts +88 -114
- package/src/world.ts +1456 -1199
- package/webui/app.js +3300 -2380
- package/webui/index.html +120 -104
- package/webui/style.css +814 -735
package/src/recall.ts
CHANGED
|
@@ -1,114 +1,215 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* 检索:纯本地词法打分,不调模型、不花 token。
|
|
3
|
-
* 中文按二元组 + 单字、英文数字按词切;分数 = 命中 + 权重 + 新鲜度 - 反复使用惩罚。
|
|
4
|
-
*/
|
|
5
|
-
import type { Card, RawEntry } from './store.ts';
|
|
6
|
-
|
|
7
|
-
const STOP = new Set(
|
|
8
|
-
'的了是在我你他她它和就都也不吗呢啊吧有会要说过这个那个把被给对说着地得然后还又很太吗嘛哦呀'.split(''),
|
|
9
|
-
);
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
}
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
}
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
1
|
+
/**
|
|
2
|
+
* 检索:纯本地词法打分,不调模型、不花 token。
|
|
3
|
+
* 中文按二元组 + 单字、英文数字按词切;分数 = 命中 + 权重 + 新鲜度 - 反复使用惩罚。
|
|
4
|
+
*/
|
|
5
|
+
import type { Card, RawEntry } from './store.ts';
|
|
6
|
+
|
|
7
|
+
const STOP = new Set(
|
|
8
|
+
'的了是在我你他她它和就都也不吗呢啊吧有会要说过这个那个把被给对说着地得然后还又很太吗嘛哦呀'.split(''),
|
|
9
|
+
);
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* 预激活专用:这些双字词在对话里到处都是,命中它们不代表「说到同一件事」。
|
|
13
|
+
* 不在这里挡,「今天好累」会把一堆不相干的卡推上来。
|
|
14
|
+
* 只影响 minBigrams 的计数,不影响普通召回打分。
|
|
15
|
+
*/
|
|
16
|
+
const PRIME_STOP = new Set(
|
|
17
|
+
('今天 明天 昨天 后天 晚上 中午 早上 上午 下午 夜里 现在 刚才 刚刚 回来 回去 出来 起来 一下 一点 一起 '
|
|
18
|
+
+ '时候 然后 真的 可以 什么 怎么 觉得 应该 已经 还是 就是 因为 所以 但是 如果 不过 而且 '
|
|
19
|
+
+ '你们 我们 他们 自己 东西 事情 一个 有点 不是 没有 知道 看到 说过 感觉 需要 之前 之后').split(' '),
|
|
20
|
+
);
|
|
21
|
+
|
|
22
|
+
/** 预激活只认「实词」:含有虚词的二元组(不是/不能/来了/的号)一律不算线索。 */
|
|
23
|
+
export function isContentToken(token: string): boolean {
|
|
24
|
+
if (token.length < 2) return false;
|
|
25
|
+
if (PRIME_STOP.has(token)) return false;
|
|
26
|
+
for (const ch of token) if (STOP.has(ch)) return false;
|
|
27
|
+
return true;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export function tokenize(text: string): string[] {
|
|
31
|
+
const norm = String(text ?? '')
|
|
32
|
+
.toLowerCase()
|
|
33
|
+
.replace(/[^\p{L}\p{N}]+/gu, ' ')
|
|
34
|
+
.trim();
|
|
35
|
+
if (!norm) return [];
|
|
36
|
+
const out: string[] = [];
|
|
37
|
+
for (const word of norm.split(/\s+/)) {
|
|
38
|
+
if (!word) continue;
|
|
39
|
+
if (/^[a-z0-9]+$/.test(word)) {
|
|
40
|
+
out.push(word);
|
|
41
|
+
continue;
|
|
42
|
+
}
|
|
43
|
+
for (let i = 0; i < word.length; i += 1) {
|
|
44
|
+
const ch = word[i];
|
|
45
|
+
if (!STOP.has(ch)) out.push(ch);
|
|
46
|
+
if (i + 1 < word.length) out.push(word.slice(i, i + 2));
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
return out;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/** 供工作区文件检索复用:同一套切词与命中打分。 */
|
|
53
|
+
export function scoreText(queryTokens: readonly string[], text: string): number {
|
|
54
|
+
return overlap(queryTokens, text);
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
function overlap(queryTokens: readonly string[], text: string): number {
|
|
58
|
+
if (!queryTokens.length) return 0;
|
|
59
|
+
const hay = String(text ?? '').toLowerCase();
|
|
60
|
+
let sum = 0;
|
|
61
|
+
for (const token of new Set(queryTokens)) {
|
|
62
|
+
if (!hay.includes(token)) continue;
|
|
63
|
+
sum += token.length > 1 ? 1.4 : 0.18;
|
|
64
|
+
}
|
|
65
|
+
return sum / Math.sqrt(new Set(queryTokens).size + 1);
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
function freshness(iso: string | undefined, now: number): number {
|
|
69
|
+
const at = Date.parse(iso ?? '');
|
|
70
|
+
if (!Number.isFinite(at)) return 0;
|
|
71
|
+
const days = Math.max(0, (now - at) / 86_400_000);
|
|
72
|
+
return 1.1 * Math.exp(-days / 45);
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
export interface RankOptions {
|
|
76
|
+
query?: string;
|
|
77
|
+
kind?: string;
|
|
78
|
+
days?: number;
|
|
79
|
+
limit: number;
|
|
80
|
+
now?: number;
|
|
81
|
+
/** 是否参考「上次被想起的时间」。关掉就退回只看关键词、标签、权重和新鲜度。 */
|
|
82
|
+
useAging?: boolean;
|
|
83
|
+
/**
|
|
84
|
+
* 只保留真的被线索命中的卡(关键词或标签重叠 > 0)。
|
|
85
|
+
* 每轮预激活必须开这个:否则一张高权重的无关卡会靠 weight 混进「想起来了」。
|
|
86
|
+
*/
|
|
87
|
+
requireHit?: boolean;
|
|
88
|
+
/**
|
|
89
|
+
* 至少命中几个「双字以上」的词。中文单字太容易撞(今/天/好),
|
|
90
|
+
* 只靠 requireHit 的话「今天好累」能把半库都捞上来。
|
|
91
|
+
*/
|
|
92
|
+
minBigrams?: number;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
export interface ScoredCard {
|
|
96
|
+
card: Card;
|
|
97
|
+
score: number;
|
|
98
|
+
/** 词面重叠(归一化后) */
|
|
99
|
+
lexical: number;
|
|
100
|
+
/** 标签命中 */
|
|
101
|
+
tagHit: number;
|
|
102
|
+
/** 命中了几个「实词二元组」——比分数更好解释「像不像」 */
|
|
103
|
+
bigrams: number;
|
|
104
|
+
/** strong = 真的对上了,weak = 只是靠权重/新鲜度浮上来的 */
|
|
105
|
+
tier: 'strong' | 'weak';
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/**
|
|
109
|
+
* 和 rankCards 同一套打分,但把分数和判断依据一起返回。
|
|
110
|
+
* 召回要分两档口气,就靠这里的 tier,不在外面重新算一遍。
|
|
111
|
+
*/
|
|
112
|
+
export function rankCardsScored(cards: readonly Card[], opts: RankOptions): ScoredCard[] {
|
|
113
|
+
const now = opts.now ?? Date.now();
|
|
114
|
+
const queryTokens = tokenize(opts.query ?? '');
|
|
115
|
+
let pool = cards.filter((c) => {
|
|
116
|
+
if (opts.kind && c.kind !== opts.kind) return false;
|
|
117
|
+
if (opts.days && opts.days > 0) {
|
|
118
|
+
const at = Date.parse(c.createdAt);
|
|
119
|
+
if (Number.isFinite(at) && now - at > opts.days * 86_400_000) return false;
|
|
120
|
+
}
|
|
121
|
+
return true;
|
|
122
|
+
});
|
|
123
|
+
if (!queryTokens.length) {
|
|
124
|
+
pool = [...pool].sort((a, b) => {
|
|
125
|
+
const sa = freshness(a.createdAt, now) + a.weight * 0.6;
|
|
126
|
+
const sb = freshness(b.createdAt, now) + b.weight * 0.6;
|
|
127
|
+
return sb - sa;
|
|
128
|
+
});
|
|
129
|
+
return pool.slice(0, opts.limit).map((card) => ({
|
|
130
|
+
card,
|
|
131
|
+
score: 0,
|
|
132
|
+
lexical: 0,
|
|
133
|
+
tagHit: 0,
|
|
134
|
+
bigrams: 0,
|
|
135
|
+
tier: 'strong' as const,
|
|
136
|
+
}));
|
|
137
|
+
}
|
|
138
|
+
// 「今天」「回来」这类词到处都是,命中它们不算线索。文档频率只能挡掉极端常见的,
|
|
139
|
+
// 挡不住「今天」(5/66)这种——所以再加一张停用词表。
|
|
140
|
+
const common = new Set<string>();
|
|
141
|
+
if (opts.minBigrams) {
|
|
142
|
+
const cap = Math.max(3, Math.ceil(pool.length * 0.3));
|
|
143
|
+
for (const token of new Set(queryTokens)) {
|
|
144
|
+
if (token.length < 2) continue;
|
|
145
|
+
let n = 0;
|
|
146
|
+
for (const c of pool) {
|
|
147
|
+
if (`${c.text} ${c.tags.join(' ')}`.toLowerCase().includes(token)) {
|
|
148
|
+
n += 1;
|
|
149
|
+
if (n > cap) break;
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
if (n > cap) common.add(token);
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
// 标签也过一遍 IDF:出现在三成以上卡里的标签(「日常」「工作」)不该算命中
|
|
156
|
+
const commonTag = new Set<string>();
|
|
157
|
+
{
|
|
158
|
+
const cap = Math.max(3, Math.ceil(pool.length * 0.3));
|
|
159
|
+
const df = new Map<string, number>();
|
|
160
|
+
for (const c of pool) for (const t of c.tags ?? []) df.set(t, (df.get(t) ?? 0) + 1);
|
|
161
|
+
for (const [tag, n] of df) if (n > cap) commonTag.add(tag);
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
const scored = pool.map((card) => {
|
|
165
|
+
const lexical = overlap(queryTokens, card.text);
|
|
166
|
+
// 标签单独算一次:对方说「生日」时,打了 #生日 的卡要比正文里顺嘴提到的排得靠前。
|
|
167
|
+
// 但泛标签会把所有卡都拉高,所以先剔掉「到处都是」的那些。
|
|
168
|
+
const weakTags = card.tags.filter((t) => !commonTag.has(t));
|
|
169
|
+
const tagHit = weakTags.length ? overlap(queryTokens, weakTags.join(' ')) : 0;
|
|
170
|
+
// 同一张卡被反复召回只做有限的边际压制(封顶 8 次),别让常用的重要记忆越用越沉
|
|
171
|
+
const used = Math.min(card.uses || 0, 8) * 0.03;
|
|
172
|
+
// 最近被想起过的卡给一点小加成:三个月没动过的旧卡不该把上周刚聊过的挤下去。
|
|
173
|
+
// 权重刻意压得很小(0.15 上限),压不倒一个关键词命中(2 分)。
|
|
174
|
+
const lastUsed = Date.parse(card.lastUsedAt ?? '');
|
|
175
|
+
const glow =
|
|
176
|
+
opts.useAging && Number.isFinite(lastUsed)
|
|
177
|
+
? 0.15 * Math.exp(-(now - lastUsed) / (30 * 86_400_000))
|
|
178
|
+
: 0;
|
|
179
|
+
const score = lexical * 2 + tagHit * 1.2 + card.weight * 0.5 + freshness(card.createdAt, now) + glow - used;
|
|
180
|
+
// 双字以上的命中数:预激活用它挡单字噪音
|
|
181
|
+
const hay = `${card.text} ${card.tags.join(' ')}`.toLowerCase();
|
|
182
|
+
let bigrams = 0;
|
|
183
|
+
for (const token of new Set(queryTokens)) {
|
|
184
|
+
if (isContentToken(token) && !common.has(token) && hay.includes(token)) bigrams += 1;
|
|
185
|
+
}
|
|
186
|
+
return { card, score, lexical, tagHit, hit: lexical > 0 || tagHit > 0, bigrams };
|
|
187
|
+
});
|
|
188
|
+
scored.sort((a, b) => b.score - a.score);
|
|
189
|
+
return scored
|
|
190
|
+
.filter((x) => x.score > 0.25 && (!opts.requireHit || x.hit) && (!opts.minBigrams || x.bigrams >= opts.minBigrams))
|
|
191
|
+
.slice(0, opts.limit)
|
|
192
|
+
.map((x) => ({
|
|
193
|
+
...x,
|
|
194
|
+
// 两个实词对上、或一个实词且词面确实重合,才算「对得上」;
|
|
195
|
+
// 只靠权重和新鲜度浮上来的,一律算「可能沾边」。
|
|
196
|
+
tier: (x.bigrams >= 2 || (x.bigrams >= 1 && x.lexical >= 0.45) || x.tagHit >= 0.6 || x.lexical >= 1.2
|
|
197
|
+
? 'strong'
|
|
198
|
+
: 'weak') as 'strong' | 'weak',
|
|
199
|
+
}));
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
export function rankCards(cards: readonly Card[], opts: RankOptions): Card[] {
|
|
203
|
+
return rankCardsScored(cards, opts).map((x) => x.card);
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
export function rankRaw(entries: readonly RawEntry[], query: string, limit: number): RawEntry[] {
|
|
207
|
+
const queryTokens = tokenize(query);
|
|
208
|
+
if (!queryTokens.length) return [];
|
|
209
|
+
const scored = entries.map((entry) => ({
|
|
210
|
+
entry,
|
|
211
|
+
score: overlap(queryTokens, entry.text) * 2 + freshness(entry.ts, Date.now()) * 0.4,
|
|
212
|
+
}));
|
|
213
|
+
scored.sort((a, b) => b.score - a.score);
|
|
214
|
+
return scored.filter((x) => x.score > 0.8).slice(0, limit).map((x) => x.entry);
|
|
215
|
+
}
|
package/src/site.ts
CHANGED
|
@@ -1,14 +1,17 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* 记忆地图的本地站点:一个只绑 127.0.0.1 的小 HTTP 服务。
|
|
3
3
|
*
|
|
4
|
-
*
|
|
5
|
-
* 1) **只绑 127.0.0.1** ——
|
|
6
|
-
* 2)
|
|
7
|
-
* 3)
|
|
4
|
+
* 六条约束(改的时候别破坏):
|
|
5
|
+
* 1) **只绑 127.0.0.1** —— 站点不对局域网露面;
|
|
6
|
+
* 2) **只认 127.0.0.1 / localhost 这两个 Host** —— 别人把域名解析到本机(DNS 重绑定)也进不来;
|
|
7
|
+
* 3) **写接口必须带页面注入的一次性令牌** —— 别的网页能打 localhost,但拿不到这个令牌;
|
|
8
|
+
* 4) 端口被占就 +1 重试,起不来不算致命,只少一个链接;
|
|
9
|
+
* 5) 写操作走**插件内存里的同一份 store**,不直接改文件 ——
|
|
8
10
|
* 否则宿主下一次 save() 会用内存状态把文件覆盖回去;
|
|
9
|
-
*
|
|
11
|
+
* 6) 读文件接口只允许在已扫描的目录内,防目录穿越。
|
|
10
12
|
*/
|
|
11
13
|
import { createServer, type IncomingMessage, type Server, type ServerResponse } from 'node:http';
|
|
14
|
+
import { randomBytes, timingSafeEqual } from 'node:crypto';
|
|
12
15
|
import { existsSync, readFileSync, statSync } from 'node:fs';
|
|
13
16
|
import { extname, join, normalize, resolve, sep } from 'node:path';
|
|
14
17
|
import type { Card, CoreState, PlanItem, RawEntry } from './store.ts';
|
|
@@ -67,12 +70,15 @@ export interface MaintenanceReport {
|
|
|
67
70
|
export interface HealthReport {
|
|
68
71
|
generatedAt: string;
|
|
69
72
|
cards: { total: number; active: number; retired: number; dead: number };
|
|
70
|
-
recall: { calls: number; cardsTouched: number };
|
|
73
|
+
recall: { calls: number; cardsTouched: number; primed: number };
|
|
71
74
|
perDay: Array<{ day: string; n: number }>;
|
|
72
75
|
promises: { open: number; overdue: number; noDue: number; repeating: number };
|
|
73
76
|
raw: { lines: number; archivedDays: number; archivedLines: number };
|
|
74
77
|
backup: { count: number; latest: string | null; dir: string };
|
|
78
|
+
/** 冷层:沉下去多少、还能再沉多少、门槛多少天。 */
|
|
79
|
+
chill: { cold: number; eligible: number; afterDays: number };
|
|
75
80
|
deadIds: string[];
|
|
81
|
+
coldIds: string[];
|
|
76
82
|
}
|
|
77
83
|
|
|
78
84
|
export interface ImportReport {
|
|
@@ -102,6 +108,9 @@ export interface SiteHooks {
|
|
|
102
108
|
archiveSearch(q: string, days: number, limit: number): RawEntry[];
|
|
103
109
|
/** 删掉一条原文(热数据或归档)。 */
|
|
104
110
|
deleteTurn(cursor: number): boolean;
|
|
111
|
+
/** 把记忆沉到冷层 / 从冷层捞回来。 */
|
|
112
|
+
chillCards(ids: string[]): number;
|
|
113
|
+
warmCards(ids: string[]): number;
|
|
105
114
|
patchState(input: Record<string, unknown>): CoreState;
|
|
106
115
|
planAction(input: Record<string, unknown>): unknown;
|
|
107
116
|
exportAll(fmt: string): { body: string; mime: string; filename: string };
|
|
@@ -112,6 +121,8 @@ export class MemorySite {
|
|
|
112
121
|
private port: number | null = null;
|
|
113
122
|
private readonly basePort: number;
|
|
114
123
|
private readonly webDir: string;
|
|
124
|
+
/** 进程级一次性令牌:只有这个站点发出的页面才知道,别的网页拿不到。 */
|
|
125
|
+
private readonly token = randomBytes(18).toString('base64url');
|
|
115
126
|
|
|
116
127
|
constructor(private readonly hooks: SiteHooks, webDir: string, port: number) {
|
|
117
128
|
this.webDir = resolve(webDir);
|
|
@@ -174,6 +185,9 @@ export class MemorySite {
|
|
|
174
185
|
const url = new URL(req.url ?? '/', 'http://127.0.0.1');
|
|
175
186
|
const path = url.pathname;
|
|
176
187
|
|
|
188
|
+
// 只认本机这两个 Host:域名解析到 127.0.0.1(DNS 重绑定)会在这一步被挡掉
|
|
189
|
+
if (!this.hostOk(req)) return this.json(rsp, 403, { error: '只能通过 127.0.0.1 或 localhost 打开' });
|
|
190
|
+
|
|
177
191
|
if (path.startsWith('/api/')) return this.api(req, rsp, url, path);
|
|
178
192
|
|
|
179
193
|
// 无域名、无认证:只服务本机,禁止被 iframe 之外的地方引用
|
|
@@ -182,7 +196,29 @@ export class MemorySite {
|
|
|
182
196
|
return this.sendFile(rsp, file);
|
|
183
197
|
}
|
|
184
198
|
|
|
199
|
+
private hostOk(req: IncomingMessage): boolean {
|
|
200
|
+
const host = String(req.headers.host ?? '').toLowerCase();
|
|
201
|
+
const port = this.port ?? this.basePort;
|
|
202
|
+
return host === `127.0.0.1:${port}` || host === `localhost:${port}`;
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
/** 定长比较,别用 === 给出计时侧信道。 */
|
|
206
|
+
private tokenOk(req: IncomingMessage): boolean {
|
|
207
|
+
const got = String(req.headers['x-mcore-token'] ?? '');
|
|
208
|
+
if (got.length !== this.token.length) return false;
|
|
209
|
+
try {
|
|
210
|
+
return timingSafeEqual(Buffer.from(got), Buffer.from(this.token));
|
|
211
|
+
} catch {
|
|
212
|
+
return false;
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
|
|
185
216
|
private async api(req: IncomingMessage, rsp: ServerResponse, url: URL, path: string): Promise<void> {
|
|
217
|
+
// GET/HEAD 是只读,随便看(跨站也读不到内容,因为没有 CORS 头);
|
|
218
|
+
// 其余方法一律要令牌——跨站页面能打到这里,但发不出这个头。
|
|
219
|
+
if (req.method !== 'GET' && req.method !== 'HEAD' && !this.tokenOk(req)) {
|
|
220
|
+
return this.json(rsp, 403, { error: '写操作需要页面上带过来的一次性令牌,刷新一下页面' });
|
|
221
|
+
}
|
|
186
222
|
if (path === '/api/snapshot' && req.method === 'GET') {
|
|
187
223
|
return this.json(rsp, 200, this.hooks.snapshot());
|
|
188
224
|
}
|
|
@@ -226,6 +262,14 @@ export class MemorySite {
|
|
|
226
262
|
const ids = Array.isArray(body.ids) ? (body.ids as unknown[]).map((x) => String(x)) : [];
|
|
227
263
|
return this.json(rsp, 200, { removed: this.hooks.purgeCards(ids) });
|
|
228
264
|
}
|
|
265
|
+
if (path === '/api/chill' || path === '/api/warm') {
|
|
266
|
+
if (req.method !== 'POST') return this.text(rsp, 405, 'method not allowed');
|
|
267
|
+
const body = await this.body(req);
|
|
268
|
+
const ids = Array.isArray(body.ids) ? (body.ids as unknown[]).map((x) => String(x)) : [];
|
|
269
|
+
// 不带 ids 就是「全部符合条件的」:冷层一键沉、一键回暖
|
|
270
|
+
const n = path === '/api/chill' ? this.hooks.chillCards(ids) : this.hooks.warmCards(ids);
|
|
271
|
+
return this.json(rsp, 200, { changed: n });
|
|
272
|
+
}
|
|
229
273
|
if (path === '/api/health' && req.method === 'GET') {
|
|
230
274
|
return this.json(rsp, 200, this.hooks.health());
|
|
231
275
|
}
|
|
@@ -318,8 +362,22 @@ export class MemorySite {
|
|
|
318
362
|
try {
|
|
319
363
|
if (!statSync(full).isFile()) return this.text(rsp, 404, 'not found');
|
|
320
364
|
const body = readFileSync(full);
|
|
365
|
+
const type = MIME[extname(full).toLowerCase()] ?? 'application/octet-stream';
|
|
366
|
+
// 首页注入一次性令牌:app.js 把它放进每个写请求的头里。
|
|
367
|
+
// 这份 HTML 不进缓存,否则进程重启后旧令牌会让所有写操作 403。
|
|
368
|
+
if (safe === 'index.html') {
|
|
369
|
+
const html = body
|
|
370
|
+
.toString('utf8')
|
|
371
|
+
.replace('<head>', `<head>\n<meta name="mcore-token" content="${this.token}">`);
|
|
372
|
+
rsp.writeHead(200, {
|
|
373
|
+
'content-type': type,
|
|
374
|
+
'cache-control': 'no-store',
|
|
375
|
+
'x-content-type-options': 'nosniff',
|
|
376
|
+
});
|
|
377
|
+
return rsp.end(html);
|
|
378
|
+
}
|
|
321
379
|
rsp.writeHead(200, {
|
|
322
|
-
'content-type':
|
|
380
|
+
'content-type': type,
|
|
323
381
|
'cache-control': 'no-cache',
|
|
324
382
|
'x-content-type-options': 'nosniff',
|
|
325
383
|
});
|
package/src/store.ts
CHANGED
|
@@ -37,6 +37,19 @@ export interface Card {
|
|
|
37
37
|
supersedes?: string[];
|
|
38
38
|
/** 记忆域:main(自己写的)/ import(旧插件导入的),给以后接 QQ 分流留位。 */
|
|
39
39
|
scope?: string;
|
|
40
|
+
/**
|
|
41
|
+
* 写这条时最近的一句原文(游标 + 时间)。卡片是模型改写过的结论,
|
|
42
|
+
* 不是原话;留一个指针,召回时才敢说「这条能追到当时的哪一句」。
|
|
43
|
+
*/
|
|
44
|
+
src?: { cursor: number; ts: string };
|
|
45
|
+
/** 被「主动想起」过几次(每轮预激活),和 uses(工具召回)分开记。 */
|
|
46
|
+
primedCount?: number;
|
|
47
|
+
lastPrimedAt?: string;
|
|
48
|
+
/**
|
|
49
|
+
* 冷层标记:长期没被想起、又不重要的卡沉到这一层。
|
|
50
|
+
* 不是删除——默认不进召回和预激活,显式搜索仍然找得到,一键回暖。
|
|
51
|
+
*/
|
|
52
|
+
coldAt?: string;
|
|
40
53
|
}
|
|
41
54
|
|
|
42
55
|
export interface RawEntry {
|
|
@@ -67,6 +80,10 @@ export interface CoreState {
|
|
|
67
80
|
proactiveDay?: string;
|
|
68
81
|
proactiveCount?: number;
|
|
69
82
|
lastNightlyDay?: string;
|
|
83
|
+
/** 夜里备好的整理材料:等下一次开口时再交付,别在凌晨三点推给没人看的会话。 */
|
|
84
|
+
nightlyPending?: { day: string; text: string };
|
|
85
|
+
/** 冷层每天只判一次,记下今天判过了。 */
|
|
86
|
+
lastChillDay?: string;
|
|
70
87
|
rawWatermark?: number;
|
|
71
88
|
/** 水位是按哪一版捕获逻辑推进的。旧版用了错的 range 语义,水位不可信,见 CAPTURE_WATERMARK_VERSION。 */
|
|
72
89
|
watermarkVersion?: number;
|
|
@@ -211,6 +228,73 @@ export class CardStore {
|
|
|
211
228
|
return this.cards.filter((c) => c.status !== 'retired');
|
|
212
229
|
}
|
|
213
230
|
|
|
231
|
+
/** 能进「主动想起」和「最近」的那一层:在用的、还没沉到冷层的。 */
|
|
232
|
+
recallable(): Card[] {
|
|
233
|
+
return this.cards.filter((c) => c.status !== 'retired' && !c.coldAt);
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
cold(): Card[] {
|
|
237
|
+
return this.cards.filter((c) => c.status !== 'retired' && Boolean(c.coldAt));
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
/**
|
|
241
|
+
* 该冷的卡:好久没被碰过(工具召回和预激活都算)、权重不高、不是没做完的承诺。
|
|
242
|
+
* 只是候选,真正下沉要显式调用 chill()——分层必须是可逆的、看得见的。
|
|
243
|
+
*/
|
|
244
|
+
chillEligible(days = 30, now = Date.now()): Card[] {
|
|
245
|
+
const span = Math.max(0, Number(days) || 0);
|
|
246
|
+
if (!span) return [];
|
|
247
|
+
const cutoff = now - span * 86_400_000;
|
|
248
|
+
const lastTouch = (c: Card) =>
|
|
249
|
+
Math.max(
|
|
250
|
+
Date.parse(c.createdAt) || 0,
|
|
251
|
+
Date.parse(c.lastUsedAt ?? '') || 0,
|
|
252
|
+
Date.parse(c.lastPrimedAt ?? '') || 0,
|
|
253
|
+
);
|
|
254
|
+
return this.active()
|
|
255
|
+
.filter((c) => {
|
|
256
|
+
if (c.coldAt) return false;
|
|
257
|
+
// 只沉流水账和临时信息;fact / self / 未完成的承诺是「人」,不能沉
|
|
258
|
+
if (c.kind !== 'episode' && c.kind !== 'note') return false;
|
|
259
|
+
if (c.weight > 0.45) return false;
|
|
260
|
+
if ((c.uses || 0) + (c.primedCount || 0) > 1) return false;
|
|
261
|
+
return lastTouch(c) < cutoff;
|
|
262
|
+
})
|
|
263
|
+
.sort((a, b) => lastTouch(a) - lastTouch(b)); // 最久没碰的排前面,配额先吃它们
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
chill(ids: readonly string[]): number {
|
|
267
|
+
const at = new Date().toISOString();
|
|
268
|
+
let n = 0;
|
|
269
|
+
for (const id of ids) {
|
|
270
|
+
const card = this.find(id);
|
|
271
|
+
if (!card || card.status === 'retired' || card.coldAt) continue;
|
|
272
|
+
card.coldAt = at;
|
|
273
|
+
n += 1;
|
|
274
|
+
}
|
|
275
|
+
if (n) {
|
|
276
|
+
this.dirty = true;
|
|
277
|
+
this.save(true);
|
|
278
|
+
}
|
|
279
|
+
return n;
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
warm(ids: readonly string[]): number {
|
|
283
|
+
let n = 0;
|
|
284
|
+
for (const id of ids) {
|
|
285
|
+
const card = this.find(id);
|
|
286
|
+
if (!card || !card.coldAt) continue;
|
|
287
|
+
delete card.coldAt;
|
|
288
|
+
card.updatedAt = new Date().toISOString();
|
|
289
|
+
n += 1;
|
|
290
|
+
}
|
|
291
|
+
if (n) {
|
|
292
|
+
this.dirty = true;
|
|
293
|
+
this.save(true);
|
|
294
|
+
}
|
|
295
|
+
return n;
|
|
296
|
+
}
|
|
297
|
+
|
|
214
298
|
retired(): Card[] {
|
|
215
299
|
return this.cards.filter((c) => c.status === 'retired');
|
|
216
300
|
}
|
|
@@ -250,6 +334,7 @@ export class CardStore {
|
|
|
250
334
|
origin?: string;
|
|
251
335
|
createdAt?: string;
|
|
252
336
|
scope?: string;
|
|
337
|
+
src?: { cursor: number; ts: string };
|
|
253
338
|
}): { card: Card; merged: boolean } {
|
|
254
339
|
const text = String(input.text ?? '').replace(/\s+/g, ' ').trim().slice(0, 500);
|
|
255
340
|
const key = normalizeText(text);
|
|
@@ -282,6 +367,7 @@ export class CardStore {
|
|
|
282
367
|
scope: String(input.scope ?? 'main').slice(0, 24),
|
|
283
368
|
...(input.dueAt ? { dueAt: input.dueAt } : {}),
|
|
284
369
|
...(input.kind === 'promise' ? { done: false } : {}),
|
|
370
|
+
...(input.src ? { src: input.src } : {}),
|
|
285
371
|
};
|
|
286
372
|
this.cards.push(card);
|
|
287
373
|
this.dirty = true;
|
|
@@ -359,6 +445,8 @@ export class CardStore {
|
|
|
359
445
|
status: 'active',
|
|
360
446
|
uses: old.uses,
|
|
361
447
|
supersedes: [...(old.supersedes ?? []), old.id],
|
|
448
|
+
// 文本换了,旧的出处就对不上了,别再挂一个会骗人的 ↩
|
|
449
|
+
src: undefined,
|
|
362
450
|
};
|
|
363
451
|
delete next.retiredAt;
|
|
364
452
|
delete next.retiredBy;
|
|
@@ -521,11 +609,30 @@ export class CardStore {
|
|
|
521
609
|
if (!card) continue;
|
|
522
610
|
card.uses = (card.uses || 0) + 1;
|
|
523
611
|
card.lastUsedAt = now;
|
|
612
|
+
// 真被用上了就不该还算「冷」的,顺手回暖
|
|
613
|
+
delete card.coldAt;
|
|
524
614
|
}
|
|
525
615
|
this.dirty = true;
|
|
526
616
|
this.save(true);
|
|
527
617
|
}
|
|
528
618
|
|
|
619
|
+
/**
|
|
620
|
+
* 记「主动想起」的账。和 touch 分开:预激活是系统推的,工具召回是模型要的。
|
|
621
|
+
* 两者都算「被用过」,但只有后者说明模型真的去查了。
|
|
622
|
+
*/
|
|
623
|
+
prime(ids: readonly string[]): void {
|
|
624
|
+
if (!ids.length) return;
|
|
625
|
+
const now = new Date().toISOString();
|
|
626
|
+
for (const id of ids) {
|
|
627
|
+
const card = this.find(id);
|
|
628
|
+
if (!card) continue;
|
|
629
|
+
card.primedCount = (card.primedCount || 0) + 1;
|
|
630
|
+
card.lastPrimedAt = now;
|
|
631
|
+
}
|
|
632
|
+
this.dirty = true;
|
|
633
|
+
this.save();
|
|
634
|
+
}
|
|
635
|
+
|
|
529
636
|
openPromises(limit = 5, now = Date.now()): Card[] {
|
|
530
637
|
return this.cards
|
|
531
638
|
.filter((c) => c.kind === 'promise' && !c.done && c.status !== 'retired')
|
|
@@ -609,6 +716,14 @@ export class CardStore {
|
|
|
609
716
|
retiredBy: typeof c.retiredBy === 'string' ? c.retiredBy : undefined,
|
|
610
717
|
supersedes: Array.isArray(c.supersedes) ? (c.supersedes as unknown[]).map((x) => String(x)).slice(0, 20) : undefined,
|
|
611
718
|
scope: typeof c.scope === 'string' && c.scope ? c.scope.slice(0, 20) : 'import',
|
|
719
|
+
src:
|
|
720
|
+
c.src && typeof c.src === 'object' && Number.isFinite(Number((c.src as { cursor?: unknown }).cursor))
|
|
721
|
+
&& typeof (c.src as { ts?: unknown }).ts === 'string'
|
|
722
|
+
? { cursor: Number((c.src as { cursor: number }).cursor), ts: String((c.src as { ts: string }).ts) }
|
|
723
|
+
: undefined,
|
|
724
|
+
primedCount: Number.isFinite(Number(c.primedCount)) ? Number(c.primedCount) : undefined,
|
|
725
|
+
lastPrimedAt: typeof c.lastPrimedAt === 'string' ? c.lastPrimedAt : undefined,
|
|
726
|
+
coldAt: typeof c.coldAt === 'string' ? c.coldAt : undefined,
|
|
612
727
|
};
|
|
613
728
|
this.cards.push(card);
|
|
614
729
|
byId.add(id);
|