tensorlake 0.5.157

A Rust SDK for interacting with Tensorlake Cloud APIs.
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
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
//! Workspace client: private durable refs (`refs/workspaces/<id>`) on artifact storage.
//!
//! A workspace is the unit of ongoing work: it is allocated lazily by the first write, advances a
//! crash-safe autosave WAL without creating commits, materializes explicit snapshots as commits,
//! and publishes only through promote (squash by default). All calls authenticate with a minted
//! git credential, like the repo/commit APIs.

use reqwest::Method;
use serde::{Deserialize, Serialize};

use crate::Traced;
use crate::error::SdkError;

use super::ingest::{expect_json, with_transient_retries};
use super::merge::{MergeConflict, MergeReport, MergeStats, Signature, expect_json_or_conflict};
use super::{ArtifactStorageClient, advance_pagination_cursor, decode_empty};

fn encoded_git_path(path: &str, allow_empty: bool) -> Result<String, SdkError> {
    if path.is_empty() {
        return if allow_empty {
            Ok(String::new())
        } else {
            Err(SdkError::ClientError("Git path must not be empty".into()))
        };
    }
    if path.starts_with('/')
        || path.split('/').any(|component| {
            component.is_empty()
                || component == "."
                || component == ".."
                || component.contains('\0')
        })
    {
        return Err(SdkError::ClientError(format!(
            "Git path is not canonical: {path:?}"
        )));
    }
    Ok(path
        .split('/')
        .map(super::encode_path_segment)
        .collect::<Vec<_>>()
        .join("/"))
}

/// One workspace joined across its identity record, ref, and lease rows.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct WorkspaceInfo {
    pub id: String,
    pub ref_name: String,
    /// Principal bound at creation; empty for open-mode workspaces.
    pub principal: String,
    /// Base commit (hex) the workspace was created from.
    pub base: String,
    /// The ref the base was resolved from, when created from one; display-only.
    pub base_ref: Option<String>,
    /// Current snapshot tip (hex); equals `base` until the first snapshot.
    pub head: String,
    pub created_at_secs: u64,
    pub lease_secs: u64,
    /// Epoch-ms lease expiry. `None` means pinned: never expires.
    pub lease_due_ms: Option<u64>,
    pub pinned: bool,
    /// Shared-rw mode: every snapshot is automatically reconciled into this branch (short
    /// name), in server-assigned order.
    #[serde(default)]
    pub shared_target: Option<String>,
    /// Number of explicit snapshot commits on this workspace line. Autosave checkpoints are not
    /// commits and are deliberately excluded.
    #[serde(default)]
    pub snapshot_count: u64,
    /// Newest mount heartbeat, WAL append, snapshot, or promote time.
    #[serde(default)]
    pub last_activity_ms: Option<u64>,
    /// `none`, `dirty`, or `materialized`.
    #[serde(default = "default_workspace_wal_state")]
    pub wal_state: String,
    /// `attached` or `detached`; `unknown` when returned by an older server.
    #[serde(default = "default_workspace_attachment_state")]
    pub attachment_state: String,
    #[serde(default)]
    pub mounted_on: Option<String>,
    #[serde(default)]
    pub wal_generation: Option<u64>,
}

fn default_workspace_wal_state() -> String {
    "none".to_string()
}

fn default_workspace_attachment_state() -> String {
    "unknown".to_string()
}

#[derive(Clone, Debug, Deserialize)]
struct WorkspaceListPage {
    workspaces: Vec<WorkspaceInfo>,
    #[serde(default)]
    next_after: Option<String>,
}

#[derive(Clone, Debug, Default, Serialize)]
pub struct CreateWorkspaceRequest {
    /// Base commit-ish (branch, full ref, tag, or commit hex). Defaults to the repo's HEAD.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub base: Option<String>,
    /// Shared-rw mode: reconcile every snapshot into this branch (short name) in server order.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub shared_target: Option<String>,
    /// Shared-rw conflict handling: `"materialize"` (default — three-way merge, diff3 markers
    /// on conflicts) or `"lww"` (legacy last-writer-wins overwrite).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub reconcile_policy: Option<String>,
    /// Which product surface this session belongs to: `"filesystem"` makes the SERVER apply
    /// filesystem semantics from the repo's authoritative kind (publish-on-save defaults;
    /// kind=repository rejected with the right command). Requires a server with repo
    /// surface support (issue #103); older servers ignore the field.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub surface: Option<String>,
    /// The session will never write (a read-only mount's anchor): the surface kind check
    /// still applies, publish defaults are skipped.
    #[serde(skip_serializing_if = "std::ops::Not::not")]
    pub read_only: bool,
}

#[derive(Clone, Debug, Deserialize)]
pub struct WorkspaceHeartbeat {
    /// New lease expiry (epoch ms); absent when the workspace is pinned.
    pub lease_due_ms: Option<u64>,
    pub pinned: bool,
}

/// Writable-mount presence update. This is deliberately separate from the bodyless lease
/// heartbeat so callers must opt into changing fleet-visible attachment state.
#[derive(Clone, Debug, Default, Serialize)]
pub struct WorkspaceMountHeartbeatRequest {
    /// Stable random owner of this writable attachment. Attach, heartbeat, and unmount carry the
    /// same id so a stale process cannot replace or clear another sandbox's live claim.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub mount_id: Option<String>,
    /// Human-readable mount location shown by workspace listing/status.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub mounted_on: Option<String>,
    /// Clear the active attachment on a clean unmount while re-arming detached retention.
    #[serde(skip_serializing_if = "std::ops::Not::not")]
    pub unmount: bool,
}

#[derive(Clone, Debug, Default, Serialize)]
pub struct PromoteWorkspaceRequest {
    /// Target branch (short name; `refs/heads/` implied).
    pub branch: String,
    /// Expected target branch head; defaults to the observed head (CAS either way).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub expect_oid: Option<String>,
    /// Land the full checkpoint chain instead of the default squash.
    #[serde(skip_serializing_if = "std::ops::Not::not")]
    pub full_history: bool,
    /// `"squash"` (default) | `"full_history"` | `"merge"`. Takes precedence over the legacy
    /// `full_history` flag. `merge` lands a two-parent merge commit when the target moved
    /// since the workspace forked; conflicts come back as `PromoteOutcome::Conflicted`
    /// (`fail` policy — the workspace is the resolution surface).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub mode: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub message: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub author: Option<Signature>,
    /// Writable mount owner. Omitted callers remain compatible while the workspace is unclaimed;
    /// once a daemon claims it the server rejects no-id mutations.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub mount_id: Option<String>,
}

