Files
museion/Museion/PostFrontmatter.swift
T
AlexKucera 6aa31a419a feat(microblog): show Micro.blog publish status
The publish sheet flipped a draft live and remembered nothing, so
nothing on disk said a piece was out and the library could not show
it. A successful Publish now stamps `micropub_published` in the
piece's frontmatter; the row and the sheet read `published <date>`
or `draft on Micro.blog`, and a published piece's menu opens the
live post.

Sending a piece again no longer creates a second post: a piece that
remembers its post updates it in place (name and content only, so
categories set on Micro.blog survive). An image whose bytes are
unchanged rides its earlier upload through a per-piece memo. When
Micro.blog answers 404 the piece forgets both keys and the sheet
offers a fresh draft; a clear that cannot land says so instead of
claiming the link is gone.

Museion's micropub keys are dropped at the import boundary. An
imported `micropub_url` passes the format gate and would aim the
in-place update at one of the writer's own posts under their token,
so the keys are treated like `origin`: ours to set, never a foreign
file's to carry in. Publish is model-owned and trust-gates its URL
before anything is stamped.

Tests read recorded requests through an optional accessor: an
out-of-range subscript after a failed count expectation trapped the
hosted runner and reported every queued test as crashed.

+16 tests net (17 new pins in MicropubStatusTests, one retired whose
premise the in-place design voids); every new pin was watched fail
on its own guard. Rail 752/752; SwiftFormat and SwiftLint clean.
Reviews: standards + spec during the build, then a three-reviewer
finish audit. Docs: AGENTS.md bullets and learnings, GLOSSARY
terms, CHANGELOG [Unreleased], README, and the devlog.

Closes #206
2026-12-04 17:45:35 +01:00

225 lines
11 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.
//
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: - 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)
}
}