@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,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 {};
@@ -0,0 +1,338 @@
1
+ import { HEADLINE_MAX_CHARS, MAX_CLAIMS, MAX_SCENARIOS, STATEMENT_MAX_CHARS, THESIS_MAX_CHARS } from './schemas.js';
2
+ /** Subset of JSON Schema used by the protocol: types, properties, required, items, enum, bounds. */
3
+ export function validateAgainstSchema(value, schema, path = '$') {
4
+ if (schema === undefined || Object.keys(schema).length === 0)
5
+ return [];
6
+ const issues = [];
7
+ if (Array.isArray(schema.anyOf)) {
8
+ const failures = schema.anyOf.map((option) => validateAgainstSchema(value, option, path));
9
+ if (failures.every((items) => items.length > 0))
10
+ issues.push(`${path} 不满足任何允许的形态`);
11
+ return issues;
12
+ }
13
+ const type = schema.type;
14
+ if (typeof type === 'string' && !matchesType(value, type)) {
15
+ issues.push(`${path} 应为 ${type},实际是 ${describeType(value)}`);
16
+ return issues;
17
+ }
18
+ if (Array.isArray(schema.enum) && !schema.enum.some((item) => item === value)) {
19
+ issues.push(`${path} 必须是 ${schema.enum.join(' / ')} 之一`);
20
+ }
21
+ if (typeof value === 'string') {
22
+ const maxLength = schema.maxLength;
23
+ if (typeof maxLength === 'number' && value.length > maxLength)
24
+ issues.push(`${path} 超长:${value.length} > ${maxLength}`);
25
+ }
26
+ if (typeof value === 'number' && typeof schema.minimum === 'number' && value < schema.minimum) {
27
+ issues.push(`${path} 小于最小值 ${schema.minimum}`);
28
+ }
29
+ if (Array.isArray(value)) {
30
+ if (typeof schema.maxItems === 'number' && value.length > schema.maxItems) {
31
+ issues.push(`${path} 条目过多:${value.length} > ${schema.maxItems}`);
32
+ }
33
+ if (schema.items !== undefined) {
34
+ value.forEach((item, index) => issues.push(...validateAgainstSchema(item, schema.items, `${path}[${index}]`)));
35
+ }
36
+ }
37
+ if (value !== null && typeof value === 'object' && !Array.isArray(value)) {
38
+ const record = value;
39
+ const properties = (schema.properties ?? {});
40
+ const required = Array.isArray(schema.required) ? schema.required : [];
41
+ for (const key of required) {
42
+ if (record[key] === undefined)
43
+ issues.push(`${path}.${key} 是必填字段`);
44
+ }
45
+ if (schema.additionalProperties === false) {
46
+ for (const key of Object.keys(record)) {
47
+ if (!(key in properties))
48
+ issues.push(`${path}.${key} 是未声明的字段`);
49
+ }
50
+ }
51
+ for (const [key, childSchema] of Object.entries(properties)) {
52
+ if (record[key] !== undefined)
53
+ issues.push(...validateAgainstSchema(record[key], childSchema, `${path}.${key}`));
54
+ }
55
+ }
56
+ return issues;
57
+ }
58
+ function matchesType(value, type) {
59
+ switch (type) {
60
+ case 'object': return value !== null && typeof value === 'object' && !Array.isArray(value);
61
+ case 'array': return Array.isArray(value);
62
+ case 'string': return typeof value === 'string';
63
+ case 'boolean': return typeof value === 'boolean';
64
+ case 'integer': return typeof value === 'number' && Number.isInteger(value);
65
+ case 'number': return typeof value === 'number' && Number.isFinite(value);
66
+ case 'null': return value === null;
67
+ default: return true;
68
+ }
69
+ }
70
+ function describeType(value) {
71
+ if (value === null)
72
+ return 'null';
73
+ if (Array.isArray(value))
74
+ return 'array';
75
+ if (typeof value === 'number' && !Number.isFinite(value))
76
+ return 'non-finite number';
77
+ return typeof value;
78
+ }
79
+ /** Lossless JSON: `undefined`, `NaN`, `Infinity` and array holes must not cross the boundary. */
80
+ export function losslessIssues(value, path = '$') {
81
+ if (value === undefined)
82
+ return [`${path} 是 undefined`];
83
+ if (typeof value === 'number' && !Number.isFinite(value))
84
+ return [`${path} 是 ${String(value)}(非有限数)`];
85
+ if (typeof value === 'function' || typeof value === 'symbol' || typeof value === 'bigint')
86
+ return [`${path} 是 ${typeof value}`];
87
+ if (Array.isArray(value)) {
88
+ const issues = [];
89
+ for (let index = 0; index < value.length; index += 1) {
90
+ if (!(index in value))
91
+ issues.push(`${path}[${index}] 是数组空洞`);
92
+ else
93
+ issues.push(...losslessIssues(value[index], `${path}[${index}]`));
94
+ }
95
+ return issues;
96
+ }
97
+ if (value !== null && typeof value === 'object') {
98
+ const issues = [];
99
+ for (const [key, item] of Object.entries(value))
100
+ issues.push(...losslessIssues(item, `${path}.${key}`));
101
+ return issues;
102
+ }
103
+ return [];
104
+ }
105
+ /** Validate the worker's result object: lossless, then the manifest's declared output schema. */
106
+ export function validateModuleResult(value, manifest) {
107
+ const issues = [];
108
+ if (value === null || typeof value !== 'object' || Array.isArray(value)) {
109
+ return {
110
+ ok: false,
111
+ issues: [{ code: 'analysis_output_invalid', severity: 'error', detail: '模块结果必须是 JSON 对象' }],
112
+ result: undefined,
113
+ };
114
+ }
115
+ for (const detail of losslessIssues(value)) {
116
+ issues.push({ code: 'analysis_output_invalid', severity: 'error', detail });
117
+ }
118
+ const schema = (manifest.output_schema ?? {});
119
+ for (const detail of validateAgainstSchema(value, schema)) {
120
+ issues.push({ code: 'analysis_output_invalid', severity: 'error', detail });
121
+ }
122
+ const result = value;
123
+ if (typeof result.status !== 'string')
124
+ issues.push({ code: 'analysis_output_invalid', severity: 'error', field: 'status', detail: '模块结果缺 status' });
125
+ if (typeof result.summary !== 'string')
126
+ issues.push({ code: 'analysis_output_invalid', severity: 'error', field: 'summary', detail: '模块结果缺 summary' });
127
+ if (!Array.isArray(result.limitations))
128
+ issues.push({ code: 'analysis_output_invalid', severity: 'error', field: 'limitations', detail: '模块结果缺 limitations 数组' });
129
+ if (!Array.isArray(result.data_gaps))
130
+ issues.push({ code: 'analysis_output_invalid', severity: 'error', field: 'data_gaps', detail: '模块结果缺 data_gaps 数组' });
131
+ // §12.2: a result without assumptions or a method log is not reproducible, so it cannot be audited.
132
+ for (const [field, label] of [['assumptions', '假设'], ['methodology_log', '方法日志']]) {
133
+ const items = result[field];
134
+ if (!Array.isArray(items) || items.length === 0) {
135
+ issues.push({ code: 'analysis_output_invalid', severity: 'error', field, detail: `模块结果必须写明${label}(至少一条)` });
136
+ }
137
+ else if (items.some((item) => typeof item !== 'string' || item.trim() === '')) {
138
+ issues.push({ code: 'analysis_output_invalid', severity: 'error', field, detail: `${label}里不能有空串或非字符串` });
139
+ }
140
+ }
141
+ return { ok: issues.every((issue) => issue.severity !== 'error'), issues, result };
142
+ }
143
+ const UNIT_CONSTANTS = new Set([1e4, 1e6, 1e8, 1e12]);
144
+ const YEAR = /^(?:19|20)\d{2}$/u;
145
+ const NUMBER_TOKEN = /-?\d+(?:\.\d+)?/gu;
146
+ const PERCENT_AFTER = /^\s*[%%]/u;
147
+ /** Numeric tokens with just enough context to honour the exemption set. */
148
+ export function numberTokens(text) {
149
+ const tokens = [];
150
+ for (const match of text.matchAll(NUMBER_TOKEN)) {
151
+ const start = match.index ?? 0;
152
+ const raw = match[0];
153
+ const value = Number(raw);
154
+ if (!Number.isFinite(value))
155
+ continue;
156
+ tokens.push({ text: raw, value, percent: PERCENT_AFTER.test(text.slice(start + raw.length)), start });
157
+ }
158
+ return tokens;
159
+ }
160
+ function tolerance(precision) {
161
+ const digits = typeof precision === 'number' && precision >= 0 && precision <= 12 ? precision : 4;
162
+ return 0.5 * 10 ** -digits;
163
+ }
164
+ function exemptToken(text, token, source) {
165
+ // Digits inside an identifier (`claim_1`, `FY2025`) are not quantities.
166
+ const before = source[token.start - 1];
167
+ const after = source[token.start + token.text.length];
168
+ if ((before !== undefined && /[A-Za-z_]/u.test(before)) || (after !== undefined && /[A-Za-z_]/u.test(after)))
169
+ return true;
170
+ if (!token.percent && YEAR.test(token.text))
171
+ return true;
172
+ if (Number.isInteger(token.value) && Math.abs(token.value) <= 20) {
173
+ const before = source.slice(Math.max(0, token.start - 2), token.start);
174
+ if (/[第期条项]/u.test(before))
175
+ return true;
176
+ }
177
+ if (UNIT_CONSTANTS.has(token.value) && /^\d+$/u.test(token.text))
178
+ return true;
179
+ return false;
180
+ }
181
+ function anchoredNumbers(artifact) {
182
+ const anchors = [];
183
+ const values = [];
184
+ for (const claim of [...artifact.support_claims, ...artifact.counter_claims]) {
185
+ for (const anchor of claim.number_anchors ?? []) {
186
+ if (typeof anchor?.value === 'number' && Number.isFinite(anchor.value))
187
+ anchors.push(anchor);
188
+ }
189
+ }
190
+ for (const calculation of artifact.calculations ?? []) {
191
+ if (typeof calculation?.value === 'number' && Number.isFinite(calculation.value))
192
+ values.push(calculation.value);
193
+ }
194
+ return { anchors, values };
195
+ }
196
+ function unmatchedNumbers(text, anchors, calculations) {
197
+ const misses = [];
198
+ for (const token of numberTokens(text)) {
199
+ if (exemptToken(text, token, text))
200
+ continue;
201
+ const hit = anchors.some((anchor) => {
202
+ const tol = tolerance(anchor.precision);
203
+ if (Math.abs(anchor.value - token.value) <= tol)
204
+ return true;
205
+ // Ratio written as a percentage (0.1823 ↔ 18.23) — same precision, scaled by 100.
206
+ return Math.abs(anchor.value * 100 - token.value) <= Math.max(tol * 100, 0.5 * 10 ** -2);
207
+ });
208
+ if (hit)
209
+ continue;
210
+ if (calculations.some((value) => Math.abs(value - token.value) <= tolerance(undefined)))
211
+ continue;
212
+ misses.push(token.text);
213
+ }
214
+ return misses;
215
+ }
216
+ function claimIssues(claim, path, tier1, tier2) {
217
+ if (typeof claim?.statement === 'string' && claim.statement.length > STATEMENT_MAX_CHARS) {
218
+ tier1.push({ code: 'analysis_result_too_large', severity: 'error', field: `${path}.statement`, detail: `单条 statement 超过 ${STATEMENT_MAX_CHARS} 字符` });
219
+ }
220
+ if (typeof claim?.confidence_basis !== 'string' || claim.confidence_basis.trim() === '') {
221
+ tier2.push({ code: 'confidence_basis_missing', severity: 'warning', field: `${path}.confidence_basis`, detail: 'confidence 必须带一句依据' });
222
+ }
223
+ }
224
+ /**
225
+ * Artifact validation in the three tiers of the design (Tier 1 rejects, Tier 2 downgrades to
226
+ * `partial`, Tier 3 is advisory). Returns issues; persistence is the caller's decision.
227
+ */
228
+ export function validateArtifact(artifact, snapshot) {
229
+ const tier1 = [];
230
+ const tier2 = [];
231
+ const tier3 = [];
232
+ if (typeof artifact.headline === 'string' && artifact.headline.length > HEADLINE_MAX_CHARS) {
233
+ tier1.push({ code: 'analysis_result_too_large', severity: 'error', field: 'headline', detail: `headline 超过 ${HEADLINE_MAX_CHARS} 字符` });
234
+ }
235
+ if (typeof artifact.thesis === 'string' && artifact.thesis.length > THESIS_MAX_CHARS) {
236
+ tier1.push({ code: 'analysis_result_too_large', severity: 'error', field: 'thesis', detail: `thesis 超过 ${THESIS_MAX_CHARS} 字符` });
237
+ }
238
+ const claims = [...(artifact.support_claims ?? []), ...(artifact.counter_claims ?? [])];
239
+ if (claims.length > MAX_CLAIMS * 2) {
240
+ tier1.push({ code: 'analysis_result_too_large', severity: 'error', field: 'support_claims', detail: `正反论据合计 ${claims.length} 条,超过 ${MAX_CLAIMS * 2} 条上限` });
241
+ }
242
+ // §10.6 budgets live here, not in the tool schema: the host's JSON-Schema subset has no `maxItems`,
243
+ // so a schema keyword would cost the whole family row at boot.
244
+ for (const [field, list, limit] of [
245
+ ['support_claims', artifact.support_claims, MAX_CLAIMS],
246
+ ['counter_claims', artifact.counter_claims, MAX_CLAIMS],
247
+ ['scenarios', artifact.scenarios, MAX_SCENARIOS],
248
+ ]) {
249
+ if (Array.isArray(list) && list.length > limit) {
250
+ tier1.push({ code: 'analysis_result_too_large', severity: 'error', field, detail: `${field} ${list.length} 条,超过 ${limit} 条上限` });
251
+ }
252
+ }
253
+ claims.forEach((claim, index) => claimIssues(claim, `claims[${index}]`, tier1, tier2));
254
+ // Hard rule: a conclusion with no invalidation condition is not a judgement, it is a slogan.
255
+ if (!Array.isArray(artifact.invalidation_conditions) || artifact.invalidation_conditions.length === 0) {
256
+ tier1.push({ code: 'invalidation_missing', severity: 'error', field: 'invalidation_conditions', detail: '至少要一条能推翻主判断的条件' });
257
+ }
258
+ else {
259
+ const ids = [...claims.map((claim) => claim.claim_id), ...(artifact.calculations ?? []).map((item) => item.calculation_id)]
260
+ .filter((id) => typeof id === 'string' && id !== '');
261
+ const references = artifact.invalidation_conditions.some((condition) => ids.some((id) => condition.includes(id)));
262
+ if (!references) {
263
+ tier2.push({ code: 'invalidation_unreferenced', severity: 'warning', field: 'invalidation_conditions', detail: '失效条件没有引用任何 claim_id / calculation_id,无法核对它推翻的是哪一条' });
264
+ }
265
+ }
266
+ // Evidence level and status must agree; `completed` also requires a clean validation.
267
+ if (artifact.evidence_level === 'insufficient' && artifact.status === 'completed') {
268
+ tier1.push({ code: 'evidence_level_conflict', severity: 'error', field: 'status', detail: 'evidence_level=insufficient 时 status 只能是 partial / blocked' });
269
+ }
270
+ if (artifact.status === 'completed' && !Array.isArray(artifact.limitations)) {
271
+ tier1.push({ code: 'limitations_missing', severity: 'error', field: 'limitations', detail: 'completed 的产物必须有 limitations 字段(可以为空数组,但不能缺)' });
272
+ }
273
+ if (Array.isArray(artifact.limitations) && artifact.limitations.length === 0) {
274
+ tier2.push({ code: 'limitations_empty', severity: 'warning', field: 'limitations', detail: 'limitations 为空:至少写明一条口径或数据限制' });
275
+ }
276
+ // Refs must exist inside this snapshot.
277
+ const datasetIds = new Set(snapshot.dataset_refs.map((item) => item.dataset_id));
278
+ const profileIds = new Set(snapshot.profile_refs.map((item) => item.profile_id));
279
+ const evidenceIds = new Set(snapshot.evidence.map((item) => item.source_id));
280
+ const calcIds = new Set((artifact.calculations ?? []).map((item) => item.calculation_id));
281
+ for (const claim of claims) {
282
+ for (const ref of claim.evidence_refs ?? []) {
283
+ if (!evidenceIds.has(ref)) {
284
+ tier1.push({ code: 'evidence_ref_missing', severity: 'error', field: claim.claim_id, detail: `引用的证据 ${ref} 不在本次快照里` });
285
+ }
286
+ }
287
+ for (const anchor of claim.number_anchors ?? []) {
288
+ const ref = anchor?.source?.ref;
289
+ if (typeof ref !== 'string')
290
+ continue;
291
+ const known = anchor.source.kind === 'dataset' ? datasetIds.has(ref)
292
+ : anchor.source.kind === 'profile' ? profileIds.has(ref)
293
+ : anchor.source.kind === 'evidence' ? evidenceIds.has(ref)
294
+ : calcIds.has(ref);
295
+ if (!known) {
296
+ tier1.push({ code: 'anchor_ref_missing', severity: 'error', field: claim.claim_id, detail: `数字锚点引用的 ${ref} 不在本次快照/计算里` });
297
+ }
298
+ }
299
+ }
300
+ // Number traceability on the conclusion fields only (Tier 1) and on calculations (Tier 2).
301
+ const { anchors, values } = anchoredNumbers(artifact);
302
+ const conclusionTexts = [
303
+ { field: 'headline', text: artifact.headline ?? '' },
304
+ { field: 'thesis', text: artifact.thesis ?? '' },
305
+ ...claims.map((claim, index) => ({ field: `claims[${index}].statement`, text: claim.statement ?? '' })),
306
+ ...(artifact.invalidation_conditions ?? []).map((condition, index) => ({ field: `invalidation_conditions[${index}]`, text: condition })),
307
+ ];
308
+ for (const { field, text } of conclusionTexts) {
309
+ const misses = unmatchedNumbers(text, anchors, values);
310
+ if (misses.length > 0) {
311
+ tier1.push({ code: 'number_without_anchor', severity: 'error', field, detail: `这些数字没有来源锚点:${misses.slice(0, 6).join('、')}` });
312
+ }
313
+ }
314
+ for (const [index, calculation] of (artifact.calculations ?? []).entries()) {
315
+ const known = anchors.some((anchor) => Math.abs(anchor.value - calculation.value) <= tolerance(anchor.precision));
316
+ if (!known) {
317
+ tier2.push({ code: 'calculation_without_anchor', severity: 'warning', field: `calculations[${index}]`, detail: `计算结果 ${calculation.metric}=${calculation.value} 没有对应锚点` });
318
+ }
319
+ }
320
+ // Peer exchanges: an unanswered peer request means the result is not final.
321
+ const unanswered = (artifact.peer_exchanges ?? []).filter((item) => item?.answered !== true);
322
+ if (unanswered.length > 0) {
323
+ tier2.push({ code: 'peer_unanswered', severity: 'warning', field: 'peer_exchanges', detail: `${unanswered.length} 条 peer 请求没有回执;产物最多 partial` });
324
+ }
325
+ if (artifact.status === 'completed' && unanswered.length > 0) {
326
+ tier1.push({ code: 'peer_unanswered_completed', severity: 'error', field: 'status', detail: '存在未回执的 peer 请求时不能写 completed' });
327
+ }
328
+ for (const [index, scenario] of (artifact.scenarios ?? []).entries()) {
329
+ const assumptions = scenario?.assumptions;
330
+ if (!Array.isArray(assumptions) || assumptions.length === 0) {
331
+ tier2.push({ code: 'scenario_assumptions_missing', severity: 'warning', field: `scenarios[${index}]`, detail: '情景必须写明假设' });
332
+ }
333
+ }
334
+ if ((artifact.alternative_explanations ?? []).length === 0) {
335
+ tier3.push({ code: 'no_alternative_explanation', severity: 'notice', field: 'alternative_explanations', detail: '没有替代解释:审阅者会问"还可能是别的什么"' });
336
+ }
337
+ return { tier1, tier2, tier3 };
338
+ }
@@ -0,0 +1,10 @@
1
+ /**
2
+ * `tools/analysis` row: the senior analyst's analysis family (snapshot / module run / submit).
3
+ *
4
+ * A family row, not a host row — the role preset mounts it and `src/tool-exec.ts` authorizes the
5
+ * caller by preset identity. The store is built per mount (same rule as the dataset-read row).
6
+ */
7
+ import type { Context } from '@deepseek-ai/cordis';
8
+ export declare const name = "capital-analysis-tools";
9
+ export declare const inject: string[];
10
+ export declare function apply(ctx: Context): void;
@@ -0,0 +1,7 @@
1
+ import { registerAnalysisTools } from './analysis/tools.js';
2
+ import { capitalDatasetStore } from './runtime.js';
3
+ export const name = 'capital-analysis-tools';
4
+ export const inject = ['tools'];
5
+ export function apply(ctx) {
6
+ registerAnalysisTools({ ctx, store: capitalDatasetStore(ctx) });
7
+ }