@v587d/capital-generation 2.30.0 → 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 (76) hide show
  1. package/CHANGELOG.md +99 -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/dataset-tools.js +4 -2
  33. package/lib/data-collector/describe.d.ts +2 -0
  34. package/lib/data-collector/describe.js +2 -0
  35. package/lib/data-collector/store.d.ts +25 -1
  36. package/lib/data-collector/store.js +124 -1
  37. package/lib/data-collector/tools.d.ts +1 -1
  38. package/lib/data-collector/tools.js +3 -2
  39. package/lib/data-contract.d.ts +3 -2
  40. package/lib/data-contract.js +18 -2
  41. package/lib/preset-ids.d.ts +5 -0
  42. package/lib/preset-ids.js +7 -1
  43. package/lib/python-runtime/errors.d.ts +7 -1
  44. package/lib/python-runtime/errors.js +9 -1
  45. package/lib/python-runtime/manager.d.ts +30 -0
  46. package/lib/python-runtime/manager.js +88 -0
  47. package/lib/python-runtime/probe.js +5 -1
  48. package/lib/selected-skills-entry.js +1 -1
  49. package/lib/sources/tencent-http.js +1 -1
  50. package/lib/sources/ths-http.js +5 -2
  51. package/lib/time/tools.js +1 -1
  52. package/lib/web-retriever/local-fetch.d.ts +1 -1
  53. package/lib/web-retriever/local-fetch.js +1 -1
  54. package/lib/web-retriever/wind-client.d.ts +1 -1
  55. package/lib/web-retriever/wind-client.js +1 -1
  56. package/package.json +6 -1
  57. package/preset/capital-generation/README.md +5 -6
  58. package/preset/capital-generation/agent.patch.yml +47 -58
  59. package/preset/capital-generation/skills/capital-analysis-evidence/SKILL.md +99 -0
  60. package/preset/capital-generation/skills/capital-analysis-synthesis/SKILL.md +110 -0
  61. package/preset/capital-generation/skills/capital-analysis-validation/SKILL.md +93 -0
  62. package/preset/capital-generation/skills/capital-data-query/SKILL.md +1 -1
  63. package/preset/capital-generation/skills/capital-equity-research/SKILL.md +1 -1
  64. package/preset/capital-generation/skills/capital-event-impact/SKILL.md +1 -1
  65. package/preset/capital-generation/skills/capital-orchestration/SKILL.md +1 -1
  66. package/preset/capital-generation/skills/capital-portfolio-review/SKILL.md +1 -1
  67. package/preset/capital-generation/skills/capital-senior-analysis/SKILL.md +100 -0
  68. package/python/analysis/modules/financial_quality/LICENSE +27 -0
  69. package/python/analysis/modules/financial_quality/module.json +65 -0
  70. package/python/analysis/modules/financial_quality/module.py +535 -0
  71. package/python/analysis/modules/hello/LICENSE +21 -0
  72. package/python/analysis/modules/hello/module.json +46 -0
  73. package/python/analysis/modules/hello/module.py +56 -0
  74. package/python/worker.py +152 -5
  75. package/selected-skills/routing.js +5 -2
  76. package/watchlist/package.json +1 -1
