On this page

ADR-0294: Unified json.lib.Value Builders & codec derive JsonValue

Context

Tenon provides two complementary JSON layers:

  1. json.lib (plugins/json/lib.tn), which defines the canonical recursive Value AST (Null | Bool(bool) | Num(i64) | Float(f64) | Str(str) | Arr(vec<Value>) | Obj(map<str, Value>)) with exact 64-bit integer fidelity distinct from f64.
  2. codec.json (plugins/codec/json.tn), a GEN_ABI 2 generator (derive Json) that previously emitted only wire-string/bytes serializers (<type>_to_json / <type>_from_json) without direct json.lib.Value conversion.

Callers bridging typed structs/enums and dynamic json.lib.Value trees (such as MCP payloads, state deltas, and action projections) had to either serialize and re-parse intermediate JSON strings or hand-write verbose map().set(...) boilerplate.

Decision

  1. Preserve One Canonical json.lib.Value AST with Zero Breakage

    • Keep json.lib.Value as the single canonical 7-variant enum, retaining Value.Num(i64) alongside Value.Float(f64) so all existing exhaustive matchers (e.g. plugins/state_delta/diff.tn) and constructors across the 69-plugin catalog continue compiling unchanged while preserving exact 64-bit integer fidelity (i64::MIN..i64::MAX).
    • Add as_int (exact i64 alias for as_num) and full type predicates (is_int, is_float, is_bool, is_str, is_arr, is_obj).
  2. Concise json.lib Builder & Chaining API

    • Add JsonEntry, scalar/container constructors (null_val, bool_val, int_val, float_val, str_val, arr, obj_empty, obj), key-value entry helpers (kv, kv_str, kv_int, kv_float, kv_bool, kv_null, kv_arr, kv_opt, kv_opt_str, kv_opt_int, kv_opt_bool), and immutable chaining helpers (with_kv, with_str, with_int, with_float, with_bool, with_opt, push_val).
  3. Extend codec.json (GEN_ABI 2) for Wire Strings and json.lib.Value

    • Extend derive Json to also emit <type>_to_json_str(v: T) -> str and <type>_from_json_str(text: str) -> result<T, JsonError> alongside <type>_to_json / <type>_from_json, keeping 100% compatibility with existing callers that do not depend on json.
    • Add derive JsonValue (codec.json.JsonValue) emitting <type>_to_value(v: T) -> Value and <type>_from_value(v: Value) -> result<T, JsonError> for structs, enums (unit and payload variants), and newtypes, including nested vec, option, map<str, T>, bytes (hex), and cross-module derived types.
    • Following the GEN_ABI 2 sandbox pattern established by app_actions_gen (ADR-0293), modules using derive JsonValue import json.lib { Value }; all generated helper aliases use a disjoint __codec_val_<type>_* prefix so a type can derive both Json and JsonValue in the same module.
    • Add integer range-validation helpers (value_to_i32, value_to_u8, value_to_u32, value_to_u64) to codec.rt so from_value fails closed on out-of-range integers, wrong JSON types, floats passed for integer fields, missing fields, unknown fields, and malformed enum variants.

Consequences