Coverage for fastblocks / actions / sync / settings.py: 34%

358 statements  

« prev     ^ index     » next       coverage.py v7.13.1, created at 2026-01-02 20:00 -0800

1"""Settings file synchronization between filesystem and cloud storage. 

2 

3Settings sync is intentionally limited to filesystem and cloud storage only. 

4Unlike templates, settings are not cached for security and consistency reasons. 

5""" 

6 

7import typing as t 

8from pathlib import Path 

9 

10import yaml 

11from oneiric.core.resolution import Resolver 

12 

13# Migration from ACB to Oneiric 

14depends = Resolver() 

15 

16# ACB compatibility imports - these will be migrated in future phases 

17try: 

18 # MIGRATED: Removed ACB import - using Oneiric equivalent 

19 # MIGRATED: Removed ACB import - debug import debug 

20 pass 

21except ImportError: 

22 # Fallback for Oneiric-only mode 

23 def debug(msg: str) -> None: 

24 """Debug function fallback.""" 

25 print(f"[DEBUG] {msg}") 

26 

27 # Note: hash module would need Oneiric equivalent for production use 

28 import hashlib 

29 

30 class HashFallback: 

31 @staticmethod 

32 async def blake3(data: bytes) -> str: 

33 """Blake3 fallback using SHA256.""" 

34 return hashlib.sha256(data).hexdigest() 

35 

36 hash = HashFallback() 

37 

38from anyio import Path as AsyncPath 

39 

40from .strategies import ( 

41 ConflictStrategy, 

42 SyncDirection, 

43 SyncResult, 

44 SyncStrategy, 

45 create_backup, 

46 get_file_info, 

47 resolve_conflict, 

48 should_sync, 

49) 

50 

51 

52class SettingsSyncResult(SyncResult): 

53 def __init__( 

54 self, 

55 *, 

56 config_reloaded: list[str] | None = None, 

57 adapters_affected: list[str] | None = None, 

58 **kwargs: t.Any, 

59 ) -> None: 

60 super().__init__(**kwargs) 

61 self.config_reloaded = config_reloaded if config_reloaded is not None else [] 

62 self.adapters_affected = ( 

63 adapters_affected if adapters_affected is not None else [] 

64 ) 

65 

66 

67async def sync_settings( 

68 *, 

69 settings_path: AsyncPath | None = None, 

70 adapter_names: list[str] | None = None, 

71 strategy: SyncStrategy | None = None, 

72 storage_bucket: str | None = None, 

73 reload_config: bool = True, 

74) -> SettingsSyncResult: 

75 config = _prepare_settings_sync_config(settings_path, strategy) 

76 result = SettingsSyncResult() 

77 

78 if storage_bucket is None: 

79 storage_bucket = await _get_default_settings_bucket() 

80 

81 storage = await _initialize_storage_only(result) 

82 if not storage: 

83 return result 

84 

85 settings_files = await _discover_settings_files( 

86 config["settings_path"], 

87 adapter_names, 

88 ) 

89 if not settings_files: 

90 debug("No settings files found to sync") 

91 return result 

92 

93 debug(f"Found {len(settings_files)} settings files to sync") 

94 

95 await _sync_settings_files( 

96 settings_files, 

97 storage, 

98 config["strategy"], 

99 storage_bucket, 

100 result, 

101 ) 

102 

103 await _handle_config_reload(reload_config, result) 

104 

105 debug( 

106 f"Settings sync completed: {len(result.synced_items)} synced, {len(result.conflicts)} conflicts", 

107 ) 

108 

109 return result 

110 

111 

112def _prepare_settings_sync_config( 

113 settings_path: AsyncPath | None, 

114 strategy: SyncStrategy | None, 

115) -> dict[str, t.Any]: 

116 return { 

117 "settings_path": settings_path or AsyncPath("settings"), 

118 "strategy": strategy or SyncStrategy(), 

119 } 

120 

121 

122async def _initialize_storage_only(result: SettingsSyncResult) -> t.Any | None: 

123 try: 

124 # MIGRATED: Removed ACB import - using Oneiric equivalent 

125 

126 storage = await depends.resolve("fastblocks", "storage") 

127 if not storage: 

