dsh-memorytree-rule 0.0.0-stage → 1.0.2
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 +36 -0
- package/LICENSE +21 -0
- package/README.md +144 -3
- package/bin/mt.mjs +589 -0
- package/client.js +227 -0
- package/cordis.patch.yml +14 -0
- package/docs/DETAIL.md +69 -0
- package/docs/DETAIL.svg +85 -0
- package/docs/EMOTION.md +99 -0
- package/examples/AGENTS.demo.md +22 -0
- package/examples/AGENTS.template.md +212 -0
- package/icon.svg +17 -0
- package/index.js +418 -0
- package/lib/board.mjs +1113 -0
- package/lib/cards.mjs +56 -0
- package/lib/daily.mjs +140 -0
- package/lib/db.mjs +84 -0
- package/lib/demo.mjs +161 -0
- package/lib/diary.mjs +92 -0
- package/lib/emotion.mjs +474 -0
- package/lib/import-legacy.mjs +167 -0
- package/lib/ingest.mjs +279 -0
- package/lib/levels.mjs +40 -0
- package/lib/paths.mjs +85 -0
- package/lib/report.mjs +2130 -0
- package/lib/rules.mjs +635 -0
- package/lib/runtime.mjs +232 -0
- package/lib/schema.mjs +363 -0
- package/lib/search.mjs +264 -0
- package/lib/store.mjs +1334 -0
- package/lib/text.mjs +161 -0
- package/lib/tools.mjs +962 -0
- package/lib/vector.mjs +51 -0
- package/locale/en.json +7 -0
- package/locale/zh.json +7 -0
- package/package.json +81 -6
- package/tests/emotion.test.mjs +215 -0
- package/tests/memory-tree.test.mjs +620 -0
- package/tests/regressions.test.mjs +834 -0
- package/tests/renumber.test.mjs +276 -0
- package/tests/trunk-bucket.test.mjs +225 -0
package/bin/mt.mjs
ADDED
|
@@ -0,0 +1,589 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// bin/mt.mjs — 不进宿主也能用的命令行:排查、迁移、导出、生成看板。
|
|
3
|
+
//
|
|
4
|
+
// 它和插件共用同一套 lib/(同一个库、同一套检索与分拣逻辑),
|
|
5
|
+
// 区别只是没有 agent 上下文:作用域用 --scope 指定,默认 user+当前目录。
|
|
6
|
+
import fs from "node:fs";
|
|
7
|
+
import path from "node:path";
|
|
8
|
+
import process from "node:process";
|
|
9
|
+
import { fileURLToPath } from "node:url";
|
|
10
|
+
import { MemoryRuntime } from "../lib/runtime.mjs";
|
|
11
|
+
import { searchMemory } from "../lib/search.mjs";
|
|
12
|
+
import { importLegacy } from "../lib/import-legacy.mjs";
|
|
13
|
+
import { buildDailyReport, applyDailyDecisions } from "../lib/daily.mjs";
|
|
14
|
+
import { buildReportHtml } from "../lib/report.mjs";
|
|
15
|
+
import { runDemo } from "../lib/demo.mjs";
|
|
16
|
+
import { localDate } from "../lib/diary.mjs";
|
|
17
|
+
import { LAYERS, STATUSES } from "../lib/schema.mjs";
|
|
18
|
+
|
|
19
|
+
class CliError extends Error {}
|
|
20
|
+
|
|
21
|
+
const SCOPE_NAMES = new Set(["all", "user", "global", "workspace"]);
|
|
22
|
+
|
|
23
|
+
const HELP = `dsh-memorytree-rule CLI(离线,不联网、不调 LLM)
|
|
24
|
+
|
|
25
|
+
用法:node bin/mt.mjs <命令> [参数]
|
|
26
|
+
|
|
27
|
+
常用:
|
|
28
|
+
doctor 自检:路径、库、主干文件、旧库
|
|
29
|
+
init [--force] 把起步模板写成 <DSH_HOME>/AGENTS.md 并同步(已存在不覆盖)
|
|
30
|
+
stats 四枝/状态统计
|
|
31
|
+
sync [--force] 把 AGENTS.md 的 §1 主干同步成枝条目
|
|
32
|
+
migrate [--apply] [--db 路径] 迁移旧 memories.db(默认只预览)
|
|
33
|
+
search "关键词" [--scope all|user|workspace] [--layer task,trunk] [--limit 8] [--mode keyword|vector|hybrid]
|
|
34
|
+
add --layer task --text "..." [--subject eac] [--title "..."] [--tags a,b] [--scope user|workspace] [--importance 0.7] [--half-life 60] [--valid-until 2027-01-01]
|
|
35
|
+
list [--scope all|user|workspace] [--layer task] [--status active] [--limit 20]
|
|
36
|
+
card --subject eac | --id 12 一张卡 + 相关条目
|
|
37
|
+
tree [--scope all|user|workspace]
|
|
38
|
+
daily [--hours 24] [--limit 30] 待分拣报告(JSON)
|
|
39
|
+
diary [auto|get|list|add] [--date 2026-11-15] [--text "..."] [--mood note] [--force]
|
|
40
|
+
日记索引:auto=按库内变动自动拼装(默认),add=手写
|
|
41
|
+
apply --file 决定.json 提交分拣决定([{id,to,subject,...}])
|
|
42
|
+
forget --ids 3,4 [--hard] [--reason "..."] 默认归档,--hard 才物理删
|
|
43
|
+
reindex 重建词表与向量
|
|
44
|
+
export [--out 文件.jsonl]
|
|
45
|
+
import --file 文件.jsonl
|
|
46
|
+
report [--out 文件.html] 自包含 HTML 看板
|
|
47
|
+
demo [--out 文件.html] 生成隔离的四枝示例库与看板,不碰真实记忆
|
|
48
|
+
|
|
49
|
+
全局:--data-dir <目录> --db <文件> --agents <AGENTS.md> --json
|
|
50
|
+
`;
|
|
51
|
+
|
|
52
|
+
function parseArgs(argv) {
|
|
53
|
+
const out = { _: [] };
|
|
54
|
+
for (let i = 0; i < argv.length; i += 1) {
|
|
55
|
+
const a = argv[i];
|
|
56
|
+
if (a.startsWith("--")) {
|
|
57
|
+
const key = a.slice(2);
|
|
58
|
+
const next = argv[i + 1];
|
|
59
|
+
if (next !== undefined && !next.startsWith("--")) {
|
|
60
|
+
out[key] = next;
|
|
61
|
+
i += 1;
|
|
62
|
+
} else {
|
|
63
|
+
out[key] = true;
|
|
64
|
+
}
|
|
65
|
+
} else {
|
|
66
|
+
out._.push(a);
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
return out;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
function splitList(v) {
|
|
73
|
+
if (v === undefined || v === true || v === "") return [];
|
|
74
|
+
return String(v).split(/[,,]/).map((s) => s.trim()).filter(Boolean);
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
function print(value, asJson = false) {
|
|
78
|
+
if (asJson) {
|
|
79
|
+
process.stdout.write(JSON.stringify(value, null, 2) + "\n");
|
|
80
|
+
return;
|
|
81
|
+
}
|
|
82
|
+
if (typeof value === "string") {
|
|
83
|
+
process.stdout.write(value.endsWith("\n") ? value : value + "\n");
|
|
84
|
+
return;
|
|
85
|
+
}
|
|
86
|
+
process.stdout.write(JSON.stringify(value, null, 2) + "\n");
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
function fmtTime(ms) {
|
|
90
|
+
if (!ms) return "-";
|
|
91
|
+
const d = new Date(ms);
|
|
92
|
+
const p = (n) => String(n).padStart(2, "0");
|
|
93
|
+
return `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())} ${p(d.getHours())}:${p(d.getMinutes())}`;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
function layerLabel(l) {
|
|
97
|
+
return { trunk: "§1 主干", emotion: "§2 情感枝", task: "§3 任务枝", leaf: "§4 判断叶" }[l] ?? l;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
function makeRuntime(args) {
|
|
101
|
+
const config = { redact: true, autoSync: true };
|
|
102
|
+
if (args["data-dir"]) config.dataDir = String(args["data-dir"]);
|
|
103
|
+
if (args.db) config.dbFile = String(args.db);
|
|
104
|
+
if (args.agents) config.agentsPath = String(args.agents);
|
|
105
|
+
return new MemoryRuntime(config);
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
function resolveScope(rt, requested) {
|
|
109
|
+
const want = String(requested ?? "all");
|
|
110
|
+
if (!SCOPE_NAMES.has(want)) {
|
|
111
|
+
throw new CliError("--scope 只能是 all/user/workspace,收到:" + want);
|
|
112
|
+
}
|
|
113
|
+
return rt.scopesFor(null, want);
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
function pluginVersion() {
|
|
117
|
+
try {
|
|
118
|
+
const pkg = JSON.parse(fs.readFileSync(new URL("../package.json", import.meta.url), "utf8"));
|
|
119
|
+
return String(pkg.version || "unknown");
|
|
120
|
+
} catch {
|
|
121
|
+
return "unknown";
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
async function main() {
|
|
126
|
+
const argv = process.argv.slice(2);
|
|
127
|
+
const args = parseArgs(argv);
|
|
128
|
+
const cmd = args._[0] ?? "help";
|
|
129
|
+
const asJson = args.json === true || args.json === "true";
|
|
130
|
+
|
|
131
|
+
if (cmd === "help" || args.help) {
|
|
132
|
+
process.stdout.write(HELP);
|
|
133
|
+
return 0;
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
// demo 必须走独立临时库:不能先打开真实库,也不能沿用 --data-dir。
|
|
137
|
+
if (cmd === "demo") {
|
|
138
|
+
const res = runDemo({ out: args.out });
|
|
139
|
+
if (asJson) print(res, true);
|
|
140
|
+
else {
|
|
141
|
+
const by = res.stats?.byLayer ?? {};
|
|
142
|
+
const lines = [
|
|
143
|
+
"Memorytree 演示库(隔离,不影响真实记忆)",
|
|
144
|
+
"",
|
|
145
|
+
`临时目录:${res.dir}`,
|
|
146
|
+
`主干文件:${res.agentsPath}`,
|
|
147
|
+
`记忆库:${res.dbFile}`,
|
|
148
|
+
`主干同步:${res.sync.rules ?? 0} 条规则(added ${res.sync.added ?? 0})`,
|
|
149
|
+
`四枝条目:主干 ${by.trunk ?? 0} / 情感 ${by.emotion ?? 0} / 任务 ${by.task ?? 0} / 判断叶 ${by.leaf ?? 0}`,
|
|
150
|
+
`看板:${res.reportPath}`,
|
|
151
|
+
"",
|
|
152
|
+
"用浏览器打开上面的 HTML 即可;这个目录可以随时删除。",
|
|
153
|
+
];
|
|
154
|
+
print(lines.join("\n"));
|
|
155
|
+
}
|
|
156
|
+
return res.ok ? 0 : 1;
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
// init 只写 AGENTS.md 正本,不先打开真实库;默认不覆盖已有文件。
|
|
160
|
+
if (cmd === "init") {
|
|
161
|
+
const rt = makeRuntime(args);
|
|
162
|
+
const target = rt.paths.agentsPath;
|
|
163
|
+
const template = fileURLToPath(new URL("../examples/AGENTS.template.md", import.meta.url));
|
|
164
|
+
if (!fs.existsSync(template)) {
|
|
165
|
+
const err = { ok: false, error: "找不到起步模板:" + template };
|
|
166
|
+
if (asJson) print(err, true);
|
|
167
|
+
else print("初始化失败:" + err.error);
|
|
168
|
+
return 1;
|
|
169
|
+
}
|
|
170
|
+
if (fs.existsSync(target) && args.force !== true) {
|
|
171
|
+
const err = {
|
|
172
|
+
ok: false,
|
|
173
|
+
error: "AGENTS.md 已存在,未覆盖:" + target + "(确需覆盖请加 --force;会先备份)",
|
|
174
|
+
};
|
|
175
|
+
if (asJson) print(err, true);
|
|
176
|
+
else print(err.error);
|
|
177
|
+
return 1;
|
|
178
|
+
}
|
|
179
|
+
let backup = null;
|
|
180
|
+
try {
|
|
181
|
+
fs.mkdirSync(path.dirname(target), { recursive: true });
|
|
182
|
+
if (fs.existsSync(target) && args.force === true) {
|
|
183
|
+
const stamp = new Date().toISOString().replace(/[:.]/g, "-");
|
|
184
|
+
backup = target + ".bak-" + stamp;
|
|
185
|
+
fs.copyFileSync(target, backup);
|
|
186
|
+
}
|
|
187
|
+
fs.copyFileSync(template, target);
|
|
188
|
+
} catch (err) {
|
|
189
|
+
const out = { ok: false, error: "写 AGENTS.md 失败:" + (err?.message ?? String(err)), path: target };
|
|
190
|
+
if (asJson) print(out, true);
|
|
191
|
+
else print(out.error);
|
|
192
|
+
return 1;
|
|
193
|
+
}
|
|
194
|
+
const sync = rt.ensureTrunk(null, { force: true });
|
|
195
|
+
const out = {
|
|
196
|
+
ok: sync.ok === true,
|
|
197
|
+
path: target,
|
|
198
|
+
backup,
|
|
199
|
+
sync,
|
|
200
|
+
message: sync.ok === true
|
|
201
|
+
? "已创建 AGENTS.md 并同步 " + (sync.rules ?? 0) + " 条主干规则。"
|
|
202
|
+
: "已创建 AGENTS.md,但同步失败:" + (sync.reason || sync.error || "未知原因"),
|
|
203
|
+
};
|
|
204
|
+
if (asJson) print(out, true);
|
|
205
|
+
else {
|
|
206
|
+
print(out.message);
|
|
207
|
+
if (backup) print("原文件已备份:" + backup);
|
|
208
|
+
print("下一步:按注释把 <...> 换成真实值,再运行 node bin/mt.mjs sync --force");
|
|
209
|
+
}
|
|
210
|
+
return out.ok ? 0 : 1;
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
// migrate 的 --db 指的是“旧库路径”,不能把它当成当前记忆库打开。
|
|
214
|
+
const runtimeArgs = { ...args };
|
|
215
|
+
if (cmd === "migrate") delete runtimeArgs.db;
|
|
216
|
+
const rt = makeRuntime(runtimeArgs);
|
|
217
|
+
const store = rt.open();
|
|
218
|
+
|
|
219
|
+
switch (cmd) {
|
|
220
|
+
case "doctor": {
|
|
221
|
+
const sync = fs.existsSync(rt.paths.agentsPath) ? rt.ensureTrunk(null, { force: true }) : { ok: true, skipped: true, reason: "未找到 AGENTS.md,已跳过主干同步" };
|
|
222
|
+
const info = rt.info();
|
|
223
|
+
const warnings = [];
|
|
224
|
+
const checks = [];
|
|
225
|
+
checks.push({ name: "数据目录", ok: fs.existsSync(rt.paths.dataDir), detail: rt.paths.dataDir });
|
|
226
|
+
checks.push({ name: "记忆库", ok: fs.existsSync(rt.paths.dbFile), detail: rt.paths.dbFile });
|
|
227
|
+
const agentsOk = info.agentsExists === true;
|
|
228
|
+
if (!agentsOk) warnings.push("未找到 AGENTS.md:" + rt.paths.agentsPath + "(可选;创建后可运行 sync)");
|
|
229
|
+
checks.push({ name: "主干文件", ok: true, detail: agentsOk ? rt.paths.agentsPath : "未找到(可选,不影响库)" });
|
|
230
|
+
if (!info.legacyExists) warnings.push("没有旧库 memories.db(正常,全新安装不需要迁移)");
|
|
231
|
+
checks.push({ name: "旧库(可迁移)", ok: true, detail: info.legacyExists ? rt.paths.legacyDb : "不存在(正常)" });
|
|
232
|
+
if (sync.ok !== true) warnings.push("主干同步失败:" + (sync.reason || "未知原因"));
|
|
233
|
+
checks.push({ name: "主干同步", ok: sync.ok === true, detail: sync.ok ? (sync.skipped ? sync.reason : `${sync.rules ?? sync.unchanged ?? 0} 条规则,changed=${sync.changed}`) : sync.reason });
|
|
234
|
+
const st = info.stats;
|
|
235
|
+
const report = {
|
|
236
|
+
version: pluginVersion(),
|
|
237
|
+
node: process.version,
|
|
238
|
+
paths: rt.paths,
|
|
239
|
+
checks,
|
|
240
|
+
warnings,
|
|
241
|
+
stats: st,
|
|
242
|
+
ok: checks.every((c) => c.ok),
|
|
243
|
+
};
|
|
244
|
+
if (asJson) print(report, true);
|
|
245
|
+
else {
|
|
246
|
+
const lines = ["记忆树自检", ""];
|
|
247
|
+
for (const c of checks) lines.push(`${c.ok ? "✔" : "✖"} ${c.name}:${c.detail}`);
|
|
248
|
+
for (const w of warnings) lines.push(`提醒:${w}`);
|
|
249
|
+
lines.push("", `条目:${st.total}(active ${st.byStatus?.active ?? 0} / candidate ${st.byStatus?.candidate ?? 0} / superseded ${st.byStatus?.superseded ?? 0} / archived ${st.byStatus?.archived ?? 0})`);
|
|
250
|
+
lines.push(`库大小:${(info.dbBytes / 1024).toFixed(1)} KB`);
|
|
251
|
+
print(lines.join("\n"));
|
|
252
|
+
}
|
|
253
|
+
return report.ok ? 0 : 2;
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
case "stats": {
|
|
257
|
+
const st = store.stats();
|
|
258
|
+
if (asJson) print(st, true);
|
|
259
|
+
else {
|
|
260
|
+
const lines = [`条目 ${st.total}(${fmtTime(st.newestAt)} 最新)`];
|
|
261
|
+
const byLayer = st.byLayer ?? {};
|
|
262
|
+
for (const l of LAYERS) lines.push(` ${layerLabel(l)}:${byLayer[l] ?? 0}`);
|
|
263
|
+
const byStatus = st.byStatus ?? {};
|
|
264
|
+
lines.push("状态:" + STATUSES.map((s) => `${s} ${byStatus[s] ?? 0}`).join(" / "));
|
|
265
|
+
lines.push("作用域:" + Object.entries(st.byScope ?? {}).map(([k, v]) => `${k} ${v}`).join(" / "));
|
|
266
|
+
lines.push(`日记:${st.diaryTotal ?? 0} 条` + (st.diaryLastDate ? `(最近 ${st.diaryLastDate})` : ""));
|
|
267
|
+
print(lines.join("\n"));
|
|
268
|
+
}
|
|
269
|
+
return 0;
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
case "sync": {
|
|
273
|
+
const res = rt.ensureTrunk(null, { force: args.force === true });
|
|
274
|
+
print(res, asJson);
|
|
275
|
+
return res.ok ? 0 : 1;
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
case "migrate": {
|
|
279
|
+
const legacyFile = args.db ? String(args.db) : rt.paths.legacyDb;
|
|
280
|
+
if (!fs.existsSync(legacyFile)) {
|
|
281
|
+
print({ ok: false, reason: "旧库不存在:" + legacyFile }, asJson);
|
|
282
|
+
return 1;
|
|
283
|
+
}
|
|
284
|
+
const apply = args.apply === true;
|
|
285
|
+
const res = importLegacy(store, legacyFile, { scope: "user", dryRun: !apply });
|
|
286
|
+
if (res.ok && apply) {
|
|
287
|
+
try { rt.exportCards(); } catch { /* 快照失败不影响迁移结果 */ }
|
|
288
|
+
}
|
|
289
|
+
print(res, asJson);
|
|
290
|
+
return res.ok ? 0 : 1;
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
case "search": {
|
|
294
|
+
const query = args._[1] ?? args.query;
|
|
295
|
+
if (!query) {
|
|
296
|
+
print({ ok: false, reason: "缺少关键词,例如:mt search \"记忆树\"" }, asJson);
|
|
297
|
+
return 1;
|
|
298
|
+
}
|
|
299
|
+
const sc = resolveScope(rt, args.scope);
|
|
300
|
+
const layers = splitList(args.layer);
|
|
301
|
+
const res = searchMemory(store, {
|
|
302
|
+
query: String(query),
|
|
303
|
+
scopes: sc.scopes,
|
|
304
|
+
layers: layers.length ? layers : undefined,
|
|
305
|
+
limit: Number(args.limit ?? 8),
|
|
306
|
+
mode: String(args.mode ?? "hybrid"),
|
|
307
|
+
status: args["include-archived"] === true ? undefined : ["active", "candidate"],
|
|
308
|
+
});
|
|
309
|
+
if (asJson) print(res, true);
|
|
310
|
+
else if (res.empty) {
|
|
311
|
+
print(`没有命中(${res.reason})。记忆树里没有与「${query}」匹配的条目——不编造。`);
|
|
312
|
+
} else {
|
|
313
|
+
const lines = [`命中 ${res.hits.length} 条(${res.mode},作用域 ${sc.scopes.join(" + ")})`];
|
|
314
|
+
for (const h of res.hits) {
|
|
315
|
+
lines.push("", `#${h.id} [${layerLabel(h.layer)}] ${h.title || h.subject || "(无标题)"} · 分数 ${Number(h.relevance ?? 0).toFixed(3)}${h.expired ? " · 已过期" : ""}`);
|
|
316
|
+
lines.push(` ${h.snippet || h.text.slice(0, 160)}`);
|
|
317
|
+
lines.push(` uid ${h.uid}${h.source ? " · 来源 " + h.source : ""}`);
|
|
318
|
+
}
|
|
319
|
+
print(lines.join("\n"));
|
|
320
|
+
}
|
|
321
|
+
return res.empty ? 3 : 0;
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
case "add": {
|
|
325
|
+
const layer = String(args.layer ?? "leaf");
|
|
326
|
+
if (!LAYERS.includes(layer)) {
|
|
327
|
+
print({ ok: false, reason: "layer 只能是 " + LAYERS.join("/") }, asJson);
|
|
328
|
+
return 1;
|
|
329
|
+
}
|
|
330
|
+
const text = args.text ?? args._.slice(1).join(" ");
|
|
331
|
+
if (!text) {
|
|
332
|
+
print({ ok: false, reason: "缺少 --text" }, asJson);
|
|
333
|
+
return 1;
|
|
334
|
+
}
|
|
335
|
+
const scopeArg = args.scope === undefined ? null : String(args.scope);
|
|
336
|
+
if (scopeArg !== null && scopeArg !== "user" && scopeArg !== "workspace") {
|
|
337
|
+
print({ ok: false, reason: "scope 只能是 user/workspace:" + scopeArg }, asJson);
|
|
338
|
+
return 1;
|
|
339
|
+
}
|
|
340
|
+
const scope = scopeArg === "user" ? "user" : scopeArg === "workspace" ? rt.workspaceOf(null).scope : rt.defaultScope(layer, null);
|
|
341
|
+
const res = store.add({
|
|
342
|
+
layer,
|
|
343
|
+
scope,
|
|
344
|
+
text: String(text),
|
|
345
|
+
subject: args.subject ? String(args.subject) : null,
|
|
346
|
+
title: args.title ? String(args.title) : null,
|
|
347
|
+
tags: splitList(args.tags),
|
|
348
|
+
evidence: args.evidence ? String(args.evidence) : null,
|
|
349
|
+
importance: args.importance !== undefined ? Number(args.importance) : undefined,
|
|
350
|
+
halfLifeDays: args["half-life"] !== undefined ? Number(args["half-life"]) : undefined,
|
|
351
|
+
validUntil: args["valid-until"] ? Date.parse(String(args["valid-until"])) : null,
|
|
352
|
+
});
|
|
353
|
+
print({ ok: true, duplicate: res.duplicate === true, node: res.node }, asJson);
|
|
354
|
+
return 0;
|
|
355
|
+
}
|
|
356
|
+
|
|
357
|
+
case "list": {
|
|
358
|
+
const sc = resolveScope(rt, args.scope);
|
|
359
|
+
const layers = splitList(args.layer);
|
|
360
|
+
const status = splitList(args.status);
|
|
361
|
+
const badLayer = layers.find((x) => !LAYERS.includes(x));
|
|
362
|
+
if (badLayer) {
|
|
363
|
+
print({ ok: false, reason: "未知 layer:" + badLayer + "(可选 " + LAYERS.join("/") + ")" }, asJson);
|
|
364
|
+
return 1;
|
|
365
|
+
}
|
|
366
|
+
const badStatus = status.find((x) => !STATUSES.includes(x));
|
|
367
|
+
if (badStatus) {
|
|
368
|
+
print({ ok: false, reason: "未知 status:" + badStatus + "(可选 " + STATUSES.join("/") + ")" }, asJson);
|
|
369
|
+
return 1;
|
|
370
|
+
}
|
|
371
|
+
const rows = store.list({
|
|
372
|
+
scope: sc.scopes,
|
|
373
|
+
layers: layers.length ? layers : undefined,
|
|
374
|
+
status: status.length ? status : ["active", "candidate"],
|
|
375
|
+
limit: Number(args.limit ?? 20),
|
|
376
|
+
order: args.order ? String(args.order) : "updated",
|
|
377
|
+
});
|
|
378
|
+
if (asJson) print(rows, true);
|
|
379
|
+
else {
|
|
380
|
+
const lines = [`${rows.length} 条(作用域 ${sc.scopes.join(" + ")})`];
|
|
381
|
+
for (const n of rows) lines.push(`#${n.id} [${layerLabel(n.layer)}/${n.status}] ${n.title || n.subject || ""} · ${n.text.replace(/\s+/g, " ").slice(0, 100)}`);
|
|
382
|
+
print(lines.join("\n"));
|
|
383
|
+
}
|
|
384
|
+
return 0;
|
|
385
|
+
}
|
|
386
|
+
|
|
387
|
+
case "card": {
|
|
388
|
+
const sc = resolveScope(rt, args.scope);
|
|
389
|
+
if (args.id) {
|
|
390
|
+
const n = store.get(Number(args.id) || args.id, { scope: sc.scopes });
|
|
391
|
+
if (!n) {
|
|
392
|
+
print({ ok: false, reason: "找不到 #" + args.id + "(或它不在当前作用域)" }, asJson);
|
|
393
|
+
return 1;
|
|
394
|
+
}
|
|
395
|
+
const related = searchMemory(store, { query: n.text.slice(0, 40), scopes: [n.scope], limit: 6, status: ["active", "candidate"] });
|
|
396
|
+
print(asJson ? { node: n, related: related.hits } : formatCard(n, related.hits), asJson);
|
|
397
|
+
return 0;
|
|
398
|
+
}
|
|
399
|
+
const subject = args.subject;
|
|
400
|
+
if (!subject) {
|
|
401
|
+
print({ ok: false, reason: "需要 --subject 或 --id" }, asJson);
|
|
402
|
+
return 1;
|
|
403
|
+
}
|
|
404
|
+
const rows = store.list({ scope: sc.scopes, layers: ["task"], status: ["active", "candidate"], subject: String(subject), limit: 5, order: "updated" });
|
|
405
|
+
const card = rows[0] ?? null;
|
|
406
|
+
print(asJson ? { subject, card } : card ? formatCard(card, []) : `没有「${subject}」的任务卡。`, asJson);
|
|
407
|
+
return card ? 0 : 3;
|
|
408
|
+
}
|
|
409
|
+
|
|
410
|
+
case "tree": {
|
|
411
|
+
const sc = resolveScope(rt, args.scope);
|
|
412
|
+
const tree = store.tree({ scopes: sc.scopes });
|
|
413
|
+
if (asJson) print(tree, true);
|
|
414
|
+
else {
|
|
415
|
+
const lines = [`作用域 ${sc.scopes.join(" + ")}`];
|
|
416
|
+
for (const bucket of tree.layers ?? []) {
|
|
417
|
+
lines.push("", `${layerLabel(bucket.layer)}(active ${bucket.active})`);
|
|
418
|
+
for (const n of bucket.items.slice(0, Number(args.limit ?? 12))) lines.push(` #${n.id} ${n.title || n.subject || ""} · ${n.preview.slice(0, 80)}`);
|
|
419
|
+
}
|
|
420
|
+
if (tree.candidates?.length) {
|
|
421
|
+
lines.push("", `主干候选(${tree.candidates.length})`);
|
|
422
|
+
for (const c of tree.candidates.slice(0, Number(args.limit ?? 12))) lines.push(` #${c.id} ${c.title} ← ${c.source}`);
|
|
423
|
+
}
|
|
424
|
+
print(lines.join("\n"));
|
|
425
|
+
}
|
|
426
|
+
return 0;
|
|
427
|
+
}
|
|
428
|
+
|
|
429
|
+
case "daily": {
|
|
430
|
+
const sc = resolveScope(rt, args.scope);
|
|
431
|
+
const rep = buildDailyReport(store, { scopes: sc.scopes, hours: Number(args.hours ?? 24), limit: Number(args.limit ?? 30) });
|
|
432
|
+
if (asJson) print(rep, true);
|
|
433
|
+
else {
|
|
434
|
+
const lines = [`待分拣 ${rep.pendingCount} 条(最近 ${rep.hours} 小时;更早未分拣 ${rep.pendingOlderThanWindow} 条)`];
|
|
435
|
+
for (const it of rep.items) lines.push(`#${it.id} ${it.text.slice(0, 120)}${it.tags.length ? " · " + it.tags.join(",") : ""}`);
|
|
436
|
+
if (rep.clusters.length) lines.push("", "聚类:" + rep.clusters.map((c) => `${c.key}(${c.ids.length})`).join(" "));
|
|
437
|
+
if (rep.staleCards.length) lines.push("", "陈旧任务卡:" + rep.staleCards.map((c) => `${c.subject}(${c.days}天)`).join(" "));
|
|
438
|
+
if (rep.expired.length) lines.push("过期:" + rep.expired.map((e) => `#${e.id} ${e.title}`).join(" "));
|
|
439
|
+
print(lines.join("\n"));
|
|
440
|
+
}
|
|
441
|
+
return 0;
|
|
442
|
+
}
|
|
443
|
+
|
|
444
|
+
case "apply": {
|
|
445
|
+
if (!args.file) {
|
|
446
|
+
print({ ok: false, reason: "需要 --file 决定.json" }, asJson);
|
|
447
|
+
return 1;
|
|
448
|
+
}
|
|
449
|
+
let decisions;
|
|
450
|
+
try {
|
|
451
|
+
decisions = JSON.parse(fs.readFileSync(String(args.file), "utf8"));
|
|
452
|
+
} catch (err) {
|
|
453
|
+
print({ ok: false, reason: "读取或解析决定文件失败:" + (err?.message ?? String(err)) }, asJson);
|
|
454
|
+
return 1;
|
|
455
|
+
}
|
|
456
|
+
const list = Array.isArray(decisions) ? decisions : decisions.decisions;
|
|
457
|
+
if (!Array.isArray(list)) {
|
|
458
|
+
print({ ok: false, reason: "文件里需要数组,或 {decisions:[...]}" }, asJson);
|
|
459
|
+
return 1;
|
|
460
|
+
}
|
|
461
|
+
const sc = resolveScope(rt, args.scope);
|
|
462
|
+
const applied = applyDailyDecisions(store, list, { scopes: sc.scopes });
|
|
463
|
+
if (applied.applied > 0) {
|
|
464
|
+
try { rt.exportCards(); } catch { /* 快照失败不影响分拣结果 */ }
|
|
465
|
+
}
|
|
466
|
+
print(applied, asJson);
|
|
467
|
+
return 0;
|
|
468
|
+
}
|
|
469
|
+
|
|
470
|
+
case "forget": {
|
|
471
|
+
const ids = splitList(args.ids).map(Number).filter(Number.isFinite);
|
|
472
|
+
if (!ids.length) {
|
|
473
|
+
print({ ok: false, reason: "需要 --ids 1,2,3" }, asJson);
|
|
474
|
+
return 1;
|
|
475
|
+
}
|
|
476
|
+
const res = ids.map((id) => {
|
|
477
|
+
try {
|
|
478
|
+
return { id, ok: true, ...store.forget(id, { hard: args.hard === true, reason: String(args.reason ?? "cli forget") }) };
|
|
479
|
+
} catch (err) {
|
|
480
|
+
return { id, ok: false, error: err?.message ?? String(err) };
|
|
481
|
+
}
|
|
482
|
+
});
|
|
483
|
+
print({ ok: res.every((r) => r.ok), results: res }, asJson);
|
|
484
|
+
return res.every((r) => r.ok) ? 0 : 1;
|
|
485
|
+
}
|
|
486
|
+
|
|
487
|
+
case "reindex": {
|
|
488
|
+
print(store.reindexAll(), asJson);
|
|
489
|
+
return 0;
|
|
490
|
+
}
|
|
491
|
+
|
|
492
|
+
case "export": {
|
|
493
|
+
const text = store.exportJsonl();
|
|
494
|
+
const out = args.out ? String(args.out) : path.join(rt.paths.exportDir, `memory-${Date.now()}.jsonl`);
|
|
495
|
+
fs.mkdirSync(path.dirname(out), { recursive: true });
|
|
496
|
+
fs.writeFileSync(out, text, "utf8");
|
|
497
|
+
print({ ok: true, out, bytes: Buffer.byteLength(text) }, asJson);
|
|
498
|
+
return 0;
|
|
499
|
+
}
|
|
500
|
+
|
|
501
|
+
case "import": {
|
|
502
|
+
if (!args.file) {
|
|
503
|
+
print({ ok: false, reason: "需要 --file 文件.jsonl" }, asJson);
|
|
504
|
+
return 1;
|
|
505
|
+
}
|
|
506
|
+
const file = String(args.file);
|
|
507
|
+
const size = fs.statSync(file).size;
|
|
508
|
+
if (size > 50 * 1024 * 1024) {
|
|
509
|
+
print({ ok: false, reason: "导入文件超过 50 MB 上限:" + size + " 字节" }, asJson);
|
|
510
|
+
return 1;
|
|
511
|
+
}
|
|
512
|
+
const res = store.importJsonl(fs.readFileSync(file, "utf8"));
|
|
513
|
+
print(res, asJson);
|
|
514
|
+
return 0;
|
|
515
|
+
}
|
|
516
|
+
|
|
517
|
+
case "diary": {
|
|
518
|
+
const op = args._[1] ?? "auto";
|
|
519
|
+
const date = args.date ? String(args.date) : localDate(store.now());
|
|
520
|
+
if (op === "auto") {
|
|
521
|
+
const res = store.diaryAuto(date, { force: args.force === true, dbFile: rt.paths.dbFile, agentsPath: rt.paths.agentsPath, scopes: resolveScope(rt, args.scope).scopes });
|
|
522
|
+
if (asJson) print({ ok: true, op, date, ...res }, true);
|
|
523
|
+
else if (res.skipped) print(`未覆盖 ${date}:${res.reason}`);
|
|
524
|
+
else print(res.record.text);
|
|
525
|
+
return res.skipped ? 0 : 0;
|
|
526
|
+
}
|
|
527
|
+
if (op === "add" || op === "write") {
|
|
528
|
+
if (!args.text) {
|
|
529
|
+
print({ ok: false, reason: "需要 --text \"日记正文\"" }, asJson);
|
|
530
|
+
return 1;
|
|
531
|
+
}
|
|
532
|
+
const rec = store.diaryAdd(date, String(args.text), String(args.mood ?? "manual"));
|
|
533
|
+
print(asJson ? { ok: true, op: "add", record: rec } : `已写入 ${rec.date} 日记(${rec.text.length} 字)`, asJson);
|
|
534
|
+
return 0;
|
|
535
|
+
}
|
|
536
|
+
if (op === "get") {
|
|
537
|
+
const rec = store.diaryGet(date);
|
|
538
|
+
print(asJson ? { ok: true, op, date, record: rec } : rec ? rec.text : `${date} 还没有日记。`, asJson);
|
|
539
|
+
return 0;
|
|
540
|
+
}
|
|
541
|
+
if (op === "list") {
|
|
542
|
+
const rows = store.diaryList(Number(args.limit) || 30);
|
|
543
|
+
if (asJson) print({ ok: true, op, rows }, true);
|
|
544
|
+
else if (!rows.length) print("还没有日记。");
|
|
545
|
+
else print(rows.map((r) => `${r.date}(${r.mood === "manual" ? "手写" : "自动"})\n${r.text}`).join("\n\n"));
|
|
546
|
+
return 0;
|
|
547
|
+
}
|
|
548
|
+
print({ ok: false, reason: "未知 diary 子命令:" + op + "(auto|get|list|add)" }, asJson);
|
|
549
|
+
return 1;
|
|
550
|
+
}
|
|
551
|
+
|
|
552
|
+
case "report": {
|
|
553
|
+
const html = buildReportHtml(rt, store, null);
|
|
554
|
+
const out = args.out ? String(args.out) : rt.paths.reportFile;
|
|
555
|
+
fs.mkdirSync(path.dirname(out), { recursive: true });
|
|
556
|
+
fs.writeFileSync(out, html, "utf8");
|
|
557
|
+
print({ ok: true, out, bytes: Buffer.byteLength(html) }, asJson);
|
|
558
|
+
return 0;
|
|
559
|
+
}
|
|
560
|
+
|
|
561
|
+
default:
|
|
562
|
+
print({ ok: false, reason: "未知命令:" + cmd + "(mt help 看用法)" }, asJson);
|
|
563
|
+
return 1;
|
|
564
|
+
}
|
|
565
|
+
}
|
|
566
|
+
|
|
567
|
+
function formatCard(n, related) {
|
|
568
|
+
const lines = [
|
|
569
|
+
`#${n.id} [${layerLabel(n.layer)}/${n.status}] ${n.title || n.subject || ""}`,
|
|
570
|
+
`作用域 ${n.scope} · uid ${n.uid}`,
|
|
571
|
+
n.subject ? `卡片 ${n.subject}` : "",
|
|
572
|
+
n.source ? `来源 ${n.source}` : "",
|
|
573
|
+
"",
|
|
574
|
+
n.text,
|
|
575
|
+
].filter((x) => x !== "");
|
|
576
|
+
if (related && related.length) {
|
|
577
|
+
lines.push("", "相关:");
|
|
578
|
+
for (const h of related) lines.push(` #${h.id} ${layerLabel(h.layer)} · ${h.text.replace(/\s+/g, " ").slice(0, 80)}`);
|
|
579
|
+
}
|
|
580
|
+
return lines.join("\n");
|
|
581
|
+
}
|
|
582
|
+
|
|
583
|
+
main()
|
|
584
|
+
.then((code) => process.exit(code))
|
|
585
|
+
.catch((err) => {
|
|
586
|
+
const text = err instanceof CliError ? err.message : err && err.stack ? err.stack : String(err);
|
|
587
|
+
process.stderr.write(text + "\n");
|
|
588
|
+
process.exit(1);
|
|
589
|
+
});
|