agent-first-data 0.40.0

A naming convention that lets AI agents understand your data without being told what it means, plus the afdata CLI and a Rust library for reading Markdown structure and safely editing structured JSON, TOML, YAML, dotenv, and INI documents.
Documentation
package afdata

import (
	"crypto/sha256"
	"encoding/json"
	"errors"
	"math"
	"reflect"
	"testing"
	"time"
)

type nativeProgress struct {
	Done  int     `json:"done"`
	Ratio float64 `json:"ratio"`
	Note  string  `json:"note"`
}

func TestNativeStructNaNMarksOnlyLeaf(t *testing.T) {
	got := sanitizeForJSON(nativeProgress{Done: 3, Ratio: math.NaN(), Note: "ok"}).(map[string]any)
	if got["ratio"] != "<unsupported:number>" || got["note"] != "ok" || got["done"] != json.Number("3") {
		t.Fatalf("got %#v", got)
	}
}

func TestNativeProgressStructKeepsPayloadAndTimestamp(t *testing.T) {
	event := NewJSONProgress(nativeProgress{Done: 1, Ratio: math.Inf(1)}).TimestampEpochMs(5).Build()
	progress, ok := event.Value()["progress"].(map[string]any)
	if !ok {
		t.Fatalf("progress = %#v", event.Value()["progress"])
	}
	if progress["ratio"] != "<unsupported:number>" || progress["done"] != json.Number("1") || progress["timestamp_epoch_ms"] != int64(5) {
		t.Fatalf("progress = %#v", progress)
	}
}

func TestNativeMapFloatLeaf(t *testing.T) {
	got := sanitizeForJSON(map[string]float64{"a": 1.5, "b": math.Inf(1)}).(map[string]any)
	if got["b"] != "<unsupported:number>" || got["a"] != 1.5 {
		t.Fatalf("got %#v", got)
	}
}

func TestNativeErrorField(t *testing.T) {
	type s struct {
		Err  error
		Errs map[string]error
	}
	got := sanitizeForJSON(s{Err: errors.New("boom"), Errs: map[string]error{"x": errors.New("bad")}}).(map[string]any)
	if got["Err"] != "boom" || got["Errs"].(map[string]any)["x"] != "bad" {
		t.Fatalf("got %#v", got)
	}
}

func TestNativeTimesAreUTC(t *testing.T) {
	zone := time.FixedZone("x", 3*3600)
	at := time.Date(2026, 1, 2, 3, 4, 5, 0, zone)
	want := "2026-01-02T00:04:05Z"
	type s struct {
		T  time.Time
		P  *time.Time
		L  []time.Time
		NP *time.Time
	}
	got := sanitizeForJSON(s{T: at, P: &at, L: []time.Time{at}}).(map[string]any)
	if got["T"] != want || got["P"] != want || got["L"].([]any)[0] != want || got["NP"] != nil {
		t.Fatalf("got %#v", got)
	}
	if sanitizeForJSON(&at) != want {
		t.Fatalf("top-level pointer not UTC")
	}
}

func TestNativeBytesAreBase64(t *testing.T) {
	sum := sha256.Sum256([]byte("a"))
	got := sanitizeForJSON(map[string]any{"arr": sum, "sl": []byte("hi")}).(map[string]any)
	if got["sl"] != "aGk=" {
		t.Fatalf("slice = %#v", got["sl"])
	}
	s, _ := got["arr"].(string)
	if len(s) != 44 || s[len(s)-1] != '=' {
		t.Fatalf("array = %#v", got["arr"])
	}
}

type nativeStructKey struct{ A int }

func TestNativeMapKeys(t *testing.T) {
	got := sanitizeForJSON(map[int]string{1: "a", -2: "b"}).(map[string]any)
	if got["1"] != "a" || got["-2"] != "b" {
		t.Fatalf("got %#v", got)
	}
	if got := sanitizeForJSON(map[nativeStructKey]int{{1}: 1}); got != "<unsupported:map[afdata.nativeStructKey]int>" {
		t.Fatalf("got %#v", got)
	}
}

type nativeBase struct {
	ID   int `json:"id"`
	Name string
}
type nativeOther struct {
	Name string
	Only string
}
type nativeHidden struct{ Visible int }
type nativeTaggedA struct {
	X int `json:"x"`
}
type nativeTaggedB struct{ X int }
type nativeIsZero struct{ N int }

func (z nativeIsZero) IsZero() bool { return z.N == 7 }