128 result.errors.append(Exception("Storage adapter not available")) 

129 return None 

130 

131 return storage 

132 except Exception as e: 

133 result.errors.append(e) 

134 return None 

135 

136 

137async def _get_default_settings_bucket() -> str: 

138 try: 

139 storage_config_path = AsyncPath("settings/storage.yml") 

140 if await storage_config_path.exists(): 

141 content = await storage_config_path.read_text() 

142 config = yaml.safe_load(content) 

143 if isinstance(config, dict): 

144 bucket_name = t.cast( 

145 str, config.get("buckets", {}).get("settings", "settings") 

146 ) 

147 else: 

148 bucket_name = "settings" 

149 debug(f"Using settings bucket from config: {bucket_name}") 

150 return bucket_name 

151 except Exception as e: 

152 debug(f"Could not load storage config, using default: {e}") 

153 debug("Using fallback settings bucket: settings") 

154 return "settings" 

155 

156 

157async def _sync_settings_files( 

158 settings_files: list[dict[str, t.Any]], 

159 storage: t.Any, 

160 strategy: SyncStrategy, 

161 storage_bucket: str, 

162 result: SettingsSyncResult, 

163) -> None: 

164 for settings_info in settings_files: 

165 try: 

166 file_result = await _sync_single_settings_file( 

167 settings_info, 

168 storage, 

169 strategy, 

170 storage_bucket, 

171 ) 

172 _accumulate_settings_sync_results(file_result, result) 

173 

174 except Exception as e: 

175 result.errors.append(e) 

176 debug(f"Error syncing settings {settings_info['relative_path']}: {e}") 

177 

178 

179def _accumulate_settings_sync_results( 

180 file_result: dict[str, t.Any], 

181 result: SettingsSyncResult, 

182) -> None: 

183 if file_result.get("synced"): 

184 result.synced_items.extend(file_result["synced"]) 

185 result.adapters_affected.extend(file_result.get("adapters_affected", [])) 

186 if file_result.get("conflicts"): 

187 result.conflicts.extend(file_result["conflicts"]) 

188 if file_result.get("errors"): 

189 result.errors.extend(file_result["errors"]) 

190 if file_result.get("skipped"): 

191 result.skipped.extend(file_result["skipped"]) 

192 if file_result.get("backed_up"): 

193 result.backed_up.extend(file_result["backed_up"]) 

194 

195 

196async def _handle_config_reload( 

197 reload_config: bool, 

198 result: SettingsSyncResult, 

199) -> None: 

200 if reload_config and result.synced_items: 

201 try: 

202 await _reload_configuration(result.adapters_affected) 

203 result.config_reloaded = result.adapters_affected.copy() 

204 except Exception as e: 

205 result.errors.append(e) 

206 debug(f"Error reloading configuration: {e}") 

207 

208 

209async def _discover_settings_files( 

210 settings_path: AsyncPath, 

211 adapter_names: list[str] | None = None, 

212) -> list[dict[str, t.Any]]: 

213 settings_files: list[dict[str, t.Any]] = [] 

214 

215 if not await settings_path.exists(): 

216 debug(f"Settings path does not exist: {settings_path}") 

217 return settings_files 

218 

219 for pattern in ("*.yml", "*.yaml"): 

220 await _discover_files_with_pattern( 

221 settings_path, 

222 pattern, 

223 adapter_names, 

224 settings_files, 

225 ) 

226 

227 return settings_files 

228 

229 

230async def _discover_files_with_pattern( 

231 settings_path: AsyncPath, 

232 pattern: str, 

233 adapter_names: list[str] | None, 

234 settings_files: list[dict[str, t.Any]], 

235) -> None: 

236 async for file_path in settings_path.rglob(pattern): 

237 if await file_path.is_file(): 

238 await _process_settings_file( 

239 file_path, 

240 settings_path, 

241 adapter_names, 

242 settings_files, 

243 ) 

244 

245 

246async def _process_settings_file( 

247 file_path: AsyncPath, 

248 settings_path: AsyncPath, 

249 adapter_names: list[str] | None, 

250 settings_files: list[dict[str, t.Any]], 

251) -> None: 

252 adapter_name = file_path.stem 

