// // 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 /// #26 (S4.1): when the writer promoted this card into a Learning — /// the EXPLICIT confirm only; nil until then. Optional: pre-#26 card /// JSON decodes nil (a missing key never errors), and one stamp per /// card is enforced at promote. var promotedAt: Date? } /// 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. /// #177: decoded by ToolPayloads — the one tool-payload decoder; the /// struct keeps its memberwise init for direct construction (the /// native lint, tests) but carries no Codable conformance of its own. struct Input { 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) // Security (audit): a pre-planted symlink under the piece must not // turn a card submit into an arbitrary-directory JSON drop — // promote's learnings posture, now covering the rail the native // lint auto-fires on every Run Pass. let values = try? dir.resourceValues(forKeys: [.isSymbolicLinkKey]) if values?.isSymbolicLink == true { throw CardError(message: "cards path is a symlink: \(dir.path)") } 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, ), promotedAt: nil, ) } /// 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 { formatted(date, "yyyyMMdd-HHmmss") } /// en_US_POSIX date formatting, created per access — no non-Sendable /// statics (repo convention). stamp(), promote's day stamps, and /// LearningDecay's dismiss stamp (#27) share it. static func formatted(_ date: Date, _ format: String) -> String { let formatter = DateFormatter() formatter.dateFormat = format formatter.locale = Locale(identifier: "en_US_POSIX") return formatter.string(from: date) } /// First free filename for `base`: base, base-2, base-3… (#26: `ext` — /// cards are .json, Learnings and research notes .md.) Internal, not /// private: PostStore.writeResearchNote reuses it (#29) instead of /// copying it. // ponytail: exists-then-write race needs two concurrent same-second // same-pattern writers to matter (atomic rename = replace, not // corrupt); O_EXCL retry if a second writer ever appears. static func uniqueFile(_ dir: URL, base: String, ext: String = "json") -> String { var name = "\(base).\(ext)" var suffix = 2 while FileManager.default.fileExists(atPath: dir.appendingPathComponent(name).path) { name = "\(base)-\(suffix).\(ext)" 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 — the pass rail consults /// exactly these files (query_learnings; #26 promote writes them). /// #27 (S4.2): dismissed learnings stop feeding passes until their /// decay interval elapses — LearningDecay.passesHidden filters them /// out here. Missing dir → empty (fresh start is the correct v1 /// answer); a missing piece still throws. static func learnings(piecePath: String) throws -> [(file: String, markdown: String)] { let postURL = try resolvePostURL(piecePath) let text = try String(contentsOf: postURL, encoding: .utf8) let (home, type) = homeAndType(postURL: postURL, text: text) let dir = learningsDir(home: home, type: type) let currentPass = LearningDecay.passCounts(home: home)[LearningDecay.passKey(type)] ?? 0 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), LearningDecay.passesHidden(Post.frontmatter(of: markdown), currentPass: currentPass) == nil else { return nil } return (file: name, markdown: markdown) } } /// #26: the Learnings directory for a content type under a Home — /// LITERAL plural ("posts", "outlines"). ADR-0005: Museion owns these /// files, the engine profile never does. static func learningsDir(home: URL, type: Post.ContentType) -> URL { home.appendingPathComponent("learnings/\(LearningDecay.passKey(type))", isDirectory: true) } /// post.md URL + its text → (Home, content type) — the ADR-0012 layout /// walk learnings(piecePath:) and promote(pieceURL:) share: the Home is /// four components up from the file, the type from the frontmatter /// (default post). private static func homeAndType(postURL: URL, text: String) -> (home: URL, type: Post.ContentType) { var home = postURL for _ in 0 ..< 4 { home.deleteLastPathComponent() } return (home, Post.ContentType(rawValue: Post.frontmatter(of: text)["type"] ?? "") ?? .post) } // MARK: - Promote (#26, S4.1/S4.3) /// #26 (S4.1/S4.3): promote a card into ONE plain markdown Learning /// under `/learnings/s/` — the writer's EXPLICIT /// confirmation only: one confirm = one entry, never a repetition /// counter (an already-promoted card throws before anything is /// written). The Learning is Museion's file (ADR-0005): plain /// markdown, hand-editable, git-diffable; `learnings(piecePath:)` /// serves it to the next pass. Returns the card with `promotedAt` /// stamped — its JSON rewritten in place (close()'s pattern), every /// other field untouched. A missing/unreadable piece throws (trust /// boundary, resolvePostURL). @discardableResult static func promote(pieceURL: URL, card: StoredFixCard, now: Date = Date()) throws -> StoredFixCard { let postURL = try resolvePostURL(pieceURL.path) let text = try String(contentsOf: postURL, encoding: .utf8) let (home, type) = homeAndType(postURL: postURL, text: text) let dir = learningsDir(home: home, type: type) // Security (audit): a pre-planted symlink under the Home must not // turn promote into a file-plant primitive — reject before any // write when an existing learnings component is a symlink (the // read side skips symlinked dirs, Post.scan posture). for component in [home.appendingPathComponent("learnings"), dir] { let values = try? component.resourceValues(forKeys: [.isSymbolicLinkKey]) if values?.isSymbolicLink == true { throw CardError(message: "learnings path is a symlink: \(component.path)") } } // The on-disk card is the truth, not the caller's copy: a stale // palette copy (promotedAt nil while disk is stamped) or a // vanished/undecodable card JSON must refuse BEFORE anything is // written — one confirm = one entry, no duplicate Learnings. let cards = cardsDir(for: postURL) guard let entry = decoded(in: cards).first(where: { $0.card.id == card.id }) else { throw CardError(message: "card not found: \(card.id)") } guard entry.card.promotedAt == nil else { throw CardError(message: "card already promoted") } // ONE file: -.md, collision -2/-3 (submit's // uniqueFile, .md edition) — written from the on-disk card. try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true) let base = "\(formatted(now, "yyyyMMdd"))-\(PostStore.slug(from: entry.card.pattern))" try learningMarkdown(card: entry.card, now: now).write( to: dir.appendingPathComponent(uniqueFile(dir, base: base, ext: "md")), atomically: true, encoding: .utf8, ) // Stamp the card in place (close()'s rewrite): promotedAt on, // everything else untouched — the on-disk one-stamp guarantee. // (Learning-first ordering is deliberate — the inverse would lock // re-promotion forever after a mid-promote crash.) var stamped = entry.card stamped.promotedAt = now try encoder.encode(stamped).write(to: cards.appendingPathComponent(entry.file), options: .atomic) return stamped } /// The Learning file's exact shape (tests pin it): the TEACHING text — /// pattern, problem, diagnostic question, and the demonstration /// example when the lane is one — never the instance-bound evidence /// (the anchor quote and a mechanical fix are apply-machinery from the /// originating piece; the card JSON keeps them, `from_card` traces /// back). Single-line frontmatter values (newlines flatten to a /// space), then a human-readable body with an italic provenance /// footer that omits missing parts — never a dangling separator. private static func learningMarkdown(card: StoredFixCard, now: Date) -> String { func flat(_ value: String) -> String { value.components(separatedBy: .newlines).joined(separator: " ") } var keys = [ "pattern: \(flat(card.pattern))", "problem: \(flat(card.problem))", ] if !card.diagnosticQuestion.isEmpty { keys.append("diagnostic_question: \(flat(card.diagnosticQuestion))") } // Demonstration lanes: the fix IS the example rewrite — teaching // material, it travels. Mechanical lanes: the fix is a literal // replacement string from one instance — it teaches nothing // general and would mislead as "the fix". let example = card.lane == .demonstration ? card.fix : "" if !example.isEmpty { keys.append("fix: \(flat(example))") } keys.append("lane: \(card.lane.rawValue)") keys.append("emitter: \(card.emitter.rawValue)") if let piece = card.provenance?.piece { keys.append("piece: \(flat(piece))") } if let pass = card.provenance?.pass { keys.append("pass: \(pass)") } if let engine = card.provenance?.engine { keys.append("engine: \(flat(engine))") } keys.append("promoted: \(formatted(now, "yyyy-MM-dd"))") keys.append("from_card: \(card.id.uuidString)") var body = [ "# \(flat(card.pattern))", "**Problem.** \(flat(card.problem))", ] if !card.diagnosticQuestion.isEmpty { body.append("**Diagnostic.** \(flat(card.diagnosticQuestion))") } if !example.isEmpty { body.append("**Example.** \(flat(example))") } var footer = [(card.provenance?.piece).map(flat) ?? "a fix card"] if let pass = card.provenance?.pass { footer.append("Pass \(pass)") } footer.append(formatted(now, "yyyy-MM-dd")) body.append("*Promoted from \(footer.joined(separator: " · ")).*") return "---\n\(keys.joined(separator: "\n"))\n---\n\n\(body.joined(separator: "\n\n"))\n" } }