@v587d/capital-generation 2.21.4 → 2.23.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.
Files changed (47) hide show
  1. package/CHANGELOG.md +31 -0
  2. package/README.md +15 -5
  3. package/automation/board.js +89 -22
  4. package/automation/client.js +3 -3
  5. package/automation/client.src.cjs +5 -1
  6. package/automation/index.js +45 -1
  7. package/automation/package.json +2 -1
  8. package/automation/route.js +8 -0
  9. package/automation/runner.js +3 -2
  10. package/automation/schema.js +4 -0
  11. package/automation/service.js +64 -1
  12. package/automation/storage.js +329 -0
  13. package/chart-ui/package.json +1 -1
  14. package/config/client.js +36 -5
  15. package/config/client.src.cjs +389 -2
  16. package/config/package.json +1 -1
  17. package/lib/agents/messaging-policy.d.ts +21 -0
  18. package/lib/agents/messaging-policy.js +100 -0
  19. package/lib/agents/role-tool-policy.d.ts +23 -7
  20. package/lib/agents/role-tool-policy.js +118 -33
  21. package/lib/agents/root-tool-policy.d.ts +13 -2
  22. package/lib/agents/root-tool-policy.js +87 -28
  23. package/lib/agents/wait-for-agents.d.ts +7 -3
  24. package/lib/agents/wait-for-agents.js +4 -3
  25. package/lib/collector-runtime.js +2 -2
  26. package/lib/data-collector/tools.d.ts +1 -1
  27. package/lib/data-collector/tools.js +31 -3
  28. package/lib/data-collector/upstream-retry.d.ts +48 -0
  29. package/lib/data-collector/upstream-retry.js +192 -0
  30. package/lib/policy-entry.d.ts +3 -3
  31. package/lib/policy-entry.js +3 -1
  32. package/lib/web-retriever/local-fetch.d.ts +1 -1
  33. package/lib/web-retriever/local-fetch.js +1 -1
  34. package/lib/web-retriever/wind-client.d.ts +1 -1
  35. package/lib/web-retriever/wind-client.js +1 -1
  36. package/package.json +6 -6
  37. package/preset/capital-generation/README.md +2 -1
  38. package/preset/capital-generation/agent.patch.yml +58 -44
  39. package/preset/capital-generation/skills/capital-data-profile/SKILL.md +2 -2
  40. package/preset/capital-generation/skills/capital-data-protocol/SKILL.md +20 -8
  41. package/preset/capital-generation/skills/capital-data-query/SKILL.md +2 -2
  42. package/preset/capital-generation/skills/capital-equity-research/SKILL.md +1 -1
  43. package/preset/capital-generation/skills/capital-event-impact/SKILL.md +1 -1
  44. package/preset/capital-generation/skills/capital-orchestration/SKILL.md +70 -72
  45. package/preset/capital-generation/skills/capital-portfolio-review/SKILL.md +1 -1
  46. package/preset/capital-generation/skills/capital-visualization-protocol/SKILL.md +1 -0
  47. package/watchlist/package.json +1 -1
@@ -86,7 +86,7 @@ const BOARD_UI_KEY = 'capital-automation:board-ui:v3'
86
86
  const BOARD_PANEL_KEYS = ['todo', 'stocks', 'gaps', 'health']
87
87
  const BOARD_TODO_PERIODS = ['today', 'future', 'expired']
88
88
  const BOARD_STOCK_PAGE_SIZE = 12
89
- const BOARD_STOCK_ROLES = ['holding', 'risk', 'event', 'watch']
89
+ const BOARD_STOCK_ROLES = ['holding', 'risk', 'event', 'watch', 'other']
90
90
  const BOARD_BRIEF_HIGHLIGHT_MS = 3_000