@@ -144,6 +144,7 @@ const datasetRefProperties = { dataset_id: { type: 'string' },
144
144
  captured_at: { type: 'integer' },
145
145
  retention_until: { type: 'integer' },
146
146
  params_digest: { type: 'string' },
147
+ envelope: { type: 'object', additionalProperties: true },
147
148
  time_coverage: {
148
149
  type: 'object',
149
150
  properties: {
@@ -315,6 +316,7 @@ const describeResultSchema = jsonObject({
315
316
  shape: { type: 'string', enum: ['array', 'envelope_item', 'document', 'none'] },
316
317
  reason: { type: 'string' },
317
318
  }, ['readable', 'shape']),
319
+ envelope: { type: 'object', additionalProperties: true },
318
320
  profile_id: { type: 'string' },
319
321
  profile_ref: { type: 'string' },
320
322
  columns: { type: 'array', items: { type: 'string' } },
@@ -348,7 +350,7 @@ export function registerDatasetTools(ctx, store, options = {}) {
348
350
  if (!tools)
349
351
  return;
350
352
  const registrations = [
351
- tool('inspect_dataset', '读取当前 session 已授权 Dataset 的元数据和可读性。只返回 DatasetRef 与可读性信息,不返回原始 rows,也不接受任何文件路径。query_access.shape 取值:array / envelope_item = 行集合,可 profile 也可 query;document = 顶层是文档对象(财务指标、回测结果这类),可 profile(宿主给结构摘要与有界内容)但不能 query;none = 不可读,reason 说明原因。批量描述多份 Dataset 请用 describe_dataset(一次一份、可并发);本工具用于单点复核。', jsonObject({ dataset_id: datasetIdSchema }, ['dataset_id']), datasetRefWithAccessSchema, async (args, exec) => store.inspectDataset(readDatasetId(args.dataset_id), authorizedSession(ctx, exec, 'inspect_dataset', DATASET_READING_PRESET_IDS), exec.signal)),
353
+ tool('inspect_dataset', '读取当前 session 已授权 Dataset 的元数据和可读性。只返回 DatasetRef 与可读性信息,不返回原始 rows,也不接受任何文件路径。envelope(若有)是响应根级标量:交易日、requested_date_clamped、available、note、calculated_at 这类口径标记,用它核对「数据归属哪一天/是否被夹日期」;它不是列,不能 query,也不是行数据。query_access.shape 取值:array / envelope_item = 行集合,可 profile 也可 query;document = 顶层是文档对象(财务指标、回测结果这类),可 profile(宿主给结构摘要与有界内容)但不能 query;none = 不可读,reason 说明原因。批量描述多份 Dataset 请用 describe_dataset(一次一份、可并发);本工具用于单点复核。', jsonObject({ dataset_id: datasetIdSchema }, ['dataset_id']), datasetRefWithAccessSchema, async (args, exec) => store.inspectDataset(readDatasetId(args.dataset_id), authorizedSession(ctx, exec, 'inspect_dataset', DATASET_READING_PRESET_IDS), exec.signal)),
352
354
  tool('profile_dataset', `由宿主读取 Dataset 并返回基础质量检查与四类事实;原始 rows 不进入模型上下文。行集合返回:① schema/quality——字段 observed/contract 类型、missing/null/invalid 计数、重复行、时间顺序;② statistics——数值字段的 count/sum/min/max/mean/分位数;③ categories——字符串字段的 distinct_count 与最多 5 个高频取值(truncated=true 表示未列全);④ time_facts——时间列覆盖范围与首行/末行的数值取值(回答"最新值、区间涨跌"必须用它,不要用 min/max 代替首末值);⑤ structure——行内数组/对象的路径摘要(对象字段用 .name、数组元素用 [];未抽样时用 total_elements,超过 50 项时用 sampled_elements,后者明确表示只是抽样,不能据此回答完整数量)。文档型 Dataset(顶层是文档对象,没有行数组)返回 structure 结构摘要 + document 有界内容,不返回行列统计。time_column 可显式指定,省略时按列名候选并只在取值全为数字或日期样式时采用。不接受任何文件路径、脚本内容或额外 schema。批量描述请用 describe_dataset(一次一份、可并发);本工具用于单点复核或补取一份完整 profile。`, jsonObject({
353
355
  dataset_id: datasetIdSchema,
354
356
  task_id: { type: 'string' },
@@ -386,7 +388,7 @@ export function registerDatasetTools(ctx, store, options = {}) {
386
388
  withIsoTimeColumns(result, prepared.axis);
387
389
  return result;
388
390
  }),
389
- tool('describe_dataset', `读取一份 Dataset 的**默认入口**:一次调用完成 inspect(元数据与可读性/形状)、profile(宿主算基础质量与四类事实,写入 profile_ref)与受控 query(可选);原始 rows 不进入模型上下文。一次只处理一个 dataset_id——本轮有多份数据时请并发调用本工具(PTC 在同一个 run_code 程序里用 Promise.all,native 在同一条消息里一次发出多个调用),不要一份一份等。行集合返回:① 元数据 artifact_ref/capability/source_label/captured_at/retention_until 与 query_access.shape(array / envelope_item = 行集合;document = 顶层文档对象,只能 profile,queries 由宿主跳过);② profile 四类事实——statistics(count/sum/min/max/mean/分位数)、categories(distinct + 最多 5 个高频取值)、time_facts(覆盖范围与首行/末行取值;回答"最新值、区间涨跌"必须用它,不要用 min/max 代替)、structure(嵌套路径摘要);③ queries——每条的 QueryResult,或该条自己的 error(单条失败不影响其余)。columns_of_interest 只对这些列返回 statistics/categories/schema(并同样收窄 time_facts 的首末值投影,时间列永远保留),是收窄结果体积的唯一手段。结果超过 ${SAFE_RESULT_CHARS} 码点时宿主不返回超长载荷,而返回 {status:'too_large', profile_ref, columns, bytes, facts_bytes, queries_bytes, hint}:facts_bytes/queries_bytes 是体积归因(哪边大砍哪边),按 hint 重发一次即可——queries 大就先去掉 queries(聚合改单独走 query_dataset),facts 大就用 columns_of_interest 收窄列(或减少 queries,最多 ${MAX_DESCRIBE_QUERIES} 条)。单点复核仍可用 inspect_dataset / profile_dataset / query_dataset;不接受任何文件路径、脚本内容或自定义表达式。`, describeParametersSchema, describeResultSchema, async (args, exec) => describeDataset({
391
+ tool('describe_dataset', `读取一份 Dataset 的**默认入口**:一次调用完成 inspect(元数据与可读性/形状)、profile(宿主算基础质量与四类事实,写入 profile_ref)与受控 query(可选);原始 rows 不进入模型上下文。一次只处理一个 dataset_id——本轮有多份数据时请并发调用本工具(PTC 在同一个 run_code 程序里用 Promise.all,native 在同一条消息里一次发出多个调用),不要一份一份等。行集合返回:① 元数据 artifact_ref/capability/source_label/captured_at/retention_until 与 query_access.shape(array / envelope_item = 行集合;document = 顶层文档对象,只能 profile,queries 由宿主跳过),以及 envelope(若响应是 envelope 形态:根级交易日/请求日钳制标记/available/note/计算时间等标量,回答「数据属于哪一天、是否被夹到最近交易日」必须看它,它不是列、不能 query);② profile 四类事实——statistics(count/sum/min/max/mean/分位数)、categories(distinct + 最多 5 个高频取值)、time_facts(覆盖范围与首行/末行取值;回答"最新值、区间涨跌"必须用它,不要用 min/max 代替)、structure(嵌套路径摘要);③ queries——每条的 QueryResult,或该条自己的 error(单条失败不影响其余)。columns_of_interest 只对这些列返回 statistics/categories/schema(并同样收窄 time_facts 的首末值投影,时间列永远保留),是收窄结果体积的唯一手段。结果超过 ${SAFE_RESULT_CHARS} 码点时宿主不返回超长载荷,而返回 {status:'too_large', profile_ref, columns, bytes, facts_bytes, queries_bytes, hint}:facts_bytes/queries_bytes 是体积归因(哪边大砍哪边),按 hint 重发一次即可——queries 大就先去掉 queries(聚合改单独走 query_dataset),facts 大就用 columns_of_interest 收窄列(或减少 queries,最多 ${MAX_DESCRIBE_QUERIES} 条)。单点复核仍可用 inspect_dataset / profile_dataset / query_dataset;不接受任何文件路径、脚本内容或自定义表达式。`, describeParametersSchema, describeResultSchema, async (args, exec) => describeDataset({
390
392
  store,
391
393
  session: authorizedSession(ctx, exec, 'describe_dataset', DATASET_READING_PRESET_IDS),
392
394
  request: normalizeDescribeArgs(args),
@@ -39,6 +39,8 @@ export interface DescribeResult {
39
39
  retention_until: number;
40
40
  params_digest: string;
41
41
  query_access: DatasetInspection['query_access'];
42
+ /** Envelope root scalars (trade_date / requested_date_clamped / calculated_at …), never rows. */
43
+ envelope?: Record<string, unknown>;
42
44
  profile_id: string;
43
45
  profile_ref: string;
44
46
  columns: string[];
@@ -173,6 +173,7 @@ export async function describeDataset(input) {
173
173
  params_digest: inspection.params_digest,
174
174
  time_coverage: inspection.time_coverage,
175
175
  query_access: inspection.query_access,
176
+ envelope: inspection.envelope,
176
177
  profile_id: profile.profile_id,
177
178
  profile_ref: profile.artifact_ref,
178
179
  columns: profile.columns,
@@ -200,6 +201,7 @@ export async function describeDataset(input) {
200
201
  profile_ref: profile.artifact_ref,
201
202
  shape,
202
203
  columns: profile.columns,
204
+ envelope: inspection.envelope,
203
205
  bytes,
204
206
  facts_bytes: factsBytes,
205
207
  queries_bytes: queriesBytes,
@@ -25,6 +25,11 @@ export declare const MAX_STRUCTURE_ENTRIES = 24;
25
25
  export declare const MAX_DOCUMENT_CHARS = 6000;
26
26
  /** Presentation rows are capped: charts are bounded rendering, not a general analysis channel. */
27
27
  export declare const MAX_PRESENTATION_ROWS = 200000;
28
+ /**
29
+ * Envelope root scalars carried on DatasetRef (dates, clamp flags, notes). Rows never ride here;
30
+ * this is the only way a consumer can see `requested_date_clamped` / `calculated_at` at all.
31
+ */
32
+ export declare const MAX_ENVELOPE_BYTES = 4096;
28
33
  export declare const ARTIFACT_SCHEME = "workspace://";
29
34
  export interface DatasetRef {
30
35
  dataset_id: string;
@@ -41,6 +46,12 @@ export interface DatasetRef {
41
46
  params_digest: string;
42
47
  /** Host-computed from the stored rows; omitted only by manifests written before this field existed. */
43
48
  time_coverage?: DatasetTimeCoverage;
49
+ /**
50
+ * Bounded root-level scalars of an envelope-shaped response (trade_date / requested_date_clamped /
51
+ * available / note / calculated_at …). Never rows and never nested payloads; omitted for arrays,
52
+ * for documents, and by manifests written before this field existed.
53
+ */
54
+ envelope?: Record<string, unknown>;
44
55
  }
45
56
  export type DatasetShape = 'array' | 'envelope_item' | 'document' | 'none';
46
57
  export interface DatasetInspection extends DatasetRef {
@@ -177,7 +188,7 @@ export interface ProfilePayload {
177
188
  validation?: ProfileValidation;
178
189
  warnings: string[];
179
190
  }
180
- export type DatasetStoreErrorCode = 'workspace_not_writable' | 'session_unavailable' | 'session_cwd_unavailable' | 'sandbox_policy_unavailable' | 'filesystem_unavailable' | 'dataset_write_failed' | 'dataset_id_invalid' | 'dataset_not_found' | 'dataset_expired' | 'dataset_session_mismatch' | 'dataset_manifest_invalid' | 'dataset_format_unsupported' | 'dataset_not_row_readable' | 'dataset_too_large' | 'profile_invalid' | 'profile_too_large' | 'profile_dataset_mismatch' | 'workspace_path_invalid' | 'workspace_file_invalid';
191
+ export type DatasetStoreErrorCode = 'workspace_not_writable' | 'session_unavailable' | 'session_cwd_unavailable' | 'sandbox_policy_unavailable' | 'filesystem_unavailable' | 'dataset_write_failed' | 'dataset_id_invalid' | 'dataset_not_found' | 'dataset_expired' | 'dataset_session_mismatch' | 'dataset_manifest_invalid' | 'dataset_format_unsupported' | 'dataset_not_row_readable' | 'dataset_too_large' | 'profile_invalid' | 'profile_not_found' | 'profile_expired' | 'profile_too_large' | 'profile_dataset_mismatch' | 'workspace_path_invalid' | 'workspace_file_invalid';
181
192
  export declare class DatasetStoreError extends Error {
182
193
  readonly code: DatasetStoreErrorCode;
183
194
  constructor(code: DatasetStoreErrorCode, detail: string);
@@ -345,6 +356,19 @@ export declare class WorkspaceDatasetStore {
345
356
  signal?: AbortSignal;
346
357
  }): Promise<TimeAxisSnapshot | undefined>;
347
358
  writeProfile(input: WriteProfileInput): Promise<ProfileRef>;
359
+ /**
360
+ * Host-internal profile read (analysis staging and `read_profile`). Same scope and expiry rules as
361
+ * Datasets: a profile belongs to the parent session scope and an expired one must not be analyzed.
362
+ * There is no model-facing read path for the raw profile object.
363
+ */
364
+ readProfile(input: {
365
+ session: SessionLike;
366
+ profile_id: string;
367
+ signal?: AbortSignal;
368
+ }): Promise<{
369
+ ref: ProfileRef;
370
+ profile: ProfilePayload;
371
+ }>;
348
372
  /**
349
373
  * Host-internal presentation read (charts). The returned rows must never enter any agent message,
350
374
  * tool result or model context; this is the only path that hands raw rows outside the store.
@@ -34,6 +34,13 @@ const MAX_AXIS_PROBE_ROWS = 500;
34
34
  export const MAX_DOCUMENT_CHARS = 6_000;
35
35
  /** Presentation rows are capped: charts are bounded rendering, not a general analysis channel. */
36
36
  export const MAX_PRESENTATION_ROWS = 200_000;
37
+ /**
38
+ * Envelope root scalars carried on DatasetRef (dates, clamp flags, notes). Rows never ride here;
39
+ * this is the only way a consumer can see `requested_date_clamped` / `calculated_at` at all.
40
+ */
41
+ export const MAX_ENVELOPE_BYTES = 4_096;
42
+ const MAX_ENVELOPE_TEXT_CHARS = 512;
43
+ const MAX_ENVELOPE_OBJECT_BYTES = 1_024;
37
44
  const DOCUMENT_ARRAY_KEEP_STEPS = [8, 3, 1, 0];
38
45
  const DOCUMENT_MAX_DEPTH = 6;
39
46
  const DOCUMENT_MAX_OMISSIONS = 8;
@@ -104,6 +111,63 @@ function canonicalProfileRef(profileId) {
104
111
  function validNonNegativeInteger(value) {
105
112
  return typeof value === 'number' && Number.isSafeInteger(value) && value >= 0;
106
113
  }
114
+ /**
115
+ * Envelope root scalars are the only part of a response that otherwise reaches nobody: rows stay in
116
+ * raw.json, while `requested_date_clamped` / `calculated_at` / `available` live beside the row array.
117
+ * Arrays and nested objects are skipped on purpose — they are rows or payloads, not metadata.
118
+ */
119
+ function envelopeOf(data, rowKey) {
120
+ if (!isRecord(data))
121
+ return undefined;
122
+ const rowRoot = rowKey?.split('.')[0];
123
+ const envelope = {};
124
+ for (const [key, value] of Object.entries(data)) {
125
+ if (key === rowRoot)
126
+ continue;
127
+ const picked = envelopeValueOf(value);
128
+ if (picked === undefined)
129
+ continue;
130
+ if (JSON.stringify({ ...envelope, [key]: picked }).length > MAX_ENVELOPE_BYTES)
131
+ break;
132
+ envelope[key] = picked;
133
+ }
134
+ return Object.keys(envelope).length === 0 ? undefined : envelope;
135
+ }
136
+ /** Primitives, plus one shallow object of primitives (upstream wraps page totals this way). */
137
+ function envelopeValueOf(value) {
138
+ if (value === null || typeof value === 'boolean')
139
+ return value;
140
+ if (typeof value === 'number')
141
+ return Number.isFinite(value) ? value : undefined;
142
+ if (typeof value === 'string') {
143
+ return value.length > MAX_ENVELOPE_TEXT_CHARS ? `${value.slice(0, MAX_ENVELOPE_TEXT_CHARS)}…` : value;
144
+ }
145
+ if (!isRecord(value))
146
+ return undefined;
147
+ const flat = {};
148
+ for (const [key, entry] of Object.entries(value)) {
149
+ if (entry === null || typeof entry === 'boolean' || typeof entry === 'string') {
150
+ flat[key] = entry;
151
+ continue;
152
+ }
153
+ if (typeof entry === 'number' && Number.isFinite(entry)) {
154
+ flat[key] = entry;
155
+ continue;
156
+ }
157
+ return undefined;
158
+ }
159
+ return JSON.stringify(flat).length > MAX_ENVELOPE_OBJECT_BYTES ? undefined : flat;
160
+ }
161
+ function validEnvelope(value) {
162
+ if (!isRecord(value) || !Object.keys(value).every((key) => envelopeValueOf(value[key]) !== undefined))
163
+ return false;
164
+ try {
165
+ return JSON.stringify(value).length <= MAX_ENVELOPE_BYTES;
166
+ }
167
+ catch {
168
+ return false;
169
+ }
170
+ }
107
171
  export class WorkspaceDatasetStore {
108
172
  fs;
109
173
  sandboxPolicy;
@@ -127,6 +191,7 @@ export class WorkspaceDatasetStore {
127
191
  const dirPath = `${DATASETS_SUBDIR}/${datasetId}`;
128
192
  await this.assertContained(root, dirPath, signal);
129
193
  const capturedAt = this.now();
194
+ const envelope = input.format === 'json_rows' ? envelopeOf(input.data, input.row_key) : undefined;
130
195
  const manifest = {
131
196
  dataset_id: datasetId,
132
197
  task_id: input.task_id ?? null,
@@ -141,6 +206,7 @@ export class WorkspaceDatasetStore {
141
206
  retention_until: capturedAt + this.retentionMs,
142
207
  params_digest: input.params_digest,
143
208
  ...(input.time_coverage === undefined ? {} : { time_coverage: input.time_coverage }),
209
+ ...(envelope === undefined ? {} : { envelope }),
144
210
  };
145
211
  const storedManifest = {
146
212
  ...manifest,
@@ -211,7 +277,17 @@ export class WorkspaceDatasetStore {
211
277
  const { session_scope_id: _scope, row_key: rowKey, ...ref } = stored;
212
278
  try {
213
279
  const raw = await this.readRaw(ref, session, signal, rowKey);
214
- return { ...ref, query_access: { readable: true, shape: raw.kind === 'document' ? 'document' : raw.shape } };
280
+ // Manifests written before `envelope` existed still have the raw response: derive it on read
281
+ // so a Dataset taken minutes before the upgrade stays readable on the same terms.
282
+ const envelope = ref.envelope
283
+ ?? (raw.kind === 'rows' && raw.shape === 'envelope_item' && raw.envelope !== undefined
284
+ ? envelopeOf(raw.envelope, rowKey)
285
+ : undefined);
286
+ return {
287
+ ...ref,
288
+ ...(envelope === undefined ? {} : { envelope }),
289
+ query_access: { readable: true, shape: raw.kind === 'document' ? 'document' : raw.shape },
290
+ };
215
291
  }
216
292
  catch (error) {
217
293
  if (error instanceof DatasetStoreError && ['dataset_too_large', 'dataset_not_row_readable'].includes(error.code)) {
@@ -317,6 +393,50 @@ export class WorkspaceDatasetStore {
317
393
  }
318
394
  return profileRef;
319
395
  }
396
+ /**
397
+ * Host-internal profile read (analysis staging and `read_profile`). Same scope and expiry rules as
398
+ * Datasets: a profile belongs to the parent session scope and an expired one must not be analyzed.
399
+ * There is no model-facing read path for the raw profile object.
400
+ */
401
+ async readProfile(input) {
402
+ if (!PROFILE_ID_PATTERN.test(input.profile_id))
403
+ throw new DatasetStoreError('profile_invalid', 'profile_id is invalid');
404
+ const root = this.readRoot(input.session);
405
+ if (!root || !this.fs)
406
+ throw new DatasetStoreError('filesystem_unavailable', 'workspace filesystem is unavailable');
407
+ let text;
408
+ try {
409
+ const target = await this.resolveContained(`${PROFILES_SUBDIR}/${input.profile_id}/${PROFILE_FILE}`, root, input.signal);
410
+ text = await this.fs.readText(target, input.signal);
411
+ }
412
+ catch (error) {
413
+ if (errorCodeOf(error) === 'FS_NOT_FOUND')
414
+ throw new DatasetStoreError('profile_not_found', `profile ${input.profile_id} was not found`);
415
+ if (error instanceof DatasetStoreError)
416
+ throw error;
417
+ throw new DatasetStoreError('profile_invalid', 'profile.json could not be read');
418
+ }
419
+ let parsed;
420
+ try {
421
+ parsed = JSON.parse(text);
422
+ }
423
+ catch {
424
+ throw new DatasetStoreError('profile_invalid', 'profile.json is not valid JSON');
425
+ }
426
+ if (!isRecord(parsed) || !isRecord(parsed.ref))
427
+ throw new DatasetStoreError('profile_invalid', 'profile.json is missing its ref');
428
+ const ref = parsed.ref;
429
+ if (typeof ref.profile_id !== 'string' || ref.profile_id !== input.profile_id) {
430
+ throw new DatasetStoreError('profile_invalid', 'profile ref does not match its directory');
431
+ }
432
+ if (ref.session_id !== sessionScopeFor(input.session)) {
433
+ throw new DatasetStoreError('dataset_session_mismatch', 'profile belongs to another session scope');
434
+ }
435
+ if (typeof ref.retention_until === 'number' && ref.retention_until <= this.now()) {
436
+ throw new DatasetStoreError('profile_expired', `profile ${input.profile_id} has expired`);
437
+ }
438
+ return { ref, profile: validateProfile(parsed.profile) };
439
+ }
320
440
  /**
321
441
  * Host-internal presentation read (charts). The returned rows must never enter any agent message,
322
442
  * tool result or model context; this is the only path that hands raw rows outside the store.
@@ -1146,6 +1266,8 @@ function validateStoredDatasetManifest(value, datasetId) {
1146
1266
  return undefined;
1147
1267
  if (value.time_coverage !== undefined && !validTimeCoverage(value.time_coverage))
1148
1268
  return undefined;
1269
+ if (value.envelope !== undefined && !validEnvelope(value.envelope))
1270
+ return undefined;
1149
1271
  const ref = {
1150
1272
  dataset_id: value.dataset_id,
1151
1273
  task_id: value.task_id,
@@ -1160,6 +1282,7 @@ function validateStoredDatasetManifest(value, datasetId) {
1160
1282
  retention_until: value.retention_until,
1161
1283
  params_digest: value.params_digest,
1162
1284
  ...(value.time_coverage === undefined ? {} : { time_coverage: value.time_coverage }),
1285
+ ...(value.envelope === undefined ? {} : { envelope: value.envelope }),
1163
1286
  };
1164
1287
  return {
1165
1288
  ...ref,
@@ -29,4 +29,4 @@ export interface DataCollectorDiagnostics {
29
29
  }
30
30
  export declare function registerDataCollectorTools(ctx: Context, hub: DataCollectorHub, diagnostics?: DataCollectorDiagnostics): void;
31
31
  /** Model-visible DatasetRef field whitelist (tests and host assertions). */
32
- export declare const DATASET_REF_FIELDS: readonly ["dataset_id", "task_id", "session_id", "artifact_ref", "format", "capability", "source_label", "schema", "row_count", "captured_at", "retention_until", "params_digest", "time_coverage"];
32
+ export declare const DATASET_REF_FIELDS: readonly ["dataset_id", "task_id", "session_id", "artifact_ref", "format", "capability", "source_label", "schema", "row_count", "captured_at", "retention_until", "params_digest", "time_coverage", "envelope"];
@@ -44,6 +44,7 @@ const datasetRefSchema = () => jsonObject({
44
44
  captured_at: { type: 'integer' },
45
45
  retention_until: { type: 'integer' },
46
46
  params_digest: { type: 'string' },
47
+ envelope: { type: 'object', additionalProperties: true },
47
48
  time_coverage: {
48
49
  type: 'object',
49
50
  properties: {
@@ -145,7 +146,7 @@ export function registerDataCollectorTools(ctx, hub, diagnostics) {
145
146
  return;
146
147
  const retryBudget = new UpstreamRetryBudget();
147
148
  const registrations = [
148
- tool('request_data', '向数据管道请求数据:宿主先按 capability+params 校验当前 session 的已验证 manifest;force_refresh=false 或省略且命中未过期、满足该来源缓存新鲜度的 Dataset 时直接返回已有 DatasetRef,不访问上游;force_refresh=true 才重新取数并生成新的不可变 Dataset(默认保留 7 天),绝不覆盖旧 Dataset。明确要现在/最新的行情快照时请用 force_refresh=true,7 天是保留期而非实时新鲜度。本工具只返回 DatasetRef(dataset_id / artifact_ref / schema / row_count / captured_at / retention_until 等元数据),绝不返回原始数据行。capability 必须是 list_capabilities 返回的短能力名(如 ticker_search / quote / history / trading_calendar),params 必须按 describe_capability({ capability }) 返回的 input_schema 填写。若返回 request_params_invalid,先重新调用 describe_capability({ capability: "<当前能力名>" }),再按 schema 修正并重试一次;不要凭记忆猜参数。可重试上游失败(限流、网络、超时、5xx)对同一 capability 最多 3 次尝试;返回 upstream_retry_exhausted 后停止重试,改用等价能力或回告主 Agent,不要用 wait_agent 等上游恢复。task_id 必须由主 Agent 在本轮委派前确定,并在所有子 Agent 与最终报告中原样复用;不要由 data_collector 自行生成。相同 capability+params 的并发请求合并为同一次执行。当前 workspace 只读或落盘失败时抛错 workspace_not_writable(绝不退化为内存假成功)。请求归属自动记为当前 delegated child session,不接收 requester_agent_id 参数。', jsonObject({
149
+ tool('request_data', '向数据管道请求数据:宿主先按 capability+params 校验当前 session 的已验证 manifest;force_refresh=false 或省略且命中未过期、满足该来源缓存新鲜度的 Dataset 时直接返回已有 DatasetRef,不访问上游;force_refresh=true 才重新取数并生成新的不可变 Dataset(默认保留 7 天),绝不覆盖旧 Dataset。明确要现在/最新的行情快照时请用 force_refresh=true,7 天是保留期而非实时新鲜度。本工具只返回 DatasetRef(dataset_id / artifact_ref / schema / row_count / captured_at / retention_until 等元数据,以及 envelope——响应根级的日期/钳制标记/计算时间等标量,若有),绝不返回原始数据行。envelope 是核对口径用的(例如 requested_date_clamped=true 表示上游把请求日夹到了最近交易日),不是行数据、不能 query。capability 必须是 list_capabilities 返回的短能力名(如 ticker_search / quote / history / trading_calendar),params 必须按 describe_capability({ capability }) 返回的 input_schema 填写。若返回 request_params_invalid,先重新调用 describe_capability({ capability: "<当前能力名>" }),再按 schema 修正并重试一次;不要凭记忆猜参数。可重试上游失败(限流、网络、超时、5xx)对同一 capability 最多 3 次尝试;返回 upstream_retry_exhausted 后停止重试,改用等价能力或回告主 Agent,不要用 wait_agent 等上游恢复。task_id 必须由主 Agent 在本轮委派前确定,并在所有子 Agent 与最终报告中原样复用;不要由 data_collector 自行生成。相同 capability+params 的并发请求合并为同一次执行。当前 workspace 只读或落盘失败时抛错 workspace_not_writable(绝不退化为内存假成功)。请求归属自动记为当前 delegated child session,不接收 requester_agent_id 参数。', jsonObject({
149
150
  capability: { type: 'string' },
150
151
  params: freeObject,
151
152
  force_refresh: { type: 'boolean' },
@@ -292,5 +293,5 @@ export function registerDataCollectorTools(ctx, hub, diagnostics) {
292
293
  export const DATASET_REF_FIELDS = [
293
294
  'dataset_id', 'task_id', 'session_id', 'artifact_ref', 'format',
294
295
  'capability', 'source_label', 'schema', 'row_count', 'captured_at',
295
- 'retention_until', 'params_digest', 'time_coverage',
296
+ 'retention_until', 'params_digest', 'time_coverage', 'envelope',
296
297
  ];
@@ -7,9 +7,10 @@
7
7
  export declare const DATA_CONTRACT_SECTION = "capital:data-contract";
8
8
  /** Just before the selected-skill brief (order 60). */
9
9
  export declare const DATA_CONTRACT_ORDER = 59;
10
- export declare function dataContractSection(): {
10
+ export interface DataContractSection {
11
11
  name: string;
12
12
  order: number;
13
13
  interpolate: false;
14
14
  text: string;
15
- };
15
+ }
16
+ export declare function dataContractSection(role?: string): DataContractSection;
@@ -21,6 +21,22 @@ const TEXT = `# 数据边界
21
21
  每个数字都要带出处(场所、文档名、文档日期、accession 或该次检索返回的链接)、取数路径与缺口。缺字段就点名缺哪个并停止该字段下的分析,不估算、不回填;用户粘贴的材料标 pasted by user,不因此提高置信度。
22
22
 
23
23
  skill 正文只写"要什么证据",不写服务商、密钥、URL、下载步骤或脚本命令。`;
24
- export function dataContractSection() {
25
- return { name: DATA_CONTRACT_SECTION, order: DATA_CONTRACT_ORDER, interpolate: false, text: TEXT };
24
+ /**
25
+ * The senior analyst has no delegation right: its inputs arrive as an AnalysisSnapshot, and every
26
+ * request for more goes through the lead. Same section name, different text — one home per role.
27
+ */
28
+ const SENIOR_TEXT = `# 数据边界
29
+
30
+ 你的输入由宿主冻结的 \`AnalysisSnapshot\` 给出:Dataset / profile / 证据都以 opaque ref 出现,快照在前、分析在后。你不取数、不检索、不读原始 rows,也没有 shell 或文件入口。
31
+
32
+ - 缺数据(快照里没有的字段、期间或来源)→ 经主 Agent 发 \`analysis_data_request\`,写清标的、字段、期间与用途;由主 Agent 决定是否扩大范围。
33
+ - 需要补计算(用快照里已有的 Dataset/profile)→ 也经主 Agent 转交,并在请求里带 task_id 与要算的口径;不自己找 data_collector / web_retriever。
34
+ - \`run_analysis\` 只返回指标、假设、缺口与 run ref;原始 rows 留在快照的宿主副本里,不会进你的上下文。
35
+
36
+ 每个数字都要能被宿主追溯:claim 的 \`number_anchors\`、\`calculations\` 必须指向快照里的 dataset / profile / evidence 或本次计算,否则 \`submit_analysis\` 会拒。缺字段就点名缺哪个并写进 \`data_gaps\`,不估算、不回填、不用训练记忆补数字。用户粘贴的材料标 pasted by user,不因此提高置信度。
37
+
38
+ skill 正文只写"要什么证据",不写服务商、密钥、URL、下载步骤或脚本命令。`;
39
+ export function dataContractSection(role) {
40
+ const text = role === 'senior_analyst' ? SENIOR_TEXT : TEXT;
41
+ return { name: DATA_CONTRACT_SECTION, order: DATA_CONTRACT_ORDER, interpolate: false, text };
26
42
  }
@@ -36,3 +36,8 @@ export declare const DATA_COLLECTION_PRESET_IDS: readonly string[];
36
36
  export declare const DATASET_READING_PRESET_IDS: readonly string[];
37
37
  /** May issue `chart_source_ref` for chart reads. */
38
38
  export declare const CHART_SOURCE_PRESET_IDS: readonly string[];
39
+ /**
40
+ * May call the `tools/analysis` family. The senior analyst consumes snapshot refs and never reads
41
+ * raw rows, so it is deliberately absent from `DATASET_READING_PRESET_IDS` above.
42
+ */
43
+ export declare const ANALYSIS_PRESET_IDS: readonly string[];
package/lib/preset-ids.js CHANGED
@@ -28,6 +28,7 @@ export function isCapitalPresetId(id) {
28
28
  export const INTERNAL_ROLE_PRESET_IDS = [
29
29
  ROLE_PRESET_IDS.junior,
30
30
  ROLE_PRESET_IDS.specialist,
31
+ ROLE_PRESET_IDS.analyst,
31
32
  ];
32
33
  const INTERNAL_ROLE_PRESET_ID_SET = new Set(INTERNAL_ROLE_PRESET_IDS);
33
34
  export function isInternalRolePresetId(id) {
@@ -41,6 +42,11 @@ export function isInternalRolePresetId(id) {
41
42
  * data and chart layers must not depend on the agents layer.
42
43
  */
43
44
  export const DATA_COLLECTION_PRESET_IDS = [ROLE_PRESET_IDS.collector];
44
- export const DATASET_READING_PRESET_IDS = [ROLE_PRESET_IDS.junior, ROLE_PRESET_IDS.analyst];
45
+ export const DATASET_READING_PRESET_IDS = [ROLE_PRESET_IDS.junior];
45
46
  /** May issue `chart_source_ref` for chart reads. */
46
47
  export const CHART_SOURCE_PRESET_IDS = [ROLE_PRESET_IDS.junior];
48
+ /**
49
+ * May call the `tools/analysis` family. The senior analyst consumes snapshot refs and never reads
50
+ * raw rows, so it is deliberately absent from `DATASET_READING_PRESET_IDS` above.
51
+ */
52
+ export const ANALYSIS_PRESET_IDS = [ROLE_PRESET_IDS.analyst];
@@ -2,7 +2,13 @@ export type PythonRuntimeErrorCode = 'unsupported-platform' | 'manifest-invalid'
2
2
  export declare class PythonRuntimeError extends Error {
3
3
  readonly code: PythonRuntimeErrorCode;
4
4
  readonly diagnostics?: string;
5
- constructor(code: PythonRuntimeErrorCode, message?: string, diagnostics?: string);
5
+ /**
6
+ * Stable analysis code raised by a reviewed module (e.g. `analysis_input_invalid`). The worker
7
+ * reports it because a module cannot throw a TypeScript error; `script-failed` alone would hide
8
+ * "this input shape is unsupported" behind "the module crashed".
9
+ */
10
+ readonly analysisCode?: string;
11
+ constructor(code: PythonRuntimeErrorCode, message?: string, diagnostics?: string, analysisCode?: string);
6
12
  }
7
13
  export declare function isPythonRuntimeError(value: unknown): value is PythonRuntimeError;
8
14
  export declare function messageOf(value: unknown): string;
@@ -21,11 +21,19 @@ const MESSAGES = {
21
21
  export class PythonRuntimeError extends Error {
22
22
  code;
23
23
  diagnostics;
24
- constructor(code, message, diagnostics) {
24
+ /**
25
+ * Stable analysis code raised by a reviewed module (e.g. `analysis_input_invalid`). The worker
26
+ * reports it because a module cannot throw a TypeScript error; `script-failed` alone would hide
27
+ * "this input shape is unsupported" behind "the module crashed".
28
+ */
29
+ analysisCode;
30
+ constructor(code, message, diagnostics, analysisCode) {
25
31
  super(message ?? MESSAGES[code]);
26
32
  this.name = 'PythonRuntimeError';
27
33
  this.code = code;
28
34
  this.diagnostics = diagnostics;
35
+ if (analysisCode !== undefined)
36
+ this.analysisCode = analysisCode;
29
37
  }
30
38
  }
31
39
  export function isPythonRuntimeError(value) {
@@ -35,6 +35,28 @@ export interface DataScriptResult {
35
35
  pythonVersion: string;
36
36
  durationMs: number;
37
37
  }
38
+ export interface RunAnalysisModuleOptions {
39
+ /** Absolute directory of the reviewed module inside the package. */
40
+ moduleDir: string;
41
+ entrypoint: string;
42
+ /** Absolute run directory the worker reads `request.json` from and writes `result.json` into. */
43
+ runDir: string;
44
+ /** Absolute `inputs/` directory of the snapshot (staged dataset/profile/evidence copies). */
45
+ inputsDir: string;
46
+ capabilities: readonly string[];
47
+ limits: {
48
+ max_input_rows: number;
49
+ max_output_bytes: number;
50
+ max_log_bytes: number;
51
+ };
52
+ timeoutMs: number;
53
+ signal?: AbortSignal;
54
+ }
55
+ export interface AnalysisModuleRunResult {
56
+ result: unknown;
57
+ pythonVersion: string;
58
+ durationMs: number;
59
+ }
38
60
  export declare class PythonRuntimeManager {
39
61
  readonly manifest: RuntimeManifest;
40
62
  readonly dshHome: string;
@@ -81,6 +103,14 @@ export declare class PythonRuntimeManager {
81
103
  * an extra `--site-packages` entry so no pip/venv/pack is involved.
82
104
  */
83
105
  runDataScript(options: RunDataScriptOptions): Promise<DataScriptResult>;
106
+ /**
107
+ * Run one reviewed analysis module and return the object it wrote.
108
+ *
109
+ * The child gets a run directory inside the workspace: `request.json` is already there (the store
110
+ * wrote it), and the module's `outputs/` and `logs/` land beside it. The run directory is not
111
+ * deleted here — it is the audit trail; retention is the analysis layer's decision.
112
+ */
113
+ runAnalysisModule(options: RunAnalysisModuleOptions): Promise<AnalysisModuleRunResult>;
84
114
  resolve(packs?: unknown): Promise<RuntimeHandle>;
85
115
  remove(pack: PackName): Promise<void>;
86
116
  dispose(): Promise<void>;
@@ -1,4 +1,5 @@
1
1
  import { chmod, mkdir, readFile, rename, rm, stat, writeFile } from 'node:fs/promises';
2
+ import { tmpdir } from 'node:os';
2
3
  import { randomUUID } from 'node:crypto';
3
4
  import { dirname, join, resolve } from 'node:path';
4
5
  import { fileURLToPath, pathToFileURL } from 'node:url';
@@ -18,6 +19,7 @@ const PYTHON_VENDOR_DIR = fileURLToPath(new URL('../../python/vendor', import.me
18
19
  const DATA_SCRIPT_ID = /^[a-z0-9_]+$/u;
19
20
  const DATA_RUN_DIR = 'data-runs';
20
21
  const DIAGNOSTIC_TAIL_CHARS = 2_000;
22
+ const ANALYSIS_ENTRYPOINT = /^[A-Za-z0-9_.-]{1,64}$/u;
21
23
  function recordOf(value) {
22
24
  return typeof value === 'object' && value !== null && !Array.isArray(value) ? value : undefined;
23
25
  }
@@ -592,6 +594,92 @@ export class PythonRuntimeManager {
592
594
  await rm(runDir, { recursive: true, force: true }).catch(() => undefined);
593
595
  }
594
596
  }
597
+ /**
598
+ * Run one reviewed analysis module and return the object it wrote.
599
+ *
600
+ * The child gets a run directory inside the workspace: `request.json` is already there (the store
601
+ * wrote it), and the module's `outputs/` and `logs/` land beside it. The run directory is not
602
+ * deleted here — it is the audit trail; retention is the analysis layer's decision.
603
+ */
604
+ async runAnalysisModule(options) {
605
+ const entrypoint = typeof options?.entrypoint === 'string' ? options.entrypoint : '';
606
+ if (!ANALYSIS_ENTRYPOINT.test(entrypoint) || entrypoint.includes('..')) {
607
+ throw new PythonRuntimeError('invalid-request', `分析模块入口名不合法:${JSON.stringify(entrypoint)}`);
608
+ }
609
+ if (typeof options?.runDir !== 'string' || typeof options?.inputsDir !== 'string'
610
+ || typeof options?.moduleDir !== 'string') {
611
+ throw new PythonRuntimeError('invalid-request', '分析模块运行需要绝对 runDir / inputsDir / moduleDir');
612
+ }
613
+ const timeoutMs = options.timeoutMs;
614
+ if (!Number.isSafeInteger(timeoutMs) || timeoutMs <= 0) {
615
+ throw new PythonRuntimeError('invalid-request', 'timeoutMs 必须是正整数。');
616
+ }
617
+ const signal = options.signal;
618
+ const handle = await this.resolveDataRuntime();
619
+ const sitePackages = [...handle.sitePackages];
620
+ if (await exists(PYTHON_VENDOR_DIR))
621
+ sitePackages.push(PYTHON_VENDOR_DIR);
622
+ // The cache root can be mounted read-only for the running process; the child only needs a
623
+ // writable HOME/TMPDIR, and the run directory itself already lives in the workspace.
624
+ const homeDir = join(tmpdir(), 'cg-analysis-home');
625
+ const tempDir = join(tmpdir(), 'cg-analysis-tmp');
626
+ await mkdir(homeDir, { recursive: true, mode: 0o700 });
627
+ await mkdir(tempDir, { recursive: true, mode: 0o700 });
628
+ const env = pythonChildEnv({ pythonDir: dirname(handle.python), homeDir, tempDir, baseEnv: process.env });
629
+ const args = [
630
+ ...pythonFlags,
631
+ this.workerPath,
632
+ 'analysis',
633
+ ...sitePackages.flatMap((item) => ['--site-packages', item]),
634
+ '--run-dir',
635
+ options.runDir,
636
+ '--module-dir',
637
+ options.moduleDir,
638
+ '--inputs-dir',
639
+ options.inputsDir,
640
+ '--entrypoint',
641
+ entrypoint,
642
+ '--capabilities',
643
+ options.capabilities.join(','),
644
+ '--limits',
645
+ JSON.stringify({
646
+ max_input_rows: options.limits.max_input_rows,
647
+ max_output_bytes: options.limits.max_output_bytes,
648
+ max_log_bytes: options.limits.max_log_bytes,
649
+ }),
650
+ ];
651
+ const worker = await this.runWorker({
652
+ python: handle.python,
653
+ args,
654
+ cwd: options.runDir,
655
+ env,
656
+ timeoutMs,
657
+ ...(signal === undefined ? {} : { signal }),
658
+ });
659
+ if (worker.spawnError !== undefined) {
660
+ throw new PythonRuntimeError('script-failed', `启动 Python 失败:${worker.spawnError}`, diagnosticTail(worker.stderr));
661
+ }
662
+ if (worker.timedOut)
663
+ throw new PythonRuntimeError('timeout', `分析模块超时(${timeoutMs}ms)。`, diagnosticTail(worker.stderr));
664
+ if (worker.aborted)
665
+ throw new PythonRuntimeError('cancelled', undefined, diagnosticTail(worker.stderr));
666
+ const executed = recordOf(await readJson(join(options.runDir, 'result.json')));
667
+ if (executed === undefined) {
668
+ throw new PythonRuntimeError('script-failed', `分析模块没有写出 result.json(退出码 ${String(worker.code)})。`, diagnosticTail(worker.stderr || worker.stdout));
669
+ }
670
+ const failure = recordOf(executed.error);
671
+ if (executed.ok !== true) {
672
+ const workerMessage = typeof failure?.message === 'string' && failure.message.trim() !== '' ? failure.message.trim() : undefined;
673
+ const message = lastStderrLine(worker.stderr) ?? workerMessage ?? `分析模块退出码 ${String(worker.code)}。`;
674
+ const analysisCode = typeof failure?.code === 'string' && failure.code.startsWith('analysis_') ? failure.code : undefined;
675
+ throw new PythonRuntimeError('script-failed', message, failureDiagnostics(worker, failure), analysisCode);
676
+ }
677
+ return {
678
+ result: executed.result,
679
+ pythonVersion: typeof executed.python === 'string' ? executed.python : handle.pythonVersion,
680
+ durationMs: typeof executed.durationMs === 'number' && Number.isFinite(executed.durationMs) ? executed.durationMs : 0,
681
+ };
682
+ }
595
683
  async resolve(packs = ['base']) {
596
684
  const names = normalizePackNames(packs);
597
685
  const target = this.targetId();
@@ -28,7 +28,11 @@ export async function runWorkerProcess(options) {
28
28
  setTimeout(() => { void killTree(child.pid, child, 'SIGKILL'); }, 2_000).unref?.();
29
29
  }, options.timeoutMs);
30
30
  timer.unref?.();
31
- const abort = () => { void killTree(child.pid, child, 'SIGTERM'); };
31
+ // Abort escalates once: a child that ignores SIGTERM would keep the workspace run directory open.
32
+ const abort = () => {
33
+ void killTree(child.pid, child, 'SIGTERM');
34
+ setTimeout(() => { void killTree(child.pid, child, 'SIGKILL'); }, 5_000).unref?.();
35
+ };
32
36
  options.signal?.addEventListener('abort', abort, { once: true });
33
37
  const finish = (code) => {
34
38
  if (settled)
@@ -19,7 +19,7 @@ export function apply(ctx, config = {}) {
19
19
  let lastRenderError;
20
20
  ctx.effect(() => {
21
21
  // Every role that can load a skill also needs the boundary that says where its data comes from.
22
- const disposeContract = ctx.systemPrompt.section(dataContractSection());
22
+ const disposeContract = ctx.systemPrompt.section(dataContractSection(role));
23
23
  const dispose = ctx.systemPrompt.section({
24
24
  name: SECTION_NAME,
25
25
  order: SECTION_ORDER,