Skip to main content

evorule_tcb/
executor.rs

1// SPDX-License-Identifier: AGPL-3.0-or-later
2// Copyright (C) 2026 EvoRule Project
3// This file is part of EvoRule, licensed under GNU Affero General Public License v3 or later.
4//! 元指令执行器 - 5 个元指令 + `io_request` 信号 + `enforce` 强制原语
5//!
6//! # 元指令列表
7//! - `set`:修改 payload 字段
8//! - `push`:推指令到队列前端
9//! - `branch`:条件执行子指令列表
10//! - `io_request`:产生 I/O 请求信号(不修改状态)
11//! - `enforce`:元规则强制原语(回归验证)——params.domain 匹配即返回 Halted 信号
12//!
13//! # 设计原则
14//! `io_request` 是"半元指令"——在执行器中硬编码识别,但行为完全由 JSON 参数驱动。
15//! 它不修改任何状态,仅返回 `MetaInstructionResult::IoRequired` 信号。
16
17use crate::domain::{declared_on_missing, evaluate_domain_outcome, DomainAttribution};
18use crate::error::TcbError;
19use crate::path::{parse_path_segments, resolve_path, resolve_path_mut, PathSegment};
20use crate::value::{JsonValue, ObjectMap};
21use alloc::format;
22use alloc::string::{String, ToString};
23use alloc::vec::Vec;
24
25/// 元指令执行器的最大嵌套深度
26pub const MAX_BRANCH_DEPTH: usize = 64;
27
28/// 单次状态转换允许执行的元指令总数上限(终止性宽度防线,M6)
29///
30/// 与 `MAX_BRANCH_DEPTH`(深度防线)、`MAX_TRANSFORM_RULES`(规则数防线)、
31/// `MAX_DOMAIN_DEPTH`(域递归防线)共同构成完整的终止性保证:
32/// 深度限制无法约束**宽度**(单条 branch 的子指令列表长度无上界),
33/// 本上限补齐该缺口——任意 core_eval 的执行路径指令总数有界。
34///
35/// 取值依据:`MAX_TRANSFORM_RULES`(128) × 单规则平均指令数(≤16) = 2048,
36/// 覆盖 ReAct 宪法的实际需求(每条规则 < 15 条指令)并留有余量。
37pub const MAX_TOTAL_META_INSTRUCTIONS: usize = 2048;
38
39/// 合法 core_eval 元指令类型权威清单(SSOT / C2)
40///
41/// 与下方 `execute_meta_instruction_budgeted` 的 dispatch 分支一一对应。
42/// 消费方(如 evorule-cli validate 的规则白名单)**必须引用本常量**,
43/// 禁止自行硬编码副本——防止 tcb 新增元指令时消费方误报合法规则。
44///
45/// # 漂移防线
46/// - 本表 → dispatch:`test_meta_instruction_types_ssot` 逐类型断言
47///   dispatch 不返回 `UnknownMetaInstruction`;
48/// - dispatch → 本表:新增 dispatch 分支时须同步更新本表并登记变更
49///   (该方向不可由枚举自动穷尽,靠 CR 门禁约束)。
50pub const META_INSTRUCTION_TYPES: &[&str] = &["branch", "set", "push", "io_request", "enforce"];
51
52/// 元指令执行结果
53#[derive(Debug, Clone, PartialEq)]
54pub enum MetaInstructionResult {
55    /// 正常执行,返回更新后的状态
56    State(JsonValue),
57    /// I/O 请求信号(立即传播,不继续执行后续指令)
58    IoRequired {
59        /// I/O 类型(如 "call_external"、"query_db")
60        io_type: String,
61        /// I/O 请求参数(路径引用已解析为具体值)
62        params: JsonValue,
63    },
64    /// 强制中断信号(`enforce` 原语命中,回归验证)
65    ///
66    /// 纯信号:立即向上传播,不携带状态;状态转换层据此返回
67    /// `TransitionResult::Halted`(违规指令被拒,此前状态修改随
68    /// 半成品纪律一并丢弃)。与 `IoRequired` 同为传播即停语义。
69    Halted {
70        /// 违规说明(enforce params.reason,供 Violation 事实审计回显)
71        reason: String,
72    },
73}
74
75/// 执行一条元指令,返回执行结果
76///
77/// 独立入口:每次调用获得满额执行预算(`MAX_TOTAL_META_INSTRUCTIONS`)。
78/// 状态转换层(`execute_transition`)使用 [`execute_meta_instruction_budgeted`]
79/// 在整棵规则树上共享单一预算。
80pub fn execute_meta_instruction(
81    instr: &JsonValue,
82    state: JsonValue,
83    depth: usize,
84) -> Result<MetaInstructionResult, TcbError> {
85    let mut budget = MAX_TOTAL_META_INSTRUCTIONS;
86    let mut hit = false;
87    let mut domain_attr = None;
88    execute_meta_instruction_budgeted(instr, state, depth, &mut budget, &mut hit, &mut domain_attr)
89}
90
91/// 执行一条元指令(受共享预算约束,M6 终止性宽度防线)
92///
93/// 每执行一条指令(含 branch 的子指令递归)消耗 1 个预算单位;
94/// 预算耗尽返回 `TooManyExecutedInstructions`。
95///
96/// # 命中归因(结构命中口径)
97///
98/// `hit_out` 在执行成功时写入该条指令是否**结构命中**:
99/// - 直接指令(set/push):执行成功即命中;
100/// - `io_request`:产生信号即命中;
101/// - `branch`:所选分支(on_true/on_false)**存在且非空**即命中——
102///   空数组或缺失分支不命中(无效果路径)。
103///
104/// 口径为**结构命中**而非副作用命中:与值是否实际变化无关(幂等重放
105/// 如 `set` 同值仍算命中),判定稳定且零状态对比开销。调用方在
106/// `Err` 返回时不得采信 `hit_out`(未定义)。递归子指令的命中
107/// 不计入顶层规则(命中粒度 = 顶层规则级,见 `TransitionResult`)。
108///
109/// # 域判定归因(专项-20261001 方案 2' v4,R1/R2 纪律)
110///
111/// `domain_attr_out` 在 branch/enforce 的域求值成功后写入三态归因
112/// (`DomainAttribution`:`DomainOutcome` 含 Missing 分类 + `on_missing`
113/// 声明值);其余指令类型不写入(保持 `None`)。
114/// - **R1 归因不回灌执行**:branch 走向仅由投影 bool(`Sat → true`,其余
115///   `→ false`)+ 规则文本 `on_missing` 静态声明决定;归因仅作审计用途。
116/// - **R2 半成品纪律**:`IoRequired`/`Halted` 不携带 `rule_hits`(转换层
117///   既有契约),中途归因同样不随半成品交付,以收敛后的重放结果为准。
118/// - 调用方在 `Err` 返回时不得采信 `domain_attr_out`(未定义)。
119/// - 递归子指令的域归因不计入顶层规则(同命中粒度:顶层规则级)。
120pub(crate) fn execute_meta_instruction_budgeted(
121    instr: &JsonValue,
122    state: JsonValue,
123    depth: usize,
124    budget: &mut usize,
125    hit_out: &mut bool,
126    domain_attr_out: &mut Option<DomainAttribution>,
127) -> Result<MetaInstructionResult, TcbError> {
128    // 预算检查:先扣减后执行(失败指令同样计入,防止用错误路径消耗无界资源)
129    if let Some(next) = budget.checked_sub(1) {
130        *budget = next;
131    } else {
132        return Err(TcbError::TooManyExecutedInstructions {
133            limit: MAX_TOTAL_META_INSTRUCTIONS,
134        });
135    }
136
137    let instr_type = instr
138        .get("type")
139        .and_then(|v| v.as_str())
140        .ok_or(TcbError::MissingField {
141            field: "type".to_string(),
142        })?;
143
144    match instr_type {
145        "set" => exec_set(instr, state)
146            .map(MetaInstructionResult::State)
147            .inspect(|_| *hit_out = true),
148        "push" => exec_push(instr, state)
149            .map(MetaInstructionResult::State)
150            .inspect(|_| *hit_out = true),
151        "branch" => exec_branch(instr, state, depth, budget, hit_out, domain_attr_out),
152        "io_request" => exec_io_request(instr, state).inspect(|_| *hit_out = true),
153        "enforce" => exec_enforce(instr, state, domain_attr_out).inspect(|result| {
154            // 结构命中口径:domain 求值为真(Halted 信号产生)即命中;
155            // 求值为假(noop 继续)不命中。
156            if matches!(result, MetaInstructionResult::Halted { .. }) {
157                *hit_out = true;
158            }
159        }),
160        _ => Err(TcbError::UnknownMetaInstruction {
161            meta_type: instr_type.to_string(),
162        }),
163    }
164}
165
166#[cfg(test)]
167mod executor_ssot_tests {
168    #![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
169    use super::*;
170
171    /// SSOT 漂移防线( / C2):
172    /// `META_INSTRUCTION_TYPES` 中每个类型都必须被 dispatch 实际处理
173    /// (不得返回 `UnknownMetaInstruction`)——防止白名单比执行器更严,
174    /// 导致消费方(evorule-cli validate)误报合法规则。
175    #[test]
176    fn test_meta_instruction_types_ssot() {
177        assert_eq!(META_INSTRUCTION_TYPES.len(), 5);
178        for t in META_INSTRUCTION_TYPES {
179            let instr = JsonValue::object_from_pairs(&[("type", JsonValue::string(*t))]);
180            if let Err(TcbError::UnknownMetaInstruction { .. }) =
181                execute_meta_instruction(&instr, JsonValue::Null, 0)
182            {
183                panic!("META_INSTRUCTION_TYPES 含未实现类型 '{t}'——白名单与 dispatch 漂移");
184            }
185            // Ok 或其他错误(如缺字段路径)均不算白名单漂移
186        }
187    }
188}
189
190/// 解析路径或字面值
191///
192/// 如果值是 `__` 开头的字符串,则视为路径并解析;
193/// 否则作为字面值返回。
194fn resolve_path_or_literal(
195    state: &JsonValue,
196    val: Option<&JsonValue>,
197) -> Result<JsonValue, TcbError> {
198    match val {
199        Some(JsonValue::String(s)) if s.starts_with("__") => resolve_path(state, s)
200            .cloned()
201            .ok_or_else(|| TcbError::PathResolutionFailed {
202                path: s.to_string(),
203                reason: "path not found".to_string(),
204            }),
205        Some(v) => Ok(v.clone()),
206        None => Err(TcbError::MissingField {
207            field: "value".to_string(),
208        }),
209    }
210}
211
212/// 返回 `JsonValue` 的小写类型名,用于错误诊断。
213pub(crate) fn json_type_name(v: &JsonValue) -> &'static str {
214    match v {
215        JsonValue::Null => "null",
216        JsonValue::Bool(_) => "boolean",
217        JsonValue::Integer(_) => "integer",
218        JsonValue::U64(_) => "u64",
219        JsonValue::String(_) => "string",
220        JsonValue::Array(_) => "array",
221        JsonValue::Object(_) => "object",
222    }
223}
224
225/// set 元指令:修改 payload 字段(attr 支持数组索引,v0.3.2 起)
226///
227/// attr 的三种写法:
228/// 1. 普通 payload 字段路径(如 `"x"`、`"a.b"`、`"items[0].done"`):相对
229///    `__exec__.payload` 解析,语法与 domain 读取路径一致(点号 + `[N]` 索引)
230/// 2. 状态路径引用(如 `"__exec__.instruction.params.attr"`):先解析为字符串,
231///    再作为 payload 字段路径(间接寻址)
232/// 3. 显式 payload 相对路径(如 `"__exec__.payload.__io_results__.call_external"`):
233///    前缀 `__exec__.payload.` 之后的后缀直接作为 payload 内相对路径,不做状态解析。
234///    用于引用 payload 内以 `__` 开头的字段(否则写法 2 会把它误判为状态根路径)
235///
236/// # 索引写入语义(显式优先)
237/// - 中间对象段缺失/null:自动创建空对象(auto-vivification,既有行为)
238/// - 索引段:目标数组**必须已存在**(不隐式创建,数组长度无法从索引推断);
239///   索引越界报错(不隐式追加,追加须由 push 显式完成)
240//
241// 注:本函数有意保持单一函数承载完整路径解析语义分支(三种 attr 写法 +
242// payload 前缀守卫 + 索引写入语义),便于审计路径解析行为;行数超出 clippy
243// 默认阈值(105/100),按 clippy 官方建议用函数级 allow 豁免。
244#[allow(clippy::too_many_lines)]
245fn exec_set(instr: &JsonValue, mut state: JsonValue) -> Result<JsonValue, TcbError> {
246    let params = instr.get("params").ok_or(TcbError::MissingField {
247        field: "params".to_string(),
248    })?;
249
250    // attr 支持路径引用;同时支持显式 payload 相对路径(见函数文档注释)
251    let attr_raw = params.get("attr").ok_or(TcbError::MissingField {
252        field: "attr".to_string(),
253    })?;
254
255    let resolve_attr_from_state = || -> Result<String, TcbError> {
256        let attr_value = resolve_path_or_literal(&state, Some(attr_raw))?;
257        attr_value
258            .as_str()
259            .map(ToString::to_string)
260            .ok_or_else(|| TcbError::InvalidType {
261                expected: "string",
262                actual: json_type_name(&attr_value),
263                context: "attr".to_string(),
264            })
265    };
266
267    // 写侧 attr 禁止 payload. 前缀(方案 a,引擎级运行时守卫):
268    // attr 相对 __exec__.payload 解析,带 payload. 前缀会双重嵌套写入
269    // payload.payload.*(静默失败——不报错但写到错误位置,读者永远 miss,
270    // 实证:种子元规则哨兵自读不到自身状态标记恒违规)。
271    // schema 门禁(payload_attr_path)在加载/提交期已拒;此处兜底覆盖
272    // 状态引用间接产生的前缀与绕过门禁的执行入口。
273    // 豁免:__exec__.payload. 显式全形式剥离后的后缀不再守卫——作者显式锚定
274    // payload 根(如 __exec__.payload.payload.deep 写 payload 内同名子字段)
275    // 是意图明确的合法写法;schema 侧 not.pattern 只匹配裸串,与此一致。
276    let attr: String = match attr_raw.as_str() {
277        Some(raw) => match raw.strip_prefix("__exec__.payload.") {
278            Some(suffix) => suffix.to_string(),
279            None => {
280                let resolved = resolve_attr_from_state()?;
281                if resolved.starts_with("payload.") {
282                    return Err(TcbError::PathResolutionFailed {
283                        path: resolved,
284                        reason: "写侧 attr 禁止以 payload. 开头:attr 相对 __exec__.payload \
285                                 解析,带前缀会双重嵌套写入 payload.payload.*。请直接写 \
286                                 payload 内相对路径(如 meta_guard.cleared_for_move),\
287                                 真需写 payload 内同名子字段时用 __exec__.payload. 显式全形式"
288                            .to_string(),
289                    });
290                }
291                resolved
292            }
293        },
294        None => {
295            let resolved = resolve_attr_from_state()?;
296            if resolved.starts_with("payload.") {
297                return Err(TcbError::PathResolutionFailed {
298                    path: resolved,
299                    reason: "写侧 attr 禁止以 payload. 开头:attr 相对 __exec__.payload 解析,\
300                             带前缀会双重嵌套写入 payload.payload.*。请直接写 \
301                             payload 内相对路径(如 meta_guard.cleared_for_move),\
302                             真需写 payload 内同名子字段时用 __exec__.payload. 显式全形式"
303                        .to_string(),
304                });
305            }
306            resolved
307        }
308    };
309
310    let operation =
311        params
312            .get("operation")
313            .and_then(|v| v.as_str())
314            .ok_or(TcbError::MissingField {
315                field: "operation".to_string(),
316            })?;
317
318    let value = resolve_path_or_literal(&state, params.get("value"))?;
319
320    // 解析 attr 路径为段序列(支持字段访问与数组索引,语法与 domain 读取路径一致)
321    let segments = parse_path_segments(&attr).ok_or_else(|| TcbError::PathResolutionFailed {
322        path: attr.to_string(),
323        reason: "invalid path syntax (empty segment or malformed index)".to_string(),
324    })?;
325    if segments.is_empty() {
326        return Err(TcbError::PathResolutionFailed {
327            path: attr.to_string(),
328            reason: "empty path".to_string(),
329        });
330    }
331
332    // 获取 __exec__.payload 根节点
333    let payload = resolve_path_mut(&mut state, "__exec__.payload").ok_or_else(|| {
334        TcbError::PathResolutionFailed {
335            path: "__exec__.payload".to_string(),
336            reason: "payload not found in state".to_string(),
337        }
338    })?;
339
340    let slot = descend_to_write_slot(payload, &segments, &attr)?;
341
342    let current = match &slot {
343        WriteSlot::Field(obj, name) => obj
344            .get(name.as_str())
345            .cloned()
346            // null ≡ 已清除/不存在 ≡ 算术起点 0(L7:与缺失字段、
347            // domain.exists 的 null 哲学对齐;operation=set 时 current 被丢弃,不受影响)
348            .map(|v| match v {
349                JsonValue::Null => JsonValue::Integer(0),
350                other => other,
351            })
352            .unwrap_or(JsonValue::Integer(0)),
353        WriteSlot::Index(arr, idx) => {
354            arr.get(*idx)
355                .cloned()
356                .ok_or_else(|| TcbError::PathResolutionFailed {
357                    path: attr.to_string(),
358                    reason: "array slot vanished".to_string(),
359                })?
360        }
361    };
362
363    let new_value = apply_set_operation(operation, current, value)?;
364
365    match slot {
366        WriteSlot::Field(obj, name) => {
367            obj.insert(name, new_value);
368        }
369        WriteSlot::Index(arr, idx) => {
370            if let Some(element) = arr.get_mut(idx) {
371                *element = new_value;
372            }
373        }
374    }
375    Ok(state)
376}
377
378/// 应用 set 运算:`set` 覆盖、`add`/`sub` checked 算术(溢出报 `IntegerOverflow`)
379///
380/// # 架构裁定(2026-10-19):本枚举刻意不引入 `mul`/`div`
381///
382/// 规则层词汇表止步于加减——加减服务步进语义(计数器/期限/循环推进),
383/// 乘除属计算语义,一律走服务面原生服务(黄金向量+双跑锁定,正确性
384/// 证明一次、处处受证)。比例/百分比类治理需求由带参数的通用服务
385/// 承担(如 ratio_split);若某类场景高频出现,演化路径是立法一条
386/// 治理语义的新指令(乘除内化为指令实现并全程入审计),而非向本
387/// 函数追加算术操作码——词汇表每收一个算术词,规则作者就被迫在
388/// 立法文本里手写一段算术。校验面对应枚举:
389/// core/rule_schema/schemas/_shared/v1.0.json 的 operation 字段。
390fn apply_set_operation(
391    operation: &str,
392    current: JsonValue,
393    value: JsonValue,
394) -> Result<JsonValue, TcbError> {
395    match operation {
396        "set" => Ok(value),
397        "add" | "sub" => {
398            let cur = current.as_i64().ok_or_else(|| TcbError::InvalidType {
399                expected: "integer",
400                actual: json_type_name(&current),
401                context: format!("{operation} left operand"),
402            })?;
403            let val = value.as_i64().ok_or_else(|| TcbError::InvalidType {
404                expected: "integer",
405                actual: json_type_name(&value),
406                context: format!("{operation} right operand"),
407            })?;
408            let result = if operation == "add" {
409                cur.checked_add(val)
410            } else {
411                cur.checked_sub(val)
412            }
413            .ok_or_else(|| TcbError::IntegerOverflow {
414                operation: operation.to_string(),
415                left: cur,
416                right: val,
417            })?;
418            Ok(JsonValue::Integer(result))
419        }
420        op => Err(TcbError::UnknownOperation {
421            operation: op.to_string(),
422        }),
423    }
424}
425
426/// attr 下降后的可写位置:对象字段或数组元素槽位
427enum WriteSlot<'a> {
428    /// 对象字段(`&mut ObjectMap`,字段名)
429    Field(&'a mut ObjectMap, String),
430    /// 数组元素槽位(`&mut [JsonValue]`,已验证索引)
431    Index(&'a mut [JsonValue], usize),
432}
433
434/// 沿段序列下降到可写位置(支持数组索引写入)
435///
436/// # 下降语义(结构错误显式报错)
437///
438/// - **中间字段段**:缺失或为 null 时自动创建空对象(auto-vivification,
439///   与既有行为一致);存在但非对象 → 报错。
440///   例外:若下一段是索引段,则缺失/null **不**创建占位对象而是直接报错
441///   (数组长度无法从索引推断,隐式创建会制造语义陷阱)。
442/// - **索引段**:目标数组**必须已存在**(缺失/null → 报错,禁止隐式创建);
443///   索引越界(`>= len`)→ 报错(禁止稀疏数组与隐式追加,追加须由
444///   push 等显式机制完成);存在但非数组 → 报错。
445/// - **末段**:返回可写槽位(字段或元素)。
446fn descend_to_write_slot<'a>(
447    payload: &'a mut JsonValue,
448    segments: &[PathSegment],
449    attr: &str,
450) -> Result<WriteSlot<'a>, TcbError> {
451    let mut current = payload;
452    let Some(last) = segments.len().checked_sub(1) else {
453        return Err(TcbError::PathResolutionFailed {
454            path: attr.to_string(),
455            reason: "empty path".to_string(),
456        });
457    };
458
459    for (i, seg) in segments.iter().enumerate() {
460        let is_last = i == last;
461        match seg {
462            PathSegment::Field(name) => {
463                match descend_field_segment(current, name, is_last, segments, i, attr)? {
464                    DescendStep::Slot(slot) => return Ok(slot),
465                    DescendStep::Next(next) => current = next,
466                }
467            }
468            PathSegment::Index(opt_field, idx) => {
469                match descend_index_segment(current, opt_field, *idx, is_last, attr)? {
470                    DescendStep::Slot(slot) => return Ok(slot),
471                    DescendStep::Next(next) => current = next,
472                }
473            }
474        }
475    }
476
477    Err(TcbError::PathResolutionFailed {
478        path: attr.to_string(),
479        reason: "empty path".to_string(),
480    })
481}
482
483/// 单段下降的结果:到达可写槽位,或取得继续下降的下一节点
484enum DescendStep<'a> {
485    /// 末段:返回可写槽位
486    Slot(WriteSlot<'a>),
487    /// 中间段:继续下降的下一节点
488    Next(&'a mut JsonValue),
489}
490
491/// 处理字段段下降(auto-vivification 规则见 `descend_to_write_slot` 文档)
492fn descend_field_segment<'a>(
493    current: &'a mut JsonValue,
494    name: &str,
495    is_last: bool,
496    segments: &[PathSegment],
497    i: usize,
498    attr: &str,
499) -> Result<DescendStep<'a>, TcbError> {
500    if !matches!(current, JsonValue::Object(_)) {
501        let ty = json_type_name(current);
502        return Err(TcbError::PathResolutionFailed {
503            path: attr.to_string(),
504            reason: format!("node at segment '{}' is {}, expected object", name, ty),
505        });
506    }
507    let obj = current
508        .as_object_mut()
509        .ok_or_else(|| TcbError::PathResolutionFailed {
510            path: attr.to_string(),
511            reason: "failed to enter object node".to_string(),
512        })?;
513    if is_last {
514        return Ok(DescendStep::Slot(WriteSlot::Field(obj, name.to_string())));
515    }
516    let next_is_index = matches!(segments.get(i + 1), Some(PathSegment::Index(..)));
517    match obj.get_mut(name) {
518        None | Some(JsonValue::Null) => {
519            if next_is_index {
520                return Err(TcbError::PathResolutionFailed {
521                    path: attr.to_string(),
522                    reason: format!(
523                        "array '{}' not found; set cannot auto-create arrays \
524                         (create via push first)",
525                        name
526                    ),
527                });
528            }
529            obj.insert(name.to_string(), JsonValue::empty_object());
530        }
531        Some(JsonValue::Object(_)) => {}
532        Some(other) => {
533            let ty = json_type_name(other);
534            return Err(TcbError::PathResolutionFailed {
535                path: attr.to_string(),
536                reason: format!("intermediate segment '{}' is {}, expected object", name, ty),
537            });
538        }
539    }
540    let next = obj
541        .get_mut(name)
542        .ok_or_else(|| TcbError::PathResolutionFailed {
543            path: attr.to_string(),
544            reason: "failed to descend into intermediate object".to_string(),
545        })?;
546    Ok(DescendStep::Next(next))
547}
548
549/// 处理索引段下降(数组必须已存在、越界报错,规则见 `descend_to_write_slot` 文档)
550fn descend_index_segment<'a>(
551    current: &'a mut JsonValue,
552    opt_field: &Option<String>,
553    idx: usize,
554    is_last: bool,
555    attr: &str,
556) -> Result<DescendStep<'a>, TcbError> {
557    let target: &mut JsonValue = if let Some(f) = opt_field {
558        if !matches!(current, JsonValue::Object(_)) {
559            return Err(TcbError::PathResolutionFailed {
560                path: attr.to_string(),
561                reason: format!(
562                    "node before array '{}' is {}, expected object",
563                    f,
564                    json_type_name(current)
565                ),
566            });
567        }
568        let obj = current
569            .as_object_mut()
570            .ok_or_else(|| TcbError::PathResolutionFailed {
571                path: attr.to_string(),
572                reason: "failed to enter object node".to_string(),
573            })?;
574        match obj.get_mut(f.as_str()) {
575            None | Some(JsonValue::Null) => {
576                return Err(TcbError::PathResolutionFailed {
577                    path: attr.to_string(),
578                    reason: format!(
579                        "array '{}' not found; set cannot auto-create arrays \
580                         (create via push first)",
581                        f
582                    ),
583                });
584            }
585            Some(v) => v,
586        }
587    } else {
588        current
589    };
590    let arr = target
591        .as_array_mut()
592        .ok_or_else(|| TcbError::PathResolutionFailed {
593            path: attr.to_string(),
594            reason: format!(
595                "segment '{}' is not an array",
596                opt_field.clone().unwrap_or_default()
597            ),
598        })?;
599    if idx >= arr.len() {
600        return Err(TcbError::PathResolutionFailed {
601            path: attr.to_string(),
602            reason: format!("index {} out of bounds (array length {})", idx, arr.len()),
603        });
604    }
605    if is_last {
606        return Ok(DescendStep::Slot(WriteSlot::Index(arr, idx)));
607    }
608    let next = arr
609        .get_mut(idx)
610        .ok_or_else(|| TcbError::PathResolutionFailed {
611            path: attr.to_string(),
612            reason: "failed to descend into array element".to_string(),
613        })?;
614    Ok(DescendStep::Next(next))
615}
616
617/// 解析 instructions 列表,支持数组元素中的路径引用
618///
619/// 顶层值如果是路径引用字符串,先解析为数组;
620/// 然后遍历数组元素,如果元素是 `__` 开头的字符串,解析为路径引用。
621/// 路径引用解析为数组时自动展平。
622fn resolve_instructions_list(
623    state: &JsonValue,
624    val: Option<&JsonValue>,
625) -> Result<Vec<JsonValue>, TcbError> {
626    let val = resolve_path_or_literal(state, val)?;
627    let arr = val.as_array().ok_or_else(|| TcbError::InvalidType {
628        expected: "array",
629        actual: json_type_name(&val),
630        context: "instructions".to_string(),
631    })?;
632
633    let mut result = Vec::new();
634    for item in arr {
635        match item {
636            JsonValue::String(s) if s.starts_with("__") => {
637                let mut resolved = resolve_path(state, s).cloned().ok_or_else(|| {
638                    TcbError::PathResolutionFailed {
639                        path: s.to_string(),
640                        reason: "path not found".to_string(),
641                    }
642                })?;
643                // mem::take: whole-value move out via &mut borrow (partial move-out
644                // is rejected for types with Drop impl, e.g. cfg(kani) no-op Drop).
645                if let JsonValue::Array(inner) = &mut resolved {
646                    result.extend(core::mem::take(inner));
647                } else {
648                    result.push(resolved);
649                }
650            }
651            _ => result.push(item.clone()),
652        }
653    }
654    Ok(result)
655}
656
657/// push 元指令:推指令到队列前端
658///
659/// 空指令列表视为 no-op,不返回错误。
660fn exec_push(instr: &JsonValue, mut state: JsonValue) -> Result<JsonValue, TcbError> {
661    let params = instr.get("params").ok_or(TcbError::MissingField {
662        field: "params".to_string(),
663    })?;
664
665    let instructions = resolve_instructions_list(&state, params.get("instructions"))?;
666
667    // 空指令列表 = no-op
668    if instructions.is_empty() {
669        return Ok(state);
670    }
671
672    // 获取当前队列切片
673    let queue_slice = resolve_path_mut(&mut state, "__exec__.queue")
674        .and_then(|v| v.as_array_mut())
675        .ok_or_else(|| TcbError::InvalidState {
676            reason: "__exec__.queue is missing or not an array".to_string(),
677        })?;
678
679    // 构建新队列:新指令在前,旧队列在后
680    let mut new_queue = Vec::with_capacity(instructions.len() + queue_slice.len());
681    new_queue.extend(instructions);
682    new_queue.extend_from_slice(queue_slice);
683
684    // 替换回 state
685    let queue =
686        resolve_path_mut(&mut state, "__exec__.queue").ok_or_else(|| TcbError::InvalidState {
687            reason: "__exec__.queue disappeared".to_string(),
688        })?;
689
690    *queue = JsonValue::Array(new_queue);
691
692    Ok(state)
693}
694
695/// branch 元指令:条件执行子指令列表
696///
697/// 如果子指令返回 `IoRequired`,立即传播信号,不继续执行后续子指令。
698/// 子指令递归共享外层执行预算(终止性宽度防线)。
699fn exec_branch(
700    instr: &JsonValue,
701    mut state: JsonValue,
702    depth: usize,
703    budget: &mut usize,
704    hit_out: &mut bool,
705    domain_attr_out: &mut Option<DomainAttribution>,
706) -> Result<MetaInstructionResult, TcbError> {
707    if depth >= MAX_BRANCH_DEPTH {
708        return Err(TcbError::NestingTooDeep {
709            limit: MAX_BRANCH_DEPTH,
710        });
711    }
712
713    let params = instr.get("params").ok_or(TcbError::MissingField {
714        field: "params".to_string(),
715    })?;
716
717    let domain = resolve_path_or_literal(&state, params.get("domain"))?;
718    // 域结构错误(未知类型/缺字段/超深/结构错误)显式报错,不在 TCB 层静默求值;
719    // on_missing=error 声明的 Missing 同样显式报错(MissingRejected,专项-20261001)
720    let outcome = evaluate_domain_outcome(&domain, &state)?;
721
722    // R1 归因不回灌执行:走向仅由投影 bool 决定,三态归因(含声明值)仅作审计透传
723    let branch_key = if outcome.to_bool() {
724        "on_true"
725    } else {
726        "on_false"
727    };
728    *domain_attr_out = Some(DomainAttribution {
729        outcome,
730        on_missing: declared_on_missing(&domain),
731    });
732
733    let branch_instrs = params.get(branch_key).and_then(|v| v.as_array());
734
735    if let Some(instrs) = branch_instrs {
736        // 结构命中:所选分支存在且非空即命中;子指令命中不细记
737        // (命中粒度 = 顶层规则级)。空数组/缺失分支 = 无效果路径,不命中。
738        if !instrs.is_empty() {
739            *hit_out = true;
740        }
741        for sub_instr in instrs {
742            let mut sub_hit = false;
743            // 子指令的域归因不细记(同命中粒度:顶层规则级),落本地变量丢弃
744            let mut sub_attr = None;
745            let result = execute_meta_instruction_budgeted(
746                sub_instr,
747                state,
748                depth + 1,
749                budget,
750                &mut sub_hit,
751                &mut sub_attr,
752            )?;
753            match result {
754                MetaInstructionResult::State(new_state) => state = new_state,
755                io_required @ MetaInstructionResult::IoRequired { .. } => return Ok(io_required),
756                // enforce 信号传播即停(回归验证):branch 子指令内的 enforce
757                // 命中同样中断整个转换(半成品纪律与顶层一致)
758                halted @ MetaInstructionResult::Halted { .. } => return Ok(halted),
759            }
760        }
761    }
762
763    Ok(MetaInstructionResult::State(state))
764}
765
766/// `enforce` 元指令:元规则强制原语(回归验证,纯机制不存策略)
767///
768/// # 参数(schema 门禁同口径:domain/reason 必填)
769/// - `domain`:域结构(7 基础域类型,与 branch 的 domain 同构;支持
770///   `__` 路径引用动态域,与 branch 范式一致)
771/// - `reason`:违规说明字符串——命中时随 Halted 信号透传,供反应器
772///   系统独占发射的 Violation 事实审计回显(必填:无 reason 的拦截
773///   不可审计,不允许静默强制)
774///
775/// # 语义
776/// - domain 求值 `Ok(true)` → `Halted { reason }`:状态转换层立即中断
777///   剩余 transform,违规指令被拒(此前状态修改随半成品一并丢弃);
778/// - domain 求值 `Ok(false)` → `State(state)` noop 继续(不命中);
779/// - domain 结构错误(未知类型/缺字段/超深)→ 显式 `TcbError`
780///   (fail-fast,与 branch 同语义:规则结构错误不允许静默求值)。
781///
782/// # 层级边界(引擎无层级概念)
783/// 本原语不感知 tier——"enforce 仅允许出现在 L2 元规则文件"由 server
784/// 侧装载门禁强制(见 evorule-server tier gate / schema 门禁)。
785fn exec_enforce(
786    instr: &JsonValue,
787    state: JsonValue,
788    domain_attr_out: &mut Option<DomainAttribution>,
789) -> Result<MetaInstructionResult, TcbError> {
790    let params = instr.get("params").ok_or(TcbError::MissingField {
791        field: "params".to_string(),
792    })?;
793
794    let domain = resolve_path_or_literal(&state, params.get("domain"))?;
795    // 域结构错误(未知类型/缺字段/超深/结构错误)显式报错,不在 TCB 层静默求值;
796    // on_missing=error 声明的 Missing 同样显式报错(MissingRejected,专项-20261001)
797    let outcome = evaluate_domain_outcome(&domain, &state)?;
798
799    // R1 归因不回灌执行:命中与否仅由投影 bool 决定,三态归因(含声明值)仅作审计透传
800    // (Unsat/Missing 不命中也要留归因——「为什么没拦住」的审计答案)
801    let domain_satisfied = outcome.to_bool();
802    *domain_attr_out = Some(DomainAttribution {
803        outcome,
804        on_missing: declared_on_missing(&domain),
805    });
806
807    if !domain_satisfied {
808        return Ok(MetaInstructionResult::State(state));
809    }
810
811    let reason = params
812        .get("reason")
813        .and_then(|v| v.as_str())
814        .ok_or(TcbError::MissingField {
815            field: "reason".to_string(),
816        })?;
817
818    Ok(MetaInstructionResult::Halted {
819        reason: reason.to_string(),
820    })
821}
822
823/// `io_request` 元指令:产生 I/O 请求信号(不修改状态)
824///
825/// # 参数可选性(显式声明)
826///
827/// - 键名**不带** `?` 后缀(如 `"messages"`):必选参数。路径引用解析失败
828///   立即报错 `PathResolutionFailed`——拼写错误的路径在根因处暴露,
829///   不再静默吞掉。
830/// - 键名**带** `?` 后缀(如 `"tools?"`):可选参数。路径引用解析失败时
831///   跳过该参数(业务性缺省),请求参数使用去掉 `?` 的键名(`"tools"`)。
832///
833/// 「可选」必须显式声明而非由解析失败隐式推断(审计决策):
834/// 静默跳过会把拼写错误伪装成「参数未提供」,错误在远离根因的
835/// 上游(外部系统行为异常)才暴露。
836fn exec_io_request(instr: &JsonValue, state: JsonValue) -> Result<MetaInstructionResult, TcbError> {
837    let params = instr.get("params").ok_or(TcbError::MissingField {
838        field: "params".to_string(),
839    })?;
840
841    let io_type = params
842        .get("io_type")
843        .and_then(|v| v.as_str())
844        .ok_or(TcbError::MissingField {
845            field: "io_type".to_string(),
846        })?
847        .to_string();
848
849    // 构造请求参数:解析所有路径引用
850    // 可选参数必须以 '?' 后缀显式声明;必选参数解析失败立即报错
851    let mut request_params = ObjectMap::new();
852    if let Some(obj) = params.as_object() {
853        for (key, value) in obj.iter() {
854            if key == "io_type" {
855                continue;
856            }
857            let (param_name, optional) = match key.strip_suffix('?') {
858                Some(stripped) => (stripped, true),
859                None => (key.as_str(), false),
860            };
861            match resolve_path_or_literal(&state, Some(value)) {
862                Ok(resolved) => {
863                    request_params.insert(param_name.to_string(), resolved);
864                }
865                // 显式声明的可选参数:路径不存在时跳过(业务性缺省)
866                Err(TcbError::PathResolutionFailed { .. }) if optional => {}
867                // 必选参数路径解析失败:显式报错,不静默吞掉拼写错误
868                Err(e) => return Err(e),
869            }
870        }
871    }
872
873    Ok(MetaInstructionResult::IoRequired {
874        io_type,
875        params: JsonValue::Object(request_params),
876    })
877}
878
879#[cfg(test)]
880mod tests {
881    #![allow(clippy::unwrap_used)]
882    #![allow(clippy::expect_used)]
883    #![allow(clippy::panic)]
884    #![allow(clippy::indexing_slicing)]
885
886    use super::*;
887    use crate::domain::DomainOutcome;
888    use crate::value::{JsonValue, ObjectMap};
889    use alloc::string::ToString;
890    use alloc::vec;
891    use alloc::vec::Vec;
892
893    // ===== 辅助函数 =====
894
895    fn make_exec_state(
896        instruction_type: &str,
897        payload: JsonValue,
898        queue: Vec<JsonValue>,
899    ) -> JsonValue {
900        let mut exec = ObjectMap::new();
901        exec.insert(
902            "instruction".to_string(),
903            make_instruction(instruction_type, &[]),
904        );
905        exec.insert("payload".to_string(), payload);
906        exec.insert("queue".to_string(), JsonValue::Array(queue));
907        let mut root = ObjectMap::new();
908        root.insert("__exec__".to_string(), JsonValue::Object(exec));
909        JsonValue::Object(root)
910    }
911
912    fn make_exec_state_with_instruction(
913        instruction: JsonValue,
914        payload: JsonValue,
915        queue: Vec<JsonValue>,
916    ) -> JsonValue {
917        let mut exec = ObjectMap::new();
918        exec.insert("instruction".to_string(), instruction);
919        exec.insert("payload".to_string(), payload);
920        exec.insert("queue".to_string(), JsonValue::Array(queue));
921        let mut root = ObjectMap::new();
922        root.insert("__exec__".to_string(), JsonValue::Object(exec));
923        JsonValue::Object(root)
924    }
925
926    fn make_payload(x: i64) -> JsonValue {
927        let mut map = ObjectMap::new();
928        map.insert("x".to_string(), JsonValue::Integer(x));
929        JsonValue::Object(map)
930    }
931
932    fn make_instruction(instr_type: &str, params: &[(&str, JsonValue)]) -> JsonValue {
933        JsonValue::object_from_pairs(&[
934            ("type", JsonValue::string(instr_type)),
935            ("params", JsonValue::object_from_pairs(params)),
936        ])
937    }
938
939    fn make_instruction_simple(instr_type: &str, value: i64) -> JsonValue {
940        make_instruction(instr_type, &[("value", JsonValue::Integer(value))])
941    }
942
943    // ===== set 测试 =====
944
945    #[test]
946    fn test_set_add() {
947        let state = make_exec_state("increment", make_payload(5), vec![]);
948        let instr = JsonValue::object_from_pairs(&[
949            ("type", JsonValue::string("set")),
950            (
951                "params",
952                JsonValue::object_from_pairs(&[
953                    ("attr", JsonValue::string("x")),
954                    ("operation", JsonValue::string("add")),
955                    ("value", JsonValue::Integer(3)),
956                ]),
957            ),
958        ]);
959
960        let result = exec_set(&instr, state).unwrap();
961        let payload = resolve_path(&result, "__exec__.payload").unwrap();
962        assert_eq!(payload.get("x"), Some(&JsonValue::Integer(8)));
963    }
964
965    #[test]
966    fn test_set_sub() {
967        let state = make_exec_state("decrement", make_payload(10), vec![]);
968        let instr = JsonValue::object_from_pairs(&[
969            ("type", JsonValue::string("set")),
970            (
971                "params",
972                JsonValue::object_from_pairs(&[
973                    ("attr", JsonValue::string("x")),
974                    ("operation", JsonValue::string("sub")),
975                    ("value", JsonValue::Integer(3)),
976                ]),
977            ),
978        ]);
979
980        let result = exec_set(&instr, state).unwrap();
981        let payload = resolve_path(&result, "__exec__.payload").unwrap();
982        assert_eq!(payload.get("x"), Some(&JsonValue::Integer(7)));
983    }
984
985    #[test]
986    fn test_set_operation_set_string_value() {
987        let state = make_exec_state("set", make_payload(0), vec![]);
988        let instr = JsonValue::object_from_pairs(&[
989            ("type", JsonValue::string("set")),
990            (
991                "params",
992                JsonValue::object_from_pairs(&[
993                    ("attr", JsonValue::string("name")),
994                    ("operation", JsonValue::string("set")),
995                    ("value", JsonValue::string("hello")),
996                ]),
997            ),
998        ]);
999
1000        let result = exec_set(&instr, state).unwrap();
1001        let value = resolve_path(&result, "__exec__.payload.name").unwrap();
1002        assert_eq!(value, &JsonValue::string("hello"));
1003    }
1004
1005    // ===== 写侧 attr payload. 前缀守卫测试(方案 a)=====
1006
1007    /// 错误形态:attr 带 payload. 前缀 → 显式报错(拒绝双重嵌套静默写歪)
1008    #[test]
1009    fn test_set_payload_prefix_attr_rejected() {
1010        let state = make_exec_state("set", make_payload(0), vec![]);
1011        let instr = JsonValue::object_from_pairs(&[
1012            ("type", JsonValue::string("set")),
1013            (
1014                "params",
1015                JsonValue::object_from_pairs(&[
1016                    ("attr", JsonValue::string("payload.meta_guard.cleared")),
1017                    ("operation", JsonValue::string("set")),
1018                    ("value", JsonValue::Bool(true)),
1019                ]),
1020            ),
1021        ]);
1022
1023        let err = exec_set(&instr, state).unwrap_err();
1024        match err {
1025            TcbError::PathResolutionFailed { path, reason } => {
1026                assert_eq!(path, "payload.meta_guard.cleared");
1027                assert!(
1028                    reason.contains("payload.") && reason.contains("双重嵌套"),
1029                    "错误原因应含双重嵌套指引: {reason}"
1030                );
1031            }
1032            other => panic!("expected PathResolutionFailed, got: {other:?}"),
1033        }
1034    }
1035
1036    /// 状态引用间接产生的 payload. 前缀同样被拒(守卫作用于解析后的最终 attr)
1037    #[test]
1038    fn test_set_state_ref_attr_resolving_to_payload_prefix_rejected() {
1039        let mut params = ObjectMap::new();
1040        params.insert("target".to_string(), JsonValue::string("payload.x"));
1041        let instruction = JsonValue::object_from_pairs(&[
1042            ("type", JsonValue::string("set")),
1043            ("params", JsonValue::Object(params)),
1044        ]);
1045        let state = make_exec_state_with_instruction(instruction, make_payload(0), vec![]);
1046        let instr = JsonValue::object_from_pairs(&[
1047            ("type", JsonValue::string("set")),
1048            (
1049                "params",
1050                JsonValue::object_from_pairs(&[
1051                    (
1052                        "attr",
1053                        JsonValue::string("__exec__.instruction.params.target"),
1054                    ),
1055                    ("operation", JsonValue::string("set")),
1056                    ("value", JsonValue::Integer(1)),
1057                ]),
1058            ),
1059        ]);
1060
1061        let err = exec_set(&instr, state).unwrap_err();
1062        assert!(
1063            matches!(err, TcbError::PathResolutionFailed { ref path, .. } if path == "payload.x"),
1064            "运行时解析出 payload. 前缀 attr 应被拒: {err:?}"
1065        );
1066    }
1067
1068    /// 显式全形式 __exec__.payload.x 放行(剥离前缀后写 payload.x)
1069    #[test]
1070    fn test_set_exec_payload_full_form_ok() {
1071        let state = make_exec_state("set", make_payload(0), vec![]);
1072        let instr = JsonValue::object_from_pairs(&[
1073            ("type", JsonValue::string("set")),
1074            (
1075                "params",
1076                JsonValue::object_from_pairs(&[
1077                    ("attr", JsonValue::string("__exec__.payload.x")),
1078                    ("operation", JsonValue::string("set")),
1079                    ("value", JsonValue::Integer(9)),
1080                ]),
1081            ),
1082        ]);
1083
1084        let result = exec_set(&instr, state).unwrap();
1085        let payload = resolve_path(&result, "__exec__.payload").unwrap();
1086        assert_eq!(payload.get("x"), Some(&JsonValue::Integer(9)));
1087    }
1088
1089    /// 显式全形式 __exec__.payload.payload.deep 是写 payload.payload.* 的唯一合法途径
1090    #[test]
1091    fn test_set_exec_payload_nested_full_form_ok() {
1092        let state = make_exec_state("set", make_payload(0), vec![]);
1093        let instr = JsonValue::object_from_pairs(&[
1094            ("type", JsonValue::string("set")),
1095            (
1096                "params",
1097                JsonValue::object_from_pairs(&[
1098                    ("attr", JsonValue::string("__exec__.payload.payload.deep")),
1099                    ("operation", JsonValue::string("set")),
1100                    ("value", JsonValue::Integer(1)),
1101                ]),
1102            ),
1103        ]);
1104
1105        let result = exec_set(&instr, state).unwrap();
1106        let nested = resolve_path(&result, "__exec__.payload.payload.deep").unwrap();
1107        assert_eq!(nested, &JsonValue::Integer(1));
1108    }
1109
1110    /// 裸简写嵌套路径(种子元规则正确形态)不受守卫影响
1111    #[test]
1112    fn test_set_bare_shorthand_nested_path_ok() {
1113        let state = make_exec_state("set", make_payload(0), vec![]);
1114        let instr = JsonValue::object_from_pairs(&[
1115            ("type", JsonValue::string("set")),
1116            (
1117                "params",
1118                JsonValue::object_from_pairs(&[
1119                    ("attr", JsonValue::string("meta_guard.cleared_for_move")),
1120                    ("operation", JsonValue::string("set")),
1121                    ("value", JsonValue::Bool(true)),
1122                ]),
1123            ),
1124        ]);
1125
1126        let result = exec_set(&instr, state).unwrap();
1127        let flag = resolve_path(&result, "__exec__.payload.meta_guard.cleared_for_move").unwrap();
1128        assert_eq!(flag, &JsonValue::Bool(true));
1129    }
1130
1131    #[test]
1132    fn test_set_type_safety() {
1133        let state = make_exec_state("set", make_payload(5), vec![]);
1134        let instr = JsonValue::object_from_pairs(&[
1135            ("type", JsonValue::string("set")),
1136            (
1137                "params",
1138                JsonValue::object_from_pairs(&[
1139                    ("attr", JsonValue::string("x")),
1140                    ("operation", JsonValue::string("add")),
1141                    ("value", JsonValue::string("hello")),
1142                ]),
1143            ),
1144        ]);
1145
1146        let result = exec_set(&instr, state);
1147        assert!(matches!(result, Err(TcbError::InvalidType { .. })));
1148    }
1149
1150    #[test]
1151    fn test_set_add_overflow() {
1152        let state = make_exec_state("set", make_payload(i64::MAX), vec![]);
1153        let instr = JsonValue::object_from_pairs(&[
1154            ("type", JsonValue::string("set")),
1155            (
1156                "params",
1157                JsonValue::object_from_pairs(&[
1158                    ("attr", JsonValue::string("x")),
1159                    ("operation", JsonValue::string("add")),
1160                    ("value", JsonValue::Integer(1)),
1161                ]),
1162            ),
1163        ]);
1164
1165        let result = exec_set(&instr, state);
1166        assert!(matches!(result, Err(TcbError::IntegerOverflow { .. })));
1167    }
1168
1169    #[test]
1170    fn test_set_sub_overflow() {
1171        let state = make_exec_state("set", make_payload(i64::MIN), vec![]);
1172        let instr = JsonValue::object_from_pairs(&[
1173            ("type", JsonValue::string("set")),
1174            (
1175                "params",
1176                JsonValue::object_from_pairs(&[
1177                    ("attr", JsonValue::string("x")),
1178                    ("operation", JsonValue::string("sub")),
1179                    ("value", JsonValue::Integer(1)),
1180                ]),
1181            ),
1182        ]);
1183
1184        let result = exec_set(&instr, state);
1185        assert!(matches!(result, Err(TcbError::IntegerOverflow { .. })));
1186    }
1187
1188    #[test]
1189    fn test_set_nested_attr_path() {
1190        let mut inner = ObjectMap::new();
1191        inner.insert("b".to_string(), JsonValue::Integer(1));
1192        let mut payload = ObjectMap::new();
1193        payload.insert("a".to_string(), JsonValue::Object(inner));
1194        let payload = JsonValue::Object(payload);
1195
1196        let state = make_exec_state("set", payload, vec![]);
1197        let instr = JsonValue::object_from_pairs(&[
1198            ("type", JsonValue::string("set")),
1199            (
1200                "params",
1201                JsonValue::object_from_pairs(&[
1202                    ("attr", JsonValue::string("a.b")),
1203                    ("operation", JsonValue::string("add")),
1204                    ("value", JsonValue::Integer(10)),
1205                ]),
1206            ),
1207        ]);
1208
1209        let result = exec_set(&instr, state).unwrap();
1210        let value = resolve_path(&result, "__exec__.payload.a.b").unwrap();
1211        assert_eq!(value, &JsonValue::Integer(11));
1212    }
1213
1214    #[test]
1215    fn test_set_nested_attr_create_field() {
1216        let mut inner = ObjectMap::new();
1217        inner.insert("existing".to_string(), JsonValue::Integer(100));
1218        let mut payload = ObjectMap::new();
1219        payload.insert("a".to_string(), JsonValue::Object(inner));
1220        let payload = JsonValue::Object(payload);
1221
1222        let state = make_exec_state("set", payload, vec![]);
1223        let instr = JsonValue::object_from_pairs(&[
1224            ("type", JsonValue::string("set")),
1225            (
1226                "params",
1227                JsonValue::object_from_pairs(&[
1228                    ("attr", JsonValue::string("a.new_field")),
1229                    ("operation", JsonValue::string("set")),
1230                    ("value", JsonValue::Integer(42)),
1231                ]),
1232            ),
1233        ]);
1234
1235        let result = exec_set(&instr, state).unwrap();
1236        let value = resolve_path(&result, "__exec__.payload.a.new_field").unwrap();
1237        assert_eq!(value, &JsonValue::Integer(42));
1238    }
1239
1240    // ── M2:attr 数组索引写入 ────────────────────────────────────────────
1241
1242    fn make_payload_with_items() -> JsonValue {
1243        // payload.items = [ { done: false }, { done: false } ]
1244        let item0 = JsonValue::object_from_pairs(&[("done", JsonValue::Bool(false))]);
1245        let item1 = JsonValue::object_from_pairs(&[("done", JsonValue::Bool(false))]);
1246        JsonValue::object_from_pairs(&[("items", JsonValue::array(vec![item0, item1]))])
1247    }
1248
1249    fn set_instr(attr: &str, op: &str, value: JsonValue) -> JsonValue {
1250        JsonValue::object_from_pairs(&[
1251            ("type", JsonValue::string("set")),
1252            (
1253                "params",
1254                JsonValue::object_from_pairs(&[
1255                    ("attr", JsonValue::string(attr)),
1256                    ("operation", JsonValue::string(op)),
1257                    ("value", value),
1258                ]),
1259            ),
1260        ])
1261    }
1262
1263    #[test]
1264    fn test_set_array_index_field_write() {
1265        // items[0].done:既有数组元素的字段写入(domain 读取同款路径语法)
1266        let state = make_exec_state("set", make_payload_with_items(), vec![]);
1267        let result = exec_set(
1268            &set_instr("items[0].done", "set", JsonValue::Bool(true)),
1269            state,
1270        )
1271        .unwrap();
1272        assert_eq!(
1273            resolve_path(&result, "__exec__.payload.items[0].done"),
1274            Some(&JsonValue::Bool(true))
1275        );
1276        // 其余元素不受影响
1277        assert_eq!(
1278            resolve_path(&result, "__exec__.payload.items[1].done"),
1279            Some(&JsonValue::Bool(false))
1280        );
1281    }
1282
1283    #[test]
1284    fn test_set_array_index_element_write() {
1285        // items[1]:末段索引,替换整个数组元素
1286        let state = make_exec_state("set", make_payload_with_items(), vec![]);
1287        let replacement = JsonValue::object_from_pairs(&[("done", JsonValue::Bool(true))]);
1288        let result = exec_set(&set_instr("items[1]", "set", replacement), state).unwrap();
1289        assert_eq!(
1290            resolve_path(&result, "__exec__.payload.items[1].done"),
1291            Some(&JsonValue::Bool(true))
1292        );
1293        assert_eq!(
1294            resolve_path(&result, "__exec__.payload.items[0].done"),
1295            Some(&JsonValue::Bool(false))
1296        );
1297    }
1298
1299    #[test]
1300    fn test_set_array_index_add_operation() {
1301        // items[0].count = 5 + 3:索引槽位上的算术运算
1302        let item0 = JsonValue::object_from_pairs(&[("count", JsonValue::Integer(5))]);
1303        let payload = JsonValue::object_from_pairs(&[("items", JsonValue::array(vec![item0]))]);
1304        let state = make_exec_state("set", payload, vec![]);
1305        let result = exec_set(
1306            &set_instr("items[0].count", "add", JsonValue::Integer(3)),
1307            state,
1308        )
1309        .unwrap();
1310        assert_eq!(
1311            resolve_path(&result, "__exec__.payload.items[0].count"),
1312            Some(&JsonValue::Integer(8))
1313        );
1314    }
1315
1316    #[test]
1317    fn test_set_array_missing_errors_no_auto_create() {
1318        // 数组不存在 → 报错(数组长度无法从索引推断,禁止隐式创建)
1319        let payload = JsonValue::empty_object();
1320        let state = make_exec_state("set", payload, vec![]);
1321        let result = exec_set(
1322            &set_instr("items[0].done", "set", JsonValue::Bool(true)),
1323            state,
1324        );
1325        match result {
1326            Err(TcbError::PathResolutionFailed { path, reason }) => {
1327                assert!(path.contains("items[0].done"));
1328                assert!(
1329                    reason.contains("cannot auto-create arrays"),
1330                    "reason: {reason}"
1331                );
1332            }
1333            other => panic!("expected PathResolutionFailed, got {:?}", other),
1334        }
1335    }
1336
1337    #[test]
1338    fn test_set_array_index_out_of_bounds_errors() {
1339        // 索引越界 → 报错(禁止稀疏数组与隐式追加)
1340        let state = make_exec_state("set", make_payload_with_items(), vec![]);
1341        let result = exec_set(
1342            &set_instr("items[2].done", "set", JsonValue::Bool(true)),
1343            state,
1344        );
1345        match result {
1346            Err(TcbError::PathResolutionFailed { path, reason }) => {
1347                assert!(path.contains("items[2].done"));
1348                assert!(reason.contains("out of bounds"), "reason: {reason}");
1349            }
1350            other => panic!("expected PathResolutionFailed, got {:?}", other),
1351        }
1352    }
1353
1354    #[test]
1355    fn test_set_array_index_no_malformed_field_created() {
1356        // M2 回归核心:旧实现会把 "items[0]" 当字段名创建畸形键;
1357        // 新实现要么成功写入元素、要么显式报错,绝不创建 "items[0]" 字面键
1358        let state = make_exec_state("set", make_payload_with_items(), vec![]);
1359        let result = exec_set(
1360            &set_instr("items[0].done", "set", JsonValue::Bool(true)),
1361            state,
1362        )
1363        .unwrap();
1364        let items = resolve_path(&result, "__exec__.payload.items").unwrap();
1365        let arr = items.as_array().unwrap();
1366        assert_eq!(arr.len(), 2, "数组长度不变(无追加)");
1367        // 确认没有 "items[0]" 畸形键出现在 payload 顶层
1368        let payload_obj = resolve_path(&result, "__exec__.payload").unwrap();
1369        assert!(payload_obj.get("items[0]").is_none(), "不得创建畸形字段名");
1370        assert!(payload_obj.get("items[1]").is_none(), "不得创建畸形字段名");
1371    }
1372
1373    #[test]
1374    fn test_set_array_index_on_non_array_errors() {
1375        // 字段存在但非数组 → 显式报错
1376        let payload = JsonValue::object_from_pairs(&[("items", JsonValue::Integer(42))]);
1377        let state = make_exec_state("set", payload, vec![]);
1378        let result = exec_set(&set_instr("items[0]", "set", JsonValue::Bool(true)), state);
1379        match result {
1380            Err(TcbError::PathResolutionFailed { path, reason }) => {
1381                assert!(path.contains("items[0]"));
1382                assert!(reason.contains("not an array"), "reason: {reason}");
1383            }
1384            other => panic!("expected PathResolutionFailed, got {:?}", other),
1385        }
1386    }
1387
1388    #[test]
1389    fn test_set_arithmetic_null_field_treated_as_zero() {
1390        // L7 回归:null ≡ 已清除/不存在 ≡ 算术起点 0,
1391        // add/sub 不得对 null 字段报 InvalidType(与缺失字段行为对齐)
1392        let payload = JsonValue::object_from_pairs(&[("x", JsonValue::Null)]);
1393        let state = make_exec_state("set", payload, vec![]);
1394
1395        let result = exec_set(&set_instr("x", "add", JsonValue::Integer(5)), state).unwrap();
1396        assert_eq!(
1397            resolve_path(&result, "__exec__.payload.x").unwrap(),
1398            &JsonValue::Integer(5)
1399        );
1400    }
1401
1402    #[test]
1403    fn test_set_arithmetic_missing_field_treated_as_zero() {
1404        // 对照组:缺失字段 add 从 0 起算(既有行为,防止 L7 修改引入回归)
1405        let state = make_exec_state("set", JsonValue::empty_object(), vec![]);
1406        let result = exec_set(&set_instr("x", "sub", JsonValue::Integer(3)), state).unwrap();
1407        assert_eq!(
1408            resolve_path(&result, "__exec__.payload.x").unwrap(),
1409            &JsonValue::Integer(-3)
1410        );
1411    }
1412
1413    #[test]
1414    fn test_set_attr_with_path_reference_from_instruction() {
1415        let instruction = JsonValue::object_from_pairs(&[
1416            ("type", JsonValue::string("increment")),
1417            (
1418                "params",
1419                JsonValue::object_from_pairs(&[
1420                    ("attr", JsonValue::string("x")),
1421                    ("delta", JsonValue::Integer(5)),
1422                ]),
1423            ),
1424        ]);
1425        let state = make_exec_state_with_instruction(instruction, make_payload(10), vec![]);
1426
1427        let set_instr = JsonValue::object_from_pairs(&[
1428            ("type", JsonValue::string("set")),
1429            (
1430                "params",
1431                JsonValue::object_from_pairs(&[
1432                    (
1433                        "attr",
1434                        JsonValue::string("__exec__.instruction.params.attr"),
1435                    ),
1436                    ("operation", JsonValue::string("add")),
1437                    (
1438                        "value",
1439                        JsonValue::string("__exec__.instruction.params.delta"),
1440                    ),
1441                ]),
1442            ),
1443        ]);
1444
1445        let result = exec_set(&set_instr, state).unwrap();
1446        let x = resolve_path(&result, "__exec__.payload.x").unwrap();
1447        assert_eq!(x, &JsonValue::Integer(15));
1448    }
1449
1450    #[test]
1451    fn test_set_nested_attr_through_null_intermediate() {
1452        let mut payload = ObjectMap::new();
1453        let mut audit = ObjectMap::new();
1454        audit.insert("evolve_request".to_string(), JsonValue::Null);
1455        payload.insert("audit".to_string(), JsonValue::Object(audit));
1456        let state = make_exec_state_with_instruction(
1457            JsonValue::object_from_pairs(&[("type", JsonValue::string("evolution_scanner"))]),
1458            JsonValue::Object(payload),
1459            vec![],
1460        );
1461
1462        let instr = JsonValue::object_from_pairs(&[
1463            ("type", JsonValue::string("set")),
1464            (
1465                "params",
1466                JsonValue::object_from_pairs(&[
1467                    ("attr", JsonValue::string("audit.evolve_request.reason")),
1468                    ("operation", JsonValue::string("set")),
1469                    ("value", JsonValue::string("test reason")),
1470                ]),
1471            ),
1472        ]);
1473
1474        let result = exec_set(&instr, state).unwrap();
1475        let reason = resolve_path(&result, "__exec__.payload.audit.evolve_request.reason");
1476        assert_eq!(reason.and_then(|v| v.as_str()), Some("test reason"));
1477    }
1478
1479    #[test]
1480    fn test_set_nested_attr_through_scalar_intermediate_errors() {
1481        let mut payload = ObjectMap::new();
1482        let mut audit = ObjectMap::new();
1483        audit.insert("evolve_request".to_string(), JsonValue::Integer(42));
1484        payload.insert("audit".to_string(), JsonValue::Object(audit));
1485        let state = make_exec_state_with_instruction(
1486            JsonValue::object_from_pairs(&[("type", JsonValue::string("evolution_scanner"))]),
1487            JsonValue::Object(payload),
1488            vec![],
1489        );
1490
1491        let instr = JsonValue::object_from_pairs(&[
1492            ("type", JsonValue::string("set")),
1493            (
1494                "params",
1495                JsonValue::object_from_pairs(&[
1496                    ("attr", JsonValue::string("audit.evolve_request.reason")),
1497                    ("operation", JsonValue::string("set")),
1498                    ("value", JsonValue::string("test reason")),
1499                ]),
1500            ),
1501        ]);
1502
1503        let result = exec_set(&instr, state);
1504        match result {
1505            Err(TcbError::PathResolutionFailed { path, reason }) => {
1506                assert!(path.contains("audit.evolve_request.reason"));
1507                assert!(reason.contains("integer"));
1508                assert!(reason.contains("object"));
1509            }
1510            other => panic!("expected PathResolutionFailed, got {:?}", other),
1511        }
1512    }
1513
1514    #[test]
1515    fn test_set_missing_attr_field() {
1516        let state = make_exec_state("set", make_payload(0), vec![]);
1517        let instr = JsonValue::object_from_pairs(&[
1518            ("type", JsonValue::string("set")),
1519            (
1520                "params",
1521                JsonValue::object_from_pairs(&[
1522                    ("operation", JsonValue::string("set")),
1523                    ("value", JsonValue::Integer(1)),
1524                ]),
1525            ),
1526        ]);
1527
1528        let result = exec_set(&instr, state);
1529        assert!(matches!(result, Err(TcbError::MissingField { field }) if field == "attr"));
1530    }
1531
1532    #[test]
1533    fn test_set_missing_value_field() {
1534        let state = make_exec_state("set", make_payload(0), vec![]);
1535        let instr = JsonValue::object_from_pairs(&[
1536            ("type", JsonValue::string("set")),
1537            (
1538                "params",
1539                JsonValue::object_from_pairs(&[
1540                    ("attr", JsonValue::string("x")),
1541                    ("operation", JsonValue::string("set")),
1542                ]),
1543            ),
1544        ]);
1545
1546        let result = exec_set(&instr, state);
1547        assert!(matches!(result, Err(TcbError::MissingField { field }) if field == "value"));
1548    }
1549
1550    #[test]
1551    fn test_set_unknown_operation() {
1552        let state = make_exec_state("set", make_payload(10), vec![]);
1553        let instr = JsonValue::object_from_pairs(&[
1554            ("type", JsonValue::string("set")),
1555            (
1556                "params",
1557                JsonValue::object_from_pairs(&[
1558                    ("attr", JsonValue::string("x")),
1559                    ("operation", JsonValue::string("multiply")),
1560                    ("value", JsonValue::Integer(2)),
1561                ]),
1562            ),
1563        ]);
1564
1565        let result = exec_set(&instr, state);
1566        assert!(
1567            matches!(result, Err(TcbError::UnknownOperation { operation }) if operation == "multiply")
1568        );
1569    }
1570
1571    // ===== push 测试 =====
1572
1573    #[test]
1574    fn test_push_basic() {
1575        let state = make_exec_state("sequence", make_payload(0), vec![]);
1576        let instr = JsonValue::object_from_pairs(&[
1577            ("type", JsonValue::string("push")),
1578            (
1579                "params",
1580                JsonValue::object_from_pairs(&[(
1581                    "instructions",
1582                    JsonValue::array(vec![JsonValue::object_from_pairs(&[
1583                        ("type", JsonValue::string("increment")),
1584                        (
1585                            "params",
1586                            JsonValue::object_from_pairs(&[
1587                                ("attr", JsonValue::string("x")),
1588                                ("delta", JsonValue::Integer(1)),
1589                            ]),
1590                        ),
1591                    ])]),
1592                )]),
1593            ),
1594        ]);
1595
1596        let result = exec_push(&instr, state).unwrap();
1597        let queue = resolve_path(&result, "__exec__.queue").unwrap();
1598        let arr = queue.as_array().unwrap();
1599        assert_eq!(arr.len(), 1);
1600    }
1601
1602    #[test]
1603    fn test_push_prepends_to_existing_queue() {
1604        let existing = make_instruction_simple("old_op", 0);
1605        let state = make_exec_state("sequence", make_payload(0), vec![existing]);
1606        let new_instr = make_instruction_simple("new_op", 1);
1607        let instr = JsonValue::object_from_pairs(&[
1608            ("type", JsonValue::string("push")),
1609            (
1610                "params",
1611                JsonValue::object_from_pairs(&[(
1612                    "instructions",
1613                    JsonValue::array(vec![new_instr]),
1614                )]),
1615            ),
1616        ]);
1617
1618        let result = exec_push(&instr, state).unwrap();
1619        let queue = resolve_path(&result, "__exec__.queue").unwrap();
1620        let arr = queue.as_array().unwrap();
1621        assert_eq!(arr.len(), 2);
1622        assert_eq!(arr[0].get("type").and_then(|v| v.as_str()), Some("new_op"));
1623        assert_eq!(arr[1].get("type").and_then(|v| v.as_str()), Some("old_op"));
1624    }
1625
1626    #[test]
1627    fn test_push_empty_list_is_noop() {
1628        let existing = make_instruction_simple("old_op", 0);
1629        let state = make_exec_state("sequence", make_payload(0), vec![existing]);
1630        let instr = JsonValue::object_from_pairs(&[
1631            ("type", JsonValue::string("push")),
1632            (
1633                "params",
1634                JsonValue::object_from_pairs(&[("instructions", JsonValue::array(vec![]))]),
1635            ),
1636        ]);
1637
1638        let result = exec_push(&instr, state).unwrap();
1639        let queue = resolve_path(&result, "__exec__.queue").unwrap();
1640        let arr = queue.as_array().unwrap();
1641        assert_eq!(arr.len(), 1);
1642        assert_eq!(arr[0].get("type").and_then(|v| v.as_str()), Some("old_op"));
1643    }
1644
1645    #[test]
1646    fn test_push_with_path_reference_elements() {
1647        let then_instr = JsonValue::object_from_pairs(&[
1648            ("type", JsonValue::string("set")),
1649            (
1650                "params",
1651                JsonValue::object_from_pairs(&[
1652                    ("attr", JsonValue::string("x")),
1653                    ("operation", JsonValue::string("set")),
1654                    ("value", JsonValue::Integer(42)),
1655                ]),
1656            ),
1657        ]);
1658        let instruction = JsonValue::object_from_pairs(&[
1659            ("type", JsonValue::string("conditional")),
1660            (
1661                "params",
1662                JsonValue::object_from_pairs(&[("then", then_instr)]),
1663            ),
1664        ]);
1665        let state = make_exec_state_with_instruction(instruction, make_payload(0), vec![]);
1666
1667        let push_instr = JsonValue::object_from_pairs(&[
1668            ("type", JsonValue::string("push")),
1669            (
1670                "params",
1671                JsonValue::object_from_pairs(&[(
1672                    "instructions",
1673                    JsonValue::array(vec![JsonValue::string("__exec__.instruction.params.then")]),
1674                )]),
1675            ),
1676        ]);
1677
1678        let result = exec_push(&push_instr, state).unwrap();
1679        let queue = resolve_path(&result, "__exec__.queue").unwrap();
1680        let arr = queue.as_array().unwrap();
1681        assert_eq!(arr.len(), 1);
1682        assert_eq!(arr[0].get("type").and_then(|v| v.as_str()), Some("set"));
1683    }
1684
1685    #[test]
1686    fn test_push_with_array_body_flattened() {
1687        let body_array = JsonValue::array(vec![
1688            JsonValue::object_from_pairs(&[
1689                ("type", JsonValue::string("increment")),
1690                (
1691                    "params",
1692                    JsonValue::object_from_pairs(&[
1693                        ("attr", JsonValue::string("x")),
1694                        ("delta", JsonValue::Integer(1)),
1695                    ]),
1696                ),
1697            ]),
1698            JsonValue::object_from_pairs(&[
1699                ("type", JsonValue::string("set")),
1700                (
1701                    "params",
1702                    JsonValue::object_from_pairs(&[
1703                        ("attr", JsonValue::string("y")),
1704                        ("operation", JsonValue::string("set")),
1705                        ("value", JsonValue::Integer(42)),
1706                    ]),
1707                ),
1708            ]),
1709        ]);
1710        let while_instr = JsonValue::object_from_pairs(&[
1711            ("type", JsonValue::string("while_loop")),
1712            (
1713                "params",
1714                JsonValue::object_from_pairs(&[
1715                    ("body", body_array),
1716                    (
1717                        "condition",
1718                        JsonValue::object_from_pairs(&[
1719                            ("type", JsonValue::string("lt")),
1720                            ("path", JsonValue::string("__exec__.payload.x")),
1721                            ("value", JsonValue::Integer(10)),
1722                        ]),
1723                    ),
1724                ]),
1725            ),
1726        ]);
1727        let state = make_exec_state_with_instruction(while_instr, make_payload(0), vec![]);
1728
1729        let push_instr = JsonValue::object_from_pairs(&[
1730            ("type", JsonValue::string("push")),
1731            (
1732                "params",
1733                JsonValue::object_from_pairs(&[(
1734                    "instructions",
1735                    JsonValue::array(vec![
1736                        JsonValue::string("__exec__.instruction.params.body"),
1737                        JsonValue::string("__exec__.instruction"),
1738                    ]),
1739                )]),
1740            ),
1741        ]);
1742
1743        let result = exec_push(&push_instr, state).unwrap();
1744        let queue = resolve_path(&result, "__exec__.queue").unwrap();
1745        let arr = queue.as_array().unwrap();
1746        assert_eq!(arr.len(), 3);
1747        assert_eq!(
1748            arr[0].get("type").and_then(|v| v.as_str()),
1749            Some("increment")
1750        );
1751        assert_eq!(arr[1].get("type").and_then(|v| v.as_str()), Some("set"));
1752        assert_eq!(
1753            arr[2].get("type").and_then(|v| v.as_str()),
1754            Some("while_loop")
1755        );
1756    }
1757
1758    // ===== branch 测试 =====
1759
1760    #[test]
1761    fn test_branch_true() {
1762        let state = make_exec_state("branch", make_payload(10), vec![]);
1763        let instr = JsonValue::object_from_pairs(&[
1764            ("type", JsonValue::string("branch")),
1765            (
1766                "params",
1767                JsonValue::object_from_pairs(&[
1768                    (
1769                        "domain",
1770                        JsonValue::object_from_pairs(&[
1771                            ("type", JsonValue::string("eq")),
1772                            ("path", JsonValue::string("__exec__.payload.x")),
1773                            ("value", JsonValue::Integer(10)),
1774                        ]),
1775                    ),
1776                    (
1777                        "on_true",
1778                        JsonValue::array(vec![JsonValue::object_from_pairs(&[
1779                            ("type", JsonValue::string("set")),
1780                            (
1781                                "params",
1782                                JsonValue::object_from_pairs(&[
1783                                    ("attr", JsonValue::string("x")),
1784                                    ("operation", JsonValue::string("set")),
1785                                    ("value", JsonValue::Integer(1)),
1786                                ]),
1787                            ),
1788                        ])]),
1789                    ),
1790                ]),
1791            ),
1792        ]);
1793
1794        let result = execute_meta_instruction(&instr, state, 0).unwrap();
1795        match result {
1796            MetaInstructionResult::State(new_state) => {
1797                let x = resolve_path(&new_state, "__exec__.payload.x").unwrap();
1798                assert_eq!(x, &JsonValue::Integer(1));
1799            }
1800            _ => panic!("expected State"),
1801        }
1802    }
1803
1804    #[test]
1805    fn test_branch_false() {
1806        let state = make_exec_state("branch", make_payload(5), vec![]);
1807        let instr = JsonValue::object_from_pairs(&[
1808            ("type", JsonValue::string("branch")),
1809            (
1810                "params",
1811                JsonValue::object_from_pairs(&[
1812                    (
1813                        "domain",
1814                        JsonValue::object_from_pairs(&[
1815                            ("type", JsonValue::string("eq")),
1816                            ("path", JsonValue::string("__exec__.payload.x")),
1817                            ("value", JsonValue::Integer(10)),
1818                        ]),
1819                    ),
1820                    (
1821                        "on_false",
1822                        JsonValue::array(vec![JsonValue::object_from_pairs(&[
1823                            ("type", JsonValue::string("set")),
1824                            (
1825                                "params",
1826                                JsonValue::object_from_pairs(&[
1827                                    ("attr", JsonValue::string("x")),
1828                                    ("operation", JsonValue::string("set")),
1829                                    ("value", JsonValue::Integer(2)),
1830                                ]),
1831                            ),
1832                        ])]),
1833                    ),
1834                ]),
1835            ),
1836        ]);
1837
1838        let result = execute_meta_instruction(&instr, state, 0).unwrap();
1839        match result {
1840            MetaInstructionResult::State(new_state) => {
1841                let x = resolve_path(&new_state, "__exec__.payload.x").unwrap();
1842                assert_eq!(x, &JsonValue::Integer(2));
1843            }
1844            _ => panic!("expected State"),
1845        }
1846    }
1847
1848    #[test]
1849    fn test_branch_with_both_branches() {
1850        let state = make_exec_state("branch", make_payload(5), vec![]);
1851        let instr = JsonValue::object_from_pairs(&[
1852            ("type", JsonValue::string("branch")),
1853            (
1854                "params",
1855                JsonValue::object_from_pairs(&[
1856                    (
1857                        "domain",
1858                        JsonValue::object_from_pairs(&[
1859                            ("type", JsonValue::string("eq")),
1860                            ("path", JsonValue::string("__exec__.payload.x")),
1861                            ("value", JsonValue::Integer(10)),
1862                        ]),
1863                    ),
1864                    (
1865                        "on_true",
1866                        JsonValue::array(vec![JsonValue::object_from_pairs(&[
1867                            ("type", JsonValue::string("set")),
1868                            (
1869                                "params",
1870                                JsonValue::object_from_pairs(&[
1871                                    ("attr", JsonValue::string("x")),
1872                                    ("operation", JsonValue::string("set")),
1873                                    ("value", JsonValue::Integer(1)),
1874                                ]),
1875                            ),
1876                        ])]),
1877                    ),
1878                    (
1879                        "on_false",
1880                        JsonValue::array(vec![JsonValue::object_from_pairs(&[
1881                            ("type", JsonValue::string("set")),
1882                            (
1883                                "params",
1884                                JsonValue::object_from_pairs(&[
1885                                    ("attr", JsonValue::string("x")),
1886                                    ("operation", JsonValue::string("set")),
1887                                    ("value", JsonValue::Integer(2)),
1888                                ]),
1889                            ),
1890                        ])]),
1891                    ),
1892                ]),
1893            ),
1894        ]);
1895
1896        let result = execute_meta_instruction(&instr, state, 0).unwrap();
1897        match result {
1898            MetaInstructionResult::State(new_state) => {
1899                let x = resolve_path(&new_state, "__exec__.payload.x").unwrap();
1900                assert_eq!(x, &JsonValue::Integer(2));
1901            }
1902            _ => panic!("expected State"),
1903        }
1904    }
1905
1906    #[test]
1907    fn test_branch_no_matching_branch_returns_state_unchanged() {
1908        let state = make_exec_state("branch", make_payload(5), vec![]);
1909        let instr = JsonValue::object_from_pairs(&[
1910            ("type", JsonValue::string("branch")),
1911            (
1912                "params",
1913                JsonValue::object_from_pairs(&[
1914                    (
1915                        "domain",
1916                        JsonValue::object_from_pairs(&[
1917                            ("type", JsonValue::string("eq")),
1918                            ("path", JsonValue::string("__exec__.payload.x")),
1919                            ("value", JsonValue::Integer(10)),
1920                        ]),
1921                    ),
1922                    (
1923                        "on_true",
1924                        JsonValue::array(vec![JsonValue::object_from_pairs(&[
1925                            ("type", JsonValue::string("set")),
1926                            (
1927                                "params",
1928                                JsonValue::object_from_pairs(&[
1929                                    ("attr", JsonValue::string("x")),
1930                                    ("operation", JsonValue::string("set")),
1931                                    ("value", JsonValue::Integer(1)),
1932                                ]),
1933                            ),
1934                        ])]),
1935                    ),
1936                ]),
1937            ),
1938        ]);
1939
1940        let result = execute_meta_instruction(&instr, state.clone(), 0).unwrap();
1941        match result {
1942            MetaInstructionResult::State(new_state) => {
1943                let x = resolve_path(&new_state, "__exec__.payload.x").unwrap();
1944                assert_eq!(x, &JsonValue::Integer(5));
1945            }
1946            _ => panic!("expected State"),
1947        }
1948    }
1949
1950    #[test]
1951    fn test_branch_depth_limit() {
1952        let state = make_exec_state("branch", make_payload(0), vec![]);
1953        let instr = JsonValue::object_from_pairs(&[
1954            ("type", JsonValue::string("branch")),
1955            (
1956                "params",
1957                JsonValue::object_from_pairs(&[
1958                    (
1959                        "domain",
1960                        JsonValue::object_from_pairs(&[
1961                            ("type", JsonValue::string("eq")),
1962                            ("path", JsonValue::string("__exec__.payload.x")),
1963                            ("value", JsonValue::Integer(0)),
1964                        ]),
1965                    ),
1966                    ("on_true", JsonValue::array(vec![])),
1967                ]),
1968            ),
1969        ]);
1970
1971        // depth = 63 (MAX-1) 应该可以执行(预算充足)
1972        let mut budget = MAX_TOTAL_META_INSTRUCTIONS;
1973        let mut hit = false;
1974        let result = exec_branch(&instr, state.clone(), 63, &mut budget, &mut hit, &mut None);
1975        assert!(result.is_ok());
1976
1977        // depth = 64 (MAX) 应该返回 NestingTooDeep(深度检查先于预算扣减)
1978        let mut budget2 = MAX_TOTAL_META_INSTRUCTIONS;
1979        let mut hit2 = false;
1980        let result = exec_branch(
1981            &instr,
1982            state,
1983            MAX_BRANCH_DEPTH,
1984            &mut budget2,
1985            &mut hit2,
1986            &mut None,
1987        );
1988        assert!(matches!(result, Err(TcbError::NestingTooDeep { .. })));
1989    }
1990
1991    /// branch 递归深度必须沿调用链逐层传递:65 层嵌套 branch(经
1992    /// `depth + 1` 递归传入)在子层触顶报错。直接以 depth=MAX 调
1993    /// `exec_branch` 只覆盖门检查本身,测不到传递链——若深度增量丢失
1994    /// (恒为同层),超深嵌套会静默执行到底。
1995    #[test]
1996    fn test_branch_recursion_depth_via_nested_branches() {
1997        let domain = JsonValue::object_from_pairs(&[
1998            ("type", JsonValue::string("exists")),
1999            ("path", JsonValue::string("__exec__.payload.x")),
2000        ]);
2001        let make_branch = |inner: JsonValue| {
2002            JsonValue::object_from_pairs(&[
2003                ("type", JsonValue::string("branch")),
2004                (
2005                    "params",
2006                    JsonValue::object_from_pairs(&[
2007                        ("domain", domain.clone()),
2008                        ("on_true", JsonValue::array(vec![inner])),
2009                    ]),
2010                ),
2011            ])
2012        };
2013
2014        let state = make_exec_state("branch", make_payload(1), vec![]);
2015        let mut instr = make_instruction_simple("set", 1);
2016        for _ in 0..65 {
2017            instr = make_branch(instr);
2018        }
2019
2020        let mut budget = MAX_TOTAL_META_INSTRUCTIONS;
2021        let mut hit = false;
2022        let result =
2023            execute_meta_instruction_budgeted(&instr, state, 0, &mut budget, &mut hit, &mut None);
2024        assert!(matches!(result, Err(TcbError::NestingTooDeep { .. })));
2025    }
2026
2027    /// `resolve_instructions_list` 元素级路径引用的形态判别:`__` 前缀
2028    /// 字符串解析为状态引用,普通字符串必须原样保留(误当路径解析即
2029    /// PathResolutionFailed,push 的字面指令清单从此无法携带普通字符串)
2030    #[test]
2031    fn test_resolve_instructions_list_plain_strings_verbatim() {
2032        let state = make_exec_state("push", make_payload(7), vec![]);
2033        let instrs = JsonValue::array(vec![
2034            JsonValue::string("__exec__.payload.x"),
2035            JsonValue::string("plain_literal"),
2036        ]);
2037
2038        let resolved = resolve_instructions_list(&state, Some(&instrs)).unwrap();
2039        assert_eq!(
2040            resolved,
2041            vec![JsonValue::Integer(7), JsonValue::string("plain_literal"),]
2042        );
2043    }
2044
2045    // ===== M6 元指令执行总数预算测试 =====
2046
2047    #[test]
2048    fn test_budget_zero_returns_error() {
2049        let state = make_exec_state("set", make_payload(0), vec![]);
2050        let instr = make_instruction(
2051            "set",
2052            &[
2053                ("attr", JsonValue::string("x")),
2054                ("operation", JsonValue::string("set")),
2055                ("value", JsonValue::Integer(1)),
2056            ],
2057        );
2058
2059        let mut budget = 0usize;
2060        let mut hit = false;
2061        let result =
2062            execute_meta_instruction_budgeted(&instr, state, 0, &mut budget, &mut hit, &mut None);
2063        assert!(
2064            matches!(result, Err(TcbError::TooManyExecutedInstructions { limit }) if limit == MAX_TOTAL_META_INSTRUCTIONS)
2065        );
2066    }
2067
2068    #[test]
2069    fn test_budget_single_instruction_consumes_one() {
2070        let state = make_exec_state("set", make_payload(0), vec![]);
2071        let instr = make_instruction(
2072            "set",
2073            &[
2074                ("attr", JsonValue::string("x")),
2075                ("operation", JsonValue::string("set")),
2076                ("value", JsonValue::Integer(7)),
2077            ],
2078        );
2079
2080        let mut budget = 1usize;
2081        let mut hit = false;
2082        let result =
2083            execute_meta_instruction_budgeted(&instr, state, 0, &mut budget, &mut hit, &mut None)
2084                .unwrap();
2085        assert!(matches!(result, MetaInstructionResult::State(_)));
2086        // 单条指令恰好耗尽预算
2087        assert_eq!(budget, 0);
2088    }
2089
2090    #[test]
2091    fn test_branch_sub_instructions_share_budget() {
2092        // branch(1) + 2 个子指令 = 共 3 个预算单位
2093        let instr = JsonValue::object_from_pairs(&[
2094            ("type", JsonValue::string("branch")),
2095            (
2096                "params",
2097                JsonValue::object_from_pairs(&[
2098                    (
2099                        "domain",
2100                        JsonValue::object_from_pairs(&[
2101                            ("type", JsonValue::string("eq")),
2102                            ("path", JsonValue::string("__exec__.payload.x")),
2103                            ("value", JsonValue::Integer(0)),
2104                        ]),
2105                    ),
2106                    (
2107                        "on_true",
2108                        JsonValue::array(vec![
2109                            make_instruction(
2110                                "set",
2111                                &[
2112                                    ("attr", JsonValue::string("x")),
2113                                    ("operation", JsonValue::string("set")),
2114                                    ("value", JsonValue::Integer(1)),
2115                                ],
2116                            ),
2117                            make_instruction(
2118                                "set",
2119                                &[
2120                                    ("attr", JsonValue::string("x")),
2121                                    ("operation", JsonValue::string("set")),
2122                                    ("value", JsonValue::Integer(2)),
2123                                ],
2124                            ),
2125                        ]),
2126                    ),
2127                ]),
2128            ),
2129        ]);
2130
2131        // 预算 = 2(不足 3):应报错,不允许部分执行后静默成功
2132        let state = make_exec_state("branch", make_payload(0), vec![]);
2133        let mut budget = 2usize;
2134        let mut hit = false;
2135        let result =
2136            execute_meta_instruction_budgeted(&instr, state, 0, &mut budget, &mut hit, &mut None);
2137        assert!(matches!(
2138            result,
2139            Err(TcbError::TooManyExecutedInstructions { .. })
2140        ));
2141
2142        // 预算 = 3(恰好):应成功
2143        let state = make_exec_state("branch", make_payload(0), vec![]);
2144        let mut budget = 3usize;
2145        let mut hit2 = false;
2146        let result =
2147            execute_meta_instruction_budgeted(&instr, state, 0, &mut budget, &mut hit2, &mut None)
2148                .unwrap();
2149        match result {
2150            MetaInstructionResult::State(new_state) => {
2151                let x = resolve_path(&new_state, "__exec__.payload.x").unwrap();
2152                assert_eq!(x, &JsonValue::Integer(2));
2153            }
2154            _ => panic!("expected State"),
2155        }
2156        assert_eq!(budget, 0);
2157    }
2158
2159    #[test]
2160    fn test_budget_error_reports_limit_constant() {
2161        let state = make_exec_state("set", make_payload(0), vec![]);
2162        let instr = make_instruction(
2163            "set",
2164            &[
2165                ("attr", JsonValue::string("x")),
2166                ("operation", JsonValue::string("set")),
2167                ("value", JsonValue::Integer(1)),
2168            ],
2169        );
2170
2171        let mut budget = 0usize;
2172        let mut hit = false;
2173        let err =
2174            execute_meta_instruction_budgeted(&instr, state, 0, &mut budget, &mut hit, &mut None)
2175                .unwrap_err();
2176        match err {
2177            TcbError::TooManyExecutedInstructions { limit } => {
2178                assert_eq!(limit, MAX_TOTAL_META_INSTRUCTIONS);
2179                assert_eq!(limit, 2048);
2180            }
2181            other => panic!("unexpected error: {:?}", other),
2182        }
2183    }
2184
2185    // ===== io_request 测试 =====
2186
2187    #[test]
2188    fn test_io_request_basic() {
2189        let state = make_exec_state("call_external", make_payload(0), vec![]);
2190        let instr = JsonValue::object_from_pairs(&[
2191            ("type", JsonValue::string("io_request")),
2192            (
2193                "params",
2194                JsonValue::object_from_pairs(&[
2195                    ("io_type", JsonValue::string("call_external")),
2196                    ("prompt", JsonValue::string("Hello")),
2197                ]),
2198            ),
2199        ]);
2200
2201        let result = exec_io_request(&instr, state).unwrap();
2202        match result {
2203            MetaInstructionResult::IoRequired { io_type, params } => {
2204                assert_eq!(io_type, "call_external");
2205                assert_eq!(params.get("prompt").and_then(|v| v.as_str()), Some("Hello"));
2206                assert!(params.get("io_type").is_none());
2207            }
2208            _ => panic!("expected IoRequired"),
2209        }
2210    }
2211
2212    #[test]
2213    fn test_io_request_path_resolution() {
2214        let instruction = JsonValue::object_from_pairs(&[
2215            ("type", JsonValue::string("call_external")),
2216            (
2217                "params",
2218                JsonValue::object_from_pairs(&[("prompt", JsonValue::string("Summarize this"))]),
2219            ),
2220        ]);
2221        let state = make_exec_state_with_instruction(instruction, make_payload(0), vec![]);
2222
2223        let io_instr = JsonValue::object_from_pairs(&[
2224            ("type", JsonValue::string("io_request")),
2225            (
2226                "params",
2227                JsonValue::object_from_pairs(&[
2228                    ("io_type", JsonValue::string("call_external")),
2229                    (
2230                        "prompt",
2231                        JsonValue::string("__exec__.instruction.params.prompt"),
2232                    ),
2233                ]),
2234            ),
2235        ]);
2236
2237        let result = exec_io_request(&io_instr, state).unwrap();
2238        match result {
2239            MetaInstructionResult::IoRequired { io_type, params } => {
2240                assert_eq!(io_type, "call_external");
2241                assert_eq!(
2242                    params.get("prompt").and_then(|v| v.as_str()),
2243                    Some("Summarize this")
2244                );
2245            }
2246            _ => panic!("expected IoRequired"),
2247        }
2248    }
2249
2250    #[test]
2251    fn test_io_request_does_not_modify_state() {
2252        let state = make_exec_state("call_external", make_payload(42), vec![]);
2253        let state_snapshot = state.clone();
2254
2255        let instr = JsonValue::object_from_pairs(&[
2256            ("type", JsonValue::string("io_request")),
2257            (
2258                "params",
2259                JsonValue::object_from_pairs(&[
2260                    ("io_type", JsonValue::string("call_external")),
2261                    ("prompt", JsonValue::string("test")),
2262                ]),
2263            ),
2264        ]);
2265
2266        let result = exec_io_request(&instr, state).unwrap();
2267        assert!(matches!(result, MetaInstructionResult::IoRequired { .. }));
2268        assert_eq!(state_snapshot, state_snapshot);
2269    }
2270
2271    #[test]
2272    fn test_io_request_optional_params_skipped_when_path_not_found() {
2273        let instruction = JsonValue::object_from_pairs(&[
2274            ("type", JsonValue::string("call_external")),
2275            (
2276                "params",
2277                JsonValue::object_from_pairs(&[("prompt", JsonValue::string("hello"))]),
2278            ),
2279        ]);
2280        let state = make_exec_state_with_instruction(instruction, make_payload(0), vec![]);
2281
2282        let io_instr = JsonValue::object_from_pairs(&[
2283            ("type", JsonValue::string("io_request")),
2284            (
2285                "params",
2286                JsonValue::object_from_pairs(&[
2287                    ("io_type", JsonValue::string("call_external")),
2288                    (
2289                        "prompt",
2290                        JsonValue::string("__exec__.instruction.params.prompt"),
2291                    ),
2292                    (
2293                        "temperature?",
2294                        JsonValue::string("__exec__.instruction.params.temperature"),
2295                    ),
2296                    (
2297                        "max_tokens?",
2298                        JsonValue::string("__exec__.instruction.params.max_tokens"),
2299                    ),
2300                ]),
2301            ),
2302        ]);
2303
2304        let result = exec_io_request(&io_instr, state).unwrap();
2305        match result {
2306            MetaInstructionResult::IoRequired { io_type, params } => {
2307                assert_eq!(io_type, "call_external");
2308                assert_eq!(params.get("prompt").and_then(|v| v.as_str()), Some("hello"));
2309                assert!(params.get("temperature").is_none());
2310                assert!(params.get("max_tokens").is_none());
2311            }
2312            _ => panic!("expected IoRequired"),
2313        }
2314    }
2315
2316    #[test]
2317    fn test_io_request_required_param_path_failure_errors() {
2318        let instruction = JsonValue::object_from_pairs(&[
2319            ("type", JsonValue::string("call_external")),
2320            (
2321                "params",
2322                JsonValue::object_from_pairs(&[("prompt", JsonValue::string("hello"))]),
2323            ),
2324        ]);
2325        let state = make_exec_state_with_instruction(instruction, make_payload(0), vec![]);
2326
2327        // messaegs 是拼写错误的必选参数(正确应为 messages):
2328        // 必须显式报错,不得静默跳过
2329        let io_instr = JsonValue::object_from_pairs(&[
2330            ("type", JsonValue::string("io_request")),
2331            (
2332                "params",
2333                JsonValue::object_from_pairs(&[
2334                    ("io_type", JsonValue::string("call_external")),
2335                    (
2336                        "messaegs",
2337                        JsonValue::string("__exec__.instruction.params.messaegs"),
2338                    ),
2339                ]),
2340            ),
2341        ]);
2342
2343        let result = exec_io_request(&io_instr, state);
2344        assert!(matches!(
2345            result,
2346            Err(TcbError::PathResolutionFailed { ref path, .. }) if path == "__exec__.instruction.params.messaegs"
2347        ));
2348    }
2349
2350    #[test]
2351    fn test_io_request_optional_param_key_stripped_when_present() {
2352        // 带 '?' 后缀的可选参数在路径存在时:正常包含,且请求键名去掉 '?'
2353        let instruction = JsonValue::object_from_pairs(&[
2354            ("type", JsonValue::string("call_external")),
2355            (
2356                "params",
2357                JsonValue::object_from_pairs(&[
2358                    ("prompt", JsonValue::string("hello")),
2359                    ("temperature", JsonValue::Integer(7)),
2360                ]),
2361            ),
2362        ]);
2363        let state = make_exec_state_with_instruction(instruction, make_payload(0), vec![]);
2364
2365        let io_instr = JsonValue::object_from_pairs(&[
2366            ("type", JsonValue::string("io_request")),
2367            (
2368                "params",
2369                JsonValue::object_from_pairs(&[
2370                    ("io_type", JsonValue::string("call_external")),
2371                    (
2372                        "prompt",
2373                        JsonValue::string("__exec__.instruction.params.prompt"),
2374                    ),
2375                    (
2376                        "temperature?",
2377                        JsonValue::string("__exec__.instruction.params.temperature"),
2378                    ),
2379                ]),
2380            ),
2381        ]);
2382
2383        let result = exec_io_request(&io_instr, state).unwrap();
2384        match result {
2385            MetaInstructionResult::IoRequired { params, .. } => {
2386                assert_eq!(params.get("prompt").and_then(|v| v.as_str()), Some("hello"));
2387                assert_eq!(params.get("temperature"), Some(&JsonValue::Integer(7)));
2388                // 键名不带 '?' 后缀
2389                assert!(params.get("temperature?").is_none());
2390            }
2391            _ => panic!("expected IoRequired"),
2392        }
2393    }
2394
2395    #[test]
2396    fn test_io_request_missing_io_type() {
2397        let state = make_exec_state("call_external", make_payload(0), vec![]);
2398        let instr = JsonValue::object_from_pairs(&[
2399            ("type", JsonValue::string("io_request")),
2400            (
2401                "params",
2402                JsonValue::object_from_pairs(&[("prompt", JsonValue::string("test"))]),
2403            ),
2404        ]);
2405
2406        let result = exec_io_request(&instr, state);
2407        assert!(matches!(result, Err(TcbError::MissingField { field }) if field == "io_type"));
2408    }
2409
2410    #[test]
2411    fn test_io_request_missing_params() {
2412        let state = make_exec_state("call_external", make_payload(0), vec![]);
2413        let instr = JsonValue::object_from_pairs(&[("type", JsonValue::string("io_request"))]);
2414
2415        let result = exec_io_request(&instr, state);
2416        assert!(matches!(result, Err(TcbError::MissingField { field }) if field == "params"));
2417    }
2418
2419    #[test]
2420    fn test_io_request_in_branch_propagates() {
2421        let state = make_exec_state("call_external", make_payload(10), vec![]);
2422        let instr = JsonValue::object_from_pairs(&[
2423            ("type", JsonValue::string("branch")),
2424            (
2425                "params",
2426                JsonValue::object_from_pairs(&[
2427                    (
2428                        "domain",
2429                        JsonValue::object_from_pairs(&[
2430                            ("type", JsonValue::string("eq")),
2431                            ("path", JsonValue::string("__exec__.payload.x")),
2432                            ("value", JsonValue::Integer(10)),
2433                        ]),
2434                    ),
2435                    (
2436                        "on_true",
2437                        JsonValue::array(vec![JsonValue::object_from_pairs(&[
2438                            ("type", JsonValue::string("io_request")),
2439                            (
2440                                "params",
2441                                JsonValue::object_from_pairs(&[
2442                                    ("io_type", JsonValue::string("call_external")),
2443                                    ("prompt", JsonValue::string("hi")),
2444                                ]),
2445                            ),
2446                        ])]),
2447                    ),
2448                ]),
2449            ),
2450        ]);
2451
2452        let result = execute_meta_instruction(&instr, state, 0).unwrap();
2453        match result {
2454            MetaInstructionResult::IoRequired { io_type, .. } => {
2455                assert_eq!(io_type, "call_external");
2456            }
2457            _ => panic!("expected IoRequired"),
2458        }
2459    }
2460
2461    #[test]
2462    fn test_io_request_stops_subsequent_instructions() {
2463        let state = make_exec_state("call_external", make_payload(10), vec![]);
2464        let instr = JsonValue::object_from_pairs(&[
2465            ("type", JsonValue::string("branch")),
2466            (
2467                "params",
2468                JsonValue::object_from_pairs(&[
2469                    (
2470                        "domain",
2471                        JsonValue::object_from_pairs(&[
2472                            ("type", JsonValue::string("eq")),
2473                            ("path", JsonValue::string("__exec__.payload.x")),
2474                            ("value", JsonValue::Integer(10)),
2475                        ]),
2476                    ),
2477                    (
2478                        "on_true",
2479                        JsonValue::array(vec![
2480                            JsonValue::object_from_pairs(&[
2481                                ("type", JsonValue::string("io_request")),
2482                                (
2483                                    "params",
2484                                    JsonValue::object_from_pairs(&[
2485                                        ("io_type", JsonValue::string("call_external")),
2486                                        ("prompt", JsonValue::string("hi")),
2487                                    ]),
2488                                ),
2489                            ]),
2490                            JsonValue::object_from_pairs(&[
2491                                ("type", JsonValue::string("set")),
2492                                (
2493                                    "params",
2494                                    JsonValue::object_from_pairs(&[
2495                                        ("attr", JsonValue::string("x")),
2496                                        ("operation", JsonValue::string("set")),
2497                                        ("value", JsonValue::Integer(999)),
2498                                    ]),
2499                                ),
2500                            ]),
2501                        ]),
2502                    ),
2503                ]),
2504            ),
2505        ]);
2506
2507        let result = execute_meta_instruction(&instr, state, 0).unwrap();
2508        match result {
2509            MetaInstructionResult::IoRequired { io_type, .. } => {
2510                assert_eq!(io_type, "call_external");
2511            }
2512            _ => panic!("expected IoRequired"),
2513        }
2514    }
2515
2516    #[test]
2517    fn test_io_request_in_on_false_propagates() {
2518        let state = make_exec_state("fallback", make_payload(5), vec![]);
2519        let instr = JsonValue::object_from_pairs(&[
2520            ("type", JsonValue::string("branch")),
2521            (
2522                "params",
2523                JsonValue::object_from_pairs(&[
2524                    (
2525                        "domain",
2526                        JsonValue::object_from_pairs(&[
2527                            ("type", JsonValue::string("eq")),
2528                            ("path", JsonValue::string("__exec__.payload.x")),
2529                            ("value", JsonValue::Integer(100)),
2530                        ]),
2531                    ),
2532                    ("on_true", JsonValue::array(vec![])),
2533                    (
2534                        "on_false",
2535                        JsonValue::array(vec![JsonValue::object_from_pairs(&[
2536                            ("type", JsonValue::string("io_request")),
2537                            (
2538                                "params",
2539                                JsonValue::object_from_pairs(&[
2540                                    ("io_type", JsonValue::string("fallback_handler")),
2541                                    ("reason", JsonValue::string("primary_failed")),
2542                                ]),
2543                            ),
2544                        ])]),
2545                    ),
2546                ]),
2547            ),
2548        ]);
2549
2550        let result = execute_meta_instruction(&instr, state, 0).unwrap();
2551        match result {
2552            MetaInstructionResult::IoRequired { io_type, params } => {
2553                assert_eq!(io_type, "fallback_handler");
2554                assert_eq!(
2555                    params.get("reason").and_then(|v| v.as_str()),
2556                    Some("primary_failed")
2557                );
2558            }
2559            _ => panic!("expected IoRequired"),
2560        }
2561    }
2562
2563    #[test]
2564    fn test_io_request_nested_two_layers_propagates() {
2565        let state = make_exec_state("call_external", make_payload(10), vec![]);
2566        let inner_branch = JsonValue::object_from_pairs(&[
2567            ("type", JsonValue::string("branch")),
2568            (
2569                "params",
2570                JsonValue::object_from_pairs(&[
2571                    (
2572                        "domain",
2573                        JsonValue::object_from_pairs(&[
2574                            ("type", JsonValue::string("eq")),
2575                            ("path", JsonValue::string("__exec__.payload.x")),
2576                            ("value", JsonValue::Integer(10)),
2577                        ]),
2578                    ),
2579                    (
2580                        "on_true",
2581                        JsonValue::array(vec![JsonValue::object_from_pairs(&[
2582                            ("type", JsonValue::string("io_request")),
2583                            (
2584                                "params",
2585                                JsonValue::object_from_pairs(&[
2586                                    ("io_type", JsonValue::string("call_external")),
2587                                    ("prompt", JsonValue::string("nested")),
2588                                ]),
2589                            ),
2590                        ])]),
2591                    ),
2592                ]),
2593            ),
2594        ]);
2595        let outer_branch = JsonValue::object_from_pairs(&[
2596            ("type", JsonValue::string("branch")),
2597            (
2598                "params",
2599                JsonValue::object_from_pairs(&[
2600                    (
2601                        "domain",
2602                        JsonValue::object_from_pairs(&[
2603                            ("type", JsonValue::string("eq")),
2604                            ("path", JsonValue::string("__exec__.payload.x")),
2605                            ("value", JsonValue::Integer(10)),
2606                        ]),
2607                    ),
2608                    ("on_true", JsonValue::array(vec![inner_branch])),
2609                ]),
2610            ),
2611        ]);
2612
2613        let result = execute_meta_instruction(&outer_branch, state, 0).unwrap();
2614        match result {
2615            MetaInstructionResult::IoRequired { io_type, params } => {
2616                assert_eq!(io_type, "call_external");
2617                assert_eq!(
2618                    params.get("prompt").and_then(|v| v.as_str()),
2619                    Some("nested")
2620                );
2621            }
2622            _ => panic!("expected IoRequired"),
2623        }
2624    }
2625
2626    // ===== 未知元指令测试 =====
2627
2628    #[test]
2629    fn test_unknown_meta_instruction() {
2630        let state = make_exec_state("unknown", make_payload(0), vec![]);
2631        let instr = JsonValue::object_from_pairs(&[
2632            ("type", JsonValue::string("unknown_op")),
2633            ("params", JsonValue::object_from_pairs(&[])),
2634        ]);
2635
2636        let result = execute_meta_instruction(&instr, state, 0);
2637        assert!(
2638            matches!(result, Err(TcbError::UnknownMetaInstruction { meta_type }) if meta_type == "unknown_op")
2639        );
2640    }
2641
2642    #[test]
2643    fn test_missing_type_field() {
2644        let state = make_exec_state("noop", make_payload(0), vec![]);
2645        let instr = JsonValue::object_from_pairs(&[("params", JsonValue::object_from_pairs(&[]))]);
2646
2647        let result = execute_meta_instruction(&instr, state, 0);
2648        assert!(matches!(result, Err(TcbError::MissingField { field }) if field == "type"));
2649    }
2650
2651    // ===== 字面量指令测试 =====
2652
2653    #[test]
2654    fn test_push_with_literal_object() {
2655        let state = make_exec_state("while_loop", make_payload(0), vec![]);
2656        let push_instr = JsonValue::object_from_pairs(&[
2657            ("type", JsonValue::string("push")),
2658            (
2659                "params",
2660                JsonValue::object_from_pairs(&[(
2661                    "instructions",
2662                    JsonValue::array(vec![JsonValue::object_from_pairs(&[(
2663                        "type",
2664                        JsonValue::string("noop"),
2665                    )])]),
2666                )]),
2667            ),
2668        ]);
2669
2670        let result = exec_push(&push_instr, state).unwrap();
2671        let queue = resolve_path(&result, "__exec__.queue").unwrap();
2672        let arr = queue.as_array().unwrap();
2673        assert_eq!(arr.len(), 1);
2674        assert_eq!(arr[0].get("type").and_then(|v| v.as_str()), Some("noop"));
2675    }
2676
2677    #[test]
2678    fn test_io_request_literal_params_always_included() {
2679        let state = make_exec_state("call_external", make_payload(0), vec![]);
2680        let io_instr = JsonValue::object_from_pairs(&[
2681            ("type", JsonValue::string("io_request")),
2682            (
2683                "params",
2684                JsonValue::object_from_pairs(&[
2685                    ("io_type", JsonValue::string("call_external")),
2686                    ("prompt", JsonValue::string("fixed_prompt")),
2687                    ("timeout_ms", JsonValue::Integer(5000)),
2688                ]),
2689            ),
2690        ]);
2691
2692        let result = exec_io_request(&io_instr, state).unwrap();
2693        match result {
2694            MetaInstructionResult::IoRequired { params, .. } => {
2695                assert_eq!(
2696                    params.get("prompt").and_then(|v| v.as_str()),
2697                    Some("fixed_prompt")
2698                );
2699                assert_eq!(params.get("timeout_ms"), Some(&JsonValue::Integer(5000)));
2700            }
2701            _ => panic!("expected IoRequired"),
2702        }
2703    }
2704
2705    mod react_tests {
2706        use super::*;
2707        use crate::value::{JsonValue, ObjectMap};
2708        use alloc::vec;
2709
2710        /// 构建包含 tool_calls 的 llm_response 状态
2711        fn make_state_with_tool_calls() -> JsonValue {
2712            let tool_call1 = JsonValue::object_from_pairs(&[
2713                ("name", JsonValue::string("get_weather")),
2714                (
2715                    "args",
2716                    JsonValue::object_from_pairs(&[("city", JsonValue::string("Beijing"))]),
2717                ),
2718            ]);
2719            let tool_call2 = JsonValue::object_from_pairs(&[
2720                ("name", JsonValue::string("get_time")),
2721                ("args", JsonValue::object_from_pairs(&[])),
2722            ]);
2723
2724            let tool_calls = JsonValue::array(vec![tool_call1, tool_call2]);
2725            let mut llm_response = ObjectMap::new();
2726            llm_response.insert("tool_calls".to_string(), tool_calls);
2727            // 添加消息历史
2728            let messages = JsonValue::array(vec![JsonValue::object_from_pairs(&[
2729                ("role", JsonValue::string("user")),
2730                ("content", JsonValue::string("What's the weather?")),
2731            ])]);
2732            llm_response.insert("messages".to_string(), messages);
2733
2734            let mut payload = ObjectMap::new();
2735            payload.insert("llm_response".to_string(), JsonValue::Object(llm_response));
2736
2737            let mut exec = ObjectMap::new();
2738            exec.insert("payload".to_string(), JsonValue::Object(payload));
2739            exec.insert("queue".to_string(), JsonValue::empty_array());
2740
2741            let mut root = ObjectMap::new();
2742            root.insert("__exec__".to_string(), JsonValue::Object(exec));
2743            JsonValue::Object(root)
2744        }
2745
2746        #[test]
2747        fn test_has_fields_with_tool_calls() {
2748            let state = make_state_with_tool_calls();
2749            let domain = JsonValue::object_from_pairs(&[
2750                ("type", JsonValue::string("has_fields")),
2751                ("path", JsonValue::string("__exec__.payload.llm_response")),
2752                (
2753                    "fields",
2754                    JsonValue::array(vec![JsonValue::string("tool_calls")]),
2755                ),
2756            ]);
2757            assert_eq!(
2758                evaluate_domain_outcome(&domain, &state).unwrap(),
2759                DomainOutcome::Sat
2760            );
2761        }
2762
2763        #[test]
2764        fn test_has_fields_missing_field() {
2765            let state = make_state_with_tool_calls();
2766            let domain = JsonValue::object_from_pairs(&[
2767                ("type", JsonValue::string("has_fields")),
2768                ("path", JsonValue::string("__exec__.payload.llm_response")),
2769                (
2770                    "fields",
2771                    JsonValue::array(vec![JsonValue::string("missing_field")]),
2772                ),
2773            ]);
2774            assert_eq!(
2775                evaluate_domain_outcome(&domain, &state).unwrap(),
2776                DomainOutcome::Unsat
2777            );
2778        }
2779
2780        #[test]
2781        fn test_has_fields_empty_tool_calls_returns_false() {
2782            let mut llm_response = ObjectMap::new();
2783            llm_response.insert("tool_calls".to_string(), JsonValue::empty_array());
2784            let mut payload = ObjectMap::new();
2785            payload.insert("llm_response".to_string(), JsonValue::Object(llm_response));
2786            let mut exec = ObjectMap::new();
2787            exec.insert("payload".to_string(), JsonValue::Object(payload));
2788            let mut root = ObjectMap::new();
2789            root.insert("__exec__".to_string(), JsonValue::Object(exec));
2790            let state = JsonValue::Object(root);
2791
2792            let domain = JsonValue::object_from_pairs(&[
2793                ("type", JsonValue::string("has_fields")),
2794                ("path", JsonValue::string("__exec__.payload.llm_response")),
2795                (
2796                    "fields",
2797                    JsonValue::array(vec![JsonValue::string("tool_calls")]),
2798                ),
2799            ]);
2800            assert_eq!(
2801                evaluate_domain_outcome(&domain, &state).unwrap(),
2802                DomainOutcome::Unsat
2803            );
2804        }
2805    }
2806}