agent-first-data 0.28.1

A naming convention that lets AI agents understand your data without being told what it means, plus a CLI and library for reading and safely editing structured JSON, TOML, YAML, dotenv, and INI documents.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
"""Tests for AFDATA output formatting — driven by shared spec/fixtures."""

import json
import os

import pytest

from agent_first_data import (
    json_result,
    json_error,
    json_progress,
    json_log,
    LogLevel,
    EventBuildError,
    validate_protocol_event,
    validate_protocol_stream,
    EventDecodeError,
    DecodedResult,
    DecodedError,
    DecodedProgress,
    DecodedLog,
    decode_protocol_event,
    RedactionPolicy,
    PlainStyle,
    OutputOptions,
    OutputFormat,
    redacted_value,
    redact_argv,
    redact_url_secrets,
    render,
    normalize_utc_offset,
    is_valid_rfc3339_date,
    is_valid_rfc3339_time,
    is_valid_rfc3339,
    is_valid_bcp47,
)
from agent_first_data.format import (
    _format_bytes_human,
    _format_with_commas,
    _extract_currency_code,
)

FIXTURES_DIR = os.path.join(os.path.dirname(__file__), "..", "..", "spec", "fixtures")


def _load(name):
    with open(os.path.join(FIXTURES_DIR, name)) as f:
        return json.load(f)


def test_builder_contract_fixtures():
    for case in _load("builder_contract.json"):
        action = case["action"]
        builder = json_error("code", "message")
        if action == "empty_code":
            builder = json_error("", "message")
        elif action == "empty_message":
            builder = json_error("code", "")
        elif action == "empty_hint":
            builder.hint("")
        elif action == "bulk_non_object":
            builder.fields(1)
        elif action == "reserved_field":
            builder.field("code", "other")
        elif action == "non_object_trace":
            builder.trace(1)
        elif action == "serialization_failure":
            circular = {}
            circular["self"] = circular
            builder.field("bad", circular)
        else:
            raise AssertionError(f"unknown action {action}")

        try:
            event = builder.build()
            built = True
        except EventBuildError:
            event = None
            built = False
        assert built is case["should_build"], f"[builder_contract/{case['name']}]"
        if built and "hint_present" in case:
            assert ("hint" in event.to_dict()["error"]) is case["hint_present"]


def _redaction_options(case):
    opts = case.get("options", {})
    policy = RedactionPolicy(opts["policy"]) if "policy" in opts else None
    return OutputOptions(policy=policy, secret_names=opts.get("secret_names", ()))


# --- Redact fixtures ---


def test_redact_fixtures():
    for case in _load("redact.json"):
        name = case["name"]
        got = redacted_value(case["input"])
        assert got == case["expected"], f"[redact/{name}] got {got!r}"


def test_redact_url_fixtures():
    for case in _load("redact_url.json"):
        name = case["name"]
        options = _redaction_options(case)
        got = redact_url_secrets(
            case["input"],
            secret_names=options.secret_names,
            policy=options.policy,
        )
        assert got == case["expected"], f"[redact_url/{name}] got {got!r}"


def test_redact_argv_fixtures():
    for case in _load("redact_argv.json"):
        name = case["name"]
        options = _redaction_options(case)
        got = redact_argv(
            case["input"],
            secret_names=options.secret_names,
            policy=options.policy,
        )
        assert got == case["expected"], f"[redact_argv/{name}] got {got!r}"


def test_redact_argv_default_matches_explicit_defaults():
    args = ["tool", "--api-key-secret=sk-live"]
    assert redact_argv(args) == redact_argv(args, secret_names=(), policy=None)


