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
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
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
#!/usr/bin/env python3
"""End-to-end checks for the closed-world afdata CLI."""

from __future__ import annotations

import json
import os
import subprocess
import sys
import tempfile
from pathlib import Path
from typing import Sequence


ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "scripts"))
from validate_protocol_docs import check_help_events


def run_afdata(args: Sequence[str], stdin: str) -> subprocess.CompletedProcess[str]:
    return subprocess.run(
        ["cargo", "run", "--quiet", "--bin", "afdata", "--", *args],
        cwd=ROOT,
        text=True,
        input=stdin,
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE,
        timeout=60,
        check=False,
    )


def run_rust_example(args: Sequence[str]) -> subprocess.CompletedProcess[str]:
    return subprocess.run(
        ["cargo", "run", "--quiet", "--example", "agent_cli", "--", *args],
        cwd=ROOT,
        text=True,
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE,
        timeout=60,
        check=False,
    )


def run_afdata_skill(
    args: Sequence[str],
    *,
    cwd: Path = ROOT,
    env: dict[str, str] | None = None,
) -> subprocess.CompletedProcess[str]:
    manifest = str(ROOT / "Cargo.toml")
    return subprocess.run(
        [
            "cargo", "run", "--quiet", "--manifest-path", manifest,
            "--features", "skill-admin", "--bin", "afdata", "--", *args,
        ],
        cwd=cwd,
        env=env,
        text=True,
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE,
        timeout=60,
        check=False,
    )


def run_afdata_minimal(args: Sequence[str]) -> subprocess.CompletedProcess[str]:
    """Run the afdata binary built with only the core CLI (default features off)."""
    return subprocess.run(
        [
            "cargo", "run", "--quiet",
            "--no-default-features", "--features", "cli",
            "--bin", "afdata", "--", *args,
        ],
        cwd=ROOT,
        text=True,
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE,
        timeout=120,
        check=False,
    )


def parse_events(stdout: str) -> list[dict[str, object]]:
    # `go run` appends its own "exit status N" line to stderr when the program
    # exits non-zero. That is a go-run wrapper artifact, not part of the
    # program's AFDATA output, so drop it before parsing. (Rust/afdata use
    # `cargo run --quiet`, which suppresses the equivalent trailer.)
    lines = [
        line
        for line in stdout.splitlines()
        if line.strip() and not line.strip().startswith("exit status ")
    ]
    return [json.loads(line) for line in lines]


def terminal_events(proc: subprocess.CompletedProcess[str]) -> list[dict[str, object]]:
    """The terminal event(s) from the stream a finite CLI used under the default
    split: `result` on stdout (exit 0), `error` on stderr (non-zero exit).
    Diagnostics (`log`/`progress`) go to stderr regardless — parse `proc.stderr`
    directly for those."""
    return parse_events(proc.stdout if proc.returncode == 0 else proc.stderr)



def validate_help_v2_event(event: dict[str, object]) -> dict[str, object]:
    checked, problems = check_help_events([event])
    assert checked == 1 and not problems, problems
    assert set(event) == {"kind", "result", "trace"}, event
    assert event["kind"] == "result", event
    assert event["trace"] == {}, event
    result = event["result"]
    assert isinstance(result, dict) and set(result) == {"code", "help"}, event
    assert result["code"] == "help", event
    help_model = result["help"]
    assert isinstance(help_model, dict), event
    assert help_model.get("schema") == "cli-help-v2", event
    assert isinstance(help_model.get("command_path"), str), event
    about = help_model.get("about")
    assert about is None or (
        isinstance(about, str) and about and "\n" not in about and "\r" not in about
    ), event
    shapes = help_model.get("shapes", [])
    assert isinstance(shapes, list), event
    for shape in shapes:
        assert set(shape) <= {"id", "about", "usage"}, event
        assert isinstance(shape.get("id"), str) and shape["id"], event
        usage = shape.get("usage")
        assert isinstance(usage, str) and usage and "\n" not in usage, event
    # Help answers in one round trip, so every shape is complete: there is no
    # second level that could have carried the optional arguments.
    if len(shapes) > 1:
        assert all(shape.get("about") for shape in shapes), event
    elif shapes:
        assert "about" not in shapes[0], event
    return help_model


def assert_rust_example_uses_help_v2() -> None:
    help_proc = run_rust_example(("echo", "--help"))
    assert help_proc.returncode == 0, help_proc.stderr
    help_model = validate_help_v2_event(json.loads(help_proc.stdout))
    assert [shape["id"] for shape in help_model["shapes"]] == ["echo"]
    assert help_model["shapes"][0]["usage"].startswith("agent-cli echo <MESSAGE>")

    version_proc = run_rust_example(("--version",))
    assert version_proc.returncode == 0, version_proc.stderr
    version = json.loads(version_proc.stdout)
    assert version["result"]["code"] == "version", version

    # Past the command path the spelling is the application's: this asks the
    # release command for version 1.2.0, not agent-cli for its own version.
    release_proc = run_rust_example(("release", "--version", "1.2.0"))
    assert release_proc.returncode == 0, release_proc.stderr
    release = json.loads(release_proc.stdout)
    assert release["result"] == {"code": "release", "version": "1.2.0"}, release

    conflict = run_rust_example(("ping", "--host", "example.com", "--dry-run"))
    assert conflict.returncode == 2, conflict
    assert not conflict.stdout, conflict.stdout
    error = json.loads(conflict.stderr)
    assert error["error"]["code"] == "cli_unknown_argument", error

    # A mistyped long argument may be positional data, even when it looks
    # like a well-formed option name.
    for operand in ("--sample-canary", "-- sample canary"):
        rejected = run_rust_example(("echo", operand))
        assert rejected.returncode == 2, rejected
        assert not rejected.stdout, rejected.stdout
        assert "canary" not in rejected.stderr, rejected.stderr
        error = json.loads(rejected.stderr)["error"]
        assert error["code"] == "cli_unknown_argument", error
        assert "agent-cli echo --help" in error["hint"], error


def assert_afdata_validate() -> None:
    proc = run_afdata(("validate", "-"), '{"kind":"result","result":{"ok":true}}\n')
    assert proc.returncode == 0, f"afdata validate failed: stderr={proc.stderr!r}, stdout={proc.stdout!r}"
    events = terminal_events(proc)
    assert len(events) == 1, f"afdata validate emitted unexpected events: {events!r}"
    assert events[0]["kind"] == "result", f"afdata validate did not emit result: {events[0]!r}"
    assert events[0]["trace"] == {}, f"afdata validate result is not strict: {events[0]!r}"
    assert events[0]["result"] == {"ok": True, "findings": []}