// Cases without special values must match encoding/json exactly.
func TestNativeStructMatchesEncodingJSON(t *testing.T) {
	type embedTagged struct {
		nativeTaggedA
		nativeTaggedB
	}
	type shadow struct {
		nativeBase
		Name string
	}
	cases := map[string]any{
		"tags": struct {
			A int    `json:"a"`
			B string `json:"-"`
			C string `json:",omitempty"`
			D int    `json:"d,omitempty"`
			E []int  `json:"e,omitempty"`
			F *int   `json:"f,omitempty"`
			g int
			H string
		}{A: 1, B: "x", H: "h"},
		"string-opt": struct {
			A int     `json:",string"`
			B bool    `json:",string"`
			C float64 `json:",string"`
			D string  `json:",string"`
			E *int    `json:",string"`
			F uint64  `json:",string"`
		}{A: 5, B: true, C: 1.5, D: "q\"x", E: new(int), F: math.MaxUint64},
		"embedded":      struct{ nativeBase }{nativeBase{ID: 1, Name: "n"}},
		"embedded-ptr":  struct{ *nativeBase }{&nativeBase{ID: 2}},
		"embedded-nil":  struct{ *nativeBase }{},
		"embedded-hide": struct{ nativeHidden }{nativeHidden{9}},
		"conflict": struct {
			nativeBase
			nativeOther
		}{nativeBase{1, "a"}, nativeOther{"b", "c"}},
		"shadow":        shadow{nativeBase{1, "inner"}, "outer"},
		"tag-tie-break": embedTagged{nativeTaggedA{1}, nativeTaggedB{2}},
		"omitzero": struct {
			A nativeIsZero `json:",omitzero"`
			B nativeIsZero `json:",omitzero"`
			C int          `json:",omitzero"`
			D time.Time    `json:",omitzero"`
		}{A: nativeIsZero{7}, B: nativeIsZero{1}},
		"nested": struct {
			M map[string][]int
			P *struct{ Z int }
		}{M: map[string][]int{"k": {1, 2}}, P: &struct{ Z int }{4}},
	}
	for name, value := range cases {
		t.Run(name, func(t *testing.T) {
			raw, err := json.Marshal(value)
			if err != nil {
				t.Fatal(err)
			}
			var want any
			if err := json.Unmarshal(raw, &want); err != nil {
				t.Fatal(err)
			}
			gotRaw, err := json.Marshal(sanitizeForJSON(value))
			if err != nil {
				t.Fatal(err)
			}
			var got any
			if err := json.Unmarshal(gotRaw, &got); err != nil {
				t.Fatal(err)
			}
			if !reflect.DeepEqual(got, want) {
				t.Fatalf("got %s want %s", gotRaw, raw)
			}
		})
	}
}

type nativePtrMarshal struct{ N int }

func (p *nativePtrMarshal) MarshalJSON() ([]byte, error) { return []byte(`"ptr-method"`), nil }

func TestNativePointerReceiverMarshalerOnAddressableField(t *testing.T) {
	type s struct {
		F nativePtrMarshal
		L []nativePtrMarshal
	}
	got := sanitizeForJSON(&s{L: make([]nativePtrMarshal, 1)}).(map[string]any)
	if got["F"] != "ptr-method" || got["L"].([]any)[0] != "ptr-method" {
		t.Fatalf("got %#v", got)
	}
}

func TestNativePointerCycle(t *testing.T) {
	type node struct {
		Self *node
		V    int
	}
	n := &node{V: 1}
	n.Self = n
	got := sanitizeForJSON(n).(map[string]any)
	if got["Self"] != "<unsupported:circular>" || got["V"] != json.Number("1") {
		t.Fatalf("got %#v", got)
	}
}

func TestNativeUint64MaxSurvives(t *testing.T) {
	obj, err := marshalToObject(struct {
		N uint64 `json:"n"`
		M int64  `json:"m"`
	}{N: math.MaxUint64, M: 1<<53 + 1})
	if err != nil {
		t.Fatal(err)
	}
	if obj["n"] != json.Number("18446744073709551615") || obj["m"] != json.Number("9007199254740993") {
		t.Fatalf("obj = %#v", obj)
	}
}

func TestNativeMarshalToObjectShapes(t *testing.T) {
	if obj, err := marshalToObject(nil); obj != nil || err != nil {
		t.Fatalf("nil: %v %v", obj, err)
	}
	if _, err := marshalToObject([]int{1}); err == nil {
		t.Fatal("array must error")
	}
	if _, err := marshalToObject(5); err == nil {
		t.Fatal("scalar must error")
	}
}

func TestNativeUnsupportedKinds(t *testing.T) {
	type s struct {
		C chan int
		F func()
		X complex128
	}
	got := sanitizeForJSON(s{}).(map[string]any)
	if got["C"] != "<unsupported:chan int>" || got["F"] != "<unsupported:func()>" || got["X"] != "<unsupported:complex128>" {
		t.Fatalf("got %#v", got)
	}
}