@v587d/capital-generation 2.30.1 → 2.31.1

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 (69) hide show
  1. package/CHANGELOG.md +127 -0
  2. package/README.md +4 -4
  3. package/THIRD_PARTY_NOTICES.md +1 -0
  4. package/automation/package.json +1 -1
  5. package/automation/storage.js +4 -0
  6. package/chart-ui/package.json +1 -1
  7. package/config/client.js +1 -1
  8. package/config/package.json +1 -1
  9. package/lib/agents/messaging-policy.d.ts +23 -6
  10. package/lib/agents/messaging-policy.js +64 -9
  11. package/lib/agents/role-tool-policy.d.ts +3 -0
  12. package/lib/agents/role-tool-policy.js +15 -5
  13. package/lib/agents/selected-skills-provider.d.ts +1 -1
  14. package/lib/agents/selected-skills-provider.js +3 -1
  15. package/lib/analysis/registry.d.ts +12 -0
  16. package/lib/analysis/registry.js +76 -0
  17. package/lib/analysis/runtime.d.ts +87 -0
  18. package/lib/analysis/runtime.js +225 -0
  19. package/lib/analysis/schemas.d.ts +58 -0
  20. package/lib/analysis/schemas.js +276 -0
  21. package/lib/analysis/snapshot.d.ts +102 -0
  22. package/lib/analysis/snapshot.js +266 -0
  23. package/lib/analysis/storage.d.ts +64 -0
  24. package/lib/analysis/storage.js +96 -0
  25. package/lib/analysis/tools.d.ts +17 -0
  26. package/lib/analysis/tools.js +357 -0
  27. package/lib/analysis/types.d.ts +201 -0
  28. package/lib/analysis/types.js +44 -0
  29. package/lib/analysis/validation.d.ts +44 -0
  30. package/lib/analysis/validation.js +381 -0
  31. package/lib/analysis-entry.d.ts +10 -0
  32. package/lib/analysis-entry.js +7 -0
  33. package/lib/data-collector/store.d.ts +14 -1
  34. package/lib/data-collector/store.js +47 -1
  35. package/lib/data-contract.d.ts +3 -2
  36. package/lib/data-contract.js +18 -2
  37. package/lib/preset-ids.d.ts +5 -0
  38. package/lib/preset-ids.js +7 -1
  39. package/lib/python-runtime/errors.d.ts +7 -1
  40. package/lib/python-runtime/errors.js +9 -1
  41. package/lib/python-runtime/manager.d.ts +30 -0
  42. package/lib/python-runtime/manager.js +88 -0
  43. package/lib/python-runtime/probe.js +5 -1
  44. package/lib/selected-skills-entry.js +1 -1
  45. package/lib/web-retriever/local-fetch.d.ts +1 -1
  46. package/lib/web-retriever/local-fetch.js +1 -1
  47. package/lib/web-retriever/wind-client.d.ts +1 -1
  48. package/lib/web-retriever/wind-client.js +1 -1
  49. package/package.json +6 -1
  50. package/preset/capital-generation/README.md +5 -6
  51. package/preset/capital-generation/agent.patch.yml +54 -65
  52. package/preset/capital-generation/skills/capital-analysis-evidence/SKILL.md +99 -0
  53. package/preset/capital-generation/skills/capital-analysis-synthesis/SKILL.md +110 -0
  54. package/preset/capital-generation/skills/capital-analysis-validation/SKILL.md +96 -0
  55. package/preset/capital-generation/skills/capital-data-query/SKILL.md +1 -1
  56. package/preset/capital-generation/skills/capital-equity-research/SKILL.md +1 -1
  57. package/preset/capital-generation/skills/capital-event-impact/SKILL.md +1 -1
  58. package/preset/capital-generation/skills/capital-orchestration/SKILL.md +32 -27
  59. package/preset/capital-generation/skills/capital-portfolio-review/SKILL.md +1 -1
  60. package/preset/capital-generation/skills/capital-senior-analysis/SKILL.md +105 -0
  61. package/python/analysis/modules/financial_quality/LICENSE +27 -0
  62. package/python/analysis/modules/financial_quality/module.json +65 -0
  63. package/python/analysis/modules/financial_quality/module.py +535 -0
  64. package/python/analysis/modules/hello/LICENSE +21 -0
  65. package/python/analysis/modules/hello/module.json +46 -0
  66. package/python/analysis/modules/hello/module.py +56 -0
  67. package/python/worker.py +152 -5
  68. package/selected-skills/routing.js +5 -2
  69. package/watchlist/package.json +1 -1
