@v587d/capital-generation 2.19.3 → 2.20.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.
@@ -36,6 +36,7 @@ export const MAX_RUNS_PER_TASK = 200
36
36
  export const MAX_RUNS_PER_PROFILE = 2_000
37
37
  export const MAX_NOTIFICATIONS_PER_PROFILE = 200
38
38
  export const MAX_TODO_ACKS_PER_PROFILE = 500
39
+ export const MAX_TODO_WATCHES_PER_PROFILE = 600
39
40
  export const MAX_ASKS_PER_PROFILE = 400
40
41
  export const MAX_ASK_QUESTION_CHARS = 500
41
42
  export const MAX_ASK_PREVIEW_CHARS = 160
@@ -10,6 +10,7 @@ import { join } from 'node:path'
10
10
  import { createRunRunner, buildRunPrompt, sessionTitleOf } from './runner.js'
11
11
  import { createBriefService } from './brief.js'
12
12
  import { createBoardService } from './board.js'
13
+ import { createTodoWatchService } from './watch.js'
13
14
  import { createAskService } from './ask.js'
14
15
  import { createScheduler } from './scheduler.js'
15
16
  import { createAutomationService, AutomationError } from './service.js'
@@ -91,18 +92,28 @@ export function createAutomationRuntime(options) {
91
92
  now,
92
93
  logger,
93
94
  })