def test_redaction_options_fixtures():
    for case in _load("redaction_options.json"):
        name = case["name"]
        output_options = _redaction_options(case)
        expected = case["expected"]

        got = redacted_value(case["input"], secret_names=output_options.secret_names, policy=output_options.policy)
        assert got == expected, f"[redaction_options/{name}] value mismatch: {got}"

        got_json = json.loads(render(case["input"], OutputFormat.JSON, options=output_options))
        assert got_json == expected, f"[redaction_options/{name}] json mismatch: {got_json}"

        if "expected_yaml" in case:
            got_yaml = render(case["input"], OutputFormat.YAML, options=output_options)
            assert got_yaml == case["expected_yaml"], f"[redaction_options/{name}] yaml mismatch: {got_yaml!r}"
        if "expected_plain" in case:
            got_plain = render(case["input"], OutputFormat.PLAIN, options=output_options)
            assert got_plain == case["expected_plain"], f"[redaction_options/{name}] plain mismatch: {got_plain!r}"


def test_security_fixtures():
    fixture = _load("security.json")
    for case in fixture["redaction_cases"]:
        name = case["name"]
        output_options = _redaction_options(case)
        assert redacted_value(case["input"], secret_names=output_options.secret_names, policy=output_options.policy) == case["expected"]
        outputs = (
            render(case["input"], OutputFormat.JSON, options=output_options),
            render(case["input"], OutputFormat.YAML, options=output_options),
            render(case["input"], OutputFormat.PLAIN, options=output_options),
        )
        for output in outputs:
            for needle in case["must_contain"]:
                assert needle in output, f"[security/{name}] output missing {needle!r}: {output}"
            for needle in case["must_not_contain"]:
                assert needle not in output, f"[security/{name}] output leaked {needle!r}: {output}"


# --- URL fragments carry secrets too ---


def test_url_fragment_params_redacted_like_query_params():
    assert (
        redact_url_secrets("https://h/p?token_secret=QUERYLEAK#token_secret=FRAGLEAK")
        == "https://h/p?token_secret=***#token_secret=***"
    )


def test_url_fragment_params_redacted_without_a_query():
    # The OAuth implicit-flow shape: the credential exists only after '#'.
    assert (
        redact_url_secrets("https://h/cb#access_token_secret=abc&state=xyz")
        == "https://h/cb#access_token_secret=***&state=xyz"
    )


def test_url_fragment_without_params_is_preserved():
    for url in ("https://h/p?a=1#section", "https://h/p#", "https://h/p#a/b?c"):
        assert redact_url_secrets(url) == url, f"fragment mangled: {url}"


def test_url_fragment_honors_secret_names():
    assert (
        redact_url_secrets("https://h/cb#token=abc&page=2", secret_names=["token"])
        == "https://h/cb#token=***&page=2"
    )


# --- One policy meaning across value, argv, url ---


def _scoped_value():
    return {
        "result": {"api_key_secret": "sk-result"},
        "trace": {"api_key_secret": "sk-trace"},
    }


def _argv():
    return ["tool", "--api-key-secret=sk-live"]


def test_all_policy_redacts_every_path():
    policy = RedactionPolicy.All
    assert redacted_value(_scoped_value(), policy=policy) == {
        "result": {"api_key_secret": "***"},
        "trace": {"api_key_secret": "***"},
    }
    assert redact_argv(_argv(), policy=policy) == ["tool", "--api-key-secret=***"]
    assert (
        redact_url_secrets("https://u:pw@h/cb?token_secret=abc", policy=policy)
        == "https://u:***@h/cb?token_secret=***"
    )


def test_trace_only_scopes_a_value_but_redacts_argv_and_url_in_full():
    policy = RedactionPolicy.TraceOnly
    # Scoped input: only the `trace` half is scrubbed.
    assert redacted_value(_scoped_value(), policy=policy) == {
        "result": {"api_key_secret": "sk-result"},
        "trace": {"api_key_secret": "***"},
    }
    # Unscoped input: a command line and a bare URL have no non-`trace` half to
    # leave alone, so they are redacted like `All`.
    assert redact_argv(_argv(), policy=policy) == ["tool", "--api-key-secret=***"]
    assert (
        redact_url_secrets("https://u:pw@h/cb?token_secret=abc", policy=policy)
        == "https://u:***@h/cb?token_secret=***"
    )


