📝 docs(tsl-api): resolve backtesting return contract

This commit is contained in:
csh
2026-08-25 13:16:45 +08:00
parent d1568c02cd
commit 9c8d77e1c4
7 changed files with 834 additions and 56 deletions
@@ -98,11 +98,46 @@
},
{
"api": "tsBackTesting.FGroupType",
"role": "candidate_mode_discriminator",
"role": "return_schema_discriminator",
"contract_evidence_required": true,
"evidence": [
"module/ts-backtesting.md#fgrouptype"
]
},
{
"api": "tsBackTesting.FRateType",
"role": "ratio_allocation_mode",
"evidence": [
"module/ts-backtesting.md#fratetype"
]
},
{
"api": "tsBackTesting.FPriceType",
"role": "execution_price_mode",
"evidence": [
"module/ts-backtesting.md#fpricetype"
]
},
{
"api": "tsBackTesting.FFeeType",
"role": "fee_input_mode",
"evidence": [
"module/ts-backtesting.md#ffeetype"
]
},
{
"api": "tsBackTesting.FOpenVolType",
"role": "quantity_open_size_mode",
"evidence": [
"module/ts-backtesting.md#fopenvoltype"
]
},
{
"api": "tsBackTesting.FCloseVolType",
"role": "quantity_close_size_mode",
"evidence": [
"module/ts-backtesting.md#fclosevoltype"
]
}
],
"hooks": [
@@ -198,10 +233,394 @@
"contracts": [
{
"id": "ts-backtesting-trade-order",
"status": "incomplete",
"status": "resolved",
"callback": "tsBackTesting.GetTradeOrder",
"reason": "The reference states target holdings or trade details but does not yet define the mode-specific record fields.",
"required_next_step": "Resolve the configuration-to-return-schema mapping before generating callback fields.",
"mode_discriminator": {
"api": "tsBackTesting.FGroupType"
},
"return_schemas": [
{
"id": "ratio-target-holdings",
"when": {
"FGroupType": "1"
},
"result_kind": "target_holdings",
"record_shape": "table_array",
"fields": [
{
"name": "截止日",
"type": "date_time",
"required": true,
"pdf_non_empty": true
},
{
"name": "代码",
"type": "string",
"required": true,
"pdf_non_empty": true
},
{
"name": "方向",
"type": "integer",
"required": false,
"default": "1",
"pdf_non_empty": true,
"values": {
"0": "short",
"1": "long"
}
},
{
"name": "比例(%)",
"type": "numeric",
"pdf_non_empty": true,
"required_when": [
{
"field": "FRateType",
"equals": [
"-1"
]
}
]
},
{
"name": "成交价",
"type": "numeric",
"pdf_non_empty": false,
"required_when": [
{
"field": "FPriceType",
"equals": [
"-1"
]
}
],
"description": "Provide when FPriceType=-1; otherwise the framework selects the execution price."
},
{
"name": "乘数",
"type": "numeric",
"required": false,
"pdf_non_empty": false,
"default": "1_or_instrument_default"
},
{
"name": "保证金比例(%)",
"type": "numeric",
"required": false,
"pdf_non_empty": false,
"default": "100_or_instrument_default"
},
{
"name": "开仓费率(%)",
"type": "numeric",
"required": false,
"pdf_non_empty": true,
"used_when": [
{
"field": "FFeeType",
"equals": [
"1"
]
}
],
"fallback": "tsBackTesting.StockFee"
},
{
"name": "平仓费率(%)",
"type": "numeric",
"required": false,
"pdf_non_empty": true,
"used_when": [
{
"field": "FFeeType",
"equals": [
"1"
]
}
],
"fallback": "tsBackTesting.StockFee"
}
],
"alternate_returns": [
{
"type": "empty_array",
"meaning": "clear_all_positions"
},
{
"type": "non_array",
"meaning": "skip_current_rebalance",
"documented_examples": [
-1,
1
]
}
],
"evidence": [
"module/ts-backtesting.md#gettradeorderv_end_t"
]
},
{
"id": "quantity-trade-details",
"when": {
"FGroupType": "2"
},
"result_kind": "trade_details",
"record_shape": "table_array",
"fields": [
{
"name": "截止日",
"type": "date_time",
"required": true,
"pdf_non_empty": true
},
{
"name": "代码",
"type": "string",
"required": true,
"pdf_non_empty": true
},
{
"name": "方向",
"type": "integer",
"required": false,
"default": "1",
"pdf_non_empty": true,
"values": {
"0": "short",
"1": "long"
}
},
{
"name": "动作",
"type": "integer",
"required": true,
"compat_default": "0",
"pdf_non_empty": true,
"values": {
"0": "open",
"1": "close",
"32": "build_option_group",
"33": "unlock_option_group"
}
},
{
"name": "成交量",
"type": "numeric",
"pdf_non_empty": true,
"required_when": [
{
"field": "FOpenVolType",
"equals": [
"1"
],
"record_when": {
"动作": [
"0"
]
}
},
{
"field": "FCloseVolType",
"equals": [
"1"
],
"record_when": {
"动作": [
"1"
]
}
}
],
"record_required_when": {
"动作": [
"32",
"33"
]
}
},
{
"name": "成交价",
"type": "numeric",
"pdf_non_empty": true,
"required_when": [
{
"field": "FPriceType",
"equals": [
"-1"
]
}
],
"record_required_when": {
"动作": [
"32",
"33"
]
},
"record_constraint_when": {
"动作": {
"32": "greater_than_zero",
"33": "greater_than_zero"
}
}
},
{
"name": "资金",
"type": "numeric",
"required_when": [
{
"field": "FOpenVolType",
"equals": [
"2"
],
"record_when": {
"动作": [
"0"
]
}
}
]
},
{
"name": "剩余资金占比(%)",
"type": "numeric",
"required_when": [
{
"field": "FOpenVolType",
"equals": [
"3"
],
"record_when": {
"动作": [
"0"
]
}
}
]
},
{
"name": "平仓数量占比(%)",
"type": "numeric",
"required_when": [
{
"field": "FCloseVolType",
"equals": [
"2"
],
"record_when": {
"动作": [
"1"
]
}
}
]
},
{
"name": "乘数",
"type": "numeric",
"required": false,
"pdf_non_empty": false,
"default": "1_or_instrument_default"
},
{
"name": "保证金比例(%)",
"type": "numeric",
"required": false,
"pdf_non_empty": false,
"default": "100_or_instrument_default"
},
{
"name": "费率(%)",
"type": "numeric",
"pdf_non_empty": true,
"used_when": [
{
"field": "FFeeType",
"equals": [
"1"
]
}
],
"record_value_when": {
"动作": {
"32": 0,
"33": 0
}
},
"fallback": "tsBackTesting.StockFee"
},
{
"name": "费用",
"type": "numeric",
"pdf_non_empty": false,
"required_when": [
{
"field": "FFeeType",
"equals": [
"2"
]
}
],
"record_value_when": {
"动作": {
"32": 0,
"33": 0
}
}
},
{
"name": "组 ID",
"type": "string",
"pdf_non_empty": true,
"required": false,
"applies_when": "option_group_strategy",
"required_in_extension": true,
"description": "Required as a non-empty shared identifier for option-group rows; empty for ungrouped single-leg rows."
},
{
"name": "组合类型",
"type": "string",
"pdf_non_empty": false,
"required": false,
"applies_when": "option_group_strategy",
"description": "Option strategy identifier such as CNSJC or STD; may be empty for single-leg or unrecognized combinations."
}
],
"record_rules": [
{
"when": "option_group_strategy",
"rule": "Return all component contracts for a group; rows in the same group share 组 ID, 动作, and 成交量."
},
{
"when": {
"动作": [
"0",
"32",
"33"
]
},
"rule": "Option-group opening, construction, and unlock records use a concrete 成交量; action 1 may instead use 平仓数量占比(%)."
},
{
"when": {
"动作": [
"0"
]
},
"rule": "Option-group opening (action 0) uses FOpenVolType=1; fixed-amount and remaining-funds modes are not supported for this action."
}
],
"alternate_returns": [
{
"type": "empty_array",
"meaning": "no_trade_at_current_time"
}
],
"evidence": [
"module/ts-backtesting.md#gettradeorderv_end_t"
]
}
],
"evidence": [
"module/ts-backtesting.md#gettradeorderv_end_t"
]
@@ -2658,6 +2658,7 @@ FClearCycle module ts-timing-evaluation FClearCycle module/ts-timing-evaluation.
FClose_N1 module ts-statistical-arbitrage FClose_N1 module/ts-statistical-arbitrage.md fclose_n1 上侧平仓标准差倍数 field instance public tsStatisticalArbitrage tsStatisticalArbitrage.FClose_N1
FClose_N2 module ts-statistical-arbitrage FClose_N2 module/ts-statistical-arbitrage.md fclose_n2 下侧平仓标准差倍数 field instance public tsStatisticalArbitrage tsStatisticalArbitrage.FClose_N2
FCloseFeeRate module ts-timing-evaluation FCloseFeeRate module/ts-timing-evaluation.md fclosefeerate 平仓费率(%) 0 field instance public tsTimingEvaluation tsTimingEvaluation.FCloseFeeRate
FCloseVolType module ts-backtesting FCloseVolType module/ts-backtesting.md fclosevoltype 数量类组合平仓数量模式 1:固定成交量法;2:可平仓数量占比法 field instance public tsBackTesting tsBackTesting.FCloseVolType
FcLowestFee module ts-backtesting FcLowestFee module/ts-backtesting.md fclowestfee 平仓最低费用 5.0 field instance public tsBackTesting tsBackTesting.FcLowestFee
FCombinations module ts-backtest-overfit-prob FCombinations module/ts-backtest-overfit-prob.md fcombinations 生成的子集组合 field instance public tsBacktestOverfitProb tsBacktestOverfitProb.FCombinations
FComFactorArr module ts-hg-data-process FComFactorArr module/ts-hg-data-process.md fcomfactorarr 合成因子库 array() field instance public ts_HGDataProcess ts_HGDataProcess.FComFactorArr
@@ -2782,7 +2783,7 @@ FFaRet module ts-factor-portfolio-optimizer FFaRet module/ts-factor-portfolio-op
FFaRets module ts-factor-portfolio-optimizer FFaRets module/ts-factor-portfolio-optimizer.md ffarets 因子收益序列 field instance public tsFactorPortfolioOptimizer tsFactorPortfolioOptimizer.FFaRets
FFeature module ts-persistence-of-fund FFeature module/ts-persistence-of-fund.md ffeature 基金业绩指标 field instance public ts_PersistenceOfFund ts_PersistenceOfFund.FFeature
FFeeRate module derivatives-analysis FFeeRate module/derivatives-analysis/option-delta-hedging.md ffeerate 交易费率百分比,默认值为 0 field instance public opDeltaHedging opDeltaHedging.FFeeRate
FFeeType module ts-backtesting FFeeType module/ts-backtesting.md ffeetype 费用类别 1:费率法 field instance public tsBackTesting tsBackTesting.FFeeType
FFeeType module ts-backtesting FFeeType module/ts-backtesting.md ffeetype 费用类别 1:费率法;2:费用法。比例类只能使用费率法;数量类可使用费率法或费用法 field instance public tsBackTesting tsBackTesting.FFeeType
FFeeType2 module ts-backtesting FFeeType2 module/ts-backtesting.md ffeetype2 比例类费率 1: 历史明细中查找开、 平仓费率 field instance public tsBackTesting tsBackTesting.FFeeType2
FfhExchangeRatetype module ts-backtesting FfhExchangeRatetype module/ts-backtesting.md ffhexchangeratetype 分红汇率类型 2:对应市场结算汇率中间价 field instance public tsBackTesting tsBackTesting.FfhExchangeRatetype
ffi_es dotnet financial ffi_es(w_p, x, f, delta, confidence_interval) dotnet/financial/financial_engineering-risk_model-application-risk_analysis-algorithm_layer.md ffi_es 金融 金融工程 风险模型 应用 风险分析 算法层 返回 获取 ES 返回期望损失ES function ffi_es
@@ -2824,7 +2825,7 @@ fgRight builtin graph fgRight() builtin/graph.md fgright 图形对象 图形 图
fgRightDown builtin graph fgRightDown() builtin/graph.md fgrightdown 图形对象 图形 图表 graph 对象 实例 object 右下 function fgRightDown
fgRightUp builtin graph fgRightUp() builtin/graph.md fgrightup 图形对象 图形 图表 graph 对象 实例 object 右上 function fgRightUp
FGroups module ts-multi-factor FGroups module/ts-multi-factor.md fgroups 五分位 field instance public tsMultiFactor tsMultiFactor.FGroups
FGroupType module ts-backtesting FGroupType module/ts-backtesting.md fgrouptype 组合类型 1:比例类组合 field instance public tsBackTesting tsBackTesting.FGroupType
FGroupType module ts-backtesting FGroupType module/ts-backtesting.md fgrouptype 组合类型 1:比例类组合2:数量类组合。期权不支持比例类回测 field instance public tsBackTesting tsBackTesting.FGroupType
FGroupType module ts-multi-factor FGroupType module/ts-multi-factor.md fgrouptype 分组方式 1:百分位 field instance public tsMultiFactor tsMultiFactor.FGroupType
fgUp builtin graph fgUp() builtin/graph.md fgup 图形对象 图形 图表 graph 对象 实例 object 上 function fgUp
Fh dotnet math Fh dotnet/math/optimization.md fh 二次型 field instance public tsOptimizer tsOptimizer.Fh
@@ -3149,6 +3150,7 @@ footerValue dotnet base footerValue(t, from_col, tocol, average_col_field, _type
FOpen_N1 module ts-statistical-arbitrage FOpen_N1 module/ts-statistical-arbitrage.md fopen_n1 上侧开仓标准差倍数 field instance public tsStatisticalArbitrage tsStatisticalArbitrage.FOpen_N1
FOpen_N2 module ts-statistical-arbitrage FOpen_N2 module/ts-statistical-arbitrage.md fopen_n2 下侧开仓标准差倍数 field instance public tsStatisticalArbitrage tsStatisticalArbitrage.FOpen_N2
FOpenFeeRate module ts-timing-evaluation FOpenFeeRate module/ts-timing-evaluation.md fopenfeerate 开仓费率(%) 0 field instance public tsTimingEvaluation tsTimingEvaluation.FOpenFeeRate
FOpenVolType module ts-backtesting FOpenVolType module/ts-backtesting.md fopenvoltype 数量类组合开仓数量模式 1:固定成交量法;2:固定金额法;3:剩余资金占比法 field instance public tsBackTesting tsBackTesting.FOpenVolType
FOPMaturityDate module derivatives-analysis FOPMaturityDate module/derivatives-analysis/option-instrument-indicators.md fopmaturitydate 到期月份序号;0 为全部,1 为近月,2 为次近月,依次类推 field instance public ts_Options_Screening ts_Options_Screening.FOPMaturityDate
FOPPZID module derivatives-analysis FOPPZID module/derivatives-analysis/option-instrument-indicators.md foppzid 期权品种或标的代码;空字符串表示不按品种筛选 field instance public ts_Options_Screening ts_Options_Screening.FOPPZID
FOpsId module ts-ops FOpsId module/ts-ops.md fopsid 服务标识 TS-OPS 服务 ID property instance public opsServer opsServer.FOpsId
@@ -3189,7 +3191,7 @@ FPriceRateTo0 module ts-backtesting FPriceRateTo0 module/ts-backtesting.md fpric
FPriceStep module bond-research FPriceStep module/bond-research/bond-price-segmentation.md fpricestep 价格频数分布步长,单位为元,默认 10 field instance public cb_PriceAndDeadlineData cb_PriceAndDeadlineData.FPriceStep
FPriceType module bond-research FPriceType module/bond-research/bond-price-segmentation.md fpricetype 统计最高价和最低价时使用的价格类型;0 为收盘价,1 为当日最高价或最低价 field instance public cb_PriceAndDeadlineData cb_PriceAndDeadlineData.FPriceType
FPriceType module factor-research FPriceType module/factor-research/index-chip-factors.md fpricetype 指数均价算法;支持算术平均、成交量加权、成交金额加权及调整后的成交量加权 field instance public ts_IndexChipDistribution ts_IndexChipDistribution.FPriceType
FPriceType module ts-backtesting FPriceType module/ts-backtesting.md fpricetype 成交价类别 3:日均价 field instance public tsBackTesting tsBackTesting.FPriceType
FPriceType module ts-backtesting FPriceType module/ts-backtesting.md fpricetype 成交价类别 -1:用户自定义;1:时点价格;2:收盘价;3:日均价;4:开盘价;5:系统昨收 field instance public tsBackTesting tsBackTesting.FPriceType
FpriceType module ts-multi-factor FpriceType module/ts-multi-factor.md fpricetype 成交价类别 2:收盘价 field instance public tsMultiFactor tsMultiFactor.FpriceType
FPrincDZ module ts-hg-risk-pca FPrincDZ module/ts-hg-risk-pca.md fprincdz 主成分对照 见 FPrincDZ 默认值 field instance public ts_HGRiskPCA ts_HGRiskPCA.FPrincDZ
FPurchaseRatio module fund-research FPurchaseRatio module/fund-research/fixed-amount-investment.md fpurchaseratio 申购费率,单位为百分比 field instance public ts_AIPBackTesting ts_AIPBackTesting.FPurchaseRatio
@@ -3229,7 +3231,7 @@ frameStocksMark_GetGrouptail module strategy-selection-tools frameStocksMark_Get
frameupdate dotnet base frameupdate(left, right, ons, type) dotnet/base/array.md frameupdate 数组 数据表 更新 缺失值 merge update table 按键字段用右表补充或更新左表中的缺失值,并直接修改左表 function frameupdate
framevaluecounts dotnet base framevaluecounts(data, countfieldname, iforder) dotnet/base/array.md framevaluecounts 数据表-计数 function framevaluecounts
FRateType module quick-back-testing FRateType module/quick-back-testing.md fratetype 比例类组合资金分配方式 4:等权重 field instance public quickBackTesting quickBackTesting.FRateType
FRateType module ts-backtesting FRateType module/ts-backtesting.md fratetype 比例类组合资金分配方式 4:等权重 field instance public tsBackTesting tsBackTesting.FRateType
FRateType module ts-backtesting FRateType module/ts-backtesting.md fratetype 比例类组合资金分配方式;-1:用户自定义比例;0/1/4/5/6/7 为系统配比;8:剩余资金等比例分配;默认 4:等权重 field instance public tsBackTesting tsBackTesting.FRateType
FRateType module ts-future-multifactor FRateType module/ts-future-multifactor.md fratetype 比例类型 4(等权) field instance public tsFutureMultiFactor tsFutureMultiFactor.FRateType
FRateType module ts-multi-factor FRateType module/ts-multi-factor.md fratetype 个股资金分配方法 4:等权重 field instance public tsMultiFactor tsMultiFactor.FRateType
FRatio module tinysoft-strategies FRatio module/tinysoft-strategies/market-cap-rotation.md fratio 买卖费率百分比,默认值为 0.1 field instance public tsLargeAndSmallTurning tsLargeAndSmallTurning.FRatio
Can't render this file because it is too large.
@@ -42,7 +42,7 @@
声明:field
组合类型 1:比例类组合
组合类型 1:比例类组合2:数量类组合。期权不支持比例类回测
可见性:`public`
@@ -82,7 +82,7 @@
声明:field
成交价类别 3:日均价
成交价类别 -1:用户自定义;1:时点价格;2:收盘价;3:日均价;4:开盘价;5:系统昨收
可见性:`public`
@@ -92,7 +92,27 @@
声明:field
费用类别 1:费率法
费用类别 1:费率法;2:费用法。比例类只能使用费率法;数量类可使用费率法或费用法
可见性:`public`
类型:integer
### `FOpenVolType`
声明:field
数量类组合开仓数量模式 1:固定成交量法;2:固定金额法;3:剩余资金占比法
可见性:`public`
类型:integer
### `FCloseVolType`
声明:field
数量类组合平仓数量模式 1:固定成交量法;2:可平仓数量占比法
可见性:`public`
@@ -102,7 +122,7 @@
声明:field
比例类组合资金分配方式 4:等权重
比例类组合资金分配方式;-1:用户自定义比例;0/1/4/5/6/7 为系统配比;8:剩余资金等比例分配;默认 4:等权重
可见性:`public`
@@ -631,7 +651,67 @@ return ret;
| --------- | --------- | -------------- |
| `v_end_t` | date_time | 日期,当前时点 |
返回:array
返回:通常为 `array`;比例类当前调仓日不调仓时,可返回非数组控制值
返回契约
`GetTradeOrder(v_end_t)` 的返回值是框架回调输入,不是固定列集合;记录字段由
`FGroupType` 及数量、费用和成交价配置共同决定。每行是二维数组中的一条记录。
比例类组合(`FGroupType := 1`)返回目标持仓记录:
| 字段 | 类型 | 标准非空 | 配置/省略规则 |
| --------------- | ---------- | -------- | ------------------------------------------------------ |
| `截止日` | `date_time` | 是 | 当前调仓时点,通常等于 `v_end_t` |
| `代码` | `string` | 是 | 目标持仓证券代码 |
| `方向` | `integer` | 是 | `1` 多单;`0` 空单;兼容省略时默认多单 |
| `比例(%)` | `numeric` | 是 | `FRateType := -1` 必须提供;系统配比时由框架计算 |
| `成交价` | `numeric` | 否 | 通常由 `FPriceType` 获取;自定义成交价时必须提供 |
| `乘数` | `numeric` | 否 | 省略时按品种或默认 `1` |
| `保证金比例(%)` | `numeric` | 否 | 省略时按品种或默认 `100` |
| `开仓费率(%)` | `numeric` | 是 | 省略时使用品种默认费率 |
| `平仓费率(%)` | `numeric` | 是 | 省略时使用品种默认费率 |
`名称` 可出现在用户导入数据或范例中,但不属于比例类必需契约字段。
数量类组合(`FGroupType := 2`)返回交易明细记录:
| 字段 | 类型 | 标准非空 | 配置/省略规则 |
| ------------------- | ---------- | -------- | ------------------------------------------------------ |
| `截止日` | `date_time` | 是 | 当前交易时点,通常等于 `v_end_t` |
| `代码` | `string` | 是 | 交易证券代码 |
| `方向` | `integer` | 是 | `1` 多单;`0` 空单;兼容省略时默认多单 |
| `动作` | `integer` | 是 | `0` 开仓;`1` 平仓;兼容省略时默认开仓 |
| `成交量` | `numeric` | 是 | 固定成交量时提供;期权动作 `0/32/33` 必须提供 |
| `成交价` | `numeric` | 是 | 标准交易明细应提供;系统价 `FPriceType` 可代取,自定义时必须提供 |
| `乘数` | `numeric` | 否 | 省略时按品种或默认值处理 |
| `保证金比例(%)` | `numeric` | 否 | 省略时按品种或默认值处理 |
| `费率(%)` | `numeric` | 是 | `FFeeType := 1`;省略时使用品种默认费率 |
| `资金` | `numeric` | 条件 | 开仓且 `FOpenVolType := 2` |
| `剩余资金占比(%)` | `numeric` | 条件 | 开仓且 `FOpenVolType := 3` |
| `平仓数量占比(%)` | `numeric` | 条件 | 平仓且 `FCloseVolType := 2` |
| `费用` | `numeric` | 条件 | `FFeeType := 2`;只适合数量类,直接提供单笔费用 |
`FOpenVolType`/`FCloseVolType` 决定成交量替代字段:开仓模式为 `2/3` 时分别提供 `资金`/`剩余资金占比(%)`,平仓模式为 `2` 时提供 `平仓数量占比(%)`。这些模式下不应再把 `成交量` 当作用户输入列。
`名称` 可出现在导入数据或范例中,但不属于数量类必需契约字段。
期权组合扩展(数量类专用):
| 字段 | 类型 | 规则 |
| ---------- | -------- | ---- |
| `组 ID` | `string` | 组合策略数据必有;未构成组合时为空字符串;同一组合的所有成分合约使用同一值 |
| `组合类型` | `string` | 组合策略标识,如 `CNSJC``STD`;未识别或单腿时可为空 |
- `动作 := 32` 表示申请构建组合,`动作 := 33` 表示组合解锁;框架后续可能标准化为 `34/35` 调入/调出数据。
- 对一个组合必须提供所有成分合约,且这些行的 `组 ID``动作``成交量` 相同。
- 期权动作 `0``32``33` 使用固定成交量法;动作 `1` 可使用固定成交量或可平仓数量占比法。
- 采用费率法时动作 `32/33``费率(%)``0`;采用费用法时对应 `费用``0`
控制返回:
- 数量类在当前时点无交易时返回空数组。
- 比例类返回空数组表示完全清仓;比例类某个调仓日不调仓时返回非数组控制值,不要将其解释为交易字段。
### `GetTA(v_end_t)`
@@ -2,6 +2,7 @@
"""Library for validating and resolving evidence-backed framework profiles."""
import json
from copy import deepcopy
from pathlib import Path
from lookup import (
@@ -87,6 +88,17 @@ def validate_source_ids(data, rows):
errors.append(
f"{section}[{entry_index}].evidence references unknown source {source}"
)
if section == "contracts" and isinstance(entry, dict):
for schema_index, schema in enumerate(
entry.get("return_schemas", [])
):
for source in evidence_set(schema):
if source not in known_sources:
errors.append(
f"contracts[{entry_index}].return_schemas"
f"[{schema_index}].evidence references unknown source "
f"{source}"
)
return errors
@@ -209,6 +221,54 @@ def validate_framework(framework, rows, codegen_root, index):
f"{framework['qualified_name']}.contracts[{contract_index}] "
f"references unknown source {source}"
)
if not isinstance(contract, dict) or contract.get("status") != "resolved":
continue
discriminator = contract.get("mode_discriminator")
if not isinstance(discriminator, dict) or not discriminator.get("api"):
errors.append(
f"{framework['qualified_name']}.contracts[{contract_index}] resolved "
"contracts must contain mode_discriminator.api"
)
continue
configured_apis = {
normalize(entry.get("api", ""))
for entry in framework.get("configuration", [])
if isinstance(entry, dict)
}
if normalize(discriminator["api"]) not in configured_apis:
errors.append(
f"{framework['qualified_name']}.contracts[{contract_index}]."
f"mode_discriminator.api {discriminator['api']!r} is not a "
"configuration member"
)
schemas = contract.get("return_schemas")
if not isinstance(schemas, list) or not schemas:
errors.append(
f"{framework['qualified_name']}.contracts[{contract_index}] resolved "
"contracts must contain return_schemas"
)
continue
discriminator_field = discriminator["api"].rsplit(".", 1)[-1]
seen_values = set()
for schema_index, schema in enumerate(schemas):
path = (
f"{framework['qualified_name']}.contracts[{contract_index}]."
f"return_schemas[{schema_index}]"
)
if not isinstance(schema, dict):
errors.append(f"{path} must be an object")
continue
value = schema.get("when", {}).get(discriminator_field)
if value is None or str(value).strip() == "":
errors.append(f"{path}.when must select {discriminator_field}")
elif str(value) in seen_values:
errors.append(f"{path}.when duplicates {discriminator_field}={value}")
else:
seen_values.add(str(value))
if not isinstance(schema.get("fields"), list) or not schema["fields"]:
errors.append(f"{path}.fields must be a non-empty array")
if not evidence_set(schema):
errors.append(f"{path}.evidence must contain at least one source id")
return errors
@@ -225,6 +285,47 @@ def validate_index(data, rows, codegen_root):
return errors
def contract_mode_mapping(contract, configuration_api):
discriminator = contract.get("mode_discriminator", {})
return (
contract.get("status") == "resolved"
and normalize(discriminator.get("api", "")) == normalize(configuration_api)
and isinstance(contract.get("return_schemas"), list)
)
def resolved_contract_packet(contract, config):
packet = deepcopy(contract)
discriminator = packet.get("mode_discriminator")
packet["selected_return_schema"] = None
if not isinstance(discriminator, dict) or not discriminator.get("api"):
return packet
field = discriminator["api"].rsplit(".", 1)[-1]
schemas = packet.get("return_schemas", [])
values = [
str(schema.get("when", {}).get(field))
for schema in schemas
if schema.get("when", {}).get(field) is not None
]
packet["mode_discriminator"] = {
**discriminator,
"field": field,
"values": values,
}
if field in config:
requested = str(config[field])
packet["selected_return_schema"] = next(
(
schema
for schema in schemas
if str(schema.get("when", {}).get(field)) == requested
),
None,
)
return packet
def scaffold_packet(framework, config):
configured_names = {
entry["api"].rsplit(".", 1)[-1]
@@ -245,7 +346,15 @@ def scaffold_packet(framework, config):
}
)
for entry in framework["configuration"]:
if entry.get("contract_evidence_required") and entry["api"].rsplit(".", 1)[-1] in config:
field = entry["api"].rsplit(".", 1)[-1]
if not entry.get("contract_evidence_required") or field not in config:
continue
mapped_contracts = [
contract
for contract in framework["contracts"]
if contract_mode_mapping(contract, entry["api"])
]
if not mapped_contracts:
diagnostics.append(
{
"code": "CONTRACT_MODE_UNRESOLVED",
@@ -258,6 +367,29 @@ def scaffold_packet(framework, config):
"source_ids": entry.get("evidence", []),
}
)
continue
requested = str(config[field])
available = {
str(schema.get("when", {}).get(field))
for contract in mapped_contracts
for schema in contract.get("return_schemas", [])
if schema.get("when", {}).get(field) is not None
}
if requested not in available:
diagnostics.append(
{
"code": "CONTRACT_MODE_UNKNOWN",
"severity": "error",
"message": (
f"{entry['api']}={requested!r} has no recorded return schema."
),
"next_action": (
"Use one of the documented mode values: "
+ ", ".join(sorted(available))
),
"source_ids": entry.get("evidence", []),
}
)
contract_status = "resolved"
for contract in framework["contracts"]:
if contract.get("status") != "resolved":
@@ -271,6 +403,15 @@ def scaffold_packet(framework, config):
"source_ids": contract.get("evidence", []),
}
)
contracts = [
resolved_contract_packet(contract, config)
for contract in framework["contracts"]
]
if any(
diagnostic["code"] in {"CONTRACT_MODE_UNKNOWN", "CONTRACT_MODE_UNRESOLVED"}
for diagnostic in diagnostics
):
contract_status = "incomplete"
return {
"status": "resolved",
"scaffold_status": "resolved",
@@ -285,6 +426,7 @@ def scaffold_packet(framework, config):
"state_apis": framework["state_apis"],
"execution": framework["execution"],
"result_apis": framework["result_apis"],
"contracts": contracts,
"diagnostics": diagnostics,
"evidence": framework.get("evidence", []),
}
@@ -38,6 +38,8 @@ python <this-skill-dir>/scripts/class_lookup.py \
- `scaffold_status=resolved` 只表示生命周期和成员引用完整。
- `contract_status` 不是 `resolved` 时,必须按 `diagnostics` 补齐模式与返回 schema 证据,
并停止生成回调字段。
- `contract_status=resolved` 时,`contracts[].return_schemas` 给出全部已验证模式;传入
`--config` 命中模式后,`contracts[].selected_return_schema` 给出当前配置对应的字段契约。
Framework Profile 只描述 API 协议,不定义 TSL 语法或代码结构。解析后的 Framework
Contract Packet 仅作为已验证的 API 事实输出。