94
- briefs = createBriefService({
95
- ctx,
95
+ const boardService = createBoardService({
96
96
  store,
97
97
  scheduler,
98
+ asks,
99
+ now,
100
+ })
101
+ const watches = createTodoWatchService({
102
+ ctx,
103
+ store,
104
+ board: boardService,
98
105
  now,
99
106
  logger,
107
+ getSettings,
108
+ isOwner: () => scheduler.status().state === 'active',
100
109
  })
101
- const boardService = createBoardService({
110
+ briefs = createBriefService({
111
+ ctx,
102
112
  store,
103
113
  scheduler,
104
- asks,
105
114
  now,
115
+ logger,
116
+ onBriefReady: (payload) => watches.onBriefReady(payload),
106
117
  })
107
118
  const service = createAutomationService({
108
119
  store,
@@ -124,7 +135,7 @@ export function createAutomationRuntime(options) {
124
135
  installAutomationPolicy({ ctx: toolsCtx, runner, logger })
125
136
  })
126
137
  }
127
- return { store, runner, scheduler, briefs, asks, service, calendar, workspaces, profile: { displayName, runDir, ownerDir } }
138
+ return { store, runner, scheduler, briefs, watches, asks, service, calendar, workspaces, profile: { displayName, runDir, ownerDir } }
128
139
  }
129
140
 
130
141
  function authorizeFactory(ctx) {
@@ -187,6 +198,7 @@ export function apply(ctx) {
187
198
  created.scheduler.start()
188
199
  .then(() => {
189
200
  created.briefs?.start()
201
+ created.watches?.start()
190
202
  logger?.info?.(`capital-automation: scheduler ${created.scheduler.status().state}`)
191
203
  })
192
204
  .catch((error) => logger?.error?.(`capital-automation: scheduler 启动失败:${String(error)}`))
@@ -195,6 +207,7 @@ export function apply(ctx) {
195
207
  activeService = undefined
196
208
  }
197
209
  await created.briefs?.stop?.()
210
+ created.watches?.stop?.()
198
211
  await created.scheduler.stop().catch(() => {})
199
212
  created.calendar.dispose?.()
200
213
  await created.runner.dispose?.()
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@v587d/capital-automation",
3
- "version": "2.19.3",
3
+ "version": "2.20.0",
4
4
  "description": "CapGen 投研自动化:独立 host bundle(固定 capital_automation 域、单 scheduler owner、/capital-automation 路由与浏览器页面)。",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -41,6 +41,7 @@
41
41
  "runner.js",
42
42
  "brief.js",
43
43
  "board.js",
44
+ "watch.js",
44
45
  "ask.js",
45
46
  "scheduler.js",
46
47
  "workspaces.js",
@@ -240,6 +240,11 @@ async function dispatch({ req, method, suffix, url, service, requestId }) {
240
240
  if (askCreate !== null && method === 'POST') {
241
241
  return { body: await service.askBrief(decodeId(askCreate[1]), await readBody(req)), status: 202 }
242
242
  }
243
+ const askHistory = /^\/board\/briefs\/([^/]+)\/asks$/.exec(suffix)
244
+ if (askHistory !== null) {
245
+ if (method !== 'GET') throw new AutomationError('method_not_allowed', '只支持 GET。', 405)
246
+ return { body: await service.askHistory(decodeId(askHistory[1])) }
247
+ }
243
248
  const askAnswer = /^\/board\/asks\/([^/]+)\/answer$/.exec(suffix)
244
249
  if (askAnswer !== null) {
245
250
  if (method !== 'GET') throw new AutomationError('method_not_allowed', '只支持 GET。', 405)
@@ -271,11 +271,21 @@ export const NotificationSchema = z.strictObject({
271
271
  schemaVersion: z.literal(1),
272
272
  id: z.string().min(1).max(80),
273
273
  profileKey: z.string().min(1).max(80),
274
- kind: z.enum(['run_failed', 'run_timeout', 'run_succeeded', 'scheduler_standby', 'calendar_unavailable', 'skipped']),
274
+ kind: z.enum([
275
+ 'run_failed',
276
+ 'run_timeout',
277
+ 'run_succeeded',
278
+ 'scheduler_standby',
279
+ 'calendar_unavailable',
280
+ 'skipped',
281
+ 'todo_triggered',
282
+ 'todo_needs_human',
283
+ ]),
275
284
  title: z.string().min(1).max(120),
276
285
  message: z.string().max(MAX_ERROR_MESSAGE_CHARS),
277
286
  runId: z.string().min(1).max(80).optional(),
278
287
  taskId: z.string().min(1).max(80).optional(),
288
+ todoId: z.string().min(1).max(200).optional(),
279
289
  createdAt: isoInstant,
280
290
  readAt: isoInstant.optional(),
281
291
  })
@@ -352,6 +362,41 @@ export const TodoAckSchema = z.strictObject({
352
362
  confirmedAt: isoInstant,
353
363
  })
354
364
 
365
+ /** Derived tracking state for one TODO item; briefs and acks stay the source of truth. */
366
+ export const TodoWatchSchema = z.strictObject({
367
+ schemaVersion: z.literal(1),
368
+ id: z.string().min(1).max(80),
369
+ profileKey: z.string().min(1).max(80),
370
+ todoId: z.string().min(1).max(200),
371
+ kind: z.enum(['confirm', 'verify']),
372
+ status: z.enum(['watching', 'triggered', 'needs_human', 'resolved', 'expired']),
373
+ resolvedFrom: z.enum(['watching', 'triggered', 'needs_human', 'expired']).optional(),
374
+ title: z.string().min(1).max(40),
375
+ detail: z.string().max(120).optional(),
376
+ symbol: z.string().max(20).optional(),
377
+ trigger: z.string().max(80).optional(),
378
+ dueAt: z.string().refine(isCalendarDate, { message: 'must be a valid YYYY-MM-DD date' }).optional(),
379
+ firstSeenAt: isoInstant,
380
+ lastSeenAt: isoInstant,
381
+ checkedAt: isoInstant.optional(),
382
+ verdict: z.enum(['triggered', 'not_triggered', 'insufficient']).optional(),
383
+ evidence: z.string().max(300).optional(),
384
+ handoffReason: z.string().max(160).optional(),
385
+ evidenceRunId: z.string().min(1).max(80).optional(),
386
+ evidenceSessionId: z.string().min(1).max(120).optional(),
387
+ notifiedAt: isoInstant.optional(),
388
+ notifiedStatus: z.enum(['triggered', 'needs_human']).optional(),
389
+ createdAt: isoInstant,
390
+ updatedAt: isoInstant,
391
+ }).superRefine((watch, ctx) => {
392
+ if (watch.status === 'triggered' && watch.evidence === undefined) {
393
+ ctx.addIssue({ code: 'custom', path: ['evidence'], message: 'triggered watch requires evidence' })
394
+ }
395
+ if (watch.status === 'needs_human' && watch.handoffReason === undefined) {
396
+ ctx.addIssue({ code: 'custom', path: ['handoffReason'], message: 'needs_human watch requires handoffReason' })
397
+ }
398
+ })
399
+
355
400
  /**
356
401
  * One board follow-up. The question and its first finished turn live here; the Session remains
357
402
  * the full transcript. `baselineSeq` is the log cursor before the prompt, so a later lazy read
@@ -439,6 +439,17 @@ export function createAutomationService(options) {
439
439
  }
440
440
  }
441
441
 
442
+ async function askHistory(runId) {
443
+ if (asks === undefined || typeof asks.history !== 'function') {
444
+ throw new AutomationError('ask_unavailable', '追问服务暂时不可用。', 503)
445
+ }
446
+ try {
447
+ return { asks: await asks.history(runId) }
448
+ } catch (error) {
449
+ mapAskError(error)
450
+ }
451
+ }
452
+
442
453
  async function askAnswer(askId) {
443
454
  if (asks === undefined || typeof asks.answer !== 'function') {
444
455
  throw new AutomationError('ask_unavailable', '追问服务暂时不可用。', 503)
@@ -514,6 +525,7 @@ export function createAutomationService(options) {
514
525
  retryBrief,
515
526
  askBrief,
516
527
  askStatus,
528
+ askHistory,
517
529
  askAnswer,
518
530
  listNotifications,
519
531
  markNotificationsRead,
@@ -17,6 +17,7 @@ import {
17
17
  TaskOverridesSchema,
18
18
  TaskRecordSchema,
19
19
  TodoAckSchema,
20
+ TodoWatchSchema,
20
21
  isActiveRun,
21
22
  parseStrict,
22
23
  resolveTaskRecord,
@@ -31,6 +32,7 @@ import {
31
32
  MAX_RUNS_PER_PROFILE,
32
33
  MAX_RUNS_PER_TASK,
33
34
  MAX_TODO_ACKS_PER_PROFILE,
35
+ MAX_TODO_WATCHES_PER_PROFILE,
34
36
  SETTLED_RUN_STATUSES,
35
37
  } from './defaults.js'
36
38
  import { canonicalTrigger, formatInZone, nextOccurrence } from './time.js'
@@ -53,6 +55,7 @@ export const domainSpec = {
53
55
  meta: { valueSchema: OwnerRecordSchema },
54
56
  briefs: { valueSchema: TaskBriefSchema },
55
57
  todo_acks: { valueSchema: TodoAckSchema },
58
+ todo_watches: { valueSchema: TodoWatchSchema },
56
59
  asks: { valueSchema: AskRecordSchema },
57
60
  },
58
61
  }
@@ -203,6 +206,7 @@ export function createAutomationStore(options) {
203
206
  meta: domain.table('meta'),
204
207
  briefs: domain.table('briefs'),
205
208
  todoAcks: domain.table('todo_acks'),
209
+ todoWatches: domain.table('todo_watches'),
206
210
  asks: domain.table('asks'),
207
211
  }
208
212
  })()
@@ -655,6 +659,7 @@ export function createAutomationStore(options) {
655
659
  message: input.message,
656
660
  ...(input.runId === undefined ? {} : { runId: input.runId }),
657
661
  ...(input.taskId === undefined ? {} : { taskId: input.taskId }),
662
+ ...(input.todoId === undefined ? {} : { todoId: input.todoId }),
658
663
  createdAt: iso(now()),
659
664
  }, 'notification')
660
665
  await tables.notifications.put(record.id, record)
@@ -850,6 +855,18 @@ export function createAutomationStore(options) {
850
855
  return result
851
856
  }
852
857
 
858
+ async function listAsksForRun(runId) {
859
+ const tables = await ensure()
860
+ const records = []
861
+ for (const [, record] of tables.asks.entries()) {
862
+ if (ownAsk(record) && record.runId === runId) records.push(record)
863
+ }
864
+ records.sort((left, right) =>
865
+ String(left.createdAt).localeCompare(String(right.createdAt))
866
+ || String(left.id).localeCompare(String(right.id)))
867
+ return records
868
+ }
869
+
853
870
  async function updateAsk(id, patch) {
854
871
  const tables = await ensure()
855
872
  const current = tables.asks.get(id)
@@ -904,6 +921,35 @@ export function createAutomationStore(options) {
904
921
  return record
905
922
  }
906
923
 
924
+ async function listTodoWatches() {
925
+ const tables = await ensure()
926
+ const records = []
927
+ for (const [, record] of tables.todoWatches.entries()) {
928
+ if (record.profileKey === profileKey) records.push(record)
929
+ }
930
+ return records
931
+ }
932
+
933
+ async function putTodoWatch(record) {
934
+ const tables = await ensure()
935
+ const next = parseStrict(TodoWatchSchema, { ...record, profileKey }, 'todo watch')
936
+ await tables.todoWatches.put(next.id, next)
937
+ await retainTodoWatches(tables)
938
+ return next
939
+ }
940
+
941
+ async function retainTodoWatches(tables) {
942
+ const records = []
943
+ for (const [key, record] of tables.todoWatches.entries()) {
944
+ if (record.profileKey === profileKey) records.push({ key, record })
945
+ }
946
+ if (records.length <= MAX_TODO_WATCHES_PER_PROFILE) return
947
+ records.sort((left, right) =>
948
+ right.record.updatedAt.localeCompare(left.record.updatedAt)
949
+ || right.key.localeCompare(left.key))
950
+ for (const entry of records.slice(MAX_TODO_WATCHES_PER_PROFILE)) await tables.todoWatches.delete(entry.key)
951
+ }
952
+
907
953
  async function updateBrief(runId, patch) {
908
954
  const tables = await ensure()
909
955
  const current = tables.briefs.get(runId)
@@ -1109,10 +1155,13 @@ export function createAutomationStore(options) {
1109
1155
  getAsk,
1110
1156
  pendingAskForRun,
1111
1157
  latestAsksForRuns,
1158
+ listAsksForRun,
1112
1159
  updateAsk,
1113
1160
  deleteAsk,
1114
1161
  listTodoAcks,
1115
1162
  confirmTodo,
1163
+ listTodoWatches,
1164
+ putTodoWatch,
1116
1165
  updateBrief,
1117
1166
  deleteBrief,
1118
1167
  publicBrief,