// // FixCardStore.swift // Museion // // #23 (M2, slice 1): the durable fix-card side of ADR-0006 — the stored // card (one snake_case JSON file under /cards/), pure anchor // validation against post.md, and the learnings reader the museion-tools // MCP server exposes. Plain disk work, no UI; the transcript-side // FixCard in MentorSessionModel is the ephemeral sibling. // import Foundation /// #23: Fix Card persistence. nonisolated like PostStore — the headless /// MCP mode calls this before any app machinery exists. nonisolated enum FixCardStore { // MARK: - Model /// One durable Fix Card as written to `/cards/*.json`. struct StoredFixCard: Codable, Equatable { /// Where the card anchors in the piece: an exact-substring quote, /// its 1-based occurrence, optional human context note. struct Anchor: Codable, Equatable { var quote: String var occurrence: Int var context: String? init(quote: String, occurrence: Int = 1, context: String? = nil) { self.quote = quote self.occurrence = occurrence self.context = context } init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) quote = try container.decode(String.self, forKey: .quote) // The wire schema declares default 1 — an omitted occurrence // means "the first one". occurrence = try container.decodeIfPresent(Int.self, forKey: .occurrence) ?? 1 context = try container.decodeIfPresent(String.self, forKey: .context) } } /// ADR-0006 lanes: the mechanical fix vs the demonstration rewrite. enum Lane: String, Codable { case mechanical, demonstration } /// Who emitted the card. enum Emitter: String, Codable { case lint, engine } /// Anchor validation outcome: a stale card still lands (the writer /// decides), it just never auto-applies. enum AnchorStatus: String, Codable { case valid, stale } /// #25 (S3.3): the card's lifecycle state — "open" on submit, one of /// the CONTEXT.md terminals on close: applied (Apply wrote the edit), /// skipped (not this instance), done (the writer rewrote the span). /// A foreign status string on disk fails decode → scan's junk-skip. enum Status: String, Codable { case open, applied, skipped, done } struct Provenance: Codable, Equatable { var piece: String var date: String? var engine: String? /// Which pass found it (1, 2…) — optional: pre-schema cards and /// foreign MCP clients may omit it; the palette renders it when /// present. #23 follow-up: pass differentiation. var pass: Int? } var id: UUID var submittedAt: Date /// #25 (S3.2): the card's rank in its submit — the persona's ranked /// order, 1-based, stamped by the store like id/submittedAt. Optional: /// pre-#25 cards on disk carry no rank key. var rank: Int? var pattern: String var problem: String var diagnosticQuestion: String var fix: String var anchor: Anchor var lane: Lane var emitter: Emitter var provenance: Provenance? /// "open" on submit; a Status terminal once the writer closes it. var status: Status var anchorStatus: AnchorStatus } /// The wire shape of one submitted card (ADR-0006 input fields only — /// the server stamps id/submittedAt/status/anchorStatus). This is the /// trust boundary: malformed input throws, never becomes a card. struct Input: Decodable { var pattern: String var problem: String var diagnosticQuestion: String? var fix: String? var anchor: StoredFixCard.Anchor var lane: StoredFixCard.Lane var emitter: StoredFixCard.Emitter var provenance: StoredFixCard.Provenance? } // MARK: - Codec /// Shared codec: snake_case keys + ISO-8601 dates — the wire and the /// disk format agree. Created per access; no non-Sendable statics /// (repo convention, ProfileBackup.stamp). static var encoder: JSONEncoder { let instance = JSONEncoder() instance.keyEncodingStrategy = .convertToSnakeCase instance.dateEncodingStrategy = .iso8601 return instance } static var decoder: JSONDecoder { let instance = JSONDecoder() instance.keyDecodingStrategy = .convertFromSnakeCase instance.dateDecodingStrategy = .iso8601 return instance } /// Descriptive failures surfaced verbatim as tool error text. struct CardError: LocalizedError, Equatable { let message: String var errorDescription: String? { message } } // MARK: - Anchor validation (pure) /// `quote` must appear in `text` at least `occurrence` times /// (non-overlapping, 1-based). Empty quote or a vanished quote → /// stale — never a crash, never a rejection. static func anchorStatus(text: String, quote: String, occurrence: Int) -> StoredFixCard.AnchorStatus { guard !quote.isEmpty, occurrence >= 1 else { return .stale } return text.ranges(of: quote).count >= occurrence ? .valid : .stale } // MARK: - Apply (pure) /// #25 (S3.2/S3.3): the mechanical Apply as a pure function — the edit /// the card makes in `text`: the anchor's quote occurrence (1-based, /// non-overlapping — the anchorStatus math) replaced by the fix, /// everything else untouched. nil = the card must not touch text: a /// demonstration lane (only a mechanical fix is ever applied, /// ADR-0006) or an anchor that no longer resolves — edits between /// issue and accept degrade to a loud no-match, never a wrong-span /// patch. The caller owns the ask and the file write. static func appliedText(of card: StoredFixCard, in text: String) -> String? { guard card.lane == .mechanical, card.anchor.occurrence >= 1, !card.anchor.quote.isEmpty, let range = text.ranges(of: card.anchor.quote).dropFirst(card.anchor.occurrence - 1).first else { return nil } return text.replacingCharacters(in: range, with: card.fix) } // MARK: - Submit /// Validate every card first, then write one JSON file per card into /// `/cards/` named `-.json` (collision → /// -2, -3…). Stale anchors still land, flagged. No dedup — every /// submission lands (explicit product decision). /// #25 (S3.2): the pass ceiling — `passCardCeiling` per submit, the /// ranked head kept (the persona's cap is the primary filter; this is /// the backstop). Tail cards drop before validation. static let passCardCeiling = 10 static func submit(piecePath: String, cards: [Input]) throws -> [(card: StoredFixCard, file: String)] { let postURL = try resolvePostURL(piecePath) let text = try String(contentsOf: postURL, encoding: .utf8) // Whole-call semantics: a malformed card errors the call before // anything is written. let materialized = try cards.prefix(passCardCeiling).enumerated().map { index, input in try materialize(input, postText: text, rank: index + 1) } let dir = postURL.deletingLastPathComponent().appendingPathComponent("cards", isDirectory: true) try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true) let stamp = Self.stamp(Date()) var written: [(card: StoredFixCard, file: String)] = [] for card in materialized { let file = uniqueFile(dir, base: "\(stamp)-\(PostStore.slug(from: card.pattern))") do { try encoder.encode(card).write(to: dir.appendingPathComponent(file), options: .atomic) } catch { // Honesty at the trust boundary: a mid-loop write failure leaves // earlier cards landed — say which, so a client retry doesn't // blindly duplicate them (there is no dedup, by decision). let landed = written.map(\.file).joined(separator: ", ") throw CardError(message: "card write failed: \(error.localizedDescription)" + (landed.isEmpty ? "" : " — already written: \(landed)")) } written.append((card, file)) } return written } /// Trust-boundary validation + server stamping. private static func materialize(_ input: Input, postText: String, rank: Int) throws -> StoredFixCard { guard !input.pattern.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else { throw CardError(message: "card pattern must not be empty") } guard !input.problem.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else { throw CardError(message: "card problem must not be empty") } guard !input.anchor.quote.isEmpty else { throw CardError(message: "card anchor quote must not be empty") } guard input.anchor.occurrence >= 1 else { throw CardError(message: "card anchor occurrence must be ≥ 1") } return StoredFixCard( id: UUID(), submittedAt: Date(), rank: rank, pattern: input.pattern, problem: input.problem, diagnosticQuestion: input.diagnosticQuestion ?? "", fix: input.fix ?? "", anchor: input.anchor, lane: input.lane, emitter: input.emitter, provenance: input.provenance, status: .open, anchorStatus: anchorStatus( text: postText, quote: input.anchor.quote, occurrence: input.anchor.occurrence, ), ) } /// A piece path is the piece folder or its post.md; it must exist and /// be readable — a missing piece is a tool error, never an empty /// submit. No tilde expansion: the pass stub pins absolute paths, and /// expanding a foreign string needlessly widens what a client can /// address (trust boundary — standards review). The file form must be /// named post.md AND sit under a `projects/` or `archive/` component /// (ADR-0012) — otherwise any readable file becomes a "piece", submit /// becomes a JSON-drop beside it, and anchor validation a substring /// oracle over it (security review: both MEDIUMs, one guard). private static func resolvePostURL(_ piecePath: String) throws -> URL { let url = URL(fileURLWithPath: piecePath) var isDir: ObjCBool = false guard FileManager.default.fileExists(atPath: url.path, isDirectory: &isDir) else { throw CardError(message: "piece not found: \(piecePath)") } var postURL = url if isDir.boolValue { postURL.appendPathComponent("post.md") } guard postURL.lastPathComponent == "post.md", postURL.pathComponents.contains(where: { $0 == "projects" || $0 == "archive" }), FileManager.default.isReadableFile(atPath: postURL.path) else { throw CardError(message: "not a piece (expected /…/post.md): \(piecePath)") } return postURL } /// Timestamped card filename prefix, lexicographically sortable /// (ProfileBackup convention). private static func stamp(_ date: Date) -> String { let formatter = DateFormatter() formatter.dateFormat = "yyyyMMdd-HHmmss" formatter.locale = Locale(identifier: "en_US_POSIX") return formatter.string(from: date) } /// First free filename for `base` (no extension): base, base-2, base-3… // ponytail: exists-then-write race needs two concurrent same-second // same-pattern submits to matter (atomic rename = replace, not corrupt); // O_EXCL retry if a second writer ever appears. private static func uniqueFile(_ dir: URL, base: String) -> String { var name = "\(base).json" var suffix = 2 while FileManager.default.fileExists(atPath: dir.appendingPathComponent(name).path) { name = "\(base)-\(suffix).json" suffix += 1 } return name } // MARK: - Scan /// `/cards/`, tolerating a post.md URL (app-side call sites /// hold the file URL). private static func cardsDir(for pieceURL: URL) -> URL { var dir = pieceURL if ["md", "markdown"].contains(dir.pathExtension.lowercased()) { dir.deleteLastPathComponent() } return dir.appendingPathComponent("cards", isDirectory: true) } /// Every stored card under `/cards/`, the persona's ranked order: /// submittedAt DESC (newest submit first), then rank ASC within a /// submit, pre-#25 cards (rank nil) AFTER ranked ones of the same /// submit. Undecodable files are skipped silently — a stranger's /// hand-edit never crashes the reader. A post.md URL is tolerated /// (app-side call sites hold the file URL). static func scan(pieceURL: URL) -> [StoredFixCard] { decoded(in: cardsDir(for: pieceURL)).sorted { lhs, rhs in if lhs.card.submittedAt != rhs.card.submittedAt { return lhs.card.submittedAt > rhs.card.submittedAt } switch (lhs.card.rank, rhs.card.rank) { case let (ranked?, other?) where ranked != other: return ranked < other case (.some, nil): return true // ranked cards lead their unranked siblings case (nil, .some): return false default: return lhs.file > rhs.file } } .map(\.card) } /// The shared cards/ walk — decoded cards with their filenames; scan /// sorts it, close finds in it. Undecodable files are skipped silently /// (a stranger's hand-edit never crashes the reader). The comparator's /// filename tiebreak totally orders unique names, so walk order never /// matters. private static func decoded(in cards: URL) -> [(file: String, card: StoredFixCard)] { let files = ((try? FileManager.default.contentsOfDirectory(atPath: cards.path)) ?? []) .filter { $0.hasSuffix(".json") } return files.compactMap { name in guard let data = try? Data(contentsOf: cards.appendingPathComponent(name)), let card = try? decoder.decode(StoredFixCard.self, from: data) else { return nil } return (name, card) } } // MARK: - Close /// #25 (S3.3): close a stored card IN PLACE — its JSON file rewritten /// with the new status, every other field untouched (Skip records /// nothing beyond the flip). `anchorStatus`, when non-nil, rides the /// same rewrite (the stale-anchor flag); nil preserves it. Returns /// the closed card. Throws when no card with the id sits under the /// piece (the app surface routes the error); undecodable stranger /// files are skipped, same as scan. @discardableResult static func close( pieceURL: URL, id: UUID, status: StoredFixCard.Status, anchorStatus: StoredFixCard.AnchorStatus? = nil, ) throws -> StoredFixCard { let cards = cardsDir(for: pieceURL) for entry in decoded(in: cards) where entry.card.id == id { var card = entry.card card.status = status if let anchorStatus { card.anchorStatus = anchorStatus } try encoder.encode(card).write(to: cards.appendingPathComponent(entry.file), options: .atomic) return card } throw CardError(message: "card not found: \(id)") } // MARK: - Learnings /// The piece's visible learnings: raw markdown per file under /// `/learnings/s/` (LITERAL plural — "posts", "outlines"), /// name-sorted. Raw contents, no parsing — promotion stays a later /// decision (#26). Missing dir → empty (fresh start is the correct /// v1 answer); a missing piece still throws. // ponytail: decay filtering is pass-through until issue #26 defines // the frontmatter fields. static func learnings(piecePath: String) throws -> [(file: String, markdown: String)] { let postURL = try resolvePostURL(piecePath) let text = try String(contentsOf: postURL, encoding: .utf8) // ADR-0012 layout: ////post.md — // the Home is four components up from the file. var home = postURL for _ in 0 ..< 4 { home.deleteLastPathComponent() } let type = Post.ContentType(rawValue: Post.frontmatter(of: text)["type"] ?? "") ?? .post let dir = home.appendingPathComponent("learnings/\(type.rawValue)s", isDirectory: true) let files = ((try? FileManager.default.contentsOfDirectory(atPath: dir.path)) ?? []) .filter { $0.hasSuffix(".md") } .sorted() return files.compactMap { name in guard let markdown = try? String(contentsOf: dir.appendingPathComponent(name), encoding: .utf8) else { return nil } return (file: name, markdown: markdown) } } }