apoc 0.3.0

Agentic process control for LLMs
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
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
//! Shared process, run, and action contracts.

use std::collections::BTreeMap;

use schemars::JsonSchema;
use serde::{Deserialize, Serialize};

/// Version of the public apoc data contract.
pub const SCHEMA_VERSION: u32 = 4;

/// One exact command within a composed execution.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct CommandUnit {
    /// Stable identifier unique within the parent execution.
    pub id: String,
    /// Executable followed by its exact arguments.
    pub argv: Vec<String>,
    /// Working directory, inheriting the parent workspace when omitted.
    #[serde(default)]
    pub cwd: Option<String>,
    /// Literal environment values layered over the parent environment.
    #[serde(default)]
    pub env: BTreeMap<String, String>,
    /// Secret environment values layered over the parent secrets.
    #[serde(default)]
    pub secrets: BTreeMap<String, SecretRef>,
    /// Whether apoc must invoke `/bin/zsh -lc` explicitly.
    #[serde(default)]
    pub shell: bool,
    /// Command-specific wall-clock deadline in milliseconds.
    #[serde(default)]
    pub timeout_ms: Option<u64>,
}

/// How commands in one composed execution exchange control and data.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum CommandTopology {
    /// Independent commands scheduled with bounded concurrency.
    Parallel {
        /// Maximum number of commands running at once.
        max_parallel: u32,
        /// Stop launching queued commands after the first failure.
        #[serde(default)]
        fail_fast: bool,
    },
    /// Ordered commands connected through native operating-system pipes.
    Pipeline {
        /// Fail when any stage exits unsuccessfully instead of only the final stage.
        #[serde(default = "pipefail_default")]
        pipefail: bool,
    },
}

fn pipefail_default() -> bool {
    true
}

/// Stable identity for one operating-system process.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
pub struct ProcessIdentity {
    /// Identifier for the current host boot.
    #[serde(default)]
    pub boot_id: String,
    /// Operating-system process identifier.
    pub pid: u32,
    /// Parent process identifier, when available.
    pub ppid: Option<u32>,
    /// Process group identifier on Unix.
    pub pgid: Option<u32>,
    /// Absolute Unix start timestamp in seconds.
    pub started_at: u64,
    /// Absolute Unix start timestamp in nanoseconds at the best host resolution.
    #[serde(default)]
    pub started_at_ns: u64,
    /// Executable name.
    pub name: String,
    /// Executable path, when available.
    pub executable: Option<String>,
}

/// Program executed by an apoc execution.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum ExecutionProgram {
    /// Exact executable and argument vector.
    Command {
        /// Executable followed by its arguments.
        argv: Vec<String>,
        /// Whether apoc must invoke `/bin/zsh -lc` explicitly.
        shell: bool,
    },
    /// Exact commands composed as a bounded batch or linear native pipeline.
    Commands {
        /// Commands in declaration order.
        commands: Vec<CommandUnit>,
        /// Scheduling and data-flow topology.
        topology: CommandTopology,
    },
    /// JavaScript evaluated by Code Mode.
    Javascript {
        /// JavaScript source.
        source: String,
        /// Structured input exposed to the program.
        #[serde(default)]
        input: serde_json::Value,
    },
}

/// Lifetime owner for an execution or resource lease.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum LeaseOwnerKind {
    /// A parent execution owns the lease.
    Execution,
    /// An agent session owns the lease.
    Session,
    /// The lease survives callers until explicit release or expiry.
    Persistent,
}

/// Finite retry behavior for an execution.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct RetryPolicy {
    /// Maximum total attempts, including the first attempt.
    pub max_attempts: u32,
    /// Initial delay before retrying.
    pub backoff_ms: u64,
    /// Maximum delay between attempts.
    pub max_backoff_ms: u64,
}

impl Default for RetryPolicy {
    fn default() -> Self {
        Self {
            max_attempts: 1,
            backoff_ms: 500,
            max_backoff_ms: 30_000,
        }
    }
}

/// Enforceable limits for one execution.
#[derive(Debug, Clone, Default, Serialize, Deserialize, JsonSchema)]
pub struct ExecutionBudget {
    /// Maximum wall-clock lifetime in milliseconds.
    pub wall_time_ms: Option<u64>,
    /// Maximum child process count.
    pub child_processes: Option<u32>,
    /// Maximum retained output and artifact bytes.
    pub artifact_bytes: Option<u64>,
    /// Maximum time without progress before apoc reports a stall.
    pub progress_timeout_ms: Option<u64>,
    /// Whether a reported stall must cancel the execution.
    #[serde(default)]
    pub cancel_on_stall: bool,
}

/// Repository and worktree context captured for an execution.
#[derive(Debug, Clone, Default, Serialize, Deserialize, JsonSchema)]
pub struct WorkspaceContext {
    /// Current working directory.
    pub cwd: Option<String>,
    /// Repository root, when detected.
    pub repository: Option<String>,
    /// Worktree root, when detected.
    pub worktree: Option<String>,
    /// Current commit, when detected.
    pub commit: Option<String>,
    /// Current branch, when detected.
    pub branch: Option<String>,
    /// Digest of the dirty worktree state without copied file contents.
    pub dirty_digest: Option<String>,
}

