// MicropubSummaryTests.swift // MuseionTests // // #208: a post summary for Micro.blog — the wire + codec half. The // sheet's Summary field is sheet state (the Categories discipline); // the edit lands on the piece AT THE SEND as a one-line `summary:` // key, and the wire reads from disk: a CREATE carries // `properties.summary` when non-empty; a RE-SEND carries `summary` // in `replace` ONLY when the piece has the line (opt-in by key — // an empty string is sent and clears the post's summary; no line → // `replace` names exactly name + content, the blog keeps whatever it // has). The AI half (the one-shot engine drafting the summary) rides // its own file; the sheet itself is not pinned here. // // Pins: S1 the codec reads the line · S2 create carries it · S3 the // re-send opt-in by key · S4 the edit lands at the send (sanitized, // one line, readable through the model; a failed write refuses). // // ## Scenario: the summary travels on the wire // From #208 // // Given a saved Post whose frontmatter carries a one-line `summary:` // When the writer sends it to Micro.blog or re-sends over the // remembered post // Then a CREATE carries `properties.summary` (only when non-empty); // a RE-SEND carries `summary` in `replace` ONLY when the piece has // the line (`""` is sent and clears; no line leaves the blog's). // // ## Scenario: the edit lands at the send // From #208 // // Given a sheet Summary edit (the model's `summary:` argument) // When the writer sends // Then the line is written to the piece AFTER the flush and BEFORE // the one disk read that feeds the wire — disk and blog never // disagree; a write that cannot land REFUSES the send with nothing // on the wire. // import Foundation @testable import Museion import Testing @Suite("MicropubSummaryTests") struct MicropubSummaryTests { /// A saved piece opened in the model, with `frontmatter` planted /// after the owned keys; returns its id. @MainActor private func openPiece(_ model: PostsModel, _ home: URL, frontmatter: String = "") throws -> String { let id = try plantedPiece(home, frontmatter: frontmatter) model.select(id) return id } /// A recorded create's `properties` — through `request(_:)`, never a /// subscript (#206). private nonisolated func createProperties(_ log: MicropubRequestLog, _ index: Int) throws -> [String: Any] { let request = try #require(log.request(index)) return try #require(micropubJSON(request)["properties"] as? [String: Any]) } /// A recorded update's `replace`. private nonisolated func updateReplace(_ log: MicropubRequestLog, _ index: Int) throws -> [String: Any] { let request = try #require(log.request(index)) return try #require(micropubJSON(request)["replace"] as? [String: Any]) } // MARK: S1 — the codec reads the one-line summary (pure) @Test func `summary read is the raw line's scalar and empty when absent`() { #expect(PostFrontmatter.summary(inText: "---\nsummary: Why I left the city.\n---\n") == "Why I left the city.") #expect(PostFrontmatter.summary(inText: "---\nsummary: Padded. \n---\n") == "Padded.") // A hand-quoted scalar reads back as the bare text. #expect(PostFrontmatter.summary(inText: "---\nsummary: \"Quoted, with comma\"\n---\n") == "Quoted, with comma") // Empty, blank, or absent → "" (a piece without a line never gains one). #expect(PostFrontmatter.summary(inText: "---\nsummary:\n---\n") == "") #expect(PostFrontmatter.summary(inText: "---\nsummary: \n---\n") == "") #expect(PostFrontmatter.summary(inText: "---\ntype: post\n---\n") == "") // A body line named summary: never claims the key. #expect(PostFrontmatter.summary(inText: "---\ntype: post\n---\n\nsummary: not frontmatter\n") == "") // No block at all → nothing. #expect(PostFrontmatter.summary(inText: "# Title\n\nBody.\n") == "") // A body line named summary: never claims the key — fenced or not. #expect(PostFrontmatter.summary(inText: "# Title\n\nsummary: body prose\n") == "") // ponytail: a CRLF post.md is one grapheme-cluster "line" to every // `\n` split in the corpus (PostStore: LF-only by design, CRLF is // normalized at the boundaries) — no reader sees its block, this // one included. The MIXED shape (an LF block with a stray trailing // \r on one line) is where parse and a `.whitespaces` trim would // diverge — pinned at the wire in `a mixed-line-ending piece…`. #expect(PostFrontmatter.summary(inText: "---\nsummary: Why I left.\r\n---\n") == "Why I left.") } @Test func `summary value strips newlines so the line-bounded sink is safe`() { // The frontmatter sink is line-bounded — a summary can never ride // a newline into the block; the value is one line or nothing. let value = PostFrontmatter.summaryValue("Line one.\nLine two.") #expect(!value.contains("\n")) #expect(PostFrontmatter.summary(inText: "---\nsummary: \(value)\n---\n") == "Line one. Line two.") // Leading/trailing whitespace trims; a blank becomes "". #expect(PostFrontmatter.summaryValue(" ") == "") } @Test func `summary value round-trips through the raw line read without losing edge quotes or controls`() { // The lenient parse trims EVERY leading/trailing quote char, so // the wire and the sheet read the raw line (`summary(inText:)`); // the render QUOTES anything holding a quote or backslash, so // `asked "why"` ships exactly as typed. let read = { text in PostFrontmatter.summary(inText: "---\nsummary: \(PostFrontmatter.summaryValue(text))\n---\n") } #expect(read(#"I finally asked "why""#) == #"I finally asked "why""#) #expect(read(#""Why did you leave?" haunted me."#) == #""Why did you leave?" haunted me."#) // An inner quote and a newline together: flattened AND round-tripped. #expect(read("Line \"one\".\nLine two.") == "Line \"one\". Line two.") // A backslash survives too (the category codec's escape). #expect(read(#"C:\path "x""#) == #"C:\path "x""#) // Control characters (NUL, ESC) never reach the sink — the // category codec's rule; whitespace still collapses to one space. #expect(PostFrontmatter.summaryValue("a\u{0}b\u{1B} c") == "ab c") // A plain value renders bare. #expect(PostFrontmatter.summaryValue("Why I left.") == "Why I left.") } // MARK: S2 — a create carries the summary when non-empty (builder + model) @Test func `draft request carries summary only when non-empty`() throws { let request = Micropub.makeDraftRequest(title: "T", body: "B", token: "tok", summary: "Why I left.") let props = try #require(micropubJSON(request)["properties"] as? [String: Any]) #expect(props["summary"] as? [String] == ["Why I left."]) #expect(props["name"] as? [String] == ["T"]) #expect(props["content"] as? [String] == ["B"]) // No summary → no key at all (a create never carries an empty one). let bare = try #require(micropubJSON(Micropub.makeDraftRequest(title: "T", body: "B", token: "tok"))["properties"] as? [String: Any]) #expect(bare["summary"] == nil) } @Test @MainActor func `create carries the piece's summary and no key when there is none`() async throws { let (model, home) = try makeModelHome() let log = MicropubRequestLog() let transport = micropubCanned(201, headers: ["Location": "https://example.micro.blog/summarized"], log: log) _ = try openPiece(model, home, frontmatter: "summary: Why I left the city.\n") let outcome = await model.micropubSend(token: "tok", transport: transport) #expect(outcome == .drafted(url: "https://example.micro.blog/summarized", preview: nil)) let props = try createProperties(log, 0) #expect(props["summary"] as? [String] == ["Why I left the city."]) // No line at all → no key; an empty line → no key either. _ = try openPiece(model, home) _ = await model.micropubSend(token: "tok", transport: transport) #expect(try createProperties(log, 1)["summary"] == nil) _ = try openPiece(model, home, frontmatter: "summary:\n") _ = await model.micropubSend(token: "tok", transport: transport) #expect(try createProperties(log, 2)["summary"] == nil) } // MARK: S3 — a re-send replaces, opt-in by key (the model) @Test @MainActor func `a re-send carries the line's summary in replace and clears on an empty one`() async throws { let (model, home) = try makeModelHome() let url = "https://example.micro.blog/live" let log = MicropubRequestLog() let transport = micropubCanned(200, log: log) _ = try openPiece(model, home, frontmatter: "micropub_url: \(url)\nsummary: Why I left.\n") let outcome = await model.micropubSend(token: "tok", transport: transport) #expect(outcome == .updated(url: url)) let replace = try updateReplace(log, 0) #expect(replace["summary"] as? [String] == ["Why I left."]) #expect(replace["name"] as? [String] == ["Titled"]) // An empty summary IS sent — it clears the post's. _ = try openPiece(model, home, frontmatter: "micropub_url: \(url)\nsummary:\n") _ = await model.micropubSend(token: "tok", transport: transport) let cleared = try updateReplace(log, 1) #expect(cleared["summary"] as? [String] == [""]) // No line → replace names exactly name + content: the blog keeps whatever it has. _ = try openPiece(model, home, frontmatter: "micropub_url: \(url)\n") _ = await model.micropubSend(token: "tok", transport: transport) let kept = try updateReplace(log, 2) #expect(Set(kept.keys) == ["name", "content"]) } // MARK: S4 — the edit lands at the send @Test @MainActor func `a summary edit lands on the piece before the wire`() async throws { let (model, home) = try makeModelHome() let id = try openPiece(model, home) // no summary line yet let before = try PostFrontmatter.split(readPost(home, id)).body let log = MicropubRequestLog() let transport = micropubCanned(201, headers: ["Location": "https://example.micro.blog/edited"], log: log) let outcome = await model.micropubSend(token: "tok", summary: "A teaser.", transport: transport) #expect(outcome == .drafted(url: "https://example.micro.blog/edited", preview: nil)) let after = try readPost(home, id) // The line is a line of the block; the body is byte-identical. #expect(PostFrontmatter.split(after).block.contains("\nsummary: A teaser.\n")) #expect(PostFrontmatter.split(after).body == before) let props = try createProperties(log, 0) #expect(props["summary"] as? [String] == ["A teaser."]) } @Test @MainActor func `a refused send with a summary edit writes nothing`() async throws { let (model, home) = try makeModelHome() let post = try PostStore.writeNew(body: "# Unopened\n\nBody.", home: home) // written, never opened let before = try readPost(home, post.id) let log = MicropubRequestLog() let outcome = await model.micropubSend(token: "tok", summary: "A teaser.", transport: micropubCanned(201, log: log)) guard case .refused = outcome else { Issue.record("expected refused, got \(outcome)") return } #expect(log.requests.isEmpty) #expect(try readPost(home, post.id) == before) // the edit never reached the disk } @Test @MainActor func `a summary write that cannot land refuses the send with nothing on the wire`() async throws { let (model, home) = try makeModelHome() let id = try openPiece(model, home) // The piece folder goes read-only: the summary line cannot land. let dir = try #require(PostStore.folder(of: id, home: home)) defer { try? FileManager.default.setAttributes([.posixPermissions: 0o755], ofItemAtPath: dir.path) } try FileManager.default.setAttributes([.posixPermissions: 0o500], ofItemAtPath: dir.path) let log = MicropubRequestLog() let outcome = await model.micropubSend(token: "tok", summary: "A teaser.", transport: micropubCanned(201, log: log)) guard case let .refused(reason) = outcome else { Issue.record("expected refused, got \(outcome)") return } #expect(reason.hasPrefix("Couldn't save this piece's summary — nothing was sent.")) #expect(log.requests.isEmpty) #expect(try PostFrontmatter.summary(inText: readPost(home, id)) == "") } @Test @MainActor func `an edge-quote summary reaches the wire exactly as typed`() async throws { // The review's finding: the lenient parse trims every edge quote, // so a teaser closing in `"why"` must still ship whole — on a // create AND on a re-send, and reopen whole in the sheet's read. let (model, home) = try makeModelHome() let teaser = #"I finally asked "why""# let log = MicropubRequestLog() let transport = micropubCanned(201, headers: ["Location": "https://example.micro.blog/quoted"], log: log) _ = try openPiece(model, home) _ = await model.micropubSend(token: "tok", summary: teaser, transport: transport) #expect(try createProperties(log, 0)["summary"] as? [String] == [teaser]) #expect(model.openPieceSummary() == teaser) // A re-send reads the stamped line back — still whole. The piece // remembers its post from the first send, so this is the update. _ = await model.micropubSend(token: "tok", transport: transport) #expect(log.requests.count == 2) #expect(try updateReplace(log, 1)["summary"] as? [String] == [teaser]) } @Test @MainActor func `the sheet's disk read is the open piece's summary line`() async throws { let (model, home) = try makeModelHome() #expect(model.openPieceSummary() == "") // nothing open _ = try openPiece(model, home) #expect(model.openPieceSummary() == "") // no line yet _ = await model.micropubSend( token: "tok", summary: "A teaser.", transport: micropubCanned(201, headers: ["Location": "https://example.micro.blog/one"], log: MicropubRequestLog()), ) #expect(model.openPieceSummary() == "A teaser.") // read from disk, never a snapshot } @Test @MainActor func `a mixed-line-ending piece re-sends its real summary never an empty clear`() async throws { // The trimmed() rule. A pure CRLF file is ONE grapheme "line" to // every `\n` split in the corpus (LF-only by design, normalized at // the boundaries) — no reader sees its block, so nothing can // disagree. The shape that CAN: an LF block carrying a stray // trailing \r on the summary line (a half-converted edit) — parse's // trimmed() sees the key, a `.whitespaces` trim would leave `\r` // on the fence and read "" → replace summary [""] over the live post. let (model, home) = try makeModelHome() let url = "https://example.micro.blog/live" let log = MicropubRequestLog() _ = try openPiece(model, home, frontmatter: "micropub_url: \(url)\nsummary: Why I left.\n") let id = try #require(model.selectedPostID) let file = try #require(PostStore.folder(of: id, home: home)?.appendingPathComponent("post.md")) try String(contentsOf: file, encoding: .utf8) .replacingOccurrences(of: "summary: Why I left.\n", with: "summary: Why I left.\r\n") .write(to: file, atomically: true, encoding: .utf8) let outcome = await model.micropubSend(token: "tok", transport: micropubCanned(200, log: log)) #expect(outcome == .updated(url: url)) #expect(log.requests.count == 1) let replace = try updateReplace(log, 0) #expect(replace["summary"] as? [String] == ["Why I left."]) } @Test @MainActor func `publish with only a summary edit updates first then flips the status`() async throws { // The applies-first condition is `categories != nil || summary != nil` — // a summary-only edit must still send before the flip, or Publish // would publish the stale post and silently drop the edit. let (model, home) = try makeModelHome() let url = "https://example.micro.blog/drafted" let id = try openPiece(model, home, frontmatter: "micropub_url: \(url)\n") let log = MicropubRequestLog() let outcome = await model.micropubPublish(url: url, token: "tok", summary: "A teaser.", transport: micropubCanned(200, log: log)) #expect(outcome == .published) // TWO requests, in order: the update carrying the edit, THEN the flip. #expect(log.requests.count == 2) #expect(try updateReplace(log, 0)["summary"] as? [String] == ["A teaser."]) let flip = try #require(log.request(1)) let flipReplace = try #require(micropubJSON(flip)["replace"] as? [String: Any]) #expect(flipReplace["post-status"] as? [String] == ["published"]) #expect(flipReplace["summary"] == nil) #expect(model.openPieceSummary() == "A teaser.") #expect(try PostFrontmatter.split(readPost(home, id)).block.contains("micropub_published: ")) } @Test @MainActor func `clearing a sent summary writes the empty line and clears the post's`() async throws { // End to end through the model's own written form (not a hand-planted // line): send, then clear → the update carries summary [""]. let (model, home) = try makeModelHome() let url = "https://example.micro.blog/live" let log = MicropubRequestLog() let transport = micropubCanned(200, headers: ["Location": url], log: log) _ = try openPiece(model, home, frontmatter: "micropub_url: \(url)\n") _ = await model.micropubSend(token: "tok", summary: "A teaser.", transport: transport) #expect(model.openPieceSummary() == "A teaser.") let outcome = await model.micropubSend(token: "tok", summary: "", transport: transport) #expect(outcome == .updated(url: url)) #expect(log.requests.count == 2) let cleared = try updateReplace(log, 1) #expect(cleared["summary"] as? [String] == [""]) let id = try #require(model.selectedPostID) let disk = try readPost(home, id) #expect(PostFrontmatter.split(disk).block.contains("\nsummary: \n")) #expect(model.openPieceSummary() == "") } @Test func `an imported summary line rides through import`() throws { let home = try storeHome() // The summary is the writer's content, like `category:` — it stays; // only Museion's bookkeeping drops at the boundary (#206). let ext = FileManager.default.temporaryDirectory.appendingPathComponent("summarized-\(UUID().uuidString).md") try "---\nsummary: Why I left.\nmicropub_url: https://example.micro.blog/x\n---\n\n# Outside\n\nBody.\n" .write(to: ext, atomically: true, encoding: .utf8) defer { try? FileManager.default.removeItem(at: ext) } let post = try PostStore.importFile(at: ext, origin: .writer, home: home) let disk = try readPost(home, post.id) let matter = try PostFrontmatter.parse(disk) #expect(PostFrontmatter.summary(inText: disk) == "Why I left.") #expect(matter["micropub_url"] == nil) } // MARK: S5 — the sheet field's pending-edit rule (pure) @Test func `a summary edit is pending only when the trimmed field differs from the settled one`() { #expect(MicropubSummaryField.pendingSummary(field: "Why I left.", settled: "Why I left.") == nil) // Trailing whitespace is not an edit. #expect(MicropubSummaryField.pendingSummary(field: "Why I left. ", settled: "Why I left.") == nil) // Clearing a piece that had a line sends an empty summary. #expect(MicropubSummaryField.pendingSummary(field: "", settled: "Why I left.") == "") #expect(MicropubSummaryField.pendingSummary(field: "New", settled: "") == "New") // A piece without a line never gains an empty key. #expect(MicropubSummaryField.pendingSummary(field: " ", settled: "") == nil) } }