1use 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
25pub const MAX_BRANCH_DEPTH: usize = 64;
27
28pub const MAX_TOTAL_META_INSTRUCTIONS: usize = 2048;
38
39pub const META_INSTRUCTION_TYPES: &[&str] = &["branch", "set", "push", "io_request", "enforce"];
51
52#[derive(Debug, Clone, PartialEq)]
54pub enum MetaInstructionResult {
55 State(JsonValue),
57 IoRequired {
59 io_type: String,
61 params: JsonValue,
63 },
64 Halted {
70 reason: String,
72 },
73}
74
75pub 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
91pub(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 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 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 #[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 }
187 }
188}
189
190fn 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
212pub(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#[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 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 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 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 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 .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
378fn 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(¤t),
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
426enum WriteSlot<'a> {
428 Field(&'a mut ObjectMap, String),
430 Index(&'a mut [JsonValue], usize),
432}
433
434fn 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
483enum DescendStep<'a> {
485 Slot(WriteSlot<'a>),
487 Next(&'a mut JsonValue),
489}
490
491fn 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
549fn 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
617fn 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 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
657fn 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 if instructions.is_empty() {
669 return Ok(state);
670 }
671
672 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 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 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
695fn 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 let outcome = evaluate_domain_outcome(&domain, &state)?;
721
722 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 if !instrs.is_empty() {
739 *hit_out = true;
740 }
741 for sub_instr in instrs {
742 let mut sub_hit = false;
743 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 halted @ MetaInstructionResult::Halted { .. } => return Ok(halted),
759 }
760 }
761 }
762
763 Ok(MetaInstructionResult::State(state))
764}
765
766fn 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 let outcome = evaluate_domain_outcome(&domain, &state)?;
798
799 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
823fn 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 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 Err(TcbError::PathResolutionFailed { .. }) if optional => {}
867 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 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 #[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 #[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 #[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 #[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 #[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 #[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 fn make_payload_with_items() -> JsonValue {
1243 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 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 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 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 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 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 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 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 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 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 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 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 #[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 #[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 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 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 #[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 #[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 #[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 assert_eq!(budget, 0);
2088 }
2089
2090 #[test]
2091 fn test_branch_sub_instructions_share_budget() {
2092 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 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 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 #[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 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 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 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 #[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 #[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 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 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}