filesweep-cli 3.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
sweep.py ADDED
@@ -0,0 +1,1782 @@
1
+ """Sweep: safe, reversible Windows command-line file organiser."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import ctypes
7
+ from ctypes import wintypes
8
+ from dataclasses import dataclass
9
+ from datetime import datetime, timezone
10
+ import importlib.metadata
11
+ import io
12
+ import json
13
+ import os
14
+ from pathlib import Path
15
+ import re
16
+ import shutil
17
+ import sys
18
+ import tempfile
19
+ import uuid
20
+
21
+ from clustering import (
22
+ CandidateCluster,
23
+ FOLDER_PROJECT_MARKERS,
24
+ PROJECT_MARKER_EXTS,
25
+ apply_clusters_to_plan,
26
+ build_existing_folder_index,
27
+ detect_folder_project_marker,
28
+ discover_clusters,
29
+ is_cloud_sync_folder_name,
30
+ match_existing_folder,
31
+ normalise_kebab_filename,
32
+ normalise_kebab_folder_name,
33
+ normalise_kebab_stem,
34
+ validate_folder_name,
35
+ )
36
+
37
+ SHORTCUT_EXTENSIONS = frozenset({".lnk", ".url", ".ini"})
38
+ EXCLUDED_EXTENSIONS = SHORTCUT_EXTENSIONS | frozenset({".rdp", ".key", ".pem"})
39
+ PARTIAL_EXTENSIONS = frozenset({".crdownload", ".part", ".tmp", ".opdownload"})
40
+ PROJECT_MARKER_FILES = frozenset({"pyproject.toml", "package.json"})
41
+ MIN_AGE_SECONDS = 24 * 60 * 60
42
+
43
+ FILE_ATTRIBUTE_OFFLINE = 0x00001000
44
+ FILE_ATTRIBUTE_RECALL_ON_DATA_ACCESS = 0x00400000
45
+ CLOUD_PLACEHOLDER_MASK = FILE_ATTRIBUTE_OFFLINE | FILE_ATTRIBUTE_RECALL_ON_DATA_ACCESS
46
+ INVALID_FILE_ATTRIBUTES = 0xFFFFFFFF
47
+
48
+ GENERIC_READ = 0x80000000
49
+ OPEN_EXISTING = 3
50
+ FILE_ATTRIBUTE_NORMAL = 0x00000080
51
+ FILE_FLAG_BACKUP_SEMANTICS = 0x02000000
52
+ LOCK_ERROR_CODES = frozenset({5, 32, 33})
53
+
54
+ _kernel32 = ctypes.WinDLL("kernel32", use_last_error=True)
55
+ _kernel32.GetFileAttributesW.argtypes = [wintypes.LPCWSTR]
56
+ _kernel32.GetFileAttributesW.restype = wintypes.DWORD
57
+ _kernel32.CreateFileW.argtypes = [
58
+ wintypes.LPCWSTR, wintypes.DWORD, wintypes.DWORD, wintypes.LPVOID,
59
+ wintypes.DWORD, wintypes.DWORD, wintypes.HANDLE,
60
+ ]
61
+ _kernel32.CreateFileW.restype = wintypes.HANDLE
62
+ _kernel32.CloseHandle.argtypes = [wintypes.HANDLE]
63
+ _kernel32.CloseHandle.restype = wintypes.BOOL
64
+ INVALID_HANDLE_VALUE = wintypes.HANDLE(-1).value
65
+ FALLBACK_VERSION = "3.0.0"
66
+
67
+
68
+ def get_version() -> str:
69
+ """Return the installed package version or fallback version string."""
70
+ try:
71
+ return importlib.metadata.version("filesweep-cli")
72
+ except importlib.metadata.PackageNotFoundError:
73
+ return FALLBACK_VERSION
74
+
75
+
76
+ def utc_now_iso() -> str:
77
+ """Return the current UTC timestamp in ISO-8601 format."""
78
+ return datetime.now(timezone.utc).isoformat()
79
+
80
+
81
+ def user_profile_dir() -> Path:
82
+ """Return the current user's profile directory."""
83
+ env_profile = os.environ.get("USERPROFILE")
84
+ return Path(env_profile) if env_profile else Path.home()
85
+
86
+
87
+ def default_targets() -> list[Path]:
88
+ """Return the default v1 top-level folders to organise."""
89
+ profile = user_profile_dir()
90
+ return [profile / "Downloads", profile / "Desktop", profile / "Documents"]
91
+
92
+
93
+ def default_log_dir() -> Path:
94
+ """Return the default directory for write-ahead undo logs."""
95
+ return user_profile_dir() / ".sweep" / "logs"
96
+
97
+
98
+ def default_rules_path() -> Path:
99
+ """Return the default rules.json path alongside sweep.py."""
100
+ return Path(__file__).resolve().parent / "rules.json"
101
+
102
+
103
+ def _norm_path(path: Path) -> str:
104
+ return os.path.normcase(str(path.resolve(strict=False)))
105
+
106
+
107
+ def is_system_path(path: Path, allow_temp_subdir: bool = False) -> bool:
108
+ """Return True if path lies inside a protected Windows system directory."""
109
+ resolved = path.resolve(strict=False)
110
+ norm = _norm_path(resolved)
111
+ parts_lower = [part.lower() for part in resolved.parts]
112
+
113
+ always_blocked = [
114
+ os.environ.get("SystemRoot", r"C:\Windows"),
115
+ os.environ.get("WINDIR", r"C:\Windows"),
116
+ os.environ.get("ProgramFiles", r"C:\Program Files"),
117
+ os.environ.get("ProgramFiles(x86)", r"C:\Program Files (x86)"),
118
+ ]
119
+ for raw in always_blocked:
120
+ base = _norm_path(Path(raw))
121
+ if norm == base or norm.startswith(base + os.sep):
122
+ return True
123
+ if len(parts_lower) >= 2 and parts_lower[1] in {"windows", "program files", "program files (x86)"}:
124
+ return True
125
+
126
+ if allow_temp_subdir:
127
+ temp_base = _norm_path(Path(tempfile.gettempdir()))
128
+ if norm.startswith(temp_base + os.sep):
129
+ return False
130
+
131
+ if "appdata" in parts_lower:
132
+ return True
133
+ for env_key in ("APPDATA", "LOCALAPPDATA"):
134
+ raw = os.environ.get(env_key, "")
135
+ if raw:
136
+ base = _norm_path(Path(raw))
137
+ if norm == base or norm.startswith(base + os.sep):
138
+ return True
139
+ return False
140
+
141
+
142
+ def get_file_attributes(path: Path) -> int:
143
+ """Fetch Windows file attributes via GetFileAttributesW."""
144
+ return int(_kernel32.GetFileAttributesW(str(path)))
145
+
146
+
147
+ def is_cloud_placeholder(path: Path) -> bool:
148
+ """Return True for OneDrive cloud-only placeholder files."""
149
+ attrs = get_file_attributes(path)
150
+ return attrs != INVALID_FILE_ATTRIBUTES and bool(attrs & CLOUD_PLACEHOLDER_MASK)
151
+
152
+
153
+ def _is_path_locked(path: Path, flags: int) -> bool:
154
+ """Return True if another process holds a conflicting handle on path."""
155
+ handle = _kernel32.CreateFileW(
156
+ str(path), GENERIC_READ, 0, None, OPEN_EXISTING, flags, None
157
+ )
158
+ if handle == INVALID_HANDLE_VALUE:
159
+ return ctypes.get_last_error() in LOCK_ERROR_CODES
160
+ _kernel32.CloseHandle(handle)
161
+ return False
162
+
163
+
164
+ def is_file_locked(path: Path) -> bool:
165
+ """Return True if another process holds an open or conflicting handle on a file."""
166
+ return _is_path_locked(path, FILE_ATTRIBUTE_NORMAL)
167
+
168
+
169
+ def is_folder_locked(path: Path) -> bool:
170
+ """Return True if another process holds an open handle or working directory in path."""
171
+ return _is_path_locked(path, FILE_FLAG_BACKUP_SEMANTICS)
172
+
173
+
174
+ def detect_project_marker(target: Path) -> str | None:
175
+ """Return the first active project marker found directly inside target."""
176
+ try:
177
+ entries = sorted(os.scandir(target), key=lambda e: e.name.lower())
178
+ except OSError:
179
+ return None
180
+ for entry in entries:
181
+ lower = entry.name.lower()
182
+ if lower == ".git":
183
+ return entry.name
184
+ if entry.is_file(follow_symlinks=False):
185
+ if lower in PROJECT_MARKER_FILES or Path(lower).suffix in PROJECT_MARKER_EXTS:
186
+ return entry.name
187
+ return None
188
+
189
+
190
+ @dataclass(frozen=True)
191
+ class RuleSet:
192
+ """Ordered title-keyword and file-extension rules."""
193
+
194
+ title_rules: list[tuple[str, list[re.Pattern[str]]]]
195
+ ext_rules: list[tuple[str, list[str]]]
196
+
197
+
198
+ def _validate_folder_name(name: str, field_name: str) -> str:
199
+ return validate_folder_name(name, field_name)
200
+
201
+
202
+ def _collision_key(path: Path) -> str:
203
+ return os.path.normcase(str(path)).casefold()
204
+
205
+
206
+ def load_rules(rules_path: Path) -> RuleSet:
207
+ """Load ordered title and extension rules from a JSON file."""
208
+ data = json.loads(rules_path.read_text(encoding="utf-8"))
209
+ raw_ext = data.get("rules")
210
+ if not isinstance(raw_ext, list):
211
+ raise ValueError("rules.json must contain a 'rules' list.")
212
+
213
+ raw_title = data.get("title_rules", [])
214
+ if not isinstance(raw_title, list):
215
+ raise ValueError("rules.json 'title_rules' must be a list when present.")
216
+
217
+ title_rules: list[tuple[str, list[re.Pattern[str]]]] = []
218
+ for item in raw_title:
219
+ bucket = _validate_folder_name(str(item.get("bucket", item.get("category", ""))), "bucket")
220
+ patterns = []
221
+ for kw in item.get("keywords", []):
222
+ parts = [re.escape(part) for part in str(kw).strip().lower().split() if part]
223
+ if parts:
224
+ expr = r"[^a-z0-9]+".join(parts)
225
+ patterns.append(re.compile(rf"(?<![a-z0-9]){expr}(?![a-z0-9])", re.IGNORECASE))
226
+ title_rules.append((bucket, patterns))
227
+
228
+ ext_rules: list[tuple[str, list[str]]] = []
229
+ for item in raw_ext:
230
+ category = _validate_folder_name(str(item["category"]), "category")
231
+ exts = [
232
+ "*" if str(e).strip() == "*" else (f".{str(e).strip().lower().lstrip('.')}")
233
+ for e in item.get("extensions", [])
234
+ ]
235
+ ext_rules.append((category, exts))
236
+ return RuleSet(title_rules=title_rules, ext_rules=ext_rules)
237
+
238
+
239
+ def match_title_rule(path: Path, rules: RuleSet | list[tuple[str, list[str]]]) -> tuple[str | None, str]:
240
+ """Evaluate custom title_rules and return (bucket, rule_label) or (None, '-')."""
241
+ if isinstance(rules, RuleSet):
242
+ stem = path.stem
243
+ for bucket, patterns in rules.title_rules:
244
+ if any(pat.search(stem) for pat in patterns):
245
+ return bucket, f"Title: {bucket}"
246
+ return None, "-"
247
+
248
+
249
+ def match_ext_rule(path: Path, rules: RuleSet | list[tuple[str, list[str]]]) -> tuple[str | None, str]:
250
+ """Evaluate extension fallback rules and return (category, rule_label) or (None, '-')."""
251
+ ext_rules = rules.ext_rules if isinstance(rules, RuleSet) else rules
252
+ suffix = path.suffix.lower()
253
+ for category, extensions in ext_rules:
254
+ if "*" in extensions or (suffix and suffix in extensions):
255
+ return category, f"Ext: {category}"
256
+ return None, "-"
257
+
258
+
259
+ def match_rule(path: Path, rules: RuleSet | list[tuple[str, list[str]]]) -> tuple[str | None, str]:
260
+ """Return (destination_folder, rule_label) evaluating title rules before extensions."""
261
+ bucket, label = match_title_rule(path, rules)
262
+ if bucket is not None:
263
+ return bucket, label
264
+ return match_ext_rule(path, rules)
265
+
266
+
267
+ def _ignored_fallback_categories(rules: RuleSet | list[tuple[str, list[str]]]) -> set[str]:
268
+ """Return case-folded generic fallback category names from rules."""
269
+ ext_rules = rules.ext_rules if isinstance(rules, RuleSet) else rules
270
+ ignored: set[str] = set()
271
+ for category, _ in ext_rules:
272
+ ignored.add(category.casefold())
273
+ ignored.add(normalise_kebab_folder_name(category).casefold())
274
+ return ignored
275
+
276
+
277
+ def resolve_collision(
278
+ dest: Path, reserved: set[str], same_source: Path | None = None
279
+ ) -> Path:
280
+ """Return a non-colliding destination path using Windows-style numbering."""
281
+ source_key = _collision_key(same_source) if same_source is not None else None
282
+ candidate = dest
283
+ counter = 1
284
+ while (
285
+ _collision_key(candidate) in reserved
286
+ or (candidate.exists() and _collision_key(candidate) != source_key)
287
+ ):
288
+ candidate = dest.with_name(f"{dest.stem} ({counter}){dest.suffix}")
289
+ counter += 1
290
+ reserved.add(_collision_key(candidate))
291
+ return candidate
292
+
293
+
294
+ def write_json_atomic(path: Path, payload: dict) -> None:
295
+ """Atomically write JSON via a staging file without calling unlink."""
296
+ path.parent.mkdir(parents=True, exist_ok=True)
297
+ stage_path = path.with_suffix(".json.stage")
298
+ stage_path.write_text(json.dumps(payload, indent=2), encoding="utf-8")
299
+ os.replace(stage_path, path)
300
+
301
+
302
+ def _skip_record(src: Path, reason: str) -> dict:
303
+ return {
304
+ "source": str(src), "destination": "", "category": "",
305
+ "rule": "-", "status": "skipped", "reason": reason,
306
+ }
307
+
308
+
309
+ def _check_file_safety(
310
+ entry: os.DirEntry[str],
311
+ now_ts: float,
312
+ project_marker: str | None,
313
+ allow_temp_subdir: bool,
314
+ ) -> dict | None:
315
+ """Return a skip record if a file fails mandatory safety checks, else None."""
316
+ src = Path(entry.path)
317
+ if entry.is_symlink():
318
+ return _skip_record(src, "Symbolic link")
319
+ if src.name.startswith("~$"):
320
+ return _skip_record(src, "Temporary Microsoft Office file (~$)")
321
+ if project_marker is not None:
322
+ return _skip_record(src, f"Project-safe mode: marker '{project_marker}' present")
323
+ if is_system_path(src, allow_temp_subdir=allow_temp_subdir):
324
+ return _skip_record(src, "Protected system path")
325
+
326
+ ext = src.suffix.lower()
327
+ if ext in EXCLUDED_EXTENSIONS:
328
+ return _skip_record(src, f"Excluded file type ({ext})")
329
+ if ext in PARTIAL_EXTENSIONS:
330
+ return _skip_record(src, f"Partial download ({ext})")
331
+ # Check cloud attributes before opening any handle to avoid triggering hydration.
332
+ if is_cloud_placeholder(src):
333
+ return _skip_record(src, "OneDrive cloud-only placeholder")
334
+
335
+ try:
336
+ stat_result = entry.stat(follow_symlinks=False)
337
+ except OSError as exc:
338
+ return _skip_record(src, f"Unable to stat file: {exc}")
339
+
340
+ if (now_ts - stat_result.st_mtime) < MIN_AGE_SECONDS:
341
+ return _skip_record(src, "Modified within last 24 hours")
342
+ if is_file_locked(src):
343
+ return _skip_record(src, "File locked by another process")
344
+ return None
345
+
346
+
347
+ def _build_category_move(
348
+ src: Path,
349
+ target: Path,
350
+ category: str,
351
+ rule_label: str,
352
+ dest_name: str,
353
+ reserved: set[str],
354
+ canonical_folders: dict[tuple[str, str], str] | None,
355
+ kebab_case: bool,
356
+ ) -> dict:
357
+ """Build a planned category-folder move record with collision resolution."""
358
+ if kebab_case:
359
+ category = normalise_kebab_folder_name(category)
360
+ if canonical_folders is not None:
361
+ folder_key = (_collision_key(target), category.casefold())
362
+ category = canonical_folders.setdefault(folder_key, category)
363
+ planned_dest = resolve_collision(target / category / dest_name, reserved)
364
+ return {
365
+ "source": str(src), "destination": str(planned_dest),
366
+ "category": category, "rule": rule_label, "status": "planned",
367
+ "reason": "", "entry_type": "file",
368
+ }
369
+
370
+
371
+ def _evaluate_entry(
372
+ entry: os.DirEntry[str],
373
+ target: Path,
374
+ rules: RuleSet | list[tuple[str, list[str]]],
375
+ now_ts: float,
376
+ reserved: set[str],
377
+ project_marker: str | None,
378
+ allow_temp_subdir: bool,
379
+ canonical_folders: dict[tuple[str, str], str] | None = None,
380
+ kebab_case: bool = False,
381
+ existing_folders: list[tuple[str, frozenset[str]]] | None = None,
382
+ ) -> dict | None:
383
+ """Evaluate one top-level entry and return a plan record, or None for folders."""
384
+ if entry.is_dir(follow_symlinks=False):
385
+ return None
386
+ skip_rec = _check_file_safety(entry, now_ts, project_marker, allow_temp_subdir)
387
+ if skip_rec is not None:
388
+ return skip_rec
389
+
390
+ src = Path(entry.path)
391
+ dest_name = normalise_kebab_filename(src.name) if kebab_case else src.name
392
+
393
+ # Layer 1: Custom title_rules from rules.json.
394
+ category, rule_label = match_title_rule(src, rules)
395
+ if category is not None:
396
+ return _build_category_move(
397
+ src, target, category, rule_label, dest_name, reserved, canonical_folders, kebab_case
398
+ )
399
+
400
+ # Layer 2: Existing-folder matching (preserving exact on-disk folder name).
401
+ if existing_folders:
402
+ matched_folder = match_existing_folder(src.stem, existing_folders)
403
+ if matched_folder is not None:
404
+ planned_dest = resolve_collision(target / matched_folder / dest_name, reserved)
405
+ return {
406
+ "source": str(src), "destination": str(planned_dest),
407
+ "category": matched_folder, "rule": f"Existing folder: {matched_folder}",
408
+ "status": "planned", "reason": f"existing folder: {matched_folder}",
409
+ "entry_type": "file",
410
+ }
411
+
412
+ # Layer 4 (Layer 3 clustering runs over these fallback items in guided sort).
413
+ category, rule_label = match_ext_rule(src, rules)
414
+ if category is None:
415
+ return _skip_record(src, "No matching rule")
416
+ return _build_category_move(
417
+ src, target, category, rule_label, dest_name, reserved, canonical_folders, kebab_case
418
+ )
419
+
420
+
421
+ def _evaluate_rename_file(
422
+ entry: os.DirEntry[str],
423
+ target: Path,
424
+ now_ts: float,
425
+ reserved: set[str],
426
+ project_marker: str | None,
427
+ allow_temp_subdir: bool,
428
+ ) -> dict:
429
+ """Evaluate one top-level file for in-place kebab-case renaming."""
430
+ skip_rec = _check_file_safety(entry, now_ts, project_marker, allow_temp_subdir)
431
+ if skip_rec is not None:
432
+ skip_rec["entry_type"] = "file"
433
+ return skip_rec
434
+
435
+ src = Path(entry.path)
436
+ stem = normalise_kebab_stem(src.stem)
437
+ if not stem:
438
+ rec = _skip_record(src, "Original name preserved (empty or reserved after normalisation)")
439
+ rec["entry_type"] = "file"
440
+ return rec
441
+
442
+ dest_name = f"{stem}{src.suffix.lower()}"
443
+ if dest_name == src.name:
444
+ rec = _skip_record(src, "Already in kebab-case")
445
+ rec["entry_type"] = "file"
446
+ return rec
447
+
448
+ planned_dest = resolve_collision(target / dest_name, reserved, same_source=src)
449
+ return {
450
+ "source": str(src), "destination": str(planned_dest),
451
+ "category": "File renames", "rule": "Rename: File",
452
+ "status": "planned", "reason": "", "entry_type": "file",
453
+ }
454
+
455
+
456
+ def _evaluate_rename_folder(
457
+ entry: os.DirEntry[str],
458
+ target: Path,
459
+ reserved: set[str],
460
+ project_marker: str | None,
461
+ allow_temp_subdir: bool,
462
+ ) -> tuple[dict, bool]:
463
+ """Evaluate one top-level subfolder; return (plan_record, is_safe_for_inner_files)."""
464
+ src = Path(entry.path)
465
+ def _unsafe_skip(reason: str) -> tuple[dict, bool]:
466
+ rec = _skip_record(src, reason)
467
+ rec["entry_type"] = "folder"
468
+ return rec, False
469
+
470
+ if entry.is_symlink():
471
+ return _unsafe_skip("Symbolic link")
472
+ if is_system_path(src, allow_temp_subdir=allow_temp_subdir):
473
+ return _unsafe_skip("Protected system path")
474
+ if src.name.startswith("."):
475
+ return _unsafe_skip("Hidden or dot folder")
476
+ if src.name.startswith("~$"):
477
+ return _unsafe_skip("Temporary folder (~$)")
478
+ if project_marker is not None:
479
+ return _unsafe_skip(f"Project-safe mode: marker '{project_marker}' present")
480
+ if src.name.lower() in {".git", ".venv", "venv"}:
481
+ return _unsafe_skip(f"Protected project folder ({src.name})")
482
+ if is_cloud_sync_folder_name(src.name):
483
+ return _unsafe_skip(f"Protected cloud-sync root folder ({src.name})")
484
+ if is_cloud_placeholder(src):
485
+ return _unsafe_skip("OneDrive cloud-only placeholder")
486
+
487
+ folder_marker, inspect_err = detect_folder_project_marker(src)
488
+ if inspect_err is not None:
489
+ return _unsafe_skip(inspect_err)
490
+ if folder_marker is not None:
491
+ return _unsafe_skip(f"Project folder: marker '{folder_marker}' present")
492
+ if is_folder_locked(src):
493
+ return _unsafe_skip("Folder locked by another process")
494
+
495
+ kebab_name = normalise_kebab_stem(src.name)
496
+ if not kebab_name:
497
+ rec = _skip_record(src, "Original name preserved (empty or reserved after normalisation)")
498
+ rec["entry_type"] = "folder"
499
+ return rec, True
500
+ if kebab_name == src.name:
501
+ rec = _skip_record(src, "Already in kebab-case")
502
+ rec["entry_type"] = "folder"
503
+ return rec, True
504
+
505
+ planned_dest = resolve_collision(target / kebab_name, reserved, same_source=src)
506
+ return {
507
+ "source": str(src), "destination": str(planned_dest),
508
+ "category": "Folder renames", "rule": "Rename: Folder",
509
+ "status": "planned", "reason": "", "entry_type": "folder",
510
+ }, True
511
+
512
+
513
+ def build_plan(
514
+ targets: list[Path],
515
+ rules: RuleSet | list[tuple[str, list[str]]],
516
+ now_ts: float | None = None,
517
+ allow_temp_sandbox: bool = False,
518
+ kebab_case: bool = False,
519
+ ) -> tuple[list[dict], list[str]]:
520
+ """Scan top-level files across targets and return plan items and notices."""
521
+ current_ts = now_ts if now_ts is not None else datetime.now(timezone.utc).timestamp()
522
+ reserved: set[str] = set()
523
+ canonical_folders: dict[tuple[str, str], str] = {}
524
+ items: list[dict] = []
525
+ notices: list[str] = []
526
+
527
+ for raw_target in targets:
528
+ target = raw_target.resolve(strict=False)
529
+ if not target.exists() or not target.is_dir():
530
+ notices.append(f"Target folder not found, skipped: {target}")
531
+ continue
532
+ if is_system_path(target, allow_temp_subdir=allow_temp_sandbox):
533
+ notices.append(f"Protected system target skipped: {target}")
534
+ continue
535
+
536
+ marker = detect_project_marker(target)
537
+ existing_folders = (
538
+ []
539
+ if marker is not None
540
+ else build_existing_folder_index(
541
+ target,
542
+ ignored_categories=_ignored_fallback_categories(rules),
543
+ is_system_path_fn=lambda p: is_system_path(p, allow_temp_subdir=allow_temp_sandbox),
544
+ )
545
+ )
546
+ try:
547
+ entries = sorted(os.scandir(target), key=lambda e: e.name.lower())
548
+ except OSError as exc:
549
+ notices.append(f"Unable to read folder {target}: {exc}")
550
+ continue
551
+ for entry in entries:
552
+ rec = _evaluate_entry(
553
+ entry, target, rules, current_ts, reserved,
554
+ marker, allow_temp_sandbox, canonical_folders,
555
+ kebab_case=kebab_case, existing_folders=existing_folders,
556
+ )
557
+ if rec is not None:
558
+ items.append(rec)
559
+ return items, notices
560
+
561
+
562
+ def _append_unique_rename(
563
+ rec: dict, items: list[dict], seen_entries: set[tuple[str, str]]
564
+ ) -> None:
565
+ """Append a rename record if its (entry_type, source) has not been queued yet."""
566
+ key = (str(rec.get("entry_type", "file")), _collision_key(Path(rec["source"])))
567
+ if key not in seen_entries:
568
+ seen_entries.add(key)
569
+ items.append(rec)
570
+
571
+
572
+ def build_rename_plan(
573
+ targets: list[Path],
574
+ rename_files: bool = True,
575
+ rename_folders: bool = False,
576
+ now_ts: float | None = None,
577
+ allow_temp_sandbox: bool = False,
578
+ ) -> tuple[list[dict], list[str]]:
579
+ """Scan targets for in-place kebab-case renaming of files and/or subfolders."""
580
+ current_ts = now_ts if now_ts is not None else datetime.now(timezone.utc).timestamp()
581
+ reserved: set[str] = set()
582
+ seen_targets: set[str] = set()
583
+ seen_entries: set[tuple[str, str]] = set()
584
+ items: list[dict] = []
585
+ notices: list[str] = []
586
+
587
+ for raw_target in targets:
588
+ target = raw_target.resolve(strict=False)
589
+ target_key = _collision_key(target)
590
+ if target_key in seen_targets:
591
+ continue
592
+ seen_targets.add(target_key)
593
+
594
+ if not target.exists() or not target.is_dir():
595
+ notices.append(f"Target folder not found, skipped: {target}")
596
+ continue
597
+ if is_system_path(target, allow_temp_subdir=allow_temp_sandbox):
598
+ notices.append(f"Protected system target skipped: {target}")
599
+ continue
600
+
601
+ marker = detect_project_marker(target)
602
+ try:
603
+ entries = sorted(os.scandir(target), key=lambda e: e.name.lower())
604
+ except OSError as exc:
605
+ notices.append(f"Unable to read folder {target}: {exc}")
606
+ continue
607
+
608
+ for entry in entries:
609
+ is_dir = entry.is_dir(follow_symlinks=False)
610
+ if is_dir and rename_folders:
611
+ folder_rec, is_safe_folder = _evaluate_rename_folder(
612
+ entry, target, reserved, marker, allow_temp_sandbox
613
+ )
614
+ _append_unique_rename(folder_rec, items, seen_entries)
615
+ if rename_files and is_safe_folder:
616
+ subfolder = Path(entry.path)
617
+ try:
618
+ sub_entries = sorted(os.scandir(subfolder), key=lambda e: e.name.lower())
619
+ except OSError as exc:
620
+ notices.append(f"Unable to read subfolder {subfolder}: {exc}")
621
+ continue
622
+ for sub_entry in sub_entries:
623
+ if not sub_entry.is_dir(follow_symlinks=False):
624
+ file_rec = _evaluate_rename_file(
625
+ sub_entry, subfolder, current_ts, reserved, None, allow_temp_sandbox
626
+ )
627
+ _append_unique_rename(file_rec, items, seen_entries)
628
+ elif not is_dir and rename_files:
629
+ file_rec = _evaluate_rename_file(
630
+ entry, target, current_ts, reserved, marker, allow_temp_sandbox
631
+ )
632
+ _append_unique_rename(file_rec, items, seen_entries)
633
+
634
+ # Order deeper paths and files before shallower folders so forward apply and reverse undo stay valid.
635
+ items.sort(
636
+ key=lambda item: (
637
+ -len(Path(item["source"]).parts),
638
+ 0 if item.get("entry_type") != "folder" else 1,
639
+ _collision_key(Path(item["source"])),
640
+ )
641
+ )
642
+ return items, notices
643
+
644
+
645
+ def format_plan_report(
646
+ items: list[dict],
647
+ notices: list[str],
648
+ dry_run: bool,
649
+ empty_message: str = "No loose top-level files found.",
650
+ ) -> str:
651
+ """Format the planned moves table and per-category summary."""
652
+ lines = ["DRY-RUN PREVIEW (no disk changes made)" if dry_run else "SWEEP EXECUTION PLAN"]
653
+ lines.extend(f"Notice: {n}" for n in notices)
654
+ if not items:
655
+ lines.append(empty_message)
656
+ return "\n".join(lines)
657
+
658
+ headers = ("Source", "Destination", "Rule", "Status")
659
+ rows, counts, skipped = [], {}, 0
660
+ for item in items:
661
+ if item["status"] == "planned":
662
+ bucket = item.get("category") or item["rule"]
663
+ counts[bucket] = counts.get(bucket, 0) + 1
664
+ status_text = "Planned"
665
+ else:
666
+ skipped += 1
667
+ status_text = f"Skipped: {item['reason']}"
668
+ rows.append((item["source"], item["destination"] or "-", item["rule"], status_text))
669
+
670
+ widths = [max(len(headers[i]), *(len(r[i]) for r in rows)) for i in range(4)]
671
+ fmt = " ".join(f"{{:<{w}}}" for w in widths)
672
+ lines.extend(["", fmt.format(*headers), " ".join("-" * w for w in widths)])
673
+ lines.extend(fmt.format(*r) for r in rows)
674
+ lines.extend(["", "Summary by category:"])
675
+ if counts:
676
+ lines.extend(f" {cat}: {cnt}" for cat, cnt in sorted(counts.items()))
677
+ else:
678
+ lines.append(" No files scheduled to move.")
679
+ lines.append(f" Skipped: {skipped}")
680
+ return "\n".join(lines)
681
+
682
+
683
+ def _resolve_apply_mode(planned: list[dict], mode: str | None) -> str:
684
+ """Return the operation mode name, inferring from planned entries if omitted."""
685
+ if mode:
686
+ return mode
687
+ if any(str(item.get("rule", "")).startswith("Rename:") or item.get("entry_type") == "folder" for item in planned):
688
+ return "Batch rename"
689
+ if any(str(item.get("rule", "")).startswith("Cluster:") for item in planned):
690
+ return "Guided sort"
691
+ return "Sort"
692
+
693
+
694
+ def _build_wal_summary(mode: str, entries: list[dict], pre_skipped: int = 0) -> dict[str, int]:
695
+ """Build lightweight move and rename counts from WAL entries."""
696
+ committed_files = sum(
697
+ 1 for e in entries if e.get("status") == "committed" and e.get("entry_type", "file") != "folder"
698
+ )
699
+ folder_renames = sum(
700
+ 1 for e in entries if e.get("status") == "committed" and e.get("entry_type") == "folder"
701
+ )
702
+ entry_skipped = sum(1 for e in entries if e.get("status") == "skipped")
703
+ failed = sum(1 for e in entries if e.get("status") == "failed")
704
+ return {
705
+ "file_moves": 0 if mode == "Batch rename" else committed_files,
706
+ "file_renames": committed_files if mode == "Batch rename" else 0,
707
+ "folder_renames": folder_renames,
708
+ "skipped": pre_skipped + entry_skipped,
709
+ "failed": failed,
710
+ }
711
+
712
+
713
+ def apply_plan(
714
+ items: list[dict],
715
+ targets: list[Path],
716
+ rules_path: Path,
717
+ log_dir: Path,
718
+ mode: str | None = None,
719
+ ) -> tuple[str | None, dict[str, int]]:
720
+ """Execute planned moves or renames using write-ahead logging to log_dir."""
721
+ planned = [item for item in items if item["status"] == "planned"]
722
+ pre_skipped = sum(1 for item in items if item["status"] == "skipped")
723
+ summary = {"committed": 0, "skipped": pre_skipped, "failed": 0}
724
+ if not planned:
725
+ return None, summary
726
+
727
+ resolved_mode = _resolve_apply_mode(planned, mode)
728
+ run_id = f"{datetime.now(timezone.utc).strftime('%Y%m%dT%H%M%SZ')}_{uuid.uuid4().hex[:8]}"
729
+ log_path = log_dir / f"{run_id}.json"
730
+ entries = [
731
+ {
732
+ "index": idx, "source": item["source"], "destination": item["destination"],
733
+ "rule": item["rule"], "entry_type": item.get("entry_type", "file"),
734
+ "status": "pending", "reason": "", "updated_at": utc_now_iso(),
735
+ }
736
+ for idx, item in enumerate(planned)
737
+ ]
738
+ log_payload = {
739
+ "run_id": run_id,
740
+ "created_at": utc_now_iso(),
741
+ "mode": resolved_mode,
742
+ "targets": [str(Path(t).resolve(strict=False)) for t in targets],
743
+ "rules_path": str(rules_path),
744
+ "status": "in_progress",
745
+ "undone": False,
746
+ "summary": _build_wal_summary(resolved_mode, entries, pre_skipped=pre_skipped),
747
+ "entries": entries,
748
+ }
749
+ write_json_atomic(log_path, log_payload)
750
+
751
+ for entry in entries:
752
+ src, dest = Path(entry["source"]), Path(entry["destination"])
753
+ is_folder = entry.get("entry_type") == "folder" or src.is_dir()
754
+ if not src.exists():
755
+ label = "Folder" if is_folder else "File"
756
+ entry.update(status="skipped", reason=f"Source {label.lower()} disappeared before move", updated_at=utc_now_iso())
757
+ summary["skipped"] += 1
758
+ write_json_atomic(log_path, log_payload)
759
+ continue
760
+ locked = is_folder_locked(src) if is_folder else is_file_locked(src)
761
+ if locked:
762
+ label = "Folder" if is_folder else "File"
763
+ entry.update(status="skipped", reason=f"{label} became locked before move", updated_at=utc_now_iso())
764
+ summary["skipped"] += 1
765
+ write_json_atomic(log_path, log_payload)
766
+ continue
767
+ if dest.exists() and _collision_key(dest) != _collision_key(src):
768
+ dest = resolve_collision(dest, set(), same_source=src)
769
+ entry.update(destination=str(dest), updated_at=utc_now_iso())
770
+ write_json_atomic(log_path, log_payload)
771
+ try:
772
+ dest.parent.mkdir(parents=True, exist_ok=True)
773
+ if is_folder:
774
+ os.rename(str(src), str(dest))
775
+ else:
776
+ shutil.move(str(src), str(dest))
777
+ entry["status"] = "committed"
778
+ summary["committed"] += 1
779
+ except PermissionError as exc:
780
+ if is_folder or str(entry.get("rule", "")).startswith("Rename:"):
781
+ label = "Folder" if is_folder else "File"
782
+ entry["status"] = "skipped"
783
+ entry["reason"] = f"{label} locked or permission denied: {exc}"
784
+ summary["skipped"] += 1
785
+ else:
786
+ entry["status"] = "failed"
787
+ entry["reason"] = str(exc)
788
+ summary["failed"] += 1
789
+ except OSError as exc:
790
+ entry["status"] = "failed"
791
+ entry["reason"] = str(exc)
792
+ summary["failed"] += 1
793
+ entry["updated_at"] = utc_now_iso()
794
+ write_json_atomic(log_path, log_payload)
795
+
796
+ log_payload["status"] = "completed_with_errors" if summary["failed"] else "completed"
797
+ log_payload["completed_at"] = utc_now_iso()
798
+ log_payload["summary"] = _build_wal_summary(resolved_mode, entries, pre_skipped=pre_skipped)
799
+ write_json_atomic(log_path, log_payload)
800
+ return run_id, summary
801
+
802
+
803
+ def _select_log_file(log_dir: Path, run_id: str | None) -> Path:
804
+ if not log_dir.exists():
805
+ raise FileNotFoundError(f"No undo log directory found at {log_dir}")
806
+ if run_id is not None:
807
+ candidate = log_dir / f"{run_id}.json"
808
+ if not candidate.exists():
809
+ raise FileNotFoundError(f"Run log not found: {candidate}")
810
+ return candidate
811
+ for log_file in sorted(log_dir.glob("*.json"), reverse=True):
812
+ payload = json.loads(log_file.read_text(encoding="utf-8"))
813
+ if not (payload.get("undone") is True or payload.get("status") == "undone"):
814
+ return log_file
815
+ raise FileNotFoundError("No active run logs available to undo.")
816
+
817
+
818
+ def undo_run(log_dir: Path, run_id: str | None = None) -> tuple[str, dict[str, int]]:
819
+ """Reverse a logged run, recovering safely from mid-run crashes."""
820
+ log_path = _select_log_file(log_dir, run_id)
821
+ log_payload = json.loads(log_path.read_text(encoding="utf-8"))
822
+ resolved_id = str(log_payload["run_id"])
823
+ summary = {"restored": 0, "already_in_place": 0, "skipped": 0, "failed": 0}
824
+
825
+ for entry in reversed(log_payload.get("entries", [])):
826
+ if entry.get("status") not in {"committed", "pending"}:
827
+ summary["skipped"] += 1
828
+ continue
829
+ src, dest = Path(entry["source"]), Path(entry["destination"])
830
+ is_folder = entry.get("entry_type") == "folder" or dest.is_dir()
831
+ if dest.exists():
832
+ if _collision_key(src) == _collision_key(dest):
833
+ restore_target = src
834
+ note = ""
835
+ elif src.exists():
836
+ restore_target = resolve_collision(src, set(), same_source=dest)
837
+ note = f"Original path occupied; restored as {restore_target.name}"
838
+ else:
839
+ restore_target = src
840
+ note = ""
841
+ try:
842
+ restore_target.parent.mkdir(parents=True, exist_ok=True)
843
+ if is_folder:
844
+ os.rename(str(dest), str(restore_target))
845
+ else:
846
+ shutil.move(str(dest), str(restore_target))
847
+ entry.update(status="undone", reason=note)
848
+ summary["restored"] += 1
849
+ except OSError as exc:
850
+ entry["reason"] = f"Undo failed: {exc}"
851
+ summary["failed"] += 1
852
+ elif src.exists():
853
+ entry.update(status="undone", reason="Already at source (pending move had not occurred)")
854
+ summary["already_in_place"] += 1
855
+ else:
856
+ entry["reason"] = "Neither source nor destination exists"
857
+ summary["failed"] += 1
858
+ entry["updated_at"] = utc_now_iso()
859
+ write_json_atomic(log_path, log_payload)
860
+
861
+ if summary["failed"]:
862
+ log_payload["status"] = "undo_partial"
863
+ log_payload["undone"] = False
864
+ else:
865
+ log_payload["status"] = "undone"
866
+ log_payload["undone"] = True
867
+ log_payload["undone_at"] = utc_now_iso()
868
+ write_json_atomic(log_path, log_payload)
869
+ return resolved_id, summary
870
+
871
+
872
+ def _parse_wal_timestamp(payload: dict, log_path: Path | None = None) -> datetime | None:
873
+ """Parse run timestamp from created_at, run_id, or log file mtime as UTC datetime."""
874
+ raw_ts = str(payload.get("created_at", "")).strip()
875
+ if raw_ts:
876
+ try:
877
+ dt = datetime.fromisoformat(raw_ts.replace("Z", "+00:00"))
878
+ return dt if dt.tzinfo is not None else dt.replace(tzinfo=timezone.utc)
879
+ except ValueError:
880
+ pass
881
+ run_id = str(payload.get("run_id", "")).strip()
882
+ match = re.match(r"^(\d{8}T\d{6})Z(?:_|$)", run_id)
883
+ if match:
884
+ try:
885
+ return datetime.strptime(match.group(1), "%Y%m%dT%H%M%S").replace(tzinfo=timezone.utc)
886
+ except ValueError:
887
+ pass
888
+ if log_path is not None:
889
+ try:
890
+ return datetime.fromtimestamp(log_path.stat().st_mtime, tz=timezone.utc)
891
+ except OSError:
892
+ pass
893
+ return None
894
+
895
+
896
+ def format_relative_timestamp(dt: datetime | None, now: datetime | None = None) -> str:
897
+ """Format a UTC or aware datetime as relative age plus readable local timestamp."""
898
+ if dt is None:
899
+ return "unknown time"
900
+ dt_utc = dt.astimezone(timezone.utc) if dt.tzinfo is not None else dt.replace(tzinfo=timezone.utc)
901
+ if now is None:
902
+ now_utc = datetime.now(timezone.utc)
903
+ else:
904
+ now_utc = now.astimezone(timezone.utc) if now.tzinfo is not None else now.replace(tzinfo=timezone.utc)
905
+ seconds = max(0, int((now_utc - dt_utc).total_seconds()))
906
+ if seconds < 60:
907
+ rel = "just now"
908
+ elif seconds < 3600:
909
+ mins = seconds // 60
910
+ rel = f"{mins} {'min' if mins == 1 else 'mins'} ago"
911
+ elif seconds < 86400:
912
+ hours = seconds // 3600
913
+ rel = f"{hours} {'hour' if hours == 1 else 'hours'} ago"
914
+ elif seconds < 86400 * 7:
915
+ days = seconds // 86400
916
+ rel = f"{days} {'day' if days == 1 else 'days'} ago"
917
+ elif seconds < 86400 * 30:
918
+ weeks = seconds // (86400 * 7)
919
+ rel = f"{weeks} {'week' if weeks == 1 else 'weeks'} ago"
920
+ elif seconds < 86400 * 365:
921
+ months = max(1, seconds // (86400 * 30))
922
+ rel = f"{months} {'month' if months == 1 else 'months'} ago"
923
+ else:
924
+ years = max(1, seconds // (86400 * 365))
925
+ rel = f"{years} {'year' if years == 1 else 'years'} ago"
926
+ local_str = dt_utc.astimezone().strftime("%d %b %Y, %H:%M")
927
+ return f"{rel} ({local_str})"
928
+
929
+
930
+ def _infer_wal_targets(payload: dict, entries: list[dict]) -> list[str]:
931
+ """Return target folder paths from metadata or infer them from WAL entries."""
932
+ raw_targets = payload.get("targets")
933
+ if isinstance(raw_targets, list):
934
+ cleaned = [str(t) for t in raw_targets if str(t).strip()]
935
+ if cleaned:
936
+ return cleaned
937
+ inferred: list[str] = []
938
+ seen: set[str] = set()
939
+ for entry in entries:
940
+ raw_src = str(entry.get("source", "")).strip()
941
+ if not raw_src:
942
+ continue
943
+ parent = Path(raw_src).parent
944
+ key = _collision_key(parent)
945
+ if key not in seen:
946
+ seen.add(key)
947
+ inferred.append(str(parent))
948
+ return inferred
949
+
950
+
951
+ def _infer_wal_mode(payload: dict, entries: list[dict]) -> str:
952
+ """Return operation mode from metadata or infer it from legacy WAL entries."""
953
+ explicit = str(payload.get("mode", "")).strip()
954
+ if explicit:
955
+ return explicit
956
+ summary_meta = payload.get("summary")
957
+ if isinstance(summary_meta, dict) and str(summary_meta.get("mode", "")).strip():
958
+ return str(summary_meta["mode"]).strip()
959
+ if any(
960
+ str(e.get("rule", "")).startswith("Rename:")
961
+ or e.get("entry_type") == "folder"
962
+ or e.get("category") in {"File renames", "Folder renames"}
963
+ for e in entries
964
+ ):
965
+ return "Batch rename"
966
+ if any(str(e.get("rule", "")).startswith("Cluster:") for e in entries):
967
+ return "Guided sort"
968
+ return "Sort"
969
+
970
+
971
+ def _infer_wal_counts(payload: dict, entries: list[dict]) -> tuple[int, int]:
972
+ """Return (file_count, folder_count) from summary metadata or WAL entries."""
973
+ summary_meta = payload.get("summary")
974
+ if isinstance(summary_meta, dict) and payload.get("status") != "in_progress":
975
+ has_new_keys = any(
976
+ k in summary_meta for k in ("file_moves", "file_renames", "folder_renames", "file_count", "folder_count")
977
+ )
978
+ if has_new_keys:
979
+ if "file_moves" in summary_meta or "file_renames" in summary_meta:
980
+ file_count = int(summary_meta.get("file_moves", 0)) + int(summary_meta.get("file_renames", 0))
981
+ else:
982
+ file_count = int(summary_meta.get("file_count", 0))
983
+ folder_count = int(summary_meta.get("folder_renames", summary_meta.get("folder_count", 0)))
984
+ return file_count, folder_count
985
+ active_entries = [e for e in entries if e.get("status") in {"committed", "pending", "undone"}]
986
+ folder_count = sum(
987
+ 1 for e in active_entries if e.get("entry_type") == "folder" or e.get("rule") == "Rename: Folder"
988
+ )
989
+ file_count = len(active_entries) - folder_count
990
+ return file_count, folder_count
991
+
992
+
993
+ def _format_action_summary(mode: str, file_count: int, folder_count: int) -> str:
994
+ """Format a concise human-readable action summary for a WAL run."""
995
+ if mode == "Batch rename":
996
+ parts: list[str] = []
997
+ if file_count:
998
+ parts.append(f"{file_count} {'file' if file_count == 1 else 'files'}")
999
+ if folder_count:
1000
+ parts.append(f"{folder_count} {'folder' if folder_count == 1 else 'folders'}")
1001
+ if not parts:
1002
+ parts.append("0 items")
1003
+ return f"{mode} | {', '.join(parts)}"
1004
+ if folder_count > 0:
1005
+ return (
1006
+ f"{mode} | {file_count} {'file' if file_count == 1 else 'files'}, "
1007
+ f"{folder_count} {'folder' if folder_count == 1 else 'folders'}"
1008
+ )
1009
+ return f"{mode} | {file_count} {'file' if file_count == 1 else 'files'} moved"
1010
+
1011
+
1012
+ def summarise_wal_run(
1013
+ payload: dict, log_path: Path | None = None, now: datetime | None = None
1014
+ ) -> dict:
1015
+ """Normalise new and legacy WAL payloads into display-ready run metadata."""
1016
+ entries = payload.get("entries", [])
1017
+ if not isinstance(entries, list):
1018
+ entries = []
1019
+ is_undone = payload.get("undone") is True or payload.get("status") == "undone"
1020
+ status_tag = "[Undone]" if is_undone else "[Active]"
1021
+ timestamp = _parse_wal_timestamp(payload, log_path)
1022
+ mode = _infer_wal_mode(payload, entries)
1023
+ file_count, folder_count = _infer_wal_counts(payload, entries)
1024
+ targets = _infer_wal_targets(payload, entries)
1025
+ return {
1026
+ "run_id": str(payload["run_id"]),
1027
+ "log_path": log_path,
1028
+ "payload": payload,
1029
+ "status": str(payload.get("status", "unknown")),
1030
+ "is_undone": is_undone,
1031
+ "status_tag": status_tag,
1032
+ "timestamp": timestamp,
1033
+ "time_display": format_relative_timestamp(timestamp, now=now),
1034
+ "mode": mode,
1035
+ "file_count": file_count,
1036
+ "folder_count": folder_count,
1037
+ "action_summary": _format_action_summary(mode, file_count, folder_count),
1038
+ "targets": targets,
1039
+ "targets_display": ", ".join(targets) if targets else "(unknown folder)",
1040
+ }
1041
+
1042
+
1043
+ def load_wal_runs(log_dir: Path, now: datetime | None = None) -> list[dict]:
1044
+ """Load and summarise all valid WAL logs from log_dir sorted newest first."""
1045
+ if not log_dir.exists():
1046
+ return []
1047
+ runs: list[dict] = []
1048
+ for log_file in log_dir.glob("*.json"):
1049
+ try:
1050
+ payload = json.loads(log_file.read_text(encoding="utf-8"))
1051
+ if not isinstance(payload, dict) or "run_id" not in payload:
1052
+ continue
1053
+ runs.append(summarise_wal_run(payload, log_path=log_file, now=now))
1054
+ except (OSError, json.JSONDecodeError, KeyError, TypeError, ValueError):
1055
+ continue
1056
+ runs.sort(
1057
+ key=lambda r: (
1058
+ r["timestamp"].timestamp() if r["timestamp"] is not None else -1.0,
1059
+ r["log_path"].name if r["log_path"] is not None else r["run_id"],
1060
+ ),
1061
+ reverse=True,
1062
+ )
1063
+ return runs
1064
+
1065
+
1066
+ def format_undo_list(runs: list[dict], limit: int = 10) -> str:
1067
+ """Format a clean numbered list of recent runs capped to limit."""
1068
+ shown = runs[:limit]
1069
+ omitted = max(0, len(runs) - len(shown))
1070
+ lines = ["Recent runs:"]
1071
+ for idx, run in enumerate(shown, start=1):
1072
+ lines.append(f" {idx}. {run['status_tag']} {run['time_display']} | {run['action_summary']}")
1073
+ target_label = "Targets" if len(run["targets"]) > 1 else "Target"
1074
+ lines.append(f" {target_label}: {run['targets_display']} (run {run['run_id']})")
1075
+ if omitted > 0:
1076
+ noun = "run" if omitted == 1 else "runs"
1077
+ lines.append(
1078
+ f" Note: Showing the {limit} most recent runs ({omitted} older {noun} not shown; all logs preserved)."
1079
+ )
1080
+ return "\n".join(lines)
1081
+
1082
+
1083
+ def build_undo_preview(log_payload: dict) -> list[dict]:
1084
+ """Return ordered list of items that would be restored for a logged run."""
1085
+ preview: list[dict] = []
1086
+ for entry in reversed(log_payload.get("entries", [])):
1087
+ if entry.get("status") not in {"committed", "pending"}:
1088
+ continue
1089
+ src = Path(entry["source"])
1090
+ dest = Path(entry["destination"])
1091
+ is_folder = entry.get("entry_type") == "folder" or dest.is_dir()
1092
+ kind = "Folder" if is_folder else "File"
1093
+ if dest.exists():
1094
+ state = "restore"
1095
+ elif src.exists():
1096
+ state = "already_in_place"
1097
+ else:
1098
+ state = "missing"
1099
+ preview.append({
1100
+ "kind": kind,
1101
+ "source": str(src),
1102
+ "destination": str(dest),
1103
+ "state": state,
1104
+ })
1105
+ return preview
1106
+
1107
+
1108
+ def format_undo_preview(
1109
+ log_payload: dict,
1110
+ limit: int | None = None,
1111
+ dry_run_header: bool = False,
1112
+ now: datetime | None = None,
1113
+ ) -> str:
1114
+ """Format a rollback preview for interactive confirmation or CLI --dry-run."""
1115
+ run_info = summarise_wal_run(log_payload, now=now)
1116
+ preview = build_undo_preview(log_payload)
1117
+ lines: list[str] = []
1118
+ if dry_run_header:
1119
+ lines.append("DRY-RUN PREVIEW (no disk changes made)")
1120
+ lines.append(
1121
+ f"Items to restore for run {run_info['run_id']} "
1122
+ f"({run_info['status_tag']} {run_info['action_summary']} | {run_info['targets_display']}):"
1123
+ )
1124
+ if not preview:
1125
+ lines.append(" No restorable items found in this run.")
1126
+ return "\n".join(lines)
1127
+
1128
+ shown = preview[:limit] if limit is not None else preview
1129
+ for item in shown:
1130
+ prefix = "[Folder] " if item["kind"] == "Folder" else ""
1131
+ if item["state"] == "already_in_place":
1132
+ suffix = " (already at source)"
1133
+ elif item["state"] == "missing":
1134
+ suffix = " (missing on disk)"
1135
+ else:
1136
+ suffix = ""
1137
+ lines.append(f" - {prefix}{item['destination']} -> {item['source']}{suffix}")
1138
+ if limit is not None and len(preview) > limit:
1139
+ lines.append(f" ... and {len(preview) - limit} more")
1140
+ return "\n".join(lines)
1141
+
1142
+
1143
+ def _is_interactive_session(raw_argv: list[str]) -> bool:
1144
+ """Return True when Sweep starts with no arguments in an interactive terminal."""
1145
+ if raw_argv or not sys.stdin.isatty():
1146
+ return False
1147
+ return sys.stdout.isatty() or isinstance(sys.stdout, io.StringIO)
1148
+
1149
+
1150
+ def _summarise_loose_files(items: list[dict]) -> tuple[list[tuple[str, int]], int, int]:
1151
+ """Return sorted extension counts, planned count, and skipped count."""
1152
+ ext_counts: dict[str, int] = {}
1153
+ planned = 0
1154
+ skipped = 0
1155
+ for item in items:
1156
+ suffix = Path(item["source"]).suffix.lower() or "[no ext]"
1157
+ ext_counts[suffix] = ext_counts.get(suffix, 0) + 1
1158
+ if item["status"] == "planned":
1159
+ planned += 1
1160
+ else:
1161
+ skipped += 1
1162
+ ordered = sorted(ext_counts.items(), key=lambda pair: (-pair[1], pair[0]))
1163
+ return ordered, planned, skipped
1164
+
1165
+
1166
+ def _print_interactive_header(
1167
+ targets: list[Path],
1168
+ items: list[dict],
1169
+ notices: list[str],
1170
+ cluster_count: int = 0,
1171
+ kebab_case: bool = False,
1172
+ ) -> None:
1173
+ """Display the auto-scan dashboard and 6-option interactive menu."""
1174
+ ext_counts, planned, skipped = _summarise_loose_files(items)
1175
+ total_files = planned + skipped
1176
+ print("\n=== Sweep v3 Interactive Mode ===")
1177
+ print("Folder(s):")
1178
+ for target in targets:
1179
+ resolved = target.resolve(strict=False)
1180
+ marker = "" if resolved.exists() and resolved.is_dir() else " (not found)"
1181
+ print(f" - {resolved}{marker}")
1182
+ for notice in notices:
1183
+ print(f"Notice: {notice}")
1184
+
1185
+ print(f"Scan summary: {total_files} loose file(s) ({planned} ready to sort, {skipped} safely skipped)")
1186
+ top_exts = ext_counts[:6]
1187
+ breakdown = ", ".join(f"{ext}: {cnt}" for ext, cnt in top_exts) if top_exts else "none"
1188
+ if len(ext_counts) > 6:
1189
+ breakdown += f", +{len(ext_counts) - 6} more"
1190
+ print(f"Top extensions: {breakdown}")
1191
+ if cluster_count:
1192
+ print(f"Smart file groups spotted: {cluster_count}")
1193
+
1194
+ kebab_state = "ON" if kebab_case else "OFF"
1195
+ naming_mode = "kebab-case: ON" if kebab_case else "Original names (kebab-case: OFF)"
1196
+ print(f"Naming mode: {naming_mode}")
1197
+ print("\nChoose an option:")
1198
+ print(" 1. Guided sort (review groups, preview plan, then apply)")
1199
+ print(" 2. Switch folder")
1200
+ print(f" 3. Toggle kebab-case naming (currently {kebab_state})")
1201
+ print(" 4. Undo a previous run")
1202
+ print(" 5. Batch rename files or folders (kebab-case)")
1203
+ print(" 6. Exit")
1204
+
1205
+
1206
+ def _interactive_undo(log_dir: Path) -> None:
1207
+ """List recent run logs by number, preview items, and undo the selected run."""
1208
+ if not log_dir.exists():
1209
+ print(f"No undo logs found in {log_dir}.")
1210
+ return
1211
+ runs = load_wal_runs(log_dir)
1212
+ if not runs:
1213
+ print("No undo logs available.")
1214
+ return
1215
+
1216
+ capped = runs[:10]
1217
+ print("")
1218
+ print(format_undo_list(runs, limit=10))
1219
+ print(" 0. Cancel")
1220
+ try:
1221
+ choice = input("Select a run number to undo: ").strip()
1222
+ except (EOFError, KeyboardInterrupt):
1223
+ print("\nUndo cancelled.")
1224
+ return
1225
+ if choice in {"", "0"}:
1226
+ print("Undo cancelled.")
1227
+ return
1228
+ if not choice.isdigit() or not (1 <= int(choice) <= len(capped)):
1229
+ print("Invalid selection.")
1230
+ return
1231
+
1232
+ selected = capped[int(choice) - 1]
1233
+ if selected["is_undone"]:
1234
+ print(f"Run {selected['run_id']} has already been undone.")
1235
+ return
1236
+
1237
+ preview = build_undo_preview(selected["payload"])
1238
+ if not preview:
1239
+ print(f"Run {selected['run_id']} has no restorable items.")
1240
+ return
1241
+
1242
+ print("")
1243
+ print(format_undo_preview(selected["payload"], limit=5, dry_run_header=False))
1244
+ try:
1245
+ confirm = input("Restore these items now? (y/n): ").strip().lower()
1246
+ except (EOFError, KeyboardInterrupt):
1247
+ print("\nUndo cancelled.")
1248
+ return
1249
+ if confirm not in {"y", "yes"}:
1250
+ print("Undo cancelled.")
1251
+ return
1252
+
1253
+ undone_id, summary = undo_run(log_dir, selected["run_id"])
1254
+ print(
1255
+ f"Undo complete for run {undone_id}: {summary['restored']} restored, "
1256
+ f"{summary['already_in_place']} already at source, "
1257
+ f"{summary['skipped']} skipped, {summary['failed']} failed."
1258
+ )
1259
+
1260
+
1261
+ def _interactive_change_target(
1262
+ current_targets: list[Path], current_allow_temp: bool
1263
+ ) -> tuple[list[Path], bool]:
1264
+ """Prompt the user to switch between default folders or a custom path."""
1265
+ profile = user_profile_dir()
1266
+ print("\nSelect target folder:")
1267
+ print(" 1. Downloads")
1268
+ print(" 2. Desktop")
1269
+ print(" 3. Documents")
1270
+ print(" 4. All defaults (Downloads, Desktop, Documents)")
1271
+ print(" 5. Custom path")
1272
+ print(" 0. Cancel")
1273
+ try:
1274
+ choice = input("Select option: ").strip()
1275
+ except (EOFError, KeyboardInterrupt):
1276
+ print("\nTarget change cancelled.")
1277
+ return current_targets, current_allow_temp
1278
+ presets = {
1279
+ "1": [profile / "Downloads"],
1280
+ "2": [profile / "Desktop"],
1281
+ "3": [profile / "Documents"],
1282
+ "4": default_targets(),
1283
+ }
1284
+ if choice in presets:
1285
+ return presets[choice], False
1286
+ if choice == "5":
1287
+ try:
1288
+ raw_path = input("Enter folder path: ").strip().strip('"')
1289
+ except (EOFError, KeyboardInterrupt):
1290
+ print("\nTarget change cancelled.")
1291
+ return current_targets, current_allow_temp
1292
+ if not raw_path:
1293
+ print("No path entered.")
1294
+ return current_targets, current_allow_temp
1295
+ candidate = Path(raw_path).resolve(strict=False)
1296
+ if not candidate.exists() or not candidate.is_dir():
1297
+ print(f"Folder not found: {candidate}")
1298
+ return current_targets, current_allow_temp
1299
+ if is_system_path(candidate, allow_temp_subdir=True):
1300
+ print(f"Protected system folder cannot be targeted: {candidate}")
1301
+ return current_targets, current_allow_temp
1302
+ return [candidate], True
1303
+ if choice not in {"", "0"}:
1304
+ print("Invalid selection.")
1305
+ return current_targets, current_allow_temp
1306
+
1307
+
1308
+ def save_clusters_to_rules(rules_path: Path, clusters: list[CandidateCluster]) -> list[str]:
1309
+ """Atomically append approved clusters as title_rules in rules.json."""
1310
+ if not clusters:
1311
+ return []
1312
+ data = json.loads(rules_path.read_text(encoding="utf-8"))
1313
+ title_rules = data.get("title_rules")
1314
+ if title_rules is None:
1315
+ title_rules = []
1316
+ data["title_rules"] = title_rules
1317
+ if not isinstance(title_rules, list):
1318
+ raise ValueError("rules.json 'title_rules' must be a list.")
1319
+
1320
+ saved_labels: list[str] = []
1321
+ for cluster in clusters:
1322
+ bucket = _validate_folder_name(cluster.label, "bucket")
1323
+ keyword_phrase = " ".join(cluster.keywords).lower()
1324
+ existing = next(
1325
+ (entry for entry in title_rules
1326
+ if str(entry.get("bucket", entry.get("category", ""))).casefold() == bucket.casefold()),
1327
+ None,
1328
+ )
1329
+ if existing is not None:
1330
+ kws = [str(k).lower() for k in existing.get("keywords", [])]
1331
+ if keyword_phrase not in kws:
1332
+ existing.setdefault("keywords", []).append(keyword_phrase)
1333
+ saved_labels.append(bucket)
1334
+ else:
1335
+ title_rules.append({"bucket": bucket, "keywords": [keyword_phrase]})
1336
+ saved_labels.append(bucket)
1337
+
1338
+ if saved_labels:
1339
+ write_json_atomic(rules_path, data)
1340
+ return saved_labels
1341
+
1342
+
1343
+ def _interactive_select_clusters(
1344
+ discovered: list[CandidateCluster],
1345
+ rules_path: Path,
1346
+ ) -> list[CandidateCluster] | None:
1347
+ """Step A of guided sort: let the user select smart groups or press Enter to skip."""
1348
+ if not discovered:
1349
+ return []
1350
+
1351
+ print("\nSmart file groups (3+ similarly named files):")
1352
+ for idx, cluster in enumerate(discovered, start=1):
1353
+ samples = ", ".join(cluster.sample_names)
1354
+ print(
1355
+ f" {idx}. Move {len(cluster.item_indices)} files in {cluster.target.name} "
1356
+ f"into '{cluster.label}'"
1357
+ )
1358
+ print(f" Examples: {samples}")
1359
+ try:
1360
+ raw = input(
1361
+ "Select group numbers to include (e.g. 1 or 1,2, 'all', or press Enter to skip): "
1362
+ ).strip().lower()
1363
+ except (EOFError, KeyboardInterrupt):
1364
+ print("\nGuided sort cancelled.")
1365
+ return None
1366
+ if raw in {"", "0"}:
1367
+ return []
1368
+
1369
+ selected: list[CandidateCluster] = []
1370
+ if raw == "all":
1371
+ selected = list(discovered)
1372
+ else:
1373
+ tokens = [part.strip() for part in raw.split(",") if part.strip()]
1374
+ seen_idx: set[int] = set()
1375
+ for tok in tokens:
1376
+ if not tok.isdigit() or not (1 <= int(tok) <= len(discovered)):
1377
+ print(f"Invalid selection: {tok}")
1378
+ return None
1379
+ num = int(tok)
1380
+ if num not in seen_idx:
1381
+ seen_idx.add(num)
1382
+ selected.append(discovered[num - 1])
1383
+
1384
+ try:
1385
+ save_ans = input("Save selected group(s) to rules.json for future runs too? (y/n): ").strip().lower()
1386
+ except (EOFError, KeyboardInterrupt):
1387
+ print("\nSkipped saving to rules.json.")
1388
+ return selected
1389
+ if save_ans in {"y", "yes"}:
1390
+ try:
1391
+ saved = save_clusters_to_rules(rules_path, selected)
1392
+ except (OSError, json.JSONDecodeError, ValueError) as exc:
1393
+ print(f"Unable to save rules to {rules_path}: {exc}")
1394
+ return selected
1395
+ if saved:
1396
+ print(f"Saved rule(s) to {rules_path}: {', '.join(saved)}")
1397
+ else:
1398
+ print("Selected group rule(s) already exist in rules.json.")
1399
+ return selected
1400
+
1401
+
1402
+ def _interactive_guided_sort(
1403
+ items: list[dict],
1404
+ notices: list[str],
1405
+ discovered: list[CandidateCluster],
1406
+ targets: list[Path],
1407
+ rules_path: Path,
1408
+ log_dir: Path,
1409
+ kebab_case: bool,
1410
+ ) -> None:
1411
+ """Run the linear guided sort flow: groups -> preview -> confirm and apply."""
1412
+ selected_clusters = _interactive_select_clusters(discovered, rules_path)
1413
+ if selected_clusters is None:
1414
+ return
1415
+ if selected_clusters:
1416
+ apply_clusters_to_plan(items, selected_clusters, resolve_collision, kebab_case=kebab_case)
1417
+
1418
+ print("")
1419
+ print(format_plan_report(items, notices, dry_run=True))
1420
+
1421
+ planned_count = sum(1 for item in items if item["status"] == "planned")
1422
+ if planned_count == 0:
1423
+ print("No files scheduled to move.")
1424
+ return
1425
+
1426
+ try:
1427
+ confirm = input("Apply these moves now? (y/n): ").strip().lower()
1428
+ except (EOFError, KeyboardInterrupt):
1429
+ print("\nMove cancelled.")
1430
+ return
1431
+ if confirm not in {"y", "yes"}:
1432
+ print("Move cancelled.")
1433
+ return
1434
+
1435
+ run_id, summary = apply_plan(items, targets, rules_path, log_dir, mode="Guided sort")
1436
+ if run_id is None:
1437
+ print("No files moved.")
1438
+ return
1439
+ print(
1440
+ f"Apply complete (run {run_id}): {summary['committed']} committed, "
1441
+ f"{summary['skipped']} skipped, {summary['failed']} failed."
1442
+ )
1443
+ print(f"Undo log saved to: {log_dir / f'{run_id}.json'}")
1444
+
1445
+
1446
+ def _dedupe_paths(paths: list[Path]) -> list[Path]:
1447
+ """Return paths deduplicated case-insensitively while preserving order."""
1448
+ seen: set[str] = set()
1449
+ unique: list[Path] = []
1450
+ for path in paths:
1451
+ key = _collision_key(path.resolve(strict=False))
1452
+ if key not in seen:
1453
+ seen.add(key)
1454
+ unique.append(path)
1455
+ return unique
1456
+
1457
+
1458
+ def _interactive_pick_batch_targets(
1459
+ current_targets: list[Path], current_allow_temp: bool
1460
+ ) -> tuple[list[Path], bool] | None:
1461
+ """Prompt the user to pick one or more folders for batch renaming."""
1462
+ profile = user_profile_dir()
1463
+ current_label = ", ".join(str(p.resolve(strict=False)) for p in current_targets)
1464
+ print("\nBatch rename (kebab-case, in-place)")
1465
+ print("Select folder(s) to scan:")
1466
+ print(f" 1. Current target folder(s): {current_label}")
1467
+ print(" 2. Downloads")
1468
+ print(" 3. Desktop")
1469
+ print(" 4. Documents")
1470
+ print(" 5. All defaults (Downloads, Desktop, Documents)")
1471
+ print(" 6. Custom folder path(s) (comma-separated)")
1472
+ print(" 0. Cancel")
1473
+ try:
1474
+ raw_choice = input("Select option(s) (e.g. 1, 2,3, or 6): ").strip()
1475
+ except (EOFError, KeyboardInterrupt):
1476
+ print("\nBatch rename cancelled.")
1477
+ return None
1478
+ if raw_choice in {"", "0"}:
1479
+ print("Batch rename cancelled.")
1480
+ return None
1481
+
1482
+ tokens = [part.strip() for part in raw_choice.split(",") if part.strip()]
1483
+ if tokens == ["6"]:
1484
+ try:
1485
+ raw_paths = input("Enter folder path(s) (comma-separated): ").strip()
1486
+ except (EOFError, KeyboardInterrupt):
1487
+ print("\nBatch rename cancelled.")
1488
+ return None
1489
+ parts = [p.strip().strip('"') for p in raw_paths.split(",") if p.strip().strip('"')]
1490
+ if not parts:
1491
+ print("No paths entered.")
1492
+ return None
1493
+ chosen: list[Path] = []
1494
+ for raw_path in parts:
1495
+ candidate = Path(raw_path).resolve(strict=False)
1496
+ if not candidate.exists() or not candidate.is_dir():
1497
+ print(f"Folder not found: {candidate}")
1498
+ return None
1499
+ if is_system_path(candidate, allow_temp_subdir=True):
1500
+ print(f"Protected system folder cannot be targeted: {candidate}")
1501
+ return None
1502
+ chosen.append(candidate)
1503
+ return _dedupe_paths(chosen), True
1504
+
1505
+ preset_map = {
1506
+ "1": current_targets,
1507
+ "2": [profile / "Downloads"],
1508
+ "3": [profile / "Desktop"],
1509
+ "4": [profile / "Documents"],
1510
+ "5": default_targets(),
1511
+ }
1512
+ selected: list[Path] = []
1513
+ selected_allow_temp = False
1514
+ for tok in tokens:
1515
+ if tok not in preset_map:
1516
+ print(f"Invalid selection: {tok}")
1517
+ return None
1518
+ if tok == "1" and current_allow_temp:
1519
+ selected_allow_temp = True
1520
+ selected.extend(preset_map[tok])
1521
+ return _dedupe_paths(selected), selected_allow_temp
1522
+
1523
+
1524
+ def _interactive_batch_rename(
1525
+ current_targets: list[Path],
1526
+ current_allow_temp: bool,
1527
+ rules_path: Path,
1528
+ log_dir: Path,
1529
+ ) -> None:
1530
+ """Run the interactive batch rename flow: pick folders -> scope -> preview -> confirm."""
1531
+ picked = _interactive_pick_batch_targets(current_targets, current_allow_temp)
1532
+ if picked is None:
1533
+ return
1534
+ selected_targets, batch_allow_temp = picked
1535
+
1536
+ print("\nSelect items to rename to kebab-case:")
1537
+ print(" a. Files only (top-level loose files, in place)")
1538
+ print(" b. Subfolders in root folder only (top-level subfolders)")
1539
+ print(" c. Folders and files inside them (top-level files, safe subfolders, and files inside them)")
1540
+ print(" 0. Cancel")
1541
+ try:
1542
+ scope = input("Choose scope (a/b/c, or 0 to cancel): ").strip().lower()
1543
+ except (EOFError, KeyboardInterrupt):
1544
+ print("\nBatch rename cancelled.")
1545
+ return
1546
+ if scope in {"", "0"}:
1547
+ print("Batch rename cancelled.")
1548
+ return
1549
+ scope_map = {
1550
+ "a": (True, False),
1551
+ "b": (False, True),
1552
+ "c": (True, True),
1553
+ }
1554
+ if scope not in scope_map:
1555
+ print("Invalid selection.")
1556
+ return
1557
+ rename_files, rename_folders = scope_map[scope]
1558
+
1559
+ items, notices = build_rename_plan(
1560
+ selected_targets,
1561
+ rename_files=rename_files,
1562
+ rename_folders=rename_folders,
1563
+ allow_temp_sandbox=batch_allow_temp,
1564
+ )
1565
+ print("")
1566
+ print(format_plan_report(items, notices, dry_run=True, empty_message="No eligible files or folders found."))
1567
+
1568
+ planned_count = sum(1 for item in items if item["status"] == "planned")
1569
+ if planned_count == 0:
1570
+ print("No items scheduled to rename.")
1571
+ return
1572
+
1573
+ try:
1574
+ confirm = input("Apply these renames now? (y/n): ").strip().lower()
1575
+ except (EOFError, KeyboardInterrupt):
1576
+ print("\nRename cancelled.")
1577
+ return
1578
+ if confirm not in {"y", "yes"}:
1579
+ print("Rename cancelled.")
1580
+ return
1581
+
1582
+ run_id, summary = apply_plan(items, selected_targets, rules_path, log_dir, mode="Batch rename")
1583
+ if run_id is None:
1584
+ print("No items renamed.")
1585
+ return
1586
+ print(
1587
+ f"Apply complete (run {run_id}): {summary['committed']} committed, "
1588
+ f"{summary['skipped']} skipped, {summary['failed']} failed."
1589
+ )
1590
+ print(f"Undo log saved to: {log_dir / f'{run_id}.json'}")
1591
+
1592
+
1593
+ def run_interactive(
1594
+ targets: list[Path],
1595
+ rules_path: Path,
1596
+ log_dir: Path,
1597
+ allow_temp_sandbox: bool = False,
1598
+ kebab_case: bool = False,
1599
+ ) -> int:
1600
+ """Run the auto-scan dashboard and 6-option interactive terminal loop."""
1601
+ current_targets = list(targets)
1602
+ allow_temp = allow_temp_sandbox
1603
+ kebab_enabled = bool(kebab_case)
1604
+ while True:
1605
+ try:
1606
+ rules = load_rules(rules_path)
1607
+ except (OSError, json.JSONDecodeError, KeyError, ValueError) as exc:
1608
+ print(f"Error loading rules from {rules_path}: {exc}", file=sys.stderr)
1609
+ return 1
1610
+
1611
+ items, notices = build_plan(
1612
+ current_targets, rules, allow_temp_sandbox=allow_temp, kebab_case=kebab_enabled
1613
+ )
1614
+ discovered = discover_clusters(items, kebab_case=kebab_enabled)
1615
+
1616
+ _print_interactive_header(
1617
+ current_targets, items, notices,
1618
+ cluster_count=len(discovered), kebab_case=kebab_enabled,
1619
+ )
1620
+ try:
1621
+ choice = input("Enter choice (1-6): ").strip()
1622
+ except (EOFError, KeyboardInterrupt):
1623
+ print("\nExiting Sweep.")
1624
+ return 0
1625
+
1626
+ if choice == "1":
1627
+ _interactive_guided_sort(
1628
+ items, notices, discovered, current_targets, rules_path, log_dir, kebab_enabled
1629
+ )
1630
+ elif choice == "2":
1631
+ current_targets, allow_temp = _interactive_change_target(current_targets, allow_temp)
1632
+ elif choice == "3":
1633
+ kebab_enabled = not kebab_enabled
1634
+ print(f"Kebab-case renaming is now {'ON' if kebab_enabled else 'OFF'}.")
1635
+ elif choice == "4":
1636
+ _interactive_undo(log_dir)
1637
+ elif choice == "5":
1638
+ _interactive_batch_rename(current_targets, allow_temp, rules_path, log_dir)
1639
+ elif choice == "6":
1640
+ print("Goodbye.")
1641
+ return 0
1642
+ else:
1643
+ print("Invalid choice. Please enter a number from 1 to 6.")
1644
+
1645
+
1646
+ def build_parser() -> argparse.ArgumentParser:
1647
+ """Create the CLI argument parser for Sweep."""
1648
+ parser = argparse.ArgumentParser(prog="sweep", description="Safe, reversible Windows file organiser.")
1649
+ parser.add_argument("--version", action="version", version=f"%(prog)s {get_version()}")
1650
+ parser.add_argument("--apply", action="store_true", help="Execute planned moves (default is dry-run).")
1651
+ parser.add_argument("--target", action="append", dest="targets", help="Target folder to scan (repeatable).")
1652
+ parser.add_argument("--rules", type=Path, default=default_rules_path(), help="Path to rules.json.")
1653
+ parser.add_argument("--log-dir", type=Path, default=None, help="Override directory for undo logs.")
1654
+ parser.add_argument(
1655
+ "--kebab",
1656
+ action="store_true",
1657
+ help="Normalise destination filenames and auto-created category folders to lowercase kebab-case (opt-in).",
1658
+ )
1659
+ parser.add_argument(
1660
+ "--rename-only",
1661
+ action="store_true",
1662
+ help="Rename eligible loose files in place to lowercase kebab-case without sorting into folders.",
1663
+ )
1664
+ parser.add_argument(
1665
+ "--rename-folders",
1666
+ action="store_true",
1667
+ help="Opt-in: rename safe top-level subfolders (and files inside them when paired with --rename-only).",
1668
+ )
1669
+
1670
+ subparsers = parser.add_subparsers(dest="command")
1671
+ undo_parser = subparsers.add_parser("undo", help="Reverse a previously applied run.")
1672
+ undo_parser.add_argument("--run", dest="run_id", default=None, help="Specific run ID to undo.")
1673
+ undo_parser.add_argument("--log-dir", type=Path, default=argparse.SUPPRESS, help="Override undo log directory.")
1674
+ undo_parser.add_argument(
1675
+ "--list",
1676
+ action="store_true",
1677
+ help="List recent logged runs without undoing.",
1678
+ )
1679
+ undo_parser.add_argument(
1680
+ "--dry-run",
1681
+ action="store_true",
1682
+ help="Preview the items that would be restored without modifying disk.",
1683
+ )
1684
+ return parser
1685
+
1686
+
1687
+ def main(argv: list[str] | None = None) -> int:
1688
+ """Entry point for the Sweep CLI."""
1689
+ if hasattr(sys.stdout, "reconfigure"):
1690
+ sys.stdout.reconfigure(encoding="utf-8", errors="replace")
1691
+ if hasattr(sys.stderr, "reconfigure"):
1692
+ sys.stderr.reconfigure(encoding="utf-8", errors="replace")
1693
+
1694
+ raw_argv = sys.argv[1:] if argv is None else argv
1695
+ if _is_interactive_session(raw_argv):
1696
+ return run_interactive(default_targets(), default_rules_path(), default_log_dir())
1697
+
1698
+ args = build_parser().parse_args(raw_argv)
1699
+ log_dir = args.log_dir if getattr(args, "log_dir", None) else default_log_dir()
1700
+
1701
+ if args.command == "undo":
1702
+ if args.list:
1703
+ if not log_dir.exists():
1704
+ print(f"No undo logs found in {log_dir}.")
1705
+ return 0
1706
+ runs = load_wal_runs(log_dir)
1707
+ if not runs:
1708
+ print("No undo logs available.")
1709
+ return 0
1710
+ print(format_undo_list(runs, limit=10))
1711
+ return 0
1712
+ if args.dry_run:
1713
+ try:
1714
+ log_path = _select_log_file(log_dir, args.run_id)
1715
+ log_payload = json.loads(log_path.read_text(encoding="utf-8"))
1716
+ except (FileNotFoundError, json.JSONDecodeError, KeyError, OSError) as exc:
1717
+ print(f"Undo error: {exc}", file=sys.stderr)
1718
+ return 1
1719
+ print(format_undo_preview(log_payload, limit=None, dry_run_header=True))
1720
+ return 0
1721
+ try:
1722
+ undone_id, summary = undo_run(log_dir, args.run_id)
1723
+ except (FileNotFoundError, json.JSONDecodeError, KeyError, OSError) as exc:
1724
+ print(f"Undo error: {exc}", file=sys.stderr)
1725
+ return 1
1726
+ print(
1727
+ f"Undo complete for run {undone_id}: {summary['restored']} restored, "
1728
+ f"{summary['already_in_place']} already at source, "
1729
+ f"{summary['skipped']} skipped, {summary['failed']} failed."
1730
+ )
1731
+ return 1 if summary["failed"] else 0
1732
+
1733
+ explicit_targets = bool(args.targets)
1734
+ targets = [Path(t) for t in args.targets] if explicit_targets else default_targets()
1735
+ if explicit_targets:
1736
+ missing = [str(t) for t in targets if not t.exists() or not t.is_dir()]
1737
+ if missing:
1738
+ print(f"Error: target folder not found: {', '.join(missing)}", file=sys.stderr)
1739
+ return 1
1740
+
1741
+ if args.rename_only or args.rename_folders:
1742
+ items, notices = build_rename_plan(
1743
+ targets,
1744
+ rename_files=bool(args.rename_only),
1745
+ rename_folders=bool(args.rename_folders),
1746
+ allow_temp_sandbox=explicit_targets,
1747
+ )
1748
+ print(format_plan_report(
1749
+ items, notices, dry_run=not args.apply,
1750
+ empty_message="No eligible files or folders found.",
1751
+ ))
1752
+ else:
1753
+ try:
1754
+ rules = load_rules(args.rules)
1755
+ except (OSError, json.JSONDecodeError, KeyError, ValueError) as exc:
1756
+ print(f"Error loading rules from {args.rules}: {exc}", file=sys.stderr)
1757
+ return 1
1758
+
1759
+ items, notices = build_plan(
1760
+ targets, rules, allow_temp_sandbox=explicit_targets, kebab_case=args.kebab
1761
+ )
1762
+ print(format_plan_report(items, notices, dry_run=not args.apply))
1763
+
1764
+ if not args.apply:
1765
+ return 0
1766
+
1767
+ apply_mode = "Batch rename" if (args.rename_only or args.rename_folders) else "Sort"
1768
+ run_id, summary = apply_plan(items, targets, args.rules, log_dir, mode=apply_mode)
1769
+ print("")
1770
+ if run_id is None:
1771
+ print(f"Apply complete: 0 moved, {summary['skipped']} skipped, 0 failed.")
1772
+ return 0
1773
+ print(
1774
+ f"Apply complete (run {run_id}): {summary['committed']} committed, "
1775
+ f"{summary['skipped']} skipped, {summary['failed']} failed."
1776
+ )
1777
+ print(f"Undo log saved to: {log_dir / f'{run_id}.json'}")
1778
+ return 1 if summary["failed"] else 0
1779
+
1780
+
1781
+ if __name__ == "__main__":
1782
+ raise SystemExit(main())