diff --git a/AGENTS.md b/AGENTS.md index 319b4e9..75ac59d 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** (5420 symbols, 21204 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** (5542 symbols, 22245 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). @@ -178,10 +178,13 @@ This project is indexed by GitNexus as **museion** (5420 symbols, 21204 relation ### Testing - Real-Process fake-ACP tests flake under concurrent build/analyze load — verify a failure in isolation and run the definitive full suite on an idle machine (#30) - Verify xcodebuild runs by the xcresult executed count, never the SUCCEEDED banner — single-name `-only-testing` filters can match zero free-function Swift Testing tests and "pass" vacuously (#31); suite-member names with spaces/backticks ALSO fail to match — run the whole suite and count (#134) +- Read the xcresult bundle only AFTER xcodebuild exits — `ls -td | head -1` inside the test command races bundle finalization and reports a phantom missing path while the run itself is green (#33) +- Keychain-touching tests run in their OWN account slot (inject the account param) — a locked login keychain makes read() return nil, so a save/restore defer around the PRODUCTION slot deletes a real live credential (#33) - When the hosted-test runner fails the IDE-session handshake on EVERY run ("Timed out while preparing IDE session" / "Lost connection to testmanagerd"), stop resetting — `killall testmanagerd` and orphan cleanup don't clear it; the machine needs a reboot. Meanwhile `build-for-testing` + a standalone `swift ` check of the pure logic still verify honestly (#134) ### 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) +- 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) ## Session Logs @@ -190,6 +193,7 @@ Session logs live in `docs/devlog/` (one per completed task/issue/milestone). Fu | Date | Log | |------|-----| +| 2026-10-31 | [20261031-issue33-m6-micropub-draft-publish-s6-1_log.md](20261031-issue33-m6-micropub-draft-publish-s6-1_log.md) | | 2026-10-31 | [20261031-issue32-m4-trend-view-s5-2_log.md](20261031-issue32-m4-trend-view-s5-2_log.md) | | 2026-10-30 | [20261030-issue122-blind-read-writer-triggered-whole-document-ab-judgment_log.md](20261030-issue122-blind-read-writer-triggered-whole-document-ab-judgment_log.md) | | 2026-10-30 | [20261030-issue6-native-deslop-lint-swift-banned-vocab-em-dash-fix-cards_log.md](20261030-issue6-native-deslop-lint-swift-banned-vocab-em-dash-fix-cards_log.md) | @@ -199,5 +203,4 @@ Session logs live in `docs/devlog/` (one per completed task/issue/milestone). Fu | 2026-10-27 | [20261027-issue135-profiles-s2-settings-page-ui_log.md](20261027-issue135-profiles-s2-settings-page-ui_log.md) | | 2026-10-27 | [20261027-issue134-profiles-s1-registry-provisioning-x3_log.md](20261027-issue134-profiles-s1-registry-provisioning-x3_log.md) | | 2026-10-22 | [20261022-issue31-first-draft-stats-capture-s5-1_log.md](20261022-issue31-first-draft-stats-capture-s5-1_log.md) | -| 2026-10-22 | [20261022-issue30-sessions-new-post-from-session-drill-offers_log.md](20261022-issue30-sessions-new-post-from-session-drill-offers_log.md) | diff --git a/CHANGELOG.md b/CHANGELOG.md index 985ee63..afe50ae 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,7 @@ All notable changes to this project will be documented in this file. The format ### Added +- **publish:** Micropub draft → publish to Micro.blog (PRD S6.1, G2/G11) — a Publish button in the editor toolbar opens the two-step ask: Send as Draft (JSON Micropub `h=entry` create — name = the piece's Title, markdown content verbatim, `post-status: draft`; the piece's frontmatter `category:` is accepted but never travels), review via the Micro.blog preview link, then Publish (the `action=update` post-status flip against the piece's remembered `micropub_url` — persisted in frontmatter so a draft survives a reopen; Send Again re-drafts after edits). The Micro.blog app token lives in the Keychain (login keychain, entered once in the sheet, re-offered only on an auth failure — rotation replaces). Every draft URL passes a format gate at both the decode and the scan read-back: the URL is trust-boundary data landing in frontmatter, and a newline-`---` rider would close the block and reparse as attacker markdown in the writer's piece; the preview URL is display-only, never the publish target. Frontmatter-only stamps keep the body and foreign keys byte-identical (issue #33) - **stats:** Trend view — the writer's arc (PRD S5.2) — a Trends pane (rail destination after Learnings, measurement beside memory): one line chart per style metric (burstiness, type-token ratio, sentence variation, trigram repetition) across unaided-first-draft CAPTURES over time, each card carrying an honest first→last read (`improving`/`steady`/`slipping` at ±0.01, direction inverted for trigram repetition — the one ↓-better metric; one capture shows its value with no verdict) plus the per-metric ↑/↓-better hint and a one-line plain-language gloss of the term beneath each chart (grain + better-direction, pinned distinct). Points are capture moments, never draft grades — the pane answers "am I getting better," not "is this draft good." The edited-text leak is closed by construction: `Post.scan` reads the five `stats_*` frontmatter keys into `firstDraftStats` only when every key parses to a finite double AND the piece carries the capture gate's immutable pair (origin writer, type post) — so ai-origin pieces, outlines, edited-before-first-pass drafts, and imported or hand-edited frontmatter (non-finite values, stamped ai pieces) carry nothing to show, while a migrated writer piece keeps its real arc. The pane rides PostsModel's watched scan (no scan of its own, refreshes with the library); fixed y-domains keep single captures visible (sentence variation scales to its peak); the empty state names how the data arrives (issue #32) - **mentor:** Blind Read — writer-triggered advisory A/B judgment (#122, decision #120) — a purposeful "Blind Read" button beside Run Pass in the pass bar judges the current document against the Pass-start snapshot (the newest `passes/pass-N.md` on disk): both versions travel INLINE in one prompt under neutral A/B position labels with randomized order (origin words never appear — the judge can't know which is the rewrite), a fresh one-shot engine on the same `museion` chat profile renders its pick + one-line reason into the transient transcript, and the A/B↔origin reveal lands only AFTER the verdict so it can never leak; cancelled, refused, and spawn-failed turns reveal nothing. Advisory-only per #120: nothing advances, no cards, no Learnings, the roster never grows — the verdict dies with the transcript and the writer stays judge of record. Honest refusals: no snapshot yet ("run a Pass first"), an unchanged document ("No edits since…"), or a busy rail (passes and reads refuse each other; one Cancel ends either). The pass engine's spawn/session/teardown block became one shared `runOneShot` rail (failure rows speak the run's own name), the fake ACP gained a prompt-log observable, and the GLOSSARY "Blind Read" term landed. Finish-audit (3 reviewers) fixed the refusal-reveal gate (a refusal still ends `.ended` — gate on the stopReason; flip-verified), the hardcoded "Pass failed" copy, and pinned the Cancel/exclusivity rail. Suite 500 (issue #122) diff --git a/Museion/AGENTS.md b/Museion/AGENTS.md index 5bf585c..82b020b 100644 --- a/Museion/AGENTS.md +++ b/Museion/AGENTS.md @@ -22,15 +22,16 @@ Owned by the root AGENTS.md contract. The `.xcodeproj` uses **filesystem-synchro - `DesignTokens.swift` — palette/geometry from the design contract (`ref/Web-Prototype/museion-workspace.html` `:root` + grid): background/surface/foreground/muted/border/accent colors, radius 10, column widths (rail 56, library 232, mentor 356; the export's editor min 420 lands with #19's editor column), serif/mono font designs. **#89 (2026-10-09):** two-color world, calibrated live — `background` #FAF9F3 (chrome + focus ground), `surface` #FFFEFB (one page color for edit AND read); deliberate departure from the export palette, values live-calibrated not contract-fixed. Light-only — one palette. - `WorkspaceView.swift` — post-gate main surface (replaces the M0 mentor pane as root): nav rail (Posts/Sessions/Learnings/Trends + Settings at bottom) + active pane. `RailButton` per the export (44×44, muted icon, hover wash, surface card + 2px edge bar when current). **#32 (S5.2):** the rail's fourth destination — Trends (`chart.xyaxis.line`, after Learnings — measurement beside memory) → `TrendsPaneView` (own file). **#28 (S2.3):** Sessions is real — `SessionsPaneView` (own file) over the engine-owned session model: `PaneHeader("Sessions")` carries the New Session control (**#30: always a Menu** — "New Session" / "New Session on \" when Posts has an open piece / "New Brainstorm" → `beginBrainstormSession`; the plain-button branch died with the second action; association stays by name/convention, `pieceTitle` on the roster entry; disabled on `!canStartSession`), two-column body — roster list at `libraryWidth` (rows in `LibraryPostRow`'s exact 2px-strip language: serif-13 name + mono-11 meta `pieceTitle · yyyy-MM-dd HH:mm`; row click = `resumeSession`, the engine replays the transcript, an engine-unknown id lands the model's honest refusal row and the entry stays) | transcript via the shared `SessionTranscriptView` (home passed through — #29 research candidates curate in either pane; **#30: the shared surface carries the freeform composer + liveness + Stop too — the pane is a conversation, not a read-only transcript**; the pane-local liveness row died with the move). Detail column: idle/starting → "Starting the mentor engine…" progress; crashed → a plain "Restart it in the Mentor pane" pointer (never a second restart flow); ready → actions row (active session name serif + engine version mono, **#30: New Post · Fork · Compact** bordered mono-11 — Fork · Compact disabled on `!canStartSession`, New Post never engine-gated (it reads in-memory transcript rows; a crashed engine must not strand the draft); New Post stages the pane-local ask — `sessionDraft` @State seeded from `draftCandidateText()`, the private `NewPostFromSessionSheet` prefills the editable candidate (origin: ai stated in-UI, Create disabled on blank), Create → `PostsModel.newPostFromSession`, dismissal is the cancel; a FAILED write keeps the sheet up with the reason inline (ApplyAskSheet posture — the edited draft is never destroyed); empty transcript = empty prefill, the sheet still works) + transcript. The pane's `.task` runs the same idempotent `openSession()` (XCTest-guarded) and seeds `model.binaryPath` from the gate when nil, so the pane can be the first to spawn the engine. Empty state names how sessions arrive (a pass, or New Session). The transcript renderer + freeform input rail live in `SessionTranscriptView` (own file) — MentorPaneView's transcript views moved there verbatim (#24's `defaultScrollAnchor(.bottom)` preserved); `isWritingRow` moved with it and MentorPaneView delegates; **#30: the composer (input 1…4 lines + send + liveness + Stop) moved there too — one conversation surface, two panes** (the Mentor pane keeps the crash card + debug toggle). **#26:** Learnings is real — `LearningsPaneView` (own file), a list-only pane (Archive posture) over `/learnings/`: `LearningsIndex` (nonisolated) scans type dirs → groups (dir name lowercased, library section-head voice) → entries newest-first (`YYYYMMDD-` filename prefix desc, undated last), pattern/problem/promoted read leniently via `Post.frontmatter` (missing pattern → filename minus date+ext), scan detached off MainActor from `.task(id: home)` with a `Task.isCancelled` gate on the hop back (a slow old Home's scan must not overwrite the new one's), no watcher (ponytail: re-scans on pane re-entry); audit: file reads are unbounded and follow file symlinks — same ceiling as Post.scan, ponytail-noted. **#27 (S4.2):** `Entry` gains `resurfacesIn` (nil = visible, positive = passes until resurface; `currentPass` init param — nil/absent = an unclocked foreign dir, never a verdict: its clock can't advance, a countdown would lie, mirroring the store's dismiss refusal; #27 review) and `scan` reads `LearningDecay.passCounts(home:)` once, feeding each CLOCKED group its dir's clock (foreign dirs nil); rows DISMISS — visible entries in clocked dirs carry a mono-11 Dismiss button (Unarchive voice, no confirm sheet — dismissal is low-stakes and self-healing; foreign unclocked dirs offer none), dismissed rows dim to 0.45 (closed-card voice) with "dismissed · resurfaces in N passes" leading the meta; the scan is refactored into a private `rescan(_:)` reused after a dismiss (detached task; errors land in a mono-11 orange `lastError` strip under the header, cleared on the next successful rescan; assignments gate on `scannedHome` — a dismiss Task holds the OLD home beyond `.task` cancellation and must not overwrite a repointed Home's groups). Posts renders the full grid; **column collapse mirrors the export's media queries** (library hides < 1100 px, mentor hides < 920 px budget) as macOS pane collapse — never a fixed four-column minWidth that clips. `PaneHeader` = 52pt serif-15 title row + border. **#22:** window-level `.dropDestination(for: URL.self)` (markdown only via `PostStore.isMarkdown`, first match — same guest slot as ⌘O), the `OriginAskSheet` (ONE ask per import batch — "Who wrote this?", writer default / ai, immutability line; Cancel drops the batch), and pane auto-switch to Posts when a guest buffer opens or an import's post opens. **#108:** rail gains the Archive destination (archivebox icon, above Settings — the #104 verdict: a destination, not a library disclosure); `ArchivePaneView` = list-only pane over archived pieces grouped by project (same section-head voice as the library + mono-11 Unarchive button per project → `PostsModel.unarchiveProject`), rows reuse `LibraryPostRow` with Move Back to `` + Rename…, row-click selects + hops to Posts (`onOpenPiece` closure — the pane can't reach the rail selection); empty state names how things arrive. The New Project ask presents here too (`newProjectAskBinding`, the OriginAsk pattern). **#111 (S7):** the third ask — `OutlineGuardSheet` (`outlineGuardBinding`, same pattern) for the mixed-content outline guard: Open in Prose (default) · Open as Outline · Cancel (= binding dismissal → `cancelOutlineGuard`, Esc included). **#114 (S4):** the fourth ask — `ConvertSheet` (`convertAskBinding`) for Convert to Post: Verbatim Bullets (default — lossless) · Headings · Cancel (= `cancelConversion`); a ladder-drops-prose warning when `lossy`; the Archive pane's row menu also carries Convert to Post… on outline pieces (archived stays archived — only type + body flip). -- `PostsPaneView.swift` — Posts destination: library column (Pass State groups in mono-11 uppercase labels, post rows with title + passState/origin meta), empty state, editor column (`PostEditorView`), mentor column (`MentorPaneView`, fixed 356). Selecting a post opens an editing session; `PaneHeader` carries the New Post button (export `.pane-head .icon-btn`). **#92:** the editor column renders the external guest (`model.externalSession`) ahead of the post session — one guest at a time, mentor column stays. **#108 (variant B, `ref/prototypes/wf104-library-ui-prototype.html`):** `PostsLibraryColumn` regroups — serif-15 semibold project section heads (lowercased in display — #108 live verdict; small caps rejected as a UI treatment for project names) + mono-11 `· N` count, Pass-State groups inside (10px mono, 0.8 opacity, leading-22 indent), collapse restored per the prototype's toggle (click the head — chevron rotates; per-view state, not persisted); `LibraryPostRow` (extracted, internal — Archive reuses it): always-2px leading strip (accent when selected — no layout shift; `UnevenRoundedRectangle` 0/8/8/0 per `.vB .post-row`), ✳ suffix on outline pieces (row-level help — a Text span isn't individually hoverable); row menu = Rename… · Convert to Post… (outline pieces only, #114 — stages the ask) · Move to Project… (`MoveToProjectSheet`, radio list of non-archived projects, Move disabled when unchanged) · Move to Archive · Move to Trash; `RenamePostSheet` internal for the Archive pane's reuse. -- `PostLibrary.swift` — `Post` (nonisolated: id/title/passState/origin + #107 type/project/isArchived + #32 `firstDraftStats: FirstDraftStats?`; `ContentType` post|outline) + `Post.scan(home:) -> [Post]`: **#107/ADR-0012 two-level scan** — enumerates `projects///post.md` AND `archive///post.md` (archive → isArchived), same skip guards at both levels (no post.md = lazy folder, loose files, hidden dirs, symlinked dirs), `type` read leniently (absent/unknown → post), title-sorted; Title = first non-empty line after frontmatter (`untitled` on blank, marker-only, or unterminated-frontmatter bodies); `pass_state`/`origin` frontmatter keys read leniently (First Draft/writer defaults, quoted YAML values unquoted, leading blank line before `---` tolerated). Scan runs off-main (bind/rescan in PostsModel). **#32 (S5.2):** scan also reads the five `stats_*` keys into `firstDraftStats` — `Post.FirstDraftStats` (captured Date parsed from the `yyyy-MM-dd'T'HH:mm:ss` stamp, per-access POSIX formatter — the repo's no-static convention; + `DraftStats`), nil unless EVERY key parses to a FINITE Double (`Double("nan")`/`"inf"` parse — a non-finite peak would trap the chart's y-domain; finish-audit #32). The read-back re-gates on the capture gate's immutable pair (origin writer, type post — NOT pass_state, which legitimately advances): app-internal edit paths never grow the keys, and `stats_*` arriving by import (external YAML rides verbatim) on an ai or outline piece still never renders — a migrated writer piece keeps its real arc. -- `PostStore.swift` — #18 write side (nonisolated), **#107/ADR-0012 re-root**: the shared slug function (#60: lowercase, diacritic-fold, strip punctuation, whitespace→hyphens, keep CJK, 80-char cap, `untitled` fallback), `availableSlug(for:home:)` collision suffixes `-2`/`-3`… over the GLOBAL slug space (all entries under `projects/*/` AND `archive/*/` — an archived slug is never reused, restore can't collide; all comparisons through private `folded(_:)` = NFC + lowercase — the canonical compare key: APFS is case-insensitive and normalization-insensitive, and NFC-vs-NFD names (Hangul jamo, Finder-made folders) are one folder to the FS; Swift `==`/Set hashing already fold canonical equivalence, so `folded` is the explicit, tested contract with the lowercase load-bearing; `createProject`'s duplicate check uses the same fold), `folder(of:home:)` = the one id→folder resolver (projects/ before archive/, project names sorted — every write path derives its target from the id alone; nothing threads (project, id)), `writeNew(body:project:type:home:)` (lazy folder under `projects//` — default `posts`, the selected project flows in from PostsModel; #109: `type` param default `.post`, stamped first in the block — New Outline passes `.outline`; the returned Post carries it; #30: `origin` param default `.writer` — New Post from Session passes `.ai` so a session-born piece stamps immutable `origin: ai`), `overwrite` (resolves via `folder(of:)`, preserves existing type/pass_state/origin, normalizes bare posts on save; **#31 finish-audit: the three owned keys update IN PLACE on blocked files — the old stamped() round-trip erased the captured stats and foreign frontmatter on every editor save; the body always swaps to the caller's**), `rename` = retitle + move WITHIN the same parent dir (piece stays in its project, stays archived if archived; file stays `post.md`; a title slugging to the current id only retitles), `trash` (resolves via `folder(of:)` + `FileManager.trashItem` — recoverable), `readBody` (frontmatter stripped for editing). **#114 (S4):** `convert(id:headingsLadder:home:)` — the one-time in-place Convert to Post: `type` flips to post, body transforms once (verbatim = unchanged; ladder = `OutlineTree.headingsLadderBody`), id/folder never move, vanished piece throws. One-way in v1. `overwrite` + `convert` share `existingStamp(id:home:)` (folder resolve + read + preserved pass_state/origin/type derivation — one source of truth). **#22:** `openableTypes`/`isMarkdown` (.md/.markdown only, local file URLs — a dragged web link is not a document; shared `markdownExtensions` list), `importFile(at:origin:project:home:)` (copy never move; lands in the selected project else default; BOM stripped + CRLF→LF normalized at the boundary — in Swift a CRLF pair is one grapheme and every `\n` split sees one line, so the corpus machinery needs LF; external YAML keys kept verbatim with `type`/`pass_state`/`origin` set-overwritten via `mergedFrontmatter` — `type: post` wins even over an external `type: outline`; absent keys inserted before the closing `---`; empty block → fresh stamp shape; id = title slug at import, #60 collision machinery; private `materialize` is the one lazy-folder path `writeNew` shares). **#108:** `move(_:to:home:)` (projects→projects folder move; refuses archived pieces **via the resolved disk path** — never the scan snapshot's `isArchived` flag — and derives the current project from the same path, so a Finder-side move between scan and click can't misfile; validates the name via `validatedProject`, same-project confirm = no-op not an error, destination-exists = disk anomaly that throws — never clobbers), `archive(_:home:)`/`restore(_:home:)` (folder moves into/out of `archive//`, project disk-derived the same way), `unarchiveProject(_:home:)` (moves every child of `archive//` into `projects//` — one path covers fresh and merge; the source is removed only when the loop emptied it — dot-entries skipped by the move are not destroyed with the folder; duplicate-id collisions throw honestly), `createProject(named:home:)` (empty/slash/dot-prefix/`:`/control-char names + case-insensitive duplicates throw; lazily materializes `projects//`), private `relocate` behind them — post.md bytes are never rewritten by any of these; ops return Void (the rescan re-derives posts from disk). **#24 (S3.1):** a same-file `extension PostStore` carries the pass write side — `snapshotPass(id:kind:body:home:)` (pre-pass body verbatim to `/passes/pass-.md`; fixed filename per pass type, so a re-run overwrites and the latest per type survives; body only, no frontmatter — the writer's diff anchor against post.md) and `advancePassState(id:kind:home:)` (monotonic: the new state is the higher of the file's pass_state and the pass's doneState via private `higherState` — passes run in any order, never regress; **#31 (S5.1): the state update is an IN-PLACE key stamp (`stampingFrontmatter` — bare blockless posts still normalize through `stamped`), replacing the old existingStamp→stamped block rewrite that silently erased the invocation-time stats and foreign frontmatter keys; vanished piece throws)**. **#27 (S4.2):** `advancePassState` also ticks the decay clock — `try? LearningDecay.recordPass(home:type:)` after the stamped write (every completed pass counts, re-runs included; `try?` because a failed bump must never fail a completed pass, and a lagging clock only delays resurfacing — safe direction). **#29 (S8.2):** a same-file extension carries the research write side — `writeResearchNote(piecePath:title:url:quote:note:home:)`, the keep write (the writer's explicit act — the ONLY path to `research/`; the tool rail writes nothing): the piece resolves through the ONE `folder(of:)` id lookup (folder or post.md path form; a garbage path fails the lookup honestly — the write anchors to THIS Home), a symlinked `research/` refuses before any write (promote's posture), file `-.md` via FixCardStore's now-internal `uniqueFile` (collision `-2`/`-3`), flat single-line frontmatter (`source`/`kept` — title/url flattened so a hostile newline can't break the shape; note/quote stay verbatim as content), empty note/quote sections omitted, atomic write, returns the landed file name. **#31 (S5.1):** a same-file extension carries the first-draft stats capture — `captureFirstDraftStats(id:body:home:) -> Bool` (@discardableResult, `try?`-free: any read/write failure returns false, a failed capture must never fail the pass — decay-clock posture): eligibility is the FILE's own frontmatter via the lenient defaults (origin writer, Pass State First Draft, type post — a bare legacy post qualifies), metrics come from `DraftStats.compute(body:)` and five flat `stats_*` keys (`stats_captured` = `yyyy-MM-dd'T'HH:mm:ss` lexically sortable; four metrics `%.3f`) stamp IN PLACE through `stampingFrontmatter` (widened internal — the third caller), so a re-invocation while still First Draft overwrites (latest draft wins) and the trend view (S5.2) is a plain scan of `Post.frontmatter`. +- `PostsPaneView.swift` — Posts destination: library column (Pass State groups in mono-11 uppercase labels, post rows with title + passState/origin meta), empty state, editor column (`PostEditorView`), mentor column (`MentorPaneView`, fixed 356). Selecting a post opens an editing session; `PaneHeader` carries the New Post button (export `.pane-head .icon-btn`). **#92:** the editor column renders the external guest (`model.externalSession`) ahead of the post session — one guest at a time, mentor column stays. **#108 (variant B, `ref/prototypes/wf104-library-ui-prototype.html`):** `PostsLibraryColumn` regroups — serif-15 semibold project section heads (lowercased in display — #108 live verdict; small caps rejected as a UI treatment for project names) + mono-11 `· N` count, Pass-State groups inside (10px mono, 0.8 opacity, leading-22 indent), collapse restored per the prototype's toggle (click the head — chevron rotates; per-view state, not persisted); `LibraryPostRow` (extracted, internal — Archive reuses it): always-2px leading strip (accent when selected — no layout shift; `UnevenRoundedRectangle` 0/8/8/0 per `.vB .post-row`), ✳ suffix on outline pieces (row-level help — a Text span isn't individually hoverable); row menu = Rename… · Convert to Post… (outline pieces only, #114 — stages the ask) · Move to Project… (`MoveToProjectSheet`, radio list of non-archived projects, Move disabled when unchanged) · Move to Archive · Move to Trash; `RenamePostSheet` internal for the Archive pane's reuse. **#33 (S6.1):** the editor column's session branch passes `publish:` to PostEditorView (a mono-11 Publish toolbar button, nil = hidden — drafts/guests/previews carry none); the pane hosts the `MicropubPublishSheet` (`.sheet(isPresented:)` beside `.task(id: home)`). +- `PostLibrary.swift` — `Post` (nonisolated: id/title/passState/origin + #107 type/project/isArchived + #32 `firstDraftStats: FirstDraftStats?`; `ContentType` post|outline) + `Post.scan(home:) -> [Post]`: **#107/ADR-0012 two-level scan** — enumerates `projects///post.md` AND `archive///post.md` (archive → isArchived), same skip guards at both levels (no post.md = lazy folder, loose files, hidden dirs, symlinked dirs), `type` read leniently (absent/unknown → post), title-sorted; Title = first non-empty line after frontmatter (`untitled` on blank, marker-only, or unterminated-frontmatter bodies); `pass_state`/`origin` frontmatter keys read leniently (First Draft/writer defaults, quoted YAML values unquoted, leading blank line before `---` tolerated). Scan runs off-main (bind/rescan in PostsModel). **#32 (S5.2):** scan also reads the five `stats_*` keys into `firstDraftStats` — `Post.FirstDraftStats` (captured Date parsed from the `yyyy-MM-dd'T'HH:mm:ss` stamp, per-access POSIX formatter — the repo's no-static convention; + `DraftStats`), nil unless EVERY key parses to a FINITE Double (`Double("nan")`/`"inf"` parse — a non-finite peak would trap the chart's y-domain; finish-audit #32). The read-back re-gates on the capture gate's immutable pair (origin writer, type post — NOT pass_state, which legitimately advances): app-internal edit paths never grow the keys, and `stats_*` arriving by import (external YAML rides verbatim) on an ai or outline piece still never renders — a migrated writer piece keeps its real arc. **#33 (S6.1):** `Post` gains `micropubURL: String?` (frontmatter `micropub_url`, read leniently but gated on `Micropub.trustworthyURL` — imported frontmatter rides verbatim, so a hostile value scans nil and never pre-arms the publish sheet; defaulted so every hand-constructed `Post(id:…)` site keeps compiling). +- `PostStore.swift` — #18 write side (nonisolated), **#107/ADR-0012 re-root**: the shared slug function (#60: lowercase, diacritic-fold, strip punctuation, whitespace→hyphens, keep CJK, 80-char cap, `untitled` fallback), `availableSlug(for:home:)` collision suffixes `-2`/`-3`… over the GLOBAL slug space (all entries under `projects/*/` AND `archive/*/` — an archived slug is never reused, restore can't collide; all comparisons through private `folded(_:)` = NFC + lowercase — the canonical compare key: APFS is case-insensitive and normalization-insensitive, and NFC-vs-NFD names (Hangul jamo, Finder-made folders) are one folder to the FS; Swift `==`/Set hashing already fold canonical equivalence, so `folded` is the explicit, tested contract with the lowercase load-bearing; `createProject`'s duplicate check uses the same fold), `folder(of:home:)` = the one id→folder resolver (projects/ before archive/, project names sorted — every write path derives its target from the id alone; nothing threads (project, id)), `writeNew(body:project:type:home:)` (lazy folder under `projects//` — default `posts`, the selected project flows in from PostsModel; #109: `type` param default `.post`, stamped first in the block — New Outline passes `.outline`; the returned Post carries it; #30: `origin` param default `.writer` — New Post from Session passes `.ai` so a session-born piece stamps immutable `origin: ai`), `overwrite` (resolves via `folder(of:)`, preserves existing type/pass_state/origin, normalizes bare posts on save; **#31 finish-audit: the three owned keys update IN PLACE on blocked files — the old stamped() round-trip erased the captured stats and foreign frontmatter on every editor save; the body always swaps to the caller's**), `rename` = retitle + move WITHIN the same parent dir (piece stays in its project, stays archived if archived; file stays `post.md`; a title slugging to the current id only retitles), `trash` (resolves via `folder(of:)` + `FileManager.trashItem` — recoverable), `readBody` (frontmatter stripped for editing). **#114 (S4):** `convert(id:headingsLadder:home:)` — the one-time in-place Convert to Post: `type` flips to post, body transforms once (verbatim = unchanged; ladder = `OutlineTree.headingsLadderBody`), id/folder never move, vanished piece throws. One-way in v1. `overwrite` + `convert` share `existingStamp(id:home:)` (folder resolve + read + preserved pass_state/origin/type derivation — one source of truth). **#22:** `openableTypes`/`isMarkdown` (.md/.markdown only, local file URLs — a dragged web link is not a document; shared `markdownExtensions` list), `importFile(at:origin:project:home:)` (copy never move; lands in the selected project else default; BOM stripped + CRLF→LF normalized at the boundary — in Swift a CRLF pair is one grapheme and every `\n` split sees one line, so the corpus machinery needs LF; external YAML keys kept verbatim with `type`/`pass_state`/`origin` set-overwritten via `mergedFrontmatter` — `type: post` wins even over an external `type: outline`; absent keys inserted before the closing `---`; empty block → fresh stamp shape; id = title slug at import, #60 collision machinery; private `materialize` is the one lazy-folder path `writeNew` shares). **#108:** `move(_:to:home:)` (projects→projects folder move; refuses archived pieces **via the resolved disk path** — never the scan snapshot's `isArchived` flag — and derives the current project from the same path, so a Finder-side move between scan and click can't misfile; validates the name via `validatedProject`, same-project confirm = no-op not an error, destination-exists = disk anomaly that throws — never clobbers), `archive(_:home:)`/`restore(_:home:)` (folder moves into/out of `archive//`, project disk-derived the same way), `unarchiveProject(_:home:)` (moves every child of `archive//` into `projects//` — one path covers fresh and merge; the source is removed only when the loop emptied it — dot-entries skipped by the move are not destroyed with the folder; duplicate-id collisions throw honestly), `createProject(named:home:)` (empty/slash/dot-prefix/`:`/control-char names + case-insensitive duplicates throw; lazily materializes `projects//`), private `relocate` behind them — post.md bytes are never rewritten by any of these; ops return Void (the rescan re-derives posts from disk). **#24 (S3.1):** a same-file `extension PostStore` carries the pass write side — `snapshotPass(id:kind:body:home:)` (pre-pass body verbatim to `/passes/pass-.md`; fixed filename per pass type, so a re-run overwrites and the latest per type survives; body only, no frontmatter — the writer's diff anchor against post.md) and `advancePassState(id:kind:home:)` (monotonic: the new state is the higher of the file's pass_state and the pass's doneState via private `higherState` — passes run in any order, never regress; **#31 (S5.1): the state update is an IN-PLACE key stamp (`stampingFrontmatter` — bare blockless posts still normalize through `stamped`), replacing the old existingStamp→stamped block rewrite that silently erased the invocation-time stats and foreign frontmatter keys; vanished piece throws)**. **#27 (S4.2):** `advancePassState` also ticks the decay clock — `try? LearningDecay.recordPass(home:type:)` after the stamped write (every completed pass counts, re-runs included; `try?` because a failed bump must never fail a completed pass, and a lagging clock only delays resurfacing — safe direction). **#29 (S8.2):** a same-file extension carries the research write side — `writeResearchNote(piecePath:title:url:quote:note:home:)`, the keep write (the writer's explicit act — the ONLY path to `research/`; the tool rail writes nothing): the piece resolves through the ONE `folder(of:)` id lookup (folder or post.md path form; a garbage path fails the lookup honestly — the write anchors to THIS Home), a symlinked `research/` refuses before any write (promote's posture), file `-.md` via FixCardStore's now-internal `uniqueFile` (collision `-2`/`-3`), flat single-line frontmatter (`source`/`kept` — title/url flattened so a hostile newline can't break the shape; note/quote stay verbatim as content), empty note/quote sections omitted, atomic write, returns the landed file name. **#31 (S5.1):** a same-file extension carries the first-draft stats capture — `captureFirstDraftStats(id:body:home:) -> Bool` (@discardableResult, `try?`-free: any read/write failure returns false, a failed capture must never fail the pass — decay-clock posture): eligibility is the FILE's own frontmatter via the lenient defaults (origin writer, Pass State First Draft, type post — a bare legacy post qualifies), metrics come from `DraftStats.compute(body:)` and five flat `stats_*` keys (`stats_captured` = `yyyy-MM-dd'T'HH:mm:ss` lexically sortable; four metrics `%.3f`) stamp IN PLACE through `stampingFrontmatter` (widened internal — the third caller), so a re-invocation while still First Draft overwrites (latest draft wins) and the trend view (S5.2) is a plain scan of `Post.frontmatter`. **#33 (S6.1):** `stampMicropubURL(id:url:home:)` — in-place `micropub_url` stamp through `stampingFrontmatter` (frontmatter-only: body + foreign keys byte-identical, so the open session's readBody echo check never fires); vanished piece throws. - `DraftStats.swift` — #31 (S5.1) the four unaided-first-draft style metrics (nonisolated, pure, deterministic — CONTEXT.md 'Unaided First Draft'): `DraftStats.compute(body:)` → burstiness ((σ−μ)/(σ+μ) over sentence token counts, population σ, −1 for a single sentence), typeTokenRatio (unique/total), sentenceVariation (σ/μ), trigramRepetition ((total−unique)/total over consecutive token triples) — all 0 on empty/undefined input, never NaN. Tokens = lowercased `isLetter||isNumber` runs (ponytail ceiling: no apostrophe joining); sentences = chunks between `.!?` with a token count > 0 (heading text gloms into the first sentence). Full precision out; the `%.3f` rounding lives at store time (`captureFirstDraftStats`). #32 re-added `Equatable` (Post's synthesized equality rides `firstDraftStats`). - `TrendsPaneView.swift` — #32 (S5.2) the arc: per-metric line charts across unaided-first-draft CAPTURES over time (Swift Charts `LineMark`+`PointMark`, one card per metric, adaptive ≥340 2-col grid). Reads `PostsModel.posts` — the watched scan — so it refreshes with the library; no scan of its own. Only pieces with `firstDraftStats` appear (AC: the view answers "am I getting better," never "is this draft good" — points are capture moments, not draft grades). `TrendMetric` (nonisolated, pure, pinned in TrendViewTests): title / `higherIsBetter` (`trigramRepetition` is the one ↓-better metric) / value rail / fixed y-domain (burstiness −1…1, TTR + trigram 0…1; sentenceVariation scales to 1.2× the observed peak, floor 1 — a single dot never flattens into an empty axis) / `verdict(first:last:)` — improving/steady/slipping at ±0.01 tolerance, direction inverted for trigram. Card readout = mono-11 `first → last · verdict` (accent improving, orange slipping — the stale-anchor deviation color, muted steady); ONE capture shows `value · one capture`, no verdict — an arc needs two. Below the readout, `TrendMetric.explain` — one plain-language line per term (grain + which direction reads better), always visible, prose voice vs the mono data lines; pinned distinct + non-empty in TrendViewTests. Header carries the capture count; empty state names how data arrives (Learnings posture: run a Pass on a writer First Draft). - `DeslopLint.swift` — #6 (S3.4) the native deslop lint (nonisolated, pure compute): the SAME deterministic findings the deslop skill doctrine defines — banned-vocab tiers + em-dash density — computed in Swift at pass invocation, no engine round-trip (the #31 stats-capture posture: a failed lint never blocks the pass). Data: `Resources/deslop-lint.json` is the bundled default (mirrors the deslop SKILL.md tier doctrine verbatim — owner-facing, copy exactly; `key`/`landscape`/`highlight`/bare `underscore` deliberately omitted: POS-ambiguous / character-name collision — a writer adds them via the `/deslop-lint.json` override, which wins whenever it exists AND decodes; any read/decode failure → bundled, `Config(tiers: [], emDashBudget: .max)` = silent no-op). `compute(body:config:)`: one finding per phrase over its tier allowance (case-insensitive whole-word ICU match — `delved` never matches `delve`), anchor = first match (case-preserved quote, exact-substring occurrence), em-dash finding first when over budget, then tiers by first-match position; lanes mechanical (mapped replacement, case-matched to the anchor) vs demonstration. `emit` dedups against OPEN cards (pattern + anchor.quote + occurrence) BEFORE `FixCardStore.submit` — closed cards never block, re-runs make progress (and the GLOSSARY emitter contract keeps the engine from re-carding a live lint finding). The `runPass` seam fires it right after `captureFirstDraftStats`. - `Pass.swift` — #24 (S3.1) the pass substrate's shared vocabulary (nonisolated): `PassKind` (pass1/pass2 — the app's OWN names, rawValues "Pass 1"/"Pass 2"; the skill stack's compose/hunt vocabulary stays engine-side, CONTEXT.md; `level` = paragraph-level-and-up / sentence-level-and-below, `snapshotFileName` = pass-1.md/pass-2.md, `doneState` = .pass1Done/.pass2Done) and `PassContext` (`stub(kind:pieceURL:hasResearch:)` — the PRD G6 pinned minimal engine prompt: pass name + level, piece path, research-notes line only when research exists, and the closing contract "Fact-check claims where needed — research findings travel as candidate source-note tool calls (submit_research_notes), never written to disk. Deliver the verdict in your reply — findings travel as fix-card tool calls (submit_fix_cards). Do not write to the piece folder." — the RESTORED contract (#23 registered the museion-tools rail; the #24-era interim reply-only line is gone), **#29: the research rail clause added — candidates are session cargo (S8.2), the engine never writes them**); `estimateTokens` = (stub + body) chars/4 rounded up — the honest pre-pass estimate, shown before, never a deterrent). - `BlindRead.swift` — #122 the Blind Read's prompt vocabulary (nonisolated): `prompt(snapshot:current:snapshotFirst:)` — both versions INLINE under neutral "Version A/B" position labels (origin-free words never appear — the judge must not know which is the rewrite; #120's flagged default: unlabeled origins, randomized order kills position bias; the caller rolls `Bool.random()`), ask pinned to a pick ("A"/"B") + one line why, no rewrites; `reveal(kind:snapshotFirst:)` — the writer-side mapping ("A = Pass N start snapshot · B = current document"), appended by the model ONLY after the turn ends so it can never leak to the judge. GLOSSARY term "Blind Read" landed with this issue. -- `PostsModel.swift` — `PostsModel` (@MainActor @Observable, app-scoped via `AppGateState.posts`): posts list + selection + New Post draft (`PostDraft`, in-memory, no folder until first save; #107: carries `project` — captured at `newPost()` from the selected non-archived post's project, else the default `posts`; #109: carries `type` too, default `.post` — `saveDraft` threads it into `writeNew`; `mountID` (UUID per staging) keys the editor's `.id` so every newly staged draft REMOUNTS the editor — the outliner seeds its tree once per mount, a same-identity draft swap would keep the stale tree; `newOutline()` is newPost's exact dismissal/selection path with a `"- "`/`.outline` draft instead; `importFiles` lands in the same target project; **#30 (S2.7): `newPostFromSession(body:home:)` — the session-born materialize+open path: `writeNew` with `origin: .ai` (never stats-eligible), then `select` (the WorkspaceView selection onChange hops the pane) + rescan; nil + `lastError` on failure**); the open post's `EditorSession` (#19) — `select(_:home:)` ends the prior session with a flush and opens a new one, rename/trash of the open post drops the session, `shutdown()` flushes on app quit; recursive FSEvents stream (`kFSEventStreamCreateFlagFileEvents`, 0.5 s latency — the debounce; file-level so nested `post.md` edits fire) on BOTH `projects/` and `archive/` (#107 — `PostsWatcher.start(urls:)` takes an array), rescan reusing `Post.scan` off-main (#61 — own ops route through the same rescan; the rescan also hands the session the open post's disk text — the #67 external-change check, watcher-echo suppressed by equality with the session's last-flushed text); `bind(home:)` from `.task(id: home)` creates `projects/` + `archive/` if missing + rebinds on repoint; lifecycle ops (`saveDraft`/`rename`/`trash`) set `lastError` on failure, never alert; the session's `onError` routes save failures into the same strip. **#111 (S7) mixed-content outline guard:** `select` on a `type: outline` piece whose body `OutlineTree.parsesWithLoss` flags ends the old session, nils the new one, and holds the open (`outlineGuardPieceID`) — the `OutlineGuardSheet` ask (WorkspaceView, house binding pattern) presents over an EMPTY editor so nothing can normalize on ⌘S before the choice; a RESELECT of the already-open piece is a no-op (early return — the guard must never re-fire over a prior answer, which would nil the session without teardown and let the armed debounce flush mid-ask); answers `openGuardedOutlineInProse(home:)` (sets `proseOverridePostID` — a routing override with `lastDraftWasOutline`'s exact lifecycle, cleared in newPost/newOutline/select/openExternal) / `openGuardedOutlineAsOutline(home:)` (consented drop on save) / `cancelOutlineGuard()` (no session, selection cleared; still guarded next open); `outlineGuardPieceID` also dies in newPost/newOutline/openExternal (a draft/guest displaces a held ask — audit); select's tail routes through `openUnguarded` (the one open body; it clears the hold too); `isGuardedOutline` does ONE disk read deriving type (scan-known, else frontmatter) + body via `splitFrontmatter`; guard members live in a file-scope `extension PostsModel` (type_body_length posture). Routing: PostsPaneView suppresses outline for `proseOverridePostID` and renders an inert notice while a guard hold is up. **#22:** `externalSession` guest slot (#92 — one at a time, transient per launch, takes the editor column; `openExternal(url:)` refuses non-file URLs, resolves symlinks (an atomic write renames over a symlink — the link would be severed), flushes and replaces, opening any Post/draft dismisses it flush-first via `dismissExternal`; `select`/`newPost` both route through the dismissal), a second `PostsWatcher` on the external file's folder (#93 — its events re-read the file and feed the session's `diskDidChange`, the #67 conflict check reused verbatim), `shutdown()` also flushes the guest (#96.3), and the import path: `stageImport`/`cancelImport` hold `pendingImportURLs` for the ONE Origin ask, `importFiles(origin:home:)` copies each via `PostStore.importFile`, continues past per-file failures into `lastError`, opens the last success, `wireSession()` routes both sessions' `onError` into the same strip. **#108:** project ops behind the variant-B library + Archive pane — `pendingProject` (the explicit target for the NEXT new piece, set by New Project, outranks selection, cleared when the draft lands, on `select`, and on `openExternal` — anywhere the draft dies), `targetProject` = pending ?? selected-non-archived ?? default, `flushOrAbort` (audit: `EditorSession.flush()` returns Bool — a failed write aborts the op and appends "— nothing was changed." to the flush-routed reason, never replacing it; the session stays up dirty; #114 audit: an unanswered `conflictAlert` aborts the same way — "answer the reload question first", the alert stays up), `moveToProject`/`archivePost`/`restorePost`/`rename`/`unarchiveProject` (all flush-first — audit 2 closed the rename + unarchive gaps; `unarchiveProject`'s membership check is disk-derived via `folder(of:)`, captured before the move, not the posts snapshot), `restorePost` (reopens the session off the archive path — `select` alone would keep the init-time `folderURL`; a cold restore still selects), `moveTargets(home:)` (audit 2: every project on disk + the default, localized-sorted — piece-derived keys hid empty projects), `createProject(named:) -> String?` (nil = success; the failure reason shows inline in the sheet, never double-messaged into `lastError`), `stageNewProject`/`cancelNewProject`/`askNewProject` (the New Project ask, pendingImportURLs pattern), `newProjectPending` (no re-validation — the sheet trimmed, `createProject` validated). **#114 (S4) Convert to Post:** `pendingConversion` (`PendingConversion {id, lossy}` — id-scoped, survives background selects; lossy = `parsesWithLoss`, drives the sheet's ladder warning) staged by `stageConversion(_:home:)` (outline pieces only; lossy from `session.text` when the piece is open — disk lags the debounce, else disk), `cancelConversion()`; `convertToPost(headingsLadder:home:)` = `flushOrAbort` (failed write or unanswered conflict aborts) → answer-time consent recheck (Headings aborts "nothing was converted" when the post-flush body went lossy behind an unwarned ask) → `PostStore.convert` → when the piece was the open session: teardown-no-flush + reopen via `openUnguarded` with `proseOverridePostID` set (the prose re-route over the rescan lag — lastDraftWasOutline's machinery reversed; an unopened piece just converts, session untouched) → a held #111 guard ask on the piece dies as a cancel; members in a file-scope `extension PostsModel`. rescan's #67 echo check is gated by session IDENTITY (`openSession === session` — a same-id reopen must not receive the old session's stale disk text as a conflict). **#24 (S3.1) pass orchestration:** `runningPass` (stored on the class — one pass at a time, drives the pass bar's Run ↔ Cancel) + `runPass(_:home:mentor:)` in a file-scope extension: guards (one pass, mentor not mid-turn, engine ready, an OPEN saved piece — draft/external guest/guard hold all refuse with `lastError`) → `flushOrAbort` (the engine reads disk) → `PostStore.snapshotPass` (pre-pass, unconditional — even a cancelled pass snapshots) → **#31 (S5.1): `PostStore.captureFirstDraftStats(id:body:home:)` — fires at the invocation, before ANY engine traffic; eligibility is read from disk (writer origin, First Draft, post type), the Bool is ignored — a failed capture never fails the pass** → **#6 (S3.4): `DeslopLint.emit(body:pieceID:pieceURL:kind:home:)` — the native deslop lint, same invocation posture (pure Swift, no engine round-trip, a failure never blocks the pass); findings land as emitter `lint` fix cards in `/cards/` (see `DeslopLint.swift`)** → **#137 (S4, per #129/ADR-0014): `runningPass` goes live BEFORE the mentor awaits (flush/snapshot/capture are synchronous — no suspension between the guards and the flag, so the #124 Cancel-visibility invariant holds for the WHOLE run incl. the engine spawn) → `mentor.runPass(kind:stub:pieceTitle:)` — the pass runs on its OWN one-shot engine (`hermes acp -p museion-passN`), streams into the transient unrostered transcript under `passTranscriptKey`, tears down at the verdict (the label renders, the wire stub never lands; passes never mint sessions)** → advance ONLY on `.ended(stopReason)` with stopReason ≠ "refusal": `PostStore.advancePassState` + rescan (the library regroups). `cancelPass(mentor:)` = the existing session/cancel rail (`stopStreaming`); cancel/refusal/crash advance nothing — the transcript tells the story. **#122 Blind Read:** `blindRead(home:mentor:)` (file-scope extension) — the writer-triggered, whole-document A/B judgment (advisory-only, decision #120): guards mirror runPass (one rail — `runningPass`/`runningBlindRead` refuse each other; mentor not mid-turn; engine ready; OPEN saved piece) → `flushOrAbort` → `PostStore.latestPassSnapshot` (newest snapshot on disk, either kind; none → honest `lastError` "run a Pass first"; snapshot == current → "No edits since…", a vacuous read refuses) → `runningBlindRead` + `mentor.runBlindRead` with `BlindRead.prompt` (order randomized per trigger) and the reveal; `lastError` clears when the run fires (runPass's success-path posture); NOTHING advances or records — the transient transcript is the whole deliverable. `openPieceHasSnapshot` (the pass bar's disabled-with-help gate) derives in `refreshCards`. **#23 (S2.4) fix-card surfacing:** `openPieceCards` ([FixCardStore.StoredFixCard] — the OPEN piece's durable cards, newest-first) refreshed by `refreshCards(home:)` (session's piece id → `PostStore.folder(of:)` → `FixCardStore.scan`; nil session/draft/guest → []) — called as rescan's single additive tail (the existing watcher already fires on `cards/` writes, projects/ and archive/ both) and at openUnguarded's tail (select/guard-answers/convert-reopen); newPost/newOutline/openExternal clear it. **#25 (S3.2/S3.3) card lifecycle:** `applyCard(_:home:)` → `FixCardApplyOutcome` (.applied | .stale | .refused(reason)) — guards (closed card, demonstration lane, open post session), `flushOrAbort` (dirty buffer lands first; an unanswered #67 conflict aborts with the reload-question wording), stale anchor → `close(status: .open, anchorStatus: .stale)` + NO text selected or changed, the edit lands through `EditorSession.adoptText` (buffer and disk agree, both surfaces re-seed), the card closes .applied, `refreshCards` re-derives; `skipCard`/`doneCard` → one private closeCard (status flip only — Skip records nothing beyond the flip, CONTEXT.md). **#26 (S4.1):** `promoteCard(_:home:)` → `FixCardPromoteOutcome` (.promoted | .refused(reason)) — guards already-promoted + open session (applyCard's wording), calls `FixCardStore.promote(pieceURL: session.passPieceURL, …)`, failure → `lastError` "learning write failed: …", success → `refreshCards`; touches no text, flushes nothing (writes a Learning, not an edit). +- `Micropub.swift` + `MicropubPublishSheet.swift` — #33 (S6.1, M6) the Micro.blog publish path: **`Micropub.swift`** (nonisolated) holds `Micropub` (the client: fixed endpoint `https://micro.blog/micropub`, ProviderProbe's Transport seam — URLSession live, canned in tests; `makeDraftRequest` = JSON h=entry create with `name` [Title], `content` [markdown body verbatim — GLOSSARY: never stripped], `post-status: draft`, sorted keys, **`category:` frontmatter never travels**; `makePublishRequest` = `action=update` + `replace.post-status: published` against the draft URL; outcome decode: Location header → body `url` — the `preview` link is display-only, NEVER the publish target; every draft URL passes `trustworthyURL` (https + host + no line/control characters — the URL is trust-boundary data landing in frontmatter; a newline-`---` rider would close the block and reparse as body), a create with no trustworthy URL = requestFailed (never silent success), 401/403 → authFailed carrying Micropub's `error_description`, transport throw → unreachable) and `MicropubTokenStore` (the app's OWN credential — ADR-0014's no-Keychain rule covers only provider keys hermes reads from `.env`; legacy login keychain, NO `kSecUseDataProtectionKeychain` which needs keychain-access-groups this undistributed app doesn't sign with; `kSecAttrAccessibleWhenUnlockedThisDeviceOnly`; service `com.babylondreams.Museion.micropub`, account `micro.blog`; read/save-replaces/delete, `account` param defaulting to the production slot — tests inject their own so a live token is never touched or, on a locked keychain, deleted); the file also carries the `PostsModel` publish-flow extension (see the PostsModel bullet). **`MicropubPublishSheet.swift`** — the G9 ask-before surface owning both steps: Send as Draft → (review via the preview link) → Publish, each its own explicit click; refusals inline orange with buttons kept (ApplyAskSheet posture); the token field appears when none is saved or after an auth failure (re-entry replaces — never a dead end), a fresh entry is saved ONCE to the Keychain; `Send Again` re-drafts (the piece changed post-draft) and overwrites the remembered URL; `.onAppear` seeds from the piece's `micropubURL` so a draft from an earlier session still publishes. +- `PostsModel.swift` — `PostsModel` (@MainActor @Observable, app-scoped via `AppGateState.posts`): posts list + selection + New Post draft (`PostDraft`, in-memory, no folder until first save; #107: carries `project` — captured at `newPost()` from the selected non-archived post's project, else the default `posts`; #109: carries `type` too, default `.post` — `saveDraft` threads it into `writeNew`; `mountID` (UUID per staging) keys the editor's `.id` so every newly staged draft REMOUNTS the editor — the outliner seeds its tree once per mount, a same-identity draft swap would keep the stale tree; `newOutline()` is newPost's exact dismissal/selection path with a `"- "`/`.outline` draft instead; `importFiles` lands in the same target project; **#30 (S2.7): `newPostFromSession(body:home:)` — the session-born materialize+open path: `writeNew` with `origin: .ai` (never stats-eligible), then `select` (the WorkspaceView selection onChange hops the pane) + rescan; nil + `lastError` on failure**); the open post's `EditorSession` (#19) — `select(_:home:)` ends the prior session with a flush and opens a new one, rename/trash of the open post drops the session, `shutdown()` flushes on app quit; recursive FSEvents stream (`kFSEventStreamCreateFlagFileEvents`, 0.5 s latency — the debounce; file-level so nested `post.md` edits fire) on BOTH `projects/` and `archive/` (#107 — `PostsWatcher.start(urls:)` takes an array), rescan reusing `Post.scan` off-main (#61 — own ops route through the same rescan; the rescan also hands the session the open post's disk text — the #67 external-change check, watcher-echo suppressed by equality with the session's last-flushed text); `bind(home:)` from `.task(id: home)` creates `projects/` + `archive/` if missing + rebinds on repoint; lifecycle ops (`saveDraft`/`rename`/`trash`) set `lastError` on failure, never alert; the session's `onError` routes save failures into the same strip. **#111 (S7) mixed-content outline guard:** `select` on a `type: outline` piece whose body `OutlineTree.parsesWithLoss` flags ends the old session, nils the new one, and holds the open (`outlineGuardPieceID`) — the `OutlineGuardSheet` ask (WorkspaceView, house binding pattern) presents over an EMPTY editor so nothing can normalize on ⌘S before the choice; a RESELECT of the already-open piece is a no-op (early return — the guard must never re-fire over a prior answer, which would nil the session without teardown and let the armed debounce flush mid-ask); answers `openGuardedOutlineInProse(home:)` (sets `proseOverridePostID` — a routing override with `lastDraftWasOutline`'s exact lifecycle, cleared in newPost/newOutline/select/openExternal) / `openGuardedOutlineAsOutline(home:)` (consented drop on save) / `cancelOutlineGuard()` (no session, selection cleared; still guarded next open); `outlineGuardPieceID` also dies in newPost/newOutline/openExternal (a draft/guest displaces a held ask — audit); select's tail routes through `openUnguarded` (the one open body; it clears the hold too); `isGuardedOutline` does ONE disk read deriving type (scan-known, else frontmatter) + body via `splitFrontmatter`; guard members live in a file-scope `extension PostsModel` (type_body_length posture). Routing: PostsPaneView suppresses outline for `proseOverridePostID` and renders an inert notice while a guard hold is up. **#22:** `externalSession` guest slot (#92 — one at a time, transient per launch, takes the editor column; `openExternal(url:)` refuses non-file URLs, resolves symlinks (an atomic write renames over a symlink — the link would be severed), flushes and replaces, opening any Post/draft dismisses it flush-first via `dismissExternal`; `select`/`newPost` both route through the dismissal), a second `PostsWatcher` on the external file's folder (#93 — its events re-read the file and feed the session's `diskDidChange`, the #67 conflict check reused verbatim), `shutdown()` also flushes the guest (#96.3), and the import path: `stageImport`/`cancelImport` hold `pendingImportURLs` for the ONE Origin ask, `importFiles(origin:home:)` copies each via `PostStore.importFile`, continues past per-file failures into `lastError`, opens the last success, `wireSession()` routes both sessions' `onError` into the same strip. **#108:** project ops behind the variant-B library + Archive pane — `pendingProject` (the explicit target for the NEXT new piece, set by New Project, outranks selection, cleared when the draft lands, on `select`, and on `openExternal` — anywhere the draft dies), `targetProject` = pending ?? selected-non-archived ?? default, `flushOrAbort` (audit: `EditorSession.flush()` returns Bool — a failed write aborts the op and appends "— nothing was changed." to the flush-routed reason, never replacing it; the session stays up dirty; #114 audit: an unanswered `conflictAlert` aborts the same way — "answer the reload question first", the alert stays up), `moveToProject`/`archivePost`/`restorePost`/`rename`/`unarchiveProject` (all flush-first — audit 2 closed the rename + unarchive gaps; `unarchiveProject`'s membership check is disk-derived via `folder(of:)`, captured before the move, not the posts snapshot), `restorePost` (reopens the session off the archive path — `select` alone would keep the init-time `folderURL`; a cold restore still selects), `moveTargets(home:)` (audit 2: every project on disk + the default, localized-sorted — piece-derived keys hid empty projects), `createProject(named:) -> String?` (nil = success; the failure reason shows inline in the sheet, never double-messaged into `lastError`), `stageNewProject`/`cancelNewProject`/`askNewProject` (the New Project ask, pendingImportURLs pattern), `newProjectPending` (no re-validation — the sheet trimmed, `createProject` validated). **#114 (S4) Convert to Post:** `pendingConversion` (`PendingConversion {id, lossy}` — id-scoped, survives background selects; lossy = `parsesWithLoss`, drives the sheet's ladder warning) staged by `stageConversion(_:home:)` (outline pieces only; lossy from `session.text` when the piece is open — disk lags the debounce, else disk), `cancelConversion()`; `convertToPost(headingsLadder:home:)` = `flushOrAbort` (failed write or unanswered conflict aborts) → answer-time consent recheck (Headings aborts "nothing was converted" when the post-flush body went lossy behind an unwarned ask) → `PostStore.convert` → when the piece was the open session: teardown-no-flush + reopen via `openUnguarded` with `proseOverridePostID` set (the prose re-route over the rescan lag — lastDraftWasOutline's machinery reversed; an unopened piece just converts, session untouched) → a held #111 guard ask on the piece dies as a cancel; members in a file-scope `extension PostsModel`. rescan's #67 echo check is gated by session IDENTITY (`openSession === session` — a same-id reopen must not receive the old session's stale disk text as a conflict). **#24 (S3.1) pass orchestration:** `runningPass` (stored on the class — one pass at a time, drives the pass bar's Run ↔ Cancel) + `runPass(_:home:mentor:)` in a file-scope extension: guards (one pass, mentor not mid-turn, engine ready, an OPEN saved piece — draft/external guest/guard hold all refuse with `lastError`) → `flushOrAbort` (the engine reads disk) → `PostStore.snapshotPass` (pre-pass, unconditional — even a cancelled pass snapshots) → **#31 (S5.1): `PostStore.captureFirstDraftStats(id:body:home:)` — fires at the invocation, before ANY engine traffic; eligibility is read from disk (writer origin, First Draft, post type), the Bool is ignored — a failed capture never fails the pass** → **#6 (S3.4): `DeslopLint.emit(body:pieceID:pieceURL:kind:home:)` — the native deslop lint, same invocation posture (pure Swift, no engine round-trip, a failure never blocks the pass); findings land as emitter `lint` fix cards in `/cards/` (see `DeslopLint.swift`)** → **#137 (S4, per #129/ADR-0014): `runningPass` goes live BEFORE the mentor awaits (flush/snapshot/capture are synchronous — no suspension between the guards and the flag, so the #124 Cancel-visibility invariant holds for the WHOLE run incl. the engine spawn) → `mentor.runPass(kind:stub:pieceTitle:)` — the pass runs on its OWN one-shot engine (`hermes acp -p museion-passN`), streams into the transient unrostered transcript under `passTranscriptKey`, tears down at the verdict (the label renders, the wire stub never lands; passes never mint sessions)** → advance ONLY on `.ended(stopReason)` with stopReason ≠ "refusal": `PostStore.advancePassState` + rescan (the library regroups). `cancelPass(mentor:)` = the existing session/cancel rail (`stopStreaming`); cancel/refusal/crash advance nothing — the transcript tells the story. **#122 Blind Read:** `blindRead(home:mentor:)` (file-scope extension) — the writer-triggered, whole-document A/B judgment (advisory-only, decision #120): guards mirror runPass (one rail — `runningPass`/`runningBlindRead` refuse each other; mentor not mid-turn; engine ready; OPEN saved piece) → `flushOrAbort` → `PostStore.latestPassSnapshot` (newest snapshot on disk, either kind; none → honest `lastError` "run a Pass first"; snapshot == current → "No edits since…", a vacuous read refuses) → `runningBlindRead` + `mentor.runBlindRead` with `BlindRead.prompt` (order randomized per trigger) and the reveal; `lastError` clears when the run fires (runPass's success-path posture); NOTHING advances or records — the transient transcript is the whole deliverable. `openPieceHasSnapshot` (the pass bar's disabled-with-help gate) derives in `refreshCards`. **#23 (S2.4) fix-card surfacing:** `openPieceCards` ([FixCardStore.StoredFixCard] — the OPEN piece's durable cards, newest-first) refreshed by `refreshCards(home:)` (session's piece id → `PostStore.folder(of:)` → `FixCardStore.scan`; nil session/draft/guest → []) — called as rescan's single additive tail (the existing watcher already fires on `cards/` writes, projects/ and archive/ both) and at openUnguarded's tail (select/guard-answers/convert-reopen); newPost/newOutline/openExternal clear it. **#25 (S3.2/S3.3) card lifecycle:** `applyCard(_:home:)` → `FixCardApplyOutcome` (.applied | .stale | .refused(reason)) — guards (closed card, demonstration lane, open post session), `flushOrAbort` (dirty buffer lands first; an unanswered #67 conflict aborts with the reload-question wording), stale anchor → `close(status: .open, anchorStatus: .stale)` + NO text selected or changed, the edit lands through `EditorSession.adoptText` (buffer and disk agree, both surfaces re-seed), the card closes .applied, `refreshCards` re-derives; `skipCard`/`doneCard` → one private closeCard (status flip only — Skip records nothing beyond the flip, CONTEXT.md). **#26 (S4.1):** `promoteCard(_:home:)` → `FixCardPromoteOutcome` (.promoted | .refused(reason)) — guards already-promoted + open session (applyCard's wording), calls `FixCardStore.promote(pieceURL: session.passPieceURL, …)`, failure → `lastError` "learning write failed: …", success → `refreshCards`; touches no text, flushes nothing (writes a Learning, not an edit). **#33 (S6.1):** `micropubSendDraft(home:token:transport:)` (same-file-extension shape, lives in Micropub.swift at PostsModel.swift's file-length ceiling) — runPass's guard set minus the engine gates, `flushOrAbort` first (widened internal — the one cross-file writer), then ONE disk read serves both wire fields (`Post.title` = the entry's name, `splitFrontmatter` body = the content; no scan dependency), `Micropub.sendDraft` over the injected Transport, and a successful draft stamps the piece's `micropub_url` (`try?` — the draft already landed; a stamp failure only costs the cross-reopen memory). - `OutlineTree.swift` — #109 (ADR-0013) the Outline tree model (nonisolated, pure): `OutlineNode` (id = runtime UUID, regenerated per parse — fold keys in the view, never serialized; text is inert single-line markdown) + `OutlineTree` parse/serialize over the ONE-file plain nested-bullet format. Lenient parse, canonical serialize, normalize on save: `-`/`*` + space markers, any whitespace indent (tab = 2), repeated indent widths keep their established level while jumps clamp to prev+1 (4-space files parse as siblings, 8-space jumps don't orphan); lines before the first item are a verbatim preamble (`# Title` from the renamer survives above the tree), non-item lines after it drop; serialize emits `" " * depth + "- " + text`, no trailing newline. **#111:** `parsesWithLoss(_:)` — true when any non-blank non-item line follows the first item (the drop the mixed-content guard asks about; shares `parseItem` so detector and parser never disagree). Structural ops are path-addressed (`[Int]`), move whole subtrees, preserve node UUIDs, and return the moved node's new path (nil = boundary no-op): `indent` (last child of previous sibling), `outdent` (right after parent), `move(up:)` (sibling swap; at a sibling boundary the block CROSSES ITS PARENT LogSeq-style — up lands directly before the parent, down directly after, one visible row per press; root boundary nil), `enter(caretOffset:)` (empty+depth>0 → outdent; empty root → new empty sibling below; else split at caret — whitespace at the split boundary rides off the tail's head, "hello world"@5 → "hello"+"world") with `EnterResult` for focus routing. **#112 drag primitives:** `extract(_:path:)` (remove + return a whole subtree) and `insertRun(_:parentPath:index:in:)` (splice consecutive siblings at any parent, index clamps to append) over private `withChildren` — id-preserving like every op; the presenter sequences them for drops. **#114:** `headingsLadderBody(_:)` — the Convert-to-Post ladder transform (roots `##`, steps to the `######` floor, deeper stay bullets re-based flush; preamble verbatim; shares `scan` so depths never disagree). Folds live in the view, keyed by node UUID — never modeled here. - `OutlineEditorView.swift` — #109 the outliner editing surface (#105 verdict, variant B): `OutlinePresenter` (nonisolated, pure, tested) projects the tree into visible `Row`s (preorder, fold-skipping, per-row childCount + foldedDescendantCount; **#112:** `zoomRootID` roots the projection at that node's CHILDREN with depths re-based to 0 — the zoom root's own fold is ignored while it is the root, unknown ids fall back to the whole document; `rangeIDs` is zoom-aware), resolves id↔path/node + `setText` by identity, `rangeIDs` (block-selection span, ⇧↑/⇧↓ anchor↔focus) and `applyBatch` (block-selection structural ops: indent/outdent per-node, moves SIBLING-ONLY via `OutlineTree.siblingMove` with boundary-leader no-op — batch runs never cross parents, a crossing run tears itself apart; single-node ⌥↑/⌥↓ DOES cross parents, LogSeq-style). `OutlineEditorView` (SwiftUI): chrome bullets (fold toggle "●" when children, leaf "◦"; folded → accent + "⋯ N" mono-11 rust count; **#112:** double-click ANY bullet zooms in — the two clicks round-trip the fold toggle, net state unchanged) + per-depth 1px vertical rails (Canvas, 18px/level); ONE promoted `OutlineRowTextView` on the focused row (see its own file), static inline-markdown text elsewhere. **#112 (S6, wf113 verdict — variant A "fat gaps"):** the 20pt left margin is a hover-revealed ⋮⋮ grip cell (fills the row height so its frame reads as row geometry); static rows carry a body catcher (click focuses, ⇧click extends the block selection, drag runs when the row is in it); drop chrome = 2px rust seam line with its left edge at the future bullet column (20 + depth·18 + 11) or a 2px ring for onto, dashed + muted when the target is invalid; the moving run lifts to 0.3 opacity; after a drop the moved run IS the selection (anchor = first, focus = last). Zoom chrome = breadcrumb above the rows ("⟵ zoom out" = full out, ancestor crumbs zoom to that node, current crumb inert); Esc stack = drag-cancel → selection-collapse → zoom-out-one (the drag's own monitor runs first — last installed wins); zoom survives only fully-visible selections, focus falls to the projection's first row when it leaves. Zoom/drag state is view-only — never serializes, reset on every load. Key set (AppKit traps documented at the `keyDown` head in OutlineRowTextView.swift: function-key scalars `"\u{F700}"`/`"\u{F701}"` — `String(NSUpArrowFunctionKey)` is its decimal description; `.function`/`.numericPad` bits stripped before modifier compare; ⇧⇥ = backtab `\u{19}` with an `insertBacktab` override; Esc via a local `NSEvent` keyDown monitor — SwiftUI's hosting layer swallows Esc before keyDown AND before `.onExitCommand`, probe-pinned in EscEventProbeTests): Tab/⇧Tab indent/outdent · ⌥↑/⌥↓ move subtree · ↑/↓ hop visible blocks · ⇧↑/⇧↓ extend block selection · ⌘↑/⌘↓ fold/unfold · Enter → `enter` (UTF-16→grapheme caret conversion). Typography contract: live rows carry `ProseTypography.outlineRowAttributes` (body face, NATURAL line box), static rows render the same NSFont, the live row mirrors staticText's `.padding(.vertical, 3)`, and `sizeThatFits` floors at 21 so textview + padding = 27 — the bullet-cell height, no focus jump. The zoom+drag+structure handlers live in a same-file `extension OutlineEditorView` (type_body_length posture — private state stays file-scoped). Every text keystroke + structural op serializes the whole tree into the EXISTING machinery — `session.edit(md)` or `onDraftEdit` for drafts; focus follows node IDs; folds are session-scoped view state. Routing: `PostEditorView.outline` flag swaps `editingSurface` to the outliner; `PostsPaneView` passes `draft.type == .outline` for drafts and `lastDraftWasOutline || posts-lookup` for sessions. - `OutlineDrag.swift` — #112 (S6) the drag plumbing + drop math: `OutlineDragCatcher`/`CatcherView` (one transparent NSView per row — `.grip` owns the left margin, click focuses / drag always runs; `.body` overlays static row text, ⇧click extends / drag only when the row is in the block selection). 4px threshold separates clicks from drags; past it `DragTracker` owns the gesture via NSEvent monitors (local for dragged/up/Esc, GLOBAL for dragged/up outside the app — mouse capture without a system dragging session, and an Esc-cancel can never resolve as a drop). The gesture is self-contained from arm time: window + callbacks captured STRONGLY in `armDrag` — a mid-drag scroll can drop the origin row's catcher out of the lazy stack, and mouse-up must still clear the surface's drag state (no weak reads of the view at fire time); a `static current` guard finishes a never-ended predecessor as a cancel instead of stacking trackers. Live row geometry = `CatcherView.rowFrames(in:)`, a view-tree walk reading CURRENT window-space frames per pointer event — SwiftUI 27 removed the `.window` coordinate space and cached frames go stale on scroll; AppKit's convert-to-window is the stable truth; the GRIP frame (full row height) wins over the body catcher's text-only frame regardless of visit order. The pure drop math rides here as a `nonisolated extension OutlinePresenter`: `DropTarget` (`.before`/`.afterLast`/`.lastChild`, id-referenced, resolved AFTER extraction — the applyBatch re-resolve discipline; line-insertion semantics mean a drop can never steal siblings), `draggedIDs` (selection rides deduped — a selected ancestor carries its selected descendants), `isValidDrop` (ref at/inside the moving run), `applyDrop` (extract reverse-doc-order → re-resolve anchor by id → splice contiguous; no-op drops restore the snapshot), `hitTestDrop` (fat-gap 30/40/30 bands, ±6 tolerance INTO the edge rows, window-space y-up only — both callers feed window geometry). Plus `DragInfo`, `DropGeometry` (grip 20 / rail 18 / bullet-center 11 = the indicator's bullet-column math; the guide-rail Canvas reads the same constants — seam and rails cannot drift), `HLine` (dashed invalid seam). diff --git a/Museion/Micropub.swift b/Museion/Micropub.swift new file mode 100644 index 0000000..6bb1024 --- /dev/null +++ b/Museion/Micropub.swift @@ -0,0 +1,283 @@ +// +// Micropub.swift +// Museion +// +// #33 (S6.1): the Micro.blog Micropub client + the app-token store. +// Two-step publish (G2/G11): create with `post-status: draft`, review, +// then `action=update` flips the draft to published. Bearer app-token +// auth — no OAuth in v1; the token lives in the Keychain, entered +// once. Frontmatter `category:` is permitted but inert (v1 never +// sends it — the request carries name + content only). +// +// Wire facts live-verified 2026-10-31 (microblog.dev/api/posting, +// book.micro.blog/micropub): JSON create = type/properties; the +// draft's final URL arrives in the Location header, the body carries +// url + preview; update is JSON-only action/replace. +// + +import Foundation +import Security + +nonisolated enum Micropub { + /// Micro.blog's Micropub endpoint (G2: the fixed v1 target — no + /// discovery, no per-blog config). + static let endpoint = URL(string: "https://micro.blog/micropub")! + + enum Outcome: Equatable { + /// Create landed; `url` is the draft's final URL (Location + /// header, body url as fallback) — what `publish` targets and + /// what the piece remembers. + case drafted(url: String, preview: String?) + case published + /// No open saved piece (model guard) — nothing went out. + case refused(String) + case authFailed(String) + case requestFailed(status: Int, detail: String) + case unreachable(String) + } + + // MARK: Transport (ProviderProbe seam: canned in tests, URLSession live) + + typealias Transport = @Sendable (_ request: URLRequest) async throws -> (Data, HTTPURLResponse) + + static let urlSessionTransport: Transport = { request in + let (data, response) = try await URLSession.shared.data(for: request) + guard let http = response as? HTTPURLResponse else { throw URLError(.badServerResponse) } + return (data, http) + } + + // MARK: Requests (JSON Micropub — sorted keys keep the wire deterministic) + + static func makeDraftRequest(title: String, body: String, token: String) -> URLRequest { + var request = URLRequest(url: endpoint) + request.httpMethod = "POST" + request.timeoutInterval = 30 + request.setValue("application/json", forHTTPHeaderField: "Content-Type") + request.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization") + // h=entry with markdown content and name for the title; the + // Title publishes as the entry's name, the body ships verbatim + // (GLOSSARY: never stripped). category: never sent in v1. + request.httpBody = try? JSONSerialization.data(withJSONObject: [ + "type": ["h-entry"], + "properties": [ + "name": [title], + "content": [body], + "post-status": ["draft"], + ], + ], options: [.sortedKeys]) + return request + } + + static func makePublishRequest(url: String, token: String) -> URLRequest { + var request = URLRequest(url: endpoint) + request.httpMethod = "POST" + request.timeoutInterval = 30 + request.setValue("application/json", forHTTPHeaderField: "Content-Type") + request.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization") + request.httpBody = try? JSONSerialization.data(withJSONObject: [ + "action": "update", + "url": url, + "replace": ["post-status": ["published"]], + ], options: [.sortedKeys]) + return request + } + + // MARK: The two steps + + /// Step 1: send the piece as a draft. The piece's Title is the + /// entry's name; the markdown body is the content. + static func sendDraft( + title: String, + body: String, + token: String, + transport: Transport = urlSessionTransport, + ) async -> Outcome { + await run(makeDraftRequest(title: title, body: body, token: token), transport: transport, decodeDraftURL: true) + } + + /// Step 2: publish the draft — flip its post-status. Needs the + /// draft's URL from step 1 (the piece's remembered `micropub_url`). + static func publish( + url: String, + token: String, + transport: Transport = urlSessionTransport, + ) async -> Outcome { + guard !url.isEmpty else { return .refused("No draft URL on this piece — send it as a draft first.") } + return await run(makePublishRequest(url: url, token: token), transport: transport, decodeDraftURL: false) + } + + /// One POST + the honest decode: 2xx → drafted/published (drafts + /// need a URL — Location header first, body `url` second; the + /// preview link is display-only, never the publish target; a create + /// with no trustworthy URL is a request failure, never a silent + /// success), 401/403 → authFailed, other statuses carry Micropub's + /// `error_description`, transport throws → unreachable. + private static func run( + _ request: URLRequest, + transport: Transport, + decodeDraftURL: Bool, + ) async -> Outcome { + do { + let (data, response) = try await transport(request) + guard (200 ..< 300).contains(response.statusCode) else { + return decodeFailure(status: response.statusCode, body: data) + } + guard decodeDraftURL else { return .published } + let root = (try? JSONSerialization.jsonObject(with: data)) as? [String: Any] ?? [:] + // #33 audit: the URL is trust-boundary data — it lands in + // frontmatter and drives a later publish. Location first, + // body url second; both must pass the format guard. + let url = response.value(forHTTPHeaderField: "Location") ?? root["url"] as? String + guard let url, trustworthyURL(url) else { + return .requestFailed(status: response.statusCode, detail: "no trustworthy URL in the response") + } + return .drafted(url: url, preview: root["preview"] as? String) + } catch { + return .unreachable(error.localizedDescription) + } + } + + /// A draft URL Museion will persist and act on: https, a host, no + /// line/control characters — a `\n---` riding this value would close + /// the frontmatter block on the next parse and re-parse as BODY + /// (arbitrary markdown in the writer's piece, shipped under their + /// token by the next send). Applied at both ends: the decode above + /// and `Post.scan`'s read-back (imported frontmatter rides verbatim). + /// Format-only by design — ponytail: a well-formed foreign URL still + /// passes (the label shows its full text); host-allowlist when v2's + /// q=config surface names the blog's real domains. + static func trustworthyURL(_ string: String) -> Bool { + guard !string.isEmpty, + string.rangeOfCharacter(from: .newlines.union(.controlCharacters)) == nil, + let url = URL(string: string), + url.scheme?.lowercased() == "https", + url.host != nil + else { return false } + return true + } + + private static func decodeFailure(status: Int, body: Data) -> Outcome { + let root = (try? JSONSerialization.jsonObject(with: body)) as? [String: Any] ?? [:] + let detail = (root["error_description"] as? String) ?? (root["error"] as? String) ?? "HTTP \(status)" + if status == 401 || status == 403 { + return .authFailed(detail) + } + return .requestFailed(status: status, detail: detail) + } +} + +/// The Micro.blog app token — Museion's OWN credential, read only by +/// this app (ADR-0014's no-Keychain rule covers provider keys hermes +/// must read from `.env`; this token has no engine consumer). +/// Entered once, stored in the login keychain (the legacy file-based +/// store — no `kSecUseDataProtectionKeychain`, which needs +/// keychain-access-groups from a provisioning profile this +/// not-yet-distributed app doesn't sign with). +nonisolated enum MicropubTokenStore { + private static let service = "com.babylondreams.Museion.micropub" + /// The production slot. Tests pass their own account — the suite + /// must never touch (or, on a locked keychain, delete) a real + /// live token (#33 audit). + private static let account = "micro.blog" + + /// `account` is overridable for tests only; production callers use + /// the default. + static func read(account: String = account) -> String? { + var query = baseQuery(account: account) + query[kSecReturnData as String] = true + query[kSecMatchLimit as String] = kSecMatchLimitOne + var out: CFTypeRef? + guard SecItemCopyMatching(query as CFDictionary, &out) == errSecSuccess, + let data = out as? Data + else { return nil } + return String(data: data, encoding: .utf8) + } + + /// Add-or-replace (rotation replaces, never duplicates). An empty + /// token is never stored. + static func save(_ token: String, account: String = account) { + guard !token.isEmpty else { return } + let data = Data(token.utf8) + var update = baseQuery(account: account) + update[kSecValueData as String] = data + if SecItemUpdate(update as CFDictionary, [kSecValueData as String: data] as CFDictionary) == errSecItemNotFound { + var add = update + add[kSecAttrAccessible as String] = kSecAttrAccessibleWhenUnlockedThisDeviceOnly + SecItemAdd(add as CFDictionary, nil) + } + } + + static func delete(account: String = account) { + SecItemDelete(baseQuery(account: account) as CFDictionary) + } + + private static func baseQuery(account: String) -> [String: Any] { + [ + kSecClass as String: kSecClassGenericPassword, + kSecAttrService as String: service, + kSecAttrAccount as String: account, + ] + } +} + +// MARK: - #33 (S6.1) Micropub draft → publish + +extension PostsModel { + /// Step 1 of the two-step publish: send the OPEN piece to Micro.blog + /// as a draft (h=entry, name = Title, markdown content, post-status + /// draft — category frontmatter never travels). runPass's guard set + /// minus the engine gates (no engine involved); flush-first so the + /// wire carries the editor's latest. On success the piece remembers + /// the draft URL (`micropub_url` stamp) — a stamp failure never + /// un-sends the draft; it lands in lastError while the outcome stays + /// honest. Publishing (step 2) is stateless: the sheet calls + /// `Micropub.publish` against the remembered URL directly. + func micropubSendDraft( + home: URL, + token: String, + transport: Micropub.Transport = Micropub.urlSessionTransport, + ) async -> Micropub.Outcome { + guard let session, + let id = session.postID, + id == selectedPostID, + draft == nil, + externalSession == nil, + outlineGuardPieceID == nil + else { + return .refused("Open a saved post to publish.") + } + guard flushOrAbort(id) else { + return .refused(lastError ?? "Couldn't save the piece before sending.") + } + // Disk is the truth post-flush — ONE read serves both wire fields: + // Title (heading markers stripped — it publishes as the entry's + // name) and the frontmatter-stripped body (the stamp is + // bookkeeping, never prose; the body itself is never stripped, + // GLOSSARY). No scan dependency: the list can lag the open piece. + guard let dir = PostStore.folder(of: id, home: home), + let raw = try? String(contentsOf: dir.appendingPathComponent("post.md"), encoding: .utf8) + else { + return .refused("Couldn't read the piece before sending.") + } + let body = PostStore.splitFrontmatter(raw).body + guard !body.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else { + return .refused("This piece has no text to send.") + } + let outcome = await Micropub.sendDraft( + title: Post.title(of: raw), + body: body, + token: token, + transport: transport, + ) + if case let .drafted(url, _) = outcome { + // Remember the draft URL for the publish step. A stamp + // failure can't un-send the draft; the sheet still holds + // the URL for this session — the piece just loses the + // memory across a reopen (re-send the draft then). Kept + // quiet: lastError's setter stays PostsModel-file-private, + // and the same disk accepted the flush moments before. + try? PostStore.stampMicropubURL(id: id, url: url, home: home) + } + return outcome + } +} diff --git a/Museion/MicropubPublishSheet.swift b/Museion/MicropubPublishSheet.swift new file mode 100644 index 0000000..d1b304a --- /dev/null +++ b/Museion/MicropubPublishSheet.swift @@ -0,0 +1,212 @@ +// +// MicropubPublishSheet.swift +// Museion +// +// #33 (S6.1): the publish ask — draft first, then publish (G9: +// publish is ask-before; each step is its own explicit click). The +// sheet owns the whole two-step flow over the OPEN piece: Send as +// Draft (h=entry, name, markdown content) → review on Micro.blog → +// Publish (the post-status update against the piece's remembered +// draft URL). The app token is entered here ONCE and lives in the +// Keychain (G11; re-offered only on an auth failure). Refusals show +// inline with the buttons kept (ApplyAskSheet posture). +// + +import SwiftUI + +/// #33 (S6.1): the two-step Micro.blog ask over the open piece. +struct MicropubPublishSheet: View { + let posts: PostsModel + let home: URL + @Environment(\.dismiss) private var dismiss + + private enum Phase: Equatable { + case idle + case drafting + case drafted + case publishing + case published + } + + @State private var phase: Phase = .idle + /// The draft URL this sheet knows: fresh from a send, or the piece's + /// remembered `micropub_url` (a draft sent in an earlier session). + @State private var draftURL: String? + @State private var previewURL: String? + @State private var refusal: String? + @State private var tokenField = "" + @State private var reentry = false + + /// Token entry shows when none is saved — or again after an auth + /// failure (the entered-once token can be replaced, never a dead end). + private var showsTokenField: Bool { + reentry || MicropubTokenStore.read() == nil + } + + var body: some View { + VStack(alignment: .leading, spacing: 12) { + Text("Publish to Micro.blog?") + .font(.headline) + Text(pieceTitle) + .font(.callout.weight(.semibold)) + .lineLimit(2) + Text("Museion sends it as a draft first — nothing goes out until you publish.") + .font(.callout) + .foregroundStyle(DesignTokens.muted) + + if showsTokenField { + SecureField("App token", text: $tokenField) + .textFieldStyle(.roundedBorder) + .font(.system(size: 12, design: DesignTokens.mono)) + Text("From micro.blog → Account → App Tokens. Stored in your Keychain.") + .font(.system(size: 11, design: DesignTokens.mono)) + .foregroundStyle(DesignTokens.muted) + } + + if phase == .drafting || phase == .publishing { + ProgressView() + } + + if let url = statusURL { + // The draft lives on Micro.blog — the preview link goes + // there for review; once published it's the post itself. + VStack(alignment: .leading, spacing: 4) { + Text(phase == .published ? "Published" : "Draft on Micro.blog") + .font(.system(size: 11, design: DesignTokens.mono)) + .foregroundStyle(DesignTokens.muted) + if let link = URL(string: phase == .published ? url : (previewURL ?? url)) { + Link(destination: link) { + Text(link.absoluteString) + .font(.system(size: 11, design: DesignTokens.mono)) + .lineLimit(1) + .truncationMode(.middle) + } + } + } + } + if let refusal { + Text(refusal) + .font(.callout) + .foregroundStyle(.orange) + } + + HStack(spacing: 8) { + if phase == .published { + Button("Done") { dismiss() } + .buttonStyle(.borderedProminent) + } else { + Button("Publish") { publish() } + .buttonStyle(.borderedProminent) + .disabled(draftURL == nil || phase == .drafting || phase == .publishing) + if draftURL != nil { + // The piece changed since the draft — a fresh send + // replaces it (and the remembered URL). + Button("Send Again") { sendDraft() } + .buttonStyle(.bordered) + .disabled(phase == .drafting || phase == .publishing) + } else { + Button("Send as Draft") { sendDraft() } + .buttonStyle(.bordered) + .disabled(phase == .drafting || phase == .publishing) + } + Button("Cancel") { dismiss() } + .buttonStyle(.bordered) + } + } + .frame(maxWidth: .infinity, alignment: .trailing) + } + .padding(16) + .frame(width: 340, alignment: .leading) + .onAppear { + // A draft sent in an earlier session is still publishable: + // the piece remembers its URL. + if draftURL == nil, let id = posts.session?.postID { + if let remembered = posts.posts.first(where: { $0.id == id })?.micropubURL { + draftURL = remembered + } + } + } + } + + // MARK: Steps + + /// The open piece's Title (the sheet is only reachable with a piece + /// open; the id is the honest fallback). + private var pieceTitle: String { + posts.session?.postID.map { posts.title(of: $0) } ?? "This piece" + } + + private var statusURL: String? { + phase == .drafted || phase == .published || phase == .publishing ? draftURL : nil + } + + /// Resolve the token: a freshly entered one is saved ONCE (rotation + /// replaces); otherwise the Keychain's. Nil → the inline ask, never + /// a silent send. + private func resolveToken() -> String? { + if !tokenField.trimmingCharacters(in: .whitespaces).isEmpty { + let token = tokenField.trimmingCharacters(in: .whitespaces) + MicropubTokenStore.save(token) + reentry = false + return token + } + guard let saved = MicropubTokenStore.read() else { return nil } + return saved + } + + private func sendDraft() { + guard let token = resolveToken() else { + refusal = "Paste your Micro.blog app token first." + return + } + refusal = nil + phase = .drafting + Task { + switch await posts.micropubSendDraft(home: home, token: token) { + case let .drafted(url, preview): + draftURL = url + previewURL = preview + phase = .drafted + case let .authFailed(detail): + reentry = true // the entered-once token may be wrong + refusal = "Micro.blog rejected the token: \(detail)" + phase = draftURL == nil ? .idle : .drafted + case let .refused(reason), let .unreachable(reason): + refusal = reason + phase = draftURL == nil ? .idle : .drafted + case let .requestFailed(status, detail): + refusal = "Micro.blog said \(status): \(detail)" + phase = draftURL == nil ? .idle : .drafted + case .published: + break + } + } + } + + private func publish() { + guard let url = draftURL, let token = resolveToken() else { + refusal = "Paste your Micro.blog app token first." + return + } + refusal = nil + phase = .publishing + Task { + switch await Micropub.publish(url: url, token: token) { + case .published: + phase = .published + case let .authFailed(detail): + reentry = true + refusal = "Micro.blog rejected the token: \(detail)" + phase = .drafted + case let .refused(reason), let .unreachable(reason): + refusal = reason + phase = .drafted + case let .requestFailed(status, detail): + refusal = "Micro.blog said \(status): \(detail)" + phase = .drafted + case .drafted: + break + } + } + } +} diff --git a/Museion/PostEditorView.swift b/Museion/PostEditorView.swift index 66bcd35..120d066 100644 --- a/Museion/PostEditorView.swift +++ b/Museion/PostEditorView.swift @@ -34,6 +34,10 @@ struct PostEditorView: View { var draftSave: (() -> Void)? /// #109: render the outline editing surface instead of prose. var outline = false + /// #33 (S6.1): open the Micro.blog publish ask. Nil (default) hides + /// the toolbar button — drafts, the external guest, and previews + /// have nothing to publish. + var publish: (() -> Void)? @State private var closeObserver: AnyCancellable? @State private var toggleObserver: AnyCancellable? @@ -228,6 +232,15 @@ struct PostEditorView: View { .lineLimit(1) .truncationMode(.head) Spacer() + // #33 (S6.1): the publish entry — draft first, then publish. + if let publish { + Button("Publish") { publish() } + .buttonStyle(.plain) + .font(.system(size: 11, design: DesignTokens.mono)) + .foregroundStyle(DesignTokens.muted) + .help("Send to Micro.blog — draft first, then publish") + .padding(.trailing, 10) + } if let session { SaveStateDot(state: session.saveState) } else { diff --git a/Museion/PostLibrary.swift b/Museion/PostLibrary.swift index c907cab..d7edcb6 100644 --- a/Museion/PostLibrary.swift +++ b/Museion/PostLibrary.swift @@ -28,6 +28,10 @@ nonisolated struct Post: Identifiable, Equatable { var project: String /// True when the piece lives under archive/ (#107). var isArchived: Bool + /// #33 (S6.1): the remembered Micro.blog draft URL (frontmatter + /// `micropub_url`) — set when a draft was sent, the target the + /// publish step updates. Inert to everything else. + var micropubURL: String? /// #32 (S5.2): the captured first-draft stats — present ONLY when /// `captureFirstDraftStats` stamped the piece at a pass invocation /// (writer origin, First Draft, post type, decided there against the @@ -154,6 +158,15 @@ nonisolated struct Post: Identifiable, Equatable { type: type, project: projectDir.lastPathComponent, isArchived: isArchived, + // #33: the remembered Micro.blog draft URL — + // one flat key, read leniently like the rest. + // #33 audit: imported frontmatter rides + // verbatim, so the read-back gates on the same + // format guard the decode applies — a hostile + // value never pre-arms the publish sheet. + 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. diff --git a/Museion/PostStore.swift b/Museion/PostStore.swift index 2792a4a..1b46d9b 100644 --- a/Museion/PostStore.swift +++ b/Museion/PostStore.swift @@ -770,4 +770,21 @@ nonisolated extension PostStore { )) != nil else { return false } return true } + + // MARK: #33 (S6.1) — the remembered Micro.blog draft URL + + /// Stamp `micropub_url` in place on a successful draft send — the + /// publish step's target (a frontmatter-only change: the body and + /// every other key stay byte-identical, so the open session's + /// readBody-based echo check never fires). A vanished piece throws + /// (write-never-resurrects, `writeNew` is the only creator). + static func stampMicropubURL(id: String, url: String, home: URL) throws { + guard let dir = folder(of: id, home: home) else { + throw CocoaError(.fileReadNoSuchFile) + } + let file = dir.appendingPathComponent("post.md") + let raw = try String(contentsOf: file, encoding: .utf8) + try LearningDecay.stampingFrontmatter(of: raw, with: [("micropub_url", url)]) + .write(to: file, atomically: true, encoding: .utf8) + } } diff --git a/Museion/PostsModel.swift b/Museion/PostsModel.swift index 91ec35a..ccdbdfd 100644 --- a/Museion/PostsModel.swift +++ b/Museion/PostsModel.swift @@ -473,7 +473,9 @@ final class PostsModel { /// folder move must never carry away text that didn't land (the move /// itself succeeds exactly when a file write fails). Returns false with /// lastError set; the session stays up, dirty and honest. - private func flushOrAbort(_ postID: String) -> Bool { + /// #33: internal — the Micropub draft flow (Micropub.swift) flushes + /// through the same rail. + func flushOrAbort(_ postID: String) -> Bool { guard let session, session.postID == postID else { return true } // #114 audit: an unanswered #67 conflict means disk holds foreign // text with the session's version unwritten — proceeding would act diff --git a/Museion/PostsPaneView.swift b/Museion/PostsPaneView.swift index 85cfc98..44ed8ea 100644 --- a/Museion/PostsPaneView.swift +++ b/Museion/PostsPaneView.swift @@ -29,6 +29,8 @@ struct PostsPaneView: View { /// keeps previews compiling). var onOpenSettings: (() -> Void)? @Environment(AppGateState.self) private var gate + /// #33 (S6.1): the Micro.blog publish ask over the open piece. + @State private var showingPublish = false private var showsLibrary: Bool { availableWidth >= 1100 - DesignTokens.railWidth @@ -71,6 +73,11 @@ struct PostsPaneView: View { // Bind: initial off-main scan + (re)start the FSEvents watcher (#61). model.bind(home: home) } + // #33 (S6.1): the publish ask rides the pane (not the library + // column) — it targets the open piece. + .sheet(isPresented: $showingPublish) { + MicropubPublishSheet(posts: model, home: home) + } } private var paneBorder: some View { @@ -113,6 +120,7 @@ struct PostsPaneView: View { outline: session.postID != model.proseOverridePostID && (model.lastDraftWasOutline || model.posts.first(where: { $0.id == session.postID })?.type == .outline), + publish: { showingPublish = true }, ) .id(session.postID ?? "post") } else if model.outlineGuardPieceID != nil { diff --git a/MuseionTests/AGENTS.md b/MuseionTests/AGENTS.md index e9171ac..e4ca23a 100644 --- a/MuseionTests/AGENTS.md +++ b/MuseionTests/AGENTS.md @@ -23,6 +23,7 @@ Owned by the root AGENTS.md contract. - `PostLibraryTests.swift` (#17, #107) — throwaway Homes via `makeHome`/`writePiece`/`writePost` in temp dirs: bare corpus posts (First Draft/writer defaults), lenient + quoted frontmatter (`pass_state`/`origin`/`type`), two-level scan across `projects///` + `archive///` (project/isArchived stamped, noise at both levels), lazy folders / hidden dirs / symlinks not surfacing, localizedStandardCompare title sort, `untitled` edges (blank, marker-only, unterminated frontmatter), leading-blank-line frontmatter, default Home = `~/Documents/Museion`. - `PostStoreTests.swift` (#18, #107) — write side via `storeHome`/`readPost` (same temp-dir pattern): slug algorithm cases (diacritics, CJK, cap, punctuation-only → untitled), lazy first write into `projects///` + #59 stamp (type first) round-trip through `Post.scan`, untitled fallback, case-insensitive collision suffixes over the GLOBAL slug space (projects + archive; archived slugs never reused), `writeNew(project:)` routing, rename (retitle + move within the same project, archived stays archived, insert-title path, same-slug retitle-only, collision -2), trash removes from projects/ and archive/, overwrite preservation + bare-post normalization, `readBody` stripping, blocked-project failure path, writeNew outline stamping (#109: `type: outline` first line, `projects///post.md` placement, scan round-trip; default `.post` pinned). **#30:** the New-Post-from-Session origin pins — `writeNew origin ai stamps the session-born piece and scans back` (the #30 scenario comment above it: `origin: ai` stamped first-write, default `posts/` landing, exact frontmatter + scan round-trip) and `writeNew default origin stays writer for existing callers` (the additive-default regression pin), and `a session-born ai piece keeps origin ai through overwrite` (the immutability AC pin — the save path never flips the ai stamp). **#114:** convert round-trip — verbatim keeps the body + flips type (scan reads post, stamp values kept), ladder shape, vanished-piece throw, archived piece converts in place (stays under `archive/`). **#108:** project moves — `readPiece(home:root:project:id:)` path-aware helper; move (byte-identity, same-project no-op), archive/restore round-trip, archived-move refusal, `unarchiveProject` fresh + merge cases (dot-entries skipped), `createProject` validation matrix (duplicate case-insensitive + NFD twin, empty/slash/dot/`:` rejected), hidden user folders survive unarchive (source removed only when emptied), `unarchiveProject` model test (dirty open piece flushes before the move). **Fold pin:** decomposed-jamo folder on disk vs a precomposed title → `-2` (Swift `==`/Set already fold canonical equivalence — the premise asserts byte inequality; `folded` is the explicit, tested contract). **#24 (S3.1) pass substrate:** `snapshotPass` (body verbatim under `passes/pass-1.md`, no frontmatter; re-run overwrites = latest per type; pass-1/pass-2 coexist; vanished id throws), `advancePassState` (First Draft + pass1 → Pass-1 Done with origin/type/body byte-preserved — through the in-place `pass_state` stamp since #31, formerly the block rewrite; First Draft + pass2 → Pass-2 Done order-free; Pass-2 Done + pass1 stays put — monotonic, never regresses; re-run idempotent; vanished id throws), `PassContext` stub shape (pass name + level, piece path, research line only when hasResearch, fix-card reminder — **#29: renamed pin, the stub carries the research rail clause too**) + `estimateTokens` (stub+body chars/4 rounded up, expected derived independently in the test). **#29 (S8.2) research write side:** `writeResearchNote` pins — the exact markdown shape (`source`/`kept` frontmatter, `# title`, note, blockquote quote), absent note/quote sections omitted, same-day collision `-2`, the post.md file path form, vanished-piece throw, and the audit pin — a symlinked `research/` refuses with nothing planted. **#31 (S5.1) capture pins:** five `stats_*` keys stamp in place (foreign key + body byte-preserved, `stats_captured` exactly 19 chars, `%.3f` shape via the `threeDecimals` regex helper), ai-origin / past-First-Draft / outline pieces refuse untouched, recapture while still First Draft overwrites (latest draft wins), a bare legacy post qualifies through the lenient defaults, and the #31 regression pin — `advancePassState` preserves the stats AND foreign keys in place (the old block rewrite erased them). **#31 finish-audit pins:** `overwrite` preserves stats + foreign keys while swapping the body (the mid-pass editor save no longer erases the capture) and still normalizes a bare post through the full #59 stamp; the apostrophe-joining ceiling pin now discriminates (`writer's note writer` → 3/4, not the vacuous all-unique 1.0); the two never-firing NaN guards in `DraftStats.compute` are deleted (converged ponytail+general finding) and `DraftStats` lost its unused `Equatable`. - `DraftStatsTests.swift` (#31, S5.1) — the four metrics pinned over hand-derived expectations (the scenario header lives in the file top): sentences [3,2,1] → burstiness ≈ −0.4202 / variation ≈ 0.4082 / TTR 1 / trigram 0, regular sentences → burstiness −1 with trigram 0.25, empty body → all zeros, single sentence → −1, case folding (`Dog dog DOG` → 1/3) + the no-apostrophe-joining ceiling pinned as TTR facts. +- `MicropubTests.swift` (#33, S6.1 — scenario header at file top, `@Suite`; shared helpers `MicropubRequestLog`/`micropubHTTP`/`micropubCanned`/`micropubJSON` internal) — the wire contract pinned over canned transports (ProviderProbeTransportTests pattern): draft request = h=entry with name/content/post-status draft and Bearer auth; publish request = the post-status update; Location-then-body-url decode with preview, preview-only = requestFailed (display-only, never the publish target), an injection-carrying URL = requestFailed (trustworthyURL gate), a scan-side untrustworthy `micropub_url` reads nil, no-URL create = requestFailed, 401/403 → authFailed with the error_description, non-2xx → requestFailed, transport throw → unreachable; `MicropubTokenStore` round-trips the REAL login keychain against its OWN injected account slot (a live production token is never read, replaced, or deleted — the finish-audit #33 clobber fix); `stampMicropubURL` pins (in-place stamp: foreign `category:` key + body byte-preserved, scan reads `micropub_url` back, vanished throws); and the model flow over `makeModelHome` (flush-first — the wire carries the edited text, Title publishes as name from the ONE disk read, refused-without-open-piece and refused-on-unsaved-draft and refused-on-whitespace-only-body send nothing, **the AC pin: a piece carrying `category:` frontmatter drafts with NO category key on the wire**, a failed draft stamps nothing, re-draft overwrites the remembered URL — the model pins live in `MicropubModelTests.swift` (own file, the decode suite crossed its type-body ceiling; finish-audit split)). - `TrendViewTests.swift` (#32, S5.2 — scenario header at file top, `@Suite` so suite filters run it) — the trend view's pure facts: scan reads a REAL capture back (`writeNew` + `captureFirstDraftStats` → `firstDraftStats` values match `DraftStats.compute` at %.3f grain; the parsed date round-trips through the exact stamp format via `FixCardStore.formatted` — locale-independent proof), never-captured pieces scan nil BY CONSTRUCTION (an ai piece whose capture RAN and was refused at the gate + an outline + an untouched writer post — no filtering, the keys just never exist), partial/malformed `stats_*` keys never half-load, `TrendMetric.verdict` pins (improving/steady/slipping at ±0.01, trigram inverted), and the y-domain pins (burstiness −1…1 / TTR + trigram fixed 0…1 / sentenceVariation scales to 1.2× peak with floor 1), the explain pin (every metric carries a distinct, non-empty gloss naming its better-direction — a fifth metric without one fails), the finish-audit pins — `non-finite stats values never load` (`nan`/`inf` in one key, all else valid, via the `writeStamped(id:overriding:home:)` shared fixture whose per-key overrides keep each test's one varying fact visible), `read-back gates on the immutable pair` (imported ai/outline pieces carrying hand-stamped keys scan nil; a Pass-1-Done writer piece keeps its arc — pass_state never gates) — both flip-verified (each pin fails on its own guard) — and the exact-tolerance verdict boundary (delta == 0.01 reads steady, strict comparisons). - `MCPToolsTests.swift` + `MCPServerWireTests.swift` (#23, S2.4) — the museion-tools store + wire: anchor matrix (exact substring, occurrence 2-of-2 valid / 3-of-2 stale / vanished quote / empty quote → stale), submit round-trip (snake_case card file in `/cards/`, stale lands flagged, vanished piece + malformed card throw), `submit refuses a symlinked cards dir` (#6 audit — throws with nothing written through the link, promote's posture), scan newest-first + junk skip, learnings per content type (learnings/posts|outlines) + missing dir → empty; the wire tests drive `MCPServer.run(lines:write:)` in-process — initialize protocolVersion echo, notifications silent, both tools with typed schemas, a full submit round-trip through real JSON-RPC lines, isError tool failures, -32601/-32700. **#25 slice 1 pins:** the ten-card pass ceiling (12-card submit → the ranked head P1–P10 lands, the malformed 12th never errors the call), rank stamped in submit order + pre-schema card decodes rank nil, `appliedText` (nth-occurrence replacement, empty fix cuts, beyond-count/vanished/empty quote + demonstration lane → nil), `close` (same file rewritten with the status flipped, all other fields intact, scan sees it, foreign id throws); **#25 wire pin:** an 11-card submit through the wire lands 10 on disk and the reply JSON carries `dropped_over_ceiling` == 1. **#29:** all three tools listed with required arrays (research schema: piece_path+notes at top, title+url per note); a well-formed `submit_research_notes` round-trip replies `{"received": N}` with isError absent and lands NOTHING on disk (the candidates rail writes nothing); a note missing `title` answers isError (the trust boundary). **#26:** promote pins live in `MCPToolsPromoteTests.swift` (own file — MCPToolsTests crossed its type-body ceiling; `toolsHome`/`writePiece`/`card(provenance:)` widened internal for it): one-confirm-writes-one-learning (pinned teaching shape — anchor + mechanical fix asserted ABSENT, filename + body pinned, card stamped `promotedAt`, second confirm throws, missing piece throws), promoted learnings consultable via `learnings(piecePath:)`, content-type partition (learnings/outlines), same-day same-pattern `-2` collision, newline flattening + the demonstration example pin (demonstration `fix` travels as `fix:` + `**Example.**`, mechanical's drops), pre-#26 card JSON decodes `promotedAt` nil, and the audit pins — a stale unstamped copy cannot double-promote, a vanished card refuses BEFORE writing, a symlinked learnings dir refuses with nothing planted. `LearningsPaneTests.swift` — `LearningsIndex.scan` over hand-written fixtures: type-dir grouping + newest-first ordering (undated last), lenient edges (no frontmatter → filename pattern, non-md/hidden/loose ignored), missing learnings/ → empty. **#27:** `Entry.resurfacesIn` pins (visible nil; remaining-count math at a given currentPass; scan carrying the clock from pass-counts.json; foreign unclocked dirs carry no verdict even with hand-edited decay state); its `writeLearning` helper is internal (shared with LearningDecayTests); date-stamp expectations call the prod `FixCardStore.formatted` directly (no test-side formatter copy, format literals pinned) and the blank-line-above-the-block preservation is pinned. `LearningDecayTests.swift` (own file) — the #27 decay pins: per-type pass clock (every `advancePassState` ticks its type, re-runs included, fresh home reads [:]), dismiss stamps in place (frontmatter keys + clock anchor pinned, every other key + the body byte-identical, hidden from `learnings(piecePath:)`), resurface at anchor+10 (hidden through +9), re-dismiss doubles to 20 + re-anchors at the current clock, `resurface_after: 3` override, lenient edges (garbage ints, huge hand-edits clamp so no arithmetic can trap, negative anchor counts from zero, corrupt clock → [:]), hostile-path/missing-file dismiss guards, and the audit pins — symlinked learning FILE and symlinked-dir `recordPass` write-through refusals, re-dismiss-while-hidden refusal (double-click harmless) + negative-count clamp, foreign-dir refusal (`isClocked`), and the fresh-block prepend on frontmatter-less files. `FixCardApplyTests` gains the model pins: promoteCard writes one learning + refuses repeats; no open piece refuses. - `FixCardApplyTests.swift` (#25, S3.2/S3.3) — the apply/skip/done lifecycle over `makeModelHome` + direct `FixCardStore.submit` seeding, scenario header first: apply on an open piece with a dirty buffer (flush-first, disk + card agree, saveState saved, `loadGeneration` moved — the `adoptText` rail), stale anchor at apply (.stale, post.md byte-identical, the card flags itself stale and stays open), demonstration card refused, unanswered #67 conflict refused (disk untouched), skip/done flip only the status (poll for the watcher rescan), and the store addenda pins (scan sorts submittedAt DESC → rank ASC with a slug-order-divergent batch + newest-submit-first; `close`'s anchorStatus refresh/preserve). diff --git a/MuseionTests/MicropubModelTests.swift b/MuseionTests/MicropubModelTests.swift new file mode 100644 index 0000000..69076c0 --- /dev/null +++ b/MuseionTests/MicropubModelTests.swift @@ -0,0 +1,144 @@ +// +// MicropubModelTests.swift +// MuseionTests +// +// #33 (S6.1) finish-audit split: the model-flow pins (guards + +// flush-first + the category AC) out of MicropubTests — that suite +// crossed its type-body ceiling. Scenario header + shared canned +// helpers live in MicropubTests.swift. +// + +import Foundation +@testable import Museion +import Testing + +@Suite("MicropubModelTests") +struct MicropubModelTests { + // MARK: The model flow (guards + flush-first + disk body + stamp) + + @Test @MainActor func `sendDraft flushes the open piece and sends the disk body with the title`() async throws { + let (model, home) = try makeModelHome() + let post = try PostStore.writeNew(body: "# Flush Me\n\nOriginal.", home: home) + model.select(post.id, home: home) + model.session?.edit("# Flush Me\n\nEdited on the way.") // inside the debounce window + + let log = MicropubRequestLog() + let outcome = await model.micropubSendDraft( + home: home, token: "tok", + transport: micropubCanned(201, body: "{}", headers: ["Location": "https://example.micro.blog/flush-me"], log: log), + ) + + #expect(outcome == .drafted(url: "https://example.micro.blog/flush-me", preview: nil)) + let request = try #require(log.requests.first) + let body = String(bytes: request.httpBody ?? Data(), encoding: .utf8) ?? "" + #expect(body.contains("Edited on the way.")) // the flush landed before the read + let props = try #require(micropubJSON(request)["properties"] as? [String: Any]) + #expect(props["name"] as? [String] == ["Flush Me"]) // Title publishes as the name + + // The piece remembers its draft URL. + #expect(Post.scan(home: home).first?.micropubURL == "https://example.micro.blog/flush-me") + } + + @Test @MainActor func `sendDraft refuses without an open saved piece`() async throws { + let (model, home) = try makeModelHome() + let log = MicropubRequestLog() + let outcome = await model.micropubSendDraft( + home: home, token: "tok", + transport: micropubCanned(201, body: "{}", log: log), + ) + guard case .refused = outcome else { + Issue.record("expected refused, got \(outcome)") + return + } + #expect(log.requests.isEmpty) // nothing went out + } + + @Test @MainActor func `sendDraft refuses an unsaved draft`() async throws { + let (model, home) = try makeModelHome() + model.newPost() // staged draft — no folder, no session + let log = MicropubRequestLog() + let outcome = await model.micropubSendDraft( + home: home, token: "tok", + transport: micropubCanned(201, body: "{}", log: log), + ) + guard case .refused = outcome else { + Issue.record("expected refused, got \(outcome)") + return + } + #expect(log.requests.isEmpty) + } + + @Test @MainActor func `sendDraft refuses a whitespace-only body and sends nothing`() async throws { + let (model, home) = try makeModelHome() + // All-whitespace body — no Title, no content (a heading-only + // piece DOES send: the Title line is content on Micro.blog). + let post = try PostStore.writeNew(body: " \n", home: home) + model.select(post.id, home: home) + + let log = MicropubRequestLog() + let outcome = await model.micropubSendDraft( + home: home, token: "tok", + transport: micropubCanned(201, body: "{}", log: log), + ) + guard case .refused = outcome else { + Issue.record("expected refused, got \(outcome)") + return + } + #expect(log.requests.isEmpty) // the trimmed-emptiness guard, #6's class + #expect(Post.scan(home: home).first?.micropubURL == nil) + } + + @Test @MainActor func `frontmatter category never travels`() async throws { + let (model, home) = try makeModelHome() + let post = try PostStore.writeNew(body: "# Categorized\n\nBody.", home: home) + model.select(post.id, home: home) + // The writer's own category frontmatter — permitted, inert. + let fileURL = try #require(PostStore.folder(of: post.id, home: home)?.appendingPathComponent("post.md")) + let raw = try String(contentsOf: fileURL, encoding: .utf8) + try raw.replacingOccurrences(of: "origin: writer\n", with: "origin: writer\ncategory: Essays\n") + .write(to: fileURL, atomically: true, encoding: .utf8) + + let log = MicropubRequestLog() + _ = await model.micropubSendDraft( + home: home, token: "tok", + transport: micropubCanned(201, body: "{}", headers: ["Location": "https://example.micro.blog/categorized"], log: log), + ) + + let request = try #require(log.requests.first) + let wire = String(bytes: request.httpBody ?? Data(), encoding: .utf8) ?? "" + #expect(!wire.lowercased().contains("category")) + #expect(!wire.contains("Essays")) + } + + @Test @MainActor func `a failed draft stamps nothing`() async throws { + let (model, home) = try makeModelHome() + let post = try PostStore.writeNew(body: "# Fails\n\nBody.", home: home) + model.select(post.id, home: home) + + let log = MicropubRequestLog() + _ = await model.micropubSendDraft( + home: home, token: "tok", + transport: micropubCanned(500, body: "{}", log: log), + ) + + #expect(Post.scan(home: home).first?.micropubURL == nil) + } + + @Test @MainActor func `re-drafting overwrites the remembered url`() async throws { + let (model, home) = try makeModelHome() + let post = try PostStore.writeNew(body: "# Again\n\nBody.", home: home) + model.select(post.id, home: home) + + let log = MicropubRequestLog() + _ = await model.micropubSendDraft( + home: home, token: "tok", + transport: micropubCanned(201, body: "{}", headers: ["Location": "https://example.micro.blog/first"], log: log), + ) + _ = await model.micropubSendDraft( + home: home, token: "tok", + transport: micropubCanned(201, body: "{}", headers: ["Location": "https://example.micro.blog/second"], log: log), + ) + + #expect(Post.scan(home: home).first?.micropubURL == "https://example.micro.blog/second") + } +} diff --git a/MuseionTests/MicropubTests.swift b/MuseionTests/MicropubTests.swift new file mode 100644 index 0000000..a2f93f5 --- /dev/null +++ b/MuseionTests/MicropubTests.swift @@ -0,0 +1,321 @@ +// +// MicropubTests.swift +// MuseionTests +// +// #33 (S6.1): Micropub draft → publish. Scenario: +// +// Given a saved Post open in the editor and a Micro.blog app token +// entered once (Keychain) +// When the writer sends the piece as a draft, reviews it, then +// confirms publish +// Then Micro.blog receives an h=entry create (markdown content, name, +// post-status=draft) followed by an update flipping post-status to +// published — the piece's frontmatter `category:` never travels, and +// the draft URL is remembered on the piece. +// +// Wire facts live-verified against microblog.dev/api/posting and +// Micro.blog's Micropub docs (2026-10-31): JSON create reads +// type/properties; `post-status: draft` creates a draft whose final +// URL arrives in the Location header (body carries url + preview); +// publishing the draft is `action=update` + `replace.post-status +// published` (JSON only). +// + +import Foundation +@testable import Museion +import Testing + +// MARK: Shared helpers (shared-helper convention) + +/// Records every request a canned transport saw, thread-safely. +final class MicropubRequestLog: @unchecked Sendable { + private let lock = NSLock() + private var items: [URLRequest] = [] + + func append(_ request: URLRequest) { + lock.lock() + items.append(request) + lock.unlock() + } + + var requests: [URLRequest] { + lock.lock() + defer { lock.unlock() } + return items + } +} + +nonisolated func micropubHTTP(_ status: Int, headers: [String: String]? = nil) -> HTTPURLResponse { + HTTPURLResponse( + url: Micropub.endpoint, + statusCode: status, + httpVersion: "HTTP/1.1", + headerFields: headers, + )! +} + +/// A canned transport that always answers `(status, body, headers)` and +/// logs the requests it served. +nonisolated func micropubCanned( + _ status: Int, + body: String = "{}", + headers: [String: String]? = nil, + log: MicropubRequestLog, +) -> Micropub.Transport { + { request in + log.append(request) + return (Data(body.utf8), micropubHTTP(status, headers: headers)) + } +} + +nonisolated func micropubJSON(_ request: URLRequest) -> [String: Any] { + guard let data = request.httpBody else { return [:] } + return (try? JSONSerialization.jsonObject(with: data)) as? [String: Any] ?? [:] +} + +@Suite("MicropubTests") +struct MicropubTests { + // MARK: Request shapes (the wire contract) + + @Test func `draft request is an h-entry create with name content and post-status draft`() { + let request = Micropub.makeDraftRequest(title: "The Title", body: "The body.", token: "tok") + + #expect(request.url == Micropub.endpoint) + #expect(request.httpMethod == "POST") + #expect(request.value(forHTTPHeaderField: "Authorization") == "Bearer tok") + #expect(request.value(forHTTPHeaderField: "Content-Type") == "application/json") + + let root = micropubJSON(request) + #expect(root["type"] as? [String] == ["h-entry"]) + let props = root["properties"] as? [String: Any] + #expect(props?["name"] as? [String] == ["The Title"]) + #expect(props?["content"] as? [String] == ["The body."]) + #expect(props?["post-status"] as? [String] == ["draft"]) + } + + @Test func `publish request is the post-status update against the draft url`() { + let request = Micropub.makePublishRequest(url: "https://example.micro.blog/hello.html", token: "tok") + + #expect(request.url == Micropub.endpoint) + #expect(request.httpMethod == "POST") + #expect(request.value(forHTTPHeaderField: "Authorization") == "Bearer tok") + + let root = micropubJSON(request) + #expect(root["action"] as? String == "update") + #expect(root["url"] as? String == "https://example.micro.blog/hello.html") + let replace = root["replace"] as? [String: Any] + #expect(replace?["post-status"] as? [String] == ["published"]) + } + + // MARK: Outcome decoding over canned transports + + @Test func `sendDraft reads Location then body url and carries the preview`() async { + let log = MicropubRequestLog() + let headers = ["Location": "https://example.micro.blog/hello.html"] + let body = #"{"url":"https://ignored.example/should-not-win","preview":"https://micro.blog/account/posts/1/preview/2"}"# + let outcome = await Micropub.sendDraft( + title: "T", body: "B", token: "tok", + transport: micropubCanned(201, body: body, headers: headers, log: log), + ) + #expect(outcome == .drafted(url: "https://example.micro.blog/hello.html", preview: "https://micro.blog/account/posts/1/preview/2")) + + // No Location header → the body's url is the fallback. + let fallback = await Micropub.sendDraft( + title: "T", body: "B", token: "tok", + transport: micropubCanned(200, body: #"{"url":"https://example.micro.blog/from-body"}"#, log: log), + ) + #expect(fallback == .drafted(url: "https://example.micro.blog/from-body", preview: nil)) + } + + @Test func `a create with no url anywhere is a request failure not a silent success`() async { + let log = MicropubRequestLog() + let outcome = await Micropub.sendDraft( + title: "T", body: "B", token: "tok", + transport: micropubCanned(200, body: "{}", log: log), + ) + guard case let .requestFailed(status, _) = outcome else { + Issue.record("expected requestFailed, got \(outcome)") + return + } + #expect(status == 200) + } + + @Test func `a draft url carrying injection characters is refused not stamped`() async { + // #33 audit: the URL is trust-boundary data — a `\n---` riding + // it would close the frontmatter block on the next parse and + // re-parse as BODY. The JSON carries the ESCAPED form (valid + // JSON); the decode yields real newlines at the guard — the + // refusal is the guard's, not a parse failure's. + let log = MicropubRequestLog() + let outcome = await Micropub.sendDraft( + title: "T", body: "# B\n\nBody.", token: "tok", + transport: micropubCanned(201, body: "{\"url\":\"https://x.example/a\\n---\\ninjected\"}", log: log), + ) + guard case .requestFailed = outcome else { + Issue.record("expected requestFailed for the injected URL, got \(outcome)") + return + } + } + + @Test func `preview never becomes the publish target`() async { + let log = MicropubRequestLog() + // Location AND body url absent — only a preview URL rides the + // body. Display-only: the outcome must not adopt it. + let outcome = await Micropub.sendDraft( + title: "T", body: "B", token: "tok", + transport: micropubCanned(200, body: #"{"preview":"https://micro.blog/account/posts/1/preview/2"}"#, log: log), + ) + guard case .requestFailed = outcome else { + Issue.record("expected requestFailed, got \(outcome)") + return + } + } + + @Test func `auth failures decode with the error description`() async { + let log = MicropubRequestLog() + let body = #"{"error":"forbidden","error_description":"token not authorized"}"# + let outcome = await Micropub.sendDraft( + title: "T", body: "B", token: "tok", + transport: micropubCanned(401, body: body, log: log), + ) + guard case let .authFailed(detail) = outcome else { + Issue.record("expected authFailed, got \(outcome)") + return + } + #expect(detail.contains("token not authorized")) + + let update = await Micropub.publish( + url: "https://example.micro.blog/hello.html", token: "tok", + transport: micropubCanned(403, body: body, log: log), + ) + guard case .authFailed = update else { + Issue.record("expected authFailed, got \(update)") + return + } + } + + @Test func `non-2xx maps to requestFailed and transport errors to unreachable`() async { + let log = MicropubRequestLog() + let outcome = await Micropub.sendDraft( + title: "T", body: "B", token: "tok", + transport: micropubCanned(500, body: "{}", log: log), + ) + guard case let .requestFailed(status, _) = outcome else { + Issue.record("expected requestFailed, got \(outcome)") + return + } + #expect(status == 500) + + let dead: Micropub.Transport = { _ in throw URLError(.notConnectedToInternet) } + let unreachable = await Micropub.publish(url: "https://x.example/", token: "tok", transport: dead) + guard case .unreachable = unreachable else { + Issue.record("expected unreachable, got \(unreachable)") + return + } + } + + @Test func `publish outcome is published on 2xx`() async { + let log = MicropubRequestLog() + let outcome = await Micropub.publish( + url: "https://example.micro.blog/hello.html", token: "tok", + transport: micropubCanned(200, body: "", log: log), + ) + #expect(outcome == .published) + } + + // MARK: Keychain token store (entered once) + + @Test func `token store round-trips through the login keychain`() { + // #33 audit: the suite runs against its OWN slot — a real live + // token in the production account is never read, replaced, or + // (on a locked keychain's nil read) deleted by cleanup. + let slot = "museion-tests-\(UUID().uuidString)" + defer { MicropubTokenStore.delete(account: slot) } + + #expect(MicropubTokenStore.read(account: slot) == nil) + + MicropubTokenStore.save("test-token-abc", account: slot) + #expect(MicropubTokenStore.read(account: slot) == "test-token-abc") + + // Re-save replaces (rotation), never duplicates. + MicropubTokenStore.save("test-token-xyz", account: slot) + #expect(MicropubTokenStore.read(account: slot) == "test-token-xyz") + + MicropubTokenStore.delete(account: slot) + #expect(MicropubTokenStore.read(account: slot) == nil) + } + + // MARK: The stamp + scan (the remembered draft URL) + + @Test func `stampMicropubURL stamps in place and scan reads it back`() throws { + let home = FileManager.default.temporaryDirectory + .appendingPathComponent("micropub-\(UUID().uuidString)", isDirectory: true) + try FileManager.default.createDirectory(at: home, withIntermediateDirectories: true) + defer { try? FileManager.default.removeItem(at: home) } + + let post = try PostStore.writeNew( + body: "# Kept Title\n\nBody byte-preserved.", + home: home, + ) + // A foreign key rides along — the stamp must not disturb it. + let fileURL = try #require(PostStore.folder(of: post.id, home: home)?.appendingPathComponent("post.md")) + try [ + "---", + "type: post", + "pass_state: First Draft", + "origin: writer", + "category: Essays", + "---", + "", + "# Kept Title", + "", + "Body byte-preserved.", + ].joined(separator: "\n").write(to: fileURL, atomically: true, encoding: .utf8) + let before = try String(contentsOf: fileURL, encoding: .utf8) + + try PostStore.stampMicropubURL(id: post.id, url: "https://example.micro.blog/hello.html", home: home) + + let after = try String(contentsOf: fileURL, encoding: .utf8) + #expect(after.contains("micropub_url: https://example.micro.blog/hello.html")) + #expect(after.contains("category: Essays")) // foreign keys survive + // The BODY is byte-identical — only the frontmatter block grew a line. + #expect(after.components(separatedBy: "---\n").last == before.components(separatedBy: "---\n").last) + + let scanned = Post.scan(home: home).first + #expect(scanned?.micropubURL == "https://example.micro.blog/hello.html") + #expect(scanned?.title == "Kept Title") // the stamp disturbs nothing else + } + + @Test func `stampMicropubURL throws on a vanished piece`() throws { + let home = FileManager.default.temporaryDirectory + .appendingPathComponent("micropub-\(UUID().uuidString)", isDirectory: true) + #expect(throws: (any Error).self) { + try PostStore.stampMicropubURL(id: "ghost", url: "https://x.example/", home: home) + } + } + + @Test func `scan reads an untrustworthy micropub_url as nil`() throws { + let home = FileManager.default.temporaryDirectory + .appendingPathComponent("micropub-\(UUID().uuidString)", isDirectory: true) + try FileManager.default.createDirectory(at: home, withIntermediateDirectories: true) + defer { try? FileManager.default.removeItem(at: home) } + + let post = try PostStore.writeNew(body: "# Imported\n\nBody.", home: home) + let fileURL = try #require(PostStore.folder(of: post.id, home: home)?.appendingPathComponent("post.md")) + let raw = try String(contentsOf: fileURL, encoding: .utf8) + // #33 audit: imported frontmatter rides verbatim — a hostile + // value must never pre-arm the publish sheet. The scan parse is + // line-bounded (a newline can't ride one value); the vectors + // here are a non-URL value and a control character. + try raw.replacingOccurrences(of: "origin: writer\n", with: "origin: writer\nmicropub_url: not a url\n") + .write(to: fileURL, atomically: true, encoding: .utf8) + + #expect(Post.scan(home: home).first?.micropubURL == nil) + + // A clean hand-edited value still reads back (format-only gate). + let clean = try String(contentsOf: fileURL, encoding: .utf8) + try clean.replacingOccurrences(of: "micropub_url: not a url\n", with: "micropub_url: https://example.micro.blog/imported\n") + .write(to: fileURL, atomically: true, encoding: .utf8) + #expect(Post.scan(home: home).first?.micropubURL == "https://example.micro.blog/imported") + } +} diff --git a/docs/devlog/20261031-issue33-m6-micropub-draft-publish-s6-1_log.md b/docs/devlog/20261031-issue33-m6-micropub-draft-publish-s6-1_log.md new file mode 100644 index 0000000..7299eda --- /dev/null +++ b/docs/devlog/20261031-issue33-m6-micropub-draft-publish-s6-1_log.md @@ -0,0 +1,79 @@ +# M6: Micropub draft & publish (S6.1) + +> **Date:** 2026-10-31 +> **Type:** issue +> **Reference:** https://git.babylondreams.de/AlexKucera/museion/issues/33 (PRD S6.1, G11) + +## Goal + +Implement #33: the writer sends a Post to Micro.blog as a draft first, then publishes — Micropub `h=entry` with markdown content and `name` for the title; Bearer app-token auth with the token in Keychain, entered once; no OAuth in v1; frontmatter `category:` permitted but inert (never sent). Followed by a three-reviewer finish-audit fanout and fixes. + +## What Was Done + +- `Museion/Micropub.swift` (new) — `Micropub` client (fixed endpoint `https://micro.blog/micropub`, ProviderProbe's injected Transport seam): `makeDraftRequest` = JSON h=entry create (name = Title, markdown content verbatim, `post-status: draft`, sorted keys, `category:` never travels); `makePublishRequest` = `action=update` + `replace.post-status: published`; decode = Location header → body `url` (**preview is display-only, never the publish target**), every draft URL passes `trustworthyURL`, 401/403 → authFailed with the server's `error_description`, transport throw → unreachable. `MicropubTokenStore` = SecItem login-keychain store (add-or-replace, `account` param defaulting to the production slot so tests never touch a live token). The file also carries the `PostsModel.micropubSendDraft` extension (PostsModel.swift sits at its file-length ceiling): runPass's guard set minus the engine gates, `flushOrAbort` first (widened internal), ONE disk read serves both wire fields (`Post.title(of: raw)` + `splitFrontmatter(raw).body` — no scan dependency), stamp `micropub_url` only on `.drafted` (`try?`: the draft already landed). +- `Museion/MicropubPublishSheet.swift` (new) — the G9 ask-before sheet owning both steps (Send as Draft → preview link → Publish, each an explicit click); token SecureField appears when none is saved or after an auth failure (re-entry replaces — no dead end), a fresh entry saves ONCE to the Keychain; `Send Again` re-drafts after edits; `.onAppear` seeds from the piece's `micropub_url` so a draft from an earlier session still publishes; refusals inline orange, buttons kept (ApplyAskSheet posture). +- `Museion/PostLibrary.swift` — `Post.micropubURL: String?` (defaulted property — all hand-constructed `Post(id:…)` sites keep compiling), scan reads `micropub_url` gated on `Micropub.trustworthyURL` (imported frontmatter rides verbatim; hostile values scan nil and never pre-arm the sheet). +- `Museion/PostStore.swift` — `stampMicropubURL(id:url:home:)`: in-place `micropub_url` stamp through `stampingFrontmatter` (frontmatter-only, body + foreign keys byte-identical — the open session's readBody echo check never fires); vanished piece throws `CocoaError(.fileReadNoSuchFile)` (the 8-sibling convention; finish-audit ponytail finding). +- `Museion/PostEditorView.swift` — optional `publish` closure + mono-11 Publish toolbar button (nil = hidden; drafts/guest/previews carry none). +- `Museion/PostsPaneView.swift` — `showingPublish` @State, `.sheet` beside `.task(id: home)`, closure wired in the editor column's session branch. +- Tests: `MuseionTests/MicropubTests.swift` (wire contract, decode matrix, keychain own-slot round-trip, stamp/scan) + `MuseionTests/MicropubModelTests.swift` (model flow: flush-first, refusal guards, the category AC pin, stamp lifecycle) — 20 tests. +- Finish-audit fanout (ponytail/security/general, fresh-context, read-only) → 6 accepted fixes, 2 declines, 1 parked ceiling; 4 guard flip-verification cycles. + +## Decisions & Rationale + +| Decision | Rationale | +|----------|-----------| +| Wire = JSON Micropub create → `action=update` publish | Live-verified against microblog.dev/api/posting + book.micro.blog (2026-10-31): draft's final URL rides the Location header; publishing the draft IS the post-status update. No content re-send. | +| `micropub_url` frontmatter key remembers the draft URL | Publish must work after a reopen; follows the repo's in-place stamp corpus pattern (hand-editable, git-diffable). Not in the ticket verbatim — the two-step AC forces persistence of step 1's handle. | +| Legacy login keychain (no `kSecUseDataProtectionKeychain`) | DP-keychain SecItemAdd needs keychain-access-groups from a provisioning profile this undistributed app doesn't sign with (macos-keychain-token-storage skill matrix). ADR-0014's no-Keychain rule covers only provider keys hermes reads from `.env`; this token has no engine consumer. | +| Title/body from ONE disk read in `micropubSendDraft` | Disk is the truth post-flush; the scan snapshot can lag (the first test run caught `title(of: id)` returning the id in a fresh home — scan dependency removed, not poll-looped around). GLOSSARY: Title publishes as the entry's name; body never stripped. | +| `trustworthyURL` format gate at BOTH ends (decode + scan) | Converged security finding: the draft URL is trust-boundary data landing in frontmatter — a `\n---` rider closes the block and re-parses as body (attacker markdown ships under the writer's token). Format-only by design: a well-formed foreign URL still passes (ponytail ceiling: host-allowlist when v2's `q=config` names the blog's domains). | +| Preview link display-only | A server omitting Location+url made the preview URL the publish target and the remembered `micropub_url` (general-review finding) — a preview page is not the post's address. | +| Publish button in the editor toolbar only | One placement; publish targets the open piece while the writer is looking at it. | +| Keychain test slot via `account` param | A locked keychain makes `read()` return nil; the old restore-dance defer then DELETED a real live token (security finding). Tests now run in their own slot. | + +## Gotchas & Fixes + +| Problem | Root Cause | Fix | +|---------|------------|-----| +| `Post.scan` impact = HIGH before edits | Pure fan-out through 7 callers on a shared model type | Stated-and-proceed: additive diff (defaulted property + one key read), 509-test baseline green before/after | +| First model test failed: name was `flush-me` (the id) | `title(of: id)` reads the scan snapshot, which lags a fresh home | Derive title AND body from the one post-flush disk read — no scan dependency | +| Two compile-error suite runs (exit 65) | Moving the model extension out of PostsModel.swift hit `private` members: `flushOrAbort`, then `lastError`'s `private(set)` | flushOrAbort → internal (one cross-file writer, documented); dropped the lastError write from the stamp-failure branch (the draft already landed; sheet holds the URL for the session) | +| Test suite crossed swiftlint's 400/250 ceilings after the audit pins | 5 new tests grew MicropubTests past file- and type-body limits | Split per repo precedent: `MicropubModelTests.swift` (MCPToolsPromoteTests pattern) | +| Whitespace-body pin failed on first run | Fixture had a heading line — the Title line IS content; the guard is right, the fixture was wrong | All-whitespace body fixture; comment names the distinction (heading-only pieces DO send) | +| Scan-gate pin fixture initially used `\n---` injection | `Post.frontmatter` parses line-bounded — a newline can't ride a scanned value; the injection vector is the STAMP side (already decode-gated) | Fixture pins the real scan vectors (non-URL value → nil; clean https → reads back) | +| 4 dead background-run notifications | xcresult read raced the run (`ls -td` grabbed a finalizing bundle); one run raced a visibility fix mid-flight | Post-run xcresult re-read (the repo's count-not-banner rule); each dead run diagnosed and superseded in-turn | +| First reviewer child died on a provider stall (1251s) | Provider hiccup mid-fanout | Salvaged transcript (no findings recorded), re-dispatched leaner per protocol → PASS | + +## Files Changed + +| File | Change Summary | +|------|---------------| +| `Museion/Micropub.swift` | new — client, trustworthyURL gate, token store, model publish flow | +| `Museion/MicropubPublishSheet.swift` | new — the two-step ask sheet | +| `Museion/PostLibrary.swift` | `Post.micropubURL` + gated scan read | +| `Museion/PostStore.swift` | `stampMicropubURL` in-place stamp | +| `Museion/PostsModel.swift` | `flushOrAbort` private → internal | +| `Museion/PostEditorView.swift` | optional publish closure + toolbar button | +| `Museion/PostsPaneView.swift` | sheet hosting + wiring | +| `MuseionTests/MicropubTests.swift` | new — wire/decode/store/scan pins (15) | +| `MuseionTests/MicropubModelTests.swift` | new — model-flow pins (5) | +| `Museion/AGENTS.md`, `MuseionTests/AGENTS.md`, `AGENTS.md` | DOX pass (file bullets, test-suite entry, GitNexus stats line) | + +## Open Items & Next Steps + +- [ ] **AC1 live verification (yours):** open a saved post → Publish → paste the Micro.blog app token (needs create+update scopes) → Send as Draft → review via preview link → Publish. Ticket #33 stays open until you've run it on a real post. +- [ ] `ref/opendesign-prompt.md` at the repo root is pre-existing scratch from another session — untouched, excluded from this commit. +- [ ] v2 (PRD): category round-trip (`q=config` + category create), host-allowlist for remembered URLs, illustrations (S6.2, #34 — separate fence, deliberately not built). + +## Verification + +- Full suite **529 passed / 0 failed** (xcresult executed count; baseline 509 + 20 new) — code tree identical since (post-suite edits were docs-only) +- All 4 audit guards flip-verified: guards off → their pins failed; chain flipped → preview pin failed; restored → green +- swiftformat 0 dirty, swiftlint zero findings on all touched files (pre-existing repo violations unchanged from HEAD) +- Reviewer fanout: initial PASS (zero findings) + finish-audit 3-reviewer pass (6 fixed, 2 declined with rationale, 1 parked ceiling) +- GitNexus: impact-before-edit, detect-changes scope check (intended symbols only), index re-analyzed twice + +--- + +*Log written by write-log skill* diff --git a/docs/devlog/INDEX.md b/docs/devlog/INDEX.md index c6a2031..4d14126 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-10-31 | issue | [20261031-issue33-m6-micropub-draft-publish-s6-1_log.md](20261031-issue33-m6-micropub-draft-publish-s6-1_log.md) | Two-step Micro.blog publish: Micropub draft→update, Keychain token, trustworthyURL gate, category inert | | 2026-10-31 | issue | [20261031-issue32-m4-trend-view-s5-2_log.md](20261031-issue32-m4-trend-view-s5-2_log.md) | #32 trend view: four metric charts over first-draft captures, read-back origin/type gate + finite parse; audit fixed nan/inf crash — 508 tests | | 2026-10-30 | issue | [20261030-issue122-blind-read-writer-triggered-whole-document-ab-judgment_log.md](20261030-issue122-blind-read-writer-triggered-whole-document-ab-judgment_log.md) | #122 Blind Read: advisory whole-document A/B on a fresh museion session, randomized unlabeled pair, reveal after verdict; 500 tests | | 2026-10-30 | issue | [20261030-issue6-native-deslop-lint-swift-banned-vocab-em-dash-fix-cards_log.md](20261030-issue6-native-deslop-lint-swift-banned-vocab-em-dash-fix-cards_log.md) | #6 native deslop lint: banned-vocab tiers + em-dash budget as data, emitter-lint cards at pass invocation; audit fixes — 489 tests |