harn-cli 0.10.49

CLI for the Harn programming language — run, test, REPL, format, and lint
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
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
use std::io::Write;
use std::process::{Command, Stdio};

use harn_serve::adapters::acp::{
    ACP_PROMPT_ERROR_DATA_SCHEMA, ACP_SCHEMA_COMPATIBILITY, HARN_AGENT_EVENT_KINDS,
    HARN_AGENT_EVENT_METHOD, HARN_CONTENT_EXTENSION_FIELDS, HARN_PROMPT_RESULT_EXTENSION_FIELDS,
    HARN_PROVIDER_CATALOG_METHOD, HARN_SESSION_UPDATE_EXTENSIONS,
    HARN_TOOL_LIFECYCLE_EXTENSION_FIELDS,
};
use harn_serve::{A2A_PROTOCOL_VERSION, MCP_PROTOCOL_VERSION};
use harn_vm::llm::receipts::{TOOL_CALL_RECEIPT_EXECUTORS, TOOL_CALL_RECEIPT_STATUSES};

use super::constants::*;
use super::support::*;
use super::values::*;

#[cfg(test)]
pub(super) fn generate_go_artifact() -> Result<String, String> {
    generate_go_artifact_for_version(env!("CARGO_PKG_VERSION"))
}

pub(super) fn generate_go_artifact_for_version(artifact_version: &str) -> Result<String, String> {
    format_go_source(generate_go_for_version(artifact_version))
}

#[cfg(test)]
pub(super) fn generate_go() -> String {
    generate_go_for_version(env!("CARGO_PKG_VERSION"))
}

