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
@@ -0,0 +1,111 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * scorecard.js — v2.9.27 数字员工 Scorecard 传播卡(README 徽章式 SVG)
5
+ *
6
+ * GET /api/scorecard/<agent>.svg → 深色主题 SVG 卡片:
7
+ * agent 名 + 近 28 天 会话数 / 活跃分钟 / 触达项目数 / 最近活跃。
8
+ * 数据面:复用 heatmap.buildHeatmap(listAgentSessions 每源 50 条帽,只读零写盘)。
9
+ * 无该源数据 → 404 SCORECARD_NOT_FOUND(徽章显示 0 无意义,宁缺)。
10
+ * 输出 Content-Type: image/svg+xml(sendJSON 不适用,原生 res 写)。
11
+ * 数字全部来自本机观测,文案不夸大(传播卡纪律:数字即事实)。
12
+ */
13
+
14
+ const at = require('./agentTranscript');
15
+ const heatmap = require('./heatmap');
16
+ const snapshot = require('./sessionSnapshot');
17
+ const { HttpError } = require('./router');
18
+
19
+ const AGENT_LABEL = { zcode: 'ZCode', claude: 'Claude Code', dsh: 'DSH', workbuddy: 'WorkBuddy', codex: 'Codex', opencode: 'OpenCode' };
20
+
21
+ function esc(s) {
22
+ return String(s == null ? '' : s).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
23
+ }
24
+
25
+ /** 分钟 → 人读(如 3.2h / 45m) */
26
+ function fmtMinutes(m) {
27
+ if (m >= 600) return (m / 60).toFixed(1) + 'h';
28
+ return String(m) + 'm';
29
+ }
30
+
31
+ /**
32
+ * buildScorecard(config, agent, opts) → {agent,label,sessions,minutes,projects,lastActive,svg}
33
+ * @param {{now?:number, adapters?:object}} opts(adapters 同 heatmap 纯注入语义)
34
+ */
35
+ function buildScorecard(config, agent, opts) {
36
+ const o = opts || {};
37
+ if (!at.SOURCE_IDS.includes(agent)) throw new HttpError(400, 'BAD_AGENT', 'agent 必须为六源 id 之一');
38
+ // v2.9.29 D3:直接吃共享快照(原实现寄居 buildHeatmap 再补一遍 list——双倍扫描已消灭)
39
+ const { byAgent } = snapshot.getSnapshot(config, { now: o.now, adapters: o.adapters });
40
+ const DAY_MS = 24 * 3600 * 1000;
41
+ const WINDOW_MS = 28 * DAY_MS;
42
+ const now = Number.isFinite(o.now) ? o.now : Date.now();
43
+ let mySessions = 0;
44
+ let myMinutes = 0;
45
+ let lastActiveMs = null;
46
+ const projects = new Set();
47
+ for (const it of byAgent[agent] || []) {
48
+ const lastMs = Date.parse(it.lastActiveAt);
49
+ if (!Number.isFinite(lastMs) || lastMs < now - WINDOW_MS) continue; // 与热力图同窗口径
50
+ mySessions += 1;
51
+ const startMs = Date.parse(it.startedAt);
52
+ myMinutes += Number.isFinite(startMs) && lastMs > startMs
53
+ ? Math.min(Math.max(Math.round((lastMs - startMs) / 60000), 1), 360)
54
+ : 1;
55
+ if (lastMs && (lastActiveMs === null || lastMs > lastActiveMs)) lastActiveMs = lastMs;
56
+ if (it.projectId) projects.add(String(it.projectId));
57
+ }
58
+ if (mySessions === 0) throw new HttpError(404, 'SCORECARD_NOT_FOUND', '该源近 28 天无会话数据');
59
+ const lastActiveDaysAgo = lastActiveMs !== null
60
+ ? Math.max(0, Math.round((now - lastActiveMs) / DAY_MS))
61
+ : null;
62
+ const label = AGENT_LABEL[agent] || agent;
63
+ const svg = renderSvg({ agent, label, sessions: mySessions, minutes: myMinutes, projects: projects.size, lastActiveDaysAgo });
64
+ return { agent, label, sessions: mySessions, minutes: myMinutes, projects: projects.size, svg };
65
+ }
66
+
67
+ function renderSvg(m) {
68
+ const W = 460;
69
+ const H = 132;
70
+ return `<svg xmlns="http://www.w3.org/2000/svg" width="${W}" height="${H}" viewBox="0 0 ${W} ${H}" role="img" aria-label="${esc(m.label)} scorecard">
71
+ <rect x="1" y="1" width="${W - 2}" height="${H - 2}" rx="10" fill="#0f1216" stroke="rgba(148,163,184,.26)"/>
72
+ <text x="20" y="34" font-family="Segoe UI,sans-serif" font-size="17" font-weight="700" fill="#e7ebf2">${esc(m.label)}</text>
73
+ <text x="${W - 20}" y="34" text-anchor="end" font-family="Segoe UI,sans-serif" font-size="11" fill="#8b93a3">FDE Console · 28d</text>
74
+ ${statCell(20, 58, String(m.sessions), 'sessions')}
75
+ ${statCell(130, 58, fmtMinutes(m.minutes), 'active time')}
76
+ ${statCell(240, 58, String(m.projects), 'projects')}
77
+ ${statCell(350, 58, esc(fmtAgoDays(m.lastActiveDaysAgo)), 'last active')}
78
+ <text x="20" y="${H - 14}" font-family="Segoe UI,sans-serif" font-size="10" fill="#8b93a3">local-only · cap 50 sessions/src · docs/ADAPTERS.md</text>
79
+ </svg>`;
80
+ }
81
+
82
+ function fmtAgoDays(d) {
83
+ if (d === null || d === undefined) return '—';
84
+ if (d === 0) return 'today';
85
+ return d + 'd ago';
86
+ }
87
+
88
+ function statCell(x, y, value, label) {
89
+ return `<text x="${x}" y="${y + 22}" font-family="Consolas,monospace" font-size="22" font-weight="700" fill="#34d399">${esc(value)}</text>
90
+ <text x="${x}" y="${y + 40}" font-family="Segoe UI,sans-serif" font-size="10" fill="#8b93a3">${esc(label)}</text>`;
91
+ }
92
+
93
+ /** 路由挂载:GET /api/scorecard/<agent>[.svg](router :param 捕获整段,.svg 后缀在 handler 内剥) */
94
+ function registerScorecardRoute(router, ctx) {
95
+ router.add('GET', '/api/scorecard/:agent', (c) => {
96
+ let r;
97
+ try {
98
+ r = buildScorecard(ctx.config, String(c.params.agent || '').replace(/\.svg$/i, ''), {});
99
+ } catch (e) {
100
+ const status = e instanceof HttpError ? e.status : 500;
101
+ const body = JSON.stringify({ error: { code: (e && e.code) || 'INTERNAL', message: (e && e.message) || 'internal' } });
102
+ c.res.writeHead(status, { 'Content-Type': 'application/json; charset=utf-8' });
103
+ c.res.end(body);
104
+ return;
105
+ }
106
+ c.res.writeHead(200, { 'Content-Type': 'image/svg+xml; charset=utf-8', 'Cache-Control': 'no-cache' });
107
+ c.res.end(r.svg);
108
+ });
109
+ }
110
+
111
+ module.exports = { buildScorecard, renderSvg, registerScorecardRoute, AGENT_LABEL };
@@ -0,0 +1,227 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * sessionRef.js — 会话不透明引用(SPEC-READER v2.3 D1):编解码 + 双闸校验单一收口
5
+ *
6
+ * 结构:base64url(JSON {s:源 id, k:locator 种类, v:locator 对象})。仅后端构造,出现在
7
+ * 会话列表条目、activity 条目(可选 ref)中;客户端永不持有原始路径,穿越面收口到本模块。
8
+ *
9
+ * 校验流水线(§3.3,任一不过 → HttpError 400 BAD_REF,错误信息一律不回显解析后路径):
10
+ * ① base64url + JSON 解码;
11
+ * ② s ∈ 六源、k ∈ 该源 locator 白名单;
12
+ * ③ v 逐字段过白名单正则(形态见 §3.4 映射表 + §10 spike 回写:zcode id 实测含
13
+ * sess_<uuid> / session_<hex32> / sess_subagent_agent_<uuid> 三形态,与目录名同名同形);
14
+ * ④ 路径类 locator(claude/dsh/codex):path.resolve 后 realpath 必须 startsWith 对应源根
15
+ * (config.agentActivity.sources.*.root 推导);文件不存在同样按 BAD_REF 处理(规格字面:
16
+ * realpath 任一不过 → 400;id 类 locator 不触 fs,无此闸);
17
+ * ⑤ 无状态、不落库、无失效问题。
18
+ *
19
+ * 红线:本模块对任何源零写入;绝不把解码后的 v 原文拼进错误消息(防探测)。
20
+ */
21
+
22
+ const fs = require('node:fs');
23
+ const path = require('node:path');
24
+ const { HttpError } = require('./router');
25
+
26
+ const SOURCE_IDS = ['zcode', 'claude', 'dsh', 'codex', 'opencode', 'workbuddy', 'hermes'];
27
+
28
+ /** 各源 locator 种类白名单(§3.4) */
29
+ const LOCATOR_KINDS = {
30
+ zcode: ['session'],
31
+ claude: ['project'],
32
+ dsh: ['file'],
33
+ codex: ['file'],
34
+ opencode: ['session'],
35
+ workbuddy: ['session'],
36
+ hermes: ['session'],
37
+ };
38
+
39
+ // ---------- 各源 locator 字段正则(§3.4 + spike R1 回写) ----------
40
+
41
+ /** zcode session id 实测三形态:sess_<uuid> / session_<hex32> / sess_subagent_agent_<uuid>(R1) */
42
+ const ZCODE_ID_RE = /^(?:sess(?:_subagent_agent)?|session)_[0-9a-f][0-9a-f-]{7,120}$/i;
43
+ /** opencode session id 实测形态:ses_ + 24 位大小写字母数字(spike 回写:非 uuid) */
44
+ const OPENCODE_ID_RE = /^ses_[A-Za-z0-9]{8,64}$/;
45
+ /** workbuddy session id:sessions 表主键(保守字符集,杜绝路径/SQL 元字符) */
46
+ const WORKBUDDY_ID_RE = /^[A-Za-z0-9_-]{1,128}$/;
47
+ /** hermes session id:20261018_223147_c80c5b 形态(sessions 表主键;与 workbuddy 同款保守字符集) */
48
+ const HERMES_ID_RE = /^[A-Za-z0-9_-]{1,128}$/;
49
+ /** claude:项目编码目录名(无路径分隔符)+ <uuid>.jsonl 文件名 */
50
+ const CLAUDE_DIR_RE = /^[^\\/]{1,200}$/;
51
+ const CLAUDE_FILE_RE = /^[0-9a-f][0-9a-f-]{15,120}\.jsonl$/i;
52
+ /** dsh:相对路径(正斜杠或反斜杠段),末段 session*.jsonl.zstd 或 rollout-*.jsonl(明文分支同构) */
53
+ const DSH_BASENAME_RE = /^(?:session[^\\/]*\.jsonl\.zstd|rollout-[^\\/]*\.jsonl)$/;
54
+ /** codex:YYYY/MM/DD/rollout-*.jsonl */
55
+ const CODEX_SEG_RE = { y: /^\d{4}$/, m: /^\d{2}$/, d: /^\d{2}$/, f: /^rollout-[^\\/]{1,160}\.jsonl$/ };
56
+
57
+ const BAD_REF_MSG = '会话引用非法';
58
+
59
+ function isPlainObject(v) {
60
+ return v !== null && typeof v === 'object' && !Array.isArray(v);
61
+ }
62
+
63
+ function validString(v, re) {
64
+ return typeof v === 'string' && v.length > 0 && re.test(v);
65
+ }
66
+
67
+ /** 相对路径段通用闸:禁 .. 段、禁盘符、禁绝对/UNC 路径、段数与单段长度受限 */
68
+ function safeRelativeSegments(relPath, maxSegs) {
69
+ if (typeof relPath !== 'string' || relPath.length === 0 || relPath.length > 600) return null;
70
+ if (/^[A-Za-z]:/.test(relPath)) return null; // 盘符
71
+ if (/^[\\/]/.test(relPath)) return null; // 绝对路径 / UNC(\\srv\share)
72
+ const segs = relPath.split(/[\\/]/).filter((s) => s.length > 0);
73
+ if (segs.length === 0 || segs.length > maxSegs) return null;
74
+ for (const s of segs) {
75
+ if (s === '.' || s === '..') return null;
76
+ }
77
+ return segs;
78
+ }
79
+
80
+ /** base64url 编码(无填充) */
81
+ function encodeRef(locator) {
82
+ return Buffer.from(JSON.stringify(locator), 'utf8').toString('base64url');
83
+ }
84
+
85
+ /** 解码(不抛错):非法返回 null;只做形状浅检,白名单校验在 validateRef */
86
+ function decodeRef(ref) {
87
+ if (typeof ref !== 'string' || ref.length === 0 || ref.length > 1024) return null;
88
+ let json;
89
+ try {
90
+ json = Buffer.from(ref, 'base64url').toString('utf8');
91
+ } catch (e) {
92
+ return null;
93
+ }
94
+ let o;
95
+ try {
96
+ o = JSON.parse(json);
97
+ } catch (e) {
98
+ return null;
99
+ }
100
+ if (!isPlainObject(o)) return null;
101
+ if (typeof o.s !== 'string' || typeof o.k !== 'string' || !isPlainObject(o.v)) return null;
102
+ return o;
103
+ }
104
+
105
+ /**
106
+ * 双闸校验单一收口:非法一律 throw HttpError(400,'BAD_REF'),合法返回 {s,k,v}。
107
+ * cfg:全量 config(读 config.agentActivity.sources.*.root 推导源根)。
108
+ */
109
+ function validateRef(ref, cfg) {
110
+ const loc = decodeRef(ref);
111
+ if (!loc) throw new HttpError(400, 'BAD_REF', BAD_REF_MSG);
112
+ const { s, k, v } = loc;
113
+ if (!SOURCE_IDS.includes(s)) throw new HttpError(400, 'BAD_REF', BAD_REF_MSG);
114
+ if (!LOCATOR_KINDS[s].includes(k)) throw new HttpError(400, 'BAD_REF', BAD_REF_MSG);
115
+
116
+ if (k === 'session') {
117
+ // id 类 locator:仅白名单正则,不触 fs
118
+ const re = s === 'zcode'
119
+ ? ZCODE_ID_RE
120
+ : s === 'opencode'
121
+ ? OPENCODE_ID_RE
122
+ : s === 'hermes'
123
+ ? HERMES_ID_RE
124
+ : WORKBUDDY_ID_RE;
125
+ if (!validString(v.id, re)) throw new HttpError(400, 'BAD_REF', BAD_REF_MSG);
126
+ return loc;
127
+ }
128
+
129
+ // 路径类 locator
130
+ if (s === 'claude') {
131
+ if (k !== 'project') throw new HttpError(400, 'BAD_REF', BAD_REF_MSG);
132
+ if (!validString(v.dir, CLAUDE_DIR_RE) || v.dir === '.' || v.dir === '..') {
133
+ throw new HttpError(400, 'BAD_REF', BAD_REF_MSG);
134
+ }
135
+ if (!validString(v.file, CLAUDE_FILE_RE)) throw new HttpError(400, 'BAD_REF', BAD_REF_MSG);
136
+ return loc;
137
+ }
138
+
139
+ const relPath = typeof v.path === 'string' ? v.path : '';
140
+ if (s === 'dsh') {
141
+ const segs = safeRelativeSegments(relPath, 6);
142
+ if (!segs || !DSH_BASENAME_RE.test(segs[segs.length - 1])) {
143
+ throw new HttpError(400, 'BAD_REF', BAD_REF_MSG);
144
+ }
145
+ return loc;
146
+ }
147
+ if (s === 'codex') {
148
+ const segs = safeRelativeSegments(relPath, 4);
149
+ if (
150
+ !segs ||
151
+ segs.length !== 4 ||
152
+ !CODEX_SEG_RE.y.test(segs[0]) ||
153
+ !CODEX_SEG_RE.m.test(segs[1]) ||
154
+ !CODEX_SEG_RE.d.test(segs[2]) ||
155
+ !CODEX_SEG_RE.f.test(segs[3])
156
+ ) {
157
+ throw new HttpError(400, 'BAD_REF', BAD_REF_MSG);
158
+ }
159
+ return loc;
160
+ }
161
+ throw new HttpError(400, 'BAD_REF', BAD_REF_MSG);
162
+ }
163
+
164
+ /** 六源根路径推导(与 agentActivity.defaultRoot 同口径;dbPath 源无 root 语义返回 '') */
165
+ function sourceRoot(s, cfg) {
166
+ const sec = (cfg && cfg.agentActivity) || {};
167
+ const sc = (sec.sources && sec.sources[s]) || {};
168
+ if (s === 'workbuddy' || s === 'opencode' || s === 'hermes') return ''; // id 类 locator 不触 fs
169
+ const { resolveHome, defaultRoot } = require('./agentActivity');
170
+ return resolveHome(sc.root) || defaultRoot(s);
171
+ }
172
+
173
+ /**
174
+ * 路径类 locator → 绝对路径 + realpath 双闸(包含校验)。
175
+ * 合法返回 { absolute }(realpath 后);否则 throw 400 BAD_REF。不回显路径。
176
+ */
177
+ function resolveLocatorPath(loc, cfg) {
178
+ const { s, k, v } = loc;
179
+ const root = sourceRoot(s, cfg);
180
+ if (!root) throw new HttpError(400, 'BAD_REF', BAD_REF_MSG);
181
+ let rel;
182
+ if (s === 'claude') {
183
+ if (k !== 'project') throw new HttpError(400, 'BAD_REF', BAD_REF_MSG);
184
+ rel = path.join(v.dir, v.file);
185
+ } else {
186
+ rel = v.path;
187
+ }
188
+ const abs = path.resolve(root, rel);
189
+ // 双闸②:realpath 包含校验(realpath 失败 = 文件缺失/不可达,同样按 BAD_REF,规格字面)
190
+ let realFile;
191
+ let realRoot;
192
+ try {
193
+ realFile = fs.realpathSync(abs);
194
+ realRoot = fs.realpathSync(root);
195
+ } catch (e) {
196
+ throw new HttpError(400, 'BAD_REF', BAD_REF_MSG);
197
+ }
198
+ const rootWithSep = realRoot.endsWith(path.sep) ? realRoot : realRoot + path.sep;
199
+ if (realFile !== realRoot && !realFile.startsWith(rootWithSep)) {
200
+ throw new HttpError(400, 'BAD_REF', BAD_REF_MSG);
201
+ }
202
+ return { absolute: abs };
203
+ }
204
+
205
+ /**
206
+ * 形状预检(不触 fs、不抛错):activity 适配器发 ref 前用——形状必不过的 locator 不发,
207
+ * 避免活动流出现「一点就 400」的死引用。完整双闸仍以 validateRef/resolveLocatorPath 为准。
208
+ */
209
+ function locatorShapeOk(loc) {
210
+ try {
211
+ validateRef(encodeRef(loc), {});
212
+ return true;
213
+ } catch (e) {
214
+ return false;
215
+ }
216
+ }
217
+
218
+ module.exports = {
219
+ SOURCE_IDS,
220
+ LOCATOR_KINDS,
221
+ encodeRef,
222
+ decodeRef,
223
+ validateRef,
224
+ resolveLocatorPath,
225
+ sourceRoot,
226
+ locatorShapeOk,
227
+ };
@@ -0,0 +1,67 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * sessionSnapshot.js — v2.9.29 六源会话快照(读时聚合共享层,D3 债务收敛)
5
+ *
6
+ * heatmap / scorecard / agentContext 三个消费方曾各自 listAgentSessions(limit 50)——
7
+ * 同一请求周期内重复全源扫描(scorecard 甚至双倍)。本模块提供 60s TTL 进程内快照:
8
+ * getSnapshot(config, {now, adapters})
9
+ * - adapters 提供时 = 纯注入模式(同 heatmap 语义:未注入源零贡献、绝不回落真实路径、绝不走缓存)
10
+ * - 否则一次扫描六源(limit 50/源,单源故障零贡献),缓存 {at, byAgent}
11
+ * 消费方拿到的每条 item 形状 = listAgentSessions.items(id/title/projectId/startedAt/lastActiveAt/state/ref)。
12
+ * workSearch 暂留自有索引(同 TTL 语义,P1 再并);dispatchPrompt 缓存独立(粒度不同)。
13
+ */
14
+
15
+ const at = require('./agentTranscript');
16
+
17
+ const SNAPSHOT_TTL_MS = 60 * 1000;
18
+ const PER_SOURCE_LIMIT = 50;
19
+
20
+ let cache = { at: 0, byAgent: null };
21
+
22
+ function scan(config) {
23
+ const byAgent = {};
24
+ for (const agent of at.SOURCE_IDS) {
25
+ try {
26
+ const page = at.listAgentSessions(config, { agent, limit: PER_SOURCE_LIMIT });
27
+ byAgent[agent] = Array.isArray(page.items) ? page.items : [];
28
+ } catch (e) {
29
+ byAgent[agent] = []; // 单源故障隔离:零贡献
30
+ }
31
+ }
32
+ return byAgent;
33
+ }
34
+
35
+ /**
36
+ * getSnapshot(config, opts) → { byAgent: {<agent>: items[]}, fromCache: boolean }
37
+ * @param {{now?:number, adapters?:object}} opts
38
+ */
39
+ function getSnapshot(config, opts) {
40
+ const o = opts || {};
41
+ const now = Number.isFinite(o.now) ? o.now : Date.now();
42
+ const injectMode = o.adapters !== undefined && o.adapters !== null && typeof o.adapters === 'object';
43
+ if (injectMode) {
44
+ const byAgent = {};
45
+ for (const agent of at.SOURCE_IDS) {
46
+ const injected = typeof o.adapters[agent] === 'function' ? o.adapters[agent] : null;
47
+ if (!injected) { byAgent[agent] = []; continue; }
48
+ try {
49
+ const items = injected();
50
+ byAgent[agent] = Array.isArray(items) ? items : [];
51
+ } catch (e) {
52
+ byAgent[agent] = []; // 注入源抛错 = 该源零贡献(同真实源隔离语义)
53
+ }
54
+ }
55
+ return { byAgent, fromCache: false };
56
+ }
57
+ if (cache.byAgent && now - cache.at < SNAPSHOT_TTL_MS) return { byAgent: cache.byAgent, fromCache: true };
58
+ cache = { at: now, byAgent: scan(config) };
59
+ return { byAgent: cache.byAgent, fromCache: false };
60
+ }
61
+
62
+ /** 测试/换配置场景强制失效 */
63
+ function clearSnapshot() {
64
+ cache = { at: 0, byAgent: null };
65
+ }
66
+
67
+ module.exports = { getSnapshot, clearSnapshot, SNAPSHOT_TTL_MS, PER_SOURCE_LIMIT };
@@ -0,0 +1,186 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * sessionSuggest.js — v2.9.24 会话成果自动归因建议(验收证据自动送货上门)
5
+ *
6
+ * 定位:闭环四环「看见→理解→归因→验收」的归因环补最后一块——commit 已自动归因(lib/attribute.js
7
+ * branch 约定),而会话(AI 干活的直接证据)仍要人工去智能体动态里狩猎挂接。本模块产出
8
+ * 「建议挂接」候选(排序+理由),**绝不自动落库**——人工一键确认走既有 POST artifacts(雷达同款
9
+ * 「AI 提议 → 人工闸门」哲学)。
10
+ *
11
+ * 识别链(宁缺勿滥,attribute.js 同款纪律):
12
+ * ① 主键(确定性):task.projectDir 与 session.projectId 经 normalizeProjectKey 归一相等 → 入候选池。
13
+ * 绑定项目只圈候选不唯一(多任务可绑同一目录);未绑定项目 → 空建议零扫描。
14
+ * ② 排序信号(只加分减分不做门禁——真机实证:派工词与任务标题词项重合可为零但分明是同一活):
15
+ * - 时间窗:活跃于 [createdAt-7d, completedAt||now] +2;已完成任务完成时刻之后 -3;早于创建 7 天前 -2
16
+ * - commit 桥:会话活跃时刻 ±24h 内有本任务已归因的 commit/pr 成果 +2
17
+ * - 文本:派工词命中任务全文 +2;有真人派工词 +1
18
+ * - 近期:7 天内活跃 +1
19
+ * ③ 闸门:score < SCORE_THRESHOLD 不出(宁缺);已挂 sessionRef 出局(幂等);每源最多取
20
+ * PER_SOURCE_CAND 条最近会话,总分排序后截 SUGGEST_CAP 条。
21
+ *
22
+ * 数据面:会话候选复用 lib/workSearch 的六源标题索引(60s TTL 共享缓存,项目过滤零重复成本);
23
+ * 派工词复用 lib/agentTranscript.getDispatchPrompt(120s TTL 缓存)。全部只读零写盘零出网。
24
+ */
25
+
26
+ const { HttpError, sendJSON } = require('./router');
27
+ const store = require('./store');
28
+ const at = require('./agentTranscript');
29
+ const ws = require('./workSearch');
30
+
31
+ const DAY_MS = 24 * 3600 * 1000;
32
+ const BRIDGE_WINDOW_MS = DAY_MS; // commit 桥:±24h
33
+ const CREATED_BEFORE_GRACE_MS = 7 * DAY_MS; // 任务创建前 7 天内的活跃不算「太早」
34
+ const RECENT_WINDOW_MS = 7 * DAY_MS;
35
+ const SCORE_THRESHOLD = 2;
36
+ const PER_SOURCE_CAND = 5; // 每源最近 5 条进候选(后再统一排序截帽)
37
+ const SUGGEST_CAP = 5;
38
+ const DISPATCH_DISPLAY_CAP = 120; // 建议卡片展示派工词首行长度
39
+
40
+ function msOf(v) {
41
+ const t = Date.parse(String(v || ''));
42
+ return Number.isFinite(t) ? t : null;
43
+ }
44
+
45
+ /** 文本信号打分:派工词 vs 任务标题/描述(返回 {score, textHit}) */
46
+ function textScore(dispatchText, task) {
47
+ const t = String(dispatchText || '').trim();
48
+ if (!t) return { score: 0, textHit: false };
49
+ let score = 1; // 有真人派工词本身就是信号
50
+ const hay = `${task.title || ''}\n${task.desc || ''}`;
51
+ const needle = String(task.title || '').trim();
52
+ if (needle && needle.length >= 4 && t.includes(needle)) score += 2;
53
+ else if (hay && t.includes(hay.split('\n')[0])) score += 2;
54
+ return { score, textHit: needle.length >= 4 && t.includes(needle) };
55
+ }
56
+
57
+ /**
58
+ * 单任务 × 单会话候选打分(透明规则,逐条给 reasons 供前端展示)
59
+ * @returns {{score:number, reasons:string[]}}
60
+ */
61
+ function scoreCandidate(sess, task, nowMs) {
62
+ const reasons = [];
63
+ let score = 0;
64
+ const lastMs = msOf(sess.lastActiveAt);
65
+ const createdMs = msOf(task.createdAt);
66
+ const completedMs = msOf(task.completedAt);
67
+
68
+ // 时间窗
69
+ if (lastMs != null) {
70
+ if (completedMs != null && lastMs > completedMs) {
71
+ score -= 3;
72
+ reasons.push('任务完成之后才活跃');
73
+ } else if (createdMs != null && lastMs >= createdMs - CREATED_BEFORE_GRACE_MS && (completedMs == null || lastMs <= completedMs)) {
74
+ score += 2;
75
+ reasons.push('活跃于任务时间窗内');
76
+ } else if (createdMs != null && lastMs < createdMs - CREATED_BEFORE_GRACE_MS) {
77
+ score -= 2;
78
+ reasons.push('远早于任务创建');
79
+ }
80
+ if (nowMs - lastMs <= RECENT_WINDOW_MS) {
81
+ score += 1;
82
+ reasons.push('近期活跃');
83
+ }
84
+ }
85
+
86
+ // commit 桥:本任务已归因 commit/pr 的 at与会话活跃 ±24h
87
+ const arts = Array.isArray(task.artifacts) ? task.artifacts : [];
88
+ const bridged = arts.some((a) => {
89
+ if (!a || (a.kind !== 'commit' && a.kind !== 'pr')) return false;
90
+ const atMs = msOf(a.at);
91
+ return atMs != null && lastMs != null && Math.abs(atMs - lastMs) <= BRIDGE_WINDOW_MS;
92
+ });
93
+ if (bridged) {
94
+ score += 2;
95
+ reasons.push('同期有本任务归因提交');
96
+ }
97
+
98
+ // 文本信号
99
+ const ts = textScore(sess.dispatchText, task);
100
+ score += ts.score;
101
+ if (ts.textHit) reasons.push('派工词提及本任务');
102
+
103
+ return { score, reasons };
104
+ }
105
+
106
+ /**
107
+ * suggestSessionsForTask(ctx, taskId, opts)
108
+ * → {task:{id,title,projectDir}, items:[{agent,ref,title,dispatchText,lastActiveAt,score,reasons}]}
109
+ * 任务不存在 404;未绑定项目 → items:[](零扫描);阈值下不显示(宁缺勿滥)。
110
+ * @param {{tasksPath:string, config:object}} ctx
111
+ * @param {{freshIndex?:boolean, now?:number}} opts
112
+ */
113
+ function suggestSessionsForTask(ctx, taskId, opts) {
114
+ const o = opts || {};
115
+ const nowMs = Number.isFinite(o.now) ? o.now : Date.now();
116
+ const data = store.loadTasks(ctx);
117
+ const task = (Array.isArray(data.tasks) ? data.tasks : []).find((t) => t && t.id === taskId);
118
+ if (!task) throw new HttpError(404, 'TASK_NOT_FOUND', '任务不存在');
119
+ const projectDir = typeof task.projectDir === 'string' ? task.projectDir.trim() : '';
120
+ const base = { task: { id: task.id, title: task.title || '', projectDir }, items: [] };
121
+ if (!projectDir) return base; // 未绑定:零扫描
122
+
123
+ const want = at.normalizeProjectKey(projectDir);
124
+ const existingRefs = new Set(
125
+ (Array.isArray(task.artifacts) ? task.artifacts : [])
126
+ .filter((a) => a && a.kind === 'session' && typeof a.sessionRef === 'string')
127
+ .map((a) => a.sessionRef)
128
+ );
129
+
130
+ // 候选池:六源标题索引(TTL 共享)项目过滤,每源截最近 PER_SOURCE_CAND 条
131
+ const index = ws.buildSessionIndex(ctx.config, nowMs, !!o.freshIndex);
132
+ const perSourceCount = new Map();
133
+ const cands = [];
134
+ for (const it of index) {
135
+ if (at.normalizeProjectKey(it.projectId) !== want) continue;
136
+ if (existingRefs.has(it.ref)) continue; // 幂等:已挂不重推
137
+ const n = perSourceCount.get(it.agent) || 0;
138
+ if (n >= PER_SOURCE_CAND) continue;
139
+ perSourceCount.set(it.agent, n + 1);
140
+ cands.push(it);
141
+ }
142
+
143
+ const items = [];
144
+ for (const c of cands) {
145
+ let dispatchText = '';
146
+ try {
147
+ const d = at.getDispatchPrompt(ctx.config, c.ref, { now: nowMs });
148
+ if (d && d.found) dispatchText = String(d.text || '');
149
+ } catch (e) { /* 会话消失/源故障:该候选降级为无派工词继续参评 */ }
150
+ const { score, reasons } = scoreCandidate(
151
+ { lastActiveAt: c.lastActiveAt, dispatchText },
152
+ task,
153
+ nowMs
154
+ );
155
+ if (score < SCORE_THRESHOLD) continue; // 闸门:宁缺勿滥
156
+ items.push({
157
+ agent: c.agent,
158
+ ref: c.ref,
159
+ title: c.title || '',
160
+ dispatchText: dispatchText.length > DISPATCH_DISPLAY_CAP ? dispatchText.slice(0, DISPATCH_DISPLAY_CAP) : dispatchText,
161
+ lastActiveAt: c.lastActiveAt,
162
+ score,
163
+ reasons,
164
+ });
165
+ }
166
+ items.sort((a, b) => b.score - a.score || String(b.lastActiveAt || '').localeCompare(String(a.lastActiveAt || '')));
167
+ base.items = items.slice(0, SUGGEST_CAP);
168
+ return base;
169
+ }
170
+
171
+ /** 路由挂载:GET /api/tasks/:id/session-suggestions(appAssembler 任务路由之后调用) */
172
+ function registerSessionSuggestRoute(router, ctx) {
173
+ router.add('GET', '/api/tasks/:id/session-suggestions', (c) => {
174
+ sendJSON(c.res, 200, suggestSessionsForTask({ tasksPath: ctx.tasksPath, config: ctx.config }, c.params.id, {}));
175
+ });
176
+ }
177
+
178
+ module.exports = {
179
+ suggestSessionsForTask,
180
+ registerSessionSuggestRoute,
181
+ scoreCandidate,
182
+ textScore,
183
+ SCORE_THRESHOLD,
184
+ PER_SOURCE_CAND,
185
+ SUGGEST_CAP,
186
+ };