def test_off_policy_disables_every_path():
    policy = RedactionPolicy.Off
    assert redacted_value(_scoped_value(), policy=policy) == _scoped_value()
    assert redact_argv(_argv(), policy=policy) == _argv()
    assert (
        redact_url_secrets("https://u:pw@h/cb?token_secret=abc", policy=policy)
        == "https://u:pw@h/cb?token_secret=abc"
    )


def test_absent_url_policy_matches_the_all_policy():
    url = "https://u:pw@h/cb?token_secret=abc#id_token_secret=xyz"
    assert redact_url_secrets(url) == redact_url_secrets(url, policy=RedactionPolicy.All)


# --- `_secret` stripping follows redaction ---


def _plain(value, policy):
    return render(value, OutputFormat.PLAIN, options=OutputOptions(policy=policy))


def test_plain_strips_secret_suffix_once_the_value_is_redacted():
    assert _plain({"api_key_secret": "sk-live-xxx"}, RedactionPolicy.All) == "api_key=***"


def test_plain_keeps_secret_suffix_when_redaction_is_off():
    # Stripping here would hand a live credential to a reader under a name that
    # no longer says it is one.
    assert (
        _plain({"api_key_secret": "sk-live-xxx"}, RedactionPolicy.Off)
        == "api_key_secret=sk-live-xxx"
    )
    assert (
        _plain({"API_KEY_SECRET": "sk-live-xxx"}, RedactionPolicy.Off)
        == "API_KEY_SECRET=sk-live-xxx"
    )


def test_plain_keeps_secret_suffix_outside_trace_under_trace_only():
    assert (
        _plain(
            {
                "api_key_secret": "sk-live-xxx",
                "trace": {"request_secret": "top-secret"},
            },
            RedactionPolicy.TraceOnly,
        )
        == "api_key_secret=sk-live-xxx trace.request=***"
    )


def test_plain_keeps_secret_suffix_on_an_unredacted_subtree():
    assert (
        _plain({"db_secret": {"password": "hunter2"}}, RedactionPolicy.Off)
        == "db_secret.password=hunter2"
    )
    assert _plain({"db_secret": {"password": "hunter2"}}, RedactionPolicy.All) == "db=***"


def test_plain_unstripped_secret_key_does_not_collide_with_its_stem():
    # Keeping the suffix also means no collision to fall back from: both fields
    # keep their own name and value.
    assert (
        _plain({"api_key": "public", "api_key_secret": "sk-live-xxx"}, RedactionPolicy.Off)
        == "api_key=public api_key_secret=sk-live-xxx"
    )


# --- Protocol fixtures ---


def _build_protocol_case_event(typ, args):
    """Build an Event from a protocol.json builder case.

    args vocabulary: "result" (payload), "code"+"message" (error),
    "hint" (-> .hint()), "retryable" (bool -> .retryable_if()),
    "fields" (object -> .fields()), "trace" (object -> .trace()), and complete
    progress/log payloads.
    """
    kind = typ.split("_", 1)[0]

    if kind == "result":
        builder = json_result(args["result"])
    elif kind == "error":
        builder = json_error(args["code"], args["message"])
        if "hint" in args:
            builder = builder.hint(args["hint"])
        if "retryable" in args:
            builder = builder.retryable_if(args["retryable"])
    elif kind == "progress":
        builder = json_progress({"message": args["message"], **args.get("fields", {})})
    elif kind == "log":
        builder = json_log({"level": args["level"], "message": args["message"], **args.get("fields", {})})
    else:
        raise ValueError(f"unknown fixture type: {typ}")

    if "fields" in args and kind not in ("progress", "log"):
        builder = builder.fields(args["fields"])
    if "trace" in args:
        builder = builder.trace(args["trace"])
    return builder.build()


def test_protocol_fixtures():
    for case in _load("protocol.json"):
        name = case["name"]
        if "invalid" in case:
            try:
                validate_protocol_event(case["invalid"], strict=False)
            except ValueError:
                pass
            else:
                raise AssertionError(f"[protocol/{name}] invalid event unexpectedly passed")
            continue

        result = _build_protocol_case_event(case["type"], case["args"]).to_dict()
        validate_protocol_event(result, strict=False)
        validate_protocol_event(result, strict=True)
        expected = case["expected"]
        assert result == expected, (
            f"[protocol/{name}] deep equality failed:\n"
            f"  got:      {result}\n"
            f"  expected: {expected}"
        )