#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct PromoteWorkspaceResponse {
    pub commit: String,
    pub ref_name: String,
    pub created: bool,
    pub squashed: bool,
    /// Merge-mode promote landed a merge (or found nothing to do).
    #[serde(default)]
    pub merged: bool,
    /// Merge mode advanced the ref to the workspace tip with no new commit object.
    #[serde(default)]
    pub fast_forwarded: bool,
}

/// A merge-mode promote either lands or reports why it can't — conflicts are a normal outcome,
/// not a transport error (the server's `409` report body).
#[derive(Clone, Debug)]
pub enum PromoteOutcome {
    Promoted(PromoteWorkspaceResponse),
    /// `fail`-policy conflicts: nothing was published; the target branch and the workspace are
    /// both untouched. Sync the workspace, resolve, and promote again.
    Conflicted(MergeReport),
}

/// Ref-level promote preflight: did the target move since the workspace forked?
/// (Tree-level conflict prediction is `repo_merge` in preflight mode.)
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct PromotePreflight {
    pub target_ref: String,
    /// Absent when the target branch does not exist yet.
    pub target_head: Option<String>,
    pub workspace_base: String,
    pub workspace_head: String,
    pub moved: bool,
    pub fast_forward: bool,
}

#[derive(Clone, Debug, Default, Serialize)]
pub struct SyncWorkspaceRequest {
    /// Branch to pull from (short name). Defaults to the workspace's shared-rw target, else
    /// the ref it was created from.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub target: Option<String>,
    /// `"materialize"` (default — conflicts land as diff3 markers in the workspace, with the
    /// commit's structured conflict record) or `"fail"` (a conflicted sync changes nothing and
    /// returns the report).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub policy: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub message: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub author: Option<Signature>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub mount_id: Option<String>,
}

#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct SyncWorkspaceResponse {
    /// The workspace ref after the sync (unchanged when `up_to_date`, or when a
    /// `fail`-policy sync hit conflicts).
    pub workspace_head: String,
    pub target_head: String,
    /// The workspace's fork point after the sync.
    pub base: String,
    pub clean: bool,
    pub up_to_date: bool,
    /// The workspace had no snapshots: its ref moved to the target head with no new commit.
    pub fast_forwarded: bool,
    pub changed_paths: u64,
    pub conflicts: Vec<MergeConflict>,
    pub stats: MergeStats,
}

/// Result of a non-history-rewriting view refresh or pristine-workspace target switch.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct ViewSyncWorkspaceResponse {
    pub workspace_head: String,
    pub target_head: String,
    pub base: String,
    pub target_ref: Option<String>,
    pub changed: bool,
}

/// Server-resolved source for a lazy repository mount. The canonical ref is returned by the
/// server so clients never reinterpret a tag as a branch while following it.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct GitMountSource {
    pub format_ver: u16,
    /// `branch` | `tag` | `commit`.
    pub kind: String,
    /// `follow` for canonical branch/tag refs; `pinned` for full commits.
    pub follow_policy: String,
    #[serde(default)]
    pub canonical_ref: Option<String>,
    pub resolved_commit: String,
    #[serde(default)]
    pub subtree: Option<String>,
    pub root_tree: String,
}

/// Expiring liveness record for a read-only repository mount. Presence never roots repository
/// history; expiry is authoritative when a sandbox disappears without unmounting.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct GitMountPresence {
    pub format_ver: u16,
    pub session_id: String,
    pub principal: String,
    pub source: GitMountSource,
    pub mounted_on: String,
    pub started_at_ms: u64,
    pub last_heartbeat_ms: u64,
    pub expires_at_ms: u64,
}

#[derive(Clone, Debug, Serialize)]
pub struct RecordGitMountPresenceRequest<'a> {
    pub source: &'a GitMountSource,
    pub mounted_on: &'a str,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub ttl_seconds: Option<u64>,
}

#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct GitMountPresencePage {
    pub mounts: Vec<GitMountPresence>,
    pub truncated: bool,
    #[serde(default)]
    pub next_after: Option<String>,
}

/// The explicit history-rewriting workspace operation. `sync` is reserved for refreshing or
/// switching a view when no workspace snapshots would be rewritten.
pub type RebaseWorkspaceRequest = SyncWorkspaceRequest;

#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct RebaseWorkspaceResponse {
    #[serde(flatten)]
    pub result: SyncWorkspaceResponse,
    /// Retained server ref for the replaced chain. Absent for an up-to-date rebase.
    #[serde(default)]
    pub recovery_ref: Option<String>,
}

/// One durable commit in a workspace's active or retained chain.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct GitWorkspaceLogEntry {
    pub oid: String,
    pub subject: String,
    #[serde(default)]
    pub actor: Option<String>,
    #[serde(default)]
    pub operation: Option<String>,
    pub at_ms: u64,
    #[serde(default)]
    pub conflicted: bool,
}

#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct GitRetainedChain {
    pub recovery_ref: String,
    pub head: String,
    pub base: String,
    pub created_at_ms: u64,
    pub reason: String,
    pub retention: String,
}

#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct GitWorkspaceLogPage {
    pub format_ver: u16,
    pub workspace_id: String,
    #[serde(default)]
    pub active_chain: Vec<GitWorkspaceLogEntry>,
    #[serde(default)]
    pub retained_chains: Vec<GitRetainedChain>,
    pub truncated: bool,
    #[serde(default)]
    pub next_after: Option<String>,
}

/// One bounded node/edge page used by repository and project-fleet smartlog views.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct GitSmartlogNode {
    pub id: String,
    pub kind: String,
    #[serde(default)]
    pub label: Option<String>,
    #[serde(default)]
    pub oid: Option<String>,
    #[serde(default)]
    pub repo: Option<String>,
    #[serde(default)]
    pub workspace_id: Option<String>,
    #[serde(default)]
    pub actor: Option<String>,
    #[serde(default)]
    pub state: Option<String>,
    #[serde(default)]
    pub timestamp_ms: Option<u64>,
}