253 

254 if adapter_names and adapter_name not in adapter_names: 

255 return 

256 

257 try: 

258 rel_path = file_path.relative_to(settings_path) 

259 settings_files.append( 

260 { 

261 "local_path": file_path, 

262 "relative_path": rel_path, 

263 "storage_path": str(rel_path), 

264 "adapter_name": adapter_name, 

265 }, 

266 ) 

267 except ValueError: 

268 debug(f"Could not get relative path for {file_path}") 

269 

270 

271async def _sync_single_settings_file( 

272 settings_info: dict[str, t.Any], 

273 storage: t.Any, 

274 strategy: SyncStrategy, 

275 storage_bucket: str, 

276) -> dict[str, t.Any]: 

277 local_path = settings_info["local_path"] 

278 storage_path = settings_info["storage_path"] 

279 adapter_name = settings_info["adapter_name"] 

280 

281 result = _create_sync_result() 

282 

283 try: 

284 local_info, remote_info = await _get_file_infos( 

285 local_path, 

286 storage, 

287 storage_bucket, 

288 storage_path, 

289 ) 

290 

291 if not await _should_sync_file( 

292 local_info, 

293 remote_info, 

294 strategy, 

295 storage_path, 

296 result, 

297 ): 

298 return result 

299 

300 if not await _validate_local_yaml(local_info, storage_path, result): 

301 return result 

302 

303 await _execute_sync_operation( 

304 local_path, 

305 storage, 

306 storage_bucket, 

307 storage_path, 

308 local_info, 

309 remote_info, 

310 strategy, 

311 result, 

312 ) 

313 

314 if result["synced"]: 

315 result["adapters_affected"].append(adapter_name) 

316 

317 except Exception as e: 

318 result["errors"].append(e) 

319 debug(f"Error in _sync_single_settings_file for {storage_path}: {e}") 

320 

321 return result 

322 

323 

324def _create_sync_result() -> dict[str, t.Any]: 

325 return { 

326 "synced": [], 

327 "conflicts": [], 

328 "errors": [], 

329 "skipped": [], 

330 "backed_up": [], 

331 "adapters_affected": [], 

332 } 

333 

334 

335async def _get_file_infos( 

336 local_path: t.Any, 

337 storage: t.Any, 

338 storage_bucket: str, 

339 storage_path: str, 

340) -> tuple[dict[str, t.Any], dict[str, t.Any]]: 

341 local_info = await get_file_info(Path(local_path)) 

342 remote_info = await _get_storage_file_info(storage, storage_bucket, storage_path) 

343 return local_info, remote_info 

344 

345 

346async def _should_sync_file( 

347 local_info: dict[str, t.Any], 

348 remote_info: dict[str, t.Any], 

349 strategy: SyncStrategy, 

350 storage_path: str, 

351 result: dict[str, t.Any], 

352) -> bool: 

353 sync_needed, reason = should_sync(local_info, remote_info, strategy.direction) 

354 if not sync_needed: 

355 result["skipped"].append(f"{storage_path} ({reason})") 

356 return False 

357 

358 debug(f"Syncing settings {storage_path}: {reason}") 

359 return True 

360 

361 

362async def _validate_local_yaml( 

363 local_info: dict[str, t.Any], 

364 storage_path: str, 

365 result: dict[str, t.Any], 

366) -> bool: 

367 if local_info["exists"]: 

368 try: 

369 await _validate_yaml_content(local_info["content"]) 

370 except Exception as e: 

371 result["errors"].append(f"Invalid YAML in {storage_path}: {e}") 

372 return False 

373 return True 

374 

375 

376async def _execute_sync_operation( 

377 local_path: t.Any, 

378 storage: t.Any, 

379 storage_bucket: str, 

380 storage_path: str, 

381 local_info: dict[str, t.Any], 

382 remote_info: dict[str, t.Any], 

383 strategy: SyncStrategy, 

384 result: dict[str, t.Any], 

385) -> None: 

386 if _should_pull_settings(strategy, local_info, remote_info): 

387 await _pull_settings( 

388 local_path, 

389 storage, 

390 storage_bucket, 

391 storage_path, 

392 strategy, 

393 result, 

394 ) 