pub(super) fn generate_go_for_version(artifact_version: &str) -> String {
    let mut out = String::new();
    out.push_str("// GENERATED by `harn dump-protocol-artifacts` - do not edit by hand.\n");
    out.push_str("// Source: Harn adapter schemas and Rust wire vocabulary.\n\n");
    out.push_str("// Package harnprotocol mirrors the host/integrator surface generated for\n");
    out.push_str("// TypeScript, Swift, and Python. Field names match the wire JSON; optional\n");
    out.push_str("// fields use pointer types or `omitempty` so encoding/json round-trips\n");
    out.push_str("// produce minimal envelopes equivalent to the Rust adapters.\n");
    out.push_str("package harnprotocol\n\n");
    out.push_str("import \"encoding/json\"\n\n");

    for (doc, name, value) in [
        (
            "// ArtifactVersion pins the Harn release that generated this binding.\n",
            "ArtifactVersion",
            artifact_version,
        ),
        (
            "// HarnAgentEventMethod is the JSON-RPC method for `_harn/agentEvent` notifications.\n",
            "HarnAgentEventMethod",
            HARN_AGENT_EVENT_METHOD,
        ),
        (
            "// HarnProviderCatalogMethod is the JSON-RPC method for Harn's provider catalog extension.\n",
            "HarnProviderCatalogMethod",
            HARN_PROVIDER_CATALOG_METHOD,
        ),
        (
            "// ACPSchemaCompatibility is the upstream ACP schema version Harn tracks.\n",
            "ACPSchemaCompatibility",
            ACP_SCHEMA_COMPATIBILITY,
        ),
        (
            "// ACPPromptErrorDataSchema identifies typed session/prompt JSON-RPC error data.\n",
            "ACPPromptErrorDataSchema",
            ACP_PROMPT_ERROR_DATA_SCHEMA,
        ),
        (
            "// A2AProtocolVersion is the A2A protocol version Harn implements.\n",
            "A2AProtocolVersion",
            A2A_PROTOCOL_VERSION,
        ),
        (
            "// MCPProtocolVersion is the MCP protocol version Harn implements.\n",
            "MCPProtocolVersion",
            MCP_PROTOCOL_VERSION,
        ),
        (
            "// MCPStableProtocolVersion is the stable MCP protocol version Harn implements at runtime.\n",
            "MCPStableProtocolVersion",
            MCP_PROTOCOL_VERSION,
        ),
        (
            "// MCPDraftProtocolVersion is the opt-in MCP release-candidate profile identity.\n",
            "MCPDraftProtocolVersion",
            MCP_DRAFT_PROTOCOL_VERSION,
        ),
        (
            "// MCPLegacy20250618ProtocolVersion is the prior stable MCP protocol Harn still accepts.\n",
            "MCPLegacy20250618ProtocolVersion",
            MCP_LEGACY_2025_06_18_PROTOCOL_VERSION,
        ),
        (
            "// MCPFinal2026ProtocolVersion is the scheduled final identity for the RC profile.\n",
            "MCPFinal2026ProtocolVersion",
            MCP_FINAL_2026_PROTOCOL_VERSION,
        ),
        (
            "// MCPJSONSchema202012Dialect is the JSON Schema dialect used by the MCP RC artifact profile.\n",
            "MCPJSONSchema202012Dialect",
            MCP_JSON_SCHEMA_2020_12_DIALECT,
        ),
        (
            "// MCPInputRequiredResultType is the resultType discriminator for multi round-trip requests.\n",
            "MCPInputRequiredResultType",
            MCP_INPUT_REQUIRED_RESULT_TYPE,
        ),
        (
            "// MCPUnsupportedProtocolVersionErrorMessage is the standard message for unsupported versions.\n",
            "MCPUnsupportedProtocolVersionErrorMessage",
            MCP_UNSUPPORTED_PROTOCOL_VERSION_ERROR_MESSAGE,
        ),
    ] {
        out.push_str(doc);
        out.push_str(&format!(
            "const {name} = {}\n\n",
            json_string_literal(value)
        ));
    }
    out.push_str(&format!(
        "// MCPUnsupportedProtocolVersionErrorCode is the JSON-RPC server error for unsupported versions.\nconst MCPUnsupportedProtocolVersionErrorCode = {MCP_UNSUPPORTED_PROTOCOL_VERSION_ERROR_CODE}\n\n"
    ));

    out.push_str(&go_typed_array(
        "ACPAgentMethod",
        "ACPAgentMethods",
        ACP_AGENT_METHODS,
    ));
    out.push_str(&go_typed_array(
        "ACPClientMethod",
        "ACPClientMethods",
        ACP_CLIENT_METHODS,
    ));
    out.push_str(&go_typed_array(
        "ACPAgentNotification",
        "ACPAgentNotifications",
        ACP_AGENT_NOTIFICATIONS,
    ));
    let session_updates = all_acp_session_updates();
    out.push_str(&go_typed_array_owned(
        "ACPSessionUpdate",
        "ACPSessionUpdates",
        &session_updates,
    ));
    out.push_str(&go_typed_array(
        "HarnACPSessionUpdateExtension",
        "HarnACPSessionUpdateExtensions",
        HARN_SESSION_UPDATE_EXTENSIONS,
    ));
    out.push_str(&go_typed_array(
        "HarnAgentEventKind",
        "HarnAgentEventKinds",
        HARN_AGENT_EVENT_KINDS,
    ));
    out.push_str(&go_typed_array(
        "HarnPromptResultExtensionField",
        "HarnPromptResultExtensionFields",
        HARN_PROMPT_RESULT_EXTENSION_FIELDS,
    ));
    out.push_str(&go_typed_array(
        "ACPContentBlockType",
        "ACPContentBlockTypes",
        ACP_CONTENT_BLOCK_TYPES,
    ));
    out.push_str(&go_typed_array_owned(
        "ACPToolKind",
        "ACPToolKinds",
        &tool_kind_values(),
    ));
    out.push_str(&go_typed_array_owned(
        "ACPToolCallStatus",
        "ACPToolCallStatuses",
        &tool_call_status_values(),
    ));
    out.push_str(&go_typed_array_owned(
        "HarnToolCallErrorCategory",
        "HarnToolCallErrorCategories",
        &tool_call_error_category_values(),
    ));
    out.push_str(&go_typed_array_owned(
        "HarnToolMutationStatus",
        "HarnToolMutationStatuses",
        &tool_mutation_status_values(),
    ));
    out.push_str(&go_typed_array_owned(
        "HarnSideEffectLevel",
        "HarnSideEffectLevels",
        &side_effect_level_values(),
    ));
    out.push_str(&go_typed_array_owned(
        "HarnWorkerStatus",
        "HarnWorkerStatuses",
        &worker_status_values(),
    ));
    out.push_str(&go_typed_array_owned(
        "AgentTerminalClass",
        "AgentTerminalClasses",
        &agent_terminal_class_values(),
    ));
    out.push_str(&go_typed_array_owned(
        "AgentTerminalKind",
        "AgentTerminalKinds",
        &agent_terminal_kind_values(),
    ));
    out.push_str(&go_typed_array_owned(
        "AgentTerminalOwner",
        "AgentTerminalOwners",
        &agent_terminal_owner_values(),
    ));
    out.push_str(&go_typed_array(
        "ToolCallReceiptStatus",
        "ToolCallReceiptStatuses",
        TOOL_CALL_RECEIPT_STATUSES,
    ));
    out.push_str(&go_typed_array(
        "ToolCallReceiptExecutor",
        "ToolCallReceiptExecutors",
        TOOL_CALL_RECEIPT_EXECUTORS,
    ));
    out.push_str(&go_typed_array(
        "A2ATaskState",
        "A2ATaskStates",
        A2A_TASK_STATES,
    ));
    out.push_str(&go_typed_array(
        "A2ATaskEventType",
        "A2ATaskEventTypes",
        A2A_TASK_EVENT_TYPES,
    ));
    out.push_str(&go_typed_array(
        "MCPProtocolVersionValue",
        "MCPProtocolVersions",
        MCP_PROTOCOL_VERSIONS,
    ));
    out.push_str(&go_typed_array("MCPMethod", "MCPMethods", MCP_METHODS));
    out.push_str(&go_typed_array(
        "MCPCacheScope",
        "MCPCacheScopes",
        MCP_CACHE_SCOPES,
    ));
    out.push_str(&go_typed_array(
        "MCPResultType",
        "MCPResultTypes",
        MCP_RESULT_TYPES,
    ));
    out.push_str(&go_typed_array(
        "MCPLoggingLevel",
        "MCPLoggingLevels",
        MCP_LOGGING_LEVELS,
    ));
    out.push_str(&go_string_array(
        "HarnToolLifecycleExtensionFields",
        HARN_TOOL_LIFECYCLE_EXTENSION_FIELDS,
    ));
    out.push_str(&go_string_array(
        "HarnContentExtensionFields",
        HARN_CONTENT_EXTENSION_FIELDS,
    ));
    out.push_str(&go_string_array("A2AMethods", A2A_METHODS));
    out.push_str(&go_string_array(
        "MCPRequiredMetadataKeys",
        MCP_REQUIRED_METADATA_KEYS,
    ));
    out.push_str(&go_string_array("MCPMetadataKeys", MCP_METADATA_KEYS));
    out.push_str(&go_string_array(
        "MCPStandardHTTPHeaders",
        MCP_STANDARD_HTTP_HEADERS,
    ));
    out.push_str(&go_string_array(
        "MCPCacheResultFields",
        MCP_CACHE_RESULT_FIELDS,
    ));

    out.push_str(&format_go_struct_fields(GO_TYPE_DEFINITIONS));
    out
}