#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct GitSmartlogEdge {
    pub from: String,
    pub to: String,
    pub kind: String,
}

#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct GitSmartlogPage {
    pub format_ver: u16,
    #[serde(default)]
    pub repo: Option<String>,
    #[serde(default)]
    pub nodes: Vec<GitSmartlogNode>,
    #[serde(default)]
    pub edges: Vec<GitSmartlogEdge>,
    pub truncated: bool,
    #[serde(default)]
    pub next_after: Option<String>,
}

/// One ref's head and movement generation — the poll target for branch/workspace following.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct RefStatus {
    pub ref_name: String,
    /// Raw ref target (hex); for annotated tags this is the tag-object oid. Absent when deleted.
    pub oid: Option<String>,
    /// Commit reached by peeling the ref target. New servers populate this for every live ref;
    /// older servers omit it, so branch/lightweight-tag clients may fall back to `oid`.
    #[serde(default)]
    pub resolved_commit: Option<String>,
    /// Movement counter: bumps on every write or delete of the ref. 0 = never written.
    pub generation: u64,
}

/// One directory page from the paged tree listing.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct TreePage {
    pub entries: Vec<TreeEntry>,
    pub truncated: bool,
    pub next_after: Option<String>,
}

#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct TreeEntry {
    pub name: String,
    pub oid: String,
    /// Raw git mode (`0o100644`, `0o100755`, `0o120000`, `0o40000` for directories).
    pub mode: u32,
    /// Blob size when cheaply known server-side.
    pub size: Option<u64>,
}

/// One row of the project-scope workspace fleet listing
/// (`GET /project/{project}/workspaces`, artifact_storage issue #56).
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct WorkspaceFleetItem {
    pub id: String,
    /// Full repo id (`{project}/{repo}`).
    pub repo: String,
    /// `git` for repository workspaces, `native` for filesystem workspaces. Defaults to `git`
    /// against servers predating native fleet rows.
    #[serde(default = "default_workspace_storage")]
    pub storage: String,
    /// Derived server-side at read time: `live` | `gap` | `idle` | `detached`.
    pub status: String,
    /// `default` | `shared-rw`.
    pub mode: String,
    /// Creating principal; absent for unbound (open-mode) workspaces.
    #[serde(default)]
    pub created_by: Option<WorkspaceActor>,
    /// Base commit (hex) the workspace was created from.
    pub base: String,
    #[serde(default)]
    pub base_ref: Option<String>,
    /// Current snapshot tip (hex); equals `base` until the first snapshot.
    pub head: String,
    pub created_at_secs: u64,
    /// Lease duration from the identity record; 0 for durable (modern) workspaces. Defaults
    /// to 0 against servers that predate the field.
    #[serde(default)]
    pub lease_secs: u64,
    /// Epoch-ms lease expiry. `None` means pinned: never expires. Servers that predate the
    /// field omit it, which decodes as pinned — correct for every durable workspace.
    #[serde(default)]
    pub lease_due_ms: Option<u64>,
    #[serde(default)]
    pub shared_target: Option<String>,
    #[serde(default)]
    pub snapshot_count: u64,
    #[serde(default)]
    pub last_snapshot_ms: Option<u64>,
    #[serde(default)]
    pub last_heartbeat_ms: Option<u64>,
    /// Host reported by the currently-open mount session, if any.
    #[serde(default)]
    pub mounted_on: Option<String>,
}

fn default_workspace_storage() -> String {
    "git".to_string()
}

/// A workspace's creating principal: the authenticated `sub` and its human/agent classification.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct WorkspaceActor {
    pub name: String,
    /// `human` | `agent` | `unknown`.
    pub kind: String,
}

/// Per-status totals for the fleet page's filter set (status filter excluded).
#[derive(Clone, Debug, Default, Deserialize)]
pub struct WorkspaceFleetCounts {
    pub total: u64,
    pub live: u64,
    pub detached: u64,
    pub gap: u64,
    pub idle: u64,
    /// Counts cover only the server's bounded scan prefix when the fleet exceeds its cap.
    pub truncated: bool,
}

/// One page of the project-scope workspace fleet.
#[derive(Clone, Debug, Deserialize)]
pub struct WorkspaceFleetPage {
    pub project: String,
    pub items: Vec<WorkspaceFleetItem>,
    pub counts: WorkspaceFleetCounts,
    /// More items exist past this page; resume with `after = next_after`.
    pub truncated: bool,
    #[serde(default)]
    pub next_after: Option<String>,
}

/// Filters for one fleet page. `repo` accepts the bare repo name (the server also matches the
/// full `{project}/{repo}` id); `q` is an id substring match.
#[derive(Clone, Copy, Debug, Default)]
pub struct WorkspaceFleetQuery<'a> {
    pub repo: Option<&'a str>,
    pub q: Option<&'a str>,
    /// Ask the server for the caller's own + unbound workspaces only (`principal=self`).
    /// Servers that predate the param ignore it — callers relying on the narrowing must also
    /// filter client-side.
    pub principal_self: bool,
    pub after: Option<&'a str>,
    /// Page size; the server clamps to its own cap (200).
    pub limit: Option<usize>,
}

impl ArtifactStorageClient {
    /// Resolve a branch, tag, full commit, and optional subtree into a canonical lazy-mount
    /// source. The server owns namespace resolution and directory validation.
    pub async fn resolve_git_mount_source(
        &self,
        project_id: &str,
        repo: &str,
        git_username: &str,
        git_token: &str,
        source: Option<&str>,
        subtree: Option<&str>,
    ) -> Result<Traced<GitMountSource>, SdkError> {
        // Scoped so the `Serializer` is dropped before the await below: it holds a non-`Send`
        // encoding callback, and leaving it alive across the request makes this future non-`Send`,
        // which stops callers from renewing mount presence from a spawned task.
        let params = {
            let mut params = url::form_urlencoded::Serializer::new(String::new());
            if let Some(source) = source {
                params.append_pair("source", source);
            }
            if let Some(subtree) = subtree {
                params.append_pair("subtree", subtree);
            }
            params.finish()
        };
        let suffix = if params.is_empty() {
            "mount-source".to_string()
        } else {
            format!("mount-source?{params}")
        };
        let (req, trace_id) = self.git_request(
            Method::GET,
            project_id,
            repo,
            Some(&suffix),
            git_username,
            git_token,
        )?;
        let source = expect_json(req.send().await?).await?;
        Ok(Traced::new(trace_id, source))
    }

