agent-first-data 0.22.0

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
"""Tests for agent_first_data CLI helpers."""
import json

import pytest
from io import StringIO
from agent_first_data import (
    OutputFormat,
    OutputTo,
    PlainStyle,
    OutputOptions,
    LogLevel,
    CliEmitter,
    json_error,
    json_log,
    json_result,
    cli_parse_output,
    cli_parse_log_filters,
    render,
    build_cli_error,
    build_cli_version,
    cli_render_version,
    cli_handle_version_or_continue,
)


# ── cli_parse_output ──────────────────────────────────────────────────────────

def test_parse_output_all_formats():
    assert cli_parse_output("json") is OutputFormat.JSON
    assert cli_parse_output("yaml") is OutputFormat.YAML
    assert cli_parse_output("plain") is OutputFormat.PLAIN


def test_parse_output_rejects_unknown():
    with pytest.raises(ValueError):
        cli_parse_output("xml")
    with pytest.raises(ValueError):
        cli_parse_output("JSON")
    with pytest.raises(ValueError):
        cli_parse_output("")


def test_parse_output_error_contains_value():
    with pytest.raises(ValueError, match="toml"):
        cli_parse_output("toml")
    with pytest.raises(ValueError, match="json"):
        cli_parse_output("toml")


# ── cli_parse_log_filters ─────────────────────────────────────────────────────

def test_parse_log_filters_trims_and_lowercases():
    assert list(cli_parse_log_filters(["  Query  ", "ERROR"])) == ["query", "error"]


def test_parse_log_filters_deduplicates():
    assert list(cli_parse_log_filters(["query", "error", "Query", "query"])) == ["query", "error"]


def test_parse_log_filters_removes_empty():
    assert list(cli_parse_log_filters(["", "query", "  "])) == ["query"]


def test_parse_log_filters_empty_list():
    assert list(cli_parse_log_filters([])) == []


def test_parse_log_filters_preserves_order():
    assert list(cli_parse_log_filters(["startup", "request", "retry"])) == ["startup", "request", "retry"]


# ── build_cli_error ───────────────────────────────────────────────────────────

def test_build_cli_error_required_fields():
    v = build_cli_error("missing --sql")
    assert v["kind"] == "error"
    assert v["error"]["code"] == "cli_error"
    assert v["error"]["message"] == "missing --sql"
    assert v["error"]["retryable"] is False
    assert "error_code" not in v
    assert "retryable" not in v
    assert v["trace"] == {}


def test_build_cli_error_is_valid_json():
    import json
    v = build_cli_error("oops")
    s = render(v, OutputFormat.JSON)
    parsed = json.loads(s)
    assert parsed["kind"] == "error"
    assert parsed["error"]["code"] == "cli_error"


def test_build_cli_error_with_hint():
    v = build_cli_error("bad flag", hint="try --help")
    assert v["error"]["hint"] == "try --help"


def test_build_cli_error_without_hint_has_no_hint_key():
    v = build_cli_error("oops")
    assert "hint" not in v["error"]


def test_build_cli_error_never_raises_on_empty_message():
    # L1: build_cli_error must never raise. An empty message is substituted
    # with a placeholder so the internal json_error(...).build() cannot fail.
    v = build_cli_error("")
    assert v["kind"] == "error"
    assert v["error"]["code"] == "cli_error"
    assert v["error"]["message"] == "unspecified error"


# ── render ────────────────────────────────────────────────────────────────────

def test_render_dispatches_json():
    v = json_result({"size_bytes": 1024}).build().to_dict()
    out = render(v, OutputFormat.JSON)
    assert "size_bytes" in out   # json: raw keys, no suffix processing
    assert "\n" not in out


def test_render_dispatches_yaml():
    v = json_result({"size_bytes": 1024}).build().to_dict()
    out = render(v, OutputFormat.YAML)
    assert out.startswith("---")
    assert "size_bytes: 1024" in out   # yaml: structure-preserving, raw keys/values
    assert "size:" not in out


def test_render_dispatches_plain():
    v = json_result({"ok": True}).build().to_dict()
    out = render(v, OutputFormat.PLAIN)
    assert "\n" not in out
    assert "kind=result" in out


def test_render_dispatches_raw_yaml_with_options():
    v = {"size_bytes": 1024}
    out = render(
        v,
        OutputFormat.YAML,
        options=OutputOptions(style=PlainStyle.Raw),
    )
    assert "size_bytes: 1024" in out
    assert "size:" not in out