91
91
  const BOARD_PANEL_IDS = {
92
92
  'capital-automation-todo': 'todo',
@@ -212,10 +212,12 @@ const zh = {
212
212
  roleWatch: '关注',
213
213
  roleEvent: '事件',
214
214
  roleRisk: '风险',
215
+ roleOther: '其他',
215
216
  roleHoldingHint: '自选清单里标记为持仓',
216
217
  roleWatchHint: '在自选清单里关注,未标记持仓',
217
218
  roleEventHint: '近期运行提到需要跟踪的事件或催化',
218
219
  roleRiskHint: '近期运行提示存在风险',
220
+ roleOtherHint: '近期运行提到,不在自选清单里',
219
221
  gapEmpty: '最近运行没有报告数据缺口',
220
222
  gapSeen: '{n} 次运行',
221
223
  gapAll: '查看全部',
@@ -5536,6 +5538,7 @@ function boardRoleLabel(role) {
5536
5538
  if (role === 'holding') return zh.board.roleHolding
5537
5539
  if (role === 'watch') return zh.board.roleWatch
5538
5540
  if (role === 'event') return zh.board.roleEvent
5541
+ if (role === 'other') return zh.board.roleOther
5539
5542
  return zh.board.roleRisk
5540
5543
  }
5541
5544
 
@@ -5543,6 +5546,7 @@ function boardRoleHint(role) {
5543
5546
  if (role === 'holding') return zh.board.roleHoldingHint
5544
5547
  if (role === 'watch') return zh.board.roleWatchHint
5545
5548
  if (role === 'event') return zh.board.roleEventHint
5549
+ if (role === 'other') return zh.board.roleOtherHint
5546
5550
  return zh.board.roleRiskHint
5547
5551
  }
5548
5552
 
@@ -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 },
@@ -109,6 +117,7 @@ export function createAutomationRuntime(options) {
109
117
  scheduler,
110
118
  asks,
111
119
  now,
120
+ loadWatchlist: watchlistLoader(ctx, logger),
112
121
  })
113
122
  watches = createTodoWatchService({
114
123
  store,
@@ -147,6 +156,7 @@ export function createAutomationRuntime(options) {
147
156
  briefs,
148
157
  asks,
149
158
  boardService,
159
+ storage,
150
160
  now,
151
161
  })
152
162
  runner.installListeners()
@@ -155,7 +165,41 @@ export function createAutomationRuntime(options) {
155
165
  installAutomationPolicy({ ctx: toolsCtx, runner, logger })
156
166
  })
157
167
  }
158
- 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 } }
169
+ }
170
+
171
+ /**
172
+ * Radar tiering reads the user's watchlist panel. The watchlist row may settle after this
173
+ * one, so only a successful lookup is cached; a failed read retries next time and the
174
+ * radar falls back to brief tags instead of claiming an empty list.
175
+ */
176
+ function watchlistLoader(ctx, logger) {
177
+ let service
178
+ let warned = false
179
+ return async () => {
180
+ if (service === undefined) {
181
+ try {
182
+ const candidate = ctx.get('capitalWatchlist')
183
+ if (typeof candidate?.list === 'function') service = candidate
184
+ } catch {
185
+ service = undefined
186
+ }
187
+ if (service === undefined && !warned) {
188
+ warned = true
189
+ logger?.warn?.('capital-automation: 自选股服务不可用,个股动态按简报标签排序')
190
+ }
191
+ }
192
+ if (service === undefined) return undefined
193
+ try {
194
+ return await service.list()
195
+ } catch (error) {
196
+ if (!warned) {
197
+ warned = true
198
+ logger?.warn?.(`capital-automation: 自选股清单读取失败,个股动态按简报标签排序(${sanitizeMessage(String(error))})`)
199
+ }
200
+ return undefined
201
+ }
202
+ }
159
203
  }
160
204
 
161
205
  function authorizeFactory(ctx) {
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@v587d/capital-automation",
3
- "version": "2.21.4",
3
+ "version": "2.23.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",
@@ -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
  }
@@ -425,8 +425,9 @@ export function createRunRunner(options) {
425
425
  try {
426
426
  if (entry.finished) return
427
427
  const subagents = service(ctx, 'subagents')
428
- if (subagents?.waitForChildren !== undefined && entry.agent !== undefined) {
429
- const joined = await subagents.waitForChildren(entry.agent).catch(() => true)
428
+ const waitTree = subagents?.waitForTreeWork ?? subagents?.waitForChildren
429
+ if (typeof waitTree === 'function' && entry.agent !== undefined) {
430
+ const joined = await waitTree.call(subagents, entry.agent).catch(() => true)
430
431
  if (joined && !entry.finished && entry.cancelRequested === undefined) {
431
432
  armIdle(entry)
432
433
  return
@@ -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(),
@@ -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
+ }
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@v587d/capital-charts",
3
- "version": "2.21.4",
3
+ "version": "2.23.0",
4
4
  "description": "自动模式的图表前端组件(浏览器半边 + 序列旁路路由):由 @v587d/capital-generation 随包携带并作为 host 平面行挂载。",
5
5
  "license": "MIT",
6
6
  "type": "module",