/// Public definition of one durable agent execution.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct ExecutionSpec {
    /// Public contract version.
    pub schema_version: u32,
    /// Stable caller key that prevents duplicate execution launches.
    #[serde(default)]
    pub idempotency_key: Option<String>,
    /// Human-readable name.
    pub name: String,
    /// Agent-supplied reason for the execution.
    pub purpose: Option<String>,
    /// Searchable labels.
    #[serde(default)]
    pub labels: BTreeMap<String, String>,
    /// Program to execute.
    pub program: ExecutionProgram,
    /// Working directory and repository context.
    #[serde(default)]
    pub workspace: WorkspaceContext,
    /// Explicit environment values. Literal values are recordable.
    #[serde(default)]
    pub env: BTreeMap<String, String>,
    /// Secret references resolved only while launching the program.
    #[serde(default)]
    pub secrets: BTreeMap<String, SecretRef>,
    /// Process I/O mode for command programs.
    pub io: IoMode,
    /// Lease owner kind.
    pub owner_kind: LeaseOwnerKind,
    /// Owning execution or session identifier, when applicable.
    pub owner_id: Option<String>,
    /// Optional absolute lease expiry in Unix milliseconds.
    pub expires_at: Option<u64>,
    /// Finite retry behavior.
    #[serde(default)]
    pub retry: RetryPolicy,
    /// Resource budgets.
    #[serde(default)]
    pub budget: ExecutionBudget,
}

/// Reference to a secret that apoc must not persist after resolution.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct SecretRef {
    /// Secret provider name.
    pub provider: String,
    /// Provider-specific reference identifier.
    pub reference: String,
    /// Optional provider version that does not contain the secret value.
    pub version: Option<String>,
}

/// Durable execution state.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum ExecutionStatus {
    /// Accepted but not yet running.
    Queued,
    /// Actively evaluating or supervising work.
    Running,
    /// No progress was observed before the configured deadline.
    Stalled,
    /// Replay or an external event may resume the execution.
    Interrupted,
    /// Completed successfully.
    Completed,
    /// Completed unsuccessfully.
    Failed,
    /// Canceled by its owner or budget.
    Canceled,
}

/// One resumable evaluation pass of an execution program.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct ExecutionPass {
    /// Stable pass identifier.
    pub id: String,
    /// One-based pass number.
    pub number: u32,
    /// Pass start timestamp in Unix milliseconds.
    pub started_at: u64,
    /// Pass completion timestamp, when terminal.
    pub completed_at: Option<u64>,
    /// Current pass status.
    pub status: ExecutionStatus,
    /// Error code, when unsuccessful.
    pub error_code: Option<String>,
    /// Human-readable failure detail.
    pub error: Option<String>,
}

/// One concrete process attempt owned by an execution.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct ExecutionAttempt {
    /// Stable attempt identifier.
    pub id: String,
    /// One-based attempt number.
    pub number: u32,
    /// Exact process identities created by this attempt.
    #[serde(default)]
    pub processes: Vec<ProcessIdentity>,
    /// Attempt start timestamp in Unix milliseconds.
    pub started_at: u64,
    /// Attempt completion timestamp, when terminal.
    pub completed_at: Option<u64>,
    /// Process exit code, when known.
    pub exit_code: Option<i32>,
    /// Stable outcome code, when unsuccessful.
    pub error_code: Option<String>,
    /// Standard-output artifact identifier, when retained.
    pub stdout_artifact: Option<String>,
    /// Standard-error artifact identifier, when retained.
    pub stderr_artifact: Option<String>,
}

/// Durable record of one agent execution.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct Execution {
    /// Stable execution identifier.
    pub id: String,
    /// Parent execution, when this execution was composed by another.
    pub parent_id: Option<String>,
    /// Owning agent session, when applicable.
    pub session_id: Option<String>,
    /// Definition used to create the execution.
    pub spec: ExecutionSpec,
    /// Current execution status.
    pub status: ExecutionStatus,
    /// Evaluation passes in chronological order.
    #[serde(default)]
    pub passes: Vec<ExecutionPass>,
    /// Process attempts in chronological order.
    #[serde(default)]
    pub attempts: Vec<ExecutionAttempt>,
    /// Creation timestamp in Unix milliseconds.
    pub created_at: u64,
    /// Last state update in Unix milliseconds.
    pub updated_at: u64,
    /// Last observed progress in Unix milliseconds.
    pub last_progress_at: u64,
    /// Structured final result or summary.
    pub result: Option<serde_json::Value>,
}

/// Compact program identity returned by execution history pages.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct ExecutionProgramSummary {
    /// Program kind: command, batch, pipeline, or javascript.
    pub kind: String,
    /// Bounded executable identity for command programs.
    pub executable: Option<String>,
    /// Number of arguments after the executable.
    pub argument_count: usize,
    /// Number of commands in a batch or pipeline.
    pub command_count: usize,
}

