@v587d/capital-generation 2.19.3 → 2.21.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,75 @@
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.21.0] - 2026-11-11
11
+
12
+ TODO 核验从「读其他任务终稿」改成「专用任务主动调查」:新增默认启用的「TODO 核验」,交易日收盘后直接拿候选 TODO 去取数,不再依赖午间快照/每日复盘的终稿。
13
+
14
+ ### Added
15
+
16
+ - **TODO 核验内置任务**:`todo-verifier-close`(「TODO 核验」,交易日 17:00,默认启用)。服务端在运行前注入 A/H 与无标的的候选 TODO(最多 30 条),任务用数据/网页工具逐条调查,返回 `triggered / not_triggered / insufficient` JSON。
17
+ - **原文校验**:`evidence` 必须能在本次运行的答复或 `tool/result` 原文中找到,`source` 记录数据集/URL/工具与 as-of;找不到原文的引用直接丢弃,不写成触发。
18
+ - **无候选跳过**:scheduler 在投递前检查候选;没有待核验 TODO 时消费 occurrence,不创建空 run/session。
19
+
20
+ ### Changed
21
+
22
+ - **移除检查点判卷**:午间快照、每日复盘不再核验 TODO;`onBriefReady` 判卷链路和 `TODO_WATCH_SYSTEM_PROMPT` 删除。普通任务即使提到 TODO,也不会直接改 watch 状态。
23
+ - **核验运行不生成简报**:`todo-verifier-close` 的 run 只写 `todo_watches` 与通知,不进入看板简报流,避免把核验 JSON 当成新的 TODO 来源。
24
+ - **单批上限 30 条**:按到期日、上次核验时间与最近出现时间排序,超出的留到下一窗口,不静默丢弃。
25
+ - 看板「自动核验中」的 hover 改为列出当前启用的 TODO 核验任务;不再显示「午间快照 / 每日复盘」。
26
+ - **TODO 行从单个勾选框改为「...」决定菜单**:待人工处理 / 已触发 / 跟踪 / 自动核验中的行提供「已确认 / 转入自动校验 / 忽略」三个分支。已确认与忽略都即时收起成单行并排到今天 TODO 最后,标签不同,均不计入今日 TODO 与个股跟进、不再提醒;后续新版本重新出现。已确认标签不再附带对勾,避免与状态文字重复。已决定行之间不再重复画分隔线,只在第一条已决定行上方保留一条与待处理项分隔;标签与标题的间距固定。已决定行保留菜单,可改判。转入自动校验把条目排入下一次 17:00 核验并显示「自动核验中」,失败退回人工处理;`track` 保持两项,美股与已触发项在菜单中显示禁用原因(「美股暂不支持 / 条件已触发」)。写回在后台完成,期间跨过的看板轮询不会把行刷回旧状态,失败才撤回并提示。
27
+ - **用户决定落库**:`todo_acks` 增加可选 `decision: confirmed|deferred`(旧记录按 confirmed 读),`todo_watches` 增加可选 `autoRequestedAt`;新增 `POST /capital-automation/board/todos/decision`。`confirm` 条目也可由用户主动转入核验,候选池优先处理并只尝试一轮。
28
+ - **已过期 TODO 改为只读归档**:到期即结算,除已触发外不再保留「待人工处理 / 自动核验中」;`todo_watches` 增加可选 `expiredReason`(`not_triggered` / `no_data` / `not_verified` / `not_confirmed` / `stale`)。过期条目不再进入核验候选、不能再转自动、不写通知、不计入个股待跟进;看板统一显示「已过期」与结果,只保留查看依据 / 打开来源,并按到期日倒序排列(无日期项排最后)。连续 3 天没有新运行提到的 watch 也归档为 `stale`。
29
+
30
+ ### Migration
31
+
32
+ - 升级后 `todo-verifier-close` 按内置任务播种为 `active`;如不需要,可在任务页暂停。
33
+ - 既有 `todo_watches` 保留,下一次 16:30 核验会直接接管;没有候选的日子不会产生空运行。
34
+ - 需要重启 dsh 进程并刷新页面后生效。
35
+ - 回滚到 2.20.x 前先清空 `todo_watches`(2.21 新增可选 `source` 字段,旧 schema 会拒绝含该字段的记录);`todo_triggered` / `todo_needs_human` 通知也需先清理。
36
+ - 回滚到 2.21.0 及更早版本前,先清空 `todo_acks` 中含 `decision` 的记录,并清掉 `todo_watches` 中的 `autoRequestedAt` 与 `expiredReason` 字段;旧 schema 会拒绝这些新增的可选字段。
37
+
38
+ ### Fixed
39
+
40
+ - **结算通知唤醒的短确认不再覆盖任务简报**:最后一轮只由 `subagent-settled` 唤醒、只写“本轮没有新增信息”时,简报会连带上一轮完整答复一起交给模型挑选;`BRIEF_PROMPT_VERSION` 升到 8。
41
+ - **收尾后晚到的结算通知不再多开一轮**:wake guard 现在在每次纯文本 finish 就武装,不要求根会话当时已经 idle;child 仍标记 running、收尾后才 settle 时会直接撤掉冗余通知。
42
+ - **失败 / 跳过态简报卡不再显示文字版「打开 session」**:卡片只保留右上角图标入口。
43
+
44
+ ## [2.20.0] - 2026-11-10
45
+
46
+ 投研自动化的 TODO 支持自动核验与人工交接;看板对话弹窗保留该次运行的全部追问。
47
+
48
+ ### Added
49
+
50
+ - **TODO 自动跟踪**:`confirm` 与 `verify` 进入 `todo_watches`;`track` 保持只展示。最近 3 天仍被运行提到的条目才进入跟踪,避免把历史待办一次性变成提醒。
51
+ - **无工具核验**:只在内置「午间快照」与「每日复盘」成功运行后,用同一模型对全部 `watching` / `needs_human` 的 `verify` 条目做一次三值判断(触发 / 未触发 / 数据不足),不再限制 16 条;判卷稿用终稿全文。只认同一标的、同一口径、同一时点,`evidence` 必须能在终稿原文中找到,否则按数据不足处理。
52
+ - **简报与核验都读全文**:任务简报不再把终稿截成头 6000 + 尾 6000;`sourceBlocks` 也不再按行截 600 字。正文清洗后直接进入简报与 TODO 判卷,避免关键证据落在中间被省略。
53
+ - **人工交接**:`confirm` 直接标记「待人工确认」;`verify` 在终稿提到但缺少核验数据时也转「待人工确认」。看板 TODO 行显示核验状态、核验时间与原文依据。
54
+ - **任务通知**:新增 `todo_triggered` / `todo_needs_human`;同一状态只通知一次,通知带 `todoId`,点击直接回到看板 TODO。
55
+ - **用户确认收口**:确认仍写入 `todo_acks`,对应跟踪记录转为 `resolved`;该版本在列表里保留为「已确认」,不计入今日 TODO 与个股跟进数,后续运行再次提到时重新出现。连续 3 天没有新运行提到则移出跟踪,`dueAt` 已过且有过核验记录转 `expired`;到期仍没拿到可复核数据则转「待人工确认」并通知,不静默过期。
56
+
57
+ ### Changed
58
+
59
+ - 看板 TODO 排序在同类型内优先显示「已触发 / 待人工确认」,再按日期与最近出现时间排列;确认后条目留在原位显示「已确认」。
60
+ - 看板 TODO 只保留一个状态标签,`待验证` / `待确认` / `待你核对` 不再并列显示;待人工确认的「确认」按钮换成勾选框,勾选后显示「已确认 ✓」。
61
+ - **看板个股动态**:模块名从「标的」改为「个股动态」,统计卡改为「个股」。同一代码带 / 不带交易所后缀的写法合并(如 `300803` 与 `300803.SZ`),持仓 / 风险 / 事件 / 关注标签合并去重;标签 hover 显示释义。
62
+ - **个股筛选与展开**:右上角改为标签筛选(全部 / 持仓 / 风险 / 事件 / 关注),默认首屏展示 12 只,其余通过「展开全部 N 只」完整加载。
63
+ - **跟进数一致**:「N 项待办」改为「N 条待跟进」,并与展开条目共用服务端随个股返回的同一份列表;即使页面 TODO 被截到 50 条,个股计数仍等于实际能展开的条目数,不再出现「写着 13 条却只展开 8 条」或有点击无内容。
64
+ - **可点击反馈**:个股行与跟进条目 hover / 聚焦时变为品牌蓝色,明确提示可点击。
65
+ - **个股跟进直达来源**:展开后的条目整行可点,直接打开来源 session,移除逐条「打开 session」按钮。
66
+ - 移除 TODO 标题行的「N 条待你处理」计数和待人工确认的通用交接说明,减少重复信息。
67
+ - **数据体检更轻**:移除每条缺口前的「能力缺口 / 本次未取到 / 口径冲突 / 数据质量」标签;展开后的「打开 session」收成 30px 外链箭头,与 TODO 依据行一致。
68
+ - **运行健康更轻**:异常行右侧的「打开 session」也收成 30px 外链箭头(`title` / `aria-label` 仍为「打开 session」)。
69
+ - **对话弹窗保留全部追问**:打开弹窗时按创建时间正序展示该 run 的全部问答;卡片仍只显示最新一轮。新增 `GET /board/briefs/:runId/asks`。
70
+ - `capital_automation` 域新增 `todo_watches` 表;`notifications` 增加可选 `todoId`,未知字段仍严格拒绝。
71
+
72
+ ### Migration
73
+
74
+ - 升级后 `capital_automation` 域自动新增 `todo_watches` 表;任务、运行、简报与既有 TODO 确认记录不变。
75
+ - 首次启动只跟踪最近 3 天出现且未到期的 `confirm` / `verify`;历史条目不会批量补发通知。
76
+ - 需要重启 dsh 进程并刷新页面后生效。
77
+ - 回滚到 2.19.x 前先清空 `todo_triggered` / `todo_needs_human` 通知:旧版不认识这两个 kind,批量已读会拒绝这些记录;`todo_watches` 是派生数据,回滚后丢失可接受。
78
+
10
79
  ## [2.19.3] - 2026-11-09