pub(super) const GO_TYPE_DEFINITIONS: &str = r#"// JSONValue is the Go counterpart of the TypeScript ACPValue / Python JsonValue
// type. Concrete fields generally use json.RawMessage so callers can defer
// decoding to their own dataclasses.
type JSONValue = json.RawMessage

// JSONObject mirrors `Record<string, JsonValue>`.
type JSONObject = map[string]json.RawMessage

// HarnSessionTimelineCursor advances independently over each projected topic.
type HarnSessionTimelineCursor struct {
	Topics map[string]uint64 `json:"topics"`
}

// HarnSessionTimelineQuery filters and paginates the canonical semantic timeline.
type HarnSessionTimelineQuery struct {
	SessionID  *string                   `json:"sessionId,omitempty"`
	RunID      *string                   `json:"runId,omitempty"`
	RunPath    *string                   `json:"runPath,omitempty"`
	ProjectID  *string                   `json:"projectId,omitempty"`
	FromCursor HarnSessionTimelineCursor `json:"fromCursor"`
	Limit      *uint64                   `json:"limit,omitempty"`
}

// HarnSessionTimelineReference binds a semantic node to stable source evidence.
type HarnSessionTimelineReference struct {
	Kind    string  `json:"kind"`
	ID      *string `json:"id,omitempty"`
	Topic   *string `json:"topic,omitempty"`
	EventID *uint64 `json:"eventId,omitempty"`
}

// HarnSessionTimelineLink carries causal or identity relationships.
type HarnSessionTimelineLink struct {
	Kind     string  `json:"kind"`
	TargetID *string `json:"targetId,omitempty"`
	TraceID  *string `json:"traceId,omitempty"`
	SpanID   *string `json:"spanId,omitempty"`
	EventID  *string `json:"eventId,omitempty"`
}

// HarnSessionTimelineNode is Harn's semantic chronology row; Kind remains open.
type HarnSessionTimelineNode struct {
	ID           string                         `json:"id"`
	ParentID     *string                        `json:"parentId,omitempty"`
	Children     []string                       `json:"children"`
	Category     string                         `json:"category"`
	Kind         string                         `json:"kind"`
	Name         string                         `json:"name"`
	Status       string                         `json:"status"`
	TraceID      *string                        `json:"traceId,omitempty"`
	SpanID       *string                        `json:"spanId,omitempty"`
	OccurredAtMs *int64                         `json:"occurredAtMs,omitempty"`
	StartMs      *uint64                        `json:"startMs,omitempty"`
	DurationMs   *uint64                        `json:"durationMs,omitempty"`
	Attributes   JSONValue                      `json:"attributes,omitempty"`
	References   []HarnSessionTimelineReference `json:"references"`
	Links        []HarnSessionTimelineLink      `json:"links"`
	Order        uint64                         `json:"order"`
}

// HarnSessionTimelineSnapshot is a point-in-time semantic timeline query result.
type HarnSessionTimelineSnapshot struct {
	SchemaVersion uint32                    `json:"schemaVersion"`
	Query         HarnSessionTimelineQuery  `json:"query"`
	Cursor        HarnSessionTimelineCursor `json:"cursor"`
	Nodes         []HarnSessionTimelineNode `json:"nodes"`
}

// HarnSessionTimelineUpdate revises one semantic node for subscribers.
type HarnSessionTimelineUpdate struct {
	SchemaVersion uint32                    `json:"schemaVersion"`
	Cursor        HarnSessionTimelineCursor `json:"cursor"`
	Node          HarnSessionTimelineNode   `json:"node"`
}

// HarnPlanAuthor identifies the author of a plan revision or comment.
type HarnPlanAuthor struct {
	ID          string  `json:"id"`
	DisplayName *string `json:"display_name,omitempty"`
}

// HarnPlanSource records where a plan revision originated.
type HarnPlanSource struct {
	Kind string  `json:"kind"`
	URI  *string `json:"uri,omitempty"`
}

// HarnPlanCommentState is the closed collaborative comment lifecycle.
type HarnPlanCommentState string

const (
	HarnPlanCommentOpen      HarnPlanCommentState = "open"
	HarnPlanCommentAddressed HarnPlanCommentState = "addressed"
	HarnPlanCommentResolved  HarnPlanCommentState = "resolved"
	HarnPlanCommentReopened  HarnPlanCommentState = "reopened"
)

// HarnPlanApprovalState is the closed executable-plan approval lifecycle.
type HarnPlanApprovalState string

const (
	HarnPlanApprovalUnrequested HarnPlanApprovalState = "unrequested"
	HarnPlanApprovalRequested   HarnPlanApprovalState = "requested"
	HarnPlanApprovalApproved    HarnPlanApprovalState = "approved"
	HarnPlanApprovalRejected    HarnPlanApprovalState = "rejected"
)

// HarnPlanStep is one normalized executable plan step.
type HarnPlanStep struct {
	ID       string          `json:"id"`
	Content  string          `json:"content"`
	Status   string          `json:"status"`
	Priority json.RawMessage `json:"priority"`
}

// HarnPlanApproval carries the typed approval state for an executable plan.
type HarnPlanApproval struct {
	State      HarnPlanApprovalState `json:"state"`
	RequestID  *string  `json:"request_id,omitempty"`
	Reviewer   *string  `json:"reviewer,omitempty"`
	Reviewers  []string `json:"reviewers,omitempty"`
	ApprovedAt *string  `json:"approved_at,omitempty"`
	Reason     *string  `json:"reason,omitempty"`
}

