@v587d/capital-generation 2.30.1 → 2.31.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 (68) hide show
  1. package/CHANGELOG.md +79 -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 +1 -1
  10. package/lib/agents/role-tool-policy.d.ts +3 -0
  11. package/lib/agents/role-tool-policy.js +12 -2
  12. package/lib/agents/selected-skills-provider.d.ts +1 -1
  13. package/lib/agents/selected-skills-provider.js +3 -1
  14. package/lib/analysis/registry.d.ts +12 -0
  15. package/lib/analysis/registry.js +76 -0
  16. package/lib/analysis/runtime.d.ts +87 -0
  17. package/lib/analysis/runtime.js +225 -0
  18. package/lib/analysis/schemas.d.ts +52 -0
  19. package/lib/analysis/schemas.js +270 -0
  20. package/lib/analysis/snapshot.d.ts +102 -0
  21. package/lib/analysis/snapshot.js +266 -0
  22. package/lib/analysis/storage.d.ts +64 -0
  23. package/lib/analysis/storage.js +96 -0
  24. package/lib/analysis/tools.d.ts +17 -0
  25. package/lib/analysis/tools.js +352 -0
  26. package/lib/analysis/types.d.ts +201 -0
  27. package/lib/analysis/types.js +44 -0
  28. package/lib/analysis/validation.d.ts +44 -0
  29. package/lib/analysis/validation.js +338 -0
  30. package/lib/analysis-entry.d.ts +10 -0
  31. package/lib/analysis-entry.js +7 -0
  32. package/lib/data-collector/store.d.ts +14 -1
  33. package/lib/data-collector/store.js +44 -0
  34. package/lib/data-contract.d.ts +3 -2
  35. package/lib/data-contract.js +18 -2
  36. package/lib/preset-ids.d.ts +5 -0
  37. package/lib/preset-ids.js +7 -1
  38. package/lib/python-runtime/errors.d.ts +7 -1
  39. package/lib/python-runtime/errors.js +9 -1
  40. package/lib/python-runtime/manager.d.ts +30 -0
  41. package/lib/python-runtime/manager.js +88 -0
  42. package/lib/python-runtime/probe.js +5 -1
  43. package/lib/selected-skills-entry.js +1 -1
  44. package/lib/web-retriever/local-fetch.d.ts +1 -1
  45. package/lib/web-retriever/local-fetch.js +1 -1
  46. package/lib/web-retriever/wind-client.d.ts +1 -1
  47. package/lib/web-retriever/wind-client.js +1 -1
  48. package/package.json +6 -1
  49. package/preset/capital-generation/README.md +5 -6
  50. package/preset/capital-generation/agent.patch.yml +47 -58
  51. package/preset/capital-generation/skills/capital-analysis-evidence/SKILL.md +99 -0
  52. package/preset/capital-generation/skills/capital-analysis-synthesis/SKILL.md +110 -0
  53. package/preset/capital-generation/skills/capital-analysis-validation/SKILL.md +93 -0
  54. package/preset/capital-generation/skills/capital-data-query/SKILL.md +1 -1
  55. package/preset/capital-generation/skills/capital-equity-research/SKILL.md +1 -1
  56. package/preset/capital-generation/skills/capital-event-impact/SKILL.md +1 -1
  57. package/preset/capital-generation/skills/capital-orchestration/SKILL.md +1 -1
  58. package/preset/capital-generation/skills/capital-portfolio-review/SKILL.md +1 -1
  59. package/preset/capital-generation/skills/capital-senior-analysis/SKILL.md +100 -0
  60. package/python/analysis/modules/financial_quality/LICENSE +27 -0
  61. package/python/analysis/modules/financial_quality/module.json +65 -0
  62. package/python/analysis/modules/financial_quality/module.py +535 -0
  63. package/python/analysis/modules/hello/LICENSE +21 -0
  64. package/python/analysis/modules/hello/module.json +46 -0
  65. package/python/analysis/modules/hello/module.py +56 -0
  66. package/python/worker.py +152 -5
  67. package/selected-skills/routing.js +5 -2
  68. package/watchlist/package.json +1 -1