def assert_afdata_validate_strict_event() -> None:
    valid = '{"kind":"log","log":{"event":"startup"},"trace":{}}\n'
    proc = run_afdata(("validate", "-", "--strict", "--per-event"), valid)
    assert proc.returncode == 0, f"strict event failed: stderr={proc.stderr!r}, stdout={proc.stdout!r}"
    events = terminal_events(proc)
    assert events[0]["kind"] == "result", f"strict event result missing: {events!r}"

    invalid = '{"kind":"log","log":{"event":"startup"}}\n'
    proc = run_afdata(("validate", "-", "--strict", "--per-event"), invalid)
    assert proc.returncode != 0, "strict event accepted an event without trace"
    events = terminal_events(proc)
    assert events[0]["kind"] == "error", f"strict event error missing: {events!r}"
    assert events[0]["trace"] == {}, f"strict event error is not strict: {events[0]!r}"
    finding, = events[0]["error"]["findings"]
    assert finding["severity"] == "error" and finding["pointer"] == "/trace", finding


def assert_afdata_validate_stream_error() -> None:
    proc = run_afdata(("validate", "-"), '{"kind":"log","log":{"event":"startup"}}\n')
    assert proc.returncode != 0, "afdata validate accepted a stream without terminal event"
    events = terminal_events(proc)
    assert events[0]["kind"] == "error", f"afdata validate stream error missing: {events!r}"
    assert events[0]["error"]["code"] == "validation_failed", f"wrong validation code: {events[0]!r}"


def assert_afdata_lint_report() -> None:
    for payload, violations, advisories in (
        ({"build": "8165"}, [], []),
        ({"rows": "1,200"}, [], ["/rows"]),
        ({"size_bytes": -1}, ["/size_bytes"], []),
        ({"size_bytes": "8 MB"}, ["/size_bytes"], ["/size_bytes"]),
    ):
        for flags in ((), ("--violations-only",)):
            proc = run_afdata(("lint", *flags, "-"), json.dumps(payload))
            assert proc.returncode == int(bool(violations)), (proc.stdout, proc.stderr)
            assert not (proc.stdout if violations else proc.stderr)
            event = json.loads(proc.stderr if violations else proc.stdout)
            kind = "error" if violations else "result"
            assert event["kind"] == kind and event["trace"] == {}, event
            report = event[kind]
            if violations:
                assert report["code"] == "lint_failed" and report["retryable"] is False
            else:
                assert report["ok"] is True
            assert "findings" not in report
            for group, expected in (("violations", violations), ("advisories", [] if flags else advisories)):
                assert [item["pointer"] for item in report[group]] == expected, report
                assert all(set(item) == {"rule_id", "pointer", "message"} for item in report[group])

    for args in (("lint", "--help"), ("--docs",)):
        help_text = run_afdata(args, "")
        assert help_text.returncode == 0
        for flag in ("--violations-only", "--schema"):
            assert flag in help_text.stdout
        assert "--min-severity" not in help_text.stdout

    old = run_afdata(("lint", "--min-severity", "error", "missing.json"), "")
    assert old.returncode == 2 and not old.stdout
    assert json.loads(old.stderr)["error"]["code"] == "cli_unknown_argument"


def assert_afdata_lint_schema_secret() -> None:
    schema = '{"type":"object","properties":{"api_key_secret":{"type":"string","default":"sk-live"}}}\n'
    proc = run_afdata(("lint", "--schema", "-"), schema)
    assert proc.returncode != 0, "afdata lint accepted exposed secret default"
    events = terminal_events(proc)
    assert events[0]["kind"] == "error", f"afdata lint error missing: {events!r}"
    findings = events[0]["error"]["violations"]
    assert findings[0]["rule_id"] == "secret_schema_value_exposed", f"wrong lint finding: {findings!r}"
    # A null default/example is a valid absent/redacted secret literal, not an
    # exposed one.
    ok_schema = (
        '{"type":"object","properties":{"api_key_secret":'
        '{"type":"string","default":null,"examples":[null,"***"]}}}\n'
    )
    ok = run_afdata(("lint", "--schema", "-"), ok_schema)
    assert ok.returncode == 0, f"afdata lint rejected a null secret schema default/examples: {ok.stdout!r}"


def assert_afdata_lint_schema_literals_and_advisories() -> None:
    properties = {
        "build": {"type": "string", "const": "8165"},
        "seen_epoch_ns": {"type": "string", "example": "1707868800000000000"},
        "timeout": {"type": ["integer", "null"]},
        "api_key": {"type": "string"},
        "request_timeout": {"type": "object"},
        "timeout_ms": {"type": "integer"},
        "api_key_secret": {"type": "string", "const": "***", "enum": [None, "***"]},
    }
    proc = run_afdata(("lint", "--schema", "-"), json.dumps({"properties": properties}))
    assert proc.returncode == 0, proc.stderr
    result = terminal_events(proc)[0]["result"]
    assert result["violations"] == [], result
    assert {(item["rule_id"], item["pointer"]) for item in result["advisories"]} == {
        ("missing_suffix", "/properties/timeout"),
        ("missing_suffix", "/properties/api_key"),
    }, result
    for keyword, value, suffix in (("const", "sk-live-123", ""), ("enum", ["sk-live-123"], "/0")):
        properties["api_key_secret"] = {"type": "string", keyword: value}
        proc = run_afdata(("lint", "--schema", "-"), json.dumps({"properties": properties}))
        assert proc.returncode == 1
        finding = terminal_events(proc)[0]["error"]["violations"][0]
        assert finding["rule_id"] == "secret_schema_value_exposed"
        assert finding["pointer"] == f"/properties/api_key_secret/{keyword}{suffix}"


    literals = {
        "retry_ms": {"default": "slow", "enum": [0, "never"]},
        "seen_rfc3339": {"example": "yesterday"},
        "choice_secret": {"anyOf": [{"const": "fictional-canary"}, {"enum": [None, "***"]}]},
    }
    proc = run_afdata(("lint", "--schema", "--violations-only", "-"), json.dumps({"properties": literals}))
    assert proc.returncode == 1, proc
    assert "fictional-canary" not in proc.stdout + proc.stderr
    findings = terminal_events(proc)[0]["error"]["violations"]
    assert {(item["rule_id"], item["pointer"]) for item in findings} == {
        ("suffix_type_mismatch", "/properties/retry_ms/default"),
        ("suffix_type_mismatch", "/properties/retry_ms/enum/1"),
        ("suffix_type_mismatch", "/properties/seen_rfc3339/example"),
        ("secret_schema_value_exposed", "/properties/choice_secret/anyOf/0/const"),
    }, findings


    secret_object = {"properties": {"choice_secret": {"const": {"fictional-canary_url": "not a URL"}}}}
    proc = run_afdata(("lint", "--schema", "-"), json.dumps(secret_object))
    assert proc.returncode == 1, proc
    assert "fictional-canary" not in proc.stdout + proc.stderr
    findings = terminal_events(proc)[0]["error"]["violations"]
    assert [item["pointer"] for item in findings] == ["/properties/choice_secret/const"], findings