/// Compact durable execution identity returned by history pages.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct ExecutionSummary {
    /// Stable execution identifier.
    pub id: String,
    /// Parent execution identifier, when composed.
    pub parent_id: Option<String>,
    /// Owning session identifier, when applicable.
    pub session_id: Option<String>,
    /// Stable caller idempotency key, when supplied.
    pub idempotency_key: Option<String>,
    /// Bounded human-readable execution name.
    pub name: String,
    /// Whether the stored name was shortened for this summary.
    pub name_truncated: bool,
    /// Current durable execution status.
    pub status: ExecutionStatus,
    /// Compact program identity.
    pub program: ExecutionProgramSummary,
    /// Bounded canonical working directory.
    pub cwd: Option<String>,
    /// Whether the stored working directory was shortened for this summary.
    pub cwd_truncated: bool,
    /// Number of process attempts recorded.
    pub attempt_count: usize,
    /// Terminal process exit code, when available.
    pub exit_code: Option<i32>,
    /// Stable terminal error code, when available.
    pub error_code: Option<String>,
    /// Creation timestamp in Unix milliseconds.
    pub created_at: u64,
    /// Last state update in Unix milliseconds.
    pub updated_at: u64,
}

/// Bounded cursor page of durable execution summaries.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct ExecutionListPage {
    /// Execution summaries in reverse update order.
    pub executions: Vec<ExecutionSummary>,
    /// Opaque cursor for the next older page.
    pub next_cursor: Option<String>,
}

/// Durable agent identity and heartbeat scope.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct AgentSession {
    /// Stable session identifier.
    pub id: String,
    /// Agent or actor name.
    pub actor: String,
    /// Searchable labels.
    #[serde(default)]
    pub labels: BTreeMap<String, String>,
    /// Session creation timestamp in Unix milliseconds.
    pub created_at: u64,
    /// Most recent heartbeat in Unix milliseconds.
    pub heartbeat_at: u64,
    /// Absolute expiry in Unix milliseconds.
    pub expires_at: u64,
    /// Whether the session has closed or expired.
    pub closed: bool,
}

/// Durable ownership lease for processes or resources.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct Lease {
    /// Stable lease identifier.
    pub id: String,
    /// Owner category.
    pub owner_kind: LeaseOwnerKind,
    /// Execution, session, or persistent owner identifier.
    pub owner_id: String,
    /// Resource keys owned by the lease.
    #[serde(default)]
    pub resources: Vec<String>,
    /// Lease creation timestamp in Unix milliseconds.
    pub created_at: u64,
    /// Most recent renewal in Unix milliseconds.
    pub renewed_at: u64,
    /// Optional absolute expiry in Unix milliseconds.
    pub expires_at: Option<u64>,
    /// Whether the lease was released or expired.
    pub released: bool,
}

/// Resource categories coordinated by apoc.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum ReservationKind {
    /// TCP or UDP port key.
    Port,
    /// Canonical filesystem path.
    Path,
    /// Exact process identity.
    Process,
    /// Device name.
    Device,
    /// Caller-defined coordination key.
    Custom,
}

/// Atomic apoc-local resource claim.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct Reservation {
    /// Stable reservation identifier.
    pub id: String,
    /// Resource category.
    pub kind: ReservationKind,
    /// Canonical resource key.
    pub key: String,
    /// Owning lease identifier.
    pub lease_id: String,
    /// Creation timestamp in Unix milliseconds.
    pub created_at: u64,
    /// Optional absolute expiry in Unix milliseconds.
    pub expires_at: Option<u64>,
    /// Whether a non-apoc owner currently conflicts with the claim.
    pub external_conflict: bool,
    /// Whether the reservation was released or expired.
    pub released: bool,
}

/// Durable result state for an operation receipt.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum ReceiptState {
    /// Every requested effect was applied.
    Applied,
    /// At least one effect succeeded and one failed.
    Partial,
    /// No effect was applied.
    Failed,
    /// An effect may have occurred but its result could not be durably recorded.
    Unknown,
}

/// One exact target result within an operation receipt.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct OperationTarget {
    /// Canonical target key.
    pub key: String,
    /// Whether the effect was applied.
    pub applied: bool,
    /// Stable error code, when unsuccessful.
    pub error_code: Option<String>,
    /// Human-readable failure detail.
    pub error: Option<String>,
}

/// Idempotent durable receipt for one operation.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct OperationReceipt {
    /// Stable receipt identifier.
    pub id: String,
    /// Caller-supplied or generated idempotency key.
    pub idempotency_key: String,
    /// Canonical operation name.
    pub operation: String,
    /// Actor that requested the operation.
    pub actor: String,
    /// Owning execution, when applicable.
    pub execution_id: Option<String>,
    /// Receipt outcome.
    pub state: ReceiptState,
    /// Exact target outcomes.
    pub targets: Vec<OperationTarget>,
    /// Intent timestamp in Unix milliseconds.
    pub started_at: u64,
    /// Result timestamp, when recorded.
    pub completed_at: Option<u64>,
}