// HarnPlanArtifact is the normalized executable plan within a document revision.
type HarnPlanArtifact struct {
	Type                 string           `json:"_type"`
	SchemaVersion        string           `json:"schema_version"`
	ID                   string           `json:"id"`
	Tool                 string           `json:"tool"`
	Title                string           `json:"title"`
	Summary              string           `json:"summary"`
	Steps                []HarnPlanStep   `json:"steps"`
	Assumptions          []string         `json:"assumptions"`
	OpenQuestions        []string         `json:"open_questions"`
	VerificationCommands []string         `json:"verification_commands"`
	Approval             HarnPlanApproval `json:"approval"`
}

// HarnPlanRevisionOperation is the typed mutation that produced a revision.
type HarnPlanRevisionOperation struct {
	Kind      string                `json:"kind"`
	EventID   string                `json:"event_id"`
	CommentID *string               `json:"comment_id,omitempty"`
	State     *HarnPlanCommentState `json:"state,omitempty"`
}

// HarnPlanRevision is one immutable collaborative plan revision.
type HarnPlanRevision struct {
	RevisionID       string          `json:"revision_id"`
	ParentRevisionID *string         `json:"parent_revision_id,omitempty"`
	Markdown         string          `json:"markdown"`
	Plan             HarnPlanArtifact `json:"plan"`
	Author           HarnPlanAuthor  `json:"author"`
	Source           HarnPlanSource  `json:"source"`
	CreatedAt        string          `json:"created_at"`
	Operation        HarnPlanRevisionOperation `json:"operation"`
}

// HarnPlanTextRange is a UTF-8 byte range fallback for a comment anchor.
type HarnPlanTextRange struct {
	Start int `json:"start"`
	End   int `json:"end"`
}

// HarnPlanCommentAnchor survives edits through step identity and text fallbacks.
type HarnPlanCommentAnchor struct {
	StepID     *string        `json:"step_id,omitempty"`
	QuotedText *string        `json:"quoted_text,omitempty"`
	Range      *HarnPlanTextRange `json:"range,omitempty"`
}

// HarnPlanComment is an anchored collaborative review comment.
type HarnPlanComment struct {
	CommentID string                `json:"comment_id"`
	Anchor    HarnPlanCommentAnchor `json:"anchor"`
	Body      string                `json:"body"`
	State     HarnPlanCommentState  `json:"state"`
	Author    HarnPlanAuthor        `json:"author"`
	CreatedAt string                `json:"created_at"`
	UpdatedAt string                `json:"updated_at"`
}

// HarnPlanCommentResolutionReceipt binds a comment transition to revisions and an agent event.
type HarnPlanCommentResolutionReceipt struct {
	ReceiptID        string  `json:"receipt_id"`
	CommentID        string  `json:"comment_id"`
	InputRevisionID  string  `json:"input_revision_id"`
	OutputRevisionID string  `json:"output_revision_id"`
	AgentRunID       string  `json:"agent_run_id"`
	EventID          string  `json:"event_id"`
	Explanation      *string `json:"explanation,omitempty"`
	CreatedAt        string  `json:"created_at"`
}

// HarnPlanDocument is Harn's canonical collaborative plan-document contract.
type HarnPlanDocument struct {
	Type               string                             `json:"_type"`
	SchemaVersion      string                             `json:"schema_version"`
	DocumentID         string                             `json:"document_id"`
	CurrentRevision    HarnPlanRevision                   `json:"current_revision"`
	Comments           []HarnPlanComment                  `json:"comments"`
	ResolutionReceipts []HarnPlanCommentResolutionReceipt `json:"resolution_receipts"`
	CreatedAt          string                             `json:"created_at"`
	UpdatedAt          string                             `json:"updated_at"`
}

// JSONRPCID encodes a JSON-RPC id, which may be an integer, a string, or null.
// Use NewJSONRPCIDInt / NewJSONRPCIDString to construct, or NullJSONRPCID for
// the null variant.
type JSONRPCID struct {
	raw     json.RawMessage
	present bool
}

// NewJSONRPCIDInt builds a JSON-RPC id from an integer.
func NewJSONRPCIDInt(value int64) JSONRPCID {
	bytes, _ := json.Marshal(value)
	return JSONRPCID{raw: bytes, present: true}
}

// NewJSONRPCIDString builds a JSON-RPC id from a string.
func NewJSONRPCIDString(value string) JSONRPCID {
	bytes, _ := json.Marshal(value)
	return JSONRPCID{raw: bytes, present: true}
}

// NullJSONRPCID returns a JSON-RPC id explicitly encoded as null.
func NullJSONRPCID() JSONRPCID {
	return JSONRPCID{raw: json.RawMessage("null"), present: true}
}

// IsPresent reports whether the id field was present on the wire.
func (id JSONRPCID) IsPresent() bool { return id.present }

// MarshalJSON implements json.Marshaler.
func (id JSONRPCID) MarshalJSON() ([]byte, error) {
	if !id.present {
		return []byte("null"), nil
	}
	return id.raw, nil
}

// UnmarshalJSON implements json.Unmarshaler.
func (id *JSONRPCID) UnmarshalJSON(data []byte) error {
	id.raw = append(id.raw[:0], data...)
	id.present = true
	return nil
}

// Raw exposes the encoded bytes for callers that need to inspect the variant.
func (id JSONRPCID) Raw() json.RawMessage { return id.raw }