def assert_afdata_lint_schema_suffix_types() -> None:
    schema = {
        "type": "object",
        "properties": {
            "duration_ms": {"type": ["integer", "null"], "minimum": 0},
            "callback_url": {"type": "string"},
            "created_rfc3339": {"type": "string"},
            "nested": {
                "type": "object",
                "properties": {
                    "payload_bytes": {"type": "integer", "minimum": 0},
                },
            },
        },
    }
    proc = run_afdata(("lint", "--schema", "-"), json.dumps(schema) + "\n")
    assert proc.returncode == 0, (
        "afdata lint treated JSON Schema descriptors as runtime values: "
        f"{proc.stdout!r} {proc.stderr!r}"
    )

    schema["properties"]["duration_ms"] = {"type": "string"}
    invalid = run_afdata(("lint", "--schema", "-"), json.dumps(schema) + "\n")
    assert invalid.returncode != 0, "afdata lint accepted an incompatible schema suffix type"
    findings = terminal_events(invalid)[0]["error"]["violations"]
    assert findings[0]["rule_id"] == "suffix_type_mismatch", findings

    # A `properties` object whose values are not schemas (an object or a
    # boolean) is runtime data using `properties` as a field name, so its
    # values keep the ordinary runtime suffix check.
    data = run_afdata(("lint", "-"), '{"properties":{"timeout_ms":"5000"}}\n')
    assert data.returncode != 0, "afdata lint skipped runtime data under a `properties` field"
    findings = terminal_events(data)[0]["error"]["violations"]
    assert findings[0]["rule_id"] == "suffix_type_mismatch", findings
    assert findings[0]["pointer"] == "/properties/timeout_ms", findings


def assert_afdata_lint_bcp47() -> None:
    proc = run_afdata(("lint", "-"), '{"language_bcp47":"zh_CN"}\n')
    assert proc.returncode != 0, "afdata lint accepted malformed BCP 47 tag"
    events = terminal_events(proc)
    assert events[0]["kind"] == "error", f"afdata lint error missing: {events!r}"
    findings = events[0]["error"]["violations"]
    assert findings[0]["rule_id"] == "suffix_type_mismatch", f"wrong lint finding: {findings!r}"
    ok = run_afdata(("lint", "-"), '{"language_bcp47":"zh-CN"}\n')
    assert ok.returncode == 0, f"afdata lint rejected valid BCP 47 tag: {ok.stdout!r}"


def assert_afdata_lint_strict_strings() -> None:
    for payload in (
        '{"timezone_utc_offset":"Asia/Shanghai"}\n',
        '{"market_open_rfc3339_time":"09:30:00Z"}\n',
        '{"invoice_due_rfc3339_date":"2026-13-01"}\n',
        # RFC 3339 date-time with no offset — the offset is mandatory.
        '{"expires_rfc3339":"2026-02-14T10:30:00"}\n',
        # Space separator instead of T.
        '{"expires_rfc3339":"2026-02-14 10:30:00Z"}\n',
    ):
        proc = run_afdata(("lint", "-"), payload)
        assert proc.returncode != 0, f"afdata lint accepted malformed strict string: {payload!r}"
        events = terminal_events(proc)
        findings = events[0]["error"]["violations"]
        assert findings[0]["rule_id"] == "suffix_type_mismatch", f"wrong lint finding: {findings!r}"
    ok = run_afdata(
        ("lint", "-"),
        '{"timezone_utc_offset":"+08:00","market_open_rfc3339_time":"09:30:00","invoice_due_rfc3339_date":"2026-06-13","expires_rfc3339":"2026-02-14T10:30:00.5+08:00"}\n',
    )
    assert ok.returncode == 0, f"afdata lint rejected valid strict strings: {ok.stdout!r}"


def assert_afdata_lint_numeric_and_url() -> None:
    for payload in (
        # Durations must be numeric, not unit-in-value strings.
        '{"timeout_s":"30"}\n',
        '{"retry_after_ms":"100ms"}\n',
        # Minor-unit currency amounts must be integers.
        '{"price_usd_cents":12.5}\n',
        '{"fee_jpy":"100"}\n',
        # A _url must be a single URL: no internal whitespace, no bare credentials.
        '{"callback_url":"https://example.com/a b"}\n',
        '{"db_url":"user:pass@host:5432/db"}\n',
    ):
        proc = run_afdata(("lint", "-"), payload)
        assert proc.returncode != 0, f"afdata lint accepted malformed numeric/url field: {payload!r}"
        events = terminal_events(proc)
        findings = events[0]["error"]["violations"]
        assert findings[0]["rule_id"] == "suffix_type_mismatch", f"wrong lint finding: {findings!r}"
    ok = run_afdata(
        ("lint", "-"),
        '{"timeout_s":30,"retry_after_ms":100,"price_usd_cents":1250,"fee_jpy":100,"callback_url":"https://example.com/cb?page=2","final_url":"/relative/path"}\n',
    )
    assert ok.returncode == 0, f"afdata lint rejected valid numeric/url fields: {ok.stdout!r}"


