Repository navigation
Expand file tree
/
Copy pathcli.py
More file actions
2479 lines (2211 loc) · 116 KB
/
Copy pathcli.py
File metadata and controls
2479 lines (2211 loc) · 116 KB
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
"""``agentsync`` command line (owner: integrator).
Subcommands: add-source PATH · init (hidden) · sync (hidden options: --once, --mode poll|reconcile|dry_run,
--materialise-budget BYTES) · accept-deletions SOURCE · status · curate · materialise [--budget BYTES]
[PATH ...] (hidden) · adopt SRC_DIR · migrate (hidden, a no-op) · graph login|logout|whoami|discover (also as
top-level login · logout · whoami · discover; login [--device-code]; discover [--url URL ...] [--toml]) ·
install-agent (hidden) · uninstall-agent (hidden) · purge SELECTOR | --queue · compact-history [--keep-days N
(at least 1)] (hidden) · hold · offboard [--purge-data] [--confirm DOCS_REPO] · setup-report (hidden; hidden
--out PATH, default ~/agent-context/setup-report.md) · it-request --out PATH.
Every subcommand accepts ``--config PATH`` (default ~/agent-context/sources.toml) and ``-v/--verbose``.
``sync`` without ``--mode`` ends with the loop's ``NEXT:`` line and any ``WAITING ON YOU:`` lines
(:mod:`agentsync.loop`); ``status``, the single read-only check, starts with them (KISS K08a; ``doctor``
and ``policy show`` are hidden aliases of it). ``AGENTSYNC_NO_NEXT_HINT=1`` (scripts/install.sh sets it) drops
them from both.
``setup-report`` ends with the issue link, never a hint.
C15 section 9 item 32: the macOS trust store is injected into ``ssl`` (truststore) as the very first thing,
before any agentsync module imports ``msal``, ``requests`` or ``httpx``; tests/test_cli.py asserts the order.
"""
from __future__ import annotations
# The trust-store injection must precede every other import (C15 section 9 item 32).
import ssl as _ssl
import truststore as _truststore
if _ssl.SSLContext is not _truststore.SSLContext: # same effect as agentsync.net.inject_system_trust()
_truststore.inject_into_ssl()
import argparse
import contextlib
import dataclasses
import json
import logging
import os
import re
import sqlite3
import subprocess
import sys
import time
from collections.abc import Callable, Iterator, Mapping, Sequence
from datetime import UTC, datetime, timedelta
from pathlib import Path
from typing import Any
from agentsync import (
__version__,
curate,
gitops,
governance,
it_request,
lints,
loop,
net,
setup_report,
skill,
)
from agentsync import policy as content_policy
from agentsync.arm_local import ECHOED_ALARM, exclude_advice, exclude_globs
from agentsync.config import (
Config,
SourceConfig,
append_to_config,
canonical_source_root,
default_config_text,
derive_source_id,
ensure_inbox,
load_config,
local_source_table,
parse_config,
parse_size,
set_source_exclude,
)
from agentsync.cycle import (
ECHOED_WHEN,
INTERACTIVE_LOCK_WAIT_S,
_acquire_waiting,
_holds_home,
_tighten_own_paths,
quiet_lock_wait,
run_cycle,
source_statuses,
)
from agentsync.errors import (
AgentSyncError,
AuthError,
AuthRequiredError,
ConfigError,
LockHeldError,
ManifestSchemaError,
)
from agentsync.graph.auth import TokenProvider
from agentsync.graph.errors import AuthBlockedError
from agentsync.loop import NO_NEXT_HINT_ENV
from agentsync.manifest import Manifest
from agentsync.model import CycleMode, CycleReport, LintFinding, SourceKind, Verdict
from agentsync.ops import doctor, launchd
from agentsync.ops.lock import SingleWriterLock, read_heartbeat
from agentsync.paths import DocsLayout, default_config_path, expand, is_under, provider_link_resolved
from agentsync.publish import Publisher, archive_path
from agentsync.slug import collision_key
from agentsync.text import plural
EXIT_OK = 0
EXIT_FAILED = 1 # a source failed, or a blocking lint or curate finding fired
EXIT_USAGE = 2
EXIT_LOCK_HELD = 75 # EX_TEMPFAIL: another cycle holds the lock; logged "skipped: lock held by <holder>"
EXIT_REAUTH = 77 # EX_NOPERM: auth REAUTH_REQUIRED
EXIT_CONFIG = 78 # EX_CONFIG: sources.toml invalid
EXIT_STATE = 65 # EX_DATAERR: the manifest is no database or a damaged one (doctor's state_dir.manifest)
EXIT_TCC_PENDING = launchd.EXIT_TCC_PENDING # 79: only from the signed launcher that wraps a LaunchAgent run
# Commands by their full path, which works with ~/.local/bin off PATH (B13 round 6 G79, as §16.51 Q49); the
# usage line keeps prog="agentsync".
_EPILOG = f"""\
exit codes:
0 ok
1 failed: a source failed, a blocking lint fired, curate found a blocking finding, a status check
failed, a purge/compaction was not verified, or discovery was incomplete (curate rows are not a failure)
2 usage error (bad arguments)
65 the state file (manifest.sqlite) is no database or a damaged one: the person's to fix (the message
names the file and the fix; `{loop.BIN} status` prints it as state_dir.manifest)
75 skipped: another agentsync cycle holds the single-writer lock (EX_TEMPFAIL; launchd retries later);
`sync` (not a LaunchAgent's run) first waits up to 10 minutes for it
77 sign-in required: a Graph source needs `{loop.BIN} graph login` (auth REAUTH_REQUIRED),
or Entra blocked sign-in (blocked: device|policy|consent|assignment, config-invalid; the message
names the fix)
78 configuration invalid: sources.toml or policy.toml is missing or wrong (the message names the key)
79 (LaunchAgent runs only) TCC_PENDING: the signed launcher's canary or watchdog timed out waiting for a
macOS privacy prompt; the cycle never ran or was stopped (see the job's .err.log,
`{loop.BIN} status`)
files: ~/agent-context/sources.toml (config) · ~/agent-context/docs (the docs git repo) ·
~/Library/Application Support/agentsync (manifest, lock, heartbeat, governance/) · ~/Library/Caches/agentsync
"""
_log = logging.getLogger("agentsync.cli")
_TCC_TOKENS = ("TCC_PENDING", "TCC_DENIED")
Handler = Callable[[argparse.Namespace], int]
def _out(text: str = "") -> None:
sys.stdout.write(text + "\n")
def _err(text: str) -> None:
# stdout first: in a pipe it is block-buffered and stderr is not, so a line printed before an error
# landed after it (B13 round 11 M26)
with contextlib.suppress(OSError, ValueError):
sys.stdout.flush()
sys.stderr.write(text + "\n")
# ---------------------------------------------------------------------------------------------------------
# parser
# ---------------------------------------------------------------------------------------------------------
def _common(sub_default: object) -> argparse.ArgumentParser:
"""--config / -v, accepted before or after the subcommand. KISS K18: --config (another sources.toml,
default ~/agent-context/sources.toml) still parses but is hidden from help."""
p = argparse.ArgumentParser(add_help=False)
p.add_argument("--config", type=Path, default=sub_default, metavar="PATH", help=argparse.SUPPRESS)
p.add_argument(
"-v", "--verbose", action="count", default=sub_default, help="more logging (-v info, -vv debug)"
)
return p
def _graph_options(p: argparse.ArgumentParser) -> None:
# KISS K18: --device-code (login: go straight to device-code sign-in, refused unless [graph]
# allow_device_code = true) still works but is hidden: it is the only probe for Conditional Access.
p.add_argument("--device-code", action="store_true", help=argparse.SUPPRESS)
p.add_argument(
"--url",
action="append",
default=[],
metavar="URL",
help="discover: resolve this SharePoint/OneDrive site or sharing link instead (repeatable)",
)
p.add_argument("--toml", action="store_true", help="discover: print only the sources.toml snippet")
def build_parser() -> argparse.ArgumentParser:
"""Return the argparse parser for every subcommand."""
parser = argparse.ArgumentParser(
prog="agentsync",
description="Keep an agent-readable docs/ git repo in sync with OneDrive/SharePoint/Outlook/Teams "
"and local sync-client folders, processing only what changed.",
epilog=_EPILOG,
formatter_class=argparse.RawDescriptionHelpFormatter,
parents=[_common(None)],
)
parser.add_argument("--version", action="version", version=f"agentsync {__version__}")
common = _common(argparse.SUPPRESS)
sub = parser.add_subparsers(dest="command", metavar="COMMAND")
def add(name: str, help_text: str, handler: Handler, *, hidden: bool = False) -> argparse.ArgumentParser:
kwargs: dict[str, Any] = {
"description": help_text,
"parents": [common],
"epilog": _EPILOG,
"formatter_class": argparse.RawDescriptionHelpFormatter,
}
# A hidden command gets no ``help=``: argparse then lists no entry for it (``help=SUPPRESS`` would
# print "==SUPPRESS==" on Python 3.11), yet it still parses.
p = sub.add_parser(name, **kwargs) if hidden else sub.add_parser(name, help=help_text, **kwargs)
p.set_defaults(handler=handler)
return p
add(
"init",
"create whatever is missing of sources.toml, the docs repo (no remote), its scaffold, the inbox and "
"the state dir (idempotent; add-source does the same and adds a folder)",
_cmd_init,
hidden=True,
)
p = add(
"add-source",
"sync a folder: append a live local source for it, creating whatever is missing of sources.toml, the "
"docs repo (no remote), its scaffold, the inbox and the state dir (idempotent)",
_cmd_add_source,
)
p.add_argument("path", type=Path, metavar="PATH", help="the folder to sync (it must exist)")
p = add("sync", "run one sync cycle (what the launchd agents run)", _cmd_sync)
# KISS K13b: sync takes no visible option. --once (a no-op: one cycle is the default), --mode (the launchd
# agents' poll | reconcile; dry_run classifies only) and --materialise-budget BYTES (a download budget
# per source for this run only; 0, install.sh's first sync, converts every local file and downloads
# nothing) still parse; --dry-run and --source are deleted.
p.add_argument("--once", action="store_true", help=argparse.SUPPRESS)
p.add_argument("--mode", choices=[m.value for m in CycleMode], default=None, help=argparse.SUPPRESS)
p.add_argument("--materialise-budget", metavar="BYTES", help=argparse.SUPPRESS)
p = add(
"accept-deletions",
"the deletion is real: clear SOURCE's tripped deletion breaker and apply its removals (a pass "
"that does not list SOURCE in full applies none and keeps the breaker)",
_cmd_accept_deletions,
)
p.add_argument("source", metavar="SOURCE", help="the source id the breaker tripped on")
p = add(
"exclude-empty",
"add SOURCE's empty cloud folders, those holding no mirrored file, to its exclude in sources.toml "
"(the empty-folder WAITING ON YOU line names this command)",
_cmd_exclude_empty,
hidden=True,
)
p.add_argument("source", metavar="SOURCE", help="the source id the WAITING ON YOU line names")
p = add(
"reconcile",
f"run one full-enumeration cycle (`{loop.BIN} sync` runs one when due)",
_cmd_reconcile,
hidden=True,
)
p.add_argument(
"--source", action="append", default=[], metavar="ID", help="only this source (repeatable)"
)
p.add_argument(
"--accept-deletions",
action="store_true",
help=f"old spelling of {loop.BIN} accept-deletions SOURCE (needs --source)",
)
add(
"status",
"the single read-only check: NEXT, the loop line, every preflight check with its fix (rc 1 on any "
"FAIL), then policy, holds, queued purges and each source",
_cmd_status,
)
add("doctor", f"renamed: run {loop.BIN} status", _cmd_status_renamed, hidden=True)
add(
"curate",
"the curation work list: every lint finding, mirror changes since the last checkpoint, the refresh "
"queue, then UNCOVERED mirror pages no curated page cites, then NEXT (rc 1 only on a blocking "
"finding)",
_cmd_curate,
)
for old_name in ("curate-queue", "lint", "refresh-queue"):
add(old_name, f"renamed: run {loop.BIN} curate", _cmd_curate_renamed, hidden=True)
add("checkpoint", "run sync (every sync records the checkpoint itself)", _cmd_checkpoint, hidden=True)
add(
"install-skill",
"write the Claude Code skill now (every sync already writes it)",
_cmd_install_skill,
hidden=True,
)
p = add(
"materialise",
"hydrate + convert named files (or pending work) within a byte budget",
_cmd_mat,
hidden=True,
)
p.add_argument(
"--budget", metavar="BYTES", help='byte budget for this run, e.g. "500MB" (default: config)'
)
p.add_argument("paths", nargs="*", type=Path, metavar="PATH", help="files inside a local/inbox source")
p = add("adopt", "copy an existing hand-made docs tree into topics/ as hand-written pages", _cmd_adopt)
p.add_argument("src_dir", type=Path, metavar="PATH")
add("migrate", "a no-op: every command migrates the manifest itself", _cmd_migrate, hidden=True)
# KISS K18: graph and its four top-level aliases are hidden (they still parse): on a zero-IT Mac they
# lead an agent into Entra errors it cannot fix, and published fix strings and docs keep working.
p = add("graph", "Microsoft Graph sign-in: login | logout | whoami | discover", _cmd_graph, hidden=True)
p.add_argument("action", choices=["login", "logout", "whoami", "discover"])
_graph_options(p)
for name, text in (
("login", "sign in to Microsoft Graph: broker, then browser (PKCE), then device code if allowed"),
("logout", "remove the cached Graph sign-in (same as `graph logout`)"),
("whoami", "show the cached Graph account and sign-in method, offline (same as `graph whoami`)"),
("discover", "propose sources.toml tables for every drive, site, channel, chat and mail folder"),
):
_graph_options(add(name, text, _cmd_graph, hidden=True))
sub.choices[name].set_defaults(action=name)
# KISS K11a: background sync is optional and operator-owned (docs/deploy), so both are hidden; the
# intervals come from sources.toml and the Time Machine exclusions always apply.
add(
"install-agent",
"install the poll + reconcile LaunchAgents (optional background sync; no admin rights)",
_cmd_install,
hidden=True,
)
add("uninstall-agent", "unload and remove both LaunchAgents", _cmd_uninstall, hidden=True)
p = add("purge", "remove items from the docs repo's whole history, cache and manifest", _cmd_purge)
p.add_argument(
"selector",
nargs="?",
metavar="SELECTOR",
help="id=<stable_id> | path=<source glob> | docs=<docs-repo glob>",
)
p.add_argument("--source", metavar="ID", help="only items of this source")
p.add_argument(
"--reason",
choices=[r.value for r in governance.PurgeReason],
default=governance.PurgeReason.OPERATOR.value,
help="recorded in the audit trail (default: operator)",
)
p.add_argument("--queue", action="store_true", help="run every queued purge instead of SELECTOR")
p.add_argument(
"--dry-run",
action="store_true",
help="report what would be purged; change nothing (an older manifest is still migrated first)",
)
p.add_argument("--push", action="store_true", help="force-push the rewrite to an allowed tenant remote")
p = add(
"compact-history",
"squash mirror history older than [governance] history_days",
_cmd_compact,
hidden=True,
)
p.add_argument("--keep-days", type=int, metavar="N", help=">= 1; default: [governance] history_days")
p.add_argument("--dry-run", action="store_true", help="report only")
p = add("hold", "legal/records hold: suspend purge and compaction for a scope", _cmd_hold)
p.add_argument("scope", nargs="?", metavar="SCOPE", help="'all' or a source id")
p.add_argument("--reason", help="why (required to set)")
p.add_argument("--owner", help="records/legal owner setting or releasing the hold")
p.add_argument("--release", action="store_true", help="release the hold on SCOPE")
p.add_argument("--list", action="store_true", help="list active holds")
p = add("offboard", "list (default) or remove every local copy agentsync made", _cmd_offboard)
p.add_argument("--purge-data", action="store_true", help="also remove the docs repo and sources.toml")
p.add_argument("--dry-run", action="store_true", help="list only (the default without --confirm)")
p.add_argument("--confirm", metavar="DOCS_REPO", help="the docs repo path: required to remove anything")
p = add("policy", f"renamed: run {loop.BIN} status", _cmd_status_renamed, hidden=True)
p.add_argument("action", choices=["show"])
p = add(
"setup-report",
f"write a redacted Markdown report of this Mac's setup to {setup_report.DEFAULT_OUT} (a summary, "
"the agent's friction log, environment, installer, doctor, status, background runs, recent errors) "
f"for the setup feedback loop; read-only, no network, under {setup_report.TIME_BUDGET_S:.0f} s",
_cmd_setup_report,
hidden=True,
)
# KISS K16a: --no-redact and --friction are deleted (the friction log is $AGENTSYNC_FRICTION_LOG, else the
# setup prompt's file); --out is hidden, install.sh passes it with its AGENTSYNC_SETUP_REPORT override.
p.add_argument("--out", type=Path, default=Path(setup_report.DEFAULT_OUT), help=argparse.SUPPRESS)
p = add(
"it-request",
"write the IT request (docs/deploy/it-request.md) as an email draft with this Mac's values filled in "
"and the fields still open listed first; never sends anything",
_cmd_it_request,
hidden=True,
)
p.add_argument(
"--out",
type=Path,
default=Path(it_request.DEFAULT_OUT),
metavar="PATH",
help=f"write the draft here, mode 0600 (default {it_request.DEFAULT_OUT}); never inside the "
"agentsync checkout or the docs repo",
)
return parser
# ---------------------------------------------------------------------------------------------------------
# helpers
# ---------------------------------------------------------------------------------------------------------
def _config(args: argparse.Namespace) -> Config:
path: Path | None = getattr(args, "config", None)
return load_config(path)
_OVER_BUDGET = "exceeds the per-cycle budget ("
# why the sync line's W files were withheld unread: the cause the stub kinds W holds share (B13 round 9 K33;
# round 10 L50: a binary .msg on this Mac is read, so it is in R, named by the split's K clause; round 13 O34:
# the comma, since "an image or a .msg not on this Mac" read as an image not on this Mac too)
_WITHHELD_WHY = "a file whose label cannot be read: an image, or a .msg not on this Mac"
def _print_report(report: CycleReport, *, run_budget: int | None = None) -> None:
"""Print a cycle's report, ending with one line for the whole run, ``converted N, deferred M online-only``
(N files read and converted, M online-only files left for a later run's download budget), then ``, read
again R`` when R files were read again for what their converter has gained (a re-read for a capability of
the same bytes is never in N; a no-converter stub's re-read is the first read of its bytes, so it is in N
as well, and `` (F of them a first read: a stub whose bytes had never been read, so also counted as
converted)`` says how many: B13 round 4 Q28; round 9 K34 reworded it, since "read for the first time",
said of files read again, said both things of the same files; when all R are first reads the head says so
instead, ``, first read R (stubs whose bytes had never been read, so also counted as converted)``, since
"read again" was false of every one: round 10 L34; round 10 L16 named the count both brackets are in; ``a
stub whose bytes ...`` for R = 1: round 11 M11),
then `` (of the converted: U unreadable, F failed, R refused)`` when some of the N are UNREADABLE stubs
(U), conversions that failed (F; §16.45 R2) or files refused after their bytes were read (R: a label rule,
a .msg whose label cannot be read; B13 round 6 G35, which also prints the split for F or R alone; an inbox
duplicate is quarantined, never in R: round 7 H49), with ``, K of them withheld by the label rule`` after
R when K of the R have a stub that says so (a binary .msg on this Mac, read and then refused: B13 round 10
L33), as ``; of the converted: ...`` after the Q28 clause, so two parentheses never stand side by side
(B13 round 5 F34), then ``; re-screened S for a rule change (also counted above, K of them unchanged)``: a
[policy] or secret-rule re-screen runs the converter on the same bytes, so it is in N, and counted again
in S (F35), then ``; Q refused without a read (no converter for the type, or a rule that needs no bytes)``
when Q files were refused with no byte read: those are in each source line's ``refused=`` but not in N, so
with R and W the line's refusals add up to the sources' (B13 round 7 H32). Before it, ``; W withheld
unread by the label rule (a file whose label cannot be read: an image, or a .msg not on this Mac)`` counts
the files refused with no byte read whose stub says a label rule withheld them, by the page's own test, so
K + W are the stubs that say so. They are not in Q (W and Q are disjoint), and R + W + Q add up to the
sources' ``refused=`` (B13 round 8 J29: the one clause named no label rule, so a withheld image read as a
type with no converter; round 9 K54). The parenthesis names the cause the stub kinds W holds share:
"without the file" was false for an image on this Mac (round 9 K33), and a binary .msg on this Mac is
never in W (round 10 L50). With ``run_budget`` (``sync --materialise-budget``) the
per-file "exceeds the per-cycle budget" alarms are
one count per source: at 0 every changed online-only file would otherwise get one."""
commit = report.commit_sha[:12] if report.commit_sha else "none (no content change)"
counted = plural(len(report.changes), "change") # a known count needs no "(s)" (B13 round 16 T32, T36)
if report.commit_sha and not report.changes:
counted += " (no source changed a mirror page; the commit holds other docs-repo files)"
_out(f"run {report.run_id} · mode {report.mode.value} · commit {commit} · {counted}")
for s in report.sources:
counts = ", ".join(
f"{k.value}={v}" + (f" ({s.new} new)" if k is Verdict.CHANGED and s.new else "")
for k, v in sorted(s.counts.items(), key=lambda kv: kv[0].value)
)
if s.pass_kind is None: # no listing this run: no completeness word, no cursor
bits = [f"skipped ({s.skipped_reason or '-'})"]
else:
bits = [s.pass_kind.value, "complete" if s.enumeration_complete else "INCOMPLETE"]
if s.deferred:
bits.append(f"{s.deferred} deferred")
if s.breaker_tripped:
bits.append("BREAKER TRIPPED")
# the counts line's deletion_candidate=N is the same on the marking and the removing pass: say which
if s.absent_marked:
bits.append(f"{plural(s.absent_marked, 'file')} marked absent")
if s.absent_removed:
# its pages are counted nowhere here (a workbook's sheets are pages of one file): "(s)" stays
bits.append(
f"{plural(s.absent_removed, 'file')} removed upstream "
f"({'its' if s.absent_removed == 1 else 'their'} page(s) are now deletion notice(s))"
)
if s.pass_kind is not None:
bits.append("cursor advanced" if s.cursor_advanced else "cursor held")
_out(f" {s.source_id}: {' · '.join(bits)}" + (f" · {counts}" if counts else ""))
over = [a for a in s.alarms if run_budget is not None and _OVER_BUDGET in a]
for a in s.alarms:
if a not in over:
_out(f" alarm: {a}")
if over:
_out(
f" {plural(len(over), 'online-only file')} left for a later run (over this run's "
f"--materialise-budget of {run_budget} bytes)"
)
for e in s.errors:
_out(f" error: {e}")
for f in report.lint_findings:
_out(f" {'BLOCKING' if f.blocking else 'warning'} {f.code} {f.path}: {f.message}")
if report.broke_stale_lock:
_out(" note: a stale lock from a dead run was broken; every source ran a full pass")
if report.auth_required:
_out(f" sign-in required: run `{loop.BIN} graph login` (errors above name any IT action)")
_print_checkpoint(report)
converted = sum(s.converted for s in report.sources)
online = sum(s.deferred_online_only for s in report.sources)
again = f", read again {report.read_again}" if report.read_again else ""
# No bare "converted" field: install.sh's awk adds the one after it ("converted)" is no such field), and
# no bare "again" in a bracket: R stays right after "read again" (B13 round 9 K34; setup_report reads
# both). Each bracket names the count it is in: "the count above" pointed at nothing in install.sh's
# one-line summary, and at "read again R" before it (B13 round 10 L16)
if report.read_again and report.read_first == report.read_again:
# all of them first reads: no "again" at all, and R right after "first read", which install.sh's awk
# and setup_report read as they read "read again R" (B13 round 10 L34)
what = "a stub whose bytes" if report.read_again == 1 else "stubs whose bytes" # B13 round 11 M11
again = f", first read {report.read_again} ({what} had never been read, so also counted as converted)"
elif report.read_again and report.read_first:
again += (
f" ({report.read_first} of them a first read: a stub whose bytes had never been read, so also "
"counted as converted)"
)
unreadable = sum(s.unreadable for s in report.sources)
failed = sum(s.conversion_failed for s in report.sources)
refused = sum(s.refused for s in report.sources)
# last, so install.sh's and setup-report's "converted N, deferred M online-only" patterns still match
of_them = ""
if unreadable or failed or refused:
# refused after failed, so an older reader's "U unreadable, F failed" still matches
split = f"of the converted: {unreadable} unreadable, {failed} failed, {refused} refused"
# no bracket of its own, so the split stays one parenthesis (B13 round 10 L33)
if withheld_read := sum(s.withheld_read for s in report.sources):
split += f", {withheld_read} of them withheld by the label rule"
of_them = f"; {split}" if report.read_again and report.read_first else f" ({split})"
# No bare "converted", "deferred" or "read again" in it: install.sh's awk adds the number after each.
rescreened = (
f"; re-screened {report.rescreened} for a rule change (also counted above, "
f"{report.rescreened_unchanged} of them unchanged)"
if report.rescreened
else ""
)
# No bare "converted", "deferred" or "read again" in it either, and nothing when Q is 0 (B13 round 7 H32).
# A file whose stub says a label rule withheld it is counted apart, by the page's own test, so the line
# names the cause its page names (B13 round 8 J29), the one an image, and a .msg not on this Mac, share
# (round 9 K33; round 10 L50); setup_report reads only the prefix up to "label rule".
withheld = sum(s.withheld_unread for s in report.sources)
unread = sum(s.refused_unread for s in report.sources)
unread_tail = "".join(
f"; {n} {what}"
for n, what in (
(withheld, f"withheld unread by the label rule ({_WITHHELD_WHY})"),
(unread, "refused without a read (no converter for the type, or a rule that needs no bytes)"),
)
if n
)
_out(f"converted {converted}, deferred {online} online-only{again}{of_them}{rescreened}{unread_tail}")
def _print_checkpoint(report: CycleReport) -> None:
"""KISS K06: one line on the automatic checkpoint when this run had session topic pages (nothing
when not); a held checkpoint names every error that holds it."""
if report.checkpoint == "advanced":
_out(
f"checkpoint advanced: curated at {report.checkpoint_detail[:12]}; the next curate lists mirror "
"changes since here"
)
if report.snapshot_tag is not None:
tag = report.snapshot_tag
_out(f" snapshot {tag}: a permanent tag; read a past page with git show {tag}:<path>")
elif report.checkpoint == "held":
held = len(report.checkpoint_blockers)
_out(
f"checkpoint held: {plural(held, 'curation error')}; {'fix it' if held == 1 else 'fix them'}, "
"then sync again (every sync retries it)"
)
for f in report.checkpoint_blockers:
_out(f" ERROR {f.code} {f.path}: {f.message}")
elif report.checkpoint == "failed":
_out(
f"checkpoint not recorded (the sync itself landed; the next sync retries it): "
f"{report.checkpoint_detail}"
)
class _HeldAlarms(logging.Filter):
"""Holds back the records :data:`ECHOED_ALARM` or :data:`ECHOED_WHEN` marks, whose words the run's
report prints; :meth:`log` logs the ones it did not print, once the filter is off."""
def __init__(self, handlers: Sequence[logging.Handler]) -> None:
super().__init__()
self.handlers = list(handlers)
self.held: list[logging.LogRecord] = []
def filter(self, record: logging.LogRecord) -> bool:
if getattr(record, ECHOED_ALARM, False) or getattr(record, ECHOED_WHEN, None):
self.held.append(record)
return False
return True
def log(self, records: Sequence[logging.LogRecord]) -> None:
for record in records:
for h in self.handlers:
if record.levelno >= h.level:
h.handle(record)
def _printed(record: logging.LogRecord, report: CycleReport) -> bool:
"""Whether ``report`` prints what a held ``record`` says: an arm_local alarm always does; a
:data:`ECHOED_WHEN` record only when its alarm line, its held checkpoint or its re-screen count is
in this report (B13 round 16 T33, T56: never hidden when the report leaves it out)."""
when = getattr(record, ECHOED_WHEN, None)
if when == "alarm":
return any(record.getMessage() in s.alarms for s in report.sources)
if when == "checkpoint":
return report.checkpoint == "held"
if when == "rescreen": # re-screened this run, none of the [policy] change's files still waiting
return report.rescreened > 0 and report.rescreen_left == 0
return bool(getattr(record, ECHOED_ALARM, False))
@contextlib.contextmanager
def _alarms_in_the_report(config: Config) -> Iterator[_HeldAlarms | None]:
"""A run that prints its own report drops the WARNING its alarms were logged with from agentsync's stderr
handler, since each one prints as that source's alarm line (B13 round 15 S2, S13), and holds back the
cycle's WARNINGs whose words the report may print (OCR or media helper down, a held checkpoint, a
[policy] re-screen; round 16 T33, T56), which the caller logs with :func:`_printed` once it has the
report. The LaunchAgent's job keeps them all: its stderr is the err.log the setup report's Recent errors
reads, which no alarm line on its out.log matches (None is yielded). A cycle that raises prints no
report, so the held records are logged then."""
handlers = [h for h in logging.getLogger().handlers if getattr(h, "_agentsync", False)]
if not handlers or launchd.started_by_our_job(config):
yield None
return
held = _HeldAlarms(handlers)
for h in handlers:
h.addFilter(held)
try:
yield held
except BaseException:
for h in handlers:
h.removeFilter(held)
held.log(held.held)
raise
finally:
for h in handlers:
h.removeFilter(held)
class StateUnreadableError(AgentSyncError):
"""The manifest is no database or a damaged one (``doctor.manifest_unreadable``): exit 65, one line."""
@contextlib.contextmanager
def _state_readable(config: Config) -> Iterator[None]:
"""A database error whose cause is the manifest itself, no database or a damaged one, becomes one line
naming the file and the person's fix (exit 65), never a traceback; init and add-source then stop where
install.sh names the owner, not "fix the error above, then re-run" (B13 round 16 T12). A locked or busy
database is raised as it was."""
try:
yield
except sqlite3.DatabaseError as exc:
# the manifest is the one database these commands open: its own NOTADB or CORRUPT, or one the
# read-only probe finds, names it (damage under a table shows only when a command reads that table)
db = expand(config.state_paths.db)
if not doctor.unreadable_code(exc) and doctor.manifest_unreadable(db) is None:
raise
raise StateUnreadableError(f"{db} cannot be read: {exc}") from exc
def _run(config: Config, **kwargs: object) -> int:
with _alarms_in_the_report(config) as held, _state_readable(config):
report = run_cycle(config, **kwargs) # type: ignore[arg-type]
if held is not None:
held.log([r for r in held.held if not _printed(r, report)])
budget = kwargs.get("budget_bytes")
_print_report(report, run_budget=budget if isinstance(budget, int) else None)
if kwargs.get("mode") is not CycleMode.DRY_RUN and report.exit_code in (EXIT_OK, EXIT_FAILED):
# C15 req 42 outside install-agent: exclude mirror/, .git, the cache and the manifest from Time
# Machine once they exist (a cheap xattr check; tmutil runs only for a path still missing it).
try:
for line in governance.ensure_time_machine_exclusions(config):
_log.warning("time machine: %s", line)
except (OSError, AgentSyncError) as exc:
_log.warning("time machine exclusions not applied: %s", exc)
return report.exit_code
def _owner_only_dirs(config: Config) -> list[Path]:
"""Directories that hold tenant data and must not be group/world readable (existing ones). A cache,
log or state folder that is the home folder, or holds it, is not one of them, in any spelling: the
sync leaves it as it is, and so does setup (:func:`agentsync.cycle._holds_home`)."""
named = (expand(config.cache_dir), expand(config.log_dir), expand(config.state_dir))
candidates = [
expand(config.docs_repo),
expand(config.docs_repo) / ".git",
*(d for d in named if not _holds_home(d)),
]
home_ctx = expand(config.config_path).parent
if home_ctx != Path.home() and home_ctx in expand(config.docs_repo).parents:
candidates.insert(0, home_ctx)
return [d for d in candidates if d.is_dir() and not d.is_symlink()]
def _refuse_remotes(config: Config, gov: governance.GovernanceConfig) -> list[str]:
"""C15 req 36: the docs repo has no remote unless [governance] names a tenant-owned one."""
if not (expand(config.docs_repo) / ".git").exists():
return []
return governance.remote_policy_findings(config.docs_repo, gov)
# ---------------------------------------------------------------------------------------------------------
# commands
# ---------------------------------------------------------------------------------------------------------
def _write_config(cfg_path: Path, text: str) -> None:
"""Write a new sources.toml (0600), its folder included."""
cfg_path.parent.mkdir(parents=True, exist_ok=True)
cfg_path.write_text(text, encoding="utf-8")
cfg_path.chmod(0o600)
_out(f"wrote {cfg_path}")
def _ensure_setup(config: Config) -> int:
"""Create whatever is missing for ``config`` (KISS K14, shared by init and add-source): the inbox, the
docs repo (no remote) and its scaffold, the state dir, owner-only modes, the Time Machine exclusions.
Exit 1 when the docs repo has a remote [governance] does not allow (C15 req 36), else 0."""
config = _ensure_inbox(config)
gov = governance.load_governance(config.config_path)
created = gitops.ensure_repo(config.docs_repo)
config.state_dir.mkdir(parents=True, exist_ok=True, mode=0o700)
for d in _owner_only_dirs(config):
mode = d.stat().st_mode & 0o777
if mode & 0o077:
d.chmod(0o700)
_out(f"tightened {d} to 0700 (was {mode:04o}): it holds tenant data")
# What is inside them too, as every sync does: install.sh runs status right after this command and
# stops on a docs_repo.permissions FAIL, so the paths a sync would clear are cleared here first.
inside = _tighten_own_paths(config)
if inside:
_out(
f"tightened {plural(inside, 'path')} inside the docs repo, the cache or the logs: "
f"{'it holds' if inside == 1 else 'they hold'} tenant data"
)
with _state_readable(config), Manifest(config.state_paths.db) as manifest:
written = Publisher(config, manifest).ensure_scaffold()
# The count carries its verb: install.sh calls add-source once per folder, and a bare "0 scaffold
# file(s)" on the second call read as the first call's files undone. One is "1 scaffold file" (B13
# round 14 Q39).
scaffold = f"{plural(len(written), 'scaffold file')} written" if written else "scaffold up to date"
_out(f"docs repo {config.docs_repo} ({'created' if created else 'exists'}, no remote; {scaffold})")
findings = _refuse_remotes(config, gov)
for f in findings:
_err(f"governance: {f}")
for line in governance.ensure_time_machine_exclusions(config):
_out(f"time machine: {line}")
if any(s.kind is not SourceKind.INBOX for s in config.sources):
_out(f"sources: {', '.join(s.id for s in config.sources)}")
elif config.sources: # an inbox is not a source to sync (KISS K05): point at the one verb that adds one
# a Mac may hold hand-added inbox sources too: they are counted and named (B13 round 11 M13), after a
# colon, so the line has no two brackets side by side (round 12 N13)
inbox = [s.id for s in config.sources]
besides = "the inbox" if len(inbox) == 1 else f"{len(inbox)} inbox sources: {', '.join(inbox)}"
_out(f"sources: no folder yet besides {besides}{_add_folder_hint()}")
else:
_out(f"sources: none yet{_add_folder_hint()}")
return EXIT_FAILED if findings else EXIT_OK
def _add_folder_hint() -> str:
"""How the no-folder sources line ends: the command that adds a folder, for a bare run; nothing under
scripts/install.sh (:data:`NO_NEXT_HINT_ENV` is 1 there), whose NEXT line names its own re-run with
``--source-local``, so step 2 never gives two commands for one step (B13 round 13 O17: the prompt says not
to use add-source)."""
if os.environ.get(NO_NEXT_HINT_ENV, "").strip() == "1":
return ""
return f"; run {loop.BIN} add-source <folder>"
def _cmd_init(args: argparse.Namespace) -> int:
"""Hidden since KISS K14 (add-source does the same and adds a folder): idempotent, no options."""
cfg_path = expand(args.config or default_config_path())
if cfg_path.exists():
# loaded first: a config that fails to load is named by its error, never announced as in use
# (B13 round 11 M26)
config = load_config(cfg_path)
_out(f"using existing {cfg_path}")
else:
text = default_config_text()
config = parse_config(text, config_path=cfg_path) # validate before writing anything
_write_config(cfg_path, text)
return _ensure_setup(config)
def _ensure_inbox(config: Config) -> Config:
""":func:`agentsync.config.ensure_inbox` for init and add-source (KISS K05): prints the inbox it added.
An inbox that cannot be added is a warning, never a failure of the command that asked for more."""
try:
config, added = ensure_inbox(config.config_path)
except (ConfigError, OSError) as exc:
_err(f"inbox: not added: {exc}")
return config
if added is not None and added.path is not None:
# The path is stored resolved (canonical_source_root: how a OneDrive link reaches the CloudStorage
# checks), so a home reached through a link stores /private/tmp/... beside a docs repo and config
# printed as /tmp/...: the line leads with the form the other lines use and names what is stored
# (B13 round 4 Q36).
typed = expand(config.docs_repo).parent / "inbox"
shown = f"{added.path}" if typed == added.path else f"{typed}, stored as {added.path}"
_out(f"added inbox source {added.id!r} ({shown}): drop files you save by hand here")
return config
def _same_folder(configured: Path, path: Path) -> bool:
"""Whether ``path`` (an existing folder) is the folder a source already has as ``configured``. macOS
takes a name in any case and in either Unicode form for the same folder, so a path typed back in lower
case, or with a composed é where the disk holds e and an accent, is not a second folder. The key is the
one the manifest and the docs repo use for "the same path" (:func:`agentsync.slug.collision_key`); the
file system then confirms it, so on a case-sensitive volume two folders that differ only in case stay
two (and a configured folder that is gone is not the one that exists). A folder stored through a link
that is a provider entry in ~/Library/CloudStorage (``OneDrive-Link -> OneDrive-Contoso``) is compared
by its real name, read with one readlink of that entry (:func:`paths.provider_link_resolved`, B13 round
6 G39), so typing it by that name is not a second folder."""
if configured == path:
return True
keys = [collision_key(str(provider_link_resolved(p))) for p in (configured, path)]
if keys[0] != keys[1]:
return False
try:
return configured.samefile(path)
except OSError:
return False
def _cmd_add_source(args: argparse.Namespace) -> int:
"""KISS K14: the one setup verb. Validates PATH before writing anything; a missing sources.toml is
written from the template with the folder's table; then :func:`_ensure_setup` creates the rest. A
folder a source already has, in any spelling macOS takes for it (:func:`_same_folder`), is left as it
is."""
cfg_path = expand(args.config or default_config_path())
fresh = not cfg_path.exists()
template = default_config_text()
# A broken sources.toml exits 78 before anything is written; a missing one is checked as the template.
config = parse_config(template, config_path=cfg_path) if fresh else load_config(cfg_path)
raw: Path = args.path
path = canonical_source_root(expand(raw)) # a symlinked cloud root stays protected
if not path.exists():
_err(f"add-source {raw}: no such folder")
return EXIT_USAGE
if not path.is_dir():
_err(f"add-source {raw}: not a directory")
return EXIT_USAGE
docs = expand(config.docs_repo)
# Compared as written and canonical: the source path is canonical, docs_repo is not (e.g. /var vs
# /private/var, or a symlinked ~/agent-context).
if any(is_under(path, d) or is_under(d, path) for d in {docs, canonical_source_root(docs)}):
_err(f"add-source {raw}: {path} and the docs repo {docs} must not contain each other")
return EXIT_USAGE
# PATH is the inbox folder of a config with no inbox (one from before K05): the inbox first, so that
# folder becomes kind "inbox", never a local source install.sh would count as a folder to sync.
if path == canonical_source_root(docs.parent / "inbox") and not any(
s.kind is SourceKind.INBOX for s in config.sources
):
if fresh:
_write_config(cfg_path, template)
fresh = False
config = _ensure_inbox(config)
known = next((s for s in config.sources if s.path is not None and _same_folder(s.path, path)), None)
typed = expand(raw)
typed = typed if typed.is_absolute() else Path.cwd() / typed
if known is not None:
# The folder as typed when it is not the stored path (a provider link, another case or Unicode form,
# /tmp as /private/tmp), so the line says why two paths are one folder; after the config path, which
# "has path <stored> in " ends with, and naming no cause, since several reach here (B13 round 8 J35).
same = "" if typed == known.path else f": {typed} is the same folder by another name or path"
_out(
f"already configured: source {known.id!r} ({known.kind.value}, {known.state.value}) has path "
f"{known.path} in {config.config_path}{same}"
)
else:
sid = derive_source_id(path, {s.id for s in config.sources})
table = local_source_table(sid, path)
try:
if fresh:
text = template.rstrip("\n") + "\n" + table
config = parse_config(text, config_path=cfg_path) # validate before writing anything
_write_config(cfg_path, text)
else:
config = append_to_config(config.config_path, table) # validated before anything is written
except ConfigError as exc:
_err(f"add-source {raw}: refused, sources.toml would not load: {exc}")
return EXIT_USAGE
# The folder as typed when the stored form differs (a link resolved, /tmp as /private/tmp), as the
# inbox line says it (Q36; B13 round 5 F49): the table below names only the stored one.
note = "" if typed == path else f" ({typed}, stored as {path})"
_out(f"added source {sid!r} to {config.config_path}{note}:")
_out(table.strip("\n"))
return _ensure_setup(config)
def _cmd_sync(args: argparse.Namespace) -> int:
"""One cycle; without ``--mode`` (an agent's or a person's run, never a LaunchAgent's) the report ends
with the loop's NEXT and WAITING ON YOU lines, unless :data:`NO_NEXT_HINT_ENV` is 1 (KISS K01)."""
config = _config(args)
mode = CycleMode(args.mode) if args.mode else None
if args.materialise_budget is None:
rc = _run(config, mode=mode)
else:
budget = parse_size(args.materialise_budget, where="--materialise-budget")
rc = _run(config, mode=mode, budget_bytes=budget)
if mode is None and os.environ.get(NO_NEXT_HINT_ENV, "").strip() != "1":
for line in loop.next_lines(config):
_out(line)
return rc
def _cmd_reconcile(args: argparse.Namespace) -> int:
config = _config(args)
if args.accept_deletions and not args.source:
_err(f"--accept-deletions needs a source: run {loop.BIN} accept-deletions SOURCE")
return EXIT_USAGE
accept = tuple(args.source) if args.accept_deletions else ()
return _run(
config,
mode=CycleMode.RECONCILE,
only=tuple(args.source),
accept_deletions=accept,
recordings="none", # an operator's run, which a tool's timeout can end: it reads no recording
)
def _cmd_accept_deletions(args: argparse.Namespace) -> int:
"""The operator asserts SOURCE's absent files really were deleted: a RECONCILE of that source alone that
clears its breaker and applies the held removals (the breaker itself is unchanged). A pass that leaves a
known file unlisted confirms no absence: it applies no deletion, keeps the breaker and says so. Like
interactive sync it waits for a running cycle's lock: launchd never re-runs an operator's assertion after
exit 75."""
config = _config(args)
return _run(
config,
mode=CycleMode.RECONCILE,
only=(args.source,),
accept_deletions=(args.source,),
wait_for_lock=True,
recordings="none",
)
def _cmd_exclude_empty(args: argparse.Namespace) -> int:
"""Add SOURCE's empty cloud folders to its ``exclude`` in sources.toml (B13 round 4 Q71): the folders its
last walk stored as zero-child (manifest meta, never a folder read here) that today's exclude does not
prune and that hold no mirrored file, all of them, each as ``/<path>/``. A folder that held mirrored
files is left as it is: excluding it would retire its pages at once, with no deletion check. The file is
edited as text and checked before it is written (:func:`config.set_source_exclude`); under the cycle's
lock, as an interactive sync waits for it. Nothing to exclude exits 0; a refused edit prints the line to
paste instead and exits 78. sources.toml is read again once the lock is held, and the write refuses an
``exclude`` that changed after that read (B13 round 5 F70)."""
config = _config(args)
src = _exclude_empty_source(config, args.source)
if src is None:
return EXIT_USAGE
where = loop._shown(config.config_path)
db = config.state_paths.db
if not db.is_file():
_out(f"exclude-empty {src.id}: nothing to exclude: no sync has stored an empty cloud folder yet")
return EXIT_OK
lock = SingleWriterLock(config.state_paths.lock, "exclude-empty")
_acquire_waiting(lock, INTERACTIVE_LOCK_WAIT_S)
try:
# the wait can be minutes: an exclude edited by hand meanwhile is read again, not written over (F70)
try:
config = load_config(config.config_path)
except ConfigError as exc:
_err(f"exclude-empty {args.source}: sources.toml does not load: {exc}")
return EXIT_CONFIG
src = _exclude_empty_source(config, args.source)
if src is None:
return EXIT_USAGE
with Manifest(db) as manifest:
found = loop._empty_dirs(manifest, src)
below = found.below
# A folder's glob that would also prune a folder holding mirrored files (a "[" is written as
# "?") is left as well: excluding that folder would retire its pages at once. The loop's wait
# names this command by the same rule (B13 round 5 F65).
clear, collides = loop._excludable(found)
gone = len(below) - len(clear)
left = "it" if gone == 1 else "them" # B13 round 12 N40: by the count, as the line's own folders
# the alarm is from the walk before this exclude (or one by hand since): it names folders now excluded
# (B13 round 15 S32), so the pointer says so, as the loop's waits do
since = bool(clear) or len(below) < found.stored
if found.stored > 5:
# past five the alarm names five and how to list the rest (B13 round 14 Q41's rule), and the left
# folder may be among the rest: the loop's own words, as its gone wait says (round 15 S42: "names
# it, up to five" of a folder the alarm does not name)
left = loop._alarm_names("the folders", found.stored)
# Each cause in its own words, with its own count, as the loop's waits say them (B13 round 16 T38: one
# hedge, "held file(s) ..., or its exclude would also match ...", for both); noun, verb and pronoun
# by the count (B13 round 14 Q42, Q57). The gone folders' files are summed: theirs may differ.
kept = [d for d, n in below.items() if n]
parts: list[str] = []