Files
museion/Museion/HomeResolution.swift
AlexKucera 8b0d43aed8
CI / ci (push) Canceled after 0s
fix(editor): Home repoint rides the departure gate; document identity is (Home, ID)
Settings committed the new Home and bind flipped watchedHome without
departing the open session: the session's immutable target kept the
OLD Home, a same-slug piece in the new library made the ID-only
reselect return it, and autosave/Save/quit wrote the old library
while structural operations resolved against the new one. #198's
departure gate never saw this seam; a no-collision piece was torn
down by the vanish path with its dirty buffer dropped.

The gate runs BEFORE anything commits. PostsModel.repoint(to:) is a
document departure through the same sessionMayDepart (all three legs:
unanswered #67, failed flush, never-loaded retype — no parallel
gate); on refusal nothing changes (preference, watchedHome, the
session's (A, id) target, its buffer), on acceptance the departed
piece's state dies with it. AppGateState.repointMuseionHome(to:)
commits the preference and its persistence only after the gate;
WorkspaceView's Settings binding routes through it and the root
.task(id:) binds the model after that commit — the dumb binder. A
refusal speaks the #198 reason the way #200's quit refusal does
(hosted-guarded alert: no Posts strip is in sight from Settings).
Nothing auto-reopens after an accepted repoint — the writer picks
from the new list; the in-memory draft survives (no Home until first
save; dropping it would drop the only copy).

Document identity is (Home, ID) everywhere — EditorSession.targets
is the pair, PostsModel.openSessionTargets the model-side question;
every ID-only session comparison is retired: select's reselect
no-op, openUnguarded, the structural rail (rename/trash/move/archive/
restore/unarchive + flushOrAbort), conversion, the pass guard (its
answer now carries the Home it validated), Micropub's launch, the
lock's arm/body reads. Async continuations re-validate identity at
COMPLETION: refreshCards (launch and hop-back — the old ID-only guard
let a scan from the previous library land its cards on the new
library's same-slug piece) and rescan (the stale-Home verdict is
hoisted: a scan that outlived a repoint applies nothing, not just
the vanish check; the #67 disk read runs only for a session targeting
the scan's own Home). scanPieceCards is the per-model injectable
scanner the deterministic stale-scan pin needs.

Tests: PostsModelRepointTests (7) move to the gated entry and go
green (17/17 with PostsModelDepartureTests — the #198 matrix stays
green and composes); the stale-scan pin's RED is a mutation check
(completion guard reverted to ID-only → only that pin fails, cards
→ ["Hedging"]; restored byte-exact). The #179 mid-pass repoint pin
drives the real Settings path now (repoint + bind). swiftformat 0/152,
swiftlint 0.
2026-11-23 20:23:57 +01:00

99 lines
4.1 KiB
Swift

//
// HomeResolution.swift
// Museion
//
// #171: fresh-install Home resolution — the ladder + probes AppGateState
// pins through at first launch. Own file so MuseionApp.swift stays under
// the lint line cap (WritingLockState extraction precedent).
//
import Foundation
extension AppGateState {
/// The legacy default Home — `~/Documents/Museion` (#171: still the
/// fallback when iCloud is absent; b3daac9: Documents, not the account
/// root; TCC note in ADR-0004).
nonisolated static let defaultMuseionHome = FileManager.default.homeDirectoryForCurrentUser
.appendingPathComponent("Documents/Museion", isDirectory: true)
/// The stored override, if it decodes to a file URL (existing
/// semantics — the Home is always a folder).
nonisolated static func fileHomeURL(in defaults: UserDefaults) -> URL? {
defaults.string(forKey: "museionHome")
.flatMap(URL.init(string:))
.flatMap { $0.isFileURL ? $0 : nil }
}
/// #171: the fresh-install ladder — (2) a legacy `~/Documents/Museion`
/// (a real directory, per the default probe's `existingDirectory` gate —
/// the Home is always a folder) IS the Home (existing Homes migrate
/// manually, never silently),
/// (3) `<CloudDocs>/Museion` when iCloud Drive is present,
/// (4) else the silent Documents fallback. The stored override (1) is
/// checked by the caller.
nonisolated static func resolvedInitialHome(
legacyHomeExists: () -> Bool,
cloudDocsDir: () -> URL?,
) -> URL {
if legacyHomeExists() {
return defaultMuseionHome
}
if let cloudDocs = cloudDocsDir() {
return cloudDocs.appendingPathComponent("Museion", isDirectory: true)
}
return defaultMuseionHome
}
/// #171: CloudDocs resolved dynamically at the unprefixed path — the
/// `iCloud~`-prefixed spelling varies per account, never hard-code it.
/// Plain FileManager probing; the app has no ubiquity entitlements
/// (ADR-0009).
nonisolated static func liveCloudDocsDir() -> URL? {
existingDirectory(cloudDocsURL(under: FileManager.default.homeDirectoryForCurrentUser))
}
/// The CloudDocs path — unprefixed (the `iCloud~`-prefixed spelling
/// varies per account, never hard-code it); the seam the spelling pin
/// drives.
nonisolated static func cloudDocsURL(under home: URL) -> URL {
home.appendingPathComponent("Library/Mobile Documents/com~apple~CloudDocs", isDirectory: true)
}
/// `url` back only when it exists AND is a directory — the dir-ness
/// gate `liveCloudDocsDir` rides.
nonisolated static func existingDirectory(_ url: URL) -> URL? {
var isDirectory: ObjCBool = false
guard FileManager.default.fileExists(atPath: url.path, isDirectory: &isDirectory), isDirectory.boolValue else { return nil }
return url
}
/// True when running as the hosted-test runner app (the panes' guard
/// pattern) — machine-state writes and probes are skipped there. Tests
/// constructing `AppGateState` with DEFAULT arguments hit this via the
/// init's early return: neither the real iCloud probes nor the pin run,
/// so the runner app's real state is never touched. An injected suite
/// is a test's own sandbox and always runs the full ladder + pin.
nonisolated static var hostedTestRun: Bool {
ProcessInfo.processInfo.environment["XCTestConfigurationFilePath"] != nil
}
nonisolated static func storeHome(_ home: URL, in defaults: UserDefaults) {
defaults.set(home.absoluteString, forKey: "museionHome")
}
/// brief-28 (home-repoint-retains-old-editor-target): the ONE repoint
/// entry at runtime — the departure gate runs FIRST (`posts.repoint`:
/// every open document lands, or nothing changes and `posts.lastError`
/// names the piece); the preference and its persistence (`museionHome`'s
/// didSet) commit only after. True = committed. WorkspaceView's Settings
/// binding routes through here; the root `.task(id: museionHome)` binds
/// the model after the commit, so `watchedHome` can never move past a
/// live session again.
@discardableResult
func repointMuseionHome(to newHome: URL) -> Bool {
guard posts.repoint(to: newHome) else { return false }
museionHome = newHome
return true
}
}