// ACPRequest is a JSON-RPC request envelope.
type ACPRequest struct {
	JSONRPC string          `json:"jsonrpc"`
	ID      JSONRPCID       `json:"id"`
	Method  string          `json:"method"`
	Params  json.RawMessage `json:"params,omitempty"`
}

// ACPError is the JSON-RPC error sub-envelope.
type ACPError struct {
	Code    int             `json:"code"`
	Message string          `json:"message"`
	Data    json.RawMessage `json:"data,omitempty"`
}

// HarnACPPromptErrorData is the typed data payload for failed session/prompt calls.
type HarnACPPromptErrorData struct {
	Schema        string             `json:"schema"`
	TerminalClass AgentTerminalClass `json:"terminalClass"`
	Category *string `json:"category,omitempty"`
	Kind *string `json:"kind,omitempty"`
	Reason *string `json:"reason,omitempty"`
	Code *string `json:"code,omitempty"`
	Retryable *bool `json:"retryable,omitempty"`
	RetryAfterMs *int64 `json:"retryAfterMs,omitempty"`
	Provider *string `json:"provider,omitempty"`
	Model *string `json:"model,omitempty"`
}

// HarnAgentTerminalOutcome is the producer-owned reason an agent loop ended.
type HarnAgentTerminalOutcome struct {
	Kind AgentTerminalKind `json:"kind"`
	Reason string `json:"reason"`
	Owner AgentTerminalOwner `json:"owner"`
}

// HarnACPPromptResultHarnMetadata contains Harn prompt-result extensions.
type HarnACPPromptResultHarnMetadata struct {
	Terminal *HarnAgentTerminalOutcome `json:"terminal,omitempty"`
}

// HarnACPPromptResultMetadata is the standard ACP extension envelope.
type HarnACPPromptResultMetadata struct {
	Harn HarnACPPromptResultHarnMetadata `json:"harn"`
}

// HarnACPPromptResult preserves terminal truth alongside canonical stopReason.
type HarnACPPromptResult struct {
	StopReason string `json:"stopReason"`
	Meta *HarnACPPromptResultMetadata `json:"_meta,omitempty"`
}

// ACPResponse is a JSON-RPC response envelope.
type ACPResponse struct {
	JSONRPC string          `json:"jsonrpc"`
	ID      JSONRPCID       `json:"id"`
	Result  json.RawMessage `json:"result,omitempty"`
	Error   *ACPError       `json:"error,omitempty"`
}

// ACPNotification is a JSON-RPC notification envelope.
type ACPNotification struct {
	JSONRPC string          `json:"jsonrpc"`
	Method  string          `json:"method"`
	Params  json.RawMessage `json:"params,omitempty"`
}

// HarnHostInjectionProvenance records who supplied a typed host event.
type HarnHostInjectionProvenance struct {
	Initiator string  `json:"initiator"`
	Source    string  `json:"source"`
	Host      *string `json:"host,omitempty"`
	TsMs      int64   `json:"ts_ms"`
}

// HarnHostInjectionEvent is the canonical host-to-agent typed injection contract.
type HarnHostInjectionEvent struct {
	Kind       string                      `json:"kind"`
	Delivery   string                      `json:"delivery,omitempty"`
	Payload    JSONObject                  `json:"payload"`
	Provenance HarnHostInjectionProvenance `json:"provenance"`
}

// ACPSessionInjectHostEventParams is the session/inject_host_event request payload.
type ACPSessionInjectHostEventParams struct {
	SessionID string                 `json:"sessionId"`
	Event     HarnHostInjectionEvent `json:"event"`
}

// HarnExtensionMeta is the canonical envelope for `_meta.harn` payloads.
type HarnExtensionMeta struct {
	Harn JSONObject `json:"harn,omitempty"`
}

// ACPContentBlock is one element inside a session update or message content array.
type ACPContentBlock struct {
	Type string             `json:"type"`
	Text *string            `json:"text,omitempty"`
	Meta *HarnExtensionMeta `json:"_meta,omitempty"`
}

// HarnToolLifecycleMeta is the Harn-specific tool-call lifecycle metadata
// living under `_meta.harn` on tool_call / tool_call_update notifications.
type HarnToolLifecycleMeta struct {
	Audit               json.RawMessage `json:"audit,omitempty"`
	ChangedPaths        []string        `json:"changedPaths,omitempty"`
	Data                json.RawMessage `json:"data,omitempty"`
	DurationMs          *float64        `json:"durationMs,omitempty"`
	Error               *string         `json:"error,omitempty"`
	ErrorCategory       *string         `json:"errorCategory,omitempty"`
	ExecutionDurationMs *float64        `json:"executionDurationMs,omitempty"`
	Executor            json.RawMessage `json:"executor,omitempty"`
	MutationStatus      *HarnToolMutationStatus `json:"mutationStatus,omitempty"`
	Parsing             *bool           `json:"parsing,omitempty"`
	RawInputPartial     *string         `json:"rawInputPartial,omitempty"`
}