/// Compact causal record shared by processes, executions, and resources.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct CausalEvent {
    /// Monotonic SQLite sequence.
    pub sequence: u64,
    /// Stable event identifier.
    pub id: String,
    /// Event timestamp in Unix milliseconds.
    pub at: u64,
    /// Canonical event kind.
    pub kind: String,
    /// Primary subject key.
    pub subject: String,
    /// Actor responsible for the event.
    pub actor: String,
    /// Correlation scope shared by related events.
    pub correlation_id: String,
    /// Direct causal predecessor, when known.
    pub causation_id: Option<String>,
    /// Owning execution, when applicable.
    pub execution_id: Option<String>,
    /// Owning session, when applicable.
    pub session_id: Option<String>,
    /// Content-addressed snapshot or payload identifier.
    pub payload_id: Option<String>,
    /// Compact structured details kept with the event.
    #[serde(default)]
    pub details: serde_json::Value,
}

/// Metadata for one retained content-addressed payload.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct ArtifactMetadata {
    /// Content digest and artifact identifier.
    pub id: String,
    /// Artifact kind.
    pub kind: String,
    /// Owning execution, when applicable.
    pub execution_id: Option<String>,
    /// Stored byte count.
    pub bytes: u64,
    /// Creation timestamp in Unix milliseconds.
    pub created_at: u64,
    /// Last access timestamp in Unix milliseconds.
    pub accessed_at: u64,
    /// Whether retention pruning must preserve the payload.
    pub pinned: bool,
    /// Whether the payload bytes were pruned while metadata was preserved.
    pub pruned: bool,
}

/// Agent-oriented process observation.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct ProcessInfo {
    /// Stable process identity.
    pub identity: ProcessIdentity,
    /// Operating-system process state.
    pub status: String,
    /// Real user identifier, when available.
    #[serde(default)]
    pub user_id: Option<String>,
    /// Effective user identifier, when available.
    #[serde(default)]
    pub effective_user_id: Option<String>,
    /// Real group identifier, when available.
    #[serde(default)]
    pub group_id: Option<String>,
    /// Login or job-control session identifier, when available.
    #[serde(default)]
    pub session_id: Option<u32>,
    /// CPU use as a percentage of one logical CPU.
    pub cpu_percent: f32,
    /// Resident memory in bytes.
    pub memory_bytes: u64,
    /// Virtual memory in bytes.
    pub virtual_memory_bytes: u64,
    /// Observed runtime in seconds.
    pub runtime_seconds: u64,
    /// Full command line.
    pub command: Vec<String>,
    /// Current working directory, when available.
    pub cwd: Option<String>,
    /// Total bytes read from storage.
    pub disk_read_bytes: u64,
    /// Total bytes written to storage.
    pub disk_written_bytes: u64,
}

/// Timestamped bounded process-table sample.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct ProcessSample {
    /// Observation timestamp in Unix milliseconds.
    pub at: u64,
    /// Processes included in this sample.
    pub processes: Vec<ProcessInfo>,
}

/// Result of waiting for a process selection condition.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct ProcessWait {
    /// Original selector.
    pub selector: String,
    /// Requested condition.
    pub condition: String,
    /// Whether the condition was reached.
    pub satisfied: bool,
    /// Wall-clock wait in milliseconds.
    pub elapsed_ms: u64,
    /// Last exact process identities still matching.
    pub processes: Vec<ProcessIdentity>,
}

/// One socket owned by a process.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct PortInfo {
    /// Transport protocol.
    pub protocol: String,
    /// Local IP address.
    pub address: String,
    /// Local port.
    pub port: u16,
    /// TCP state, when applicable.
    pub state: Option<String>,
    /// Associated process identifiers.
    pub pids: Vec<u32>,
}

/// One open vnode-backed file descriptor owned by a process.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct ProcessFile {
    /// Exact owning process identity.
    pub process: ProcessIdentity,
    /// Numeric file descriptor.
    pub fd: i32,
    /// Native file descriptor type.
    pub kind: String,
    /// Resolved path.
    pub path: String,
    /// Native open flags.
    pub open_flags: u32,
    /// Current file offset.
    pub offset: i64,
}

/// Exact process-liveness probe result.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct ProcessProbe {
    /// Requested selector or exact process key.
    pub target: String,
    /// Whether at least one exact identity still exists.
    pub exists: bool,
    /// Matching exact identities.
    pub processes: Vec<ProcessIdentity>,
    /// Observation timestamp in Unix milliseconds.
    pub observed_at: u64,
}