    pub async fn record_git_mount_presence(
        &self,
        project_id: &str,
        repo: &str,
        git_username: &str,
        git_token: &str,
        session_id: &str,
        request: &RecordGitMountPresenceRequest<'_>,
    ) -> Result<Traced<GitMountPresence>, SdkError> {
        let (req, trace_id) = self.git_request(
            Method::POST,
            project_id,
            repo,
            Some(&format!("mount-presence/{session_id}")),
            git_username,
            git_token,
        )?;
        let presence = expect_json(req.json(request).send().await?).await?;
        Ok(Traced::new(trace_id, presence))
    }

    pub async fn delete_git_mount_presence(
        &self,
        project_id: &str,
        repo: &str,
        git_username: &str,
        git_token: &str,
        session_id: &str,
    ) -> Result<Traced<()>, SdkError> {
        let (req, trace_id) = self.git_request(
            Method::DELETE,
            project_id,
            repo,
            Some(&format!("mount-presence/{session_id}")),
            git_username,
            git_token,
        )?;
        decode_empty(req.send().await?, trace_id).await
    }

    pub async fn list_git_mount_presence(
        &self,
        project_id: &str,
        repo: &str,
        git_username: &str,
        git_token: &str,
        after: Option<&str>,
        limit: usize,
    ) -> Result<Traced<GitMountPresencePage>, SdkError> {
        let mut params = url::form_urlencoded::Serializer::new(String::new());
        params.append_pair("limit", &limit.to_string());
        if let Some(after) = after {
            params.append_pair("after", after);
        }
        let (req, trace_id) = self.git_request(
            Method::GET,
            project_id,
            repo,
            Some(&format!("mount-presence?{}", params.finish())),
            git_username,
            git_token,
        )?;
        let page = expect_json(req.send().await?).await?;
        Ok(Traced::new(trace_id, page))
    }

    pub async fn create_workspace(
        &self,
        project_id: &str,
        repo: &str,
        git_username: &str,
        git_token: &str,
        request: &CreateWorkspaceRequest,
    ) -> Result<Traced<WorkspaceInfo>, SdkError> {
        let (req, trace_id) = self.git_request(
            Method::POST,
            project_id,
            repo,
            Some("workspaces"),
            git_username,
            git_token,
        )?;
        let info = expect_json(req.json(request).send().await?).await?;
        Ok(Traced::new(trace_id, info))
    }

    pub async fn get_workspace(
        &self,
        project_id: &str,
        repo: &str,
        git_username: &str,
        git_token: &str,
        workspace_id: &str,
    ) -> Result<Traced<WorkspaceInfo>, SdkError> {
        let (req, trace_id) = self.git_request(
            Method::GET,
            project_id,
            repo,
            Some(&format!("workspaces/{workspace_id}")),
            git_username,
            git_token,
        )?;
        let info = expect_json(req.send().await?).await?;
        Ok(Traced::new(trace_id, info))
    }

    /// One page of the project-scope workspace fleet: every repo in one call, joined with
    /// liveness (status, `mounted_on`). Requires a project-wide credential — repo-scoped mints
    /// carry no `project:read` and are refused. Page with `next_after` until `truncated` is
    /// false.
    pub async fn workspace_fleet(
        &self,
        project_id: &str,
        git_username: &str,
        git_token: &str,
        query: &WorkspaceFleetQuery<'_>,
    ) -> Result<Traced<WorkspaceFleetPage>, SdkError> {
        let mut params = url::form_urlencoded::Serializer::new(String::new());
        if let Some(repo) = query.repo {
            params.append_pair("repo", repo);
        }
        if let Some(q) = query.q {
            params.append_pair("q", q);
        }
        if query.principal_self {
            params.append_pair("principal", "self");
        }
        if let Some(after) = query.after {
            params.append_pair("after", after);
        }
        if let Some(limit) = query.limit {
            params.append_pair("limit", &limit.to_string());
        }
        let params = params.finish();
        let suffix = if params.is_empty() {
            "workspaces".to_string()
        } else {
            format!("workspaces?{params}")
        };
        let (req, trace_id) =
            self.project_git_request(Method::GET, project_id, &suffix, git_username, git_token);
        let page = expect_json(req.send().await?).await?;
        Ok(Traced::new(trace_id, page))
    }

    /// The complete fleet for the given filters: pages internally (like every other list
    /// helper in this crate) until the server reports no more rows, starting from `query.after`
    /// if set. Returns the items and the trace id of the final page.
    pub async fn workspace_fleet_all(
        &self,
        project_id: &str,
        git_username: &str,
        git_token: &str,
        query: &WorkspaceFleetQuery<'_>,
    ) -> Result<Traced<Vec<WorkspaceFleetItem>>, SdkError> {
        let mut items = Vec::new();
        let mut after: Option<String> = query.after.map(str::to_string);
        let mut seen_after = std::collections::HashSet::new();
        if let Some(after) = &after {
            seen_after.insert(after.clone());
        }
        loop {
            let page = self
                .workspace_fleet(
                    project_id,
                    git_username,
                    git_token,
                    &WorkspaceFleetQuery {
                        after: after.as_deref(),
                        ..*query
                    },
                )
                .await?;
            let trace_id = page.trace_id.clone();
            let page = page.into_inner();
            items.extend(page.items);
            if !page.truncated {
                return Ok(Traced::new(trace_id, items));
            }
            let next = page.next_after.ok_or_else(|| {
                SdkError::ClientError(
                    "workspace fleet page was truncated without a pagination cursor".to_string(),
                )
            })?;
            after = Some(advance_pagination_cursor(
                &mut seen_after,
                next,
                "workspace fleet listing",
            )?);
        }
    }