11
80
 
12
81
  插件页改为面向已安装用户的索引页;README 补清版本检查与回滚路径。
package/README.md CHANGED
@@ -1,26 +1,12 @@
1
- <p align="center">
2
- <a href="https://github.com/v587d/capital-generation"><img src="https://img.shields.io/badge/Market-CN%20%7C%20HK%20%7C%20US-orange" alt="Market·CN+HK+US"></a>
3
- <a href="https://github.com/v587d/capital-generation"><img src="https://img.shields.io/badge/Financial-Agent-red" alt="Financial Agent"></a>
4
- <a href="https://github.com/v587d/capital-generation">
5
- <img src="https://img.shields.io/badge/%E5%93%81%E7%A7%8D-%E8%82%A1%E7%A5%A8%20%7C%E5%80%BA%E5%88%B8%20%7C%E6%9C%9F%E8%B4%A7%20%7C%E5%95%86%E5%93%81%20%7C%E8%A1%8D%E7%94%9F%E5%93%81-fedcba" alt="股票·债券·期货·商品·衍生品">
6
- </a>
7
- </p>
8
- <p align="center">
9
- <a href="https://github.com/deepseek-ai"><img src="https://img.shields.io/badge/DeepSeek_Harness-plugin-blue" alt="DSH Plugin"></a>
10
- <a href="https://github.com/deepseek-ai"><img src="https://img.shields.io/badge/DeepSeek_Harness-web-orange" alt="DSH Web"></a>
11
- <a href="https://github.com/deepseek-ai"><img src="https://img.shields.io/badge/DeepSeek_Harness-desktop-brightgreen" alt="DSH Desktop · 已实机验证"></a>
12
- <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>
13
- </p>
14
- <p align="center">
15
- <a href="https://awesome-dsh-plugin.com"><img src="https://awesome-dsh-plugin.com/badge.svg" alt="awesome · DSH plugin"></a>
1
+ # Capital Generation
2
+ <p align="left">
16
3
  <a href="LICENSE"><img src="https://img.shields.io/badge/License-MIT-green" alt="License"></a>
