File size: 54,795 Bytes
c786dae
adf68aa
 
 
 
 
 
 
 
 
 
 
 
 
 
c786dae
 
 
adf68aa
 
 
 
 
 
 
 
 
c786dae
adf68aa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c786dae
adf68aa
 
c786dae
adf68aa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c786dae
adf68aa
 
c786dae
 
adf68aa
 
 
 
c786dae
adf68aa
 
c786dae
 
adf68aa
 
 
 
 
 
 
 
 
 
 
 
 
 
c786dae
adf68aa
c786dae
adf68aa
 
 
 
c786dae
 
adf68aa
 
 
c786dae
adf68aa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c786dae
 
 
adf68aa
c786dae
adf68aa
 
 
c786dae
adf68aa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c786dae
adf68aa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c786dae
adf68aa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c786dae
adf68aa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c786dae
adf68aa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c786dae
adf68aa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Bucket sync: per agent, `<bucket_id>/<swarm>/<type>/<agent>/` holds

    workdir/<path relative to the workdir>        (if persist_workdir; the deltas with a base)
    workdir.base.tar, workdir.base.json           (only with the type's workdir.base, below)
    meta.json                                     ({files, bytes, ts} of the mirrored workdir when it last changed)
    sessions/<agent>.jsonl, <agent>.state.json    (pi session log + worker state)
    harness/<path relative to the harness home>   (a Trial's Pi sessions)

The workdir goes through `sync_bucket` (the Python form of `hf buckets sync`), upward with delete so the bucket mirrors the workdir. The handful of
session and harness files go through `batch_bucket_files`, only those whose (mtime, size)
changed since the last push by this worker. `restore` brings all three areas back to the
same absolute paths (workdir and work root are fixed, harness homes are fixed by the image)
before the first resume.

Restore lists the agent's prefix once, then downloads every file it found in batches
(`restore_batch()`: env `LEGION_RESTORE_BATCH`, default 1000, minimum 1, an invalid value
means the default), `restore_threads()` batches at a time (env `LEGION_RESTORE_THREADS`,
default 4; the type's `worker:` block overrides both), each to a `.legion-part` sibling renamed into place on success. A batch that
fails is retried file by file, with backoff (`RESTORE_BACKOFF`) between rounds: one unreadable
file is skipped and reported in `RestoreResult.failed` instead of aborting the whole restore. A
permanent "not found" (HTTP 404, e.g. xet "CAS Client Error: ... 404 Not Found" on the
reconstruction: the entry's data is gone) is skipped at once, without the backoff rounds (an
already-corrupt copy with ~42k such entries took 636 s to restore with them). Skipped files are
logged as one summary line per agent. Only a failed listing makes `restore` raise.

Buckets store bytes, not file modes: a restored file comes back 0644, so an executable script
would stop running after a move. Each
push therefore writes `<workdir>/.legion-modes.json` ({relative path: octal mode} for every file
with an executable bit) when it changed, and restore re-applies it after the workdir download.

Push safety (a periodic sync must never mirror a half-restored workdir over the bucket copy,
deleting entries the in-flight restore has not fetched yet):

- No push before setup: `AgentRuntime.sync_now` does nothing until the agent's `setup()` has
  finished its restore (every caller: the periodic sync, drain, preempt, unassign), and
  `BucketSync.push` refuses an agent whose restore is in flight. The bucket copy is the truth
  until the restore is done.
- Delete-mirror only from a full baseline: the workdir push deletes remote files missing
  locally only when this worker's restore of the agent was complete (the listing succeeded and
  no file failed; an empty prefix counts as complete) or when no restore was attempted (a new
  agent). After a failed listing, a skipped file or an interrupted restore, pushes upload
  changed files but never delete, for as long as this worker holds the agent: a file it could
  not fetch stays in the bucket for the next restore.
- `*.legion-part` (restore temporaries) is never uploaded nor deleted by a push; restore removes
  stray ones left by a crash.
- Regenerable caches (`workdir_excludes`: `__pycache__/`, `*.pyc`, `node_modules/`, `.venv/`, ...; env
  LEGION_SYNC_EXCLUDE adds globs, LEGION_SYNC_EXCLUDE_DEFAULTS=0 drops the defaults) are neither
  uploaded nor deleted by the mirror, and restore skips them, also those already in the bucket.
  `.git/` and worktrees are never excluded by default.
- The type's `workdir.ephemeral` dirs (root-relative) are excluded like the caches; the agent's
  setup empties them (`reset_ephemeral`), so they never come back after a move.
- Each push's modes walk also measures what is mirrored (`WorkdirStats`): above the type's
  `workdir.soft_*` the agent gets a note, above `max_*` a `workdir_over_quota` event (each at
  most hourly, `BucketSync._quota`). A push is never refused for size.
- Restore sets each workdir file's mtime to the bucket's (the listing carries it), so the first
  push after a restore uploads only real changes; session and harness files are marked as
  pushed (`_mark`).

Base tar (the type's `workdir.base: true`; off by default). A restore of N small files costs N
downloads; a base turns most of them into one:

- A periodic push (never drain, preempt or unassign) makes a base when the agent has none, every
  `workdir.base_interval_s` (3600) or when the delta passes `workdir.base_delta_files` (5000,
  changed + deleted): an uncompressed tar of the workdir, sorted, regular files and symlinks
  with modes and mtimes (excludes and ephemeral dirs left out), written to local disk and
  uploaded as `workdir.base.tar`; then `workdir.base.json` `{created_at, files, bytes, deleted,
  links}` is written: the commit point. Only from a full baseline (`_mirror`), like deletes.
- Every push after that uploads to `workdir/` only files whose (mtime, size) differ from the
  base's local index (`<sessions>/<agent>.base-index.json`), giving a changed file with an mtime
  not after the base (`cp -p`) the current time; base paths gone locally go to `deleted`
  (tombstones) and new or changed symlinks to `links`, rewriting the manifest when they change;
  delta entries not needed any more (in the base, or deleted) are removed from `workdir/`.
- Restore with a manifest: download it and the tar, extract the tar member by member from disk,
  apply `deleted` and `links`, then download only the `workdir/` entries newer than
  `created_at` (older ones are already in the tar). A failed manifest, tar or member makes the
  restore incomplete (no deletes, no new base). Buckets without a manifest restore file by file.
- Crash safety: before the manifest is written the old manifest (or the plain mirror) stays
  valid; after it, stale `workdir/` entries are older than `created_at`, ignored by restore and
  removed by the next push. Turning `base` off makes the next full-baseline push mirror the whole
  workdir to `workdir/` again and delete the base.
"""

from __future__ import annotations

import asyncio
import fnmatch
import functools
import json
import logging
import os
import re
import shutil
import stat
import tarfile
import threading
import time
from collections import Counter
from concurrent.futures import ThreadPoolExecutor
from dataclasses import dataclass, field
from datetime import UTC, datetime
from pathlib import Path
from typing import TYPE_CHECKING, Protocol

from legion.models import WorkdirSpec

if TYPE_CHECKING:
    from legion.models import TypeSpec
    from legion.worker.agents import AgentRuntime

log = logging.getLogger(__name__)

UPLOAD_CHUNK = 200
MODES_FILE = ".legion-modes.json"
BASE_TAR = "workdir.base.tar"  # under the agent prefix (module docstring, "Base tar")
BASE_JSON = "workdir.base.json"
RESTORE_BATCH = 1000  # default of LEGION_RESTORE_BATCH
RESTORE_THREADS = 4  # default of LEGION_RESTORE_THREADS
# The type's `worker:` values for this module (sync_exclude, restore_batch, restore_threads),
# set live by `Worker.apply_knobs`; each one present wins over its env variable.
SPEC_KNOBS: dict[str, object] = {}


def _env_int(name: str, default: int, cap: int | None = None) -> int:
    try:
        n = int(os.environ.get(name, ""))
    except ValueError:
        return default
    return min(n, cap or n) if n >= 1 else default


def restore_batch() -> int:
    """Files per restore download batch: the spec's, else env LEGION_RESTORE_BATCH (>= 1), else
    RESTORE_BATCH."""
    return SPEC_KNOBS.get("restore_batch") or _env_int("LEGION_RESTORE_BATCH", RESTORE_BATCH)


def restore_threads() -> int:
    """Batches of one agent's restore downloaded in parallel: the spec's, else env
    LEGION_RESTORE_THREADS (>= 1), else RESTORE_THREADS."""
    return SPEC_KNOBS.get("restore_threads") or _env_int("LEGION_RESTORE_THREADS", RESTORE_THREADS, 32)


RESTORE_BACKOFF = (1.0, 4.0, 10.0)  # seconds before each per-file retry round
PART_SUFFIX = ".legion-part"
PUSH_EXCLUDE = ["*" + PART_SUFFIX]  # sync_bucket patterns, matched on relative paths
# Regenerable caches left out of the workdir mirror and of restore (module docstring). A trailing
# "/" names a directory at any depth (`workdir_excludes`); other entries are plain globs.
# Not build/, dist/ or target/: sometimes source.
DEFAULT_WORKDIR_EXCLUDE = ["__pycache__/", "*.pyc", ".pytest_cache/", ".mypy_cache/",
                           ".ruff_cache/", ".hypothesis/", "*.egg-info/", ".cache/",
                           "node_modules/", ".venv/", "venv/", ".tox/", ".nox/",
                           ".ipynb_checkpoints/", ".gradle/", ".next/", "*.o"]


def _expand(pattern: str) -> list[str]:
    """`name/` -> `name/*` and `*/name/*` (the directory at the root and below any directory);
    anything else is returned as is. `sync_bucket` globs are fnmatch on the whole relative path,
    where `*` also crosses `/`."""
    if pattern.endswith("/"):
        d = pattern.rstrip("/")
        return [f"{d}/*", f"*/{d}/*"]
    return [pattern]


def workdir_excludes() -> list[str]:
    """Globs for the workdir mirror, relative to the workdir, always including `*.legion-part`:
    the defaults (unless env LEGION_SYNC_EXCLUDE_DEFAULTS=0) plus the spec's `sync_exclude`, else
    the comma-separated LEGION_SYNC_EXCLUDE. `.git/` is never in the defaults."""
    pats = list(PUSH_EXCLUDE)
    if os.environ.get("LEGION_SYNC_EXCLUDE_DEFAULTS", "1").strip() != "0":
        pats += [x for d in DEFAULT_WORKDIR_EXCLUDE for x in _expand(d)]
    extra = SPEC_KNOBS.get("sync_exclude")
    if extra is None:
        extra = os.environ.get("LEGION_SYNC_EXCLUDE", "").split(",")
    for item in extra:
        if item.strip():
            pats += _expand(item.strip())
    return pats


@functools.lru_cache(maxsize=64)
def _matcher(patterns: tuple[str, ...]):
    """One compiled regex for a pattern list (a walk tests every file of a workdir)."""
    if not patterns:
        return lambda rel: None
    return re.compile("|".join(fnmatch.translate(p.replace("\\", "/")) for p in patterns)).match


def is_excluded(rel: str, patterns: list[str]) -> bool:
    """Does the workdir-relative posix path match one of the patterns (as `sync_bucket` does)?"""
    return _matcher(tuple(patterns))(rel) is not None


@dataclass
class WorkdirStats:
    """What a push mirrors: regular files and their bytes, excluded paths left out, and the
    top-level directories with the most files ((name, files), largest first, up to 5)."""

    files: int = 0
    bytes: int = 0
    top_dirs: list[tuple[str, int]] = field(default_factory=list)

    def summary(self) -> str:
        """'182k files, 3100 MB; largest: snaps/ 140k, src/ 2k' (`{workspace}` in loop prompts)."""
        top = ", ".join(f"{d}/ {_k(n)}" for d, n in self.top_dirs[:3])
        return (f"{_k(self.files)} files, {self.bytes / 2**20:.0f} MB"
                + (f"; largest: {top}" if top else ""))


def _k(n: int) -> str:
    return f"{n / 1000:.0f}k" if n >= 1000 else str(n)


QUOTA_NOTE_EVERY = 3600.0  # s, per agent: the over-soft-limit note and workdir_over_quota


def quota_note(ws: WorkdirStats, w: WorkdirSpec) -> str | None:
    """The note for an agent whose workdir is above its soft limit, else None."""
    if ws.files <= w.soft_files and ws.bytes / 2**20 <= w.soft_mb:
        return None
    where = f", or keep throwaway clones in {w.ephemeral[0]}" if w.ephemeral else ""
    return (f"your workspace has {ws.summary()} (soft limit {_k(w.soft_files)} files, "
            f"{w.soft_mb:.0f} MB); delete clones you no longer need{where}")


def over_hard_limit(ws: WorkdirStats, w: WorkdirSpec) -> bool:
    return (ws.files > (w.max_files or 5 * w.soft_files)
            or ws.bytes / 2**20 > (w.max_mb or 5 * w.soft_mb))


def ephemeral_excludes(spec: TypeSpec) -> list[str]:
    """The type's `workdir.ephemeral` dirs as root-anchored globs (never synced nor restored)."""
    return [d + "*" for d in (spec.workdir.ephemeral if spec.workdir else [])]


def reset_ephemeral(workdir: Path, spec: TypeSpec) -> None:
    """Empty (or create) the type's ephemeral dirs: run at every agent setup, so a move or a
    restart never brings back their content. Blocking."""
    root = workdir.resolve()
    for d in spec.workdir.ephemeral if spec.workdir else []:
        p = workdir / d
        try:
            if not p.parent.resolve().is_relative_to(root):  # a symlinked parent: leave it
                log.warning("ephemeral dir %s is outside %s; not touched", p, root)
                continue
            if p.is_symlink() or p.is_file():
                p.unlink()
            elif p.is_dir():
                shutil.rmtree(p, ignore_errors=True)
            p.mkdir(parents=True, exist_ok=True)
        except OSError as e:
            log.warning("ephemeral dir %s: %s", p, e)


def _walk(workdir: Path, exclude: list[str] | None = None):
    """(relative posix path, lstat) of every regular file and symlink under `workdir`, sorted per
    directory; excluded directories are not entered, symlinked directories are not followed."""
    excl = _matcher(tuple(exclude or ()))
    for root, dirs, files in os.walk(workdir):
        base = Path(root).relative_to(workdir).as_posix()
        base = "" if base == "." else base + "/"
        links = [d for d in dirs if os.path.islink(os.path.join(root, d))]
        dirs[:] = sorted(d for d in dirs if d not in links and excl(f"{base}{d}/") is None)
        for f in sorted(files + links):
            rel = base + f
            if excl(rel) is not None:
                continue
            try:
                st = os.lstat(os.path.join(root, f))
            except OSError:
                continue
            if stat.S_ISREG(st.st_mode) or stat.S_ISLNK(st.st_mode):
                yield rel, st


def collect_modes(workdir: Path, stats: WorkdirStats | None = None,
                  exclude: list[str] | None = None) -> dict[str, str]:
    """{relative posix path: "0o755"} for regular files with any executable bit (symlinks and
    the manifest itself excluded). `exclude`: paths left out of the walk (excluded directories
    are not entered). `stats` gets the walk's counts (`WorkdirStats`)."""
    out: dict[str, str] = {}
    per_dir: Counter[str] = Counter()
    for rel, st in _walk(workdir, exclude):
        if not stat.S_ISREG(st.st_mode):
            continue
        if stats is not None:
            stats.files += 1
            stats.bytes += st.st_size
            if "/" in rel:
                per_dir[rel.split("/", 1)[0]] += 1
        if st.st_mode & 0o111 and rel != MODES_FILE:
            out[rel] = oct(stat.S_IMODE(st.st_mode))
    if stats is not None:
        stats.top_dirs = per_dir.most_common(5)
    return dict(sorted(out.items()))


def _write_synced(path: Path, text: str) -> None:  # fsync before a later os.replace
    with path.open("w") as f:
        f.write(text)
        f.flush()
        os.fsync(f.fileno())


def write_modes(workdir: Path, stats: WorkdirStats | None = None,
                exclude: list[str] | None = None) -> bool:
    """(Re)write the manifest if its content changed, remove it when nothing is executable.
    Returns whether the file changed."""
    path = workdir / MODES_FILE
    modes = collect_modes(workdir, stats, exclude)
    old = path.read_text() if path.is_file() else None
    if not modes:
        if old is not None:
            path.unlink()
            return True
        return False
    new = json.dumps(modes, indent=0, sort_keys=True) + "\n"
    if new == old:
        return False
    path.write_text(new)
    return True


def apply_modes(workdir: Path) -> int:
    """chmod the files listed in the manifest (inside the workdir, regular files only)."""
    path = workdir / MODES_FILE
    try:
        modes = json.loads(path.read_text())
    except (OSError, ValueError):
        return 0
    n = 0
    root = workdir.resolve()
    for rel, mode in (modes.items() if isinstance(modes, dict) else []):
        p = workdir / rel
        try:
            if ".." in Path(rel).parts or not p.resolve().is_relative_to(root) or p.is_symlink() \
                    or not p.is_file():
                continue
            os.chmod(p, int(mode, 8) & 0o7777)
            n += 1
        except (OSError, ValueError, TypeError):
            continue
    return n


class _Padded:
    """A file that may shrink while it is read: short reads are padded with zeros, so the tar
    stays well formed; the file's new mtime makes the next push send it as a delta."""

    def __init__(self, f) -> None:
        self.f = f

    def read(self, n: int = -1) -> bytes:
        b = self.f.read(n)
        return b + bytes(max(0, n - len(b)))


TAR_PER_FILE = 2048  # bytes of tar overhead per member, at most (pax header + padding)


def _fits(needs: list[tuple[Path, int]]) -> bool:
    """Do these byte counts fit in the free space of their file systems (summed per device)?"""
    per: dict[int, list] = {}
    for p, n in needs:
        p.mkdir(parents=True, exist_ok=True)
        per.setdefault(os.stat(p).st_dev, [p, 0])[1] += n
    return all(shutil.disk_usage(p).free >= n for p, n in per.values())


def write_base_tar(workdir: Path, exclude: list[str], dest: Path,
                   stop=lambda: False) -> dict[str, list] | None:
    """Write an uncompressed tar of the workdir (regular files and symlinks, sorted, with modes
    and mtimes) to `dest`; returns the index {relative path: [mtime, size]} of what it holds
    (lstat before each read), or None when `stop()` turned true between two members."""
    index: dict[str, list] = {}
    dest.parent.mkdir(parents=True, exist_ok=True)
    with tarfile.open(dest, "w", format=tarfile.PAX_FORMAT) as tf:
        for rel, st in _walk(workdir, exclude):
            if stop():
                return None
            ti = tarfile.TarInfo(rel)
            ti.mode, ti.mtime = stat.S_IMODE(st.st_mode), int(st.st_mtime)
            ti.pax_headers = {"mtime": f"{st.st_mtime_ns / 1e9:.9f}"}  # sub-second mtimes
            p = workdir / rel
            try:
                if stat.S_ISLNK(st.st_mode):
                    ti.type, ti.linkname = tarfile.SYMTYPE, os.readlink(p)
                    tf.addfile(ti)
                else:
                    with open(p, "rb") as f:
                        ti.size = st.st_size
                        tf.addfile(ti, _Padded(f))
            except OSError:  # gone since the walk (open or readlink, before anything is written)
                continue
            index[rel] = [st.st_mtime, st.st_size]
    return index


def extract_base_tar(src: Path, workdir: Path, exclude: list[str],
                     base: dict) -> tuple[dict[str, list], int]:
    """Extract a base tar into the workdir member by member (regular files and symlinks with
    their modes and mtimes; nothing outside the workdir, nothing excluded), then apply the
    manifest's tombstones (`deleted`) and symlinks (`links`). Returns (the index of the
    extracted files {relative path: [mtime, size]}, members that failed)."""
    workdir.mkdir(parents=True, exist_ok=True)
    root = workdir.resolve()
    index: dict[str, list] = {}
    bad = 0

    safe: set[str] = set()  # parent dirs checked (and made): one realpath per directory

    def target(rel: str, make: bool = True) -> str | None:
        """The local path for `rel`, cleared, or None when it must not be written."""
        if rel.startswith("/") or ".." in rel.split("/") or is_excluded(rel, exclude):
            return None
        p = os.path.join(workdir, rel)
        parent = os.path.dirname(p)
        if parent not in safe:
            if not Path(parent).resolve().is_relative_to(root):
                return None
            if make:
                os.makedirs(parent, exist_ok=True)
                safe.add(parent)
        try:
            if stat.S_ISDIR(os.lstat(p).st_mode):
                return None  # a directory in the way
            os.unlink(p)  # also read-only files (git objects) and links
        except FileNotFoundError:
            pass
        return p

    with tarfile.open(src, "r:") as tf:
        while (m := tf.next()) is not None:
            tf.members.clear()  # a 500k-file tar keeps no member list in memory
            try:
                if not (m.isreg() or m.issym()) or (p := target(m.name)) is None:
                    continue
                if m.issym():
                    os.symlink(m.linkname, p)
                else:
                    with tf.extractfile(m) as f, open(p, "wb") as out:
                        shutil.copyfileobj(f, out)
                    os.chmod(p, m.mode & 0o777)
                os.utime(p, (m.mtime, m.mtime), follow_symlinks=False)
                index[m.name] = [m.mtime, len(os.fsencode(m.linkname)) if m.issym() else m.size]
            except OSError as e:
                bad += 1
                log.debug("base member %s: %s", m.name, e)
    for rel in base.get("deleted", []):
        try:
            target(rel, make=False)
        except OSError:
            bad += 1
    for rel, link in base.get("links", {}).items():
        try:
            if (p := target(rel)) is not None:
                os.symlink(link, p)
        except OSError:
            bad += 1
    return index, bad


def _same(a: list | None, mtime: float, size: int) -> bool:
    return a is not None and abs(a[0] - mtime) <= 2e-3 and a[1] == size


def workdir_delta(workdir: Path, exclude: list[str], index: dict[str, list],
                  created_at: float) -> tuple[dict[str, float], dict[str, str], list[str]]:
    """Against the base's index: (regular files new or changed {rel: mtime}, symlinks new or
    changed {rel: target}, base paths gone). A changed file whose mtime is not after the base
    (`cp -p`, `tar x`) gets its mtime set to now, since restore only takes deltas newer than the
    base."""
    files: dict[str, float] = {}
    links: dict[str, str] = {}
    seen: set[str] = set()
    now = max(time.time(), created_at + 1.0)
    for rel, st in _walk(workdir, exclude):
        seen.add(rel)
        if _same(index.get(rel), st.st_mtime, st.st_size):
            continue
        p = workdir / rel
        try:
            if stat.S_ISLNK(st.st_mode):
                links[rel] = os.readlink(p)
                continue
            mt = st.st_mtime
            if mt <= created_at + 2e-3:  # the Hub keeps milliseconds
                os.utime(p, (now, now))
                mt = now
        except OSError:
            continue
        files[rel] = mt
    return files, links, sorted(set(index) - seen)


def _load_index(path: Path) -> dict[str, list]:
    try:
        return json.loads(path.read_text())
    except (OSError, ValueError):
        return {}


@dataclass
class BucketStats:
    """Bucket traffic counters for the worker log: store operations (`ops`), the Hub HTTP
    requests behind them (`http`, by method and route; xet CAS transfers run in hf_xet and are
    not seen here) and HTTP error statuses (`errors`, e.g. 429). Thread-safe."""

    ops: Counter = field(default_factory=Counter)
    http: Counter = field(default_factory=Counter)
    errors: Counter = field(default_factory=Counter)
    _lock: threading.Lock = field(default_factory=threading.Lock, repr=False)

    def add(self, kind: str, key: str, n: int = 1) -> None:
        with self._lock:
            getattr(self, kind)[key] += n

    def snapshot(self) -> dict[str, Counter]:
        with self._lock:
            return {"ops": Counter(self.ops), "http": Counter(self.http),
                    "errors": Counter(self.errors)}

    def since(self, before: dict[str, Counter]) -> dict[str, dict[str, int]]:
        now = self.snapshot()
        return {k: dict(now[k] - before[k]) for k in now}


_BUCKET_ROUTE = re.compile(r"^/api/buckets/[^/]+/[^/]+(?:/([^/]+))?")


def http_route(method: str, host: str, path: str) -> str:
    """'GET /api/buckets/ns/b/tree/x/y' -> 'GET buckets/tree'; other hosts by first segment."""
    m = _BUCKET_ROUTE.match(path)
    if m:
        return f"{method} buckets/{m.group(1) or ''}".rstrip("/")
    first = path.strip("/").split("/", 1)[0]
    if host.endswith("huggingface.co"):
        return f"{method} {first or '/'}"
    return f"{method} {host}/{first}"


def count_hub_http(stats: BucketStats) -> None:
    """Count every request huggingface_hub's shared client makes (one install per process)."""
    import huggingface_hub
    from huggingface_hub.utils._http import default_client_factory

    def on_request(request) -> None:
        stats.add("http", http_route(request.method, request.url.host, request.url.path))

    def on_response(response) -> None:
        if response.status_code >= 400:
            req = response.request
            route = http_route(req.method, req.url.host, req.url.path)
            stats.add("errors", f"{response.status_code} {route}")

    def factory():
        client = default_client_factory()
        client.event_hooks["request"].append(on_request)
        client.event_hooks.setdefault("response", []).append(on_response)
        return client

    huggingface_hub.set_client_factory(factory)


class BucketStore(Protocol):
    """Blocking bucket operations on paths relative to the legion root."""

    def upload(self, files: list[tuple[Path, str]]) -> None: ...
    def list(self, prefix: str) -> list[str]: ...
    def first(self, prefix: str) -> str | None: ...  # one file under prefix (the launch guard)
    # optional: `list_info(prefix) -> list[tuple[str, float | None]]`, paths with their mtime
    # (POSIX seconds) when the store keeps one; restore uses it to set local mtimes
    def download(self, files: list[tuple[str, Path]]) -> None: ...
    def sync_up(self, local: Path, prefix: str, *, delete: bool = True,
                exclude: list[str] | None = None) -> None:
        """Upload new/changed files of a local directory to `prefix`; with `delete`, also
        delete remote files missing locally. `exclude`: fnmatch patterns on relative paths,
        neither uploaded nor deleted."""
        ...

    def sync_down(self, prefix: str, local: Path) -> None: ...
    def delete(self, paths: list[str]) -> None:
        """Delete files (paths relative to the legion root). Used by the controller's state."""
        ...


def parse_bucket(url: str) -> tuple[str, str]:
    """'hf://buckets/ns/name/some/prefix' -> ('ns/name', 'some/prefix/')."""
    rest = url.removeprefix("hf://").removeprefix("buckets/").strip("/")
    parts = rest.split("/")
    if len(parts) < 2:
        raise ValueError(f"bad bucket url {url!r}; expected hf://buckets/<namespace>/<name>[/prefix]")
    prefix = "/".join(parts[2:])
    return f"{parts[0]}/{parts[1]}", (prefix + "/" if prefix else "")


class HubBucketStore:
    """huggingface_hub bucket API (batch_bucket_files / list_bucket_tree / download_bucket_files)."""

    def __init__(self, url: str, token: str | None = None, stats: BucketStats | None = None) -> None:
        from huggingface_hub import HfApi

        self.bucket_id, self.base = parse_bucket(url)
        self.api = HfApi(token=token)
        self.stats = stats or BucketStats()

    def upload(self, files: list[tuple[Path, str]]) -> None:
        for i in range(0, len(files), UPLOAD_CHUNK):
            self.stats.add("ops", "batch_bucket_files")
            chunk = files[i : i + UPLOAD_CHUNK]
            self.api.batch_bucket_files(self.bucket_id, add=[(str(p), self.base + r) for p, r in chunk])

    def list(self, prefix: str) -> list[str]:
        return [r for r, _ in self.list_info(prefix)]

    def first(self, prefix: str) -> str | None:
        """One file under `prefix` (None: empty), without listing the rest."""
        from huggingface_hub import BucketFile

        self.stats.add("ops", "list_bucket_tree")
        full = self.base + prefix
        for f in self.api.list_bucket_tree(self.bucket_id, prefix=full, recursive=True):
            if isinstance(f, BucketFile) and f.path.startswith(full):
                return f.path[len(self.base):]
        return None

    def list_info(self, prefix: str) -> list[tuple[str, float | None]]:
        from huggingface_hub import BucketFile

        self.stats.add("ops", "list_bucket_tree")
        full = self.base + prefix
        out: list[tuple[str, float | None]] = []
        for f in self.api.list_bucket_tree(self.bucket_id, prefix=full, recursive=True):
            if isinstance(f, BucketFile) and f.path.startswith(full):
                mt = f.mtime.timestamp() if isinstance(f.mtime, datetime) else None
                out.append((f.path[len(self.base):], mt))
        return out

    def download(self, files: list[tuple[str, Path]]) -> None:
        self.stats.add("ops", "download_bucket_files")
        for _, local in files:
            local.parent.mkdir(parents=True, exist_ok=True)
        self.api.download_bucket_files(self.bucket_id, [(self.base + r, str(p)) for r, p in files])

    def delete(self, paths: list[str]) -> None:
        for i in range(0, len(paths), UPLOAD_CHUNK):
            self.stats.add("ops", "batch_bucket_files")
            chunk = paths[i : i + UPLOAD_CHUNK]
            self.api.batch_bucket_files(self.bucket_id, delete=[self.base + r for r in chunk])

    def _url(self, prefix: str) -> str:
        return f"hf://buckets/{self.bucket_id}/{self.base}{prefix}".rstrip("/")

    def sync_up(self, local: Path, prefix: str, *, delete: bool = True,
                exclude: list[str] | None = None) -> None:
        self.stats.add("ops", "sync_bucket_up")
        self.api.sync_bucket(str(local), self._url(prefix), delete=delete, exclude=exclude or None,
                             quiet=True)

    def sync_down(self, prefix: str, local: Path) -> None:
        self.stats.add("ops", "sync_bucket_down")
        local.mkdir(parents=True, exist_ok=True)
        self.api.sync_bucket(self._url(prefix), str(local), quiet=True)


@dataclass
class RestoreResult:
    workdir: int = 0
    sessions: int = 0
    harness: int = 0
    # bucket paths (relative to the legion root) that could not be downloaded, after retries
    failed: list[str] = field(default_factory=list)


_NOT_FOUND = re.compile(r"\b404\b|not found", re.IGNORECASE)


def _permanent(e: BaseException) -> bool:
    """A download error that retrying cannot fix: the entry's data is gone (HTTP 404)."""
    resp = getattr(e, "response", None)
    if getattr(resp, "status_code", None) == 404:
        return True
    return bool(_NOT_FOUND.search(str(e)))


def _part(p: Path) -> Path:
    return p.with_name(p.name + PART_SUFFIX)


def download_resilient(store: BucketStore, files: list[tuple[str, Path]], *,
                       backoff: tuple[float, ...] | None = None, sleep=None,
                       progress=None) -> tuple[list[tuple[str, Path]], list[str]]:
    """Download (remote, local) pairs; returns (downloaded, failed remote paths). Never raises
    for a file: batches first, then the files of a failed batch one by one, retried after each
    delay in `backoff` unless the error is a permanent "not found" (`_permanent`). Each file lands in a `.legion-part` sibling, renamed into place only
    when it arrived, so a failed file never leaves a truncated copy at its real path.
    `progress(n)` is called with the number of files each attempt brought in (serialized: the
    first pass runs `restore_threads()` batches in parallel threads)."""

    gone: list[str] = []  # permanent "not found": skipped, never retried
    lock = threading.Lock()  # first-pass batches run in threads

    def attempt(batch: list[tuple[str, Path]]) -> tuple[list[tuple[str, Path]], list[tuple[str, Path]]]:
        ok, bad = [], []
        try:
            store.download([(r, _part(p)) for r, p in batch])
        except Exception as e:  # noqa: BLE001 - sorted out per file below
            err = e
        else:
            err = None
        for r, p in batch:
            part = _part(p)
            if err is None and part.is_file():
                try:
                    os.replace(part, p)
                    ok.append((r, p))
                    continue
                except OSError:
                    pass
            part.unlink(missing_ok=True)
            bad.append((r, p))
        if ok and progress is not None:
            with lock:
                progress(len(ok))
        if err is not None and len(batch) == 1:
            log.debug("download of %s failed: %s", batch[0][0], _short(err))
            if bad and _permanent(err):
                gone.append(bad[0][0])
                return ok, []
        return ok, bad

    backoff = RESTORE_BACKOFF if backoff is None else backoff
    sleep = sleep or time.sleep
    done: list[tuple[str, Path]] = []
    pending: list[tuple[str, Path]] = []
    size = restore_batch()
    batches = [files[i : i + size] for i in range(0, len(files), size)]
    # the first pass runs `restore_threads()` batches at once (per-request latency, not
    # bandwidth, bounds a restore); the per-file retry rounds below stay sequential
    with ThreadPoolExecutor(max(1, min(restore_threads(), len(batches)))) as pool:
        for ok, bad in pool.map(attempt, batches):
            done += ok
            pending += bad
    if pending:  # each file alone, so one bad file costs only itself
        retry, pending = pending, []
        for f in retry:
            ok, bad = attempt([f])
            done += ok
            pending += bad
    for delay in backoff:
        if not pending:
            break
        sleep(delay)
        retry, pending = pending, []
        for f in retry:
            ok, bad = attempt([f])
            done += ok
            pending += bad
    # the caller logs the skipped files (one summary line per agent, `BucketSync._restore_files`)
    return done, gone + [r for r, _ in pending]


def _clean_parts(root: Path) -> int:
    """Remove stray `.legion-part` files under `root` (a crash mid-download leaves them)."""
    n = 0
    if root.is_dir():
        for p in root.rglob("*" + PART_SUFFIX):
            try:
                if p.is_file() and not p.is_symlink():
                    p.unlink()
                    n += 1
            except OSError:
                pass
    return n


def _short(e: BaseException) -> str:
    return f"{type(e).__name__}: {str(e)[:300]}"


class BucketSync:
    def __init__(self, store: BucketStore, swarm: str) -> None:
        self.store = store
        self.swarm = swarm
        self.stats: BucketStats = getattr(store, "stats", None) or BucketStats()
        self._seen: dict[Path, tuple[int, int]] = {}
        # per agent prefix: may the workdir push delete remote files? Absent: no restore was
        # attempted (a new agent), deletes allowed. False from the start of a restore until it
        # completes with every file; stays False after an incomplete one (module docstring).
        self._mirror: dict[str, bool] = {}
        self._restoring: set[str] = set()  # agent prefixes with a restore in flight
        self._meta: dict[str, dict] = {}  # per agent prefix: the meta.json last pushed
        self._quota_note: dict[str, str] = {}  # per agent prefix: the quota note last queued
        self._base: dict[str, dict] = {}  # per agent prefix: its committed workdir.base.json
        self._building: set[str] = set()  # agent prefixes with a base tar being made
        self.stop_rebase = False  # set by drain/preempt: base builds stop, none start
        self._quota_at: dict[str, float] = {}  # per agent prefix: monotonic time of the last note
        # per agent prefix with a restore in flight: [files done, files listed, started (UTC)]
        self.restore_progress: dict[str, list] = {}

    def mirror_deletes(self, rt: AgentRuntime) -> bool:
        return self._mirror.get(self.prefix(rt), True)

    def prefix(self, rt: AgentRuntime) -> str:
        return f"{self.swarm}/{rt.type_name}/{rt.name}/"

    def collect(self, rt: AgentRuntime) -> list[tuple[Path, str]]:
        """The agent's session-log, state and harness files, with their bucket paths."""
        pre = self.prefix(rt)
        out: list[tuple[Path, str]] = []
        for p in (rt.log.path, rt.state_path):
            if p.is_file():
                out.append((p, f"{pre}sessions/{p.name}"))
        home = Path(rt.adapter.home)
        for p in rt.harness_files():
            try:
                rel = p.relative_to(home)
            except ValueError:
                log.warning("%s: harness file %s is outside %s; not synced", rt.name, p, home)
                continue
            out.append((p, f"{pre}harness/{rel.as_posix()}"))
        return out

    def _changed(self, files: list[tuple[Path, str]]) -> list[tuple[Path, str]]:
        changed = []
        for p, r in files:
            try:
                st = p.stat()
            except OSError:
                continue
            sig = (st.st_mtime_ns, st.st_size)
            if self._seen.get(p) != sig:
                changed.append((p, r))
        return changed

    def _mark(self, files: list[tuple[Path, str]]) -> None:
        for p, _ in files:
            try:
                st = p.stat()
                self._seen[p] = (st.st_mtime_ns, st.st_size)
            except OSError:
                pass

    async def push(self, rt: AgentRuntime, *, rebase: bool = False) -> int:
        """`rebase`: may make a new base tar when one is due (periodic pushes only, so drain
        and preempt stay as cheap as a delta)."""
        try:
            return await self._push(rt, rebase)
        except Exception:
            self.stats.add("errors", "push_failed")
            raise

    async def _push(self, rt: AgentRuntime, rebase: bool = False) -> int:
        pre = self.prefix(rt)
        if pre in self._restoring:  # never mirror a half-restored agent (module docstring)
            log.warning("%s: push skipped, its restore is still running", rt.name)
            return 0
        meta: list[tuple[Path, str]] = []
        if rt.spec.persist_workdir and rt.workdir.is_dir():
            exclude = workdir_excludes() + ephemeral_excludes(rt.spec)
            ws = WorkdirStats()
            await asyncio.to_thread(write_modes, rt.workdir, ws, exclude)
            rt.workdir_files, rt.workdir_stats = ws.files, ws
            self._quota(rt, ws)
            stats = {"files": ws.files, "bytes": ws.bytes}
            if self._meta.get(pre) != stats:  # the workdir's size: predicts a restore's time
                path = rt.sessions_dir / f"{rt.name}.meta.json"
                path.parent.mkdir(parents=True, exist_ok=True)
                path.write_text(json.dumps({**stats, "ts": datetime.now(UTC).isoformat()}))
                meta = [(path, pre + "meta.json")]
            delete = self.mirror_deletes(rt)
            if not delete:
                log.info("%s: workdir push without remote deletes (last restore incomplete)",
                         rt.name)
            w = rt.spec.workdir or WorkdirSpec()
            if not (w.base and (pre in self._base or (rebase and delete))
                    and await self._push_base(rt, exclude, w, rebase and delete, ws)):
                await asyncio.to_thread(self.store.sync_up, rt.workdir, pre + "workdir",
                                        delete=delete, exclude=exclude)
                if pre in self._base and delete:  # base turned off: the full mirror replaces it
                    await asyncio.to_thread(self.store.delete, [pre + BASE_JSON, pre + BASE_TAR])
                    self._base.pop(pre)
        files = self._changed(self.collect(rt)) + meta
        if files:
            await asyncio.to_thread(self.store.upload, files)
            self._mark(files)
            if meta:
                self._meta[pre] = stats
        return len(files)

    def _index_path(self, rt: AgentRuntime) -> Path:
        return rt.sessions_dir / f"{rt.name}.base-index.json"

    async def _push_base(self, rt: AgentRuntime, exclude: list[str], w: WorkdirSpec,
                         may_rebase: bool, ws: WorkdirStats) -> bool:
        """Workdir push with a base tar (module docstring, "Base tar"): a new base when due,
        then the files changed since the base, and tombstones and symlinks in the manifest.
        False: no base yet and none made (stopped, no disk); the caller mirrors file by file."""
        pre, dpre = self.prefix(rt), self.prefix(rt) + "workdir/"
        base = self._base.get(pre)

        def delta():
            index = _load_index(self._index_path(rt))
            return workdir_delta(rt.workdir, exclude, index, base["created_at"])

        async def send() -> dict[str, float | None]:
            remote = {r[len(dpre):]: mt for r, mt in
                      await asyncio.to_thread(self.store.list_info, dpre)}
            up = [(rt.workdir / r, dpre + r) for r, mt in files.items()
                  if remote.get(r) is None or abs(remote[r] - mt) > 2e-3]
            if up:
                await asyncio.to_thread(self.store.upload, up)
            return remote

        if base is not None:
            files, links, deleted = await asyncio.to_thread(delta)
        if may_rebase and (base is None or time.time() - base["created_at"] >= w.base_interval_s
                           or len(files) + len(links) + len(deleted) > w.base_delta_files):
            if not _fits([(rt.sessions_dir, ws.bytes + ws.files * TAR_PER_FILE)]):
                log.warning("%s: no new workdir base, not enough free disk for a %s tar",
                            rt.name, ws.summary())
            elif (new := await self._make_base(rt, exclude)) is not None:
                base = new
                files, links, deleted = await asyncio.to_thread(delta)
        if base is None:
            return False
        remote = await send()
        if not self.mirror_deletes(rt):  # tombstones and remote deletes: full baseline only
            return True
        while pre in self._building:  # another push is making a base: its manifest goes first
            await asyncio.sleep(0.1)
        if self._base.get(pre) is not base:  # ... and was committed: diff against it
            base = self._base[pre]
            files, links, deleted = await asyncio.to_thread(delta)
            remote = await send()
        if base.get("deleted", []) != deleted or base.get("links", {}) != links:
            await self._write_base(rt, {**base, "deleted": deleted, "links": links})

        def stale(index: dict[str, list], r: str) -> bool:
            """Remote delta not needed: not changed in this walk and, locally, gone or as in the
            base (a file a concurrent push uploaded after this walk differs from it: it stays)."""
            if r in files or is_excluded(r, exclude):
                return False
            try:
                st = os.lstat(rt.workdir / r)
            except OSError:
                return True
            return _same(index.get(r), st.st_mtime, st.st_size)

        def stale_all() -> list[str]:
            index = _load_index(self._index_path(rt))
            return [dpre + r for r in remote if stale(index, r)]

        gone = await asyncio.to_thread(stale_all)
        if gone:  # deltas now in the base, or deleted
            await asyncio.to_thread(self.store.delete, gone)
        return True

    async def _make_base(self, rt: AgentRuntime, exclude: list[str]) -> dict | None:
        """Tar the workdir, upload it, then commit `workdir.base.json` (the commit point); the
        local index of the base replaces the old one only after the commit. None when
        `stop_rebase` (drain, preempt) stopped it before the upload: nothing was written."""
        pre = self.prefix(rt)
        tar, idx = rt.sessions_dir / f"{rt.name}.base.tar", self._index_path(rt)
        new_idx = idx.with_name(idx.name + ".new")
        self._building.add(pre)
        try:
            t0 = time.time()
            index = await asyncio.to_thread(write_base_tar, rt.workdir, exclude, tar,
                                            lambda: self.stop_rebase)
            if index is None or self.stop_rebase:
                log.info("%s: workdir base build stopped (drain or preempt)", rt.name)
                return None
            await asyncio.to_thread(_write_synced, new_idx, json.dumps(index))
            await asyncio.to_thread(self.store.upload, [(tar, pre + BASE_TAR)])
            base = {"created_at": t0, "files": len(index),
                    "bytes": sum(s for _, s in index.values()), "deleted": [], "links": {}}
            await self._write_base(rt, base)
            os.replace(new_idx, idx)
        finally:
            self._building.discard(pre)
            tar.unlink(missing_ok=True)
            new_idx.unlink(missing_ok=True)
        log.info("%s: new workdir base: %d files, %.0f MB in %.1f s", rt.name, base["files"],
                 base["bytes"] / 2**20, time.time() - t0)
        return base

    async def _write_base(self, rt: AgentRuntime, base: dict) -> None:
        path = rt.sessions_dir / f"{rt.name}.base.json"
        path.parent.mkdir(parents=True, exist_ok=True)
        path.write_text(json.dumps(base))
        await asyncio.to_thread(self.store.upload, [(path, self.prefix(rt) + BASE_JSON)])
        self._base[self.prefix(rt)] = base

    async def _restore_base(self, rt: AgentRuntime,
                            skip: list[str]) -> tuple[dict | None, list[str], int]:
        """Manifest, then tar (extracted while read from disk), tombstones and symlinks.
        Returns (the manifest or None when the base could not be restored, failed bucket paths,
        files extracted)."""
        pre = self.prefix(rt)
        mpath, tar = rt.sessions_dir / f"{rt.name}.base.json", rt.sessions_dir / f"{rt.name}.base.tar"
        try:
            _, failed = await asyncio.to_thread(download_resilient, self.store,
                                                [(pre + BASE_JSON, mpath)])
            if failed:
                return None, failed, 0
            base = json.loads(mpath.read_text())
            size = int(base["bytes"])
            if not _fits([(rt.sessions_dir, size + int(base["files"]) * TAR_PER_FILE),
                          (rt.workdir, size)]):
                log.error("%s: workdir base not restored: not enough free disk for %d MB "
                          "(tar plus files)", rt.name, 2 * size // 2**20)
                return None, [pre + BASE_TAR], 0
            _, failed = await asyncio.to_thread(download_resilient, self.store,
                                                [(pre + BASE_TAR, tar)])
            if failed:
                return None, failed, 0
            index, bad = await asyncio.to_thread(extract_base_tar, tar, rt.workdir, skip, base)
        except (OSError, ValueError, KeyError, AttributeError, tarfile.TarError) as e:
            log.warning("%s: workdir base not restored: %s", rt.name, _short(e))
            return None, [pre + BASE_TAR], 0
        finally:
            tar.unlink(missing_ok=True)
        await asyncio.to_thread(self._index_path(rt).write_text, json.dumps(index))
        self._base[pre] = base
        if bad:
            log.warning("%s: %d workdir base entries not restored", rt.name, bad)
        return base, [pre + BASE_TAR] if bad else [], len(index)

    def _quota(self, rt: AgentRuntime, ws: WorkdirStats) -> None:
        """Above the soft limit: a note in front of the agent's next prompt, and above the hard
        one a `workdir_over_quota` event, each at most hourly. The push itself goes on."""
        w = rt.spec.workdir or WorkdirSpec()
        note, pre, now = quota_note(ws, w), self.prefix(rt), time.monotonic()
        if note is None or now - self._quota_at.get(pre, -QUOTA_NOTE_EVERY) < QUOTA_NOTE_EVERY:
            return
        rt._notes.pop(self._quota_note.pop(pre, None), None)  # replace, do not stack
        rt._note(note)
        if note not in rt._notes:  # dropped (no turn yet): try again at the next push
            return
        self._quota_at[pre] = now
        self._quota_note[pre] = note
        if over_hard_limit(ws, w):
            rt.emit("workdir_over_quota", {"files": ws.files, "bytes": ws.bytes,
                                           "top_dirs": [list(t) for t in ws.top_dirs]})

    async def restore(self, rt: AgentRuntime) -> RestoreResult:
        try:
            return await self._restore(rt)
        except Exception:
            self.stats.add("errors", "restore_failed")
            raise

    async def _restore(self, rt: AgentRuntime) -> RestoreResult:
        pre = self.prefix(rt)
        self._mirror[pre] = False  # until this restore completes with every file
        self._restoring.add(pre)
        self.restore_progress[pre] = [0, 0, datetime.now(UTC)]
        try:
            res = await self._restore_files(rt, pre)
        finally:
            self._restoring.discard(pre)
            self.restore_progress.pop(pre, None)
        self._mirror[pre] = not res.failed
        return res

    async def _restore_files(self, rt: AgentRuntime, pre: str) -> RestoreResult:
        lister = getattr(self.store, "list_info", None)
        if lister is not None:  # raises: the caller starts fresh
            listed = await asyncio.to_thread(lister, pre)
        else:
            listed = [(r, None) for r in await asyncio.to_thread(self.store.list, pre)]
        mtimes = {r: mt for r, mt in listed}
        self._base.pop(pre, None)  # known again only if this listing has one
        res = RestoreResult()
        work: list[tuple[str, Path]] = []
        plan: list[tuple[str, Path]] = []
        home = Path(rt.adapter.home)
        n = sum([await asyncio.to_thread(_clean_parts, d) for d in (rt.workdir, rt.sessions_dir)])
        if n:
            log.info("%s: removed %d stray %s file(s)", rt.name, n, PART_SUFFIX)
        skip = workdir_excludes() + ephemeral_excludes(rt.spec)
        for r, _ in listed:
            rel = r[len(pre):]
            area, _, sub = rel.partition("/")
            if rel == "meta.json":  # known, the first push after a move need not resend it
                plan.append((r, rt.sessions_dir / f"{rt.name}.meta.json"))
                continue
            if not sub or ".." in Path(sub).parts:
                continue
            if area == "workdir":
                if rt.spec.persist_workdir and not is_excluded(sub, skip):
                    work.append((r, rt.workdir / sub))
            elif area == "sessions":
                plan.append((r, rt.sessions_dir / sub))
            elif area == "harness":
                plan.append((r, home / sub))
        prog = self.restore_progress.get(pre)
        if prog is not None:
            prog[1] = len(work) + len(plan)

        def progress(n: int) -> None:
            if prog is not None:
                prog[0] += n

        if rt.spec.persist_workdir and pre + BASE_JSON in mtimes:
            base, failed, n = await self._restore_base(rt, skip)
            res.workdir, res.failed = n, res.failed + failed
            if prog is not None:
                prog[1] += n
            progress(n)
            if base is not None:  # older deltas are already in the tar (or stale)
                work = [(r, p) for r, p in work
                        if mtimes.get(r) is None or mtimes[r] > base["created_at"]]
                await asyncio.to_thread(_no_links, rt.workdir, work)
        if work:
            rt.workdir.mkdir(parents=True, exist_ok=True)
            got, failed = await asyncio.to_thread(download_resilient, self.store, work,
                                                  progress=progress)
            res.workdir, res.failed = res.workdir + len(got), res.failed + failed
            await asyncio.to_thread(_set_mtimes, got, mtimes)
            if n := await asyncio.to_thread(apply_modes, rt.workdir):
                log.info("%s: restored the mode of %d file(s)", rt.name, n)
        if plan:
            for _, p in plan:
                _part(p).unlink(missing_ok=True)
            got, failed = await asyncio.to_thread(download_resilient, self.store, plan,
                                                  progress=progress)
            res.failed += failed
            await asyncio.to_thread(_set_mtimes, got, mtimes)
            for r, p in got:
                if r == pre + "meta.json":
                    try:
                        self._meta[pre] = {k: v for k, v in json.loads(p.read_text()).items()
                                           if k in ("files", "bytes")}
                    except (OSError, ValueError, AttributeError):
                        pass
                elif r.startswith(pre + "sessions/"):
                    res.sessions += 1
                else:
                    res.harness += 1
            self._mark([(p, r) for r, p in got])
        if res.failed:
            self.stats.add("errors", "restore_file_failed", len(res.failed))
            state = f"{pre}sessions/{rt.state_path.name}"
            if state in res.failed:
                log.warning("%s: state file %s not restored; the agent starts a fresh session",
                            rt.name, state)
            log.warning("%s: restored workdir=%d sessions=%d harness=%d; %d file(s) skipped "
                        "(not found or still failing after retries), e.g. %s", rt.name,
                        res.workdir, res.sessions, res.harness, len(res.failed),
                        ", ".join(res.failed[:10]))
        else:
            log.info("%s: restored %s", rt.name, res)
        return res


def _no_links(workdir: Path, work: list[tuple[str, Path]]) -> None:
    """Deltas over a tar's symlinks: a file or directory replaced a symlink after the base, so
    remove symlinks at a delta's path and its parents, or the download writes through them."""
    for _, p in work:
        parts = p.relative_to(workdir).parts
        for i in range(1, len(parts) + 1):
            q = workdir.joinpath(*parts[:i])
            if q.is_symlink():
                q.unlink()
                break
            if not q.is_dir():
                break


def _set_mtimes(files: list[tuple[str, Path]], mtimes: dict[str, float | None]) -> None:
    """Give restored files the bucket's mtime, so the next `sync_up` sees them unchanged."""
    for r, p in files:
        mt = mtimes.get(r)
        if mt is None:
            continue
        try:
            os.utime(p, (mt, mt), follow_symlinks=False)
        except (OSError, NotImplementedError):
            pass