def test_render_yaml_ignores_style_option():
    """PlainStyle no longer affects YAML: Readable and Raw dispatch to identical output."""
    v = {"size_bytes": 1024}
    readable = render(v, OutputFormat.YAML, options=OutputOptions(style=PlainStyle.Readable))
    raw = render(v, OutputFormat.YAML, options=OutputOptions(style=PlainStyle.Raw))
    assert readable == raw
    assert "size_bytes: 1024" in readable


# ── CliEmitter ────────────────────────────────────────────────────────────────

def test_cli_emitter_writes_events_and_tracks_terminal():
    writer = StringIO()
    emitter = CliEmitter(writer, OutputFormat.JSON)
    emitter.emit(json_log({"level": "info", "message": "startup"}).build())
    emitter.emit(json_result({"rows": 2}).build())
    lines = writer.getvalue().splitlines()
    assert len(lines) == 2
    assert '"kind":"log"' in lines[0]
    assert '"kind":"result"' in lines[1]


def test_cli_emitter_framing_all_formats():
    events = [
        json_log({"level": "info", "message": "startup"}).build(),
        json_result({"rows": 2}).build(),
    ]
    for fmt in (OutputFormat.JSON, OutputFormat.PLAIN, OutputFormat.YAML):
        writer = StringIO()
        emitter = CliEmitter(writer, fmt)
        for event in events:
            emitter.emit(event)
        out = writer.getvalue()
        if fmt is OutputFormat.JSON:
            lines = out.rstrip("\n").split("\n")
            assert len(lines) == 2
            assert [json.loads(line)["kind"] for line in lines] == ["log", "result"]
        elif fmt is OutputFormat.PLAIN:
            lines = out.rstrip("\n").split("\n")
            assert len(lines) == 2
            assert lines[0].startswith("kind=log")
            assert lines[1].startswith("kind=result")
        else:
            assert out.count("---") == 2
            log_idx = out.index('kind: "log"')
            result_idx = out.index('kind: "result"')
            assert log_idx < result_idx, "records must stay in emission order"
            assert 'level: "info"' in out    # yaml: structure-preserving, raw keys
            assert "rows: 2" in out


def test_cli_emitter_rejects_duplicate_terminal():
    writer = StringIO()
    emitter = CliEmitter(writer, OutputFormat.JSON)
    emitter.emit(json_result({"rows": 2}).build())
    with pytest.raises(RuntimeError, match="duplicate terminal"):
        emitter.emit(json_error("late_error", "too late").build())


def test_cli_emitter_rejects_non_terminal_after_terminal():
    writer = StringIO()
    emitter = CliEmitter(writer, OutputFormat.JSON)
    emitter.emit(json_result({"rows": 2}).build())
    with pytest.raises(RuntimeError, match="after terminal"):
        emitter.emit_progress("100%")


class FailingWriter:
    def write(self, _value: str) -> None:
        raise BrokenPipeError("closed")


def test_cli_emitter_returns_writer_errors():
    emitter = CliEmitter(FailingWriter(), OutputFormat.JSON)
    with pytest.raises(BrokenPipeError):
        emitter.emit(json_result({"rows": 2}).build())


class FailOnceWriter:
    def __init__(self) -> None:
        self.failed = False
        self.value = ""

    def write(self, value: str) -> None:
        if not self.failed:
            self.failed = True
            raise InterruptedError("retry")
        self.value += value

    def flush(self) -> None:
        pass


def test_cli_emitter_does_not_commit_terminal_state_when_write_fails():
    writer = FailOnceWriter()
    emitter = CliEmitter(writer, OutputFormat.JSON)
    event = json_result({"rows": 2}).build()
    with pytest.raises(InterruptedError):
        emitter.emit(event)
    emitter.emit(event)
    assert len(writer.value.rstrip("\n").split("\n")) == 1


def test_cli_emitter_convenience_methods():
    writer = StringIO()
    emitter = CliEmitter(writer, OutputFormat.JSON)
    emitter.emit_log(LogLevel.INFO, "starting")
    emitter.emit_result({"ok": True})
    lines = writer.getvalue().splitlines()
    assert len(lines) == 2
    assert '"kind":"log"' in lines[0]
    assert '"kind":"result"' in lines[1]