    pub async fn list_workspaces(
        &self,
        project_id: &str,
        repo: &str,
        git_username: &str,
        git_token: &str,
    ) -> Result<Traced<Vec<WorkspaceInfo>>, SdkError> {
        let mut workspaces = Vec::new();
        let mut after = None::<String>;
        let mut seen_after = std::collections::HashSet::new();
        loop {
            let suffix = after.as_ref().map_or_else(
                || "workspaces?limit=1000".to_string(),
                |after| format!("workspaces?limit=1000&after={}", urlencoding::encode(after)),
            );
            let (req, trace_id) = self.git_request(
                Method::GET,
                project_id,
                repo,
                Some(&suffix),
                git_username,
                git_token,
            )?;
            let page: WorkspaceListPage = expect_json(req.send().await?).await?;
            workspaces.extend(page.workspaces);
            let Some(next) = page.next_after else {
                return Ok(Traced::new(trace_id, workspaces));
            };
            after = Some(advance_pagination_cursor(
                &mut seen_after,
                next,
                "workspace listing",
            )?);
        }
    }

    /// Re-arm the workspace's activity lease. Pinned workspaces heartbeat as a no-op.
    pub async fn workspace_heartbeat(
        &self,
        project_id: &str,
        repo: &str,
        git_username: &str,
        git_token: &str,
        workspace_id: &str,
    ) -> Result<Traced<WorkspaceHeartbeat>, SdkError> {
        let suffix = format!("workspaces/{workspace_id}/heartbeat");
        let (hb, trace_id) = with_transient_retries(|| async {
            let (req, trace_id) = self.git_request(
                Method::POST,
                project_id,
                repo,
                Some(&suffix),
                git_username,
                git_token,
            )?;
            Ok((expect_json(req.send().await?).await?, trace_id))
        })
        .await?;
        Ok(Traced::new(trace_id, hb))
    }

    /// Re-arm a writable workspace lease and atomically update its fleet-visible mount presence.
    pub async fn workspace_mount_heartbeat(
        &self,
        project_id: &str,
        repo: &str,
        git_username: &str,
        git_token: &str,
        workspace_id: &str,
        request: &WorkspaceMountHeartbeatRequest,
    ) -> Result<Traced<WorkspaceHeartbeat>, SdkError> {
        let suffix = format!("workspaces/{workspace_id}/heartbeat");
        let (hb, trace_id) = with_transient_retries(|| async {
            let (req, trace_id) = self.git_request(
                Method::POST,
                project_id,
                repo,
                Some(&suffix),
                git_username,
                git_token,
            )?;
            Ok((
                expect_json(req.json(request).send().await?).await?,
                trace_id,
            ))
        })
        .await?;
        Ok(Traced::new(trace_id, hb))
    }

    /// CAS-advance a real branch to the workspace's snapshot (squash by default). Merge mode
    /// (`mode: "merge"`) lands a two-parent merge commit when the target moved; its conflicts
    /// are returned as `PromoteOutcome::Conflicted`, not an error. A plain `409` (concurrent
    /// ref move) still surfaces as `SdkError::ServerError`.
    pub async fn workspace_promote(
        &self,
        project_id: &str,
        repo: &str,
        git_username: &str,
        git_token: &str,
        workspace_id: &str,
        request: &PromoteWorkspaceRequest,
    ) -> Result<Traced<PromoteOutcome>, SdkError> {
        let (req, trace_id) = self.git_request(
            Method::POST,
            project_id,
            repo,
            Some(&format!("workspaces/{workspace_id}/promote")),
            git_username,
            git_token,
        )?;
        let outcome = expect_json_or_conflict::<PromoteWorkspaceResponse, MergeReport>(
            req.json(request).send().await?,
        )
        .await?
        .map(PromoteOutcome::Promoted)
        .unwrap_or_else(PromoteOutcome::Conflicted);
        Ok(Traced::new(trace_id, outcome))
    }

    /// Ref-level promote preflight: whether `target` moved since the workspace forked, and
    /// whether a promote would fast-forward.
    pub async fn workspace_promote_preflight(
        &self,
        project_id: &str,
        repo: &str,
        git_username: &str,
        git_token: &str,
        workspace_id: &str,
        target: &str,
    ) -> Result<Traced<PromotePreflight>, SdkError> {
        let suffix = format!(
            "workspaces/{workspace_id}/promote/preflight?target={}",
            url::form_urlencoded::byte_serialize(target.as_bytes()).collect::<String>()
        );
        let (req, trace_id) = self.git_request(
            Method::GET,
            project_id,
            repo,
            Some(&suffix),
            git_username,
            git_token,
        )?;
        let preflight = expect_json(req.send().await?).await?;
        Ok(Traced::new(trace_id, preflight))
    }

    /// Refresh the current workspace source or switch a pristine workspace to `target`. The
    /// server rejects a base-changing sync once snapshots exist; use `workspace_rebase` when
    /// rewriting the active chain is intentional.
    pub async fn workspace_sync(
        &self,
        project_id: &str,
        repo: &str,
        git_username: &str,
        git_token: &str,
        workspace_id: &str,
        request: &SyncWorkspaceRequest,
    ) -> Result<Traced<ViewSyncWorkspaceResponse>, SdkError> {
        let (req, trace_id) = self.git_request(
            Method::POST,
            project_id,
            repo,
            Some(&format!("workspaces/{workspace_id}/sync")),
            git_username,
            git_token,
        )?;
        let resp = expect_json(req.json(request).send().await?).await?;
        Ok(Traced::new(trace_id, resp))
    }

    /// Rebase a snapshotted workspace onto `target`, retaining the replaced chain under the
    /// returned recovery ref. This is deliberately separate from pristine/view-only sync.
    pub async fn workspace_rebase(
        &self,
        project_id: &str,
        repo: &str,
        git_username: &str,
        git_token: &str,
        workspace_id: &str,
        request: &RebaseWorkspaceRequest,
    ) -> Result<Traced<RebaseWorkspaceResponse>, SdkError> {
        let (req, trace_id) = self.git_request(
            Method::POST,
            project_id,
            repo,
            Some(&format!("workspaces/{workspace_id}/rebase")),
            git_username,
            git_token,
        )?;
        let resp = expect_json_or_conflict::<RebaseWorkspaceResponse, RebaseWorkspaceResponse>(
            req.json(request).send().await?,
        )
        .await?
        .unwrap_or_else(|conflicted| conflicted);
        Ok(Traced::new(trace_id, resp))
    }