/// One process predicate in a structured boolean query.
#[derive(Debug, Clone, Default, Serialize, Deserialize, JsonSchema)]
pub struct ProcessPredicate {
    /// Exact process identifier.
    pub pid: Option<u32>,
    /// Exact parent process identifier.
    pub ppid: Option<u32>,
    /// Exact process-group identifier.
    pub pgid: Option<u32>,
    /// Exact executable name.
    pub name: Option<String>,
    /// Regular expression matched against the executable name.
    pub name_regex: Option<String>,
    /// Regular expression matched against the complete argument vector.
    pub argv_regex: Option<String>,
    /// Required working-directory prefix.
    pub cwd_prefix: Option<String>,
    /// Exact native process state.
    pub status: Option<String>,
    /// Exact real user identifier.
    pub user_id: Option<String>,
    /// Required local TCP or UDP port.
    pub port: Option<u16>,
    /// Port protocol. Defaults to tcp when `port` is present.
    pub protocol: Option<String>,
    /// Actor found in the durable process ledger.
    pub actor: Option<String>,
    /// Execution found in the durable process ledger.
    pub execution_id: Option<String>,
}

/// Structured boolean process query.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct ProcessQuery {
    /// Predicates that must all match.
    #[serde(default)]
    pub all: Vec<ProcessPredicate>,
    /// Predicates where at least one must match. Empty means no disjunction.
    #[serde(default)]
    pub any: Vec<ProcessPredicate>,
    /// Predicates that must not match.
    #[serde(default)]
    pub not: Vec<ProcessPredicate>,
    /// Sort field: cpu, memory, runtime, pid, or name.
    pub sort: String,
    /// Maximum result count.
    pub limit: usize,
}

/// Evidence-backed causal answer about one process target.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct ProcessInsight {
    /// Query kind: why, impact, owner, related, or changed.
    pub kind: String,
    /// Original target.
    pub target: String,
    /// Exact process observations supporting the answer.
    pub processes: Vec<ProcessInfo>,
    /// Known related executions.
    pub executions: Vec<Execution>,
    /// Known related ownership leases.
    pub leases: Vec<Lease>,
    /// Known related resource reservations.
    pub reservations: Vec<Reservation>,
    /// Relevant compact causal events.
    pub events: Vec<CausalEvent>,
    /// Explicit limits on what apoc can establish from recorded evidence.
    pub limitations: Vec<String>,
}

/// A resolved immutable process selection.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct ProcessSelection {
    /// Identifier derived from the resolved process identities.
    pub id: String,
    /// Original selector.
    pub selector: String,
    /// Resolution timestamp in Unix milliseconds.
    pub resolved_at: u64,
    /// Exact process identities selected.
    pub processes: Vec<ProcessIdentity>,
}

/// The apoc controller responsible for one process interaction.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct ProcessController {
    /// Unique identifier for this apoc command invocation.
    pub invocation_id: String,
    /// Whether Incurs identified the caller as an agent.
    pub agent: bool,
    /// Caller label from `APOC_ACTOR`, or `agent`/`human`.
    pub actor: String,
    /// apoc process identifier.
    pub controller_pid: u32,
    /// Parent of the apoc process, when available.
    pub parent_pid: Option<u32>,
    /// Working directory from which apoc was invoked.
    pub cwd: Option<String>,
    /// Exact apoc argument vector.
    pub argv: Vec<String>,
    /// Code Mode execution identifier when supplied by the host.
    pub execution_id: Option<String>,
}

impl ProcessController {
    /// Captures the current apoc controller without reading target-process environment.
    pub fn capture(agent: bool, execution_id: Option<String>) -> Self {
        Self {
            invocation_id: uuid::Uuid::now_v7().to_string(),
            agent,
            actor: std::env::var("APOC_ACTOR").unwrap_or_else(|_| {
                if agent {
                    "agent".to_string()
                } else {
                    "human".to_string()
                }
            }),
            controller_pid: std::process::id(),
            parent_pid: {
                let pid = unsafe { libc::getppid() };
                (pid > 0).then_some(pid as u32)
            },
            cwd: std::env::current_dir()
                .ok()
                .map(|path| path.to_string_lossy().into_owned()),
            argv: std::env::args().collect(),
            execution_id,
        }
    }
}

/// Durable latest-known context for one stable process identity.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct ProcessContext {
    /// Stable `BOOT_ID:PID@STARTED_AT_NS` context key.
    pub key: String,
    /// First time apoc observed this identity.
    pub first_observed_at: u64,
    /// Most recent time apoc observed this identity.
    pub last_observed_at: u64,
    /// Number of recorded interactions with this identity.
    pub observations: u64,
    /// Content-addressed latest native process snapshot.
    #[serde(default)]
    pub snapshot_id: Option<String>,
    /// How apoc first gained authority over the process.
    pub origin: String,
    /// Owning execution identifier, when apoc launched the process.
    #[serde(default, alias = "run_id")]
    pub execution_id: Option<String>,
    /// Most recent full native process snapshot.
    pub latest: ProcessInfo,
}

