@v587d/capital-generation 2.16.1 → 2.18.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -7,6 +7,81 @@
7
7
  - **第三位(patch)**:不破坏既有工具 / 配置 / 会话的新增与修复(如 2.1.1、2.1.2)。
8
8
  - **第二位(minor)**:有需要用户知晓的行为变更,且段内附迁移说明(如 2.1.0 的图表呈现通道重做、2.2.0 的数据源与检索来源扩容、2.4.0 的**必须换宿主版本**、2.9.0 的选择器收敛与质检前置——本插件自己的工具与数据契约没变,所以只抬第二位)。
9
9
 
10
+ ## [2.18.0] - 2026-11-06
11
+
12
+ 适配 DSH 0.2.2-rc.1:宿主把工具执行面拆成 native / PTC 两个 executor、把工具调用管线与并发调度
13
+ 移出 `dsh-tools` 主入口,并重做了交付卡重放与委派工具面的几处契约。本版同步插件装配、依赖
14
+ pin、探针与文档;本插件自己的工具与数据契约不变。
15
+
16
+ ### Changed
17
+
18
+ - **宿主基线升至 `@deepseek-ai/dsh@0.2.2-rc.1`**:两个 dsh peer 精确 pin 到该版本,devDependencies
19
+ 与 `package-lock.json` 同步;`@deepseek-ai/cordis` 升到 `~4.1.0`、`@deepseek-ai/schemastery` 升到
20
+ `^3.19.0`。宿主最低 Node.js 版本现为 24.9。
21
+ - **data_junior 的 PTC 行改为直接挂 `@deepseek-ai/dsh-tool-executor-ptc`**(`maxParallelSubCalls: 10`):
22
+ 0.2.1 的 `@deepseek-ai/dsh-agent-tool-presentation`(`mode: ptc`)在 0.2.2 只剩 Deprecated 兼容壳。
23
+ 行 id 仍是 `tool-presentation`,宿主 `ptc-runtime` 仍由 `dsh-base` 提供。
24
+ - **删掉 `@deepseek-ai/dsh-tool-subagent-control/list-agents` 子路径行**:0.2.2 起主入口一次注册
25
+ `send_message` / `interrupt_agent` / `list_agents`,旧子路径不存在;保留它会让整颗根 preset
26
+ `broken`、所有根族行不激活。
27
+ - **叶子角色同时减掉 `list_agents`**:它随 `tool-subagent-control` 主入口焊进每颗角色,角色只需
28
+ `send_message`;`role-tool-policy` 的兄弟名字 deny 与调用级 guard 都从一颗变两颗。
29
+ - **交付卡语义跟随上游**:0.2.2 的客户端重放**整轮** `deliverables/presented`(去掉
30
+ `file.seq < owner.seq` 过滤),收尾回复之后写入的交付也会显示;本仓仍在收尾流 `finish` 帧写入,
31
+ 因为那里才是"这轮是纯文本收尾"的判定点,不再是为了躲 seq 截断。
32
+ - **探针与账本跟随 0.2.2 的实现落点**:`tools` 的 invoke pipeline / 并发调度移到
33
+ `dsh-tools/lib/pipeline.js`;`tools.guard` 与 `tools.layers` 分成两个 ScopedLayers(smoke 读
34
+ `tools.guards.global.guards`);`webServer.register` 收 `WebRoute | WebResourceRoute`;
35
+ `dsh-tool-subagent` 的 `modelSelectionSettings` 拆成 `modelSelection` / `modelDiscovery`。
36
+
37
+ ### Fixed
38
+
39
+ - **`verify:sessions` 跟随 0.2.2 的持久化导出面**:`@deepseek-ai/dsh-session-persistence-jsonl`
40
+ 不再默认导出后端类,改为插件 `apply`;脚本改为挂载到裸 `Context` 后取 `sessionPersistence`
41
+ 服务。旧写法在核对任何会话之前就 `TypeError: Backend is not a constructor`,整道闸门失效;
42
+ 新增回归用例钉住导出面。实机 E2E 复核(自动模式取数→分析→出图、资讯专员、设置卡片、自动化
43
+ 看板)见 `docs/reference/host-upgrade-analysis-0.2.1-rc.5-to-0.2.2-rc.1.md` §5.1。
44
+
45
+ ### Migration
46
+
47
+ - **先升宿主,再更新插件**:`npm install -g @deepseek-ai/dsh@0.2.2-rc.1`,重启 dsh 后再把本插件
48
+ 更新到 2.18.0。顺序反过来时,2.18.0 会被 0.2.1 宿主的兼容预检拒绝(peer 精确 pin)。
49
+ - 不需要改任务、配置或历史会话:preset `config.id` 与 `tool-presentation` 行 id 都没变,
50
+ 已保存的 Capital 会话仍能恢复。
51
+ - 仍停留在 0.2.1-rc.5 的用户留在 2.17.0;2.18.0 不声明对旧宿主兼容。
52
+
53
+ ## [2.17.0] - 2026-11-05
54
+
55
+ 投研自动化补上默认首页「看板」:把每次成功运行的结论收成任务简报,并把待办、自选股、
56
+ 数据缺口与运行健康放进同一页。看板只读,不做历史回填;新运行成功后才自动生成简报。
57
+
58
+ ### Added
59
+
60
+ - **看板(默认首页)**:任务简报平铺列表 + TODO + 自选股雷达 + 数据体检 + 运行健康五块;
61
+ 右栏可整体收起,TODO 与自选股雷达默认展开,数据体检与运行健康默认折叠。
62
+ - **任务简报生成**:每次成功运行追加一次无工具模型调用,把最终答复压成 40–200 字人话简报,
63
+ 并提取 TODO、标的与数据缺口;引用按最终答复的行号 block 取原文,不要求模型逐字复制。
64
+ - **JSON 持久化**:固定 `capital_automation` 域新增 `briefs` 表;不引入 SQL,不扫描历史 run。
65
+ - **看板接口**:`/capital-automation/board` 返回简报、待办、标的、缺口与运行健康;
66
+ 时间范围/分类筛选、简报重试与打开 session 都走同一路由。
67
+ - **运行健康**:运行状态计数、简报状态、调度器与交易日历;异常行可打开对应 session。
68
+
69
+ ### Changed
70
+
71
+ - **自动化页默认停在看板**,任务与运行页保留;看板顶部统计只做锚点,不自动运行任务。
72
+ - **简报卡**:显示相对时间(完整时间在 `title`);去掉待办/标的计数与免责声明 footer,
73
+ 只保留一个小号「AI 简报」标识。
74
+ - **TODO**:标题即依据入口,按日期单选筛选(全部/今天/明天/本周/以后/未定/已过期),
75
+ 不再渲染日期分组标题。
76
+ - **简报校验**:标的代码按基础代码匹配(`000877.SZ` 与原文 `000877` 视为同一标的);
77
+ 模型调用失败自动重试一次,失败原因保留在 `lastError` 供排查。
78
+
79
+ ### Migration
80
+
81
+ - 升级后看板初始为空;历史成功运行**不会补生成简报**,第一次新运行成功后开始出现卡片。
82
+ - 旧的失败简报在重启 dsh 后可重试;重试会按当前 prompt 版本重新生成。
83
+ - 不需要改任务或配置;未使用的模板、任务与运行记录保持不变。
84
+
10
85
  ## [2.16.1] - 2026-11-04