    pub async fn workspace_log(
        &self,
        project_id: &str,
        repo: &str,
        git_username: &str,
        git_token: &str,
        workspace_id: &str,
        after: Option<&str>,
        limit: usize,
    ) -> Result<Traced<GitWorkspaceLogPage>, SdkError> {
        let mut params = url::form_urlencoded::Serializer::new(String::new());
        params.append_pair("limit", &limit.to_string());
        if let Some(after) = after {
            params.append_pair("after", after);
        }
        let suffix = format!("workspaces/{workspace_id}/log?{}", params.finish());
        let (req, trace_id) = self.git_request(
            Method::GET,
            project_id,
            repo,
            Some(&suffix),
            git_username,
            git_token,
        )?;
        let page = expect_json(req.send().await?).await?;
        Ok(Traced::new(trace_id, page))
    }

    pub async fn repo_smartlog(
        &self,
        project_id: &str,
        repo: &str,
        git_username: &str,
        git_token: &str,
        after: Option<&str>,
        limit: usize,
    ) -> Result<Traced<GitSmartlogPage>, SdkError> {
        let mut params = url::form_urlencoded::Serializer::new(String::new());
        params.append_pair("limit", &limit.to_string());
        if let Some(after) = after {
            params.append_pair("after", after);
        }
        let (req, trace_id) = self.git_request(
            Method::GET,
            project_id,
            repo,
            Some(&format!("smartlog?{}", params.finish())),
            git_username,
            git_token,
        )?;
        let page = expect_json(req.send().await?).await?;
        Ok(Traced::new(trace_id, page))
    }

    pub async fn project_smartlog(
        &self,
        project_id: &str,
        git_username: &str,
        git_token: &str,
        repo: Option<&str>,
        workspace: Option<&str>,
        after: Option<&str>,
        limit: usize,
    ) -> Result<Traced<GitSmartlogPage>, SdkError> {
        let mut params = url::form_urlencoded::Serializer::new(String::new());
        params.append_pair("limit", &limit.to_string());
        if let Some(repo) = repo {
            params.append_pair("repo", repo);
        }
        if let Some(workspace) = workspace {
            params.append_pair("workspace", workspace);
        }
        if let Some(after) = after {
            params.append_pair("after", after);
        }
        let (req, trace_id) = self.project_git_request(
            Method::GET,
            project_id,
            &format!("smartlog?{}", params.finish()),
            git_username,
            git_token,
        );
        let page = expect_json(req.send().await?).await?;
        Ok(Traced::new(trace_id, page))
    }

    pub async fn delete_workspace(
        &self,
        project_id: &str,
        repo: &str,
        git_username: &str,
        git_token: &str,
        workspace_id: &str,
    ) -> Result<Traced<()>, SdkError> {
        let (req, trace_id) = self.git_request(
            Method::DELETE,
            project_id,
            repo,
            Some(&format!("workspaces/{workspace_id}")),
            git_username,
            git_token,
        )?;
        decode_empty(req.send().await?, trace_id).await
    }

    /// One ref's head + movement generation (`?ref=` accepts a short branch or full ref name).
    pub async fn ref_status(
        &self,
        project_id: &str,
        repo: &str,
        git_username: &str,
        git_token: &str,
        refspec: &str,
    ) -> Result<Traced<RefStatus>, SdkError> {
        let suffix = format!(
            "ref-status?ref={}",
            url::form_urlencoded::byte_serialize(refspec.as_bytes()).collect::<String>()
        );
        let (req, trace_id) = self.git_request(
            Method::GET,
            project_id,
            repo,
            Some(&suffix),
            git_username,
            git_token,
        )?;
        let status = expect_json(req.send().await?).await?;
        Ok(Traced::new(trace_id, status))
    }

    /// One page of a directory listing at `version` (commit hex, branch, or ref).
    pub async fn list_tree_page(
        &self,
        project_id: &str,
        repo: &str,
        git_username: &str,
        git_token: &str,
        version: &str,
        dir_path: &str,
        after: Option<&str>,
        limit: usize,
    ) -> Result<Traced<TreePage>, SdkError> {
        let enc = |s: &str| url::form_urlencoded::byte_serialize(s.as_bytes()).collect::<String>();
        let encoded_dir_path = encoded_git_path(dir_path, true)?;
        let mut suffix = if dir_path.is_empty() {
            format!("tree?version={}&limit={limit}", enc(version))
        } else {
            format!(
                "tree/{encoded_dir_path}?version={}&limit={limit}",
                enc(version)
            )
        };
        if let Some(after) = after {
            suffix.push_str(&format!("&after={}", enc(after)));
        }
        let (req, trace_id) = self.git_request(
            Method::GET,
            project_id,
            repo,
            Some(&suffix),
            git_username,
            git_token,
        )?;
        let page = expect_json(req.send().await?).await?;
        Ok(Traced::new(trace_id, page))
    }