def assert_afdata_lint_null_suffix_exempt() -> None:
    # `null` means the field is absent/unset, so every suffix-typed family
    # must accept it with zero findings — one field per family.
    payload = {
        "cached_epoch_s": None,
        "created_at_epoch_ms": None,
        "created_epoch_ns": None,
        "payload_bytes": None,
        "withdrawn_sats": None,
        "balance_msats": None,
        "cpu_percent": None,
        "dns_ttl_s": None,
        "latency_ms": None,
        "session_timeout_minutes": None,
        "price_usd_cents": None,
        "deposit_eur_cents": None,
        "cost_usd_micro": None,
        "fee_jpy": None,
        "expires_rfc3339": None,
        "invoice_due_rfc3339_date": None,
        "market_open_rfc3339_time": None,
        "timezone_utc_offset": None,
        "callback_url": None,
        "language_bcp47": None,
        "api_key_secret": None,
    }
    proc = run_afdata(("lint", "-"), json.dumps(payload) + "\n")
    assert proc.returncode == 0, f"afdata lint rejected null suffix-typed fields: {proc.stdout!r} {proc.stderr!r}"
    events = terminal_events(proc)
    assert events[0]["kind"] == "result", f"afdata lint did not pass null suffix-typed fields: {events!r}"
    assert events[0]["result"] == {"ok": True, "violations": [], "advisories": []}, f"unexpected findings for null fields: {events[0]!r}"


def assert_afdata_lint_null_suffix_exempt_nested() -> None:
    # The same exemption applies at any nesting depth: inside an object and
    # inside array elements.
    payload = {
        "meta": {"cached_epoch_s": None, "callback_url": None},
        "items": [
            {"withdrawn_sats": None, "language_bcp47": None},
            {"price_usd_cents": None, "api_key_secret": None},
        ],
    }
    proc = run_afdata(("lint", "-"), json.dumps(payload) + "\n")
    assert proc.returncode == 0, f"afdata lint rejected nested null suffix-typed fields: {proc.stdout!r} {proc.stderr!r}"
    events = terminal_events(proc)
    assert events[0]["kind"] == "result", f"afdata lint did not pass nested null suffix-typed fields: {events!r}"
    assert events[0]["result"] == {"ok": True, "violations": [], "advisories": []}, f"unexpected findings for nested null fields: {events[0]!r}"


def assert_afdata_lint_suffix_type_regressions() -> None:
    # Present-but-wrong-type values must still fail — the null exemption must
    # not have loosened the type checks for actual values.
    for payload in (
        '{"count_epoch_s":"abc"}\n',
        '{"size_bytes":-1}\n',
        # A bare number, not the required decimal integer string.
        '{"x_epoch_ns":123}\n',
        '{"when_rfc3339":"not-a-date"}\n',
    ):
        proc = run_afdata(("lint", "-"), payload)
        assert proc.returncode != 0, f"afdata lint accepted an invalid present value: {payload!r}"
        events = terminal_events(proc)
        findings = events[0]["error"]["violations"]
        assert findings[0]["rule_id"] == "suffix_type_mismatch", f"wrong lint finding: {findings!r}"
    # Valid present values must still pass.
    ok = run_afdata(
        ("lint", "-"),
        '{"cached_epoch_s":1707868800,"id_epoch_ns":"1707868800000000000"}\n',
    )
    assert ok.returncode == 0, f"afdata lint rejected valid present suffix-typed values: {ok.stdout!r}"

    # Naming suffixes are ASCII case-insensitive. Uppercase spellings must
    # enforce the same contracts as their lowercase equivalents.
    uppercase_bad = run_afdata(
        ("lint", "-"),
        '{"CACHED_EPOCH_S":"abc","SIZE_BYTES":-1,"CALLBACK_URL":7}\n',
    )
    assert uppercase_bad.returncode != 0, (
        f"afdata lint accepted invalid uppercase suffix-typed fields: "
        f"{uppercase_bad.stdout!r}"
    )
    uppercase_findings = terminal_events(uppercase_bad)[0]["error"]["violations"]
    assert len(uppercase_findings) == 3, uppercase_findings
    assert all(
        finding["rule_id"] == "suffix_type_mismatch"
        for finding in uppercase_findings
    ), uppercase_findings

    uppercase_ok = run_afdata(
        ("lint", "-"),
        '{"CACHED_EPOCH_S":1707868800,"CALLBACK_URL":"https://example.com"}\n',
    )
    assert uppercase_ok.returncode == 0, (
        f"afdata lint rejected valid uppercase suffix-typed fields: "
        f"{uppercase_ok.stdout!r}"
    )


def assert_afdata_lint_suffix_arrays() -> None:
    ok_proc = run_afdata(
        ("lint", "-"),
        '{"retry_delays_ms":[100,2500],"seen_epoch_ms":[1700000000000],"sizes_bytes":[1024],"accepted_bcp47":["zh-CN","en"],"seen_rfc3339":["2026-01-01T00:00:00Z"],"range_ms":[100,null],"empty_ms":[]}\n',
    )
    assert ok_proc.returncode == 0, (
        f"afdata lint rejected valid suffix arrays: {ok_proc.stdout!r}"
    )

    # A plain collection name carries no element contract, so nested arrays
    # under it are data, not a suffix violation.
    unsuffixed_proc = run_afdata(
        ("lint", "--violations-only", "-"),
        '{"rows":[["a","b"]],"edits":[["first","/form/name","submitted"]]}\n',
    )
    assert unsuffixed_proc.returncode == 0, (
        f"afdata lint rejected nested arrays under unsuffixed keys: {unsuffixed_proc.stdout!r}"
    )

    bad_cases = [
        ('{"retry_delays_ms":[100,"2500"]}\n', "/retry_delays_ms/1"),
        ('{"seen_epoch_ms":[1.5]}\n', "/seen_epoch_ms/0"),
        ('{"accepted_bcp47":["zh_CN"]}\n', "/accepted_bcp47/0"),
        ('{"retry_delays_ms":[[100]]}\n', "/retry_delays_ms/0"),
        ('{"latency_ms":{"p50":1}}\n', "/latency_ms"),
    ]
    for payload, expected_pointer in bad_cases:
        proc = run_afdata(("lint", "--violations-only", "-"), payload)
        assert proc.returncode != 0, f"expected lint failure for {payload!r}: {proc.stdout!r}"
        findings = terminal_events(proc)[0]["error"]["violations"]
        assert len(findings) == 1, findings
        assert findings[0]["rule_id"] == "suffix_type_mismatch", findings
        assert findings[0]["pointer"] == expected_pointer, findings

    schema_ok = run_afdata(
        ("lint", "--schema", "-"),
        '{"properties":{"retry_delays_ms":{"type":"array","items":{"type":"integer"}}}}\n',
    )
    assert schema_ok.returncode == 0, schema_ok.stdout

    schema_bad = run_afdata(
        ("lint", "--schema", "-"),
        '{"properties":{"retry_delays_ms":{"type":"array","items":{"type":"string"}}}}\n',
    )
    assert schema_bad.returncode != 0, schema_bad.stdout

    schema_no_items = run_afdata(
        ("lint", "--schema", "-"),
        '{"properties":{"retry_delays_ms":{"type":"array"}}}\n',
    )
    assert schema_no_items.returncode == 0, schema_no_items.stdout

    schema_url_array = run_afdata(
        ("lint", "--schema", "-"),
        '{"properties":{"relay_url":{"type":"array","items":{"type":"string"}}}}\n',
    )
    assert schema_url_array.returncode == 0, schema_url_array.stdout

    plain_render = run_afdata(
        ("render", "--output", "plain", "-"),
        '{"retry_delays_ms":[100,2500]}\n',
    )
    assert plain_render.returncode == 0, plain_render.stderr
    assert plain_render.stdout.strip() == "retry_delays_ms=100,2500", plain_render.stdout