def test_cli_emitter_with_log_fields_provider():
    writer = StringIO()
    def log_fields():
        return {
            "source": "test",
            "code": "cache_miss",
            "message": "provider default",
            "level": "debug",
        }
    emitter = CliEmitter(writer, OutputFormat.JSON, log_fields=log_fields)
    emitter.emit_log(LogLevel.INFO, "test message")
    lines = writer.getvalue().splitlines()
    parsed = json.loads(lines[0])
    assert parsed["log"]["source"] == "test"
    assert parsed["log"]["code"] == "cache_miss"
    assert parsed["log"]["message"] == "test message"
    assert parsed["log"]["level"] == "info"


# ── OutputTo parsing ──────────────────────────────────────────────────────────

def test_output_to_parse_all_variants():
    assert OutputTo.parse("split") is OutputTo.SPLIT
    assert OutputTo.parse("stdout") is OutputTo.STDOUT
    assert OutputTo.parse("stderr") is OutputTo.STDERR


def test_output_to_parse_rejects_unknown():
    with pytest.raises(ValueError, match="unsupported --output-to"):
        OutputTo.parse("xml")
    # The offending value and the accepted set are named in the message.
    with pytest.raises(ValueError, match="xml"):
        OutputTo.parse("xml")
    with pytest.raises(ValueError, match="split, stdout, or stderr"):
        OutputTo.parse("both")


def test_output_to_parse_is_case_sensitive():
    with pytest.raises(ValueError):
        OutputTo.parse("SPLIT")
    with pytest.raises(ValueError):
        OutputTo.parse("")


# ── CliEmitter two-mode routing ───────────────────────────────────────────────

def test_finite_split_routes_result_and_diagnostics_separately():
    out = StringIO()
    err = StringIO()
    emitter = CliEmitter.finite_with(out, err, OutputFormat.JSON)
    emitter.emit_log(LogLevel.INFO, "startup")
    emitter.emit_progress("halfway")
    emitter.emit_result({"rows": 2})

    # result → primary (stdout) sink only
    result_lines = out.getvalue().splitlines()
    assert len(result_lines) == 1
    assert json.loads(result_lines[0])["kind"] == "result"

    # log + progress → diagnostic (stderr) sink only
    diag_kinds = [json.loads(line)["kind"] for line in err.getvalue().splitlines()]
    assert diag_kinds == ["log", "progress"]


def test_finite_split_routes_error_to_diagnostic():
    out = StringIO()
    err = StringIO()
    emitter = CliEmitter.finite_with(out, err, OutputFormat.JSON)
    emitter.emit_error("boom", "it broke")
    # error is a diagnostic: it must land on stderr, never on the result stream,
    # so a shell capture of stdout never mistakes a failure for data.
    assert out.getvalue() == ""
    err_lines = err.getvalue().splitlines()
    assert len(err_lines) == 1
    assert json.loads(err_lines[0])["kind"] == "error"


def test_stream_mode_collapses_every_event_onto_one_writer():
    buf = StringIO()
    emitter = CliEmitter.stream(buf, OutputFormat.JSON)
    emitter.emit_log(LogLevel.INFO, "startup")
    emitter.emit_progress("halfway")
    emitter.emit_error("boom", "it broke")
    kinds = [json.loads(line)["kind"] for line in buf.getvalue().splitlines()]
    # every event, including error, preserves interleaved order on one stream
    assert kinds == ["log", "progress", "error"]


def test_default_constructor_is_stream_form():
    # The plain CliEmitter(writer, ...) constructor is the unified/stream form:
    # no diagnostic sink, so every event stays on the single writer.
    buf = StringIO()
    emitter = CliEmitter(buf, OutputFormat.JSON)
    emitter.emit_progress("halfway")
    emitter.emit_error("boom", "it broke")
    kinds = [json.loads(line)["kind"] for line in buf.getvalue().splitlines()]
    assert kinds == ["progress", "error"]


def test_from_output_to_split_is_finite(monkeypatch):
    out = StringIO()
    err = StringIO()
    monkeypatch.setattr("sys.stdout", out)
    monkeypatch.setattr("sys.stderr", err)
    emitter = CliEmitter.from_output_to(OutputTo.SPLIT, OutputFormat.JSON)
    emitter.emit_error("boom", "it broke")
    assert out.getvalue() == ""
    assert json.loads(err.getvalue().splitlines()[0])["kind"] == "error"