def test_protocol_stream_fixtures():
    for case in _load("protocol_streams.json"):
        name = case["name"]
        valid = case["valid"]
        try:
            validate_protocol_stream(case["events"], strict=False)
        except ValueError as exc:
            assert not valid, f"[protocol_streams/{name}] unexpected error: {exc}"
        else:
            assert valid, f"[protocol_streams/{name}] invalid stream unexpectedly passed"


def test_protocol_strict_fixtures():
    for case in _load("protocol_strict.json"):
        try:
            validate_protocol_stream(case["events"], strict=True)
        except ValueError:
            assert not case["valid"], case["name"]
        else:
            assert case["valid"], case["name"]


# --- LogLevel string shape ---
#
# LogLevel is `class LogLevel(str, Enum)`, not `enum.StrEnum`, because StrEnum
# is 3.11-only and the package's requires-python floor is lower. The two spell
# `str(member)`/`format(member)` differently ('info' vs 'LogLevel.INFO'), and
# that spelling has moved between Python releases, so nothing may render a
# LogLevel through its `__str__`. The wire form is the value in all four
# language implementations (Go's `type LogLevel string`, TypeScript's
# `"debug" | "info" | ...`), and these pin that for Python.


def test_log_level_is_a_string_carrying_its_value():
    assert LogLevel.INFO.value == "info"
    assert LogLevel.INFO == "info"
    assert LogLevel("info") is LogLevel.INFO
    assert json.dumps(LogLevel.INFO) == '"info"'


def test_log_level_renders_as_its_value_in_every_format():
    payload = {"level": LogLevel.WARN}
    assert render(payload, OutputFormat.JSON) == '{"level":"warn"}'
    assert render(payload, OutputFormat.YAML) == '---\nlevel: "warn"'
    # The plain renderer f-string-interpolates scalars, which is where a
    # str-mixin member would otherwise leak as `level=LogLevel.WARN`.
    assert render(payload, OutputFormat.PLAIN) == "level=warn"


def test_log_level_renders_as_its_value_when_nested_or_used_as_a_key():
    payload = {"levels": [LogLevel.DEBUG, LogLevel.ERROR], LogLevel.INFO: "seen"}
    assert render(payload, OutputFormat.JSON) == '{"levels":["debug","error"],"info":"seen"}'
    assert render(payload, OutputFormat.PLAIN) == "info=seen levels=debug,error"


def test_redacted_value_normalizes_str_enum_members_to_plain_strings():
    # The single normalization point every renderer depends on: a str-mixin
    # member must leave the sanitizer as an exact str, not as an enum that
    # happens to be a str.
    out = redacted_value({"level": LogLevel.INFO})
    assert out == {"level": "info"}
    assert type(out["level"]) is str


def test_error_builder_rejects_reserved_extension_fields():
    # 0.16 spec: reserved fields must not be writable, errors are collected at build()
    try:
        json_error("explicit", "message").fields({"code": "wrong", "message": "wrong", "hint": "wrong", "detail": 1}).build()
        assert False, "should have raised EventBuildError"
    except Exception as e:
        assert "cannot override reserved field" in str(e)


def test_error_builder_empty_code_deferred_to_build():
    # L1: ErrorBuilder is the only fallible builder. json_error("", ...) must not
    # fail eagerly at construction; the empty-code error is deferred to build().
    builder = json_error("", "message")
    with pytest.raises(EventBuildError, match="error code must not be empty"):
        builder.build()


def test_error_builder_empty_message_deferred_to_build():
    builder = json_error("code", "")
    with pytest.raises(EventBuildError, match="error message must not be empty"):
        builder.build()