def assert_afdata_lint_text_formats() -> None:
    dotenv_ok = run_afdata(
        ("lint", "--input-format", "dotenv", "-"),
        (
            "CACHE_TTL_S=3600\n"
            "TOKEN_VALIDITY_HOURS=24\n"
            "SIZE_BYTES=1024\n"
            "CPU_PERCENT=99.5\n"
            "SEEN_EPOCH_MS=1700000000000\n"
            "EMPTY_MS=\n"
        ),
    )
    assert dotenv_ok.returncode == 0, dotenv_ok.stdout

    dotenv_bad_text = run_afdata(
        ("lint", "--input-format", "dotenv", "-"),
        "TIMEOUT_MS=5s\n",
    )
    assert dotenv_bad_text.returncode != 0, dotenv_bad_text.stdout
    findings = terminal_events(dotenv_bad_text)[0]["error"]["violations"]
    assert len(findings) == 1, findings
    assert findings[0]["rule_id"] == "suffix_type_mismatch", findings
    assert findings[0]["pointer"] == "/TIMEOUT_MS", findings

    for payload in ("SIZE_BYTES=-1\n", "SEEN_EPOCH_MS=1.5\n"):
        proc = run_afdata(("lint", "--input-format", "dotenv", "-"), payload)
        assert proc.returncode != 0, f"expected lint failure for {payload!r}: {proc.stdout!r}"

    dotenv_missing = run_afdata(
        ("lint", "--input-format", "dotenv", "-"),
        "TIMEOUT=5000\n",
    )
    assert dotenv_missing.returncode == 0, dotenv_missing.stdout
    missing_findings = terminal_events(dotenv_missing)[0]["result"]["advisories"]
    assert any(
        f["rule_id"] == "missing_suffix" and f["pointer"] == "/TIMEOUT"
        for f in missing_findings
    ), missing_findings

    ini_ok = run_afdata(
        ("lint", "--input-format", "ini", "-"),
        "[s]\ntimeout_ms=5000\n",
    )
    assert ini_ok.returncode == 0, ini_ok.stdout

    ini_bad = run_afdata(
        ("lint", "--input-format", "ini", "-"),
        "[s]\ntimeout_ms=fast\n",
    )
    assert ini_bad.returncode != 0, ini_bad.stdout
    ini_findings = terminal_events(ini_bad)[0]["error"]["violations"]
    assert len(ini_findings) == 1, ini_findings
    assert ini_findings[0]["rule_id"] == "suffix_type_mismatch", ini_findings
    assert ini_findings[0]["pointer"] == "/s/timeout_ms", ini_findings

    json_bad = run_afdata(("lint", "-"), '{"timeout_ms":"5000"}\n')
    assert json_bad.returncode != 0, json_bad.stdout


def assert_afdata_lint_plural_missing_suffix() -> None:
    advisory_cases = [
        ('{"tokens":["sk-live"]}\n', "/tokens"),
        ('{"passwords":["p"]}\n', "/passwords"),
        ('{"api_keys":["k"]}\n', "/api_keys"),
        ('{"timeouts":[5]}\n', "/timeouts"),
        ('{"retry_delays":[100,200]}\n', "/retry_delays"),
        ('{"created_at":[1700000000]}\n', "/created_at"),
        ('{"timeouts":5}\n', "/timeouts"),
    ]
    for payload, expected_pointer in advisory_cases:
        proc = run_afdata(("lint", "-"), payload)
        assert proc.returncode == 0, f"expected advisory exit 0 for {payload!r}: {proc.stdout!r}"
        findings = terminal_events(proc)[0]["result"]["advisories"]
        assert len(findings) == 1, findings
        assert findings[0]["rule_id"] == "missing_suffix", findings
        assert terminal_events(proc)[0]["result"]["ok"] is True
        assert findings[0]["pointer"] == expected_pointer, findings

        err_only = run_afdata(("lint", "--violations-only", "-"), payload)
        assert err_only.returncode == 0, err_only.stdout
        assert terminal_events(err_only)[0]["result"] == {"ok": True, "violations": [], "advisories": []}, err_only.stdout

    ok_cases = [
        '{"tokens":1500}\n',
        '{"max_tokens":4096}\n',
        '{"tokens":[]}\n',
        '{"tokens":[{"id":1}]}\n',
        '{"tokens_secret":["sk-live"]}\n',
        '{"retry_delays_ms":[100]}\n',
    ]
    for payload in ok_cases:
        proc = run_afdata(("lint", "-"), payload)
        assert proc.returncode == 0, proc.stdout
        assert terminal_events(proc)[0]["result"] == {"ok": True, "violations": [], "advisories": []}, (
            f"unexpected findings for {payload!r}: {proc.stdout!r}"
        )