def test_from_output_to_stdout_streams_everything_to_stdout(monkeypatch):
    out = StringIO()
    err = StringIO()
    monkeypatch.setattr("sys.stdout", out)
    monkeypatch.setattr("sys.stderr", err)
    emitter = CliEmitter.from_output_to(OutputTo.STDOUT, OutputFormat.JSON)
    emitter.emit_progress("halfway")
    emitter.emit_error("boom", "it broke")
    assert err.getvalue() == ""
    kinds = [json.loads(line)["kind"] for line in out.getvalue().splitlines()]
    assert kinds == ["progress", "error"]


def test_from_output_to_stderr_streams_everything_to_stderr(monkeypatch):
    out = StringIO()
    err = StringIO()
    monkeypatch.setattr("sys.stdout", out)
    monkeypatch.setattr("sys.stderr", err)
    emitter = CliEmitter.from_output_to(OutputTo.STDERR, OutputFormat.JSON)
    emitter.emit_result({"rows": 1})
    assert out.getvalue() == ""
    assert json.loads(err.getvalue().splitlines()[0])["kind"] == "result"


def test_finite_split_still_enforces_terminal_lifecycle():
    out = StringIO()
    err = StringIO()
    emitter = CliEmitter.finite_with(out, err, OutputFormat.JSON)
    emitter.emit_result({"rows": 2})
    with pytest.raises(RuntimeError, match="duplicate terminal"):
        emitter.emit_error("late", "too late")


# ── CliEmitter.finish / finish_result ─────────────────────────────────────────

def test_finish_returns_success_code_on_success():
    buf = StringIO()
    emitter = CliEmitter.stream(buf, OutputFormat.JSON)
    code = emitter.finish(json_result({"rows": 1}).build(), 0)
    assert code == 0
    assert json.loads(buf.getvalue().splitlines()[0])["kind"] == "result"


def test_finish_honors_a_nonzero_success_code():
    buf = StringIO()
    emitter = CliEmitter.stream(buf, OutputFormat.JSON)
    # finish returns the caller's success_code verbatim on a good write.
    code = emitter.finish(json_error("cancelled", "cancelled").build(), 1)
    assert code == 1
    assert json.loads(buf.getvalue().splitlines()[0])["error"]["code"] == "cancelled"


def test_finish_result_writes_result_and_returns_zero():
    out = StringIO()
    err = StringIO()
    emitter = CliEmitter.finite_with(out, err, OutputFormat.JSON)
    code = emitter.finish_result({"ok": True})
    assert code == 0
    assert err.getvalue() == ""
    parsed = json.loads(out.getvalue().splitlines()[0])
    assert parsed["kind"] == "result"
    assert parsed["result"] == {"ok": True}


def test_finish_routes_a_built_error_to_the_diagnostic_sink():
    # The error "type" is the builder: build via json_error(...).hint_if_some(...)
    # and hand the event to finish with the desired exit code. In finite mode the
    # error is a diagnostic → stderr, and finish returns the caller's exit code.
    out = StringIO()
    err = StringIO()
    emitter = CliEmitter.finite_with(out, err, OutputFormat.JSON)
    event = json_error("bad_flag", "bad flag").hint_if_some("try --help").build()
    code = emitter.finish(event, 2)
    assert code == 2
    assert out.getvalue() == ""
    parsed = json.loads(err.getvalue().splitlines()[0])
    assert parsed["error"]["code"] == "bad_flag"
    assert parsed["error"]["hint"] == "try --help"


class _BrokenPipeWriter:
    def write(self, _value: str) -> None:
        raise BrokenPipeError("reader hung up")


class _FailingWriter:
    def write(self, _value: str) -> None:
        raise OSError("disk full")


def test_finish_returns_0_on_broken_pipe():
    emitter = CliEmitter.stream(_BrokenPipeWriter(), OutputFormat.JSON)
    assert emitter.finish(json_result({"rows": 1}).build(), 0) == 0


def test_finish_returns_4_on_other_write_failure():
    emitter = CliEmitter.stream(_FailingWriter(), OutputFormat.JSON)
    assert emitter.finish(json_result({"rows": 1}).build(), 0) == 4


def test_finish_result_returns_0_on_broken_pipe():
    emitter = CliEmitter.stream(_BrokenPipeWriter(), OutputFormat.JSON)
    assert emitter.finish_result({"ok": True}) == 0


