Files
museion/Museion/PostFrontmatter.swift
T
AlexKucera 6db4cf8cf1 feat(microblog): set and create categories
A piece's `category:` frontmatter line now travels to Micro.blog: a
first send carries the list beside title and content, and a re-send
replaces the post's categories with exactly the piece's list — only
when the piece has the line (opt-in by key; `[]` clears; no line
leaves the blog's). Naming a category Micro.blog doesn't know creates
it there, so there is no separate create step.

The publish sheet gains a Categories field: a comma list with the
system completion menu over the blog's own categories. The system
replaces the whole field text with a completion, so the completion is
the merge — a pick adds, a half-typed last word is replaced. The edit
lands on the piece at the send (a failed write refuses with nothing
on the wire); Publish with a pending edit applies it first and flips
the post that send touched.

The one-line codec lives in PostFrontmatter (line-bounded; backslashes
and quotes escaped; a Set de-duplicates). Import keeps an imported
`category:` line — the writer's classification, unlike the micropub
bookkeeping keys.

Reviewed twice (two-axis during the build, finish-audit after): the
stale pending baseline after a failed step, the backslash round-trip,
and the publish targeting the caller's possibly-stale URL were found
and fixed before this commit. 39 of the 40 new or changed pins were
watched fail on their own guard. Rail 791/791; SwiftFormat and
SwiftLint clean.

Docs: AGENTS.md bullets and learnings, the GLOSSARY term, CHANGELOG
[Unreleased], PRD S6.1, the devlog, and the swift wiki (text
completion is a whole-text contract).

Closes #207
2026-12-05 08:09:57 +01:00

349 lines
15 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) + "]"
}
// 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)
}
}