import Foundation import os // MARK: - HistoryStore /// **A board's git state** (02-architecture.md ▸ Components ▸ HistoryStore): which mode the board /// opened in, the repository behind it when there is one, and the two operations that can change /// either — the app's own add-git, and nothing else. /// /// ### One per board session, composed under the tier /// /// `compose(boardRoot:tier:)` is the whole gate: **the free tier gets no `HistoryStore` at all**, so /// a free-tier session runs no detection, opens no repository, and does not so much as `stat` a /// `.git` — "any `.git` is inert … the app never reads history, never commits, never touches `.git` /// in any way" (12-editions.md ▸ The free tier and `.git`), which `InertGitTests` pins against real /// bytes. Nothing in this type is conditional on a tier, because the tier decided whether the type /// exists. /// /// ### What it does not do yet /// /// This is the foundation card of pro-m1: mode, a repository, add-git, and the loader's path-history /// ranker. **The provider binding is not part of it** — both tiers still bind /// `NativeHistoryProvider` (`AppModel.makeHistoryProvider`), and the consumer of `mode` is the /// undo/redo card two cards later, which builds the git `HistoryProviding` implementation over /// exactly this object. Auto-commit, commit messages, branch controls, the identity fields, remotes /// and `.gitignore` seeding are each their own card and deliberately absent here. @MainActor @Observable public final class HistoryStore { /// The board this is the git state of. The board root *is* the repository's working-tree root /// in git mode — that is what mode `git` means. public let boardRoot: URL /// **Detected once, at composition, and changed by exactly one thing afterwards.** /// /// "Detection is nearest-`.git`-wins, checked at every board open … never mid-session" /// (06-history-undo.md ▸ Rules). A `git init` run in a terminal under an open board therefore /// takes effect at its *next* open — the watcher does not scan for `.git` appearing, and nothing /// re-runs `BoardGitMode.detect` for the life of this object. /// /// The one deliberate mid-session transition is `addGit()` below: "the rule forbids *discovered* /// flips, never commanded ones." public private(set) var mode: BoardGitMode /// The current branch's short name in git mode, `nil` until it has been read (or when there is /// nothing to read). /// /// Filled by `refreshBranch()` rather than at composition, deliberately: composition happens on /// the board-open path, where 02-architecture.md's hang-avoidance doctrine says nothing may /// block, and opening a repository is libgit2 work — small, but work. Detection is a `stat`; /// this is a read, and it waits until the popover actually asks. public private(set) var branch: String? /// Whether add-git is in flight — the button's disabled state, and the guard that keeps a double /// click from running `git_repository_init` twice. public private(set) var isAddingGit = false /// The last add-git failure, or `nil` if the last attempt succeeded (or there hasn't been one). /// /// Surfaced inline in the popover rather than as a banner: the popover is where the operation /// was asked for and is still open when it answers, and 02-architecture.md's one-shot banner /// vocabulary is for failures of writes the user made *elsewhere*. DESIGN does not settle /// add-git's failure surface either way. public private(set) var lastFailure: GitOperationFailure? private static let logger = Logger(subsystem: "dev.rzen.indie.Kanban", category: "git") init(boardRoot: URL, mode: BoardGitMode) { self.boardRoot = boardRoot self.mode = mode } /// **The tier gate and the open-time detection, in one line** (12-editions.md ▸ The provider /// seam; 06-history-undo.md ▸ Rules ▸ Detection) — called by `AppModel.beginSession` beside the /// entitlement read that supplies `tier`. /// /// `nil` under `.free` means exactly what it says: no git state exists for that session, so no /// caller can accidentally consult one. Under `.pro` the mode is whatever the filesystem says /// right now, and a board that has changed mode since its last open simply opens in the new one /// — "the app just reflects what it finds". /// /// **Adoption needs no step of its own**: a board whose root already carries `.git` lands in /// `.git` here, silently, with no dialog and nothing to confirm — "the repo's presence *is* the /// opt-in" (06 ▸ Rules ▸ Adoption). public static func compose(boardRoot: URL, tier: Tier) -> HistoryStore? { guard tier == .pro else { return nil } let mode = BoardGitMode.detect(boardRoot: boardRoot) logger.debug("board opened in git mode \(mode.rawValue, privacy: .public)") return HistoryStore(boardRoot: boardRoot, mode: mode) } // MARK: - Add git /// **Opt-in init** (06-history-undo.md ▸ Rules): initializes a repository at the board root and /// immediately commits the whole tree as "Initial board state". /// /// Reachable from one place — the board popover's git section under Pro — and from nowhere else: /// "No silent auto-init, ever", a deliberate pivot from the pathfinder, which initialized a repo /// under every board it opened. /// /// **It flips the open board's mode immediately**, which is the design's one sanctioned /// mid-session transition: "clicking it flips the open board into git mode immediately — the /// popover flows straight into the git controls". The flip is commanded, not discovered, which /// is what distinguishes it from the `git init` a user runs in a terminal under an open board. /// /// Only mode `none` can be added to. Mode `git` has nothing to add, and a repo-nested board is /// one the app "leaves strictly alone" — no nested repo, ever. @discardableResult public func addGit() async -> Bool { guard mode == .none, !isAddingGit else { return false } isAddingGit = true lastFailure = nil defer { isAddingGit = false } let root = boardRoot // Off the main actor: `git_repository_init` plus a whole-tree stage and commit is real // filesystem work, and the popover it was clicked in stays live while it runs. let outcome = await Task.detached(priority: .userInitiated) { GitRepository.create(at: root) }.value switch outcome { case .success(let branchName): mode = .git branch = branchName Self.logger.notice("add-git initialized a repository at \(root.path, privacy: .public)") return true case .failure(let failure): lastFailure = failure Self.logger.error("add-git failed: \(failure.description, privacy: .public)") return false } } /// Reads the current branch name into `branch` — the popover's read-only display line, refreshed /// when the popover opens. A no-op outside git mode. public func refreshBranch() async { guard mode == .git else { return } let root = boardRoot branch = await Task.detached(priority: .userInitiated) { GitRepository.branchName(at: root) }.value } // MARK: - The loader's history seam /// **The git-backed `IdentityHistoryRanker`** (01-storage-format.md ▸ Fractal layout ▸ Rules; /// `BoardLoader.IdentityHistoryRanker`), or `nil` on any board the app manages no git for — the /// free tier and modes `none`/`repoNested` alike, all of which fall through to the ladder's /// remaining rungs (birth date, then traversal order). /// /// **A fresh ranker per ask, deliberately.** Each one computes its map at most once, lazily, and /// only if something actually asks — which is only when a duplicate identity was found, since /// that is the only thing `BoardLoader.dedupeIdentities` consults it for. A ranker cached across /// loads would answer from a history that has since moved; one built per load never can. public var identityHistoryRanker: BoardLoader.IdentityHistoryRanker? { guard mode == .git else { return nil } return GitPathHistory(boardRoot: boardRoot).ranker } }