refactor(posts): one frontmatter read/write codec
CI / ci (push) Canceled after 0s
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:
1 parent
5bf09552f6
commit
218e2db397
22 files changed
+479
-221
No files matched your search
+3
-2
@@ -25,8 +25,9 @@ The map and the contracts, one bullet per file. Pin-level detail lives in the te
|
||||
- `DesignTokens.swift` — palette/geometry. Two-color world, live-calibrated (deliberate departure from the export palette): `background` #FAF9F3 (chrome + focus ground), `surface` #FFFEFB (one page color for edit AND read); light-only, the single semantic exception `readyGreen` (the mentor ready dot — a meaning, never a style color). Radius 10; column widths rail 56 / library 232 / mentor 356; chat face constructors `valkyrie`/`concourse`/`ubuntuMono` (Font.custom falls back to system).
|
||||
- `WorkspaceView.swift` — first-frame main surface, rendered unconditionally (gateless: the engine check runs async beside it). Nav rail Posts / Sessions / Learnings / Trends / Archive + engine-status pill + Settings. Column collapse mirrors the export's media queries as pane collapse — library hides < 1100 px, mentor < 920 px; never a fixed four-column minWidth. Window-level `.dropDestination` (markdown only → external guest): ONE window-level destination is the whole routing surface under this hosting — nested editor-level SwiftUI destinations and NSTextView drag registrations starve (field-verified); a mixed md+image set refuses loudly. The house ask sheets present here (pending-state + binding pattern): `OriginAskSheet` (one ask per import batch), `OutlineGuardSheet`, `ConvertSheet`, `NewProjectSheet`.
|
||||
- `PostsPaneView.swift` — Posts destination: library column (`PostsLibraryColumn`: project section heads + Pass-State groups, collapse toggle per-view; `LibraryPostRow` — 2px leading strip, ✳ on outline pieces, row menu Rename/Convert/Move to Project/Move to Archive/Trash), editor column, mentor column (fixed 356). Library search: debounced, title+body over non-archived pieces, body scan off-main through `readBody` (frontmatter never searched). Editor column renders the external guest ahead of the post session (one guest at a time). Focused branch mounts the Cold Turkey chrome as overlays; lock transitions never restructure the editor column.
|
||||
- `PostLibrary.swift` — `Post` + `Post.scan`: two-level scan over `projects/<name>/<id>/post.md` AND `archive/<name>/<id>/post.md` (ADR-0012), skip guards at both levels (lazy folders, loose files, hidden dirs, symlinked dirs); frontmatter keys read leniently (First Draft/writer/post defaults); title = first non-empty body line, `untitled` fallbacks; runs off-main. `stats_*` keys load only if EVERY value parses finite (a non-finite peak would trap the chart y-domain); read-back re-gates on the immutable pair (origin writer, type post — never pass_state, which legitimately advances). `scan(home:cache:)` takes a `PostScanCache` (path+mtime+size memo; the stamp is taken BEFORE the read, so a mid-scan rewrite can never pin as fresh). `micropubURL` gated on `Micropub.trustworthyURL` — imported YAML rides verbatim, so hostile values scan nil.
|
||||
- `PostStore.swift` — write side (nonisolated). Shared slug (lowercase, diacritic-fold, strip punctuation, whitespace→hyphens, keep CJK, 80-char cap); collision suffixes over the GLOBAL slug space (projects + archive — an archived slug is never reused), all comparisons through `folded` = NFC + lowercase (APFS is case- and normalization-insensitive); `folder(of:home:)` is the ONE id→folder resolver — write paths derive their target from the id alone. `writeNew` defaults `type: .post` / `origin: .writer` (session-born pieces pass `.ai`, immutable). `overwrite` preserves type/pass_state/origin and updates owned keys IN PLACE via `stampingFrontmatter` — block rewrites erase captured stats and foreign frontmatter. `rename` = retitle + move within the same parent. `importFile` copies (never moves), strips BOM + normalizes CRLF→LF at the boundary, external YAML keys verbatim with our `type`/`pass_state`/`origin` winning. Project ops (`move`/`archive`/`restore`/`unarchiveProject`/`createProject`) derive current state from the resolved DISK path, never the scan snapshot; post.md bytes are never rewritten by them; `createProject` validates names (empty/slash/dot/`:`/control + case-insensitive duplicates throw). Pass substrate: `snapshotPass` (pre-pass body verbatim to `passes/pass-<n>.md`, fixed name per type), `advancePassState` (monotonic, in-place stamp; also ticks the decay clock — a failed tick never fails a pass). `writeResearchNote` is the ONLY path to `research/` (a symlinked dir refuses). `captureFirstDraftStats` — eligibility read from the file's own frontmatter (writer/First Draft/post); failure never fails the pass. `ingestImage` copies into `assets/`, publishable types only (what can't ship can't enter); `illustrationRef` is the one `` builder.
|
||||
- `PostLibrary.swift` — `Post` + `Post.scan`: two-level scan over `projects/<name>/<id>/post.md` AND `archive/<name>/<id>/post.md` (ADR-0012), skip guards at both levels (lazy folders, loose files, hidden dirs, symlinked dirs); frontmatter keys read leniently (First Draft/writer/post defaults); title = first non-empty body line, `untitled` fallbacks; runs off-main. `stats_*` keys load only if EVERY value parses finite (a non-finite peak would trap the chart y-domain); read-back re-gates on the named immutable pair (`PostFrontmatter.isUnaidedFirstDraftPair` — origin writer, type post; never pass_state, which legitimately advances). `scan(home:cache:)` takes a `PostScanCache` (path+mtime+size memo; the stamp is taken BEFORE the read, so a mid-scan rewrite can never pin as fresh). `micropubURL` gated on `Micropub.trustworthyURL` — imported YAML rides verbatim, so hostile values scan nil.
|
||||
- `PostFrontmatter.swift` — #180: the Post frontmatter codec — the ONE lenient read (`parse`/`split`/`decoded`) and the three write postures behind one known-key table (`ownedKeys`: type, pass_state, origin — one insertion-order rule): fresh stamp (`stamped`), merge-import (`mergingImport` — external keys verbatim, ours win), update-keys (`updating` — the in-place line-walk, every other line byte-identical). Absorbed and deleted `PostStore.stamped/splitFrontmatter/mergedFrontmatter` and `LearningDecay.stampingFrontmatter` byte-identically (merge-import's documented prefix-preservation divergence excepted). Owns the two named eligibility predicates both gates consume: `isUnaidedFirstDraftPair` (writer ∧ post — the scan's read-back gate) and `isCaptureEligible` (pair ∧ First Draft — the capture gate). Learning/Fix Card documents stay out of scope; the learnings dismiss stamp rides the generic update posture.
|
||||
- `PostStore.swift` — write side (nonisolated). Shared slug (lowercase, diacritic-fold, strip punctuation, whitespace→hyphens, keep CJK, 80-char cap); collision suffixes over the GLOBAL slug space (projects + archive — an archived slug is never reused), all comparisons through `folded` = NFC + lowercase (APFS is case- and normalization-insensitive); `folder(of:home:)` is the ONE id→folder resolver — write paths derive their target from the id alone. `writeNew` defaults `type: .post` / `origin: .writer` (session-born pieces pass `.ai`, immutable). `overwrite` preserves type/pass_state/origin and updates owned keys IN PLACE via the codec's update posture — block rewrites erase captured stats and foreign frontmatter. `rename` = retitle + move within the same parent. `importFile` copies (never moves), strips BOM + normalizes CRLF→LF at the boundary, external YAML keys verbatim with our `type`/`pass_state`/`origin` winning. Project ops (`move`/`archive`/`restore`/`unarchiveProject`/`createProject`) derive current state from the resolved DISK path, never the scan snapshot; post.md bytes are never rewritten by them; `createProject` validates names (empty/slash/dot/`:`/control + case-insensitive duplicates throw). Pass substrate: `snapshotPass` (pre-pass body verbatim to `passes/pass-<n>.md`, fixed name per type), `advancePassState` (monotonic, in-place stamp; also ticks the decay clock — a failed tick never fails a pass). `writeResearchNote` is the ONLY path to `research/` (a symlinked dir refuses). `captureFirstDraftStats` — eligibility is the codec's named `isCaptureEligible` predicate over the file's own frontmatter; failure never fails the pass. `ingestImage` copies into `assets/`, publishable types only (what can't ship can't enter); `illustrationRef` is the one `` builder.
|
||||
- `DraftStats.swift` — the four unaided-first-draft metrics (burstiness, typeTokenRatio, sentenceVariation, trigramRepetition), pure and never NaN; `words(in:)` is the ONE word-count rail (Cold Turkey counts with it — text metrics can never drift).
|
||||
- `WritingGoal.swift` — the pure goal engine (no UI, no clock): `now` injected, `isMet` live and unlatched (deleting below target un-mets).
|
||||
- `WritingLockState.swift` — the lock machine + kiosk: 1 s ticker + per-keystroke `feed(text:)` drive the goal run, `tick(at:)` completes on the first met tick; kiosk = the 6-option combo recipe, enter/exit replay only what entry toggled, exit clears options FIRST; ⌘W/⌃⌘F/⌘N refusals = a local keyDown monitor matched by KEY CODE + exact modifier set + lowercased character net (charactersIgnoringModifiers is layout- and Caps-Lock-dependent); hosted-test guard = full no-op (never kiosk the test machine); nothing persists — the block dies with the session.
|
||||
|
||||
@@ -422,7 +422,7 @@ nonisolated enum FixCardStore {
|
||||
.sorted()
|
||||
return files.compactMap { name in
|
||||
guard let markdown = try? String(contentsOf: dir.appendingPathComponent(name), encoding: .utf8),
|
||||
LearningDecay.passesHidden(Post.frontmatter(of: markdown), currentPass: currentPass) == nil
|
||||
LearningDecay.passesHidden(PostFrontmatter.parse(markdown), currentPass: currentPass) == nil
|
||||
else { return nil }
|
||||
return (file: name, markdown: markdown)
|
||||
}
|
||||
@@ -444,7 +444,7 @@ nonisolated enum FixCardStore {
|
||||
for _ in 0 ..< 4 {
|
||||
home.deleteLastPathComponent()
|
||||
}
|
||||
return (home, Post.ContentType(rawValue: Post.frontmatter(of: text)["type"] ?? "") ?? .post)
|
||||
return (home, PostFrontmatter.decoded(PostFrontmatter.parse(text)).type)
|
||||
}
|
||||
|
||||
// MARK: - Promote (#26, S4.1/S4.3)
|
||||
|
||||
@@ -160,7 +160,7 @@ nonisolated enum LearningDecay {
|
||||
throw FixCardStore.CardError(message: "learning not found: \(file)")
|
||||
}
|
||||
|
||||
let frontmatter = Post.frontmatter(of: text)
|
||||
let frontmatter = PostFrontmatter.parse(text)
|
||||
let clock = passCounts(home: home)[typeDir] ?? 0
|
||||
if let remaining = passesHidden(frontmatter, currentPass: clock) {
|
||||
throw FixCardStore.CardError(message: "already dismissed — resurfaces in \(remaining) \(remaining == 1 ? "pass" : "passes")")
|
||||
@@ -168,8 +168,10 @@ nonisolated enum LearningDecay {
|
||||
// Clamped before +1 — an absurd hand-edited dismiss_count must not
|
||||
// trap the stamp.
|
||||
let count = min(dismissCount(in: frontmatter), valueCeiling)
|
||||
let stamped = stampingFrontmatter(
|
||||
of: text,
|
||||
// #180: the codec's update-keys posture (the mechanical walk this
|
||||
// file used to own); the Learning document shape is unchanged.
|
||||
let stamped = PostFrontmatter.updating(
|
||||
text: text,
|
||||
with: [
|
||||
("dismissed", FixCardStore.formatted(now, "yyyy-MM-dd")),
|
||||
("dismiss_count", "\(count + 1)"),
|
||||
@@ -178,48 +180,4 @@ nonisolated enum LearningDecay {
|
||||
)
|
||||
try stamped.write(to: url, atomically: true, encoding: .utf8)
|
||||
}
|
||||
|
||||
/// The surgical frontmatter rewrite (mergedFrontmatter's line-walk,
|
||||
/// generalized to ordered pairs): set-overwrite the keys in place,
|
||||
/// insert absent ones before the closing `---`, preserve every other
|
||||
/// line verbatim (leading hand-edit lines above the opening `---`
|
||||
/// included), keep the block's trailing newline. No frontmatter
|
||||
/// block at all → prepend a fresh one. Internal since #31: the
|
||||
/// first-draft stats capture is the third caller.
|
||||
// ponytail: PostStore.mergedFrontmatter's line-walk duplicated and
|
||||
// generalized — extraction would grow PostStore at its type-body
|
||||
// ceiling; #31's capture is the third caller and it STILL isn't
|
||||
// extracted (LearningDecay + PostStore stay the two owners; the
|
||||
// type-body ceilings named above are unchanged).
|
||||
static func stampingFrontmatter(of text: String, with pairs: [(key: String, value: String)]) -> String {
|
||||
let (block, body) = PostStore.splitFrontmatter(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 —
|
||||
// Post.frontmatter tolerates one) fall in neither block nor
|
||||
// body; keep them verbatim so the rewrite loses nothing (#27 review).
|
||||
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()
|
||||
}
|
||||
let oursByKey = Dictionary(pairs.map { ($0.key, $0.value) }, uniquingKeysWith: { first, _ in first })
|
||||
var seen = Set<String>()
|
||||
for (index, line) in lines.enumerated() {
|
||||
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 = 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
|
||||
}
|
||||
}
|
||||
@@ -32,7 +32,7 @@ nonisolated enum LearningsIndex {
|
||||
let resurfacesIn: Int?
|
||||
|
||||
init(file: String, text: String, currentPass: Int? = nil) {
|
||||
let frontmatter = Post.frontmatter(of: text)
|
||||
let frontmatter = PostFrontmatter.parse(text)
|
||||
id = file
|
||||
pattern = frontmatter["pattern"] ?? Self.pattern(fromFilename: file)
|
||||
problem = frontmatter["problem"].flatMap { $0.isEmpty ? nil : $0 }
|
||||
|
||||
@@ -273,7 +273,7 @@ extension PostsModel {
|
||||
else {
|
||||
return .refused("Couldn't read the piece before sending.")
|
||||
}
|
||||
let body = PostStore.splitFrontmatter(raw).body
|
||||
let body = PostFrontmatter.split(raw).body
|
||||
guard !body.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else {
|
||||
return .refused("This piece has no text to send.")
|
||||
}
|
||||
|
||||
@@ -0,0 +1,193 @@
|
||||
//
|
||||
// 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).
|
||||
/// - **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 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.
|
||||
static func updating(text: String, with pairs: [(key: String, value: 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.
|
||||
let oursByKey = Dictionary(pairs.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 = 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). 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))
|
||||
}
|
||||
}
|
||||
+11
-31
@@ -179,15 +179,14 @@ nonisolated struct Post: Identifiable, Equatable {
|
||||
/// kept this a pure function of (text, location); the cache memoizes
|
||||
/// its output, nothing else).
|
||||
private static func parse(text: String, id: String, project: String, isArchived: Bool) -> Post {
|
||||
let frontmatter = frontmatter(of: text)
|
||||
let origin = Origin(rawValue: frontmatter["origin"] ?? "") ?? .writer
|
||||
let type = ContentType(rawValue: frontmatter["type"] ?? "") ?? .post
|
||||
let frontmatter = PostFrontmatter.parse(text)
|
||||
let stamp = PostFrontmatter.decoded(frontmatter)
|
||||
return Post(
|
||||
id: id,
|
||||
title: title(of: text),
|
||||
passState: PassState(rawValue: frontmatter["pass_state"] ?? "") ?? .firstDraft,
|
||||
origin: origin,
|
||||
type: type,
|
||||
passState: stamp.passState,
|
||||
origin: stamp.origin,
|
||||
type: stamp.type,
|
||||
project: project,
|
||||
isArchived: isArchived,
|
||||
// #33: the remembered Micro.blog draft URL —
|
||||
@@ -199,37 +198,18 @@ nonisolated struct Post: Identifiable, Equatable {
|
||||
micropubURL: frontmatter["micropub_url"].flatMap {
|
||||
Micropub.trustworthyURL($0) ? $0 : nil
|
||||
},
|
||||
// #32 read-back gate: the capture gate's immutable
|
||||
// pair (origin writer, type post) — NOT pass_state,
|
||||
// which legitimately advances after the capture.
|
||||
// `stats_*` keys can arrive by import (external YAML
|
||||
// rides verbatim), so an imported ai piece or outline
|
||||
// #32/#180 read-back gate: the named immutable pair
|
||||
// (origin writer, type post) — NOT pass_state, which
|
||||
// legitimately advances after the capture. `stats_*`
|
||||
// keys can arrive by import (external YAML rides
|
||||
// verbatim), so an imported ai piece or outline
|
||||
// carrying hand-stamped keys still never renders;
|
||||
// a migrated writer piece keeps its real arc.
|
||||
firstDraftStats: origin == .writer && type == .post
|
||||
firstDraftStats: PostFrontmatter.isUnaidedFirstDraftPair(frontmatter)
|
||||
? Post.FirstDraftStats(frontmatter: frontmatter) : nil,
|
||||
)
|
||||
}
|
||||
|
||||
/// The `---`-delimited frontmatter block if present; empty otherwise.
|
||||
/// Quoted scalar values (`origin: "ai"`) are unquoted — lenient YAML.
|
||||
static func frontmatter(of 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
|
||||
}
|
||||
|
||||
/// The Post's Title: first non-empty line after any frontmatter block,
|
||||
/// `#` heading markers stripped; `untitled` when nothing readable remains.
|
||||
static func title(of text: String) -> String {
|
||||
|
||||
+31
-95
@@ -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)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -29,9 +29,9 @@ extension PostsModel {
|
||||
let type: Post.ContentType = if let known = posts.first(where: { $0.id == id })?.type {
|
||||
known
|
||||
} else {
|
||||
Post.ContentType(rawValue: Post.frontmatter(of: text)["type"] ?? "") ?? .post
|
||||
PostFrontmatter.decoded(PostFrontmatter.parse(text)).type
|
||||
}
|
||||
return type == .outline && OutlineTree.parsesWithLoss(PostStore.splitFrontmatter(text).body)
|
||||
return type == .outline && OutlineTree.parsesWithLoss(PostFrontmatter.split(text).body)
|
||||
}
|
||||
|
||||
/// #111 (S7): guard answers. Prose = safe open in prose mode (the
|
||||
|
||||
Reference in new issue
Block a user