17
- <a href="https://github.com/v587d/capital-generation/releases"><img src="https://img.shields.io/badge/version-2.19.3-9cf" alt="Version"></a>
4
+ <a href="https://github.com/v587d/capital-generation"><img src="https://img.shields.io/badge/Financial%20Market-CN%20%7C%20HK%20%7C%20US-orange" alt="Market·CN+HK+US"></a>
5
+ <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>
6
+ <a href="https://github.com/v587d/capital-generation/releases"><img src="https://img.shields.io/badge/version-2.21.0-9cf" alt="Version"></a>
18
7
  <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>
19
- <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>
20
8
  </p>
21
9
 
22
- # Capital Generation
23
-
24
10
  > Next-Gen AI-Driven Capital Generation.
25
11
 
26
12
  Capital Generation 是运行在 [DeepSeek Harness(DSH)](https://github.com/deepseek-ai/deepseek-harness) 里的证券研究插件,面向关注 A 股、港股、美股的个体投资者。安装后,新会话的选择器里会多出 **自动模式**、**行情专家**、**资讯专员** 三个模式;日常研究选 **自动模式**,用自然语言查行情、财务数据、公告和新闻,由它安排取数、数据质检、资料检索与图表,最后给出带来源的结论。它不是独立应用,需要先安装 DSH。
@@ -179,7 +165,7 @@ Capital Generation 是运行在 [DeepSeek Harness(DSH)](https://github.com/d
179
165
  | [Quant Agent Skills](https://github.com/Howard-Jerry/quant-agent-skills) | 1 个跨市场选线 Skill:同一家公司在 A 股与港股、或美股 ADR 与港股各有一条线时该走哪一条——价差、币种与股息税、流动性与通道、披露文件路径各不相同。公司本身只研究一次,便宜的那条线不构成"这家公司更值得买";A/H 溢价与 ADR 平价没有现成条目,须按两条线同一天的收盘价与当日汇率现算,缺任一项就只报缺的那一项 |
180
166
 
181
167
  <a id="capgen-automation" name="capgen-automation"></a>
182
- - **CapGen 投研自动化:** 内置 16 个模板(默认未添加,按需添加),覆盖资讯、行情、复盘、研究、组合与监控:交易日有盘前公告(08:00)、早间资讯(08:30)、午间快照(11:35)、当日公告(16:00)、港股收盘(16:30)与每日复盘(20:00),另有美股收盘(周二至周六 07:00)、美股盘前(周一至周五 20:30)、组合周报、自选股周检、行业周报、研究选题、财报跟踪、下周事件日历、市场周报与组合风险月报;也可新建自己的任务,并从 30 个图标里挑一个;内置模板也有各自的固定图标,看板卡片沿用同一枚。到点自动新建 session 执行,也能手动运行。任务、看板、12 个月运行热力图与任务通知在同一页,可在设置卡把任一已注册工作区设为任务统一使用的默认工作区,支持运行预算、通知和仅交易日触发;看板简报卡右上角的对话入口可直接追问,回答完成后卡片显示最新一轮摘要并可在卡内展开全文,弹窗右上角显示对话数并可打开该次运行的完整 session。
168
+ - **CapGen 投研自动化:** 内置 17 个模板:16 个内容模板默认未添加、按需添加,覆盖资讯、行情、复盘、研究、组合与监控;交易日有盘前公告(08:00)、早间资讯(08:30)、午间快照(11:35)、当日公告(16:00)、港股收盘(16:30)与每日复盘(20:00),另有美股收盘(周二至周六 07:00)、美股盘前(周一至周五 20:30)、组合周报、自选股周检、行业周报、研究选题、财报跟踪、下周事件日历、市场周报与组合风险月报;「TODO 核验」默认启用,交易日 17:00 主动核验看板里的待验证条件。也可新建自己的任务,并从 30 个图标里挑一个;内置模板也有各自的固定图标,看板卡片沿用同一枚。到点自动新建 session 执行,也能手动运行。任务、看板、12 个月运行热力图与任务通知在同一页,可在设置卡把任一已注册工作区设为任务统一使用的默认工作区,支持运行预算、通知和仅交易日触发;看板简报卡右上角的对话入口可直接追问,回答完成后卡片显示最新一轮摘要并可在卡内展开全文,弹窗按时间列出这次运行的全部追问,右上角可打开完整 session。看板 TODO 由「TODO 核验」主动调查触发条件,待确认或数据不足的条目交给你核对;触发或需要你处理时写入任务通知。
183
169
 
184
170
  <p align="center">
185
171
  <a href="assets/capgen-automation-kanban.png">
@@ -198,7 +184,7 @@ Capital Generation 是运行在 [DeepSeek Harness(DSH)](https://github.com/d
198
184
  - **安装后找不到模式?** 确认插件出现在「插件」→ 已安装列表;Web / CLI profile 安装后要重启该 profile,并在新会话选择模式。选择器里应看到自动模式、行情专家、资讯专员;分析师和绘图专员是自动模式的内部角色,不会出现在这里。
199
185
  - **配置在哪?** 打开「插件」→ 已安装的 **Capital Generation**,插件介绍下方就是「数据源 / 投研自动化 / 精选 Skills / 包含的组件」四格,五把密钥都在第一格;第二格可指定任务统一使用的默认工作区,也能改自动检查间隔与最长运行时间等上限;不在 DSH 的普通「设置」页面,也不用点进任何一行组件。保存密钥后新建会话再试。
200
186
  - **升级到 2.9.0 后,分析师和绘图专员去哪了?** 这一版把它们收进自动模式内部,不再出现在选择器与预设管理里,避免误开一个没有取数入口的空会话。旧会话仍能按原身份恢复;新任务直接用自动模式提出即可。
201
- - **桌面端升级后仍是旧版?** 桌面端安装时会固定所解析的版本,不会自动升级。卸载后重新安装,再到插件详情查看版本号;如需指定版本,可在地址末尾加 `#v2.19.3` 或 `@2.19.3`。
187
+ - **桌面端升级后仍是旧版?** 桌面端安装时会固定所解析的版本,不会自动升级。卸载后重新安装,再到插件详情查看版本号;如需指定版本,可在地址末尾加 `#v2.21.0` 或 `@2.21.0`。
202
188
  - **刚发布的新版本装不到?** 桌面端取包时会跳过**刚发布不久**的版本(宿主侧包管理器的发布冷却策略,实测会静默装成上一个版本),国内镜像的同步也可能滞后一段时间。急着用最新代码,改用仓库地址安装最直接;但仓库地址安装的是 git 依赖,插件页不显示「版本」检查。
203
189
  - **插件页的「版本」段怎么用?** 只有用包名从 npm 安装的版本才有;它只列比当前新的版本。回旧版要先卸载,再安装 `@v587d/capital-generation@版本号`(桌面端地址末尾加 `#v版本号`);旧版必须匹配当前 DSH 基线,对应关系见 [CHANGELOG 的 Migration](CHANGELOG.md)。
204
190
  - **网页抓取失败?** 配置卡片中的「允许启动本地提取网页内容」默认开启:AnySearch 提取失败时可尝试本机直连。关闭后,本机直连的具名来源查询也不可用;请检查该开关和网络连接。
package/automation/ask.js CHANGED
@@ -327,6 +327,13 @@ export function createAskService(options) {
327
327
  return result
328
328
  }
329
329
 
330
+ async function history(runId) {
331
+ const run = await store.getRun(runId)
332
+ if (run === undefined) throw new AskError('run_not_found', '运行不存在。', 404)
333
+ const records = await store.listAsksForRun(runId)
334
+ return records.map(publicOf)
335
+ }
336
+
330
337
  async function answer(askId) {
331
338
  const record = await store.getAsk(askId)
332
339
  if (record === undefined) throw new AskError('ask_not_found', '这条追问不存在。', 404)
@@ -353,5 +360,5 @@ export function createAskService(options) {
353
360
  }
354
361
  }
355
362
 
356
- return { ask, status, latestForRuns, answer }
363
+ return { ask, status, latestForRuns, history, answer }
357
364
  }
@@ -5,21 +5,72 @@
5
5
  import { TaskCategorySchema, isValidTimeZone } from './schema.js'
6
6
  import { taskIconId } from './task-icons.js'
7
7
  import { addDays, localPartsAt } from './time.js'
8
+ import { isUsSymbol } from './watch.js'
8
9
 
9
10
  const DAY_VALUES = new Set(['7', '14', '30', 'all'])
10
11
  const DEFAULT_DAYS = '14'
11
12
  const DEFAULT_LIMIT = 30
12
13
  const MAX_LIMIT = 50
13
14
  const MAX_TODOS = 50
14
- const MAX_STOCKS = 12
15
+ // The client paints 12 rows first and reveals the rest on demand. 200 leaves room for that
16
+ // interaction across a large run window without letting symbol churn inflate one response.
17
+ const MAX_STOCKS = 200
18
+ // Stock rows carry their own follow-up summaries so the count always equals what expands,
19
+ // even when the page-wide TODO slice is capped. 100 leaves ample room per instrument without
20
+ // duplicating every historical item into the board response.
21
+ const MAX_STOCK_ITEMS = 100
15
22
  const MAX_GAPS = 20
16
23
  const HEALTH_DAYS = 7
17
24
  const RUN_ID_PATTERN = /^[A-Za-z0-9_-]{1,120}$/
18
25
  const CATEGORY_VALUES = new Set(TaskCategorySchema.options)
19
26
  const FAILURE_STATUSES = new Set(['failed', 'timed_out', 'blocked_requires_user', 'unknown_after_restart', 'missed'])
20
27
  const KIND_RANK = { confirm: 0, verify: 1, track: 2 }
28
+ const WATCH_RANK = { triggered: 0, needs_human: 1, watching: 2, expired: 3, resolved: 4 }
21
29
  const GAP_RANK = { capability: 0, conflict: 1, quality: 2, transient: 3 }
22
30
  const ROLE_RANK = { holding: 0, risk: 1, event: 2, watch: 3 }
31
+ const A_SHARE_MARKETS = new Set(['SH', 'SZ', 'BJ'])
32
+ const US_MARKETS = new Set(['OQ', 'N', 'US', 'NYSE', 'NASDAQ'])
33
+
34
+ function inferredMarket(code) {
35
+ if (/^\d{6}$/.test(code)) {
36
+ if (code.startsWith('6')) return 'SH'
37
+ if (code.startsWith('4') || code.startsWith('8')) return 'BJ'
38
+ return 'SZ'
39
+ }
40
+ if (/^\d{5}$/.test(code)) return 'HK'
41
+ return undefined
42
+ }
43
+
44
+ /**
45
+ * Merge the same instrument written with and without an exchange suffix. A bare six-digit A-share
46
+ * code can infer its market from the code pattern; explicit suffixes still win, so an index such as
47
+ * `000001.SS` does not collapse into Shenzhen's `000001`.
48
+ */
49
+ export function stockSymbolKey(value) {
50
+ const raw = String(value ?? '').trim().toUpperCase()
51
+ if (raw.length === 0) return raw
52
+ const match = /^([A-Z0-9]+)\.([A-Z]+)$/.exec(raw)
53
+ if (match === null) {
54
+ const market = inferredMarket(raw)
55
+ return market === undefined ? raw : `${raw}.${market}`
56
+ }
57
+ const [, base, suffix] = match
58
+ if (/^\d{6}$/.test(base) && (suffix === 'SS' || A_SHARE_MARKETS.has(suffix))) {
59
+ return `${base}.${suffix === 'SS' ? 'SH' : suffix}`
60
+ }
61
+ if (/^\d{5}$/.test(base) && suffix === 'HK') return `${base}.HK`
62
+ if (US_MARKETS.has(suffix)) return base
63
+ return `${base}.${suffix}`
64
+ }
65
+
66
+ function symbolDisplayScore(symbol) {
67
+ const raw = String(symbol ?? '')
68
+ return (raw === raw.toUpperCase() ? 1 : 0) + (raw.includes('.') ? 2 : 0)
69
+ }
70
+
71
+ function preferredSymbol(current, incoming) {
72
+ return symbolDisplayScore(incoming) > symbolDisplayScore(current) ? incoming : current
73
+ }
23
74
 
24
75
  export class BoardError extends Error {
25
76
  constructor(code, message, status = 400) {
@@ -114,13 +165,17 @@ function normalize(value) {
114
165
  return String(value ?? '').trim().toLowerCase().replace(/[\s|,,。;;::()[\]{}'"“”‘’\-_/]+/g, '')
115
166
  }
116
167
 
168
+ function gapKey(gap) {
169
+ return `${gap.kind}|${normalize(gap.topic)}`
170
+ }
171
+
117
172
  function todoKey(item) {
118
173
  if (item.kind === 'confirm') return `confirm|${item.symbol ?? normalize(item.title)}`
119
174
  if (item.kind === 'verify') return `verify|${item.symbol ?? ''}|${normalize(item.trigger ?? item.detail ?? item.title)}`
120
175
  return `track|${item.symbol ?? ''}|${item.dueAt ?? normalize(item.title)}`
121
176
  }
122
177
 
123
- /** An ack hides only the version the user saw; a later run makes the item visible again. */
178
+ /** An ack covers only the version the user saw; a later run makes the item open again. */
124
179
  function todoAckCovers(ack, item) {
125
180
  if (ack === undefined) return false
126
181
  const confirmedAt = Date.parse(ack.confirmedAt)
@@ -139,6 +194,56 @@ function sourceOf(run, item) {
139
194
  }
140
195
  }
141
196
 
197
+ /** Only the tracking facts belong on the wire; profileKey and storage ids stay server-side. */
198
+ function watchSummary(watch, today) {
199
+ if (watch === undefined) return null
200
+ const pastDue = typeof watch.dueAt === 'string' && typeof today === 'string' && watch.dueAt < today
201
+ return {
202
+ status: watch.status,
203
+ resolvedFrom: watch.resolvedFrom ?? null,
204
+ checkedAt: watch.checkedAt ?? null,
205
+ evidence: watch.evidence ?? null,
206
+ source: watch.source ?? null,
207
+ handoffReason: watch.handoffReason ?? null,
208
+ dueAt: watch.dueAt ?? null,
209
+ autoRequestedAt: watch.autoRequestedAt ?? null,
210
+ expiredReason: watch.expiredReason ?? null,
211
+ autoEligible: watch.status !== 'triggered'
212
+ && watch.status !== 'expired'
213
+ && !pastDue
214
+ && !isUsSymbol(watch.symbol),
215
+ autoIneligibleReason: watch.status === 'triggered'
216
+ ? 'triggered'
217
+ : watch.status === 'expired' || pastDue
218
+ ? 'expired'
219
+ : isUsSymbol(watch.symbol) ? 'us_symbol' : null,
220
+ }
221
+ }
222
+
223
+ function watchRank(item) {
224
+ if (item.watch === null || item.watch === undefined) return 9
225
+ return WATCH_RANK[item.watch.resolvedFrom ?? item.watch.status] ?? 9
226
+ }
227
+
228
+ /** Expired rows stay in the TODO archive but must not inflate stock follow-up counts. */
229
+ function todoExpired(item, today, timeZone) {
230
+ const decidedAt = typeof item.ackedAt === 'string' ? item.ackedAt : item.deferredAt
231
+ if (decidedAt !== undefined) {
232
+ const decidedDate = dateOf(decidedAt, timeZone)
233
+ return decidedDate === undefined || decidedDate < today
234
+ }
235
+ const watchStatus = item.watch?.resolvedFrom ?? item.watch?.status
236
+ if (watchStatus === 'triggered') return false
237
+ if (item.watch?.status === 'expired') return true
238
+ if (typeof item.dueAt === 'string' && /^\d{4}-\d{2}-\d{2}$/.test(item.dueAt)) return item.dueAt < today
239
+ const label = typeof item.dueLabel === 'string' ? item.dueLabel.trim() : ''
240
+ if (label === '今天' || label === '今日') {
241
+ const seen = dateOf(item.lastSeenAt, timeZone)
242
+ return seen !== undefined && seen < today
243
+ }
244
+ return false
245
+ }
246
+
142
247
  function aggregateTodos(entries) {
143
248
  const byKey = new Map()
144
249
  for (const { run, brief } of entries) {
@@ -199,25 +304,30 @@ function aggregateTodos(entries) {
199
304
  return result
200
305
  }
201
306
 
202
- function aggregateStocks(entries, todos) {
307
+ function aggregateStocks(entries, todos, firstSeenByKey = new Map()) {
203
308
  const bySymbol = new Map()
204
309
  for (const { run, brief } of entries) {
205
310
  if (brief.status !== 'ready') continue
206
311
  for (const stock of brief.stocks) {
207
312
  const at = run.finishedAt ?? run.queuedAt
208
- const current = bySymbol.get(stock.symbol)
313
+ const symbolKey = stockSymbolKey(stock.symbol)
314
+ const current = bySymbol.get(symbolKey)
209
315
  if (current === undefined) {
210
- bySymbol.set(stock.symbol, {
316
+ bySymbol.set(symbolKey, {
317
+ symbolKey,
211
318
  symbol: stock.symbol,
212
319
  name: stock.name,
213
320
  roles: new Set(stock.roles),
214
321
  note: stock.note,
215
322
  nextAt: stock.nextAt,
323
+ firstSeenAt: firstSeenByKey.get(symbolKey) ?? at,
216
324
  lastSeenAt: at,
217
325
  })
218
326
  continue
219
327
  }
220
328
  for (const role of stock.roles) current.roles.add(role)
329
+ current.symbol = preferredSymbol(current.symbol, stock.symbol)
330
+ if (at < current.firstSeenAt) current.firstSeenAt = at
221
331
  if (at >= current.lastSeenAt) {
222
332
  current.name = stock.name
223
333
  current.note = stock.note
@@ -226,17 +336,30 @@ function aggregateStocks(entries, todos) {
226
336
  if (stock.nextAt !== undefined && (current.nextAt === undefined || stock.nextAt < current.nextAt)) current.nextAt = stock.nextAt
227
337
  }
228
338
  }
229
- const todoCounts = new Map()
230
- for (const item of todos) if (item.symbol !== undefined) todoCounts.set(item.symbol, (todoCounts.get(item.symbol) ?? 0) + 1)
231
- const result = [...bySymbol.values()].map((stock) => ({
232
- symbol: stock.symbol,
233
- name: stock.name,
234
- roles: [...stock.roles].sort((left, right) => (ROLE_RANK[left] ?? 9) - (ROLE_RANK[right] ?? 9)),
235
- ...(stock.note === undefined ? {} : { note: stock.note }),
236
- ...(stock.nextAt === undefined ? {} : { nextAt: stock.nextAt }),
237
- todoCount: todoCounts.get(stock.symbol) ?? 0,
238
- lastSeenAt: stock.lastSeenAt,
239
- }))
339
+ const stockItems = new Map()
340
+ for (const item of todos) {
341
+ if (item.symbol === undefined) continue
342
+ const key = stockSymbolKey(item.symbol)
343
+ const items = stockItems.get(key) ?? []
344
+ if (items.length >= MAX_STOCK_ITEMS) continue
345
+ items.push({ id: item.id, title: item.title, sessionId: item.sessionId ?? null })
346
+ stockItems.set(key, items)
347
+ }
348
+ const result = [...bySymbol.values()].map((stock) => {
349
+ const items = stockItems.get(stock.symbolKey) ?? []
350
+ return {
351
+ symbol: stock.symbol,
352
+ symbolKey: stock.symbolKey,
353
+ name: stock.name,
354
+ roles: [...stock.roles].sort((left, right) => (ROLE_RANK[left] ?? 9) - (ROLE_RANK[right] ?? 9)),
355
+ ...(stock.note === undefined ? {} : { note: stock.note }),
356
+ ...(stock.nextAt === undefined ? {} : { nextAt: stock.nextAt }),
357
+ todoCount: items.length,
358
+ items,
359
+ firstSeenAt: stock.firstSeenAt,
360
+ lastSeenAt: stock.lastSeenAt,
361
+ }
362
+ })
240
363
  result.sort((left, right) => {
241
364
  const role = (ROLE_RANK[left.roles[0]] ?? 9) - (ROLE_RANK[right.roles[0]] ?? 9)
242
365
  if (role !== 0) return role
@@ -245,12 +368,12 @@ function aggregateStocks(entries, todos) {
245
368
  return result
246
369
  }
247
370
 
248
- function aggregateGaps(entries) {
371
+ function aggregateGaps(entries, firstSeenByKey = new Map()) {
249
372
  const byKey = new Map()
250
373
  for (const { run, brief } of entries) {
251
374
  if (brief.status !== 'ready') continue
252
375
  for (const gap of brief.gaps) {
253
- const key = `${gap.kind}|${normalize(gap.topic)}`
376
+ const key = gapKey(gap)
254
377
  const at = run.finishedAt ?? run.queuedAt
255
378
  const source = {
256
379
  runId: run.id,
@@ -265,7 +388,7 @@ function aggregateGaps(entries) {
265
388
  id: key,
266
389
  ...gap,
267
390
  seenCount: 1,
268
- firstSeenAt: at,
391
+ firstSeenAt: firstSeenByKey.get(key) ?? at,
269
392
  lastSeenAt: at,
270
393
  sources: [source],
271
394
  runIds: new Set([run.id]),
@@ -296,6 +419,25 @@ function aggregateGaps(entries) {
296
419
  return result
297
420
  }
298
421
 
422
+ /** First mention across the whole retained run window, not just the selected date range. */
423
+ function firstSeenMaps(entries) {
424
+ const stocks = new Map()
425
+ const gaps = new Map()
426
+ for (const { run, brief } of entries) {
427
+ if (brief.status !== 'ready') continue
428
+ const at = run.finishedAt ?? run.queuedAt
429
+ for (const stock of brief.stocks) {
430
+ const key = stockSymbolKey(stock.symbol)
431
+ if (!stocks.has(key) || at < stocks.get(key)) stocks.set(key, at)
432
+ }
433
+ for (const gap of brief.gaps) {
434
+ const key = gapKey(gap)
435
+ if (!gaps.has(key) || at < gaps.get(key)) gaps.set(key, at)
436
+ }
437
+ }
438
+ return { stocks, gaps }
439
+ }
440
+
299
441
  function statusCounts(runs) {
300
442
  const counts = {
301
443
  total: runs.length,
@@ -376,6 +518,8 @@ function healthOf({ runs, briefs, timeZone, now, scheduler, tasks }) {
376
518
  calendar: schedulerStatus.calendar ?? { available: false, source: 'none' },
377
519
  recentIssues,
378
520
  issueCount: ordered.filter((run) => FAILURE_STATUSES.has(run.status)).length,
521
+ todayIssueCount: runs.filter((run) => FAILURE_STATUSES.has(run.status)
522
+ && dateOf(run.finishedAt ?? run.queuedAt, timeZone) === today).length,
379
523
  nextRuns,
380
524
  }
381
525
  }
@@ -413,26 +557,73 @@ function cardOf(run, brief, task, ask) {
413
557
  export function createBoardService(options) {
414
558
  const { store, scheduler, asks, now = () => Date.now() } = options
415
559
 
416
- async function board(query = {}) {
417
- const parsed = parseBoardQuery(query, now)
560
+ /** Same entries back the page projection and the unbounded watcher projection. */
561
+ async function entriesFor(parsed) {
418
562
  const page = await store.listRunsPage({ limit: 2_000 })
419
563
  const tasks = await store.listTasks()
420
564
  const taskById = new Map(tasks.map((task) => [task.id, task]))
421
565
  const briefs = await store.listBriefsForRuns(page.runs.map((run) => run.id))
422
- const todoAcks = await store.listTodoAcks()
423
- const lifetime = await store.countBriefs()
424
566
  const entries = []
567
+ const historyEntries = []
425
568
  for (const run of page.runs) {
426
569
  const brief = briefs.get(run.id)
427
570
  if (run.status !== 'succeeded' || brief === undefined) continue
428
571
  const task = taskById.get(run.taskId)
429
572
  if (parsed.category !== undefined && task?.category !== parsed.category) continue
573
+ const entry = { run, task, brief }
574
+ historyEntries.push(entry)
430
575
  if (!inRange(run.finishedAt ?? run.queuedAt, parsed.from, parsed.to, parsed.timeZone)) continue
431
- entries.push({ run, task, brief })
576
+ entries.push(entry)
432
577
  }
433
578
  entries.sort((left, right) =>
434
579
  String(right.run.finishedAt ?? right.run.queuedAt).localeCompare(String(left.run.finishedAt ?? left.run.queuedAt))
435
580
  || String(right.run.id).localeCompare(String(left.run.id)))
581
+ return { page, tasks, briefs, entries, historyEntries }
582
+ }
583
+
584
+ async function todosFor(parsed, sourceEntries, options = {}) {
585
+ const entries = sourceEntries ?? (await entriesFor(parsed)).entries
586
+ const [acks, watches] = await Promise.all([store.listTodoAcks(), store.listTodoWatches()])
587
+ const ackById = new Map(acks.map((ack) => [ack.todoId, ack]))
588
+ const watchById = new Map(watches.map((watch) => [watch.todoId, watch]))
589
+ const todos = aggregateTodos(entries).map((item) => {
590
+ const ack = ackById.get(item.id)
591
+ const decision = ack !== undefined && todoAckCovers(ack, item) ? (ack.decision ?? 'confirmed') : undefined
592
+ const decidedAt = decision === undefined ? undefined : ack.confirmedAt
593
+ return {
594
+ ...item,
595
+ watch: watchSummary(watchById.get(item.id), parsed.to),
596
+ ...(item.symbol === undefined ? {} : { symbolKey: stockSymbolKey(item.symbol) }),
597
+ ...(decision === 'confirmed' ? { ackedAt: decidedAt } : {}),
598
+ ...(decision === 'deferred' ? { deferredAt: decidedAt } : {}),
599
+ ...(decision === undefined ? {} : { decision }),
600
+ }
601
+ })
602
+ const visible = options.includeAcked === true ? todos : todos.filter((item) => item.ackedAt === undefined)
603
+ const expiredIds = new Set(visible.filter((item) => todoExpired(item, parsed.to, parsed.timeZone)).map((item) => item.id))
604
+ visible.sort((left, right) => {
605
+ const archive = (expiredIds.has(left.id) ? 1 : 0) - (expiredIds.has(right.id) ? 1 : 0)
606
+ if (archive !== 0) return archive
607
+ if (expiredIds.has(left.id)) {
608
+ return String(right.dueAt ?? '').localeCompare(String(left.dueAt ?? ''))
609
+ || String(right.lastSeenAt).localeCompare(String(left.lastSeenAt))
610
+ || String(left.id).localeCompare(String(right.id))
611
+ }
612
+ const kind = (KIND_RANK[left.kind] ?? 9) - (KIND_RANK[right.kind] ?? 9)
613
+ if (kind !== 0) return kind
614
+ const watch = watchRank(left) - watchRank(right)
615
+ if (watch !== 0) return watch
616
+ return String(left.dueAt ?? '9999-12-31').localeCompare(String(right.dueAt ?? '9999-12-31'))
617
+ || String(right.lastSeenAt).localeCompare(String(left.lastSeenAt))
618
+ || String(left.id).localeCompare(String(right.id))
619
+ })
620
+ return visible
621
+ }
622
+
623
+ async function board(query = {}) {
624
+ const parsed = parseBoardQuery(query, now)
625
+ const { page, tasks, briefs, entries, historyEntries } = await entriesFor(parsed)
626
+ const lifetime = await store.countBriefs()
436
627
  let start = 0
437
628
  if (parsed.before !== undefined) {
438
629
  const index = entries.findIndex((entry) => entry.run.id === parsed.before)
@@ -445,10 +636,12 @@ export function createBoardService(options) {
445
636
  const askByRun = typeof asks?.latestForRuns === 'function'
446
637
  ? await asks.latestForRuns(pageRunIds)
447
638
  : new Map()
448
- const ackById = new Map(todoAcks.map((ack) => [ack.todoId, ack]))
449
- const todos = aggregateTodos(entries).filter((item) => !todoAckCovers(ackById.get(item.id), item))
450
- const stocks = aggregateStocks(entries, todos)
451
- const gaps = aggregateGaps(entries)
639
+ const todos = await todosFor(parsed, entries, { includeAcked: true })
640
+ const openTodos = todos.filter((item) => item.ackedAt === undefined && item.deferredAt === undefined)
641
+ const activeTodos = openTodos.filter((item) => !todoExpired(item, parsed.to, parsed.timeZone))
642
+ const firstSeen = firstSeenMaps(historyEntries)
643
+ const stocks = aggregateStocks(entries, activeTodos, firstSeen.stocks)
644
+ const gaps = aggregateGaps(entries, firstSeen.gaps)
452
645
  const health = healthOf({
453
646
  runs: page.runs,
454
647
  briefs,
@@ -457,6 +650,8 @@ export function createBoardService(options) {
457
650
  scheduler,
458
651
  tasks,
459
652
  })
653
+ const today = parsed.to
654
+ const isToday = (value) => dateOf(value, parsed.timeZone) === today
460
655
  return {
461
656
  ok: true,
462
657
  generatedAt: iso(now()),
@@ -464,10 +659,14 @@ export function createBoardService(options) {
464
659
  range: { days: parsed.days === 'all' ? 'all' : Number(parsed.days), from: parsed.from ?? null, to: parsed.to },
465
660
  stats: {
466
661
  briefs: entries.length,
467
- todos: todos.length,
662
+ briefsToday: entries.filter((entry) => isToday(entry.run.finishedAt ?? entry.run.queuedAt)).length,
663
+ todos: openTodos.length,
468
664
  stocks: stocks.length,
665
+ stocksNewToday: stocks.filter((stock) => isToday(stock.firstSeenAt)).length,
469
666
  gaps: gaps.length,
667
+ gapsNewToday: gaps.filter((gap) => isToday(gap.firstSeenAt)).length,
470
668
  issues7d: health.issueCount,
669
+ issuesToday: health.todayIssueCount,
471
670
  },
472
671
  cards: pageEntries.map((entry) => cardOf(entry.run, entry.brief, entry.task, askByRun.get(entry.run.id))),
473
672
  todos: todos.slice(0, MAX_TODOS),
@@ -478,10 +677,82 @@ export function createBoardService(options) {
478
677
  }
479
678
  }
480
679
 
680
+ /** Unbounded TODO projection for the watcher; the page still gets MAX_TODOS. */
681
+ async function openTodos(query = {}) {
682
+ return todosFor(parseBoardQuery(query, now))
683
+ }
684
+
685
+ async function closeWatch(todoId, at) {
686
+ const watches = await store.listTodoWatches()
687
+ const watch = watches.find((entry) => entry.todoId === todoId)
688
+ if (watch === undefined || watch.status === 'resolved') return
689
+ const next = {
690
+ ...watch,
691
+ status: 'resolved',
692
+ ...(watch.status === 'resolved' ? {} : { resolvedFrom: watch.status }),
693
+ updatedAt: at,
694
+ }
695
+ delete next.handoffReason
696
+ delete next.autoRequestedAt
697
+ delete next.expiredReason
698
+ await store.putTodoWatch(next)
699
+ }
700
+
701
+ async function promoteTodo(todoId) {
702
+ const watches = await store.listTodoWatches()
703
+ const watch = watches.find((entry) => entry.todoId === todoId)
704
+ if (watch === undefined) {
705
+ throw new BoardError('todo_not_tracked', '这条 TODO 没有跟踪记录,暂时不能转入自动核验。', 409)
706
+ }
707
+ if (watch.kind !== 'confirm' && watch.kind !== 'verify') {
708
+ throw new BoardError('todo_auto_unsupported', '这条 TODO 暂不支持自动核验。', 409)
709
+ }
710
+ if (watch.status === 'expired' || (typeof watch.dueAt === 'string' && watch.dueAt < localPartsAt(now()).date)) {
711
+ throw new BoardError('todo_expired', '这条 TODO 已过期,不能再转入自动核验。', 409)
712
+ }
713
+ if (isUsSymbol(watch.symbol)) {
714
+ throw new BoardError('todo_auto_unsupported', '美股标的暂不支持自动核验。', 409)
715
+ }
716
+ if (watch.status === 'triggered') {
717
+ throw new BoardError('todo_already_triggered', '这条条件已经触发,请直接确认或忽略。', 409)
718
+ }
719
+ const at = iso(now())
720
+ const next = {
721
+ ...watch,
722
+ status: 'watching',
723
+ autoRequestedAt: at,
724
+ updatedAt: at,
725
+ }
726
+ delete next.resolvedFrom
727
+ delete next.handoffReason
728
+ delete next.expiredReason
729
+ delete next.verdict
730
+ delete next.evidence
731
+ delete next.source
732
+ delete next.evidenceRunId
733
+ delete next.evidenceSessionId
734
+ delete next.notifiedAt
735
+ delete next.notifiedStatus
736
+ await store.putTodoWatch(next)
737
+ await store.clearTodoDecision(todoId)
738
+ return { id: todoId, action: 'auto', status: 'watching', requestedAt: at }
739
+ }
740
+
741
+ async function decideTodo(todoId, action) {
742
+ if (action === 'auto') return promoteTodo(todoId)
743
+ if (action !== 'confirm' && action !== 'defer') {
744
+ throw new BoardError('invalid_action', '未知的 TODO 操作。', 400)
745
+ }
746
+ const decision = action === 'defer' ? 'deferred' : 'confirmed'
747
+ const record = await store.decideTodo(todoId, decision)
748
+ await closeWatch(todoId, record.confirmedAt)
749
+ return { id: record.todoId, action, decision, decidedAt: record.confirmedAt }
750
+ }
751
+
481
752
  async function confirmTodo(todoId) {
482
- const record = await store.confirmTodo(todoId)
483
- return { id: record.todoId, confirmedAt: record.confirmedAt }
753
+ const result = await decideTodo(todoId, 'confirm')
754
+ return { id: result.id, confirmedAt: result.decidedAt }
484
755
  }
485
756
 
486
- return { board, confirmTodo }
757
+ return { board, openTodos, confirmTodo, decideTodo }
487
758
  }