def assert_afdata_lint_formatted_quantities() -> None:
    samples = [
        "1,200", "1.200", "1 200", "1\u00a0200", "1\u202f200",
        "8 MB", "3.8 kB", "512 bytes", "23 °C", "38%", "12 ms", "1.5 s", "12 EUR",
        "3m", "1h 2m", "2d 4h", "00:03:12", "—", "-", "n/a", "N/A", "none", "7", "-3",
    ]
    payload = json.dumps({
        "tables": [{"rows": sample} for sample in samples],
        "total_size": "8 MB", "age": "3m", "live_rows": "1,200", "row_count": "1,200",
        "build_count": "1,200",
        "summary": "3 tables · 1 view",
        **{f"item_{key}": "7" for key in
           ("version", "build", "id", "code", "zip", "postcode", "phone", "sku",
            "label", "name", "title", "sqlstate")},
        "itemId": "7", "build": "12345", "itemBuild": "7",
        "elapsed_clock_rfc3339_time": "00:03:12",
        "seen_epoch_ns": "7", "amount_sats": "7", "price_msats": "7",
    })
    proc = run_afdata(("lint", "-"), payload)
    assert proc.returncode == 0, proc.stdout
    findings = terminal_events(proc)[0]["result"]["advisories"]
    assert {f["pointer"] for f in findings} == {
        *(f"/tables/{index}/rows" for index in range(len(samples))),
        "/total_size", "/age", "/live_rows", "/row_count", "/build_count",
    }, findings
    assert all(f["rule_id"] == "formatted_quantity_string"
               for f in findings), findings
    errors_only = run_afdata(("lint", "--violations-only", "-"), payload)
    assert errors_only.returncode == 0, errors_only.stdout
    assert terminal_events(errors_only)[0]["result"] == {"ok": True, "violations": [], "advisories": []}, errors_only.stdout

    invalid = run_afdata(("lint", "-"), json.dumps({
        "total_bytes": "8 MB", "age_s": "3m",
        "last_vacuum_epoch_ms": "2026-11-01", "ratio_percent": "38%",
    }))
    assert invalid.returncode != 0, invalid.stdout
    event = terminal_events(invalid)[0]["error"]
    bytes_advice = next(item for item in event["advisories"] if item["pointer"] == "/total_bytes")
    assert bytes_advice["message"] == "If this is a quantity, send integer bytes.", bytes_advice
    findings = terminal_events(invalid)[0]["error"]["violations"]
    assert {f["pointer"] for f in findings if f["rule_id"] == "suffix_type_mismatch"} == {
        "/total_bytes", "/age_s", "/last_vacuum_epoch_ms", "/ratio_percent",
    }, findings


def assert_afdata_cli_capabilities() -> None:
    ver = run_afdata(("--version", "--output", "json"), "")
    assert ver.returncode == 0, f"afdata --version --output json failed: {ver.stderr!r}"
    payload = json.loads(ver.stdout)
    assert payload["result"]["version"], f"no version in {ver.stdout!r}"

    default_help = run_afdata(("--help",), "")
    assert default_help.returncode == 0, f"afdata --help failed: {default_help.stderr!r}"
    help_event = json.loads(default_help.stdout)
    help_model = validate_help_v2_event(help_event)
    assert help_model["command_path"] == "afdata", help_model
    assert "arguments" not in help_model, help_model
    assert len(default_help.stdout.encode()) < 2000, (
        f"root discovery help is too large: {len(default_help.stdout.encode())} bytes"
    )
    validated_help = run_afdata(
        ("validate", "-", "--strict", "--per-event"),
        default_help.stdout,
    )
    assert validated_help.returncode == 0, (
        f"default help is not a strict protocol event: {validated_help.stderr!r}"
    )
    plain = run_afdata(("--help", "--output", "plain"), "")
    assert plain.returncode == 0, f"afdata --help --output plain failed: {plain.stderr!r}"
    assert "more:" in plain.stdout, plain.stdout[:160]

    recursive_json = run_afdata(("--help", "--recursive"), "")
    assert recursive_json.returncode == 2, "--recursive must not survive help-v2"
    assert json.loads(recursive_json.stderr)["error"]["code"] == "cli_unknown_argument"

    md = run_afdata(("--help", "--output", "markdown"), "")
    assert md.returncode == 2, "help-v2 must not retain Markdown export"
    assert json.loads(md.stderr)["error"]["code"] == "cli_invalid_argument_value"

    scoped = run_afdata(("set", "--help"), "")
    assert scoped.returncode == 0, f"afdata set --help failed: {scoped.stderr!r}"
    scoped_event = json.loads(scoped.stdout)
    scoped_help = validate_help_v2_event(scoped_event)
    assert scoped_help["command_path"] == "afdata set", scoped_help
    assert [shape["id"] for shape in scoped_help["shapes"]] == [
        "set-value",
        "set-null",
        "set-secret",
    ], scoped_help
    for shape in scoped_help["shapes"]:
        assert "--output <json|yaml|plain>" in shape["usage"], shape
    set_value, set_null, set_secret = scoped_help["shapes"]
    assert scoped_help["defaults"]["--value-type"] == "string", scoped_help
    assert "--value-type=string" in set_value["about"], set_value
    assert "[--value-type <string|number|bool|json>]" in set_value["usage"], set_value
    assert "--value-type null" in set_null["usage"], set_null
    assert "--value-type" not in set_secret["usage"], set_secret
    for shape in (set_null, set_secret):
        assert "--value-type=" not in shape["about"], shape

    plain = run_afdata(("set", "--help", "--output", "plain"), "")
    assert plain.returncode == 0, plain.stderr
    shape_help = plain.stdout.split("\ndefaults:", 1)[0]
    value_help, remaining_help = shape_help.split("set-null  ", 1)
    assert "--value-type=string" in value_help, plain.stdout
    assert "--value-type=string" not in remaining_help, plain.stdout

    docs = run_afdata(("--docs",), "")
    assert docs.returncode == 0, docs.stderr
    set_docs = docs.stdout.split("### `afdata set`\n", 1)[1].split("\n### ", 1)[0]
    value_docs, remaining_docs = set_docs.split("#### `set-null`", 1)
    assert "`--value-type` = `string`" in value_docs, set_docs
    assert "`--value-type` = `string`" not in remaining_docs, set_docs
    # One complete answer costs more than the old first level did, and less than
    # that level plus a follow-up for the shape the caller actually wanted.
    assert len(scoped.stdout.encode()) < 2200, (
        f"set help is too large: {len(scoped.stdout.encode())} bytes"
    )

    combination_help = run_afdata(("set", "--help-combination", "set-null"), "")
    assert combination_help.returncode == 2, "the second help level must not survive"
    assert (
        json.loads(combination_help.stderr)["error"]["code"] == "cli_unknown_argument"
    ), combination_help.stderr

    missing = run_afdata((), "")
    assert missing.returncode == 2, f"afdata without a command returned {missing.returncode}"
    assert not missing.stdout, f"split output leaked an error to stdout: {missing.stdout!r}"
    missing_event = json.loads(missing.stderr)
    assert missing_event["error"]["code"] == "cli_unregistered_combination", missing_event
    assert "`afdata --help`" in missing_event["error"]["hint"], missing_event
    assert len(missing.stderr.encode()) < 512, (
        f"missing-command error embedded eager help: {len(missing.stderr.encode())} bytes"
    )

    # `-h`/`-V` are deliberately unsupported: AFDATA spells both out in full, and
    # Short aliases are deliberately unsupported by the registered grammar.
    for short_flag in ("-h", "-V"):
        short = run_afdata((short_flag,), "")
        assert short.returncode == 2, (
            f"afdata {short_flag} returned {short.returncode}, expected a structured error"
        )
        assert not short.stdout, f"split output leaked an error to stdout: {short.stdout!r}"
        short_event = json.loads(short.stderr)
        assert short_event["error"]["code"] == "cli_unknown_argument", short_event
        assert "--help" in short_event["error"]["hint"], short_event
    scoped_short = run_afdata(("get", "-h"), "")
    assert scoped_short.returncode == 2, (
        f"afdata get -h returned {scoped_short.returncode}, expected a structured error"
    )

    pseudo = run_afdata(("help",), "")
    assert pseudo.returncode == 2, f"afdata help pseudo-command returned {pseudo.returncode}"
    assert not pseudo.stdout, f"split output leaked an error to stdout: {pseudo.stdout!r}"
    pseudo_event = json.loads(pseudo.stderr)
    assert pseudo_event["error"]["code"] == "cli_unknown_command", pseudo_event

    conflict = run_afdata(
        ("set", "data.json", "key", "visible", "--secret-from", "env:VALUE_SECRET"),
        "",
    )
    assert conflict.returncode == 2
    assert not conflict.stdout
    assert "VALUE_SECRET" not in conflict.stderr
    assert json.loads(conflict.stderr)["error"]["code"] == "cli_unregistered_combination"

    raw_conflict = run_afdata(("value", "data.json", "key", "--output", "json"), "")
    assert raw_conflict.returncode == 2
    assert json.loads(raw_conflict.stderr)["error"]["code"] == "cli_unregistered_combination"

    # A value the registry accepted but the command cannot use is still an
    # invalid argument value. `cli-spec-v1` has no "non-empty string" type, so
    # this one is decided a layer later — but a caller branches on `error.code`,
    # and the layer that noticed is not something it should have to know. The
    # generic `cli_error` stays available to CLIs with no registry to name a
    # rule; a registry-compiled one must never fall back to it.
    for argv in (
        ("emit", "result", ""),
        ("emit", "log", "info", ""),
        ("emit", "error", "", "boom"),
        ("emit", "error", "code", "boom", "--hint", ""),
    ):
        empty = run_afdata(argv, "")
        assert empty.returncode == 2, f"{argv} returned {empty.returncode}"
        assert not empty.stdout, f"split output leaked an error to stdout: {empty.stdout!r}"
        empty_event = json.loads(empty.stderr)
        assert empty_event["error"]["code"] == "cli_invalid_argument_value", empty_event
        assert "--help" in empty_event["error"]["hint"], empty_event


