@v587d/capital-generation 2.22.0 → 2.24.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 +38 -0
- package/README.md +12 -2
- package/automation/index.js +10 -1
- package/automation/package.json +2 -1
- package/automation/route.js +8 -0
- package/automation/schema.js +4 -0
- package/automation/service.js +64 -1
- package/automation/storage.js +329 -0
- package/chart-ui/package.json +1 -1
- package/config/client.js +36 -5
- package/config/client.src.cjs +389 -2
- package/config/package.json +1 -1
- package/lib/data-collector/catalog-taxonomy.d.ts +16 -0
- package/lib/data-collector/catalog-taxonomy.js +175 -0
- package/lib/data-collector/hub.d.ts +16 -3
- package/lib/data-collector/hub.js +40 -6
- package/lib/data-collector/tools.js +46 -8
- package/lib/web-retriever/local-fetch.d.ts +1 -1
- package/lib/web-retriever/local-fetch.js +1 -1
- package/lib/web-retriever/wind-client.d.ts +1 -1
- package/lib/web-retriever/wind-client.js +1 -1
- package/package.json +1 -1
- package/preset/capital-generation/skills/capital-data-protocol/SKILL.md +21 -22
- package/watchlist/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -7,6 +7,44 @@
|
|
|
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.24.0] - 2026-11-14
|
|
11
|
+
|
|
12
|
+
数据能力目录改为九主题分片:`list_capabilities()` 先给索引,按 topic 取片,需要全量时可九片全取;目录不再受单条 6,144 / 8,192 字符约束,同时收紧诊断口,避免全量名字绕过协议。
|
|
13
|
+
|
|
14
|
+
### Added
|
|
15
|
+
|
|
16
|
+
- **九主题能力目录**:新增 `catalog-taxonomy.ts`,128 个 capability 显式落到 `quote / flow / financials / fund / events / macro / futures / cross / meta` 九片;缺项、孤儿项由测试点名。`list_capabilities()` 无参数返回九行索引(`topic|中文|条数|码点|例子`,当前 545 字符),`list_capabilities({ topic })` 返回该片 `capability|summary|paginated` 行;当前单片最大 1,182 码点(原始回执 1,216 字符)。
|
|
17
|
+
- **按问题取片,不设片数上限**:复杂/跨资产问题可在同一条消息里九片全取(九个独立调用、框架并发),单一资产按需取;`topic=all` 仍不提供,避免把九片合成一条 10k 结果触发剪枝。
|
|
18
|
+
- **能力总表加 topic 列**:`docs/data-collector-capabilities.md` 与生成脚本同步;新增能力忘登记 topic 时测试直接失败。
|
|
19
|
+
|
|
20
|
+
### Changed
|
|
21
|
+
|
|
22
|
+
- **`list_capabilities` 行为变更**:无参数不再返回 128 行全目录,而是九行索引;旧调用方需先取索引,再按 topic 取片。协议 skill、data_collector persona 与 `docs/dev/data-roles.md` 已同步。
|
|
23
|
+
- **目录预算重划**:`thresholdChars` 仍为 8192;索引 <1024、单片 <2048 软目标 / 4096 硬上限、单能力详情 <4096。6,144 不再是能力总数的上限,也不再作为 CI 的目录闸门。
|
|
24
|
+
- **能力发现改为三步**:索引 → 主题分片 → `describe_capability` 详情;同一个 topic 只取一次,同一个能力只描述一次。
|
|
25
|
+
|
|
26
|
+
### Fixed
|
|
27
|
+
|
|
28
|
+
- **诊断口泄漏全量目录**:`dc_status` 原先返回 128 个 capability 名字的 4,160 字符清单,模型可据此跳过主题分片,10k 时会把分片打回原形;现在只返回 `registered_capability_count` 与九片 `registered_topics` 计数。
|
|
29
|
+
- **`capability_unknown` 回流全量名字**:未知能力原先 `join` 全部可用名字,现在回九行索引,按 topic 取片后原样复制;错误长度不再随目录条数增长。
|
|
30
|
+
- **索引体积旧数**:设计文档里的 477 码点更新为实测 545(含例子),测试仍以实测索引与分片计数为准。
|
|
31
|
+
|
|
32
|
+
### Migration
|
|
33
|
+
|
|
34
|
+
- data_collector 或脚本若依赖 `list_capabilities()` 一次拿全目录:改为先取索引,再按 topic 分片取;需要全量就九片分别取,不要新增 `topic=all`。
|
|
35
|
+
- `dc_status` 的 `registered_capabilities: string[]` 改为 `registered_capability_count: number` + `registered_topics: { topic, label, count }[]`;排障看计数与片汇总,名字从分片取。
|
|
36
|
+
- 无配置项变更;升级后重启 dsh 进程生效。
|
|
37
|
+
|
|
38
|
+
## [2.23.0] - 2026-11-13
|
|
39
|
+
|
|
40
|
+
投研自动化设置新增「存储」面板:工作区占用一眼可见,缓存一键清理,清理边界只碰 `capital-data`。
|
|
41
|
+
|
|
42
|
+
### Added
|
|
43
|
+
|
|
44
|
+
- **投研自动化设置新增「存储」组**:显示当前默认工作区的 `capital-data` 可清理尺寸(按数据集 / 数据档案 / OCR 拆分)、`capital-analysis` 保留尺寸、运行会话尺寸与个数;「清除数据缓存」二次确认后只删 `capital-data` 的直接子项,保留 `capital-analysis`、任务、运行记录、简报、通知与运行会话。有活动运行时禁止清理。
|
|
45
|
+
- **「存储」组面板化呈现**:合计、可清理缓存、分析结果、运行会话收进带描边圆角的面板,分类尺寸用胶囊展示、分析结果带「保留」徽章;空缓存、读取失败、活动运行等状态都在行内说明,不再散落成小字。
|
|
46
|
+
|
|
47
|
+
|
|
10
48
|
## [2.22.0] - 2026-11-13
|
|
11
49
|
|
|
12
50
|
适配 DSH `0.2.2-rc.2`:子 Agent 改为具名协作,单轮编排与数据/图表契约不变。
|
package/README.md
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
<a href="LICENSE"><img src="https://img.shields.io/badge/License-MIT-green" alt="License"></a>
|
|
4
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
5
|
<a href="https://github.com/deepseek-ai"><img src="https://img.shields.io/badge/DSH%20Baseline-0.2.2--rc.2-blue" alt="DSH@0.2.2-rc.2"></a>
|
|
6
|
-
<a href="https://github.com/v587d/capital-generation/releases"><img src="https://img.shields.io/badge/version-2.
|
|
6
|
+
<a href="https://github.com/v587d/capital-generation/releases"><img src="https://img.shields.io/badge/version-2.24.0-9cf" alt="Version"></a>
|
|
7
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>
|
|
8
8
|
</p>
|
|
9
9
|
|
|
@@ -184,7 +184,7 @@ Capital Generation 是运行在 [DeepSeek Harness(DSH)](https://github.com/d
|
|
|
184
184
|
- **安装后找不到模式?** 确认插件出现在「插件」→ 已安装列表;Web / CLI profile 安装后要重启该 profile,并在新会话选择模式。选择器里应看到自动模式、行情专家、资讯专员;分析师和绘图专员是自动模式的内部角色,不会出现在这里。
|
|
185
185
|
- **配置在哪?** 打开「插件」→ 已安装的 **Capital Generation**,插件介绍下方就是「数据源 / 投研自动化 / 精选 Skills / 包含的组件」四格,五把密钥都在第一格;第二格可指定任务统一使用的默认工作区,也能改自动检查间隔与最长运行时间等上限;不在 DSH 的普通「设置」页面,也不用点进任何一行组件。保存密钥后新建会话再试。
|
|
186
186
|
- **升级到 2.9.0 后,分析师和绘图专员去哪了?** 这一版把它们收进自动模式内部,不再出现在选择器与预设管理里,避免误开一个没有取数入口的空会话。旧会话仍能按原身份恢复;新任务直接用自动模式提出即可。
|
|
187
|
-
- **桌面端升级后仍是旧版?** 桌面端安装时会固定所解析的版本,不会自动升级。卸载后重新安装,再到插件详情查看版本号;如需指定版本,可在地址末尾加 `#v2.
|
|
187
|
+
- **桌面端升级后仍是旧版?** 桌面端安装时会固定所解析的版本,不会自动升级。卸载后重新安装,再到插件详情查看版本号;如需指定版本,可在地址末尾加 `#v2.24.0` 或 `@2.24.0`。
|
|
188
188
|
- **刚发布的新版本装不到?** 桌面端取包时会跳过**刚发布不久**的版本(宿主侧包管理器的发布冷却策略,实测会静默装成上一个版本),国内镜像的同步也可能滞后一段时间。急着用最新代码,改用仓库地址安装最直接;但仓库地址安装的是 git 依赖,插件页不显示「版本」检查。
|
|
189
189
|
- **插件页的「版本」段怎么用?** 只有用包名从 npm 安装的版本才有;它只列比当前新的版本。回旧版要先卸载,再安装 `@v587d/capital-generation@版本号`(桌面端地址末尾加 `#v版本号`);旧版必须匹配当前 DSH 基线,对应关系见 [CHANGELOG 的 Migration](CHANGELOG.md)。
|
|
190
190
|
- **网页抓取失败?** 配置卡片中的「允许启动本地提取网页内容」默认开启:AnySearch 提取失败时可尝试本机直连。关闭后,本机直连的具名来源查询也不可用;请检查该开关和网络连接。
|
|
@@ -217,3 +217,13 @@ npm run smoke:boot # 检查插件装配
|
|
|
217
217
|
- 行情、财务、公告与网页材料来自五类需自备密钥的服务(同花顺 Fuyao、Wind Alice、AnySearch、PaddleOCR、FTShare 非凸科技)与一批公开口径的来源(东方财富、腾讯、新浪、财联社、华尔街见闻、巨潮互动易、上证 e互动、同花顺公开站点);数据版权归各服务方,额度与条款以服务方为准,本项目不重新分发原始数据。
|
|
218
218
|
|
|
219
219
|
第三方组件、版本与许可,以及宿主提供哪部分、构建期用什么、各服务的数据会出到哪些地方,逐条列在 [第三方组件与许可](THIRD_PARTY_NOTICES.md)。
|
|
220
|
+
|
|
221
|
+
## Star History
|
|
222
|
+
|
|
223
|
+
<a href="https://www.star-history.com/?repos=v587d%2Fcapital-generation&type=date&legend=top-left">
|
|
224
|
+
<picture>
|
|
225
|
+
<source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/chart?repos=v587d/capital-generation&type=date&theme=dark&legend=top-left" />
|
|
226
|
+
<source media="(prefers-color-scheme: light)" srcset="https://api.star-history.com/chart?repos=v587d/capital-generation&type=date&legend=top-left" />
|
|
227
|
+
<img alt="Star History Chart" src="https://api.star-history.com/chart?repos=v587d/capital-generation&type=date&legend=top-left" />
|
|
228
|
+
</picture>
|
|
229
|
+
</a>
|
package/automation/index.js
CHANGED
|
@@ -20,6 +20,7 @@ import { resolveAutomationSettings } from './settings.js'
|
|
|
20
20
|
import { installAutomationPolicy } from './policy.js'
|
|
21
21
|
import { createCalendarSource } from './calendar-source.js'
|
|
22
22
|
import { createWorkspaceCatalog, defaultWorkspacePath } from './workspaces.js'
|
|
23
|
+
import { createStorageService } from './storage.js'
|
|
23
24
|
import { sanitizeMessage } from './redact.js'
|
|
24
25
|
|
|
25
26
|
export const name = 'capital-automation'
|
|
@@ -59,6 +60,13 @@ export function createAutomationRuntime(options) {
|
|
|
59
60
|
getDefaultWorkspaceId: () => getSettings()?.defaultWorkspaceId,
|
|
60
61
|
logger,
|
|
61
62
|
})
|
|
63
|
+
const storage = createStorageService({
|
|
64
|
+
ctx,
|
|
65
|
+
workspaces,
|
|
66
|
+
profile: { runDir, displayName },
|
|
67
|
+
now,
|
|
68
|
+
logger,
|
|
69
|
+
})
|
|
62
70
|
const store = createAutomationStore({
|
|
63
71
|
openDomain: () => storageDomain.open(domainSpec),
|
|
64
72
|
profile: { name: rawProfileName },
|
|
@@ -148,6 +156,7 @@ export function createAutomationRuntime(options) {
|
|
|
148
156
|
briefs,
|
|
149
157
|
asks,
|
|
150
158
|
boardService,
|
|
159
|
+
storage,
|
|
151
160
|
now,
|
|
152
161
|
})
|
|
153
162
|
runner.installListeners()
|
|
@@ -156,7 +165,7 @@ export function createAutomationRuntime(options) {
|
|
|
156
165
|
installAutomationPolicy({ ctx: toolsCtx, runner, logger })
|
|
157
166
|
})
|
|
158
167
|
}
|
|
159
|
-
return { store, runner, scheduler, briefs, watches, asks, service, calendar, workspaces, profile: { displayName, runDir, ownerDir } }
|
|
168
|
+
return { store, runner, scheduler, briefs, watches, asks, service, calendar, workspaces, storage, profile: { displayName, runDir, ownerDir } }
|
|
160
169
|
}
|
|
161
170
|
|
|
162
171
|
/**
|
package/automation/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@v587d/capital-automation",
|
|
3
|
-
"version": "2.
|
|
3
|
+
"version": "2.24.0",
|
|
4
4
|
"description": "CapGen 投研自动化:独立 host bundle(固定 capital_automation 域、单 scheduler owner、/capital-automation 路由与浏览器页面)。",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"type": "module",
|
|
@@ -45,6 +45,7 @@
|
|
|
45
45
|
"ask.js",
|
|
46
46
|
"scheduler.js",
|
|
47
47
|
"workspaces.js",
|
|
48
|
+
"storage.js",
|
|
48
49
|
"contract.js",
|
|
49
50
|
"policy.js",
|
|
50
51
|
"route.js",
|
package/automation/route.js
CHANGED
|
@@ -230,6 +230,14 @@ async function dispatch({ req, method, suffix, url, service, requestId }) {
|
|
|
230
230
|
if (suffix === WORKSPACES_SUFFIX && method === 'GET') {
|
|
231
231
|
return { body: await service.workspaceCatalog() }
|
|
232
232
|
}
|
|
233
|
+
if (suffix === '/storage') {
|
|
234
|
+
if (method !== 'GET') throw new AutomationError('method_not_allowed', '只支持 GET。', 405)
|
|
235
|
+
return { body: await service.storage() }
|
|
236
|
+
}
|
|
237
|
+
if (suffix === '/storage/clear') {
|
|
238
|
+
if (method !== 'POST') throw new AutomationError('method_not_allowed', '只支持 POST。', 405)
|
|
239
|
+
return { body: await service.clearStorage(await readBody(req)) }
|
|
240
|
+
}
|
|
233
241
|
if (suffix === '/board' && method === 'GET') {
|
|
234
242
|
return { body: await service.board(queryOf(url, new Set(['days', 'tz', 'limit', 'before', 'category']), 5)) }
|
|
235
243
|
}
|
package/automation/schema.js
CHANGED
|
@@ -485,6 +485,10 @@ export const TodoDecisionSchema = z.strictObject({
|
|
|
485
485
|
action: z.enum(['confirm', 'defer', 'auto']),
|
|
486
486
|
})
|
|
487
487
|
|
|
488
|
+
export const StorageClearSchema = z.strictObject({
|
|
489
|
+
confirm: z.literal(true),
|
|
490
|
+
})
|
|
491
|
+
|
|
488
492
|
export const AskCreateSchema = z.strictObject({
|
|
489
493
|
question: z.string().trim().min(1).max(MAX_ASK_QUESTION_CHARS),
|
|
490
494
|
timeZone: timeZone.optional(),
|
package/automation/service.js
CHANGED
|
@@ -19,6 +19,7 @@ import {
|
|
|
19
19
|
import {
|
|
20
20
|
AskCreateSchema,
|
|
21
21
|
NotificationsReadSchema,
|
|
22
|
+
StorageClearSchema,
|
|
22
23
|
TaskCategorySchema,
|
|
23
24
|
TaskCreateSchema,
|
|
24
25
|
TaskPatchSchema,
|
|
@@ -107,7 +108,7 @@ export class AutomationError extends Error {
|
|
|
107
108
|
}
|
|
108
109
|
|
|
109
110
|
export function createAutomationService(options) {
|
|
110
|
-
const { store, scheduler, runner, calendar, profile, workspaces, version, settings, briefs, asks, boardService, now = () => Date.now() } = options
|
|
111
|
+
const { store, scheduler, runner, calendar, profile, workspaces, version, settings, briefs, asks, boardService, storage, now = () => Date.now() } = options
|
|
111
112
|
let chain = Promise.resolve()
|
|
112
113
|
|
|
113
114
|
function serialize(operation) {
|
|
@@ -116,6 +117,29 @@ export function createAutomationService(options) {
|
|
|
116
117
|
return next
|
|
117
118
|
}
|
|
118
119
|
|
|
120
|
+
function storageMissing() {
|
|
121
|
+
return new AutomationError('storage_unavailable', '工作区存储服务尚未就绪。', 503)
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
function storageFailure(error) {
|
|
125
|
+
if (error instanceof AutomationError) return error
|
|
126
|
+
if (error?.code === 'cache_root_unsafe') {
|
|
127
|
+
return new AutomationError('cache_root_unsafe', '缓存目录不是普通目录,已停止清理。', 409)
|
|
128
|
+
}
|
|
129
|
+
if (error?.code === 'workspace_unavailable') {
|
|
130
|
+
return new AutomationError('workspace_unavailable', '工作区目录暂时不可用。', 503)
|
|
131
|
+
}
|
|
132
|
+
if (error?.code === 'clear_failed') {
|
|
133
|
+
return new AutomationError('clear_failed', '清理失败,请稍后再试。', 500)
|
|
134
|
+
}
|
|
135
|
+
return new AutomationError('storage_unavailable', '工作区存储暂时不可用。', 503)
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
async function activeRuns() {
|
|
139
|
+
const page = await store.listRunsPage({ limit: 2_000 })
|
|
140
|
+
return page.runs.filter((run) => ACTIVE_STATUSES.has(run.status))
|
|
141
|
+
}
|
|
142
|
+
|
|
119
143
|
async function withTask(id) {
|
|
120
144
|
const task = await store.getTask(id)
|
|
121
145
|
if (task === undefined) throw new AutomationError('task_not_found', '任务不存在。', 404)
|
|
@@ -224,6 +248,43 @@ export function createAutomationService(options) {
|
|
|
224
248
|
}
|
|
225
249
|
}
|
|
226
250
|
|
|
251
|
+
async function storageStats() {
|
|
252
|
+
if (storage === undefined) throw storageMissing()
|
|
253
|
+
let stats
|
|
254
|
+
try {
|
|
255
|
+
stats = await storage.stats()
|
|
256
|
+
} catch (error) {
|
|
257
|
+
throw storageFailure(error)
|
|
258
|
+
}
|
|
259
|
+
const active = await activeRuns()
|
|
260
|
+
return {
|
|
261
|
+
storage: {
|
|
262
|
+
...stats,
|
|
263
|
+
activeRuns: active.length,
|
|
264
|
+
canClear: active.length === 0 && stats.cache?.unsafe !== true,
|
|
265
|
+
},
|
|
266
|
+
}
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
async function clearStorage(input) {
|
|
270
|
+
const parsed = parseStrict(StorageClearSchema, input, 'storage/clear')
|
|
271
|
+
if (parsed.confirm !== true) throw new AutomationError('invalid_request', '确认清理后才能删除缓存。', 400)
|
|
272
|
+
if (storage === undefined) throw storageMissing()
|
|
273
|
+
return serialize(async () => {
|
|
274
|
+
const active = await activeRuns()
|
|
275
|
+
if (active.length > 0) {
|
|
276
|
+
throw new AutomationError('run_in_progress', '有运行正在进行,请等运行结束后再清理。', 409, { runId: active[0].id })
|
|
277
|
+
}
|
|
278
|
+
let cleared
|
|
279
|
+
try {
|
|
280
|
+
cleared = await storage.clear()
|
|
281
|
+
} catch (error) {
|
|
282
|
+
throw storageFailure(error)
|
|
283
|
+
}
|
|
284
|
+
return { cleared }
|
|
285
|
+
})
|
|
286
|
+
}
|
|
287
|
+
|
|
227
288
|
async function createTask(input) {
|
|
228
289
|
const parsed = parseStrict(TaskCreateSchema, input, 'task')
|
|
229
290
|
const defaults = { ...DEFAULT_AUTOMATION_SETTINGS, ...settings() }
|
|
@@ -522,6 +583,8 @@ export function createAutomationService(options) {
|
|
|
522
583
|
serialize,
|
|
523
584
|
meta,
|
|
524
585
|
workspaceCatalog,
|
|
586
|
+
storage: storageStats,
|
|
587
|
+
clearStorage,
|
|
525
588
|
listTasks,
|
|
526
589
|
taskDetail,
|
|
527
590
|
createTask,
|
|
@@ -0,0 +1,329 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Workspace storage accounting and cache cleanup. `capital-data` is disposable
|
|
3
|
+
* (datasets, derived profiles, OCR); `capital-analysis` is user-facing output and
|
|
4
|
+
* stays read-only. Only direct children of `capital-data` are removed, never the
|
|
5
|
+
* directory itself, and symlinks are never followed.
|
|
6
|
+
*/
|
|
7
|
+
import { lstat, readdir, realpath, rm, unlink } from 'node:fs/promises'
|
|
8
|
+
import { homedir } from 'node:os'
|
|
9
|
+
import { isAbsolute, join, relative, resolve, sep } from 'node:path'
|
|
10
|
+
|
|
11
|
+
import { defaultWorkspaceTitle, workspaceDisplayPath } from './workspaces.js'
|
|
12
|
+
|
|
13
|
+
export const CACHE_DIR = 'capital-data'
|
|
14
|
+
export const RETAINED_DIR = 'capital-analysis'
|
|
15
|
+
|
|
16
|
+
const CACHE_GROUPS = [
|
|
17
|
+
{ id: 'datasets', name: 'datasets' },
|
|
18
|
+
{ id: 'profiles', name: 'profiles' },
|
|
19
|
+
{ id: 'ocr', name: 'ocr' },
|
|
20
|
+
]
|
|
21
|
+
const ANALYSIS_GROUPS = [
|
|
22
|
+
{ id: 'charts', name: 'charts' },
|
|
23
|
+
{ id: 'runs', name: 'runs' },
|
|
24
|
+
]
|
|
25
|
+
const OTHER_ID = 'other'
|
|
26
|
+
const MAX_SCAN_ENTRIES = 150_000
|
|
27
|
+
const MAX_SCAN_MS = 5_000
|
|
28
|
+
const STATS_TTL_MS = 15_000
|
|
29
|
+
|
|
30
|
+
const ZERO = Object.freeze({ bytes: 0, files: 0 })
|
|
31
|
+
|
|
32
|
+
export class StorageError extends Error {
|
|
33
|
+
constructor(code, message) {
|
|
34
|
+
super(message)
|
|
35
|
+
this.name = 'StorageError'
|
|
36
|
+
this.code = code
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
function isMissing(error) {
|
|
41
|
+
return error?.code === 'ENOENT'
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
function safeJoin(root, relativePath) {
|
|
45
|
+
if (typeof root !== 'string' || root.length === 0 || !isAbsolute(root)) {
|
|
46
|
+
throw new StorageError('workspace_unavailable', '工作区路径不可用。')
|
|
47
|
+
}
|
|
48
|
+
if (typeof relativePath !== 'string' || relativePath.length === 0 || isAbsolute(relativePath)) {
|
|
49
|
+
throw new StorageError('workspace_unavailable', '缓存目录不可用。')
|
|
50
|
+
}
|
|
51
|
+
const base = resolve(root)
|
|
52
|
+
const target = resolve(base, relativePath)
|
|
53
|
+
const rel = relative(base, target)
|
|
54
|
+
if (rel === '' || rel === '..' || rel.startsWith(`..${sep}`) || isAbsolute(rel)) {
|
|
55
|
+
throw new StorageError('workspace_unavailable', '缓存目录不在工作区内。')
|
|
56
|
+
}
|
|
57
|
+
return target
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
function scanState() {
|
|
61
|
+
return { entries: 0, truncated: false, unreadable: 0, startedAt: Date.now() }
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
function overLimit(scan) {
|
|
65
|
+
if (scan.truncated) return true
|
|
66
|
+
scan.entries += 1
|
|
67
|
+
if (scan.entries > MAX_SCAN_ENTRIES || Date.now() - scan.startedAt > MAX_SCAN_MS) {
|
|
68
|
+
scan.truncated = true
|
|
69
|
+
return true
|
|
70
|
+
}
|
|
71
|
+
return false
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
function add(target, value) {
|
|
75
|
+
target.bytes += value.bytes
|
|
76
|
+
target.files += value.files
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/**
|
|
80
|
+
* Sizes without following symlinks. Unreadable entries still count toward
|
|
81
|
+
* `unreadable` but do not fail the whole panel; a capped scan reports `truncated`
|
|
82
|
+
* while cleanup may still remove everything.
|
|
83
|
+
*/
|
|
84
|
+
async function measurePath(target, scan) {
|
|
85
|
+
if (overLimit(scan)) return ZERO
|
|
86
|
+
let metadata
|
|
87
|
+
try {
|
|
88
|
+
metadata = await lstat(target)
|
|
89
|
+
} catch (error) {
|
|
90
|
+
if (!isMissing(error)) scan.unreadable += 1
|
|
91
|
+
return ZERO
|
|
92
|
+
}
|
|
93
|
+
if (metadata.isSymbolicLink()) return ZERO
|
|
94
|
+
if (metadata.isFile()) return { bytes: metadata.size, files: 1 }
|
|
95
|
+
if (!metadata.isDirectory()) return ZERO
|
|
96
|
+
let entries
|
|
97
|
+
try {
|
|
98
|
+
entries = await readdir(target, { withFileTypes: true })
|
|
99
|
+
} catch (error) {
|
|
100
|
+
if (!isMissing(error)) scan.unreadable += 1
|
|
101
|
+
return ZERO
|
|
102
|
+
}
|
|
103
|
+
const result = { bytes: 0, files: 0 }
|
|
104
|
+
for (const entry of entries) {
|
|
105
|
+
add(result, await measurePath(join(target, entry.name), scan))
|
|
106
|
+
if (scan.truncated) break
|
|
107
|
+
}
|
|
108
|
+
return result
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
function emptyGroups(groups) {
|
|
112
|
+
return Object.fromEntries([...groups.map((group) => [group.id, { ...ZERO }]), [OTHER_ID, { ...ZERO }]])
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
async function measureRoot(workspace, group, groups, scan) {
|
|
116
|
+
const categories = emptyGroups(groups)
|
|
117
|
+
const root = safeJoin(workspace, group)
|
|
118
|
+
let rootMeta
|
|
119
|
+
try {
|
|
120
|
+
rootMeta = await lstat(root)
|
|
121
|
+
} catch (error) {
|
|
122
|
+
if (isMissing(error)) {
|
|
123
|
+
return { bytes: 0, files: 0, categories, truncated: scan.truncated, unreadable: scan.unreadable, unsafe: false }
|
|
124
|
+
}
|
|
125
|
+
throw new StorageError('workspace_unavailable', '工作区目录不可读。')
|
|
126
|
+
}
|
|
127
|
+
if (rootMeta.isSymbolicLink() || !rootMeta.isDirectory()) {
|
|
128
|
+
return { bytes: 0, files: 0, categories, truncated: scan.truncated, unreadable: scan.unreadable, unsafe: true }
|
|
129
|
+
}
|
|
130
|
+
const known = new Set(groups.map((item) => item.name))
|
|
131
|
+
const result = { bytes: 0, files: 0, categories, truncated: false, unreadable: 0, unsafe: false }
|
|
132
|
+
for (const item of groups) {
|
|
133
|
+
const measured = await measurePath(join(root, item.name), scan)
|
|
134
|
+
categories[item.id] = measured
|
|
135
|
+
add(result, measured)
|
|
136
|
+
}
|
|
137
|
+
let entries = []
|
|
138
|
+
try {
|
|
139
|
+
entries = await readdir(root, { withFileTypes: true })
|
|
140
|
+
} catch (error) {
|
|
141
|
+
if (!isMissing(error)) scan.unreadable += 1
|
|
142
|
+
}
|
|
143
|
+
for (const entry of entries) {
|
|
144
|
+
if (known.has(entry.name)) continue
|
|
145
|
+
if (scan.truncated) break
|
|
146
|
+
const measured = await measurePath(join(root, entry.name), scan)
|
|
147
|
+
categories[OTHER_ID].bytes += measured.bytes
|
|
148
|
+
categories[OTHER_ID].files += measured.files
|
|
149
|
+
add(result, measured)
|
|
150
|
+
}
|
|
151
|
+
result.truncated = scan.truncated
|
|
152
|
+
result.unreadable = scan.unreadable
|
|
153
|
+
return result
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
/** Both roots share one scan budget so a huge `capital-data` cannot stall the panel twice. */
|
|
157
|
+
export async function measureWorkspace(workspacePath) {
|
|
158
|
+
const scan = scanState()
|
|
159
|
+
// Retained analysis is usually much smaller; measure it first so a huge
|
|
160
|
+
// `capital-data` cannot starve the retained number behind the same budget.
|
|
161
|
+
const analysis = await measureRoot(workspacePath, RETAINED_DIR, ANALYSIS_GROUPS, scan)
|
|
162
|
+
const cache = await measureRoot(workspacePath, CACHE_DIR, CACHE_GROUPS, scan)
|
|
163
|
+
return { cache, analysis }
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
function categoryOf(name, groups) {
|
|
167
|
+
return groups.find((group) => group.name === name)?.id ?? OTHER_ID
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
function failureCode(error) {
|
|
171
|
+
return typeof error?.code === 'string' && error.code.length <= 40 ? error.code : 'unknown'
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
/**
|
|
175
|
+
* Remove every direct child of `capital-data`; keep the directory and never touch
|
|
176
|
+
* `capital-analysis`. A symlinked cache root is refused outright because following
|
|
177
|
+
* it would turn "clean this workspace" into an arbitrary delete.
|
|
178
|
+
*/
|
|
179
|
+
export async function clearWorkspaceCache(workspacePath) {
|
|
180
|
+
const root = safeJoin(workspacePath, CACHE_DIR)
|
|
181
|
+
let rootMeta
|
|
182
|
+
try {
|
|
183
|
+
rootMeta = await lstat(root)
|
|
184
|
+
} catch (error) {
|
|
185
|
+
if (isMissing(error)) {
|
|
186
|
+
return { bytes: 0, files: 0, categories: emptyGroups(CACHE_GROUPS), failed: [], truncated: false, unreadable: 0 }
|
|
187
|
+
}
|
|
188
|
+
throw new StorageError('clear_failed', '工作区缓存目录不可读。')
|
|
189
|
+
}
|
|
190
|
+
if (rootMeta.isSymbolicLink() || !rootMeta.isDirectory()) {
|
|
191
|
+
throw new StorageError('cache_root_unsafe', '缓存目录不是普通目录,已停止清理。')
|
|
192
|
+
}
|
|
193
|
+
let entries
|
|
194
|
+
try {
|
|
195
|
+
entries = await readdir(root, { withFileTypes: true })
|
|
196
|
+
} catch (error) {
|
|
197
|
+
throw new StorageError('clear_failed', '工作区缓存目录不可读。')
|
|
198
|
+
}
|
|
199
|
+
const scan = scanState()
|
|
200
|
+
const categories = emptyGroups(CACHE_GROUPS)
|
|
201
|
+
const result = { bytes: 0, files: 0, categories, failed: [], truncated: false, unreadable: 0 }
|
|
202
|
+
for (const entry of entries) {
|
|
203
|
+
const category = categoryOf(entry.name, CACHE_GROUPS)
|
|
204
|
+
const target = join(root, entry.name)
|
|
205
|
+
const measured = await measurePath(target, scan)
|
|
206
|
+
try {
|
|
207
|
+
const metadata = await lstat(target)
|
|
208
|
+
if (metadata.isSymbolicLink() || !metadata.isDirectory()) await unlink(target)
|
|
209
|
+
else await rm(target, { recursive: true, force: true, maxRetries: 3, retryDelay: 100 })
|
|
210
|
+
} catch (error) {
|
|
211
|
+
if (!isMissing(error)) result.failed.push({ category, code: failureCode(error) })
|
|
212
|
+
continue
|
|
213
|
+
}
|
|
214
|
+
result.bytes += measured.bytes
|
|
215
|
+
result.files += measured.files
|
|
216
|
+
categories[category].bytes += measured.bytes
|
|
217
|
+
categories[category].files += measured.files
|
|
218
|
+
}
|
|
219
|
+
result.truncated = scan.truncated
|
|
220
|
+
result.unreadable = scan.unreadable
|
|
221
|
+
return result
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
async function sessionSummary(ctx, workspacePath) {
|
|
225
|
+
let persistence
|
|
226
|
+
try {
|
|
227
|
+
persistence = ctx.get('sessionPersistence')
|
|
228
|
+
} catch {
|
|
229
|
+
persistence = undefined
|
|
230
|
+
}
|
|
231
|
+
if (typeof persistence?.list !== 'function') return { available: false, bytes: 0, count: 0 }
|
|
232
|
+
let canonical = workspacePath
|
|
233
|
+
try {
|
|
234
|
+
canonical = await realpath(workspacePath)
|
|
235
|
+
} catch {
|
|
236
|
+
// Keep the registry spelling when realpath races away; exact comparison still helps.
|
|
237
|
+
}
|
|
238
|
+
try {
|
|
239
|
+
const snapshots = await persistence.list()
|
|
240
|
+
let bytes = 0
|
|
241
|
+
let count = 0
|
|
242
|
+
for (const snapshot of snapshots) {
|
|
243
|
+
const cwd = snapshot?.header?.cwd
|
|
244
|
+
if (cwd !== workspacePath && cwd !== canonical) continue
|
|
245
|
+
count += 1
|
|
246
|
+
if (Number.isSafeInteger(snapshot.sizeBytes) && snapshot.sizeBytes > 0) bytes += snapshot.sizeBytes
|
|
247
|
+
}
|
|
248
|
+
return { available: true, bytes, count }
|
|
249
|
+
} catch {
|
|
250
|
+
return { available: false, bytes: 0, count: 0 }
|
|
251
|
+
}
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
function publicWorkspace(workspace) {
|
|
255
|
+
return {
|
|
256
|
+
...(workspace.id === undefined ? {} : { id: workspace.id }),
|
|
257
|
+
title: workspace.title,
|
|
258
|
+
displayPath: workspace.displayPath,
|
|
259
|
+
scope: workspace.scope,
|
|
260
|
+
}
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
/**
|
|
264
|
+
* Active workspace follows the same default the run loop uses: the saved default
|
|
265
|
+
* id when the registry can resolve it, otherwise the dedicated run directory.
|
|
266
|
+
*/
|
|
267
|
+
export function createStorageService(options) {
|
|
268
|
+
const { ctx, workspaces, profile, now = () => Date.now(), logger } = options
|
|
269
|
+
let cached
|
|
270
|
+
let warned = false
|
|
271
|
+
|
|
272
|
+
async function workspaceOf() {
|
|
273
|
+
try {
|
|
274
|
+
const details = await workspaces?.details?.()
|
|
275
|
+
const list = Array.isArray(details?.workspaces) ? details.workspaces : []
|
|
276
|
+
const current = list.find((item) => item?.default === true) ?? list.find((item) => item?.dedicated === true)
|
|
277
|
+
if (current !== undefined && typeof current.path === 'string' && current.path.length > 0) {
|
|
278
|
+
return {
|
|
279
|
+
...(typeof current.id === 'string' ? { id: current.id } : {}),
|
|
280
|
+
title: typeof current.title === 'string' ? current.title : defaultWorkspaceTitle(profile.displayName),
|
|
281
|
+
displayPath: typeof current.displayPath === 'string' ? current.displayPath : current.path,
|
|
282
|
+
scope: current.dedicated === true ? 'dedicated' : 'selected',
|
|
283
|
+
path: current.path,
|
|
284
|
+
}
|
|
285
|
+
}
|
|
286
|
+
} catch (error) {
|
|
287
|
+
if (!warned) {
|
|
288
|
+
warned = true
|
|
289
|
+
logger?.warn?.(`capital-automation: 工作区列表读取失败,存储面板回退到专属目录(${String(error?.message ?? error)})`)
|
|
290
|
+
}
|
|
291
|
+
}
|
|
292
|
+
const path = profile.runDir
|
|
293
|
+
return {
|
|
294
|
+
title: defaultWorkspaceTitle(profile.displayName),
|
|
295
|
+
displayPath: workspaceDisplayPath(path, homedir()),
|
|
296
|
+
scope: 'dedicated',
|
|
297
|
+
path,
|
|
298
|
+
}
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
async function stats(options = {}) {
|
|
302
|
+
const workspace = await workspaceOf()
|
|
303
|
+
const key = workspace.path
|
|
304
|
+
if (options.force !== true && cached !== undefined && cached.key === key && now() - cached.at < STATS_TTL_MS) {
|
|
305
|
+
return cached.value
|
|
306
|
+
}
|
|
307
|
+
const [measured, sessions] = await Promise.all([
|
|
308
|
+
measureWorkspace(workspace.path),
|
|
309
|
+
sessionSummary(ctx, workspace.path),
|
|
310
|
+
])
|
|
311
|
+
const value = {
|
|
312
|
+
workspace: publicWorkspace(workspace),
|
|
313
|
+
cache: measured.cache,
|
|
314
|
+
analysis: measured.analysis,
|
|
315
|
+
sessions,
|
|
316
|
+
}
|
|
317
|
+
cached = { key, at: now(), value }
|
|
318
|
+
return value
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
async function clear() {
|
|
322
|
+
const workspace = await workspaceOf()
|
|
323
|
+
const cleared = await clearWorkspaceCache(workspace.path)
|
|
324
|
+
cached = undefined
|
|
325
|
+
return cleared
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
return { stats, clear, workspaceOf }
|
|
329
|
+
}
|