@pytest.mark.parametrize(
    "make_builder",
    [
        lambda: json_result("ok"),
        lambda: json_progress({"message": "working"}),
        lambda: json_log({"level": "info", "message": "hi"}),
    ],
    ids=["result", "progress", "log"],
)
def test_non_error_builders_never_raise_on_build(make_builder):
    # L1: ResultBuilder/ProgressBuilder/LogBuilder.build() must never raise, even
    # after a non-dict trace() — the invalid trace is stored verbatim and only
    # surfaces later at validate_protocol_event, not at build time.
    event = make_builder().trace("not-an-object").build()
    assert event.to_dict()["trace"] == "not-an-object"

    # A dict trace still builds normally.
    event2 = make_builder().trace({"request_id": "abc"}).build()
    assert event2.to_dict()["trace"] == {"request_id": "abc"}


# --- Helper fixtures ---


def test_helper_fixtures():
    for case in _load("helpers.json"):
        name = case["name"]
        for tc in case["cases"]:
            inp, expected = tc
            if name == "format_bytes_human":
                got = _format_bytes_human(inp)
                assert got == expected, f"[helpers/{name}({inp})] got {got!r}"
            elif name == "format_with_commas":
                got = _format_with_commas(inp)
                assert got == expected, f"[helpers/{name}({inp})] got {got!r}"
            elif name == "extract_currency_code":
                got = _extract_currency_code(inp)
                assert got == expected, f"[helpers/{name}({inp!r})] got {got!r}"
            elif name == "normalize_utc_offset":
                got = normalize_utc_offset(inp)
                assert got == expected, f"[helpers/{name}({inp!r})] got {got!r}"
            elif name == "is_valid_rfc3339_date":
                got = is_valid_rfc3339_date(inp)
                assert got == expected, f"[helpers/{name}({inp!r})] got {got!r}"
            elif name == "is_valid_rfc3339_time":
                got = is_valid_rfc3339_time(inp)
                assert got == expected, f"[helpers/{name}({inp!r})] got {got!r}"
            elif name == "is_valid_bcp47":
                got = is_valid_bcp47(inp)
                assert got == expected, f"[helpers/{name}({inp!r})] got {got!r}"
            elif name == "is_valid_rfc3339":
                got = is_valid_rfc3339(inp)
                assert got == expected, f"[helpers/{name}({inp!r})] got {got!r}"


def test_output_format_fixtures():
    for case in _load("output_formats.json"):
        name = case["name"]
        inp = json.loads(json.dumps(case["input"]))

        got_json = json.loads(render(inp, OutputFormat.JSON))
        assert got_json == case["expected_json"], f"[output/{name}] json mismatch: {got_json}"

        got_yaml = render(inp, OutputFormat.YAML)
        assert got_yaml == case["expected_yaml"], f"[output/{name}] yaml mismatch: {got_yaml!r}"

        if "expected_plain" in case:
            got_plain = render(inp, OutputFormat.PLAIN)
            assert got_plain == case["expected_plain"], f"[output/{name}] plain mismatch: {got_plain!r}"


def test_render_yaml_raw_keeps_suffix_keys_and_structure():
    options = OutputOptions(
        policy=RedactionPolicy.TraceOnly,
        style=PlainStyle.Raw,
    )
    out = render(
        {
            "code": "result",
            "rows": [{"api_key_secret": "sk-live-1", "duration_ms": 42}],
            "trace": {"request_secret": "top-secret"},
        },
        OutputFormat.YAML,
        options=options,
    )

    assert "rows:\n  -" in out
    assert 'api_key_secret: "sk-live-1"' in out
    assert "duration_ms: 42" in out
    assert 'request_secret: "***"' in out
    assert 'duration: "42ms"' not in out


def test_render_plain_raw_keeps_suffix_keys_and_redacts_trace():
    options = OutputOptions(
        policy=RedactionPolicy.TraceOnly,
        style=PlainStyle.Raw,
    )
    out = render(
        {
            "duration_ms": 42,
            "trace": {"request_secret": "top-secret"},
        },
        OutputFormat.PLAIN,
        options=options,
    )

    assert "duration_ms=42" in out
    assert "trace.request_secret=***" in out
    assert "duration=42ms" not in out


