@jokab1074/rememberme 0.0.0-stage → 0.22.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/ARCHITECTURE.md +787 -0
- package/LICENSE +201 -0
- package/README.en.md +441 -0
- package/README.md +459 -2
- package/dist/mcp/index.js +37287 -0
- package/package.json +67 -4
- package/server.json +38 -0
- package/settings.json.example +7 -0
- package/src/bigfive.ts +163 -0
- package/src/bootstrap.ts +104 -0
- package/src/classify.ts +186 -0
- package/src/compact.ts +225 -0
- package/src/context-file.ts +305 -0
- package/src/embedded-proactive.ts +214 -0
- package/src/evolution/access-tracker.ts +118 -0
- package/src/evolution/curator.ts +220 -0
- package/src/evolution/lifecycle.ts +175 -0
- package/src/feedback-detector.ts +177 -0
- package/src/i18n.ts +89 -0
- package/src/index.ts +1479 -0
- package/src/loop.ts +396 -0
- package/src/mcp/build.ts +64 -0
- package/src/mcp/config.ts +108 -0
- package/src/mcp/index.ts +66 -0
- package/src/mcp/instructions.ts +43 -0
- package/src/mcp/logger.ts +32 -0
- package/src/mcp/provider.ts +142 -0
- package/src/mcp/server.ts +52 -0
- package/src/mcp/tools/memory.ts +126 -0
- package/src/mcp/tools/profile.ts +67 -0
- package/src/mcp/tools/record-turn.ts +239 -0
- package/src/memory-extract.ts +390 -0
- package/src/memory.ts +790 -0
- package/src/persona-init.ts +153 -0
- package/src/persona-learner.ts +349 -0
- package/src/proactive.ts +557 -0
- package/src/profile.ts +1008 -0
- package/src/prompt.ts +288 -0
- package/src/provider.ts +292 -0
- package/src/reflection.ts +552 -0
- package/src/sessions.ts +140 -0
- package/src/timeline.ts +208 -0
- package/src/utils.ts +91 -0
- package/src/web.ts +624 -0
|
@@ -0,0 +1,214 @@
|
|
|
1
|
+
// src/embedded-proactive.ts
|
|
2
|
+
// 嵌入式主动问题 - "对了..." 在主回复末尾自然嵌入
|
|
3
|
+
// 修复 Bun 解析器对全角标点 + template literal 的兼容问题
|
|
4
|
+
|
|
5
|
+
import type { ModelProvider } from "./provider.ts";
|
|
6
|
+
import type { Profile } from "./profile.ts";
|
|
7
|
+
import { validateProactiveMessage } from "./proactive.ts";
|
|
8
|
+
|
|
9
|
+
export type EmbeddedProactiveConfig = {
|
|
10
|
+
/** 用户上次活跃距今多少小时才触发(默认 4h) */
|
|
11
|
+
idleHours: number;
|
|
12
|
+
/** 本次会话至少有几轮用户消息才触发(默认 2) */
|
|
13
|
+
minUserTurns: number;
|
|
14
|
+
/** 上次嵌入距今多少小时才再触发(默认 24h) */
|
|
15
|
+
cooldownHours: number;
|
|
16
|
+
};
|
|
17
|
+
|
|
18
|
+
export const DEFAULT_EMBEDDED_PROACTIVE_CONFIG: EmbeddedProactiveConfig = {
|
|
19
|
+
idleHours: 4,
|
|
20
|
+
minUserTurns: 2,
|
|
21
|
+
cooldownHours: 24,
|
|
22
|
+
};
|
|
23
|
+
|
|
24
|
+
export type EmbeddedProactiveInput = {
|
|
25
|
+
lastUserActivityAt: number;
|
|
26
|
+
currentUserTurns: number;
|
|
27
|
+
lastEmbeddedAt: number;
|
|
28
|
+
profile: Profile | null;
|
|
29
|
+
memorySummary: string;
|
|
30
|
+
recentUserMessage: string;
|
|
31
|
+
currentReply: string;
|
|
32
|
+
replyAlreadyHasProbe: boolean;
|
|
33
|
+
};
|
|
34
|
+
|
|
35
|
+
export type EmbeddedProactiveDecision = {
|
|
36
|
+
shouldEmbed: boolean;
|
|
37
|
+
reason: string;
|
|
38
|
+
question?: string;
|
|
39
|
+
validationScore: number;
|
|
40
|
+
};
|
|
41
|
+
|
|
42
|
+
const PROACTIVE_PROBE_PROMPT = [
|
|
43
|
+
"你是用户的长期陪聊伙伴。",
|
|
44
|
+
"用户离开了一会儿,又回来了。",
|
|
45
|
+
"请基于【用户画像】和【近期记忆】,在主回复后面接一个自然的小追问。",
|
|
46
|
+
"",
|
|
47
|
+
"硬性规则(绝不能违反):",
|
|
48
|
+
"1. 只能引用用户画像或记忆里出现过的具体内容",
|
|
49
|
+
"2. 上下文中没有的,绝对不能提",
|
|
50
|
+
"3. 保持随和的语气,像朋友突然想起什么",
|
|
51
|
+
"4. 简短 - 30 字以内,对了你加 1 句问句",
|
|
52
|
+
"5. 不要打断主回复的逻辑",
|
|
53
|
+
"6. 用户的名字、宠物、爱好等只能从 context 里有",
|
|
54
|
+
"",
|
|
55
|
+
"只输出问题本身(含'对了'或'话说'开头),不要任何前言。",
|
|
56
|
+
].join("\n");
|
|
57
|
+
|
|
58
|
+
async function generateProactiveQuestion(
|
|
59
|
+
provider: ModelProvider,
|
|
60
|
+
input: {
|
|
61
|
+
personalityName: string;
|
|
62
|
+
recentUserMessage: string;
|
|
63
|
+
currentReply: string;
|
|
64
|
+
idleHours: number;
|
|
65
|
+
profileSummary: string;
|
|
66
|
+
memorySummary: string;
|
|
67
|
+
},
|
|
68
|
+
options: { signal?: AbortSignal } = {},
|
|
69
|
+
): Promise<string | null> {
|
|
70
|
+
const userContext = [
|
|
71
|
+
"用户画像:",
|
|
72
|
+
input.profileSummary || "(暂无)",
|
|
73
|
+
"",
|
|
74
|
+
"近期记忆:",
|
|
75
|
+
input.memorySummary || "(暂无)",
|
|
76
|
+
"",
|
|
77
|
+
"用户最近说: " + input.recentUserMessage,
|
|
78
|
+
"你刚才回复: " + input.currentReply,
|
|
79
|
+
"用户离开了 " + input.idleHours.toFixed(1) + " 小时",
|
|
80
|
+
].join("\n");
|
|
81
|
+
|
|
82
|
+
try {
|
|
83
|
+
const raw = await provider.complete({
|
|
84
|
+
model: provider.model,
|
|
85
|
+
params: {
|
|
86
|
+
system: PROACTIVE_PROBE_PROMPT,
|
|
87
|
+
messages: [
|
|
88
|
+
{ role: "user", content: userContext },
|
|
89
|
+
],
|
|
90
|
+
maxTokens: 200,
|
|
91
|
+
temperature: 0.7,
|
|
92
|
+
signal: options.signal,
|
|
93
|
+
},
|
|
94
|
+
});
|
|
95
|
+
return raw.trim();
|
|
96
|
+
} catch {
|
|
97
|
+
return null;
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
export async function maybeEmbedProactive(
|
|
102
|
+
provider: ModelProvider,
|
|
103
|
+
config: EmbeddedProactiveConfig,
|
|
104
|
+
input: EmbeddedProactiveInput,
|
|
105
|
+
options: { signal?: AbortSignal; now?: number } = {},
|
|
106
|
+
): Promise<EmbeddedProactiveDecision> {
|
|
107
|
+
const now = options.now ?? Date.now();
|
|
108
|
+
const idleMs = now - input.lastUserActivityAt;
|
|
109
|
+
const idleHours = idleMs / (1000 * 60 * 60);
|
|
110
|
+
const cooldownMs = now - input.lastEmbeddedAt;
|
|
111
|
+
const cooldownHours = cooldownMs / (1000 * 60 * 60);
|
|
112
|
+
|
|
113
|
+
const idleOk = idleHours >= config.idleHours;
|
|
114
|
+
const turnsOk = input.currentUserTurns >= config.minUserTurns;
|
|
115
|
+
const cooldownOk =
|
|
116
|
+
input.lastEmbeddedAt === 0 || cooldownHours >= config.cooldownHours;
|
|
117
|
+
const contextOk =
|
|
118
|
+
(input.profile &&
|
|
119
|
+
Object.values(input.profile.sections).some(
|
|
120
|
+
(s) => s && !s.includes("暂无"),
|
|
121
|
+
)) ||
|
|
122
|
+
(input.memorySummary && input.memorySummary.trim().length > 0);
|
|
123
|
+
const notInReply = !input.replyAlreadyHasProbe;
|
|
124
|
+
|
|
125
|
+
if (!idleOk) {
|
|
126
|
+
return {
|
|
127
|
+
shouldEmbed: false,
|
|
128
|
+
reason: "用户刚活跃(" + idleHours.toFixed(1) + "h 前 < " + config.idleHours + "h 阈值)",
|
|
129
|
+
validationScore: 0,
|
|
130
|
+
};
|
|
131
|
+
}
|
|
132
|
+
if (!turnsOk) {
|
|
133
|
+
return {
|
|
134
|
+
shouldEmbed: false,
|
|
135
|
+
reason: "会话刚开始(" + input.currentUserTurns + " 轮 < " + config.minUserTurns + ")",
|
|
136
|
+
validationScore: 0,
|
|
137
|
+
};
|
|
138
|
+
}
|
|
139
|
+
if (!cooldownOk) {
|
|
140
|
+
return {
|
|
141
|
+
shouldEmbed: false,
|
|
142
|
+
reason: "上次嵌入才 " + cooldownHours.toFixed(1) + "h 前(< " + config.cooldownHours + "h cooldown)",
|
|
143
|
+
validationScore: 0,
|
|
144
|
+
};
|
|
145
|
+
}
|
|
146
|
+
if (!contextOk) {
|
|
147
|
+
return {
|
|
148
|
+
shouldEmbed: false,
|
|
149
|
+
reason: "没有可用的 profile/memory 上下文(避免编造)",
|
|
150
|
+
validationScore: 0,
|
|
151
|
+
};
|
|
152
|
+
}
|
|
153
|
+
if (!notInReply) {
|
|
154
|
+
return {
|
|
155
|
+
shouldEmbed: false,
|
|
156
|
+
reason: "主回复已经包含探针(对了/话说),不再重复",
|
|
157
|
+
validationScore: 0,
|
|
158
|
+
};
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
const profileSummary = input.profile
|
|
162
|
+
? Object.entries(input.profile.sections)
|
|
163
|
+
.filter(([_, v]) => v && !v.includes("暂无"))
|
|
164
|
+
.map(([k, v]) => k + ": " + v.slice(0, 200))
|
|
165
|
+
.join("\n")
|
|
166
|
+
: "(暂无)";
|
|
167
|
+
|
|
168
|
+
const question = await generateProactiveQuestion(
|
|
169
|
+
provider,
|
|
170
|
+
{
|
|
171
|
+
personalityName: "",
|
|
172
|
+
recentUserMessage: input.recentUserMessage,
|
|
173
|
+
currentReply: input.currentReply,
|
|
174
|
+
idleHours,
|
|
175
|
+
profileSummary,
|
|
176
|
+
memorySummary: input.memorySummary,
|
|
177
|
+
},
|
|
178
|
+
options,
|
|
179
|
+
);
|
|
180
|
+
|
|
181
|
+
if (!question) {
|
|
182
|
+
return {
|
|
183
|
+
shouldEmbed: false,
|
|
184
|
+
reason: "LLM 无法生成有效问题",
|
|
185
|
+
validationScore: 0,
|
|
186
|
+
};
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
// 用同样的关键词验证:必须引用 context
|
|
190
|
+
const ctx: ProactiveContext = {
|
|
191
|
+
profile: input.profile,
|
|
192
|
+
memories: [],
|
|
193
|
+
timelineSummary: input.memorySummary,
|
|
194
|
+
personalityName: "",
|
|
195
|
+
personalityDescription: "",
|
|
196
|
+
};
|
|
197
|
+
const validation = validateProactiveMessage(question, ctx);
|
|
198
|
+
if (!validation.valid) {
|
|
199
|
+
return {
|
|
200
|
+
shouldEmbed: false,
|
|
201
|
+
reason: "生成的问题未通过验证: " + validation.reason,
|
|
202
|
+
validationScore: 0,
|
|
203
|
+
};
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
return {
|
|
207
|
+
shouldEmbed: true,
|
|
208
|
+
question,
|
|
209
|
+
reason: "用户离开 " + idleHours.toFixed(1) + "h,嵌入自然问题",
|
|
210
|
+
validationScore: 1,
|
|
211
|
+
};
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
type ProactiveContext = Parameters<typeof validateProactiveMessage>[1];
|
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
// src/evolution/access-tracker.ts
|
|
2
|
+
// 访问追踪:每轮对话记录哪些 memory / profile item 被引用
|
|
3
|
+
// 用途:curator 据此判断"哪些条目其实没人在用"(→ stale / archived)。
|
|
4
|
+
// 设计:纯函数式 + 状态保存在 dataDir/access-log.jsonl(append-only)。
|
|
5
|
+
|
|
6
|
+
import { readFile, writeFile, mkdir, appendFile } from "node:fs/promises";
|
|
7
|
+
import { join, dirname } from "node:path";
|
|
8
|
+
import type { AccessRecord } from "./lifecycle.ts";
|
|
9
|
+
|
|
10
|
+
export type AccessKind = "memory" | "profile" | "skill";
|
|
11
|
+
|
|
12
|
+
export type AccessEvent = {
|
|
13
|
+
ts: number;
|
|
14
|
+
kind: AccessKind;
|
|
15
|
+
/** 条目的稳定 id(memory 用 filename,profile 用 section 名) */
|
|
16
|
+
itemId: string;
|
|
17
|
+
/** 触发来源 */
|
|
18
|
+
source: AccessRecord["source"];
|
|
19
|
+
/** 触发的那条用户消息(可选,用于事后追溯) */
|
|
20
|
+
context?: string;
|
|
21
|
+
};
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* 记录一次访问事件。
|
|
25
|
+
* append-only JSONL,失败不抛错(不能让跟踪崩溃主对话)。
|
|
26
|
+
*/
|
|
27
|
+
export async function recordAccessEvent(
|
|
28
|
+
dataDir: string,
|
|
29
|
+
event: AccessEvent,
|
|
30
|
+
): Promise<void> {
|
|
31
|
+
try {
|
|
32
|
+
const path = join(dataDir, "evolution", "access-log.jsonl");
|
|
33
|
+
await mkdir(dirname(path), { recursive: true });
|
|
34
|
+
await appendFile(path, JSON.stringify(event) + "\n", "utf-8");
|
|
35
|
+
} catch {
|
|
36
|
+
// 静默失败
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* 批量记录(一次主循环里通常有多个被引用的条目)。
|
|
42
|
+
*/
|
|
43
|
+
export async function recordAccessEvents(
|
|
44
|
+
dataDir: string,
|
|
45
|
+
events: AccessEvent[],
|
|
46
|
+
): Promise<void> {
|
|
47
|
+
if (events.length === 0) return;
|
|
48
|
+
try {
|
|
49
|
+
const path = join(dataDir, "evolution", "access-log.jsonl");
|
|
50
|
+
await mkdir(dirname(path), { recursive: true });
|
|
51
|
+
const lines = events.map((e) => JSON.stringify(e)).join("\n") + "\n";
|
|
52
|
+
await appendFile(path, lines, "utf-8");
|
|
53
|
+
} catch {
|
|
54
|
+
// 静默
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* 读取最近 N 条访问事件。
|
|
60
|
+
* 倒序读取文件(最新在最后),取最近 N 条并反转。
|
|
61
|
+
*/
|
|
62
|
+
export async function readRecentAccessEvents(
|
|
63
|
+
dataDir: string,
|
|
64
|
+
limit: number = 1000,
|
|
65
|
+
): Promise<AccessEvent[]> {
|
|
66
|
+
const path = join(dataDir, "evolution", "access-log.jsonl");
|
|
67
|
+
try {
|
|
68
|
+
const raw = await readFile(path, "utf-8");
|
|
69
|
+
const lines = raw.split("\n").filter(Boolean);
|
|
70
|
+
const events: AccessEvent[] = [];
|
|
71
|
+
for (const line of lines) {
|
|
72
|
+
try {
|
|
73
|
+
events.push(JSON.parse(line) as AccessEvent);
|
|
74
|
+
} catch {
|
|
75
|
+
// skip corrupt
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
return events.slice(-limit);
|
|
79
|
+
} catch {
|
|
80
|
+
return [];
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/**
|
|
85
|
+
* 聚合:每个 item 的最后访问时间 + 累计访问次数。
|
|
86
|
+
*/
|
|
87
|
+
export function aggregateAccessStats(
|
|
88
|
+
events: AccessEvent[],
|
|
89
|
+
): Map<string, { lastAccessedAt: number; count: number; kind: AccessKind }> {
|
|
90
|
+
const map = new Map<string, { lastAccessedAt: number; count: number; kind: AccessKind }>();
|
|
91
|
+
for (const e of events) {
|
|
92
|
+
const existing = map.get(e.itemId);
|
|
93
|
+
if (existing) {
|
|
94
|
+
existing.count++;
|
|
95
|
+
if (e.ts > existing.lastAccessedAt) existing.lastAccessedAt = e.ts;
|
|
96
|
+
} else {
|
|
97
|
+
map.set(e.itemId, { lastAccessedAt: e.ts, count: 1, kind: e.kind });
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
return map;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/**
|
|
104
|
+
* 把当前轮"用到的 memory 文件名"转成 AccessEvent 列表。
|
|
105
|
+
* loop.ts 在 runTurn 末尾调用这个,传给 recordAccessEvents。
|
|
106
|
+
*/
|
|
107
|
+
export function buildEventsFromMemoryFiles(
|
|
108
|
+
ts: number,
|
|
109
|
+
memoryFilenames: string[],
|
|
110
|
+
source: AccessRecord["source"] = "conversation",
|
|
111
|
+
): AccessEvent[] {
|
|
112
|
+
return memoryFilenames.map((filename) => ({
|
|
113
|
+
ts,
|
|
114
|
+
kind: "memory" as const,
|
|
115
|
+
itemId: filename,
|
|
116
|
+
source,
|
|
117
|
+
}));
|
|
118
|
+
}
|
|
@@ -0,0 +1,220 @@
|
|
|
1
|
+
// src/evolution/curator.ts
|
|
2
|
+
// 策展人:空闲触发的 3-pass 自我维护
|
|
3
|
+
// 3-pass 模式:状态转移 → 归档 → LLM 合并重复。
|
|
4
|
+
// 这是 LLM agent 通用模式(自维护 / auto-curation 是常见做法),本项目独立实现。
|
|
5
|
+
// 触发:每次启动 REPL 时检查"距上次策展"时间 + 用户活跃时间,空闲才跑。
|
|
6
|
+
|
|
7
|
+
import { readFile, writeFile, mkdir } from "node:fs/promises";
|
|
8
|
+
import { join } from "node:path";
|
|
9
|
+
import {
|
|
10
|
+
DEFAULT_LIFECYCLE_CONFIG,
|
|
11
|
+
transitionBatch,
|
|
12
|
+
type LifecycleMeta,
|
|
13
|
+
type LifecycleState,
|
|
14
|
+
} from "./lifecycle.ts";
|
|
15
|
+
import { readRecentAccessEvents, aggregateAccessStats } from "./access-tracker.ts";
|
|
16
|
+
|
|
17
|
+
/** curator 状态(持久化在 dataDir/evolution/curator-state.json) */
|
|
18
|
+
export type CuratorState = {
|
|
19
|
+
/** 上次跑 curator 的时间(ms) */
|
|
20
|
+
lastRunAt: number;
|
|
21
|
+
/** 累计跑了多少次 */
|
|
22
|
+
runCount: number;
|
|
23
|
+
/** 上次运行产生的状态变化数(仅显示用) */
|
|
24
|
+
lastChanges: number;
|
|
25
|
+
/** 是否暂停 */
|
|
26
|
+
paused: boolean;
|
|
27
|
+
/** 用户最小空闲小时数(默认 2h) */
|
|
28
|
+
minIdleHours: number;
|
|
29
|
+
/** 跑 curator 的最小间隔(默认 24h) */
|
|
30
|
+
minIntervalHours: number;
|
|
31
|
+
};
|
|
32
|
+
|
|
33
|
+
export const DEFAULT_CURATOR_STATE: CuratorState = {
|
|
34
|
+
lastRunAt: 0,
|
|
35
|
+
runCount: 0,
|
|
36
|
+
lastChanges: 0,
|
|
37
|
+
paused: false,
|
|
38
|
+
minIdleHours: 2,
|
|
39
|
+
minIntervalHours: 24,
|
|
40
|
+
};
|
|
41
|
+
|
|
42
|
+
export const CURATOR_STATE_FILENAME = "curator-state.json";
|
|
43
|
+
|
|
44
|
+
function curatorStatePath(dataDir: string): string {
|
|
45
|
+
return join(dataDir, "evolution", CURATOR_STATE_FILENAME);
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
export async function loadCuratorState(dataDir: string): Promise<CuratorState> {
|
|
49
|
+
try {
|
|
50
|
+
const raw = await readFile(curatorStatePath(dataDir), "utf-8");
|
|
51
|
+
const parsed = JSON.parse(raw);
|
|
52
|
+
return { ...DEFAULT_CURATOR_STATE, ...parsed };
|
|
53
|
+
} catch {
|
|
54
|
+
return { ...DEFAULT_CURATOR_STATE };
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
export async function saveCuratorState(
|
|
59
|
+
dataDir: string,
|
|
60
|
+
state: CuratorState,
|
|
61
|
+
): Promise<void> {
|
|
62
|
+
try {
|
|
63
|
+
await mkdir(join(dataDir, "evolution"), { recursive: true });
|
|
64
|
+
await writeFile(
|
|
65
|
+
curatorStatePath(dataDir),
|
|
66
|
+
JSON.stringify(state, null, 2),
|
|
67
|
+
"utf-8",
|
|
68
|
+
);
|
|
69
|
+
} catch {
|
|
70
|
+
// 静默
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/** curator 单次运行的结果 */
|
|
75
|
+
export type CuratorRunResult = {
|
|
76
|
+
pass1_marked: number; // active → stale
|
|
77
|
+
pass2_archived: number; // stale → archived
|
|
78
|
+
pass3_consolidated: number; // 合并的条目数(如果启用)
|
|
79
|
+
skipped_pinned: number;
|
|
80
|
+
skipped_no_change: number;
|
|
81
|
+
durationMs: number;
|
|
82
|
+
};
|
|
83
|
+
|
|
84
|
+
/**
|
|
85
|
+
* 是否应该现在跑 curator?
|
|
86
|
+
* 条件:用户最后活跃 > minIdleHours 小时前 + 距上次策展 > minIntervalHours 小时前
|
|
87
|
+
*/
|
|
88
|
+
export function shouldRunCurator(
|
|
89
|
+
state: CuratorState,
|
|
90
|
+
lastUserActivityAt: number,
|
|
91
|
+
now: number = Date.now(),
|
|
92
|
+
): { shouldRun: boolean; reason: string } {
|
|
93
|
+
if (state.paused) {
|
|
94
|
+
return { shouldRun: false, reason: "已暂停" };
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
const sinceLastRun = now - state.lastRunAt;
|
|
98
|
+
const minIntervalMs = state.minIntervalHours * 3600 * 1000;
|
|
99
|
+
if (state.lastRunAt > 0 && sinceLastRun < minIntervalMs) {
|
|
100
|
+
const hoursLeft = ((minIntervalMs - sinceLastRun) / 3600000).toFixed(1);
|
|
101
|
+
return { shouldRun: false, reason: `距上次策展 ${hoursLeft} 小时,间隔未到` };
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
const sinceActivity = now - lastUserActivityAt;
|
|
105
|
+
const minIdleMs = state.minIdleHours * 3600 * 1000;
|
|
106
|
+
if (lastUserActivityAt > 0 && sinceActivity < minIdleMs) {
|
|
107
|
+
const minutesLeft = Math.ceil((minIdleMs - sinceActivity) / 60000);
|
|
108
|
+
return { shouldRun: false, reason: `用户 ${minutesLeft} 分钟前还活跃,等空闲` };
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
return { shouldRun: true, reason: "可以跑" };
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/**
|
|
115
|
+
* 跑一次 curator(不含 LLM 合并——Pass 3 由调用方决定)。
|
|
116
|
+
*
|
|
117
|
+
* 输入:
|
|
118
|
+
* - items: 待审查的条目(含 meta)
|
|
119
|
+
* - dataDir: 用于读取 access-log
|
|
120
|
+
* - config: 生命周期配置
|
|
121
|
+
* - applyChanges: 把状态变化写回数据的回调(每个 item 一个)
|
|
122
|
+
*/
|
|
123
|
+
export async function runCurator<T extends { filename: string; meta: LifecycleMeta }>(
|
|
124
|
+
items: T[],
|
|
125
|
+
dataDir: string,
|
|
126
|
+
options: {
|
|
127
|
+
applyStateChange?: (item: T, oldState: LifecycleState, newState: LifecycleState) => void;
|
|
128
|
+
config?: typeof DEFAULT_LIFECYCLE_CONFIG;
|
|
129
|
+
now?: number;
|
|
130
|
+
} = {},
|
|
131
|
+
): Promise<CuratorRunResult> {
|
|
132
|
+
const start = Date.now();
|
|
133
|
+
const config = options.config ?? DEFAULT_LIFECYCLE_CONFIG;
|
|
134
|
+
const now = options.now ?? Date.now();
|
|
135
|
+
|
|
136
|
+
// 读取最近 90 天的访问记录(用 lastAccessedAt 来判断状态)
|
|
137
|
+
const events = await readRecentAccessEvents(dataDir, 5000);
|
|
138
|
+
const accessStats = aggregateAccessStats(events);
|
|
139
|
+
|
|
140
|
+
// 把访问记录合并到 items 的 meta(如果 meta.lastAccessedAt 早于实际访问记录,就更新)
|
|
141
|
+
// 这是为了"如果某个 memory 文件没在这次对话里被显式引用,但历史上被用过,就别误判为 stale"
|
|
142
|
+
const updatedItems = items.map((item) => {
|
|
143
|
+
const stat = accessStats.get(item.filename);
|
|
144
|
+
if (stat && stat.lastAccessedAt > item.meta.lastAccessedAt) {
|
|
145
|
+
return {
|
|
146
|
+
...item,
|
|
147
|
+
meta: {
|
|
148
|
+
...item.meta,
|
|
149
|
+
lastAccessedAt: stat.lastAccessedAt,
|
|
150
|
+
accessCount: stat.count,
|
|
151
|
+
},
|
|
152
|
+
};
|
|
153
|
+
}
|
|
154
|
+
return item;
|
|
155
|
+
});
|
|
156
|
+
|
|
157
|
+
// Pass 1: 状态转移(active → stale / archived)
|
|
158
|
+
const transition = transitionBatch(updatedItems, config, now);
|
|
159
|
+
let pass1 = 0;
|
|
160
|
+
let pass2 = 0;
|
|
161
|
+
let skippedPinned = 0;
|
|
162
|
+
let skippedNoChange = transition.skipped;
|
|
163
|
+
|
|
164
|
+
for (const c of transition.changed) {
|
|
165
|
+
if (c.oldState === "active" && c.newState === "stale") pass1++;
|
|
166
|
+
if (c.oldState === "stale" && c.newState === "archived") pass2++;
|
|
167
|
+
|
|
168
|
+
// pinned 永远不动(不变量 #3)
|
|
169
|
+
if (c.item.meta.pinned) {
|
|
170
|
+
skippedPinned++;
|
|
171
|
+
continue;
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
// 调用回调(让调用方把状态写回磁盘)
|
|
175
|
+
options.applyStateChange?.(c.item, c.oldState, c.newState);
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
// 累加 pinned 到 skipped(不变量 #3 验证)
|
|
179
|
+
skippedNoChange += skippedPinned;
|
|
180
|
+
|
|
181
|
+
return {
|
|
182
|
+
pass1_marked: pass1,
|
|
183
|
+
pass2_archived: pass2,
|
|
184
|
+
pass3_consolidated: 0, // 由调用方单独跑
|
|
185
|
+
skipped_pinned: skippedPinned,
|
|
186
|
+
skipped_no_change: skippedNoChange,
|
|
187
|
+
durationMs: Date.now() - start,
|
|
188
|
+
};
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
/**
|
|
192
|
+
* 更新 curator 状态(用 run 后)。
|
|
193
|
+
*/
|
|
194
|
+
export function recordCuratorRun(
|
|
195
|
+
state: CuratorState,
|
|
196
|
+
result: CuratorRunResult,
|
|
197
|
+
now: number = Date.now(),
|
|
198
|
+
): CuratorState {
|
|
199
|
+
return {
|
|
200
|
+
...state,
|
|
201
|
+
lastRunAt: now,
|
|
202
|
+
runCount: state.runCount + 1,
|
|
203
|
+
lastChanges:
|
|
204
|
+
result.pass1_marked + result.pass2_archived + result.pass3_consolidated,
|
|
205
|
+
};
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
/**
|
|
209
|
+
* 重新激活 archived 项(用户手动 `/reactivate <id>`)。
|
|
210
|
+
* 从 caller 传入。
|
|
211
|
+
*/
|
|
212
|
+
export function shouldReactivate(
|
|
213
|
+
meta: LifecycleMeta,
|
|
214
|
+
now: number = Date.now(),
|
|
215
|
+
): boolean {
|
|
216
|
+
return (
|
|
217
|
+
meta.state === "archived" &&
|
|
218
|
+
(now - meta.lastAccessedAt) / (1000 * 60 * 60 * 24) > 7
|
|
219
|
+
);
|
|
220
|
+
}
|