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/storeDb.js ADDED
@@ -0,0 +1,418 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * storeDb.js — v2.9.33 存储后端抽象的 SQLite 侧核心(红线 3 修订后的执行体)
5
+ *
6
+ * data/fde.db(WAL):第一批承载 messages / task_events 两单元(SPEC-STORAGE §1.1)。
7
+ * - 单元台账:meta 表 key='unit:<name>';进程内缓存一次读取——台账无该单元 = 该单元仍走 JSON
8
+ * (路由以台账为准,绝不以「db 文件存在」为准);迁移器(lib/migration.js)是台账唯一写入方
9
+ * - 读写全部 prepared statement 参数绑定(零拼接——Mimosa 生成前约束+本仓安全纪律)
10
+ * - 损坏:quick_check 失败 → fde.db 改名 *.corrupt-* → throw 503 DATA_CORRUPT(受影响路由
11
+ * 500 loud;**绝不静默回落 JSON 旧数据**——JSON 原档已在迁移时改名归档,回落=拿旧数据当新数据)
12
+ * - 事务:BEGIN IMMEDIATE / COMMIT / ROLLBACK(同步 API;busy_timeout 5s 跨进程排队)
13
+ * - 本模块不建业务表(DDL 归迁移器);openDb 只打开已存在的库
14
+ */
15
+
16
+ const fs = require('node:fs');
17
+ const path = require('node:path');
18
+ const { HttpError } = require('./router');
19
+
20
+ const DB_NAME = 'fde.db';
21
+ const handles = new Map(); // dbPath -> DatabaseSync(进程内单例)
22
+ const ledgerCache = new Map(); // dbPath -> Set(unit)(台账缓存;clearCache 可清)
23
+
24
+ /** dataDir 或某数据文件路径 → fde.db 绝对路径 */
25
+ function dbPathFor(dataDirOrFile) {
26
+ const base = path.extname(dataDirOrFile) ? path.dirname(dataDirOrFile) : dataDirOrFile;
27
+ return path.join(base, DB_NAME);
28
+ }
29
+
30
+ function corrupt(dbPath, reason) {
31
+ const stamp = new Date().toISOString().replace(/[:.]/g, '-');
32
+ const backup = `${dbPath}.corrupt-${stamp}`;
33
+ try {
34
+ fs.renameSync(dbPath, backup);
35
+ console.error(`[storeDb] ${dbPath} quick_check 失败(${reason}),已保全为 ${backup};受影响数据路由将 500,请用备份恢复`);
36
+ } catch (e) {
37
+ console.error(`[storeDb] ${dbPath} 损坏且隔离失败: ${e.message}`);
38
+ }
39
+ handles.delete(dbPath);
40
+ ledgerCache.delete(dbPath);
41
+ }
42
+
43
+ /** 打开已存在的库(单例)。损坏 → 改名保全并 throw;库不存在 → null(调用方走 JSON 路径) */
44
+ function openDb(dbPath) {
45
+ if (handles.has(dbPath)) return handles.get(dbPath);
46
+ if (!fs.existsSync(dbPath)) return null;
47
+ const { DatabaseSync } = require('node:sqlite');
48
+ let db;
49
+ try {
50
+ db = new DatabaseSync(dbPath);
51
+ db.exec('PRAGMA journal_mode = WAL');
52
+ db.exec('PRAGMA synchronous = NORMAL');
53
+ db.exec('PRAGMA busy_timeout = 5000');
54
+ const qc = db.prepare('PRAGMA quick_check').get();
55
+ if (!qc || !/^ok/i.test(String(qc.quick_check || ''))) {
56
+ corrupt(dbPath, String(qc && qc.quick_check));
57
+ throw new HttpError(503, 'DATA_CORRUPT', 'fde.db 完整性检查失败,原库已隔离为 *.corrupt-*,请用备份恢复');
58
+ }
59
+ } catch (e) {
60
+ if (e instanceof HttpError) throw e;
61
+ corrupt(dbPath, (e && e.message) || 'open failed');
62
+ throw new HttpError(503, 'DATA_CORRUPT', `fde.db 打开失败:${(e && e.message) || e}`);
63
+ }
64
+ handles.set(dbPath, db);
65
+ return db;
66
+ }
67
+
68
+ /** 读台账(缓存):meta 表 key LIKE 'unit:%' → Set(unit);无 meta 表 = 空台账 */
69
+ function readLedger(db) {
70
+ const set = new Set();
71
+ try {
72
+ const rows = db.prepare("SELECT key FROM meta WHERE key LIKE 'unit:%'").all();
73
+ for (const r of rows) set.add(String(r.key).slice('unit:'.length));
74
+ } catch (e) {
75
+ return set; // meta 表不存在 = 尚未迁移任何单元
76
+ }
77
+ return set;
78
+ }
79
+
80
+ /** 已迁移单元集合(备份恢复的自动重导入用;库不存在返回 null) */
81
+ function unitsMigrated(dbPath) {
82
+ if (!fs.existsSync(dbPath)) return null;
83
+ const db = openDb(dbPath);
84
+ if (!ledgerCache.has(dbPath)) ledgerCache.set(dbPath, readLedger(db));
85
+ return ledgerCache.get(dbPath);
86
+ }
87
+
88
+ /** 单元路由:'sqlite' | 'json'。库不存在/台账无该单元 → json(零行为变更的默认态) */
89
+ function unitBackend(dataDirOrFile, unit) {
90
+ const dbPath = dbPathFor(dataDirOrFile);
91
+ if (!fs.existsSync(dbPath)) return { backend: 'json', dbPath };
92
+ const db = openDb(dbPath);
93
+ if (!ledgerCache.has(dbPath)) ledgerCache.set(dbPath, readLedger(db));
94
+ return {
95
+ backend: ledgerCache.get(dbPath).has(unit) ? 'sqlite' : 'json',
96
+ dbPath,
97
+ };
98
+ }
99
+
100
+ function inTransaction(db, fn) {
101
+ db.exec('BEGIN IMMEDIATE');
102
+ try {
103
+ const out = fn();
104
+ db.exec('COMMIT');
105
+ return out;
106
+ } catch (e) {
107
+ try { db.exec('ROLLBACK'); } catch (e2) { /* 已回滚/连接异常 */ }
108
+ throw e;
109
+ }
110
+ }
111
+
112
+ // ---------- messages(第一批) ----------
113
+
114
+ const MSG_COLS = 'id, title, source, occurred_at, created_at, analyzed_at, analyze_state, analyze_attempts, data';
115
+
116
+ /** → 消息数组(形状与 JSON 后端逐字段同构:data 列=原始对象真源,投影列只写不读) */
117
+ function loadMessages(dbPath) {
118
+ const db = openDb(dbPath);
119
+ const rows = db.prepare(`SELECT ${MSG_COLS} FROM messages ORDER BY rowid`).all();
120
+ return rows.map((r) => {
121
+ let obj = {};
122
+ try { obj = JSON.parse(r.data); } catch (e) { obj = {}; }
123
+ // data 为真源;投影列仅兜底(防御 data 缺键的极端行)
124
+ return Object.assign(obj, {
125
+ id: obj.id || r.id,
126
+ title: obj.title === undefined ? r.title : obj.title,
127
+ });
128
+ });
129
+ }
130
+
131
+ /** 全量替换语义(与 JSON 后端同构):事务内 DELETE ALL + INSERT 全量 */
132
+ function saveMessages(dbPath, messages) {
133
+ const db = openDb(dbPath);
134
+ const ins = db.prepare(
135
+ `INSERT INTO messages (${MSG_COLS}) VALUES (?,?,?,?,?,?,?,?,?)`
136
+ );
137
+ inTransaction(db, () => {
138
+ db.exec('DELETE FROM messages');
139
+ for (const m of Array.isArray(messages) ? messages : []) {
140
+ if (!m || typeof m.id !== 'string') continue; // 坏行不静默入库(与 JSON 形状校验同口径)
141
+ ins.run(
142
+ m.id,
143
+ m.title === undefined ? null : String(m.title),
144
+ m.source === undefined ? null : String(m.source),
145
+ m.occurredAt === undefined ? null : String(m.occurredAt),
146
+ m.createdAt === undefined ? null : String(m.createdAt),
147
+ m.analyzedAt === undefined ? null : String(m.analyzedAt),
148
+ m.analyzeState === undefined ? null : String(m.analyzeState),
149
+ Number.isFinite(m.analyzeAttempts) ? m.analyzeAttempts : 0,
150
+ JSON.stringify(m)
151
+ );
152
+ }
153
+ });
154
+ }
155
+
156
+ // ---------- task_events(第一批) ----------
157
+
158
+ /** → 事件数组(列封闭七字段,映射回 JSON 后端键名 id/taskId/from/to) */
159
+ function loadEvents(dbPath) {
160
+ const db = openDb(dbPath);
161
+ const rows = db
162
+ .prepare('SELECT event_id, task_id, type, from_v, to_v, detail, at FROM task_events ORDER BY seq')
163
+ .all();
164
+ return rows.map((r) => ({
165
+ id: r.event_id,
166
+ taskId: r.task_id,
167
+ type: r.type,
168
+ from: r.from_v,
169
+ to: r.to_v,
170
+ detail: r.detail,
171
+ at: r.at,
172
+ }));
173
+ }
174
+
175
+ /** 全量替换语义(含双重裁剪):事务内 DELETE ALL + INSERT 全量 + 裁剪(saveEvents 的 db 路径) */
176
+ function saveEventsSqlite(dbPath, events, globalLimit, perTaskLimit) {
177
+ const db = openDb(dbPath);
178
+ const ins = db.prepare(
179
+ 'INSERT INTO task_events (event_id, task_id, type, from_v, to_v, detail, at) VALUES (?,?,?,?,?,?,?)'
180
+ );
181
+ inTransaction(db, () => {
182
+ db.exec('DELETE FROM task_events');
183
+ for (const e of Array.isArray(events) ? events : []) {
184
+ if (!e || typeof e.id !== 'string' || typeof e.taskId !== 'string') continue;
185
+ ins.run(e.id, e.taskId, String(e.type || ''), e.from === undefined ? null : String(e.from), e.to === undefined ? null : String(e.to), e.detail === undefined ? null : String(e.detail), String(e.at || ''));
186
+ }
187
+ trimEvents(db, Number(globalLimit), Number(perTaskLimit));
188
+ });
189
+ }
190
+
191
+ /** 双重裁剪:全局 5000 丢最旧 + 每任务 100 丢最旧(保留条数语义与 JSON 版逐条同构)
192
+ * 边界用 seq <(严格小于)第 N 新的 seq——`<=` 会把边界行也删掉(差一缺陷,单测抓到)。
193
+ * 全程 prepared statement 参数绑定(LIMIT/OFFSET 亦可绑定——零字符串拼装 SQL) */
194
+ function trimEvents(db, globalLimit, perTaskLimit) {
195
+ db.prepare(
196
+ `DELETE FROM task_events WHERE seq < (
197
+ SELECT seq FROM task_events ORDER BY seq DESC LIMIT 1 OFFSET ?
198
+ )`
199
+ ).run(Number(globalLimit) - 1);
200
+ const tasks = db.prepare('SELECT DISTINCT task_id FROM task_events').all();
201
+ for (const t of tasks) {
202
+ db.prepare(
203
+ `DELETE FROM task_events WHERE task_id = ? AND seq < (
204
+ SELECT seq FROM task_events WHERE task_id = ? ORDER BY seq DESC LIMIT 1 OFFSET ?
205
+ )`
206
+ ).run(t.task_id, t.task_id, Number(perTaskLimit) - 1);
207
+ }
208
+ }
209
+
210
+ /**
211
+ * 追加 + 双重裁剪(全局 5000 / 每任务 100),单事务(消除 JSON 读-改-写竞态)。
212
+ * 与 JSON 版语义逐条同构:追加 list → 全局超限丢最旧 → 每任务超限丢最旧。
213
+ */
214
+ function appendEvents(dbPath, list, globalLimit, perTaskLimit) {
215
+ const db = openDb(dbPath);
216
+ const items = Array.isArray(list) ? list : [];
217
+ if (!items.length) return;
218
+ const ins = db.prepare(
219
+ 'INSERT INTO task_events (event_id, task_id, type, from_v, to_v, detail, at) VALUES (?,?,?,?,?,?,?)'
220
+ );
221
+ inTransaction(db, () => {
222
+ for (const e of items) {
223
+ if (!e || typeof e.id !== 'string' || typeof e.taskId !== 'string') continue;
224
+ ins.run(e.id, e.taskId, String(e.type || ''), e.from === undefined ? null : String(e.from), e.to === undefined ? null : String(e.to), e.detail === undefined ? null : String(e.detail), String(e.at || ''));
225
+ }
226
+ trimEvents(db, Number(globalLimit), Number(perTaskLimit));
227
+ });
228
+ }
229
+
230
+ /** 删除某任务全部事件(removeTaskEvents 的 db 路径);返回删除条数(与 JSON 版返回语义同构) */
231
+ function deleteEventsForTask(dbPath, taskId) {
232
+ const db = openDb(dbPath);
233
+ const r = db.prepare('DELETE FROM task_events WHERE task_id = ?').run(String(taskId));
234
+ return Number(r.changes);
235
+ }
236
+
237
+ /** 测试/运维:清进程内缓存(连接与台账) */
238
+ function clearCache() {
239
+ for (const db of handles.values()) {
240
+ try { db.close(); } catch (e) { /* 幂等 */ }
241
+ }
242
+ handles.clear();
243
+ ledgerCache.clear();
244
+ }
245
+
246
+ // ---------- tasks / activities / inbox / diary(第二批) ----------
247
+ // 语义均为「全量替换」(调用方契约不变):事务内 DELETE ALL + INSERT 全量;tasks diff 键=id。
248
+ // 投影列只写不读(data 列唯一真源,SPEC-STORAGE §2.1)。
249
+
250
+ const TASK_COLS = 'id, status, priority, project_dir, branch, repo, member_id, acceptor_id, due_date, created_at, updated_at, completed_at, data';
251
+
252
+ function loadTasks(dbPath) {
253
+ const db = openDb(dbPath);
254
+ const rows = db.prepare(`SELECT ${TASK_COLS} FROM tasks ORDER BY rowid`).all();
255
+ return rows.map((r) => {
256
+ let obj = {};
257
+ try { obj = JSON.parse(r.data); } catch (e) { obj = {}; }
258
+ return Object.assign(obj, { id: obj.id || r.id });
259
+ });
260
+ }
261
+
262
+ function saveTasks(dbPath, data) {
263
+ const db = openDb(dbPath);
264
+ const list = Array.isArray(data && data.tasks) ? data.tasks : [];
265
+ const ins = db.prepare(
266
+ `INSERT INTO tasks (${TASK_COLS}) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)`
267
+ );
268
+ inTransaction(db, () => {
269
+ db.exec('DELETE FROM tasks');
270
+ for (const t of list) {
271
+ if (!t || typeof t.id !== 'string') continue;
272
+ ins.run(
273
+ t.id,
274
+ String(t.status || ''),
275
+ t.priority === undefined ? null : String(t.priority),
276
+ t.projectDir === undefined ? null : String(t.projectDir),
277
+ t.branch === undefined ? null : String(t.branch),
278
+ t.repo === undefined ? null : String(t.repo),
279
+ t.memberId === undefined ? null : String(t.memberId),
280
+ t.acceptorId === undefined ? null : String(t.acceptorId),
281
+ t.dueDate === undefined ? null : String(t.dueDate),
282
+ t.createdAt === undefined ? null : String(t.createdAt),
283
+ t.updatedAt === undefined ? null : String(t.updatedAt),
284
+ t.completedAt === undefined ? null : String(t.completedAt),
285
+ JSON.stringify(t)
286
+ );
287
+ }
288
+ });
289
+ }
290
+
291
+ function loadActivities(dbPath) {
292
+ const db = openDb(dbPath);
293
+ const rows = db.prepare('SELECT data FROM activities ORDER BY rowid').all();
294
+ return rows.map((r) => {
295
+ try { return JSON.parse(r.data); } catch (e) { return {}; }
296
+ });
297
+ }
298
+
299
+ function saveActivities(dbPath, activities) {
300
+ const db = openDb(dbPath);
301
+ const ins = db.prepare(
302
+ 'INSERT INTO activities (url, type, actor, repo, branch, sha, title, message_body, occurred_at, fetched_at, data) VALUES (?,?,?,?,?,?,?,?,?,?,?)'
303
+ );
304
+ inTransaction(db, () => {
305
+ db.exec('DELETE FROM activities');
306
+ for (const a of Array.isArray(activities) ? activities : []) {
307
+ if (!a || typeof a.url !== 'string' || !a.url) continue; // 幂等键必须有
308
+ ins.run(
309
+ a.url,
310
+ String(a.type || ''),
311
+ a.actor === undefined ? null : String(a.actor),
312
+ a.repo === undefined ? null : String(a.repo),
313
+ a.branch === undefined ? null : String(a.branch),
314
+ a.sha === undefined ? null : String(a.sha),
315
+ a.title === undefined ? null : String(a.title),
316
+ a.messageBody === undefined ? null : String(a.messageBody),
317
+ a.occurredAt === undefined ? null : String(a.occurredAt),
318
+ a.fetchedAt === undefined ? null : String(a.fetchedAt),
319
+ JSON.stringify(a)
320
+ );
321
+ }
322
+ });
323
+ }
324
+
325
+ function loadInbox(dbPath) {
326
+ const db = openDb(dbPath);
327
+ const rows = db.prepare('SELECT data FROM inbox ORDER BY rowid').all();
328
+ return rows.map((r) => {
329
+ try { return JSON.parse(r.data); } catch (e) { return {}; }
330
+ });
331
+ }
332
+
333
+ function saveInbox(dbPath, candidates) {
334
+ const db = openDb(dbPath);
335
+ const ins = db.prepare(
336
+ 'INSERT INTO inbox (id, kind, message_id, state, confidence, suggested_member_id, existing_task_id, created_at, decided_at, data) VALUES (?,?,?,?,?,?,?,?,?,?)'
337
+ );
338
+ inTransaction(db, () => {
339
+ db.exec('DELETE FROM inbox');
340
+ for (const c of Array.isArray(candidates) ? candidates : []) {
341
+ if (!c || typeof c.id !== 'string') continue;
342
+ ins.run(
343
+ c.id,
344
+ String(c.kind || 'task'),
345
+ c.messageId === undefined ? null : String(c.messageId),
346
+ String(c.state || 'pending'),
347
+ Number.isFinite(c.confidence) ? c.confidence : null,
348
+ c.suggestedMemberId === undefined ? null : String(c.suggestedMemberId),
349
+ c.existingTaskId === undefined ? null : String(c.existingTaskId),
350
+ c.createdAt === undefined ? null : String(c.createdAt),
351
+ c.decidedAt === undefined ? null : String(c.decidedAt),
352
+ JSON.stringify(c)
353
+ );
354
+ }
355
+ });
356
+ }
357
+
358
+ function loadDiaries(dbPath) {
359
+ const db = openDb(dbPath);
360
+ const rows = db.prepare('SELECT task_id, date, content, updated_at FROM diary ORDER BY rowid').all();
361
+ return rows.map((r) => ({ taskId: r.task_id, date: r.date, content: r.content, updatedAt: r.updated_at }));
362
+ }
363
+
364
+ function saveDiaries(dbPath, diaries) {
365
+ const db = openDb(dbPath);
366
+ const ins = db.prepare(
367
+ 'INSERT INTO diary (task_id, date, content, updated_at) VALUES (?,?,?,?)'
368
+ );
369
+ inTransaction(db, () => {
370
+ db.exec('DELETE FROM diary');
371
+ for (const d of Array.isArray(diaries) ? diaries : []) {
372
+ if (!d || typeof d.taskId !== 'string' || typeof d.date !== 'string') continue;
373
+ ins.run(d.taskId, d.date, String(d.content || ''), d.updatedAt === undefined ? null : String(d.updatedAt));
374
+ }
375
+ });
376
+ }
377
+
378
+ // ---------- learn(第二批,单文档行——SPEC-STORAGE §2.4) ----------
379
+
380
+ /** → 文档对象或 null(无该单元行);形状与 learn/*.json 完全一致 */
381
+ function loadLearnDoc(dbPath, unit) {
382
+ const db = openDb(dbPath);
383
+ const r = db.prepare('SELECT data FROM learn_docs WHERE unit = ?').get(String(unit));
384
+ if (!r) return null;
385
+ try { return JSON.parse(r.data); } catch (e) { return null; }
386
+ }
387
+
388
+ /** 单文档 upsert(learn_docs 五单元) */
389
+ function saveLearnDoc(dbPath, unit, doc) {
390
+ const db = openDb(dbPath);
391
+ db.prepare(
392
+ 'INSERT INTO learn_docs (unit, data, updated_at) VALUES (?,?,?) ON CONFLICT(unit) DO UPDATE SET data=excluded.data, updated_at=excluded.updated_at'
393
+ ).run(String(unit), JSON.stringify(doc), new Date().toISOString());
394
+ }
395
+
396
+ module.exports = {
397
+ DB_NAME,
398
+ dbPathFor,
399
+ unitBackend,
400
+ unitsMigrated,
401
+ loadMessages,
402
+ saveMessages,
403
+ loadEvents,
404
+ saveEventsSqlite,
405
+ appendEvents,
406
+ deleteEventsForTask,
407
+ loadTasks,
408
+ saveTasks,
409
+ loadActivities,
410
+ saveActivities,
411
+ loadInbox,
412
+ saveInbox,
413
+ loadDiaries,
414
+ saveDiaries,
415
+ loadLearnDoc,
416
+ saveLearnDoc,
417
+ clearCache,
418
+ };
@@ -0,0 +1,243 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * taskEvents.js — v1.7 任务事件流(时间轴数据源)
5
+ *
6
+ * - 存储 data/task_events.json:事件 {id, taskId, type, from, to, detail, at},追加式
7
+ * - 双重上限防膨胀:每任务保留最近 100 条(超出丢最旧);全文件上限 5000 条(丢最旧)
8
+ * - 事件类型:created / status / completed(进 done 的 status 特化)/ assign / due / priority / edit;
9
+ * v1.9 新增 memo(更新提案确认,来源收件箱,detail=纪要《标题》:引用原句)
10
+ * 与 artifact(Gitea 成果手动挂接,detail=挂接成果:kind repo);
11
+ * v2.0 新增 accept(v2.0 验收签字事件:验收人变更/清除,进 done 且已有验收人时联动「验收通过」)
12
+ * - 防噪:同一次 PATCH 多字段变更按字段类型合并——每类型最多一条
13
+ * - 删任务时顺带清理其事件(removeTaskEvents);存量老任务不回填(详情自然为空数组)
14
+ */
15
+
16
+ const store = require('./store');
17
+ const storeDb = require('./storeDb');
18
+ const path = require('node:path');
19
+
20
+ const PER_TASK_LIMIT = 100;
21
+ const GLOBAL_LIMIT = 5000;
22
+
23
+ /** v2.9.33 存储后端路由:台账标记 task_events 已迁移 → SQLite(ctx 路径仅用于推导 data 目录) */
24
+ function eventsBackend(ctx) {
25
+ return storeDb.unitBackend(path.dirname(ctx.taskEventsPath), 'task_events');
26
+ }
27
+ function eventsDbPath(ctx) {
28
+ return storeDb.dbPathFor(path.dirname(ctx.taskEventsPath));
29
+ }
30
+
31
+ function genEventId() {
32
+ return `e-${Date.now().toString(36)}-${store.randomToken(6)}`;
33
+ }
34
+
35
+ /** 事件落盘形态:{events:[...]} 或裸数组均容忍;缺失回退空 */
36
+ function loadEvents(ctx) {
37
+ if (eventsBackend(ctx).backend === 'sqlite') return storeDb.loadEvents(eventsDbPath(ctx));
38
+ const d = store.readJSON(ctx.taskEventsPath, null);
39
+ if (Array.isArray(d)) return d;
40
+ if (store.isPlainObject(d) && Array.isArray(d.events)) return d.events;
41
+ return [];
42
+ }
43
+
44
+ function saveEvents(ctx, events) {
45
+ if (eventsBackend(ctx).backend === 'sqlite') {
46
+ // 全量替换语义保留:事务内 DELETE ALL + INSERT(JSON 版调用方契约不变)
47
+ storeDb.saveEventsSqlite(eventsDbPath(ctx), events, GLOBAL_LIMIT, PER_TASK_LIMIT);
48
+ return;
49
+ }
50
+ store.writeJSON(ctx.taskEventsPath, { events });
51
+ }
52
+
53
+ /**
54
+ * 追加事件并施加双重上限(均丢最旧):
55
+ * ① 全文件 > 5000 → 截保留最新 5000;② 单任务 > 100 → 该任务只留最新 100。
56
+ * 裁剪只在实际超限时发生,避免常量改写放大写放大。
57
+ * v2.9.33:task_events 已迁移时走单事务 SQLite 路径(追加+裁剪同事务,消除读-改-写竞态)
58
+ */
59
+ function appendEvents(ctx, list) {
60
+ if (!Array.isArray(list) || list.length === 0) return;
61
+ if (eventsBackend(ctx).backend === 'sqlite') {
62
+ storeDb.appendEvents(eventsDbPath(ctx), list, GLOBAL_LIMIT, PER_TASK_LIMIT);
63
+ } else {
64
+ let events = loadEvents(ctx).concat(list);
65
+ if (events.length > GLOBAL_LIMIT) events = events.slice(events.length - GLOBAL_LIMIT);
66
+
67
+ const countByTask = new Map();
68
+ for (const e of events) countByTask.set(e.taskId, (countByTask.get(e.taskId) || 0) + 1);
69
+ const over = [];
70
+ for (const [taskId, n] of countByTask) {
71
+ if (n > PER_TASK_LIMIT) over.push([taskId, n - PER_TASK_LIMIT]); // 需从头丢弃的条数
72
+ }
73
+ if (over.length > 0) {
74
+ const drop = new Map(over);
75
+ const seen = new Map();
76
+ events = events.filter((e) => {
77
+ if (!drop.has(e.taskId)) return true;
78
+ const n = (seen.get(e.taskId) || 0) + 1;
79
+ seen.set(e.taskId, n);
80
+ return n > drop.get(e.taskId); // 丢最旧 drop.get(taskId) 条
81
+ });
82
+ }
83
+ saveEvents(ctx, events);
84
+ }
85
+ // v2.9.27 Webhook 出口:fire-and-forget(绝不影响任务写路径);v2.9.29 D1 修复——
86
+ // 传懒加载器(webhookOut 内 60s TTL 缓存),禁用态不再每事件一次同步 config 读盘
87
+ try {
88
+ require('./webhookOut.js').fireTaskEvents(() => require('./giteaClient').loadConfig(), list);
89
+ } catch (e) {
90
+ console.error('[taskEvents] webhook 派发入口异常(不影响落盘):', String((e && e.message) || e));
91
+ }
92
+ // v2.9.39 IM 通知(飞书/钉钉):同样 fire-and-forget;只推 config.im.events 打开的两类
93
+ //(待验收 / 已完成),未开启时零出网。异常不得影响任务写路径。
94
+ try {
95
+ require('./imNotify.js').fireTaskEvents(ctx, list);
96
+ } catch (e) {
97
+ console.error('[taskEvents] IM 派发入口异常(不影响落盘):', String((e && e.message) || e));
98
+ }
99
+ }
100
+
101
+ /** 某任务的事件,倒序(最新在前),≤100 条 */
102
+ function eventsForTask(ctx, taskId) {
103
+ const events = loadEvents(ctx);
104
+ const out = [];
105
+ for (let i = events.length - 1; i >= 0 && out.length < PER_TASK_LIMIT; i--) {
106
+ if (events[i] && events[i].taskId === taskId) out.push(events[i]);
107
+ }
108
+ return out;
109
+ }
110
+
111
+ /** 删任务时顺带清理其事件;文件本就无该任务事件时不写盘(legacy 删除零写放大) */
112
+ function removeTaskEvents(ctx, taskId) {
113
+ if (eventsBackend(ctx).backend === 'sqlite') {
114
+ return storeDb.deleteEventsForTask(eventsDbPath(ctx), taskId);
115
+ }
116
+ const events = loadEvents(ctx);
117
+ const kept = events.filter((e) => e && e.taskId !== taskId);
118
+ if (kept.length !== events.length) saveEvents(ctx, kept);
119
+ return events.length - kept.length;
120
+ }
121
+
122
+ function makeEvent(taskId, type, from, to, detail, at) {
123
+ return { id: genEventId(), taskId, type, from: from === undefined ? null : from, to: to === undefined ? null : to, detail: detail || '', at };
124
+ }
125
+
126
+ /** created 事件:detail 含 origin 来源描述(收件箱确认入库任务),手工创建注明之 */
127
+ function createdEvent(task, at) {
128
+ const origin = task && task.origin;
129
+ const detail =
130
+ origin && origin.type === 'inbox'
131
+ ? `来源:收件箱候选 ${origin.refId}`
132
+ : '手工创建';
133
+ return makeEvent(task.id, 'created', null, task.status, detail, at);
134
+ }
135
+
136
+ /** assign 的 from/to 描述:agent:xx + member:yy,均空为「未指派」(双向清空也记) */
137
+ function assignDesc(t) {
138
+ const parts = [];
139
+ if (t.agentId) parts.push(`agent:${t.agentId}`);
140
+ if (t.memberId) parts.push(`member:${t.memberId}`);
141
+ return parts.length ? parts.join(' + ') : '未指派';
142
+ }
143
+
144
+ /**
145
+ * PATCH 前后差异 → 事件列表(防噪:每字段类型最多一条)。
146
+ * @param oldV/newV 变更前后的字段快照 {status, agentId, memberId, acceptorId, dueDate, priority, title, desc, notes}
147
+ */
148
+ function patchEvents(taskId, oldV, newV, at) {
149
+ const evts = [];
150
+ // status:to === "done" 时类型特化为 completed
151
+ if (oldV.status !== newV.status) {
152
+ if (newV.status === 'done') {
153
+ evts.push(makeEvent(taskId, 'completed', oldV.status, 'done', `状态 ${oldV.status} → done,任务完成`, at));
154
+ } else {
155
+ evts.push(makeEvent(taskId, 'status', oldV.status, newV.status, `状态 ${oldV.status} → ${newV.status}`, at));
156
+ }
157
+ }
158
+ // assign:agentId 或 memberId 任一变更,一次 PATCH 合并为一条(detail 注明改了哪个字段)
159
+ if (oldV.agentId !== newV.agentId || oldV.memberId !== newV.memberId) {
160
+ const changed = [];
161
+ if (oldV.agentId !== newV.agentId) changed.push('agentId');
162
+ if (oldV.memberId !== newV.memberId) changed.push('memberId');
163
+ evts.push(makeEvent(taskId, 'assign', assignDesc(oldV), assignDesc(newV), `指派变更(${changed.join('、')})`, at));
164
+ }
165
+ // v2.0:accept——验收签字人变更/清除(独立于 assign:验收签字与负责人/执行者语义分离)
166
+ if (oldV.acceptorId !== newV.acceptorId) {
167
+ evts.push(
168
+ makeEvent(
169
+ taskId,
170
+ 'accept',
171
+ oldV.acceptorId,
172
+ newV.acceptorId,
173
+ newV.acceptorId === null ? '清除验收人' : '验收人变更',
174
+ at
175
+ )
176
+ );
177
+ }
178
+ // due:to 为新值或「清除」
179
+ if (oldV.dueDate !== newV.dueDate) {
180
+ evts.push(makeEvent(taskId, 'due', oldV.dueDate, newV.dueDate === null ? '清除' : newV.dueDate, '截止时间变更', at));
181
+ }
182
+ // priority
183
+ if (oldV.priority !== newV.priority) {
184
+ evts.push(makeEvent(taskId, 'priority', oldV.priority, newV.priority, `优先级 ${oldV.priority} → ${newV.priority}`, at));
185
+ }
186
+ // v2.9.4:bind——项目目录绑定/解绑(绑定≠挂接:ambient 关联,进时间轴可溯)
187
+ if (oldV.projectDir !== newV.projectDir) {
188
+ evts.push(
189
+ makeEvent(
190
+ taskId,
191
+ 'bind',
192
+ oldV.projectDir,
193
+ newV.projectDir == null ? null : newV.projectDir,
194
+ newV.projectDir == null ? '解绑项目目录' : `绑定项目目录 ${newV.projectDir}`,
195
+ at
196
+ )
197
+ );
198
+ }
199
+ // edit:title/desc/notes 变更,detail 注明改了什么字段,不存全文
200
+ const edited = [];
201
+ for (const f of ['title', 'desc', 'notes']) {
202
+ if (oldV[f] !== newV[f]) edited.push(f);
203
+ }
204
+ if (edited.length > 0) {
205
+ evts.push(makeEvent(taskId, 'edit', null, null, `编辑了 ${edited.join('、')}`, at));
206
+ }
207
+ // v2.0:done 联动——进 done 且已有验收人时额外补一条「验收通过」事件(与 completed 事件独立,
208
+ // 验收人为空时不发)
209
+ if (oldV.status !== newV.status && newV.status === 'done' && newV.acceptorId) {
210
+ evts.push(makeEvent(taskId, 'accept', null, newV.acceptorId, `验收通过:by ${newV.acceptorId}`, at));
211
+ }
212
+ return evts;
213
+ }
214
+
215
+ /** PATCH 快照(只取事件相关字段,避免引用逃逸) */
216
+ function snapshotOf(task) {
217
+ return {
218
+ status: task.status,
219
+ agentId: task.agentId,
220
+ memberId: task.memberId,
221
+ acceptorId: task.acceptorId, // v2.0:验收签字人(accept 事件差分依据)
222
+ dueDate: task.dueDate,
223
+ priority: task.priority,
224
+ title: task.title,
225
+ desc: task.desc,
226
+ notes: task.notes,
227
+ projectDir: task.projectDir, // v2.9.4:项目绑定/解绑差分依据
228
+ };
229
+ }
230
+
231
+ module.exports = {
232
+ PER_TASK_LIMIT,
233
+ GLOBAL_LIMIT,
234
+ loadEvents,
235
+ saveEvents,
236
+ appendEvents,
237
+ eventsForTask,
238
+ removeTaskEvents,
239
+ makeEvent,
240
+ createdEvent,
241
+ patchEvents,
242
+ snapshotOf,
243
+ };