def test_render_yaml_ignores_output_style():
    """YAML no longer branches on PlainStyle: Readable and Raw produce identical,
    structure-preserving output (only `plain` still varies by style)."""
    value = {"duration_ms": 42, "api_key_secret": "sk-live-1"}
    readable = render(
        value,
        OutputFormat.YAML,
        options=OutputOptions(policy=RedactionPolicy.Off, style=PlainStyle.Readable),
    )
    raw = render(
        value,
        OutputFormat.YAML,
        options=OutputOptions(policy=RedactionPolicy.Off, style=PlainStyle.Raw),
    )
    assert readable == raw
    assert "duration_ms: 42" in readable
    assert 'api_key_secret: "sk-live-1"' in readable
    assert "duration:" not in readable


def test_render_json_exception_field_is_readable():
    out = render({"error": Exception("timeout")}, OutputFormat.JSON)
    parsed = json.loads(out)
    assert parsed["error"] == "timeout"


def test_render_json_unsupported_value_does_not_leak_secret():
    class SecretRepr:
        def __repr__(self) -> str:
            return "Secret(sk-live-123)"

    out = render({"meta": SecretRepr(), "api_key_secret": "sk-live-123"}, OutputFormat.JSON)
    assert "sk-live-123" not in out
    parsed = json.loads(out)
    assert parsed["api_key_secret"] == "***"
    assert parsed["meta"].startswith("<unsupported:")


def test_render_json_circular_reference():
    v = {}
    v["self"] = v
    out = render(v, OutputFormat.JSON)
    parsed = json.loads(out)
    assert parsed["self"] == "<unsupported:circular>"


def test_render_json_with_trace_only_redacts_only_trace():
    out = render(
        {
            "code": "ok",
            "result": {"api_key_secret": "sk-live-123"},
            "trace": {"request_secret": "top-secret"},
        },
        OutputFormat.JSON,
        options=OutputOptions.for_policy(RedactionPolicy.TraceOnly),
    )
    parsed = json.loads(out)
    assert parsed["trace"]["request_secret"] == "***"
    assert parsed["result"]["api_key_secret"] == "sk-live-123"


def test_render_json_with_none_keeps_secrets():
    out = render(
        {"api_key_secret": "sk-live-123"},
        OutputFormat.JSON,
        options=OutputOptions.for_policy(RedactionPolicy.Off),
    )
    parsed = json.loads(out)
    assert parsed["api_key_secret"] == "sk-live-123"


def test_output_options_for_policy_sets_only_redaction_policy():
    options = OutputOptions.for_policy(RedactionPolicy.Off)
    assert options.policy == RedactionPolicy.Off
    assert options.secret_names == ()
    assert options.style == PlainStyle.Readable


def test_redacted_value_returns_safe_copy():
    inp = {"api_key_secret": "sk-live-123", "nested": {"token_secret": "tok"}}
    got = redacted_value(inp)
    assert got["api_key_secret"] == "***"
    assert got["nested"]["token_secret"] == "***"
    assert inp["api_key_secret"] == "sk-live-123"


def test_redacted_value_redacts_secret_subtree_by_default():
    inp = {"db_secret": {"password_secret": "real", "host": "localhost"}}
    default = redacted_value(inp)
    assert default["db_secret"] == "***"


def test_max_depth_marker_is_not_secret_redaction_marker():
    inp = "leaf"
    for _ in range(300):
        inp = {"next": inp}
    out = render(inp, OutputFormat.JSON)
    assert "<afdata:max-depth>" in out
    assert "***" not in out


# --- decode_protocol_event ---


def test_decode_protocol_event_result():
    event = json_result({"rows": 2}).build()
    decoded = decode_protocol_event(render(event.to_dict(), OutputFormat.JSON))
    assert isinstance(decoded, DecodedResult)
    assert decoded.result == {"rows": 2}
    assert decoded.trace == {}