// ToolCallReceipt is the typed, privacy-preserving receipt emitted for an
// audited tool call.
type ToolCallReceipt struct {
	SchemaVersion int                      `json:"schema_version"`
	SessionID     string                   `json:"session_id"`
	RunID         *string                  `json:"run_id"`
	ToolCallID    string                   `json:"tool_call_id"`
	ToolName      string                   `json:"tool_name"`
	Iteration     uint64                   `json:"iteration"`
	TurnIndex     *uint64                  `json:"turn_index"`
	EmitOrder     uint64                   `json:"emit_order"`
	Reason        *string                  `json:"reason"`
	Kind          *string                  `json:"kind"`
	Executor      *ToolCallReceiptExecutor `json:"executor"`
	Status        ToolCallReceiptStatus    `json:"status"`
	ErrorCategory *string                  `json:"error_category"`
	DurationMs    uint64                   `json:"duration_ms"`
	ArgsHash      string                   `json:"args_hash"`
	ResultHash    *string                  `json:"result_hash"`
	Audit         json.RawMessage          `json:"audit"`
	EmittedAt     string                   `json:"emitted_at"`
	Model         *string                  `json:"model"`
	Provider      *string                  `json:"provider"`
}

// ACPToolCall is the `tool_call` session update.
type ACPToolCall struct {
	SessionUpdate string             `json:"sessionUpdate"`
	ToolCallID    string             `json:"toolCallId"`
	Title         string             `json:"title"`
	Kind          *string            `json:"kind,omitempty"`
	Status        *string            `json:"status,omitempty"`
	Content       []ACPContentBlock  `json:"content,omitempty"`
	Locations     []json.RawMessage  `json:"locations,omitempty"`
	RawInput      json.RawMessage    `json:"rawInput,omitempty"`
	RawOutput     json.RawMessage    `json:"rawOutput,omitempty"`
	Meta          *HarnExtensionMeta `json:"_meta,omitempty"`
}

// ACPToolCallUpdate is the `tool_call_update` session update.
type ACPToolCallUpdate struct {
	SessionUpdate string             `json:"sessionUpdate"`
	ToolCallID    string             `json:"toolCallId"`
	Title         *string            `json:"title,omitempty"`
	Kind          *string            `json:"kind,omitempty"`
	Status        *string            `json:"status,omitempty"`
	Content       []ACPContentBlock  `json:"content,omitempty"`
	Locations     []json.RawMessage  `json:"locations,omitempty"`
	RawInput      json.RawMessage    `json:"rawInput,omitempty"`
	RawOutput     json.RawMessage    `json:"rawOutput,omitempty"`
	Meta          *HarnExtensionMeta `json:"_meta,omitempty"`
}

// ACPSessionUpdateEnvelope is the discriminated `update` payload carried inside
// an ACP `session/update` notification. Only fields relevant to a given
// `sessionUpdate` discriminator will be populated; the rest stay zero-value
// and are stripped via `omitempty` on serialization.
type ACPSessionUpdateEnvelope struct {
	SessionUpdate    string             `json:"sessionUpdate"`
	Content          json.RawMessage    `json:"content,omitempty"`
	MessageID        *string            `json:"messageId,omitempty"`
	Entries          []json.RawMessage  `json:"entries,omitempty"`
	KeptTurnCount    *int               `json:"keptTurnCount,omitempty"`
	RemovedTurnCount *int               `json:"removedTurnCount,omitempty"`
	NewTipTurnID     *string            `json:"newTipTurnId,omitempty"`
	Reason           *string            `json:"reason,omitempty"`
	ToolCallID       *string            `json:"toolCallId,omitempty"`
	Title            *string            `json:"title,omitempty"`
	Kind             *string            `json:"kind,omitempty"`
	Status           *string            `json:"status,omitempty"`
	RawInput         json.RawMessage    `json:"rawInput,omitempty"`
	RawOutput        json.RawMessage    `json:"rawOutput,omitempty"`
	Meta             *HarnExtensionMeta `json:"_meta,omitempty"`
}

// ACPSessionUpdateParams is the params payload of `session/update`.
type ACPSessionUpdateParams struct {
	SessionID string                   `json:"sessionId"`
	Update    ACPSessionUpdateEnvelope `json:"update"`
}

// ACPSessionUpdateNotification is the full `session/update` envelope.
type ACPSessionUpdateNotification struct {
	JSONRPC string                 `json:"jsonrpc"`
	Method  string                 `json:"method"`
	Params  ACPSessionUpdateParams `json:"params"`
}

// HarnAgentEventNotification is the `_harn/agentEvent` envelope.
type HarnAgentEventNotification struct {
	JSONRPC string     `json:"jsonrpc"`
	Method  string     `json:"method"`
	Params  JSONObject `json:"params"`
}

// HarnToolArgSchema describes the static slice of a Harn tool's argument shape.
type HarnToolArgSchema struct {
	PathParams            []string            `json:"path_params"`
	DependencyKeyParams   []string            `json:"dependency_key_params"`
	DependencyRangeParams []map[string]string `json:"dependency_range_params"`
	ArgAliases            map[string]string   `json:"arg_aliases"`
	Required              []string            `json:"required"`
}

// HarnToolAnnotations describes Harn-side metadata for a tool.
type HarnToolAnnotations struct {
	Kind            string              `json:"kind"`
	SideEffectLevel string              `json:"side_effect_level"`
	ArgSchema       HarnToolArgSchema   `json:"arg_schema"`
	Capabilities    map[string][]string `json:"capabilities"`
	EmitsArtifacts  bool                `json:"emits_artifacts"`
	ResultReaders   []string            `json:"result_readers"`
	InlineResult    bool                `json:"inline_result"`
}

// A2AMessage is one message inside an A2A task history.
type A2AMessage struct {
	ID    string            `json:"id"`
	Role  string            `json:"role"`
	Parts []json.RawMessage `json:"parts"`
}

// A2ATaskStatus is the status block on an A2A task.
type A2ATaskStatus struct {
	State     string      `json:"state"`
	Message   *A2AMessage `json:"message,omitempty"`
	Timestamp *string     `json:"timestamp,omitempty"`
}