395 elif _should_push_settings(strategy, local_info, remote_info): 

396 await _push_settings( 

397 local_path, 

398 storage, 

399 storage_bucket, 

400 storage_path, 

401 strategy, 

402 result, 

403 ) 

404 elif _has_bidirectional_conflict(strategy, local_info, remote_info): 

405 await _handle_settings_conflict( 

406 local_path, 

407 storage, 

408 storage_bucket, 

409 storage_path, 

410 local_info, 

411 remote_info, 

412 strategy, 

413 result, 

414 ) 

415 

416 

417def _should_pull_settings( 

418 strategy: SyncStrategy, 

419 local_info: dict[str, t.Any], 

420 remote_info: dict[str, t.Any], 

421) -> bool: 

422 return strategy.direction == SyncDirection.PULL or ( 

423 strategy.direction == SyncDirection.BIDIRECTIONAL 

424 and remote_info["exists"] 

425 and (not local_info["exists"] or remote_info["mtime"] > local_info["mtime"]) 

426 ) 

427 

428 

429def _should_push_settings( 

430 strategy: SyncStrategy, 

431 local_info: dict[str, t.Any], 

432 remote_info: dict[str, t.Any], 

433) -> bool: 

434 return strategy.direction == SyncDirection.PUSH or ( 

435 strategy.direction == SyncDirection.BIDIRECTIONAL 

436 and local_info["exists"] 

437 and (not remote_info["exists"] or local_info["mtime"] > remote_info["mtime"]) 

438 ) 

439 

440 

441def _has_bidirectional_conflict( 

442 strategy: SyncStrategy, 

443 local_info: dict[str, t.Any], 

444 remote_info: dict[str, t.Any], 

445) -> bool: 

446 return ( 

447 strategy.direction == SyncDirection.BIDIRECTIONAL 

448 and local_info["exists"] 

449 and remote_info["exists"] 

450 ) 

451 

452 

453async def _get_storage_file_info( 

454 storage: t.Any, 

455 bucket: str, 

456 file_path: str, 

457) -> dict[str, t.Any]: 

458 try: 

459 bucket_obj = getattr(storage, bucket, None) 

460 

461 if not bucket_obj: 

462 await storage._create_bucket(bucket) 

463 bucket_obj = getattr(storage, bucket) 

464 

465 exists = await bucket_obj.exists(file_path) 

466 

467 if not exists: 

468 return { 

469 "exists": False, 

470 "size": 0, 

471 "mtime": 0, 

472 "content_hash": None, 

473 } 

474 

475 content = await bucket_obj.read(file_path) 

476 metadata = await bucket_obj.stat(file_path) 

477 

478 # ACB's Blake3 is 10x faster than Blake2b for cryptographic hashing 

479 content_hash = await hash.blake3(content) 

480 

481 return { 

482 "exists": True, 

483 "size": len(content), 

484 "mtime": metadata.get("mtime", 0), 

485 "content_hash": content_hash, 

486 "content": content, 

487 } 

488 

489 except Exception as e: 

490 debug(f"Error getting storage file info for {file_path}: {e}") 

491 return { 

492 "exists": False, 

493 "size": 0, 

494 "mtime": 0, 

495 "content_hash": None, 

496 "error": str(e), 

497 } 

498 

499 

500async def _validate_yaml_content(content: bytes) -> None: 

501 try: 

502 import yaml 

503 

504 yaml.safe_load(content.decode()) 

505 except Exception as e: 

506 msg = f"Invalid YAML content: {e}" 

507 raise ValueError(msg) 

508 

509 

510async def _pull_settings( 

511 local_path: AsyncPath, 

512 storage: t.Any, 

513 bucket: str, 

514 storage_path: str, 

515 strategy: SyncStrategy, 

516 result: dict[str, t.Any], 

517) -> None: 

518 try: 

519 bucket_obj = getattr(storage, bucket) 

520 

521 if strategy.dry_run: 

522 debug(f"DRY RUN: Would pull {storage_path} to {local_path}") 

523 result["synced"].append(f"PULL(dry-run): {storage_path}") 

524 return 

525 

526 if await local_path.exists() and strategy.backup_on_conflict: 