/// One durable interaction with a stable process identity.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct ProcessEvent {
    /// Unique event identifier.
    pub id: String,
    /// Stable `BOOT_ID:PID@STARTED_AT_NS` context key.
    pub process_key: String,
    /// Event timestamp in Unix milliseconds.
    pub at: u64,
    /// Canonical operation such as `process.get` or `execution.stop`.
    pub operation: String,
    /// Lifecycle phase: observed, intent, or result.
    pub phase: String,
    /// Selector that resolved the process, when applicable.
    pub selector: Option<String>,
    /// Controller that caused this interaction.
    pub controller: ProcessController,
    /// Managed execution identifier, when applicable.
    #[serde(default, alias = "run_id")]
    pub execution_id: Option<String>,
    /// Operation-specific structured context.
    pub details: serde_json::Value,
}

/// Indexed filters for the cross-process interaction ledger.
#[derive(Debug, Clone, Default, Serialize, Deserialize, JsonSchema)]
pub struct ProcessEventQuery {
    /// Maximum newest matching events.
    pub limit: usize,
    /// Exact stable `BOOT_ID:PID@STARTED_AT_NS` key.
    pub process_key: Option<String>,
    /// Any recorded lifetime of this PID.
    pub pid: Option<u32>,
    /// Exact canonical operation.
    pub operation: Option<String>,
    /// Exact lifecycle phase.
    pub phase: Option<String>,
    /// Exact controller actor label.
    pub actor: Option<String>,
    /// Exact controller Code Mode execution identifier.
    pub controller_execution_id: Option<String>,
    /// Exact managed execution identifier.
    pub execution_id: Option<String>,
    /// Inclusive lower event timestamp in Unix milliseconds.
    pub since_ms: Option<u64>,
    /// Inclusive upper event timestamp in Unix milliseconds.
    pub until_ms: Option<u64>,
}

/// Latest process context joined with its bounded event history.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct ProcessDossier {
    /// Durable latest-known process context.
    pub context: ProcessContext,
    /// Most recent events, newest first.
    pub events: Vec<ProcessEvent>,
}

/// Result of applying one operation to one process.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct ActionResult {
    /// Target identity captured before execution.
    pub process: ProcessIdentity,
    /// Requested action.
    pub action: String,
    /// Whether the operation reached the OS successfully.
    pub applied: bool,
    /// Whether the target exited before the receipt was returned.
    pub exited: bool,
    /// Human-readable failure detail.
    pub error: Option<String>,
}

/// Receipt for a process mutation.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct ActionReceipt {
    /// Stable receipt identifier.
    pub id: String,
    /// Requested selector.
    pub selector: String,
    /// Operation name.
    pub action: String,
    /// Start timestamp in Unix milliseconds.
    pub started_at: u64,
    /// Completion timestamp in Unix milliseconds.
    pub completed_at: u64,
    /// Per-process outcomes.
    pub results: Vec<ActionResult>,
}

/// Managed process I/O mode.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum IoMode {
    /// Capture stdout and stderr independently.
    Pipes,
    /// Run under a pseudo-terminal.
    Pty,
}

/// Managed run lifetime.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum RunLifetime {
    /// Stop the process when its owning Code Mode execution ends.
    Execution,
    /// Keep the process alive independently of its creator.
    Persistent,
}

/// Automatic restart behavior.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "kebab-case")]
pub enum RestartPolicy {
    /// Never restart automatically.
    Never,
    /// Restart only after an unsuccessful exit.
    OnFailure,
    /// Restart after every exit until explicitly stopped.
    Always,
}

/// Definition of one managed command.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct RunSpec {
    /// Stable human-readable name.
    pub name: String,
    /// Agent-supplied reason this process exists.
    #[serde(default)]
    pub purpose: Option<String>,
    /// Searchable agent-supplied labels.
    #[serde(default)]
    pub labels: std::collections::BTreeMap<String, String>,
    /// Controller that originally requested this run.
    #[serde(default)]
    pub requested_by: Option<ProcessController>,
    /// Executable followed by arguments.
    pub argv: Vec<String>,
    /// Working directory.
    pub cwd: Option<String>,
    /// Additional environment variables.
    pub env: std::collections::BTreeMap<String, String>,
    /// Whether to interpret `argv` as a zsh command string.
    pub shell: bool,
    /// Process I/O mode.
    pub io: IoMode,
    /// Run lifetime.
    pub lifetime: RunLifetime,
    /// Restart policy.
    pub restart: RestartPolicy,
    /// Optional execution deadline.
    pub timeout_ms: Option<u64>,
    /// Number of replicas.
    pub replicas: u32,
    /// Maximum total starts, including the first attempt.
    #[serde(default = "one_attempt")]
    pub max_attempts: u32,
    /// Initial retry delay in milliseconds.
    #[serde(default = "default_retry_backoff")]
    pub retry_backoff_ms: u64,
    /// Maximum retry delay in milliseconds.
    #[serde(default = "default_retry_max_backoff")]
    pub retry_max_backoff_ms: u64,
}

fn one_attempt() -> u32 {
    1
}

fn default_retry_backoff() -> u64 {
    500
}