def test_finish_returns_4_on_lifecycle_violation():
    # A non-BrokenPipe failure (here a duplicate terminal) resolves to 4.
    buf = StringIO()
    emitter = CliEmitter.stream(buf, OutputFormat.JSON)
    assert emitter.finish(json_result({"rows": 1}).build(), 0) == 0
    assert emitter.finish(json_error("late", "too late").build(), 1) == 4


# ── version helpers ───────────────────────────────────────────────────────────

# The value-taking global flags a caller passes through so their space-separated
# value is not mistaken for the subcommand boundary (the Python stand-in for the
# Rust tests' `version_test_command()` with its `--stdout-file`/`--stderr-file`).
VERSION_VALUE_FLAGS = ["--stdout-file", "--stderr-file"]


def test_build_cli_version_standard_shape():
    v = build_cli_version("agent-cli", "Agent CLI Example", "1.2.3", "abc1234")
    assert v["kind"] == "result"
    assert v["result"]["code"] == "version"
    assert v["result"]["name"] == "agent-cli"
    assert v["result"]["display_name"] == "Agent CLI Example"
    assert v["result"]["version"] == "1.2.3"
    assert v["result"]["build"] == "abc1234"
    # 0.16 spec: all events have trace by default
    assert v["trace"] == {}


def test_build_cli_version_omits_absent_display_name_and_build():
    v = build_cli_version("agent-cli", None, "1.2.3", None)
    result = v["result"]
    assert result["name"] == "agent-cli"
    assert result["version"] == "1.2.3"
    assert "display_name" not in result
    assert "build" not in result


def test_cli_render_version_renders_json():
    out = cli_render_version("agent-cli", None, "1.2.3", None, OutputFormat.JSON)
    assert out.endswith("\n")
    assert '"kind":"result"' in out
    assert '"code":"version"' in out
    assert '"name":"agent-cli"' in out
    assert '"version":"1.2.3"' in out


def test_cli_handle_version_bare_defaults_to_json():
    # The one blessed behavior: `--version` always answers with a protocol-v1
    # event, JSON by default — no more conventional bare-text special case.
    out = cli_handle_version_or_continue(
        ["--version"],
        VERSION_VALUE_FLAGS,
        "agent-cli",
        "Agent CLI Example",
        "1.2.3",
        None,
    )
    assert out is not None
    parsed = json.loads(out.strip())
    assert parsed["kind"] == "result"
    assert parsed["result"]["code"] == "version"
    assert parsed["result"]["name"] == "agent-cli"
    assert parsed["result"]["display_name"] == "Agent CLI Example"
    assert parsed["result"]["version"] == "1.2.3"
    assert "build" not in parsed["result"]
    assert parsed["trace"] == {}


def test_cli_handle_version_honors_explicit_plain_output():
    out = cli_handle_version_or_continue(
        ["--version", "--output", "plain"],
        VERSION_VALUE_FLAGS,
        "agent-cli",
        None,
        "1.2.3",
        None,
    )
    assert out is not None
    assert "kind=result" in out
    assert "result.code=version" in out
    assert "result.version=1.2.3" in out


def test_cli_handle_version_skips_output_to_space_value():
    # A preceding `--output-to <value>` (space form) must not be mistaken for
    # the subcommand boundary; the later `--version --output json` must still be
    # detected.
    out = cli_handle_version_or_continue(
        ["--output-to", "stdout", "--version", "--output", "json"],
        VERSION_VALUE_FLAGS,
        "agent-cli",
        None,
        "1.2.3",
        None,
    )
    assert out is not None
    parsed = json.loads(out.strip())
    assert parsed["kind"] == "result"
    assert parsed["result"]["version"] == "1.2.3"


def test_cli_handle_version_skips_caller_value_flag_space_value():
    # A caller's own value-taking global flag (here `--stdout-file`/
    # `--stderr-file`): the path value must not be mistaken for the subcommand
    # boundary either.
    out = cli_handle_version_or_continue(
        ["--stdout-file", "/tmp/out.log", "--stderr-file", "/tmp/err.log", "--version"],
        VERSION_VALUE_FLAGS,
        "agent-cli",
        None,
        "1.2.3",
        None,
    )
    assert out is not None
    parsed = json.loads(out.strip())
    assert parsed["result"]["name"] == "agent-cli"
    assert parsed["result"]["version"] == "1.2.3"