@@ -0,0 +1,357 @@
1
+ import { SAFE_RESULT_CHARS } from '../data-collector/describe.js';
2
+ import { ANALYSIS_PRESET_IDS } from '../preset-ids.js';
3
+ import { authorizedSession } from '../tool-exec.js';
4
+ import { analysisModuleById, listAnalysisModules } from './registry.js';
5
+ import { ANALYSIS_ARTIFACT_SCHEMA, ARTIFACT_MAX_CHARS, CREATE_SNAPSHOT_OUTPUT, CREATE_SNAPSHOT_PARAMETERS, DESCRIBE_MODULE_OUTPUT, DESCRIBE_MODULE_PARAMETERS, HEADLINE_MAX_CHARS, LIST_MODULES_OUTPUT, LIST_MODULES_PARAMETERS, MAX_CLAIMS, MAX_SCENARIOS, READ_PROFILE_OUTPUT, READ_PROFILE_PARAMETERS, RUN_ANALYSIS_OUTPUT, RUN_ANALYSIS_PARAMETERS, STATEMENT_MAX_CHARS, SUBMIT_ANALYSIS_OUTPUT, THESIS_MAX_CHARS, } from './schemas.js';
6
+ import { analysisRuntimeFrom, runModuleOnSnapshot } from './runtime.js';
7
+ import { createSnapshot, loadSnapshot, snapshotCoverage } from './snapshot.js';
8
+ import { ARTIFACT_FILE, analysisDir, artifactRef, parseSnapshotRef, parseArtifactRef, writeFiles, } from './storage.js';
9
+ import { ANALYSIS_TOOL_NAMES, AnalysisError, } from './types.js';
10
+ import { validateAgainstSchema, validateArtifact } from './validation.js';
11
+ function render(_args, value) {
12
+ return [{ type: 'text', text: JSON.stringify(value) }];
13
+ }
14
+ // ── argument normalization ─────────────────────────────────────────────────────────────────────
15
+ function text(value, field, maxLength = 400) {
16
+ if (typeof value !== 'string' || value.trim() === '') {
17
+ throw new AnalysisError('analysis_input_invalid', `${field} 必须是非空字符串`);
18
+ }
19
+ const trimmed = value.trim();
20
+ if (trimmed.length > maxLength)
21
+ throw new AnalysisError('analysis_input_invalid', `${field} 超过 ${maxLength} 字符`);
22
+ return trimmed;
23
+ }
24
+ function optionalText(value, field, maxLength = 400) {
25
+ if (value === undefined || value === null || value === '')
26
+ return undefined;
27
+ return text(value, field, maxLength);
28
+ }
29
+ function recordOf(value) {
30
+ return value !== null && typeof value === 'object' && !Array.isArray(value) ? value : {};
31
+ }
32
+ function stringArray(value, field) {
33
+ if (value === undefined || value === null)
34
+ return [];
35
+ if (!Array.isArray(value) || value.some((item) => typeof item !== 'string')) {
36
+ throw new AnalysisError('analysis_input_invalid', `${field} 必须是字符串数组`);
37
+ }
38
+ return value;
39
+ }
40
+ function oneOf(value, allowed, field) {
41
+ if (typeof value !== 'string' || !allowed.includes(value)) {
42
+ throw new AnalysisError('analysis_input_invalid', `${field} 必须是 ${allowed.join(' / ')} 之一`);
43
+ }
44
+ return value;
45
+ }
46
+ /** Dataset/profile refs arrive as objects or bare ids; only the id is used. */
47
+ function refId(value, field) {
48
+ const raw = typeof value === 'string' ? value : recordOf(value)[field];
49
+ if (typeof raw !== 'string' || raw.trim() === '') {
50
+ throw new AnalysisError('analysis_snapshot_invalid', `${field} 缺失或为空`);
51
+ }
52
+ const id = raw.trim().split('/').at(-1) ?? '';
53
+ if (!/^[A-Za-z0-9_-]{1,128}$/u.test(id))
54
+ throw new AnalysisError('analysis_snapshot_invalid', `${field} 不合法:${raw.slice(0, 80)}`);
55
+ return id;
56
+ }
57
+ function evidenceOf(value) {
58
+ if (value === undefined || value === null)
59
+ return [];
60
+ if (!Array.isArray(value))
61
+ throw new AnalysisError('analysis_input_invalid', 'evidence 必须是数组');
62
+ return value.map((item, index) => {
63
+ const record = recordOf(item);
64
+ return {
65
+ source_id: text(record.source_id, `evidence[${index}].source_id`, 128),
66
+ kind: oneOf(record.kind, ['filing', 'news', 'research', 'user_material'], `evidence[${index}].kind`),
67
+ title: text(record.title, `evidence[${index}].title`, 300),
68
+ ...(optionalText(record.source, 'source', 200) === undefined ? {} : { source: String(record.source) }),
69
+ ...(optionalText(record.published_at, 'published_at', 64) === undefined ? {} : { published_at: String(record.published_at) }),
70
+ ...(optionalText(record.url, 'url', 2000) === undefined ? {} : { url: String(record.url) }),
71
+ ...(optionalText(record.excerpt, 'excerpt', 2000) === undefined ? {} : { excerpt: String(record.excerpt) }),
72
+ verification: oneOf(record.verification, ['verified_official', 'unverified', 'not_verified'], `evidence[${index}].verification`),
73
+ };
74
+ });
75
+ }
76
+ // ── handlers ───────────────────────────────────────────────────────────────────────────────────
77
+ function createSnapshotInput(args) {
78
+ return {
79
+ task_id: text(args.task_id, 'task_id', 120),
80
+ question: text(args.question, 'question', 2000),
81
+ ...(optionalText(args.instrument, 'instrument', 120) === undefined ? {} : { instrument: String(args.instrument) }),
82
+ purpose: oneOf(args.purpose, ['observe', 'research', 'holding_review'], 'purpose'),
83
+ ...(optionalText(args.horizon, 'horizon', 120) === undefined ? {} : { horizon: String(args.horizon) }),
84
+ depth: oneOf(args.depth, ['quick', 'standard', 'deep'], 'depth'),
85
+ as_of: text(args.as_of, 'as_of', 64),
86
+ ...(optionalText(args.data_cutoff, 'data_cutoff', 64) === undefined ? {} : { data_cutoff: String(args.data_cutoff) }),
87
+ dataset_refs: (Array.isArray(args.dataset_refs) ? args.dataset_refs : []).map((item) => ({ dataset_id: refId(item, 'dataset_id') })),
88
+ profile_refs: (Array.isArray(args.profile_refs) ? args.profile_refs : []).map((item) => ({ profile_id: refId(item, 'profile_id') })),
89
+ evidence: evidenceOf(args.evidence),
90
+ prior_analysis_refs: stringArray(args.prior_analysis_refs, 'prior_analysis_refs'),
91
+ constraints: recordOf(args.constraints),
92
+ };
93
+ }
94
+ function profileIdOf(ref) {
95
+ const raw = text(ref, 'profile_ref', 400);
96
+ const id = raw.split('/').filter(Boolean).at(-1) ?? '';
97
+ if (!/^[A-Za-z0-9_-]{1,128}$/u.test(id))
98
+ throw new AnalysisError('analysis_input_invalid', `profile_ref 不合法:${raw.slice(0, 80)}`);
99
+ return id;
100
+ }
101
+ function moduleSummary(entry) {
102
+ return {
103
+ id: entry.manifest.id,
104
+ version: entry.manifest.version,
105
+ description: entry.manifest.description,
106
+ capabilities: entry.manifest.capabilities,
107
+ applicability: entry.manifest.applicability,
108
+ limits: entry.manifest.limits,
109
+ };
110
+ }
111
+ /** Serialized size by section, so a rejected artifact says which part to cut. */
112
+ function oversizedSection(artifact) {
113
+ const sections = [
114
+ ['headline', artifact.headline],
115
+ ['thesis', artifact.thesis],
116
+ ['support_claims', artifact.support_claims],
117
+ ['counter_claims', artifact.counter_claims],
118
+ ['calculations', artifact.calculations],
119
+ ['scenarios', artifact.scenarios],
120
+ ['invalidation_conditions', artifact.invalidation_conditions],
121
+ ['limitations', artifact.limitations],
122
+ ];
123
+ const sized = sections
124
+ .map(([name, value]) => [name, JSON.stringify(value ?? null)?.length ?? 0])
125
+ .sort((a, b) => b[1] - a[1]);
126
+ return sized[0]?.[0] ?? 'artifact';
127
+ }
128
+ function artifactOf(args) {
129
+ const artifact = {
130
+ analysis_id: text(args.analysis_id, 'analysis_id', 120),
131
+ task_id: text(args.task_id, 'task_id', 120),
132
+ snapshot_id: text(args.snapshot_id, 'snapshot_id', 120),
133
+ status: oneOf(args.status, ['completed', 'partial', 'blocked'], 'status'),
134
+ evidence_level: oneOf(args.evidence_level, ['sufficient', 'limited', 'insufficient'], 'evidence_level'),
135
+ headline: typeof args.headline === 'string' ? args.headline : '',
136
+ thesis: typeof args.thesis === 'string' ? args.thesis : '',
137
+ support_claims: Array.isArray(args.support_claims) ? args.support_claims : [],
138
+ counter_claims: Array.isArray(args.counter_claims) ? args.counter_claims : [],
139
+ alternative_explanations: stringArray(args.alternative_explanations, 'alternative_explanations'),
140
+ contradictions: stringArray(args.contradictions, 'contradictions'),
141
+ calculations: Array.isArray(args.calculations) ? args.calculations : [],
142
+ scenarios: Array.isArray(args.scenarios) ? args.scenarios : [],
143
+ invalidation_conditions: stringArray(args.invalidation_conditions, 'invalidation_conditions'),
144
+ unresolved_gaps: stringArray(args.unresolved_gaps, 'unresolved_gaps'),
145
+ limitations: stringArray(args.limitations, 'limitations'),
146
+ methods_used: Array.isArray(args.methods_used) ? args.methods_used : [],
147
+ peer_exchanges: Array.isArray(args.peer_exchanges) ? args.peer_exchanges : [],
148
+ };
149
+ return artifact;
150
+ }
151
+ export function registerAnalysisTools(deps) {
152
+ const { ctx, store } = deps;
153
+ const now = deps.now ?? (() => Date.now());
154
+ const tools = ctx.get('tools');
155
+ if (!tools)
156
+ return;
157
+ const authorize = (exec, tool) => authorizedSession(ctx, exec, tool, ANALYSIS_PRESET_IDS);
158
+ const definitions = [
159
+ {
160
+ name: 'create_analysis_snapshot',
161
+ description: '冻结本次分析的输入版本:把 Dataset / profile / 证据引用连同研究问题、口径与时间点打包成不可变快照,'
162
+ + '返回 snapshot 引用与到期时间。分析前必须先建快照;快照只存引用与摘要,不包含原始数据行。',
163
+ parameters: CREATE_SNAPSHOT_PARAMETERS,
164
+ output: { schema: CREATE_SNAPSHOT_OUTPUT, render },
165
+ async execute(args, exec) {
166
+ const session = authorize(exec, 'create_analysis_snapshot');
167
+ const input = createSnapshotInput(args);
168
+ const { record, ref } = await createSnapshot({
169
+ reader: store,
170
+ writer: store,
171
+ session,
172
+ input,
173
+ ...(exec.signal === undefined ? {} : { signal: exec.signal }),
174
+ now: now(),
175
+ });
176
+ return {
177
+ analysis_snapshot_ref: ref,
178
+ analysis_id: record.analysis_id,
179
+ input_fingerprint: record.input_fingerprint,
180
+ expires_at: new Date(record.expires_at).toISOString(),
181
+ coverage: snapshotCoverage(record),
182
+ limitations: [...record.limitations],
183
+ };
184
+ },
185
+ },
186
+ {
187
+ name: 'read_profile',
188
+ description: '读取一份数据档案(profile)的有界事实:行数、列、缺失、分布摘要与时间事实。用于判断这份数据能不能支撑结论;'
189
+ + '不返回原始数据行,超预算时返回小回执与收窄提示。',
190
+ parameters: READ_PROFILE_PARAMETERS,
191
+ output: { schema: READ_PROFILE_OUTPUT, render },
192
+ async execute(args, exec) {
193
+ const session = authorize(exec, 'read_profile');
194
+ const profileId = profileIdOf(args.profile_ref);
195
+ const loaded = await store.readProfile({
196
+ session,
197
+ profile_id: profileId,
198
+ ...(exec.signal === undefined ? {} : { signal: exec.signal }),
199
+ });
200
+ const columnsOfInterest = stringArray(args.columns_of_interest, 'columns_of_interest');
201
+ const profile = loaded.profile;
202
+ const facts = columnsOfInterest.length === 0
203
+ ? profile
204
+ : Object.fromEntries(Object.entries(profile).filter(([key]) => key === 'row_count' || key === 'quality' || columnsOfInterest.includes(key)));
205
+ const factsText = JSON.stringify(facts);
206
+ if (factsText.length > SAFE_RESULT_CHARS) {
207
+ return {
208
+ profile_ref: loaded.ref.artifact_ref,
209
+ columns: [...loaded.profile.columns],
210
+ facts: { row_count: loaded.profile.row_count, quality: loaded.profile.quality },
211
+ hint: `profile 事实 ${factsText.length} 字符,超过单次回执预算 ${SAFE_RESULT_CHARS}:用 columns_of_interest 收窄后再读`,
212
+ };
213
+ }
214
+ return {
215
+ profile_ref: loaded.ref.artifact_ref,
216
+ columns: [...loaded.profile.columns],
217
+ facts,
218
+ };
219
+ },
220
+ },
221
+ {
222
+ name: 'list_analysis_modules',
223
+ description: '列出当前可用的受控分析模块:id、版本、能力、适用条件与数据要求。选模块前先看这张表,不要凭记忆假定存在某个模块。',
224
+ parameters: LIST_MODULES_PARAMETERS,
225
+ output: { schema: LIST_MODULES_OUTPUT, render },
226
+ async execute(_args, exec) {
227
+ authorize(exec, 'list_analysis_modules');
228
+ return { modules: listAnalysisModules().map((entry) => moduleSummary(entry)) };
229
+ },
230
+ },
231
+ {
232
+ name: 'describe_analysis_module',
233
+ description: '查看单个分析模块的完整输入输出契约、假设与限制。参数必须符合模块声明的输入结构,否则运行会被拒绝。',
234
+ parameters: DESCRIBE_MODULE_PARAMETERS,
235
+ output: { schema: DESCRIBE_MODULE_OUTPUT, render },
236
+ async execute(args, exec) {
237
+ authorize(exec, 'describe_analysis_module');
238
+ const moduleId = text(args.module_id, 'module_id', 64);
239
+ const entry = analysisModuleById(moduleId);
240
+ if (entry === undefined) {
241
+ throw new AnalysisError('analysis_module_not_found', `没有登记名为 ${moduleId} 的分析模块;先调用 list_analysis_modules 看可用清单`);
242
+ }
243
+ return {
244
+ module_id: entry.manifest.id,
245
+ version: entry.manifest.version,
246
+ input_schema: entry.manifest.input_schema,
247
+ output_schema: entry.manifest.output_schema,
248
+ required_fields: entry.manifest.required_fields,
249
+ assumptions: entry.manifest.assumptions,
250
+ capabilities: entry.manifest.capabilities,
251
+ limits: entry.manifest.limits,
252
+ };
253
+ },
254
+ },
255
+ {
256
+ name: 'run_analysis',
257
+ description: '在快照上运行一个分析模块,返回指标、假设、数据缺口与校验结论。同一快照内输入与参数不变时会复用已有结果;'
258
+ + '模块未声明的能力(如读数据集)会在运行前被拒绝。',
259
+ parameters: RUN_ANALYSIS_PARAMETERS,
260
+ output: { schema: RUN_ANALYSIS_OUTPUT, render },
261
+ async execute(args, exec) {
262
+ const session = authorize(exec, 'run_analysis');
263
+ const analysisId = parseSnapshotRef(args.analysis_snapshot_ref);
264
+ const snapshot = await loadSnapshot({
265
+ reader: store,
266
+ session,
267
+ analysisId,
268
+ ...(exec.signal === undefined ? {} : { signal: exec.signal }),
269
+ now: now(),
270
+ });
271
+ const moduleId = text(args.module_id, 'module_id', 64);
272
+ const module = analysisModuleById(moduleId);
273
+ if (module === undefined) {
274
+ throw new AnalysisError('analysis_module_not_found', `没有登记名为 ${moduleId} 的分析模块;先调用 list_analysis_modules 看可用清单`);
275
+ }
276
+ const outcome = await runModuleOnSnapshot({
277
+ writer: store,
278
+ runtime: analysisRuntimeFrom(ctx),
279
+ session,
280
+ snapshot,
281
+ module,
282
+ params: recordOf(args.params),
283
+ ...(exec.signal === undefined ? {} : { signal: exec.signal }),
284
+ now: now(),
285
+ });
286
+ return { ...outcome };
287
+ },
288
+ },
289
+ {
290
+ name: 'submit_analysis',
291
+ description: '提交最终分析产物:结论、正反论据、替代解释、失效条件与数字锚点。宿主会校验结论里的每个数字能否追到锚点;'
292
+ + '缺失效条件、引用不存在或数字无来源会被拒绝,警告级问题会让产物降级为 partial。',
293
+ parameters: ANALYSIS_ARTIFACT_SCHEMA,
294
+ output: { schema: SUBMIT_ANALYSIS_OUTPUT, render },
295
+ async execute(args, exec) {
296
+ const session = authorize(exec, 'submit_analysis');
297
+ const artifact = artifactOf(args);
298
+ const serialized = JSON.stringify(artifact);
299
+ if (serialized.length > ARTIFACT_MAX_CHARS) {
300
+ throw new AnalysisError('analysis_result_too_large', `产物 ${serialized.length} 字符,超过 ${ARTIFACT_MAX_CHARS} 上限;先压缩 ${oversizedSection(artifact)} 再重发(上限:headline ${HEADLINE_MAX_CHARS} / thesis ${THESIS_MAX_CHARS} / 单条 statement ${STATEMENT_MAX_CHARS} / claims ${MAX_CLAIMS} / scenarios ${MAX_SCENARIOS})`);
301
+ }
302
+ // §11.4 Tier 1 covers "schema mismatch" too: the artifact schema is the contract the model
303
+ // reads, so an undeclared field or an over-long claim list must be rejected here, not ignored.
304
+ const schemaIssues = validateAgainstSchema(artifact, ANALYSIS_ARTIFACT_SCHEMA);
305
+ if (schemaIssues.length > 0) {
306
+ throw new AnalysisError('analysis_validation_failed', `产物不符合 artifact schema(${schemaIssues.length} 条):${schemaIssues.slice(0, 6).join(';')}`);
307
+ }
308
+ const analysisId = parseArtifactRef(`analysis_artifact:${artifact.analysis_id}`);
309
+ if (artifact.snapshot_id !== artifact.analysis_id) {
310
+ throw new AnalysisError('analysis_snapshot_invalid', 'snapshot_id 必须等于建快照时返回的 analysis_id');
311
+ }
312
+ const snapshot = await loadSnapshot({
313
+ reader: store,
314
+ session,
315
+ analysisId,
316
+ ...(exec.signal === undefined ? {} : { signal: exec.signal }),
317
+ now: now(),
318
+ });
319
+ const validation = validateArtifact(artifact, snapshot);
320
+ if (validation.tier1.length > 0) {
321
+ // The reserved code exists for exactly this budget (§5.6-2); a generic validation error
322
+ // would hide that the peer loop is the problem.
323
+ const budget = validation.tier1.find((issue) => issue.code === 'peer_budget_exhausted');
324
+ if (budget !== undefined)
325
+ throw new AnalysisError('analysis_peer_budget_exhausted', budget.detail);
326
+ throw new AnalysisError('analysis_validation_failed', `产物未通过硬校验(${validation.tier1.length} 条):${validation.tier1.slice(0, 6).map((issue) => `${issue.code} ${issue.detail}`).join(';')}`);
327
+ }
328
+ const downgraded = validation.tier2.length > 0 && artifact.status === 'completed' ? 'partial' : artifact.status;
329
+ const persisted = {
330
+ ...artifact,
331
+ status: downgraded,
332
+ validation: {
333
+ status: validation.tier2.length > 0 ? 'warning' : 'pass',
334
+ issues: [...validation.tier1, ...validation.tier2, ...validation.tier3],
335
+ },
336
+ };
337
+ await writeFiles(store, session, analysisDir(analysisId), [{
338
+ name: ARTIFACT_FILE,
339
+ content: JSON.stringify(persisted),
340
+ }], {
341
+ ...(exec.signal === undefined ? {} : { signal: exec.signal }),
342
+ overwrite: true,
343
+ what: '写入 artifact.json 失败',
344
+ });
345
+ return {
346
+ analysis_ref: artifactRef(analysisId),
347
+ status: 'accepted',
348
+ validation: persisted.validation,
349
+ };
350
+ },
351
+ },
352
+ ];
353
+ for (const definition of definitions) {
354
+ ctx.effect(() => tools.register(definition), `capital-generation.tool(${definition.name})`);
355
+ }
356
+ }
357
+ export { ANALYSIS_TOOL_NAMES };
@@ -0,0 +1,201 @@
1
+ /**
2
+ * Contracts shared by the `tools/analysis` family, the host validation layer and the Python module
3
+ * protocol. Phase 0 fixes the shapes only: nothing here reads, writes or executes yet.
4
+ *
5
+ * Protocol versions are literals, not configuration: a module built for v1 must not be run under a
6
+ * v2 request shape, and the mismatch has to fail loudly rather than be coerced.
7
+ */
8
+ export declare const ANALYSIS_PROTOCOL = "capital.analysis/v1";
9
+ export declare const AGENT_MESSAGE_PROTOCOL = "capital.agent.message/v1";
10
+ /** Stable error codes (`docs/dev/senior-analysis.md` §1.9). Adding one is a protocol change. */
11
+ export declare const ANALYSIS_ERROR_CODES: readonly ["analysis_snapshot_invalid", "analysis_snapshot_expired", "analysis_ref_unauthorized", "analysis_module_not_found", "analysis_module_not_applicable", "analysis_input_invalid", "analysis_runtime_not_ready", "analysis_timeout", "analysis_cancelled", "analysis_output_invalid", "analysis_result_too_large", "analysis_validation_failed", "analysis_peer_budget_exhausted", "analysis_not_implemented"];
12
+ export type AnalysisErrorCode = (typeof ANALYSIS_ERROR_CODES)[number];
13
+ /** One tool failure. The code travels in the message so a model can act on it without a parser. */
14
+ export declare class AnalysisError extends Error {
15
+ readonly code: AnalysisErrorCode;
16
+ constructor(code: AnalysisErrorCode, message: string);
17
+ }
18
+ export type AnalysisStatus = 'completed' | 'partial' | 'blocked' | 'failed';
19
+ export type ArtifactStatus = Exclude<AnalysisStatus, 'failed'>;
20
+ export type EvidenceLevel = 'sufficient' | 'limited' | 'insufficient';
21
+ export type ValidationStatus = 'pass' | 'warning';
22
+ export type EvidenceKind = 'filing' | 'news' | 'research' | 'user_material';
23
+ export type EvidenceVerification = 'verified_official' | 'unverified' | 'not_verified';
24
+ export type ClaimType = 'fact' | 'observation' | 'inference' | 'hypothesis';
25
+ export type Confidence = 'low' | 'medium' | 'high';
26
+ export type AnchorSourceKind = 'dataset' | 'profile' | 'evidence' | 'computation';
27
+ /** Bounded structured evidence item; the full document body stays with the retriever/OCR layer. */
28
+ export interface EvidenceItem {
29
+ readonly source_id: string;
30
+ readonly kind: EvidenceKind;
31
+ readonly title: string;
32
+ readonly source?: string;
33
+ readonly published_at?: string;
34
+ readonly url?: string;
35
+ readonly excerpt?: string;
36
+ readonly verification: EvidenceVerification;
37
+ }
38
+ /** Reference to a stored Dataset: the senior analyst never receives its rows. */
39
+ export interface DatasetRefLike {
40
+ readonly dataset_id: string;
41
+ readonly params_digest?: string;
42
+ readonly captured_at?: number;
43
+ }
44
+ export interface ProfileRefLike {
45
+ readonly profile_id: string;
46
+ readonly created_at?: number;
47
+ }
48
+ /** Frozen analysis input. Stores references and digests only — never raw rows. */
49
+ export interface AnalysisSnapshot {
50
+ readonly analysis_id: string;
51
+ readonly task_id: string;
52
+ readonly question: string;
53
+ readonly instrument?: string;
54
+ readonly purpose: 'observe' | 'research' | 'holding_review';
55
+ readonly horizon?: string;
56
+ readonly depth: 'quick' | 'standard' | 'deep';
57
+ readonly as_of: string;
58
+ readonly data_cutoff?: string;
59
+ readonly dataset_refs: readonly DatasetRefLike[];
60
+ readonly profile_refs: readonly ProfileRefLike[];
61
+ readonly evidence: readonly EvidenceItem[];
62
+ readonly prior_analysis_refs: readonly string[];
63
+ readonly constraints: Readonly<Record<string, unknown>>;
64
+ readonly input_fingerprint: string;
65
+ readonly created_at: number;
66
+ /** `min(created_at + 7d, earliest input retention)`; past this the snapshot must not be run. */
67
+ readonly expires_at: number;
68
+ readonly limitations: readonly string[];
69
+ }
70
+ export interface NumberAnchor {
71
+ readonly value: number;
72
+ readonly unit: string;
73
+ readonly period?: string;
74
+ readonly source: {
75
+ readonly kind: AnchorSourceKind;
76
+ readonly ref: string;
77
+ };
78
+ readonly precision?: number;
79
+ }
80
+ export interface Calculation {
81
+ readonly calculation_id: string;
82
+ readonly module_id: string;
83
+ readonly module_version: string;
84
+ readonly metric: string;
85
+ readonly value: number;
86
+ readonly unit: string;
87
+ readonly params_digest?: string;
88
+ }
89
+ export interface Claim {
90
+ readonly claim_id: string;
91
+ readonly type: ClaimType;
92
+ readonly statement: string;
93
+ readonly evidence_refs: readonly string[];
94
+ readonly number_anchors: readonly NumberAnchor[];
95
+ readonly confidence: Confidence;
96
+ readonly confidence_basis?: string;
97
+ readonly falsifier?: string;
98
+ readonly limitations?: readonly string[];
99
+ }
100
+ export interface PeerExchange {
101
+ readonly peer: string;
102
+ readonly type: string;
103
+ readonly request_id: string;
104
+ readonly answered: boolean;
105
+ }
106
+ export interface ValidationIssue {
107
+ readonly code: string;
108
+ readonly severity: 'error' | 'warning' | 'notice';
109
+ readonly field?: string;
110
+ readonly detail: string;
111
+ }
112
+ /** What the senior analyst submits. `validation` is written by the host, not by the model. */
113
+ export interface AnalysisArtifact {
114
+ readonly analysis_id: string;
115
+ readonly task_id: string;
116
+ readonly snapshot_id: string;
117
+ readonly status: ArtifactStatus;
118
+ readonly evidence_level: EvidenceLevel;
119
+ readonly headline: string;
120
+ readonly thesis: string;
121
+ readonly support_claims: readonly Claim[];
122
+ readonly counter_claims: readonly Claim[];
123
+ readonly alternative_explanations: readonly string[];
124
+ readonly contradictions: readonly string[];
125
+ readonly calculations: readonly Calculation[];
126
+ readonly scenarios: readonly unknown[];
127
+ readonly invalidation_conditions: readonly string[];
128
+ readonly unresolved_gaps: readonly string[];
129
+ readonly limitations: readonly string[];
130
+ readonly methods_used: readonly {
131
+ readonly module_id: string;
132
+ readonly module_version: string;
133
+ }[];
134
+ readonly peer_exchanges: readonly PeerExchange[];
135
+ readonly validation?: {
136
+ readonly status: ValidationStatus;
137
+ readonly issues: readonly ValidationIssue[];
138
+ };
139
+ }
140
+ /** `roles` uses the semantic key `senior_analyst`, never the preset id. */
141
+ export interface ModuleManifest {
142
+ readonly id: string;
143
+ readonly version: string;
144
+ readonly entrypoint: string;
145
+ readonly runtime: 'python';
146
+ readonly description: string;
147
+ readonly roles: readonly string[];
148
+ /** Enforced whitelist: an undeclared capability makes the module not applicable. */
149
+ readonly capabilities: readonly ('dataset.read' | 'profile.read' | 'evidence.read')[];
150
+ readonly required_fields: readonly string[];
151
+ readonly input_schema: Readonly<Record<string, unknown>>;
152
+ readonly output_schema: Readonly<Record<string, unknown>>;
153
+ readonly assumptions: readonly string[];
154
+ readonly applicability: readonly string[];
155
+ readonly limits: ModuleLimits;
156
+ readonly provenance: ModuleProvenance;
157
+ }
158
+ export interface ModuleLimits {
159
+ readonly timeout_ms: number;
160
+ readonly max_input_rows: number;
161
+ readonly max_output_bytes: number;
162
+ readonly max_log_bytes: number;
163
+ }
164
+ export interface ModuleProvenance {
165
+ readonly source_type: 'original' | 'adapted';
166
+ readonly repository?: string;
167
+ readonly commit?: string;
168
+ readonly license: string;
169
+ }
170
+ export interface ModuleRequest {
171
+ readonly protocol: typeof ANALYSIS_PROTOCOL;
172
+ readonly task_id: string;
173
+ readonly analysis_id: string;
174
+ readonly module_run_id: string;
175
+ readonly snapshot_id: string;
176
+ readonly as_of: string;
177
+ readonly inputs: {
178
+ readonly datasets: readonly DatasetRefLike[];
179
+ readonly profiles: readonly ProfileRefLike[];
180
+ readonly evidence: readonly EvidenceItem[];
181
+ };
182
+ readonly params: Readonly<Record<string, unknown>>;
183
+ }
184
+ export interface ModuleResult {
185
+ readonly status: AnalysisStatus;
186
+ readonly summary: string;
187
+ readonly metrics: Readonly<Record<string, number | string | null>>;
188
+ readonly claims: readonly Claim[];
189
+ readonly assumptions: readonly string[];
190
+ readonly methodology_log: readonly string[];
191
+ readonly sensitivity: Readonly<Record<string, unknown>>;
192
+ readonly limitations: readonly string[];
193
+ readonly data_gaps: readonly string[];
194
+ readonly outputs: readonly {
195
+ readonly name: string;
196
+ readonly ref: string;
197
+ }[];
198
+ }
199
+ /** The six model-facing tools of the `tools/analysis` family, in registration order. */
200
+ export declare const ANALYSIS_TOOL_NAMES: readonly ["create_analysis_snapshot", "read_profile", "list_analysis_modules", "describe_analysis_module", "run_analysis", "submit_analysis"];
201
+ export type AnalysisToolName = (typeof ANALYSIS_TOOL_NAMES)[number];
@@ -0,0 +1,44 @@
1
+ /**
2
+ * Contracts shared by the `tools/analysis` family, the host validation layer and the Python module
3
+ * protocol. Phase 0 fixes the shapes only: nothing here reads, writes or executes yet.
4
+ *
5
+ * Protocol versions are literals, not configuration: a module built for v1 must not be run under a
6
+ * v2 request shape, and the mismatch has to fail loudly rather than be coerced.
7
+ */
8
+ export const ANALYSIS_PROTOCOL = 'capital.analysis/v1';
9
+ export const AGENT_MESSAGE_PROTOCOL = 'capital.agent.message/v1';
10
+ /** Stable error codes (`docs/dev/senior-analysis.md` §1.9). Adding one is a protocol change. */
11
+ export const ANALYSIS_ERROR_CODES = [
12
+ 'analysis_snapshot_invalid',
13
+ 'analysis_snapshot_expired',
14
+ 'analysis_ref_unauthorized',
15
+ 'analysis_module_not_found',
16
+ 'analysis_module_not_applicable',
17
+ 'analysis_input_invalid',
18
+ 'analysis_runtime_not_ready',
19
+ 'analysis_timeout',
20
+ 'analysis_cancelled',
21
+ 'analysis_output_invalid',
22
+ 'analysis_result_too_large',
23
+ 'analysis_validation_failed',
24
+ 'analysis_peer_budget_exhausted',
25
+ 'analysis_not_implemented',
26
+ ];
27
+ /** One tool failure. The code travels in the message so a model can act on it without a parser. */
28
+ export class AnalysisError extends Error {
29
+ code;
30
+ constructor(code, message) {
31
+ super(`${code}: ${message}`);
32
+ this.name = 'AnalysisError';
33
+ this.code = code;
34
+ }
35
+ }
36
+ /** The six model-facing tools of the `tools/analysis` family, in registration order. */
37
+ export const ANALYSIS_TOOL_NAMES = [
38
+ 'create_analysis_snapshot',
39
+ 'read_profile',
40
+ 'list_analysis_modules',
41
+ 'describe_analysis_module',
42
+ 'run_analysis',
43
+ 'submit_analysis',
44
+ ];
@@ -0,0 +1,44 @@
1
+ /**
2
+ * Host-side validation for the analysis protocol.
3
+ *
4
+ * Two jobs, deliberately separate:
5
+ * - `validateModuleResult`: the worker's output must match the manifest's `output_schema` and be
6
+ * lossless JSON. A module that returns `NaN` would poison every downstream number.
7
+ * - `validateArtifact`: the submitted artifact must be traceable — conclusion numbers need anchors,
8
+ * refs must exist, and the hard rules of the artifact contract must hold.
9
+ *
10
+ * Number traceability only covers numbers it can extract. It does NOT prove the prose is unembellished;
11
+ * do not describe it as such.
12
+ */
13
+ import type { AnalysisArtifact, AnalysisSnapshot, ModuleManifest, ValidationIssue } from './types.js';
14
+ type Json = Record<string, unknown>;
15
+ /** Subset of JSON Schema used by the protocol: types, properties, required, items, enum, bounds. */
16
+ export declare function validateAgainstSchema(value: unknown, schema: Json | undefined, path?: string): string[];
17
+ /** Lossless JSON: `undefined`, `NaN`, `Infinity` and array holes must not cross the boundary. */
18
+ export declare function losslessIssues(value: unknown, path?: string): string[];
19
+ export interface ModuleResultValidation {
20
+ readonly ok: boolean;
21
+ readonly issues: readonly ValidationIssue[];
22
+ readonly result: Record<string, unknown> | undefined;
23
+ }
24
+ /** Validate the worker's result object: lossless, then the manifest's declared output schema. */
25
+ export declare function validateModuleResult(value: unknown, manifest: ModuleManifest): ModuleResultValidation;
26
+ export interface ArtifactValidation {
27
+ readonly tier1: readonly ValidationIssue[];
28
+ readonly tier2: readonly ValidationIssue[];
29
+ readonly tier3: readonly ValidationIssue[];
30
+ }
31
+ interface NumberToken {
32
+ readonly text: string;
33
+ readonly value: number;
34
+ readonly percent: boolean;
35
+ readonly start: number;
36
+ }
37
+ /** Numeric tokens with just enough context to honour the exemption set. */
38
+ export declare function numberTokens(text: string): NumberToken[];
39
+ /**
40
+ * Artifact validation in the three tiers of the design (Tier 1 rejects, Tier 2 downgrades to
41
+ * `partial`, Tier 3 is advisory). Returns issues; persistence is the caller's decision.
42
+ */
43
+ export declare function validateArtifact(artifact: AnalysisArtifact, snapshot: AnalysisSnapshot): ArtifactValidation;
44
+ export {};