    /// Raw file bytes at `version`.
    pub async fn get_file_bytes(
        &self,
        project_id: &str,
        repo: &str,
        git_username: &str,
        git_token: &str,
        version: &str,
        file_path: &str,
    ) -> Result<Traced<Vec<u8>>, SdkError> {
        let encoded_file_path = encoded_git_path(file_path, false)?;
        let suffix = format!(
            "files/{encoded_file_path}?version={}",
            url::form_urlencoded::byte_serialize(version.as_bytes()).collect::<String>()
        );
        let (req, trace_id) = self.git_request(
            Method::GET,
            project_id,
            repo,
            Some(&suffix),
            git_username,
            git_token,
        )?;
        let resp = req.send().await?;
        if !resp.status().is_success() {
            let status = resp.status();
            let body = resp.text().await.unwrap_or_default();
            return Err(SdkError::ServerError {
                status,
                message: body,
            });
        }
        let bytes = resp.bytes().await?.to_vec();
        Ok(Traced::new(trace_id, bytes))
    }
}

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

    #[test]
    fn git_paths_are_component_encoded_and_canonical() {
        assert_eq!(
            encoded_git_path("src/what ?#%.rs", false).unwrap(),
            "src/what%20%3F%23%25.rs"
        );
        assert_eq!(encoded_git_path("", true).unwrap(), "");
        assert!(encoded_git_path("../secret", false).is_err());
        assert!(encoded_git_path("a//b", false).is_err());
    }

    #[test]
    fn mount_heartbeat_distinguishes_attach_keepalive_and_clean_unmount() {
        let attached = serde_json::to_value(WorkspaceMountHeartbeatRequest {
            mount_id: Some("mount-1".to_string()),
            mounted_on: Some("sandbox:/code".to_string()),
            unmount: false,
        })
        .unwrap();
        assert_eq!(
            attached,
            serde_json::json!({"mount_id": "mount-1", "mounted_on": "sandbox:/code"})
        );

        let detached = serde_json::to_value(WorkspaceMountHeartbeatRequest {
            mount_id: Some("mount-1".to_string()),
            mounted_on: None,
            unmount: true,
        })
        .unwrap();
        assert_eq!(
            detached,
            serde_json::json!({"mount_id": "mount-1", "unmount": true})
        );
    }

    #[test]
    fn workspace_mutations_serialize_optional_mount_fence() {
        let promote = serde_json::to_value(PromoteWorkspaceRequest {
            branch: "main".to_string(),
            mount_id: Some("mount-1".to_string()),
            ..Default::default()
        })
        .unwrap();
        assert_eq!(promote["mount_id"], "mount-1");

        let sync = serde_json::to_value(SyncWorkspaceRequest {
            target: Some("main".to_string()),
            mount_id: Some("mount-1".to_string()),
            ..Default::default()
        })
        .unwrap();
        assert_eq!(sync["mount_id"], "mount-1");

        let legacy = serde_json::to_value(SyncWorkspaceRequest::default()).unwrap();
        assert!(legacy.get("mount_id").is_none());
    }

    /// Promote responses from servers that predate merge mode decode with the new fields
    /// defaulting to false.
    #[test]
    fn promote_response_tolerates_old_servers() {
        let body = r#"{"commit": "aa", "ref_name": "refs/heads/main", "created": false, "squashed": true}"#;
        let resp: PromoteWorkspaceResponse = serde_json::from_str(body).unwrap();
        assert!(resp.squashed);
        assert!(!resp.merged);
        assert!(!resp.fast_forwarded);
    }

    #[test]
    fn workspace_info_decodes_wal_and_activity_state_with_old_server_defaults() {
        let base = r#"{
            "id":"aa", "ref_name":"refs/workspaces/aa", "principal":"user:u1",
            "base":"1111111111111111111111111111111111111111",
            "base_ref":"refs/heads/main",
            "head":"1111111111111111111111111111111111111111",
            "created_at_secs":1, "lease_secs":0, "lease_due_ms":null, "pinned":true
        }"#;
        let old: WorkspaceInfo = serde_json::from_str(base).unwrap();
        assert_eq!(old.snapshot_count, 0);
        assert_eq!(old.wal_state, "none");
        assert_eq!(old.attachment_state, "unknown");
        assert_eq!(old.wal_generation, None);

        let current = base.replace(
            "\"pinned\":true",
            "\"pinned\":true,\"snapshot_count\":2,\"last_activity_ms\":99,\"wal_state\":\"dirty\",\"attachment_state\":\"attached\",\"mounted_on\":\"sandbox-1\",\"wal_generation\":7",
        );
        let current: WorkspaceInfo = serde_json::from_str(&current).unwrap();
        assert_eq!(current.snapshot_count, 2);
        assert_eq!(current.last_activity_ms, Some(99));
        assert_eq!(current.wal_state, "dirty");
        assert_eq!(current.attachment_state, "attached");
        assert_eq!(current.mounted_on.as_deref(), Some("sandbox-1"));
        assert_eq!(current.wal_generation, Some(7));
    }

    /// The fleet page decodes gsvc-server's exact wire shape (`fleet_item_json` /
    /// `WorkspaceFleetResponse` in `crates/gsvc-server/src/http.rs`) — every field the CLI
    /// listing consumes. The server side of this contract is pinned by the fleet e2e test in
    /// artifact_storage; change either together.
    #[test]
    fn fleet_page_decodes_server_shape() {
        let body = r#"{
            "project": "p1",
            "items": [{
                "id": "aabbccdd", "repo": "p1/demo", "storage": "native", "status": "live", "mode": "shared-rw",
                "created_by": {"name": "user:u1", "kind": "human"},
                "base": "1111111111111111111111111111111111111111",
                "base_ref": "refs/heads/main",
                "head": "2222222222222222222222222222222222222222",
                "created_at_secs": 1751000000,
                "lease_secs": 3600,
                "lease_due_ms": 1751003600000,
                "shared_target": "main",
                "snapshot_count": 3,
                "last_snapshot_ms": 1751000500000,
                "last_heartbeat_ms": 1751000600000,
                "mounted_on": "sandbox-42"
            }],
            "counts": {"total": 1, "live": 1, "detached": 0, "gap": 0, "idle": 0, "truncated": false},
            "truncated": true,
            "next_after": "aabbccdd"
        }"#;
        let page: WorkspaceFleetPage = serde_json::from_str(body).unwrap();
        assert_eq!(page.project, "p1");
        assert_eq!(page.counts.total, 1);
        assert!(page.truncated);
        assert_eq!(page.next_after.as_deref(), Some("aabbccdd"));
        let item = &page.items[0];
        assert_eq!(item.id, "aabbccdd");
        assert_eq!(item.repo, "p1/demo");
        assert_eq!(item.storage, "native");
        assert_eq!(item.status, "live");
        assert_eq!(item.mode, "shared-rw");
        assert_eq!(item.created_by.as_ref().unwrap().name, "user:u1");
        assert_eq!(item.created_by.as_ref().unwrap().kind, "human");
        assert_eq!(item.base_ref.as_deref(), Some("refs/heads/main"));
        assert_eq!(item.lease_secs, 3600);
        assert_eq!(item.lease_due_ms, Some(1751003600000));
        assert_eq!(item.snapshot_count, 3);
        assert_eq!(item.mounted_on.as_deref(), Some("sandbox-42"));
    }

    /// Optional fleet fields are `skip_serializing_if` on the server: an unbound, never-mounted,
    /// never-snapshotted workspace omits them entirely and must still decode. Lease fields also
    /// default (0 / pinned) against servers that predate them.
    #[test]
    fn fleet_item_tolerates_omitted_optionals() {
        let body = r#"{
            "project": "p1",
            "items": [{
                "id": "ee", "repo": "p1/demo", "status": "detached", "mode": "default",
                "base": "1111111111111111111111111111111111111111",
                "head": "1111111111111111111111111111111111111111",
                "created_at_secs": 1751000000,
                "snapshot_count": 0
            }],
            "counts": {"total": 1, "live": 0, "detached": 1, "gap": 0, "idle": 0, "truncated": false},
            "truncated": false
        }"#;
        let page: WorkspaceFleetPage = serde_json::from_str(body).unwrap();
        let item = &page.items[0];
        assert!(item.created_by.is_none(), "unbound workspace");
        assert_eq!(item.storage, "git", "old servers default to git rows");
        assert!(item.base_ref.is_none());
        assert_eq!(item.lease_secs, 0, "old servers omit lease_secs");
        assert!(item.lease_due_ms.is_none(), "omitted lease row = pinned");
        assert!(item.shared_target.is_none());
        assert!(item.last_snapshot_ms.is_none());
        assert!(item.last_heartbeat_ms.is_none());
        assert!(item.mounted_on.is_none());
        assert!(page.next_after.is_none());
    }

    /// The sync response decodes the full server shape, conflicts included.
    #[test]
    fn sync_response_decodes_server_shape() {
        let body = r#"{
            "workspace_head": "ws1", "target_head": "t1", "base": "t1",
            "clean": false, "up_to_date": false, "fast_forwarded": false,
            "changed_paths": 2,
            "conflicts": [{"path": "f", "kind": "content", "potential": false,
                           "ours": {"mode": 33188, "oid": "o"}, "base": {"mode": 33188, "oid": "b"},
                           "theirs": {"mode": 33188, "oid": "t"}}],
            "stats": {"trees_read": 4, "entries_compared": 9, "blobs_merged": 1, "wall_ms": 0.7}
        }"#;
        let resp: SyncWorkspaceResponse = serde_json::from_str(body).unwrap();
        assert!(!resp.clean);
        assert_eq!(resp.base, "t1");
        assert_eq!(resp.conflicts.len(), 1);
        assert_eq!(resp.conflicts[0].kind, "content");

        let view: ViewSyncWorkspaceResponse = serde_json::from_value(serde_json::json!({
            "workspace_head": "t2", "target_head": "t2", "base": "t2",
            "target_ref": "refs/tags/v2", "changed": true
        }))
        .unwrap();
        assert!(view.changed);
        assert_eq!(view.target_ref.as_deref(), Some("refs/tags/v2"));
    }

    #[test]
    fn mount_source_and_presence_decode_versioned_wire() {
        let source: GitMountSource = serde_json::from_value(serde_json::json!({
            "format_ver": 1,
            "kind": "tag", "follow_policy": "follow",
            "canonical_ref": "refs/tags/v1",
            "resolved_commit": "1111111111111111111111111111111111111111",
            "subtree": "services/api",
            "root_tree": "2222222222222222222222222222222222222222"
        }))
        .unwrap();
        assert_eq!(source.canonical_ref.as_deref(), Some("refs/tags/v1"));
        assert_eq!(source.subtree.as_deref(), Some("services/api"));

        let presence: GitMountPresence = serde_json::from_value(serde_json::json!({
            "format_ver": 1,
            "session_id": "mount-1",
            "principal": "user:1",
            "source": source,
            "mounted_on": "sandbox-1",
            "started_at_ms": 1,
            "last_heartbeat_ms": 2,
            "expires_at_ms": 3
        }))
        .unwrap();
        assert_eq!(presence.source.kind, "tag");
        assert_eq!(presence.expires_at_ms, 3);

        let annotated: RefStatus = serde_json::from_value(serde_json::json!({
            "ref_name": "refs/tags/v1",
            "oid": "3333333333333333333333333333333333333333",
            "resolved_commit": "1111111111111111111111111111111111111111",
            "generation": 4
        }))
        .unwrap();
        assert_eq!(
            annotated.resolved_commit.as_deref(),
            Some("1111111111111111111111111111111111111111")
        );
        let legacy: RefStatus = serde_json::from_value(serde_json::json!({
            "ref_name": "refs/heads/main", "oid": "1111", "generation": 1
        }))
        .unwrap();
        assert!(legacy.resolved_commit.is_none());
    }

    #[test]
    fn rebase_log_and_smartlog_decode_server_shapes() {
        let response: RebaseWorkspaceResponse = serde_json::from_value(serde_json::json!({
            "workspace_head": "ws1", "target_head": "t1", "base": "t1",
            "clean": true, "up_to_date": false, "fast_forwarded": false,
            "changed_paths": 1, "conflicts": [],
            "stats": {"trees_read": 1, "entries_compared": 2, "blobs_merged": 0, "wall_ms": 0.1},
            "recovery_ref": "refs/recovery/workspaces/ws-1/rebase-1"
        }))
        .unwrap();
        assert_eq!(response.result.workspace_head, "ws1");
        assert!(response.recovery_ref.unwrap().contains("recovery"));

        let log: GitWorkspaceLogPage = serde_json::from_value(serde_json::json!({
            "format_ver": 1,
            "workspace_id": "ws-1",
            "active_chain": [{
                "oid": "abc", "subject": "checkpoint", "at_ms": 10,
                "actor": "agent:1", "operation": "op-1", "conflicted": false
            }],
            "retained_chains": [{
                "recovery_ref": "refs/recovery/ws-1/one", "head": "old", "base": "base",
                "created_at_ms": 9, "reason": "rebase", "retention": "retained"
            }],
            "truncated": false,
            "next_after": null
        }))
        .unwrap();
        assert_eq!(log.active_chain[0].subject, "checkpoint");
        assert_eq!(log.retained_chains[0].retention, "retained");

        let graph: GitSmartlogPage = serde_json::from_value(serde_json::json!({
            "format_ver": 1, "repo": "demo",
            "nodes": [{
                "id": "branch:main", "kind": "branch", "label": "main", "oid": "abc",
                "workspace_id": null, "actor": null, "timestamp_ms": null, "state": "active"
            }],
            "edges": [{"from": "branch:main", "to": "abc", "kind": "points_to"}],
            "truncated": true, "next_after": "opaque-cursor"
        }))
        .unwrap();
        assert_eq!(graph.nodes[0].kind, "branch");
        assert_eq!(graph.next_after.as_deref(), Some("opaque-cursor"));
    }
}