11
86
 
12
87
  盘前公告补齐全市场覆盖:A 股、港股、美股自选股都要逐只给结论,不能只做 A 股;同时把东财公告
package/README.md CHANGED
@@ -13,12 +13,12 @@
13
13
  <a href="https://github.com/deepseek-ai"><img src="https://img.shields.io/badge/DeepSeek_Harness-plugin-blue" alt="DSH Plugin"></a>
14
14
  <a href="https://github.com/deepseek-ai"><img src="https://img.shields.io/badge/DeepSeek_Harness-web-orange" alt="DSH Web"></a>
15
15
  <a href="https://github.com/deepseek-ai"><img src="https://img.shields.io/badge/DeepSeek_Harness-desktop-brightgreen" alt="DSH Desktop · 已实机验证"></a>
16
- <a href="https://github.com/deepseek-ai"><img src="https://img.shields.io/badge/DSH%20Baseline-0.2.1--rc.5-blue" alt="DSH@0.2.1-rc.5"></a>
16
+ <a href="https://github.com/deepseek-ai"><img src="https://img.shields.io/badge/DSH%20Baseline-0.2.2--rc.1-blue" alt="DSH@0.2.2-rc.1"></a>
17
17
  </p>
18
18
  <p align="center">
19
19
  <a href="https://awesome-dsh-plugin.com"><img src="https://awesome-dsh-plugin.com/badge.svg" alt="awesome · DSH plugin"></a>
20
20
  <a href="LICENSE"><img src="https://img.shields.io/badge/License-MIT-green" alt="License"></a>
21
- <a href="https://github.com/v587d/capital-generation/releases"><img src="https://img.shields.io/badge/version-2.16.1-9cf" alt="Version"></a>
21
+ <a href="https://github.com/v587d/capital-generation/releases"><img src="https://img.shields.io/badge/version-2.18.0-9cf" alt="Version"></a>
22
22
  <a href="https://www.npmjs.com/package/@v587d/capital-generation"><img src="https://img.shields.io/npm/v/%40v587d%2Fcapital-generation" alt="npm version"></a>