def assert_afdata_render_redacts() -> None:
    proc = run_afdata(("render", "-", "--output", "json"), '{"api_key_secret":"sk-live","ok":true}\n')
    assert proc.returncode == 0, f"afdata render failed: stderr={proc.stderr!r}, stdout={proc.stdout!r}"
    value = json.loads(proc.stdout)
    assert value["api_key_secret"] == "***", f"afdata render did not redact: {value!r}"
    assert value["ok"] is True, f"afdata render changed non-secret value: {value!r}"


def assert_afdata_render_routes_values_to_stderr() -> None:
    for text, expected in (
        ('{"answer":42,"api_key_secret":"sk-live"}\n', [{"answer": 42, "api_key_secret": "***"}]),
        ('{"answer":42}\n{"answer":43}\n', [{"answer": 42}, {"answer": 43}]),
    ):
        proc = run_afdata(("render", "-", "--output-to", "stderr"), text)
        assert proc.returncode == 0, f"afdata render failed: stderr={proc.stderr!r}, stdout={proc.stdout!r}"
        assert not proc.stdout, f"render --output-to stderr leaked values to stdout: {proc.stdout!r}"
        values = [json.loads(line) for line in proc.stderr.splitlines()]
        assert values == expected, f"render changed routed values: {values!r}"
        assert proc.stderr.endswith("\n") == (len(expected) > 1), proc.stderr


def assert_afdata_parse_error() -> None:
    proc = run_afdata(("render", "-"), '{"ok":true}\nnot-json\n')
    assert proc.returncode != 0, "afdata render accepted invalid JSONL"
    events = terminal_events(proc)
    assert events[0]["kind"] == "error", f"afdata parse error missing: {events!r}"
    assert events[0]["error"]["code"] == "jsonl_parse_failed", f"wrong parse code: {events[0]!r}"


def assert_afdata_skill_validate_relative_paths() -> None:
    with tempfile.TemporaryDirectory() as temp:
        directory = Path(temp) / "example-skill"
        directory.mkdir()
        skill = directory / "SKILL.md"
        skill.write_text("---\nname: example-skill\ndescription: A sample skill.\n---\n# Example\n")
        for path in (".", "SKILL.md", "./SKILL.md", str(skill)):
            proc = run_afdata_skill(("skill", "validate", path), cwd=directory)
            assert proc.returncode == 0, proc
        skill.write_text("---\nname: wrong-name\ndescription: A sample skill.\n---\n")
        proc = run_afdata_skill(("skill", "validate", "."), cwd=directory)
        assert proc.returncode != 0, proc

        if os.name == "posix":
            link = directory / "linked.md"
            link.symlink_to(skill)
            proc = run_afdata_skill(("skill", "validate", str(link)), cwd=directory)
            assert terminal_events(proc)[0]["error"]["code"] == "document_io_failed", proc


def assert_afdata_lint_url_field_whitespace() -> None:
    data = {"relative_url": " /cb?page=2 ", "absolute_url": "https://example.test/path\u00a0"}
    good = run_afdata(("lint", "--violations-only", "-"), json.dumps(data))
    assert good.returncode == 0, good
    data["invalid_url"] = "https://example.test/a\u3000b"
    bad = run_afdata(("lint", "--violations-only", "-"), json.dumps(data))
    violations = terminal_events(bad)[0]["error"]["violations"]
    assert [(v["rule_id"], v["pointer"]) for v in violations] == [
        ("suffix_type_mismatch", "/invalid_url")
    ], violations