fn default_retry_max_backoff() -> u64 {
    30_000
}

/// Durable managed-run state.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct ManagedRun {
    /// Stable run identifier.
    pub id: String,
    /// Run definition.
    pub spec: RunSpec,
    /// Current lifecycle state.
    pub status: String,
    /// Current process identities.
    pub processes: Vec<ProcessIdentity>,
    /// Every process lifetime ever owned by this run, including restarts.
    #[serde(default)]
    pub process_history: Vec<ProcessIdentity>,
    /// Creation timestamp in Unix milliseconds.
    pub created_at: u64,
    /// Last update timestamp in Unix milliseconds.
    pub updated_at: u64,
    /// Last exit code, when known.
    pub exit_code: Option<i32>,
    /// Standard output log path.
    pub stdout_path: Option<String>,
    /// Standard error log path.
    pub stderr_path: Option<String>,
}

/// Durable named service backed by a managed run.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct Service {
    /// Unique service name.
    pub name: String,
    /// Command and restart definition.
    pub spec: RunSpec,
    /// Whether daemon startup should restore the service.
    pub enabled: bool,
    /// Current or most recent managed run identifier.
    pub run_id: Option<String>,
    /// Creation timestamp in Unix milliseconds.
    pub created_at: u64,
    /// Last update timestamp in Unix milliseconds.
    pub updated_at: u64,
}

/// Service definition joined with its current managed-run state.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct ServiceInfo {
    /// Durable service definition.
    pub service: Service,
    /// Current or most recent managed run.
    pub run: Option<ManagedRun>,
}

/// Durable reusable JavaScript orchestration.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct Recipe {
    /// Unique recipe name.
    pub name: String,
    /// Agent-facing purpose and usage guidance.
    pub description: String,
    /// JavaScript Code Mode program.
    pub code: String,
    /// Optional JSON Schema for the `input` value.
    #[serde(default)]
    pub input_schema: Option<serde_json::Value>,
    /// Creation timestamp in Unix milliseconds.
    pub created_at: u64,
    /// Last update timestamp in Unix milliseconds.
    pub updated_at: u64,
}

/// Registered provider transport.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum ProviderKind {
    /// Command graph compiled into apoc.
    Builtin,
    /// Streamable HTTP MCP server.
    McpHttp,
    /// MCP server launched and supervised over standard I/O.
    McpStdio,
    /// OpenAPI document plus authenticated HTTP base URL.
    OpenApi,
}

/// Durable capability-provider configuration.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct ProviderConfig {
    /// JavaScript namespace exposed in Code Mode.
    pub name: String,
    /// Provider transport.
    pub kind: ProviderKind,
    /// MCP endpoint or OpenAPI specification URL.
    #[serde(default)]
    pub url: Option<String>,
    /// OpenAPI request base URL. Unused by MCP.
    #[serde(default)]
    pub base_url: Option<String>,
    /// Executable used by an MCP stdio provider.
    #[serde(default)]
    pub command: Option<String>,
    /// Exact arguments passed to an MCP stdio provider.
    #[serde(default)]
    pub args: Vec<String>,
    /// Working directory for an MCP stdio provider.
    #[serde(default)]
    pub cwd: Option<String>,
    /// Literal environment values for an MCP stdio provider.
    #[serde(default)]
    pub env: BTreeMap<String, String>,
    /// Environment values resolved from secret references when the provider starts.
    #[serde(default)]
    pub secret_env: BTreeMap<String, SecretRef>,
    /// Non-secret static HTTP headers.
    #[serde(default)]
    pub headers: std::collections::BTreeMap<String, String>,
    /// HTTP headers resolved from secret references at connection time.
    #[serde(default)]
    pub secret_headers: BTreeMap<String, SecretRef>,
    /// Model-facing usage guidance.
    #[serde(default)]
    pub instructions: Option<String>,
    /// Whether the provider is included in new capability snapshots.
    #[serde(default = "provider_enabled")]
    pub enabled: bool,
    /// Content digest of the provider configuration and discovered capabilities.
    #[serde(default)]
    pub generation: String,
    /// Creation timestamp in Unix milliseconds.
    pub created_at: u64,
    /// Last update timestamp in Unix milliseconds.
    pub updated_at: u64,
}

fn provider_enabled() -> bool {
    true
}

/// Returns whether a provider name is a valid JavaScript namespace binding.
pub fn valid_provider_name(value: &str) -> bool {
    let mut characters = value.chars();
    let Some(first) = characters.next() else {
        return false;
    };
    (first.is_ascii_alphabetic() || matches!(first, '_' | '$'))
        && characters
            .all(|character| character.is_ascii_alphanumeric() || matches!(character, '_' | '$'))
}

/// Backward-compatible name for a provider transport.
pub type ConnectorKind = ProviderKind;

/// Backward-compatible name for a provider configuration.
pub type ConnectorConfig = ProviderConfig;