def test_cli_handle_version_skips_caller_value_flag_inline_value():
    out = cli_handle_version_or_continue(
        ["--stdout-file=/tmp/out.log", "--version"],
        VERSION_VALUE_FLAGS,
        "agent-cli",
        None,
        "1.2.3",
        None,
    )
    assert out is not None


def test_cli_handle_version_skips_caller_defined_value_flag():
    # A consumer's *own* value-taking global flag the pre-parser has no special
    # knowledge of — here a hypha-style comma-list `--log` — must have its
    # space-separated value recognized through `value_flags`, not a hardcoded
    # allowlist. Otherwise `request,startup` would be read as the subcommand
    # boundary and `--version` dropped.
    out = cli_handle_version_or_continue(
        ["--log", "request,startup", "--version"],
        ["--log"],
        "hypha",
        None,
        "1.2.3",
        None,
    )
    assert out is not None
    parsed = json.loads(out.strip())
    assert parsed["result"]["name"] == "hypha"
    assert parsed["result"]["version"] == "1.2.3"


def test_cli_handle_version_boolean_global_flag_does_not_over_consume():
    # The mirror of the case above: a caller's boolean global flag (absent from
    # value_flags) takes no value, so the following positional is the subcommand
    # boundary and a `--version` after it belongs to the subcommand.
    assert (
        cli_handle_version_or_continue(
            ["--verbose", "sense", "--version"],
            ["--log"],
            "hypha",
            None,
            "1.2.3",
            None,
        )
        is None
    )


def test_cli_handle_version_supports_inline_output_format():
    out = cli_handle_version_or_continue(
        ["--output=yaml", "--version"],
        VERSION_VALUE_FLAGS,
        "agent-cli",
        None,
        "1.2.3",
        None,
    )
    assert out is not None
    assert out.startswith("---\n")
    assert 'version: "1.2.3"' in out


def test_cli_handle_version_json_alias():
    out = cli_handle_version_or_continue(
        ["--version", "--json"],
        VERSION_VALUE_FLAGS,
        "agent-cli",
        None,
        "1.2.3",
        None,
    )
    assert out is not None
    parsed = json.loads(out.strip())
    assert parsed["kind"] == "result"
    assert parsed["result"]["version"] == "1.2.3"


def test_cli_handle_version_json_alias_conflict():
    with pytest.raises(ValueError, match="conflicting output formats"):
        cli_handle_version_or_continue(
            ["--version", "--json", "--output", "yaml"],
            VERSION_VALUE_FLAGS,
            "agent-cli",
            None,
            "1.2.3",
            None,
        )


def test_cli_handle_version_returns_none_without_version():
    assert (
        cli_handle_version_or_continue(
            ["ping"],
            VERSION_VALUE_FLAGS,
            "agent-cli",
            None,
            "1.2.3",
            None,
        )
        is None
    )


def test_cli_handle_version_rejects_invalid_output():
    with pytest.raises(ValueError, match="xml"):
        cli_handle_version_or_continue(
            ["--version", "--output", "xml"],
            VERSION_VALUE_FLAGS,
            "agent-cli",
            None,
            "1.2.3",
            None,
        )


def test_cli_handle_version_ignores_version_flag_after_subcommand():
    # A subcommand that takes its own --version <value> must not be hijacked
    # by the top-level pre-parser.
    assert (
        cli_handle_version_or_continue(
            ["hatch", "--version", "1.3.0"],
            VERSION_VALUE_FLAGS,
            "agent-cli",
            None,
            "1.2.3",
            None,
        )
        is None
    )
    assert (
        cli_handle_version_or_continue(
            ["hatch", "-V", "1.3.0"],
            VERSION_VALUE_FLAGS,
            "agent-cli",
            None,
            "1.2.3",
            None,
        )
        is None
    )


def test_cli_handle_version_honors_output_flag_before_top_level_version():
    # Known output flags consume their value, so a trailing top-level
    # --version is still recognized.
    out = cli_handle_version_or_continue(
        ["--output", "json", "--version"],
        VERSION_VALUE_FLAGS,
        "agent-cli",
        None,
        "1.2.3",
        None,
    )
    assert out is not None
    parsed = json.loads(out.strip())
    assert parsed["result"]["version"] == "1.2.3"