Files
museion/Museion/PostFrontmatter.swift
T
AlexKucera 36393a9e8e feat(microblog): post summary for Micro.blog
A piece's `summary:` frontmatter line now travels to Micro.blog
beside `category:`. A first send carries the summary when it is not
empty; a re-send replaces the post's summary only when the piece has
the line (opt-in by key; an empty value clears it; no line leaves the
blog's). The same rule as categories, so a piece that never gained
the line cannot blank a summary set on Micro.blog itself.

The publish sheet gains a Summary field and an AI summary button. The
button drafts a first-person teaser from the open piece on a fresh
one-shot engine on the chat profile (the Blind Read's rail — the
resident session is never touched); the reply fills the field for the
writer to edit, and nothing is written until the send stamps the
line. The sheet is modal, so while its own turn runs the button is
the Stop; a Pass or Blind Read that owns the rail disables the button
with the reason on hover and refuses from behind it.

The summary is read off the RAW frontmatter line, never through the
lenient decode — which trims every edge quote — and the read walks
the block the way the lenient reader does. A `split`-based read finds
no block in a mixed-ending file while the lenient reader still sees
the key, and the empty value it answers would have been sent over a
live post's summary.

Reviewed twice (two-axis during the build, three-reviewer
finish-audit after): the mixed-ending read, an unfenced body line
claiming the key, the uncancellable modal turn, and the wrapper rule
eating a teaser's edge quotes were found and fixed before this
commit. Every guard was watched fail on its own pin. Rail 814/814;
SwiftFormat and SwiftLint clean.

Docs: AGENTS.md bullets and learnings, the GLOSSARY term, CHANGELOG
[Unreleased], PRD S6.1, and the devlog.

Closes #208
2026-12-05 12:32:38 +01:00

401 lines
18 KiB
Swift

//
// 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.
// #207: the one-line `category:` list — read (`categories(in:)`) and
// render (`categoryValue(_:)`) over the unbracketed pair the publish
// sheet's field also speaks (`categoryList`/`categoryListValue`): ONE
// parser serves the piece, the sheet, and the wire.
//
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), and
/// Museion's Micro.blog bookkeeping dropped (#206 — a foreign file
/// carries no post of THIS library).
/// - **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 frontmatter timestamp shape (`stats_captured`, #31;
/// `micropub_published`, #206) — local time, lexically sortable. The
/// one home for the format: both stamp writers and the reader share it.
static let stampFormat = "yyyy-MM-dd'T'HH:mm:ss"
/// Museion's Micro.blog bookkeeping — written only by the app (or the
/// writer's own hand, the legacy migration), never trusted from
/// outside: the import boundary DROPS these keys and the 404 forget
/// removes them. #206: an imported `micropub_url` passes the format
/// gate and would steer the next send's content replace — under the
/// writer's token — onto whatever post it names.
static let micropubKeys: Set<String> = ["micropub_url", "micropub_published"]
/// 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[..<colon].trimmingCharacters(in: .whitespaces)
let value = trimmed[trimmed.index(after: colon)...]
.trimmingCharacters(in: .whitespaces)
.trimmingCharacters(in: CharacterSet(charactersIn: "\"'"))
map[key] = value
}
return map
}
/// Splits a file into its verbatim frontmatter block (with both `---`
/// lines) and the body; no block → ("", whole text).
static func split(_ text: String) -> (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: - Category list (#207)
/// #207: the quote-aware comma-list parse the `category:` line and
/// the publish sheet's category FIELD share — ONE parser (the
/// field holds exactly the bracket-inner text). Splits on the
/// commas OUTSIDE double quotes, trims each item, strips ONE pair
/// of surrounding double quotes and unescapes `\\` and `\"`;
/// empties drop and the first occurrence of a name wins. Creation
/// is implicit on Micro.blog: naming a category that doesn't exist
/// creates it when the post is sent.
static func categoryList(_ inner: String) -> [String] {
var names: [String] = []
var seen: Set<String> = []
for item in categorySegments(inner) {
let trimmed = item.trimmingCharacters(in: .whitespaces)
var name = trimmed
// A quoted item carries its whitespace and its escapes
// (`\\` and `\"`) verbatim; a bare item is taken as written.
if trimmed.hasPrefix("\""), trimmed.hasSuffix("\""), trimmed.count >= 2 {
name = categoryUnescaped(String(trimmed.dropFirst().dropLast()))
}
guard !name.isEmpty, seen.insert(name).inserted else { continue }
names.append(name)
}
return names
}
/// `categoryListValue`'s escape, undone: `\\` is a backslash, `\"` a
/// quote. Any other escaped character keeps its backslash (a
/// hand-typed `\n` stays the two characters it is), and a trailing
/// lone backslash stays.
private static func categoryUnescaped(_ text: String) -> String {
var out = ""
var escaped = false
for char in text {
if escaped {
if char != "\\", char != "\"" {
out.append("\\")
}
out.append(char)
escaped = false
} else if char == "\\" {
escaped = true
} else {
out.append(char)
}
}
if escaped {
out.append("\\")
}
return out
}
/// The unbracketed render `categoryList` reads back — a name
/// holding `,` `[` `]` `"` or `\` rides double-quoted with its
/// backslashes and quotes escaped. Newlines and control characters
/// strip from every name first (the frontmatter sink is
/// line-bounded) and names left empty drop.
static func categoryListValue(_ names: [String]) -> String {
names.compactMap { name -> String? in
let cleaned = String(name.trimmingCharacters(in: .whitespaces).unicodeScalars.filter {
!CharacterSet.newlines.contains($0) && !CharacterSet.controlCharacters.contains($0)
})
guard !cleaned.isEmpty else { return nil }
guard cleaned.contains(where: { ",[]\"\\".contains($0) }) else { return cleaned }
let slashed = cleaned.replacingOccurrences(of: "\\", with: "\\\\")
return "\"" + slashed.replacingOccurrences(of: "\"", with: "\\\"") + "\""
}.joined(separator: ", ")
}
/// The list items, split on the commas outside double quotes (an
/// escaped quote inside a quoted item never toggles the quote
/// state — `["say \"hi\", Notes]` is two items).
/// The ONE segment scanner behind `categoryList` and the publish
/// sheet's `partial` — the raw (untrimmed, still-quoted) items.
static func categorySegments(_ text: String) -> [String] {
var items: [String] = []
var current = ""
var quoted = false
var escaped = false
for char in text {
if escaped {
current.append(char)
escaped = false
} else if char == "\\" {
current.append(char)
escaped = true
} else if char == "\"" {
current.append(char)
quoted.toggle()
} else if char == ",", !quoted {
items.append(current)
current = ""
} else {
current.append(char)
}
}
items.append(current)
return items
}
/// #207: the piece's categories from its `category:` line — ONE
/// line by construction (the read is line-bounded, #33), so a
/// value can never carry a newline. Shapes: `[Tech, Notes]` (the
/// bracketed list, read through `categoryList`), a bare scalar
/// (`Essays` — YAML's plain string) = ONE category, and empty /
/// absent = none.
static func categories(in matter: [String: String]) -> [String] {
guard let raw = matter["category"]?.trimmingCharacters(in: .whitespaces), !raw.isEmpty else { return [] }
let listShaped = raw.hasPrefix("[") && raw.hasSuffix("]") && raw.count >= 2
return listShaped ? categoryList(String(raw.dropFirst().dropLast())) : [raw]
}
/// #207: the one-line `category:` value `categories(in:)` reads
/// back — the bracketed `categoryListValue`. `[]` is the empty
/// list, the value a re-send's clear carries.
static func categoryValue(_ names: [String]) -> String {
"[" + categoryListValue(names) + "]"
}
/// #208: the piece's summary from its raw frontmatter text — ONE
/// line by construction (the read is line-bounded). Walks the block
/// the way the lenient `parse` does (past the opening fence to the
/// next `---`), but keeps the line's own quotes: `parse`'s scalar
/// trim strips EVERY edge quote character, which would eat a
/// teaser's closing `"why"`. A quoted value (the shape `summaryValue`
/// renders) unescapes through the category codec's one unescape; a
/// bare value is taken as written. No block, or no line → `""`, the
/// field's settled empty: a piece without a line never gains one, and
/// a BODY line named `summary:` never claims the key.
static func summary(inText text: String) -> String {
let lines = text.split(separator: "\n", omittingEmptySubsequences: false)
for line in lines.drop(while: { $0.trimmed() != "---" }).dropFirst() {
let trimmed = line.trimmed()
guard trimmed != "---" else { break }
guard trimmed.hasPrefix("summary:") else { continue }
// A stray \r before the newline fuses the closing fence onto
// this line (the last block line of a mixed-ending file) —
// the fence is never part of the value.
var raw = trimmed.dropFirst("summary:".count).trimmingCharacters(in: .whitespaces)
if let fused = raw.range(of: "\r\n---") {
raw = raw[..<fused.lowerBound].trimmingCharacters(in: .whitespaces)
}
if raw.hasPrefix("\""), raw.hasSuffix("\""), raw.count >= 2 {
return categoryUnescaped(String(raw.dropFirst().dropLast()))
}
return raw
}
return ""
}
/// #208: the one-line `summary:` value `summary(inText:)` reads
/// back. Control characters drop and every run of whitespace — a
/// newline included — collapses to one space: the frontmatter sink
/// is line-bounded, so the value is ONE line or nothing. A value
/// holding a quote or backslash renders QUOTED with both escaped —
/// the category codec's own escape, so ONE grammar serves both keys:
/// the lenient `parse` trims every edge quote (a teaser's closing
/// `"why"` would vanish through that door), so the summary is read
/// off its raw line and the wire never ships an altered teaser.
static func summaryValue(_ text: String) -> String {
let flattened = text
.split(whereSeparator: \.isWhitespace)
.joined(separator: " ")
.unicodeScalars.filter { !CharacterSet.controlCharacters.contains($0) }
let cleaned = String(flattened)
let needsQuoting = cleaned.contains(where: { "\"'\\".contains($0) })
guard needsQuoting else { return cleaned }
let slashed = cleaned.replacingOccurrences(of: "\\", with: "\\\\")
return "\"" + slashed.replacingOccurrences(of: "\"", with: "\\\"") + "\""
}
// 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. `dropping` removes those keys' lines outright, first (#206:
/// the import boundary and the 404 forget).
static func updating(text: String, with pairs: [(key: String, value: String)], dropping: Set<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.
if !dropping.isEmpty {
lines.removeAll { key(ofLine: $0).map(dropping.contains) == true }
}
let oursByKey = Dictionary(pairs.map { ($0.key, $0.value) }, uniquingKeysWith: { first, _ in first })
var seen = Set<String>()
for (index, line) in lines.enumerated() {
guard let key = key(ofLine: line), let value = oursByKey[key] else { continue }
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: <chosen>` win
/// (#95: our three keys win — external `type: outline` still imports
/// as post), and Museion's Micro.blog bookkeeping is dropped (#206: a
/// foreign file carries no post of this library — its `micropub_url`
/// would otherwise aim the next send's content replace). 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),
dropping: micropubKeys,
)
}
/// A block line's key — the update posture's ONE key read (so the
/// drop and the walk can never disagree about a line): leading and
/// trailing whitespace trimmed, a trailing `\r` included (CRLF
/// files). Nil for the fences and blank lines.
private static func key(ofLine line: String) -> String? {
let trimmed = line.trimmingCharacters(in: .whitespacesAndNewlines)
guard !trimmed.isEmpty, trimmed != "---" else { return nil }
return String(line.split(separator: ":", maxSplits: 1).first ?? "").trimmingCharacters(in: .whitespaces)
}
}