527 backup_path = await create_backup(Path(local_path)) 

528 result["backed_up"].append(str(backup_path)) 

529 

530 content = await bucket_obj.read(storage_path) 

531 

532 await _validate_yaml_content(content) 

533 

534 await local_path.parent.mkdir(parents=True, exist_ok=True) 

535 

536 await local_path.write_bytes(content) 

537 

538 result["synced"].append(f"PULL: {storage_path}") 

539 debug(f"Pulled settings from storage: {storage_path}") 

540 

541 except Exception as e: 

542 result["errors"].append(e) 

543 debug(f"Error pulling settings {storage_path}: {e}") 

544 

545 

546async def _push_settings( 

547 local_path: AsyncPath, 

548 storage: t.Any, 

549 bucket: str, 

550 storage_path: str, 

551 strategy: SyncStrategy, 

552 result: dict[str, t.Any], 

553) -> None: 

554 try: 

555 bucket_obj = getattr(storage, bucket) 

556 

557 if strategy.dry_run: 

558 debug(f"DRY RUN: Would push {local_path} to {storage_path}") 

559 result["synced"].append(f"PUSH(dry-run): {storage_path}") 

560 return 

561 

562 content = await local_path.read_bytes() 

563 await _validate_yaml_content(content) 

564 

565 await bucket_obj.write(storage_path, content) 

566 

567 result["synced"].append(f"PUSH: {storage_path}") 

568 debug(f"Pushed settings to storage: {storage_path}") 

569 

570 except Exception as e: 

571 result["errors"].append(e) 

572 debug(f"Error pushing settings {storage_path}: {e}") 

573 

574 

575async def _handle_settings_conflict( 

576 local_path: AsyncPath, 

577 storage: t.Any, 

578 bucket: str, 

579 storage_path: str, 

580 local_info: dict[str, t.Any], 

581 remote_info: dict[str, t.Any], 

582 strategy: SyncStrategy, 

583 result: dict[str, t.Any], 

584) -> None: 

585 try: 

586 if strategy.conflict_strategy == ConflictStrategy.MANUAL: 

587 result["conflicts"].append( 

588 { 

589 "path": storage_path, 

590 "local_mtime": local_info["mtime"], 

591 "remote_mtime": remote_info["mtime"], 

592 "reason": "manual_resolution_required", 

593 }, 

594 ) 

595 return 

596 

597 try: 

598 await _validate_yaml_content(local_info["content"]) 

599 await _validate_yaml_content(remote_info["content"]) 

600 except Exception as e: 

601 result["errors"].append(f"Invalid YAML during conflict resolution: {e}") 

602 return 

603 

604 resolved_content, resolution_reason = await resolve_conflict( 

605 Path(local_path), 

606 remote_info["content"], 

607 local_info["content"], 

608 strategy.conflict_strategy, 

609 local_info["mtime"], 

610 remote_info["mtime"], 

611 ) 

612 

613 if strategy.dry_run: 

614 debug( 

615 f"DRY RUN: Would resolve conflict for {storage_path}: {resolution_reason}", 

616 ) 

617 result["synced"].append( 

618 f"CONFLICT(dry-run): {storage_path} - {resolution_reason}", 

619 ) 

620 return 

621 

622 if ( 

623 strategy.backup_on_conflict 

624 or strategy.conflict_strategy == ConflictStrategy.BACKUP_BOTH 

625 ): 

626 backup_path = await create_backup(Path(local_path), "conflict") 

627 result["backed_up"].append(str(backup_path)) 

628 

629 if resolved_content == remote_info["content"]: 

630 await local_path.write_bytes(resolved_content) 

631 result["synced"].append( 

632 f"CONFLICT->REMOTE: {storage_path} - {resolution_reason}", 

633 ) 

634 else: 

635 bucket_obj = getattr(storage, bucket) 

636 await bucket_obj.write(storage_path, resolved_content) 

637 result["synced"].append( 

638 f"CONFLICT->LOCAL: {storage_path} - {resolution_reason}", 

639 ) 

640 

641 debug(f"Resolved settings conflict: {storage_path} - {resolution_reason}") 

642 

643 except Exception as e: 

644 result["errors"].append(e) 