// A2ATask is the canonical A2A task envelope.
type A2ATask struct {
	ID        string            `json:"id"`
	ContextID *string           `json:"contextId,omitempty"`
	Status    A2ATaskStatus     `json:"status"`
	History   []A2AMessage      `json:"history,omitempty"`
	Artifacts []json.RawMessage `json:"artifacts,omitempty"`
	Metadata  JSONObject        `json:"metadata,omitempty"`
}

// MCPJSONSchema202012 is the JSON Schema dialect surface used by the MCP RC
// tool input/output schema profile.
type MCPJSONSchema202012 = JSONObject

// MCPImplementation describes an MCP client or server implementation.
type MCPImplementation struct {
	Name        string  `json:"name"`
	Version     string  `json:"version"`
	Title       *string `json:"title,omitempty"`
	Description *string `json:"description,omitempty"`
	WebsiteURL  *string `json:"websiteUrl,omitempty"`
}

// MCPRequestMeta is the per-request metadata required by the MCP RC profile.
type MCPRequestMeta struct {
	ProtocolVersion    string            `json:"io.modelcontextprotocol/protocolVersion"`
	ClientInfo         MCPImplementation `json:"io.modelcontextprotocol/clientInfo"`
	ClientCapabilities JSONObject        `json:"io.modelcontextprotocol/clientCapabilities"`
	LogLevel           *MCPLoggingLevel  `json:"io.modelcontextprotocol/logLevel,omitempty"`
	ProgressToken      json.RawMessage   `json:"progressToken,omitempty"`
	Traceparent        *string           `json:"traceparent,omitempty"`
	Tracestate         *string           `json:"tracestate,omitempty"`
	Baggage            *string           `json:"baggage,omitempty"`
}

// MCPHTTPHeaders names the HTTP headers used by the MCP RC Streamable HTTP profile.
type MCPHTTPHeaders struct {
	ProtocolVersion string  `json:"MCP-Protocol-Version"`
	Method          string  `json:"Mcp-Method"`
	Name            *string `json:"Mcp-Name,omitempty"`
}

// MCPCacheHints captures the RC ttlMs/cacheScope cache fields.
type MCPCacheHints struct {
	TTLMS      uint64        `json:"ttlMs"`
	CacheScope MCPCacheScope `json:"cacheScope"`
}

// MCPDiscoverResult is the result returned by server/discover.
type MCPDiscoverResult struct {
	ResultType        MCPResultType     `json:"resultType"`
	SupportedVersions []string          `json:"supportedVersions"`
	Capabilities      JSONObject        `json:"capabilities"`
	ServerInfo        MCPImplementation `json:"serverInfo"`
	Instructions      *string           `json:"instructions,omitempty"`
	Meta              JSONObject        `json:"_meta,omitempty"`
}

// MCPInputRequiredResult carries server-to-client requests for multi round-trip calls.
type MCPInputRequiredResult struct {
	ResultType    MCPResultType `json:"resultType"`
	InputRequests JSONObject    `json:"inputRequests,omitempty"`
	RequestState  *string       `json:"requestState,omitempty"`
	Meta          JSONObject    `json:"_meta,omitempty"`
}

// MCPUnsupportedProtocolVersionErrorData is the typed data payload for -32004.
type MCPUnsupportedProtocolVersionErrorData struct {
	Requested string   `json:"requested"`
	Supported []string `json:"supported"`
}

// MCPUnsupportedProtocolVersionError is the JSON-RPC error response shape for
// an unsupported MCP protocol version.
type MCPUnsupportedProtocolVersionError struct {
	JSONRPC string    `json:"jsonrpc"`
	ID      JSONRPCID `json:"id,omitempty"`
	Error   ACPError  `json:"error"`
}

// MCPTool is the MCP `tools/list` entry.
type MCPTool struct {
	Name         string              `json:"name"`
	Title        *string             `json:"title,omitempty"`
	Description  *string             `json:"description,omitempty"`
	InputSchema  MCPJSONSchema202012 `json:"inputSchema"`
	OutputSchema MCPJSONSchema202012 `json:"outputSchema,omitempty"`
	Annotations  JSONObject          `json:"annotations,omitempty"`
}

// MCPResource is the MCP `resources/list` entry.
type MCPResource struct {
	URI         string  `json:"uri"`
	Name        string  `json:"name"`
	Title       *string `json:"title,omitempty"`
	Description *string `json:"description,omitempty"`
	MimeType    *string `json:"mimeType,omitempty"`
}

// MCPResourceTemplate is the MCP `resources/templates/list` entry.
type MCPResourceTemplate struct {
	URITemplate string  `json:"uriTemplate"`
	Name        string  `json:"name"`
	Title       *string `json:"title,omitempty"`
	Description *string `json:"description,omitempty"`
	MimeType    *string `json:"mimeType,omitempty"`
}

// MCPPrompt is the MCP `prompts/list` entry.
type MCPPrompt struct {
	Name        string       `json:"name"`
	Title       *string      `json:"title,omitempty"`
	Description *string      `json:"description,omitempty"`
	Arguments   []JSONObject `json:"arguments,omitempty"`
}

// IsRequest reports whether a decoded JSON-RPC envelope is a request.
func IsRequest(envelope map[string]json.RawMessage) bool {
	_, hasID := envelope["id"]
	_, hasMethod := envelope["method"]
	return hasID && hasMethod
}

// IsResponse reports whether a decoded JSON-RPC envelope is a response.
func IsResponse(envelope map[string]json.RawMessage) bool {
	_, hasID := envelope["id"]
	_, hasMethod := envelope["method"]
	return hasID && !hasMethod
}