23
23
  <a href="https://github.com/deepseek-ai/deepseek-harness"><img src="https://img.shields.io/badge/powered_by-dsh-4D6BFE?style=flat-square&logo=deepseek&logoColor=white" alt="powered-by-dsh"></a>
24
24
  </p>
@@ -39,7 +39,7 @@ Capital Generation 是运行在 [DeepSeek Harness(DSH)](https://github.com/d
39
39
  ## 快速上手
40
40
 
41
41
  > [!NOTE]
42
- > 最新版本已适配 DSH`@0.2.1-rc.5`。
42
+ > 最新版本已适配 DSH`@0.2.2-rc.1`。
43
43
 
44
44
 
45
45
  0. **前置**
@@ -183,7 +183,13 @@ Capital Generation 是运行在 [DeepSeek Harness(DSH)](https://github.com/d
183
183
  | [Quant Agent Skills](https://github.com/Howard-Jerry/quant-agent-skills) | 1 个跨市场选线 Skill:同一家公司在 A 股与港股、或美股 ADR 与港股各有一条线时该走哪一条——价差、币种与股息税、流动性与通道、披露文件路径各不相同。公司本身只研究一次,便宜的那条线不构成"这家公司更值得买";A/H 溢价与 ADR 平价没有现成条目,须按两条线同一天的收盘价与当日汇率现算,缺任一项就只报缺的那一项 |
184
184
 
185
185
  <a id="capgen-automation" name="capgen-automation"></a>
186
- - **CapGen 投研自动化:** 内置 16 个模板(默认未添加,按需添加),覆盖资讯、行情、复盘、研究、组合与监控:交易日有盘前公告(08:00)、早间资讯(08:30)、午间快照(11:35)、当日公告(16:00)、港股收盘(16:30)与每日复盘(20:00),另有美股收盘(周二至周六 07:00)、美股盘前(周一至周五 20:30)、组合周报、自选股周检、行业周报、研究选题、财报跟踪、下周事件日历、市场周报与组合风险月报;也可新建自己的任务,并从 30 个图标里挑一个;内置模板也有各自的固定图标。到点自动新建 session 执行,也能手动运行。任务、12 个月运行热力图与任务通知在同一页,可在设置卡把任一已注册工作区设为任务统一使用的默认工作区,支持运行预算、通知和仅交易日触发。
186
+ - **CapGen 投研自动化:** 内置 16 个模板(默认未添加,按需添加),覆盖资讯、行情、复盘、研究、组合与监控:交易日有盘前公告(08:00)、早间资讯(08:30)、午间快照(11:35)、当日公告(16:00)、港股收盘(16:30)与每日复盘(20:00),另有美股收盘(周二至周六 07:00)、美股盘前(周一至周五 20:30)、组合周报、自选股周检、行业周报、研究选题、财报跟踪、下周事件日历、市场周报与组合风险月报;也可新建自己的任务,并从 30 个图标里挑一个;内置模板也有各自的固定图标。到点自动新建 session 执行,也能手动运行。任务、看板、12 个月运行热力图与任务通知在同一页,可在设置卡把任一已注册工作区设为任务统一使用的默认工作区,支持运行预算、通知和仅交易日触发。
187
+
188
+ <p align="center">
189
+ <a href="assets/capgen-automation-kanban.png">
190
+ <img src="assets/capgen-automation-kanban.png" alt="投研自动化:看板、任务简报与右栏" width="800">
191
+ </a>
192
+ </p>
187
193
 
188
194
  <p align="center">
189
195
  <a href="assets/capgen-automation-tasks.png">
@@ -196,7 +202,7 @@ Capital Generation 是运行在 [DeepSeek Harness(DSH)](https://github.com/d
196
202
  - **安装后找不到模式?** 确认插件出现在「插件」→ 已安装列表;Web / CLI profile 安装后要重启该 profile,并在新会话选择模式。选择器里应看到自动模式、行情专家、资讯专员;分析师和绘图专员是自动模式的内部角色,不会出现在这里。
197
203
  - **配置在哪?** 打开「插件」→ 已安装的 **Capital Generation**,页面顶部就是「数据源 / 投研自动化 / 精选 Skills / 包含的组件」四格,五把密钥都在第一格;第二格可指定任务统一使用的默认工作区,也能改自动检查间隔与最长运行时间等上限;不在 DSH 的普通「设置」页面,也不用点进任何一行组件。保存密钥后新建会话再试。
198
204
  - **升级到 2.9.0 后,分析师和绘图专员去哪了?** 这一版把它们收进自动模式内部,不再出现在选择器与预设管理里,避免误开一个没有取数入口的空会话。旧会话仍能按原身份恢复;新任务直接用自动模式提出即可。
199
- - **桌面端升级后仍是旧版?** 桌面端安装时会固定所解析的版本,不会自动升级。卸载后重新安装,再到插件详情查看版本号;如需指定版本,可在地址末尾加 `#v2.16.1` 或 `@2.16.1`。
205
+ - **桌面端升级后仍是旧版?** 桌面端安装时会固定所解析的版本,不会自动升级。卸载后重新安装,再到插件详情查看版本号;如需指定版本,可在地址末尾加 `#v2.18.0` 或 `@2.18.0`。
200
206
  - **刚发布的新版本装不到?** 桌面端取包时会跳过**刚发布不久**的版本(宿主侧包管理器的发布冷却策略,实测会静默装成上一个版本),国内镜像的同步也可能滞后一段时间。急着用最新代码,改用仓库地址安装最直接。
201
207
  - **网页抓取失败?** 配置卡片中的「允许启动本地提取网页内容」默认开启:AnySearch 提取失败时可尝试本机直连。关闭后,本机直连的具名来源查询也不可用;请检查该开关和网络连接。
202
208
  - **Wind 那部分会消耗积分?** 会。Wind 的公告 / 新闻语义检索、宏观 / 行业 / 汇率指标、按日期区间取的历史 K 线都按次消耗你在 Wind 侧的额度;额度与条款以 Wind 为准,插件不做用量封顶。没配 `WIND_API_KEY` 时这几类不可用,其余功能照常——公告清单与正文有零密钥的东财工具,不配 Wind 也能查。
@@ -0,0 +1,461 @@
1
+ /**
2
+ * Read-time projections for the board. A brief is the only durable board record; TODO, stock
3
+ * radar and data-health rows are merged from briefs here so the three views cannot drift apart.
4
+ */
5
+ import { TaskCategorySchema, isValidTimeZone } from './schema.js'
6
+ import { addDays, localPartsAt } from './time.js'
7
+
8
+ const DAY_VALUES = new Set(['7', '14', '30', 'all'])
9
+ const DEFAULT_DAYS = '14'
10
+ const DEFAULT_LIMIT = 30
11
+ const MAX_LIMIT = 50
12
+ const MAX_TODOS = 50
13
+ const MAX_STOCKS = 12
14
+ const MAX_GAPS = 20
15
+ const HEALTH_DAYS = 7
16
+ const RUN_ID_PATTERN = /^[A-Za-z0-9_-]{1,120}$/
17
+ const CATEGORY_VALUES = new Set(TaskCategorySchema.options)
18
+ const FAILURE_STATUSES = new Set(['failed', 'timed_out', 'blocked_requires_user', 'unknown_after_restart', 'missed'])
19
+ const KIND_RANK = { confirm: 0, verify: 1, track: 2 }
20
+ const GAP_RANK = { capability: 0, conflict: 1, quality: 2, transient: 3 }
21
+ const ROLE_RANK = { holding: 0, risk: 1, event: 2, watch: 3 }
22
+
23
+ export class BoardError extends Error {
24
+ constructor(code, message, status = 400) {
25
+ super(message)
26
+ this.name = 'BoardError'
27
+ this.code = code
28
+ this.status = status
29
+ this.boardError = true
30
+ }
31
+ }
32
+
33
+ function iso(now) {
34
+ return new Date(now).toISOString()
35
+ }
36
+
37
+ function parseDays(value) {
38
+ if (value === undefined || value === '') return DEFAULT_DAYS
39
+ if (typeof value !== 'string' || !DAY_VALUES.has(value)) {
40
+ throw new BoardError('invalid_query', 'days 必须是 7 / 14 / 30 / all。')
41
+ }
42
+ return value
43
+ }
44
+
45
+ function parseTimeZone(value) {
46
+ if (value === undefined || value === '') {
47
+ try {
48
+ return Intl.DateTimeFormat().resolvedOptions().timeZone || 'Asia/Shanghai'
49
+ } catch {
50
+ return 'Asia/Shanghai'
51
+ }
52
+ }
53
+ if (typeof value !== 'string' || !isValidTimeZone(value)) {
54
+ throw new BoardError('invalid_query', 'tz 参数无效。')
55
+ }
56
+ return value
57
+ }
58
+
59
+ function parseLimit(value) {
60
+ if (value === undefined || value === '') return DEFAULT_LIMIT
61
+ if (typeof value !== 'string' || !/^[1-9]\d?$/.test(value)) {
62
+ throw new BoardError('invalid_query', 'limit 必须是 1–50 的整数。')
63
+ }
64
+ const limit = Number(value)
65
+ if (!Number.isSafeInteger(limit) || limit < 1 || limit > MAX_LIMIT) {
66
+ throw new BoardError('invalid_query', 'limit 必须是 1–50 的整数。')
67
+ }
68
+ return limit
69
+ }
70
+
71
+ function parseBefore(value) {
72
+ if (value === undefined || value === '') return undefined
73
+ if (typeof value !== 'string' || !RUN_ID_PATTERN.test(value)) {
74
+ throw new BoardError('invalid_cursor', '分页游标无效。')
75
+ }
76
+ return value
77
+ }
78
+
79
+ function parseCategory(value) {
80
+ if (value === undefined || value === '') return undefined
81
+ if (typeof value !== 'string' || !CATEGORY_VALUES.has(value)) {
82
+ throw new BoardError('invalid_query', 'category 参数无效。')
83
+ }
84
+ return value
85
+ }
86
+
87
+ export function parseBoardQuery(query = {}, now = () => Date.now()) {
88
+ const days = parseDays(query.days)
89
+ const timeZone = parseTimeZone(query.tz)
90
+ const limit = parseLimit(query.limit)
91
+ const before = parseBefore(query.before)
92
+ const category = parseCategory(query.category)
93
+ const today = localPartsAt(now(), timeZone).date
94
+ const from = days === 'all' ? undefined : addDays(today, -(Number(days) - 1)).date
95
+ return { days, timeZone, limit, before, category, from, to: today }
96
+ }
97
+
98
+ function dateOf(isoInstant, timeZone) {
99
+ if (typeof isoInstant !== 'string') return undefined
100
+ const instant = Date.parse(isoInstant)
101
+ if (!Number.isFinite(instant)) return undefined
102
+ return localPartsAt(instant, timeZone).date
103
+ }
104
+
105
+ function inRange(value, from, to, timeZone) {
106
+ const date = dateOf(value, timeZone)
107
+ if (date === undefined) return false
108
+ if (from !== undefined && date < from) return false
109
+ return date <= to
110
+ }
111
+
112
+ function normalize(value) {
113
+ return String(value ?? '').trim().toLowerCase().replace(/[\s|,,。;;::()[\]{}'"“”‘’\-_/]+/g, '')
114
+ }
115
+
116
+ function todoKey(item) {
117
+ if (item.kind === 'confirm') return `confirm|${item.symbol ?? normalize(item.title)}`
118
+ if (item.kind === 'verify') return `verify|${item.symbol ?? ''}|${normalize(item.trigger ?? item.detail ?? item.title)}`
119
+ return `track|${item.symbol ?? ''}|${item.dueAt ?? normalize(item.title)}`
120
+ }
121
+
122
+ function sourceOf(run, item) {
123
+ return {
124
+ runId: run.id,
125
+ taskTitle: run.taskTitle,
126
+ finishedAt: run.finishedAt ?? run.queuedAt,
127
+ sessionId: run.sessionId ?? null,
128
+ sourceQuote: item.sourceQuote,
129
+ }
130
+ }
131
+
132
+ function aggregateTodos(entries) {
133
+ const byKey = new Map()
134
+ for (const { run, brief } of entries) {
135
+ if (brief.status !== 'ready') continue
136
+ for (const item of brief.items) {
137
+ const key = todoKey(item)
138
+ const at = run.finishedAt ?? run.queuedAt
139
+ const source = sourceOf(run, item)
140
+ const current = byKey.get(key)
141
+ if (current === undefined) {
142
+ byKey.set(key, {
143
+ id: key,
144
+ ...item,
145
+ runId: run.id,
146
+ taskTitle: run.taskTitle,
147
+ finishedAt: at,
148
+ sessionId: run.sessionId ?? null,
149
+ seenCount: 1,
150
+ firstSeenAt: at,
151
+ lastSeenAt: at,
152
+ sources: [source],
153
+ runIds: new Set([run.id]),
154
+ })
155
+ continue
156
+ }
157
+ if (!current.runIds.has(run.id)) {
158
+ current.runIds.add(run.id)
159
+ current.seenCount += 1
160
+ }
161
+ if (at >= current.lastSeenAt) {
162
+ current.title = item.title
163
+ current.detail = item.detail
164
+ current.symbol = item.symbol
165
+ current.trigger = item.trigger
166
+ current.dueAt = item.dueAt
167
+ current.dueLabel = item.dueLabel
168
+ current.sourceQuote = item.sourceQuote
169
+ current.runId = run.id
170
+ current.taskTitle = run.taskTitle
171
+ current.finishedAt = at
172
+ current.sessionId = run.sessionId ?? null
173
+ current.lastSeenAt = at
174
+ }
175
+ if (at < current.firstSeenAt) current.firstSeenAt = at
176
+ if (!current.sources.some((entry) => entry.runId === run.id) && current.sources.length < 5) {
177
+ current.sources.push(source)
178
+ }
179
+ }
180
+ }
181
+ const result = [...byKey.values()].map(({ runIds: _runIds, ...item }) => item)
182
+ result.sort((left, right) => {
183
+ const kind = (KIND_RANK[left.kind] ?? 9) - (KIND_RANK[right.kind] ?? 9)
184
+ if (kind !== 0) return kind
185
+ const due = String(left.dueAt ?? '9999-12-31').localeCompare(String(right.dueAt ?? '9999-12-31'))
186
+ if (due !== 0) return due
187
+ return String(right.lastSeenAt).localeCompare(String(left.lastSeenAt)) || String(left.id).localeCompare(String(right.id))
188
+ })
189
+ return result
190
+ }
191
+
192
+ function aggregateStocks(entries, todos) {
193
+ const bySymbol = new Map()
194
+ for (const { run, brief } of entries) {
195
+ if (brief.status !== 'ready') continue
196
+ for (const stock of brief.stocks) {
197
+ const at = run.finishedAt ?? run.queuedAt
198
+ const current = bySymbol.get(stock.symbol)
199
+ if (current === undefined) {
200
+ bySymbol.set(stock.symbol, {
201
+ symbol: stock.symbol,
202
+ name: stock.name,
203
+ roles: new Set(stock.roles),
204
+ note: stock.note,
205
+ nextAt: stock.nextAt,
206
+ lastSeenAt: at,
207
+ })
208
+ continue
209
+ }
210
+ for (const role of stock.roles) current.roles.add(role)
211
+ if (at >= current.lastSeenAt) {
212
+ current.name = stock.name
213
+ current.note = stock.note
214
+ current.lastSeenAt = at
215
+ }
216
+ if (stock.nextAt !== undefined && (current.nextAt === undefined || stock.nextAt < current.nextAt)) current.nextAt = stock.nextAt
217
+ }
218
+ }
219
+ const todoCounts = new Map()
220
+ for (const item of todos) if (item.symbol !== undefined) todoCounts.set(item.symbol, (todoCounts.get(item.symbol) ?? 0) + 1)
221
+ const result = [...bySymbol.values()].map((stock) => ({
222
+ symbol: stock.symbol,
223
+ name: stock.name,
224
+ roles: [...stock.roles].sort((left, right) => (ROLE_RANK[left] ?? 9) - (ROLE_RANK[right] ?? 9)),
225
+ ...(stock.note === undefined ? {} : { note: stock.note }),
226
+ ...(stock.nextAt === undefined ? {} : { nextAt: stock.nextAt }),
227
+ todoCount: todoCounts.get(stock.symbol) ?? 0,
228
+ lastSeenAt: stock.lastSeenAt,
229
+ }))
230
+ result.sort((left, right) => {
231
+ const role = (ROLE_RANK[left.roles[0]] ?? 9) - (ROLE_RANK[right.roles[0]] ?? 9)
232
+ if (role !== 0) return role
233
+ return String(right.lastSeenAt).localeCompare(String(left.lastSeenAt)) || left.symbol.localeCompare(right.symbol)
234
+ })
235
+ return result
236
+ }
237
+
238
+ function aggregateGaps(entries) {
239
+ const byKey = new Map()
240
+ for (const { run, brief } of entries) {
241
+ if (brief.status !== 'ready') continue
242
+ for (const gap of brief.gaps) {
243
+ const key = `${gap.kind}|${normalize(gap.topic)}`
244
+ const at = run.finishedAt ?? run.queuedAt
245
+ const source = {
246
+ runId: run.id,
247
+ taskTitle: run.taskTitle,
248
+ finishedAt: at,
249
+ sessionId: run.sessionId ?? null,
250
+ sourceQuote: gap.sourceQuote,
251
+ }
252
+ const current = byKey.get(key)
253
+ if (current === undefined) {
254
+ byKey.set(key, {
255
+ id: key,
256
+ ...gap,
257
+ seenCount: 1,
258
+ firstSeenAt: at,
259
+ lastSeenAt: at,
260
+ sources: [source],
261
+ runIds: new Set([run.id]),
262
+ })
263
+ continue
264
+ }
265
+ if (!current.runIds.has(run.id)) {
266
+ current.runIds.add(run.id)
267
+ current.seenCount += 1
268
+ }
269
+ if (at >= current.lastSeenAt) {
270
+ current.detail = gap.detail
271
+ current.sourceQuote = gap.sourceQuote
272
+ current.lastSeenAt = at
273
+ }
274
+ if (at < current.firstSeenAt) current.firstSeenAt = at
275
+ if (!current.sources.some((entry) => entry.runId === run.id) && current.sources.length < 5) current.sources.push(source)
276
+ }
277
+ }
278
+ const result = [...byKey.values()].map(({ runIds: _runIds, ...gap }) => gap)
279
+ result.sort((left, right) => {
280
+ const kind = (GAP_RANK[left.kind] ?? 9) - (GAP_RANK[right.kind] ?? 9)
281
+ if (kind !== 0) return kind
282
+ const seen = right.seenCount - left.seenCount
283
+ if (seen !== 0) return seen
284
+ return String(right.lastSeenAt).localeCompare(String(left.lastSeenAt)) || String(left.id).localeCompare(String(right.id))
285
+ })
286
+ return result
287
+ }
288
+
289
+ function statusCounts(runs) {
290
+ const counts = {
291
+ total: runs.length,
292
+ succeeded: 0,
293
+ failed: 0,
294
+ timedOut: 0,
295
+ missed: 0,
296
+ unknown: 0,
297
+ blocked: 0,
298
+ active: 0,
299
+ }
300
+ for (const run of runs) {
301
+ if (run.status === 'succeeded') counts.succeeded += 1
302
+ else if (run.status === 'failed') counts.failed += 1
303
+ else if (run.status === 'timed_out') counts.timedOut += 1
304
+ else if (run.status === 'missed') counts.missed += 1
305
+ else if (run.status === 'unknown_after_restart') counts.unknown += 1
306
+ else if (run.status === 'blocked_requires_user') counts.blocked += 1
307
+ else if (['queued', 'starting', 'running'].includes(run.status)) counts.active += 1
308
+ }
309
+ return counts
310
+ }
311
+
312
+ function briefCounts(briefs) {
313
+ const counts = { ready: 0, pending: 0, failed: 0, skipped: 0 }
314
+ for (const brief of briefs) {
315
+ if (Object.prototype.hasOwnProperty.call(counts, brief.status)) counts[brief.status] += 1
316
+ }
317
+ return counts
318
+ }
319
+
320
+ function healthOf({ runs, briefs, timeZone, now, scheduler, tasks }) {
321
+ const today = localPartsAt(now, timeZone).date
322
+ const from = addDays(today, -(HEALTH_DAYS - 1)).date
323
+ const windowRuns = runs.filter((run) => inRange(run.finishedAt ?? run.queuedAt, from, today, timeZone))
324
+ const counts = statusCounts(windowRuns)
325
+ const windowRunIds = new Set(windowRuns.map((run) => run.id))
326
+ const windowBriefs = [...briefs.values()].filter((brief) => windowRunIds.has(brief.runId))
327
+ const ordered = [...windowRuns].sort((left, right) =>
328
+ String(right.finishedAt ?? right.queuedAt).localeCompare(String(left.finishedAt ?? left.queuedAt))
329
+ || String(right.id).localeCompare(String(left.id)))
330
+ const recentIssues = []
331
+ for (const run of ordered) {
332
+ if (!FAILURE_STATUSES.has(run.status)) continue
333
+ const recoveredBy = ordered.find((candidate) =>
334
+ candidate.taskId === run.taskId
335
+ && candidate.status === 'succeeded'
336
+ && Date.parse(candidate.finishedAt ?? candidate.queuedAt) > Date.parse(run.finishedAt ?? run.queuedAt)
337
+ && Date.parse(candidate.finishedAt ?? candidate.queuedAt) - Date.parse(run.finishedAt ?? run.queuedAt) <= 86_400_000)
338
+ recentIssues.push({
339
+ runId: run.id,
340
+ taskId: run.taskId,
341
+ taskTitle: run.taskTitle,
342
+ status: run.status,
343
+ finishedAt: run.finishedAt ?? run.queuedAt,
344
+ sessionId: run.sessionId ?? null,
345
+ message: run.errors.at(-1)?.message ?? '',
346
+ ...(recoveredBy === undefined ? {} : { recoveredByRunId: recoveredBy.id }),
347
+ })
348
+ if (recentIssues.length >= 5) break
349
+ }
350
+ const schedulerStatus = scheduler?.status?.() ?? { state: 'unavailable' }
351
+ const nextRuns = tasks
352
+ .filter((task) => task.state === 'active')
353
+ .map((task) => {
354
+ const next = scheduler?.displayNext?.(task)
355
+ if (next?.kind !== 'occurrence') return undefined
356
+ return { taskId: task.id, taskTitle: task.title, nextAt: next.scheduledFor }
357
+ })
358
+ .filter((item) => item !== undefined)
359
+ .sort((left, right) => String(left.nextAt).localeCompare(String(right.nextAt)))
360
+ .slice(0, 3)
361
+ return {
362
+ windowDays: HEALTH_DAYS,
363
+ runs: counts,
364
+ briefs: briefCounts(windowBriefs),
365
+ scheduler: { state: schedulerStatus.state ?? 'unavailable' },
366
+ calendar: schedulerStatus.calendar ?? { available: false, source: 'none' },
367
+ recentIssues,
368
+ issueCount: ordered.filter((run) => FAILURE_STATUSES.has(run.status)).length,
369
+ nextRuns,
370
+ }
371
+ }
372
+
373
+ function cardOf(run, brief, task) {
374
+ return {
375
+ runId: run.id,
376
+ taskId: run.taskId,
377
+ taskTitle: run.taskTitle,
378
+ category: task?.category ?? 'research',
379
+ trigger: run.trigger,
380
+ finishedAt: run.finishedAt ?? run.queuedAt,
381
+ sessionId: run.sessionId ?? null,
382
+ brief: brief === undefined ? null : {
383
+ status: brief.status,
384
+ headline: brief.headline ?? null,
385
+ plain: brief.plain ?? null,
386
+ coverage: brief.coverage ?? null,
387
+ error: brief.error ?? null,
388
+ generatedAt: brief.generatedAt ?? null,
389
+ counts: {
390
+ items: brief.items.length,
391
+ stocks: brief.stocks.length,
392
+ gaps: brief.gaps.length,
393
+ },
394
+ },
395
+ }
396
+ }
397
+
398
+ export function createBoardService(options) {
399
+ const { store, scheduler, now = () => Date.now() } = options
400
+
401
+ async function board(query = {}) {
402
+ const parsed = parseBoardQuery(query, now)
403
+ const page = await store.listRunsPage({ limit: 2_000 })
404
+ const tasks = await store.listTasks()
405
+ const taskById = new Map(tasks.map((task) => [task.id, task]))
406
+ const briefs = await store.listBriefsForRuns(page.runs.map((run) => run.id))
407
+ const lifetime = await store.countBriefs()
408
+ const entries = []
409
+ for (const run of page.runs) {
410
+ const brief = briefs.get(run.id)
411
+ if (run.status !== 'succeeded' || brief === undefined) continue
412
+ const task = taskById.get(run.taskId)
413
+ if (parsed.category !== undefined && task?.category !== parsed.category) continue
414
+ if (!inRange(run.finishedAt ?? run.queuedAt, parsed.from, parsed.to, parsed.timeZone)) continue
415
+ entries.push({ run, task, brief })
416
+ }
417
+ entries.sort((left, right) =>
418
+ String(right.run.finishedAt ?? right.run.queuedAt).localeCompare(String(left.run.finishedAt ?? left.run.queuedAt))
419
+ || String(right.run.id).localeCompare(String(left.run.id)))
420
+ let start = 0
421
+ if (parsed.before !== undefined) {
422
+ const index = entries.findIndex((entry) => entry.run.id === parsed.before)
423
+ if (index === -1) throw new BoardError('invalid_cursor', '分页游标无效。')
424
+ start = index + 1
425
+ }
426
+ const pageEntries = entries.slice(start, start + parsed.limit)
427
+ const nextBefore = start + pageEntries.length < entries.length ? pageEntries.at(-1)?.run.id ?? null : null
428
+ const todos = aggregateTodos(entries)
429
+ const stocks = aggregateStocks(entries, todos)
430
+ const gaps = aggregateGaps(entries)
431
+ const health = healthOf({
432
+ runs: page.runs,
433
+ briefs,
434
+ timeZone: parsed.timeZone,
435
+ now: now(),
436
+ scheduler,
437
+ tasks,
438
+ })
439
+ return {
440
+ ok: true,
441
+ generatedAt: iso(now()),
442
+ empty: lifetime === 0,
443
+ range: { days: parsed.days === 'all' ? 'all' : Number(parsed.days), from: parsed.from ?? null, to: parsed.to },
444
+ stats: {
445
+ briefs: entries.length,
446
+ todos: todos.length,
447
+ stocks: stocks.length,
448
+ gaps: gaps.length,
449
+ issues7d: health.issueCount,
450
+ },
451
+ cards: pageEntries.map((entry) => cardOf(entry.run, entry.brief, entry.task)),
452
+ todos: todos.slice(0, MAX_TODOS),
453
+ stocks: stocks.slice(0, MAX_STOCKS),
454
+ gaps: gaps.slice(0, MAX_GAPS),
455
+ health,
456
+ nextBefore: nextBefore ?? null,
457
+ }
458
+ }
459
+
460
+ return { board }
461
+ }