645 result["conflicts"].append( 

646 { 

647 "path": storage_path, 

648 "error": str(e), 

649 "reason": "resolution_failed", 

650 }, 

651 ) 

652 

653 

654async def _reload_configuration(adapter_names: list[str]) -> None: 

655 try: 

656 # MIGRATED: Removed ACB import - using Oneiric equivalent 

657 # MIGRATED: Removed ACB import - using Oneiric equivalent 

658 

659 config = await reload_config() 

660 depends.set("config", config) 

661 debug(f"Reloaded configuration for adapters: {adapter_names}") 

662 except Exception as e: 

663 debug(f"Error reloading configuration: {e}") 

664 raise 

665 

666 

667async def backup_settings( 

668 settings_path: AsyncPath | None = None, 

669 backup_suffix: str | None = None, 

670) -> dict[str, t.Any]: 

671 settings_path = settings_path or AsyncPath("settings") 

672 backup_suffix = backup_suffix or _generate_backup_suffix() 

673 

674 result = _create_backup_result() 

675 

676 try: 

677 if not await settings_path.exists(): 

678 result["errors"].append(f"Settings path does not exist: {settings_path}") 

679 return result 

680 

681 await _backup_files_with_patterns(settings_path, backup_suffix, result) 

682 

683 except Exception as e: 

684 result["errors"].append(str(e)) 

685 debug(f"Error in backup_settings: {e}") 

686 

687 return result 

688 

689 

690def _generate_backup_suffix() -> str: 

691 import time 

692 

693 timestamp = int(time.time()) 

694 return f"backup_{timestamp}" 

695 

696 

697def _create_backup_result() -> dict[str, t.Any]: 

698 return { 

699 "backed_up": [], 

700 "errors": [], 

701 "skipped": [], 

702 } 

703 

704 

705async def _backup_files_with_patterns( 

706 settings_path: AsyncPath, 

707 backup_suffix: str, 

708 result: dict[str, t.Any], 

709) -> None: 

710 patterns = ["*.yml", "*.yaml"] 

711 

712 for pattern in patterns: 

713 await _backup_files_with_pattern(settings_path, pattern, backup_suffix, result) 

714 

715 

716async def _backup_files_with_pattern( 

717 settings_path: AsyncPath, 

718 pattern: str, 

719 backup_suffix: str, 

720 result: dict[str, t.Any], 

721) -> None: 

722 async for file_path in settings_path.rglob(pattern): 

723 if await file_path.is_file(): 

724 await _backup_single_file(file_path, backup_suffix, result) 

725 

726 

727async def _backup_single_file( 

728 file_path: AsyncPath, 

729 backup_suffix: str, 

730 result: dict[str, t.Any], 

731) -> None: 

732 try: 

733 backup_path = await create_backup(Path(file_path), backup_suffix) 

734 result["backed_up"].append(str(backup_path)) 

735 except Exception as e: 

736 result["errors"].append(f"{file_path}: {e}") 

737 

738 

739async def get_settings_sync_status( 

740 settings_path: AsyncPath | None = None, 

741 storage_bucket: str = "settings", 

742) -> dict[str, t.Any]: 

743 if settings_path is None: 

744 settings_path = AsyncPath("settings") 

745 

746 status: dict[str, t.Any] = { 

747 "total_settings": 0, 

748 "in_sync": 0, 

749 "out_of_sync": 0, 

750 "local_only": 0, 

751 "remote_only": 0, 

752 "conflicts": 0, 

753 "details": [], 

754 } 

755 

756 try: 

757 storage = await _get_storage_adapter() 

758 if not storage: 

759 status["error"] = "Storage adapter not available" 

760 return status 

761 

762 settings_files = await _discover_settings_files(settings_path) 

763 status["total_settings"] = len(settings_files) 

764 

765 await _process_settings_files(settings_files, storage, storage_bucket, status) 

766 

767 status["out_of_sync"] = ( 

768 status["conflicts"] + status["local_only"] + status["remote_only"] 

769 ) 

770 

771 except Exception as e: 

772 status["error"] = str(e) 

773 debug(f"Error getting settings sync status: {e}") 

774 

775 return status 

776 

777 