@@ -0,0 +1,64 @@
1
+ import { type SessionLike } from '../data-collector/store.js';
2
+ import { type AnalysisErrorCode } from './types.js';
3
+ export declare const ANALYSIS_ROOT = "capital-analysis/runs";
4
+ export declare const SNAPSHOT_FILE = "snapshot.json";
5
+ export declare const RUN_FILE = "run.json";
6
+ export declare const ARTIFACT_FILE = "artifact.json";
7
+ export declare const REQUEST_FILE = "request.json";
8
+ export declare const RESULT_FILE = "result.json";
9
+ /** Opaque refs: the model never learns a filesystem path, only one of these. */
10
+ export declare const ANALYSIS_ID: RegExp;
11
+ export declare const MODULE_RUN_ID: RegExp;
12
+ export interface AnalysisFileWriter {
13
+ writeWorkspaceFiles(input: {
14
+ session: SessionLike;
15
+ dir: string;
16
+ files: Array<{
17
+ name: string;
18
+ content: string;
19
+ }>;
20
+ signal?: AbortSignal;
21
+ overwrite?: boolean;
22
+ }): Promise<Array<{
23
+ name: string;
24
+ path: string;
25
+ absolutePath: string;
26
+ }>>;
27
+ readWorkspaceJson(input: {
28
+ session: SessionLike;
29
+ path: string;
30
+ signal?: AbortSignal;
31
+ }): Promise<unknown>;
32
+ }
33
+ export declare function newAnalysisId(): string;
34
+ export declare function newModuleRunId(): string;
35
+ export declare const analysisDir: (analysisId: string) => string;
36
+ export declare const inputsDir: (analysisId: string, kind: "datasets" | "profiles" | "evidence") => string;
37
+ export declare const moduleRunDir: (analysisId: string, moduleRunId: string) => string;
38
+ export declare const snapshotRef: (analysisId: string) => string;
39
+ export declare const runRef: (analysisId: string, moduleRunId: string) => string;
40
+ export declare const artifactRef: (analysisId: string) => string;
41
+ /** Parse a model-supplied ref; an unparsable ref must fail as `analysis_snapshot_invalid`. */
42
+ export declare function parseSnapshotRef(ref: unknown): string;
43
+ export declare function parseArtifactRef(ref: unknown): string;
44
+ /**
45
+ * Translate a store failure into an analysis error code. The store already names the object that
46
+ * failed (dataset id, path), so the message stays actionable without a second lookup.
47
+ */
48
+ export declare function asAnalysisError(error: unknown, fallback: AnalysisErrorCode, what: string): never;
49
+ /** Write one directory's files through the store (createIfAbsent unless `overwrite`). */
50
+ export declare function writeFiles(writer: AnalysisFileWriter, session: SessionLike, dir: string, files: Array<{
51
+ name: string;
52
+ content: string;
53
+ }>, options?: {
54
+ signal?: AbortSignal;
55
+ overwrite?: boolean;
56
+ errorCode?: AnalysisErrorCode;
57
+ what?: string;
58
+ }): Promise<Array<{
59
+ name: string;
60
+ path: string;
61
+ absolutePath: string;
62
+ }>>;
63
+ /** Read one JSON file; a missing file is `undefined` (callers decide whether that is fatal). */
64
+ export declare function readJsonFile<T>(reader: AnalysisFileWriter, session: SessionLike, path: string, signal?: AbortSignal): Promise<T | undefined>;
@@ -0,0 +1,96 @@
1
+ /**
2
+ * Run-directory layout and the workspace seam for the analysis family.
3
+ *
4
+ * Every path here is workspace-relative and goes through the Dataset store, which owns containment,
5
+ * the sandbox policy and the size gates. Nothing in `src/analysis/` touches `fs` directly.
6
+ *
7
+ * Layout (`capital-analysis/runs/<analysis_id>/`):
8
+ * snapshot.json run.json artifact.json
9
+ * inputs/{datasets,profiles,evidence}/
10
+ * modules/<module_run_id>/{request,result}.json + outputs/ + logs/
11
+ */
12
+ import { randomUUID } from 'node:crypto';
13
+ import { DatasetStoreError } from '../data-collector/store.js';
14
+ import { AnalysisError } from './types.js';
15
+ export const ANALYSIS_ROOT = 'capital-analysis/runs';
16
+ export const SNAPSHOT_FILE = 'snapshot.json';
17
+ export const RUN_FILE = 'run.json';
18
+ export const ARTIFACT_FILE = 'artifact.json';
19
+ export const REQUEST_FILE = 'request.json';
20
+ export const RESULT_FILE = 'result.json';
21
+ /** Opaque refs: the model never learns a filesystem path, only one of these. */
22
+ export const ANALYSIS_ID = /^analysis_[a-z0-9]{6,40}$/u;
23
+ export const MODULE_RUN_ID = /^module_run_[a-z0-9]{6,40}$/u;
24
+ const idSuffix = () => `${Date.now().toString(36)}${randomUUID().replace(/-/gu, '').slice(0, 10)}`;
25
+ export function newAnalysisId() {
26
+ return `analysis_${idSuffix()}`;
27
+ }
28
+ export function newModuleRunId() {
29
+ return `module_run_${idSuffix()}`;
30
+ }
31
+ export const analysisDir = (analysisId) => `${ANALYSIS_ROOT}/${analysisId}`;
32
+ export const inputsDir = (analysisId, kind) => `${analysisDir(analysisId)}/inputs/${kind}`;
33
+ export const moduleRunDir = (analysisId, moduleRunId) => `${analysisDir(analysisId)}/modules/${moduleRunId}`;
34
+ export const snapshotRef = (analysisId) => `analysis:${analysisId}`;
35
+ export const runRef = (analysisId, moduleRunId) => `analysis_run:${analysisId}/${moduleRunId}`;
36
+ export const artifactRef = (analysisId) => `analysis_artifact:${analysisId}`;
37
+ /** Parse a model-supplied ref; an unparsable ref must fail as `analysis_snapshot_invalid`. */
38
+ export function parseSnapshotRef(ref) {
39
+ const text = typeof ref === 'string' ? ref.trim() : '';
40
+ const id = text.startsWith('analysis:') ? text.slice('analysis:'.length) : '';
41
+ if (!ANALYSIS_ID.test(id)) {
42
+ throw new AnalysisError('analysis_snapshot_invalid', `snapshot 引用无法识别:${JSON.stringify(text).slice(0, 120)}`);
43
+ }
44
+ return id;
45
+ }
46
+ export function parseArtifactRef(ref) {
47
+ const text = typeof ref === 'string' ? ref.trim() : '';
48
+ const id = text.startsWith('analysis_artifact:') ? text.slice('analysis_artifact:'.length) : '';
49
+ if (!ANALYSIS_ID.test(id)) {
50
+ throw new AnalysisError('analysis_snapshot_invalid', `分析产物引用无法识别:${JSON.stringify(text).slice(0, 120)}`);
51
+ }
52
+ return id;
53
+ }
54
+ /**
55
+ * Translate a store failure into an analysis error code. The store already names the object that
56
+ * failed (dataset id, path), so the message stays actionable without a second lookup.
57
+ */
58
+ export function asAnalysisError(error, fallback, what) {
59
+ if (error instanceof AnalysisError)
60
+ throw error;
61
+ if (error instanceof DatasetStoreError) {
62
+ const code = error.code === 'dataset_expired' || error.code === 'profile_expired'
63
+ ? 'analysis_snapshot_expired'
64
+ : error.code === 'dataset_session_mismatch' || error.code === 'dataset_not_found' || error.code === 'profile_not_found'
65
+ ? 'analysis_snapshot_invalid'
66
+ : fallback;
67
+ throw new AnalysisError(code, `${what}:${error.message}`);
68
+ }
69
+ throw new AnalysisError(fallback, `${what}:${error instanceof Error ? error.message : String(error)}`);
70
+ }
71
+ /** Write one directory's files through the store (createIfAbsent unless `overwrite`). */
72
+ export async function writeFiles(writer, session, dir, files, options = {}) {
73
+ try {
74
+ return await writer.writeWorkspaceFiles({
75
+ session,
76
+ dir,
77
+ files,
78
+ ...(options.signal === undefined ? {} : { signal: options.signal }),
79
+ ...(options.overwrite === true ? { overwrite: true } : {}),
80
+ });
81
+ }
82
+ catch (error) {
83
+ asAnalysisError(error, options.errorCode ?? 'analysis_input_invalid', options.what ?? `写入 ${dir} 失败`);
84
+ }
85
+ }
86
+ /** Read one JSON file; a missing file is `undefined` (callers decide whether that is fatal). */
87
+ export async function readJsonFile(reader, session, path, signal) {
88
+ try {
89
+ return await reader.readWorkspaceJson({ session, path, ...(signal === undefined ? {} : { signal }) });
90
+ }
91
+ catch (error) {
92
+ if (error instanceof DatasetStoreError && error.code === 'dataset_not_found')
93
+ return undefined;
94
+ asAnalysisError(error, 'analysis_input_invalid', `读取 ${path} 失败`);
95
+ }
96
+ }
@@ -0,0 +1,17 @@
1
+ /**
2
+ * The `tools/analysis` family: six model-facing tools of the senior analyst.
3
+ *
4
+ * Every tool authorizes the caller through `src/tool-exec.ts` (preset identity, one implementation)
5
+ * and returns refs plus bounded summaries. Raw rows never cross this boundary: they are staged into
6
+ * the snapshot's `inputs/` and read only by the reviewed module inside the private interpreter.
7
+ */
8
+ import type { Context } from '@deepseek-ai/cordis';
9
+ import type { WorkspaceDatasetStore } from '../data-collector/store.js';
10
+ import { ANALYSIS_TOOL_NAMES } from './types.js';
11
+ export interface AnalysisToolDeps {
12
+ readonly ctx: Context;
13
+ readonly store: WorkspaceDatasetStore;
14
+ readonly now?: () => number;
15
+ }
16
+ export declare function registerAnalysisTools(deps: AnalysisToolDeps): void;
17
+ export { ANALYSIS_TOOL_NAMES };
@@ -0,0 +1,352 @@
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
+ throw new AnalysisError('analysis_validation_failed', `产物未通过硬校验(${validation.tier1.length} 条):${validation.tier1.slice(0, 6).map((issue) => `${issue.code} ${issue.detail}`).join(';')}`);
322
+ }
323
+ const downgraded = validation.tier2.length > 0 && artifact.status === 'completed' ? 'partial' : artifact.status;
324
+ const persisted = {
325
+ ...artifact,
326
+ status: downgraded,
327
+ validation: {
328
+ status: validation.tier2.length > 0 ? 'warning' : 'pass',
329
+ issues: [...validation.tier1, ...validation.tier2, ...validation.tier3],
330
+ },
331
+ };
332
+ await writeFiles(store, session, analysisDir(analysisId), [{
333
+ name: ARTIFACT_FILE,
334
+ content: JSON.stringify(persisted),
335
+ }], {
336
+ ...(exec.signal === undefined ? {} : { signal: exec.signal }),
337
+ overwrite: true,
338
+ what: '写入 artifact.json 失败',
339
+ });
340
+ return {
341
+ analysis_ref: artifactRef(analysisId),
342
+ status: 'accepted',
343
+ validation: persisted.validation,
344
+ };
345
+ },
346
+ },
347
+ ];
348
+ for (const definition of definitions) {
349
+ ctx.effect(() => tools.register(definition), `capital-generation.tool(${definition.name})`);
350
+ }
351
+ }
352
+ export { ANALYSIS_TOOL_NAMES };