// IsNotification reports whether a decoded JSON-RPC envelope is a notification.
func IsNotification(envelope map[string]json.RawMessage) bool {
	_, hasID := envelope["id"]
	_, hasMethod := envelope["method"]
	return !hasID && hasMethod
}
"#;

fn format_go_source(source: String) -> Result<String, String> {
    let mut child = match Command::new("gofmt")
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .spawn()
    {
        Ok(child) => child,
        Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(source),
        Err(error) => return Err(format!("failed to spawn gofmt: {error}")),
    };

    child
        .stdin
        .as_mut()
        .ok_or_else(|| "failed to open gofmt stdin".to_string())?
        .write_all(source.as_bytes())
        .map_err(|error| format!("failed to write generated Go to gofmt: {error}"))?;

    let output = child
        .wait_with_output()
        .map_err(|error| format!("failed to wait for gofmt: {error}"))?;
    if !output.status.success() {
        return Err(format!(
            "gofmt failed on generated Go protocol artifact: {}",
            String::from_utf8_lossy(&output.stderr)
        ));
    }

    String::from_utf8(output.stdout).map_err(|error| {
        format!("gofmt returned non-UTF-8 output for generated Go protocol artifact: {error}")
    })
}

pub(super) fn generate_go_mod() -> String {
    "module github.com/burin-labs/harn/spec/protocol-artifacts/go/harnprotocol\n\n\
     go 1.22\n"
        .to_string()
}

pub(super) fn go_typed_array(type_name: &str, slice_name: &str, values: &[&str]) -> String {
    go_typed_array_owned(type_name, slice_name, &strs_to_strings(values))
}

pub(super) fn go_typed_array_owned(type_name: &str, slice_name: &str, values: &[String]) -> String {
    let mut out =
        format!("// {type_name} is the typed alias for the {slice_name} wire vocabulary.\n");
    out.push_str(&format!("type {type_name} = string\n\n"));
    out.push_str(&format!(
        "// {slice_name} enumerates every wire value Harn currently emits for {type_name}.\n"
    ));
    out.push_str(&format!("var {slice_name} = []{type_name}{{\n"));
    for value in values {
        out.push('\t');
        out.push_str(&json_string_literal(value));
        out.push_str(",\n");
    }
    out.push_str("}\n\n");
    out
}

pub(super) fn go_string_array(name: &str, values: &[&str]) -> String {
    let mut out = format!("// {name} enumerates the wire values Harn currently emits.\n");
    out.push_str(&format!("var {name} = []string{{\n"));
    for value in values {
        out.push('\t');
        out.push_str(&json_string_literal(value));
        out.push_str(",\n");
    }
    out.push_str("}\n\n");
    out
}

pub(super) fn format_go_struct_fields(input: &str) -> String {
    // This is intentionally a tiny formatter for this generator's simple
    // named-field struct literals. It is not a general Go parser.
    let mut out = String::new();
    let mut lines = input.lines();

    while let Some(line) = lines.next() {
        out.push_str(line);
        out.push('\n');

        if !(line.starts_with("type ") && line.ends_with(" struct {")) {
            continue;
        }

        let mut struct_lines = Vec::new();
        let mut closed_struct = false;
        for struct_line in lines.by_ref() {
            if struct_line == "}" {
                out.push_str(&format_go_struct_field_block(&struct_lines));
                out.push_str("}\n");
                closed_struct = true;
                break;
            }
            struct_lines.push(struct_line.to_string());
        }
        if !closed_struct {
            for struct_line in struct_lines {
                out.push_str(&struct_line);
                out.push('\n');
            }
        }
    }

    out
}

fn format_go_struct_field_block(lines: &[String]) -> String {
    let mut parsed = Vec::new();
    let mut max_name_len = 0usize;
    let mut max_type_len = 0usize;

    for line in lines {
        let parsed_line = parse_go_struct_field(line);
        if let Some(field) = &parsed_line {
            max_name_len = max_name_len.max(field.name.len());
            max_type_len = max_type_len.max(field.ty.len());
        }
        parsed.push(parsed_line);
    }

    let mut out = String::new();
    for (line, parsed_line) in lines.iter().zip(parsed) {
        match parsed_line {
            Some(field) => {
                out.push('\t');
                out.push_str(&field.name);
                out.push_str(&" ".repeat(max_name_len - field.name.len() + 1));
                out.push_str(&field.ty);
                if let Some(tag) = field.tag {
                    out.push_str(&" ".repeat(max_type_len - field.ty.len() + 1));
                    out.push_str(&tag);
                }
                out.push('\n');
            }
            None => {
                out.push_str(line);
                out.push('\n');
            }
        }
    }
    out
}

#[derive(Debug, PartialEq, Eq)]
struct GoStructField {
    name: String,
    ty: String,
    tag: Option<String>,
}

fn parse_go_struct_field(line: &str) -> Option<GoStructField> {
    let trimmed = line.strip_prefix('\t')?;
    if trimmed.is_empty() || trimmed.starts_with("//") {
        return None;
    }

    let (before_tag, tag) = match trimmed.split_once(" `") {
        Some((before_tag, tag)) => (before_tag, Some(format!("`{tag}"))),
        None => (trimmed, None),
    };
    let mut parts = before_tag.split_whitespace();
    let name = parts.next()?;
    let ty = parts.next()?;
    if parts.next().is_some() {
        return None;
    }

    Some(GoStructField {
        name: name.to_string(),
        ty: ty.to_string(),
        tag,
    })
}