// // 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 } 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 var pattern: String var problem: String var diagnosticQuestion: String var fix: String var anchor: Anchor var lane: Lane var emitter: Emitter var provenance: Provenance? /// Always "open" on submit; later states belong to the app slice. var status: String 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: - 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). 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.map { try materialize($0, postText: text) } 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) 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(), 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 /// Every stored card under `/cards/`, newest-first (the stamp /// prefix sorts lexicographically). 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] { var dir = pieceURL if ["md", "markdown"].contains(dir.pathExtension.lowercased()) { dir.deleteLastPathComponent() } let cards = dir.appendingPathComponent("cards", isDirectory: true) let files = (try? FileManager.default.contentsOfDirectory(atPath: cards.path)) ?? [] return files .filter { $0.hasSuffix(".json") } .sorted(by: >) .compactMap { name in guard let data = try? Data(contentsOf: cards.appendingPathComponent(name)) else { return nil } return try? decoder.decode(StoredFixCard.self, from: data) } } // 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) } } }