diff --git a/AGENTS.md b/AGENTS.md index 9b54296..1f093dc 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -130,7 +130,7 @@ Single-context: `GLOSSARY.md` + `docs/adr/` at the repo root. See `docs/agents/d # GitNexus — Code Intelligence -This project is indexed by GitNexus as **museion** (6768 symbols, 31339 relationships, 300 execution flows). Use the GitNexus MCP tools to understand code, assess impact, and navigate safely. +This project is indexed by GitNexus as **museion** (6786 symbols, 31918 relationships, 300 execution flows). Use the GitNexus MCP tools to understand code, assess impact, and navigate safely. > Index stale? Run `node .gitnexus/run.cjs analyze` from the project root — it auto-selects an available runner. No `.gitnexus/run.cjs` yet? `npx gitnexus analyze` (npm 11 crash → `npm i -g gitnexus`; #1939). @@ -193,10 +193,11 @@ This project is indexed by GitNexus as **museion** (6768 symbols, 31339 relation - A `//` note sitting between a `///` doc block and its declaration detaches the doc (swiftlint orphaned_doc_comment) — fold such notes into the `///` block (#143) - Sequential bounded-poll loops each arm their OWN deadline — a shared one starves the later loop, which then fails on the earlier flush's stale observable (zeros, never nil) (#147) - A pure test-file split changes Swift Testing's parallel schedule — a green-by-luck timing test can fail ~50% idle; fix the test's timing assumptions, not the split (#147) +- One walk absorbed from near-twin writers inherits the more-lossless twin's edge behavior (import's prefix-drop became preserve) — audit each absorbed writer's divergences and pin the deliberate ones (#180) ### Trust boundaries - A guard defending against a downstream validation must mirror its EXACT emptiness/shape semantics — FixCardStore validates TRIMMED emptiness, so an `isEmpty` guard passes whitespace-only phrases through and the whole-call failure silently kills the entire submit (#6) - A trust gate matches its SINK's grammar, not just its own format check — `trustworthyURL` (built for line-bounded frontmatter) passed URLs whose `)` injects a live link once the sink became markdown; gate at the sink (angle-form destination), never trust the reused gate (#34) -- Post.frontmatter is LINE-BOUNDED on read — a newline can never ride one scanned value; multi-line injection threatens only WRITE paths that interpolate raw values into the block (stampingFrontmatter), so gate external data before it reaches a stamp, not at scan (#33) +- The frontmatter read (`PostFrontmatter.parse`) is LINE-BOUNDED — a newline can never ride one scanned value; multi-line injection threatens only WRITE paths that interpolate raw values into the block (`PostFrontmatter.updating`), so gate external data before it reaches a stamp, not at scan (#33) ## Session Logs @@ -205,6 +206,7 @@ Session logs live in `docs/devlog/` (one per completed task/issue/milestone). Fu | Date | Log | |------|-----| +| 2026-11-10 | [20261110-issue180-postfrontmatter-codec-one-readwrite-engine_log.md](docs/devlog/20261110-issue180-postfrontmatter-codec-one-readwrite-engine_log.md) | | 2026-11-09 | [20261109-issue179-postsmodel-write-rail_log.md](docs/devlog/20261109-issue179-postsmodel-write-rail_log.md) | | 2026-11-09 | [20261109-issue178-extract-engine-host-transport-seam_log.md](docs/devlog/20261109-issue178-extract-engine-host-transport-seam_log.md) | | 2026-11-09 | [20261109-issue177-type-transcript-rail-shared-tool-payload-decoder_log.md](docs/devlog/20261109-issue177-type-transcript-rail-shared-tool-payload-decoder_log.md) | @@ -214,5 +216,4 @@ Session logs live in `docs/devlog/` (one per completed task/issue/milestone). Fu | 2026-11-04 | [20261104-issue158-wayfinder-map-cold-turkey-closed_log.md](docs/devlog/20261104-issue158-wayfinder-map-cold-turkey-closed_log.md) | | 2026-11-04 | [20261104-issue166-preset-chips-cold-turkey-arm-bar_log.md](docs/devlog/20261104-issue166-preset-chips-cold-turkey-arm-bar_log.md) | | 2026-11-04 | [20261104-issue165-s5-1-tie-in-cold-turkey-block-first-draft-eligibility_log.md](docs/devlog/20261104-issue165-s5-1-tie-in-cold-turkey-block-first-draft-eligibility_log.md) | -| 2026-11-04 | [20261104-issue163-cold-turkey-calibration-gate-calm_log.md](docs/devlog/20261104-issue163-cold-turkey-calibration-gate-calm_log.md) | diff --git a/Museion/AGENTS.md b/Museion/AGENTS.md index 69f8829..544e7da 100644 --- a/Museion/AGENTS.md +++ b/Museion/AGENTS.md @@ -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///post.md` AND `archive///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-.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 `![alt](assets/…)` builder. +- `PostLibrary.swift` — `Post` + `Post.scan`: two-level scan over `projects///post.md` AND `archive///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-.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 `![alt](assets/…)` 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. diff --git a/Museion/FixCardStore.swift b/Museion/FixCardStore.swift index 4806647..ffd5b8b 100644 --- a/Museion/FixCardStore.swift +++ b/Museion/FixCardStore.swift @@ -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) diff --git a/Museion/LearningDecay.swift b/Museion/LearningDecay.swift index 9ec84d4..bac733f 100644 --- a/Museion/LearningDecay.swift +++ b/Museion/LearningDecay.swift @@ -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() - 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 - } } diff --git a/Museion/LearningsPaneView.swift b/Museion/LearningsPaneView.swift index 5c222f1..598aea9 100644 --- a/Museion/LearningsPaneView.swift +++ b/Museion/LearningsPaneView.swift @@ -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 } diff --git a/Museion/Micropub.swift b/Museion/Micropub.swift index 0eb25a1..6f531e4 100644 --- a/Museion/Micropub.swift +++ b/Museion/Micropub.swift @@ -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.") } diff --git a/Museion/PostFrontmatter.swift b/Museion/PostFrontmatter.swift new file mode 100644 index 0000000..9576aad --- /dev/null +++ b/Museion/PostFrontmatter.swift @@ -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[.. (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() + 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: ` 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)) + } +} diff --git a/Museion/PostLibrary.swift b/Museion/PostLibrary.swift index d805322..13366d0 100644 --- a/Museion/PostLibrary.swift +++ b/Museion/PostLibrary.swift @@ -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[.. String { diff --git a/Museion/PostStore.swift b/Museion/PostStore.swift index d8b3a83..46d64a5 100644 --- a/Museion/PostStore.swift +++ b/Museion/PostStore.swift @@ -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() - 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///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) } } diff --git a/Museion/PostsModelOutline.swift b/Museion/PostsModelOutline.swift index 9e49328..0d90f7f 100644 --- a/Museion/PostsModelOutline.swift +++ b/Museion/PostsModelOutline.swift @@ -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 diff --git a/MuseionTests/AGENTS.md b/MuseionTests/AGENTS.md index fe0a01f..d9c2772 100644 --- a/MuseionTests/AGENTS.md +++ b/MuseionTests/AGENTS.md @@ -33,7 +33,7 @@ Conventions every suite follows. Per-suite pin inventories are NOT kept here — - `ScriptedEngine.swift` — #178: the scripted in-process `EngineTransport` adapter, shared payloads, and the scripted rig roots every engine suite builds on. - `EngineSmokeTests` — #178: the ONLY child-spawning suite — one real-process end-to-end wire smoke per LLM Surface (chat on `museion`: handshake/stream/verdict/crash/restart/teardown; pass1/pass2: own engine under its profile, teardown reap, chat engine untouched). - `ProfileProvisionerTests`, `ProfileSurfaceTests`, `ProfileSkillMigrationTests`, `ProfileProvisionerFailureTests`, `ProfileBackupTests` — provisioning, symlink migration, failure paths, backup (one fake-`hermes` harness). -- `PostLibraryTests`, `PostStoreTests`, `PostStorePassTests` — scan, write side, pass substrate, stats capture, research notes. +- `PostLibraryTests`, `PostStoreTests`, `PostStorePassTests`, `PostFrontmatterTests` — scan, write side, pass substrate, stats capture, research notes, the frontmatter codec (#180: posture round-trips, lenient decode, named eligibility predicates). - `DraftStatsTests`, `TrendViewTests` — text metrics and the trend view's pure facts. - `WritingGoalTests`, `WritingLockTests` — Cold Turkey goal engine + lock machine (kiosk calls no-op under hosted tests by construction — never pinned by driving them). - `MicropubTests`, `MicropubModelTests`, `MicropubMediaTests` — publish wire contract, model flow, media/illustration surface. diff --git a/MuseionTests/EditorSessionTests.swift b/MuseionTests/EditorSessionTests.swift index ce98dbc..73c338c 100644 --- a/MuseionTests/EditorSessionTests.swift +++ b/MuseionTests/EditorSessionTests.swift @@ -23,7 +23,7 @@ private func makeSessionHome() -> URL { private func seedPost(_ home: URL, id: String, body: String) { let dir = home.appendingPathComponent("projects/posts/\(id)", isDirectory: true) try? FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true) - try? PostStore.stamped(body: body, passState: .firstDraft, origin: .writer) + try? PostFrontmatter.stamped(body: body, passState: .firstDraft, origin: .writer) .write(to: dir.appendingPathComponent("post.md"), atomically: true, encoding: .utf8) } diff --git a/MuseionTests/LearningDecayTests.swift b/MuseionTests/LearningDecayTests.swift index 0b9d370..4a4bb44 100644 --- a/MuseionTests/LearningDecayTests.swift +++ b/MuseionTests/LearningDecayTests.swift @@ -74,7 +74,7 @@ struct LearningDecayTests { try LearningDecay.dismiss(home: home, typeDir: "posts", file: file, now: now) let stampedText = try readLearning(home, file) - let frontmatter = Post.frontmatter(of: stampedText) + let frontmatter = PostFrontmatter.parse(stampedText) #expect(frontmatter["dismissed"] == FixCardStore.formatted(now, "yyyy-MM-dd")) #expect(frontmatter["dismiss_count"] == "1") #expect(frontmatter["dismissed_at_pass"] == "1") @@ -85,7 +85,7 @@ struct LearningDecayTests { #expect(frontmatter["promoted"] == "2026-10-21") #expect(frontmatter["from_card"] == "6D9DB4F2-82F9-4C64-9C2B-1A21B4E9B5D0") // The body is byte-identical. - #expect(PostStore.splitFrontmatter(stampedText).body == PostStore.splitFrontmatter(learning).body) + #expect(PostFrontmatter.split(stampedText).body == PostFrontmatter.split(learning).body) // Hidden from the pass rail. #expect(try FixCardStore.learnings(piecePath: piece.path).isEmpty) } @@ -125,7 +125,7 @@ struct LearningDecayTests { #expect(try FixCardStore.learnings(piecePath: piece.path).count == 1) // resurfaced try LearningDecay.dismiss(home: home, typeDir: "posts", file: file) - let frontmatter = try Post.frontmatter(of: readLearning(home, file)) + let frontmatter = try PostFrontmatter.parse(readLearning(home, file)) #expect(frontmatter["dismiss_count"] == "2") #expect(frontmatter["dismissed_at_pass"] == "10") // re-anchored at the current clock @@ -221,7 +221,7 @@ struct LearningDecayTests { #expect(throws: FixCardStore.CardError.self) { try LearningDecay.dismiss(home: hugeHome, typeDir: "posts", file: "20261021-huge.md") } - #expect(try Post.frontmatter(of: readLearning(hugeHome, "20261021-huge.md"))["dismiss_count"] == String(Int.max)) + #expect(try PostFrontmatter.parse(readLearning(hugeHome, "20261021-huge.md"))["dismiss_count"] == String(Int.max)) } /// Scenario: dismiss is a write-path trust boundary — traversal-shaped @@ -251,7 +251,7 @@ struct LearningDecayTests { // Nothing escaped the learnings tree; the real learning is untouched. #expect(!FileManager.default.fileExists(atPath: home.appendingPathComponent("x.md").path)) #expect(!FileManager.default.fileExists(atPath: home.appendingPathComponent("learnings/x.md").path)) - #expect(try Post.frontmatter(of: readLearning(home, file))["dismiss_count"] == nil) + #expect(try PostFrontmatter.parse(readLearning(home, file))["dismiss_count"] == nil) } /// Scenario: a pre-planted symlinked learnings component must not @@ -326,7 +326,7 @@ struct LearningDecayTests { #expect(throws: FixCardStore.CardError.self) { try LearningDecay.dismiss(home: home, typeDir: "posts", file: file) } - #expect(try Post.frontmatter(of: readLearning(home, file))["dismiss_count"] == "1") + #expect(try PostFrontmatter.parse(readLearning(home, file))["dismiss_count"] == "1") // A negative hand-edited count clamps to 0 at parse → stamp writes 1. let negHome = try toolsHome() @@ -338,7 +338,7 @@ struct LearningDecayTests { --- """) try LearningDecay.dismiss(home: negHome, typeDir: "posts", file: file) - #expect(try Post.frontmatter(of: readLearning(negHome, file))["dismiss_count"] == "1") + #expect(try PostFrontmatter.parse(readLearning(negHome, file))["dismiss_count"] == "1") } /// Scenario: decay is defined per pass-clocked content type — a foreign @@ -360,11 +360,11 @@ struct LearningDecayTests { contentsOf: home.appendingPathComponent("learnings/essays/\(file)"), encoding: .utf8, ) - #expect(Post.frontmatter(of: text)["dismiss_count"] == nil) + #expect(PostFrontmatter.parse(text)["dismiss_count"] == nil) } /// Scenario: a Learning with NO frontmatter (a hand-made file) still - /// dismisses — stampingFrontmatter prepends a fresh block and the body + /// dismisses — the update walk prepends a fresh block and the body /// rides verbatim below it (#27 audit: the prepend branch pinned). @Test func `dismiss prepends a fresh block on a frontmatter-less file`() throws { let home = try toolsHome() @@ -375,14 +375,14 @@ struct LearningDecayTests { try LearningDecay.dismiss(home: home, typeDir: "posts", file: file) let stampedText = try readLearning(home, file) - let frontmatter = Post.frontmatter(of: stampedText) + let frontmatter = PostFrontmatter.parse(stampedText) #expect(frontmatter["dismiss_count"] == "1") #expect(frontmatter["dismissed_at_pass"] == "0") - #expect(PostStore.splitFrontmatter(stampedText).body == body) + #expect(PostFrontmatter.split(stampedText).body == body) } /// Scenario: lines ABOVE the opening `---` (a hand-edit blank — - /// Post.frontmatter tolerates one) belong to neither block nor body; + /// PostFrontmatter.parse tolerates any count) belong to neither block nor body; /// the stamp keeps them — the "every other line verbatim" contract /// (#27 review pin). @Test func `dismiss preserves lines above the frontmatter block`() throws { @@ -394,7 +394,7 @@ struct LearningDecayTests { let stampedText = try readLearning(home, file) #expect(stampedText.hasPrefix("\n---\n")) // the leading blank survived - #expect(Post.frontmatter(of: stampedText)["dismiss_count"] == "1") + #expect(PostFrontmatter.parse(stampedText)["dismiss_count"] == "1") #expect(stampedText.hasSuffix("\n\n# Blank\n")) // body untouched } } diff --git a/MuseionTests/PassRunTests.swift b/MuseionTests/PassRunTests.swift index 7e79b85..4011e56 100644 --- a/MuseionTests/PassRunTests.swift +++ b/MuseionTests/PassRunTests.swift @@ -259,7 +259,7 @@ func textRows(of model: MentorSessionModel) -> [String] { contentsOf: home.appendingPathComponent("projects/posts/\(post.id)/post.md"), encoding: .utf8, ) // Capture fired at the invocation — the five keys ride post.md… - let matter = Post.frontmatter(of: onDisk) + let matter = PostFrontmatter.parse(onDisk) #expect(matter["stats_captured"] != nil) #expect(matter["stats_burstiness"] != nil) #expect(matter["stats_type_token_ratio"] != nil) @@ -283,7 +283,7 @@ func textRows(of model: MentorSessionModel) -> [String] { contentsOf: home.appendingPathComponent("projects/posts/\(post.id)/post.md"), encoding: .utf8, ) // Stats fire at INVOCATION, not completion — a cancelled pass has them anyway… - let matter = Post.frontmatter(of: onDisk) + let matter = PostFrontmatter.parse(onDisk) #expect(matter["stats_captured"] != nil) #expect(matter["stats_burstiness"] != nil) // …while the Pass State never advanced. @@ -308,7 +308,7 @@ func textRows(of model: MentorSessionModel) -> [String] { // The pass ran (origin alone decides, never the outcome)… #expect(onDisk.contains("pass_state: Pass-1 Done")) // …but nothing was stamped — ai-origin is never stats-eligible. - let matter = Post.frontmatter(of: onDisk) + let matter = PostFrontmatter.parse(onDisk) #expect(matter["stats_captured"] == nil) #expect(matter["stats_burstiness"] == nil) } @@ -339,7 +339,7 @@ struct DeslopLintWiringTests { #expect(cards.contains { $0.pattern == "utilize" && $0.lane == .mechanical }) // Stats capture fired at the same invocation — both hooks, one seam. let onDisk = try String(contentsOf: piece.appendingPathComponent("post.md"), encoding: .utf8) - let matter = Post.frontmatter(of: onDisk) + let matter = PostFrontmatter.parse(onDisk) #expect(matter["stats_captured"] != nil) #expect(onDisk.contains("pass_state: Pass-1 Done")) } diff --git a/MuseionTests/PostFrontmatterTests.swift b/MuseionTests/PostFrontmatterTests.swift new file mode 100644 index 0000000..e49af0d --- /dev/null +++ b/MuseionTests/PostFrontmatterTests.swift @@ -0,0 +1,117 @@ +// +// PostFrontmatterTests.swift +// MuseionTests +// +// #180: the Post frontmatter codec — one lenient read, three write +// postures (fresh / merge-import / update-keys), one known-key table. +// Pins: the foreign-keys-verbatim round trip through every posture +// (the class of bug that lost captured stats once, un-reintroducible), +// the lenient unknown-type decode, and the two named eligibility +// predicates the capture gate and the scan read-back gate share. +// + +import Foundation +@testable import Museion +import Testing + +// Scenario: One frontmatter codec behind every post read and write — +// from #180. Given a library whose post.md blocks were written by the +// old per-site writers, when any posture (import, save, advance, +// capture, publish-stamp) runs over a piece carrying foreign frontmatter +// keys, then the one PostFrontmatter engine keeps those keys verbatim, +// inserts owned keys in the one known order, reads unknown types +// leniently as post, and both eligibility gates agree on the same named +// predicates. +struct PostFrontmatterTests { + /// A block with foreign keys above and below our owned keys — every + /// posture must keep `foreign_key: keep-me` byte-identical. + private let withForeign = "---\nforeign_key: keep-me\ntype: post\npass_state: First Draft\norigin: writer\n---\n# Body" + + @Test func `fresh stamp is the 59 shape in known-key order`() { + #expect(PostFrontmatter.stamped(body: "# T", passState: .firstDraft, origin: .writer) + == "---\ntype: post\npass_state: First Draft\norigin: writer\n---\n# T") + #expect(PostFrontmatter.stamped(body: "- Root", passState: .pass2Done, origin: .ai, type: .outline) + == "---\ntype: outline\npass_state: Pass-2 Done\norigin: ai\n---\n- Root") + } + + @Test func `merge-import keeps foreign keys verbatim and ours win in place`() { + // External block with foreign keys around ours; `origin` present + // (overwritten in place), `type`/`pass_state` absent (inserted + // before the closing --- in table order). + let external = "---\ntitle: Outside\norigin: ai\ndate: 2026-10-11\n---\n# Body" + #expect(PostFrontmatter.mergingImport(text: external, origin: .writer) + == "---\ntitle: Outside\norigin: writer\ndate: 2026-10-11\ntype: post\npass_state: First Draft\n---\n# Body") + // #95: an external `type: outline` still imports as post. + #expect(PostFrontmatter.mergingImport(text: "---\ntype: outline\n---\nB", origin: .writer) + == "---\ntype: post\npass_state: First Draft\norigin: writer\n---\nB") + // Bare file → the fresh block, body verbatim below. + #expect(PostFrontmatter.mergingImport(text: "# Bare", origin: .ai) + == "---\ntype: post\npass_state: First Draft\norigin: ai\n---\n# Bare") + // #180: a hand-edit blank above the `---` survives import (the old + // writer dropped it — lossless through every posture is the contract). + #expect(PostFrontmatter.mergingImport(text: "\n---\ntitle: Outside\n---\n# B", origin: .writer) + == "\n---\ntitle: Outside\ntype: post\npass_state: First Draft\norigin: writer\n---\n# B") + } + + @Test func `update-keys stamps in place and keeps every other line byte-identical`() { + // An existing key overwrites in place; foreign keys and the body + // never move. + #expect(PostFrontmatter.updating(text: withForeign, with: [("pass_state", "Pass-1 Done")]) + == "---\nforeign_key: keep-me\ntype: post\npass_state: Pass-1 Done\norigin: writer\n---\n# Body") + // An absent key inserts before the closing --- (pair order). + #expect(PostFrontmatter.updating(text: withForeign, with: [("micropub_url", "https://micro.blog/x")]) + == "---\nforeign_key: keep-me\ntype: post\npass_state: First Draft\norigin: writer\nmicropub_url: https://micro.blog/x\n---\n# Body") + // Bare text → a fresh block prepends, body rides verbatim. + #expect(PostFrontmatter.updating(text: "# Bare", with: [("pass_state", "Pass-1 Done")]) + == "---\npass_state: Pass-1 Done\n---\n# Bare") + } + + @Test func `update-keys preserves hand-edit lines above the block`() { + // The #27 review contract, codec-level: lines above the opening + // --- belong to neither block nor body; the stamp keeps them. The + // inserted key lands before the closing --- (after existing keys). + #expect(PostFrontmatter.updating(text: "\n---\ntype: post\n---\n# B", with: [("dismiss_count", "1")]) + .hasPrefix("\n---\ntype: post\ndismiss_count: 1\n---\n")) + } + + @Test func `foreign keys ride verbatim through every posture chained`() { + // The #180 round-trip pin: import → editor save (owned keys) → + // pass advance → micropub stamp, foreign keys intact at every hop. + var text = PostFrontmatter.mergingImport(text: "---\nforeign: keep\norigin: ai\n---\n# Chain", origin: .writer) + for pairs in [ + [("type", "post"), ("pass_state", "First Draft"), ("origin", "writer")], + [("pass_state", "Pass-1 Done")], + [("micropub_url", "https://micro.blog/x")], + ] { + text = PostFrontmatter.updating(text: text, with: pairs) + #expect(text.contains("\nforeign: keep\n")) // the line never moved + } + #expect(PostFrontmatter.parse(text)["foreign"] == "keep") + #expect(text.hasSuffix("---\n# Chain")) // body untouched throughout + } + + @Test func `unknown type reads leniently as post`() { + #expect(PostFrontmatter.decoded(PostFrontmatter.parse("---\ntype: alien\norigin: writer\npass_state: First Draft\n---\nB")).type == .post) + // The lenient defaults: a bare legacy corpus post is a normal piece. + #expect(PostFrontmatter.decoded([:]) + == PostFrontmatter.Stamp(type: .post, passState: .firstDraft, origin: .writer)) + } + + @Test func `eligibility predicates name the pair and the capture gate`() { + func matter(type: String? = nil, passState: String? = nil, origin: String? = nil) -> [String: String] { + ["type": type, "pass_state": passState, "origin": origin].compactMapValues { $0 } + } + // The immutable pair: writer ∧ post, independent of pass_state — + // a writer piece that legitimately advanced still carries its arc. + #expect(PostFrontmatter.isUnaidedFirstDraftPair(matter(type: "post", passState: "Pass-1 Done", origin: "writer"))) + #expect(!PostFrontmatter.isCaptureEligible(matter(type: "post", passState: "Pass-1 Done", origin: "writer"))) + // Capture: the pair ∧ First Draft. + #expect(PostFrontmatter.isCaptureEligible(matter(type: "post", passState: "First Draft", origin: "writer"))) + #expect(PostFrontmatter.isCaptureEligible([:])) // bare legacy post qualifies + // Neither gate opens for ai or outline pieces. + #expect(!PostFrontmatter.isUnaidedFirstDraftPair(matter(type: "post", origin: "ai"))) + #expect(!PostFrontmatter.isCaptureEligible(matter(type: "post", origin: "ai"))) + #expect(!PostFrontmatter.isUnaidedFirstDraftPair(matter(type: "outline", origin: "writer"))) + #expect(!PostFrontmatter.isCaptureEligible(matter(type: "outline", origin: "writer"))) + } +} diff --git a/MuseionTests/PostLibraryTests.swift b/MuseionTests/PostLibraryTests.swift index e49cd43..39715b0 100644 --- a/MuseionTests/PostLibraryTests.swift +++ b/MuseionTests/PostLibraryTests.swift @@ -182,7 +182,7 @@ private func writePost(_ home: URL, _ id: String, _ body: String) throws { @Test func `unterminated frontmatter is untitled, never leaked`() { // No closing ---: frontmatter lines must never leak as the Title. #expect(Post.title(of: "---\npass_state: First Draft\norigin: writer\n") == "untitled") - #expect(Post.frontmatter(of: "---\npass_state: First Draft\n")["pass_state"] == "First Draft") + #expect(PostFrontmatter.parse("---\npass_state: First Draft\n")["pass_state"] == "First Draft") } @Test func `leading blank line still opens frontmatter`() throws { diff --git a/MuseionTests/PostStorePassTests.swift b/MuseionTests/PostStorePassTests.swift index 668e8d4..c12bb28 100644 --- a/MuseionTests/PostStorePassTests.swift +++ b/MuseionTests/PostStorePassTests.swift @@ -309,7 +309,7 @@ private func threeDecimals(_ value: String) -> Bool { let withForeign = try String(contentsOf: url, encoding: .utf8) .replacingOccurrences(of: "---\ntype: post", with: "---\nforeign_key: keep-me\ntype: post") try withForeign.write(to: url, atomically: true, encoding: .utf8) - let bodyBefore = PostStore.splitFrontmatter(withForeign).body + let bodyBefore = PostFrontmatter.split(withForeign).body let captured = PostStore.captureFirstDraftStats( id: post.id, body: "# Draft\n\nOne two three. Four five! Six?", home: home, @@ -317,7 +317,7 @@ private func threeDecimals(_ value: String) -> Bool { #expect(captured) let after = try String(contentsOf: url, encoding: .utf8) - let matter = Post.frontmatter(of: after) // the trend-view readiness read + let matter = PostFrontmatter.parse(after) // the trend-view readiness read #expect(matter["foreign_key"] == "keep-me") #expect(matter["stats_captured"]?.count == 19) // yyyy-MM-dd'T'HH:mm:ss, lexically sortable #expect(matter["stats_burstiness"].map(threeDecimals) == true) @@ -328,7 +328,7 @@ private func threeDecimals(_ value: String) -> Bool { #expect(matter["pass_state"] == "First Draft") #expect(matter["origin"] == "writer") // Body byte-identical — the stamp never touches content (#31 in-place proof). - #expect(PostStore.splitFrontmatter(after).body == bodyBefore) + #expect(PostFrontmatter.split(after).body == bodyBefore) } @Test func `capture refuses an ai origin piece untouched`() throws { @@ -369,7 +369,7 @@ private func threeDecimals(_ value: String) -> Bool { #expect(PostStore.captureFirstDraftStats(id: post.id, body: "One two three. Four five! Six?", home: home)) #expect(PostStore.captureFirstDraftStats(id: post.id, body: "a b c. a b c.", home: home)) - let matter = try Post.frontmatter(of: String( + let matter = try PostFrontmatter.parse(String( contentsOf: home.appendingPathComponent("projects/posts/\(post.id)/post.md"), encoding: .utf8, )) #expect(matter["stats_burstiness"] == "-1.000") // σ = 0 over [3, 3] — the second body won @@ -394,7 +394,7 @@ private func threeDecimals(_ value: String) -> Bool { let after = try String( contentsOf: home.appendingPathComponent("projects/posts/bare-legacy/post.md"), encoding: .utf8, ) - let matter = Post.frontmatter(of: after) + let matter = PostFrontmatter.parse(after) #expect(matter["stats_captured"] != nil) #expect(after.contains("# Bare")) // the body survived the fresh-block prepend } @@ -416,14 +416,14 @@ private func threeDecimals(_ value: String) -> Bool { #expect(advanced == .pass1Done) let after = try String(contentsOf: url, encoding: .utf8) - let matter = Post.frontmatter(of: after) + let matter = PostFrontmatter.parse(after) #expect(matter["pass_state"] == "Pass-1 Done") #expect(matter["stats_captured"] != nil) // survived the advance #expect(matter["stats_trigram_repetition"] != nil) #expect(matter["foreign_key"] == "keep-me") // foreign keys too — the latent #24 loss #expect(matter["origin"] == "writer") #expect(matter["type"] == "post") - #expect(PostStore.splitFrontmatter(after).body == "# Kept\n\nBody stays.") + #expect(PostFrontmatter.split(after).body == "# Kept\n\nBody stays.") } @Test func `overwrite preserves stats and foreign keys while swapping the body`() throws { @@ -442,13 +442,13 @@ private func threeDecimals(_ value: String) -> Bool { try PostStore.overwrite(id: post.id, body: "# Draft\n\nEdited mid-pass words.", home: home) let after = try String(contentsOf: url, encoding: .utf8) - let matter = Post.frontmatter(of: after) + let matter = PostFrontmatter.parse(after) #expect(matter["stats_captured"] != nil) // survived the editor save #expect(matter["foreign_key"] == "keep-me") #expect(matter["pass_state"] == "First Draft") #expect(matter["origin"] == "writer") #expect(matter["type"] == "post") - #expect(PostStore.splitFrontmatter(after).body == "# Draft\n\nEdited mid-pass words.") // the save still landed + #expect(PostFrontmatter.split(after).body == "# Draft\n\nEdited mid-pass words.") // the save still landed } @Test func `overwrite normalizes a bare post with the full stamp`() throws { @@ -465,9 +465,9 @@ private func threeDecimals(_ value: String) -> Bool { let after = try String( contentsOf: home.appendingPathComponent("projects/posts/bare-overwrite/post.md"), encoding: .utf8, ) - let matter = Post.frontmatter(of: after) + let matter = PostFrontmatter.parse(after) #expect(matter["type"] == "post") #expect(matter["pass_state"] == "First Draft") #expect(matter["origin"] == "writer") - #expect(PostStore.splitFrontmatter(after).body == "Bare body, edited.") + #expect(PostFrontmatter.split(after).body == "Bare body, edited.") } diff --git a/MuseionTests/PostStoreTests.swift b/MuseionTests/PostStoreTests.swift index 7d86294..1b0f844 100644 --- a/MuseionTests/PostStoreTests.swift +++ b/MuseionTests/PostStoreTests.swift @@ -575,7 +575,7 @@ func readPiece(_ home: URL, root: String, project: String, _ id: String) throws #expect(verbatim.hasPrefix("---\ntype: post\n")) #expect(verbatim.contains("pass_state: First Draft")) #expect(verbatim.contains("origin: writer")) - #expect(PostStore.splitFrontmatter(verbatim).body == "# Chapter\n- one\n - nested") + #expect(PostFrontmatter.split(verbatim).body == "# Chapter\n- one\n - nested") // folder never moved; scan reads the new type on rescan #expect(Post.scan(home: home).first?.id == post.id) #expect(Post.scan(home: home).first?.type == .post) @@ -584,7 +584,7 @@ func readPiece(_ home: URL, root: String, project: String, _ id: String) throws try PostStore.convert(id: post.id, headingsLadder: true, home: home) let ladder = try readPost(home, post.id) #expect(ladder.hasPrefix("---\ntype: post\n")) - #expect(PostStore.splitFrontmatter(ladder).body == "# Chapter\n## one\n### nested") + #expect(PostFrontmatter.split(ladder).body == "# Chapter\n## one\n### nested") // a vanished piece throws, never resurrects #expect(throws: CocoaError(.fileReadNoSuchFile)) { diff --git a/MuseionTests/PostsModelTests.swift b/MuseionTests/PostsModelTests.swift index 5a7b9ce..3675ba4 100644 --- a/MuseionTests/PostsModelTests.swift +++ b/MuseionTests/PostsModelTests.swift @@ -404,8 +404,10 @@ private func writeMixedOutline(home: URL) throws -> Post { model.stageConversion(post) // staged clean, no warning shown // a foreign write makes the body mixed while the sheet was up let file = home.appendingPathComponent("projects/posts/\(post.id)/post.md", isDirectory: false) - try PostStore.stamped(body: "# Clean\n- one\nA paragraph between bullets.\n- two", passState: .firstDraft, origin: .writer, type: .outline) - .write(to: file, atomically: true, encoding: .utf8) + try PostFrontmatter.stamped( + body: "# Clean\n- one\nA paragraph between bullets.\n- two", passState: .firstDraft, origin: .writer, type: .outline, + ) + .write(to: file, atomically: true, encoding: .utf8) model.convertToPost(headingsLadder: true) diff --git a/MuseionTests/TrendViewTests.swift b/MuseionTests/TrendViewTests.swift index 208ec72..933bd87 100644 --- a/MuseionTests/TrendViewTests.swift +++ b/MuseionTests/TrendViewTests.swift @@ -78,8 +78,8 @@ struct TrendViewTests { #expect(abs(captured.stats.trigramRepetition - expected.trigramRepetition) < 0.0005) // The parsed date round-trips through the exact stamp format — the // symmetric-read proof, locale-independent by construction. - let onDisk = try Post.frontmatter( - of: String( + let onDisk = try PostFrontmatter.parse( + String( contentsOf: home.appendingPathComponent("projects/posts/\(post.id)/post.md"), encoding: .utf8, ), diff --git a/docs/devlog/20261110-issue180-postfrontmatter-codec-one-readwrite-engine_log.md b/docs/devlog/20261110-issue180-postfrontmatter-codec-one-readwrite-engine_log.md new file mode 100644 index 0000000..cbca6cb --- /dev/null +++ b/docs/devlog/20261110-issue180-postfrontmatter-codec-one-readwrite-engine_log.md @@ -0,0 +1,69 @@ +# #180 PostFrontmatter codec — one read/write engine, named eligibility predicates + +> **Date:** 2026-11-10 +> **Type:** issue +> **Reference:** https://git.babylondreams.de/AlexKucera/museion/issues/180 + +## Goal + +Consolidate the three near-twin post frontmatter writers (fresh stamp, import merge, in-place key update) into ONE codec module behind one known-key table and one insertion-order rule; name the Unaided First Draft eligibility pair once and consume it from both gates; keep every existing piece byte-identical on disk. Step 2 of 2 of the 2026-11-09 architecture review's content line. + +## What Was Done + +- New `Museion/PostFrontmatter.swift` — the codec: the lenient read (`parse` moved from `Post.frontmatter(of:)`, `split` from `PostStore.splitFrontmatter`, plus `decoded` — the ONE lenient `?? default` stamp decode, extracting the third copy the #31 ponytail note deferred) and the three named write postures: `stamped` (fresh), `mergingImport` (external keys verbatim, ours win), `updating` (the in-place line-walk moved verbatim from `LearningDecay.stampingFrontmatter`). One known-key table: `ownedKeys(type:passState:origin:)`. +- Two named eligibility predicates, consumed by both gates: `isUnaidedFirstDraftPair` (writer ∧ post — `Post.scan`'s read-back gate in `PostLibrary.parse`) and `isCaptureEligible` (pair ∧ First Draft — `PostStore.captureFirstDraftStats`). +- Deleted the twins: `PostStore.stamped`, `PostStore.splitFrontmatter`, `PostStore.mergedFrontmatter`, `LearningDecay.stampingFrontmatter`, `Post.frontmatter(of:)` — 21 call sites swept across 7 production files (PostStore, PostLibrary, LearningDecay, FixCardStore ×2, LearningsPaneView, PostsModelOutline, Micropub) and 8 test files. +- New `MuseionTests/PostFrontmatterTests.swift` — 7 pins: fresh-stamp byte shape, merge-import (foreign keys verbatim, ours win in place, bare file, #180 prefix-preservation divergence), update-keys (in-place overwrite, insert-before-close, bare prepend, hand-edit lines above the block), the chained posture round-trip (import → save → advance → micropub, foreign key verbatim at every hop), lenient unknown-type decode, and the two predicates' truth table (pair true at Pass-1 Done, capture false — the AC's exact distinction). +- DOX pass: root AGENTS.md trust-boundaries learning re-pointed to the new symbols; `Museion/AGENTS.md` map entry + PostStore/PostLibrary bullets; `MuseionTests/AGENTS.md` suite map. +- Reviews: implement-close Standards+Spec fanout (2 findings, both fixed), finish-audit fanout (ponytail/security/general — 0 critical, 1 shrink applied, 2 comment fixes applied, 1 security INFO deferred with a ceiling comment). + +Net **−133 lines**, 18 files modified + 2 new. + +## Decisions & Rationale + +| Decision | Rationale | +|----------|-----------| +| `mergingImport` = one line over `updating` with `ownedKeys` | The import twin's line-walk was byte-for-byte the same walk; unifying killed the twin. Only reachable delta: hand-edit lines above `---` now SURVIVE import where the old split-first shape dropped them — deliberate, lossless-direction divergence, doc-commented on `mergingImport` and pinned in the suite (both reviewers converged on flagging it unpinned; the pin + comment landed). | +| `overwrite`'s blocked path keeps the `split(updating(...)).block + body` dance | Preserves the exact old composition (update walk → re-split → take block → swap body), so save output stays byte-identical including the prefix-drop the re-split incidentally performs. No fourth posture invented for one caller. | +| `decoded` returns a `Stamp` struct, not a 3-tuple | swiftlint `large_tuple` (default rules) warns on >2-element tuples; the struct reads better at call sites and carries `Equatable` for the bare-defaults pin. | +| `isCaptureEligible` re-derives the pair instead of calling `isUnaidedFirstDraftPair` | One decode instead of two; identical semantics (lenient triple + three equals). | +| Learnings dismiss rides `PostFrontmatter.updating` | Ticket keeps Learning/Fix Card DOCUMENTS out of scope, but deleting `stampingFrontmatter` (an AC) forces its one learning caller onto the codec's generic walk — mechanical reuse, document shape unchanged. | +| `Post.title(of:)` NOT unified with `split` | Title's unterminated-block branch returns `untitled`; split's returns the whole text as body. Different contracts; unifying would change bytes. Out of scope. | + +## Gotchas & Fixes + +| Problem | Root Cause | Fix | +|---------|------------|-----| +| My first prefix pin expected the inserted key ABOVE existing keys | The walk inserts before the CLOSING `---` (after existing keys) — the code was right, the pin was wrong | Corrected the expectation to the real shape; test green | +| `home repoint mid-pass refuses the advance` failed in both full-suite runs | Pre-existing #179 timing flake: the held prompt times out under full-suite machine load before `endHeldPrompt` — the test's own comment predicts it | PROVEN pre-existing: full suite on stashed clean main failed the same test; the suite in isolation (5/5) and the final verify run (664/664) pass. Not this diff's seam. | +| One new line_length violation after the rename sweep | `PostStore.stamped(` → `PostFrontmatter.stamped(` grew PostsModelTests:407 to 146 chars | Wrapped the call; swiftlint back to exactly the clean-main count (279) | +| Mixed `//` + `///` comment block on `mergingImport` | The #143 orphaned-doc-comment trap | Folded into one `///` block with a blank `///` separator | +| Terminal cwd drifted into a reviewer child's scratch probe dir | Child probe dirs share the session shell | Re-ran with explicit workdir; no repo files touched | + +## Files Changed + +| File | Change Summary | +|------|---------------| +| `Museion/PostFrontmatter.swift` | NEW — the codec: parse/split/decoded, three postures, ownedKeys, two predicates | +| `MuseionTests/PostFrontmatterTests.swift` | NEW — 7 pins incl. the posture round-trip and prefix divergence | +| `Museion/PostStore.swift` | Swept to the codec; mergedFrontmatter/stamped/splitFrontmatter deleted; capture gate → isCaptureEligible | +| `Museion/PostLibrary.swift` | parse → codec read; read-back gate → isUnaidedFirstDraftPair; Post.frontmatter deleted | +| `Museion/LearningDecay.swift` | dismiss → codec updating; stampingFrontmatter deleted | +| `Museion/FixCardStore.swift` ×2 sites, `Museion/LearningsPaneView.swift`, `Museion/PostsModelOutline.swift`, `Museion/Micropub.swift` | Mechanical read-site sweep | +| `MuseionTests/` (8 files) | Mechanical rename sweep + comment fixes | +| `AGENTS.md`, `Museion/AGENTS.md`, `MuseionTests/AGENTS.md` | DOX pass | + +## Open Items & Next Steps + +- [ ] Flat-key ceiling: an indented `key: value` inside a nested YAML block scalar is rewritten unindented by the walk (inherited verbatim from the deleted writers; security-review INFO-1, local-only, user's own import). Recorded as a `ponytail:` comment at the walk; indentation-aware walk only if nested frontmatter ever matters. +- [ ] The `home repoint mid-pass` flake remains open from #179 (fails under full-suite load ~2/3 runs this session, green in isolation and in the final run) — its timing assumptions, not this ticket. + +## Verification + +- `build-for-testing` exit 0; `test-without-building` exit 0 — **664 executed / 664 passed / 0 failed** (xcresult count, not the banner). +- swiftformat clean; swiftlint 279 violations = exact clean-main parity. +- GitNexus detect-changes (index-relative): affected flows all route through `overwrite`/`learnings` — the diff's own seams. + +--- + +*Log written by write-log skill* diff --git a/docs/devlog/INDEX.md b/docs/devlog/INDEX.md index ad5c1a0..970ccc0 100644 --- a/docs/devlog/INDEX.md +++ b/docs/devlog/INDEX.md @@ -5,6 +5,7 @@ Complete history of session logs in this directory, newest first. One-line summa | Date | Type | File | Summary | |------|------|------|---------| +| 2026-11-10 | issue | [20261110-issue180-postfrontmatter-codec-one-readwrite-engine_log.md](20261110-issue180-postfrontmatter-codec-one-readwrite-engine_log.md) | One PostFrontmatter codec: lenient read + three byte-identical write postures, named eligibility predicates both gates consume | | 2026-11-09 | issue | [20261109-issue179-postsmodel-write-rail_log.md](20261109-issue179-postsmodel-write-rail_log.md) | One `performWrite` rail pairs every library write with one rescan and owns the strip; model owns the Home (#179) | | 2026-11-09 | issue | [20261109-issue178-extract-engine-host-transport-seam_log.md](20261109-issue178-extract-engine-host-transport-seam_log.md) | Engine lifecycle → EngineHost behind the EngineTransport seam; scripted in-process tests, one real smoke per surface | | 2026-11-09 | issue | [20261109-issue177-type-transcript-rail-shared-tool-payload-decoder_log.md](20261109-issue177-type-transcript-rail-shared-tool-payload-decoder_log.md) | SessionRow text rows typed (speaker+notice), kick-off sniffed at append seam, one ToolPayloads decoder both rails read |