778async def _get_storage_adapter() -> t.Any: 

779 """Get the storage adapter.""" 

780 # MIGRATED: Removed ACB import - using Oneiric equivalent 

781 

782 return depends.resolve("fastblocks", "storage") 

783 

784 

785async def _process_settings_files( 

786 settings_files: list[dict[str, t.Any]], 

787 storage: t.Any, 

788 storage_bucket: str, 

789 status: dict[str, t.Any], 

790) -> None: 

791 """Process all settings files and update status.""" 

792 for settings_info in settings_files: 

793 local_info = await get_file_info(Path(settings_info["local_path"])) 

794 remote_info = await _get_storage_file_info( 

795 storage, 

796 storage_bucket, 

797 settings_info["storage_path"], 

798 ) 

799 

800 file_status = _create_file_status(settings_info, local_info, remote_info) 

801 _update_status_counters(local_info, remote_info, file_status, status) 

802 status["details"].append(file_status) 

803 

804 

805def _create_file_status( 

806 settings_info: dict[str, t.Any], 

807 local_info: dict[str, t.Any], 

808 remote_info: dict[str, t.Any], 

809) -> dict[str, t.Any]: 

810 """Create file status dictionary.""" 

811 file_status: dict[str, t.Any] = { 

812 "path": settings_info["storage_path"], 

813 "adapter": settings_info["adapter_name"], 

814 "local_exists": local_info["exists"], 

815 "remote_exists": remote_info["exists"], 

816 } 

817 

818 # Determine sync status 

819 if local_info["exists"] and remote_info["exists"]: 

820 if local_info["content_hash"] == remote_info["content_hash"]: 

821 file_status["status"] = "in_sync" 

822 else: 

823 file_status["status"] = "conflict" 

824 file_status["local_mtime"] = local_info["mtime"] 

825 file_status["remote_mtime"] = remote_info["mtime"] 

826 elif local_info["exists"]: 

827 file_status["status"] = "local_only" 

828 elif remote_info["exists"]: 

829 file_status["status"] = "remote_only" 

830 else: 

831 file_status["status"] = "missing" 

832 

833 return file_status 

834 

835 

836def _update_status_counters( 

837 local_info: dict[str, t.Any], 

838 remote_info: dict[str, t.Any], 

839 file_status: dict[str, t.Any], 

840 status: dict[str, t.Any], 

841) -> None: 

842 """Update status counters based on file status.""" 

843 if local_info["exists"] and remote_info["exists"]: 

844 if local_info["content_hash"] == remote_info["content_hash"]: 

845 status["in_sync"] += 1 

846 else: 

847 status["conflicts"] += 1 

848 elif local_info["exists"]: 

849 status["local_only"] += 1 

850 elif remote_info["exists"]: 

851 status["remote_only"] += 1 

852 

853 

854async def validate_all_settings( 

855 settings_path: AsyncPath | None = None, 

856) -> dict[str, t.Any]: 

857 if settings_path is None: 

858 settings_path = AsyncPath("settings") 

859 

860 result: dict[str, t.Any] = { 

861 "valid": [], 

862 "invalid": [], 

863 "missing": [], 

864 "total_checked": 0, 

865 } 

866 

867 try: 

868 settings_files = await _discover_settings_files(settings_path) 

869 result["total_checked"] = len(settings_files) 

870 

871 for settings_info in settings_files: 

872 file_path = settings_info["local_path"] 

873 

874 if not await file_path.exists(): 

875 result["missing"].append(str(file_path)) 

876 continue 

877 

878 try: 

879 content = await file_path.read_bytes() 

880 await _validate_yaml_content(content) 

881 result["valid"].append(str(file_path)) 

882 except Exception as e: 

883 result["invalid"].append( 

884 { 

885 "path": str(file_path), 

886 "error": str(e), 

887 }, 

888 ) 

889 

890 except Exception as e: 

891 result["error"] = str(e) 

892 debug(f"Error validating settings: {e}") 

893 

894 return result 

895 

896 

897# Migration status indicator 

898# Note: Partial migration - ACB debug and hash systems still in use 

899_using_oneiric = True # Oneiric resolver available 

900_requires_further_migration = True # ACB systems need migration