// // PostFrontmatter.swift // Museion // // #180: the Post frontmatter codec — the ONE lenient read and the three // write postures (fresh / merge-import / update-keys) behind one // known-key table and one insertion-order rule. Absorbs and deletes the // near-twin writers: PostStore.stamped (fresh), PostStore.mergedFrontmatter // (merge-import), LearningDecay.stampingFrontmatter (update-keys) — each // posture is byte-identical to the writer it replaced (merge-import's // documented prefix-preservation divergence excepted), so existing pieces // on disk never notice the migration. Learning/Fix Card DOCUMENTS stay out // of scope (#180); their dismiss stamp rides the generic update posture // without redesigning its shape. // import Foundation /// #180: one engine for the flat `---`-delimited block every post.md /// carries. Read leniently (absent or unknown keys decode to their /// defaults — a bare legacy corpus post is a normal piece), written /// through exactly three postures: /// /// - **fresh** (`stamped`) — a brand-new block: writeNew, bare-file /// normalization on save/advance, convert. Replaces any existing block. /// - **merge-import** (`mergingImport`) — an external block kept verbatim /// with our three owned keys winning in place (importFile, #95). /// - **update-keys** (`updating`) — the surgical in-place key stamp: /// every other line byte-identical (editor save, pass advance, stats /// capture, micropub URL, learnings dismiss). /// /// The known-key table and its stamp order (`type`, `pass_state`, /// `origin`) are ONE rule shared by every posture: absent owned keys /// insert before the closing `---` in that order. nonisolated enum PostFrontmatter { /// The leniently-decoded identity triple — one home for the `?? default` /// reads scan, the write paths, and the eligibility predicates share /// (the extraction the #31 capture's ponytail note deferred until this /// fourth caller). struct Stamp: Equatable { let type: Post.ContentType let passState: Post.PassState let origin: Post.Origin } // MARK: - Read /// The `---`-delimited frontmatter block's keys if present; empty /// otherwise. Quoted scalar values (`origin: "ai"`) are unquoted — /// lenient YAML. Values are line-bounded by construction (#33). static func parse(_ text: String) -> [String: String] { let lines = text.split(separator: "\n", omittingEmptySubsequences: false) guard lines.first(where: { !$0.trimmed().isEmpty })?.trimmed() == "---" else { return [:] } var map: [String: String] = [:] for line in lines.drop(while: { $0.trimmed() != "---" }).dropFirst() { let trimmed = line.trimmed() guard trimmed != "---" else { break } guard let colon = trimmed.firstIndex(of: ":") else { continue } let key = trimmed[.. (block: String, body: String) { let all = text.split(separator: "\n", omittingEmptySubsequences: false)[...] guard let open = all.firstIndex(where: { !$0.trimmed().isEmpty }), all[open].trimmed() == "---", let close = all[(open + 1)...].firstIndex(where: { $0.trimmed() == "---" }) else { return ("", text) } let block = all[open ... close].joined(separator: "\n") + "\n" return (block, all[(close + 1)...].joined(separator: "\n")) } /// The lenient stamp decode: absent or unknown keys read as their /// defaults (post / First Draft / writer) — the same verdicts /// `Post.scan`, `existingStamp`, and the capture gate must agree on. static func decoded(_ matter: [String: String]) -> Stamp { Stamp( type: Post.ContentType(rawValue: matter["type"] ?? "") ?? .post, passState: Post.PassState(rawValue: matter["pass_state"] ?? "") ?? .firstDraft, origin: Post.Origin(rawValue: matter["origin"] ?? "") ?? .writer, ) } // MARK: - Eligibility (#180: named once, consumed twice) /// The Unaided First Draft immutable pair — writer origin ∧ post type /// (CONTEXT.md). Never pass_state: that legitimately advances after a /// capture. This is the pair the scan's read-back gate re-gates on, so /// `stats_*` keys arriving by import on an ai or outline piece never /// render, while a migrated writer piece keeps its real arc (#32). static func isUnaidedFirstDraftPair(_ matter: [String: String]) -> Bool { let stamp = decoded(matter) return stamp.origin == .writer && stamp.type == .post } /// Unaided First Draft capture eligibility — the immutable pair ∧ /// Pass State First Draft. What the capture gate checks at pass /// invocation against the file's own frontmatter (#31). static func isCaptureEligible(_ matter: [String: String]) -> Bool { let stamp = decoded(matter) return stamp.origin == .writer && stamp.type == .post && stamp.passState == .firstDraft } // MARK: - Write postures /// The known-key table: Museion's three owned keys in stamp order — /// the ONE insertion-order rule every posture shares. static func ownedKeys( type: Post.ContentType, passState: Post.PassState, origin: Post.Origin, ) -> [(key: String, value: String)] { [ ("type", type.rawValue), ("pass_state", passState.rawValue), ("origin", origin.rawValue), ] } /// Posture 1 — fresh: the #59 v1 block (+ `type`, #107). Flat keys, /// the exact shape `parse` reads. Any existing block is replaced by /// design (writeNew births, bare files normalize, convert rebuilds). static func stamped( body: String, passState: Post.PassState, origin: Post.Origin, type: Post.ContentType = .post, ) -> String { "---\n" + ownedKeys(type: type, passState: passState, origin: origin) .map { "\($0.key): \($0.value)" }.joined(separator: "\n") + "\n---\n" + body } /// Posture 3 — update-keys: the surgical line-walk. Set-overwrite the /// pairs in place, insert absent ones before the closing `---` (pair /// order), preserve every other line verbatim (leading hand-edit lines /// above the opening `---` included, #27 review), keep the block's /// trailing newline. No block at all → prepend a fresh one with the /// pairs. static func updating(text: String, with pairs: [(key: String, value: String)]) -> String { let (block, body) = split(text) guard !block.isEmpty else { return "---\n" + pairs.map { "\($0.key): \($0.value)" }.joined(separator: "\n") + "\n---\n" + body } // Lines ABOVE the opening `---` (a hand-edit blank line — parse // tolerates one) fall in neither block nor body; keep them verbatim // so the rewrite loses nothing. let prefix = text.range(of: block).map { String(text[..<$0.lowerBound]) } ?? "" var lines = block.split(separator: "\n", omittingEmptySubsequences: false).map(String.init) // Drop the empty tail the block's final newline produced — re-added below. if let last = lines.last, last.isEmpty { lines.removeLast() } // ponytail: flat keys only — an indented `key: value` inside a // nested YAML block scalar is matched and rewritten unindented; // the lenient flat reader never claimed nested support (posture // inherited verbatim, #180 audit INFO-1). Indentation-aware walk // if nested frontmatter ever matters. let oursByKey = Dictionary(pairs.map { ($0.key, $0.value) }, uniquingKeysWith: { first, _ in first }) var seen = Set() for (index, line) in lines.enumerated() { // whitespacesAndNewlines: CRLF lines carry a trailing \r. let trimmed = line.trimmingCharacters(in: .whitespacesAndNewlines) guard !trimmed.isEmpty, trimmed != "---" else { continue } let key = String(line.split(separator: ":", maxSplits: 1).first ?? "").trimmingCharacters(in: .whitespaces) if let value = oursByKey[key] { lines[index] = "\(key): \(value)" seen.insert(key) } } let insertions = pairs.filter { !seen.contains($0.key) }.map { "\($0.key): \($0.value)" } if let close = lines.lastIndex(where: { $0.trimmingCharacters(in: .whitespacesAndNewlines) == "---" }), close > 0 { lines.insert(contentsOf: insertions, at: close) } return prefix + lines.joined(separator: "\n") + "\n" + body } /// Posture 2 — merge-import: external frontmatter rides verbatim; /// `type: post`, `pass_state: First Draft`, `origin: ` win /// (#95: our three keys win — external `type: outline` still imports /// as post). The update posture over the known-key table. /// /// #180 divergence from the absorbed mergedFrontmatter, deliberate: /// hand-edit lines above the opening `---` now survive import (the old /// split-first shape silently dropped them) — lossless through every /// posture is the ticket's contract. static func mergingImport(text: String, origin: Post.Origin) -> String { updating(text: text, with: ownedKeys(type: .post, passState: .firstDraft, origin: origin)) } }