fde-console 0.0.0-stage → 2.9.68

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.
Files changed (85) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +128 -2
  3. package/README.zh-CN.md +130 -0
  4. package/assets/icon.svg +9 -0
  5. package/cordis.patch.yml +7 -0
  6. package/lib/agentActivity.js +1180 -0
  7. package/lib/agentContext.js +146 -0
  8. package/lib/agentTranscript.js +1398 -0
  9. package/lib/analyze.js +625 -0
  10. package/lib/attribute.js +205 -0
  11. package/lib/backup.js +366 -0
  12. package/lib/desktopAgents.js +123 -0
  13. package/lib/diary.js +333 -0
  14. package/lib/dingtalk.js +412 -0
  15. package/lib/feishu.js +580 -0
  16. package/lib/giteaClient.js +810 -0
  17. package/lib/giteeClient.js +372 -0
  18. package/lib/githubClient.js +361 -0
  19. package/lib/heatmap.js +99 -0
  20. package/lib/imNotify.js +378 -0
  21. package/lib/inbox.js +438 -0
  22. package/lib/instanceLock.js +122 -0
  23. package/lib/jobs.js +56 -0
  24. package/lib/learn.js +1388 -0
  25. package/lib/learnImport.js +283 -0
  26. package/lib/learnSeeds.js +97 -0
  27. package/lib/learnSeedsAiEng.js +77 -0
  28. package/lib/mcpCore.js +135 -0
  29. package/lib/members.js +160 -0
  30. package/lib/migration.js +403 -0
  31. package/lib/overview.js +376 -0
  32. package/lib/postmortem.js +148 -0
  33. package/lib/radarIgnore.js +134 -0
  34. package/lib/redact.js +76 -0
  35. package/lib/router.js +246 -0
  36. package/lib/routes-gitea.js +262 -0
  37. package/lib/routes-setup.js +40 -0
  38. package/lib/scorecard.js +111 -0
  39. package/lib/sessionRef.js +227 -0
  40. package/lib/sessionSnapshot.js +67 -0
  41. package/lib/sessionSuggest.js +186 -0
  42. package/lib/settings.js +783 -0
  43. package/lib/setupCheck.js +330 -0
  44. package/lib/ssrfGuard.js +145 -0
  45. package/lib/store.js +564 -0
  46. package/lib/storeDb.js +418 -0
  47. package/lib/taskEvents.js +243 -0
  48. package/lib/webhookOut.js +125 -0
  49. package/lib/weekly.js +439 -0
  50. package/lib/workSearch.js +220 -0
  51. package/locale/en.json +6 -0
  52. package/locale/zh.json +6 -0
  53. package/package.json +46 -4
  54. package/plugin/adapter.js +157 -0
  55. package/plugin/client.js +282 -0
  56. package/plugin/index.mjs +116 -0
  57. package/plugin/static.js +99 -0
  58. package/scripts/backup-data.js +41 -0
  59. package/scripts/mcp-server.mjs +68 -0
  60. package/scripts/migrate-data.js +301 -0
  61. package/scripts/migrate-storage.js +47 -0
  62. package/scripts/seed-demo.js +200 -0
  63. package/scripts/write-agent-context.js +43 -0
  64. package/test/helpers/appAssembler.js +1078 -0
  65. package/web/client/fde-client.js +292 -0
  66. package/web/css/app.css +1510 -0
  67. package/web/index.html +69 -0
  68. package/web/js/api.js +72 -0
  69. package/web/js/app.js +313 -0
  70. package/web/js/icons.js +48 -0
  71. package/web/js/mock.js +1150 -0
  72. package/web/js/state.js +7 -0
  73. package/web/js/ui.js +276 -0
  74. package/web/js/views/activity.js +410 -0
  75. package/web/js/views/agents.js +892 -0
  76. package/web/js/views/board.js +1656 -0
  77. package/web/js/views/learn.js +530 -0
  78. package/web/js/views/members.js +344 -0
  79. package/web/js/views/onboarding.js +103 -0
  80. package/web/js/views/overview.js +508 -0
  81. package/web/js/views/radar.js +1359 -0
  82. package/web/js/views/search.js +149 -0
  83. package/web/js/views/settings.js +1351 -0
  84. package/web/js/views/topology.js +471 -0
  85. package/web/mock.json +2363 -0