def assert_afdata_reads_regular_files_under_the_byte_limit() -> None:
    with tempfile.TemporaryDirectory() as temp:
        path = Path(temp) / "sample.json"
        path.write_text("{}")
        for source in ("-", str(path)):
            for limit in ("1", "2"):
                proc = run_afdata(("lint", "--max-file-bytes", limit, source), "{}")
                assert (proc.returncode == 0) == (limit == "2"), proc
        if os.name == "posix":
            fifo = Path(temp) / "sample-fifo"
            os.mkfifo(fifo)
            for special in (os.devnull, str(fifo)):
                proc = run_afdata(("lint", "--input-format", "json", special), "")
                assert terminal_events(proc)[0]["error"]["code"] == "document_io_failed", proc


def assert_afdata_skill_status_feature() -> None:
    with tempfile.TemporaryDirectory(prefix="afdata-skill-e2e-") as tmp:
        proc = run_afdata_skill(("skill", "status", "--agent", "codex", "--skills-dir", tmp))
    assert proc.returncode == 0, f"afdata skill status failed: stderr={proc.stderr!r}, stdout={proc.stdout!r}"
    events = terminal_events(proc)
    assert len(events) == 1, f"afdata skill status emitted unexpected events: {events!r}"
    assert events[0]["kind"] == "result", f"skill status not a result event: {events[0]!r}"
    result = events[0]["result"]
    assert result["code"] == "skill_status", f"wrong skill status code: {result!r}"
    assert result["skill"] == "agent-first-data", f"wrong skill name: {result!r}"


def assert_afdata_skill_error_includes_partial_report() -> None:
    with tempfile.TemporaryDirectory(prefix="afdata-skill-error-e2e-") as tmp:
        skill_dir = Path(tmp) / "agent-first-data"
        skill_dir.mkdir(parents=True)
        (skill_dir / "SKILL.md").write_text(
            "---\nname: custom\ndescription: custom\n---\n", encoding="utf-8"
        )
        proc = run_afdata_skill(("skill", "install", "--agent", "codex", "--skills-dir", tmp))
    # Refused after resolving targets, so a domain failure (exit 1), not a
    # usage error (exit 2).
    assert proc.returncode == 1, f"unmanaged skill refusal exit: {proc.returncode}, stderr={proc.stderr!r}"
    events = terminal_events(proc)
    assert len(events) == 1, f"afdata skill install emitted unexpected events: {events!r}"
    error = events[0]["error"]
    assert error["code"] == "skill_refused", f"wrong skill error code: {events[0]!r}"
    report = error["partial_report"]
    assert report["code"] == "skill_install", f"wrong partial report code: {report!r}"
    assert report["installed"] is False, f"partial install report should be failed: {report!r}"
    assert report["targets"][0]["installed"] is True, f"partial report lost target status: {report!r}"
    assert report["targets"][0]["managed"] is False, f"unmanaged target should be reported: {report!r}"


def assert_afdata_skill_empty_home_is_a_usage_error() -> None:
    # An empty HOME or CODEX_HOME used to resolve to the current directory, so
    # a personal install landed in ./skills. Cargo and rustup keep their own
    # resolved homes so the build itself still finds them.
    env = dict(os.environ)
    env["CARGO_HOME"] = env.get("CARGO_HOME") or str(Path.home() / ".cargo")
    env["RUSTUP_HOME"] = env.get("RUSTUP_HOME") or str(Path.home() / ".rustup")
    env.update({"HOME": "", "USERPROFILE": "", "CODEX_HOME": ""})
    with tempfile.TemporaryDirectory(prefix="afdata-skill-home-e2e-") as tmp:
        proc = run_afdata_skill(("skill", "install", "--agent", "codex"), cwd=Path(tmp), env=env)
        leaked = sorted(p.name for p in Path(tmp).iterdir())
    assert leaked == [], f"empty HOME installed into the current directory: {leaked!r}"
    assert proc.returncode == 2, f"empty HOME exit: {proc.returncode}, stderr={proc.stderr!r}"
    events = terminal_events(proc)
    assert events[0]["error"]["code"] == "skill_usage_error", f"wrong empty-HOME code: {events!r}"


def assert_afdata_skill_help_is_feature_gated() -> None:
    # Default build is full-featured: skill management is present.
    full_help = run_afdata(("--help",), "")
    assert full_help.returncode == 0, f"default afdata help failed: {full_help.stderr!r}"
    assert "skill" in full_help.stdout, "default afdata help must show skill subcommand"
    # Opting out (default-features = false) drops back to the core CLI.
    minimal_help = run_afdata_minimal(("--help",))
    assert minimal_help.returncode == 0, f"minimal afdata help failed: {minimal_help.stderr!r}"
    assert "skill" not in minimal_help.stdout, "minimal afdata help must not show skill subcommand"


def main() -> None:
    assert_rust_example_uses_help_v2()
    print("[e2e] Rust CliSpec example: ok")
    for check in (
        assert_afdata_validate,
        assert_afdata_validate_strict_event,
        assert_afdata_validate_stream_error,
        assert_afdata_lint_report,
        assert_afdata_lint_schema_secret,
        assert_afdata_lint_schema_literals_and_advisories,
        assert_afdata_lint_schema_suffix_types,
        assert_afdata_lint_bcp47,
        assert_afdata_lint_strict_strings,
        assert_afdata_lint_numeric_and_url,
        assert_afdata_lint_null_suffix_exempt,
        assert_afdata_lint_null_suffix_exempt_nested,
        assert_afdata_lint_suffix_type_regressions,
        assert_afdata_lint_suffix_arrays,
        assert_afdata_lint_text_formats,
        assert_afdata_lint_plural_missing_suffix,
        assert_afdata_lint_formatted_quantities,
        assert_afdata_cli_capabilities,
        assert_afdata_render_redacts,
        assert_afdata_render_routes_values_to_stderr,
        assert_afdata_parse_error,
        assert_afdata_lint_url_field_whitespace,
        assert_afdata_reads_regular_files_under_the_byte_limit,
        assert_afdata_skill_validate_relative_paths,
        assert_afdata_skill_status_feature,
        assert_afdata_skill_error_includes_partial_report,
        assert_afdata_skill_empty_home_is_a_usage_error,
        assert_afdata_skill_help_is_feature_gated,
    ):
        check()
    print("[e2e] afdata: ok")


if __name__ == "__main__":
    main()