def test_decode_protocol_event_error():
    event = json_error("not_found", "missing").hint("check the id").field("id", "abc").retryable().build()
    decoded = decode_protocol_event(render(event.to_dict(), OutputFormat.JSON))
    assert isinstance(decoded, DecodedError)
    assert decoded.code == "not_found"
    assert decoded.message == "missing"
    assert decoded.retryable is True
    assert decoded.hint == "check the id"
    assert decoded.fields == {"id": "abc"}
    assert decoded.trace == {}


def test_decode_protocol_event_progress():
    event = json_progress({"message": "halfway", "percent": 50}).build()
    decoded = decode_protocol_event(render(event.to_dict(), OutputFormat.JSON))
    assert isinstance(decoded, DecodedProgress)
    assert decoded.progress == {"message": "halfway", "percent": 50}
    assert decoded.trace == {}


def test_decode_protocol_event_log():
    event = json_log({"level": "warn", "message": "slow query", "duration_ms": 900}).build()
    decoded = decode_protocol_event(render(event.to_dict(), OutputFormat.JSON))
    assert isinstance(decoded, DecodedLog)
    assert decoded.log == {"level": "warn", "message": "slow query", "duration_ms": 900}
    assert decoded.trace == {}


def test_decode_protocol_event_invalid_json_raises():
    import pytest

    with pytest.raises(EventDecodeError):
        decode_protocol_event("not json")


def test_decode_protocol_event_invalid_envelope_raises():
    import pytest

    with pytest.raises(EventDecodeError):
        decode_protocol_event(json.dumps({"kind": "result"}))


def test_decode_protocol_event_fails_strict_validation():
    import pytest

    # Missing trace fails the strict profile even though the shape is otherwise valid.
    with pytest.raises(EventDecodeError):
        decode_protocol_event(json.dumps({"kind": "result", "result": {}}))


# --- Number literal fidelity (shared spec/fixtures/number_fidelity.json) ---
#
# Regression guard for decode_protocol_event's parse_int/parse_float hooks
# (_RawNumber, only needed for floats and the "-0" integer edge case --
# every other integer is already arbitrary-precision via plain Python int)
# and for _encode_json_lossless/_yaml_scalar/_plain_scalar's _RawNumber
# handling in format.py.


def test_number_fidelity_fixtures():
    for case in _load("number_fidelity.json"):
        name = case["name"]
        decoded = decode_protocol_event(case["input_line"])
        assert isinstance(decoded, DecodedResult), f"[number_fidelity/{name}] expected DecodedResult"

        got_json = render(decoded.result, OutputFormat.JSON)
        assert got_json == case["expected_json"], f"[number_fidelity/{name}] json mismatch: {got_json!r}"

        if "expected_yaml" in case:
            got_yaml = render(decoded.result, OutputFormat.YAML)
            assert got_yaml == case["expected_yaml"], f"[number_fidelity/{name}] yaml mismatch: {got_yaml!r}"
        if "expected_plain" in case:
            got_plain = render(decoded.result, OutputFormat.PLAIN)
            assert got_plain == case["expected_plain"], f"[number_fidelity/{name}] plain mismatch: {got_plain!r}"


def test_protocol_decode_fixtures():
    for case in _load("protocol_decode.json"):
        try:
            decode_protocol_event(case["input_line"])
            valid = True
        except EventDecodeError:
            valid = False
        assert valid is case["valid"], f"[protocol_decode/{case['name']}]"


def test_number_fidelity_does_not_regress_ordinary_decoded_numbers_in_plain_output():
    # decode_protocol_event wraps every decoded float (not ints -- those are
    # already arbitrary-precision Python int) in _RawNumber, including small
    # ordinary ones; _try_process_field must normalize back to a float for
    # Plain's suffix arithmetic or this would silently stop formatting a
    # decoded cpu_percent for any event with a float suffix field.
    line = json.dumps({"kind": "result", "result": {"duration_ms": 42, "size_bytes": 5242880, "cpu_percent": 85.5}, "trace": {}})
    decoded = decode_protocol_event(line)
    plain = render(decoded.result, OutputFormat.PLAIN)
    assert plain == "cpu=85.5% duration=42ms size=5.0MiB"