refactor(posts): one frontmatter read/write codec
CI / ci (push) Canceled after 0s

#180: one PostFrontmatter module now owns the lenient read
(parse/split/decoded) and every write posture — fresh stamp,
merge-import, update-keys — behind one known-key table (type,
pass_state, origin; one insertion order). The three near-twin walkers
are deleted byte-identically: PostStore.stamped/splitFrontmatter/
mergedFrontmatter, LearningDecay.stampingFrontmatter,
Post.frontmatter(of:) — 21 call sites swept across seven production
files and eight test files.

The Unaided First Draft eligibility is named once and consumed by both
gates: isUnaidedFirstDraftPair (writer ∧ post — the scan's read-back
gate) and isCaptureEligible (pair ∧ First Draft — the capture gate at
pass invocation). The lenient ?? default stamp decode is extracted
with it (the third copy's deferred extraction).

One deliberate divergence from the absorbed writer, doc-commented and
pinned: mergingImport now preserves hand-edit lines above the opening
--- on import where the old split-first shape silently dropped them —
lossless through every posture is the ticket's contract. Seven codec
pins (PostFrontmatterTests) cover the posture round-trip (foreign keys
verbatim through import → save → advance → micropub), the lenient
unknown-type decode, and the predicates' truth table.

Existing pieces are untouched on disk: every posture moved verbatim
and the full suite pins the byte shapes (664/664 green; the one
under-load flake in the #179 repoint pin is pre-existing on main,
proven by a stashed-tree control run).

Closes #180
This commit is contained in:
AlexKucera committed 2026-11-10 10:21:32 +01:00
1 parent 5bf09552f6
commit 218e2db397
22 files changed
+479 -221

No files matched your search

+31 -95
View File
@@ -154,7 +154,7 @@ nonisolated enum PostStore {
origin: Post.Origin = .writer, home: URL,
) throws -> Post {
try materialize(
text: stamped(body: body, passState: .firstDraft, origin: origin, type: type),
text: PostFrontmatter.stamped(body: body, passState: .firstDraft, origin: origin, type: type),
title: Post.title(of: body),
origin: origin,
project: project,
@@ -181,11 +181,10 @@ nonisolated enum PostStore {
raw.removeFirst()
}
raw = raw.replacingOccurrences(of: "\r\n", with: "\n")
let (block, body) = splitFrontmatter(raw)
let text = mergedFrontmatter(keeping: block, origin: origin) + body
let text = PostFrontmatter.mergingImport(text: raw, origin: origin)
return try materialize(
text: text,
title: Post.title(of: body),
title: Post.title(of: PostFrontmatter.split(raw).body),
origin: origin,
project: project,
type: .post, // #95: our keys win — external `type: outline` still imports as post
@@ -193,48 +192,6 @@ nonisolated enum PostStore {
)
}
/// #95/#107: external frontmatter keys ride along verbatim; `type`,
/// `pass_state` and `origin` are set/overwritten in place — our three
/// keys win, everything else untouched. Absent keys are inserted before
/// the closing `---` (in that order). Returns the block INCLUDING its
/// trailing newline; "" for a bare file (the caller then writes the #59
/// stamp shape via a fresh block).
private static func mergedFrontmatter(keeping block: String, origin: Post.Origin) -> String {
guard !block.isEmpty else {
return "---\ntype: post\npass_state: \(Post.PassState.firstDraft.rawValue)\norigin: \(origin.rawValue)\n---\n"
}
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()
}
// #107: three our-keys win — type/pass_state/origin set-overwrite in
// place, absent ones insert before the closing --- in stamp order.
// Ordered pairs (a Dictionary's iteration order is unspecified).
let ours: [(key: String, value: String)] = [
("type", "post"),
("pass_state", Post.PassState.firstDraft.rawValue),
("origin", origin.rawValue),
]
let oursByKey = Dictionary(ours.map { ($0.key, $0.value) }, uniquingKeysWith: { first, _ in first })
var seen = Set<String>()
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 = ours.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 lines.joined(separator: "\n") + "\n"
}
/// #62/#95: lazily materialize `projects/<project>/<slug>/post.md` with
/// the given (already stamped/merged) text. Shared by `writeNew` and
/// `importFile` — one lazy-folder path, TOCTOU-guarded, never clobbering.
@@ -275,7 +232,7 @@ nonisolated enum PostStore {
/// file's present `pass_state`/`origin`/`type` are preserved (origin
/// immutable, CONTEXT.md; bare corpus posts normalize on save, #59).
/// **#31 audit fix: blocked files update the three owned keys IN PLACE
/// (stampingFrontmatter) and swap in the caller's body — the old
/// (PostFrontmatter.updating) and swap in the caller's body — the old
/// stamped() round-trip rebuilt the block from three parsed fields,
/// erasing the first-draft stats captured at the pass invocation and
/// any foreign frontmatter on every editor save.** A vanished post
@@ -284,13 +241,14 @@ nonisolated enum PostStore {
static func overwrite(id: String, body: String, home: URL) throws {
let piece = try existingStamp(id: id, home: home)
let raw = try String(contentsOf: piece.dir.appendingPathComponent("post.md"), encoding: .utf8)
let text = try PostStore.splitFrontmatter(raw).block.isEmpty
? stamped(body: body, passState: piece.passState, origin: piece.origin, type: piece.type)
: PostStore.splitFrontmatter(LearningDecay.stampingFrontmatter(of: raw, with: [
("type", piece.type.rawValue),
("pass_state", piece.passState.rawValue),
("origin", piece.origin.rawValue),
])).block + body
// #180: the codec's postures — bare files take the fresh stamp,
// blocked files update the owned keys in place (the update walk)
// and swap in the caller's body.
let text = PostFrontmatter.split(raw).block.isEmpty
? PostFrontmatter.stamped(body: body, passState: piece.passState, origin: piece.origin, type: piece.type)
: PostFrontmatter.split(PostFrontmatter.updating(text: raw, with: PostFrontmatter.ownedKeys(
type: piece.type, passState: piece.passState, origin: piece.origin,
))).block + body
try text.write(to: piece.dir.appendingPathComponent("post.md"), atomically: true, encoding: .utf8)
}
@@ -307,13 +265,14 @@ nonisolated enum PostStore {
else {
throw CocoaError(.fileReadNoSuchFile)
}
let matter = Post.frontmatter(of: existing)
let matter = PostFrontmatter.parse(existing)
let stamp = PostFrontmatter.decoded(matter)
return (
dir,
Post.PassState(rawValue: matter["pass_state"] ?? "") ?? .firstDraft,
Post.Origin(rawValue: matter["origin"] ?? "") ?? .writer,
Post.ContentType(rawValue: matter["type"] ?? "") ?? .post,
splitFrontmatter(existing).body,
stamp.passState,
stamp.origin,
stamp.type,
PostFrontmatter.split(existing).body,
)
}
@@ -323,7 +282,7 @@ nonisolated enum PostStore {
guard let dir = folder(of: id, home: home),
let text = try? String(contentsOf: dir.appendingPathComponent("post.md"), encoding: .utf8)
else { return nil }
return splitFrontmatter(text).body
return PostFrontmatter.split(text).body
}
/// #114 (S4): Convert to Post — the one-time in-place transform. The
@@ -334,7 +293,7 @@ nonisolated enum PostStore {
static func convert(id: String, headingsLadder: Bool, home: URL) throws {
let piece = try existingStamp(id: id, home: home)
let transformed = headingsLadder ? OutlineTree.headingsLadderBody(piece.body) : piece.body
try stamped(body: transformed, passState: piece.passState, origin: piece.origin, type: .post)
try PostFrontmatter.stamped(body: transformed, passState: piece.passState, origin: piece.origin, type: .post)
.write(to: piece.dir.appendingPathComponent("post.md"), atomically: true, encoding: .utf8)
}
@@ -349,7 +308,7 @@ nonisolated enum PostStore {
}
let fileURL = dir.appendingPathComponent("post.md")
let text = try String(contentsOf: fileURL, encoding: .utf8)
let (block, body) = splitFrontmatter(text)
let (block, body) = PostFrontmatter.split(text)
try (block + replacingTitleLine(of: body, with: "# \(title)"))
.write(to: fileURL, atomically: true, encoding: .utf8)
@@ -517,24 +476,6 @@ nonisolated enum PostStore {
return trimmed
}
/// The #59 v1 block (+ `type`, #107) — flat keys, the exact shape the
/// #17 reader parses.
static func stamped(body: String, passState: Post.PassState, origin: Post.Origin, type: Post.ContentType = .post) -> String {
"---\ntype: \(type.rawValue)\npass_state: \(passState.rawValue)\norigin: \(origin.rawValue)\n---\n" + body
}
/// Splits a file into its verbatim frontmatter block (with both `---`
/// lines) and the body; no block → ("", whole text).
static func splitFrontmatter(_ 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"))
}
/// Replace the body's Title heading with `line`; a body whose first
/// non-empty line is NOT a heading keeps that line (it's content) and
/// gets the heading inserted above it. An empty body becomes just `line`.
@@ -605,7 +546,7 @@ nonisolated extension PostStore {
/// the new state is the higher of the file's current state and the
/// pass's doneState — passes run in ANY order, so a Pass 1 completing
/// on a Pass-2 Done piece never regresses it. **#31 (S5.1): the state
/// update is an IN-PLACE key stamp (stampingFrontmatter), not the
/// update is an IN-PLACE key stamp (PostFrontmatter.updating), not the
/// existingStamp→stamped block rewrite — the rewrite carried only
/// type/pass_state/origin and silently erased the first-draft stats
/// captured at the invocation (and any foreign frontmatter).** Bare
@@ -615,9 +556,9 @@ nonisolated extension PostStore {
let piece = try existingStamp(id: id, home: home)
let advanced = higherState(piece.passState, kind.doneState)
let raw = try String(contentsOf: piece.dir.appendingPathComponent("post.md"), encoding: .utf8)
let text = try PostStore.splitFrontmatter(raw).block.isEmpty
? stamped(body: piece.body, passState: advanced, origin: piece.origin, type: piece.type)
: LearningDecay.stampingFrontmatter(of: raw, with: [("pass_state", advanced.rawValue)])
let text = PostFrontmatter.split(raw).block.isEmpty
? PostFrontmatter.stamped(body: piece.body, passState: advanced, origin: piece.origin, type: piece.type)
: PostFrontmatter.updating(text: raw, with: [("pass_state", advanced.rawValue)])
try text.write(to: piece.dir.appendingPathComponent("post.md"), atomically: true, encoding: .utf8)
// The decay clock counts completed passes per content type (#27).
// try?: a failed clock bump must never fail a completed pass, and
@@ -708,7 +649,7 @@ nonisolated extension PostStore {
/// own frontmatter alone (same lenient defaults as Post.scan — a bare
/// legacy post qualifies): origin writer, Pass State First Draft, type
/// post. Not eligible → false, file untouched. The stamp is in place
/// (stampingFrontmatter): every non-stats line byte-identical, so a
/// (PostFrontmatter.updating): every non-stats line byte-identical, so a
/// re-invocation while still First Draft overwrites — latest draft
/// state wins. Any read/write failure → false: a failed capture must
/// never fail the pass (the decay-clock posture).
@@ -717,16 +658,11 @@ nonisolated extension PostStore {
guard let dir = folder(of: id, home: home),
let text = try? String(contentsOf: dir.appendingPathComponent("post.md"), encoding: .utf8)
else { return false }
let matter = Post.frontmatter(of: text)
// ponytail: third copy of the lenient `?? default` stamp decode
// (Post.scan, existingStamp) — extract one shared decode when a
// fourth caller needs it.
guard Post.Origin(rawValue: matter["origin"] ?? "") ?? .writer == .writer,
Post.PassState(rawValue: matter["pass_state"] ?? "") ?? .firstDraft == .firstDraft,
Post.ContentType(rawValue: matter["type"] ?? "") ?? .post == .post
else { return false }
// #180: the named capture predicate — pair ∧ First Draft, leniently
// decoded (a bare legacy post qualifies).
guard PostFrontmatter.isCaptureEligible(PostFrontmatter.parse(text)) else { return false }
let stats = DraftStats.compute(body: body)
let stamped = LearningDecay.stampingFrontmatter(of: text, with: [
let stamped = PostFrontmatter.updating(text: text, with: [
("stats_captured", FixCardStore.formatted(Date(), "yyyy-MM-dd'T'HH:mm:ss")), // lexically sortable
("stats_burstiness", String(format: "%.3f", stats.burstiness)),
("stats_type_token_ratio", String(format: "%.3f", stats.typeTokenRatio)),
@@ -752,7 +688,7 @@ nonisolated extension PostStore {
}
let file = dir.appendingPathComponent("post.md")
let raw = try String(contentsOf: file, encoding: .utf8)
try LearningDecay.stampingFrontmatter(of: raw, with: [("micropub_url", url)])
try PostFrontmatter.updating(text: raw, with: [("micropub_url", url)])
.write(to: file, atomically: true, encoding: .utf8)
}
}