package/lib/learn.js ADDED
@@ -0,0 +1,1388 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * learn.js — v2.9.44 知识库学习模式(只读 vault + 交互式学习 + 遗忘曲线调度)
5
+ *
6
+ * 契约见 docs/SPEC-LEARN.md。三条不可违背:
7
+ * ① **vault 只读**:本模块对 `learn.root` 只有 readdir/stat/readFile,**没有任何写/删调用**;
8
+ * 全部产出落 `data/learn/`(items/schedule/sessions/scan)。
9
+ * ② **先测后学**:建会话的响应里不含材料正文;必须先提交 recall 才拿得到 digest。
10
+ * ③ **引擎失败可降级**:dsh 不可用/超时 → 会话标 `degraded:true`,按"自评"继续,绝不卡死。
11
+ *
12
+ * 调度是纯函数(输入 item+评分+now → 新状态),可表驱动测试、不依赖系统时钟。
13
+ */
14
+
15
+ const crypto = require('node:crypto');
16
+ const fs = require('node:fs');
17
+ const path = require('node:path');
18
+
19
+ const store = require('./store');
20
+ const storeDb = require('./storeDb');
21
+ const { HttpError, sendJSON } = require('./router');
22
+ const analyze = require('./analyze');
23
+ const seedsLib = require('./learnSeeds');
24
+
25
+ const LADDER = [1, 3, 7, 16, 35]; // 间隔阶梯(天),与 vault 题库的 1/2/4/8/16 同构但更缓
26
+ const DECAY_DAYS = 90; // 长期不复习且掌握度≤1 → 当新条目重学
27
+ const MAX_SCAN_FILES = 2000;
28
+ const MAX_SESSIONS = 500;
29
+
30
+ // ---------- 小工具 ----------
31
+
32
+ function pad2(n) {
33
+ return String(n).padStart(2, '0');
34
+ }
35
+
36
+ /** 本地日期 YYYY-MM-DD(用本地时区,跨日判断跟用户感知一致) */
37
+ function ymd(date) {
38
+ const d = date instanceof Date ? date : new Date(date);
39
+ return `${d.getFullYear()}-${pad2(d.getMonth() + 1)}-${pad2(d.getDate())}`;
40
+ }
41
+
42
+ function addDays(ymdStr, days) {
43
+ const [y, m, d] = ymdStr.split('-').map(Number);
44
+ const dt = new Date(y, m - 1, d, 12, 0, 0); // 中午锚点,避开夏令时/边界
45
+ dt.setDate(dt.getDate() + days);
46
+ return ymd(dt);
47
+ }
48
+
49
+ function itemId(sourcePath) {
50
+ return `L-${crypto.createHash('sha1').update(String(sourcePath)).digest('hex').slice(0, 10)}`;
51
+ }
52
+
53
+ function learnDir(ctx) {
54
+ return path.join(ctx.dataDir, 'learn');
55
+ }
56
+
57
+ function fileOf(ctx, name) {
58
+ return path.join(learnDir(ctx), name);
59
+ }
60
+
61
+ function learnCfg(ctx) {
62
+ return (ctx && ctx.config && ctx.config.learn) || {};
63
+ }
64
+
65
+ // ---------- 配置与根路径校验(只读) ----------
66
+
67
+ /**
68
+ * 根路径校验(v2.9.55 放宽):只要求 **绝对路径 + 存在 + 目录**。
69
+ * 是否 LLM Wiki 只作为 `flavor` 提示,不再硬拦——别人的库可能是 Obsidian 目录、
70
+ * 文档导出、普通 Markdown 仓库;拿"缺少 AGENTS.md"当拒绝理由是产品缺陷。
71
+ */
72
+ function validateRoot(raw) {
73
+ const root = typeof raw === 'string' ? raw.trim() : '';
74
+ if (!root) return { ok: false, reason: '未配置知识库根路径' };
75
+ if (!path.isAbsolute(root)) return { ok: false, reason: '根路径必须是绝对路径' };
76
+ let st;
77
+ try {
78
+ st = fs.statSync(root);
79
+ } catch (e) {
80
+ return { ok: false, reason: `根路径不存在或不可读:${root}` };
81
+ }
82
+ if (!st.isDirectory()) return { ok: false, reason: '根路径不是目录' };
83
+ const resolved = path.resolve(root);
84
+ let flavor = 'generic';
85
+ try {
86
+ const agents = fs.readFileSync(path.join(resolved, 'AGENTS.md'), 'utf8');
87
+ if (/LLM[\s-]*Wiki/i.test(agents)) flavor = 'llm-wiki';
88
+ } catch (e) {
89
+ /* 没有 AGENTS.md 也合法:按普通 Markdown 库处理 */
90
+ }
91
+ const warnings = flavor === 'generic'
92
+ ? ['未检测到 LLM Wiki 标记(AGENTS.md):按普通 Markdown 库处理,只读取 .md']
93
+ : [];
94
+ return { ok: true, root: resolved, flavor, warnings };
95
+ }
96
+
97
+ const MAX_PROBE_FILES = 5000;
98
+
99
+ /**
100
+ * 只读探测(初始化向导用):看清一个陌生目录里"有什么、会被怎么处理",**不写任何东西**。
101
+ * 返回 md 数、顶层目录分布、会被过滤掉的比例(_前缀/README/outputs/en.md)、样本路径。
102
+ */
103
+ function probeRoot(raw) {
104
+ const check = validateRoot(raw);
105
+ if (!check.ok) return { ok: false, reason: check.reason, root: typeof raw === 'string' ? raw : '' };
106
+ const root = check.root;
107
+ const filtered = { underscore: 0, readme: 0, outputs: 0, en: 0 };
108
+ const dirs = new Map();
109
+ const samples = [];
110
+ let md = 0;
111
+
112
+ const walk = (relDir) => {
113
+ let entries;
114
+ try {
115
+ entries = fs.readdirSync(path.join(root, relDir), { withFileTypes: true });
116
+ } catch (e) {
117
+ return;
118
+ }
119
+ for (const ent of entries) {
120
+ if (md >= MAX_PROBE_FILES) return;
121
+ if (!ent || ent.name.startsWith('.')) continue;
122
+ if (ent.name.startsWith('_')) {
123
+ if (ent.isFile() && ent.name.toLowerCase().endsWith('.md')) filtered.underscore += 1;
124
+ continue;
125
+ }
126
+ const rel = relDir ? `${relDir}/${ent.name}` : ent.name;
127
+ if (ent.isDirectory()) {
128
+ if (ent.name === 'outputs') {
129
+ filtered.outputs += 1;
130
+ continue;
131
+ }
132
+ walk(rel);
133
+ continue;
134
+ }
135
+ if (!ent.isFile() || !ent.name.toLowerCase().endsWith('.md')) continue;
136
+ const lower = ent.name.toLowerCase();
137
+ if (lower === 'readme.md') {
138
+ filtered.readme += 1;
139
+ continue;
140
+ }
141
+ if (lower === 'en.md') {
142
+ filtered.en += 1;
143
+ continue;
144
+ }
145
+ md += 1;
146
+ const top = rel.includes('/') ? rel.split('/')[0] : '(根目录)';
147
+ dirs.set(top, (dirs.get(top) || 0) + 1);
148
+ if (samples.length < 12) samples.push(rel);
149
+ }
150
+ };
151
+ walk('');
152
+
153
+ const topDirs = Array.from(dirs.entries())
154
+ .sort((a, b) => b[1] - a[1])
155
+ .slice(0, 15)
156
+ .map(([rel, count]) => ({ rel, count }));
157
+ return {
158
+ ok: true,
159
+ root,
160
+ flavor: check.flavor,
161
+ warnings: check.warnings,
162
+ counts: { md, filtered, filteredTotal: filtered.underscore + filtered.readme + filtered.outputs + filtered.en },
163
+ topDirs,
164
+ samples,
165
+ // 推荐范围:有顶层目录就全选它们(. = 整库),根目录为主时才用 '.'
166
+ suggestedScope: topDirs.filter((d) => d.rel !== '(根目录)').map((d) => d.rel),
167
+ };
168
+ }
169
+
170
+ /** scope 归一:默认 ['wiki'];每个元素必须是 root 内的相对子路径(不许 .. 逃逸) */
171
+ function scopeDirs(cfg) {
172
+ // v2.9.55:默认不再是 ['wiki'](那是本仓业主的目录约定,别人的库没有 wiki/);
173
+ // 留空 = 整库扫描('.'),只在扫描器里按过滤器剔掉索引/产出物。
174
+ const list = Array.isArray(cfg.scope) && cfg.scope.length ? cfg.scope : ['.'];
175
+ const out = [];
176
+ for (const raw of list) {
177
+ const rel = String(raw || '').replace(/\\/g, '/').replace(/^\/+|\/+$/g, '');
178
+ if (rel === '.' || rel === '') {
179
+ out.push('.');
180
+ continue;
181
+ }
182
+ if (rel.split('/').includes('..')) continue;
183
+ out.push(rel);
184
+ }
185
+ return out.length ? out : ['.'];
186
+ }
187
+
188
+ function excludeList(cfg) {
189
+ return (Array.isArray(cfg.exclude) ? cfg.exclude : [])
190
+ .map((s) => String(s || '').replace(/\\/g, '/').replace(/^\/+|\/+$/g, ''))
191
+ .filter(Boolean);
192
+ }
193
+
194
+ function isExcluded(rel, excludes) {
195
+ return excludes.some((ex) => rel === ex || rel.startsWith(`${ex}/`));
196
+ }
197
+
198
+ // ---------- 扫描(只读)+ 条目 ----------
199
+
200
+ function stripFrontmatter(text) {
201
+ const m = String(text || '').match(/^---\r?\n([\s\S]*?)\r?\n---\r?\n?/);
202
+ if (!m) return { meta: {}, body: String(text || '') };
203
+ const meta = {};
204
+ for (const line of m[1].split(/\r?\n/)) {
205
+ const kv = line.match(/^([A-Za-z_][\w-]*):\s*(.*)$/);
206
+ if (kv) meta[kv[1]] = kv[2].trim();
207
+ }
208
+ return { meta, body: String(text || '').slice(m[0].length) };
209
+ }
210
+
211
+ /** 摘要:去 frontmatter、去 markdown 记号,取前 400 字;卡片天然短,等于全文 */
212
+ function makeDigest(body, max) {
213
+ const text = String(body || '')
214
+ .replace(/```[\s\S]*?```/g, ' ')
215
+ .replace(/!\[[^\]]*\]\([^)]*\)/g, ' ')
216
+ .replace(/\[([^\]]*)\]\([^)]*\)/g, '$1')
217
+ .replace(/^#{1,6}\s*/gm, '')
218
+ .replace(/^>\s?/gm, '')
219
+ .replace(/[*_`]/g, '')
220
+ .replace(/[ \t]+/g, ' ')
221
+ .replace(/\n{2,}/g, '\n')
222
+ .trim();
223
+ const limit = max || 400;
224
+ return text.length <= limit ? text : `${text.slice(0, limit)}…`;
225
+ }
226
+
227
+ function walkMd(root, relDir, excludes, out) {
228
+ const abs = path.join(root, relDir);
229
+ let entries;
230
+ try {
231
+ entries = fs.readdirSync(abs, { withFileTypes: true });
232
+ } catch (e) {
233
+ return; // 目录不存在/无权限:跳过,不炸整次扫描
234
+ }
235
+ for (const ent of entries) {
236
+ if (out.length >= MAX_SCAN_FILES) return;
237
+ // `_` 前缀在本库是元页面约定(_index/_方法论/_audit-notes/_题库…):不是知识,别拿来出题
238
+ if (!ent || ent.name.startsWith('.') || ent.name.startsWith('_')) continue;
239
+ const rel = relDir ? `${relDir}/${ent.name}` : ent.name;
240
+ if (ent.isDirectory()) {
241
+ // 课程快照/工程仓里的 outputs 是产出物,不是课文
242
+ if (ent.name === 'outputs') continue;
243
+ if (isExcluded(rel, excludes)) continue;
244
+ walkMd(root, rel, excludes, out);
245
+ continue;
246
+ }
247
+ if (!ent.isFile() || !ent.name.toLowerCase().endsWith('.md')) continue;
248
+ // v2.9.54 课程快照适配:README 是阶段/课级索引,en.md 是同一课的英文副本(zh.md 已单独成条)
249
+ const lowerName = ent.name.toLowerCase();
250
+ if (lowerName === 'readme.md' || lowerName === 'en.md') continue;
251
+ if (isExcluded(rel, excludes)) continue;
252
+ const absFile = path.join(root, rel);
253
+ let st;
254
+ try {
255
+ st = fs.statSync(absFile);
256
+ } catch (e) {
257
+ continue;
258
+ }
259
+ let text = '';
260
+ try {
261
+ text = fs.readFileSync(absFile, 'utf8');
262
+ } catch (e) {
263
+ continue;
264
+ }
265
+ const { meta, body } = stripFrontmatter(text);
266
+ const h1 = body.match(/^#\s+(.+)$/m);
267
+ // v2.9.54 小节标题:课程/长文里 h2/h3 是最省 token 的结构信号,抽取知识点时一并喂给模型
268
+ const headings = Array.from(body.matchAll(/^#{2,3}\s+(.+)$/gm))
269
+ .map((m) => m[1].trim().replace(/[*_`]/g, ''))
270
+ .filter(Boolean)
271
+ .slice(0, 12);
272
+ out.push({
273
+ rel,
274
+ kind: rel.startsWith('wiki/学习卡片/') ? 'card' : 'page',
275
+ title: (meta.title || (h1 ? h1[1].trim() : path.basename(rel, '.md'))).slice(0, 120),
276
+ tags: String(meta.tags || '').replace(/^\[|\]$/g, '').split(',').map((s) => s.trim()).filter(Boolean).slice(0, 8),
277
+ status: typeof meta.status === 'string' ? meta.status : null,
278
+ headings,
279
+ mtime: Math.round(st.mtimeMs),
280
+ size: st.size,
281
+ digest: makeDigest(body),
282
+ });
283
+ }
284
+ }
285
+
286
+ /** 只读扫描 vault:返回条目数组(不写盘) */
287
+ function scanVault(ctx) {
288
+ const cfg = learnCfg(ctx);
289
+ const check = validateRoot(cfg.root);
290
+ if (!check.ok) throw new HttpError(400, 'LEARN_ROOT_INVALID', check.reason);
291
+ const excludes = excludeList(cfg);
292
+ const out = [];
293
+ for (const rel of scopeDirs(cfg)) walkMd(check.root, rel === '.' ? '' : rel, excludes, out);
294
+ out.sort((a, b) => (a.rel < b.rel ? -1 : a.rel > b.rel ? 1 : 0));
295
+ return { root: check.root, entries: out, scannedAt: new Date().toISOString() };
296
+ }
297
+
298
+ /** 单元名 → 台账单元 id(learn 五单元迁 SQLite 后经 storeDb 路由,SPEC-STORAGE §2.4) */
299
+ function unitIdOf(name) {
300
+ return `learn:${String(name || '').replace('.json', '')}`;
301
+ }
302
+
303
+ function loadJSON(ctx, name, fallback) {
304
+ // v2.9.33 批次 2:learn 五单元迁 learn_docs 单文档行(db 在 dataDir 根——**不是** learnDir 子目录)
305
+ if (storeDb.unitBackend(ctx.dataDir, unitIdOf(name)).backend === 'sqlite') {
306
+ const doc = storeDb.loadLearnDoc(storeDb.dbPathFor(ctx.dataDir), unitIdOf(name));
307
+ return doc && typeof doc === 'object' ? doc : fallback;
308
+ }
309
+ const d = store.readJSON(fileOf(ctx, name), null);
310
+ return d && typeof d === 'object' ? d : fallback;
311
+ }
312
+
313
+ /** 写漏斗统一出口(与 store.writeJSON 同纪律:db 路径=单文档 upsert;JSON 路径=tmp+rename) */
314
+ function saveJSON(ctx, name, obj) {
315
+ if (storeDb.unitBackend(ctx.dataDir, unitIdOf(name)).backend === 'sqlite') {
316
+ return storeDb.saveLearnDoc(storeDb.dbPathFor(ctx.dataDir), unitIdOf(name), obj);
317
+ }
318
+ store.writeJSON(fileOf(ctx, name), obj);
319
+ }
320
+
321
+ const ITEMS_VERSION = 2; // v2.9.51:学习条目从「一个 wiki 页」改为「一个原子知识点」
322
+
323
+ /**
324
+ * 学习条目 = **原子知识点**(术语/概念/机制),不是页面。页面只作为素材来源。
325
+ * 旧结构(一页一条)与"逐条学懂"的语义不符,读到旧版本就地重建(孤儿调度无害)。
326
+ */
327
+ function loadItems(ctx) {
328
+ const d = loadJSON(ctx, 'items.json', { version: ITEMS_VERSION, items: [] });
329
+ if (d.version !== ITEMS_VERSION) return [];
330
+ return Array.isArray(d.items) ? d.items : [];
331
+ }
332
+
333
+ function saveItems(ctx, items) {
334
+ saveJSON(ctx, 'items.json', { version: ITEMS_VERSION, items, updatedAt: new Date().toISOString() });
335
+ }
336
+
337
+ function loadPages(ctx) {
338
+ const d = loadJSON(ctx, 'pages.json', { pages: [] });
339
+ return Array.isArray(d.pages) ? d.pages : [];
340
+ }
341
+
342
+ function savePages(ctx, pages) {
343
+ saveJSON(ctx, 'pages.json', { pages, updatedAt: new Date().toISOString() });
344
+ }
345
+
346
+ function loadSchedule(ctx) {
347
+ const d = loadJSON(ctx, 'schedule.json', { items: {} });
348
+ return store.isPlainObject(d.items) ? d.items : {};
349
+ }
350
+
351
+ function loadSessions(ctx) {
352
+ const d = loadJSON(ctx, 'sessions.json', { sessions: [] });
353
+ return Array.isArray(d.sessions) ? d.sessions : [];
354
+ }
355
+
356
+ function saveSessions(ctx, list) {
357
+ saveJSON(ctx, 'sessions.json', { sessions: list.slice(-MAX_SESSIONS) });
358
+ }
359
+
360
+ /** 知识点 id:页面 + 术语 稳定可复算(换页面/同页同词都不重复学) */
361
+ function conceptId(pageRel, term) {
362
+ return `C-${crypto.createHash('sha1').update(`${pageRel}#${term}`).digest('hex').slice(0, 10)}`;
363
+ }
364
+
365
+ /** 内置主题知识点物化:只补缺、不动已有调度(幂等;老部署不重扫也会在出题前补上) */
366
+ function materializeSeeds(ctx) {
367
+ const cfg = learnCfg(ctx);
368
+ const domains = Array.isArray(cfg.seeds) ? cfg.seeds : seedsLib.DOMAINS;
369
+ const items = loadItems(ctx);
370
+ const have = new Set(items.map((it) => it.id));
371
+ const now = new Date().toISOString();
372
+ const added = [];
373
+ for (const domain of domains) {
374
+ for (const c of seedsLib.seedConcepts(domain)) {
375
+ const id = `S-${crypto.createHash('sha1').update(`${domain}#${c.term}`).digest('hex').slice(0, 10)}`;
376
+ if (have.has(id)) continue;
377
+ have.add(id);
378
+ added.push({
379
+ id,
380
+ kind: 'concept',
381
+ term: c.term,
382
+ definition: c.definition,
383
+ why: c.why,
384
+ sourcePath: `seed:${domain}`,
385
+ pageTitle: `内置主题 · ${domain}`,
386
+ digest: c.definition,
387
+ createdAt: now,
388
+ excluded: false,
389
+ needsRewrite: false,
390
+ });
391
+ }
392
+ }
393
+ if (added.length) saveItems(ctx, items.concat(added));
394
+ return added.length;
395
+ }
396
+
397
+ /** 扫描结果 → pages 索引(只读元数据)。页面内容变了就清掉 conceptsAt,下次重新抽知识点 */
398
+ function syncPages(ctx, scanned) {
399
+ const old = new Map(loadPages(ctx).map((p) => [p.rel, p]));
400
+ const now = new Date().toISOString();
401
+ const pages = scanned.entries.map((e) => {
402
+ const prev = old.get(e.rel);
403
+ const changed = !prev || prev.mtime !== e.mtime;
404
+ return {
405
+ rel: e.rel,
406
+ title: e.title,
407
+ kind: e.kind,
408
+ tags: e.tags,
409
+ headings: e.headings || [],
410
+ mtime: e.mtime,
411
+ digest: e.digest,
412
+ conceptsAt: changed ? null : (prev.conceptsAt || null),
413
+ createdAt: (prev && prev.createdAt) || now,
414
+ };
415
+ });
416
+ // v2.9.56 导入的资料不在知识库里(落在 data/learn/imports/),重扫必须保留
417
+ for (const p of old.values()) {
418
+ if (String(p.rel).startsWith('import:')) pages.push(p);
419
+ }
420
+ savePages(ctx, pages);
421
+ saveJSON(ctx, 'scan.json', { root: scanned.root, scannedAt: scanned.scannedAt, pages: pages.length });
422
+ materializeSeeds(ctx);
423
+ return pages;
424
+ }
425
+
426
+ // ---------- 导入器:pdf/docx/html/md/txt → 本地学习库(绝不写用户知识库) ----------
427
+
428
+ function importsDir(ctx) {
429
+ const dir = path.join(learnDir(ctx), 'imports');
430
+ try {
431
+ fs.mkdirSync(dir, { recursive: true });
432
+ } catch (e) {
433
+ /* 已存在;权限问题交给写文件时报错 */
434
+ }
435
+ return dir;
436
+ }
437
+
438
+ /** 原子写文本(tmp + rename),与 store.writeJSON 同纪律 */
439
+ function writeTextAtomic(file, text) {
440
+ const tmp = `${file}.tmp-${process.pid}-${Date.now()}`;
441
+ fs.writeFileSync(tmp, text, 'utf8');
442
+ fs.renameSync(tmp, file);
443
+ }
444
+
445
+ /** 导入预览:只列文件与类型,不抽取(只读、快) */
446
+ function previewImport(inputPath) {
447
+ const imp = require('./learnImport');
448
+ const collected = imp.collectFiles(inputPath);
449
+ if (!collected.ok) return { ok: false, reason: collected.reason };
450
+ const files = collected.files.map((abs) => {
451
+ let size = 0;
452
+ try {
453
+ size = fs.statSync(abs).size;
454
+ } catch (e) {
455
+ size = 0;
456
+ }
457
+ return { path: abs, name: path.basename(abs), kind: imp.kindOf(abs), size };
458
+ });
459
+ return { ok: true, files, total: files.length };
460
+ }
461
+
462
+ /** 执行导入:抽文本 → 落 data/learn/imports/*.md → 进页面索引(conceptsAt=null,待抽) */
463
+ function importMaterials(ctx, inputPath) {
464
+ const imp = require('./learnImport');
465
+ const collected = imp.collectFiles(inputPath);
466
+ if (!collected.ok) throw new HttpError(400, 'LEARN_IMPORT_INVALID', collected.reason);
467
+
468
+ const dir = importsDir(ctx);
469
+ const byRel = new Map(loadPages(ctx).map((p) => [p.rel, p]));
470
+ const imported = [];
471
+ const skipped = [];
472
+ const now = new Date().toISOString();
473
+
474
+ for (const abs of collected.files) {
475
+ const r = imp.extractText(abs);
476
+ if (!r.ok) {
477
+ skipped.push({ name: path.basename(abs), kind: r.kind, reason: r.reason });
478
+ continue;
479
+ }
480
+ const slug = imp.slugify(abs);
481
+ const rel = `import:${slug}`;
482
+ const title = path.basename(abs).replace(/\.[^.]+$/, '').slice(0, 120);
483
+ const md = `---\ntitle: ${title}\nsource: ${abs}\nimportedAt: ${now}\nkind: ${r.kind}\n---\n\n# ${title}\n\n${r.text}\n`;
484
+ try {
485
+ writeTextAtomic(path.join(dir, `${slug}.md`), md);
486
+ } catch (e) {
487
+ /* 副本没落盘不影响学习:内容仍在索引里 */
488
+ }
489
+ const headings = Array.from(String(r.text).matchAll(/^#{1,3}\s+(.+)$/gm))
490
+ .map((m) => m[1].trim())
491
+ .filter(Boolean)
492
+ .slice(0, 12);
493
+ byRel.set(rel, {
494
+ rel,
495
+ title,
496
+ kind: 'import',
497
+ tags: [],
498
+ headings,
499
+ mtime: Date.now(),
500
+ digest: makeDigest(r.text, 400),
501
+ conceptsAt: null,
502
+ createdAt: (byRel.get(rel) && byRel.get(rel).createdAt) || now,
503
+ sourceFile: abs,
504
+ chars: r.chars,
505
+ });
506
+ imported.push({ name: path.basename(abs), kind: r.kind, chars: r.chars, page: rel, warning: r.warning || null });
507
+ }
508
+
509
+ savePages(ctx, Array.from(byRel.values()));
510
+ return { ok: true, imported, skipped, total: collected.files.length };
511
+ }
512
+
513
+ // ---------- 原子知识点抽取(每页 1 次引擎调用,按需触发) ----------
514
+
515
+ function buildConceptPrompt(page) {
516
+ const heads = Array.isArray(page.headings) && page.headings.length
517
+ ? `\n小节(按顺序,可作为选题线索):${page.headings.join(' / ')}`
518
+ : '';
519
+ return [
520
+ '你是知识工程师。从下面这页笔记里抽取**原子知识点**,用于逐条学习。',
521
+ '要求:',
522
+ '- 每条只讲一个概念/术语/机制,能独立成题;**不要**"某方案总体介绍"这种宽泛条目。',
523
+ '- 优先抽**专业术语、模型/机制名、关键判据**(例:"基础率""纳什均衡""幂等奖赏""损耗项")。',
524
+ '- term ≤20 字;definition ≤60 字(说人话);why ≤40 字(为什么重要、用在哪)。',
525
+ '- 3-8 条;材料里没有的不编,宁可少。',
526
+ `页面标题:${page.title}${heads}`,
527
+ `<material>\n${page.digest}\n</material>`,
528
+ '只输出 JSON(不要 markdown 代码块):{"concepts":[{"term":"…","definition":"…","why":"…"}]}',
529
+ ].join('\n');
530
+ }
531
+
532
+ async function extractConcepts(ctx, page, opts) {
533
+ const engine = engineOf(ctx, opts);
534
+ if (!engine) throw new HttpError(400, 'LEARN_NO_ENGINE', '没有可用引擎,无法从页面抽取知识点(learn.engine.mode=off?)');
535
+ const parsed = parseEngineJSON(await engine(buildConceptPrompt(page)));
536
+ const list = parsed && Array.isArray(parsed.concepts) ? parsed.concepts : [];
537
+ const out = [];
538
+ const seen = new Set();
539
+ for (const c of list) {
540
+ const term = String((c && c.term) || '').trim().slice(0, 40);
541
+ if (!term || seen.has(term)) continue;
542
+ seen.add(term);
543
+ out.push({
544
+ id: conceptId(page.rel, term),
545
+ kind: 'concept',
546
+ term,
547
+ definition: String((c && c.definition) || '').trim().slice(0, 200),
548
+ why: String((c && c.why) || '').trim().slice(0, 120),
549
+ sourcePath: page.rel,
550
+ pageTitle: page.title,
551
+ digest: String((c && c.definition) || '').trim().slice(0, 200),
552
+ createdAt: new Date().toISOString(),
553
+ excluded: false,
554
+ needsRewrite: false,
555
+ });
556
+ }
557
+ return out;
558
+ }
559
+
560
+ /**
561
+ * 按需补货:没学过的知识点少于 3 条时,挑一个"还没抽过"的页面抽一批。
562
+ * 单次最多抽 1 页(1 次引擎调用,约 3-5s),避免扫描时炸出一堆调用。
563
+ */
564
+ async function ensureFreshConcepts(ctx, opts) {
565
+ materializeSeeds(ctx);
566
+ const items = loadItems(ctx);
567
+ const schedule = loadSchedule(ctx);
568
+ const isSeed = (it) => String(it.sourcePath || '').startsWith('seed:');
569
+ const unlearned = items.filter((it) => !it.excluded && !it.needsRewrite && !schedule[it.id]);
570
+ // 两个池各自保底:内置主题很多,不能因此让知识库永远不再抽页(否则 vault 池会被饿死)
571
+ const freshVault = unlearned.filter((it) => !isSeed(it));
572
+ const freshSeed = unlearned.filter(isSeed);
573
+ if (freshVault.length >= 2 && freshSeed.length >= 2) {
574
+ return { added: 0, reason: '两池都够用' };
575
+ }
576
+
577
+ const pages = loadPages(ctx);
578
+ const pending = pages
579
+ .filter((p) => !p.conceptsAt)
580
+ .sort((a, b) => (a.kind === b.kind ? a.rel.localeCompare(b.rel) : a.kind === 'card' ? -1 : 1));
581
+ const page = pending[0];
582
+ if (!page) return { added: 0, reason: '没有待抽取页面' };
583
+
584
+ const concepts = await extractConcepts(ctx, page, opts);
585
+ const have = new Set(items.map((it) => it.id));
586
+ const added = concepts.filter((c) => !have.has(c.id));
587
+ if (added.length) saveItems(ctx, items.concat(added));
588
+ page.conceptsAt = new Date().toISOString();
589
+ savePages(ctx, pages);
590
+ return { added: added.length, page: page.rel };
591
+ }
592
+
593
+ /** 知识点素材(题面只用它,避免又回到"整页综述") */
594
+ function conceptMaterial(item) {
595
+ return `${item.term}:${item.definition || '(材料未给定义)'}${item.why ? `\n为什么重要:${item.why}` : ''}`;
596
+ }
597
+
598
+ /**
599
+ * 学习材料(v2.9.58):知识点卡片 + 来源页摘录。
600
+ * 只给一句定义太薄,读不出上下文;摘录用页面 digest(≤400 字),是原文而非模型转述。
601
+ */
602
+ function materialFor(ctx, item) {
603
+ const base = conceptMaterial(item);
604
+ const rel = String(item.sourcePath || '');
605
+ if (!rel) return base;
606
+ const page = loadPages(ctx).find((x) => x.rel === rel);
607
+ if (!page || !page.digest) return base;
608
+ const label = rel.startsWith('import:') ? '导入资料摘录' : `原文摘录(《${page.title || ''}》)`;
609
+ return `${base}\n\n—— ${label}\n${page.digest}`;
610
+ }
611
+
612
+ // ---------- 调度(纯函数) ----------
613
+
614
+ function defaultState(id) {
615
+ return { itemId: id, level: 0, intervalDays: 0, lapses: 0, dueAt: null, lastReviewedAt: null, needsRewrite: false };
616
+ }
617
+
618
+ /** 下一档间隔:从当前间隔在阶梯上的位置推进;level 3 跳一级 */
619
+ function nextInterval(current, level) {
620
+ const idx = LADDER.indexOf(Number(current));
621
+ const base = idx === -1 ? -1 : idx;
622
+ const step = level >= 3 ? 2 : 1;
623
+ const next = Math.min(base + step, LADDER.length - 1);
624
+ return LADDER[Math.max(0, next)];
625
+ }
626
+
627
+ /**
628
+ * 应用一次复习评分(0-3):返回新状态。纯函数,不读时钟以外的东西。
629
+ * - 0/1:明天重来,lapses+1;连续 3 次 → needsRewrite(材料讲不清/选题太大)
630
+ * - 2:阶梯升一级;3:跳一级;35 天封顶
631
+ * - 长期(>90 天)未复习且 level≤1 → 当新条目重学(interval 归零)
632
+ */
633
+ function applyReview(state, level, now) {
634
+ const today = ymd(now || new Date());
635
+ const base = Object.assign(defaultState(state && state.itemId), state || {});
636
+ const lv = Math.max(0, Math.min(3, Number(level) || 0));
637
+ const stale = base.lastReviewedAt && (Date.parse(today) - Date.parse(base.lastReviewedAt)) / 86400000 > DECAY_DAYS;
638
+ const restart = stale && (base.level || 0) <= 1;
639
+
640
+ const next = Object.assign({}, base, { level: lv, lastReviewedAt: today });
641
+
642
+ if (lv <= 1) {
643
+ next.intervalDays = 1;
644
+ next.lapses = (Number(base.lapses) || 0) + 1;
645
+ next.dueAt = addDays(today, 1);
646
+ if (next.lapses >= 3) next.needsRewrite = true;
647
+ return next;
648
+ }
649
+ const current = restart || !base.intervalDays ? 0 : base.intervalDays;
650
+ next.intervalDays = nextInterval(current, lv);
651
+ next.dueAt = addDays(today, next.intervalDays);
652
+ next.lapses = 0;
653
+ return next;
654
+ }
655
+
656
+ function isDue(state, today) {
657
+ return !!(state && state.dueAt && state.dueAt <= today);
658
+ }
659
+
660
+ /** 今日队列:到期优先(最多 dailyReview 个,按 kind 交错);到期不足时才补 dailyNew 个新条目 */
661
+ function pickDaily(items, schedule, cfg, now) {
662
+ const today = ymd(now || new Date());
663
+ const eligible = items.filter((it) => it && !it.excluded && !it.needsRewrite && !(schedule[it.id] && schedule[it.id].needsRewrite));
664
+ const due = eligible
665
+ .filter((it) => isDue(schedule[it.id], today))
666
+ .sort((a, b) => String(schedule[a.id].dueAt).localeCompare(String(schedule[b.id].dueAt)));
667
+
668
+ const reviewLimit = Math.max(0, Number(cfg.dailyReview) || 0);
669
+ const picked = [];
670
+ const rest = due.slice();
671
+ while (picked.length < reviewLimit && rest.length) {
672
+ let i = 0;
673
+ const last = picked[picked.length - 1];
674
+ // 交错:能挑到与上一条不同 kind 的就先挑它,避免连续同主题
675
+ if (last) {
676
+ const alt = rest.findIndex((it) => it.kind !== last.kind);
677
+ if (alt > 0) i = alt;
678
+ }
679
+ picked.push(rest.splice(i, 1)[0]);
680
+ }
681
+
682
+ const out = picked.map((it) => ({ item: it, reason: 'due' }));
683
+ const newLimit = Math.max(0, Number(cfg.dailyNew) || 0);
684
+ // v2.9.61:到期与新题**并行**。之前写成"到期为空才补新",与设置里的「每日 3 新题」冲突:
685
+ // 只要有一条到期,当天就只剩 1 条。现在 = 到期(≤dailyReview)+ 新题(≤dailyNew)。
686
+ if (newLimit > 0) {
687
+ const isSeed = (it) => String(it.sourcePath || '').startsWith('seed:');
688
+ const byPath = (a, b) => (a.kind === b.kind ? a.sourcePath.localeCompare(b.sourcePath) : a.kind === 'card' ? -1 : 1);
689
+ const freshAll = eligible.filter((it) => !schedule[it.id]);
690
+ const seedPool = freshAll.filter(isSeed).sort(byPath);
691
+ const vaultPool = freshAll.filter((it) => !isSeed(it)).sort(byPath);
692
+ // 双池交替:单日先 vault、双日先内置主题,保证"业务知识"和"工程基础"都轮得到
693
+ const dayNum = new Date(now || Date.now()).getDate();
694
+ const pools = dayNum % 2 === 0 ? [seedPool, vaultPool] : [vaultPool, seedPool];
695
+ const fresh = [].concat(...pools);
696
+ for (const it of fresh.slice(0, newLimit)) out.push({ item: it, reason: 'new' });
697
+ }
698
+ return out;
699
+ }
700
+
701
+ // ---------- 引擎(可注入;失败降级) ----------
702
+
703
+ /**
704
+ * 宿主 LLM 直连(v2.9.47 首选):用「当前 profile 的默认模型」在进程内流式调用——
705
+ * 桌面端就是 DeepSeek-V4.1-Flash 那条账号通道(子进程拿不到,实测 ACCOUNT_SIGN_IN_REQUIRED),
706
+ * 也不需要 GLM_API_KEY。拿不到 llm 服务时返回 null,调用方回落 spawn 引擎。
707
+ */
708
+ function hostEngine(ctx, timeoutSec, engineCfg) {
709
+ const llm = ctx && ctx.llm;
710
+ if (!llm || typeof llm.stream !== 'function') return null;
711
+ const ec = engineCfg || {};
712
+ const reasoningEffort = typeof ec.reasoningEffort === 'string' && ec.reasoningEffort ? ec.reasoningEffort : 'off';
713
+ const maxTokens = Number(ec.maxTokens) > 0 ? Number(ec.maxTokens) : 1200;
714
+ const pick = () => {
715
+ try {
716
+ const svc = ctx.agentDefaultModel;
717
+ const sel = svc && typeof svc.currentSelection === 'function' ? svc.currentSelection() : null;
718
+ if (sel && typeof sel.provider === 'string' && typeof sel.model === 'string') return sel;
719
+ } catch (e) {
720
+ /* 拿不到选择就不指定 provider/model,交给宿主默认 */
721
+ }
722
+ return null;
723
+ };
724
+ return async (prompt) => {
725
+ const ctrl = new AbortController();
726
+ const timer = setTimeout(() => ctrl.abort(), timeoutSec * 1000);
727
+ const sel = pick();
728
+ if (!sel) throw new Error('宿主未提供默认模型(agentDefaultModel.currentSelection 为空)');
729
+ let text = '';
730
+ try {
731
+ // reasoningEffort 默认压到 low:批改/造题是短输出任务,high 会白等两三分钟(实测 187s)
732
+ const options = {
733
+ provider: sel.provider,
734
+ model: sel.model,
735
+ reasoningEffort,
736
+ maxTokens,
737
+ messages: [{ role: 'user', content: [{ type: 'text', text: String(prompt) }] }],
738
+ signal: ctrl.signal,
739
+ };
740
+ for await (const chunk of llm.stream(options)) {
741
+ if (!chunk) continue;
742
+ if (chunk.type === 'text-delta' && typeof chunk.text === 'string') text += chunk.text;
743
+ else if (chunk.type === 'finish' && chunk.reason && chunk.reason.kind && chunk.reason.kind !== 'stop') {
744
+ throw new Error(`宿主模型结束异常:${chunk.reason.kind}${chunk.reason.message ? ` ${chunk.reason.message}` : ''}`);
745
+ }
746
+ }
747
+ } finally {
748
+ clearTimeout(timer);
749
+ }
750
+ if (!text.trim()) throw new Error('宿主模型没有返回文本');
751
+ return text;
752
+ };
753
+ }
754
+
755
+ function engineOf(ctx, opts) {
756
+ if (opts && typeof opts.engine === 'function') return opts.engine;
757
+ const cfg = learnCfg(ctx);
758
+ const engineCfg = cfg.engine || {};
759
+ const mode = engineCfg.mode || 'auto';
760
+ const timeoutSec = Number(engineCfg.timeoutSec) || 180;
761
+ if (mode === 'off') return null;
762
+ if (mode !== 'dsh') {
763
+ const host = hostEngine(ctx, timeoutSec, engineCfg);
764
+ if (host) return host;
765
+ if (mode === 'host') return null; // 显式要求宿主模型却拿不到服务 → 按"无引擎"降级,不偷偷换 profile
766
+ }
767
+ return (prompt) => analyze.runHeadless(ctx.config, prompt, { timeoutSec });
768
+ }
769
+
770
+ function parseEngineJSON(text) {
771
+ const parsed = analyze.extractJSON(String(text || ''));
772
+ return parsed && typeof parsed === 'object' ? parsed : null;
773
+ }
774
+
775
+ function recallQuestion(item) {
776
+ return `先别看资料:${item.term} 是什么?它解决什么问题?用你自己的话说两句。`;
777
+ }
778
+
779
+ function feynmanPrompt(item) {
780
+ return `合上材料,给完全外行解释「${item.term}」:不许用这个术语本身或同义黑话,必须有一个类比。`;
781
+ }
782
+
783
+ function transferPrompt(item) {
784
+ return `举一个知识库之外的例子:哪里用得上「${item.term}」?在什么条件下它不成立?`;
785
+ }
786
+
787
+ function buildGradePrompt(item, material, answer) {
788
+ return [
789
+ '你是严格但克制的学习教练。只依据下面材料判定,不得补充材料之外的知识。',
790
+ '这次要检验的是**一个具体知识点**(术语/概念/机制),不是整篇文章的综述。',
791
+ `<material>\n${material}\n</material>`,
792
+ `知识点:${item.term || item.title}`,
793
+ `学员的解释:\n${answer}`,
794
+ '只输出 JSON(不要 markdown 代码块):',
795
+ '{"good":[讲对的点,最多3条],"missing":[材料里关键但没讲到的点,最多3条],"jargon":[哪句是用术语代替理解,最多2条],"misconception":[与材料相反的表述,没有则空数组],"probe":"一个能暴露是否真懂的追问","level":0|1|2|3}',
796
+ '判定:0=跑题/空白;1=复述术语;2=用自己的话讲清且类比成立;3=还能指出边界或反例。材料不足以判定时 level 返回 null。',
797
+ '若学员讲的是别的话题(哪怕讲得对),level 给 0 并直接指出跑题,不要迁就。',
798
+ ].join('\n');
799
+ }
800
+
801
+ function buildWhyPrompt(item, material) {
802
+ return [
803
+ '基于材料就这个**具体知识点**生成一条 5-why 追问链,用于检验是否懂机理而不是背结论。',
804
+ `<material>\n${material}\n</material>`,
805
+ `知识点:${item.term || item.title}`,
806
+ '要求:每问都能由上一答继续深挖,不跳步,第 5 问落到"约束/激励/成本"这类根因;',
807
+ '每问都要围绕这个知识点本身(它为什么成立、不成立会怎样、边界在哪),不要扩成整篇文章的宏观讨论。',
808
+ '只输出 JSON(不要 markdown 代码块):{"chain":["问1","问2","问3","问4","问5"],"root":"根因一句话","materialBoundary":"材料支持到第几层"}',
809
+ ].join('\n');
810
+ }
811
+
812
+ // ---------- 会话状态机 ----------
813
+
814
+ function findSession(ctx, id) {
815
+ return loadSessions(ctx).find((s) => s && s.id === id) || null;
816
+ }
817
+
818
+ function saveSession(ctx, session) {
819
+ const list = loadSessions(ctx);
820
+ const idx = list.findIndex((s) => s && s.id === session.id);
821
+ if (idx >= 0) list[idx] = session;
822
+ else list.push(session);
823
+ saveSessions(ctx, list);
824
+ }
825
+
826
+ function publicItem(item, extra) {
827
+ return Object.assign({
828
+ id: item.id,
829
+ term: item.term,
830
+ title: item.term || item.title,
831
+ kind: item.kind,
832
+ sourcePath: item.sourcePath,
833
+ pageTitle: item.pageTitle,
834
+ tags: item.tags,
835
+ }, extra || {});
836
+ }
837
+
838
+ /**
839
+ * 建会话。两种入口(v2.9.57 修正设计错误):
840
+ * - **复习**(该知识点有调度记录):先测——不给材料,靠自己回忆(检索练习的价值在这)
841
+ * - **新学**(从没学过):先给材料(study)——对完全没接触过的内容"先测"只会卡住人,
842
+ * 教学法上应先读后讲;讲(费曼)仍然是主动回忆,不违背"必须自己输出"的原则。
843
+ */
844
+ function createSession(ctx, itemIdArg, opts) {
845
+ const items = loadItems(ctx);
846
+ const item = items.find((it) => it.id === itemIdArg) || items.find((it) => it.sourcePath === itemIdArg);
847
+ if (!item) throw new HttpError(404, 'LEARN_ITEM_NOT_FOUND', `学习条目不存在:${itemIdArg}`);
848
+ if (item.excluded) throw new HttpError(400, 'LEARN_ITEM_EXCLUDED', '该条目已被手动剔除');
849
+
850
+ const today = ymd(new Date());
851
+ const schedule = loadSchedule(ctx);
852
+ const isReview = !!schedule[item.id];
853
+ const firstStage = isReview ? 'recall' : 'study';
854
+
855
+ const existing = loadSessions(ctx).find((s) => s && s.itemId === item.id && s.date === today && !s.finishedAt);
856
+ if (existing) {
857
+ let stage = existing.stage || firstStage;
858
+ // 旧会话迁移(v2.9.57 之前建的 recall 会话其实是"新学"):补上材料,别让人继续对着空白发呆
859
+ if (stage === 'recall' && existing.isReview !== true) stage = 'study';
860
+ const out = {
861
+ id: existing.id,
862
+ stage,
863
+ item: publicItem(item),
864
+ question: caseQuestion(item, stage),
865
+ isReview: stage !== 'study',
866
+ resumed: true,
867
+ };
868
+ if (stage === 'study') {
869
+ out.material = materialFor(ctx, item);
870
+ out.source = item.sourcePath;
871
+ }
872
+ return out;
873
+ }
874
+
875
+ const session = {
876
+ id: `S-${Date.now().toString(36)}-${crypto.randomBytes(3).toString('hex')}`,
877
+ date: today,
878
+ itemId: item.id,
879
+ stage: firstStage,
880
+ isReview,
881
+ chain: [],
882
+ chainIndex: 0,
883
+ turns: [],
884
+ grade: null,
885
+ degraded: false,
886
+ startedAt: new Date().toISOString(),
887
+ finishedAt: null,
888
+ level: null,
889
+ };
890
+ saveSession(ctx, session);
891
+ const out = {
892
+ id: session.id,
893
+ stage: firstStage,
894
+ item: publicItem(item),
895
+ question: caseQuestion(item, firstStage),
896
+ isReview,
897
+ resumed: false,
898
+ _item: item, // 仅供内部/测试使用,路由层会剥掉
899
+ };
900
+ if (firstStage === 'study') {
901
+ out.material = materialFor(ctx, item);
902
+ out.source = item.sourcePath;
903
+ }
904
+ return out;
905
+ }
906
+
907
+ /** 分阶段题面(先测 / 读材料 / 费曼 / 迁移) */
908
+ function caseQuestion(item, stage) {
909
+ if (stage === 'study') {
910
+ return '先读下面这段(约 1 分钟),读完用一句话概括它在讲什么。';
911
+ }
912
+ if (stage === 'transition') return '继续。';
913
+ return recallQuestion(item);
914
+ }
915
+
916
+ function stripInternal(obj) {
917
+ if (!obj || typeof obj !== 'object') return obj;
918
+ const out = Object.assign({}, obj);
919
+ delete out._item;
920
+ return out;
921
+ }
922
+
923
+ /**
924
+ * 推进一步。stage ∈ recall|feynman|why5|transfer。
925
+ * 引擎失败 → degraded,仍继续(不卡死会话)。
926
+ */
927
+ async function turn(ctx, id, stage, text, opts) {
928
+ const session = findSession(ctx, id);
929
+ if (!session) throw new HttpError(404, 'LEARN_SESSION_NOT_FOUND', '会话不存在');
930
+ if (session.finishedAt) throw new HttpError(409, 'LEARN_SESSION_CLOSED', '会话已结束');
931
+ if (session.stage !== stage) throw new HttpError(409, 'LEARN_STAGE_MISMATCH', `当前阶段是 ${session.stage},不接受 ${stage}`);
932
+
933
+ const answer = String(text || '').trim();
934
+ if (answer.length < 2) throw new HttpError(400, 'LEARN_ANSWER_EMPTY', '请先写下你的回答(至少 2 个字)');
935
+
936
+ const items = loadItems(ctx);
937
+ const item = items.find((it) => it.id === session.itemId);
938
+ if (!item) throw new HttpError(404, 'LEARN_ITEM_NOT_FOUND', '条目已不在学习库(可能被重建索引)');
939
+
940
+ session.turns.push({ stage, text: answer.slice(0, 4000), at: new Date().toISOString() });
941
+
942
+ if (stage === 'study' || stage === 'recall') {
943
+ // 新学(study):材料随建会话已给出,这里收下"一句概括"→ 进入费曼讲解
944
+ // 复习(recall):先测答案收下 → 才给材料 → 进入费曼讲解
945
+ session.stage = 'feynman';
946
+ saveSession(ctx, session);
947
+ return {
948
+ stage: 'feynman',
949
+ material: materialFor(ctx, item),
950
+ source: item.sourcePath,
951
+ prompt: feynmanPrompt(item),
952
+ };
953
+ }
954
+
955
+ if (stage === 'feynman') {
956
+ const engine = engineOf(ctx, opts);
957
+ let grade = null;
958
+ let chain = [];
959
+ let gradeErr = null;
960
+ let chainErr = null;
961
+
962
+ if (engine) {
963
+ // 两件事互不依赖(批改 + 造五问链),并行跑——串行会把等待时间翻倍(实测 187s → 见 docs)
964
+ const run = async (prompt) => {
965
+ try {
966
+ return { ok: true, value: parseEngineJSON(await engine(prompt)) };
967
+ } catch (e) {
968
+ return { ok: false, error: String((e && e.message) || e).slice(0, 300) };
969
+ }
970
+ };
971
+ const [g, w] = await Promise.all([
972
+ run(buildGradePrompt(item, item.digest, answer)),
973
+ run(buildWhyPrompt(item, item.digest)),
974
+ ]);
975
+ if (g.ok) grade = g.value;
976
+ else gradeErr = g.error;
977
+ if (w.ok) {
978
+ const why = w.value;
979
+ chain = Array.isArray(why && why.chain) ? why.chain.filter((q) => typeof q === 'string' && q.trim()).slice(0, 5) : [];
980
+ if (why && typeof why.root === 'string') session.root = why.root.slice(0, 300);
981
+ if (!chain.length) chainErr = '模型未给出可用追问链';
982
+ } else {
983
+ chainErr = w.error;
984
+ }
985
+ } else {
986
+ gradeErr = '无可用引擎(learn.engine.mode=off 或宿主 llm 与 dsh 均不可用)';
987
+ chainErr = gradeErr;
988
+ }
989
+
990
+ session.grade = grade;
991
+ // 语义纠偏:**批改成功就不算 degraded**(之前把"五问链失败"也算降级,界面会误报"本次无 AI 批改")
992
+ session.degraded = !grade;
993
+ if (gradeErr) session.engineError = gradeErr;
994
+ if (chainErr) {
995
+ session.chainError = chainErr;
996
+ session.chainFallback = true;
997
+ }
998
+ if (!chain.length) chain = ['为什么会这样?', '再往下问一层:是什么约束导致的?'];
999
+ session.chain = chain;
1000
+ session.chainIndex = 0;
1001
+ session.stage = 'why5';
1002
+ saveSession(ctx, session);
1003
+ return {
1004
+ stage: 'why5',
1005
+ question: chain[0],
1006
+ index: 0,
1007
+ total: chain.length,
1008
+ feedback: grade || null,
1009
+ degraded: session.degraded === true,
1010
+ chainFallback: session.chainFallback === true,
1011
+ };
1012
+ }
1013
+
1014
+ if (stage === 'why5') {
1015
+ session.chainIndex = (Number(session.chainIndex) || 0) + 1;
1016
+ const idx = session.chainIndex;
1017
+ if (idx < session.chain.length) {
1018
+ saveSession(ctx, session);
1019
+ return { stage: 'why5', question: session.chain[idx], index: idx, total: session.chain.length };
1020
+ }
1021
+ session.stage = 'transfer';
1022
+ saveSession(ctx, session);
1023
+ return {
1024
+ stage: 'transfer',
1025
+ prompt: transferPrompt(item),
1026
+ root: session.root || null,
1027
+ };
1028
+ }
1029
+
1030
+ // transfer:收尾
1031
+ const level = suggestLevel(session);
1032
+ session.finishedAt = new Date().toISOString();
1033
+ session.level = level;
1034
+ saveSession(ctx, session);
1035
+ const applied = applyReviewResult(ctx, session, level);
1036
+ return {
1037
+ stage: 'done',
1038
+ level,
1039
+ suggestedLevel: level,
1040
+ nextReviewAt: applied.dueAt,
1041
+ intervalDays: applied.intervalDays,
1042
+ needsRewrite: applied.needsRewrite === true,
1043
+ degraded: session.degraded === true,
1044
+ };
1045
+ }
1046
+
1047
+ /** 建议掌握度:AI 给的 level 优先;没有则按"答完 5why 且写了迁移题"给 2,否则 1 */
1048
+ function suggestLevel(session) {
1049
+ const g = session.grade;
1050
+ if (g && Number.isInteger(g.level)) return Math.max(0, Math.min(3, g.level));
1051
+ const whyAnswers = (session.turns || []).filter((t) => t.stage === 'why5').length;
1052
+ const transfer = (session.turns || []).some((t) => t.stage === 'transfer');
1053
+ if (transfer && whyAnswers >= 2) return 2;
1054
+ if (transfer) return 1;
1055
+ return 0;
1056
+ }
1057
+
1058
+ /** 落调度(幂等:同一会话只应用一次) */
1059
+ function applyReviewResult(ctx, session, level) {
1060
+ const schedule = loadSchedule(ctx);
1061
+ const prev = schedule[session.itemId] || defaultState(session.itemId);
1062
+ if (prev.lastSessionId === session.id) return prev; // 已应用过
1063
+ const next = applyReview(prev, level, new Date());
1064
+ next.lastSessionId = session.id;
1065
+ schedule[session.itemId] = next;
1066
+ saveJSON(ctx, 'schedule.json', { items: schedule, updatedAt: new Date().toISOString() });
1067
+ return next;
1068
+ }
1069
+
1070
+ function finishSession(ctx, id, level, opts) {
1071
+ const session = findSession(ctx, id);
1072
+ if (!session) throw new HttpError(404, 'LEARN_SESSION_NOT_FOUND', '会话不存在');
1073
+ if (session.finishedAt) {
1074
+ const applied = (loadSchedule(ctx)[session.itemId]) || defaultState(session.itemId);
1075
+ return { stage: 'done', level: session.level, nextReviewAt: applied.dueAt, intervalDays: applied.intervalDays, alreadyFinished: true };
1076
+ }
1077
+ const lv = Number.isInteger(level) ? Math.max(0, Math.min(3, level)) : suggestLevel(session);
1078
+ session.finishedAt = new Date().toISOString();
1079
+ session.level = lv;
1080
+ saveSession(ctx, session);
1081
+ const applied = applyReviewResult(ctx, session, lv);
1082
+ return { stage: 'done', level: lv, nextReviewAt: applied.dueAt, intervalDays: applied.intervalDays, needsRewrite: applied.needsRewrite === true };
1083
+ }
1084
+
1085
+ // ---------- 状态 ----------
1086
+
1087
+ function status(ctx) {
1088
+ const cfg = learnCfg(ctx);
1089
+ const check = validateRoot(cfg.root);
1090
+ const items = loadItems(ctx);
1091
+ const schedule = loadSchedule(ctx);
1092
+ const today = ymd(new Date());
1093
+ const eligible = items.filter((it) => !it.excluded);
1094
+ const due = eligible.filter((it) => isDue(schedule[it.id], today));
1095
+ const fresh = eligible.filter((it) => !schedule[it.id]);
1096
+ const doneToday = loadSessions(ctx).filter((s) => s && s.date === today && s.finishedAt).length;
1097
+ const pages = loadPages(ctx);
1098
+ return {
1099
+ enabled: cfg.enabled === true,
1100
+ configured: cfg.enabled === true && check.ok,
1101
+ root: typeof cfg.root === 'string' ? cfg.root : '',
1102
+ rootOk: check.ok,
1103
+ rootError: check.ok ? null : check.reason,
1104
+ scope: scopeDirs(cfg),
1105
+ exclude: excludeList(cfg),
1106
+ dailyNew: Number(cfg.dailyNew) || 1,
1107
+ dailyReview: Number(cfg.dailyReview) || 3,
1108
+ minutes: Number(cfg.minutes) || 15,
1109
+ counts: {
1110
+ items: items.length,
1111
+ seeds: items.filter((it) => String(it.sourcePath || '').startsWith('seed:')).length,
1112
+ imports: items.filter((it) => String(it.sourcePath || '').startsWith('import:')).length,
1113
+ pages: pages.length,
1114
+ pagesPending: pages.filter((p) => !p.conceptsAt).length,
1115
+ learned: eligible.length - fresh.length,
1116
+ due: due.length,
1117
+ fresh: fresh.length,
1118
+ needsRewrite: eligible.filter((it) => it.needsRewrite || (schedule[it.id] && schedule[it.id].needsRewrite)).length,
1119
+ },
1120
+ todayDone: doneToday,
1121
+ // v2.9.62:实例版本 vs 仓库 package.json ——web 改动刷新即生效、lib 改动必须重启,
1122
+ // 两者错位时前端会点到不存在的接口("接口不存在"),这里把它显式暴露出来
1123
+ version: versionInfo(ctx),
1124
+ // 引擎是否可用:宿主 llm 服务优先(桌面端=账号模型),否则看 dsh 子进程是否可解析
1125
+ engineOk: !!(ctx.llm && typeof ctx.llm.stream === 'function') || !!analyze.resolveDshBin(ctx.config),
1126
+ engine: (ctx.llm && typeof ctx.llm.stream === 'function') ? 'host' : 'dsh',
1127
+ };
1128
+ }
1129
+
1130
+ /** 今日队列(不含材料正文);没货时按需抽一页知识点(1 次引擎调用) */
1131
+ async function todayQueue(ctx) {
1132
+ try {
1133
+ await ensureFreshConcepts(ctx);
1134
+ } catch (e) {
1135
+ // 抽取失败不该让整页崩:队列可能还有已抽好的条目
1136
+ if (!loadItems(ctx).length) throw e;
1137
+ }
1138
+ const cfg = learnCfg(ctx);
1139
+ const check = validateRoot(cfg.root);
1140
+ if (!check.ok) throw new HttpError(400, 'LEARN_ROOT_INVALID', check.reason);
1141
+ const items = loadItems(ctx);
1142
+ const schedule = loadSchedule(ctx);
1143
+ const picks = pickDaily(items, schedule, cfg, new Date());
1144
+ return {
1145
+ date: ymd(new Date()),
1146
+ queue: picks.map((p) => ({
1147
+ item: publicItem(p.item),
1148
+ reason: p.reason,
1149
+ level: (schedule[p.item.id] && schedule[p.item.id].level) || 0,
1150
+ dueAt: (schedule[p.item.id] && schedule[p.item.id].dueAt) || null,
1151
+ })),
1152
+ status: status(ctx),
1153
+ };
1154
+ }
1155
+
1156
+ const MAX_SOURCE_BYTES = 400 * 1024;
1157
+
1158
+ /**
1159
+ * 读原文(v2.9.59):材料里点「查看原文」时用,**只读**。
1160
+ * 白名单:只允许 .md;必须以 root 为根(防目录穿越);导入资料走 data/learn/imports/。
1161
+ */
1162
+ function readSource(ctx, pageRel) {
1163
+ const rel = String(pageRel || '').trim();
1164
+ if (!rel) throw new HttpError(400, 'LEARN_SOURCE_INVALID', '缺少 page 参数');
1165
+
1166
+ if (rel.startsWith('import:')) {
1167
+ const slug = rel.slice('import:'.length);
1168
+ if (!/^[\w\u4e00-\u9fa5-]+$/.test(slug)) throw new HttpError(400, 'LEARN_SOURCE_INVALID', '导入页标识非法');
1169
+ const file = path.join(learnDir(ctx), 'imports', `${slug}.md`);
1170
+ let text = '';
1171
+ try {
1172
+ text = fs.readFileSync(file, 'utf8');
1173
+ } catch (e) {
1174
+ throw new HttpError(404, 'LEARN_SOURCE_MISSING', '这份导入资料的本地副本不在了');
1175
+ }
1176
+ const clipped = text.length > MAX_SOURCE_BYTES;
1177
+ return { ok: true, rel, kind: 'import', title: slug, content: clipped ? text.slice(0, MAX_SOURCE_BYTES) : text, truncated: clipped };
1178
+ }
1179
+
1180
+ const cfg = learnCfg(ctx);
1181
+ const check = validateRoot(cfg.root);
1182
+ if (!check.ok) throw new HttpError(400, 'LEARN_ROOT_INVALID', check.reason);
1183
+ const root = check.root;
1184
+ if (!rel.toLowerCase().endsWith('.md')) throw new HttpError(400, 'LEARN_SOURCE_INVALID', '只能查看 Markdown 原文');
1185
+ if (rel.split('/').includes('..')) throw new HttpError(400, 'LEARN_SOURCE_INVALID', '路径不允许包含 ..');
1186
+
1187
+ const abs = path.resolve(root, rel);
1188
+ const rootWithSep = root.endsWith(path.sep) ? root : `${root}${path.sep}`;
1189
+ if (abs !== root && !abs.startsWith(rootWithSep)) throw new HttpError(400, 'LEARN_SOURCE_INVALID', '路径越界');
1190
+
1191
+ let st;
1192
+ try {
1193
+ st = fs.statSync(abs);
1194
+ } catch (e) {
1195
+ throw new HttpError(404, 'LEARN_SOURCE_MISSING', '原文文件不在了(可能被移动或删除)');
1196
+ }
1197
+ if (!st.isFile()) throw new HttpError(400, 'LEARN_SOURCE_INVALID', '不是文件');
1198
+ const clipped = st.size > MAX_SOURCE_BYTES;
1199
+ const buf = fs.readFileSync(abs);
1200
+ const text = buf.slice(0, MAX_SOURCE_BYTES).toString('utf8');
1201
+ const title = path.basename(rel, '.md');
1202
+ return { ok: true, rel, kind: 'vault', title, content: text, truncated: clipped, size: st.size };
1203
+ }
1204
+
1205
+ /**
1206
+ * 初始化(v2.9.55):给"别人的库"用的一步到位入口。
1207
+ * 探测 → 定范围 → 落盘 → 建索引 → 试抽一页做预览(预览不落库,避免白学没确认的东西)。
1208
+ */
1209
+ async function initLearn(ctx, body, opts) {
1210
+ const input = body || {};
1211
+ const probe = probeRoot(String(input.root || ''));
1212
+ if (!probe.ok) throw new HttpError(400, 'LEARN_ROOT_INVALID', `${probe.reason}(当前:${probe.root || '空'})`);
1213
+
1214
+ const scope = Array.isArray(input.scope) && input.scope.length
1215
+ ? input.scope.map(String)
1216
+ : (probe.suggestedScope.length ? probe.suggestedScope : ['.']);
1217
+
1218
+ const patchLearn = {
1219
+ enabled: true,
1220
+ root: probe.root,
1221
+ scope,
1222
+ exclude: Array.isArray(input.exclude) ? input.exclude.map(String) : [],
1223
+ dailyNew: Number.isInteger(input.dailyNew) ? input.dailyNew : 2,
1224
+ dailyReview: Number.isInteger(input.dailyReview) ? input.dailyReview : 3,
1225
+ };
1226
+ if (Array.isArray(input.seeds)) patchLearn.seeds = input.seeds.map(String);
1227
+
1228
+ // 落盘路径与 settings PATCH 完全一致:磁盘现值 → deepMerge → 原子写 → 换运行期 config
1229
+ const settingsMod = require('./settings');
1230
+ const disk = store.readJSON(ctx.configPath, null);
1231
+ const base = store.isPlainObject(disk) ? disk : store.clone(ctx.config);
1232
+ const next = settingsMod.deepMerge(base, { learn: patchLearn });
1233
+ store.writeJSON(ctx.configPath, next);
1234
+ ctx.config = store.mergeConfigDefaults(next);
1235
+
1236
+ const scanned = scanVault(ctx);
1237
+ const pages = syncPages(ctx, scanned);
1238
+
1239
+ // 试抽一页:让用户在"确认"之前先看到知识点长什么样(预览不落库)
1240
+ let sample = null;
1241
+ let sampleError = null;
1242
+ if (input.sample !== false) {
1243
+ const page = pages.find((p) => !p.conceptsAt) || pages[0];
1244
+ if (page) {
1245
+ try {
1246
+ const cs = await extractConcepts(ctx, page, opts);
1247
+ sample = {
1248
+ page: page.rel,
1249
+ title: page.title,
1250
+ concepts: cs.slice(0, 6).map((x) => ({ term: x.term, definition: x.definition })),
1251
+ };
1252
+ } catch (e) {
1253
+ sampleError = String((e && e.message) || e).slice(0, 300);
1254
+ }
1255
+ }
1256
+ }
1257
+
1258
+ return { ok: true, root: probe.root, flavor: probe.flavor, warnings: probe.warnings, probe, scope, pages: pages.length, sample, sampleError };
1259
+ }
1260
+
1261
+ // ---------- 路由 ----------
1262
+
1263
+ function registerLearnRoutes(router, ctx) {
1264
+ router.add('GET', '/api/learn/status', (c) => {
1265
+ sendJSON(c.res, 200, status(ctx));
1266
+ });
1267
+
1268
+ // 初始化向导:探测陌生目录(只读,不写配置)
1269
+ router.add('POST', '/api/learn/probe', (c) => {
1270
+ const body = c.body || {};
1271
+ sendJSON(c.res, 200, probeRoot(String(body.root || '')));
1272
+ });
1273
+
1274
+ // v2.9.59 查看原文(只读):材料里点「查看原文」时拉本地 md
1275
+ router.add('GET', '/api/learn/source', (c) => {
1276
+ const page = (c.query && typeof c.query.get === 'function' && c.query.get('page')) || '';
1277
+ sendJSON(c.res, 200, readSource(ctx, page));
1278
+ });
1279
+
1280
+ // v2.9.56 导入器:pdf/docx/html/md/txt → 本地学习库(不写用户知识库)
1281
+ router.add('POST', '/api/learn/import/preview', (c) => {
1282
+ sendJSON(c.res, 200, previewImport((c.body && c.body.path) || ''));
1283
+ });
1284
+
1285
+ router.add('POST', '/api/learn/import', (c) => {
1286
+ sendJSON(c.res, 200, importMaterials(ctx, (c.body && c.body.path) || ''));
1287
+ });
1288
+
1289
+ // 初始化向导:确认后一步落盘 + 建索引 + 试抽预览
1290
+ router.add('POST', '/api/learn/init', async (c) => {
1291
+ sendJSON(c.res, 200, await initLearn(ctx, c.body || {}));
1292
+ });
1293
+
1294
+ // 注意:todayQueue 是 async(出题前可能按需抽一页知识点),必须 await,否则会返回 Promise 序列化成的 {}
1295
+ router.add('GET', '/api/learn/today', async (c) => {
1296
+ sendJSON(c.res, 200, await todayQueue(ctx));
1297
+ });
1298
+
1299
+ router.add('POST', '/api/learn/scan', (c) => {
1300
+ const scanned = scanVault(ctx);
1301
+ const pages = syncPages(ctx, scanned);
1302
+ sendJSON(c.res, 200, { ok: true, root: scanned.root, pages: pages.length, at: scanned.scannedAt });
1303
+ });
1304
+
1305
+ router.add('GET', '/api/learn/items', (c) => {
1306
+ const items = loadItems(ctx);
1307
+ const schedule = loadSchedule(ctx);
1308
+ sendJSON(c.res, 200, items.map((it) => Object.assign(publicItem(it), {
1309
+ level: (schedule[it.id] && schedule[it.id].level) || 0,
1310
+ dueAt: (schedule[it.id] && schedule[it.id].dueAt) || null,
1311
+ needsRewrite: it.needsRewrite === true || (schedule[it.id] && schedule[it.id].needsRewrite === true),
1312
+ excluded: it.excluded === true,
1313
+ })));
1314
+ });
1315
+
1316
+ router.add('POST', '/api/learn/items/:id/exclude', (c) => {
1317
+ const items = loadItems(ctx);
1318
+ const it = items.find((x) => x.id === c.params.id);
1319
+ if (!it) throw new HttpError(404, 'LEARN_ITEM_NOT_FOUND', '条目不存在');
1320
+ it.excluded = !it.excluded;
1321
+ saveJSON(ctx, 'items.json', { items, updatedAt: new Date().toISOString() });
1322
+ sendJSON(c.res, 200, { ok: true, id: it.id, excluded: it.excluded });
1323
+ });
1324
+
1325
+ router.add('POST', '/api/learn/session', (c) => {
1326
+ const body = c.body || {};
1327
+ sendJSON(c.res, 200, stripInternal(createSession(ctx, body.itemId)));
1328
+ });
1329
+
1330
+ router.add('POST', '/api/learn/session/:id/turn', async (c) => {
1331
+ const body = c.body || {};
1332
+ const out = await turn(ctx, c.params.id, String(body.stage || ''), body.text);
1333
+ sendJSON(c.res, 200, out);
1334
+ });
1335
+
1336
+ router.add('POST', '/api/learn/session/:id/finish', (c) => {
1337
+ const body = c.body || {};
1338
+ sendJSON(c.res, 200, finishSession(ctx, c.params.id, body.level, undefined));
1339
+ });
1340
+ }
1341
+
1342
+ module.exports = {
1343
+ LADDER,
1344
+ DECAY_DAYS,
1345
+ validateRoot,
1346
+ probeRoot,
1347
+ initLearn,
1348
+ previewImport,
1349
+ importMaterials,
1350
+ readSource,
1351
+ scopeDirs,
1352
+ stripFrontmatter,
1353
+ makeDigest,
1354
+ scanVault,
1355
+ syncPages,
1356
+ loadPages,
1357
+ loadItems,
1358
+ saveItems,
1359
+ extractConcepts,
1360
+ ensureFreshConcepts,
1361
+ materializeSeeds,
1362
+ conceptMaterial,
1363
+ loadSchedule,
1364
+ loadSessions,
1365
+ applyReview,
1366
+ nextInterval,
1367
+ pickDaily,
1368
+ createSession,
1369
+ turn,
1370
+ finishSession,
1371
+ status,
1372
+ todayQueue,
1373
+ registerLearnRoutes,
1374
+ itemId,
1375
+ };
1376
+
1377
+ /** 当前实例加载的版本 vs 仓库磁盘上的版本(不一致 = 需要重启) */
1378
+ function versionInfo(ctx) {
1379
+ const loaded = String((ctx && ctx.version) || '');
1380
+ let disk = '';
1381
+ try {
1382
+ const pkg = JSON.parse(fs.readFileSync(path.join(ctx.rootDir || process.cwd(), 'package.json'), 'utf8'));
1383
+ disk = String(pkg.version || '');
1384
+ } catch (e) {
1385
+ disk = '';
1386
+ }
1387
+ return { loaded, disk, stale: !!(loaded && disk && loaded !== disk) };
1388
+ }