/// Behavioral annotations used when coordinating one provider capability.
#[derive(Debug, Clone, Default, Serialize, Deserialize, JsonSchema)]
pub struct CapabilityAnnotations {
    /// Whether the capability is observational only.
    pub read_only: Option<bool>,
    /// Whether the capability may perform destructive updates.
    pub destructive: Option<bool>,
    /// Whether repeating the same downstream key adds no effect.
    pub idempotent: Option<bool>,
    /// Whether the capability may affect an external system or person.
    pub open_world: Option<bool>,
}

/// Strength of the identity available for a capability target.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum IdentityMode {
    /// A versioned exact identity is resolved before mutation.
    Exact,
    /// A provider-defined stable resource key is available.
    Stable,
    /// No target identity stronger than the provider is available.
    Opaque,
}

/// Resource-locking behavior for one capability.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum CoordinationMode {
    /// Independent resolved resource keys can execute concurrently.
    Resource,
    /// Mutations serialize across the provider.
    Provider,
    /// The capability is read-only and needs no mutation coordination.
    None,
}

/// Postcondition strength available for one capability.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum VerificationMode {
    /// The provider reads the affected state back after mutation.
    Readback,
    /// The provider returns a downstream receipt without state readback.
    Receipt,
    /// No postcondition verification is available.
    Unavailable,
}

/// One progressively discoverable provider capability.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct CapabilityDescriptor {
    /// Provider namespace.
    pub provider: String,
    /// Method name within the provider namespace.
    pub method: String,
    /// Human-readable capability description.
    pub description: Option<String>,
    /// JSON Schema accepted by the method.
    pub input_schema: serde_json::Value,
    /// JSON Schema returned by the method, when declared.
    pub output_schema: Option<serde_json::Value>,
    /// Truthful behavioral annotations.
    pub annotations: CapabilityAnnotations,
    /// Target identity strength.
    pub identity_mode: IdentityMode,
    /// Mutation coordination behavior.
    pub coordination_mode: CoordinationMode,
    /// Postcondition verification behavior.
    pub verification_mode: VerificationMode,
    /// Immutable provider capability generation.
    pub generation: String,
}

/// Provider-specific stable identity for one controlled resource.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct ResourceIdentity {
    /// Provider namespace.
    pub provider: String,
    /// Provider-defined resource category.
    pub kind: String,
    /// Canonical resource key.
    pub key: String,
    /// Optional version or concurrency token.
    pub version: Option<String>,
    /// Identity strength available to apoc.
    pub mode: IdentityMode,
}

/// Current Unix timestamp in milliseconds.
pub fn now_ms() -> u64 {
    std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .unwrap_or_default()
        .as_millis() as u64
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn publishes_the_v4_execution_contract() {
        assert_eq!(SCHEMA_VERSION, 4);
        let schema = serde_json::to_value(schemars::schema_for!(ExecutionSpec)).unwrap();
        let text = serde_json::to_string(&schema).unwrap();
        assert!(text.contains("schema_version"));
        assert!(text.contains("idempotency_key"));
        assert!(text.contains("javascript"));
        assert!(text.contains("max_attempts"));
        assert!(text.contains("progress_timeout_ms"));
        assert!(text.contains("commands"));
        assert!(text.contains("parallel"));
        assert!(text.contains("pipeline"));
        assert!(text.contains("max_parallel"));
        assert!(text.contains("pipefail"));
    }

    #[test]
    fn retry_policy_is_finite_by_default() {
        let retry = RetryPolicy::default();
        assert_eq!(retry.max_attempts, 1);
        assert!(retry.max_backoff_ms >= retry.backoff_ms);
    }

    #[test]
    fn publishes_the_v2_provider_contract() {
        assert_eq!(SCHEMA_VERSION, 4);
        let schema = serde_json::to_value(schemars::schema_for!(ProviderConfig)).unwrap();
        let text = serde_json::to_string(&schema).unwrap();
        assert!(text.contains("mcp_stdio"));
        assert!(text.contains("secret_headers"));
        assert!(text.contains("secret_env"));
        assert!(text.contains("command"));

        let capability = CapabilityDescriptor {
            provider: "fixture".to_string(),
            method: "apply".to_string(),
            description: Some("Apply one fixture mutation.".to_string()),
            input_schema: serde_json::json!({"type": "object"}),
            output_schema: None,
            annotations: CapabilityAnnotations {
                destructive: Some(true),
                ..CapabilityAnnotations::default()
            },
            identity_mode: IdentityMode::Opaque,
            coordination_mode: CoordinationMode::Provider,
            verification_mode: VerificationMode::Unavailable,
            generation: "fixture-generation".to_string(),
        };
        assert_eq!(capability.coordination_mode, CoordinationMode::Provider);
    }

    #[test]
    fn provider_names_are_javascript_namespace_bindings() {
        assert!(valid_provider_name("macos"));
        assert!(valid_provider_name("github_v2"));
        assert!(valid_provider_name("$host"));
        assert!(!valid_provider_name("mac-os"));
        assert!(!valid_provider_name("2mac"));
        assert!(!valid_provider_name(""));
    }
}